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

The following examples show how to use org.eclipse.xtext.nodemodel.ILeafNode#getOffset() . 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: SemanticChangeProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the offset to place the @Internal annotation in the same line
 */
private int internalAnnotationOffset(ModifiableElement element) {
	if (!(element instanceof AnnotableElement)) {
		throw new IllegalArgumentException("Can't compute @Internal offset for non-annotable element");
	}

	// If element is exported put the @Internal annotation in front of the export keyword
	// Otherwise place it in front of the modifiers

	EObject containerExportDeclaration = element.eContainer();
	if (containerExportDeclaration instanceof ExportDeclaration) {
		ILeafNode node = nodeModelAccess.nodeForKeyword(containerExportDeclaration,
				N4JSLanguageConstants.EXPORT_KEYWORD);
		if (node != null) {
			return node.getOffset();
		} else {
			throw new NullPointerException("Failed to retrieve node for export keyword");
		}
	} else {
		return modifierOffset(element);
	}
}
 
Example 2
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
private void addAbstractKeyword(XtendTypeDeclaration typeDeclaration, IXtextDocument document,
		String declarationKeyword) throws BadLocationException {
	final ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(typeDeclaration);
	if (clazzNode == null) {
		throw new IllegalStateException("Cannot determine node for the type declaration" //$NON-NLS-1$
				+ typeDeclaration.getName());
	}
	int offset = -1;
	final Iterator<ILeafNode> nodes = clazzNode.getLeafNodes().iterator();
	while (offset == -1 && nodes.hasNext()) {
		final ILeafNode leafNode  = nodes.next();
		if (leafNode.getText().equals(declarationKeyword)) {
			offset = leafNode.getOffset();
		}
	}
	final ReplacingAppendable appendable = this.appendableFactory.create(document,
			(XtextResource) typeDeclaration.eResource(),
			offset, 0);
	appendable.append(getGrammarAccess()
			.getAbstractKeyword())
			.append(" "); //$NON-NLS-1$
	appendable.commitChanges();
}
 
Example 3
Source File: AbstractHyperlinkHelperTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the offset for given text by analyzing the parse tree and looking for leaf nodes having
 * a text attribute matching given value. Returns the first instance found and an error value if
 * no match found.
 *
 * @param model
 *          the model
 * @param text
 *          the text
 * @return the offset for text
 */
protected int getOffsetForText(final EObject model, final String text) {
  Iterable<ILeafNode> parseTreeNodes = NodeModelUtils.getNode(model).getLeafNodes();

  try {
    ILeafNode result = Iterables.find(parseTreeNodes, new Predicate<ILeafNode>() {
      @Override
      public boolean apply(final ILeafNode input) {
        return text.equals(input.getText());
      }
    });
    return result.getOffset();
  } catch (NoSuchElementException e) {
    return LEAF_NOT_FOUND_VALUE;
  }
}
 
Example 4
Source File: AbstractSyntaxColoringTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the offset for given text by analyzing the parse tree and looking for leaf nodes having
 * a text attribute matching given value. Returns the first instance found and an error value if
 * no match found.
 *
 * @param model
 *          the model
 * @param text
 *          the text
 * @return the offset for text
 */
public static int getOffsetForText(final EObject model, final String text) {
  Iterable<ILeafNode> parseTreeNodes = NodeModelUtils.getNode(model).getLeafNodes();

  try {
    ILeafNode result = Iterables.find(parseTreeNodes, new Predicate<ILeafNode>() {
      @Override
      public boolean apply(final ILeafNode input) {
        return text.equals(input.getText());
      }
    });
    return result.getOffset();
  } catch (NoSuchElementException e) {
    return LEAF_NOT_FOUND_VALUE;
  }
}
 
Example 5
Source File: DefaultNodeModelFormatter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String getIndentation(ICompositeNode root, int fromOffset) {
	if (fromOffset == 0)
		return "";

	List<ILeafNode> r = new ArrayList<ILeafNode>();
	// add all nodes until fromOffset
	for(ILeafNode l: root.getLeafNodes()) {
		if (l.getOffset() >= fromOffset)
			break;
		else
			r.add(l);
	}

	// go backwards until first linewrap
	Pattern p = Pattern.compile("(\\n|\\r)([ \\t]*)");
	for (int i = r.size() - 1; i >= 0; i--) {
		Matcher m = p.matcher(r.get(i).getText());
		if (m.find()) {
			String ind = m.group(2);
			while (m.find())
				ind = m.group(2);
			return ind;
		}
	}
	return "";
}
 
