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

The following examples show how to use org.eclipse.xtext.nodemodel.ICompositeNode#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: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean doNotProposeFeatureOfBinaryOperation(ContentAssistContext contentAssistContext,
		XBinaryOperation binaryOperation) {
	List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(binaryOperation, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
	if (!nodesForFeature.isEmpty()) {
		INode node = nodesForFeature.get(0);
		if (node.getOffset() < contentAssistContext.getOffset() - contentAssistContext.getPrefix().length()) {
			XExpression rightOperand = binaryOperation.getRightOperand();
			if (rightOperand == null)
				return true;
			ICompositeNode rightOperandNode = NodeModelUtils.findActualNodeFor(rightOperand);
			if (rightOperandNode != null) {
				if (rightOperandNode.getOffset() >= contentAssistContext.getOffset())
					return true;
				if (isParentOf(rightOperandNode, contentAssistContext.getLastCompleteNode()))
					return true;
			}
		}
	}
	return false;
}
 
Example 2
Source File: SuppressWarningsAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Add SuppressWarnings annotation.
 *
 * @param element the element to receive the annotation.
 * @param annotation the suppress-warning annotation.
 * @param context the modification context.
 * @throws Exception if the document cannot be changed.
 */
protected void addAnnotation(EObject element, XAnnotation annotation,
		IModificationContext context) throws Exception {
	final ICompositeNode node = NodeModelUtils.findActualNodeFor(annotation);
	if (node != null) {
		final IXtextDocument document = context.getXtextDocument();
		final int startOffset = node.getOffset();
		final int parameterOffset = getTools().getOffsetForPattern(document, startOffset,
				"@\\s*" + toPattern(annotation.getAnnotationType().getQualifiedName()) //$NON-NLS-1$
				+ "\\s*\\(\\s*"); //$NON-NLS-1$
		final int insertOffset;
		if (document.getChar(parameterOffset) == '{') {
			insertOffset = parameterOffset + getTools().getSpaceSize(document, parameterOffset + 1) + 1;
		} else {
			insertOffset = parameterOffset;
		}
		final ReplacingAppendable appendable = getTools().getAppendableFactory().create(document,
				(XtextResource) element.eResource(), insertOffset, 0);
		appendable.append("\""); //$NON-NLS-1$
		appendable.append(extractId(this.code));
		appendable.append("\", "); //$NON-NLS-1$
		appendable.commitChanges();
	}
}
 
Example 3
Source File: SuppressWarningsAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Add SuppressWarnings annotation.
 *
 * @param element the element to receive the annotation.
 * @param context the modification context.
 * @param suppressWarningsAnnotation the type for the suppress warning annotation.
 * @throws Exception if the document cannot be changed.
 */
protected void addAnnotation(EObject element, IModificationContext context,
		JvmType suppressWarningsAnnotation) throws Exception {
	final ICompositeNode node = NodeModelUtils.findActualNodeFor(element);
	if (node != null) {
		final int insertOffset = node.getOffset();
		final IXtextDocument document = context.getXtextDocument();
		final int length = getTools().getSpaceSize(document, insertOffset);
		final ReplacingAppendable appendable = getTools().getAppendableFactory().create(document,
				(XtextResource) element.eResource(), insertOffset, length);
		appendable.append(getTools().getGrammarAccess().getCommercialAtKeyword());
		appendable.append(suppressWarningsAnnotation);
		appendable.append("(\""); //$NON-NLS-1$
		appendable.append(extractId(this.code));
		appendable.append("\")"); //$NON-NLS-1$
		appendable.newLine();
		appendable.commitChanges();
	}
}
 
Example 4
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 5
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 6
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void completeXBasicForLoopExpression_InitExpressions(EObject model, Assignment assignment,
		ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
	ICompositeNode node = NodeModelUtils.getNode(model);
	if (node.getOffset() >= context.getOffset()) {
		createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.BEFORE, context, acceptor);
		return;
	}
	if (model instanceof XBasicForLoopExpression) {
		List<XExpression> children = ((XBasicForLoopExpression) model).getInitExpressions();
		if (!children.isEmpty()) {
			for(int i = children.size() - 1; i >= 0; i--) {
				XExpression child = children.get(i);
				ICompositeNode childNode = NodeModelUtils.getNode(child);
				if (childNode.getEndOffset() <= context.getOffset()) {
					createLocalVariableAndImplicitProposals(child, IExpressionScope.Anchor.AFTER, context, acceptor);
					return;
				}
			}
		}
	}
	createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.BEFORE, context, acceptor);
}
 
