Java Code Examples for org.eclipse.xtext.nodemodel.util.NodeModelUtils#findActualSemanticObjectFor()
The following examples show how to use
org.eclipse.xtext.nodemodel.util.NodeModelUtils#findActualSemanticObjectFor() .
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: XtextElementSelectionListener.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** * Gets the URI of the semantic element currently selected. * * @return URI or null */ public URI getSelectedElementUri() { if (selection instanceof IStructuredSelection) { if (((IStructuredSelection) selection).getFirstElement() instanceof InternalEObject) { // structured selection, e.g. GMFEditor return EcoreUtil.getURI((EObject) ((IStructuredSelection) selection).getFirstElement()); } else if (((IStructuredSelection) selection).getFirstElement() instanceof EObjectNode) { // selection in outline return ((EObjectNode) ((IStructuredSelection) selection).getFirstElement()).getEObjectURI(); } } else { ILeafNode node = nodeAtTextSelection(); EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(node); if (semanticObject != null) { return EcoreUtil.getURI(semanticObject); } } return null; }
Example 2
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 3
Source File: EObjectAtOffsetHelper.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
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 4
Source File: XtextElementSelectionListener.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** * Gets the EClass of the semantic element currently selected. * * @return EClass or null */ public EClass getSelectedElementType() { if (selection instanceof IStructuredSelection) { if (((IStructuredSelection) selection).getFirstElement() instanceof EObject) { // structured selection, e.g. GMFEditor EObject eObject = (EObject) ((IStructuredSelection) selection).getFirstElement(); if (eObject.eResource() != null) { return eObject.eClass(); } } else if (((IStructuredSelection) selection).getFirstElement() instanceof EObjectNode) { // selection in outline return ((EObjectNode) ((IStructuredSelection) selection).getFirstElement()).getEClass(); } } else { ILeafNode node = nodeAtTextSelection(); EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(node); if (semanticObject != null) { return semanticObject.eClass(); } } return null; }
Example 5
Source File: XtendEObjectAtOffsetHelper.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@Override protected EObject resolveCrossReferencedElement(INode node) { EObject referencedElement = super.resolveCrossReferencedElement(node); EObject referenceOwner = NodeModelUtils.findActualSemanticObjectFor(node); if(referenceOwner instanceof XConstructorCall) { if (referenceOwner.eContainer() instanceof AnonymousClass) { AnonymousClass anon = (AnonymousClass) referenceOwner.eContainer(); JvmGenericType superType = anonymousClassUtil.getSuperType(anon); if(superType != null) { if (referencedElement instanceof JvmGenericType) return superType; else if(referencedElement instanceof JvmConstructor) { if(superType.isInterface()) return superType; JvmConstructor superConstructor = anonymousClassUtil.getSuperTypeConstructor(anon); if(superConstructor != null) return superConstructor; } } } } return referencedElement; }
Example 6
Source File: XtendProposalProvider.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@Override public void completeType_Members(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { if (isValidTypeForOverriding(model)) { INode node = context.getCurrentNode(); EObject eObject = NodeModelUtils.findActualSemanticObjectFor(node); if (!(eObject instanceof AnonymousClass)) { // due to some optimizations in the CA parser, we get some bogus context here and have to // double check that an override proposal would be valid at this location // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=370955 EObject prevModel = context.getPreviousModel(); if (prevModel instanceof XExpression) { XtendMember containingMember = EcoreUtil2.getContainerOfType(prevModel, XtendMember.class); XBlockExpression blockExpression = EcoreUtil2.getContainerOfType(prevModel, XBlockExpression.class); if (blockExpression != null && blockExpression != prevModel) { if (EcoreUtil.isAncestor(containingMember, blockExpression)) { // still inside block return; } } } overrideAssist.createOverrideProposals((XtendTypeDeclaration) model, context, acceptor, getConflictHelper()); } } super.completeType_Members(model, assignment, context, acceptor); }
Example 7
Source File: XbaseValidator.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
protected void checkNoJavaStyleTypeCasting(INode node) { BidiTreeIterator<INode> iterator = node.getAsTreeIterable().reverse().iterator(); ILeafNode child = getFirstLeafNode(iterator); if (child != null && child.getGrammarElement() == grammarAccess.getXParenthesizedExpressionAccess().getRightParenthesisKeyword_2()) { INode expressionNode = getNode(iterator, grammarAccess.getXParenthesizedExpressionAccess().getXExpressionParserRuleCall_1()); EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(expressionNode); if (semanticObject instanceof XFeatureCall || semanticObject instanceof XMemberFeatureCall) { XAbstractFeatureCall featureCall = (XAbstractFeatureCall) semanticObject; if (featureCall.isTypeLiteral()) { ICompositeNode parenthesizedNode = child.getParent(); ITextRegion parenthesizedRegion = parenthesizedNode.getTextRegion(); addIssue("Use 'as' keyword for type casting.", featureCall, parenthesizedRegion.getOffset(), parenthesizedRegion.getLength(), JAVA_STYLE_TYPE_CAST); } } } }
Example 8
Source File: ParserBasedContentAssistContextFactory.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
protected void initializeNodeAndModelData() { rootNode = parseResult.getRootNode(); lastCompleteNode = new LeafNodeFinder(completionOffset, true).searchIn(rootNode); if (lastCompleteNode == null) lastCompleteNode = rootNode; currentNode = new LeafNodeFinder(completionOffset, false).searchIn(rootNode); if (currentNode == null) currentNode = lastCompleteNode; lastVisibleNode = getLastCompleteNodeByOffset(rootNode, completionOffset); datatypeNode = getContainingDatatypeRuleNode(lastCompleteNode); currentModel = NodeModelUtils.findActualSemanticObjectFor(lastVisibleNode); }
Example 9
Source File: AbstractFragmentsTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testFragmentRecursive_04() throws Exception { ParserRuleFragments fragments = parseAndValidate("#11 myName ((myPrev))"); Assert.assertNotNull(fragments); Assert.assertEquals("myName", fragments.getElement().getName()); PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); Assert.assertEquals("myPrev", prev.getName()); ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); Assert.assertEquals("myPrev", node.getText()); EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); Assert.assertSame(prev, lookup); }
Example 10
Source File: ContentAssistContextFactory.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
protected void initializeNodeAndModelData() { rootNode = parseResult.getRootNode(); if (parser instanceof IPartialEditingContentAssistParser) { ((IPartialEditingContentAssistParser) parser).initializeFor(resource.getEntryPoint()); } lastCompleteNode = new LeafNodeFinder(completionOffset, true).searchIn(rootNode); if (lastCompleteNode == null) lastCompleteNode = rootNode; currentNode = new LeafNodeFinder(completionOffset, false).searchIn(rootNode); if (currentNode == null) currentNode = lastCompleteNode; lastVisibleNode = getLastCompleteNodeByOffset(rootNode, completionOffset); datatypeNode = getContainingDatatypeRuleNode(lastCompleteNode); currentModel = NodeModelUtils.findActualSemanticObjectFor(lastVisibleNode); }
Example 11
Source File: ExtendedFormattingConfigBasedStream.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
/** * Finds the semanticNode {@link EObject} that is associated to the container node of the given {@link INode}. * * @param givenNode * the {@link INode} to find the semantic node for * @param expectedType * The type of the semantic node to find * @return the semantic node found, {@code null} if none was found. */ private EObject findSemanticNode(final INode givenNode, final Type expectedType) { INode node = givenNode; // Node type EObject semanticNode = NodeModelUtils.findActualSemanticObjectFor(node); if (semanticNode == null) { return null; } Class<?> semanticNodeType = getSemanticNodeType(semanticNode); // Find correct node while (!expectedType.equals(semanticNodeType)) { if (semanticNode == null) { break; } if (semanticNode.eContainer() == null) { while (semanticNode != null && semanticNode.eContainer() == null) { node = findPrevious(node); semanticNode = NodeModelUtils.findActualSemanticObjectFor(node); semanticNodeType = getSemanticNodeType(semanticNode); } } else { semanticNode = semanticNode.eContainer(); semanticNodeType = getSemanticNodeType(semanticNode); } } return semanticNode; }
Example 12
Source File: JvmModelGenerator.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
public void addJavaDocImports(final EObject it, final ITreeAppendable appendable, final List<INode> documentationNodes) { for (final INode node : documentationNodes) { List<ReplaceRegion> _computeTypeRefRegions = this.javaDocTypeReferenceProvider.computeTypeRefRegions(node); for (final ReplaceRegion region : _computeTypeRefRegions) { { final String text = region.getText(); if (((text != null) && (text.length() > 0))) { final QualifiedName fqn = this.qualifiedNameConverter.toQualifiedName(text); final EObject context = NodeModelUtils.findActualSemanticObjectFor(node); if (((fqn.getSegmentCount() == 1) && (context != null))) { final IScope scope = this.scopeProvider.getScope(context, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE); final IEObjectDescription candidate = scope.getSingleElement(fqn); if ((candidate != null)) { EObject _xifexpression = null; boolean _eIsProxy = candidate.getEObjectOrProxy().eIsProxy(); if (_eIsProxy) { _xifexpression = EcoreUtil.resolve(candidate.getEObjectOrProxy(), context); } else { _xifexpression = candidate.getEObjectOrProxy(); } final JvmType jvmType = ((JvmType) _xifexpression); if (((jvmType instanceof JvmDeclaredType) && (!jvmType.eIsProxy()))) { final JvmDeclaredType referencedType = ((JvmDeclaredType) jvmType); final JvmDeclaredType contextDeclarator = EcoreUtil2.<JvmDeclaredType>getContainerOfType(it, JvmDeclaredType.class); String _packageName = referencedType.getPackageName(); String _packageName_1 = contextDeclarator.getPackageName(); boolean _notEquals = (!Objects.equal(_packageName, _packageName_1)); if (_notEquals) { final ImportManager importManager = this.getImportManager(appendable); importManager.addImportFor(jvmType); } } } } } } } } }
Example 13
Source File: MultiLineJavaDocTypeReferenceProvider.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
/** * {@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 14
Source File: N4JSOffsetAdapter.java From n4js with Eclipse Public License 1.0 | 5 votes |
/***/ @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 15
Source File: Bug407280Test.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testFindActualSemanticObjectFor() throws Exception { String modelAsString = "actions attribute ref attr1 attr2;"; int idx = modelAsString.indexOf("attr1"); Model model = (Model) getModelAndExpect(modelAsString, 1); /* linking issue */ INode root = NodeModelUtils.getNode(model).getRootNode(); ILeafNode leafNodeAtOffset = NodeModelUtils.findLeafNodeAtOffset(root, idx); assertEquals("attr1", leafNodeAtOffset.getText()); EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(leafNodeAtOffset); assertSame(model.getAttributes().get(0), semanticObject); }
Example 16
Source File: AbstractFragmentsTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testFragmentRecursive_01() throws Exception { ParserRuleFragments fragments = parseAndValidate("#10 myName myPrev"); Assert.assertNotNull(fragments); Assert.assertEquals("myName", fragments.getElement().getName()); PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); Assert.assertEquals("myPrev", prev.getName()); ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); Assert.assertEquals(" myPrev", node.getText()); EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); Assert.assertSame(prev, lookup); }
Example 17
Source File: AbstractFragmentsTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testFragmentRecursive_02() throws Exception { ParserRuleFragments fragments = parseAndValidate("#10 myName ((myPrev))"); Assert.assertNotNull(fragments); Assert.assertEquals("myName", fragments.getElement().getName()); PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); Assert.assertEquals("myPrev", prev.getName()); ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); Assert.assertEquals(" ((myPrev))", node.getText()); EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); Assert.assertSame(prev, lookup); }
Example 18
Source File: AbstractFragmentsTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Test public void testFragmentRecursive_03() throws Exception { ParserRuleFragments fragments = parseAndValidate("#11 myName myPrev"); Assert.assertNotNull(fragments); Assert.assertEquals("myName", fragments.getElement().getName()); PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); Assert.assertEquals("myPrev", prev.getName()); ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); Assert.assertEquals(" myPrev", node.getText()); EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); Assert.assertSame(prev, lookup); }
Example 19
Source File: FixedPartialParsingHelper.java From dsl-devkit with Eclipse Public License 1.0 | 4 votes |
/** * Investigates the composite nodes containing the changed region and collects a list of nodes which could possibly * replaced by a partial parse. Such a node has a parent that consumes all his current lookahead tokens and all of * these tokens are located before the changed region. */ private List<ICompositeNode> internalFindValidReplaceRootNodeForChangeRegion(final List<ICompositeNode> nodesEnclosingRegion, final Range range) { List<ICompositeNode> result = new ArrayList<ICompositeNode>(); boolean mustSkipNext = false; ICompositeNode previous = null; /* * set to 'true' as soon as the lookahead of an enclosing * exceeds the given range */ boolean done = false; for (int i = 0; i < nodesEnclosingRegion.size() && !done; i++) { ICompositeNode node = nodesEnclosingRegion.get(i); if (node.getGrammarElement() != null) { if (!mustSkipNext) { boolean process = true; if (previous != null && !node.hasNextSibling()) { if (previous.getLookAhead() == node.getLookAhead() && previous.getLookAhead() == 0) { process = false; } } EObject semanticElement = NodeModelUtils.findActualSemanticObjectFor(node); if (semanticElement != null) { ICompositeNode actualNode = NodeModelUtils.findActualNodeFor(semanticElement); if (actualNode != null && (actualNode.getTotalOffset() < node.getTotalOffset() || actualNode.getTotalEndOffset() > node.getTotalEndOffset())) { mustSkipNext = isActionNode(node); process = false; } } if (process) { int remainingLookAhead = node.getLookAhead(); if (remainingLookAhead != 0) { Iterator<ILeafNode> iterator = node.getLeafNodes().iterator(); while (iterator.hasNext() && remainingLookAhead > 0) { ILeafNode leaf = iterator.next(); if (!leaf.isHidden()) { if (remainingLookAhead > 0) { remainingLookAhead--; } if (remainingLookAhead == 0) { if (leaf.getTotalEndOffset() <= range.getOffset()) { result.add(node); previous = node; if (isActionNode(node)) { mustSkipNext = true; } break; } else { // lookahead ends left of the range, don't dive into child nodes done = true; } } } } if (remainingLookAhead != 0) { done = true; } } else { result.add(node); previous = node; if (isActionNode(node)) { mustSkipNext = true; } } } } else { // !mustSkipNext mustSkipNext = isActionNode(node); } } } return result; }
Example 20
Source File: ReorderingHiddenTokenSequencer.java From dsl-devkit with Eclipse Public License 1.0 | 4 votes |
/** * Collects all the hidden tokens between two given nodes of the node model. * * @param from * node that serves as a start point, must not be {@code null} * @param to * search end point, must not be {@code null} * @param deletedSemanticElements * set of the deleted semantic elements, must not be {@code null} * @return list of hidden tokens, never {@code null}, but can be empty */ private List<INode> getHiddenTokensBetween(final INode from, final INode to, final Set<EObject> deletedSemanticElements) { EObject fromElement = NodeModelUtils.findActualSemanticObjectFor(from); if (from.equals(NodeModelUtils.getNode(fromElement))) { // If the starting node represents some container, emit the comments that belong to it // This is needed to correctly handle some edge cases like ImportList in AvqScript // Logic for distinguishing between container's comments and the ones of first element is expected to be implemented in 'isLeadingCommentFor' emitContainerComments(from); } List<INode> result = Lists.newArrayList(); boolean handleReordering = from.getTotalOffset() > to.getTotalOffset(); if (!handleReordering) { // Elements are not reordered // Just going through the interval and collecting comments, unless they have already been emitted NodeIterator nodes = new NodeIterator(from); while (nodes.hasNext()) { INode next = nodes.next(); if (tokenUtil.isWhitespaceOrCommentNode(next)) { if (!emittedComments.contains(next)) { result.add(next); } } else if (next.equals(to)) { // We have hit the 'to' node // If it is a composite one, we have to iterate through its children // and collect whitespaces/comments until we encounter first token (keyword, identifier...) if (next instanceof ICompositeNode && (GrammarUtil.isDatatypeRuleCall(next.getGrammarElement()) || GrammarUtil.isEnumRuleCall(next.getGrammarElement()) || next.getGrammarElement() instanceof CrossReference)) { while (nodes.hasNext()) { INode lastNodeChild = nodes.next(); if (tokenUtil.isWhitespaceOrCommentNode(lastNodeChild)) { if (!emittedComments.contains(lastNodeChild)) { result.add(lastNodeChild); } } else if (lastNodeChild instanceof ILeafNode) { break; } } break; } else { // 'to' node is not a composite one, nothing to do here, just exit the loop break; } } else if (belongsToDeletedElement(next)) { handleDeletedElement(result, deletedSemanticElements, next); nodes.prune(); } else if (tokenUtil.isToken(next)) { // We have encountered some token, but not the one we expected // Will be handled by invoking 'getLeadingCommentsIncludingWhitespace' method later handleReordering = true; break; } } } if (handleReordering) { return getLeadingCommentsIncludingWhitespace(to); } return result; }