Search in sources :

Example 1 with Message

use of org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message in project VERDICT by ge-high-assurance.

the class ThreatModelUtil method getTypes.

/**
 * Build a map from type names to types. Traverses all files
 * in the current project looking for property declarations, which
 * are used to populate fields for the built-in types.
 *
 * Built-in types are system, connection, and port (also portDirection).
 *
 * This method is not very efficient, and it gets called several times
 * on every keystroke. Fortunately there still seems to be reasonably fast.
 * A crucial optimization will be caching the results because the set of
 * properties does not change that frequently.
 *
 * @param obj an AST node context, used to get access to project files
 * @param indexProvider an index provider, may be obtained through Guice
 * @return the constructed type map
 */
public static LinkedHashMap<String, VerdictType> getTypes(EObject obj, ResourceDescriptionsProvider indexProvider) {
    LinkedHashMap<String, VerdictType> types = new LinkedHashMap<>();
    // Three main built-in types
    BuiltInType connection = new BuiltInType("connection");
    BuiltInType port = new BuiltInType("port");
    BuiltInType system = new BuiltInType("system");
    addBuiltin(types, connection);
    addBuiltin(types, port);
    addBuiltin(types, system);
    // Connection fields
    connection.addField("inPort", port);
    connection.addField("outPort", port);
    connection.addField("source", system);
    connection.addField("dest", system);
    // Port direction
    BuiltInType portDir = new BuiltInType("portDirection");
    portDir.addValue("in");
    portDir.addValue("out");
    // Port fields
    port.addField("direction", portDir);
    port.addField("connections", connection.getListType());
    // System fields
    system.addField("subcomponents", system.getListType());
    system.addField("connections", connection.getListType());
    system.addField("ports", port.getListType());
    // Get the path to the current resource, used to get the project path
    String[] resSegments = obj.eResource().getURI().segments();
    // Iterate through all resources
    IResourceDescriptions index = indexProvider.getResourceDescriptions(obj.eResource());
    descLoop: for (IEObjectDescription desc : index.getExportedObjectsByType(Aadl2Package.eINSTANCE.getPropertySet())) {
        // Get the path to the resource we are examining
        String[] propsResSegments = desc.getEObjectURI().segments();
        // The project is determined by the first two URI segments
        for (int i = 0; i < Math.min(2, Math.min(resSegments.length, propsResSegments.length)); i++) {
            if (!resSegments[i].equals(propsResSegments[i])) {
                continue descLoop;
            }
        }
        // Load the resource into EMF-land; dynamically loads if necessary
        Resource res = obj.eResource().getResourceSet().getResource(desc.getEObjectURI(), true);
        if (res != null) {
            // Search the AST
            TreeIterator<EObject> it = res.getAllContents();
            while (it.hasNext()) {
                EObject next = it.next();
                if (next instanceof PropertySet) {
                    PropertySet props = (PropertySet) next;
                    // Iterate the declared properties
                    for (Element elem : props.getOwnedElements()) {
                        if (elem instanceof Property) {
                            Property prop = (Property) elem;
                            // Make sure type information is present
                            if (prop.getPropertyType() != null) {
                                // the types for which the property is a field
                                for (MetaclassReference meta : prop.getAppliesToMetaclasses()) {
                                    // Get type name, lowercase it because it is a class name
                                    String appliesToMetaclass = meta.getMetaclass().getName().toLowerCase();
                                    // Hopefully this is a type that we have accounted for
                                    if (types.containsKey(appliesToMetaclass)) {
                                        ((BuiltInType) types.get(appliesToMetaclass)).addField(prop.getName(), new AadlTypeWrapper(prop.getName(), prop.getPropertyType()));
                                    } else {
                                        // If we get this error message, then perhaps need to add
                                        // some built-in types
                                        System.err.println("could not find built in type: " + appliesToMetaclass);
                                    }
                                }
                            }
                        }
                    }
                    // Discard all children of the property set
                    it.prune();
                }
            }
        }
    }
    // Prevent synchronization issues
    portDir.lock();
    connection.lock();
    port.lock();
    system.lock();
    return types;
}
Also used : Element(org.osate.aadl2.Element) Resource(org.eclipse.emf.ecore.resource.Resource) AadlTypeWrapper(com.ge.research.osate.verdict.dsl.type.AadlTypeWrapper) BuiltInType(com.ge.research.osate.verdict.dsl.type.BuiltInType) LinkedHashMap(java.util.LinkedHashMap) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) VerdictType(com.ge.research.osate.verdict.dsl.type.VerdictType) IResourceDescriptions(org.eclipse.xtext.resource.IResourceDescriptions) EObject(org.eclipse.emf.ecore.EObject) PropertySet(org.osate.aadl2.PropertySet) MetaclassReference(org.osate.aadl2.MetaclassReference) TreeIterator(org.eclipse.emf.common.util.TreeIterator) Property(org.osate.aadl2.Property)

