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

The following examples show how to use org.eclipse.xtext.nodemodel.INode#getLeafNodes() . 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: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected String getOperatorMethodName(XAbstractFeatureCall call) {
	StringBuilder sb = new StringBuilder();
	for(INode node: NodeModelUtils.findNodesForFeature(call, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE)) {
		for(ILeafNode leafNode: node.getLeafNodes()) {
			if(!leafNode.isHidden()) {
				sb.append(leafNode.getText());
			}
		}
	}
	
	String symbol = sb.toString();
	if(!symbol.isEmpty()) {
		QualifiedName methodName = operatorMapping.getMethodName(QualifiedName.create(symbol));
		if(methodName != null)
			return methodName.getFirstSegment();
	}
	
	return null;
}
 
Example 2
Source File: FormatterTestValueConverters.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@ValueConverter(rule = "FQN")
// CHECKSTYLE:OFF
public IValueConverter<String> FQN() { // NOPMD
  // CHECKSTYLE:ON
  return new AbstractNullSafeConverter<String>() {
    @Override
    protected String internalToValue(final String string, final INode node) {
      if (!string.equals(string.trim())) {
        throw new RuntimeException(); // NOPMD
      }
      StringBuffer b = new StringBuffer();
      for (ILeafNode l : node.getLeafNodes()) {
        if (!l.isHidden()) {
          b.append(l.getText());
        }
      }
      return b.toString();
    }

    @Override
    protected String internalToString(final String value) {
      return value;
    }
  };
}
 
Example 3
Source File: AbstractSyntacticSequencer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void acceptNode(INode node) {
	Object ge = node.getGrammarElement();
	if (ge instanceof Keyword)
		acceptUnassignedKeyword((Keyword) ge, node.getText(), (ILeafNode) node);
	else if (ge instanceof RuleCall) {
		RuleCall rc = (RuleCall) ge;
		if (rc.getRule() instanceof TerminalRule)
			acceptUnassignedTerminal(rc, node.getText(), (ILeafNode) node);
		else if (rc.getRule() instanceof ParserRule) {
			StringBuilder text = new StringBuilder();
			for (ILeafNode leaf : node.getLeafNodes())
				if (text.length() > 0 || !leaf.isHidden())
					text.append(leaf.getText());
			acceptUnassignedDatatype(rc, text.toString(), (ICompositeNode) node);
		} else if (rc.getRule() instanceof EnumRule)
			acceptUnassignedEnum(rc, node.getText(), (ICompositeNode) node);
	} else if (ge instanceof Action)
		acceptUnassignedAction((Action) ge);
	else
		throw new RuntimeException("Unexpected grammar element: " + node.getGrammarElement());
}
 
Example 4
Source File: FormatterTestValueConverters.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@ValueConverter(rule = "FQN")
public IValueConverter<String> FQN() {
	return new AbstractNullSafeConverter<String>() {
		@Override
		protected String internalToString(String value) {
			return value;
		}

		@Override
		protected String internalToValue(String string, INode node) {
			if (!string.equals(string.trim()))
				throw new RuntimeException();
			StringBuffer b = new StringBuffer();
			for (ILeafNode leaf : node.getLeafNodes()) {
				if (!leaf.isHidden()) {
					b.append(leaf.getText());
				}
			}
			return b.toString();
		}
	};
}
 
Example 5
Source File: DefaultSemanticHighlightingCalculator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Highlights the non-hidden parts of {@code node} with the styles given by the {@code styleIds}
 */
protected void highlightNode(IHighlightedPositionAcceptor acceptor, INode node, String... styleIds) {
	if (node == null)
		return;
	if (node instanceof ILeafNode) {
		ITextRegion textRegion = node.getTextRegion();
		acceptor.addPosition(textRegion.getOffset(), textRegion.getLength(), styleIds);
	} else {
		for (ILeafNode leaf : node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				ITextRegion leafRegion = leaf.getTextRegion();
				acceptor.addPosition(leafRegion.getOffset(), leafRegion.getLength(), styleIds);
			}
		}
	}
}
 
