Java Code Examples for org.eclipse.jdt.core.dom.ASTNode#getLength()

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#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: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source of the given node from the location where it was parsed.
 * @param node the node to get the source from
 * @param extendedRange if set, the extended ranges of the nodes should ne used
 * @param removeIndent if set, the indentation is removed.
 * @return return the source for the given node or null if accessing the source failed.
 */
public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit astRoot= (CompilationUnit) root;
		ITypeRoot typeRoot= astRoot.getTypeRoot();
		try {
			if (typeRoot != null && typeRoot.getBuffer() != null) {
				IBuffer buffer= typeRoot.getBuffer();
				int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition();
				int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength();
				String str= buffer.getText(offset, length);
				if (removeIndent) {
					IJavaProject project= typeRoot.getJavaProject();
					int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project);
					str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator());
				}
				return str;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return null;
}
 
Example 2
Source File: ASTVisitors.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see {@link org.eclipse.jdt.core.dom.NodeFinder.NodeFinderVisitor}
 **/
private boolean findCoveringNode(final ASTNode node) {
	final int nodeStart = node.getStartPosition();
	final int nodeEnd = nodeStart + node.getLength();
	if (nodeEnd < this.fStart || this.fEnd < nodeStart) {
		return false;
	}
	if (nodeStart <= this.fStart && this.fEnd <= nodeEnd) {
		this.fCoveringBlock = node;
	}
	if (this.fStart <= nodeStart && nodeEnd <= this.fEnd) {
		if (this.fCoveringBlock == node) { // nodeStart == fStart &&
											// nodeEnd == fEnd
			return true; // look further for node with same length
							// as
							// parent
		}
		return false;
	}
	return true;
}
 
Example 3
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private int findFieldInsertIndex(List<BodyDeclaration> decls, int currPos) {
	for (int i= decls.size() - 1; i >= 0; i--) {
		ASTNode curr= decls.get(i);
		if (curr instanceof FieldDeclaration && currPos > curr.getStartPosition() + curr.getLength()) {
			return i + 1;
		}
	}
	return 0;
}
 
Example 4
Source File: ASTNodeSearchUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode getAstNode(CompilationUnit cuNode, int start, int length){
	SelectionAnalyzer analyzer= new SelectionAnalyzer(Selection.createFromStartLength(start, length), true);
	cuNode.accept(analyzer);
	//XXX workaround for jdt core feature 23527
	ASTNode node= analyzer.getFirstSelectedNode();
	if (node == null && analyzer.getLastCoveringNode() instanceof SuperConstructorInvocation)
		node= analyzer.getLastCoveringNode().getParent();
	else if (node == null && analyzer.getLastCoveringNode() instanceof ConstructorInvocation)
		node= analyzer.getLastCoveringNode().getParent();

	if (node == null)
		return null;

	ASTNode parentNode= node.getParent();

	if (parentNode instanceof MethodDeclaration){
		MethodDeclaration md= (MethodDeclaration)parentNode;
		if (!(node instanceof SimpleName)
			&& md.isConstructor()
		    && md.getBody() != null
		    && md.getBody().statements().size() > 0
		    &&(md.getBody().statements().get(0) instanceof ConstructorInvocation || md.getBody().statements().get(0) instanceof SuperConstructorInvocation)
		    &&((ASTNode)md.getBody().statements().get(0)).getLength() == length + 1)
		return (ASTNode)md.getBody().statements().get(0);
	}

	if (parentNode instanceof SuperConstructorInvocation){
		if (parentNode.getLength() == length + 1)
			return parentNode;
	}
	if (parentNode instanceof ConstructorInvocation){
		if (parentNode.getLength() == length + 1)
			return parentNode;
	}
	return node;
}
 
Example 5
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(LambdaExpression node) {
	Selection selection = getSelection();
	int selectionStart = selection.getOffset();
	int selectionExclusiveEnd = selection.getExclusiveEnd();
	int lambdaStart = node.getStartPosition();
	int lambdaExclusiveEnd = lambdaStart + node.getLength();
	ASTNode body = node.getBody();
	int bodyStart = body.getStartPosition();
	int bodyExclusiveEnd = bodyStart + body.getLength();

	boolean isValidSelection = false;
	if ((body instanceof Block) && (bodyStart < selectionStart && selectionExclusiveEnd <= bodyExclusiveEnd)) {
		// if selection is inside lambda body's block
		isValidSelection = true;
	} else if (body instanceof Expression) {
		try {
			TokenScanner scanner = new TokenScanner(fCUnit);
			int arrowExclusiveEnd = scanner.getTokenEndOffset(ITerminalSymbols.TokenNameARROW, lambdaStart);
			if (selectionStart >= arrowExclusiveEnd) {
				isValidSelection = true;
			}
		} catch (CoreException e) {
			// ignore
		}
	}
	if (selectionStart <= lambdaStart && selectionExclusiveEnd >= lambdaExclusiveEnd) {
		// if selection covers the lambda node
		isValidSelection = true;
	}

	if (!isValidSelection) {
		return false;
	}
	return super.visit(node);
}
 