Example 6
Source File: EObjectAtOffsetHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected EObject internalResolveElementAt(XtextResource resource, int offset, boolean containment) {
	if(!containment) {
		EObject crossRef = resolveCrossReferencedElementAt(resource, offset);
		if (crossRef != null)
			return crossRef;
	}
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
		if (leaf != null && leaf.isHidden() && leaf.getOffset() == offset) {
			leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
		}
		if (leaf != null) {
			return NodeModelUtils.findActualSemanticObjectFor(leaf);
		}
	}
	return null;
}
 
Example 7
Source File: EObjectAtOffsetHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.1
 */
public INode getCrossReferenceNode(XtextResource resource, ITextRegion region) {
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), region.getOffset());
		INode crossRefNode = findCrossReferenceNode(leaf);
		// if not a cross reference position and the cursor is at the beginning of a node try the previous one.
		if (crossRefNode == null && leaf != null && region.getLength()==0 && leaf.getOffset() == region.getOffset()) {
			leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), region.getOffset() - 1);
			return findCrossReferenceNode(leaf);
		} else if (crossRefNode != null && crossRefNode.getEndOffset() >= region.getOffset() + region.getLength()) {
			return crossRefNode;
		}
	}
	return null;
}
 
Example 8
Source File: InsertionOffsets.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected int inEmpty(final XtendTypeDeclaration ownerType) {
  int _xblockexpression = (int) 0;
  {
    final ICompositeNode classNode = NodeModelUtils.findActualNodeFor(ownerType);
    final Function1<ILeafNode, Boolean> _function = (ILeafNode it) -> {
      String _text = it.getText();
      return Boolean.valueOf(Objects.equal(_text, "{"));
    };
    final ILeafNode openingBraceNode = IterableExtensions.<ILeafNode>findFirst(classNode.getLeafNodes(), _function);
    int _xifexpression = (int) 0;
    if ((openingBraceNode != null)) {
      int _offset = openingBraceNode.getOffset();
      _xifexpression = (_offset + 1);
    } else {
      _xifexpression = classNode.getEndOffset();
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example 9
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void internalDoAddAbstractKeyword(EObject element, IModificationContext context)
		throws BadLocationException {
	if (element instanceof XtendFunction) {
		element = element.eContainer();
	}
	if (element instanceof XtendClass) {
		XtendClass clazz = (XtendClass) element;
		IXtextDocument document = context.getXtextDocument();
		ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(clazz);
		if (clazzNode == null)
			throw new IllegalStateException("Cannot determine node for clazz " + clazz.getName());
		int offset = -1;
		for (ILeafNode leafNode : clazzNode.getLeafNodes()) {
			if (leafNode.getText().equals("class")) {
				offset = leafNode.getOffset();
				break;
			}
		}
		ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) clazz.eResource(),
				offset, 0);
		appendable.append("abstract ");
		appendable.commitChanges();
	}
}
 
Example 10
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private HtmlTag findOpenTag(XtextResource resource,
		DocumentCommand command) {
	if (!resource.getContents().isEmpty()) {
		EObject dotAst = resource.getContents().get(0);
		INode rootNode = NodeModelUtils.getNode(dotAst);
		int cursorPosition = command.offset;
		ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode,
				cursorPosition);

		String leafNodeText = leafNode.getText();

		String htmlLabelText = extractHtmlLabelContent(leafNodeText);

		if (htmlLabelText == null) {
			return null;
		}

		int htmlLabelStartOffset = leafNode.getOffset() + 1
				+ leafNodeText.substring(1).indexOf('<');
		int htmlLabelCursorPosition = cursorPosition - htmlLabelStartOffset;

		return findOpenTag(htmlLabelText, htmlLabelCursorPosition);

	}
	return null;
}
 
