Java Code Examples for org.eclipse.xtext.nodemodel.INode#getGrammarElement()

The following examples show how to use org.eclipse.xtext.nodemodel.INode#getGrammarElement() . These examples are extracted from open source projects. 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
protected boolean isInvalidLastChildNode(ICompositeNode candidate, INode lastChild) {
	if (lastChild != null && lastChild.getSyntaxErrorMessage() != null) {
		EObject lastChildGrammarElement = lastChild.getGrammarElement();
		if (lastChildGrammarElement == null)
			return true;
		AbstractElement candidateElement = getCandidateElement(candidate.getGrammarElement());
		if (candidateElement != null) {
			if (isCalledBy(lastChildGrammarElement, candidateElement)) {
				while(candidate != null) {
					if (candidateElement != null && hasMandatoryFollowElements(candidateElement))
						return true;
					candidate = candidate.getParent();
					if (candidate != null)
						candidateElement = getCandidateElement(candidate.getGrammarElement());
				}
			}
			return true;
		}
	}
	return false;
}
 
Example 2
protected ILocationData getLocationWithoutTypeArguments(XAbstractFeatureCall call) {
	final ICompositeNode startNode = NodeModelUtils.getNode(call);
	if (startNode != null) {
		List<INode> resultNodes = Lists.newArrayList();
		if (call instanceof XFeatureCall || call instanceof XMemberFeatureCall) {
			boolean featureReferenceSeen = false;
			for (INode child : startNode.getChildren()) {
				if (featureReferenceSeen) {
					resultNodes.add(child);
				} else {
					EObject grammarElement = child.getGrammarElement();
					if (grammarElement instanceof CrossReference) {
						Assignment assignment = GrammarUtil.containingAssignment(grammarElement);
						if (assignment != null && "feature".equals(assignment.getFeature())) {
							featureReferenceSeen = true;
							resultNodes.add(child);
						}
					}
				}
			}
		}
		return toLocationData(resultNodes);
	}
	return null;
}
 
Example 3
public static ParserRule getEntryParserRule(INode node) {
	ICompositeNode root = node.getRootNode();
	EObject ge1 = root.getGrammarElement();
	if (ge1 instanceof ParserRule) {
		return (ParserRule) ge1;
	} else if (ge1 instanceof Action) {
		INode firstChild = root.getFirstChild();
		while (firstChild.getGrammarElement() instanceof Action && firstChild instanceof CompositeNode) {
			firstChild = ((CompositeNode)firstChild).getFirstChild();
		}
		EObject ge2 = firstChild.getGrammarElement();
		if (ge2 instanceof ParserRule) {
			return (ParserRule) ge2;
		}
	}
	throw new IllegalStateException("No Root Parser Rule found; The Node Model is broken.");
}
 
Example 4
protected void assignNodesByMatching(Map<EObject, AbstractToken> eObject2Token, ICompositeNode rootNode,
		Map<ILeafNode, EObject> comments) throws IOException {
	NodeIterator contents = new NodeIterator(rootNode);
	while (contents.hasNext()) {
		INode containedNode = contents.next();
		AbstractRule rule = containedNode.getGrammarElement() instanceof AbstractRule ? (AbstractRule) containedNode
				.getGrammarElement() : null;
		if (hiddenTokenHelper.isWhitespace(rule))
			continue;
		else if (containedNode instanceof ILeafNode && hiddenTokenHelper.isComment(rule))
			assignComment((ILeafNode) containedNode, eObject2Token, comments);
		else if (tokenUtil.isToken(containedNode)) {
			Pair<List<ILeafNode>, List<ILeafNode>> leadingAndTrailingHiddenTokens = tokenUtil
					.getLeadingAndTrailingHiddenTokens(containedNode);
			for (ILeafNode leadingHiddenNode : leadingAndTrailingHiddenTokens.getFirst()) {
				if (tokenUtil.isCommentNode(leadingHiddenNode)) {
					assignComment(leadingHiddenNode, eObject2Token, comments);
				}
			}
			assignTokenByMatcher(containedNode, eObject2Token);
			for (ILeafNode trailingHiddenNode : leadingAndTrailingHiddenTokens.getSecond()) {
				if (tokenUtil.isCommentNode(trailingHiddenNode)) {
					assignComment(trailingHiddenNode, eObject2Token, comments);
				}
			}
			contents.prune();
			ICompositeNode parentNode = containedNode.getParent();
			while (parentNode != null && assignTokenDirect(parentNode, eObject2Token))
				parentNode = parentNode.getParent();
			if (containedNode.getOffset() > rootNode.getEndOffset()) {
				break;
			}
		}
	}
}
 