Example 6
Source File: JavaASTAnnotatedTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void preVisit(final ASTNode node) {
	final int fromPosition = node.getStartPosition();
	final int endPosition = fromPosition + node.getLength();
	final int nodeType = node.getNodeType();
	final int parentType;
	if (node.getParent() != null) {
		parentType = node.getParent().getNodeType();
	} else {
		parentType = -1;
	}
	final SortedMap<Integer, FullToken> nodeTokens = baseTokens.subMap(
			fromPosition, endPosition);
	for (final Entry<Integer, FullToken> token : nodeTokens.entrySet()) {
		if (token.getValue().token.startsWith("WS_")
				&& baseTokenizer instanceof JavaWhitespaceTokenizer) {
			annotatedTokens.put(
					token.getKey(),
					new AstAnnotatedToken(new FullToken(token
							.getValue().token,
							token.getValue().tokenType), null, null));
		} else {
			annotatedTokens.put(
					token.getKey(),
					new AstAnnotatedToken(new FullToken(token
							.getValue().token,
							token.getValue().tokenType),
							nodeIdToString(nodeType),
							nodeIdToString(parentType)));
		}
	}
	super.preVisit(node);
}
 
Example 7
Source File: BreakContinueTargetFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private OccurrenceLocation getLocationForFirstToken(ASTNode node) {
	try {
		int nextEndOffset= new TokenScanner(fASTRoot.getTypeRoot()).getNextEndOffset(node.getStartPosition(), true);
		return new OccurrenceLocation(node.getStartPosition(), nextEndOffset - node.getStartPosition(), 0, fDescription);
	} catch (CoreException e) {
		// ignore
	}
	return new OccurrenceLocation(node.getStartPosition(), node.getLength(), 0, fDescription);
}
 
Example 8
Source File: CalleeAnalyzerVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isNodeEnclosingMethod(ASTNode node) {
    int nodeStartPosition = node.getStartPosition();
    int nodeEndPosition = nodeStartPosition + node.getLength();

    if (nodeStartPosition < fMethodStartPosition && nodeEndPosition > fMethodEndPosition) {
        // Is the method completely enclosed by the node?
        return true;
    }
    return false;
}
 
Example 9
Source File: JavaASTAnnotatedTokenizer.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void preVisit(final ASTNode node) {
	final int fromPosition = node.getStartPosition();
	final int endPosition = fromPosition + node.getLength();
	final int nodeType = node.getNodeType();
	final int parentType;
	if (node.getParent() != null) {
		parentType = node.getParent().getNodeType();
	} else {
		parentType = -1;
	}
	final SortedMap<Integer, FullToken> nodeTokens = baseTokens.subMap(
			fromPosition, endPosition);
	for (final Entry<Integer, FullToken> token : nodeTokens.entrySet()) {
		if (token.getValue().token.startsWith("WS_")
				&& baseTokenizer instanceof JavaWhitespaceTokenizer) {
			annotatedTokens.put(
					token.getKey(),
					new AstAnnotatedToken(new FullToken(token
							.getValue().token,
							token.getValue().tokenType), null, null));
		} else {
			annotatedTokens.put(
					token.getKey(),
					new AstAnnotatedToken(new FullToken(token
							.getValue().token,
							token.getValue().tokenType),
							nodeIdToString(nodeType),
							nodeIdToString(parentType)));
		}
	}
	super.preVisit(node);
}
 
Example 10
Source File: NestedDefinitionLocation.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fast and, hopefully, correct comparator of AST nodes.
 * */
private boolean same(ASTNode node1, ASTNode node2) {
	if(!node1.toString().equals(node2.toString())) return false;
	if(node1.getStartPosition() != node2.getStartPosition()) return false;
	if(node1.getLength() != node2.getLength()) return false;
	
	return true;		
}
 
