org.eclipse.jdt.core.dom.Name Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.Name. 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 Project: junion   Author: TehLeo   File: StructCache.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Entry get(Name type) {
	IBinding b = type.resolveBinding();		
	if(b == null) {
		CompilerError.exec(CompilerError.TYPE_NOT_FOUND, type.toString() + ", " + type.getClass());
		return null;
	}
	if(b instanceof IPackageBinding) {
		return null;
	}
	if(b instanceof ITypeBinding) {
		return get((ITypeBinding)b);
	}
	if(b instanceof IVariableBinding) {
		IVariableBinding vb = (IVariableBinding)b;
		return get(vb.getType());		
	}
	Log.err("IGNORING BINFIND " + b + ", " + b.getClass());
	return null;
}
 
Example #2
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ConstantChecks.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private boolean checkName(Name name) {
	IBinding binding= name.resolveBinding();
	if (binding == null)
		return true;  /* If the binding is null because of compile errors etc.,
		                  scenarios which may have been deemed unacceptable in
		                  the presence of semantic information will be admitted. */

	// If name represents a member:
	if (binding instanceof IVariableBinding || binding instanceof IMethodBinding)
		return isMemberReferenceValidInClassInitialization(name);
	else if (binding instanceof ITypeBinding)
		return ! ((ITypeBinding) binding).isTypeVariable();
	else {
		return true; // e.g. a NameQualifiedType's qualifier, which can be a package binding
	}
}
 
Example #3
Source Project: SnowGraph   Author: linzeqipku   File: NameResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates fully qualified name of the Name object.
 */
private static String getFullName(Name name) {
    // check if the root node is a CompilationUnit
    if (name.getRoot().getClass() != CompilationUnit.class) {
        // cannot resolve a full name, CompilationUnit root node is missing
        return name.getFullyQualifiedName();
    }
    // get the root node
    CompilationUnit root = (CompilationUnit) name.getRoot();
    // check if the name is declared in the same file
    TypeDeclVisitor tdVisitor = new TypeDeclVisitor(name.getFullyQualifiedName());
    root.accept(tdVisitor);
    if (tdVisitor.getFound()) {
        // the name is the use of the TypeDeclaration in the same file
        return getFullName(tdVisitor.getTypeDecl());
    }
    // check if the name is declared in the same package or imported
    PckgImprtVisitor piVisitor = new PckgImprtVisitor(name.getFullyQualifiedName());
    root.accept(piVisitor);
    if (piVisitor.getFound()) {
        // the name is declared in the same package or imported
        return piVisitor.getFullName();
    }
    // could be a class from the java.lang (String) or a param name (T, E,...)
    return name.getFullyQualifiedName();
}
 
Example #4
@Override
public final void endVisit(final QualifiedName node) {
	final ASTNode parent= node.getParent();
	final Name qualifier= node.getQualifier();
	IBinding binding= qualifier.resolveBinding();
	if (binding instanceof ITypeBinding) {
		final ConstraintVariable2 variable= fModel.createTypeVariable((ITypeBinding) binding, new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(node), new SourceRange(qualifier.getStartPosition(), qualifier.getLength())));
		if (variable != null)
			qualifier.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
	}
	binding= node.getName().resolveBinding();
	if (binding instanceof IVariableBinding && !(parent instanceof ImportDeclaration))
		endVisit((IVariableBinding) binding, qualifier, node);
	else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration)
		endVisit((ITypeBinding) binding, node);
}
 
Example #5
private SuperConstructorInvocation addEnclosingInstanceAccess(ASTRewrite rewrite, ImportRewriteContext importRewriteContext, List<SingleVariableDeclaration> parameters, String[] paramNames, ITypeBinding enclosingInstance) {
	AST ast= rewrite.getAST();
	SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();

	SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
	var.setType(getImportRewrite().addImport(enclosingInstance, ast, importRewriteContext));
	String[] enclosingArgNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaProject(), enclosingInstance.getTypeDeclaration().getName(), 0, paramNames);
	String firstName= enclosingArgNames[0];
	var.setName(ast.newSimpleName(firstName));
	parameters.add(var);

	Name enclosing= ast.newSimpleName(firstName);
	invocation.setExpression(enclosing);

	String key= "arg_name_" + firstName; //$NON-NLS-1$
	addLinkedPosition(rewrite.track(enclosing), false, key);
	for (int i= 0; i < enclosingArgNames.length; i++) {
		addLinkedPositionProposal(key, enclosingArgNames[i], null); // alternative names
	}
	return invocation;
}
 
