Search in sources :

Example 1 with Code

use of org.lflang.lf.Code in project lingua-franca by lf-lang.

the class UtilityExtensions method trimCode.

/**
 * Trims the hostcode of reactions.
 */
public String trimCode(final Code tokenizedCode) {
    if (tokenizedCode == null || StringExtensions.isNullOrEmpty(tokenizedCode.getBody())) {
        return "";
    }
    try {
        ICompositeNode node = NodeModelUtils.findActualNodeFor(tokenizedCode);
        String code = node != null ? node.getText() : null;
        int contentStart = 0;
        List<String> lines = new ArrayList<>();
        Arrays.stream(code.split("\n")).dropWhile(line -> !line.contains("{=")).forEachOrdered(lines::add);
        // Remove start pattern
        if (!lines.isEmpty()) {
            if (IterableExtensions.head(lines).trim().equals("{=")) {
                // skip
                lines.remove(0);
            } else {
                lines.set(0, IterableExtensions.head(lines).replace("{=", "").trim());
                contentStart = 1;
            }
        }
        // Remove end pattern
        if (!lines.isEmpty()) {
            if (IterableExtensions.last(lines).trim().equals("=}")) {
                // skip
                lines.remove(lines.size() - 1);
            } else {
                lines.set(lines.size() - 1, IterableExtensions.last(lines).replace("=}", ""));
            }
        }
        // Find indentation
        String indentation = null;
        while (indentation == null && lines.size() > contentStart) {
            String firstLine = lines.get(contentStart);
            String trimmed = firstLine.trim();
            if (trimmed.isEmpty()) {
                lines.set(contentStart, "");
                contentStart++;
            } else {
                int firstCharIdx = firstLine.indexOf(trimmed.charAt(0));
                indentation = firstLine.substring(0, firstCharIdx);
            }
        }
        // Remove root indentation
        if (!lines.isEmpty()) {
            for (int i = 0; i < lines.size(); i++) {
                if (lines.get(i).startsWith(indentation)) {
                    lines.set(i, lines.get(i).substring(indentation.length()));
                }
            }
        }
        return String.join("\n", lines);
    } catch (Exception e) {
        e.printStackTrace();
        return tokenizedCode.getBody();
    }
}
Also used : CoreOptions(org.eclipse.elk.core.options.CoreOptions) KNode(de.cau.cs.kieler.klighd.kgraph.KNode) Arrays(java.util.Arrays) ElkMargin(org.eclipse.elk.core.math.ElkMargin) Code(org.lflang.lf.Code) KGraphElement(de.cau.cs.kieler.klighd.kgraph.KGraphElement) IndividualSpacings(org.eclipse.elk.core.util.IndividualSpacings) KGraphFactory(de.cau.cs.kieler.klighd.kgraph.KGraphFactory) Host(org.lflang.lf.Host) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) Extension(org.eclipse.xtext.xbase.lib.Extension) AbstractSynthesisExtensions(org.lflang.diagram.synthesis.AbstractSynthesisExtensions) KIdentifier(de.cau.cs.kieler.klighd.kgraph.KIdentifier) ArrayList(java.util.ArrayList) ReactorInstance(org.lflang.generator.ReactorInstance) List(java.util.List) Value(org.lflang.lf.Value) IterableExtensions(org.eclipse.xtext.xbase.lib.IterableExtensions) ViewSynthesisShared(de.cau.cs.kieler.klighd.krendering.ViewSynthesisShared) Reactor(org.lflang.lf.Reactor) StringExtensions(org.eclipse.xtext.xbase.lib.StringExtensions) KlighdInternalProperties(de.cau.cs.kieler.klighd.internal.util.KlighdInternalProperties) ASTUtils(org.lflang.ASTUtils) ArrayList(java.util.ArrayList) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode)

Example 2 with Code

use of org.lflang.lf.Code in project lingua-franca by lf-lang.

the class ASTUtils method insertGeneratedDelays.

/**
 * Find connections in the given resource that have a delay associated with them,
 * and reroute them via a generated delay reactor.
 * @param resource The AST.
 * @param generator A code generator.
 */
