Java Code Examples for org.eclipse.xtext.nodemodel.ICompositeNode#getLength()

The following examples show how to use org.eclipse.xtext.nodemodel.ICompositeNode#getLength() . 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: DeadCodeAnalyser.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private DeadCodeRegion getDeadCodeRegion(Set<ControlFlowElement> deadCodeGroup) {
	int startIdx = Integer.MAX_VALUE;
	int endIdx = 0;
	int firstElementOffset = Integer.MAX_VALUE;
	ControlFlowElement firstElement = null;

	for (ControlFlowElement deadCodeElement : deadCodeGroup) {
		ICompositeNode compNode = NodeModelUtils.findActualNodeFor(deadCodeElement);
		int elemStartIdx = compNode.getOffset();
		int elemEndIdx = elemStartIdx + compNode.getLength();
		startIdx = Math.min(startIdx, elemStartIdx);
		endIdx = Math.max(endIdx, elemEndIdx);
		if (elemStartIdx < firstElementOffset) {
			firstElementOffset = elemStartIdx;
			firstElement = deadCodeElement;
		}
	}

	ControlFlowElement containerCFE = flowAnalyzer.getContainer(firstElement);
	ControlFlowElement reachablePredecessor = findPrecedingStatement(firstElement);
	return new DeadCodeRegion(startIdx, endIdx - startIdx, containerCFE, reachablePredecessor);
}
 
Example 2
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected int[] getOffsetAndLength(XIfExpression ifExpression, ICompositeNode node) {
	int offset = node.getOffset();
	int length = node.getLength();
	if (ifExpression.getElse() != null) {
		ICompositeNode elseNode = NodeModelUtils.findActualNodeFor(ifExpression.getElse());
		if (elseNode != null) {
			length = elseNode.getOffset() - offset;
		}
	} else {
		XIfExpression parentIfExpression = EcoreUtil2.getContainerOfType(ifExpression.eContainer(),
				XIfExpression.class);
		if (parentIfExpression != null && parentIfExpression.getElse() == ifExpression) {
			ICompositeNode thenNode = NodeModelUtils.findActualNodeFor(parentIfExpression.getThen());
			if (thenNode != null) {
				int endOffset = thenNode.getEndOffset();
				length = length + (offset - endOffset);
				offset = endOffset;
			}
		}
	}
	return new int[] { offset, length };
}
 
Example 3
Source File: InterpreterAutoEdit.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Evaluation findEvaluation(DocumentCommand command, XtextResource state) {
	if (!state.getContents().isEmpty()) {
		org.eclipse.xtext.example.arithmetics.arithmetics.Module m = 
				(org.eclipse.xtext.example.arithmetics.arithmetics.Module) state.getContents().get(0);
		for (Evaluation evaluation : Iterables.filter(m.getStatements(), Evaluation.class)) {
			ICompositeNode node = NodeModelUtils.getNode(evaluation);
			if (node.getOffset() <= command.offset && node.getOffset() + node.getLength() >= command.offset) {
				return evaluation;
			}
		}
	}
	return null;
}
 
Example 4
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void remove(IXtextDocument document, ICompositeNode node) throws BadLocationException {
	int offset = node.getOffset();
	int length = node.getLength();
	if (node.hasPreviousSibling()) {
		INode previousSibling = node.getPreviousSibling();
		int endOffset = previousSibling.getEndOffset();
		length = length + (offset - endOffset);
		offset = endOffset;
	}
	document.replace(offset, length, "");
}
 
Example 5
Source File: SemanticChangeProvider.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns IChange to remove annotation from element. Only removes exisiting annotations.
 *
 * @param document
 *            Document to modify
 * @param element
 *            Element to modify
 * @param annotation
 *            Annotation to remove
 */
TextEdit removeAnnotation(Document document, AnnotableElement element, String annotation) {
	AnnotableElement annotatedElement = element;
	Collection<Annotation> sourceList = null;
	Annotation targetAnnotation = null;

	// Search for given annotation in the elements annotation list as well as
	// in the containing export declaration as far as it exists.
	targetAnnotation = getAnnotationWithName(annotatedElement, annotation);
	if (targetAnnotation != null) {
		sourceList = annotatedElement.getAnnotations();

	} else if (element.eContainer() instanceof ExportDeclaration) {

		ExportDeclaration expDecl = (ExportDeclaration) element.eContainer();
		targetAnnotation = getAnnotationWithName(expDecl, annotation);
		if (targetAnnotation != null) {
			sourceList = expDecl.getAnnotations();
		}
	}

	if (sourceList == null || targetAnnotation == null) {
		return null;
	}

	ICompositeNode node = NodeModelUtils.findActualNodeFor(targetAnnotation);
	int offset = node.getOffset();
	int length = node.getLength();

	// Workaround the fact that the offset of the first annotation starts
	// after the '@' symbol. This is grammar caused. (The annotation can be first in the annotations list of the
	// export declaration or of the element itself)
	if (targetAnnotation == IterableExtensions.head(sourceList)) {
		var containerNode = NodeModelUtils.findActualNodeFor(targetAnnotation.eContainer());
		offset = containerNode.getOffset();
		length = node.getOffset() + node.getLength() - containerNode.getOffset();
	}

	// If the annotation is in the same line as the following element modifiers
	// also remove the additional whitespace.
	// Also consider chained one line annotations without separator
	if (element instanceof ModifiableElement) {
		ModifiableElement mElement = (ModifiableElement) element;
		Position offsetPosition = document.getPosition(offset);
		Position mOffsetPosition = document.getPosition(modifierOffset(mElement));

		if (offsetPosition.getLine() == mOffsetPosition.getLine()) {
			// Only delete trailing white space if there is white space in front of the annotation
			// Also check if there even is a trailing white space.

			String contents = document.getContents();
			char trailingChar = contents.charAt(offset + length);
			char leadingChar = contents.charAt(offset - 1);
			if (Character.isWhitespace(leadingChar) && Character.isWhitespace(trailingChar)) {
				length++;
			}
		}
	}

	return ChangeProvider.removeText(document, offset, length, true);
}
 