Example 11
Source File: N4JSSyntaxValidator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private boolean holdsCorrectOrderOfExtendsImplements(N4ClassDefinition semanticElement) {
	if (semanticElement.getSuperClassRef() == null || semanticElement.getImplementedInterfaceRefs().isEmpty()) {
		return true;
	}
	ICompositeNode node = NodeModelUtils.findActualNodeFor(semanticElement);
	if (node == null) {
		return true;
	}
	ILeafNode extendsNode = findLeafWithKeyword(semanticElement, "{", node, EXTENDS_KEYWORD, false);
	ILeafNode implementsNode = findLeafWithKeyword(semanticElement, "{", node, IMPLEMENTS_KEYWORD, false);
	if (extendsNode == null || implementsNode == null) {
		return true;
	}
	int extendsOffset = extendsNode.getOffset();
	int implementsOffset = implementsNode.getOffset();
	if (extendsOffset > implementsOffset) {
		String message = getMessageForSYN_KW_EXTENDS_IMPLEMENTS_WRONG_ORDER();
		addIssue(message, semanticElement, extendsOffset, EXTENDS_KEYWORD.length(),
				IssueCodes.SYN_KW_EXTENDS_IMPLEMENTS_WRONG_ORDER);
		return false;
	}
	return true;
}
 
Example 12
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 13
Source File: InsertionOffsets.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public int inEmpty(EObject element) {
	ICompositeNode compositeNode = NodeModelUtils.findActualNodeFor(element);
	for (ILeafNode leafNode : compositeNode.getLeafNodes()) {
		if ("{".equals(leafNode.getText())) {
			return leafNode.getOffset() + 1;
		}
	}
	return compositeNode.getEndOffset();
}
 
Example 14
Source File: XbaseHyperLinkHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isNameNode(EObject element, EStructuralFeature feature, ILeafNode node) {
	List<INode> nameNode = NodeModelUtils.findNodesForFeature(element, feature);
	for (INode iNode : nameNode) {
		if (iNode.getOffset() <= node.getOffset() && iNode.getLength()>= node.getLength()) {
			return true;
		}
	}
	return false;
}
 
