Sloth
Sloth

Reputation: 21

How to read the source of lombok?

Recently, I have a great interest in "lombok". And I want to know it more by reading the source code.

But after tried, I found it really difficult to me. i only found there are two implement of "javac" and "ECJ". but don't understand how does it works end to end.

Can anybody give some advice? like first read which package/class, or the flow of the logic?

Thanks.

Upvotes: 2

Views: 1767

Answers (1)

Coffei
Coffei

Reputation: 63

I am currently writing a Bachelor thesis on Lombok, so I will try to explain some stuff. Lombok uses Java Annotation Processing [1], which basically runs some predefined task on nodes (e.g. classes, methods) where certain annotation is used. However, you cannot modify existing source using this approach, that is why Lombok uses internal APIs, which are unsupported and viable to a change. That is why is Lombok hated by many, as it is basically a hack.

To start with Lombok source, there are two major packages:

  • lombok.javac where is implementation for Oracle Java compiler
  • lombok.eclipse where is implementation for Eclipse compiler

I will briefly describe the Oracle compiler part. This is what happens during compilation of your project with lombok annotations.

  1. lombok.javac.apt.Processor#process(...) is called and compilation units (think of them as classes) are handed over to this class for processing.
  2. Processor hands them over to JavacTransformer class where it is converted to AST.
  3. Then this AST is traversed with JavacTransformer.AnnotationVisitor which searches for all annotations in the code. This is an important part since the visitor can find ALL annotations, the Java Annotation Processing is not able to detect all annotations (e.g. it ignores annotations inside methods).
  4. Every annotation that is found is handled by HandlerLibrary, which has all the transformations (like @Getter) loaded, and knows which transformation should be triggered for which annotation.
  5. Transformation is triggered, that is a class implementing JavacAnnotationHandler. You can find the transformations in lombok.javac.handlers package. The transformation verifies the annotation is used correctly and does its job (e.g. @Getter generates a getter method).

Where is the hacky part? Well, if you look in the code, you see some suspicious casts, like:

(JCCompilationUnit) path.getCompilationUnit();

Lombok expects to receive an certain implementations of interfaces and uses those internal implementations to do what it does.

Further reading:

[1] http://deors.wordpress.com/2011/10/08/annotation-processors/ is good tutorial
[2] How does lombok work? explained by Lombok lead dev why is lombok using internal APIs
[3] http://notatube.blogspot.cz/2010/12/project-lombok-creating-custom.html article about adding your own transformations

Have fun!

Upvotes: 6

Related Questions