Example 5
Source Project: n4js   File: DocCommentLookup.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds multi line comments on eObject. Comment is consider multiline by its type (e.g. start-end markers). Actual
 * conents can be either single line, or multiline content.
 *
 * @param eObject
 *            on which we look for multiline comment
 * @return list of nodes with comment, can be empty if no comments
 */
protected List<INode> findMultiLineComments(EObject eObject) {
	// get node
	INode elementNode = NodeModelUtils.findActualNodeFor(eObject);
	HiddenLeafs hLeafs = hla.getHiddenLeafsBefore(elementNode);
	// check for comments
	if (!hLeafs.containsComment()) {
		return null;
	}
	// get all comments
	List<LeafInfo> leafs = hLeafs.getLeafs();
	List<INode> comments = new ArrayList<>();

	final TerminalRule SL = grammarAccess.getSL_COMMENTRule();
	// get only MultiLine comments
	for (LeafInfo li : leafs) {
		if (li instanceof CommentInfo) {
			INode commentNode = li.getNode();
			EObject ge = commentNode.getGrammarElement();
			// are we sure we get here only ML/SL ?
			if (ge != SL) { // ignore SL
				// finds ML and SML
				comments.add(commentNode);
			}
		}
	}
	return comments;
}
 
Example 6
protected EObject findGrammarElement(INode node, EObject obj) {
	INode current = node;
	String feature = obj.eContainingFeature().getName();
	while (current != null) {
		EObject grammarElement = current.getGrammarElement();
		Assignment assignment = GrammarUtil.containingAssignment(grammarElement);
		if (assignment != null && feature.equals(assignment.getFeature()))
			return grammarElement;
		if (grammarElement instanceof Action) {
			Action action = (Action) grammarElement;
			if (feature.equals(action.getFeature()))
				return grammarElement;
			else if (current == node && current instanceof ICompositeNode) {
				INode child = ((ICompositeNode) current).getFirstChild();
				while (child instanceof ICompositeNode) {
					EObject grammarElement2 = child.getGrammarElement();
					Assignment assignment2 = GrammarUtil.containingAssignment(grammarElement2);
					if (assignment2 != null && feature.equals(assignment2.getFeature()))
						return grammarElement2;
					// if (child.hasDirectSemanticElement() && child.getSemanticElement() != obj)
					// break;
					child = ((ICompositeNode) child).getFirstChild();
				}
			}
		}
		if (current.hasDirectSemanticElement() && current.getSemanticElement() != obj)
			return null;
		current = current.getParent();
	}
	return null;
}
 
Example 7
@Override
protected List<INode> getLocationNodes(EObject obj) {
	if (obj instanceof XMemberFeatureCall || obj instanceof XAssignment || obj instanceof XFeatureCall) {
		List<INode> resultNodes = Lists.newArrayList();
		final ICompositeNode startNode = findNodeFor(obj);
		boolean crossRefConsumed = false;
		for (INode child : startNode.getChildren()) {
			if (crossRefConsumed) {
				resultNodes.add(child);
			} else {
				EObject grammarElement = child.getGrammarElement();
				if (grammarElement instanceof CrossReference) {
					// We don't use the grammar access to be more robust against
					// overwriting grammars
					Assignment assignment = GrammarUtil.containingAssignment(grammarElement);
					if (XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE.getName().equals(assignment.getFeature())) {
						crossRefConsumed = true;
						resultNodes.add(child);
					}
				}
			} 
		}
		if (!resultNodes.isEmpty())
			return resultNodes;
	}
	return super.getLocationNodes(obj);
}
 
