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

The following examples show how to use org.eclipse.xtext.nodemodel.ILeafNode#getGrammarElement() . 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: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
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 2
Source File: MultiLineCommentDocumentationProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the nearest multi line comment node that precedes the given object. 
 * @since 2.3
 * @return a list with exactly one node or an empty list if the object is undocumented.
 */
/* @NonNull */
@Override
public List<INode> getDocumentationNodes(/* @NonNull */ EObject object) {
	ICompositeNode node = NodeModelUtils.getNode(object);
	List<INode> result = Collections.emptyList();
	if (node != null) {
		// get the last multi line comment before a non hidden leaf node
		for (ILeafNode leafNode : node.getLeafNodes()) {
			if (!leafNode.isHidden())
				break;
			if (leafNode.getGrammarElement() instanceof TerminalRule
					&& ruleName.equalsIgnoreCase(((TerminalRule) leafNode.getGrammarElement()).getName())) {
				String comment = leafNode.getText();
				if (commentStartTagRegex.matcher(comment).matches()) {
					result = Collections.<INode>singletonList(leafNode);
				}
			}
		}
	}
	return result;
}
 
Example 3
Source File: MultiLineFileHeaderProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the first non-whitespace leaf node in the file if it is a multi-line comment node.
 * 
 * @since 2.3
 * @return a list with exactly one node or an empty list if there is no header is undocumented.
 */
/* @NonNull */
@Override
public List<INode> getFileHeaderNodes(Resource resource) {
	if (resource instanceof XtextResource) {
		IParseResult parseResult = ((XtextResource) resource).getParseResult();
		if(parseResult != null) {
			for(ILeafNode leafNode: parseResult.getRootNode().getLeafNodes()) {
				EObject grammarElement = leafNode.getGrammarElement();
				if(grammarElement instanceof TerminalRule) {
					String terminalRuleName = ((TerminalRule) grammarElement).getName();
					if (ruleName.equalsIgnoreCase(terminalRuleName)) {
						return singletonList((INode) leafNode);
					} else if(wsRuleName.equals(terminalRuleName)) {
						continue;
					}
				}
				break;
			}
		}
	}
	return Collections.emptyList();
}
 
Example 4
Source File: DotIDValueConverter.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ID toValue(String string, INode node)
		throws ValueConverterException {
	if (string == null) {
		return null;
	}
	if (node == null) {
		return ID.fromString(string);
	}

	for (ILeafNode leaf : node.getLeafNodes()) {
		Object grammarElement = leaf.getGrammarElement();
		if (grammarElement instanceof RuleCall) {
			RuleCall lexerRuleCall = (RuleCall) grammarElement;
			AbstractRule nestedLexerRule = lexerRuleCall.getRule();
			String nestedLexerRuleName = nestedLexerRule.getName();
			if ("COMPASS_PT".equals(nestedLexerRuleName)) {
				nestedLexerRuleName = "STRING";
			}
			return ID.fromString(string, Type.valueOf(nestedLexerRuleName));
		}
	}
	throw new IllegalArgumentException("Invalid ID string " + string);
}
 
Example 5
Source File: XtextLinkingService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private List<EObject> getLinkedMetaModel(TypeRef context, EReference ref, ILeafNode text) throws IllegalNodeException {
	final ICompositeNode parentNode = text.getParent();
	BidiIterator<INode> iterator = parentNode.getChildren().iterator();
	while(iterator.hasPrevious()) {
		INode child = iterator.previous();
		if (child instanceof ILeafNode) {
			ILeafNode leaf = (ILeafNode) child;
			if (text == leaf)
				return super.getLinkedObjects(context, ref, text);
			if (!(leaf.getGrammarElement() instanceof Keyword) && !leaf.isHidden()) {
				IScope scope = getScope(context, ref);
				return XtextMetamodelReferenceHelper.findBestMetamodelForType(
						context, text.getText(), leaf.getText(), scope);
			}
		}
	}
	return Collections.emptyList();
}
 