Example 11
Source File: NLSKeyHyperlinkDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
	ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
	if (region == null || textEditor == null)
		return null;

	IEditorSite site= textEditor.getEditorSite();
	if (site == null)
		return null;

	ITypeRoot javaElement= getInputJavaElement(textEditor);
	if (javaElement == null)
		return null;

	CompilationUnit ast= SharedASTProvider.getAST(javaElement, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
	if (!(node instanceof StringLiteral)  && !(node instanceof SimpleName))
		return null;

	if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
		return null;

	IRegion nlsKeyRegion= new Region(node.getStartPosition(), node.getLength());
	AccessorClassReference ref= NLSHintHelper.getAccessorClassReference(ast, nlsKeyRegion);
	if (ref == null)
		return null;
	String keyName= null;
	if (node instanceof StringLiteral) {
		keyName= ((StringLiteral)node).getLiteralValue();
	} else {
		keyName= ((SimpleName)node).getIdentifier();
	}
	if (keyName != null)
		return new IHyperlink[] {new NLSKeyHyperlink(nlsKeyRegion, keyName, ref, textEditor)};

	return null;
}
 
Example 12
Source File: AbstractValidationProblem.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public AbstractValidationProblem(SourceInfo sourceInfo, ASTNode node) {
	this.sourceInfo = sourceInfo;

	ASTNode nodeToMark = getNodeToMark(node);
	this.sourceStart = nodeToMark.getStartPosition();
	this.sourceEnd = nodeToMark.getStartPosition() + nodeToMark.getLength();
	this.lineNumber = sourceInfo.getSourceLineNumber(getSourceEnd());
}
 
Example 13
Source File: TightSourceRangeComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isExtending(ASTNode child, ASTNode parent) {
   SourceRange extendedRange= super.computeSourceRange(child);

   int parentStart= parent.getStartPosition();
int extendedStart= extendedRange.getStartPosition();
if (parentStart > extendedStart)
	return true;

int parentEnd= parentStart + parent.getLength();
int extendedEnd= extendedStart + extendedRange.getLength();
if (parentEnd < extendedEnd)
	return true;

   return false;
  }
 