Example #6
Source Project: JDeodorant   Author: tsantalis   File: RefactoringUtility.java    License: MIT License 6 votes vote down vote up
private static boolean isQualifiedType(Type type) {
	if(type instanceof SimpleType) {
		SimpleType simpleType = (SimpleType)type;
		Name name = simpleType.getName();
		if(name instanceof QualifiedName) {
			return true;
		}
	}
	else if(type instanceof QualifiedType) {
		QualifiedType qualifiedType = (QualifiedType)type;
		Type qualifier = qualifiedType.getQualifier();
		return isQualifiedType(qualifier);
	}
	else if(type instanceof ArrayType) {
		ArrayType arrayType = (ArrayType)type;
		Type elementType = arrayType.getElementType();
		return isQualifiedType(elementType);
	}
	else if(type instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType)type;
		Type erasureType = parameterizedType.getType();
		return isQualifiedType(erasureType);
	}
	return false;
}
 
Example #7
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodes.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}).
 * <p>
 * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>!
 * 
 * @param node the starting node, can be <code>null</code>
 * @return the topmost type or <code>null</code> if the node is not a descendant of a type node
 * @see #getNormalizedNode(ASTNode)
 */
public static Type getTopMostType(ASTNode node) {
	ASTNode result= null;
	while (node instanceof Type && !(node instanceof UnionType)
			|| node instanceof Name
			|| node instanceof Annotation || node instanceof MemberValuePair
			|| node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation
		result= node;
		node= node.getParent();
	}
	
	if (result instanceof Type)
		return (Type) result;
	
	return null;
}
 
Example #8
Source Project: eclipse.jdt.ls   Author: eclipse   File: NewCUProposal.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static String getTypeName(int typeKind, Name node) {
	String name = ASTNodes.getSimpleNameIdentifier(node);

	if (isParameterizedType(typeKind, node)) {
		ASTNode parent = node.getParent();
		String typeArgBaseName = getGenericTypeArgBaseName(name);
		int nTypeArgs = ((ParameterizedType) parent.getParent()).typeArguments().size();
		StringBuilder buf = new StringBuilder(name);
		buf.append('<');
		if (nTypeArgs == 1) {
			buf.append(typeArgBaseName);
		} else {
			for (int i = 0; i < nTypeArgs; i++) {
				if (i != 0) {
					buf.append(", "); //$NON-NLS-1$
				}
				buf.append(typeArgBaseName).append(i + 1);
			}
		}
		buf.append('>');
		return buf.toString();
	}
	return name;
}
 
Example #9
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: CodeStyleFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	CompilationUnit compilationUnit= cuRewrite.getRoot();
	importType(fDeclaringClass, fName, cuRewrite.getImportRewrite(), compilationUnit);
	TextEditGroup group;
	if (fName.resolveBinding() instanceof IMethodBinding) {
		group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyMethodWithDeclClass_description, cuRewrite);
	} else {
		group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyFieldWithDeclClass_description, cuRewrite);
	}
	IJavaElement javaElement= fDeclaringClass.getJavaElement();
	if (javaElement instanceof IType) {
		Name qualifierName= compilationUnit.getAST().newName(((IType)javaElement).getElementName());
		SimpleName simpleName= (SimpleName)rewrite.createMoveTarget(fName);
		QualifiedName qualifiedName= compilationUnit.getAST().newQualifiedName(qualifierName, simpleName);
		rewrite.replace(fName, qualifiedName, group);
	}
}
 
