org.eclipse.jdt.core.dom.ASTNode#getLength ( )源码实例Demo

下面列出了org.eclipse.jdt.core.dom.ASTNode#getLength ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: api-mining   文件: ASTVisitors.java
/**
 * @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;
}
 
/**
 * 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;
}
 
源代码3 项目: lapse-plus   文件: NestedDefinitionLocation.java
/**
 * 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;		
}
 
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;
  }
 
源代码5 项目: txtUML   文件: AbstractValidationProblem.java
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());
}
 
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;
}
 
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;
}
 
源代码8 项目: tassal   文件: JavaASTAnnotatedTokenizer.java
@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);
}
 
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;
}
 
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);
}
 
@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);
}
 
源代码12 项目: eclipse.jdt.ls   文件: ExtractMethodAnalyzer.java
@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);
}
 
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;
}
 
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()));
}
 
public boolean endsIn(ASTNode node) {
	int nodeStart= node.getStartPosition();
	return nodeStart < fExclusiveEnd && fExclusiveEnd < nodeStart + node.getLength();
}
 
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);
		}
	}
 
public boolean covers(ASTNode node) {
	int nodeStart= node.getStartPosition();
	return fStart <= nodeStart && nodeStart + node.getLength() <= fExclusiveEnd;
}
 
源代码18 项目: JDeodorant   文件: CloneInstanceMapper.java
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;
	}
 
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;
	}
}
 
/**
 * 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());
}