Java Code Examples for org.eclipse.xtext.nodemodel.util.NodeModelUtils#findLeafNodeAtOffset()

The following examples show how to use org.eclipse.xtext.nodemodel.util.NodeModelUtils#findLeafNodeAtOffset() . 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: PartialParserTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testErrorMarkers() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	// model contains an error due to missing ) at idx 23
	String model = "spielplatz 1 {kind (k 1}"; 
	XtextResource resource = getResourceFromStringAndExpect(model, 1);
	assertEquals(1, resource.getErrors().size());
	assertEquals(1, Iterables.size(resource.getParseResult().getSyntaxErrors()));
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, model.length() - 1);
	assertTrue(leaf.getSyntaxErrorMessage() != null);
	// resource.update(23, 0, ")");
	// assertTrue(resource.getParseResult().getParseErrors().isEmpty());
	IParseResult reparse = reparse(resource.getParseResult(), 23, 0, ")");
	rootNode = reparse.getRootNode();
	String expectedFixedModel = "spielplatz 1 {kind (k 1)}";
	String fixedModel = rootNode.getText();
	assertEquals("serialized model as expected", expectedFixedModel, fixedModel);
	resource = getResourceFromString(fixedModel);
	assertEquals("full reparse is fine", 0, resource.getErrors().size());
	assertFalse("partial reparse is fine", reparse.hasSyntaxErrors());
}
 
Example 2
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * CollectAll resolutions under the cursor at offset.
 *
 */
List<IssueResolution> collectAllResolutions(XtextResource resource, RegionWithCursor offset,
		Multimap<Integer, Issue> offset2issue) {

	EObject script = resource.getContents().get(0);
	ICompositeNode scriptNode = NodeModelUtils.getNode(script);
	ILeafNode offsetNode = NodeModelUtils.findLeafNodeAtOffset(scriptNode, offset.getGlobalCursorOffset());
	int offStartLine = offsetNode.getTotalStartLine();
	List<Issue> allIssues = QuickFixTestHelper.extractAllIssuesInLine(offStartLine, offset2issue);

	List<IssueResolution> resolutions = Lists.newArrayList();

	for (Issue issue : allIssues) {
		if (issue.getLineNumber() == offsetNode.getStartLine()
				&& issue.getLineNumber() <= offsetNode.getEndLine()) {

			IssueResolutionProvider quickfixProvider = resource.getResourceServiceProvider()
					.get(IssueResolutionProvider.class);
			Display.getDefault().syncExec(() -> resolutions.addAll(quickfixProvider.getResolutions(issue)));
		}
	}
	return resolutions;
}
 
Example 3
Source File: NodeModelStateTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	model = "// comment before root\n" +
			"\n" +
			"  spielplatz 0 \"Rummel\" {\n" +
			"    // comment belongs to next composite\n" +
			"    kind // inner comment\n" +
			"      ( Bob 1) // trailing comment\n" +
			"    // comment in next line\n" +
			"  }\n" +
			"// comment after root\n";
	rootNode = getRootNode(model);
	kindLeaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, model.indexOf("kind") + 1);
	hiddenLeaf = kindLeaf.getNextSibling();
	kindNode = kindLeaf.getParent();
}
 
Example 4
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 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: EObjectAtOffsetHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected EObject internalResolveElementAt(XtextResource resource, int offset, boolean containment) {
	if(!containment) {
		EObject crossRef = resolveCrossReferencedElementAt(resource, offset);
		if (crossRef != null)
			return crossRef;
	}
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
		if (leaf != null && leaf.isHidden() && leaf.getOffset() == offset) {
			leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
		}
		if (leaf != null) {
			return NodeModelUtils.findActualSemanticObjectFor(leaf);
		}
	}
	return null;
}
 