Example #10
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodes.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static SimpleName getLeftMostSimpleName(Name name) {
	if (name instanceof SimpleName) {
		return (SimpleName)name;
	} else {
		final SimpleName[] result= new SimpleName[1];
		ASTVisitor visitor= new ASTVisitor() {
			@Override
			public boolean visit(QualifiedName qualifiedName) {
				Name left= qualifiedName.getQualifier();
				if (left instanceof SimpleName)
					result[0]= (SimpleName)left;
				else
					left.accept(this);
				return false;
			}
		};
		name.accept(visitor);
		return result[0];
	}
}
 
Example #11
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode= getGroupRoot();

	List<Expression> allOperands= findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first= allOperands.indexOf(fOperands.get(0));
	int after= first + fOperands.size();
	for (int i= first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #12
Source Project: eclipse.jdt.ls   Author: eclipse   File: OrganizeImportsHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static void addImports(CompilationUnit root, ICompilationUnit unit, String[] favourites, ImportRewrite importRewrite, AST ast, ASTRewrite astRewrite, SimpleName node, boolean isMethod) throws JavaModelException {
	String name = node.getIdentifier();
	String[] imports = SimilarElementsRequestor.getStaticImportFavorites(unit, name, isMethod, favourites);
	if (imports.length > 1) {
		// See https://github.com/redhat-developer/vscode-java/issues/1472
		return;
	}
	for (int i = 0; i < imports.length; i++) {
		String curr = imports[i];
		String qualifiedTypeName = Signature.getQualifier(curr);
		String res = importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite));
		int dot = res.lastIndexOf('.');
		if (dot != -1) {
			String usedTypeName = importRewrite.addImport(qualifiedTypeName);
			Name newName = ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name));
			astRewrite.replace(node, newName, null);
		}
	}
}
 
Example #13
Source Project: spotbugs   Author: spotbugs   File: CreateDoPrivilegedBlockResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
protected MethodInvocation createDoPrivilegedInvocation(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodInvocation doPrivilegedInvocation = ast.newMethodInvocation();
    ClassInstanceCreation privilegedActionCreation = createPrivilegedActionCreation(rewrite, classLoaderCreation);
    List<Expression> arguments = checkedList(doPrivilegedInvocation.arguments());

    if (!isStaticImport()) {
        Name accessControllerName;
        if (isUpdateImports()) {
            accessControllerName = ast.newSimpleName(AccessController.class.getSimpleName());
        } else {
            accessControllerName = ast.newName(AccessController.class.getName());
        }
        doPrivilegedInvocation.setExpression(accessControllerName);
    }
    doPrivilegedInvocation.setName(ast.newSimpleName(DO_PRIVILEGED_METHOD_NAME));
    arguments.add(privilegedActionCreation);

    return doPrivilegedInvocation;
}
 
Example #14
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Checks.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param e
 * @return int
 *          Checks.IS_RVALUE			if e is an rvalue
 *          Checks.IS_RVALUE_GUESSED	if e is guessed as an rvalue
 *          Checks.NOT_RVALUE_VOID  	if e is not an rvalue because its type is void
 *          Checks.NOT_RVALUE_MISC  	if e is not an rvalue for some other reason
 */
public static int checkExpressionIsRValue(Expression e) {
	if (e instanceof Name) {
		if(!(((Name) e).resolveBinding() instanceof IVariableBinding)) {
			return NOT_RVALUE_MISC;
		}
	}
	if (e instanceof Annotation)
		return NOT_RVALUE_MISC;
		

	ITypeBinding tb= e.resolveTypeBinding();
	boolean guessingRequired= false;
	if (tb == null) {
		guessingRequired= true;
		tb= ASTResolving.guessBindingForReference(e);
	}
	if (tb == null)
		return NOT_RVALUE_MISC;
	else if (tb.getName().equals("void")) //$NON-NLS-1$
		return NOT_RVALUE_VOID;

	return guessingRequired ? IS_RVALUE_GUESSED : IS_RVALUE;
}
 