Example 6
Source File: NodeModelUtils.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method converts a node to text.
 * 
 * Leading and trailing text from hidden tokens (whitespace/comments) is removed. Text from hidden tokens that is
 * surrounded by text from non-hidden tokens is summarized to a single whitespace.
 * 
 * The preferred use case of this method is to convert the {@link ICompositeNode} that has been created for a data
 * type rule to text.
 * 
 * This is also the recommended way to convert a node to text if you want to invoke
 * {@link org.eclipse.xtext.conversion.IValueConverterService#toValue(String, String, INode)}
 * 
 */
public static String getTokenText(INode node) {
	if (node instanceof ILeafNode)
		return ((ILeafNode) node).getText();
	else {
		StringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));
		boolean hiddenSeen = false;
		for (ILeafNode leaf : node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				if (hiddenSeen && builder.length() > 0)
					builder.append(' ');
				builder.append(leaf.getText());
				hiddenSeen = false;
			} else {
				hiddenSeen = true;
			}
		}
		return builder.toString();
	}
}
 
Example 7
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 8
Source File: SemanticHighlighter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Highlights the non-hidden parts of {@code node} with the style that is associated with {@code id}.
 */
protected void highlightNode(INode node, String id, IHighlightedPositionAcceptor acceptor) {
	if (node == null)
		return;
	if (node instanceof ILeafNode) {
		ITextRegion textRegion = node.getTextRegion();
		acceptor.addPosition(textRegion.getOffset(), textRegion.getLength(), id);
	} else {
		for (ILeafNode leaf : node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				ITextRegion leafRegion = leaf.getTextRegion();
				acceptor.addPosition(leafRegion.getOffset(), leafRegion.getLength(), id);
			}
		}
	}
}
 
Example 9
Source File: DefaultImportsConfiguration.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getLegacyImportSyntax(XImportDeclaration importDeclaration) {
	List<INode> list = NodeModelUtils.findNodesForFeature(importDeclaration, XtypePackage.Literals.XIMPORT_DECLARATION__IMPORTED_TYPE);
	if (list.isEmpty()) {
		return null;
	}
	INode singleNode = list.get(0);
	if (singleNode.getText().indexOf('$') < 0) {
		return null;
	}
	StringBuilder sb = new StringBuilder();
	for(ILeafNode node: singleNode.getLeafNodes()) {
		if (!node.isHidden()) {
			sb.append(node.getText().replace("^", ""));
		}
	}
	return sb.toString();
}
 
Example 10
Source File: XAbstractFeatureCallImplCustom.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getConcreteSyntaxFeatureName() {
	List<INode> list = NodeModelUtils.findNodesForFeature(this, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
	if (list.size()!=1) {
		if (feature == null || feature.eIsProxy())
			return "<unkown>";
		return String.format("<implicit: %s>", feature.getIdentifier());
	}
	INode node = list.get(0);
	if (node instanceof ILeafNode) {
		return node.getText();
	}
	StringBuilder result = new StringBuilder();
	for(ILeafNode leafNode: node.getLeafNodes()) {
		if (!leafNode.isHidden())
			result.append(leafNode.getText());
	}
	return result.toString();
}
 
Example 11
Source File: GamlSemanticHighlightingCalculator.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private final boolean setStyle(final EObject obj, final String s, final int position) {
	// position = -1 for all the node; 0 for the first leaf node, 1 for the
	// second one, etc.
	if (obj != null && s != null) {
		INode n = NodeModelUtils.getNode(obj);
		if (n == null) { return false; }
		if (position > -1) {
			int i = 0;
			for (final ILeafNode node : n.getLeafNodes()) {
				if (!node.isHidden()) {
					if (position == i) {
						n = node;
						break;
					}
					i++;
				}
			}
		}
		return setStyle(s, n);
	}
	return false;
}
 
Example 12
Source File: SemanticHighlightingCalculator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Highlights a given parse tree node.
 *
 * @param node
 *          the node from the parse tree
 * @param id
 *          the id of the configuration
 * @param acceptor
 *          the acceptor
 */
private void highlightNode(final INode node, final String id, final IHighlightedPositionAcceptor acceptor) {
  if (node == null) {
    return;
  }
  if (node instanceof ILeafNode) {
    acceptor.addPosition(node.getOffset(), node.getLength(), id);
  } else {
    for (ILeafNode leaf : node.getLeafNodes()) {
      if (!leaf.isHidden()) {
        acceptor.addPosition(leaf.getOffset(), leaf.getLength(), id);
      }
    }
  }
}
 
Example 13
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 14
Source File: MultiLineJavaDocTypeReferenceProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<ReplaceRegion> computeTypeRefRegions(INode node) {
	List<ReplaceRegion> regions = Lists.newArrayList();
	Iterable<ILeafNode> leafNodes = node.getLeafNodes();
	computeRegions(regions, leafNodes, LINK_TAG_WITH_SUFFIX, new String[]{"#", " ", "}"});
	computeRegions(regions, leafNodes, SEE_TAG_WITH_SUFFIX, new String[]{"#" , " ", "\r", "\n"});
	return regions;
}
 
Example 15
Source File: MultiLineJavaDocTypeReferenceProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<ReplaceRegion> computeParameterTypeRefRegions(INode node) {
	List<ReplaceRegion> regions = Lists.newArrayList();
	Iterable<ILeafNode> leafNodes = node.getLeafNodes();
	computeRegions(regions, leafNodes, "@param ", new String[]{" ", "-", "\r", "\n"});
	return regions;
}
 
Example 16
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 17
Source File: FeatureCallAsTypeLiteralHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected List<String> getTypeNameSegmentsFromConcreteSyntax(List<INode> nodes, boolean staticNotation) {
	List<String> result = null;
	for(INode node: nodes) {
		for(ILeafNode leaf: node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				String text = leaf.getText();
				// XParenthesizedExpression
				if (text.equals("(") || text.equals(")")) {
					return null;
				}
				if (text.equals(".")) {
					if (staticNotation) {
						return null;
					}
				}
				if (text.equals("::")) {
					if (!staticNotation) {
						return null;
					}
				}
				if (!text.equals(".") && !text.equals("::")) {
					if (result == null) {
						result = Lists.newArrayListWithCapacity(4);
					}
					if (text.charAt(0) == '^') {
						result.add(text.substring(1));
					} else {
						result.add(text);
					}
				}
			}
		}
	}
	return result;
}
 