Example 2 with Message

use of org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message in project AGREE by loonwerks.

the class VerifyHandler method getSysInstance.

protected SystemInstance getSysInstance(ComponentImplementation ci, EphemeralImplementationUtil implUtil) {
    try {
        AnalysisErrorReporterManager errorManager = new AnalysisErrorReporterManager(QueuingAnalysisErrorReporter.factory);
        SystemInstance result = implUtil.generateEphemeralCompInstanceFromImplementation(ci);
        QueuingAnalysisErrorReporter errorReporter = (QueuingAnalysisErrorReporter) errorManager.getReporter(result.eResource());
        StringBuilder stringBuilder = new StringBuilder();
        List<Message> instantiationMarkers = errorReporter.getErrors();
        if (!instantiationMarkers.isEmpty()) {
            instantiationMarkers.stream().forEach(marker -> {
                stringBuilder.append(marker.message);
            });
            throw new AgreeException(stringBuilder.toString());
        }
        return result;
    } catch (Exception e) {
        Dialog.showError("Model Instantiate", "Error while re-instantiating the model: " + e.getMessage());
        throw new AgreeException("Error Instantiating model");
    }
}
Also used : Message(org.osate.aadl2.modelsupport.errorreporting.QueuingAnalysisErrorReporter.Message) SystemInstance(org.osate.aadl2.instance.SystemInstance) QueuingAnalysisErrorReporter(org.osate.aadl2.modelsupport.errorreporting.QueuingAnalysisErrorReporter) AgreeException(com.rockwellcollins.atc.agree.analysis.AgreeException) AnalysisErrorReporterManager(org.osate.aadl2.modelsupport.errorreporting.AnalysisErrorReporterManager) PartInitException(org.eclipse.ui.PartInitException) AgreeException(com.rockwellcollins.atc.agree.analysis.AgreeException) JKindException(jkind.JKindException)

Example 3 with Message

use of org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message in project AGREE by loonwerks.

the class VerifyHandler method getComponentImplementation.

protected ComponentImplementation getComponentImplementation(Element root, EphemeralImplementationUtil implUtil) {
    Classifier classifier = getOutermostClassifier(root);
    if (isRealizability()) {
        if (!(classifier instanceof ComponentType)) {
            throw new AgreeException("Must select an AADL Component Type");
        }
        ComponentImplementation result;
        try {
            result = implUtil.generateEphemeralCompImplFromType((ComponentType) classifier);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AgreeException("Error creating component implementation.");
        }
        return result;
    } else {
        if (classifier instanceof ComponentImplementation) {
            return (ComponentImplementation) classifier;
        }
        if (!(classifier instanceof ComponentType)) {
            throw new AgreeException("Must select an AADL Component Type or Implementation");
        }
        ComponentType ct = (ComponentType) classifier;
        List<ComponentImplementation> cis = getComponentImplementations(ct);
        if (cis.size() == 0) {
            throw new AgreeException("AADL Component Type has no implementation to verify");
        } else if (cis.size() == 1) {
            ComponentImplementation ci = cis.get(0);
            Shell shell = getWindow().getShell();
            String message = "User selected " + ct.getFullName() + ".\nRunning analysis on " + ci.getFullName() + " instead.";
            shell.getDisplay().asyncExec(() -> MessageDialog.openInformation(shell, "Analysis information", message));
            return ci;
        } else {
            throw new AgreeException("AADL Component Type has multiple implementations to verify: please select just one");
        }
    }
}
Also used : ComponentImplementation(org.osate.aadl2.ComponentImplementation) ComponentType(org.osate.aadl2.ComponentType) Shell(org.eclipse.swt.widgets.Shell) AgreeException(com.rockwellcollins.atc.agree.analysis.AgreeException) Classifier(org.osate.aadl2.Classifier) ComponentClassifier(org.osate.aadl2.ComponentClassifier) PartInitException(org.eclipse.ui.PartInitException) AgreeException(com.rockwellcollins.atc.agree.analysis.AgreeException) JKindException(jkind.JKindException)