Example #15
Source Project: xtext-xtend   Author: eclipse   File: JavaASTFlattener.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(final SuperMethodInvocation node) {
  Name _qualifier = node.getQualifier();
  boolean _tripleNotEquals = (_qualifier != null);
  if (_tripleNotEquals) {
    node.getQualifier().accept(this);
    this.appendToBuffer(".");
  }
  this.appendToBuffer("super.");
  boolean _isEmpty = node.typeArguments().isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    this.appendTypeParameters(node.typeArguments());
  }
  node.getName().accept(this);
  this.appendToBuffer("(");
  this.visitAllSeparatedByComma(node.arguments());
  this.appendToBuffer(")");
  return false;
}
 
Example #16
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: QuickAssistProcessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static ITypeBinding extractExpressionType(SimpleType variableIdentifier) {
	ScopeAnalyzer analyzer= new ScopeAnalyzer((CompilationUnit) variableIdentifier.getRoot());
	// get the name of the variable to search the type for
	Name name= null;
	if (variableIdentifier.getName() instanceof SimpleName) {
		name= variableIdentifier.getName();
	} else if (variableIdentifier.getName() instanceof QualifiedName) {
		name= ((QualifiedName) variableIdentifier.getName()).getName();
	}

	// analyze variables which are available in the scope at the position of the quick assist invokation
	IBinding[] declarationsInScope= analyzer.getDeclarationsInScope(name.getStartPosition(), ScopeAnalyzer.VARIABLES);
	for (int i= 0; i < declarationsInScope.length; i++) {
		IBinding currentVariable= declarationsInScope[i];
		if (((IVariableBinding) currentVariable).getName().equals(name.getFullyQualifiedName())) {
			return ((IVariableBinding) currentVariable).getType();
		}
	}
	return null;
}
 
Example #17
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: RegionUpdaterFactory.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new region updater for the given text edit contained within the
 * given node.
 * 
 * @param originalEdit the text edit
 * @param node the most-specific node that contains the text edit
 * @param referenceUpdater an reference updater knowledgeable about the
 *          refactoring that is taking place
 * @param matcher an AST matcher knowledgeable about refactoring that is
 *          taking place
 * @return a region updater instance for the given text edit
 * @throws RefactoringException if there was an error creating a region
 *           updater
 */
public static RegionUpdater newRegionUpdater(ReplaceEdit originalEdit,
    ASTNode node, ReferenceUpdater referenceUpdater, ASTMatcher matcher)
    throws RefactoringException {

  if (node instanceof Name) {
    return new NameRegionUpdater(originalEdit, referenceUpdater, (Name) node,
        matcher);

  } else if (node instanceof TextElement) {
    return new TextElementRegionUpdater(originalEdit, referenceUpdater,
        (TextElement) node, matcher);
  }

  throw new RefactoringException("This AST node type is not supported");
}
 
Example #18
Source Project: lapse-plus   Author: OWASP   File: CallerFinder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Collection<Utils.ExpressionUnitPair> getActualsForFormal(IMethod method, Name name, Expression onlyCall, IProgressMonitor monitor, IJavaProject project) {
	Collection<Utils.ExpressionUnitPair> result = new ArrayList<Utils.ExpressionUnitPair>();
	Collection/*<MethodUnitPair>*/ c = findCallers(monitor, method, project);
	if (c.isEmpty()) {
		log("No callers for " + method);
	} else {
		monitor.beginTask("Getting actuals for " + name + " in " + method.getElementName(), c.size());
		int i = 0;
		for (Iterator iter = c.iterator(); iter.hasNext();) {
			Utils.ExprUnitResource mi = (Utils.ExprUnitResource) iter.next();
			int pos = SlicingUtils.getFormalArgumentPos(method, name);
			if (pos == SlicingUtils.NO_FORMAL_ARGUMENT) {
				log("No parameter " + name + " found in " + method);
				continue;
			}
			if (mi.getExpression() == null) {
				logError("unexpected error: mi.getExpression() == null when looking at " + name + " and " + method);
				continue;
			}
			String s1 = mi.getExpression().toString();
			//String s2 = onlyCall.toString();
			if ( (onlyCall != null) && (!s1.equals(onlyCall.toString())) ) {
				log("Skipping " + mi.getExpression() + "while looking for " + onlyCall + " instead");
				continue;
			}
			Expression expr = SlicingUtils.mapFormal2Actual(mi.getExpression(), pos);
			if(expr != null) {
				result.add(new Utils.ExpressionUnitPair(expr, mi.getCompilationUnit(), mi.getResource()));	
			}			
			monitor.worked(++i);
		}
		monitor.done();
	}
	
	return result;
}
 
