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

The following examples show how to use org.eclipse.xtext.nodemodel.INode#getTotalOffset() . 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: ReorderingHiddenTokenSequencer.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Helper method that collects all the hidden tokens that follow the given node.
 *
 * @param from
 *          starting point in the node model, must not be {@code null}
 * @param deletedSemanticElements
 *          set of semantic elements that have been deleted from the model, must not be {@code null}
 * @return list of hidden tokens, never {@code null}, can be empty
 */
private List<INode> getFollowingHiddenTokens(final INode from, final Set<EObject> deletedSemanticElements) {
  List<INode> result = Lists.newArrayList();
  NodeIterator nodes = new NodeIterator(from);
  while (nodes.hasNext()) {
    INode next = nodes.next();
    if (next.getTotalOffset() > rootEndOffset || next.equals(lastEmittedNode)) {
      break;
    } else if (tokenUtil.isWhitespaceOrCommentNode(next)) {
      if (!emittedComments.contains(next)) {
        result.add(next);
      }
    } else if (belongsToDeletedElement(next)) {
      handleDeletedElement(result, deletedSemanticElements, next);
      nodes.prune();
    } else {
      break;
    }
  }
  return result;
}
 
Example 2
Source File: HiddenTokenSequencer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected List<INode> getRemainingHiddenNodesInContainer(INode from, INode root) {
	if (from == null || root == null)
		return Collections.emptyList();
	List<INode> out = Lists.newArrayList();
	NodeIterator ni = new NodeIterator(from);
	while (ni.hasNext()) {
		INode next = ni.next();
		if (next.getTotalOffset() > root.getTotalEndOffset())
			return out;
		else if (tokenUtil.isWhitespaceOrCommentNode(next)) {
			out.add(next);
		} else if (tokenUtil.isToken(next))
			return Collections.emptyList();
	}
	return out;
}
 
Example 3
Source File: EObjectAtOffsetHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected EObject resolveCrossReferencedElement(INode node) {
	EObject referenceOwner = NodeModelUtils.findActualSemanticObjectFor(node);
	if (referenceOwner != null) {
		EReference crossReference = GrammarUtil.getReference((CrossReference) node.getGrammarElement(),
				referenceOwner.eClass());
		if (!crossReference.isMany()) {
			return (EObject) referenceOwner.eGet(crossReference);
		} else {
			List<?> listValue = (List<?>) referenceOwner.eGet(crossReference);
			List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(referenceOwner, crossReference);
			int currentIndex = 0;
			for (INode nodeForFeature : nodesForFeature) {
				if (currentIndex >= listValue.size())
					return null;
				if (nodeForFeature.getTotalOffset() <= node.getTotalOffset()
						&& nodeForFeature.getTotalEndOffset() >= node.getTotalEndOffset())
					return (EObject) listValue.get(currentIndex);
				currentIndex++;
			}
		}
	}
	return null;
}
 
Example 4
Source File: DotStyleValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBasedWarning(String issueCode, String message,
		StyleItem styleItem) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(styleItem,
			StylePackage.Literals.STYLE_ITEM__NAME);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	// the issueData will be evaluated by the quickfixes
	List<String> issueData = new ArrayList<>();
	issueData.add(issueCode);
	issueData.add(styleItem.getName());
	issueData.addAll(styleItem.getArgs());

	getMessageAcceptor().acceptWarning(message, styleItem, offset, length,
			issueCode, issueData.toArray(new String[0]));
}
 
Example 5
Source File: DotStyleValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBaseError(String issueCode, String message,
		StyleItem styleItem, Context attributeContext) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(styleItem,
			StylePackage.Literals.STYLE_ITEM__NAME);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	// the issueData will be evaluated by the quickfixes
	String[] issueData = { issueCode, styleItem.getName(),
			attributeContext.toString() };
	getMessageAcceptor().acceptError(message, styleItem, offset, length,
			issueCode, issueData);
}
 
Example 6
Source File: DotHtmlLabelValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBasedError(String issueCode, String message,
		EObject object, EStructuralFeature feature, String[] issueData) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(object, feature);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	getMessageAcceptor().acceptError(message, object, offset, length,
			issueCode, issueData);
}
 
Example 7
Source File: RegExLiteralConverter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private static StringConverterResult convertFromJS(String jsString, INode node) {
	StringConverterResult result = ValueConverterUtils.convertFromEscapedString(jsString, false, true, false, null);
	if (result.hasError()) {
		int offsetFixup = node.getOffset() - node.getTotalOffset();
		throw new N4JSValueConverterWithValueException(
				IssueCodes.getMessageForVCO_REGEX_ILLEGAL_ESCAPE(jsString),
				IssueCodes.VCO_REGEX_ILLEGAL_ESCAPE, node, result.getErrorOffset() + offsetFixup, 1,
				result.getValue(), null);
	}
	return result;
}
 