Example 4 with Message

use of org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message in project osate2 by osate.

the class AnnexParserAgent method processAnnexSection.

/**
 * Common functionality for processing either a {@link DefaultAnnexLibrary} or a {@link DefaultAnnexSubclause}.
 * Processing involves parsing the text, attaching the resulting {@link AnnexLibrary} or {@link AnnexSubclause} to
 * the {@link DefaultAnnexLibrary} or {@link DefaultAnnexSubclause}, setting the modes for the resulting
 * {@link AnnexSubclause}, and either running the resolver or the linking service, depending upon which one if
 * available. If the resolver produces errors, then the {@link AnnexLibrary} or {@link AnnexSubclause} will be
 * detached from the {@link DefaultAnnexLibrary} or {@link DefaultAnnexSubclause}. All error, warning, and info
 * messages that are produced from the parser, resolver, or linker will be passed along to
 * {@code diagnosticsConsumer}.
 *
 * @param <A> Type of the resulting annex section. Expected to be {@link AnnexLibrary} or {@link AnnexSubclause}.
 * @param <D> Type of the default annex section. Expected to be {@link DefaultAnnexLibrary} or
 *            {@link DefaultAnnexSubclause}.
 * @param defaultAnnexSection Either the {@link DefaultAnnexLibrary} or {@link DefaultAnnexSubclause}.
 * @param annexText Either the value of {@link DefaultAnnexLibrary#getSourceText()} or
 *                  {@link DefaultAnnexSubclause#getSourceText()}.
 * @param filename Name of the AADL file containing the annex section.
 * @param diagnosticsConsumer Used for handling error, warning, and info messages.
 * @param parserFunction Either
 *                       {@link AnnexParser#parseAnnexLibrary(String, String, String, int, int, ParseErrorReporter)}
 *                       or
 *                       {@link AnnexParser#parseAnnexSubclause(String, String, String, int, int, ParseErrorReporter)}.
 * @param setParsedAnnexSection Either {@link DefaultAnnexLibrary#setSourceText(String)} or
 *                              {@link DefaultAnnexSubclause#setSourceText(String)}.
 * @param copyModes Function for copying modes from the {@link DefaultAnnexSubclause} into the newly created
 *                  {@link AnnexSubclause}. When processing an annex library, {@code copyModes} is expected to be a
 *                  no-op {@link Consumer}.
 */
