@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; }
private boolean registerErrors(Resource dep, StringBuilder errorResult) { boolean hasErrors = false; List<Issue> issues = resourceValidator.validate(dep, CheckMode.ALL, CancelIndicator.NullImpl); List<Issue> errorIssues = new ArrayList<>(); for (Issue issue : issues) { if (Severity.ERROR == issue.getSeverity()) { errorIssues.add(issue); } } hasErrors = !errorIssues.isEmpty(); if (hasErrors) { errorResult.append("Couldn't compile resource " + dep.getURI() + " because it contains errors: "); for (Issue errorIssue : errorIssues) { errorResult .append(nl + errorIssue.getMessage() + " at line " + errorIssue.getLineNumber()); } } return hasErrors; }
@Override public void performPostProcessing(PostProcessingAwareResource resource, CancelIndicator cancelIndicator) { final N4JSResource resourceCasted = (N4JSResource) resource; final ASTMetaInfoCache cache = createASTMetaInfoCache(resourceCasted); try { postProcessN4JSResource(resourceCasted, cancelIndicator); } catch (Throwable th) { operationCanceledManager.propagateIfCancelException(th); if (cache.hasBrokenAST()) { // swallow exception, AST is broken due to parse error anyway } else { // make sure this error is being reported, even if exception will be suppressed by calling code! UtilN4.reportError("exception while post-processing resource " + resource.getURI(), th); throw th; } } finally { cache.clearTemporaryData(); } }
/** * 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 void resolveLazyCrossReferences(CancelIndicator mon) { // called from builder before resource descriptions are created + called from validator final Script script = getScriptResolved(); // need to be called before resolve() since that one injects a proxy // at resource.content[0] final Measurement measurment = collector.getMeasurement(getURI().toString()); super.resolveLazyCrossReferences(mon); measurment.end(); if (script != null) { // FIXME freezing of used imports tracking can/should now be moved to N4JSPostProcessor or ASTProcessor EcoreUtilN4.doWithDeliver(false, // freezing Tracking of used imports in OriginAwareScope () -> script.setFlaggedUsageMarkingFinished(true), script); } }
protected void runGenerator(String string) { // load the resource ResourceSet set = resourceSetProvider.get(); Resource resource = set.getResource(URI.createURI(string), true); // validate the resource List<Issue> list = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl); if (!list.isEmpty()) { for (Issue issue : list) { System.err.println(issue); } return; } // configure and start the generator fileAccess.setOutputPath("src-gen/"); generator.doGenerate(resource, fileAccess); System.out.println("Code generation finished."); }
@Override public CompletableFuture<SignatureHelp> signatureHelp(final TextDocumentPositionParams params) { final Function1<CancelIndicator, SignatureHelp> _function = (CancelIndicator cancelIndicator) -> { final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider serviceProvider = this.languagesRegistry.getResourceServiceProvider(uri); ISignatureHelpService _get = null; if (serviceProvider!=null) { _get=serviceProvider.<ISignatureHelpService>get(ISignatureHelpService.class); } final ISignatureHelpService helper = _get; if ((helper == null)) { return ISignatureHelpService.EMPTY; } final Function2<Document, XtextResource, SignatureHelp> _function_1 = (Document doc, XtextResource resource) -> { return helper.getSignatureHelp(doc, resource, params, cancelIndicator); }; return this.workspaceManager.<SignatureHelp>doRead(uri, _function_1); }; return this.requestManager.<SignatureHelp>runRead(_function); }
@Override public List<? extends Command> getCodeActions(final Document document, final XtextResource resource, final CodeActionParams params, final CancelIndicator indicator) { final ArrayList<Command> commands = CollectionLiterals.<Command>newArrayList(); List<Diagnostic> _diagnostics = params.getContext().getDiagnostics(); for (final Diagnostic d : _diagnostics) { String _code = d.getCode(); if (_code != null) { switch (_code) { case TestLanguageValidator.INVALID_NAME: Command _fixInvalidName = this.fixInvalidName(d, document, resource, params); commands.add(_fixInvalidName); break; case TestLanguageValidator.UNSORTED_MEMBERS: Command _fixUnsortedMembers = this.fixUnsortedMembers(d, document, resource, params); commands.add(_fixUnsortedMembers); break; } } } return commands; }
@Override public CompletableFuture<List<? extends Location>> references(final ReferenceParams params) { final Function1<CancelIndicator, List<? extends Location>> _function = (CancelIndicator cancelIndicator) -> { final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider resourceServiceProvider = this.languagesRegistry.getResourceServiceProvider(uri); DocumentSymbolService _get = null; if (resourceServiceProvider!=null) { _get=resourceServiceProvider.<DocumentSymbolService>get(DocumentSymbolService.class); } final DocumentSymbolService documentSymbolService = _get; if ((documentSymbolService == null)) { return CollectionLiterals.<Location>emptyList(); } final Function2<Document, XtextResource, List<? extends Location>> _function_1 = (Document document, XtextResource resource) -> { return documentSymbolService.getReferences(document, resource, params, this.resourceAccess, this.workspaceManager.getIndex(), cancelIndicator); }; return this.workspaceManager.<List<? extends Location>>doRead(uri, _function_1); }; return this.requestManager.<List<? extends Location>>runRead(_function); }
@Override public IResolvedTypes reentrantResolve(CancelIndicator monitor) { if (resolving) { throw new UnsupportedOperationException("TODO: import a functional handle on the type resolution that delegates to the best available (current, but evolving) result"); } StoppedTask task = Stopwatches.forTask("DefaultReentrantTypeResolver.resolve"); try { task.start(); resolving = true; return resolve(monitor); } catch(Throwable e) { clear(); if (operationCanceledManager.isOperationCanceledException(e)) { operationCanceledManager.propagateAsErrorIfCancelException(e); } throw Throwables.propagate(e); } finally { resolving = false; task.stop(); } }
protected Either<List<CompletionItem>, CompletionList> completion(final CancelIndicator origialCancelIndicator, final TextDocumentPositionParams params) { final LanguageServerImpl.BufferedCancelIndicator cancelIndicator = new LanguageServerImpl.BufferedCancelIndicator(origialCancelIndicator); final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider resourceServiceProvider = this.languagesRegistry.getResourceServiceProvider(uri); ContentAssistService _get = null; if (resourceServiceProvider!=null) { _get=resourceServiceProvider.<ContentAssistService>get(ContentAssistService.class); } final ContentAssistService contentAssistService = _get; if ((contentAssistService == null)) { CompletionList _completionList = new CompletionList(); return Either.<List<CompletionItem>, CompletionList>forRight(_completionList); } final Function2<Document, XtextResource, CompletionList> _function = (Document document, XtextResource resource) -> { return contentAssistService.createCompletionList(document, resource, params, cancelIndicator); }; final CompletionList completionList = this.workspaceManager.<CompletionList>doRead(uri, _function); return Either.<List<CompletionItem>, CompletionList>forRight(completionList); }
@Override /* @NonNull */ protected IResolvedTypes doResolveTypes(final /* @Nullable */ EObject object, final /* @Nullable */ CancelIndicator monitor) { // TODO: remove when we switch to an Xtend scope provider without artificial feature calls EObject nonArtificialObject = object; if(object.eResource() == null && object instanceof XAbstractFeatureCall) { nonArtificialObject = ((XAbstractFeatureCall) object).getFeature(); } // TODO final Resource resource = nonArtificialObject.eResource(); final LazyResolvedTypes result = cache.get(CachingBatchTypeResolver.class, resource, new Provider<LazyResolvedTypes>() { @Override public LazyResolvedTypes get() { final IReentrantTypeResolver resolver = delegate.getTypeResolver(object); return new LazyResolvedTypes(resolver, resource); } }); cache.execWithoutCacheClear(resource, new IUnitOfWork.Void<Resource>() { @Override public void process(Resource state) throws Exception { // trigger the actual resolution after the thing was cached result.resolveTypes(monitor == null ? CancelIndicator.NullImpl : monitor); } }); return result; }
@Test public void testResolveLazyCrossReferences_02() throws Exception { with(lazyLinkingTestLangaugeSetup()); ResourceSetImpl rs = new ResourceSetImpl(); final Resource res1 = rs.createResource(URI.createURI("file1.lazylinkingtestlanguage")); Resource res2 = rs.createResource(URI.createURI("file2.lazylinkingtestlanguage")); res1.load(new StringInputStream("type Foo { } type Baz { Foo Bar prop; } }"), null); res2.load(new StringInputStream("type Bar { }"), null); res1.eAdapters().add(notificationAlert); Model m = (Model) res1.getContents().get(0); Type t = m.getTypes().get(1); Property p = t.getProperties().get(0); final InternalEList<Type> types = (InternalEList<Type>) p.getType(); assertEquals(2, types.size()); for (Iterator<Type> it = types.basicIterator(); it.hasNext();) { final Type tt = it.next(); assertTrue(tt.eIsProxy()); } ((LazyLinkingResource) res1).resolveLazyCrossReferences(CancelIndicator.NullImpl); assertFalse(types.basicGet(0).eIsProxy()); assertTrue(types.basicGet(1).eIsProxy()); res1.eAdapters().remove(notificationAlert); EcoreUtil.resolveAll(res1); assertFalse(types.basicGet(0).eIsProxy()); assertFalse(types.basicGet(1).eIsProxy()); }
@Override protected List<IReferenceDescription> computeReferenceDescriptions() { final ImmutableList.Builder<IReferenceDescription> referenceDescriptions = ImmutableList.builder(); EcoreUtil2.resolveLazyCrossReferences(getResource(), CancelIndicator.NullImpl); Map<EObject, IEObjectDescription> eObject2exportedEObjects = createEObject2ExportedEObjectsMap(getExportedObjects()); TreeIterator<EObject> contents = EcoreUtil.getAllProperContents(getResource(), true); while (contents.hasNext()) { EObject eObject = contents.next(); URI exportedContainerURI = findExportedContainerURI(eObject, eObject2exportedEObjects); if (!strategy.createReferenceDescriptions(eObject, exportedContainerURI, referenceDescriptions::add)) { contents.prune(); } } if (strategy instanceof AbstractResourceDescriptionStrategy) { ((AbstractResourceDescriptionStrategy) strategy).createImplicitReferenceDescriptions(getResource(), referenceDescriptions::add); } return referenceDescriptions.build(); }
@Test(timeout = 1000) public void testRunWriteAfterRead() { final Function1<CancelIndicator, Integer> _function = (CancelIndicator it) -> { return Integer.valueOf(this.sharedState.incrementAndGet()); }; final CompletableFuture<Integer> previsousRead = this.requestManager.<Integer>runRead(_function); final Function0<Object> _function_1 = () -> { return null; }; final Function2<CancelIndicator, Object, Integer> _function_2 = (CancelIndicator $0, Object $1) -> { int _xblockexpression = (int) 0; { while (((this.sharedState.get() == 0) && (!previsousRead.isCancelled()))) { } _xblockexpression = this.sharedState.incrementAndGet(); } return Integer.valueOf(_xblockexpression); }; this.requestManager.<Object, Integer>runWrite(_function_1, _function_2).join(); Assert.assertEquals(2, this.sharedState.get()); }
/** * @param context unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ @SuppressWarnings("unchecked") protected Object _doEvaluate(XNumberLiteral literal, IEvaluationContext context, CancelIndicator indicator) { IResolvedTypes resolvedTypes = typeResolver.resolveTypes(literal); LightweightTypeReference expectedType = resolvedTypes.getExpectedType(literal); Class<? extends Number> type = numberLiterals.getJavaType(literal); if (expectedType != null && expectedType.isSubtypeOf(Number.class)) { try { Class<?> expectedClassType = getJavaType(expectedType.toJavaCompliantTypeReference().getType()); if (expectedClassType.isPrimitive()) { expectedClassType = ReflectionUtil.getObjectType(expectedClassType); } if (Number.class != expectedClassType && Number.class.isAssignableFrom(expectedClassType)) { type = (Class<? extends Number>) expectedClassType; } } catch (ClassNotFoundException e) { } } return numberLiterals.numberValue(literal, type); }
public Object executeCommand(final ExecuteCommandParams params, final ILanguageServerAccess access, final CancelIndicator cancelIndicator) { Object result = null; Collection<IExecutableCommandService> _get = this.registeredCommands.get(params.getCommand()); for (final IExecutableCommandService service : _get) { { final Object localResult = service.execute(params, access, cancelIndicator); if ((localResult != null)) { if ((result != null)) { StringConcatenation _builder = new StringConcatenation(); _builder.append("Multiple commands \'"); String _command = params.getCommand(); _builder.append(_command); _builder.append("\' have been registered. All are executed but only one result will be send back."); ExecutableCommandRegistry.LOG.error(_builder); } else { result = localResult; } } } } return result; }
protected Object _doEvaluate(XConstructorCall constructorCall, IEvaluationContext context, CancelIndicator indicator) { JvmConstructor jvmConstructor = constructorCall.getConstructor(); List<Object> arguments = evaluateArgumentExpressions(jvmConstructor, constructorCall.getArguments(), context, indicator); Constructor<?> constructor = javaReflectAccess.getConstructor(jvmConstructor); try { if (constructor == null) throw new NoSuchMethodException("Could not find constructor " + jvmConstructor.getIdentifier()); constructor.setAccessible(true); Object result = constructor.newInstance(arguments.toArray(new Object[arguments.size()])); return result; } catch (InvocationTargetException targetException) { throw new EvaluationException(targetException.getTargetException()); } catch (Exception e) { throw new IllegalStateException("Could not invoke constructor: " + jvmConstructor.getIdentifier(), e); } }
@Override public CompletableFuture<Hover> hover(final TextDocumentPositionParams params) { final Function1<CancelIndicator, Hover> _function = (CancelIndicator cancelIndicator) -> { final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider resourceServiceProvider = this.languagesRegistry.getResourceServiceProvider(uri); IHoverService _get = null; if (resourceServiceProvider!=null) { _get=resourceServiceProvider.<IHoverService>get(IHoverService.class); } final IHoverService hoverService = _get; if ((hoverService == null)) { return IHoverService.EMPTY_HOVER; } final Function2<Document, XtextResource, Hover> _function_1 = (Document document, XtextResource resource) -> { return hoverService.hover(document, resource, params, cancelIndicator); }; return this.workspaceManager.<Hover>doRead(uri, _function_1); }; return this.requestManager.<Hover>runRead(_function); }
public IncrementalBuilder.Result build(final BuildRequest request, final Function1<? super URI, ? extends IResourceServiceProvider> languages, final IResourceClusteringPolicy clusteringPolicy) { try { final XtextResourceSet resourceSet = request.getResourceSet(); ResourceDescriptionsData _copy = request.getState().getResourceDescriptions().copy(); Source2GeneratedMapping _copy_1 = request.getState().getFileMappings().copy(); final IndexState oldState = new IndexState(_copy, _copy_1); CancelIndicator _cancelIndicator = request.getCancelIndicator(); final BuildContext context = new BuildContext(languages, resourceSet, oldState, clusteringPolicy, _cancelIndicator); final IncrementalBuilder.InternalStatefulIncrementalBuilder builder = this.provider.get(); builder.context = context; builder.request = request; try { return builder.launch(); } catch (final Throwable _t) { if (_t instanceof Throwable) { final Throwable t = (Throwable)_t; this._operationCanceledManager.propagateIfCancelException(t); throw t; } else { throw Exceptions.sneakyThrow(_t); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
protected Object _assignValueTo(JvmField jvmField, XAbstractFeatureCall assignment, Object value, IEvaluationContext context, CancelIndicator indicator) { Object receiver = getReceiver(assignment, context, indicator); Field field = javaReflectAccess.getField(jvmField); try { if (field == null) { throw new NoSuchFieldException("Could not find field " + jvmField.getIdentifier()); } if (!Modifier.isStatic(field.getModifiers()) && receiver == null) throw new EvaluationException(new NullPointerException("Cannot assign value to field: " + jvmField.getIdentifier() + " on null instance")); JvmTypeReference type = jvmField.getType(); Object coerced = coerceArgumentType(value, type); field.setAccessible(true); field.set(receiver, coerced); return value; } catch (Exception e) { throw new IllegalStateException("Could not access field: " + jvmField.getIdentifier() + " on instance: " + receiver, e); } }
@Override public CompletableFuture<List<? extends Command>> codeAction(final CodeActionParams params) { final Function1<CancelIndicator, List<? extends Command>> _function = (CancelIndicator cancelIndicator) -> { final URI uri = this._uriExtensions.toUri(params.getTextDocument().getUri()); final IResourceServiceProvider serviceProvider = this.languagesRegistry.getResourceServiceProvider(uri); ICodeActionService _get = null; if (serviceProvider!=null) { _get=serviceProvider.<ICodeActionService>get(ICodeActionService.class); } final ICodeActionService service = _get; if ((service == null)) { return CollectionLiterals.<Command>emptyList(); } final Function2<Document, XtextResource, List<? extends Command>> _function_1 = (Document doc, XtextResource resource) -> { return service.getCodeActions(doc, resource, params, cancelIndicator); }; return this.workspaceManager.<List<? extends Command>>doRead(uri, _function_1); }; return this.requestManager.<List<? extends Command>>runRead(_function); }
@Override public void provideHighlightingFor(XtextResource resource, IHighlightedPositionAcceptor acceptor, CancelIndicator cancelIndicator) { if (resource == null) return; IParseResult parseResult = resource.getParseResult(); if (parseResult == null || parseResult.getRootASTElement() == null) return; if (highlightedIdentifiers == null) { highlightedIdentifiers = initializeHighlightedIdentifiers(); idLengthsToHighlight = new BitSet(); for (String s : highlightedIdentifiers.keySet()) { idLengthsToHighlight.set(s.length()); } } //TODO remove this check when the typesystem works without a java project if (resource.isValidationDisabled()) { highlightSpecialIdentifiers(acceptor, parseResult.getRootNode()); return; } doProvideHighlightingFor(resource, acceptor, cancelIndicator); }
public List<? extends SymbolInformation> getSymbols(final String query, final IReferenceFinder.IResourceAccess resourceAccess, final IResourceDescriptions indexData, final CancelIndicator cancelIndicator) { final LinkedList<SymbolInformation> result = CollectionLiterals.<SymbolInformation>newLinkedList(); Iterable<IResourceDescription> _allResourceDescriptions = indexData.getAllResourceDescriptions(); for (final IResourceDescription resourceDescription : _allResourceDescriptions) { { this.operationCanceledManager.checkCanceled(cancelIndicator); final IResourceServiceProvider resourceServiceProvider = this._registry.getResourceServiceProvider(resourceDescription.getURI()); DocumentSymbolService _get = null; if (resourceServiceProvider!=null) { _get=resourceServiceProvider.<DocumentSymbolService>get(DocumentSymbolService.class); } final DocumentSymbolService documentSymbolService = _get; if ((documentSymbolService != null)) { List<? extends SymbolInformation> _symbols = documentSymbolService.getSymbols(resourceDescription, query, resourceAccess, cancelIndicator); Iterables.<SymbolInformation>addAll(result, _symbols); } } } return result; }
@Test public void testRuleCalledSuper() throws Exception { XtextResource resource = getResourceFromString( "grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" + "generate metamodel 'myURI'\n" + "Model: super=super;\n" + "super: name=ID;"); IResourceValidator validator = get(IResourceValidator.class); List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl); assertEquals(issues.toString(), 1, issues.size()); assertEquals("Discouraged rule name 'super'", issues.get(0).getMessage()); Grammar grammar = (Grammar) resource.getContents().get(0); AbstractRule model = grammar.getRules().get(0); Assignment assignment = (Assignment) model.getAlternatives(); RuleCall ruleCall = (RuleCall) assignment.getTerminal(); assertSame(grammar.getRules().get(1), ruleCall.getRule()); }
@Test public void testCancelIndication() throws Exception { XExpression expression = expression("'string'", true); assertNull(interpreter.evaluate(expression, new NullEvaluationContext(), new CancelIndicator() { @Override public boolean isCanceled() { return true; } })); assertEquals("string", interpreter.evaluate(expression, new NullEvaluationContext(), null).getResult()); assertEquals("string", interpreter.evaluate(expression, new NullEvaluationContext(), new CancelIndicator() { @Override public boolean isCanceled() { return false; } }).getResult()); }
@Test public void testInfiniteLoopInJava() throws Exception { XExpression expression = expression( "try " + " new testdata.ClosureClient().infiniteApply(|{null})" + "catch(Exception e)" + " 'literal' ", true); assertNull(interpreter.evaluate(expression, new DefaultEvaluationContext(), new CancelIndicator() { private int i = 0; @Override public boolean isCanceled() { if (i == 500) return true; i++; return false; } })); }
@Test public void testCancelTypeResolution() { try { final XExpression exp = this.expression("true"); try { final CancelIndicator _function = () -> { return true; }; this.resolver.resolveTypes(exp, _function); Assert.fail("Type resolution should have been canceled"); } catch (final Throwable _t) { if (_t instanceof OperationCanceledError) { } else { throw Exceptions.sneakyThrow(_t); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
protected Map<String, List<Diagnostic>> getDiagnostics() { try { final Function1<CancelIndicator, HashMap<String, List<Diagnostic>>> _function = (CancelIndicator it) -> { final HashMap<String, List<Diagnostic>> result = CollectionLiterals.<String, List<Diagnostic>>newHashMap(); final Function1<Pair<String, Object>, Object> _function_1 = (Pair<String, Object> it_1) -> { return it_1.getValue(); }; Iterable<PublishDiagnosticsParams> _filter = Iterables.<PublishDiagnosticsParams>filter(ListExtensions.<Pair<String, Object>, Object>map(this.notifications, _function_1), PublishDiagnosticsParams.class); for (final PublishDiagnosticsParams diagnostic : _filter) { result.put(diagnostic.getUri(), diagnostic.getDiagnostics()); } return result; }; return this.languageServer.getRequestManager().<HashMap<String, List<Diagnostic>>>runRead(_function).get(); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
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; }
/** * Returns validation errors in given Xtext editor. */ protected List<Issue> getEditorValidationErrors(XtextEditor editor) { return editor.getDocument().readOnly(new IUnitOfWork<List<Issue>, XtextResource>() { @Override public List<Issue> exec(XtextResource state) throws Exception { final IResourceValidator validator = state.getResourceServiceProvider().getResourceValidator(); return validator.validate(state, CheckMode.ALL, CancelIndicator.NullImpl); } }); }
/** * Compiles provided Script. Can replace backslashes with single quote (for windows command line issues) * * @param depRoot * script to transpile * @param options * the {@link GeneratorOption}s to use during compilation. * @param replaceQuotes * should replace quotes (only for windows) * @return string representation of compilation result */ public String compile(Script depRoot, GeneratorOption[] options, boolean replaceQuotes) { final Resource resource = depRoot.eResource(); EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl); final AbstractSubGenerator generator = getGeneratorForResource(resource); String compileResultStr = generator.getCompileResultAsText(depRoot, options); if (replaceQuotes) { // Windows Node.js has problems with " as it interprets it as ending of script to execute compileResultStr = compileResultStr.replace("\"", "'"); } return compileResultStr; }
/** * Validates all non-external Xtext resources of the given project. Prints issues and adds them to the given issue * acceptor. * * @param markedProject * the project to validate * @param recorder * the progress recorder * @param issueAcceptor * the issue acceptor * @throws N4JSCompileErrorException * if an error occurs during validation */ private void validateProject(MarkedProject markedProject, N4ProgressStateRecorder recorder, IssueAcceptor issueAcceptor) throws N4JSCompileErrorException { if (logger.isVerbose()) logger.info(" Validating project " + markedProject); IssueCollector issueCollector = new IssueCollector(); IssueFilter issueFilter = new IssueFilter(issueCollector, issue -> issue.getSeverity() == Severity.ERROR); issueAcceptor = new IssueAcceptorTee(issueAcceptor, issueFilter); // validation TODO see IDE-1426 redesign validation calls with generators for (Resource resource : markedProject.resources) { if (resource instanceof XtextResource && // is Xtext resource (!n4jsCore.isNoValidate(resource.getURI())) && // is validating (!markedProject.externalResources.contains(resource)) // not in external folder ) { if (logger.isCreateDebugOutput()) logger.debug(" Validating resource " + resource.getURI()); XtextResource xtextResource = (XtextResource) resource; IResourceValidator validator = xtextResource.getResourceServiceProvider().getResourceValidator(); List<Issue> issues = validator.validate(xtextResource, CheckMode.ALL, CancelIndicator.NullImpl); if (!issues.isEmpty()) { recorder.markResourceIssues(resource, issues); issueAcceptor.acceptAll(issues); issues.stream().forEach(logger::issue); } } } // Projects should not compile if there are severe errors: if (!isKeepOnCompiling()) { failOnErrors(issueCollector.getCollectedIssues(), markedProject.project.getProjectId()); } }
@Override public List<Issue> validate(Resource resource, CheckMode mode, CancelIndicator cancelIndicator) { final Measurement measurment = collector.getMeasurement(resource.getURI().toString()); operationCanceledManager.checkCanceled(cancelIndicator); if (!isInSourceFolder(resource)) { return Collections.emptyList(); } List<Issue> res = super.validate(resource, mode, cancelIndicator); measurment.end(); return res; }
private void postProcessN4JSResource(N4JSResource resource, CancelIndicator cancelIndicator) { // step 1: process the AST (resolve all proxies in AST, infer type of all typable AST nodes, etc.) astProcessor.processAST(resource, cancelIndicator); // step 2: expose internal types visible from outside // (i.e. if they are referenced from a type that is visible form the outside) exposeReferencedInternalTypes(resource); // step 3: resolve remaining proxies in TModule // (the TModule was created programmatically, so it usually does not contain proxies; however, in case of // explicitly declared types, the types builder copies type references from the AST to the corresponding // TModule element *without* resolving proxies, so the TModule might contain lazy-cross-ref proxies; most of // these should have been resolved during AST traversal and exposing internal types, but some can be left) EcoreUtil.resolveAll(resource.getModule()); }
@SuppressWarnings("javadoc") public IssuesProvider(IResourceValidator resourceValidator, Resource res, OperationCanceledManager operationCanceledManager, CancelIndicator ci) { this.rv = resourceValidator; this.r = res; this.operationCanceledManager = operationCanceledManager; this.ci = ci; }
/** * Creates a new, empty inference context for the given inference variables. The cancellation manager and indicator * may be <code>null</code>. * * @param G * a rule environment used for subtype checking, etc. during constraint resolution. This rule environment * will not be changed by the inference context AND it is expected to <b>not</b> be changed by anyone * else during the life-time of the inference context. * @param inferenceVariables * the meta variables to be inferred. */ public InferenceContext(N4JSTypeSystem ts, TypeSystemHelper tsh, OperationCanceledManager operationCanceledManager, CancelIndicator cancelIndicator, RuleEnvironment G, InferenceVariable... inferenceVariables) { Objects.requireNonNull(ts); Objects.requireNonNull(tsh); Objects.requireNonNull(G); this.ts = ts; this.tsh = tsh; this.operationCanceledManager = operationCanceledManager; this.cancelIndicator = cancelIndicator; this.G = G; addInferenceVariables(false, inferenceVariables); this.reducer = new Reducer(this, G, ts, tsh); this.currentBounds = new BoundSet(this, G, ts); }
@Override public void performPostProcessing(CancelIndicator cancelIndicator) { // make sure post-processing is never performed in pre-linking phase // FIXME should never happen -> better throw an exception here if isPreLinkingPhase===true? final TModule module = getModule(); final boolean isPreLinkingPhase = module != null && module.isPreLinkingPhase(); if (!isPreLinkingPhase) { super.performPostProcessing(cancelIndicator); } }