Example 8
Source Project: xtext-core   File: TokenUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public EObject getTokenOwner(INode node) {
	if (node.hasDirectSemanticElement())
		return node.getSemanticElement();
	if (node.getParent() != null) {
		if (node.getParent().hasDirectSemanticElement())
			return node.getParent().getSemanticElement();
		EObject parentGrammarElement = node.getParent().getGrammarElement();
		boolean isParser = GrammarUtil.isEObjectRule(parentGrammarElement) || GrammarUtil.isEObjectRuleCall(parentGrammarElement);
		for (INode sibling : node.getParent().getChildren())
			if (sibling.hasDirectSemanticElement() && (isParser || sibling.getGrammarElement() instanceof Action))
				return sibling.getSemanticElement();
	}
	return node.getSemanticElement();
}
 
Example 9
public String getPrefix(INode prefixNode) {
	if (prefixNode instanceof ILeafNode) {
		if (((ILeafNode) prefixNode).isHidden() && prefixNode.getGrammarElement() != null)
			return "";
		return getNodeTextUpToCompletionOffset(prefixNode);
	}
	StringBuilder result = new StringBuilder(prefixNode.getTotalLength());
	doComputePrefix((ICompositeNode) prefixNode, result);
	return result.toString();
}
 
Example 10
protected AbstractRule binaryOperationPrecedence(final EObject op) {
  final INode node = this._nodeModelAccess.nodeForFeature(op, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
  if (((node != null) && (node.getGrammarElement() instanceof CrossReference))) {
    EObject _grammarElement = node.getGrammarElement();
    final AbstractElement terminal = ((CrossReference) _grammarElement).getTerminal();
    if ((terminal instanceof RuleCall)) {
      return ((RuleCall)terminal).getRule();
    }
  }
  return null;
}
 
Example 11
/**
 * Returns the textual value of the node, if it is a JavaDoc-like comment.
 * 
 * @param node
 *          a node
 * @return the comment as a string if any, else null
 */
protected String getJavaDocComment(final INode node) {
  if (node instanceof ILeafNode && !((ILeafNode) node).isHidden()) {
    return null;
  }
  if (node instanceof ILeafNode && node.getGrammarElement() instanceof TerminalRule
      && ruleName.equalsIgnoreCase(((TerminalRule) node.getGrammarElement()).getName())) {
    String comment = ((ILeafNode) node).getText();
    if (comment.matches("(?s)" + startTag + ".*")) {
      return comment;
    }
  }
  return null;
}
 
Example 12
protected Multimap<EObject, AbstractElement> computeCurrentModel(EObject currentModel, INode lastCompleteNode,
		Collection<AbstractElement> followElements) {
	Multimap<EObject, AbstractElement> result = LinkedHashMultimap.create();
	ICompositeNode currentParserNode = NodeModelUtils.getNode(currentModel);
	if (currentParserNode == null) {
		result.putAll(currentModel, followElements);
		return result;
	}
	EObject currentGrammarElement = currentParserNode.getGrammarElement();
	AbstractRule currentRule = getRule(currentGrammarElement);
	for (AbstractElement grammarElement : followElements) {
		AbstractRule rule = currentRule;
		ICompositeNode loopParserNode = currentParserNode;
		EObject loopLastGrammarElement = lastCompleteNode.getGrammarElement();
		while (!canBeCalledAfter(rule, loopLastGrammarElement, lastCompleteNode.getText(), grammarElement) && loopParserNode.getParent() != null) {
			loopLastGrammarElement = loopParserNode.getGrammarElement();
			loopParserNode = loopParserNode.getParent();
			while (loopParserNode.getGrammarElement() == null && loopParserNode.getParent() != null)
				loopParserNode = loopParserNode.getParent();
			EObject loopGrammarElement = loopParserNode.getGrammarElement();
			rule = getRule(loopGrammarElement);
		}
		EObject context = loopParserNode.getSemanticElement();
		result.put(context, grammarElement);
	}
	return result;
}
 
Example 13
public INode getContainingDatatypeRuleNode(INode node) {
	INode result = node;
	EObject grammarElement = result.getGrammarElement();
	if (grammarElement != null) {
		ParserRule parserRule = GrammarUtil.containingParserRule(grammarElement);
		while (parserRule != null && GrammarUtil.isDatatypeRule(parserRule)) {
			result = result.getParent();
			grammarElement = result.getGrammarElement();
			parserRule = GrammarUtil.containingParserRule(grammarElement);
		}
	}
	return result;
}
 
Example 14
protected INode getLastCompleteNodeByOffset(INode node, int offset) {
	BidiTreeIterator<INode> iterator = node.getRootNode().getAsTreeIterable().iterator();
	INode result = node;
	ITextRegion candidateTextRegion = node.getTextRegion();
	while (iterator.hasNext()) {
		INode candidate = iterator.next();
		ITextRegion textRegion = candidate.getTextRegion();
		if (textRegion.getOffset() >= offset && !(textRegion.getOffset() == offset && textRegion.getLength() == 0)) {
			if (!candidateTextRegion.equals(textRegion) && candidate instanceof ILeafNode && textRegion.getLength() + textRegion.getOffset() >= offset) {
				break;
			}
		} 
		if ((candidate instanceof ILeafNode) &&
				   (candidate.getGrammarElement() == null ||
						   candidate.getGrammarElement() instanceof AbstractElement ||
						   candidate.getGrammarElement() instanceof ParserRule)) {
			if (textRegion.getLength() == 0) {
				if (candidateTextRegion.getOffset() + candidateTextRegion.getLength() < offset || candidateTextRegion.getLength() == 0 && candidateTextRegion.getOffset() <= offset) {
					result = candidate;
					candidateTextRegion = candidate.getTextRegion();
				}
			} else {
				result = candidate;
				candidateTextRegion = candidate.getTextRegion();
			}
		}
	}
	return result;
}
 
Example 15
protected int doCheckChildNodeAndReturnTotalLength(INode child, ICompositeNode parent, int startsAt) {
	exceptionSeen |= child.getSyntaxErrorMessage() != null;
	if (((AbstractNode) child).basicGetNextSibling().basicGetPreviousSibling() != child)
		throw new InconsistentNodeModelException("child.next.previous != child");
	if (((AbstractNode) child).basicGetPreviousSibling().basicGetNextSibling() != child)
		throw new InconsistentNodeModelException("child.previous.next != child");
	if (((AbstractNode) child).basicGetPreviousSibling().basicGetParent() != ((AbstractNode) child).basicGetParent())
		throw new InconsistentNodeModelException("child.previous.parent != child.parent");
	if (((AbstractNode) child).basicGetNextSibling().basicGetParent() != ((AbstractNode) child).basicGetParent())
		throw new InconsistentNodeModelException("child.next.parent != child.parent");
	if (((AbstractNode) child).basicGetParent() != parent) {
		throw new InconsistentNodeModelException("node does not point to its parent");
	}
	if (child instanceof ILeafNode) {
		if (child.getGrammarElement() == null) {
			if (!exceptionSeen) {
				throw new InconsistentNodeModelException("leaf node without grammar element");
			}
		}
		return doCheckLeafNodeAndReturnLength((ILeafNode) child, startsAt);
	} else {
		if (child.getGrammarElement() == null) {
			throw new InconsistentNodeModelException("node without grammar element");
		}
		return doCheckCompositeNodeAndReturnTotalLength((ICompositeNode) child, startsAt);
	}
}
 
Example 16
Source Project: sarl   File: SARLCodeMiningProvider.java    License: Apache License 2.0 4 votes vote down vote up
/** Add an annotation when the action's return type is implicit and inferred by the SARL compiler.
 *
 * @param resource the resource to parse.
 * @param acceptor the code mining acceptor.
 */
@SuppressWarnings("checkstyle:npathcomplexity")
private void createImplicitActionReturnType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) {
	final List<XtendFunction> actions = EcoreUtil2.eAllOfType(resource.getContents().get(0), XtendFunction.class);

	for (final XtendFunction action : actions) {
		// inline annotation only for methods with no return type
		if (action.getReturnType() != null) {
			continue;
		}
		// get return type name from operation
		final JvmOperation inferredOperation = (JvmOperation) this.jvmModelAssocitions.getPrimaryJvmElement(action);
		if (inferredOperation == null || inferredOperation.getReturnType() == null) {
			continue;
		}
		// find document offset for inline annotationn
		final ICompositeNode node = NodeModelUtils.findActualNodeFor(action);
		final Keyword parenthesis = this.grammar.getAOPMemberAccess().getRightParenthesisKeyword_2_5_6_2();
		final Assignment fctname = this.grammar.getAOPMemberAccess().getNameAssignment_2_5_5();
		int offsetFctname = -1;
		int offsetParenthesis = -1;
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			final INode child = it.next();
			if (child != node) {
				final EObject grammarElement = child.getGrammarElement();
				if (grammarElement instanceof RuleCall) {
					if (fctname.equals(grammarElement.eContainer())) {
						offsetFctname = child.getTotalEndOffset();
					}
				} else if (parenthesis.equals(grammarElement)) {
					offsetParenthesis = child.getTotalEndOffset();
					break;
				}
			}
		}
		int offset = -1;
		if (offsetParenthesis >= 0) {
			offset = offsetParenthesis;
		} else if (offsetFctname >= 0) {
			offset = offsetFctname;
		}
		if (offset >= 0) {
			final String returnType = inferredOperation.getReturnType().getSimpleName();
			final String text = " " + this.keywords.getColonKeyword() + " " + returnType; //$NON-NLS-1$ //$NON-NLS-2$
			acceptor.accept(createNewLineContentCodeMining(offset, text));
		}
	}
}
 