private <A extends NamedElement, D extends A> void processAnnexSection(D defaultAnnexSection, String annexText, String filename, IDiagnosticConsumer diagnosticsConsumer, ParserFunction<A> parserFunction, Consumer<A> setParsedAnnexSection, Consumer<A> copyModes) {
    INode node = NodeModelUtils.findActualNodeFor(defaultAnnexSection);
    int line = node.getStartLine() + computeLineOffset(node);
    int offset = AnnexUtil.getAnnexOffset(defaultAnnexSection);
    // look for plug-in parser
    String annexName = defaultAnnexSection.getName();
    if (annexText != null && annexText.length() > 6 && annexName != null) {
        // strip {** **} from annex text
        if (annexText.startsWith("{**")) {
            annexText = annexText.substring(3, annexText.length() - 3);
        }
        annexName = AnnexModel.filterDisabledAnnexes(defaultAnnexSection, annexName);
        AnnexParser ap = PARSER_REGISTRY.getAnnexParser(annexName);
        try {
            QueuingParseErrorReporter parseErrReporter = new QueuingParseErrorReporter();
            parseErrReporter.setContextResource(defaultAnnexSection.eResource());
            if (defaultAnnexSection instanceof AnnexSubclause) {
                AnnexUtil.setCurrentAnnexSubclause((AnnexSubclause) defaultAnnexSection);
            }
            A annexSection = parserFunction.parse(ap, annexName, annexText, filename, line, offset, parseErrReporter);
            if (defaultAnnexSection instanceof AnnexSubclause) {
                AnnexUtil.setCurrentAnnexSubclause(null);
            }
            if (ParseResultHolder.Factory.INSTANCE.adapt(defaultAnnexSection).getParseResult() == null) {
                // Only consume messages for non-Xtext annexes
                consumeMessages(parseErrReporter, diagnosticsConsumer, annexText, line, offset);
            }
            if (annexSection != null) {
                annexSection.setName(annexName);
                setParsedAnnexSection.accept(annexSection);
                // copy in modes list
                copyModes.accept(annexSection);
                // now resolve reference so we get messages if we have references to undefined items
                AnnexResolver resolver = RESOLVER_REGISTRY.getAnnexResolver(annexName);
                AnnexLinkingService linkingService = LINKING_SERVICE_REGISTRY.getAnnexLinkingService(annexName);
                if (resolver != null && parseErrReporter.getNumErrors() == 0) {
                    // Don't resolve any annex with parsing errors.
                    QueuingParseErrorReporter resolveErrReporter = new QueuingParseErrorReporter();
                    AnalysisErrorReporterManager resolveErrManager = new AnalysisErrorReporterManager(new AnalysisToParseErrorReporterAdapter.Factory(aadlRsrc -> resolveErrReporter));
                    resolver.resolveAnnex(annexName, Collections.singletonList(annexSection), resolveErrManager);
                    consumeMessages(resolveErrReporter, diagnosticsConsumer, annexText, line, offset);
                    if (resolveErrReporter.getNumErrors() != 0) {
                        AnnexValidator.setNoValidation(defaultAnnexSection, annexName);
                    }
                } else if (linkingService != null) {
                    try {
                        XtextResource res = (XtextResource) defaultAnnexSection.eResource();
                        ILinker linker = res.getLinker();
                        linker.linkModel(annexSection, diagnosticsConsumer);
                    } catch (Exception e) {
                        String message = "Linking Service error in " + filename + " at line " + line;
                        IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message, e);
                        Activator.getDefault().getLog().log(status);
                    }
                }
            }
            if (parseErrReporter.getNumErrors() > 0) {
                AnnexValidator.setNoValidation(defaultAnnexSection, annexName);
            }
        } catch (RecognitionException e) {
            String message = "Major parsing error in " + filename + " at line " + line;
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message, e);
            Activator.getDefault().getLog().log(status);
        }
    }
}
Also used : AnnexParserRegistry(org.osate.annexsupport.AnnexParserRegistry) AnnexUtil(org.osate.annexsupport.AnnexUtil) StringUtils(org.apache.commons.lang.StringUtils) DefaultAnnexLibrary(org.osate.aadl2.DefaultAnnexLibrary) ParseErrorReporter(org.osate.aadl2.modelsupport.errorreporting.ParseErrorReporter) AnnexLinkingServiceRegistry(org.osate.annexsupport.AnnexLinkingServiceRegistry) AnalysisErrorReporterManager(org.osate.aadl2.modelsupport.errorreporting.AnalysisErrorReporterManager) Diagnostic(org.eclipse.xtext.diagnostics.Diagnostic) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) DefaultAnnexSubclause(org.osate.aadl2.DefaultAnnexSubclause) IStatus(org.eclipse.core.runtime.IStatus) RecognitionException(antlr.RecognitionException) AnnexLinkingService(org.osate.annexsupport.AnnexLinkingService) INode(org.eclipse.xtext.nodemodel.INode) AnnexRegistry(org.osate.annexsupport.AnnexRegistry) Message(org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message) XtextResource(org.eclipse.xtext.resource.XtextResource) AnnexParser(org.osate.annexsupport.AnnexParser) AnnexResolverRegistry(org.osate.annexsupport.AnnexResolverRegistry) Severity(org.eclipse.xtext.diagnostics.Severity) AnnexValidator(org.osate.annexsupport.AnnexValidator) Status(org.eclipse.core.runtime.Status) EObject(org.eclipse.emf.ecore.EObject) AadlPackage(org.osate.aadl2.AadlPackage) AnalysisToParseErrorReporterAdapter(org.osate.aadl2.modelsupport.errorreporting.AnalysisToParseErrorReporterAdapter) IDiagnosticConsumer(org.eclipse.xtext.diagnostics.IDiagnosticConsumer) ParseResultHolder(org.osate.annexsupport.ParseResultHolder) Consumer(java.util.function.Consumer) List(java.util.List) AnnexResolver(org.osate.annexsupport.AnnexResolver) AnnexModel(org.osate.annexsupport.AnnexModel) AnnexSubclause(org.osate.aadl2.AnnexSubclause) ILinker(org.eclipse.xtext.linking.ILinker) NamedElement(org.osate.aadl2.NamedElement) Activator(org.osate.xtext.aadl2.Activator) Collections(java.util.Collections) LazyLinker(org.eclipse.xtext.linking.lazy.LazyLinker) AnnexLibrary(org.osate.aadl2.AnnexLibrary) QueuingParseErrorReporter(org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) INode(org.eclipse.xtext.nodemodel.INode) ILinker(org.eclipse.xtext.linking.ILinker) IStatus(org.eclipse.core.runtime.IStatus) AnnexParser(org.osate.annexsupport.AnnexParser) XtextResource(org.eclipse.xtext.resource.XtextResource) AnalysisErrorReporterManager(org.osate.aadl2.modelsupport.errorreporting.AnalysisErrorReporterManager) RecognitionException(antlr.RecognitionException) AnalysisToParseErrorReporterAdapter(org.osate.aadl2.modelsupport.errorreporting.AnalysisToParseErrorReporterAdapter) AnnexLinkingService(org.osate.annexsupport.AnnexLinkingService) AnnexResolver(org.osate.annexsupport.AnnexResolver) QueuingParseErrorReporter(org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter) DefaultAnnexSubclause(org.osate.aadl2.DefaultAnnexSubclause) AnnexSubclause(org.osate.aadl2.AnnexSubclause) RecognitionException(antlr.RecognitionException)

