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

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#getStartPosition() . 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: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IBinding[] getDeclarationsAfter(int offset, int flags) {
	try {
		org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
		ASTNode node= finder.getCoveringNode();
		if (node == null) {
			return null;
		}

		ASTNode declaration= ASTResolving.findParentStatement(node);
		while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) {
			declaration= declaration.getParent();
		}

		if (declaration instanceof Block) {
			DefaultBindingRequestor requestor= new DefaultBindingRequestor();
			DeclarationsAfterVisitor visitor= new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor);
			declaration.accept(visitor);
			List<IBinding> result= requestor.getResult();
			return result.toArray(new IBinding[result.size()]);
		}
		return NO_BINDING;
	} finally {
		clearLists();
	}
}
 
Example 2
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ASTNode getDominantNode(SimpleName[] names) {
	ASTNode dominator= names[0]; //ASTResolving.findParentStatement(names[0]);
	for (int i= 1; i < names.length; i++) {
		ASTNode curr= names[i];// ASTResolving.findParentStatement(names[i]);
		if (curr != dominator) {
			ASTNode parent= getCommonParent(curr, dominator);

			if (curr.getStartPosition() < dominator.getStartPosition()) {
				dominator= curr;
			}
			while (dominator.getParent() != parent) {
				dominator= dominator.getParent();
			}
		}
	}
	int parentKind= dominator.getParent().getNodeType();
	if (parentKind != ASTNode.BLOCK && parentKind != ASTNode.FOR_STATEMENT) {
		return dominator.getParent();
	}
	return dominator;
}
 
Example 3
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 4
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean addProblem(final ASTNode node, final String string) {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append(string);
  _builder.append(" (start: ");
  int _startPosition = node.getStartPosition();
  _builder.append(_startPosition);
  _builder.append(", length: ");
  int _length = node.getLength();
  _builder.append(_length);
  _builder.append(")");
  return this.problems.add(_builder.toString());
}
 
Example 5
Source File: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int getStartPos(ASTNode node) {
	int n = node.getStartPosition();
	while(n == -1) {
		node = node.getParent();
		if(node == null) return n;
		n = node.getStartPosition();
	}
	return n;
}
 
Example 6
Source File: InvertBooleanUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isSelectingOperator(ASTNode n1, ASTNode n2, int offset, int length) {
	// between the nodes
	if (offset + length <= n2.getStartPosition() && offset >= ASTNodes.getExclusiveEnd(n1)) {
		return true;
	}
	// or exactly select the node (but not with infix expressions)
	if (n1.getStartPosition() == offset && ASTNodes.getExclusiveEnd(n2) == offset + length) {
		if (n1 instanceof InfixExpression || n2 instanceof InfixExpression) {
			return false;
		}
		return true;
	}
	return false;
}
 
Example 7
Source File: InlineTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkAssignments(VariableDeclaration decl) {
	TempAssignmentFinder assignmentFinder= new TempAssignmentFinder(decl);
	getASTRoot().accept(assignmentFinder);
	if (!assignmentFinder.hasAssignments())
		return new RefactoringStatus();
	ASTNode firstAssignment= assignmentFinder.getFirstAssignment();
	int start= firstAssignment.getStartPosition();
	int length= firstAssignment.getLength();
	ISourceRange range= new SourceRange(start, length);
	RefactoringStatusContext context= JavaStatusContext.create(fCu, range);
	String message= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_assigned_more_once, BasicElementLabels.getJavaElementName(decl.getName().getIdentifier()));
	return RefactoringStatus.createFatalErrorStatus(message, context);
}
 
Example 8
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void visitBackwards(List<? extends ASTNode> list) {
	if (fBreak)
		return;

	for (int i= list.size() - 1; i >= 0; i--) {
		ASTNode curr= list.get(i);
		if (curr.getStartPosition() <  fPosition) {
			curr.accept(this);
		}
	}
}
 
Example 9
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 10
Source File: TempOccurrenceAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addOffsets(int[] offsets, int start, Set<SimpleName> nodeSet) {
	int i= start;
	for (Iterator<SimpleName> iter= nodeSet.iterator(); iter.hasNext(); i++) {
		ASTNode node= iter.next();
		offsets[i]= node.getStartPosition();
	}
}
 
Example 11
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 12
Source File: StructureSelectPreviousAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean visitNode(ASTNode node) {
	int start= node.getStartPosition();
	int end= start + node.getLength();
	if (end == fOffset) {
		fPreviousNode= node;
		return true;
	} else {
		return (start < fOffset && fOffset < end);
	}
}
 
Example 13
Source File: IdentifierPerType.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static final void addToMap(
		final Map<String, RangeSet<Integer>> identifiers,
		final ASTNode node, final String identifier) {
	final int startPosition = node.getStartPosition();
	final Range<Integer> nodeRange = Range.closedOpen(startPosition,
			startPosition + node.getLength());

	RangeSet<Integer> idRanges = identifiers.get(identifier);
	if (idRanges == null) {
		idRanges = TreeRangeSet.create();
		identifiers.put(identifier, idRanges);
	}

	idRanges.add(nodeRange);
}
 
Example 14
Source File: SourceRangeFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static ISourceRange create(ASTNode node) {
	return new SourceRange(node.getStartPosition(), node.getLength());
}
 
Example 15
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public SourceRange computeSourceRange(ASTNode node) {
	return new SourceRange(node.getStartPosition(),node.getLength());
}
 
Example 16
Source File: InputFlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean traverseNode(ASTNode node) {
	return node.getStartPosition() + node.getLength() > fSelection.getInclusiveEnd();
}
 
Example 17
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 18
Source File: ASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void validateIsExistingNode(ASTNode node) {
	if (node.getStartPosition() == -1) {
		throw new IllegalArgumentException("Node is not an existing node"); //$NON-NLS-1$
	}
}
 
Example 19
Source File: CodeScopeBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private CodeScopeBuilder(ASTNode node, IBinding ignore) {
	fScope= new Scope(null, node.getStartPosition(), node.getLength());
	fScopes= new ArrayList<Scope>();
	fIgnoreBinding= ignore;
}
 
Example 20
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns true if this is an existing node, i.e. it was created as part of
 * a parsing process of a source code file. Returns false if this is a newly
 * created node which has not yet been given a source position.
 *
 * @param node the node to be tested.
 * @return true if this is an existing node, false if not.
 */
public static boolean isExistingNode(ASTNode node) {
	return node.getStartPosition() != -1;
}