org.eclipse.jdt.core.dom.SimpleName#getStartPosition ( )源码实例Demo

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

@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
源代码2 项目: JDeodorant   文件: ConditionalLoop.java
private static List<ASTNode> getAllVariableModifiersInParentBlock(SimpleName variable, Block block)
{
	List<ASTNode> bodyVariableModifiers = new ArrayList<ASTNode>();
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
	bodyVariableModifiers.addAll(expressionExtractor.getAssignments(block));
	// remove all variable updaters that are not modifying the specified variable or are after the position of the variable in use
	Iterator<ASTNode> it = bodyVariableModifiers.iterator();
	while (it.hasNext())
	{
		ASTNode currentNode = it.next();
		if (currentNode instanceof Expression)
		{
			Expression currentExpression = (Expression) currentNode;
			if (!AbstractLoopUtilities.isUpdatingVariable(currentExpression, variable) || currentExpression.getStartPosition() >= variable.getStartPosition())
			{
				it.remove();
			}
		}
	}
	return bodyVariableModifiers;
}
 
源代码3 项目: KodeBeagle   文件: MethodInvocationResolver.java
private MethodDecl getMethodDecl(MethodDeclaration node) {
    String qualifiedTypeName = currentPackage + "."
            + Joiner.on(".").skipNulls().join(typesInFile);
    SimpleName nameNode = node.getName();
    String methodName = nameNode.toString();
    String returnType = "";
    if (node.getReturnType2() != null) {
        returnType = getNameOfType(node.getReturnType2());
    }

    Map<String, String> params = new HashMap<>();
    for (Object p : node.parameters()) {
        if (p instanceof SingleVariableDeclaration) {

            SingleVariableDeclaration svd = (SingleVariableDeclaration) p;
            String varName = svd.getName().toString();
            Type type = svd.getType();
            String typeName = getNameOfType(type);

            params.put(varName, typeName);
        } else {
            System.err.println("Unxepected AST node type for param - " + p);
        }

    }
    return new MethodDecl(methodName, qualifiedTypeName, returnType, nameNode
            .getStartPosition(), params);
}
 
private boolean isInRemoved(SimpleName ref, List<int[]> removedStartsEnds) {
	int start= ref.getStartPosition();
	int end= start + ref.getLength();
	for (int[] removedStartsEnd : removedStartsEnds) {
		if (start >= removedStartsEnd[0] && end <= removedStartsEnd[1]) {
			return true;
		}
	}
	return false;
}
 
private static int getNameNodeProblemKind(IProblem[] problems, SimpleName nameNode) {
	int nameOffset= nameNode.getStartPosition();
	int nameInclEnd= nameOffset + nameNode.getLength() - 1;

	for (int i= 0; i < problems.length; i++) {
		IProblem curr= problems[i];
		if (curr.getSourceStart() == nameOffset && curr.getSourceEnd() == nameInclEnd) {
			int kind= getProblemKind(curr);
			if (kind != 0) {
				return kind;
			}
		}
	}
	return 0;
}
 
源代码6 项目: JDeodorant   文件: PreconditionExaminer.java
private boolean isInsideDifference(SimpleName simpleName, Expression difference) {
	int startOffset = simpleName.getStartPosition();
	int endOffset = simpleName.getStartPosition() + simpleName.getLength();
	int differenceStartOffset = difference.getStartPosition();
	int differenceEndOffset = difference.getStartPosition() + difference.getLength();
	if(startOffset >= differenceStartOffset && endOffset <= differenceEndOffset)
		return true;
	return false;
}
 