Example 14
Source File: CloneInstanceMapper.java    From JDeodorant with MIT License 4 votes vote down vote up
private boolean isInside(ASTNode astNode, int startOffset, int endOffset, ICompilationUnit iCompilationUnit) {

		int astNodeStartOffset = astNode.getStartPosition();
		int astNodeLength = astNode.getLength();
		int astNodeEndOffset = astNodeStartOffset + astNodeLength - 1;

		// If the node is completely inside
		if (astNodeStartOffset >= startOffset && astNodeEndOffset <= endOffset)
			return true;

		if (astNodeStartOffset >= startOffset && astNodeStartOffset <= endOffset) {
			IDocument iDocument = JavaModelUtility.getIDocument(iCompilationUnit);
			try {
				String realSourceCode = iDocument.get(astNodeStartOffset, endOffset - astNodeStartOffset + 1);
				String astNodeSourceCode = iDocument.get(astNodeStartOffset, astNodeLength);

				TextDiff td = new TextDiff();
				LinkedList<Diff> diffs = td.diff_main(realSourceCode, astNodeSourceCode, false);
				td.diff_cleanupSemantic(diffs);

				String commentRegularExpression = "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)";

				boolean realSourceCodeFound = false;
				for (Diff diff : diffs) {
					switch (diff.operation) {
					case EQUAL:
						if (diff.text.equals(realSourceCode))
							realSourceCodeFound = true;
						break;
					case DELETE:
						return false;
					case INSERT:
						String filtered = diff.text.replaceAll(commentRegularExpression, "").replaceAll("\\s", "").replaceAll("\\}", "").replaceAll("\\)", "").replaceAll(";", "");
						if(realSourceCodeFound && (filtered.isEmpty() || hasOnlyKeyWord(filtered)))
							return true;
						else
							return false;
					}
				}
				return realSourceCodeFound;
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
 
Example 15
Source File: Selection.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean covers(ASTNode node) {
	int nodeStart= node.getStartPosition();
	return fStart <= nodeStart && nodeStart + node.getLength() <= fExclusiveEnd;
}
 
Example 16
Source File: RenameLinkedMode.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void start() {
		if (getActiveLinkedMode() != null) {
			// for safety; should already be handled in RenameJavaElementAction
			fgActiveLinkedMode.startFullDialog();
			return;
		}

		ISourceViewer viewer= fEditor.getViewer();
		IDocument document= viewer.getDocument();
		fOriginalSelection= viewer.getSelectedRange();
		int offset= fOriginalSelection.x;

		try {
			CompilationUnit root= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

			fLinkedPositionGroup= new LinkedPositionGroup();
			ASTNode selectedNode= NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y);
			if (! (selectedNode instanceof SimpleName)) {
				return; // TODO: show dialog
			}
			SimpleName nameNode= (SimpleName) selectedNode;

			if (viewer instanceof ITextViewerExtension6) {
				IUndoManager undoManager= ((ITextViewerExtension6)viewer).getUndoManager();
				if (undoManager instanceof IUndoManagerExtension) {
					IUndoManagerExtension undoManagerExtension= (IUndoManagerExtension)undoManager;
					IUndoContext undoContext= undoManagerExtension.getUndoContext();
					IOperationHistory operationHistory= OperationHistoryFactory.getOperationHistory();
					fStartingUndoOperation= operationHistory.getUndoOperation(undoContext);
				}
			}
			
			fOriginalName= nameNode.getIdentifier();
			final int pos= nameNode.getStartPosition();
			ASTNode[] sameNodes= LinkedNodeFinder.findByNode(root, nameNode);

			//TODO: copied from LinkedNamesAssistProposal#apply(..):
			// sort for iteration order, starting with the node @ offset
			Arrays.sort(sameNodes, new Comparator<ASTNode>() {
				public int compare(ASTNode o1, ASTNode o2) {
					return rank(o1) - rank(o2);
				}
				/**
				 * Returns the absolute rank of an <code>ASTNode</code>. Nodes
				 * preceding <code>pos</code> are ranked last.
				 *
				 * @param node the node to compute the rank for
				 * @return the rank of the node with respect to the invocation offset
				 */
				private int rank(ASTNode node) {
					int relativeRank= node.getStartPosition() + node.getLength() - pos;
					if (relativeRank < 0)
						return Integer.MAX_VALUE + relativeRank;
					else
						return relativeRank;
				}
			});
			for (int i= 0; i < sameNodes.length; i++) {
				ASTNode elem= sameNodes[i];
				LinkedPosition linkedPosition= new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i);
				if (i == 0)
					fNamePosition= linkedPosition;
				fLinkedPositionGroup.addPosition(linkedPosition);
			}

			fLinkedModeModel= new LinkedModeModel();
			fLinkedModeModel.addGroup(fLinkedPositionGroup);
			fLinkedModeModel.forceInstall();
			fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
			fLinkedModeModel.addLinkingListener(new EditorSynchronizer());

			LinkedModeUI ui= new EditorLinkedModeUI(fLinkedModeModel, viewer);
			ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
			ui.setExitPolicy(new ExitPolicy(document));
			ui.enter();

			viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection

			if (viewer instanceof IEditingSupportRegistry) {
				IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
				registry.register(fFocusEditingSupport);
			}

			openSecondaryPopup();
//			startAnimation();
			fgActiveLinkedMode= this;

		} catch (BadLocationException e) {
			JavaPlugin.log(e);
		}
	}
 
Example 17
Source File: Selection.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean endsIn(ASTNode node) {
	int nodeStart= node.getStartPosition();
	return nodeStart < fExclusiveEnd && fExclusiveEnd < nodeStart + node.getLength();
}
 
Example 18
Source File: SelectionAwareSourceRangeComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void initializeRanges() throws CoreException {
	fRanges= new HashMap<ASTNode, SourceRange>();
	if (fSelectedNodes.length == 0)
		return;

	fRanges.put(fSelectedNodes[0], super.computeSourceRange(fSelectedNodes[0]));
	int last= fSelectedNodes.length - 1;
	fRanges.put(fSelectedNodes[last], super.computeSourceRange(fSelectedNodes[last]));

	IScanner scanner= ToolFactory.createScanner(true, false, false, false);
	char[] source= fDocumentPortionToScan.toCharArray();
	scanner.setSource(source);
	fDocumentPortionToScan= null; // initializeRanges() is only called once

	TokenScanner tokenizer= new TokenScanner(scanner);
	int pos= tokenizer.getNextStartOffset(0, false);

	ASTNode currentNode= fSelectedNodes[0];
	int newStart= Math.min(fSelectionStart + pos, currentNode.getStartPosition());
	SourceRange range= fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(newStart, range.getLength() + range.getStartPosition() - newStart));

	currentNode= fSelectedNodes[last];
	int scannerStart= currentNode.getStartPosition() + currentNode.getLength() - fSelectionStart;
	tokenizer.setOffset(scannerStart);
	pos= scannerStart;
	int token= -1;
	try {
		while (true) {
			token= tokenizer.readNext(false);
			pos= tokenizer.getCurrentEndOffset();
		}
	} catch (CoreException e) {
	}
	if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
		int index= pos - 1;
		while (index >= 0 && IndentManipulation.isLineDelimiterChar(source[index])) {
			pos--;
			index--;
		}
	}

	int newEnd= Math.max(fSelectionStart + pos, currentNode.getStartPosition() + currentNode.getLength());
	range= fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(range.getStartPosition(), newEnd - range.getStartPosition()));
}
 