Example 15
Source File: AbstractEObjectHover.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Call this method only from within an IUnitOfWork
 */
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource, final int offset) {
	// check for cross reference
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (!crossLinkedEObject.eIsProxy()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
				if(leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
					leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
				}
				if (leafNode != null) {
					ITextRegion leafRegion = leafNode.getTextRegion();
					return Tuples.create(crossLinkedEObject, (IRegion) new Region(leafRegion.getOffset(), leafRegion.getLength()));
				}
			}
		}
	} else {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
		if (o != null) {
			ITextRegion region = locationInFileProvider.getSignificantTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(), region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return null;
}
 
Example 16
Source File: HiddenLeafAccess.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public HiddenLeafs getHiddenLeafsBefore(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._nodeModelAccess.findNextLeaf(node, _function);
    final List<ILeafNode> nodes = this.findPreviousHiddenLeafs(start);
    HiddenLeafs _xifexpression = null;
    if ((start != null)) {
      int _xifexpression_1 = (int) 0;
      boolean _isEmpty = nodes.isEmpty();
      if (_isEmpty) {
        _xifexpression_1 = start.getOffset();
      } else {
        _xifexpression_1 = IterableExtensions.<ILeafNode>head(nodes).getOffset();
      }
      _xifexpression = this.newHiddenLeafs(_xifexpression_1, nodes);
    } else {
      int _offset = 0;
      if (node!=null) {
        _offset=node.getOffset();
      }
      _xifexpression = new HiddenLeafs(_offset);
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example 17
Source File: HoverService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected HoverContext createContext(Document document, XtextResource resource, int offset) {
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (crossLinkedEObject.eIsProxy()) {
			return null;
		}
		IParseResult parseResult = resource.getParseResult();
		if (parseResult == null) {
			return null;
		}
		ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
		if (leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
			leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
		}
		if (leafNode == null) {
			return null;
		}
		ITextRegion leafRegion = leafNode.getTextRegion();
		return new HoverContext(document, resource, offset, leafRegion, crossLinkedEObject);
	}
	EObject element = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
	if (element == null) {
		return null;
	}
	ITextRegion region = locationInFileProvider.getSignificantTextRegion(element);
	return new HoverContext(document, resource, offset, region, element);
}
 
Example 18
Source File: JSXIdentifierValueConverter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String toValue(String string, INode node) throws ValueConverterException {
	if (node != null) {
		Iterator<ILeafNode> leafNodes = node.getLeafNodes().iterator();
		while (leafNodes.hasNext()) {
			ILeafNode leading = leafNodes.next();
			// skip leading hidden nodes
			if (!leading.isHidden()) {
				ILeafNode first = leading;
				int firstOffset = first.getOffset();
				validate(string, firstOffset, first);
				while (leafNodes.hasNext()) {
					ILeafNode toBeChecked = leafNodes.next();
					validate(string, firstOffset, toBeChecked);
				}
			}
		}
	} else {
		int idx = disallowedChar.indexIn(string);
		if (idx != -1) {
			throw new N4JSValueConverterWithValueException(
					IssueCodes.getMessageForVCO_IDENT_ILLEGAL_CHAR_WITH_RESULT(string, string.charAt(idx), idx),
					IssueCodes.VCO_IDENT_ILLEGAL_CHAR_WITH_RESULT, node, string.substring(0, idx), null);
		}
	}
	return string;
}
 
Example 19
Source File: SemanticChangeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return the IChange to set the modifiers for the given Element. Replaces all modifiers with new ones.
 *
 * @param document
 *            Document to modify
 * @param element
 *            Element to modify
 * @param modifiers
 *            New modifiers
 */
TextEdit setModifiers(Document document, EObject element, String modifiers) {
	List<N4Modifier> declaredModifiers = (element instanceof ModifiableElement)
			? ((ModifiableElement) element).getDeclaredModifiers()
			: Collections.emptyList();

	String extra_whitespace = "";
	int delete_extra_whitespace = 0;
	int startOffset = modifierOffset(element);
	int endOffset = startOffset;

	// Calculate offset, length for all modifiers together
	if (declaredModifiers.size() > 0) {
		ILeafNode endNode = ModifierUtils.getNodeForModifier((ModifiableElement) element,
				declaredModifiers.size() - 1);
		endOffset = endNode.getOffset() + endNode.getLength();
	} else if (modifiers.length() > 0) { // spacing between declaration and modifier
		extra_whitespace = " ";
	}
	if (modifiers.length() == 0) {
		delete_extra_whitespace = 1;
	}

	int modifierLength = endOffset - startOffset + delete_extra_whitespace;

	return ChangeProvider.replace(document, startOffset, modifierLength, modifiers + extra_whitespace);
}
 
Example 20
Source File: MultiLineJavaDocTypeReferenceProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Computes regions between a given string to search and different ends searched by their precedence
 *
 * @param regions - List to put new regions in
 * @param leafNodes - nodes to search in
 * @param toSearch - String to search
 * @param ends - ends in decreasing precedence
 * @since 2.6
 */
protected void computeRegions(List<ReplaceRegion> regions, Iterable<ILeafNode> leafNodes, String toSearch, String... ends) {
	for (ILeafNode leafNode : leafNodes) {
		String text = leafNode.getText();
		int offset = leafNode.getOffset();
		int position = text.indexOf(toSearch);
		int textLength = text.length();
		while (position != -1) {
			int beginIndex = position + toSearch.length();
			// Skip leading whitespaces
			if(Character.isWhitespace(text.charAt(beginIndex))){
				while(beginIndex < textLength && Character.isWhitespace(text.charAt(beginIndex))){
					beginIndex ++;
				}
			}
			int endIndex = -1;
			for (int i = ends.length -1; i >= 0; i--) {
				String end = ends[i];
				int endCandidate = text.indexOf(end, beginIndex);
				if (endCandidate != -1)  {
					if (endIndex == -1) {
						endIndex = endCandidate;
					} else {
						if (endIndex > endCandidate) {
							endIndex = endCandidate;
						}
					}
				}
			}
			if (endIndex == -1) { 
				break;
			} else {
				String simpleName = text.substring(beginIndex, endIndex).replaceAll(" ", "");
				if(simpleName.length() > 0 && simpleName.matches("[0-9a-zA-Z\\.\\$_]*")){
					ReplaceRegion region = new ReplaceRegion(offset + beginIndex, simpleName.length(), simpleName);
					regions.add(region);
				}
			} 
			position = text.indexOf(toSearch, endIndex);
		}
	}
}