Example 7
Source File: ImportRewriter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings({ "unused", "deprecation" })
private AliasLocation enhanceExistingImportDeclaration(ImportDeclaration importDeclaration,
		QualifiedName qualifiedName,
		String optionalAlias, MultiTextEdit result) {

	addImportSpecifier(importDeclaration, qualifiedName, optionalAlias);
	ICompositeNode replaceMe = NodeModelUtils.getNode(importDeclaration);
	int offset = replaceMe.getOffset();
	AliasLocationAwareBuffer observableBuffer = new AliasLocationAwareBuffer(
			optionalAlias,
			offset,
			grammarAccess);

	try {
		serializer.serialize(
				importDeclaration,
				observableBuffer,
				SaveOptions.newBuilder().noValidation().getOptions());
	} catch (IOException e) {
		throw new RuntimeException("Should never happen since we write into memory", e);
	}
	result.addChild(new ReplaceEdit(offset, replaceMe.getLength(), observableBuffer.toString()));
	return observableBuffer.getAliasLocation();
}
 
Example 8
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 9
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void completeWithinBlock(EObject model, ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
	ICompositeNode node = NodeModelUtils.getNode(model);
	if (node.getOffset() >= context.getOffset()) {
		createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.BEFORE, context, acceptor);
		return;
	}
	if (model instanceof XBlockExpression) {
		List<XExpression> children = ((XBlockExpression) model).getExpressions();
		if (!children.isEmpty()) {
			for(int i = children.size() - 1; i >= 0; i--) {
				XExpression child = children.get(i);
				ICompositeNode childNode = NodeModelUtils.getNode(child);
				if (childNode.getEndOffset() <= context.getOffset()) {
					createLocalVariableAndImplicitProposals(child, IExpressionScope.Anchor.AFTER, context, acceptor);
					return;
				}
			}
		}
	}
	int endOffset = node.getEndOffset();
	if (endOffset <= context.getOffset()) {
		if (model instanceof XFeatureCall && model.eContainer() instanceof XClosure || endOffset == context.getOffset() && context.getPrefix().length() == 0)
			return;
		if (isInMemberFeatureCall(model, endOffset, context))
			return;
		createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.AFTER, context, acceptor);
		return;
	} else if (isInMemberFeatureCall(model, endOffset, context)) {
		return;
	}
	if (model instanceof XClosure)
		return;
	createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.BEFORE, context, acceptor);
}
 
Example 10
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 11
Source File: XbaseIdeContentProposalProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void completeXBasicForLoopInit(final EObject model, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) {
  final ICompositeNode node = NodeModelUtils.getNode(model);
  int _offset = node.getOffset();
  int _offset_1 = context.getOffset();
  boolean _greaterEqualsThan = (_offset >= _offset_1);
  if (_greaterEqualsThan) {
    this.createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.BEFORE, context, acceptor);
    return;
  }
  if ((model instanceof XBasicForLoopExpression)) {
    final EList<XExpression> children = ((XBasicForLoopExpression)model).getInitExpressions();
    for (int i = (children.size() - 1); (i >= 0); i--) {
      {
        final XExpression child = children.get(i);
        final ICompositeNode childNode = NodeModelUtils.getNode(child);
        int _endOffset = childNode.getEndOffset();
        int _offset_2 = context.getOffset();
        boolean _lessEqualsThan = (_endOffset <= _offset_2);
        if (_lessEqualsThan) {
          this.createLocalVariableAndImplicitProposals(child, IExpressionScope.Anchor.AFTER, context, acceptor);
          return;
        }
      }
    }
  }
  this.createLocalVariableAndImplicitProposals(model, IExpressionScope.Anchor.BEFORE, context, acceptor);
}
 
