private static List<MethodBinding> getApplicableExtensionMethodsDefinedInProvider(EclipseNode typeNode, ReferenceBinding extensionMethodProviderBinding, TypeBinding receiverType) { List<MethodBinding> extensionMethods = new ArrayList<MethodBinding>(); CompilationUnitScope cuScope = ((CompilationUnitDeclaration) typeNode.top().get()).scope; for (MethodBinding method : extensionMethodProviderBinding.methods()) { if (!method.isStatic()) continue; if (!method.isPublic()) continue; if (method.parameters == null || method.parameters.length == 0) continue; TypeBinding firstArgType = method.parameters[0]; if (receiverType.isProvablyDistinct(firstArgType) && !receiverType.isCompatibleWith(firstArgType.erasure())) continue; TypeBinding[] argumentTypes = Arrays.copyOfRange(method.parameters, 1, method.parameters.length); if ((receiverType instanceof ReferenceBinding) && ((ReferenceBinding) receiverType).getExactMethod(method.selector, argumentTypes, cuScope) != null) continue; extensionMethods.add(method); } return extensionMethods; }
/** * Handles the provided annotation node by first finding a qualifying instance of * {@link EclipseAnnotationHandler} and if one exists, calling it with a freshly cooked up * instance of {@link AnnotationValues}. * * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped. * * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation. * For example, if {@code lombok.*} is in the import list, then this method will guess that * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.eclipse.handlers.HandleGetter} * has been loaded. * * @param ast The Compilation Unit that contains the Annotation AST Node. * @param annotationNode The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. */ public void handleAnnotation(CompilationUnitDeclaration ast, EclipseNode annotationNode, org.eclipse.jdt.internal.compiler.ast.Annotation annotation, long priority) { TypeResolver resolver = new TypeResolver(annotationNode.getImportList()); TypeReference rawType = annotation.type; if (rawType == null) return; String fqn = resolver.typeRefToFullyQualifiedName(annotationNode, typeLibrary, toQualifiedName(annotation.type.getTypeName())); if (fqn == null) return; AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); if (container == null) return; if (priority != container.getPriority()) return; if (!annotationNode.isCompleteParse() && container.deferUntilPostDiet()) { if (needsHandling(annotation)) container.preHandle(annotation, annotationNode); return; } try { if (checkAndSetHandled(annotation)) container.handle(annotation, annotationNode); } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } catch (Throwable t) { error(ast, String.format("Lombok annotation handler %s failed", container.handler.getClass()), t); } }
public static EclipseAST getAST(CompilationUnitDeclaration ast, boolean forceRebuild) { EclipseAST existing = null; if (astCacheField != null) { try { existing = (EclipseAST) astCacheField.get(ast); } catch (Exception e) { // existing remains null } } if (existing == null) { existing = new EclipseAST(ast); if (astCacheField != null) try { astCacheField.set(ast, existing); } catch (Exception ignore) { } } else { existing.rebuild(forceRebuild); } return existing; }
/** {@inheritDoc} */ @Override protected EclipseNode buildTree(ASTNode node, Kind kind) { switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((CompilationUnitDeclaration) node); case TYPE: return buildType((TypeDeclaration) node); case FIELD: return buildField((FieldDeclaration) node); case INITIALIZER: return buildInitializer((Initializer) node); case METHOD: return buildMethod((AbstractMethodDeclaration) node); case ARGUMENT: return buildLocal((Argument) node, kind); case LOCAL: return buildLocal((LocalDeclaration) node, kind); case STATEMENT: return buildStatement((Statement) node); case ANNOTATION: return buildAnnotation((Annotation) node, false); default: throw new AssertionError("Did not expect to arrive here: " + kind); } }
private MethodDeclaration generateCleanMethod(List<BuilderFieldData> builderFields, EclipseNode builderType, ASTNode source) { List<Statement> statements = new ArrayList<Statement>(); for (BuilderFieldData bfd : builderFields) { if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, builderType, statements); } } FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0); thisUnclean.receiver = new ThisReference(0, 0); statements.add(new Assignment(thisUnclean, new FalseLiteral(0, 0), 0)); MethodDeclaration decl = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); decl.selector = CLEAN_METHOD_NAME; decl.modifiers = ClassFileConstants.AccPrivate; decl.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; decl.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); decl.statements = statements.toArray(new Statement[0]); decl.traverse(new SetGeneratedByVisitor(source), (ClassScope) null); return decl; }
public MethodDeclaration generateBuilderMethod(boolean isStatic, String builderMethodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); out.selector = builderMethodName.toCharArray(); out.modifiers = ClassFileConstants.AccPublic; if (isStatic) out.modifiers |= ClassFileConstants.AccStatic; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); out.typeParameters = copyTypeParams(typeParams, source); AllocationExpression invoke = new AllocationExpression(); invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); out.statements = new Statement[] {new ReturnStatement(invoke, pS, pE)}; out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope); return out; }
private void generateClearMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType) { MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult); md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; md.modifiers = ClassFileConstants.AccPublic; FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L); thisDotField.receiver = new ThisReference(0, 0); FieldReference thisDotField2 = new FieldReference(data.getPluralName(), 0L); thisDotField2.receiver = new ThisReference(0, 0); md.selector = HandlerUtil.buildAccessorName("clear", new String(data.getPluralName())).toCharArray(); MessageSend clearMsg = new MessageSend(); clearMsg.receiver = thisDotField2; clearMsg.selector = "clear".toCharArray(); Statement clearStatement = new IfStatement(new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.NOT_EQUAL), clearMsg, 0, 0); md.statements = returnStatement != null ? new Statement[] {clearStatement, returnStatement} : new Statement[] {clearStatement}; md.returnType = returnType; injectMethod(builderType, md); }
public void log(CompilationUnitDeclaration owner, String message, Object... params) { if (GLOBAL_DSS_DISABLE_SWITCH) return; DebugSnapshot snapshot = new DebugSnapshot(owner, -1, message, params); List<DebugSnapshot> list; synchronized (map) { list = map.get(owner); if (list == null) { list = new ArrayList<DebugSnapshot>(); map.put(owner, list); list.add(snapshot); } else if (!list.isEmpty()) { list.add(snapshot); } else { // An empty list is an indicator that we no longer care about that particular CUD. } } }
@Override public void process(CompilationUnitDeclaration unit, int unitNumber) { mCurrentUnit = lookupEnvironment.unitBeingCompleted = unit; parser.getMethodBodies(unit); if (unit.scope != null) { unit.scope.faultInTypes(); unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); } unit.resolve(); unit.analyseCode(); // This is where we differ from super: DON'T call generateCode(). // Sadly we can't just set ignoreMethodBodies=true to have the same effect, // since that would also skip the analyseCode call, which we DO, want: // unit.generateCode(); if (options.produceReferenceInfo && unit.scope != null) { unit.scope.storeDependencyInfo(); } unit.finalizeProblems(); unit.compilationResult.totalUnitsKnown = totalUnits; lookupEnvironment.unitBeingCompleted = null; }
@Nullable private static Node parse(String code) { CompilerOptions options = new CompilerOptions(); options.complianceLevel = options.sourceLevel = options.targetJDK = ClassFileConstants.JDK1_7; options.parseLiteralExpressionsAsConstants = true; ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.exitOnFirstError(), options, new DefaultProblemFactory()); Parser parser = new Parser(problemReporter, options.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = false; EcjTreeConverter converter = new EcjTreeConverter(); org.eclipse.jdt.internal.compiler.batch.CompilationUnit sourceUnit = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(code.toCharArray(), "unitTest", "UTF-8"); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration unit = parser.parse(sourceUnit, compilationResult); if (unit == null) { return null; } converter.visit(code, unit); List<? extends Node> nodes = converter.getAll(); for (lombok.ast.Node node : nodes) { if (node instanceof lombok.ast.CompilationUnit) { return node; } } return null; }
public MethodDeclaration generateBuilderMethod(String builderMethodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; MethodDeclaration out = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); out.selector = builderMethodName.toCharArray(); out.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); out.typeParameters = copyTypeParams(typeParams, source); AllocationExpression invoke = new AllocationExpression(); invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p); out.statements = new Statement[] {new ReturnStatement(invoke, pS, pE)}; out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope); return out; }
public static CompilationUnit convert( CompilationUnitDeclaration compilationUnitDeclaration, char[] contents, int flags, Map<String, String> options) { DefaultBindingResolver.BindingTables bindingTables = new DefaultBindingResolver.BindingTables(); CompilationUnit compilationUnit = convert( compilationUnitDeclaration, contents, AST.JLS4, options, true, null, bindingTables, flags, new NullProgressMonitor(), true); compilationUnit.setProperty( "compilerBindingsToASTBindings", new HashMap(bindingTables.compilerBindingsToASTBindings)); return compilationUnit; }
public static CompilationUnitDeclaration buildCompilationUnit( ISourceType[] sourceTypes, int flags, ProblemReporter problemReporter, CompilationResult compilationResult) { // long start = System.currentTimeMillis(); SourceTypeConverter converter = new SourceTypeConverter(flags, problemReporter); try { return converter.convert(sourceTypes, compilationResult); } catch (JavaModelException e) { return null; /* } finally { System.out.println("Spent " + (System.currentTimeMillis() - start) + "ms to convert " + ((JavaElement) converter.cu) .toStringWithAncestors()); */ } }
@Override public ASTNode process(Source in, Void irrelevant) throws ConversionProblem { CompilerOptions compilerOptions = ecjCompilerOptions(); Parser parser = new Parser(new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory() ), compilerOptions.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = true; CompilationUnit sourceUnit = new CompilationUnit(in.getRawInput().toCharArray(), in.getName(), charset.name()); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration cud = parser.parse(sourceUnit, compilationResult); if (cud.hasErrors()) { throw new ConversionProblem(String.format("Can't read file %s due to parse error: %s", in.getName(), compilationResult.getErrors()[0])); } return cud; }
@Override protected ASTNode parseWithLombok(Source source) { CompilerOptions compilerOptions = ecjCompilerOptions(); Parser parser = new Parser(new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory() ), compilerOptions.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = true; CompilationUnit sourceUnit = new CompilationUnit(source.getRawInput().toCharArray(), source.getName(), "UTF-8"); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration cud = parser.parse(sourceUnit, compilationResult); if (cud.hasErrors()) return null; EcjTreeConverter converter = new EcjTreeConverter(); converter.visit(source.getRawInput(), cud); Node lombokized = converter.get(); EcjTreeBuilder builder = new EcjTreeBuilder(source.getRawInput(), source.getName(), ecjCompilerOptions()); builder.visit(lombokized); return builder.get(); }
@Override protected ASTNode parseWithTargetCompiler(Source source) { CompilerOptions compilerOptions = ecjCompilerOptions(); Parser parser = new Parser(new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory() ), compilerOptions.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = true; CompilationUnit sourceUnit = new CompilationUnit(source.getRawInput().toCharArray(), source.getName(), "UTF-8"); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration cud = parser.parse(sourceUnit, compilationResult); if (cud.hasErrors()) return null; return cud; }
protected Node parseWithTargetCompiler(Source source) { CompilerOptions compilerOptions = ecjCompilerOptions(); Parser parser = new Parser(new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory() ), compilerOptions.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = true; CompilationUnit sourceUnit = new CompilationUnit(source.getRawInput().toCharArray(), source.getName(), "UTF-8"); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration cud = parser.parse(sourceUnit, compilationResult); if (cud.hasErrors()) return null; EcjTreeConverter converter = new EcjTreeConverter(); converter.visit(source.getRawInput(), cud); return converter.get(); }
public void isClassPathCorrect(char[][] wellKnownTypeName, CompilationUnitDeclaration compUnitDecl, Object location) { this.referenceContext = compUnitDecl; String[] arguments = new String[] {CharOperation.toString(wellKnownTypeName)}; int start = 0, end = 0; if (location != null) { if (location instanceof InvocationSite) { InvocationSite site = (InvocationSite) location; start = site.sourceStart(); end = site.sourceEnd(); } else if (location instanceof ASTNode) { ASTNode node = (ASTNode) location; start = node.sourceStart(); end = node.sourceEnd(); } } this.handle( IProblem.IsClassPathCorrect, arguments, arguments, start, end); }
public ProcessTaskManager(Compiler compiler) { this.compiler = compiler; this.unitIndex = 0; this.currentIndex = 0; this.availableIndex = 0; this.size = PROCESSED_QUEUE_SIZE; this.sleepCount = 0; // 0 is no one, +1 is the processing thread & -1 is the writing/main thread this.units = new CompilationUnitDeclaration[this.size]; synchronized (this) { this.processingThread = new Thread(this, "Compiler Processing Task"); //$NON-NLS-1$ this.processingThread.setDaemon(true); this.processingThread.start(); } }
private void reportBinding(Object key, ASTRequestor astRequestor, WorkingCopyOwner owner, CompilationUnitDeclaration unit) { BindingKeyResolver keyResolver = (BindingKeyResolver) key; Binding compilerBinding = keyResolver.getCompilerBinding(); if (compilerBinding != null) { DefaultBindingResolver resolver = new DefaultBindingResolver(unit.scope, owner, this.bindingTables, false, this.fromJavaProject); AnnotationBinding annotationBinding = keyResolver.getAnnotationBinding(); IBinding binding; if (annotationBinding != null) { binding = resolver.getAnnotationInstance(annotationBinding); } else { binding = resolver.getBinding(compilerBinding); } if (binding != null) astRequestor.acceptBinding(keyResolver.getKey(), binding); } }
private void reportBinding(Object key, FileASTRequestor astRequestor, CompilationUnitDeclaration unit) { BindingKeyResolver keyResolver = (BindingKeyResolver) key; Binding compilerBinding = keyResolver.getCompilerBinding(); if (compilerBinding != null) { DefaultBindingResolver resolver = new DefaultBindingResolver(unit.scope, null, this.bindingTables, false, this.fromJavaProject); AnnotationBinding annotationBinding = keyResolver.getAnnotationBinding(); IBinding binding; if (annotationBinding != null) { binding = resolver.getAnnotationInstance(annotationBinding); } else { binding = resolver.getBinding(compilerBinding); } if (binding != null) astRequestor.acceptBinding(keyResolver.getKey(), binding); } }
public Expression parseMemberValue(char[] source, int offset, int length, CompilationUnitDeclaration unit) { initialize(); goForMemberValue(); this.nestedMethod[this.nestedType]++; this.referenceContext = unit; this.compilationUnit = unit; this.scanner.setSource(source); this.scanner.resetTo(offset, offset + length - 1); try { parse(); } catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; } finally { this.nestedMethod[this.nestedType]--; } if (this.lastAct == ERROR_ACTION) { return null; } return this.expressionStack[this.expressionPtr]; }
public void packageIsNotExpectedPackage(CompilationUnitDeclaration compUnitDecl) { boolean hasPackageDeclaration = compUnitDecl.currentPackage == null; String[] arguments = new String[] { CharOperation.toString(compUnitDecl.compilationResult.compilationUnit.getPackageName()), hasPackageDeclaration ? "" : CharOperation.toString(compUnitDecl.currentPackage.tokens), //$NON-NLS-1$ }; int end; if (compUnitDecl.sourceEnd <= 0) { end = -1; } else { end = hasPackageDeclaration ? 0 : compUnitDecl.currentPackage.sourceEnd; } this.handle( IProblem.PackageIsNotExpectedPackage, arguments, arguments, hasPackageDeclaration ? 0 : compUnitDecl.currentPackage.sourceStart, end); }
public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) { if (this.stepCompleted == BUILD_FIELDS_AND_METHODS) { // This can only happen because the original set of units are completely built and // are now being processed, so we want to treat all the additional units as a group // until they too are completely processed. completeTypeBindings(); } else { if (parsedUnit.scope == null) return; // parsing errors were too severe if (this.stepCompleted >= CHECK_AND_SET_IMPORTS) (this.unitBeingCompleted = parsedUnit).scope.checkAndSetImports(); if (this.stepCompleted >= CONNECT_TYPE_HIERARCHY) (this.unitBeingCompleted = parsedUnit).scope.connectTypeHierarchy(); this.unitBeingCompleted = null; } }
public void compile(String className) { Timer timer = metric.startTimer("act:classload:compile:" + className); ICompilationUnit[] compilationUnits = new ICompilationUnit[1]; compilationUnits[0] = classLoader.source(className).compilationUnit(); IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError(); IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH); org.eclipse.jdt.internal.compiler.Compiler jdtCompiler = new Compiler( nameEnv, policy, compilerOptions, requestor, problemFactory) { @Override protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) { } }; jdtCompiler.compile(compilationUnits); timer.stop(); }
/** Obtains the AST. */ private CompilationUnitDeclaration getAST(IJavaElement javaElement) throws ConQATException { EcjCompilationResult ecjResult = JavaLibrary.getEcjAST(javaElement); if (ecjResult.getProblems().length > 0) { String message = "Could not compile " + javaElement.getId() + ": " + ecjResult.getProblems()[0]; if (lenient) { getLogger().warn(message); return null; } throw new ConQATException(message); } return ecjResult.getCompilationUnitDeclaration(); }
protected void setExtendedData( ITypeRoot typeRoot, CompilationUnitDeclaration compilationUnitDeclaration, LookupEnvironment lookupEnvironment, Scope scope, ASTNode astNode, ASTNode astNodeParent, WorkingCopyOwner owner, CompletionParser parser) { this.isExtended = true; this.extendedContext = new InternalExtendedCompletionContext( this, typeRoot, compilationUnitDeclaration, lookupEnvironment, scope, astNode, astNodeParent, owner, parser); }
public InternalExtendedCompletionContext( InternalCompletionContext completionContext, ITypeRoot typeRoot, CompilationUnitDeclaration compilationUnitDeclaration, LookupEnvironment lookupEnvironment, Scope assistScope, ASTNode assistNode, ASTNode assistNodeParent, WorkingCopyOwner owner, CompletionParser parser) { this.completionContext = completionContext; this.typeRoot = typeRoot; this.compilationUnitDeclaration = compilationUnitDeclaration; this.lookupEnvironment = lookupEnvironment; this.assistScope = assistScope; this.assistNode = assistNode; this.assistNodeParent = assistNodeParent; this.owner = owner; this.parser = parser; }
@Override public CharSequence extract(ProcessingEnvironment environment, TypeElement typeElement) throws IOException { if (typeElement instanceof ElementImpl) { Binding binding = ((ElementImpl) typeElement)._binding; if (binding instanceof SourceTypeBinding) { CompilationUnitDeclaration unit = ((SourceTypeBinding) binding).scope.referenceCompilationUnit(); char[] contents = unit.compilationResult.compilationUnit.getContents(); return CharBuffer.wrap(contents); } } return UNABLE_TO_EXTRACT; }