Example 6
Source File: SingleLineCommentDocumentationProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<INode> getDocumentationNodes(final EObject object) {
  ICompositeNode node = NodeModelUtils.getNode(object);
  if (node == null) {
    return Collections.emptyList();
  }

  // get all single line comments before a non hidden leaf node
  List<INode> result = Lists.newArrayList();
  for (ILeafNode leaf : node.getLeafNodes()) {
    if (!leaf.isHidden()) {
      break;
    }
    EObject grammarElement = leaf.getGrammarElement();
    if (grammarElement instanceof AbstractRule && ruleName.equals(((AbstractRule) grammarElement).getName())) {
      String comment = leaf.getText();
      if (getCommentPattern().matcher(comment).matches() && !comment.matches(ignore)) {
        result.add(leaf);
      }
    }
  }

  return result;
}
 
Example 7
Source File: XtendHighlightingCalculator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void highlightDeprecatedXtendAnnotationTarget(IHighlightedPositionAcceptor acceptor, XtendAnnotationTarget target, XAnnotation annotation){
	JvmType annotationType = annotation.getAnnotationType();
	if(annotationType instanceof JvmAnnotationType && DeprecationUtil.isDeprecatedAnnotation((JvmAnnotationType) annotationType)){
		if (target instanceof XtendConstructor) {
			ICompositeNode compositeNode = NodeModelUtils.getNode(target);
			for(ILeafNode leaf: compositeNode.getLeafNodes()) {
				if (leaf.getGrammarElement() == xtendGrammarAccess.getMemberAccess().getNewKeyword_2_2_2()) {
					highlightNode(acceptor, leaf, XbaseHighlightingStyles.DEPRECATED_MEMBERS);
					highlightNode(acceptor, leaf, HighlightingStyles.KEYWORD_ID);
					return;
				}
			}
		} else {
			EStructuralFeature nameFeature = target.eClass().getEStructuralFeature("name");
			if (nameFeature!=null) {
				highlightFeature(acceptor, target, nameFeature, XbaseHighlightingStyles.DEPRECATED_MEMBERS);
			}
		}
	}
}
 
Example 8
Source File: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.3
 */
protected int getFirstOffsetOfKeyword(EObject object, String keyword) {
	int offset = -1;
	ICompositeNode node = NodeModelUtils.getNode(object);
	if (node != null) {
		for (ILeafNode leafNode : node.getLeafNodes()) {
			if (leafNode.getGrammarElement() instanceof Keyword
					&& equal(keyword, ((Keyword) leafNode.getGrammarElement()).getValue())) {
				return leafNode.getOffset() + 1;
			}
		}
	}
	return offset;
}
 
Example 9
Source File: QualifiedNameValueConverter.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toValue(String string, INode node) throws ValueConverterException {
	StringBuilder buffer = new StringBuilder();
	boolean isFirst = true;
	if (node != null) {
		for(ILeafNode leafNode: node.getLeafNodes()) {
			EObject grammarElement = leafNode.getGrammarElement();
			if (isDelegateRuleCall(grammarElement) || isWildcardLiteral(grammarElement)) {
				if (!isFirst)
					buffer.append(getValueNamespaceDelimiter());
				isFirst = false;
				if (isDelegateRuleCall(grammarElement))
					buffer.append(delegateToValue(leafNode));
				else 
					buffer.append(getWildcardLiteral());
			}
		}
	} else {
		for (String segment : Strings.split(string, getStringNamespaceDelimiter())) {
			if (!isFirst)
				buffer.append(getValueNamespaceDelimiter());
			isFirst = false;
			if(getWildcardLiteral().equals(segment)) {
				buffer.append(getWildcardLiteral());
			} else {
				buffer.append((String) valueConverterService.toValue(segment, getDelegateRuleName(), null));
			}
		}
	}
	return buffer.toString();
}
 
Example 10
Source File: EnumLiteralSerializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Keyword getLiteral(INode node) {
	if (node != null) {
		for(ILeafNode leaf: node.getLeafNodes()) {
			if (leaf.getGrammarElement() instanceof EnumLiteralDeclaration)
				return ((EnumLiteralDeclaration) leaf.getGrammarElement()).getLiteral();
		}
	}
	return null;
}
 