Example #19
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: TypeContextChecker.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding resolveSuperClass(String superclass, IType typeHandle, StubTypeContext superClassContext) {
	StringBuffer cuString= new StringBuffer();
	cuString.append(superClassContext.getBeforeString());
	cuString.append(superclass);
	cuString.append(superClassContext.getAfterString());

	try {
		ICompilationUnit wc= typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
		try {
			wc.getBuffer().setContents(cuString.toString());
			CompilationUnit compilationUnit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true);
			ASTNode type= NodeFinder.perform(compilationUnit, superClassContext.getBeforeString().length(), superclass.length());
			if (type instanceof Type) {
				return handleBug84585(((Type) type).resolveBinding());
			} else if (type instanceof Name) {
				ASTNode parent= type.getParent();
				if (parent instanceof Type)
					return handleBug84585(((Type) parent).resolveBinding());
			}
			throw new IllegalStateException();
		} finally {
			wc.discardWorkingCopy();
		}
	} catch (JavaModelException e) {
		return null;
	}
}
 
Example #20
Source Project: JDeodorant   Author: tsantalis   File: SwitchControlCase.java    License: MIT License 5 votes vote down vote up
private String getConstantValue(Name name)
{
	IBinding nameBinding = name.resolveBinding();
	if (nameBinding.getKind() == IBinding.VARIABLE)
	{
		IVariableBinding nameVariableBinding = (IVariableBinding)nameBinding;
		Object valueObject = nameVariableBinding.getConstantValue();
		if (valueObject instanceof Integer || valueObject instanceof Byte || valueObject instanceof Character || valueObject instanceof String)
		{
			return valueObject.toString();
		}
	}
	return null;
}
 
Example #21
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Checks.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isEnumCase(ASTNode node) {
	if (node instanceof SwitchCase) {
		final SwitchCase caze= (SwitchCase) node;
		final Expression expression= caze.getExpression();
		if (expression instanceof Name) {
			final Name name= (Name) expression;
			final IBinding binding= name.resolveBinding();
			if (binding instanceof IVariableBinding) {
				IVariableBinding variableBinding= (IVariableBinding) binding;
				return variableBinding.isEnumConstant();
			}
		}
	}
	return false;
}
 
Example #22
private static ParameterizedType rewriteTypeVariable(TypeVariable2 typeCv, CompilationUnitRewrite rewrite, InferTypeArgumentsTCModel tCModel, boolean leaveUnconstraindRaw, SimpleType[] types) {
	ASTNode node= typeCv.getRange().getNode(rewrite.getRoot());
	if (node instanceof Name && node.getParent() instanceof Type) {
		Type originalType= (Type) node.getParent();

		if (types != null && !has(types, originalType))
			return null;

		// Must rewrite all type arguments in one batch. Do the rewrite when the first one is encountered; skip the others.
		Object rewritten= originalType.getProperty(REWRITTEN);
		if (rewritten == REWRITTEN)
			return null;
		originalType.setProperty(REWRITTEN, REWRITTEN);

		ArrayList<CollectionElementVariable2> typeArgumentCvs= getTypeArgumentCvs(typeCv, tCModel);
		Type[] typeArguments= getTypeArguments(originalType, typeArgumentCvs, rewrite, tCModel, leaveUnconstraindRaw);
		if (typeArguments == null)
			return null;

		Type movingType= (Type) rewrite.getASTRewrite().createMoveTarget(originalType);
		ParameterizedType newType= rewrite.getAST().newParameterizedType(movingType);

		for (int i= 0; i < typeArguments.length; i++) {
			newType.typeArguments().add(typeArguments[i]);
		}

		rewrite.getASTRewrite().replace(originalType, newType, rewrite.createGroupDescription(RefactoringCoreMessages.InferTypeArgumentsRefactoring_addTypeArguments));
		return newType;
	}  else {//TODO: other node types?
		return null;
	}
}
 