Example 12
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 13
Source File: XtendProposalProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void completeWithinBlock(EObject model, ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
	if (model instanceof AnonymousClass) {
		ICompositeNode node = NodeModelUtils.getNode(model);
		if (node.getOffset() >= context.getOffset()) {
			super.completeWithinBlock(model, context, acceptor);
		} else {
			return;
		}
	}
	if (model instanceof XtendMember && model.eContainer() instanceof AnonymousClass) {
		return;
	}
	super.completeWithinBlock(model, context, acceptor);
}
 
Example 14
Source File: ExtractMethodHandler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void updateSelection(final XtextEditor editor, List<XExpression> expressions) {
	ICompositeNode firstNode = NodeModelUtils.getNode(expressions.get(0));
	ICompositeNode lastNode = NodeModelUtils.getNode(expressions.get(expressions.size() - 1));
	if (firstNode != null && lastNode != null) {
		int correctedSelectionOffset = firstNode.getOffset();
		int correctedSelectionLength = lastNode.getEndOffset() - correctedSelectionOffset;
		editor.selectAndReveal(correctedSelectionOffset, correctedSelectionLength);
	}
}
 
Example 15
Source File: NodeModelStreamer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ITextRegion feedTokenStream(ITokenStream out, ICompositeNode in, int offset, int length) throws IOException {
	List<INode> nodes = getLeafs(in, offset, offset + length);
	if (nodes.isEmpty())
		return new TextRegion(in.getOffset(), 0);
	if (out instanceof ITokenStreamExtension)
		((ITokenStreamExtension) out).init(findRootRuleForRegion(nodes.get(0)));
	boolean lastIsTokenOrComment = false;
	for (INode node : nodes) {
		boolean currentIsTokenOrComment = tokenUtil.isCommentNode(node) || tokenUtil.isToken(node);
		if (lastIsTokenOrComment && currentIsTokenOrComment)
			writeHiddenEmpty(out);
		lastIsTokenOrComment = currentIsTokenOrComment;
		if (node instanceof ILeafNode) {
			ILeafNode leaf = (ILeafNode) node;
			if (leaf.isHidden())
				writeHidden(out, leaf);
			else
				writeSemantic(out, leaf);
		} else if (node instanceof ICompositeNode)
			writeSemantic(out, (ICompositeNode) node);
	}
	out.flush();
	int rStart = nodes.get(0).getOffset();
	int rLength = nodes.get(nodes.size() - 1).getEndOffset() - rStart;
	return new TextRegion(rStart, rLength);
}
 
Example 16
Source File: ReturnTypeAddModification.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
	final XtendExecutable xtendExecutable = EcoreUtil2.getContainerOfType(element, XtendExecutable.class);
	final int insertPosition;
	if (xtendExecutable.getExpression() == null) {
		final ICompositeNode functionNode = NodeModelUtils.findActualNodeFor(xtendExecutable);
		if (functionNode == null) {
			throw new IllegalStateException("functionNode may not be null"); //$NON-NLS-1$
		}
		insertPosition = functionNode.getEndOffset();
	} else {
		final ICompositeNode expressionNode = NodeModelUtils.findActualNodeFor(xtendExecutable.getExpression());
		if (expressionNode == null) {
			throw new IllegalStateException("expressionNode may not be null"); //$NON-NLS-1$
		}
		insertPosition = expressionNode.getOffset();
	}
	final ReplacingAppendable appendable = getTools().getAppendableFactory().create(context.getXtextDocument(),
			(XtextResource) xtendExecutable.eResource(), insertPosition, 0);
	if (xtendExecutable.getExpression() == null) {
		appendable.append(" "); //$NON-NLS-1$
	}
	appendable.append(getTools().getGrammarAccess().getColonKeyword());
	appendable.append(" "); //$NON-NLS-1$
	appendable.append(this.expectedType);
	if (xtendExecutable.getExpression() != null) {
		appendable.append(" "); //$NON-NLS-1$
	}
	appendable.commitChanges();
}
 
Example 17
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 18
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);
  }
}
 
Example 19
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);
}