Example 11
Source File: EnumLiteralSerializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Keyword getLiteral(INode node) {
	if (node != null) {
		for (ILeafNode leaf : node.getLeafNodes()) {
			if (leaf.getGrammarElement() instanceof EnumLiteralDeclaration)
				return ((EnumLiteralDeclaration) leaf.getGrammarElement()).getLiteral();
		}
	}
	return null;
}
 
Example 12
Source File: XtendTaskFinder.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isRichComment(final ILeafNode node) {
  EObject _grammarElement = node.getGrammarElement();
  if ((_grammarElement instanceof RuleCall)) {
    return (Objects.equal(((RuleCall) node.getGrammarElement()).getRule(), this._xtendGrammarAccess.getCOMMENT_RICH_TEXT_ENDRule()) || 
      Objects.equal(((RuleCall) node.getGrammarElement()).getRule(), this._xtendGrammarAccess.getCOMMENT_RICH_TEXT_INBETWEENRule()));
  }
  return false;
}
 
Example 13
Source File: ASTGraphProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private String getDocumentation(/* @NonNull */EObject object) {
	if (object.eContainer() == null) {
		// if a comment is at the beginning of the file it will be returned for
		// the root element (e.g. Script in N4JS) as well -> avoid this!
		return null;
	}

	ICompositeNode node = NodeModelUtils.getNode(object);
	if (node != null) {
		// get the last multi line comment before a non hidden leaf node
		for (ILeafNode leafNode : node.getLeafNodes()) {
			if (!leafNode.isHidden())
				break;

			EObject grammarElem = leafNode.getGrammarElement();
			if (grammarElem instanceof TerminalRule
					&& "ML_COMMENT".equalsIgnoreCase(((TerminalRule) grammarElem).getName())) {

				String comment = leafNode.getText();
				if (commentStartTagRegex.matcher(comment).matches()) {
					return leafNode.getText();
				}
			}
		}
	}
	return null;
}
 
Example 14
Source File: XtendExpressionUtil.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isRichTextEnd(EObject element, INode node) {
	if (!(element instanceof RichStringLiteral)) {
		return false;
	}
	for (ILeafNode leafNode : node.getLeafNodes()) {
		EObject grammarElement = leafNode.getGrammarElement();
		if (grammarElement instanceof RuleCall) {
			RuleCall ruleCall = (RuleCall) grammarElement;
			if (grammarAccess.getRICH_TEXT_ENDRule() == ruleCall.getRule()) {
				return true;
			}
		}
	}
	return false;
}
 
Example 15
Source File: XtendExpressionUtil.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isRichStringPart(ILeafNode nextNode) {
	if (nextNode == null) {
		return false;
	}
	if (grammarAccess.getRichStringForLoopAccess().getENDFORKeyword_9() == nextNode.getGrammarElement()) {
		return false;
	}
	if (grammarAccess.getRichStringIfAccess().getENDIFKeyword_6() == nextNode.getGrammarElement()) {
		return false;
	}
	return true;
}
 
Example 16
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeTypeRef_Classifier(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	Grammar grammar = GrammarUtil.getGrammar(model);
	ContentAssistContext.Builder myContextBuilder = context.copy();
	myContextBuilder.setMatcher(new ClassifierPrefixMatcher(context.getMatcher(), classifierQualifiedNameConverter));
	if (model instanceof TypeRef) {
		ICompositeNode node = NodeModelUtils.getNode(model);
		if (node != null) {
			int offset = node.getOffset();
			Region replaceRegion = new Region(offset, context.getReplaceRegion().getLength()
					+ context.getReplaceRegion().getOffset() - offset);
			myContextBuilder.setReplaceRegion(replaceRegion);
			myContextBuilder.setLastCompleteNode(node);
			StringBuilder availablePrefix = new StringBuilder(4);
			for (ILeafNode leaf : node.getLeafNodes()) {
				if (leaf.getGrammarElement() != null && !leaf.isHidden()) {
					if ((leaf.getTotalLength() + leaf.getTotalOffset()) < context.getOffset())
						availablePrefix.append(leaf.getText());
					else
						availablePrefix.append(leaf.getText().substring(0,
								context.getOffset() - leaf.getTotalOffset()));
				}
				if (leaf.getTotalOffset() >= context.getOffset())
					break;
			}
			myContextBuilder.setPrefix(availablePrefix.toString());
		}
	}
	ContentAssistContext myContext = myContextBuilder.toContext();
	for (AbstractMetamodelDeclaration declaration : grammar.getMetamodelDeclarations()) {
		if (declaration.getEPackage() != null) {
			createClassifierProposals(declaration, model, myContext, acceptor);
		}
	}
}
 