Example 18
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 19
Source File: XbaseQualifiedNameValueConverter.java    From xtext-extras 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(INode child: node.getAsTreeIterable()) {
			EObject grammarElement = child.getGrammarElement();
			if (isDelegateRuleCall(grammarElement) || isWildcardLiteral(grammarElement)) {
				if (!isFirst)
					buffer.append(getValueNamespaceDelimiter());
				isFirst = false;
				if (isDelegateRuleCall(grammarElement))
					for(ILeafNode leafNode :child.getLeafNodes()){
						if(!leafNode.isHidden())
							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 20
Source File: NodeModelBasedRegionAccessBuilder.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected void process(INode node, NodeModelBasedRegionAccess access) {
	NodeEObjectRegion tokens = stack.peek();
	boolean creator = isEObjectRoot(node);
	if (creator || tokens == null) {
		tokens = createTokens(access, node);
		tokens.setLeadingHiddenRegion(lastHidden);
		NodeEObjectRegion parent = stack.peek();
		if (parent != null) {
			parent.addChild(tokens);
		}
		stack.push(tokens);
	}
	if (tokens.getSemanticElement() == null) {
		if (node.getParent() == null) {
			tokens.setSemanticElement(resource.getContents().get(0));
			EObject element = node.getGrammarElement();
			if (element instanceof Action)
				element = ((ICompositeNode) node).getFirstChild().getGrammarElement();
			tokens.setGrammarElement(element);
		} else if (node.hasDirectSemanticElement()) {
			tokens.setSemanticElement(node.getSemanticElement());
			tokens.setGrammarElement(findGrammarElement(node, tokens.getSemanticElement()));
		}
	}
	if (include(node)) {
		if (node instanceof ICompositeNode) {
			for (ILeafNode leaf : node.getLeafNodes())
				if (leaf.isHidden())
					this.add(access, leaf);
				else
					break;
		}
		this.add(access, node);
	} else if (node instanceof ICompositeNode) {
		for (INode child : ((ICompositeNode) node).getChildren())
			process(child, access);
	}
	if (creator) {
		NodeEObjectRegion popped = stack.pop();
		popped.setTrailingHiddenRegion(lastHidden);
		EObject semanticElement = popped.getSemanticElement();
		if (semanticElement == null)
			throw new IllegalStateException();
		if (!stack.isEmpty() && semanticElement.eContainer() != stack.peek().getSemanticElement())
			throw new IllegalStateException();
		EObject grammarElement = popped.getGrammarElement();
		if (grammarElement == null) {
			throw new IllegalStateException();
		}
		NodeEObjectRegion old = eObjToTokens.put(semanticElement, popped);
		if (old != null)
			throw new IllegalStateException();
	}
}