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

The following examples show how to use org.eclipse.xtext.parser.IParseResult#getRootNode() . 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: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected ITextRegion getTextRegion(EObject eObject) {
	if (eObject == null)
		return null;
	IParseResult parseResult = ((XtextResource)eObject.eResource()).getParseResult();
	if (parseResult == null)
		return null;
	ICompositeNode rootNode = parseResult.getRootNode();
	Map<ILeafNode, EObject> comments = commentAssociater.associateCommentsWithSemanticEObjects(eObject, singleton(rootNode));
	final ITextRegion result = locationProvider.getFullTextRegion(eObject);
	int start = result.getOffset();
	int end = result.getOffset() + result.getLength();
	for (Entry<ILeafNode, EObject> entry : comments.entrySet()) {
		if (entry.getValue() == eObject) {
			ILeafNode node = entry.getKey();
			if (node.getTotalOffset() < start) {
				start = node.getTotalOffset();
			}
			if (node.getTotalEndOffset() > end) {
				end = node.getTotalEndOffset();
			}
		}
	}
	return new TextRegion(start, end-start);
}
 
Example 2
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 3
Source File: RenameService2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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 4
Source File: EntryPointFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public ICompositeNode findEntryPoint(IParseResult parseResult, int offset) {
	ICompositeNode rootNode = parseResult.getRootNode();
	if (rootNode.getTotalLength() == offset) {
		return null;
	}
	ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
	ICompositeNode parent = leafNode.getParent();
	ICompositeNode result = findEntryPoint(parent, offset);
	if (result != null) {
		EObject grammarElement = result.getGrammarElement();
		if (grammarElement instanceof AbstractElement) {
			return result;
		}
	}
	return null;
}
 
Example 5
Source File: XtextStyledTextSelectionProvider.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
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 6
Source File: ParseHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 7
Source File: XtextReconcilerDebugger.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void assertModelInSyncWithDocument(IDocument document, XtextResource resource, final ReconcilerReplaceRegion region) {
	if (document instanceof IDocumentExtension4 && resource != null) {
		long beforeGet = ((IDocumentExtension4) document).getModificationStamp();
		final String documentContent = document.get();
		long afterGet = ((IDocumentExtension4) document).getModificationStamp();
		if (beforeGet == afterGet && beforeGet == resource.getModificationStamp()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ICompositeNode rootNode = parseResult.getRootNode();
				final String resourceContent = rootNode.getText();
				if (!resourceContent.equals(documentContent)) {
					new DisplayRunnable() {
						@Override
						protected void run() throws Exception {
							LOG.error("XtextDocument and XtextResource have run out of sync:\n" 
											+ DiffUtil.diff(documentContent, resourceContent));
							LOG.error("Events: \n\t" + Joiner.on("\n\t").join(region.getDocumentEvents()));
							LOG.error("ReplaceRegion: \n\t'" + region + "'" );
							MessageDialog.openError(
									Display.getCurrent().getActiveShell(),
									"XtextReconcilerDebugger",
									"XtextDocument and XtextResource have run out of sync."
											+ "\n\nSee log for details.");
						}
						
					}.syncExec();
				} else {
					if (LOG.isDebugEnabled())
						LOG.debug("Model and document are in sync");
				}
			}
		}
	}
}
 
Example 8
Source File: AbstractXtextTests.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void checkNodeModel(XtextResource resource) {
	IParseResult parseResult = resource.getParseResult();
	if(parseResult != null) {
		ICompositeNode rootNode = parseResult.getRootNode();
		getInvariantChecker().checkInvariant(rootNode);
		new LookAheadInfo(rootNode).checkConsistency();
	}
}
 
Example 9
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ITextRegion selectEnclosing(XtextResource resource, ITextRegion currentEditorSelection) {
	Pair<EObject, EObject> currentlySelected = getSelectedAstElements(resource, currentEditorSelection);
	if (currentlySelected == null) {
		IParseResult parseResult = resource.getParseResult();
		if (parseResult != null) {
			ICompositeNode rootNode = parseResult.getRootNode();
			int offset = getSelectionOffset(rootNode, currentEditorSelection);
			INode node = findLeafNodeAtOffset(rootNode, offset);
			if (node != null) {
				ITextRegion fineGrainedRegion = computeInitialFineGrainedSelection(node, currentEditorSelection);
				if (fineGrainedRegion != null) {
					selectionHistory.clear();
					register(currentEditorSelection);
					return register(fineGrainedRegion);
				}
				EObject eObject = findSemanticObjectFor(node);
				return register(getTextRegion(eObject));
			}
		}
	} else {
		EObject first = currentlySelected.getFirst();
		if (first.eContainer() != null) {
			return register(getTextRegion(first.eContainer()));
		}
	}
	return ITextRegion.EMPTY_REGION;
}
 