源代码7 项目: JDeodorant   文件: ControlVariable.java
private static List<ASTNode> getAllVariableModifiersInParentMethod(SimpleName variable)
{
	List<ASTNode> bodyVariableModifiers = new ArrayList<ASTNode>();
	MethodDeclaration parentMethod = AbstractLoopUtilities.findParentMethodDeclaration(variable);
	if (parentMethod != null)
	{
		Block parentMethodBody = parentMethod.getBody();
		if (parentMethodBody != null)
		{
			ExpressionExtractor expressionExtractor = new ExpressionExtractor();
			bodyVariableModifiers.addAll(expressionExtractor.getVariableModifiers(parentMethodBody));
			// remove all variable updaters that are not modifying the specified variable or are after the position of the variable in use
			Iterator<ASTNode> it = bodyVariableModifiers.iterator();
			while (it.hasNext())
			{
				ASTNode currentNode = it.next();
				if (currentNode instanceof Expression)
				{
					Expression currentExpression = (Expression) currentNode;
					if (!AbstractLoopUtilities.isUpdatingVariable(currentExpression, variable) || currentExpression.getStartPosition() >= variable.getStartPosition())
					{
						it.remove();
					}
				}
			}
			// add the variable's declaration
			VariableDeclaration variableDeclaration = AbstractLoopUtilities.getVariableDeclaration(variable);
			if (variableDeclaration != null)
			{
				bodyVariableModifiers.add(0, variableDeclaration);
			}
		}
	}
	return bodyVariableModifiers;
}
 
private ASTRewrite doAddField(CompilationUnit astRoot) {
	SimpleName node= fOriginalNode;
	boolean isInDifferentCU= false;

	ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
	if (newTypeDecl == null) {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
		isInDifferentCU= true;
	}
	ImportRewrite imports= createImportRewrite(astRoot);
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);

	if (newTypeDecl != null) {
		AST ast= newTypeDecl.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(node.getIdentifier()));

		Type type= evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding, TypeLocation.FIELD);

		FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
		newDecl.setType(type);
		newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));

		if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
			fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
		}

		ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> decls= ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);

		int maxOffset= isInDifferentCU ? -1 : node.getStartPosition();

		int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset);

		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
		listRewriter.insertAt(newDecl, insertIndex, null);

		return rewrite;
	}
	return null;
}
 
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);
		}
	}
 
private ASTRewrite doAddField(CompilationUnit astRoot) {
	SimpleName node= fOriginalNode;
	boolean isInDifferentCU= false;

	ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
	if (newTypeDecl == null) {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
		isInDifferentCU= true;
	}
	ImportRewrite imports= createImportRewrite(astRoot);
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);

	if (newTypeDecl != null) {
		AST ast= newTypeDecl.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(node.getIdentifier()));

		Type type= evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);

		FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
		newDecl.setType(type);
		newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));

		if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
			fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
		}

		ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> decls= ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);

		int maxOffset= isInDifferentCU ? -1 : node.getStartPosition();

		int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset);

		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
		listRewriter.insertAt(newDecl, insertIndex, null);

		ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());

		addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
		if (!isInDifferentCU) {
			addLinkedPosition(rewrite.track(node), true, KEY_NAME);
		}
		addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);

		if (fragment.getInitializer() != null) {
			addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
		}
		return rewrite;
	}
	return null;
}
 
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
	if (this.createdNode == null) {
		this.source = removeIndentAndNewLines(this.source, cu);
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(this.source.toCharArray());
		parser.setProject(getCompilationUnit().getJavaProject());
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
		ASTNode node = parser.createAST(this.progressMonitor);
		String createdNodeSource;
		if (node.getNodeType() != ASTNode.TYPE_DECLARATION) {
			createdNodeSource = generateSyntaxIncorrectAST();
			if (this.createdNode == null)
				throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
		} else {
			TypeDeclaration typeDeclaration = (TypeDeclaration) node;
			if ((typeDeclaration.getFlags() & ASTNode.MALFORMED) != 0) {
				createdNodeSource = generateSyntaxIncorrectAST();
				if (this.createdNode == null)
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
			} else {
				List bodyDeclarations = typeDeclaration.bodyDeclarations();
				if (bodyDeclarations.size() == 0) {
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
				}
				this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
				createdNodeSource = this.source;
			}
		}
		if (this.alteredName != null) {
			SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
			SimpleName oldName = rename(this.createdNode, newName);
			int nameStart = oldName.getStartPosition();
			int nameEnd = nameStart + oldName.getLength();
			StringBuffer newSource = new StringBuffer();
			if (this.source.equals(createdNodeSource)) {
				newSource.append(createdNodeSource.substring(0, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd));
			} else {
				// syntactically incorrect source
				int createdNodeStart = this.createdNode.getStartPosition();
				int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
				newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));

			}
			this.source = newSource.toString();
		}
	}
	if (rewriter == null) return this.createdNode;
	// return a string place holder (instead of the created node) so has to not lose comments and formatting
	return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
}