org.eclipse.xtext.parser.IParseResult Java Examples
The following examples show how to use
org.eclipse.xtext.parser.IParseResult.
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: RenameService2.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
protected EObject getElementWithIdentifierAt(XtextResource xtextResource, int offset) { if (offset >= 0) { if (xtextResource != null) { IParseResult parseResult = xtextResource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); if (rootNode != null) { ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset); if (leaf != null && isIdentifier(leaf)) { return eObjectAtOffsetHelper.resolveElementAt(xtextResource, offset); } } } } } return null; }
Example #2
Source File: TokenSequencePreservingPartialParsingHelper.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void replaceOldSemanticElement(EObject oldElement, IParseResult previousParseResult, IParseResult newParseResult) { EObject oldSemanticParentElement = oldElement.eContainer(); if (oldSemanticParentElement != null) { EStructuralFeature feature = oldElement.eContainingFeature(); if (feature.isMany()) { List featureValueList = (List) oldSemanticParentElement.eGet(feature); int index = featureValueList.indexOf(oldElement); unloadSemanticObject(oldElement); featureValueList.set(index, newParseResult.getRootASTElement()); } else { unloadSemanticObject(oldElement); oldSemanticParentElement.eSet(feature, newParseResult.getRootASTElement()); } ((ParseResult) newParseResult).setRootASTElement(previousParseResult.getRootASTElement()); } else { unloadSemanticObject(oldElement); } }
Example #3
Source File: AbstractContextualAntlrParser.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** {@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 #4
Source File: ParseHelper.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public T parse(InputStream in, URI uriToUse, Map<?, ?> options, ResourceSet resourceSet) { resourceHelper.setFileExtension(fileExtension); Resource resource = resourceHelper.resource(in, uriToUse, options, resourceSet); if (resource instanceof XtextResource) { IParseResult parseResult = ((XtextResource) resource).getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); if (rootNode != null) { checkNodeModel(rootNode); } } } T root = (T) (resource.getContents().isEmpty() ? null : resource.getContents().get(0)); return root; }
Example #5
Source File: FormatHyperlinkHelper.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** {@inheritDoc} */ @Override public void createHyperlinksByOffset(final XtextResource resource, final int offset, final IHyperlinkAcceptor acceptor) { final IParseResult parseResult = resource.getParseResult(); if (parseResult == null || parseResult.getRootNode() == null) { return; // Return, no need to call in super.createAdditionalHyperlinks } // Check if the current parse tree node represents an override keyword, in which case we want to link // to the overridden rule INode node = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset); if (node != null && isOverrideKeyword(node.getGrammarElement())) { Rule rule = (Rule) eObjectAtOffsetHelper.resolveElementAt(resource, offset); Region region = new Region(node.getOffset(), node.getLength()); List<Rule> extendedRules = getExtendedRules(rule); for (Rule extendedRule : extendedRules) { createHyperlinksTo(resource, region, extendedRule, acceptor); } } super.createHyperlinksByOffset(resource, offset, acceptor); }
Example #6
Source File: XtextReconcilerDebugger.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
public void assertResouceParsedCorrectly(XtextResource resource, final ReconcilerReplaceRegion region) { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); final String resourceContent = rootNode.getText(); IParseResult reparseResult = parser.parse(new StringReader(resourceContent)); if(!emfStructureComparator.isSameStructure(parseResult.getRootASTElement(), reparseResult.getRootASTElement())) { new DisplayRunnable() { @Override protected void run() throws Exception { LOG.error("PartialParsing produced wrong model"); LOG.error("Events: \n\t" + Joiner.on("\n\t").join(region.getDocumentEvents())); LOG.error("ReplaceRegion: \n\t'" + region + "'" ); MessageDialog.openError( Display.getCurrent().getActiveShell(), "XtextReconcilerDebugger", "PartialParsing produced wrong model." + "\n\nSee log for details."); } }; } } }
Example #7
Source File: Bug419429Test.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
protected void replaceAndReparse(String model, int offset, int length, String change, String expectedReparseRegion) throws Exception { IParseResult parseResult = getParseResultAndExpect(model, UNKNOWN_EXPECTATION); PartialParsingPointers parsingPointers = getPartialParser().calculatePartialParsingPointers(parseResult, offset, length); String reparseRegion = getPartialParser().insertChangeIntoReplaceRegion(parsingPointers .getDefaultReplaceRootNode(), new ReplaceRegion(offset, length, change)); assertEquals(expectedReparseRegion, reparseRegion); final Wrapper<Boolean> unloaded = Wrapper.wrap(Boolean.FALSE); getPartialParser().setUnloader(new IReferableElementsUnloader() { @Override public void unloadRoot(EObject root) { unloaded.set(Boolean.TRUE); } }); IParseResult partiallyReparse = reparse(parseResult, offset, length, change); assertTrue("unloaded", unloaded.get()); String expectedReparseModel = model.substring(0, offset) + change + model.substring(offset + length); assertEquals(expectedReparseModel, partiallyReparse.getRootNode().getText()); compareWithFullParse(model, offset, length, change); }
Example #8
Source File: N4JSRenameStrategy.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * 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 #9
Source File: NpmNameAndVersionValidatorHelper.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * 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 #10
Source File: PartialParsingHelper.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
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 #11
Source File: SemverHelper.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** @return {@link VersionNumber} of the given {@link IParseResult} */ public VersionNumber parseVersionNumber(IParseResult semverParseResult) { VersionRangeSetRequirement vrs = parseVersionRangeSet(semverParseResult); if (vrs == null || vrs.getRanges().isEmpty()) { return null; } VersionRange firstVersionRange = vrs.getRanges().get(0); if (!(firstVersionRange instanceof VersionRangeConstraint)) { return null; } VersionRangeConstraint vrc = (VersionRangeConstraint) firstVersionRange; if (vrc.getVersionConstraints().isEmpty()) { return null; } SimpleVersion firstSimpleVersion = vrc.getVersionConstraints().get(0); return firstSimpleVersion.getNumber(); }
Example #12
Source File: XbaseHighlightingCalculator.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
@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); }
Example #13
Source File: PartialParsingProcessor.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
@Override public String processFile(String completeData, String data, int offset, int len, String change) throws Exception { IParseResult initialParseResult = parser.parse(new StringReader(data)); String newData = applyDelta(data, offset, len, change); ReplaceRegion replaceRegion = new ReplaceRegion(offset, len, change); try { IParseResult reparsed = parser.reparse(initialParseResult, replaceRegion); IParseResult parsedFromScratch = parser.parse(new StringReader(newData)); assertEqual(data, newData, parsedFromScratch, reparsed); return newData; } catch(Throwable e) { ComparisonFailure throwMe = new ComparisonFailure(e.getMessage(), newData, replaceRegion + DELIM + data); throwMe.initCause(e); throw throwMe; } }
Example #14
Source File: XtextStyledTextSelectionProvider.java From statecharts with Eclipse Public License 1.0 | 6 votes |
public ISelection getSelection() { if (styledText.isDisposed()) return StructuredSelection.EMPTY; int offset = Math.max(styledText.getCaretOffset() - 1, 0); XtextResource fakeResource = xtextResource; IParseResult parseResult = fakeResource.getParseResult(); if (parseResult == null) return StructuredSelection.EMPTY; ICompositeNode rootNode = parseResult.getRootNode(); ILeafNode selectedNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset); final EObject selectedObject = NodeModelUtils.findActualSemanticObjectFor(selectedNode); if (selectedObject == null) { return StructuredSelection.EMPTY; } return new StructuredSelection(selectedObject); }
Example #15
Source File: ContentFormatter.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
protected TextEdit exec(IXtextDocument document, IRegion region, XtextResource resource) throws Exception { try { IParseResult parseResult = resource.getParseResult(); if (parseResult != null && parseResult.getRootASTElement() != null) { FormatterRequest request = requestProvider.get(); initRequest(document, region, resource, request); IFormatter2 formatter = formatterProvider.get(); List<ITextReplacement> replacements = formatter.format(request); final TextEdit mte = createTextEdit(replacements); return mte; } } catch (Exception e) { LOG.error("Error formatting " + resource.getURI() + ": " + e.getMessage(), e); } return new MultiTextEdit(); }
Example #16
Source File: N4LanguageUtils.java From n4js with Eclipse Public License 1.0 | 6 votes |
/** * 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 #17
Source File: AbstractPackratParser.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Override public final IParseResult parse(CharSequence input, INonTerminalConsumer consumer) { this.input = input; this.offset = 0; Arrays.fill(markerBuffer, null); this.markerBufferSize = 0; return parse(consumer); }
Example #18
Source File: AbstractContextualAntlrParser.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
/** {@inheritDoc} */ @Override public IParseResult doParse(final Reader reader) { IParseResult parseResult = super.doParse(reader); if (parseResult.getRootASTElement() == null) { // Most of ASMD languages are not good with empty models, so create an empty root element AbstractRule rule = GrammarUtil.findRuleForName(grammarAccess.getGrammar(), getDefaultRuleName()); EObject newRoot = getElementFactory().create(rule.getType().getClassifier()); return new ParseResult(newRoot, parseResult.getRootNode(), true); } return parseResult; }
Example #19
Source File: DefaultFoldingRegionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void computeObjectFolding(XtextResource xtextResource, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor) { IParseResult parseResult = xtextResource.getParseResult(); if(parseResult != null){ EObject rootASTElement = parseResult.getRootASTElement(); if(rootASTElement != null){ if (cancelIndicator.isCanceled()) throw new OperationCanceledException(); if (isHandled(rootASTElement)) { computeObjectFolding(rootASTElement, foldingRegionAcceptor); } if (shouldProcessContent(rootASTElement)) { TreeIterator<EObject> allContents = rootASTElement.eAllContents(); while (allContents.hasNext()) { if (cancelIndicator.isCanceled()) throw new OperationCanceledException(); EObject eObject = allContents.next(); if (isHandled(eObject)) { computeObjectFolding(eObject, foldingRegionAcceptor); } if (!shouldProcessContent(eObject)) { allContents.prune(); } } } } } }
Example #20
Source File: DotHoverUtils.java From gef with Eclipse Public License 2.0 | 5 votes |
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 #21
Source File: CustomXtendParser.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
@Override public IParseResult parse(RuleCall ruleCall, Reader reader, int initialLookAhead) { NodeModelBuilder builder = createNodeModelBuilder(); builder.setForcedFirstGrammarElement(ruleCall); IParseResult parseResult = doParse(ruleCall.getRule().getName(), new ReaderCharStream(reader), builder, initialLookAhead); return parseResult; }
Example #22
Source File: ExpressionUtil.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * @return the smallest single expression containing the selection. */ public XExpression findSelectedExpression(XtextResource resource, ITextSelection selection) { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); INode node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset()); if (node == null) { return null; } if (isHidden(node)) { if (selection.getLength() > node.getLength()) { node = NodeModelUtils.findLeafNodeAtOffset(rootNode, node.getEndOffset()); } else { node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset() - 1); } } else if (node.getOffset() == selection.getOffset() && !isBeginOfExpression(node)) { node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset() - 1); } if(node != null) { EObject currentSemanticElement = NodeModelUtils.findActualSemanticObjectFor(node); while (!(contains(currentSemanticElement, node, selection) && currentSemanticElement instanceof XExpression)) { node = nextNodeForFindSelectedExpression(currentSemanticElement, node, selection); if(node == null) return null; currentSemanticElement = NodeModelUtils.findActualSemanticObjectFor(node); } return (XExpression) currentSemanticElement; } } return null; }
Example #23
Source File: AbstractContextualAntlrParser.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
/** * {@inheritDoc}. * For parser delegation it is critically important that the root node of the parsed sub-tree is not merged. Otherwise we do not have a proper new composite * node for replacement. */ public IParseResult parseDelegate(final ParserRule rule, final Reader reader) { try { NodeModelBuilder builder = createNodeModelBuilder(); builder.setForcedFirstGrammarElement(null); return doParse(rule.getName(), new ANTLRReaderStream(reader), builder, 0); } catch (IOException e) { throw new WrappedException(e); } }
Example #24
Source File: XtextResource.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Override protected void doLoad(InputStream inputStream, Map<?, ?> options) throws IOException { setEncodingFromOptions(options); IParseResult result; if (entryPoint == null) { result = getParser().parse(createReader(inputStream)); } else { result = getParser().parse(entryPoint, createReader(inputStream)); } updateInternalState(this.parseResult, result); }
Example #25
Source File: TestDataProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Override public IParseResult parse(RuleCall ruleCall, Reader reader, int initialLookAhead) throws TestDataCarrier { try { throw new TestDataCarrier(CharStreams.toString(reader)); } catch (IOException e) { Assert.fail(e.getMessage()); return null; } }
Example #26
Source File: DefaultSemanticHighlightingCalculator.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
protected void searchAndHighlightElements(XtextResource resource, IHighlightedPositionAcceptor acceptor, CancelIndicator cancelIndicator) { IParseResult parseResult = resource.getParseResult(); if (parseResult == null) throw new IllegalStateException("resource#parseResult may not be null"); EObject element = parseResult.getRootASTElement(); highlightElementRecursively(element, acceptor, cancelIndicator); }
Example #27
Source File: AstSelectionProvider.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected EObject getEObjectAtOffset(XtextResource resource, ITextRegion currentEditorSelection) { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); INode nodeAtOffset = findLeafNodeAtOffset(rootNode, currentEditorSelection.getOffset()); return findSemanticObjectFor(nodeAtOffset); } return null; }
Example #28
Source File: SerializableNodeModel.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
public SerializableNodeModel(XtextResource resource) { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); root = (RootNode) rootNode; } formatVersion = 1; date = new Date(); }
Example #29
Source File: XtextWebDocument.java From xtext-web with Eclipse Public License 2.0 | 5 votes |
protected String refreshText() { String newText = ""; IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); if (rootNode != null) { String text = rootNode.getText(); if (text != null) { newText = text; } } } return text = newText; }
Example #30
Source File: AbstractSCTResource.java From statecharts with Eclipse Public License 1.0 | 5 votes |
protected IParseResult parse(SpecificationElement element, String rule) { ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule(); parserRule.setName(rule); String specification = element.getSpecification(); IParseResult result = parser.parse(parserRule, new StringReader(specification != null ? specification : "")); createDiagnostics(result, element); return result; }