Example 7
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private HtmlTag findOpenTag(XtextResource resource,
		DocumentCommand command) {
	if (!resource.getContents().isEmpty()) {
		EObject dotAst = resource.getContents().get(0);
		INode rootNode = NodeModelUtils.getNode(dotAst);
		int cursorPosition = command.offset;
		ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode,
				cursorPosition);

		String leafNodeText = leafNode.getText();

		String htmlLabelText = extractHtmlLabelContent(leafNodeText);

		if (htmlLabelText == null) {
			return null;
		}

		int htmlLabelStartOffset = leafNode.getOffset() + 1
				+ leafNodeText.substring(1).indexOf('<');
		int htmlLabelCursorPosition = cursorPosition - htmlLabelStartOffset;

		return findOpenTag(htmlLabelText, htmlLabelCursorPosition);

	}
	return null;
}
 
Example 8
Source File: XtextDiagnosticConverter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected IssueLocation getLocationData(EObject obj, EStructuralFeature structuralFeature, int index) {
	if (NodeModelUtils.getNode(obj) == null) {
		ITextRegion location = locationInFileProvider.getSignificantTextRegion(obj);
		if (location != null) {
			ICompositeNode rootNode = NodeModelUtils.getNode(EcoreUtil.getRootContainer(obj));
			if (rootNode != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, location.getOffset());
				return getLocationForNode(leafNode);
			}
		} else {
			return super.getLocationData(obj.eContainer(), null, index);
		}
	}
	return super.getLocationData(obj, structuralFeature, index);
}
 
Example 9
Source File: N4JSOffsetAdapter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
@Creates
public IEObjectCoveringRegion IEObjectCoveringRegion() {
	final boolean haveRegion = region != null;

	int offset = haveRegion ? region.getOffset() : this.matchedOffset;
	int length = haveRegion ? region.getLength() : 0;
	int endOffset = offset + length;
	EObject semanticObject = null;

	INode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), offset);
	while (node != null) {
		EObject actualObject = NodeModelUtils.findActualSemanticObjectFor(node);
		if (actualObject != null) {
			if (haveRegion) {
				int nodeEndOffset = node.getEndOffset();
				if (nodeEndOffset <= endOffset || semanticObject == null) {
					semanticObject = actualObject;
				}
				if (nodeEndOffset >= endOffset) {
					break;
				}
			} else { // no region given, just a matched offset
				if (semanticObject == null) {
					semanticObject = actualObject;
					break;
				}
			}
		}
		node = node.getParent();
	}
	return new EObjectCoveringRegion(semanticObject, offset);
}
 
Example 10
Source File: HoverService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected HoverContext createContext(Document document, XtextResource resource, int offset) {
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (crossLinkedEObject.eIsProxy()) {
			return null;
		}
		IParseResult parseResult = resource.getParseResult();
		if (parseResult == null) {
			return null;
		}
		ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
		if (leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
			leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
		}
		if (leafNode == null) {
			return null;
		}
		ITextRegion leafRegion = leafNode.getTextRegion();
		return new HoverContext(document, resource, offset, leafRegion, crossLinkedEObject);
	}
	EObject element = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
	if (element == null) {
		return null;
	}
	ITextRegion region = locationInFileProvider.getSignificantTextRegion(element);
	return new HoverContext(document, resource, offset, region, element);
}
 
Example 11
Source File: CrossRefTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testGetLinkedObjects() throws Exception {
	XtextResource r = getResourceFromString("type TypeA extends TypeB type TypeB extends TypeA type AnotherType extends TypeA");
	Main model = (Main) r.getParseResult().getRootASTElement();
	ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(r.getParseResult().getRootNode(), 6);

	assertEquals(3, model.getTypes().size());

	EObject context = model.getTypes().get(0);
	Assignment asExtends = get(LangATestLanguageGrammarAccess.class).getTypeAccess().getExtendsAssignment_2_1();
	CrossReference xref = (CrossReference) asExtends.getTerminal();
	EReference ref = GrammarUtil.getReference(xref, context.eClass());

	assertEquals(1, getLinkingService().getLinkedObjects(context, ref, leaf).size());
}
 