public static void insertGeneratedDelays(Resource resource, GeneratorBase generator) {
    // The resulting changes to the AST are performed _after_ iterating
    // in order to avoid concurrent modification problems.
    List<Connection> oldConnections = new ArrayList<>();
    Map<EObject, List<Connection>> newConnections = new LinkedHashMap<>();
    Map<EObject, List<Instantiation>> delayInstances = new LinkedHashMap<>();
    Iterable<Reactor> containers = Iterables.filter(IteratorExtensions.toIterable(resource.getAllContents()), Reactor.class);
    // Iterate over the connections in the tree.
    for (Reactor container : containers) {
        for (Connection connection : allConnections(container)) {
            if (connection.getDelay() != null) {
                EObject parent = connection.eContainer();
                // Assume all the types are the same, so just use the first on the right.
                Type type = ((Port) connection.getRightPorts().get(0).getVariable()).getType();
                Reactor delayClass = getDelayClass(type, generator);
                String generic = generator.getTargetTypes().supportsGenerics() ? generator.getTargetTypes().getTargetType(InferredType.fromAST(type)) : "";
                Instantiation delayInstance = getDelayInstance(delayClass, connection, generic, !generator.generateAfterDelaysWithVariableWidth());
                // Stage the new connections for insertion into the tree.
                List<Connection> connections = convertToEmptyListIfNull(newConnections.get(parent));
                connections.addAll(rerouteViaDelay(connection, delayInstance));
                newConnections.put(parent, connections);
                // Stage the original connection for deletion from the tree.
                oldConnections.add(connection);
                // Stage the newly created delay reactor instance for insertion
                List<Instantiation> instances = convertToEmptyListIfNull(delayInstances.get(parent));
                instances.add(delayInstance);
                delayInstances.put(parent, instances);
            }
        }
    }
    // Remove old connections; insert new ones.
    oldConnections.forEach(connection -> {
        var container = connection.eContainer();
        if (container instanceof Reactor) {
            ((Reactor) container).getConnections().remove(connection);
        } else if (container instanceof Mode) {
            ((Mode) container).getConnections().remove(connection);
        }
    });
    newConnections.forEach((container, connections) -> {
        if (container instanceof Reactor) {
            ((Reactor) container).getConnections().addAll(connections);
        } else if (container instanceof Mode) {
            ((Mode) container).getConnections().addAll(connections);
        }
    });
    // Finally, insert the instances and, before doing so, assign them a unique name.
    delayInstances.forEach((container, instantiations) -> instantiations.forEach(instantiation -> {
        if (container instanceof Reactor) {
            instantiation.setName(getUniqueIdentifier((Reactor) container, "delay"));
            ((Reactor) container).getInstantiations().add(instantiation);
        } else if (container instanceof Mode) {
            instantiation.setName(getUniqueIdentifier((Reactor) container.eContainer(), "delay"));
            ((Mode) container).getInstantiations().add(instantiation);
        }
    }));
}
Also used : Code(org.lflang.lf.Code) LfPackage(org.lflang.lf.LfPackage) Delay(org.lflang.lf.Delay) WidthSpec(org.lflang.lf.WidthSpec) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) Action(org.lflang.lf.Action) Input(org.lflang.lf.Input) ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) StateVar(org.lflang.lf.StateVar) Matcher(java.util.regex.Matcher) HashMultimap(com.google.common.collect.HashMultimap) Port(org.lflang.lf.Port) Map(java.util.Map) Instantiation(org.lflang.lf.Instantiation) INode(org.eclipse.xtext.nodemodel.INode) Connection(org.lflang.lf.Connection) GeneratorBase(org.lflang.generator.GeneratorBase) Element(org.lflang.lf.Element) TypeParm(org.lflang.lf.TypeParm) Collection(java.util.Collection) CompositeNode(org.eclipse.xtext.nodemodel.impl.CompositeNode) Set(java.util.Set) InvalidSourceException(org.lflang.generator.InvalidSourceException) EObject(org.eclipse.emf.ecore.EObject) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) ArraySpec(org.lflang.lf.ArraySpec) Mode(org.lflang.lf.Mode) Parameter(org.lflang.lf.Parameter) List(java.util.List) Value(org.lflang.lf.Value) CodeMap(org.lflang.generator.CodeMap) WidthTerm(org.lflang.lf.WidthTerm) Assignment(org.lflang.lf.Assignment) Resource(org.eclipse.emf.ecore.resource.Resource) ActionOrigin(org.lflang.lf.ActionOrigin) Pattern(java.util.regex.Pattern) StringExtensions(org.eclipse.xtext.xbase.lib.StringExtensions) Output(org.lflang.lf.Output) Variable(org.lflang.lf.Variable) Iterables(com.google.common.collect.Iterables) LfFactory(org.lflang.lf.LfFactory) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) ImportedReactor(org.lflang.lf.ImportedReactor) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Pair(org.eclipse.xtext.util.Pair) TargetDecl(org.lflang.lf.TargetDecl) StringUtil(org.lflang.util.StringUtil) Reaction(org.lflang.lf.Reaction) KeyValuePair(org.lflang.lf.KeyValuePair) Type(org.lflang.lf.Type) LinkedHashSet(java.util.LinkedHashSet) Tuples(org.eclipse.xtext.util.Tuples) XtextResource(org.eclipse.xtext.resource.XtextResource) HiddenLeafNode(org.eclipse.xtext.nodemodel.impl.HiddenLeafNode) Model(org.lflang.lf.Model) ReactorDecl(org.lflang.lf.ReactorDecl) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) Time(org.lflang.lf.Time) EList(org.eclipse.emf.common.util.EList) IteratorExtensions(org.eclipse.xtext.xbase.lib.IteratorExtensions) IterableExtensions(org.eclipse.xtext.xbase.lib.IterableExtensions) TerminalRule(org.eclipse.xtext.TerminalRule) Reactor(org.lflang.lf.Reactor) VarRef(org.lflang.lf.VarRef) Timer(org.lflang.lf.Timer) Port(org.lflang.lf.Port) Mode(org.lflang.lf.Mode) Connection(org.lflang.lf.Connection) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Type(org.lflang.lf.Type) EObject(org.eclipse.emf.ecore.EObject) List(java.util.List) ArrayList(java.util.ArrayList) EList(org.eclipse.emf.common.util.EList) ImportedReactor(org.lflang.lf.ImportedReactor) Reactor(org.lflang.lf.Reactor) Instantiation(org.lflang.lf.Instantiation)

