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

The following examples show how to use org.eclipse.xtext.nodemodel.ILeafNode#isHidden() . 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: 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 2
Source File: XtextLabelProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private String getLabel(RuleCall ruleCall) {
	if (ruleCall.getRule() != null) {
		return ruleCall.getRule().getName();
	}
	ICompositeNode node = NodeModelUtils.getNode(ruleCall);
	String ruleName = UNKNOWN;
	if (node != null) {
		for (ILeafNode leaf : node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				ruleName = leaf.getText();
				break;
			}
		}
	}
	return ruleName;
}
 
Example 3
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 4
Source File: ImportsCollector.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Collects import declarations in XtextResource for the given range (selectedRegion)
 */
public void collectImports(final XtextResource state, final ITextRegion selectedRegion, final ImportsAcceptor acceptor) {
  ICompositeNode rootNode = state.getParseResult().getRootNode();
  final EObject selectedSemanticObj = this.findActualSemanticObjectFor(rootNode, selectedRegion);
  final Iterable<ILeafNode> contentsIterator = NodeModelUtils.findActualNodeFor(selectedSemanticObj).getLeafNodes();
  for (final ILeafNode node : contentsIterator) {
    {
      final ITextRegion nodeRegion = node.getTotalTextRegion();
      boolean _contains = selectedRegion.contains(nodeRegion);
      if (_contains) {
        final EObject semanticElement = node.getSemanticElement();
        if ((semanticElement != null)) {
          this.visit(semanticElement, NodeModelUtils.findActualNodeFor(semanticElement), acceptor);
        }
      }
      if ((node.isHidden() && this.grammarAccess.getML_COMMENTRule().equals(node.getGrammarElement()))) {
        this.addJavaDocReferences(node, selectedRegion, acceptor);
      }
    }
  }
}
 
