@Override protected List<Diagnostic> getScriptErrors(Script script) { EcoreUtil.resolveAll(script.eResource()); List<Diagnostic> diagnostics = super.getScriptErrors(script); Iterator<Expression> expressions = Iterators.filter(EcoreUtil2.eAll(script), Expression.class); List<Diagnostic> result = Lists.<Diagnostic> newArrayList(Iterables.filter(diagnostics, ExceptionDiagnostic.class)); while (expressions.hasNext()) { Expression expression = expressions.next(); RuleEnvironment ruleEnvironment = RuleEnvironmentExtensions.newRuleEnvironment(expression); Result<TypeRef> type = typeSystem.type(ruleEnvironment, expression); if (type.getRuleFailedException() != null) { Throwable cause = Throwables.getRootCause(type.getRuleFailedException()); if (!(cause instanceof RuleFailedException)) { if (cause instanceof Exception) { result.add(new ExceptionDiagnostic((Exception) cause)); } else { throw new RuntimeException(cause); } } } } validator.validate(script.eResource(), CheckMode.ALL, CancelIndicator.NullImpl); return result; }
/** * The heuristically computed this target, but not the directly containing function, in which the expression (or any * other object) is (indirectly) contained, may be null. This typically is an {@link ObjectLiteral}, an * {@link N4ClassDeclaration}, or another outer {@link FunctionDefinition}. Note that for expressions contained in * property name value pairs, it is <b>not</b> the object literal. * <p> * cf. ECMAScript spec 10.4.3 Entering Function Code * </p> */ public static ThisTarget getProbableThisTarget(EObject location) { if (location == null || location.eContainer() == null) { return null; } final ThisArgProvider thisArgProvider = location instanceof N4MethodDeclaration ? (N4MethodDeclaration) location : EcoreUtil2.getContainerOfType(location.eContainer(), ThisArgProvider.class); if (thisArgProvider == null) { return null; } final ThisTarget thisTarget = EcoreUtil2.getContainerOfType(thisArgProvider.eContainer(), ThisTarget.class); if (thisTarget != null) { ThisArgProvider indirectThisArgProvider = EcoreUtil2.getContainerOfType(thisArgProvider.eContainer(), ThisArgProvider.class); if (indirectThisArgProvider != null && EcoreUtil.isAncestor(thisTarget, indirectThisArgProvider)) { return null; // nested function } } return thisTarget; }
private ControlFlowElement findPrecedingStatement(ControlFlowElement cfe) { ControlFlowElement precedingStatement = null; Statement stmt = EcoreUtil2.getContainerOfType(cfe, Statement.class); if (stmt != null) { EObject stmtContainer = stmt.eContainer(); if (stmtContainer != null && stmtContainer instanceof Block) { Block block = (Block) stmtContainer; EList<Statement> stmts = block.getStatements(); int index = stmts.indexOf(stmt); if (index > 0) { precedingStatement = stmts.get(index - 1); } } } return precedingStatement; }
/** * Computes the list of virtual AccessorTuples for missing fields. * * @return List of {@link VirtualApiTField} */ private List<AccessorTuple> computeMissingApiFields(TClass declaration) { Optional<ProjectComparisonAdapter> optAdapt = firstProjectComparisonAdapter(declaration.eResource()); if (optAdapt.isPresent()) { ProjectComparisonEntry compareEntry = optAdapt.get().getEntryFor( EcoreUtil2.getContainerOfType(declaration, TModule.class)); ProjectComparisonEntry typeCompare = compareEntry.getChildForElementImpl(declaration); if (typeCompare != null) { return typeCompare.allChildren() .filter(pce -> pce.getElementAPI() instanceof TField) .filter(pce -> pce.getElementImpl()[0] == null) // only go for empty impl. .map(pce -> { TField apiField = (TField) pce.getElementAPI(); VirtualApiMissingFieldAccessorTuple ret = createVirtFieldAccessorTuple(apiField); return ret; }) .collect(Collectors.toList()); } } return emptyList(); }
/** * Computes the list of virtual fields. * * @return List of {@link VirtualApiTField} */ public List<TField> computeMissingApiFields(N4InterfaceDeclaration declaration) { Optional<ProjectComparisonAdapter> optAdapt = firstProjectComparisonAdapter(declaration.eResource()); if (optAdapt.isPresent()) { ProjectComparisonEntry compareEntry = optAdapt.get().getEntryFor( EcoreUtil2.getContainerOfType(declaration.getDefinedType(), TModule.class)); ProjectComparisonEntry typeCompare = compareEntry.getChildForElementImpl(declaration .getDefinedTypeAsInterface()); if (typeCompare != null) { return typeCompare.allChildren() .filter(pce -> pce.getElementAPI() instanceof TField) .filter(pce -> pce.getElementImpl()[0] == null) // only go for empty implementations .map(pce -> { TField apiMethod = (TField) pce.getElementAPI(); // do not touch AST on copy!: TField copy = TypeUtils.copyPartial(apiMethod, TypesPackage.Literals.SYNTAX_RELATED_TELEMENT__AST_ELEMENT); TField ret = new VirtualApiTField(apiMethod.getName(), copy); return ret; }) .collect(Collectors.toList()); } } return emptyList(); }
@Override public void collectAbstractElements(Grammar grammar, EStructuralFeature feature, IFollowElementAcceptor followElementAcceptor) { for (Grammar superGrammar : grammar.getUsedGrammars()) { collectAbstractElements(superGrammar, feature, followElementAcceptor); } EClass declarator = feature.getEContainingClass(); for (ParserRule rule : GrammarUtil.allParserRules(grammar)) { for (Assignment assignment : GrammarUtil.containedAssignments(rule)) { if (assignment.getFeature().equals(feature.getName())) { EClassifier classifier = GrammarUtil.findCurrentType(assignment); EClassifier compType = EcoreUtil2.getCompatibleType(declarator, classifier); if (compType == declarator) { followElementAcceptor.accept(assignment); } } } } }
private static void rewriteKeywords(AbstractRule rule, N4JSKeywords keywords, ImmutableMap.Builder<AbstractElement, Integer> builder) { for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) { if (obj instanceof Keyword) { Keyword keyword = (Keyword) obj; Integer type = keywords.getTokenType(keyword); if (type != null) { if (keyword.eContainer() instanceof EnumLiteralDeclaration) { builder.put((AbstractElement) keyword.eContainer(), type); } else { builder.put(keyword, type); } } } } }
private static void rewriteTypeReferences(N4JSGrammarAccess ga, ImmutableMap.Builder<AbstractElement, Integer> builder) { for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) { for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) { if (obj instanceof Assignment) { Assignment assignment = (Assignment) obj; AbstractElement terminal = assignment.getTerminal(); if (terminal instanceof RuleCall) { AbstractRule calledRule = ((RuleCall) terminal).getRule(); EClassifier classifier = calledRule.getType().getClassifier(); if (classifier instanceof EClass && TypeRefsPackage.Literals.TYPE_REF.isSuperTypeOf((EClass) classifier)) { builder.put(assignment, TYPE_REF_TOKEN); } } } } } }
private static void rewriteIdentifiers(N4JSGrammarAccess ga, ImmutableMap.Builder<AbstractElement, Integer> builder) { ImmutableSet<AbstractRule> identifierRules = ImmutableSet.of( ga.getBindingIdentifierRule(), ga.getIdentifierNameRule(), ga.getIDENTIFIERRule()); for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) { for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) { if (obj instanceof Assignment) { Assignment assignment = (Assignment) obj; AbstractElement terminal = assignment.getTerminal(); int type = InternalN4JSParser.RULE_IDENTIFIER; if (terminal instanceof CrossReference) { terminal = ((CrossReference) terminal).getTerminal(); type = IDENTIFIER_REF_TOKEN; } if (terminal instanceof RuleCall) { AbstractRule calledRule = ((RuleCall) terminal).getRule(); if (identifierRules.contains(calledRule)) { builder.put(assignment, type); } } } } } }
private static void rewriteNumberLiterals(N4JSGrammarAccess ga, ImmutableMap.Builder<AbstractElement, Integer> builder) { for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) { for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) { if (obj instanceof Assignment) { Assignment assignment = (Assignment) obj; AbstractElement terminal = assignment.getTerminal(); if (terminal instanceof RuleCall) { AbstractRule calledRule = ((RuleCall) terminal).getRule(); EClassifier classifier = calledRule.getType().getClassifier(); if (classifier == EcorePackage.Literals.EBIG_DECIMAL) { builder.put(assignment, NUMBER_LITERAL_TOKEN); } } } } } }
private boolean referenceHasBeenFound(Predicate<URI> targetURIs, URI refURI, EObject instanceOrProxy) { boolean result = false; // If the EObject is a composed member, we compare the target URIs with the URIs of the constituent members. if (instanceOrProxy instanceof TMember && ((TMember) instanceOrProxy).isComposed()) { TMember member = (TMember) instanceOrProxy; if (member.isComposed()) { for (TMember constituentMember : member.getConstituentMembers()) { URI constituentReffURI = EcoreUtil2 .getPlatformResourceOrNormalizedURI(constituentMember); result = result || targetURIs.apply(constituentReffURI); } } } else { // Standard case result = targetURIs.apply(refURI); } return result; }
/** * Returns the actual receiver type, which usually simply is the declared type of the receiver type. However, in * case of classifier references, enums, or structural type references, the actual receiver may be differently * computed. */ private Type getActualDeclaredReceiverType(EObject context, TypeRef receiverType, ResourceSet resourceSet) { if (receiverType instanceof TypeTypeRef) { final RuleEnvironment G = RuleEnvironmentExtensions.newRuleEnvironment(context); return tsh.getStaticType(G, (TypeTypeRef) receiverType); } if (receiverType instanceof ThisTypeRef) { ThisTypeRef thisTypeRef = (ThisTypeRef) receiverType; if (thisTypeRef.isUseSiteStructuralTyping()) { FunctionOrFieldAccessor foa = N4JSASTUtils.getContainingFunctionOrAccessor(thisTypeRef); N4ClassifierDefinition classifier = EcoreUtil2.getContainerOfType(foa, N4ClassifierDefinition.class); return classifier.getDefinedType(); } } if (receiverType instanceof FunctionTypeExpression) { if (resourceSet == null) return null; // Change receiverType to implicit super class Function. BuiltInTypeScope builtInTypeScope = BuiltInTypeScope.get(resourceSet); TObjectPrototype functionType = builtInTypeScope.getFunctionType(); return functionType; } return receiverType.getDeclaredType(); }
private boolean shortcutIsVisible(TMember candidate, Type contextType, TModule contextModule, Type receiverType) { /* Members of the same type are always visible */ if (receiverType == contextType && contextType == candidate.eContainer()) { return true; } /* * object literals do not constrain accessibility */ if (receiverType instanceof TStructuralType) { return true; } /* * Members of the same module are always visible */ if (contextModule == EcoreUtil2.getContainerOfType(candidate, TModule.class)) { return true; } return false; }
protected void checkIsValidConstructorArgument(XExpression argument, JvmType containerType) { TreeIterator<EObject> iterator = EcoreUtil2.eAll(argument); while(iterator.hasNext()) { EObject partOfArgumentExpression = iterator.next(); if (partOfArgumentExpression instanceof XFeatureCall || partOfArgumentExpression instanceof XMemberFeatureCall) { XAbstractFeatureCall featureCall = (XAbstractFeatureCall) partOfArgumentExpression; XExpression actualReceiver = featureCall.getActualReceiver(); if(actualReceiver instanceof XFeatureCall && ((XFeatureCall)actualReceiver).getFeature() == containerType) { JvmIdentifiableElement feature = featureCall.getFeature(); if (feature != null && !feature.eIsProxy()) { if (feature instanceof JvmField) { if (!((JvmField) feature).isStatic()) error("Cannot refer to an instance field " + feature.getSimpleName() + " while explicitly invoking a constructor", partOfArgumentExpression, null, INVALID_CONSTRUCTOR_ARGUMENT); } else if (feature instanceof JvmOperation) { if (!((JvmOperation) feature).isStatic()) error("Cannot refer to an instance method while explicitly invoking a constructor", partOfArgumentExpression, null, INVALID_CONSTRUCTOR_ARGUMENT); } } } } else if(isLocalClassSemantics(partOfArgumentExpression)) { iterator.prune(); } } }
protected void checkValidReturn(XReturnExpression object, ITypeComputationState state) { // if the expectation comes from a method's return type // then it is legal, thus we must check if the return is // contained in a throw expression if (hasThrowableExpectation(state) && EcoreUtil2.getContainerOfType(object, XThrowExpression.class) != null) { state.addDiagnostic(new EObjectDiagnosticImpl( Severity.ERROR, IssueCodes.INVALID_RETURN, "Invalid return inside throw.", object, null, -1, new String[] { })); } }
@Override // CHECKSTYLE:OFF protected void _toJavaExpression(final XAbstractFeatureCall expr, final ITreeAppendable b) { // CHECKSTYLE:ON FormalParameter parameter = getFormalParameter(expr); if (parameter != null) { // No Java entities are generated for this. Replace by a call to the getter function. b.append(generatorNaming.catalogInstanceName(parameter)).append(".").append(generatorNaming.formalParameterGetterName(parameter)); b.append("(").append(getContextImplicitVariableName(expr)).append(")"); } else { Member member = getMember(expr); if (member != null) { // Something isn't quite right in the Jvm model yet... or in the xbase compiler. Don't know what it is, but even if in an inner // class, it generates "this.foo" instead of either just "foo" or "OuterClass.this.foo". Force it to produce the latter. CheckCatalog catalog = EcoreUtil2.getContainerOfType(member, CheckCatalog.class); String catalogName = generatorNaming.validatorClassName(catalog); b.append(catalogName + ".this.").append(member.getName()); return; } super._toJavaExpression(expr, b); } }
@Test public void testgetReferenceDescriptionForMultiValue() throws Exception { with(new LangATestLanguageStandaloneSetup()); XtextResource targetResource = getResource("type C type D", "bar.langatestlanguage"); EObject typeC = targetResource.getContents().get(0).eContents().get(0); EObject typeD = targetResource.getContents().get(0).eContents().get(1); XtextResource resource = (XtextResource) targetResource.getResourceSet().createResource(URI.createURI("foo.langatestlanguage")); resource.load(new StringInputStream("type A implements B,C,D type B"), null); EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl); IResourceDescription resDesc = resource.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(resource); Iterable<IReferenceDescription> descriptions = resDesc.getReferenceDescriptions(); Collection<IReferenceDescription> collection = Lists.newArrayList(descriptions); assertEquals(2,collection.size()); Iterator<IReferenceDescription> iterator = descriptions.iterator(); IReferenceDescription refDesc1 = iterator.next(); IReferenceDescription refDesc2 = iterator.next(); Main m = (Main) resource.getParseResult().getRootASTElement(); assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc1.getSourceEObjectUri(),false)); assertEquals(typeC,resource.getResourceSet().getEObject(refDesc1.getTargetEObjectUri(),false)); assertEquals(1,refDesc1.getIndexInList()); assertEquals(LangATestLanguagePackage.Literals.TYPE__IMPLEMENTS,refDesc1.getEReference()); assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc2.getSourceEObjectUri(),false)); assertEquals(typeD,resource.getResourceSet().getEObject(refDesc2.getTargetEObjectUri(),false)); assertEquals(2,refDesc2.getIndexInList()); assertEquals(LangATestLanguagePackage.Literals.TYPE__IMPLEMENTS,refDesc2.getEReference()); }
@Override public IScope getScope(EObject context, EReference reference) { if (reference == XAnnotationsPackage.Literals.XANNOTATION_ELEMENT_VALUE_PAIR__ELEMENT) { XAnnotation annotation = EcoreUtil2.getContainerOfType(context, XAnnotation.class); JvmType annotationType = annotation.getAnnotationType(); if (annotationType == null || annotationType.eIsProxy() || !(annotationType instanceof JvmAnnotationType)) { return IScope.NULLSCOPE; } Iterable<JvmOperation> operations = ((JvmAnnotationType) annotationType).getDeclaredOperations(); Iterable<IEObjectDescription> descriptions = transform(operations, new Function<JvmOperation, IEObjectDescription>() { @Override public IEObjectDescription apply(JvmOperation from) { return EObjectDescription.create(QualifiedName.create(from.getSimpleName()), from); } }); return MapBasedScope.createScope(IScope.NULLSCOPE, descriptions); } return super.getScope(context, reference); }
protected JvmType findKnownTopLevelType(Class<?> rawType, Notifier context) { if (rawType.isArray()) { throw new IllegalArgumentException(rawType.getCanonicalName()); } if (rawType.isPrimitive()) { throw new IllegalArgumentException(rawType.getName()); } ResourceSet resourceSet = EcoreUtil2.getResourceSet(context); if (resourceSet == null) { return null; } Resource typeResource = resourceSet.getResource(URIHelperConstants.OBJECTS_URI.appendSegment(rawType.getName()), true); List<EObject> resourceContents = typeResource.getContents(); if (resourceContents.isEmpty()) return null; JvmType type = (JvmType) resourceContents.get(0); return type; }
@Override public JvmDeclaredType getContextJvmDeclaredType(EObject model) { if(model != null) { JvmIdentifiableElement logicalContainer = logicalContainerProvider.getNearestLogicalContainer(model); if(logicalContainer != null) return EcoreUtil2.getContainerOfType(logicalContainer, JvmDeclaredType.class); EObject currentElement = model; do { for(EObject jvmElement: associations.getJvmElements(currentElement)) { if(jvmElement instanceof JvmDeclaredType) return (JvmDeclaredType) jvmElement; } currentElement = currentElement.eContainer(); } while (currentElement != null); } return null; }
protected JvmTypeReference getJavaLangObjectTypeRef(JvmType rawType, TypesFactory typesFactory) { ResourceSet rs = EcoreUtil2.getResourceSet(rawType); JvmParameterizedTypeReference refToObject = typesFactory.createJvmParameterizedTypeReference(); if (rs != null) { EObject javaLangObject = rs.getEObject(javaLangObjectURI, true); if (javaLangObject instanceof JvmType) { JvmType objectDeclaration = (JvmType) javaLangObject; refToObject.setType(objectDeclaration); return refToObject; } } JvmGenericType proxy = typesFactory.createJvmGenericType(); ((InternalEObject)proxy).eSetProxyURI(javaLangObjectURI); refToObject.setType(proxy); return refToObject; }
/** * @Nullable */ protected String getTypeName(final EClass c, final EStructuralFeature referingFeature) { if ((referingFeature == XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE)) { return " to an annotation type"; } if ((c == TypesPackage.Literals.JVM_ENUMERATION_TYPE)) { return " to an enum type"; } boolean _isAssignableFrom = EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_TYPE, c); if (_isAssignableFrom) { return " to a type"; } if ((c == TypesPackage.Literals.JVM_OPERATION)) { return " to an operation"; } return ""; }
protected void computeReferencedJvmTypeHighlighting(IHighlightedPositionAcceptor acceptor, EObject referencer, CancelIndicator cancelIndicator) { for (EReference reference : referencer.eClass().getEAllReferences()) { EClass referencedType = reference.getEReferenceType(); if (EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_TYPE, referencedType)) { List<EObject> referencedObjects = EcoreUtil2.getAllReferencedObjects(referencer, reference); if (referencedObjects.size() > 0) operationCanceledManager.checkCanceled(cancelIndicator); for (EObject referencedObject : referencedObjects) { EObject resolvedReferencedObject = EcoreUtil.resolve(referencedObject, referencer); if (resolvedReferencedObject != null && !resolvedReferencedObject.eIsProxy()) { highlightReferenceJvmType(acceptor, referencer, reference, resolvedReferencedObject); } } } } }
protected Iterable<AbstractElement> getEObjectElements(final AbstractRule rule) { final Function1<AbstractElement, Boolean> _function = (AbstractElement element) -> { boolean _switchResult = false; boolean _matched = false; if (element instanceof Action) { _matched=true; } if (!_matched) { if (element instanceof RuleCall) { boolean _isEObjectRuleCall = GrammarUtil.isEObjectRuleCall(element); if (_isEObjectRuleCall) { _matched=true; } } } if (_matched) { _switchResult = true; } if (!_matched) { _switchResult = false; } return Boolean.valueOf(_switchResult); }; return IterableExtensions.<AbstractElement>filter(EcoreUtil2.<AbstractElement>eAllOfType(rule, AbstractElement.class), _function); }
/** * Checks that no explicit . * This check is either implicit (inside a context) or explicit (inside an independent implementation) * * @param expression * the expression */ @Check public void checkImplicitIssuedCheck(final XIssueExpression expression) { com.avaloq.tools.ddk.check.check.Check container = EcoreUtil2.getContainerOfType(expression, com.avaloq.tools.ddk.check.check.Check.class); if (container == null) { return; } if (expression.getCheck() != null && !expression.getCheck().eIsProxy()) { if (expression.getCheck() == container) { // if the issued check is that of the containing issue, then we only emit a warning warning(Messages.CheckJavaValidator_ISSUE_REFERS_TO_IMPLICIT_CHECK, CheckPackage.Literals.XISSUE_EXPRESSION__CHECK, IssueCodes.IMPLICIT_ISSUED_CHECK); } else { error(Messages.CheckJavaValidator_ISSUE_REFERS_TO_EXPLICIT_CHECK, CheckPackage.Literals.XISSUE_EXPRESSION__CHECK, IssueCodes.IMPLICIT_ISSUED_CHECK); } } }
public void collectAbstractElements(Grammar grammar, EStructuralFeature feature, IFollowElementAcceptor followElementAcceptor) { for (Grammar superGrammar : grammar.getUsedGrammars()) { collectAbstractElements(superGrammar, feature, followElementAcceptor); } EClass declarator = feature.getEContainingClass(); for (ParserRule rule : GrammarUtil.allParserRules(grammar)) { for (Assignment assignment : GrammarUtil.containedAssignments(rule)) { if (assignment.getFeature().equals(feature.getName())) { EClassifier classifier = GrammarUtil.findCurrentType(assignment); EClassifier compType = EcoreUtil2.getCompatibleType(declarator, classifier); if (compType == declarator) { followElementAcceptor.accept(assignment); } } } } }
@Override public String[] getExportedPackagesRt(Grammar grammar) { List<GeneratedMetamodel> typeSelect = org.eclipse.xtext.EcoreUtil2.typeSelect( grammar.getMetamodelDeclarations(), GeneratedMetamodel.class); Set<String> exportedPackages = new LinkedHashSet<String>(); if (modelPluginID == null) { for (GeneratedMetamodel generatedMetamodel : typeSelect) { final String modelPackage = Strings.skipLastToken( getGeneratedEPackageName(grammar, generatedMetamodel.getEPackage()), "."); exportedPackages.add(modelPackage); exportedPackages.add(modelPackage + ".impl"); exportedPackages.add(modelPackage + ".util"); } } return exportedPackages.toArray(new String[exportedPackages.size()]); }
@Override public JvmDeclaredType createType(Class<?> clazz) { try { JvmDeclaredType cachedResult = get(clazz); // the cached result contains proxies and is not // contained in a resource set. clone it since the // client of #createClass will usually put the result // into a resource and perform proxy resolution afterwards // in the context of a single resource set. return EcoreUtil2.cloneWithProxies(cachedResult); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } return delegate.createType(clazz); } }
@Override public JvmDeclaredType createType(BinaryClass clazz) { try { JvmDeclaredType cachedResult = get(clazz); // the cached result contains proxies and is not // contained in a resource set. clone it since the // client of #createClass will usually put the result // into a resource and perform proxy resolution afterwards // in the context of a single resource set. return EcoreUtil2.cloneWithProxies(cachedResult); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } return delegate.createType(clazz); } }
/** * looks up a JVMType corresponding to the given {@link Class}. This method ignores any Jvm types created in non- * {@link TypeResource} in the given context's resourceSet, but goes straight to the Java-layer, using a * {@link IJvmTypeProvider}. * * @return the JvmType with the same qualified name as the given {@link Class} object, or null if no such JvmType * could be found using the context's resourceSet. */ public JvmType findDeclaredType(String typeName, Notifier context) { if (typeName == null) throw new NullPointerException("typeName"); if (context == null) throw new NullPointerException("context"); ResourceSet resourceSet = EcoreUtil2.getResourceSet(context); if (resourceSet == null) return null; // make sure a type provider is configured in the resource set. IJvmTypeProvider typeProvider = typeProviderFactory.findOrCreateTypeProvider(resourceSet); try { final JvmType result = typeProvider.findTypeByName(typeName); return result; } catch (RuntimeException e) { operationCanceledManager.propagateAsErrorIfCancelException(e); log.info("Couldn't find JvmType for name '" + typeName + "' in context " + context, e); return null; } }
@Check public void checkGeneratedEnumIsValid(EnumLiteralDeclaration decl) { EnumRule rule = GrammarUtil.containingEnumRule(decl); if (!(rule.getType().getMetamodel() instanceof GeneratedMetamodel)) return; if (!(rule.getType().getClassifier() instanceof EEnum)) return; EEnum eEnum = (EEnum) rule.getType().getClassifier(); List<EnumLiteralDeclaration> declarations = EcoreUtil2.getAllContentsOfType(rule, EnumLiteralDeclaration.class); if (declarations.size() == eEnum.getELiterals().size()) return; for (EnumLiteralDeclaration otherDecl : declarations) { if (decl == otherDecl) { return; } if (otherDecl.getEnumLiteral() == decl.getEnumLiteral()) { if (!decl.getEnumLiteral().getLiteral().equals(decl.getLiteral().getValue())) addIssue("Enum literal '" + decl.getEnumLiteral().getName() + "' has already been defined with literal '" + decl.getEnumLiteral().getLiteral() + "'.", decl, XtextPackage.Literals.ENUM_LITERAL_DECLARATION__ENUM_LITERAL, DUPLICATE_ENUM_LITERAL); return; } } }
/** {@inheritDoc} */ @Override public void apply(final IModificationContext context) throws BadLocationException { final IXtextDocument xtextDocument = context.getXtextDocument(); xtextDocument.readOnly(new IUnitOfWork.Void<XtextResource>() { @Override public void process(final XtextResource state) throws Exception { // NOPMD final EObject target = EcoreUtil2.getContainerOfType(state.getEObject(issue.getUriToProblem().fragment()), type); if (type.isInstance(target)) { int offset = NodeModelUtils.findActualNodeFor(target).getOffset(); int lineOfOffset = xtextDocument.getLineOfOffset(offset); int lineOffset = xtextDocument.getLineOffset(lineOfOffset); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < (offset - lineOffset); i++) { buffer.append(' '); } xtextDocument.replace(offset, 0, NLS.bind(autodocumentation, buffer.toString())); } } }); }
protected List<IReferenceDescription> computeReferenceDescriptions() { final List<IReferenceDescription> referenceDescriptions = Lists.newArrayList(); IAcceptor<IReferenceDescription> acceptor = new IAcceptor<IReferenceDescription>() { @Override public void accept(IReferenceDescription referenceDescription) { referenceDescriptions.add(referenceDescription); } }; EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl); Map<EObject, IEObjectDescription> eObject2exportedEObjects = createEObject2ExportedEObjectsMap(getExportedObjects()); TreeIterator<EObject> contents = EcoreUtil.getAllProperContents(this.resource, true); while (contents.hasNext()) { EObject eObject = contents.next(); URI exportedContainerURI = findExportedContainerURI(eObject, eObject2exportedEObjects); if (!strategy.createReferenceDescriptions(eObject, exportedContainerURI, acceptor)) contents.prune(); } return referenceDescriptions; }
public List<CrossReference> findCrossReferences(EClassifier... targetEClassifiers) { Set<EClassifier> classifiers = new HashSet<EClassifier>(Arrays.asList(targetEClassifiers)); Collection<EClass> classes = Lists.newArrayList(Iterables.filter(classifiers, EClass.class)); ArrayList<CrossReference> r = new ArrayList<CrossReference>(); for (AbstractRule ar : getRules()) { TreeIterator<EObject> i = ar.eAllContents(); while (i.hasNext()) { EObject o = i.next(); if (o instanceof CrossReference) { CrossReference c = (CrossReference) o; if (classifiers.contains(c.getType().getClassifier())) r.add(c); else if (c.getType().getClassifier() instanceof EClass) for (EClass cls : classes) if (EcoreUtil2.isAssignableFrom(cls,(EClass) c.getType().getClassifier())) { r.add(c); break; } i.prune(); } } } return r; }
@Override public IResourceDescription getResourceDescription(URI uri) { IResourceDescription result = delegate.getResourceDescription(uri); if (result == null) { Resource resource = EcoreUtil2.getResource(context, uri.toString()); if (resource != null) { IResourceServiceProvider serviceProvider = serviceProviderRegistry.getResourceServiceProvider(uri); if (serviceProvider==null) throw new IllegalStateException("No "+IResourceServiceProvider.class.getSimpleName()+" found in registry for uri "+uri); final Manager resourceDescriptionManager = serviceProvider.getResourceDescriptionManager(); if (resourceDescriptionManager == null) throw new IllegalStateException("No "+IResourceDescription.Manager.class.getName()+" provided by service provider for URI "+uri); result = resourceDescriptionManager.getResourceDescription(resource); } } return result; }
protected LinkedHashSet<URI> getImportedUris(final Resource resource) { return cache.get(ImportUriGlobalScopeProvider.class.getName(), resource, new Provider<LinkedHashSet<URI>>(){ @Override public LinkedHashSet<URI> get() { final LinkedHashSet<URI> uniqueImportURIs = new LinkedHashSet<URI>(5); IAcceptor<String> collector = createURICollector(resource, uniqueImportURIs); TreeIterator<EObject> iterator = resource.getAllContents(); while (iterator.hasNext()) { EObject object = iterator.next(); collector.accept(importResolver.apply(object)); } Iterator<URI> uriIter = uniqueImportURIs.iterator(); while(uriIter.hasNext()) { if (!EcoreUtil2.isValidUri(resource, uriIter.next())) uriIter.remove(); } return uniqueImportURIs; } }); }
@Override public Iterable<IEObjectDescription> getExportedObjectsByObject(final EObject object) { if (allDescriptions.isEmpty()) return Collections.emptyList(); final URI uri = EcoreUtil2.getPlatformResourceOrNormalizedURI(object); return Iterables.filter(allDescriptions, new Predicate<IEObjectDescription>() { @Override public boolean apply(IEObjectDescription input) { if (input.getEObjectOrProxy() == object) return true; if (uri.equals(input.getEObjectURI())) { return true; } return false; } }); }
@Override public void setContext(final Notifier ctx) { IResourceDescriptions _localDescriptions = this.getLocalDescriptions(); final Procedure1<ResourceSetBasedResourceDescriptions> _function = (ResourceSetBasedResourceDescriptions it) -> { it.setContext(ctx); it.setData(null); }; ObjectExtensions.<ResourceSetBasedResourceDescriptions>operator_doubleArrow(((ResourceSetBasedResourceDescriptions) _localDescriptions), _function); final ResourceSet resourceSet = EcoreUtil2.getResourceSet(ctx); this.setGlobalDescriptions(ChunkedResourceDescriptions.findInEmfObject(resourceSet)); IProjectConfig _projectConfig = null; if (this.projectConfigProvider!=null) { _projectConfig=this.projectConfigProvider.getProjectConfig(resourceSet); } IWorkspaceConfig _workspaceConfig = null; if (_projectConfig!=null) { _workspaceConfig=_projectConfig.getWorkspaceConfig(); } this.workspaceConfig = _workspaceConfig; }
private void printKeywordsOnlyInDatatypeRules() { Grammar grammar = grammarAccess.getGrammar(); ListMultimap<String, Keyword> allKeywords = getAllKeywords(grammar); System.out.println("Keywords which do not occur in production rules: "); outer: for (Collection<Keyword> chunk : allKeywords.asMap().values()) { for (Keyword keyword : chunk) { AbstractRule rule = EcoreUtil2.getContainerOfType(keyword, AbstractRule.class); if (!GrammarUtil.isDatatypeRule(rule)) { continue outer; } } System.out.println(" " + ((List<Keyword>) chunk).get(0).getValue()); } System.out.println(); }
private void addFQNs(EObject object) { if (object instanceof TMember || object instanceof TEnumLiteral) { Type t = EcoreUtil2.getContainerOfType(object.eContainer(), Type.class); typesOrModulesToFind.add(qualifiedNameProvider.getFullyQualifiedName(t)); } else if (object instanceof Type) { typesOrModulesToFind.add(qualifiedNameProvider.getFullyQualifiedName(object)); } else if (object instanceof TModule) { typesOrModulesToFind.add(qualifiedNameProvider.getFullyQualifiedName(object)); } if (object instanceof IdentifiableElement) { typesOrModulesToFind.add(qualifiedNameProvider .getFullyQualifiedName(((IdentifiableElement) object).getContainingModule())); } }