Example 10
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
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 11
Source File: N4JSASTUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes an MD5 hash from the given resource's source code (the actual source text), as stored in
 * {@link TModule#getAstMD5()}. Will fail with an exception if the given resource does not have a valid
 * {@link XtextResource#getParseResult() parse result}, as created by Xtext during parsing.
 */
public static String md5Hex(XtextResource resource) {
	final IParseResult parseResult = resource.getParseResult();
	final INode rootNode = parseResult != null ? parseResult.getRootNode() : null;
	final String source = rootNode != null ? rootNode.getText() : null;
	if (source == null) {
		throw new IllegalStateException("resource does not have a valid parse result: " + resource.getURI());
	}
	return Hashing.murmur3_128(SEED).hashString(source, Charsets.UTF_8).toString();
}
 
Example 12
Source File: XtextWebDocument.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
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 13
Source File: ExpressionUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @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 14
Source File: XbaseHighlightingCalculator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void doProvideHighlightingFor(XtextResource resource, IHighlightedPositionAcceptor acceptor,
		CancelIndicator cancelIndicator) {
	IParseResult parseResult = resource.getParseResult();
	if (parseResult == null)
		throw new IllegalStateException("resource#parseResult may not be null");
	ICompositeNode node = parseResult.getRootNode();
	highlightSpecialIdentifiers(acceptor, node);
	super.doProvideHighlightingFor(resource, acceptor, cancelIndicator);
}
 
Example 15
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 16
Source File: DefaultTaskFinder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<Task> findTasks(Resource resource) {
	TaskTags taskTags = taskTagProvider.getTaskTags(resource);
	if (isEmpty(taskTags) || !(resource instanceof XtextResource)) {
		return emptyList();
	}
	IParseResult parseResult = ((XtextResource) resource).getParseResult();
	if (parseResult == null || parseResult.getRootNode() == null) {
		return emptyList();
	}
	List<Task> tasks = findTasks(parseResult.getRootNode(), taskTags);
	return unmodifiableList(tasks);
}
 
Example 17
Source File: XbaseStratumBreakpointSupport.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean isValidLineForBreakPoint(XtextResource resource, int line) {
	IParseResult parseResult = resource.getParseResult();
	if (parseResult == null)
		return false;
	ICompositeNode node = parseResult.getRootNode();
	return isValidLineForBreakpoint(node, line);
}
 
Example 18
Source File: CustomN4JSParser.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<FollowElement> getFollowElements(IParseResult parseResult, int offset, boolean strict) {
	try (Measurement m = dataCollectors.dcParseContexts().getMeasurement()) {
		Set<FollowElement> result = Sets.newLinkedHashSet();
		ICompositeNode entryPoint = entryPointFinder.findEntryPoint(parseResult, offset);
		String ruleName;
		if (entryPoint == null) {
			entryPoint = parseResult.getRootNode();
			ruleName = getRuleNames().getAntlrRuleName(getEntryRule());
		} else {
			ruleName = getRuleName(entryPoint);
		}
		// Yeah Xpect fallback, Lord this is annoying.
		if (ruleName == null) {
			entryPoint = parseResult.getRootNode();
			ruleName = "ruleScript";
		}
		TokenSource tokenSource = tokenSourceFactory.toTokenSource(entryPoint, entryPoint.getOffset(), offset,
				true);
		CustomInternalN4JSParser parser = collectFollowElements(tokenSource, getEntryGrammarElement(entryPoint),
				ruleName, strict, result);
		adjustASIAndCollectFollowElements(parser, ruleName, strict, result);

		/*
		 * Lists are easier to debug
		 */
		return Lists.newArrayList(result);
	}
}
 
Example 19
Source File: RenameService2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected Either<Range, PrepareRenameResult> doPrepareRename(Resource resource, Document document,
		PrepareRenameParams params, CancelIndicator cancelIndicator) {
	String uri = params.getTextDocument().getUri();
	if (resource instanceof XtextResource) {
		ICompositeNode rootNode = null;
		XtextResource xtextResource = (XtextResource) resource;
		if (xtextResource != null) {
			IParseResult parseResult = xtextResource.getParseResult();
			if (parseResult != null) {
				rootNode = parseResult.getRootNode();
			}
		}
		if (rootNode == null) {
			RenameService2.LOG.trace("Could not retrieve root node for resource. URI: " + uri);
			return null;
		}
		Position caretPosition = params.getPosition();
		try {
			int caretOffset = document.getOffSet(caretPosition);
			EObject element = null;
			int candidateOffset = caretOffset;
			do {
				element = getElementWithIdentifierAt(xtextResource, candidateOffset);
				if (element != null && !element.eIsProxy()) {
					ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, candidateOffset);
					if (leaf != null && isIdentifier(leaf)) {
						String convertedNameValue = getConvertedValue(leaf.getGrammarElement(), leaf);
						String elementName = getElementName(element);
						if (!Strings.isEmpty(convertedNameValue) && !Strings.isEmpty(elementName)
								&& Objects.equal(convertedNameValue, elementName)) {
							Position start = document.getPosition(leaf.getOffset());
							Position end = document.getPosition(leaf.getEndOffset());
							return Either.forLeft(new Range(start, end));
						}
					}
				}
				candidateOffset = (candidateOffset - 1);
			} while (((candidateOffset >= 0) && ((candidateOffset + 1) >= caretOffset)));
		} catch (IndexOutOfBoundsException e) {
			RenameService2.LOG.trace("Invalid document " + toPositionFragment(caretPosition, uri));
			return null;
		}
		RenameService2.LOG.trace("No element found at " + toPositionFragment(caretPosition, uri));
	} else {
		RenameService2.LOG.trace("Loaded resource is not an XtextResource. URI: " + resource.getURI());
	}
	return null;
}
 
Example 20
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IParseResult reparse(IParser parser, IParseResult previousParseResult, ReplaceRegion changedRegion) {
	if (isBrokenPreviousState(previousParseResult, changedRegion.getOffset())) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	ICompositeNode oldRootNode = previousParseResult.getRootNode();
	Iterator<ILeafNode> leafNodes = oldRootNode.getLeafNodes().iterator();
	ILeafNode leftNode = getLeftNode(leafNodes, changedRegion.getOffset());
	if (leftNode == null) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	ILeafNode rightNode = getRightNode(leafNodes, changedRegion.getEndOffset());
	if (rightNode == null) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	while(leafNodes.hasNext()) {
		if (leafNodes.next().getSyntaxErrorMessage() != null) {
			return fullyReparse(parser, previousParseResult, changedRegion);
		}
	}
	String originalText = oldRootNode.getText().substring(leftNode.getTotalOffset());
	StringBuilder newTextBuilder = new StringBuilder(originalText);
	changedRegion.shiftBy(-leftNode.getTotalOffset()).applyTo(newTextBuilder);
	String newText = newTextBuilder.toString();
	if (originalText.equals(newText)) {
		// nothing to do
		return previousParseResult;
	}
	int originalLength = rightNode.getTotalEndOffset() - leftNode.getTotalOffset();
	int expectedLength = originalLength - changedRegion.getLength() + changedRegion.getText().length();
	if (!isSameTokenSequence(originalText.substring(0, originalLength), newText, expectedLength)) {
		// different token sequence, cannot perform a partial parse run
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	
	PartialParsingPointers parsingPointers = calculatePartialParsingPointers(oldRootNode, leftNode, rightNode);
	ICompositeNode replaceMe = getReplacedNode(parsingPointers);
	if (replaceMe == null || replaceMe == oldRootNode || replaceMe.getOffset() == 0 && replaceMe.getEndOffset() == oldRootNode.getLength()) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	String reparseRegion = insertChangeIntoReplaceRegion(replaceMe, changedRegion);
	
	EObject oldSemanticElement = getOldSemanticElement(replaceMe, parsingPointers);
	if (oldSemanticElement == null)
		return fullyReparse(parser, previousParseResult, changedRegion);
	if (oldSemanticElement == replaceMe.getParent().getSemanticElement()) {
		throw new IllegalStateException("oldParent == oldElement");
	}
	
	IParseResult newParseResult = doParseRegion(parser, parsingPointers, replaceMe, reparseRegion);
	if (newParseResult == null) {
		throw new IllegalStateException("Could not perform a partial parse operation");
	}
	
	replaceOldSemanticElement(oldSemanticElement, previousParseResult, newParseResult);
	nodeModelBuilder.replaceAndTransferLookAhead(replaceMe, newParseResult.getRootNode());
	((ParseResult) newParseResult).setRootNode(oldRootNode);
	StringBuilder builder = new StringBuilder(oldRootNode.getText());
	changedRegion.applyTo(builder);
	nodeModelBuilder.setCompleteContent(oldRootNode, builder.toString());
	return newParseResult;
}