Example 12
Source File: MultiLineJavaDocTypeReferenceProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EObjectInComment computeEObjectReferencedInComment(XtextResource resource, int offset) {
	IParseResult parseResult = resource.getParseResult();
	if(parseResult != null) {
		INode rootNode = parseResult.getRootNode();
		INode node = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
		EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(node);
		if(semanticObject != null) {
			EReference reference = getEReference(semanticObject, node, offset);
			if(reference != null) {
				IScope scope = getScope(semanticObject, reference, node, offset);
				List<ReplaceRegion> eObjectReferences = computeTypeRefRegions(node);
				for(ReplaceRegion eObjectReference : eObjectReferences) {
					if(eObjectReference.getOffset() <= offset && offset <= eObjectReference.getEndOffset()) {
						String eObjectReferenceText = eObjectReference.getText();
						if(!Strings.isNullOrEmpty(eObjectReferenceText)) {
							ITextRegion region = new TextRegion(eObjectReference.getOffset(), eObjectReference.getLength());
							IEObjectDescription candidate = getElementFromScope(scope, node, region, eObjectReferenceText);
							if(candidate != null) {
								EObject eObject = candidate.getEObjectOrProxy();
								if(eObject != null) {
									return new EObjectInComment(eObject, region);
								}
							}
						}
					}
				}
			}
		}
	}
	return null;
}
 
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: DefaultQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected EReference getUnresolvedEReference(final Issue issue, EObject target) {
	final ICompositeNode node = NodeModelUtils.getNode(target);
	if (node==null)
		return null;
	ICompositeNode rootNode = node.getRootNode();
	ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, issue.getOffset());
	CrossReference crossReference = findCrossReference(target, leaf);
	if (crossReference != null) {
		return  GrammarUtil.getReference(crossReference, target.eClass());
	}
	return null;
}
 
Example 15
Source File: FormatResourceDescriptionStrategy.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether given EObject represents a Xbase local variable.
 *
 * @param eObject
 *          to be checked
 * @return true if the given object does not represent a xbase local variable
 */
public boolean isXbaseLocalVariableName(final EObject eObject) {
  INode semanticNode = NodeModelUtils.getNode(eObject);
  if (semanticNode != null) {
    INode leafNode = NodeModelUtils.findLeafNodeAtOffset(semanticNode, semanticNode.getTotalOffset());
    AbstractRule containingRule = GrammarUtil.containingRule(leafNode.getGrammarElement());
    if (leafNode != null && containingRule != null && "ValidID".equals(containingRule.getName())) {
      return true;
    }
  }
  return false;
}
 
Example 16
Source File: XbaseHighlightingCalculator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void highlightAnnotation(XAnnotation annotation, IHighlightedPositionAcceptor acceptor, String highlightingConfiguration) {
	JvmType annotationType = annotation.getAnnotationType();
	if (annotationType != null && !annotationType.eIsProxy() && annotationType instanceof JvmAnnotationType) {
		ICompositeNode xannotationNode = NodeModelUtils.findActualNodeFor(annotation);
		if (xannotationNode != null) {
			ILeafNode firstLeafNode = NodeModelUtils.findLeafNodeAtOffset(xannotationNode, xannotationNode.getOffset() );
			if(firstLeafNode != null)
				highlightNode(acceptor, firstLeafNode, highlightingConfiguration);
		}
		highlightReferenceJvmType(acceptor, annotation, XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE, annotationType, highlightingConfiguration);
	}
}
 
Example 17
Source File: AbstractXtextMarkerBasedTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Searches an object for the given tag. First checks local tags. If not found then searches this tag in the required sources.
 *
 * @param tag
 *          Tag
 * @return EObject or {@code null}
 */