Example #23
Source Project: SimFix   Author: xgdsmileboy   File: Repair.java    License: GNU General Public License v2.0 5 votes vote down vote up
private List<Set<Integer>> consistentModification(List<Modification> modifications){
	List<Set<Integer>> result = new LinkedList<>();
	String regex = "[A-Za-z_][0-9A-Za-z_.]*";
	Pattern pattern = Pattern.compile(regex);
	for(int i = 0; i < modifications.size(); i++){
		Modification modification = modifications.get(i);
		if(modification instanceof Revision){
			Set<Integer> consistant = new HashSet<>();
			consistant.add(i);
			for(int j = i + 1; j < modifications.size(); j++){
				Modification other = modifications.get(j);
				if(other instanceof Revision){
					if(modification.compatible(other) && modification.getTargetString().equals(other.getTargetString())){
						ASTNode node = JavaFile.genASTFromSource(modification.getTargetString(), ASTParser.K_EXPRESSION);
						if(node instanceof Name || node instanceof FieldAccess || pattern.matcher(modification.getTargetString()).matches()){
							consistant.add(j);
						}
					}
				}
			}
			if(consistant.size() > 1){
				result.add(consistant);
			}
		}
	}
	
	return result;
}
 
Example #24
Source Project: SimFix   Author: xgdsmileboy   File: CodeBlock.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Label visit(Name node) {
		int startLine = _cunit.getLineNumber(node.getStartPosition());
		int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
		Label expr = null;
		if(node instanceof SimpleName){
			SName sName = new SName(startLine, endLine, node);

			String name = node.getFullyQualifiedName();
			sName.setName(name);
			Pair<String, String> classAndMethodName = NodeUtils.getTypeDecAndMethodDec(node);
			Type type = ProjectInfo.getVariableType(classAndMethodName.getFirst(), classAndMethodName.getSecond(), node.toString());
			
			sName.setType(type);
			expr = sName;
		} else if(node instanceof QualifiedName){
			QualifiedName qualifiedName = (QualifiedName) node;
//			System.out.println(qualifiedName.toString());
			QName qName = new QName(startLine, endLine, node);
			SName sname = (SName) process(qualifiedName.getName());
			sname.setParent(qName);
			Label label = (Label) process(qualifiedName.getQualifier());
			label.setParent(qName);
			qName.setName(label, sname);
			qName.setType(sname.getType());
			
			expr = qName;
		}
		return expr;
	}
 
Example #25
private int evaluateModifiers(ASTNode targetTypeDecl) {
	if (getSenderBinding().isAnnotation()) {
		return 0;
	}
	if (getSenderBinding().isInterface()) {
		// for interface and annotation members copy the modifiers from an existing field
		MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods();
		if (methodDecls.length > 0) {
			return methodDecls[0].getModifiers();
		}
		return 0;
	}
	ASTNode invocationNode= getInvocationNode();
	if (invocationNode instanceof MethodInvocation) {
		int modifiers= 0;
		Expression expression= ((MethodInvocation)invocationNode).getExpression();
		if (expression != null) {
			if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
				modifiers |= Modifier.STATIC;
			}
		} else if (ASTResolving.isInStaticContext(invocationNode)) {
			modifiers |= Modifier.STATIC;
		}
		ASTNode node= ASTResolving.findParentType(invocationNode);
		if (targetTypeDecl.equals(node)) {
			modifiers |= Modifier.PRIVATE;
		} else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
			modifiers |= Modifier.PROTECTED;
			if (ASTResolving.isInStaticContext(node) && expression == null) {
				modifiers |= Modifier.STATIC;
			}
		} else {
			modifiers |= Modifier.PUBLIC;
		}
		return modifiers;
	}
	return Modifier.PUBLIC;
}
 