Example 19
Source File: SelectionAwareSourceRangeComputer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void initializeRanges() throws CoreException {
	fRanges = new HashMap<>();
	if (fSelectedNodes.length == 0) {
		return;
	}

	fRanges.put(fSelectedNodes[0], super.computeSourceRange(fSelectedNodes[0]));
	int last = fSelectedNodes.length - 1;
	fRanges.put(fSelectedNodes[last], super.computeSourceRange(fSelectedNodes[last]));

	IJavaProject javaProject = ((CompilationUnit) fSelectedNodes[0].getRoot()).getTypeRoot().getJavaProject();
	String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	IScanner scanner = ToolFactory.createScanner(true, false, false, sourceLevel, complianceLevel);
	char[] source = fDocumentPortionToScan.toCharArray();
	scanner.setSource(source);
	fDocumentPortionToScan = null; // initializeRanges() is only called once

	TokenScanner tokenizer = new TokenScanner(scanner);
	int pos = tokenizer.getNextStartOffset(0, false);

	ASTNode currentNode = fSelectedNodes[0];
	int newStart = Math.min(fSelectionStart + pos, currentNode.getStartPosition());
	SourceRange range = fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(newStart, range.getLength() + range.getStartPosition() - newStart));

	currentNode = fSelectedNodes[last];
	int scannerStart = currentNode.getStartPosition() + currentNode.getLength() - fSelectionStart;
	tokenizer.setOffset(scannerStart);
	pos = scannerStart;
	int token = -1;
	try {
		while (true) {
			token = tokenizer.readNext(false);
			pos = tokenizer.getCurrentEndOffset();
		}
	} catch (CoreException e) {
	}
	if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
		int index = pos - 1;
		while (index >= 0 && IndentManipulation.isLineDelimiterChar(source[index])) {
			pos--;
			index--;
		}
	}

	int newEnd = Math.max(fSelectionStart + pos, currentNode.getStartPosition() + currentNode.getLength());
	range = fRanges.get(currentNode);
	fRanges.put(currentNode, new SourceRange(range.getStartPosition(), newEnd - range.getStartPosition()));

	// The extended source range of the last child node can end after the selection.
	// We have to ensure that the source range of such child nodes is also capped by the selection range.
	// Example: (/*]*/TRANSFORMER::transform/*[*/)
	// Selection is between /*]*/ and /*[*/, but the extended range of the "transform" node actually includes /*[*/ as well.
	while (true) {
		List<ASTNode> children = ASTNodes.getChildren(currentNode);
		if (!children.isEmpty()) {
			ASTNode lastChild = children.get(children.size() - 1);
			SourceRange extRange = super.computeSourceRange(lastChild);
			if (extRange.getStartPosition() + extRange.getLength() > newEnd) {
				fRanges.put(lastChild, new SourceRange(extRange.getStartPosition(), newEnd - extRange.getStartPosition()));
				currentNode = lastChild;
				continue;
			}
		}
		break;
	}
}
 
Example 20
Source File: TargetSourceRangeComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the target source range of the given node. Unlike
 * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
 * the extended source range may include comments and whitespace
 * immediately before or after the normal source range for the node.
 * <p>
 * The returned source ranges must satisfy the following conditions:
 * <dl>
 * <li>no two source ranges in an AST may be overlapping</li>
 * <li>a source range of a parent node must fully cover the source ranges of its children</li>
 * 	</dl>
 * 	</p>
 * <p>
 * The default implementation uses
 * {@link CompilationUnit#getExtendedStartPosition(ASTNode)}
 * and {@link CompilationUnit#getExtendedLength(ASTNode)}
 * to compute the target source range. Clients may override or
 * extend this method to expand or contract the source range of the
 * given node. The resulting source range must cover at least the
 * original source range of the node.
 * </p>
 *
 * @param node the node with a known source range in the compilation unit
 * being rewritten
 * @return the exact source range in the compilation unit being rewritten
 * that should be replaced (or deleted)
 */
public SourceRange computeSourceRange(ASTNode node) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit cu= (CompilationUnit) root;
		return new SourceRange(cu.getExtendedStartPosition(node), cu.getExtendedLength(node));
	}
	return new SourceRange(node.getStartPosition(), node.getLength());
}