protected EObject getObjectForTag(final int tag) {
  EObject object = getMarkerTagsInfo().getModel(tag);
  if (object == null) {
    // Not in source under test
    String sourceName = getMarkerTagsInfo().getSource(tag);
    if (sourceName != null) {
      INode node = NodeModelUtils.findActualNodeFor(getTestSource(sourceName).getModel());
      INode leafNode = NodeModelUtils.findLeafNodeAtOffset(node, getMarkerTagsInfo().getOffset(tag));
      object = NodeModelUtils.findActualSemanticObjectFor(leafNode);
    }
  }
  assertNotNull("Tag " + tag + " should mark an object. Use «mark(TAG)» in a code snippet.", object); //$NON-NLS-1$//$NON-NLS-2$
  return object;
}
 
Example 18
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * If a type declaration has Java-form such as 'int foo() {}', then the following quickfix proposed which transforms
 * it to colon style: 'foo(): int {}' It searches the bogus return type (which is 'int' in the example above)
 * beginning from the parent node (N4MethodDeclarationImpl) of the method declaration. The bogus return type removed
 * from the old position. A colon followed by the bogus return type added to the right side of the method name.
 */
@Fix(IssueCodes.TYS_INVALID_TYPE_SYNTAX)
public void transformJavaTypeAnnotationToColonStyle(QuickfixContext context, ICodeActionAcceptor acceptor) {
	EObject element = getEObject(context);
	if (!(element instanceof ParameterizedTypeRef)) {
		return;
	}
	ParameterizedTypeRef typeRef = (ParameterizedTypeRef) element;
	if (!(typeRef.eContainer() instanceof N4MethodDeclaration)) {
		return;
	}
	ICompositeNode node = NodeModelUtils.getNode(element);
	ICompositeNode parentNode = findParentNodeWithSemanticElementOfType(node, N4MethodDeclaration.class);
	INode roundBracketNode = NodeModelUtilsN4.findKeywordNode(parentNode, ")");
	List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(parentNode.getSemanticElement(),
			N4JSPackage.Literals.TYPED_ELEMENT__BOGUS_TYPE_REF);

	if (nodesForFeature.isEmpty()) {
		return;
	}

	INode bogusNode = nodesForFeature.get(0);
	Document doc = context.options.getDocument();
	String stringOfBogusType = NodeModelUtilsN4.getTokenTextWithHiddenTokens(bogusNode);
	ILeafNode nodeAfterBogus = NodeModelUtils.findLeafNodeAtOffset(parentNode, bogusNode.getEndOffset());
	int spaceAfterBogusLength = (nodeAfterBogus != null && nodeAfterBogus.getText().startsWith(" ")) ? 1 : 0;
	int offsetBogusType = bogusNode.getOffset();
	int bogusTypeLength = stringOfBogusType.length();
	int offsetRoundBracket = roundBracketNode.getTotalOffset();

	List<TextEdit> textEdits = new ArrayList<>();
	// inserts the bogus type at the new location (behind the closing round bracket)
	textEdits.add(replace(doc, offsetRoundBracket + 1, 0, ": " + stringOfBogusType));
	// removes the bogus type and whitespace at the old location
	textEdits.add(replace(doc, offsetBogusType, bogusTypeLength + spaceAfterBogusLength, ""));

	acceptor.acceptQuickfixCodeAction(context, "Convert to colon style", textEdits);
}
 
Example 19
Source File: FormatterXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private ITextSegment findRegion(int lines, XpectInvocation inv, TargetSyntaxSupport syntax, ITextRegionAccess reg) {
	XtextResource resource = ((XtextTargetSyntaxSupport) syntax).getResource();

	IStatementRelatedRegion region2 = inv.getExtendedRegion();
	int end = region2.getOffset() + region2.getLength();
	ILeafNode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), end);

	int offset = node.getTotalEndOffset();
	ITextSegment region = getRegionForLines(reg, offset, lines);
	return region;
}
 
Example 20
Source File: PartialParserTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private ILeafNode findLeafNodeByText(ICompositeNode root, String model, String text) {
	return NodeModelUtils.findLeafNodeAtOffset(root, model.indexOf(text));
}