Example 17
protected boolean isSemicolon(INode child) {
	return child.getGrammarElement() == grammarAccess.getXBlockExpressionAccess().getSemicolonKeyword_2_1()
			|| child.getGrammarElement() == grammarAccess.getXExpressionInClosureAccess().getSemicolonKeyword_1_1();
}
 
Example 18
@Override
public void doProvideHighlightingFor(XtextResource resource,
		IHighlightedPositionAcceptor acceptor,
		CancelIndicator cancelIndicator) {

	// It gets a node model.
	INode root = resource.getParseResult().getRootNode();
	for (INode node : root.getAsTreeIterable()) {
		EObject grammarElement = node.getGrammarElement();
		if (grammarElement instanceof RuleCall) {
			RuleCall rc = (RuleCall) grammarElement;
			AbstractRule r = rc.getRule();
			EObject c = grammarElement.eContainer();

			// handle ID elements specifically
			if (r.getName().equals("ID")) { //$NON-NLS-1$
				EObject semanticElement = node.getSemanticElement();
				switch (((Assignment) c).getFeature()) {
				case "name": //$NON-NLS-1$
					if (semanticElement instanceof DotGraph) {
						acceptor.addPosition(node.getOffset(),
								node.getLength(),
								DotHighlightingConfiguration.GRAPH_NAME_ID);
					} else if (semanticElement instanceof NodeStmt
							|| semanticElement instanceof NodeId) {
						acceptor.addPosition(node.getOffset(),
								node.getLength(),
								DotHighlightingConfiguration.NODE_NAME_ID);
					} else if (semanticElement instanceof Attribute) {
						acceptor.addPosition(node.getOffset(),
								node.getLength(),
								DotHighlightingConfiguration.ATTRIBUTE_NAME_ID);
					} else if (semanticElement instanceof Port) {
						acceptor.addPosition(node.getOffset(),
								node.getLength(),
								DotHighlightingConfiguration.PORT_NAME_ID);
					}
					break;
				case "value": //$NON-NLS-1$
					if (semanticElement instanceof Attribute) {
						switch (((Attribute) semanticElement).getName()
								.toValue()) {
						case DotAttributes.ARROWHEAD__E:
						case DotAttributes.ARROWTAIL__E:
							provideHighlightingForArrowTypeString(node,
									acceptor);
							break;
						}
					}
					break;
				}
			}
			if (r.getName().equals("EdgeOp")) { //$NON-NLS-1$
				acceptor.addPosition(node.getOffset(), node.getLength(),
						DotHighlightingConfiguration.EDGE_OP_ID);
			}
			if (r.getName().equals("HTML_STRING")) { //$NON-NLS-1$
				provideHighlightingForHtmlString(node, acceptor);
			}
		}
	}
}
 
Example 19
@Override
public boolean equalsOrReplacesNode(EObject context, Keyword keyword, Object value, INode node) {
	return node.getGrammarElement() == keyword;
}
 
Example 20
@Override
public boolean equalsOrReplacesNode(EObject context, Keyword keyword, INode node) {
	return node.getGrammarElement() == keyword;
}