Example 17
Source File: SarlTaskFinder.java    From sarl with Apache License 2.0 5 votes vote down vote up
private boolean isRichComment(final ILeafNode node) {
	final EObject grammarElement = node.getGrammarElement();
	if (grammarElement instanceof RuleCall) {
		return Objects.equal(((RuleCall) node.getGrammarElement()).getRule(), this.grammarAccess.getCOMMENT_RICH_TEXT_ENDRule())
				|| Objects.equal(((RuleCall) node.getGrammarElement()).getRule(), this.grammarAccess.getCOMMENT_RICH_TEXT_INBETWEENRule());
	}
	return false;
}
 
Example 18
Source File: ContentAssistTokenTypeMapper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Converts a leaf node an Antlr token type (int).
 */
public int getInternalTokenType(ILeafNode leafNode) {
	EObject grammarElement = leafNode.getGrammarElement();
	if (grammarElement != null) {
		return getInternalTokenType(grammarElement);
	}
	String text = leafNode.getText();
	Integer type = tokenTypes.get("'" + text + "'");
	if (type != null) {
		return type;
	}
	throw new IllegalArgumentException(text);
}
 
Example 19
Source File: N4JSSyntaxValidator.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the first keyword with the given value, or null if no such keyword is found.
 */
private ILeafNode doFindLeafWithKeyword(EObject semanticElement, String stopAtKeyword, ICompositeNode node,
		String keyWord,
		boolean commaAlternative, int hitNumber) {
	EObject grammarElement;
	int foundHits = 0;

	for (BidiTreeIterator<INode> iter = node.getAsTreeIterable().iterator(); iter.hasNext();) {
		INode child = iter.next();
		EObject childSemElement = child.getSemanticElement();
		if (child != node && childSemElement != null && childSemElement != semanticElement) {
			iter.prune();
		} else if (child instanceof ILeafNode) {
			ILeafNode leaf = (ILeafNode) child;
			grammarElement = leaf.getGrammarElement();
			if (grammarElement instanceof Keyword) {
				String value = ((Keyword) grammarElement).getValue();
				if (stopAtKeyword.equals(value)) {
					return null;
				}
				if (keyWord.equals(value)) {
					if (grammarElement.eContainer() instanceof Alternatives) {
						AbstractElement first = ((Alternatives) (grammarElement.eContainer())).getElements().get(0);
						boolean inCommaAlternative = (first instanceof Keyword && ",".equals(((Keyword) first)
								.getValue()));
						if (inCommaAlternative == commaAlternative) {
							foundHits++;
							if (foundHits >= hitNumber) {
								return leaf;
							}
						}
					} else {
						if (!commaAlternative) {
							foundHits++;
							if (foundHits >= hitNumber) {
								return leaf;
							}
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example 20
Source File: SingleLineCommentDocumentationProvider.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Add a comment for a given node (if applicable).
 *
 * @param builder
 *          add comments to this
 * @param node
 *          the node read comments from
 * @param contextEndLine
 *          the end line (number) of the root object, used for line number comparison
 */
private void addComment(final StringBuilder builder, final ILeafNode node, final int contextEndLine) {
  if (node.getGrammarElement() instanceof TerminalRule && ruleName.equals(((TerminalRule) node.getGrammarElement()).getName())
      && node.getStartLine() == contextEndLine) {
    final String comment = node.getText();
    if (getCommentPattern().matcher(comment).matches()) {
      builder.append(comment);
    }
  }
}