Example 5 with Message

use of org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message in project osate2 by osate.

the class AnnexParserAgent method consumeMessages.

private static void consumeMessages(QueuingParseErrorReporter errReporter, IDiagnosticConsumer diagnosticsConsumer, String annexText, int annexLine, int annexOffset) {
    for (Message message : errReporter.getErrors()) {
        int lineOffset = StringUtils.ordinalIndexOf(annexText, "\n", message.line - annexLine) + 1;
        int endOfLine = annexText.indexOf('\n', lineOffset);
        if (endOfLine == -1) {
            endOfLine = annexText.length();
        } else if (endOfLine > 0 && annexText.charAt(endOfLine - 1) == '\r') {
            endOfLine--;
        }
        int diagnosticOffset = annexOffset + lineOffset;
        int diagnosticLength = endOfLine - lineOffset;
        Diagnostic diagnostic = new Diagnostic() {

            @Override
            public String getMessage() {
                return message.message;
            }

            @Override
            public String getLocation() {
                return null;
            }

            @Override
            public int getLine() {
                return message.line;
            }

            @Override
            public int getColumn() {
                return 1;
            }

            @Override
            public int getOffset() {
                return diagnosticOffset;
            }

            @Override
            public int getLength() {
                return diagnosticLength;
            }

            @Override
            public int getLineEnd() {
                return 0;
            }

            @Override
            public int getColumnEnd() {
                return 0;
            }
        };
        Severity severity;
        if (QueuingParseErrorReporter.ERROR.equals(message.kind)) {
            severity = Severity.ERROR;
        } else if (QueuingParseErrorReporter.WARNING.equals(message.kind)) {
            severity = Severity.WARNING;
        } else if (QueuingParseErrorReporter.INFO.equals(message.kind)) {
            severity = Severity.INFO;
        } else {
            severity = null;
        }
        diagnosticsConsumer.consume(diagnostic, severity);
    }
}
Also used : Message(org.osate.aadl2.modelsupport.errorreporting.QueuingParseErrorReporter.Message) Diagnostic(org.eclipse.xtext.diagnostics.Diagnostic) Severity(org.eclipse.xtext.diagnostics.Severity)

Aggregations

EObject (org.eclipse.emf.ecore.EObject)7 NamedElement (org.osate.aadl2.NamedElement)7 ComponentClassifier (org.osate.aadl2.ComponentClassifier)6 HashSet (java.util.HashSet)5 Classifier (org.osate.aadl2.Classifier)5 ArrayList (java.util.ArrayList)4 Element (org.osate.aadl2.Element)4 InstanceObject (org.osate.aadl2.instance.InstanceObject)4 AgreeException (com.rockwellcollins.atc.agree.analysis.AgreeException)3 Set (java.util.Set)3 FeatureInstance (org.osate.aadl2.instance.FeatureInstance)3 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 List (java.util.List)2 JKindException (jkind.JKindException)2 TreeIterator (org.eclipse.emf.common.util.TreeIterator)2 PartInitException (org.eclipse.ui.PartInitException)2 Diagnostic (org.eclipse.xtext.diagnostics.Diagnostic)2 Severity (org.eclipse.xtext.diagnostics.Severity)2 INode (org.eclipse.xtext.nodemodel.INode)2