org.eclipse.xtext.validation.CheckMode Java Examples

The following examples show how to use org.eclipse.xtext.validation.CheckMode. 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: XtendResourceSetBasedResourceDescriptionsTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUnloadedBidirectionalRef() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo class ClassA extends bar.ClassB {}");
    Pair<String, String> _mappedTo = Pair.<String, String>of("foo/ClassA.xtend", _builder.toString());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package bar class ClassB { public foo.ClassA myField }");
    Pair<String, String> _mappedTo_1 = Pair.<String, String>of("bar/ClassB.xtend", _builder_1.toString());
    final ResourceSet resourceSet = this.compiler.unLoadedResourceSet(_mappedTo, _mappedTo_1);
    final List<? extends Resource> resources = resourceSet.getResources();
    ArrayList<Resource> _arrayList = new ArrayList<Resource>(resources);
    for (final Resource res : _arrayList) {
      {
        final List<Issue> issues = this.validator.validate(res, CheckMode.ALL, CancelIndicator.NullImpl);
        Assert.assertTrue(issues.toString(), issues.isEmpty());
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #2
Source File: ResourceUIValidatorExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void addMarkers(IFile file, Resource resource, CheckMode mode, IProgressMonitor monitor)
		throws OperationCanceledException {
	try {
		List<Issue> list = getValidator(resource).validate(resource, mode, getCancelIndicator(monitor));
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		deleteMarkers(file, mode, monitor);
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		createMarkers(file, resource, list);
	} catch (OperationCanceledError error) {
		throw error.getWrapped();
	} catch (CoreException e) {
		LOGGER.error(e.getMessage(), e);
	}
}
 
Example #3
Source File: XpectN4JSES5GeneratorHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: GeneratorForTests.java    From xsemantics with Eclipse Public License 1.0 6 votes vote down vote up
public List<Issue> runGenerator(String string, ResourceSet set) {
	// load the resource
	Resource resource = set.getResource(URI.createURI(string), true);

	// validate the resource
	List<Issue> issues = validator.validate(resource, CheckMode.ALL,
			CancelIndicator.NullImpl);
	if (!issues.isEmpty()) {
		for (Issue issue : issues) {
			System.err.println(issue);
		}
		if (GeneratorUtils.hasErrors(issues))
			return issues;
	}

	fileAccess.setOutputPath(outputPath);
	generator.doGenerate(resource, fileAccess);

	System.out.println("Code generation finished.");

	return issues;
}
 
Example #6
Source File: ExceptionAnalyser.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<Diagnostic> getScriptErrors(Script script) {
	EcoreUtil.resolveAll(script.eResource());
	List<Diagnostic> diagnostics = super.getScriptErrors(script);
	Iterator<TypableElement> typableASTNodes = Iterators.filter(EcoreUtil2.eAll(script), TypableElement.class);
	List<Diagnostic> result = Lists.<Diagnostic> newArrayList(Iterables.filter(diagnostics,
			ExceptionDiagnostic.class));
	while (typableASTNodes.hasNext()) {
		TypableElement typableASTNode = typableASTNodes.next();
		RuleEnvironment ruleEnvironment = RuleEnvironmentExtensions.newRuleEnvironment(typableASTNode);
		try {
			typeSystem.type(ruleEnvironment, typableASTNode);
		} catch (Throwable cause) {
			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;
}
 
Example #7
Source File: N4JSResourceValidator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
	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);
	}
}
 
Example #8
Source File: XtendResourceSetBasedResourceDescriptionsTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testBidirectionalRef() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo class ClassA extends bar.ClassB {}");
    Pair<String, String> _mappedTo = Pair.<String, String>of("foo/ClassA.xtend", _builder.toString());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package bar class ClassB { public foo.ClassA myField }");
    Pair<String, String> _mappedTo_1 = Pair.<String, String>of("bar/ClassB.xtend", _builder_1.toString());
    final ResourceSet resourceSet = this.compiler.resourceSet(_mappedTo, _mappedTo_1);
    final List<? extends Resource> resources = resourceSet.getResources();
    ArrayList<Resource> _arrayList = new ArrayList<Resource>(resources);
    for (final Resource res : _arrayList) {
      {
        final List<Issue> issues = this.validator.validate(res, CheckMode.ALL, CancelIndicator.NullImpl);
        Assert.assertTrue(issues.toString(), issues.isEmpty());
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #9
Source File: ActiveAnnotationsRuntimeTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void assertIssues(final Pair<String, String> macroFile, final Pair<String, String> clientFile, final Procedure1<? super List<Issue>> expectations) {
  try {
    final XtextResourceSet resourceSet = this.compileMacroResourceSet(macroFile, clientFile);
    Resource _head = IterableExtensions.<Resource>head(resourceSet.getResources());
    final XtextResource singleResource = ((XtextResource) _head);
    boolean _isLoaded = singleResource.isLoaded();
    boolean _not = (!_isLoaded);
    if (_not) {
      singleResource.load(resourceSet.getLoadOptions());
    }
    final IResourceValidator validator = singleResource.getResourceServiceProvider().getResourceValidator();
    expectations.apply(validator.validate(singleResource, CheckMode.ALL, CancelIndicator.NullImpl));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #10
Source File: Main.java    From balzac with Apache License 2.0 6 votes vote down vote up
protected void runGenerator(String string) {
    // Load the resource
    ResourceSet set = resourceSetProvider.get();
    Resource resource = set.getResource(URI.createFileURI(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/");
    GeneratorContext context = new GeneratorContext();
    context.setCancelIndicator(CancelIndicator.NullImpl);
    generator.generate(resource, fileAccess, context);

    System.out.println("Code generation finished.");
}
 
Example #11
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug345433_02() 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(e0 | " +
		"			!e0.isAssigned() && !e0.isEObjectRuleCall()" +
		"		).map(e1 | e1.rule)\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 function = (XtendFunction) clazz.getMembers().get(1);
	XExpression body = function.getExpression();
	LightweightTypeReference bodyType = getType(body);
	assertEquals("java.lang.Iterable<org.eclipse.xtext.AbstractRule>", bodyType.getIdentifier());
	XBlockExpression block = (XBlockExpression) body;
	XMemberFeatureCall featureCall = (XMemberFeatureCall) block.getExpressions().get(0);
	XClosure closure = (XClosure) featureCall.getMemberCallArguments().get(0);
	JvmFormalParameter e1 = closure.getFormalParameters().get(0);
	assertEquals("e1", e1.getSimpleName());
	assertEquals("org.eclipse.xtext.RuleCall", getType(e1).getIdentifier());
}
 
Example #12
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 #13
Source File: ConvertJavaCode.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private boolean validateResource(Resource resource) {
	if (resource.getErrors().size() == 0) {
		List<Issue> issues = Lists.newArrayList(filter(((XtextResource) resource).getResourceServiceProvider()
				.getResourceValidator().validate(resource, CheckMode.ALL, CancelIndicator.NullImpl),
				new Predicate<Issue>() {
					@Override
					public boolean apply(Issue issue) {
						String code = issue.getCode();
						return issue.getSeverity() == Severity.ERROR
								&& !(IssueCodes.DUPLICATE_TYPE.equals(code) || org.eclipse.xtend.core.validation.IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH
										.equals(code));
					}
				}));
		return issues.size() == 0;
	}
	return false;
}
 
Example #14
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 #15
Source File: ActiveAnnotationsProcessingInIDETest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void assertProcessing(final Pair<String, String> macroContent, final Pair<String, String> clientContent, final Procedure1<? super CompilationUnitImpl> expectations) {
  try {
    this.macroFile = this.newSource(ActiveAnnotationsProcessingInIDETest.macroProject, macroContent.getKey(), macroContent.getValue().toString());
    final int lidx = macroContent.getKey().lastIndexOf("/");
    if ((lidx != (-1))) {
      this.exportedPackage = macroContent.getKey().substring(0, lidx).replace("/", ".");
      boolean _addExportedPackages = WorkbenchTestHelper.addExportedPackages(ActiveAnnotationsProcessingInIDETest.macroProject.getProject(), this.exportedPackage);
      if (_addExportedPackages) {
        IResourcesSetupUtil.reallyWaitForAutoBuild();
      }
    }
    this.clientFile = this.newSource(ActiveAnnotationsProcessingInIDETest.userProject, clientContent.getKey(), clientContent.getValue().toString());
    IResourcesSetupUtil.waitForBuild();
    final ResourceSet resourceSet = this.resourceSetProvider.get(ActiveAnnotationsProcessingInIDETest.userProject.getProject());
    final Resource resource = resourceSet.getResource(URI.createPlatformResourceURI(this.clientFile.getFullPath().toString(), true), true);
    EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
    this.validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
    final CompilationUnitImpl unit = this.compilationUnitProvider.get();
    unit.setXtendFile(IterableExtensions.<XtendFile>head(Iterables.<XtendFile>filter(resource.getContents(), XtendFile.class)));
    expectations.apply(unit);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #16
Source File: ProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	modelAsText = "stuff mystuff\nstuff yourstuff refs _mystuff stuff hisstuff refs _yourstuff// Comment";
	IFile file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
	editor = openEditor(file);
	document = editor.getDocument();
	hover = TestsActivator.getInstance().getInjector(getEditorId()).getInstance(ProblemAnnotationHover.class);
	hover.setSourceViewer(editor.getInternalSourceViewer());
	List<Issue> issues = document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
		@Override
		public List<Issue> exec(XtextResource state) throws Exception {
			return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null);
		}	
	});
	MarkerCreator markerCreator =  TestsActivator.getInstance().getInjector(getEditorId()).getInstance(MarkerCreator.class);
	for (Issue issue : issues) {
		markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
	}
}
 
Example #17
Source File: GamlEditor.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private void scheduleValidationJob() {
	if (!isEditable()) { return; }
	final IValidationIssueProcessor processor = new MarkerIssueProcessor(getResource(),
			getInternalSourceViewer().getAnnotationModel(), markerCreator, markerTypeProvider);
	final ValidationJob validate = new ValidationJob(validator, getDocument(), processor, CheckMode.FAST_ONLY) {
		@Override
		protected IStatus run(final IProgressMonitor monitor) {
			final List<Issue> issues = getDocument().readOnly(resource -> {
				if (resource.isValidationDisabled()) { return Collections.emptyList(); }
				return validator.validate(resource, getCheckMode(), null);
			});
			processor.processIssues(issues, monitor);
			return Status.OK_STATUS;
		}

	};
	validate.schedule();

}
 
Example #18
Source File: XtendBatchCompiler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected List<Issue> validate(ResourceSet resourceSet) {
	List<Issue> issues = Lists.newArrayList();
	List<Resource> resources = Lists.newArrayList(resourceSet.getResources());
	for (Resource resource : resources) {
		IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE
				.getResourceServiceProvider(resource.getURI());
		if (resourceServiceProvider != null && isSourceFile(resource)) {
			IResourceValidator resourceValidator = resourceServiceProvider.getResourceValidator();
			List<Issue> result = resourceValidator.validate(resource, CheckMode.ALL, null);
			addAll(issues, result);
		}
	}
	return issues;
}
 
Example #19
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 #20
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testMissingArgument3() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'myURI'\n" +
			"Model: rule=Rule<true>;\n" + 
			"Rule<First, Missing, AlsoMissing>: 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("Expected 3 arguments but got 1", issues.get(0).getMessage());
}
 
Example #21
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testOutOfSequenceArgument_01() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'myURI'\n" +
			"Model: rule=Rule<true, C=false, B=true>;\n" + 
			"Rule<A, B, C>: name=ID;");

	IResourceValidator validator = get(IResourceValidator.class);
	List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
	assertEquals(issues.toString(), 2, issues.size());
	assertEquals("Out of sequence named argument. Expected value for B", issues.get(0).getMessage());
	assertEquals("Out of sequence named argument. Expected value for C", issues.get(1).getMessage());
}
 
Example #22
Source File: AbstractBuilderParticipantTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
		}
	});
}
 
