@Override public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof Type) { // only export toplevel types super.createEObjectDescriptions(eObject, acceptor); return false; } return true; }
@Override protected Acceptor toAcceptor(IAcceptor<IReferenceDescription> acceptor) { return new ReferenceAcceptor(acceptor, getResourceServiceProviderRegistry()) { @Override public void accept(EObject source, URI sourceURI, EReference eReference, int index, EObject targetOrProxy, URI targetURI) { // Check if we should ignore named import specifier if (N4JSReferenceQueryExecutor.ignoreNamedImportSpecifier && source instanceof NamedImportSpecifier) return; EObject displayObject = calculateDisplayEObject(source); String logicallyQualifiedDisplayName = N4JSHierarchicalNameComputerHelper .calculateLogicallyQualifiedDisplayName(displayObject, labelProvider, false); ICompositeNode srcNode = NodeModelUtils.getNode(source); int line = srcNode.getStartLine(); LabelledReferenceDescription description = new LabelledReferenceDescription(source, displayObject, sourceURI, targetOrProxy, targetURI, eReference, index, logicallyQualifiedDisplayName, line); accept(description); } }; }
/** * Don't validate the inferred module since all validation information should be available on the AST elements. */ @Override protected void validate(Resource resource, CheckMode mode, CancelIndicator cancelIndicator, IAcceptor<Issue> acceptor) { operationCanceledManager.checkCanceled(cancelIndicator); if (n4jsCore.isNoValidate(resource.getURI())) { return; } List<EObject> contents = resource.getContents(); if (!contents.isEmpty()) { EObject firstElement = contents.get(0); // // Mark the scoping as sealed. (No other usage-flags should be set for import-declarations.) // if (firstElement instanceof Script) { // ((Script) firstElement).setFlaggedBound(true); // } validate(resource, firstElement, mode, cancelIndicator, acceptor); // UtilN4.takeSnapshotInGraphView("post validation", resource); } }
@Override public boolean createEObjectDescriptions(final EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (getQualifiedNameProvider() == null) return false; if (eObject instanceof TModule) { TModule module = (TModule) eObject; internalCreateEObjectDescriptionForRoot(module, acceptor); for (Type type : module.getTopLevelTypes()) { internalCreateEObjectDescription(type, acceptor); } for (TVariable variable : module.getVariables()) { internalCreateEObjectDescription(variable, acceptor); } } // export is only possible for top-level elements return false; }
@Override protected void buildMap(Resource resource, Map<QualifiedName, IEObjectDescription> elements) { IDefaultResourceDescriptionStrategy strategy = ((XtextResource) resource).getResourceServiceProvider() .get(IDefaultResourceDescriptionStrategy.class); TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(resource, false); IAcceptor<IEObjectDescription> acceptor = new IAcceptor<IEObjectDescription>() { @Override public void accept(IEObjectDescription description) { elements.put(description.getQualifiedName(), description); } }; while (allProperContents.hasNext()) { EObject content = allProperContents.next(); if (!strategy.createEObjectDescriptions(content, acceptor)) { allProperContents.prune(); } } }
/** * Parses, validates and compiles the given source. Calls the given acceptor for each * resource which is generated from the source. * * @param resourceSet - the {@link ResourceSet} to use * @param acceptor gets called once for each file generated in {@link IGenerator} */ public void compile(final ResourceSet resourceSet, IAcceptor<Result> acceptor) { try { List<Resource> resourcesToCheck = newArrayList(resourceSet.getResources()); if (generatorConfigProvider instanceof GeneratorConfigProvider) { GeneratorConfigProvider configProvider = (GeneratorConfigProvider) generatorConfigProvider; GeneratorConfig config = generatorConfigProvider.get(null); config.setJavaSourceVersion(javaCompiler.getJavaVersion()); GeneratorConfig existent = configProvider.install(resourceSet, config); if (existent != null) { existent.setJavaSourceVersion(javaCompiler.getJavaVersion()); configProvider.install(resourceSet, existent); } } Result result = resultProvider.get(); result.setJavaCompiler(javaCompiler); result.setCheckMode(getCheckMode()); result.setResources(resourcesToCheck); result.setResourceSet(resourceSet); result.setOutputConfigurations(getOutputConfigurations()); result.doGenerate(); acceptor.accept(result); } catch (Exception e) { Exceptions.throwUncheckedException(e); } }
@Override public boolean validate(IAcceptor<? super AbstractDiagnostic> result) { JvmDeclaredType declaringType = getConstructor().getDeclaringType(); if (declaringType.isAbstract()) { String message = "Cannot instantiate the abstract type " + declaringType.getSimpleName(); AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl( Severity.ERROR, IssueCodes.ABSTRACT_CLASS_INSTANTIATION, message, getExpression(), getDefaultValidationFeature(), -1, null); result.accept(diagnostic); return false; } return super.validate(result); }
@Override public boolean validate(IAcceptor<? super AbstractDiagnostic> result) { if (chosenCandidate.validate(result)) { StringBuilder messageBuilder = new StringBuilder("Suspiciously overloaded method.\n"); messageBuilder.append("The ").append(getFeatureTypeName()).append("\n\t"); appendCandidate(chosenCandidate, messageBuilder); messageBuilder.append("\noverloads the ").append(getFeatureTypeName()).append("\n\t"); appendCandidate(rejectedCandidate, messageBuilder); messageBuilder.append("."); AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(chosenCandidate.getSeverity(IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE), IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE, messageBuilder.toString(), getExpression(), XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null); result.accept(diagnostic); } return false; }
@Override public boolean validate(IAcceptor<? super AbstractDiagnostic> result) { if (!getState().isInstanceContext()) { JvmIdentifiableElement implicitFeature = getFeature(); if (implicitFeature instanceof JvmType) { JvmIdentifiableElement feature = getState().getResolvedTypes().getLinkedFeature(getOwner()); if (feature == null || feature.eIsProxy() || !(feature instanceof JvmFeature)) return true; String message = "Cannot make an implicit reference to this from a static context"; AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.STATIC_ACCESS_TO_INSTANCE_MEMBER, message, getOwner(), XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null); result.accept(diagnostic); return false; } } return super.validate(result); }
/** {@inheritDoc} */ @Override public boolean createEObjectDescriptions(final EObject from, final IAcceptor<IEObjectDescription> acceptor) { final IQualifiedNameProvider nameProvider = getQualifiedNameProvider(); if (nameProvider == null) { return false; } try { return doCreateEObjectDescriptions(from, acceptor); // CHECKSTYLE:OFF (IllegalCatch) } catch (final Exception e) { // We need to catch arbitrary exceptions here, otherwise building may fail spectacularly; // and the cause may be very hard to find (likely some bug in an export specification). // CHECKSTYLE:ON LOGGER.error(MessageFormat.format(Messages.AbstractSdkResourceDescription_OBJECT_DESCRIPTION_FAILURE, EObjectUtil.getLocationString(from)), e); } return true; }
/** * Validates this linking candidate and adds respective diagnostics to the given queue. * * This checks the following criteria: * <ol> * <li>{@link #validateVisibility(IAcceptor) visibility},</li> * <li>{@link #validateArity(IAcceptor) arity},</li> * <li>{@link #validateTypeArity(IAcceptor) type arity},</li> * <li>{@link #validateTypeArgumentConformance(IAcceptor) type arguments},</li> * <li>{@link #validateUnhandledExceptions(IAcceptor) unhandled excptions},</li> * </ol> */ @Override public boolean validate(IAcceptor<? super AbstractDiagnostic> result) { if (!validateVisibility(result)) { return false; } if (!validateArity(result)) { return false; } if (!validateTypeArity(result)) { return false; } if (!validateTypeArgumentConformance(result)) { return false; } if (!validateUnhandledExceptions(result)) { return false; } return true; }
protected boolean validateVisibility(IAcceptor<? super AbstractDiagnostic> result) { if (!isVisible()) { String message = String.format("The %1$s %2$s%3$s is not visible", getFeatureTypeName(), getSimpleFeatureName(), getFeatureParameterTypesAsString()); AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl( Severity.ERROR, IssueCodes.FEATURE_NOT_VISIBLE, message, getExpression(), getDefaultValidationFeature(), -1, null); result.accept(diagnostic); return false; } return true; }
protected boolean validateArity(IAcceptor<? super AbstractDiagnostic> result) { if (getArityMismatch() != 0) { String message; if (getArguments().isEmpty()) { message = String.format("Invalid number of arguments. The %1$s %2$s%3$s is not applicable without arguments" , getFeatureTypeName(), getSimpleFeatureName(), getFeatureParameterTypesAsString()); } else { message = String.format("Invalid number of arguments. The %1$s %2$s%3$s is not applicable for the arguments %4$s" , getFeatureTypeName(), getSimpleFeatureName(), getFeatureParameterTypesAsString(), getArgumentTypesAsString()); } AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl( Severity.ERROR, IssueCodes.INVALID_NUMBER_OF_ARGUMENTS, message, getExpression(), getInvalidArgumentsValidationFeature(), -1, null); result.accept(diagnostic); return false; } return true; }
protected boolean validateTypeArity(IAcceptor<? super AbstractDiagnostic> result) { if (getTypeArityMismatch() != 0) { String message = String.format("Invalid number of type arguments. The %1$s %2$s%3$s is not applicable for the type arguments %4$s", getFeatureTypeName(), getSimpleFeatureName(), getFeatureTypeParametersAsString(true), getTypeArgumentsAsString(getSyntacticTypeArguments())); AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl( Severity.ERROR, IssueCodes.INVALID_NUMBER_OF_TYPE_ARGUMENTS, message, getExpression(), getDefaultValidationFeature(), -1, null); result.accept(diagnostic); return false; } return true; }
@Override public boolean validate(IAcceptor<? super AbstractDiagnostic> result) { JvmType type = (JvmType) description.getElementOrProxy(); String typeKind = ""; if (type instanceof JvmPrimitiveType || type instanceof JvmVoid) { typeKind = "primitive type"; } else if (type instanceof JvmAnnotationType) { typeKind = "annotation type"; } else if (type instanceof JvmEnumerationType) { typeKind = "enum type"; } else if (type instanceof JvmGenericType && ((JvmGenericType) type).isInterface()) { typeKind = "interface type"; } else if (type instanceof JvmTypeParameter) { typeKind = "type parameter"; } String message = String.format("Cannot instantiate the %s %s", typeKind, type.getSimpleName()); AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.ILLEGAL_CLASS_INSTANTIATION, message, getExpression(), XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR, -1, null); result.accept(diagnostic); return false; }
/** * {@inheritDoc} */ @Override public boolean createEObjectDescriptions(final EObject eObject, final IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof XBlockExpression || isXbaseLocalVariableName(eObject)) { return false; } boolean indexObject = false; boolean indexDefault = false; String objectFingerprint = null; if (fingerprintComputer != null && eObject.eContainer() instanceof FormatConfiguration && NodeModelUtils.getNode(eObject) != null) { objectFingerprint = fingerprintComputer.computeFingerprint(eObject); } if (objectFingerprint != null && !"".equals(objectFingerprint) && eObject.eContainer() instanceof FormatConfiguration) { acceptor.accept(EObjectDescription.create(objectFingerprint, eObject)); indexObject = true; } indexDefault = createDescriptionsForNonXbaseFormalParameters(eObject, acceptor); return indexDefault || indexObject; }
protected boolean createEObjectDescriptions(IQualifiedNameProvider qualifiedNameProvider, boolean isNsURI, EObject eObject, IAcceptor<IEObjectDescription> acceptor) { try { QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(eObject); if (qualifiedName != null) { Map<String, String> userData = Maps.newHashMapWithExpectedSize(1); userData.put(NS_URI_INDEX_ENTRY, Boolean.toString(isNsURI)); IEObjectDescription description = EObjectDescription.create(qualifiedName, eObject, userData); acceptor.accept(description); return true; } } catch (Exception exc) { LOG.error(exc.getMessage(), exc); } return false; }
@Override public void convertResourceDiagnostic(Diagnostic diagnostic, Severity severity, IAcceptor<Issue> acceptor) { IssueImpl issue = new Issue.IssueImpl(); issue.setSyntaxError(diagnostic instanceof XtextSyntaxDiagnostic); issue.setSeverity(severity); issue.setLineNumber(diagnostic.getLine()); issue.setColumn(diagnostic.getColumn()); issue.setMessage(diagnostic.getMessage()); if (diagnostic instanceof org.eclipse.xtext.diagnostics.Diagnostic) { org.eclipse.xtext.diagnostics.Diagnostic xtextDiagnostic = (org.eclipse.xtext.diagnostics.Diagnostic) diagnostic; issue.setOffset(xtextDiagnostic.getOffset()); issue.setLength(xtextDiagnostic.getLength()); } if (diagnostic instanceof AbstractDiagnostic) { AbstractDiagnostic castedDiagnostic = (AbstractDiagnostic)diagnostic; issue.setUriToProblem(castedDiagnostic.getUriToProblem()); issue.setCode(castedDiagnostic.getCode()); issue.setData(castedDiagnostic.getData()); } issue.setType(CheckType.FAST); acceptor.accept(issue); }
@Override protected void initialize(IAcceptor<PreferenceKey> acceptor) { acceptor.accept(create(INVALID_ACTION_USAGE, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(EMPTY_ENUM_LITERAL, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(EMPTY_KEYWORD, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(SPACES_IN_KEYWORD, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(INVALID_HIDDEN_TOKEN, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(INVALID_HIDDEN_TOKEN_FRAGMENT, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(INVALID_PACKAGE_REFERENCE_INHERITED, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(CROSS_REFERENCE_IN_ALTERNATIVES, SeverityConverter.SEVERITY_ERROR)); acceptor.accept(create(INVALID_METAMODEL_NAME, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(INVALID_PACKAGE_REFERENCE_EXTERNAL, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(INVALID_PACKAGE_REFERENCE_NOT_ON_CLASSPATH, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(INVALID_TERMINALRULE_NAME, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(DUPLICATE_ENUM_LITERAL, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(BIDIRECTIONAL_REFERENCE, SeverityConverter.SEVERITY_WARNING)); acceptor.accept(create(DISCOURAGED_RULE_NAME, SeverityConverter.SEVERITY_WARNING)); }
@Override protected List<IEObjectDescription> computeExportedObjects() { if (!getResource().isLoaded()) { try { getResource().load(null); } catch (IOException e) { log.error(e.getMessage(), e); return Collections.<IEObjectDescription> emptyList(); } } final List<IEObjectDescription> exportedEObjects = newArrayList(); IAcceptor<IEObjectDescription> acceptor = new IAcceptor<IEObjectDescription>() { @Override public void accept(IEObjectDescription eObjectDescription) { exportedEObjects.add(eObjectDescription); } }; TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(getResource(), false); while (allProperContents.hasNext()) { EObject content = allProperContents.next(); if (!strategy.createEObjectDescriptions(content, acceptor)) allProperContents.prune(); } return exportedEObjects; }
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; }
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; } }); }
/** * A cycle is represented by the set of all nodes on that cycle. The return value maps each node that is on a cycle * to the corresponding set. Multiple cycles that are connected via a node are treated as a single cycle. */ public <S> Map<S, Set<S>> findCycles(Nfa<S> nfa) { Map<S, Set<S>> cycles = Maps.newLinkedHashMap(); IAcceptor<List<S>> cycleAcceptor = new IAcceptor<List<S>>() { @Override public void accept(List<S> t) { Set<S> cycle = Sets.newHashSet(t); for (S cycleNode : t) { // We have two cycles that are connected via at least // one node. Treat them as one cycle. Set<S> existingCycle = cycles.get(cycleNode); if (existingCycle != null) { cycle.addAll(existingCycle); } } for (S n : cycle) { cycles.put(n, cycle); } } }; findCycles(nfa, nfa.getStart(), cycleAcceptor, Maps.<S, Integer>newHashMap(), Lists.<S>newLinkedList()); return cycles; }
protected <S> void findCycles(Nfa<S> nfa, S node, IAcceptor<List<S>> cycleAcceptor, Map<S, Integer> dfsMark, LinkedList<S> dfsStack) { dfsStack.push(node); dfsMark.put(node, DFS_ON_STACK); for (S follower : nfa.getFollowers(node)) { Integer followerMark = dfsMark.get(follower); if (followerMark == null) { // The follower is not visited yet, so go deeper. findCycles(nfa, follower, cycleAcceptor, dfsMark, dfsStack); } else if (followerMark == DFS_ON_STACK) { // If the follower is on the stack that means we have a cycle // that includes all nodes between // the follower node and the current node. LinkedList<S> cycle = Lists.newLinkedList(); Iterator<S> stackIter = dfsStack.iterator(); S cycleNode; do { cycleNode = stackIter.next(); cycle.addFirst(cycleNode); } while (cycleNode != follower && stackIter.hasNext()); cycleAcceptor.accept(cycle); } } dfsStack.pop(); dfsMark.put(node, DFS_VISITED); }
@Override public void applyModifications(IAcceptor<IEmfResourceChange> changeAcceptor) { monitor.setTaskName("Preparing Text Changes..."); Set<Resource> resources = Sets.newLinkedHashSet(); for (Pair<Notifier, IModification<? extends Notifier>> p : modifications) { Notifier context = p.getFirst(); if (context instanceof EObject) resources.add(((EObject) context).eResource()); else if (context instanceof Resource) resources.add((Resource) context); else if (context instanceof ResourceSet) { throw new IllegalStateException("Not supported"); } } for (Resource res : resources) { // TODO: use the exact context beginRecordChanges(res); } checkCanceled(); for (Pair<Notifier, IModification<? extends Notifier>> entry : modifications) { apply(entry.getFirst(), entry.getSecond()); } checkCanceled(); endRecordChanges(changeAcceptor); }
public List<? extends Location> getReferences(final XtextResource resource, final int offset, final IReferenceFinder.IResourceAccess resourceAccess, final IResourceDescriptions indexData, final CancelIndicator cancelIndicator) { final EObject element = this._eObjectAtOffsetHelper.resolveElementAt(resource, offset); if ((element == null)) { return CollectionLiterals.<Location>emptyList(); } final ArrayList<Location> locations = CollectionLiterals.<Location>newArrayList(); final TargetURIs targetURIs = this.collectTargetURIs(element); final IAcceptor<IReferenceDescription> _function = (IReferenceDescription reference) -> { final Procedure1<EObject> _function_1 = (EObject obj) -> { final Location location = this._documentExtensions.newLocation(obj, reference.getEReference(), reference.getIndexInList()); if ((location != null)) { locations.add(location); } }; this.doRead(resourceAccess, reference.getSourceEObjectUri(), _function_1); }; ReferenceAcceptor _referenceAcceptor = new ReferenceAcceptor(this.resourceServiceProviderRegistry, _function); CancelIndicatorProgressMonitor _cancelIndicatorProgressMonitor = new CancelIndicatorProgressMonitor(cancelIndicator); this.referenceFinder.findAllReferences(targetURIs, resourceAccess, indexData, _referenceAcceptor, _cancelIndicatorProgressMonitor); return locations; }
protected void findTargetDeclarations(final URI sourceDeclarationURI, final IProgressMonitor monitor, final Procedure2<? super IEObjectDescription, ? super IReferenceDescription> acceptor) { final IUnitOfWork<Object, EObject> _function = (EObject sourceDeclaration) -> { Object _xblockexpression = null; { IResourceServiceProvider.Registry _resourceServiceProviderRegistry = this.getResourceServiceProviderRegistry(); final IAcceptor<IReferenceDescription> _function_1 = (IReferenceDescription reference) -> { boolean _filterReference = this.filterReference(reference); if (_filterReference) { IEObjectDescription _findTargetDeclaration = null; if (reference!=null) { _findTargetDeclaration=this.findTargetDeclaration(reference); } final IEObjectDescription targetDeclaration = _findTargetDeclaration; acceptor.apply(targetDeclaration, reference); } }; ReferenceAcceptor _referenceAcceptor = new ReferenceAcceptor(_resourceServiceProviderRegistry, _function_1); this.getReferenceFinder().findAllReferences(sourceDeclaration, _referenceAcceptor, monitor); _xblockexpression = null; } return _xblockexpression; }; this.<Object>readOnly(sourceDeclarationURI, _function); }
@Override public boolean createEObjectDescriptions(final EObject eObject, final IAcceptor<IEObjectDescription> acceptor) { if (getQualifiedNameProvider() == null || !(eObject instanceof ScopeModel)) { return false; } ScopeModel model = (ScopeModel) eObject; try { QualifiedName qualifiedName = getQualifiedNameProvider().getFullyQualifiedName(model); if (qualifiedName != null) { Hasher hasher = Hashing.murmur3_32().newHasher(HASHER_CAPACITY); hasher.putUnencodedChars(getSourceText(model)); for (ScopeModel include : model.getIncludedScopes()) { hasher.putUnencodedChars(getSourceText(include)); } acceptor.accept(EObjectDescription.create(qualifiedName, model, Collections.singletonMap("fingerprint", hasher.hash().toString()))); } // CHECKSTYLE:CHECK-OFF IllegalCatch } catch (RuntimeException e) { // CHECKSTYLE:CHECK-ON LOG.error(e.getMessage(), e); } return false; }
@Override public void convertValidatorDiagnostic(Diagnostic diagnostic, IAcceptor<Issue> acceptor) { super.convertValidatorDiagnostic(diagnostic, new IAcceptor<Issue>() { @Override public void accept(Issue t) { if (!N4JSLanguageConstants.DEFAULT_SUPPRESSED_ISSUE_CODES_FOR_TESTS.contains(t.getCode())) { acceptor.accept(t); } } }); }
private static void computeCrossRefs(N4JSResource resource, IAcceptor<TModule> acceptor) { final Script script = resource.getScript(); if (script != null && !script.eIsProxy()) { for (ScriptElement elem : script.getScriptElements()) { if (elem instanceof ImportDeclaration) { final TModule module = ((ImportDeclaration) elem).getModule(); if (module != null && !module.eIsProxy()) { acceptor.accept(module); } } } } }
@Override protected List<IEObjectDescription> computeExportedObjects() { final N4JSResource res = getResource() instanceof N4JSResource ? (N4JSResource) getResource() : null; if (res == null || !res.isLoadedFromDescription()) { // default behavior return super.computeExportedObjects(); } else { // we have an N4JSResource that is loaded from the Xtext index (AST is proxy but TModule in place) // ORIGINAL CODE FROM SUPER-CLASS: if (!getResource().isLoaded()) { try { getResource().load(null); } catch (IOException e) { log.error(e.getMessage(), e); return Collections.<IEObjectDescription> emptyList(); } } final List<IEObjectDescription> exportedEObjects = newArrayList(); IAcceptor<IEObjectDescription> acceptor = new IAcceptor<IEObjectDescription>() { @Override public void accept(IEObjectDescription eObjectDescription) { exportedEObjects.add(eObjectDescription); } }; // ADJUSTED: strategy.createEObjectDescriptions(res.getModule(), acceptor); // ORIGINAL CODE FROM SUPER-CLASS: // @formatter:off // TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(getResource(), false); // while (allProperContents.hasNext()) { // EObject content = allProperContents.next(); // <=== this would trigger demand-load of AST! // if (!strategy.createEObjectDescriptions(content, acceptor)) // allProperContents.prune(); // } // @formatter:on return exportedEObjects; } }
private IAcceptor<EObject> getCrossRefTypeAcceptor(final Set<EObject> crossRefTypesAddHere) { IAcceptor<EObject> acceptor = new IAcceptor<EObject>() { @Override public void accept(EObject to) { if (to instanceof Type || to instanceof TVariable || to instanceof TEnumLiteral) { crossRefTypesAddHere.add(to); } // Add return type of function/method to cross ref types. Note that setters/getters are methods. // Add declared type of a field to cross ref types if (to instanceof TFunction) { TypeRef returnTypeRef = ((TFunction) to).getReturnTypeRef(); crossRefTypesAddHere.add(returnTypeRef.getDeclaredType()); } if (to instanceof TField) { TypeRef typeRef = ((TField) to).getTypeRef(); crossRefTypesAddHere.add(typeRef.getDeclaredType()); } // In case of TMember, add the containing type as well if (to instanceof TMember) { TMember casted = (TMember) to; ContainerType<?> declaringType = casted.getContainingType(); crossRefTypesAddHere.add(declaringType); } } }; return acceptor; }
/** * Collects all Types, TVariables, TLiterals and IdentifiableElements that are directly referenced somewhere in the * given resource and aren't contained in this resource. References between AST element to its defined type and vice * versa as well as references to built-in and primitive types are ignored. * * @param resource * the given fully resolved resource * @param acceptor * the logic that collects the passed EObject found in a cross reference */ public void computeCrossRefs(Resource resource, IAcceptor<EObject> acceptor) { TreeIterator<EObject> allASTContentsIter; if (resource instanceof N4JSResource) { Script script = ((N4JSResource) resource).getScript(); // We traverse the AST but not the TModule tree allASTContentsIter = script.eAllContents(); } else { allASTContentsIter = resource.getAllContents(); } while (allASTContentsIter.hasNext()) { EObject eObject = allASTContentsIter.next(); computeCrossRefs(resource, eObject, acceptor); } }
private void handleReferenceObject(Resource resource, IAcceptor<EObject> acceptor, EObject to) { if (to instanceof Type) { handleType(resource, acceptor, (Type) to); } else if (to instanceof TMember) { // Special handling of TMember because it can be a composed member handleTMember(resource, acceptor, (TMember) to); } else if (to instanceof IdentifiableElement) { handleIdentifiableElement(resource, acceptor, (IdentifiableElement) to); } }
private void handleTMember(Resource resource, IAcceptor<EObject> acceptor, TMember to) { if (to.isComposed()) { // If the member is a composed member, handle the constituent members instead for (TMember constituentMember : to.getConstituentMembers()) handleIdentifiableElement(resource, acceptor, constituentMember); } else { // Standard case handleIdentifiableElement(resource, acceptor, to); } }
private void handleType(Resource resource, IAcceptor<EObject> acceptor, Type to) { if (to != null) { if (isLocatedInOtherResource(resource, to)) { acceptor.accept(to); } } }
private void handleIdentifiableElement(Resource resource, IAcceptor<EObject> acceptor, IdentifiableElement to) { if (to != null) { if (isLocatedInOtherResource(resource, to)) { acceptor.accept(to); } } }
private void internalCreateEObjectDescriptionForRoot(final TModule module, IAcceptor<IEObjectDescription> acceptor) { // user data: serialized representation final Map<String, String> userData = createUserData(module); QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(module); IEObjectDescription eod = new EObjectDescription(qualifiedName, module, userData); acceptor.accept(eod); }
/** * Create EObjectDescriptions for elements for which N4JSQualifiedNameProvider provides a FQN; elements with a FQN * of <code>null</code> will be ignored. */ private void internalCreateEObjectDescription(Type type, IAcceptor<IEObjectDescription> acceptor) { final String exportedName = type.getExportedName(); final String typeName = exportedName != null ? exportedName : type.getName(); if (typeName != null && typeName.length() != 0) { QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(type); if (qualifiedName != null) { // e.g. non-exported declared functions will return null for FQN Map<String, String> userData = Collections.singletonMap( ACCESS_MODIFIERY_KEY, String.valueOf(type.getTypeAccessModifier().ordinal())); // Add additional user data for descriptions representing a TClass if (type instanceof TClass) { final TClass tClass = (TClass) type; userData = newHashMap(userData); if (tClass.isExported()) { userData.put(EXPORTED_CLASS_KEY, Boolean.toString(tClass.isExported())); } userData.put(ABSTRACT_KEY, Boolean.toString(tClass.isAbstract())); userData.put(FINAL_KEY, Boolean.toString(tClass.isFinal())); userData.put(POLYFILL_KEY, Boolean.toString(tClass.isPolyfill())); userData.put(STATIC_POLYFILL_KEY, Boolean.toString(tClass.isStaticPolyfill())); userData.put( TEST_CLASS_KEY, Boolean.toString(tClass.getOwnedMembers().stream() .filter(m -> m instanceof TMethod) .anyMatch(m -> AnnotationDefinition.TEST_METHOD.hasAnnotation(m)))); } IEObjectDescription eod = EObjectDescription.create(qualifiedName, type, userData); acceptor.accept(eod); } } }