Example 6
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IParseResult reparse(IParser parser, IParseResult previousParseResult, ReplaceRegion changedRegion) {
	if (isBrokenPreviousState(previousParseResult, changedRegion.getOffset())) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	ICompositeNode oldRootNode = previousParseResult.getRootNode();
	Iterator<ILeafNode> leafNodes = oldRootNode.getLeafNodes().iterator();
	ILeafNode leftNode = getLeftNode(leafNodes, changedRegion.getOffset());
	if (leftNode == null) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	ILeafNode rightNode = getRightNode(leafNodes, changedRegion.getEndOffset());
	if (rightNode == null) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	while(leafNodes.hasNext()) {
		if (leafNodes.next().getSyntaxErrorMessage() != null) {
			return fullyReparse(parser, previousParseResult, changedRegion);
		}
	}
	String originalText = oldRootNode.getText().substring(leftNode.getTotalOffset());
	StringBuilder newTextBuilder = new StringBuilder(originalText);
	changedRegion.shiftBy(-leftNode.getTotalOffset()).applyTo(newTextBuilder);
	String newText = newTextBuilder.toString();
	if (originalText.equals(newText)) {
		// nothing to do
		return previousParseResult;
	}
	int originalLength = rightNode.getTotalEndOffset() - leftNode.getTotalOffset();
	int expectedLength = originalLength - changedRegion.getLength() + changedRegion.getText().length();
	if (!isSameTokenSequence(originalText.substring(0, originalLength), newText, expectedLength)) {
		// different token sequence, cannot perform a partial parse run
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	
	PartialParsingPointers parsingPointers = calculatePartialParsingPointers(oldRootNode, leftNode, rightNode);
	ICompositeNode replaceMe = getReplacedNode(parsingPointers);
	if (replaceMe == null || replaceMe == oldRootNode || replaceMe.getOffset() == 0 && replaceMe.getEndOffset() == oldRootNode.getLength()) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	String reparseRegion = insertChangeIntoReplaceRegion(replaceMe, changedRegion);
	
	EObject oldSemanticElement = getOldSemanticElement(replaceMe, parsingPointers);
	if (oldSemanticElement == null)
		return fullyReparse(parser, previousParseResult, changedRegion);
	if (oldSemanticElement == replaceMe.getParent().getSemanticElement()) {
		throw new IllegalStateException("oldParent == oldElement");
	}
	
	IParseResult newParseResult = doParseRegion(parser, parsingPointers, replaceMe, reparseRegion);
	if (newParseResult == null) {
		throw new IllegalStateException("Could not perform a partial parse operation");
	}
	
	replaceOldSemanticElement(oldSemanticElement, previousParseResult, newParseResult);
	nodeModelBuilder.replaceAndTransferLookAhead(replaceMe, newParseResult.getRootNode());
	((ParseResult) newParseResult).setRootNode(oldRootNode);
	StringBuilder builder = new StringBuilder(oldRootNode.getText());
	changedRegion.applyTo(builder);
	nodeModelBuilder.setCompleteContent(oldRootNode, builder.toString());
	return newParseResult;
}
 
Example 7
Source File: StaticExtensionMethodImporter.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void computeChange(final XMemberFeatureCall call, final DocumentRewriter rewriter) {
  try {
    boolean _isEmpty = call.getMemberCallArguments().isEmpty();
    if (_isEmpty) {
      super.computeChange(call, rewriter);
    } else {
      final XExpression firstArg = IterableExtensions.<XExpression>head(call.getMemberCallArguments());
      final ICompositeNode firstArgNode = NodeModelUtils.findActualNodeFor(firstArg);
      final String firstArgText = rewriter.getDocument().get(firstArgNode.getOffset(), firstArgNode.getLength());
      int _xifexpression = (int) 0;
      int _size = call.getMemberCallArguments().size();
      boolean _greaterThan = (_size > 1);
      if (_greaterThan) {
        int _xblockexpression = (int) 0;
        {
          final ICompositeNode secondArgNode = NodeModelUtils.findActualNodeFor(call.getMemberCallArguments().get(1));
          int _offset = secondArgNode.getOffset();
          int _offset_1 = firstArgNode.getOffset();
          _xblockexpression = (_offset - _offset_1);
        }
        _xifexpression = _xblockexpression;
      } else {
        _xifexpression = firstArgNode.getLength();
      }
      final int replaceLength = _xifexpression;
      final ICompositeNode memberNode = NodeModelUtils.findActualNodeFor(call.getMemberCallTarget());
      String _xifexpression_1 = null;
      boolean _shouldWrap = this.shouldWrap(firstArg);
      if (_shouldWrap) {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("(");
        _builder.append(firstArgText);
        _builder.append(")");
        _xifexpression_1 = _builder.toString();
      } else {
        _xifexpression_1 = firstArgText;
      }
      final String replaceText = _xifexpression_1;
      try {
        rewriter.newSection(firstArgNode.getOffset(), replaceLength);
        rewriter.newSection(memberNode.getOffset(), memberNode.getLength()).append(replaceText);
      } catch (final Throwable _t) {
        if (_t instanceof IllegalArgumentException) {
        } else {
          throw Exceptions.sneakyThrow(_t);
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}