Example #26
private boolean isParameter(ParameterInfo pi, ASTNode node, List<SingleVariableDeclaration> enclosingMethodParameters, String qualifier) {
	if (node instanceof Name) {
		Name name= (Name) node;
		IVariableBinding binding= ASTNodes.getVariableBinding(name);
		if (binding != null && binding.isParameter()) {
			return binding.getName().equals(getNameInScope(pi, enclosingMethodParameters));
		} else {
			if (node instanceof QualifiedName) {
				QualifiedName qn= (QualifiedName) node;
				return qn.getFullyQualifiedName().equals(JavaModelUtil.concatenateName(qualifier, getNameInScope(pi, enclosingMethodParameters)));
			}
		}
	}
	return false;
}
 
Example #27
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: TypeContextChecker.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static Type parseSuperType(String superType, boolean isInterface) {
	if (! superType.trim().equals(superType)) {
		return null;
	}

	StringBuffer cuBuff= new StringBuffer();
	if (isInterface)
		cuBuff.append("class __X__ implements "); //$NON-NLS-1$
	else
		cuBuff.append("class __X__ extends "); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(superType).append(" {}"); //$NON-NLS-1$

	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	Map<String, String> options= new HashMap<String, String>();
	JavaModelUtil.setComplianceOptions(options, JavaModelUtil.VERSION_LATEST);
	p.setCompilerOptions(options);
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	ASTNode selected= NodeFinder.perform(cu, offset, superType.length());
	if (selected instanceof Name)
		selected= selected.getParent();
	if (selected.getStartPosition() != offset
			|| selected.getLength() != superType.length()
			|| ! (selected instanceof Type)
			|| selected instanceof PrimitiveType) {
		return null;
	}
	Type type= (Type) selected;

	String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
	if (! superType.equals(typeNodeRange)){
		return null;
	}
	return type;
}
 
Example #28
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: CopyQualifiedNameAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the given name belongs to a {@link ClassInstanceCreation} and if so, returns
 * its constructor binding.
 * 
 * @param nameNode the name node
 * @return the constructor binding or <code>null</code> if not found
 * @since 3.7
 */
private IBinding getConstructorBindingIfAvailable(Name nameNode) {
	ASTNode type= ASTNodes.getNormalizedNode(nameNode);
	StructuralPropertyDescriptor loc= type.getLocationInParent();
	if (loc == ClassInstanceCreation.TYPE_PROPERTY) {
		return ((ClassInstanceCreation) type.getParent()).resolveConstructorBinding();
	}
	return null;
}
 
Example #29
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ConvertForLoopOperation.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static IBinding getBinding(Expression expression) {
	if (expression instanceof FieldAccess) {
		return ((FieldAccess)expression).resolveFieldBinding();
	} else if (expression instanceof Name) {
		return ((Name)expression).resolveBinding();
	}

	return null;
}
 
Example #30
Source Project: eclipse.jdt.ls   Author: eclipse   File: RenameAnalyzeUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method analyzes a set of local variable renames inside one cu. It checks whether
 * any new compile errors have been introduced by the rename(s) and whether the correct
 * node(s) has/have been renamed.
 *
 * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
 * @param cuChange the TextChange containing all local variable changes to be applied.
 * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
 * @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
 * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
 * @throws CoreException thrown if there was an error greating the preview content of the change
 */
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {

	RefactoringStatus result= new RefactoringStatus();
	ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement();

	String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);

	result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
	if (result.hasError()) {
		return result;
	}

	for (int i= 0; i < analyzePackages.length; i++) {
		ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

		// get new declaration
		IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
		ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
		Assert.isTrue(newDeclaration instanceof Name);

		VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
		Assert.isNotNull(declaration);

		SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
		result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
	}
	return result;
}