Example 8
Source File: ProposalConflictHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public boolean existsConflict(INode lastCompleteNode, int offset, String proposal, ContentAssistContext context) {
	String lastCompleteText = lastCompleteNode.getText();
	int endOffset = offset - lastCompleteNode.getTotalOffset();
	lastCompleteText = lastCompleteText.substring(0, Math.max(endOffset, 0));
	if (Strings.isEmpty(lastCompleteText))
		return false;
	return existsConflict(lastCompleteText, proposal, context);
}
 
Example 9
Source File: LeafNodeFinder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.13
 */
protected boolean matchesSearchCriteria(INode object) {
	if (leading) {
		if (object.getTotalOffset() < offset && object.getTotalLength() + object.getTotalOffset() >= offset) {
			return true;
		}
	} else {
		if (object.getTotalOffset() <= offset && object.getTotalLength() + object.getTotalOffset() > offset) {
			return true;
		}
	}
	return object.getTotalOffset() == offset && object.getTotalLength() == 0;
}
 
Example 10
Source File: DotArrowTypeValidator.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
private void reportRangeBasedWarning(String issueCode, String message,
		EObject object, EStructuralFeature feature) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(object, feature);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	String code = null;
	// the issueData will be evaluated by the quickfixes
	List<String> issueData = new ArrayList<>();
	issueData.add(issueCode);
	switch (issueCode) {
	case DEPRECATED_ARROW_SHAPE:
		DeprecatedArrowShape arrowShape = (DeprecatedArrowShape) object;
		issueData.add(arrowShape.getShape().toString());
		break;
	case INVALID_ARROW_SHAPE_MODIFIER:
		if (ArrowtypePackage.Literals.ARROW_SHAPE__OPEN == feature) {
			issueData.add("o");
		}
		if (ArrowtypePackage.Literals.ARROW_SHAPE__SIDE == feature) {
			issueData.add(((ArrowShape) object).getSide());
		}
		issueData.add(Integer.toString(offset));
	default:
		break;
	}

	getMessageAcceptor().acceptWarning(message, object, offset, length,
			code, issueData.toArray(new String[0]));
}
 
Example 11
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isInMemberFeatureCall(EObject model, int endOffset, ContentAssistContext context) {
	if (model instanceof XMemberFeatureCall && endOffset >= context.getOffset()) {
		List<INode> featureNodes = NodeModelUtils.findNodesForFeature(model, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
		if (!featureNodes.isEmpty()) {
			INode featureNode = featureNodes.get(0);
			if (featureNode.getTotalOffset() < context.getOffset() && featureNode.getTotalEndOffset() >= context.getOffset()) {
				return true;
			}
		}
	}
	return false;
}
 
Example 12
Source File: ProposalConflictHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public boolean existsConflict(INode lastCompleteNode, int offset, String proposal, ContentAssistContext context) {
	String lastCompleteText = lastCompleteNode.getText();
	int endOffset = offset - lastCompleteNode.getTotalOffset();
	lastCompleteText = lastCompleteText.substring(0, Math.max(endOffset, 0));
	if (Strings.isEmpty(lastCompleteText))
		return false;
	return existsConflict(lastCompleteText, proposal, context);
}
 
Example 13
Source File: ArithmeticsCodeMiningProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createCodeMinings(IDocument document, XtextResource resource, CancelIndicator indicator,
	IAcceptor<? super ICodeMining> acceptor) throws BadLocationException {

	EList<EObject> contents = resource.getContents();
	if (contents.isEmpty()) {
		return;
	}

	// get all evaluations contained by the open document
	List<Evaluation> allEvaluations = EcoreUtil2.eAllOfType(contents.get(0), Evaluation.class);

	// get keyword for ';'
	Keyword semicolon = grammar.getEvaluationAccess().getSemicolonKeyword_1();

	for (Evaluation evaluation : allEvaluations) {
		ICompositeNode node = NodeModelUtils.findActualNodeFor(evaluation);
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			INode child = it.next();
			if (semicolon.equals(child.getGrammarElement())) {
				int annotationOffset = child.getTotalOffset();
				String annotationText = getAnnotationText(evaluation);
				acceptor.accept(createNewLineContentCodeMining(annotationOffset, annotationText));
			}
		}
	}
}
 