Example 5
Source File: HiddenLeafAccess.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public HiddenLeafs getHiddenLeafsAfter(final INode node) {
  HiddenLeafs _xblockexpression = null;
  {
    final Function1<ILeafNode, Boolean> _function = (ILeafNode it) -> {
      boolean _isHidden = it.isHidden();
      return Boolean.valueOf((!_isHidden));
    };
    final ILeafNode start = this.findPreviousLeaf(node, _function);
    HiddenLeafs _xifexpression = null;
    if ((start != null)) {
      _xifexpression = this.newHiddenLeafs(start.getEndOffset(), this.findNextHiddenLeafs(start));
    } else {
      int _offset = 0;
      if (node!=null) {
        _offset=node.getOffset();
      }
      _xifexpression = new HiddenLeafs(_offset);
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
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: 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 8
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 9
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 10
Source File: AbstractNode.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public int getOffset() {
	Iterator<ILeafNode> leafIter = Iterators.filter(basicIterator(), ILeafNode.class);
	int firstLeafOffset = -1;
	while(leafIter.hasNext()) {
		ILeafNode leaf = leafIter.next();
		if (firstLeafOffset == -1) {
			firstLeafOffset = leaf.getTotalOffset();
		}
		if (!leaf.isHidden())
			return leaf.getTotalOffset();
	}
	if (firstLeafOffset != -1)
		return firstLeafOffset;
	return getTotalOffset();
}
 
Example 11
Source File: FeatureCallCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isDeclaredInNewLine(XExpression obj) {
	ICompositeNode node = NodeModelUtils.getNode(obj);
	if (node != null) {
		int line = -1;
		for(ILeafNode n : node.getLeafNodes()) {
			if (n.isHidden() && line == -1)
				line = n.getStartLine();
			if (!n.isHidden() && line != -1)
				return line != n.getStartLine();
		}
	}
	return false;
}
 
Example 12
Source File: EntryPointFinder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected ICompositeNode findEntryPoint(ICompositeNode node, int offset) {
	ICompositeNode result = node;
	result = getApplicableNode(result);
	while (result != null) {
		int remainingLookAhead = result.getLookAhead();
		if (remainingLookAhead != 0) {
			Iterator<ILeafNode> leafNodes = result.getLeafNodes().iterator();
			while (leafNodes.hasNext() && remainingLookAhead > 0) {
				ILeafNode leaf = leafNodes.next();
				if (leaf.getTotalOffset() >= offset) {
					break;
				}
				if (!leaf.isHidden()) {
					if (remainingLookAhead > 0) {
						remainingLookAhead--;
					}
					if (remainingLookAhead == 0) {
						if (shouldUseParent(result, offset, leaf)) {
							ICompositeNode parent = result.getParent();
							return parent;
						}
						return result;
					}
				}
			}
		}
		result = getApplicableNode(result.getParent());
	}
	return result;
}
 
Example 13
Source File: ParameterContextInformationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected String getCalledFeatureName(XExpression call) {
	StringBuilder b = new StringBuilder();
	for (INode node : NodeModelUtils.findNodesForFeature(call, getCalledFeatureReference(call))) {
		for (ILeafNode leafNode : node.getLeafNodes()) {
			if (!leafNode.isHidden()) 
				b.append(leafNode.getText());
		}
	}
	return b.toString();
}
 
Example 14
Source File: XbaseHighlightingCalculator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void highlightSpecialIdentifiers(IHighlightedPositionAcceptor acceptor, ICompositeNode root) {
	TerminalRule idRule = getIDRule();
	for (ILeafNode leaf : root.getLeafNodes()) {
		if (!leaf.isHidden()) {
			highlightSpecialIdentifiers(leaf, acceptor, idRule);
		}
	}
}
 
Example 15
Source File: ParserBasedContentAssistContextFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public boolean doComputePrefix(ICompositeNode node, StringBuilder result) {
	List<ILeafNode> hiddens = Lists.newArrayListWithCapacity(2);
	for (INode child : node.getChildren()) {
		if (child instanceof ICompositeNode) {
			if (!doComputePrefix((ICompositeNode) child, result))
				return false;
		}
		else {
			ILeafNode leaf = (ILeafNode) child;
			ITextRegion leafRegion = leaf.getTextRegion();
			if (leafRegion.getOffset() > completionOffset)
				return false;
			if (leaf.isHidden()) {
				if (result.length() != 0)
					hiddens.add((ILeafNode) child);
			}
			else {
				Iterator<ILeafNode> iter = hiddens.iterator();
				while (iter.hasNext()) {
					result.append(iter.next().getText());
				}
				hiddens.clear();
				result.append(getNodeTextUpToCompletionOffset(leaf));
				if (leafRegion.getOffset() + leafRegion.getLength() > completionOffset)
					return false;
			}
		}
	}
	return true;
}
 
Example 16
Source File: AbstractXtextTestUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Given an AST node, find the first non-hidden leaf node among child nodes using deep search.
 * For the sake of compatibility the method can handle LeafNodes and CompositeNodes.
 * In case of a LeafNode the result is the input node itself.
 *
 * @param node
 *          entry point
 * @return
 *         first node for which isHidden() is false or the original node
 */
public INode findFirstNonHiddenLeafNode(final INode node) {
  if (node instanceof ICompositeNode) {
    for (ILeafNode leaf : node.getLeafNodes()) {
      if (!leaf.isHidden()) {
        return leaf;
      }
    }
  }
  return node;
}
 
Example 17
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 18
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();
	}
}
 
Example 19
Source File: IndentationAwareCompletionPrefixProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected INode findBestEndToken(INode root, INode candidate, int completionColumn, boolean candidateIsEndToken) {
	LinkedList<ILeafNode> sameGrammarElement = Lists.newLinkedList();
	PeekingIterator<ILeafNode> iterator = createReversedLeafIterator(root, candidate, sameGrammarElement);
	if (!iterator.hasNext()) {
		return candidate;
	}
	// collect all candidates that belong to the same offset
	LinkedList<ILeafNode> sameOffset = candidateIsEndToken ? collectLeafsWithSameOffset((ILeafNode)candidate, iterator) : Lists.newLinkedList();
	// continue until we find a paired leaf with length 0 that is at the correct offset
	EObject grammarElement = tryGetGrammarElementAsRule(candidateIsEndToken || sameGrammarElement.isEmpty() ? candidate : sameGrammarElement.getLast()); 
	ILeafNode result = candidateIsEndToken ? null : (ILeafNode) candidate;
	int sameOffsetSize = sameOffset.size();
	while(iterator.hasNext()) {
		ILeafNode next = iterator.next();
		if (result == null || result.isHidden()) {
			result = next;
		}
		if (next.getTotalLength() == 0) {
			// potential indentation token
			EObject rule = tryGetGrammarElementAsRule(next);
			if (rule != grammarElement) {
				LineAndColumn lineAndColumn = NodeModelUtils.getLineAndColumn(root, next.getTotalOffset());
				if (lineAndColumn.getColumn() <= completionColumn) {
					return result;
				} else {
					if (sameOffset.isEmpty()) {
						if (sameGrammarElement.isEmpty()) {
							result = null;	
						} else {
							result = sameGrammarElement.removeLast();
						}
						
					} else {
						if (sameOffsetSize >= sameOffset.size()) {
							result = sameOffset.removeLast();	
						} else {
							sameOffset.removeLast();
						}
					}
				}
			} else {
				sameOffset.add(next);
			}
		}
	}
	return candidate;
}
 
Example 20
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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;
}