org.eclipse.xtext.util.CancelIndicator Java Examples

The following examples show how to use org.eclipse.xtext.util.CancelIndicator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LazyLinkingResource.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * resolves any lazy cross references in this resource, adding Issues for unresolvable elements to this resource.
 * This resource might still contain resolvable proxies after this method has been called.
 * 
 * @param mon a {@link CancelIndicator} can be used to stop the resolution.
 */
public void resolveLazyCrossReferences(final CancelIndicator mon) {
	final CancelIndicator monitor = mon == null ? CancelIndicator.NullImpl : mon;
	TreeIterator<Object> iterator = EcoreUtil.getAllContents(this, true);
	while (iterator.hasNext()) {
		operationCanceledManager.checkCanceled(monitor);
		InternalEObject source = (InternalEObject) iterator.next();
		EStructuralFeature[] eStructuralFeatures = ((EClassImpl.FeatureSubsetSupplier) source.eClass()
				.getEAllStructuralFeatures()).crossReferences();
		if (eStructuralFeatures != null) {
			for (EStructuralFeature crossRef : eStructuralFeatures) {
				operationCanceledManager.checkCanceled(monitor);
				resolveLazyCrossReference(source, crossRef);
			}
		}
	}
}
 
Example #2
Source File: PostProcessingAwareResource.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void doMainPostProcessing(CancelIndicator cancelIndicator) {
	try {
		postProcessingThrowable = null;
		isPostProcessing = true;

		if (postProcessor == null) {
			throw new IllegalStateException("post processor is null");
		}
		if (postProcessor.expectsLazyLinkResolution()) {
			// in next line: call on 'super' because the method in 'this' forwards here!!
			super.resolveLazyCrossReferences(cancelIndicator);
		}

		postProcessor.performPostProcessing(this, cancelIndicator);

	} catch (Throwable th) {
		markAsPostProcessingDone();
		postProcessingThrowable = th;
		throw th;
	}
}
 
Example #3
Source File: ResourceLoadingStatistics.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private FileLoadInfo investigate(IN4JSProject project, URI fileURI, IProgressMonitor monitor) {
	final CancelIndicator cancelIndicator = new MonitorBasedCancelIndicator(monitor);
	operationCanceledManager.checkCanceled(cancelIndicator);

	final ResourceSet resSet = n4jsCore.createResourceSet(Optional.of(project));
	final N4JSResource res = (N4JSResource) resSet.createResource(fileURI);
	try {
		res.load(Collections.emptyMap());
	} catch (IOException e) {
		e.printStackTrace();
	}
	res.getContents(); // trigger loading of AST
	res.resolveLazyCrossReferences(cancelIndicator);

	// now start counting what was loaded incidentally ...
	return investigate(resSet);
}
 
Example #4
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _doEvaluate(XBasicForLoopExpression forLoop, IEvaluationContext context, CancelIndicator indicator) {
	IEvaluationContext forkedContext = context.fork();
	for (XExpression initExpression : forLoop.getInitExpressions()) {
		internalEvaluate(initExpression, forkedContext, indicator);
	}
	XExpression expression = forLoop.getExpression();
	Object condition = expression == null ? Boolean.TRUE : internalEvaluate(expression, forkedContext, indicator);
	while (Boolean.TRUE.equals(condition)) {
		internalEvaluate(forLoop.getEachExpression(), forkedContext, indicator);
		for (XExpression updateExpression : forLoop.getUpdateExpressions()) {
			internalEvaluate(updateExpression, forkedContext, indicator);
		}
		condition = expression == null ? Boolean.TRUE : internalEvaluate(expression, forkedContext, indicator);
	}
	return null;
}
 
Example #5
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Object _doEvaluate(XListLiteral literal, IEvaluationContext context, CancelIndicator indicator) {
	IResolvedTypes resolveTypes = typeResolver.resolveTypes(literal);
	LightweightTypeReference type = resolveTypes.getActualType(literal);
	List<Object> list = newArrayList();
	for(XExpression element: literal.getElements()) {
		if (indicator.isCanceled())
			throw new InterpreterCanceledException();
		list.add(internalEvaluate(element, context, indicator));
	}
	if(type != null && type.isArray()) {
		try {
			LightweightTypeReference componentType = type.getComponentType();
			return Conversions.unwrapArray(list, getJavaType(componentType.getType()));
		} catch (ClassNotFoundException e) {
		}
	}
	return Collections.unmodifiableList(list);
}
 