Example 3 with Code

use of org.lflang.lf.Code in project lingua-franca by lf-lang.

the class CodeBuilder method prSourceLineNumber.

/**
 * Print the #line compiler directive with the line number of
 *  the specified object.
 *  @param eObject The node.
 */
public void prSourceLineNumber(EObject eObject) {
    var node = NodeModelUtils.getNode(eObject);
    if (node != null) {
        // For code blocks (delimited by {= ... =}, unfortunately,
        // we have to adjust the offset by the number of newlines before {=.
        // Unfortunately, this is complicated because the code has been
        // tokenized.
        var offset = 0;
        if (eObject instanceof Code) {
            offset += 1;
        }
        // Extract the filename from eResource, an astonishingly difficult thing to do.
        URI resolvedURI = CommonPlugin.resolve(eObject.eResource().getURI());
        // pr(output, "#line " + (node.getStartLine() + offset) + ' "' + FileConfig.toFileURI(fileConfig.srcFile) + '"')
        pr("#line " + (node.getStartLine() + offset) + " \"" + resolvedURI + "\"");
    }
}
Also used : Code(org.lflang.lf.Code) URI(org.eclipse.emf.common.util.URI)

Aggregations

Code (org.lflang.lf.Code)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)2 NodeModelUtils (org.eclipse.xtext.nodemodel.util.NodeModelUtils)2 IterableExtensions (org.eclipse.xtext.xbase.lib.IterableExtensions)2 StringExtensions (org.eclipse.xtext.xbase.lib.StringExtensions)2 Reactor (org.lflang.lf.Reactor)2 Value (org.lflang.lf.Value)2 HashMultimap (com.google.common.collect.HashMultimap)1 Iterables (com.google.common.collect.Iterables)1 Iterators (com.google.common.collect.Iterators)1 KlighdInternalProperties (de.cau.cs.kieler.klighd.internal.util.KlighdInternalProperties)1 KGraphElement (de.cau.cs.kieler.klighd.kgraph.KGraphElement)1 KGraphFactory (de.cau.cs.kieler.klighd.kgraph.KGraphFactory)1 KIdentifier (de.cau.cs.kieler.klighd.kgraph.KIdentifier)1 KNode (de.cau.cs.kieler.klighd.kgraph.KNode)1 ViewSynthesisShared (de.cau.cs.kieler.klighd.krendering.ViewSynthesisShared)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1