r/java • • Oct 05 '23

How does the lombok magic work underneath?

https://www.unlogged.io/post/how-does-the-lombok-magic-work-underneath
133 Upvotes

143 comments sorted by

View all comments

Show parent comment

21

u/rzwitserloot Oct 05 '23

We do not modify javac on the fly. Our plugins and such add an --add-opens line. And we modify the AST. That's modify, whereas plain jane annotation processors only make new ASTs, they don't modify existing ones.

Point is, we modify them as an AST, we don't create new nodes. We don't invent new language constructs that java does not have.

8

u/SirYwell Oct 05 '23

whereas plain jane annotation processors only make new ASTs, they don't modify existing ones.

No. Annotation processors might create files via the Filer API, but they don't make new ASTs.

6

u/rzwitserloot Oct 06 '23

java source files. Which are textual representations of ASTs.

3

u/krzyk Oct 05 '23

Well, how about val? Sounds like new language construct. And SneakyThrows, Value?

10

u/rzwitserloot Oct 06 '23

val

is just short for final var. That's not a new construct.

SneakyThrows

See this same comment thread, someone else mentioned it. It's not - you'd think so, but you can make plain jane javac without any modification or third party deps or APs throw sneakily.

@Value

Just generates a boatload of boilerplate, stated in plain java (as in, lombok generates java code, it doesn't generate class files. That's e.g. a difference between lombok and for example kotlin or any other 'JVM-based language'. They turn kotlin source files into class files. Lombok turns java code into more verbose java code, but still java code.

The java code that lombok produces, if you were to write that out manually and compile it, the class file you would get when you pass that source file to javac is bit for bit identical to what the class file emitted from lombok would provide. The API you end up with is identical to one you would get if you use vanilla Annotation Processors like immutables. Lombok just makes it more convenient - no need for separate class files, no need for a full compile run before you see your API appear in your project.

5

u/krzyk Oct 06 '23

So, how is it different from kotlin, Scala , etc.? You create language based on Java, that is close to Java but slightly different, like groovy or maybe J#?

6

u/agentoutlier Oct 07 '23

Because it only adds to the AST. It’s like a macro language for a language that doesn’t officially have one.

Scala and others have a completely different AST that gets compiled to bytecode.

2

u/krzyk Oct 07 '23

Ok, and Groovy? It has very similar language, AFAIR every java program is also a working groovy one.

6

u/agentoutlier Oct 07 '23 edited Oct 07 '23

It is a matter of which perspective you want to look at it at.

You asked how it is different: Groovy does not alter Java AST. Groovy is not a compiler plugin. Groovy might add constructs that are not possible in Java language (this I'm not sure of but Scala and Kotlin for sure do).

This back and forth of whether or not Lombok is a different language is really stupid IMO because pron and /u/rzwitserloot can argue one way or the other depending on what level of meta we want to go into.

Lombok is a like an unofficial preprocessor.

/u/rzwitserloot argument is that every annotation processor is like an unofficial preprocessor and thus on the same grounds is at a very abstract level kind of true but mostly not. Their argument is that code that depends on generated annotated code will not work in the same way lombok will not work.

However regular APT libraries do not require special IDE plugins. Lombok does so I say what it does is rather unofficial and not canonical regardless of framing of whether it is a new language or not.

1

u/wildjokers Oct 06 '23

We don't invent new language constructs that java does not have.

@SneakyThrows?

11

u/rzwitserloot Oct 06 '23

It sounds like we invented something there, doesn't it?

We didn't, though. You can sneakythrows with plain ole java in a few ways.

A key thing to remember is that the concept of a checked exception is entirely a figment of javac. The reason that this:

public void foo() /* no throws clause */ {
  throw new IOException();
}

doesn't compile is simply because javac refuses to. If it did compile it, the class verifier wouldn't mind. the runtime wouldn't mind. This is why the same code as above written in kotlin can be compiled to a class file just fine.

Thus, all we have to do to call it 'java' is to figure out a way to make the combination of 'plain jane javac straight from the OpenJDK' and 'plain jane java.* core library' somehow do it. Once we get that far, the runtime and class verifier doesn't care.

And turns out, that's not actually difficult. There are 2 main ways:

Use java.* API that breaks the safety

It's deprecated now, but java.lang.Class has a newInstance() method that throws directly. It doesn't wrap stuff in InvocationTargetException like java.lang.reflect.Constructor's newInstance() method. As long as the checked exception you want to throw isn't specifically InstantiationException or IllegalAccessException, we can use this. here it is in action:

> cat Example.java

import java.io.IOException;

class Example {
  private static class Sneaky {
      Sneaky() throws IOException { throw new IOException(); }
    }

  static void sneakyThrowIOExInPlainJava() {
    try {
      Sneaky.class.newInstance();
    } catch (IllegalAccessException | InstantiationException e) {
      // won't happen
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) {
    sneakyThrowIOExInPlainJava();
  }
}

> javac Example.java
> java Example
Exception in thread "main" java.io.IOException
	at Example$Sneaky.<init>(Example.java:5)

That's with a plain jane JDK-21 fresh off openjdk.net with no lombok or any other third party dependency or modification of anything whatsoever.

Thus proving that the act of throwing checked exceptions without declaring them is, itself, something plain jane java can do. How can it possibly be 'non java' then?

Generics

With some generics trickery we can fake out the compiler itself and make it compile a sneaky throw:

> cat Thrower.java

import java.io.IOException;
class Thrower {

  public static <E extends Throwable> void sneak(Throwable ex) throws E {
    throw (E) ex;
  }

  public static void main(String[] args) {
    sneak(new IOException());
  }
}

> javac Thrower.java
> java Thrower
Exception in thread "main" java.io.IOException
	at Thrower.main(Thrower.java:10)

This is so 'clean' a way to throw sneakily in pure java I'd call it downright elegant.

Clearly, @SneakyThrows is not inventing new constructs java does not have. It just makes it less boilerplatey to do this stuff. It's a 'generate me some java code' toolkit, not 'this is an entirely new language'.

5

u/ImpossibleTrade1385 Oct 06 '23

that's not a new language construct either, all that does is wrap all of the code in a try catch block that rethrows the exception in an unchecked manner