Example #6
Source File: GeneratorComponent.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void invoke(IWorkflowContext ctx) {
	GeneratorDelegate instance = getCompiler();
	IFileSystemAccess2 fileSystemAccess = getConfiguredFileSystemAccess();
	for (String slot : slotNames) {
		Object object = ctx.get(slot);
		if (object == null) {
			throw new IllegalStateException("Slot '"+slot+"' was empty!");
		}
		if (object instanceof Iterable) {
			Iterable<?> iterable = (Iterable<?>) object;
			for (Object object2 : iterable) {
				if (!(object2 instanceof Resource)) {
					throw new IllegalStateException("Slot contents was not a Resource but a '"+object.getClass().getSimpleName()+"'!");
				}
				GeneratorContext context = new GeneratorContext();
				context.setCancelIndicator(CancelIndicator.NullImpl);
				instance.generate((Resource) object2, fileSystemAccess, context);
			}
		} else if (object instanceof Resource) {
			instance.doGenerate((Resource) object, fileSystemAccess);
		} else {
			throw new IllegalStateException("Slot contents was not a Resource but a '"+object.getClass().getSimpleName()+"'!");
		}
	}
}
 
Example #7
Source File: XbaseHighlightingCalculator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
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);
				}
			}
		}
	}
}
 
Example #8
Source File: RenameElementHandler.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	NamedElement element = refactoring.getContextObject();
	if (element != null) {
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();

		List<Issue> issues = validator.validate(element.eResource(), CheckMode.NORMAL_AND_FAST,
				CancelIndicator.NullImpl);
		Stream<Issue> errors = issues.stream().filter(issue -> issue.getSeverity() == Severity.ERROR);

		RenameDialog dialog = new RenameDialog(window.getShell(), "Rename..", "Please enter new name: ",
				element.getName(), new NameUniquenessValidator(element), errors.count() > 0);

		if (dialog.open() == Window.OK) {
			String newName = dialog.getNewName();
			if (newName != null) {
				((RenameRefactoring) refactoring).setNewName(newName);
				refactoring.execute();
			}
		}

	}
	return null;
}
 