Example #23
Source File: ReducedXtextResourceValidatorTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNoEcoreLinkingErrors() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("import \'http://test\' as test");
  _builder.newLine();
  _builder.append("Root returns test::Foo: name=ID;");
  _builder.newLine();
  final String grammarAsString = _builder.toString();
  final List<Issue> issues = this.resourceValidator.validate(this.getErroneousResource(grammarAsString), CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl);
  Assert.assertEquals(issues.toString(), 0, issues.size());
}
 
Example #24
Source File: ReducedXtextResourceValidatorTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRuleLinkingErrors() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("import \'http://test\' as test");
  _builder.newLine();
  _builder.append("Root returns test::Foo : name=IDS;");
  _builder.newLine();
  final String grammarAsString = _builder.toString();
  final List<Issue> issues = this.resourceValidator.validate(this.getErroneousResource(grammarAsString), CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl);
  Assert.assertEquals(issues.toString(), 1, issues.size());
  Assert.assertTrue(issues.toString(), IterableExtensions.<Issue>head(issues).getMessage().contains("IDS"));
}
 
Example #25
Source File: Bug390595Test.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNoExceptionDuringResolutionCreation() {
	String code =
		// @formatter:off
		"{\n" +
		"val n = newHashSet ( )\n" +
		"val m = newHashSet ( )\n" +
		"if ( n < m ) { }\n" +
		"}";
		// @formatter:on
	XtextResource resource = getResourceFor(new StringInputStream(code));
	modificationContext.setDocument(getDocument(resource, code));
	Issue issue = Iterables.getFirst(resourceValidator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl), null);
	Iterables.getFirst(quickfixProvider.getResolutionsForLinkingIssue(issue), null);
}
 
