Java Code Examples for org.eclipse.xtext.parser.IParseResult#hasSyntaxErrors()

The following examples show how to use org.eclipse.xtext.parser.IParseResult#hasSyntaxErrors() . 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: HighlightingParserTester.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses the input and returns a list of lexer tokens. Asserts that the produced tokens are equal to the tokens
 * that the production parser produced.
 *
 * @return the tokens for the highlighting.
 */
public List<Token> getTokens(CharSequence input) {
	List<Token> result;
	IParseResult parseResult = parser.parse(new StringReader(input.toString()));
	if (!parseResult.hasSyntaxErrors()) {
		result = throwingHighlightingParser.getTokens(input);
	} else {
		result = highlightingParser.getTokens(input);
	}
	// assert equal tokens
	Iterator<Token> iter = result.iterator();
	for (ILeafNode leaf : parseResult.getRootNode().getLeafNodes()) {
		Assert.assertTrue("hasNext at index " + leaf.getTotalOffset() + " for leaf '" + leaf.getText() + "'",
				iter.hasNext());
		Token token = iter.next();
		// TODO: assert token type
		Assert.assertEquals(leaf.getText(), token.getText());
	}
	return result;
}
 
Example 2
Source File: NpmNameAndVersionValidatorHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * version validator based on N4MF parser (and its support for version syntax).
 *
 * @return error message or null if there are no errors
 */
private String parsingVersionValidator(final String data) {
	String result = null;

	IParseResult parseResult = semverHelper.getParseResult(data);
	if (parseResult == null) {
		result = "Could not create version from string :" + data + ":\n";
	} else if (parseResult.hasSyntaxErrors()) {
		INode firstErrorNode = parseResult.getSyntaxErrors().iterator().next();
		result = "Parsing error: " + firstErrorNode.getSyntaxErrorMessage().getMessage();
	}

	// otherwise, parsedVersion is valid and result remains 'null'
	// to indicate validity (see {@link IInputValidator#isValid})

	return result;
}
 
Example 3
Source File: N4JSRenameStrategy.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method uses parser of rule IdentifierName to make sure names follow the rule.
 */
@Override
public RefactoringStatus validateNewName(String newName) {
	// N4JS already contains N4JSX grammar
	IParser parser = N4LanguageUtils.getServiceForContext("n4js", IParser.class).get();
	Grammar grammar = this.getTypeExpressionsGrammar();
	ParserRule parserRule = (ParserRule) GrammarUtil.findRuleForName(grammar,
			"org.eclipse.n4js.ts.TypeExpressions.IdentifierName");

	// Parse the new name using the IdentifierName rule of the parser
	IParseResult parseResult = parser.parse(parserRule, new StringReader(newName));
	if (parseResult.hasSyntaxErrors()) {
		String parseErrorMessages = Joiner.on("\n").join(Iterables.transform(parseResult.getSyntaxErrors(),
				(node) -> node.getSyntaxErrorMessage().getMessage()));
		return RefactoringStatus.createFatalErrorStatus(parseErrorMessages);
	}

	RefactoringStatus status = new RefactoringStatus();
	return status;
}
 
Example 4
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns true if the previous document state was completely broken, e.g. the parser did not recover at all.
 * This may happen e.g. in Xtend for documents like
 * <pre>import static class C {}</pre>
 * where the class keyword is consumed as an invalid token in the import declaration and everything thereafter
 * is unrecoverable.
 */
protected boolean isBrokenPreviousState(IParseResult previousParseResult, int offset) {
	if (previousParseResult.hasSyntaxErrors()) {
		BidiTreeIterator<AbstractNode> iterator = ((AbstractNode) previousParseResult.getRootNode()).basicIterator();
		while(iterator.hasPrevious()) {
			AbstractNode previous = iterator.previous();
			if (previous.getGrammarElement() == null) {
				return true;
			}
			if (previous instanceof ILeafNode && previous.getOffset() <= offset) {
				break;
			}
		}
	}
	return false;
}
 
Example 5
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public PartialParsingPointers calculatePartialParsingPointers(IParseResult previousParseResult, final int offset,
		int replacedTextLength) {
	int myOffset = offset;
	int myReplacedTextLength = replacedTextLength;
	ICompositeNode oldRootNode = previousParseResult.getRootNode();
	if (myOffset == oldRootNode.getTotalLength() && myOffset != 0) {
		// newText is appended, so look for the last original character instead
		--myOffset;
		myReplacedTextLength = 1;
	}
	// include any existing parse errors
	Range range = new Range(myOffset, myReplacedTextLength + myOffset);
	if (previousParseResult.hasSyntaxErrors())
		range.mergeAllSyntaxErrors(oldRootNode);

	myOffset = range.getOffset();
	List<ICompositeNode> nodesEnclosingRegion = collectNodesEnclosingChangeRegion(oldRootNode, range);
	List<ICompositeNode> validReplaceRootNodes = internalFindValidReplaceRootNodeForChangeRegion(nodesEnclosingRegion, range);

	filterInvalidRootNodes(oldRootNode, validReplaceRootNodes);

	if (validReplaceRootNodes.isEmpty()) {
		validReplaceRootNodes = Collections.singletonList(oldRootNode);
	}
	return new PartialParsingPointers(oldRootNode, myOffset, myReplacedTextLength, validReplaceRootNodes, nodesEnclosingRegion);
}
 
