Java Code Examples for org.eclipse.xtext.parser.IParser#parse()

The following examples show how to use org.eclipse.xtext.parser.IParser#parse() . 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: N4LanguageUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses the given string with the parser of the Xtext language denoted by the given file extension. In case of
 * syntax errors, the returned parse result will have a non-empty list of {@link ParseResult#errors}.
 */
public static <T extends EObject> ParseResult<T> parseXtextLanguage(String fileExtOfLanguage,
		ParserRule parserRuleOrNull, Class<T> expectedTypeOfRoot, Reader sourceReader) {
	final IParser parser = getServiceForContext(fileExtOfLanguage, IParser.class)
			.orElseThrow(() -> new RuntimeException(
					"Cannot obtain Xtext parser for language with file extension: " + fileExtOfLanguage));
	final IParseResult result;
	if (parserRuleOrNull != null) {
		result = parser.parse(parserRuleOrNull, sourceReader);
	} else {
		result = parser.parse(sourceReader);
	}
	final Iterable<SyntaxErrorMessage> errors = Iterables.transform(result.getSyntaxErrors(),
			node -> node.getSyntaxErrorMessage());
	final EObject root = result.getRootASTElement();
	if (root != null && expectedTypeOfRoot.isInstance(root)) {
		final T rootCasted = expectedTypeOfRoot.cast(root);
		return new ParseResult<>(rootCasted, errors);
	}
	return new ParseResult<>(null, errors);
}
 
Example 2
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 3
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected IParseResult doParseRegion(IParser parser, PartialParsingPointers parsingPointers,
		ICompositeNode replaceMe, String reparseRegion) {
	EObject entryRuleOrRuleCall = parsingPointers.findEntryRuleOrRuleCall(replaceMe);
	IParseResult newParseResult = null;
	try {
		if (entryRuleOrRuleCall instanceof RuleCall)
			newParseResult = parser.parse((RuleCall)entryRuleOrRuleCall, new StringReader(reparseRegion), replaceMe.getLookAhead());
		else
			newParseResult = parser.parse((ParserRule)entryRuleOrRuleCall, new StringReader(reparseRegion));
	} catch (ParseException exc) {
	}
	return newParseResult;
}
 
Example 4
Source File: DotHoverUtils.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
static private Color parse(String attributeValue) {
	Injector dotColorInjector = DotActivator.getInstance().getInjector(
			DotActivator.ORG_ECLIPSE_GEF_DOT_INTERNAL_LANGUAGE_DOTCOLOR);
	IParser parser = dotColorInjector.getInstance(IParser.class);

	IParseResult result = parser.parse(new StringReader(attributeValue));

	return (Color) result.getRootASTElement();
}
 
Example 5
Source File: DotValidator.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
private void doRecordLabelValidation(Attribute attribute) {
	Injector recordLabelInjector = new DotRecordLabelStandaloneSetup()
			.createInjectorAndDoEMFRegistration();
	DotRecordLabelValidator validator = recordLabelInjector
			.getInstance(DotRecordLabelValidator.class);
	IParser parser = recordLabelInjector.getInstance(IParser.class);

	DotSubgrammarValidationMessageAcceptor messageAcceptor = new DotSubgrammarValidationMessageAcceptor(
			attribute, DotPackage.Literals.ATTRIBUTE__VALUE,
			"record-based label", getMessageAcceptor(), "\"".length());

	validator.setMessageAcceptor(messageAcceptor);

	IParseResult result = parser
			.parse(new StringReader(attribute.getValue().toValue()));

	for (INode error : result.getSyntaxErrors())
		messageAcceptor.acceptSyntaxError(error);

	Map<Object, Object> validationContext = new HashMap<Object, Object>();
	validationContext.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME,
			ReflectionUtils.getPrivateFieldValue(validator,
					"languageName"));

	// validate both the children (loop) and root element
	Iterator<EObject> iterator = result.getRootASTElement().eAllContents();
	while (iterator.hasNext())
		validator.validate(iterator.next(), null/* diagnostic chain */,
				validationContext);

	validator.validate(result.getRootASTElement(), null, validationContext);
}
 
Example 6
Source File: DotNodeModelStreamer.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
private void writeHTMLStringSemantic(AbstractRule rule,
		DotFormattingConfigBasedStream out, ICompositeNode node)
		throws IOException {
	Injector htmlLabelInjector = new DotHtmlLabelStandaloneSetup()
			.createInjectorAndDoEMFRegistration();
	IFormatter dotHtmlLabelFormatter = htmlLabelInjector
			.getInstance(IFormatter.class);
	ITokenStream htmlLabelOut = new TokenStringBuffer();
	// TODO: calculate initial indentation properly
	ITokenStream fmt = dotHtmlLabelFormatter.createFormatterStream("\t\t",
			htmlLabelOut, false);
	INodeModelStreamer dothtmlLabelNodeModelStreamer = htmlLabelInjector
			.getInstance(INodeModelStreamer.class);

	IParser dotHtmlLabelParser = htmlLabelInjector
			.getInstance(IParser.class);
	// cut off the leading and the trailing white spaces
	String trimmedNodeText = node.getText().trim();
	String htmlLabelText = trimmedNodeText.substring(1,
			trimmedNodeText.length() - 1);
	IParseResult parseResult = dotHtmlLabelParser
			.parse(new StringReader(htmlLabelText));
	ICompositeNode htmlLabelRootNode = parseResult.getRootNode();

	dothtmlLabelNodeModelStreamer.feedTokenStream(fmt, htmlLabelRootNode, 0,
			htmlLabelText.length());
	out.writeSemantic(null, "<");
	out.addNewLine();
	out.addLineEntry(node.getGrammarElement(), htmlLabelOut.toString(),
			false);
	out.addNewLine();
	out.writeSemantic(null, ">");
}
 
Example 7
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected IParseResult fullyReparse(IParser parser, IParseResult previousParseResult, ReplaceRegion replaceRegion) {
	unloadSemanticObject(previousParseResult.getRootASTElement());
	ICompositeNode node = previousParseResult.getRootNode();
	ParserRule parserRule = NodeModelUtils.getEntryParserRule(node);
	String reparseRegion = insertChangeIntoReplaceRegion(previousParseResult.getRootNode(), replaceRegion);
	return parser.parse(parserRule, new StringReader(reparseRegion));
}
 
Example 8
Source File: ParseErrorHandlingTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testExpectNoSuchMethodException() throws Exception {
	IParser parser = get(IParser.class);
	ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule();
	parserRule.setName("ruleDoesNotExist");
	try {
		parser.parse(parserRule, new StringReader("empty"));
		fail("Expected WrappedException");
	} catch(ParseException e) {
		assertTrue(e.getCause() instanceof WrappedException);
		WrappedException cause = (WrappedException) e.getCause();
		assertTrue(cause.getCause() instanceof NoSuchMethodException);
	}
}
 
Example 9
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected IParseResult fullyReparse(IParser parser, IParseResult previousParseResult, ReplaceRegion replaceRegion) {
	unloadSemanticObject(previousParseResult.getRootASTElement());
	String reparseRegion = insertChangeIntoReplaceRegion(previousParseResult.getRootNode(), replaceRegion);
	return parser.parse(new StringReader(reparseRegion));
}
 
Example 10
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
protected IParseResult fullyReparse(final IParser parser, final IParseResult previousParseResult, final ReplaceRegion replaceRegion) {
  unloadSemanticObject(previousParseResult.getRootASTElement());
  String reparseRegion = insertChangeIntoReplaceRegion(previousParseResult.getRootNode(), replaceRegion);
  return parser.parse(new StringReader(reparseRegion));
}