List of usage examples for org.eclipse.jdt.internal.compiler ASTVisitor ASTVisitor
ASTVisitor
From source file:com.google.gwt.dev.javac.GwtIncompatiblePreprocessor.java
License:Apache License
/** * Process inner classes, methods and fields from all anonymous inner classes. * * <p>Anonymous inner classes are represented inside expressions. Traverse the JDT AST removing * anonymous inner classes in one go./*from ww w. ja v a 2 s. c om*/ */ private static void processAllAnonymousInnerClasses(CompilationUnitDeclaration cud) { ASTVisitor visitor = new ASTVisitor() { // Anonymous types are represented within the AST expression that creates the it. @Override public void endVisit(QualifiedAllocationExpression qualifiedAllocationExpression, BlockScope scope) { if (qualifiedAllocationExpression.anonymousType != null) { processMembers(qualifiedAllocationExpression.anonymousType); } } }; cud.traverse(visitor, cud.scope); }
From source file:com.google.gwt.dev.javac.MethodVisitor.java
License:Open Source License
/** * Collect data about interesting methods in one compilation unit. * /*w w w . j a va2s .co m*/ * @param cud */ public final void collect(final CompilationUnitDeclaration cud) { cud.traverse(new ASTVisitor() { @Override public void endVisit(TypeDeclaration type, BlockScope scope) { collectMethods(cud, type); } @Override public void endVisit(TypeDeclaration type, ClassScope scope) { collectMethods(cud, type); } @Override public void endVisit(TypeDeclaration type, CompilationUnitScope scope) { collectMethods(cud, type); } }, cud.scope); }
From source file:lombok.eclipse.handlers.HandleHelper.java
License:Open Source License
@Override public void handle(AnnotationValues<Helper> annotation, Annotation ast, EclipseNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.HELPER_FLAG_USAGE, "@Helper"); EclipseNode annotatedType = annotationNode.up(); EclipseNode containingMethod = annotatedType == null ? null : annotatedType.up(); if (annotatedType == null || containingMethod == null || annotatedType.getKind() != Kind.TYPE || containingMethod.getKind() != Kind.METHOD) { annotationNode.addError("@Helper is legal only on method-local classes."); return;//from w w w .ja v a2 s. c o m } TypeDeclaration annotatedType_ = (TypeDeclaration) annotatedType.get(); AbstractMethodDeclaration amd = (AbstractMethodDeclaration) containingMethod.get(); Statement[] origStatements = amd.statements; int indexOfType = -1; for (int i = 0; i < origStatements.length; i++) { if (origStatements[i] == annotatedType_) { indexOfType = i; break; } } final List<String> knownMethodNames = new ArrayList<String>(); for (AbstractMethodDeclaration methodOfHelper : annotatedType_.methods) { if (!(methodOfHelper instanceof MethodDeclaration)) continue; char[] name = methodOfHelper.selector; if (name != null && name.length > 0 && name[0] != '<') knownMethodNames.add(new String(name)); } Collections.sort(knownMethodNames); final String[] knownMethodNames_ = knownMethodNames.toArray(new String[knownMethodNames.size()]); final char[] helperName = new char[annotatedType_.name.length + 1]; final boolean[] helperUsed = new boolean[1]; helperName[0] = '$'; System.arraycopy(annotatedType_.name, 0, helperName, 1, helperName.length - 1); ASTVisitor visitor = new ASTVisitor() { @Override public boolean visit(MessageSend messageSend, BlockScope scope) { if (messageSend.receiver instanceof ThisReference) { if ((((ThisReference) messageSend.receiver).bits & ASTNode.IsImplicitThis) == 0) return true; } else if (messageSend.receiver != null) return true; char[] name = messageSend.selector; if (name == null || name.length == 0 || name[0] == '<') return true; String n = new String(name); if (Arrays.binarySearch(knownMethodNames_, n) < 0) return true; messageSend.receiver = new SingleNameReference(helperName, Eclipse.pos(messageSend)); helperUsed[0] = true; return true; } }; for (int i = indexOfType + 1; i < origStatements.length; i++) { origStatements[i].traverse(visitor, null); } if (!helperUsed[0]) { annotationNode.addWarning("No methods of this helper class are ever used."); return; } Statement[] newStatements = new Statement[origStatements.length + 1]; System.arraycopy(origStatements, 0, newStatements, 0, indexOfType + 1); System.arraycopy(origStatements, indexOfType + 1, newStatements, indexOfType + 2, origStatements.length - indexOfType - 1); LocalDeclaration decl = new LocalDeclaration(helperName, 0, 0); decl.modifiers |= ClassFileConstants.AccFinal; AllocationExpression alloc = new AllocationExpression(); alloc.type = new SingleTypeReference(annotatedType_.name, 0L); decl.initialization = alloc; decl.type = new SingleTypeReference(annotatedType_.name, 0L); SetGeneratedByVisitor sgbvVisitor = new SetGeneratedByVisitor(annotationNode.get()); decl.traverse(sgbvVisitor, null); newStatements[indexOfType + 1] = decl; amd.statements = newStatements; }
From source file:org.conqat.engine.java.ecj.JavaMethodCallAnalyzerBase.java
License:Apache License
/** {@inheritDoc} */ @Override//from w w w . ja va2s . co m protected void processAST(CompilationUnitDeclaration ast, final IJavaElement javaElement) { ast.traverse(new ASTVisitor() { @Override public boolean visit(AllocationExpression allocationExpression, BlockScope scope) { process(allocationExpression.binding, javaElement); return super.visit(allocationExpression, scope); } @Override public boolean visit(MessageSend messageSend, BlockScope scope) { process(messageSend.binding, javaElement); return super.visit(messageSend, scope); } }, (CompilationUnitScope) null); }
From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java
License:Open Source License
public ASTNode[] parseClassBodyDeclarations(char[] source, int offset, int length, CompilationUnitDeclaration unit) { boolean oldDiet = this.diet; /* automaton initialization */ initialize();//from ww w .j av a2s. c o m goForClassBodyDeclarations(); /* scanner initialization */ this.scanner.setSource(source); this.scanner.resetTo(offset, offset + length - 1); if (this.javadocParser != null && this.javadocParser.checkDocComment) { this.javadocParser.scanner.setSource(source); this.javadocParser.scanner.resetTo(offset, offset + length - 1); } /* type declaration should be parsed as member type declaration */ this.nestedType = 1; /* unit creation */ TypeDeclaration referenceContextTypeDeclaration = new TypeDeclaration(unit.compilationResult); referenceContextTypeDeclaration.name = Util.EMPTY_STRING.toCharArray(); referenceContextTypeDeclaration.fields = new FieldDeclaration[0]; this.compilationUnit = unit; unit.types = new TypeDeclaration[1]; unit.types[0] = referenceContextTypeDeclaration; this.referenceContext = unit; /* run automaton */ try { this.diet = true; parse(); } catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; } finally { this.diet = oldDiet; } ASTNode[] result = null; if (this.lastAct == ERROR_ACTION) { if (!this.options.performMethodsFullRecovery && !this.options.performStatementsRecovery) { return null; } // collect all body declaration inside the compilation unit except the default constructor final List bodyDeclarations = new ArrayList(); ASTVisitor visitor = new ASTVisitor() { public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { if (!methodDeclaration.isDefaultConstructor()) { bodyDeclarations.add(methodDeclaration); } return false; } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { bodyDeclarations.add(fieldDeclaration); return false; } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { bodyDeclarations.add(memberTypeDeclaration); return false; } }; unit.ignoreFurtherInvestigation = false; unit.traverse(visitor, unit.scope); unit.ignoreFurtherInvestigation = true; result = (ASTNode[]) bodyDeclarations.toArray(new ASTNode[bodyDeclarations.size()]); } else { int astLength; if (this.astLengthPtr > -1 && (astLength = this.astLengthStack[this.astLengthPtr--]) != 0) { result = new ASTNode[astLength]; this.astPtr -= astLength; System.arraycopy(this.astStack, this.astPtr + 1, result, 0, astLength); } else { // empty class body declaration (like ';' see https://bugs.eclipse.org/bugs/show_bug.cgi?id=280079). result = new ASTNode[0]; } } boolean containsInitializers = false; TypeDeclaration typeDeclaration = null; for (int i = 0, max = result.length; i < max; i++) { // parse each class body declaration ASTNode node = result[i]; if (node instanceof TypeDeclaration) { ((TypeDeclaration) node).parseMethods(this, unit); } else if (node instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration) node).parseStatements(this, unit); } else if (node instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) node; switch (fieldDeclaration.getKind()) { case AbstractVariableDeclaration.INITIALIZER: containsInitializers = true; if (typeDeclaration == null) { typeDeclaration = referenceContextTypeDeclaration; } if (typeDeclaration.fields == null) { typeDeclaration.fields = new FieldDeclaration[1]; typeDeclaration.fields[0] = fieldDeclaration; } else { int length2 = typeDeclaration.fields.length; FieldDeclaration[] temp = new FieldDeclaration[length2 + 1]; System.arraycopy(typeDeclaration.fields, 0, temp, 0, length2); temp[length2] = fieldDeclaration; typeDeclaration.fields = temp; } break; } } if (((node.bits & ASTNode.HasSyntaxErrors) != 0) && (!this.options.performMethodsFullRecovery && !this.options.performStatementsRecovery)) { return null; } } if (containsInitializers) { FieldDeclaration[] fieldDeclarations = typeDeclaration.fields; for (int i = 0, max = fieldDeclarations.length; i < max; i++) { Initializer initializer = (Initializer) fieldDeclarations[i]; initializer.parseStatements(this, typeDeclaration, unit); if (((initializer.bits & ASTNode.HasSyntaxErrors) != 0) && (!this.options.performMethodsFullRecovery && !this.options.performStatementsRecovery)) { return null; } } } return result; }
From source file:org.eclipse.objectteams.otdt.internal.core.compiler.ast.AbstractMethodMappingDeclaration.java
License:Open Source License
/** * Look for any single names in the given expression that refer to an argument of the base method. * For error reporting only, thus only the first occurrence is of interest. * * @param mappedArgExpr expression to investigate * @param blockScope just to please the visitor * @param arguments base arguments to match against * @return a found reference or null.//from w ww. ja va2 s .c o m */ SingleNameReference findBaseArgName(Expression mappedArgExpr, BlockScope blockScope, final Argument[] arguments) { @SuppressWarnings("serial") class FoundException extends RuntimeException { SingleNameReference name; FoundException(SingleNameReference name) { this.name = name; } } ASTVisitor visitor = new ASTVisitor() { public void endVisit(SingleNameReference nameRef, BlockScope blockScope2) { for (int i = 0; i < arguments.length; i++) { if (CharOperation.equals(arguments[i].name, nameRef.token)) throw new FoundException(nameRef); } } }; try { mappedArgExpr.traverse(visitor, blockScope); } catch (FoundException e) { return e.name; } return null; }
From source file:org.eclipse.objectteams.otdt.internal.core.compiler.ast.BaseAllocationExpression.java
License:Open Source License
private boolean isArgOfOtherCtor(ConstructorDeclaration constructorDecl, BlockScope scope) { // two marker exception types: @SuppressWarnings("serial") class FoundException extends RuntimeException { /*empty*/} @SuppressWarnings("serial") class NotFoundException extends RuntimeException { /*empty*/ } try {/*w ww. ja v a2 s . c om*/ constructorDecl.traverse(new ASTVisitor() { int inCtorCall = 0; @Override public boolean visit(ExplicitConstructorCall ctorCall, BlockScope aScope) { this.inCtorCall++; return super.visit(ctorCall, aScope); } @Override public void endVisit(ExplicitConstructorCall explicitConstructor, BlockScope aScope) { super.endVisit(explicitConstructor, aScope); this.inCtorCall--; } @Override public boolean visit(Assignment assig, BlockScope aScope) { if (assig == BaseAllocationExpression.this) { if (this.inCtorCall > 0) throw new FoundException(); else throw new NotFoundException(); } return super.visit(assig, aScope); } }, scope.classScope()); } catch (FoundException fe) { return true; } catch (NotFoundException nfe) { return false; } return false; }
From source file:org.nabucco.framework.generator.compiler.transformation.java.common.reflection.NabuccoToJavaPropertiesVisitor.java
License:Open Source License
/** * Modifies the template 'createPropertyContainer' method by <li>changing the parent class * literal or removing it if there is no usable parent</li> <li>add all put statements * previously created by the/*w ww.j a v a 2s . co m*/ * {@link NabuccoToJavaPropertiesVisitor#createPropertyContainerFragment(String, String, PropertyType, List)} * method</li> * * @param unit * resulting JavaUnit. * * @throws JavaModelException * if model creation/modifications fail. */ private void createCreatePropertyContainer(JavaCompilationUnit unit) throws JavaModelException { AbstractMethodDeclaration method = JavaAstElementFactory.getInstance().getJavaAstType() .getMethod(unit.getType(), SIGNATURE_CREATEPROPERTYCONTAINER); JavaAstModelProducer producer = JavaAstModelProducer.getInstance(); final TypeReference parentType = producer.createTypeReference(this.extention, false); // Replace parent class literal if (this.extention != null) { ASTVisitor vistior = new ASTVisitor() { @Override public boolean visit(ClassLiteralAccess classLiteral, BlockScope scope) { classLiteral.type = parentType; return super.visit(classLiteral, scope); } }; for (Statement statement : method.statements) { statement.traverse(vistior, null); } } else { // remove message send for parent call method.statements[method.statements.length - 2] = method.statements[method.statements.length - 1]; method.statements = Arrays.copyOf(method.statements, 2); } int returnStatementPos = method.statements.length - 1; method.statements = Arrays.copyOf(method.statements, method.statements.length + this.propertyContainerStatements.size()); method.statements[method.statements.length - 1] = method.statements[returnStatementPos]; for (int i = 0; i < this.propertyContainerStatements.size(); i++) { method.statements[returnStatementPos + i] = this.propertyContainerStatements.get(i); } }
From source file:org.nabucco.framework.generator.compiler.transformation.java.common.reflection.NabuccoToJavaReflectionFacade.java
License:Open Source License
/** * Mofiy the static getPropertyDescriptor() methods. * // w w w . j a v a2 s . c o m * @param unit * the java unit * * @throws JavaModelException */ private void handleStaticMethods(JavaCompilationUnit unit) throws JavaModelException { JavaAstType factory = JavaAstElementFactory.getInstance().getJavaAstType(); TypeDeclaration type = unit.getType(); final TypeReference classTypeReference = JavaAstModelProducer.getInstance() .createTypeReference(factory.getTypeName(type), false); AbstractMethodDeclaration[] methods = new AbstractMethodDeclaration[] { factory.getMethod(type, GET_PROPERTY_DESCRIPTOR), factory.getMethod(type, GET_PROPERTY_DESCRIPTOR_LIST) }; ASTVisitor alterClassLiteral = new ASTVisitor() { @Override public boolean visit(ClassLiteralAccess classLiteral, BlockScope scope) { classLiteral.type = classTypeReference; return super.visit(classLiteral, scope); } }; for (AbstractMethodDeclaration currentMethodDeclaration : methods) { for (Statement statement : currentMethodDeclaration.statements) { statement.traverse(alterClassLiteral, null); } } }
From source file:org.nabucco.framework.generator.compiler.transformation.java.datatype.NabuccoToJavaDatatypeVisitor.java
License:Open Source License
/** * Find and replace the Class Literal access type. * /*from w w w . j av a2s.c o m*/ * @param methodDeclaration * method to search in. * @param targetType * the new type. */ private void alterClassLiteralAccess(Statement[] methodBody, final TypeReference targetType) { ASTVisitor visitor = new ASTVisitor() { @Override public boolean visit(ClassLiteralAccess classLiteral, BlockScope scope) { classLiteral.type = targetType; return super.visit(classLiteral, scope); } }; for (Statement current : methodBody) { current.traverse(visitor, (BlockScope) null); } }