Example #26
Source File: XtextDocumentProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected void registerAnnotationInfoProcessor(ElementInfo info) {
	XtextDocument doc = (XtextDocument) info.fDocument;
	if(info.fModel != null) {
		AnnotationIssueProcessor annotationIssueProcessor = new AnnotationIssueProcessor(doc, info.fModel,
			issueResolutionProvider);
		ValidationJob job = new ValidationJob(resourceValidator, doc, annotationIssueProcessor, CheckMode.FAST_ONLY);
		doc.setValidationJob(job);
	}
}
 
Example #27
Source File: ValidationJob.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ValidationJob(IResourceValidator xtextResourceChecker, IReadAccess<XtextResource> xtextDocument,
		IValidationIssueProcessor validationIssueProcessor,CheckMode checkMode) {
	super(Messages.ValidationJob_0);
	this.xtextDocument = xtextDocument;
	this.resourceValidator = xtextResourceChecker;
	this.validationIssueProcessor = validationIssueProcessor;
	this.checkMode = checkMode;
}
 
Example #28
Source File: ValidatingEditorCallback.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private ValidationJob newValidationJob(XtextEditor editor) {
	IValidationIssueProcessor issueProcessor;
	if (editor.getResource() == null) {
		issueProcessor = new AnnotationIssueProcessor(editor.getDocument(), editor.getInternalSourceViewer().getAnnotationModel(),
				issueResolutionProvider);
	} else {
		issueProcessor = new MarkerIssueProcessor(editor.getResource(), editor.getInternalSourceViewer().getAnnotationModel(),
				markerCreator, markerTypeProvider);
	}
	ValidationJob validationJob = new ValidationJob(resourceValidator, editor.getDocument(), issueProcessor, CheckMode.NORMAL_AND_FAST);
	return validationJob;
}
 
Example #29
Source File: IncrementalBuilder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Validate the resource and return true, if the build should proceed for the current state.
 */
protected boolean validate(Resource resource) {
	IResourceValidator resourceValidator = getResourceServiceProvider(resource).getResourceValidator();
	if (resourceValidator == null) {
		return true;
	}
	List<Issue> validationResult = resourceValidator.validate(resource, CheckMode.ALL,
			request.getCancelIndicator());
	return request.getAfterValidate().afterValidate(resource.getURI(), validationResult);
}
 
Example #30
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testOutOfSequenceArgument_02() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate metamodel 'myURI'\n" +
			"Model: rule=Rule<true, B=false, C=true>;\n" + 
			"Rule<A, B, C>: name=ID;");

	IResourceValidator validator = get(IResourceValidator.class);
	List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
	assertEquals(issues.toString(), 0, issues.size());
}