Example 14
Source File: XbaseIdeContentProposalProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isInMemberFeatureCall(final EObject model, final int endOffset, final ContentAssistContext context) {
  if (((model instanceof XMemberFeatureCall) && (endOffset >= context.getOffset()))) {
    final List<INode> featureNodes = NodeModelUtils.findNodesForFeature(model, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
    boolean _isEmpty = featureNodes.isEmpty();
    boolean _not = (!_isEmpty);
    if (_not) {
      final INode featureNode = IterableExtensions.<INode>head(featureNodes);
      if (((featureNode.getTotalOffset() < context.getOffset()) && 
        (featureNode.getTotalEndOffset() >= context.getOffset()))) {
        return true;
      }
    }
  }
  return false;
}
 
Example 15
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * If a type declaration has Java-form such as 'int foo() {}', then the following quickfix proposed which transforms
 * it to colon style: 'foo(): int {}' It searches the bogus return type (which is 'int' in the example above)
 * beginning from the parent node (N4MethodDeclarationImpl) of the method declaration. The bogus return type removed
 * from the old position. A colon followed by the bogus return type added to the right side of the method name.
 */
@Fix(IssueCodes.TYS_INVALID_TYPE_SYNTAX)
public void transformJavaTypeAnnotationToColonStyle(QuickfixContext context, ICodeActionAcceptor acceptor) {
	EObject element = getEObject(context);
	if (!(element instanceof ParameterizedTypeRef)) {
		return;
	}
	ParameterizedTypeRef typeRef = (ParameterizedTypeRef) element;
	if (!(typeRef.eContainer() instanceof N4MethodDeclaration)) {
		return;
	}
	ICompositeNode node = NodeModelUtils.getNode(element);
	ICompositeNode parentNode = findParentNodeWithSemanticElementOfType(node, N4MethodDeclaration.class);
	INode roundBracketNode = NodeModelUtilsN4.findKeywordNode(parentNode, ")");
	List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(parentNode.getSemanticElement(),
			N4JSPackage.Literals.TYPED_ELEMENT__BOGUS_TYPE_REF);

	if (nodesForFeature.isEmpty()) {
		return;
	}

	INode bogusNode = nodesForFeature.get(0);
	Document doc = context.options.getDocument();
	String stringOfBogusType = NodeModelUtilsN4.getTokenTextWithHiddenTokens(bogusNode);
	ILeafNode nodeAfterBogus = NodeModelUtils.findLeafNodeAtOffset(parentNode, bogusNode.getEndOffset());
	int spaceAfterBogusLength = (nodeAfterBogus != null && nodeAfterBogus.getText().startsWith(" ")) ? 1 : 0;
	int offsetBogusType = bogusNode.getOffset();
	int bogusTypeLength = stringOfBogusType.length();
	int offsetRoundBracket = roundBracketNode.getTotalOffset();

	List<TextEdit> textEdits = new ArrayList<>();
	// inserts the bogus type at the new location (behind the closing round bracket)
	textEdits.add(replace(doc, offsetRoundBracket + 1, 0, ": " + stringOfBogusType));
	// removes the bogus type and whitespace at the old location
	textEdits.add(replace(doc, offsetBogusType, bogusTypeLength + spaceAfterBogusLength, ""));

	acceptor.acceptQuickfixCodeAction(context, "Convert to colon style", textEdits);
}
 
Example 16
Source File: NodeModelUtils.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Find the leaf node at the given offset. May return <code>null</code> if the given offset is not valid for the
 * node (sub-)tree.
 * 
 * A node matches the <code>leafNodeOffset</code> if it fulfills the following condition:
 * <pre>
 *  node.totalOffset &lt;= leafNodeOffset &amp;&amp;
 *  node.totalEndOffset &gt; leafNodeOffset 
 * </pre>
 * 
 * @param node the container node. May not be <code>null</code>.
 * @param leafNodeOffset the offset that is covered by the searched node.
 * @return the leaf node at the given offset or <code>null</code>.
 */
/* @Nullable */
public static ILeafNode findLeafNodeAtOffset(/* @NonNull */ INode node, int leafNodeOffset) {
	INode localNode = node;
	while(!(localNode instanceof AbstractNode)) {
		localNode = localNode.getParent();
	}
	int offset = localNode.getTotalOffset();
	int length = localNode.getTotalLength();
	BidiTreeIterator<AbstractNode> iterator = ((AbstractNode) localNode).basicIterator();
	if (leafNodeOffset > (offset + length) / 2) {
		while (iterator.hasPrevious()) {
			AbstractNode previous = iterator.previous();
			int previousOffset = previous.getTotalOffset();
			int previousLength = previous.getTotalLength();
			if (!intersects(previousOffset, previousLength, leafNodeOffset)) {
				if (previousOffset + previousLength <= leafNodeOffset) {
					return null;
				}
				iterator.prune();
			} else {
				if (previous instanceof ILeafNode)
					return (ILeafNode) previous;
			}
		}
	} else {
		while (iterator.hasNext()) {
			AbstractNode next = iterator.next();
			int nextOffset = next.getTotalOffset();
			int nextLength = next.getTotalLength();
			if (!intersects(nextOffset, nextLength, leafNodeOffset)) {
				if (nextOffset > leafNodeOffset) {
					return null;
				}
				iterator.prune();
			} else {
				if (next instanceof ILeafNode)
					return (ILeafNode) next;
			}
		}
	}
	return null;
}
 
Example 17
Source File: Range.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public Range(INode node) {
	this(node.getTotalOffset(), node.getTotalEndOffset());
}
 
Example 18
Source File: ReorderingHiddenTokenSequencer.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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;
}