Example 6
Source File: AbstractContextualAntlrParser.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected IParseResult doParse(final String ruleName, final CharStream in, final NodeModelBuilder nodeModelBuilder, final int initialLookAhead) {
  final IParseResult parseResult = super.doParse(ruleName, in, nodeModelBuilder, initialLookAhead);
  if (delegate == null || parseResult.hasSyntaxErrors()) {
    return parseResult;
  }
  // If delegation was potentially used, we need to check for syntax errors in replaced nodes
  boolean hasError = false;
  Iterator<AbstractNode> nodeIterator = ((CompositeNode) parseResult.getRootNode()).basicIterator();
  while (nodeIterator.hasNext()) {
    AbstractNode node = nodeIterator.next();
    if (node.getSyntaxErrorMessage() != null) {
      hasError = true;
      break;
    }
  }
  if (hasError) {
    return new ParseResult(parseResult.getRootASTElement(), parseResult.getRootNode(), true);
  }
  return parseResult;
}
 
Example 7
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
public PartialParsingPointers calculatePartialParsingPointers(final IParseResult previousParseResult, final int offset, final int replacedTextLength) {
  int myOffset = offset;
  int myReplacedTextLength = replacedTextLength;
  ICompositeNode oldRootNode = previousParseResult.getRootNode();
  if (myOffset == oldRootNode.getTotalLength() && myOffset != 0) {
    // newText is appended, so look for the last original character instead
    --myOffset;
    myReplacedTextLength = 1;
  }
  // include any existing parse errors
  Range range = new Range(myOffset, myReplacedTextLength + myOffset);
  if (previousParseResult.hasSyntaxErrors()) {
    range.mergeAllSyntaxErrors(oldRootNode);
  }

  myOffset = range.getOffset();
  List<ICompositeNode> nodesEnclosingRegion = collectNodesEnclosingChangeRegion(oldRootNode, range);
  List<ICompositeNode> validReplaceRootNodes = internalFindValidReplaceRootNodeForChangeRegion(nodesEnclosingRegion, range);

  filterInvalidRootNodes(oldRootNode, validReplaceRootNodes);

  if (validReplaceRootNodes.isEmpty()) {
    validReplaceRootNodes = Collections.singletonList(oldRootNode);
  }
  return new PartialParsingPointers(oldRootNode, myOffset, myReplacedTextLength, validReplaceRootNodes, nodesEnclosingRegion);
}
 
Example 8
Source File: AbstractSGenTest.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected EObject parseExpression(String expression, String ruleName) {
	XtextResource resource = resourceProvider.get();
	resource.setURI(URI.createPlatformPluginURI("path", true));
	ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule();
	parserRule.setName(ruleName);
	IParseResult result = parser.parse(parserRule, new StringReader(
			expression));
	EObject rootASTElement = result.getRootASTElement();
	resource.getContents().add(rootASTElement);
	ListBasedDiagnosticConsumer diagnosticsConsumer = new ListBasedDiagnosticConsumer();
	linker.linkModel(result.getRootASTElement(), diagnosticsConsumer);
	if (result.hasSyntaxErrors()) {
		StringBuilder errorMessages = new StringBuilder();
		Iterable<INode> syntaxErrors = result.getSyntaxErrors();
		for (INode iNode : syntaxErrors) {
			errorMessages.append(iNode.getSyntaxErrorMessage());
			errorMessages.append("\n");
		}
		throw new RuntimeException(
				"Could not parse expression, syntax errors: "
						+ errorMessages);
	}
	if (diagnosticsConsumer.hasConsumedDiagnostics(Severity.ERROR)) {
		throw new RuntimeException("Error during linking: "
				+ diagnosticsConsumer.getResult(Severity.ERROR));
	}
	return rootASTElement;
}
 
Example 9
Source File: STextExpressionParser.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public EObject parseExpression(String expression, String ruleName, String specification) {
	StextResource resource = getResource();
	resource.setURI(URI.createPlatformResourceURI(getUri(), true));
	ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule();
	parserRule.setName(ruleName);
	IParseResult result = parser.parse(parserRule, new StringReader(expression));
	EObject rootASTElement = result.getRootASTElement();
	resource.getContents().add(rootASTElement);
	ListBasedDiagnosticConsumer diagnosticsConsumer = new ListBasedDiagnosticConsumer();
	Statechart sc = SGraphFactory.eINSTANCE.createStatechart();
	sc.setDomainID(domainId);
	sc.setName("sc");
	if (specification != null) {
		sc.setSpecification(specification);
	}
	resource.getContents().add(sc);
	resource.getLinkingDiagnostics().clear();
	linker.linkModel(sc, diagnosticsConsumer);
	linker.linkModel(rootASTElement, diagnosticsConsumer);
	resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	Multimap<SpecificationElement, Diagnostic> diagnostics = resource.getLinkingDiagnostics();
	if (diagnostics.size() > 0) {
		throw new LinkingException(diagnostics.toString());
	}
	if (result.hasSyntaxErrors()) {
		StringBuilder errorMessages = new StringBuilder();
		Iterable<INode> syntaxErrors = result.getSyntaxErrors();
		for (INode iNode : syntaxErrors) {
			errorMessages.append(iNode.getSyntaxErrorMessage());
			errorMessages.append("\n");
		}
		throw new SyntaxException("Could not parse expression, syntax errors: " + errorMessages);
	}
	if (diagnosticsConsumer.hasConsumedDiagnostics(Severity.ERROR)) {
		throw new LinkingException("Error during linking: " + diagnosticsConsumer.getResult(Severity.ERROR));
	}
	return rootASTElement;
}