Example #9
Source File: QuickfixTestBuilder.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public QuickfixTestBuilder create(final String fileName, final String model) {
  try {
    QuickfixTestBuilder _xblockexpression = null;
    {
      final String positionMarker = this.getPositionMarker(model);
      final IFile file = this._workbenchTestHelper.createFile(fileName, model.replace(positionMarker, ""));
      this.editor = this.openEditorSafely(file);
      final IXtextDocument document = this.editor.getDocument();
      Assert.assertNotNull("Error getting document from editor", document);
      final IUnitOfWork<List<Issue>, XtextResource> _function = (XtextResource it) -> {
        return this.issues = this._iResourceValidator.validate(it, CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl);
      };
      document.<List<Issue>>readOnly(_function);
      this.caretOffset = model.indexOf(positionMarker);
      _xblockexpression = this;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #10
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug345433_01() throws Exception {
	String classAsString = 
		"import static extension org.eclipse.xtext.GrammarUtil.*\n" +
		"class Foo {" +
		"	org.eclipse.xtext.Grammar grammar\n" +
		"	def function1() {\n" + 
		"		grammar.containedRuleCalls.filter(e | " +
		"			!e.isAssigned() && !e.isEObjectRuleCall()" +
		"		).map(e | e.rule)\n" + 
		"	}\n" +
		"	def function2() {\n" +
		"		newArrayList(function1().head())\n" +
		"	}\n" +
		"}";
	XtendClass clazz = clazz(classAsString);
	IResourceValidator validator = ((XtextResource) clazz.eResource()).getResourceServiceProvider().getResourceValidator();
	List<Issue> issues = validator.validate(clazz.eResource(), CheckMode.ALL, CancelIndicator.NullImpl);
	assertTrue("Resource contained errors : " + issues.toString(), issues.isEmpty());
	XtendFunction function1 = (XtendFunction) clazz.getMembers().get(1);
	JvmOperation operation1 = associator.getDirectlyInferredOperation(function1);
	assertEquals("java.lang.Iterable<org.eclipse.xtext.AbstractRule>", operation1.getReturnType().getIdentifier());
	XtendFunction function2 = (XtendFunction) clazz.getMembers().get(2);
	JvmOperation operation2 = associator.getDirectlyInferredOperation(function2);
	assertEquals("java.util.ArrayList<org.eclipse.xtext.AbstractRule>", operation2.getReturnType().getIdentifier());
}
 
Example #11
Source File: N4JSCodeActionService.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Applies all fixes of the same kind to the project containing the given URI.
 */
public WorkspaceEdit applyToProject(URI uri, String issueCode, String fixId, CancelIndicator cancelIndicator) {

	WorkspaceEdit result = new WorkspaceEdit();
	QuickFixImplementation quickfix = findOriginatingQuickfix(issueCode, fixId);
	if (quickfix == null) {
		return result;
	}

	Optional<? extends IN4JSProject> project = n4jsCore.findProject(uri);
	if (!project.isPresent()) {
		return result;
	}
	List<URI> urisInProject = Lists.newArrayList(
			IterableExtensions.flatMap(project.get().getSourceContainers(), sc -> sc));

	Map<String, List<TextEdit>> allEdits = new HashMap<>();
	for (URI currURI : urisInProject) {
		Map<String, List<TextEdit>> edits = doApplyToFile(currURI, issueCode, quickfix, cancelIndicator);
		allEdits.putAll(edits);
	}
	result.setChanges(allEdits);
	return result;
}
 
Example #12
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #13
Source File: RequestManagerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test(timeout = 1000)
public void testRunWriteLogExceptionCancellable() {
  final Runnable _function = () -> {
    final Function0<Object> _function_1 = () -> {
      throw new RuntimeException();
    };
    final Function2<CancelIndicator, Object, Object> _function_2 = (CancelIndicator $0, Object $1) -> {
      return null;
    };
    final CompletableFuture<Object> future = this.requestManager.<Object, Object>runWrite(_function_1, _function_2);
    try {
      future.join();
    } catch (final Throwable _t) {
      if (_t instanceof Exception) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  };
  final LoggingTester.LogCapture logResult = LoggingTester.captureLogging(Level.ALL, WriteRequest.class, _function);
  logResult.assertLogEntry("Error during request:");
}
 
Example #14
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void didRefreshOpenFile(OpenFileContext ofc, CancelIndicator ci) {
	if (client instanceof LanguageClientExtensions) {

		LanguageClientExtensions clientExtensions = (LanguageClientExtensions) client;
		XtextResource resource = ofc.getResource();
		IResourceServiceProvider resourceServiceProvider = resource.getResourceServiceProvider();
		IColoringService coloringService = resourceServiceProvider.get(IColoringService.class);

		if (coloringService != null) {
			XDocument doc = ofc.getDocument();
			List<? extends ColoringInformation> colInfos = coloringService.getColoring(resource, doc);

			if (!IterableExtensions.isNullOrEmpty(colInfos)) {
				String uri = resource.getURI().toString();
				ColoringParams colParams = new ColoringParams(uri, colInfos);
				clientExtensions.updateColoring(colParams);
			}
		}
	}

	ILanguageServerAccess.Context ctx = new ILanguageServerAccess.Context(ofc.getResource(), ofc.getDocument(),
			true, ci);
	semanticHighlightingRegistry.update(ctx);
}
 
Example #15
Source File: ContentAssistService.java    From xtext-web with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Apply a text update and then create content assist proposals. This document
 * read operation is scheduled with higher priority, so currently running
 * operations may be canceled. The document processing is rescheduled as
 * background work afterwards.
 */
public ContentAssistResult createProposalsWithUpdate(XtextWebDocumentAccess document, String deltaText,
		int deltaOffset, int deltaReplaceLength, ITextRegion selection, int caretOffset, int proposalsLimit)
		throws InvalidRequestException {
	String[] stateIdWrapper = new String[1];
	ContentAssistContext[] contexts = document
			.modify(new CancelableUnitOfWork<ContentAssistContext[], IXtextWebDocument>() {
				@Override
				public ContentAssistContext[] exec(IXtextWebDocument it, CancelIndicator cancelIndicator)
						throws Exception {
					it.setDirty(true);
					it.createNewStateId();
					stateIdWrapper[0] = it.getStateId();
					it.updateText(deltaText, deltaOffset, deltaReplaceLength);
					return getContexts(it, selection, caretOffset);
				}
			});
	List<ContentAssistContext> contextsList = Arrays.asList(contexts);
	return createProposals(contextsList, stateIdWrapper[0], proposalsLimit);
}
 
Example #16
Source File: DefaultUniqueNameContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Context tryGetContext(Resource resource, CancelIndicator cancelIndicator) {
	IResourceDescriptions index = getIndex(resource);
	if (index == null) {
		return null;
	}
	IResourceDescription description = getResourceDescription(resource);
	if (description == null) {
		return null;
	}
	List<IContainer> containers = containerManager.getVisibleContainers(description, index);
	return new DefaultUniqueNameContext(description, new Selectable(containers), getCaseInsensitivityHelper(),
			cancelIndicator);
}
 
Example #17
Source File: SCTResourceTest.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testLinkingError1() throws Exception {
	Statechart statechart = createStatechart("internal: event Event1");
	res.getContents().add(statechart);
	Transition transition = createTransition("Event2 [true] / 3 * 3");
	res.getContents().add(transition);
	res.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	System.out.println(res.getLinkingDiagnostics());
	assertEquals(1, res.getLinkingDiagnostics().size());
}
 
Example #18
Source File: MultiProjectTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCrossProjectLink() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Foo {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("Bar bar");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final URI foo = this.createFile(this.project0, "Foo.testlang", _builder);
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("type Bar {");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  final URI bar = this.createFile(this.project1, "Bar.testlang", _builder_1);
  this.workspaceManager.doBuild(Collections.<URI>unmodifiableList(CollectionLiterals.<URI>newArrayList(foo, bar)), CollectionLiterals.<URI>emptyList(), CancelIndicator.NullImpl);
  Assert.assertEquals(2, this.diagnostics.size());
  Assert.assertEquals(1, this.diagnostics.get(foo).size());
  Assert.assertEquals(Diagnostic.LINKING_DIAGNOSTIC, IterableExtensions.<Issue>head(this.diagnostics.get(foo)).getCode());
  Assert.assertTrue(this.diagnostics.get(bar).isEmpty());
  this.diagnostics.clear();
  List<String> _dependencies = this.workspaceManager.getProjectManager(this.project0.getName()).getProjectDescription().getDependencies();
  String _name = this.project1.getName();
  _dependencies.add(_name);
  this.workspaceManager.doBuild(Collections.<URI>unmodifiableList(CollectionLiterals.<URI>newArrayList(foo, bar)), CollectionLiterals.<URI>emptyList(), CancelIndicator.NullImpl);
  Assert.assertEquals(2, this.diagnostics.size());
  Assert.assertTrue(this.diagnostics.get(foo).isEmpty());
  Assert.assertTrue(this.diagnostics.get(bar).isEmpty());
}
 
Example #19
Source File: HoverService.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Compute a hover result for a content assist proposal at the given offset.
 */
public HoverResult getHover(XtextWebDocumentAccess document, String proposal, ITextRegion selection, int offset)
		throws InvalidRequestException {
	return document.readOnly(new CancelableUnitOfWork<HoverResult, IXtextWebDocument>() {
		@Override
		public HoverResult exec(IXtextWebDocument it, CancelIndicator cancelIndicator) throws Exception {
			ContentAssistContext[] contexts = contentAssistService.getContexts(it, selection, offset);
			Wrapper<Object> proposedElement = new Wrapper<Object>();
			Collection<ContentAssistContext> contextsList = Arrays.asList(contexts);
			contentAssistService.getProposalProvider().createProposals(contextsList,
					new IIdeContentProposalAcceptor() {
						@Override
						public void accept(ContentAssistEntry entry, int priority) {
							operationCanceledManager.checkCanceled(cancelIndicator);
							if (entry != null && entry.getSource() != null
									&& Objects.equal(entry.getProposal(), proposal)) {
								proposedElement.set(entry.getSource());
							}
						}

						@Override
						public boolean canAcceptMoreProposals() {
							return proposedElement.get() == null;
						}
					});
			return createHover(proposedElement.get(), it.getStateId(), cancelIndicator);
		}
	});
}
 
Example #20
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void didChangeConfiguration(DidChangeConfigurationParams params) {
	requestManager.runWrite(() -> {
		workspaceManager.refreshWorkspaceConfig(CancelIndicator.NullImpl);
		return null;
	}, (a, b) -> null);
}
 
Example #21
Source File: BuildManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Run an initial build
 *
 * @return the delta.
 */
public List<IResourceDescription.Delta> doInitialBuild(List<ProjectDescription> projects,
		CancelIndicator indicator) {
	List<ProjectDescription> sortedDescriptions = sortByDependencies(projects);
	List<IResourceDescription.Delta> result = new ArrayList<>();
	for (ProjectDescription description : sortedDescriptions) {
		IncrementalBuilder.Result partialresult = workspaceManager.getProjectManager(description.getName())
				.doInitialBuild(indicator);
		result.addAll(partialresult.getAffectedResources());
	}
	return result;
}
 
Example #22
Source File: OpenFilesManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Same as {@link #runInTemporaryFileContext(URI, String, BiFunction)}, but accepts an outer cancel indicator as
 * argument as an additional source of cancellation. The implementation of the given function 'task' should only use
 * the cancel indicator passed into 'task' (it is a {@link CancelIndicatorUtil#combine(List) combination} of the
 * given outer cancel indicator and other sources of cancellation).
 */
public synchronized <T> CompletableFuture<T> runInTemporaryFileContext(URI uri, String description,
		boolean resolveAndValidate, CancelIndicator outerCancelIndicator,
		BiFunction<OpenFileContext, CancelIndicator, T> task) {

	OpenFileContext tempOFC = createOpenFileContext(uri, true);

	String descriptionWithContext = description + " (temporary) [" + uri.lastSegment() + "]";
	return doSubmitTask(tempOFC, descriptionWithContext, (_tempOFC, ciFromExecutor) -> {
		CancelIndicator ciCombined = CancelIndicatorUtil.combine(outerCancelIndicator, ciFromExecutor);
		_tempOFC.initOpenFile(resolveAndValidate, ciCombined);
		return task.apply(_tempOFC, ciCombined);
	});
}
 
Example #23
Source File: OpenFilesManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
protected <T> CompletableFuture<T> doSubmitTask(OpenFileContext ofc, String description,
		BiFunction<OpenFileContext, CancelIndicator, T> task) {

	Object queueId = getQueueIdForOpenFileContext(ofc.getURI(), ofc.isTemporary());
	return lspExecutorService.submit(queueId, description, ci -> {
		try {
			currentContext.set(ofc);
			return task.apply(ofc, ci);
		} finally {
			currentContext.set(null);
		}
	});
}
 
Example #24
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param featureCall unused in this context but required for dispatching
 * @param indicator unused in this context but required for dispatching
 */
protected Object _invokeFeature(JvmIdentifiableElement identifiable, XAbstractFeatureCall featureCall, Object receiver,
		IEvaluationContext context, CancelIndicator indicator) {
	if (receiver != null)
		throw new IllegalStateException("feature was simple feature call but got receiver instead of null. Receiver: " + receiver);
	String localVarName = featureNameProvider.getSimpleName(identifiable);
	Object value = context.getValue(QualifiedName.create(localVarName));
	return value;
}
 
Example #25
Source File: IShouldGenerate.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean shouldGenerate(Resource resource, CancelIndicator cancelIndicator) {
	if (!resource.getErrors().isEmpty()) {
		return false;
	}
	List<Issue> issues = resourceValidator.validate(resource, CheckMode.NORMAL_AND_FAST, cancelIndicator);
	return !exists(issues, (Issue issue) -> Objects.equal(issue.getSeverity(), Severity.ERROR));
}
 
Example #26
Source File: XProjectManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Initial build reads the project state and resolves changes. Generate output files.
 * <p>
 * This method assumes that it is only invoked in situations when the client does not have any diagnostics stored,
 * e.g. directly after invoking {@link #doClean(CancelIndicator)}, and that therefore no 'publishDiagnostics' events
 * with an empty list of diagnostics need to be sent to the client in order to remove obsolete diagnostics. The same
 * applies to updates of {@link #issueRegistry}, accordingly.
 * <p>
 * NOTE: this is not only invoked shortly after server startup but also at various other occasions, for example
 * <ul>
 * <li>when the client executes the {@link N4JSCommandService#rebuild(ILanguageServerAccess, CancelIndicator)
 * rebuild command},
 * <li>when the workspace folder is changed in VS Code.
 * </ul>
 */
public XBuildResult doInitialBuild(CancelIndicator cancelIndicator) {
	ResourceChangeSet changeSet = projectStateHolder.readProjectState(projectConfig);
	XBuildResult result = doBuild(
			changeSet.getModified(), changeSet.getDeleted(), Collections.emptyList(), false, true, cancelIndicator);

	// send issues to client
	// (below code won't send empty 'publishDiagnostics' events for resources without validation issues, see API doc
	// of this method for details)
	Multimap<URI, LSPIssue> validationIssues = projectStateHolder.getValidationIssues();
	for (URI location : validationIssues.keys()) {
		Collection<LSPIssue> issues = validationIssues.get(location);
		publishIssues(location, issues);
	}

	// clear the resource set to release memory
	boolean wasDeliver = resourceSet.eDeliver();
	try {
		resourceSet.eSetDeliver(false);
		resourceSet.getResources().clear();
	} finally {
		resourceSet.eSetDeliver(wasDeliver);
	}

	LOG.info("Project built: " + this.projectConfig.getName());
	return result;
}
 
Example #27
Source File: StatemachineSemanticHighlightingCalculator.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
protected void highlightSignal(EObject owner, Signal signal, EStructuralFeature feature,
		IHighlightedPositionAcceptor acceptor, CancelIndicator cancelIndicator) {
	operationCanceledManager.checkCanceled(cancelIndicator);
	for (INode n : NodeModelUtils.findNodesForFeature(owner, feature)) {
		acceptor.addPosition(n.getOffset(), n.getLength(), signal.eClass().getName());
	}
}
 
Example #28
Source File: IssuesProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("javadoc")
public IssuesProvider(IResourceValidator resourceValidator, Resource res, CheckMode checkMode,
		OperationCanceledManager operationCanceledManager, CancelIndicator ci) {
	this.rv = resourceValidator;
	this.r = res;
	this.checkMode = checkMode;
	this.operationCanceledManager = operationCanceledManager;
	this.ci = ci;
}
 
Example #29
Source File: AbstractBatchTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public final IResolvedTypes resolveTypes(final /* @Nullable */ EObject object, CancelIndicator monitor) {
	if (object == null || object.eIsProxy()) {
		return IResolvedTypes.NULL;
	}
	Resource resource = object.eResource();
	validateResourceState(resource);
	if (resource instanceof JvmMemberInitializableResource) {
		((JvmMemberInitializableResource) resource).ensureJvmMembersInitialized();
	}
	return doResolveTypes(object, monitor);
}
 
Example #30
Source File: SarlBatchCompiler.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Run the compilation.
 *
 * @param cancel is the tool for canceling the compilation.
 * @return success status.
 */
public boolean compile(CancelIndicator cancel) {
	final IProgressMonitor monitor;
	if (cancel != null) {
		monitor = new CancelIndicatorProgressMonitor(cancel);
	} else {
		monitor = null;
	}
	return compile(monitor);
}