# Scala 3, macro annotations and code generation

**URL:** <https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035>\
**Category:** Language Design\
**Created:** [December 12, 2022, 3:01pm UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035 "2022-12-12T15:01:03Z")\
**Posts on this page:** 20\
**Page:** 3

<div class="post-metadata">

**Author:** ![lihaoyi](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/lihaoyi/32/103_2.png) [@lihaoyi](https://contributors.scala-lang.org/u/lihaoyi)\
**Post date:** [June 14, 2023, 12:45am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/41 "2023-06-14T00:45:34Z")

</div>

> [@odersky](#):
>
> The idea of @smarter, which I find quite clever, is to re-interpret a macro annotation like @data as a way to _restrict_ your program. It now indicates that the definitions required by the `@data` class specification are all present. That by itself is useful and should be uncontroversial. You _could_ manually check that all required definitions are there, but with `@data` the compiler does it for you, and you see at a glance what kind of class this is.
> 
> Then _as an added convenience_ the compiler or IDE can also generate any definitions that are missing for you. You can freely replace or edit those definitions; the annotation will simply check that even after editing they are still of the right shape.

Either the editor integration is “part of Scala”, or it’s not.

1. If the editor integration is not “part of Scala”, we do not need to worry about integrating with dozens of different editors, but all we have is a fancy linter. Linters are great, but it’s not a viable replacement for macro annotations at all. We already have plenty of linters, and do not need another one baked into the language. People can write their own linters, and have.

2. If the editor integration is “part of Scala”, then it is a viable replacement for macro annotations, but we are now committed to properly integrating this in the dozens to hundreds of different places people can write Scala.

We can’t have it both ways. Saying _“It’ll be super simple! But don’t worry about the inconvenience, because we’ll have this editor integration! But the editor integration is just a nice to have and not required, so it’s still simple!”_ does not address the real tradeoffs and challenges involved.

Nobody in the programming community does things this way, for good reason. The closest thing you’ll find in other communities is the boilerplate generators in Java IDEs or Rails, which aren’t exactly shining examples. These are exactly the kinds of things that people fled other languages and came to Scala to _avoid_!

To go back to a more fundamental question, IMO Scala definitely has a verbosity problem around definitions.

Scala has tons of ways to abstract over _expressions_: functions, higher-order functions, by-name parameters, inline, macros, etc… We hardly ever see people resorting to code-generation for dealing with expressions, the way people sometimes do so in Java. Scala’s inbuilt tooling is sufficient. Perhaps the only exception is for performance reasons due to the fact that Scala’s abstractions are not zero-overhead.

But there is basically only one way to abstract over _definitions_: you can extend a `trait`. That’s great for some use cases, but not sufficient for others. When you see codegen in Scala, it’s basically always for generating definitions. The Dotty repo itself uses codegen. Many of my own projects use codegen. _“extend a trait”_ is for definitions more or less what _"higher order function_" is for expressions: they work great when the things you are abstracting over follow predictable patterns, but fail when you need something more flexible. For expressions, you can use macros, but for definitions you’re out of luck.

This is never fatal - you can always fall back to codegen. But the point of adding these language features is so we can do more _“in language”_, in a standardized way without falling back to splicing strings in a hundred-and-one ad-hoc ways. The proposal above is unable to even replace codegen in my own projects or those of the folks I collaborate: nobody likes templating source code, but at least build-time code-gen is deterministic and automated in a way that IDE-level point-and-click code-gen is not.

I don’t know what the answer is, but I’m very sure this proposal is not it. Nobody is coming to Scala because they _love managing heaps of boilerplate with IDE-auto-generated getters and setters_. It goes against the entire ethos of the Scala community

---

<div class="post-metadata">

**Author:** ![Ichoran](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/ichoran/32/40_2.png) [@Ichoran](https://contributors.scala-lang.org/u/Ichoran)\
**Post date:** [June 14, 2023, 1:27am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/42 "2023-06-14T01:27:43Z")

</div>

> [@odersky](#):
>
> The idea of @smarter, which I find quite clever, is to re-interpret a macro annotation like @data as a way to _restrict_ your program.

Thank you for making this so clear! Previously I don’t think I was really conceiving of the feature quite the right way.

However, I think that the issue of language fragmentation is there regardless. In some ways it’s even worse, because it’s language-and-toolset fragmentation. Metals/VSCode Scala looks like this, full of `@data` annotations that have conveniently been filled out; but people with different tools use non-`@data`-heavy Scala because without the convenience, there’s no point.

Sometimes you want things to be inconvenient _on purpose_ to encourage a uniformity of design. Yes, you can do the weird thing, but you have to pay the inconvenience-tax.

What you point out is that there’s really no clear dividing line between helpful linting and toolchain fixes, and unbridled tool-driven codegen that pushes everyone effectively into their own silos, even though technically anyone can edit anything (but nobody would, without the right tools).

So I think a serious conversation still needs to be had about where to try to draw the line. “We encourage you to write unrestricted macro annotations, but this is how you do it: frame it as a lint, then write a code generator for your favorite tool that fixes the code when it (obviously always) fails the lint when you write it by hand” is not avoiding unrestricted macro annotations in any meaningful sense, is it?

I would instead think that an avenue to explore that might have more principled boundaries intrinsic to it is whether additional transparency (c.f. transparent inline) could cover enough of the remaining important use cases to be able to forget about the rest. Basically, the idea would be to have a structured but more flexible way to indicate the content–maybe allowing abstraction over parameter list lengths or somesuch?–without enabling so much abstraction that one can’t even tell what code means any longer due to the proliferation of dialects.

---

<div class="post-metadata">

**Author:** ![jducoeur](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/jducoeur/32/32_2.png) [@jducoeur](https://contributors.scala-lang.org/u/jducoeur)\
**Post date:** [June 14, 2023, 3:08am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/43 "2023-06-14T03:08:04Z")

</div>

I don’t think I’ve said this previously, but I _hate_ this approach (macros built along the lines of `@tailrec`) with a burning passion. I find the approach really awkward, and I’m pretty sure I would never, ever use it. I mean, `@tailrec` confuses the bloody _hell_ out of new Scala programmers – doubling down on that is not a good plan.

(ETA: sharpening the reason why I would never use this – it encourages boilerplate in the code. In the world of enterprises that require double code reviews on every PR, where you usually have to struggle to get reviewers, this is _horrifying_. It literally makes my life harder than writing things by hand, since it blurs the distinction between “this is real code that you need to read carefully” and “this is a generated file that you can basically ignore in PR review”. If I’m understanding it correctly, it’s an absolute anti-feature from my POV, and I would probably fight to forbid its use in our repos.)

I agree with the folks above – specifically, I find the arguments against classic in-the-compiler-pipeline macros to be really overblown. Yes, there will be some problems. But we have stuff like this all over the place today, and the convenience massively outweighs the occasional downsides.

I really think the team is being excessively clever here, and fighting against what I believe most of the in-the-trenches Scala engineers want. IMO, that’s a mistake.

---

<div class="post-metadata">

**Author:** ![rssh](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/rssh/32/745_2.png) [@rssh](https://contributors.scala-lang.org/u/rssh)\
**Post date:** [June 14, 2023, 3:39am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/44 "2023-06-14T03:39:16Z")

</div>

During the program lifecycle, code is read much more times than written. A generated boilerplate code, which is visible, adds cognitive load to each reading act, making working with code much harder.

---

<div class="post-metadata">

**Author:** ![soronpo](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/soronpo/32/533_2.png) [@soronpo](https://contributors.scala-lang.org/u/soronpo)\
**Post date:** [June 14, 2023, 4:59am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/45 "2023-06-14T04:59:35Z")

</div>

> [@odersky](#):
>
> @nafg I am arguing against the very idea of allowing to create language dialects like @data classes. Whether you do it via macro-expansion or via a super-powerful meta-type system is secondary. If we allow that by whatever means, we will get dozens or hundreds of un-coordinated de facto language extensions. That’s the Lisp dream and the Lisp curse.

I had a need for a macro annotation that adds (private) implicit arguments. IIUC, this is not a language dialect, but it’s also something that must occur before typer.

---

<div class="post-metadata">

**Author:** ![adampauls](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/adampauls/32/2186_2.png) [@adampauls](https://contributors.scala-lang.org/u/adampauls)\
**Post date:** [June 14, 2023, 5:05am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/46 "2023-06-14T05:05:53Z")

</div>

I said it over in [the other thread](https://contributors.scala-lang.org/t/pre-sip-export-macros/6168/7), but do folks think that forbidding macros from synthesizing declarations but allowing them to fill in arbitrary definitions is a reasonable compromise? This would mean that `@data` would not be able to generate an `apply` or `withX` methods, but it could still fill in `equals` and `hashCode.` I think the `withX` methods could be done lens style with `.with(_.x)(value)` if there is a `trait Data` with `def with[T](field: Self => T)(value: T): Self`. Okay, `Self` doesn’t exist in Scala 3 (right?), but that’s a separate issue 🙂

---

<div class="post-metadata">

**Author:** ![kjsingh](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/kjsingh/32/1186_2.png) [@kjsingh](https://contributors.scala-lang.org/u/kjsingh)\
**Post date:** [June 14, 2023, 5:09am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/47 "2023-06-14T05:09:15Z")

</div>

C# had same problem when they had to generate code from XAML to merge with user’s C#.

They did it with Partial classes

> **[Partial Classes and Methods - C# Programming Guide](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods)**
>
> Partial classes and methods in C# split the definition of a class, a struct, an interface, or a method over two or more source files.

---

<div class="post-metadata">

**Author:** ![MateuszKowalewski](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mateuszkowalewski/32/77_2.png) [@MateuszKowalewski](https://contributors.scala-lang.org/u/MateuszKowalewski)\
**Post date:** [June 14, 2023, 5:40am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/48 "2023-06-14T05:40:45Z")

</div>

I try to clarify what _I’m_ after.

I didn’t care so much about macro annotations so far. I thought they’re on a good way, especially as they’re useful already. Since you can generate “internal” definitions (not visible to the rest of the program) now I was under the impression that the next logical step is to make those definitions somehow visible outside of the macro (e. g. “export” them to the outer scope) to achieve what I’m _actually_ after.

I’m after some nice code-gen facility, coherent with the rest of the language.

> [@lihaoyi](#):
>
> Scala has tons of ways to abstract over _expressions_: functions, higher-order functions, by-name parameters, inline, macros, etc…

> [@lihaoyi](#):
>
> But there is basically only one way to abstract over _definitions_: you can extend a `trait`. That’s great for some use cases, but not sufficient for others.

That’s _exactly_ the point!

And you can’t, by no means, do code-gen without introducing new definitions. That would fully defeat the point in most cases.

But Scala has _still no proper facility for code-gen_.

I really don’t understand why such an important feature is neglected!

I’m waiting for this feature more or less since macros were announced in Scala 2. I knew that those would go away and never invested in learning them. But since than I’m waiting for “the real thing”. And now? Nothing?

I say it once more: Concatenating strings into source files is a joke. More or less everything else is better. Even C++ templates are better in this regard. (And C++ template magic is actually hell).

Quite a lot of other people were so desperate that they used the interim solution in Scala 2. Why did they? Why would anybody invest in a “throw away” solution? Especially as this meant to dabble in complex compiler internals without any stability guaranty.

Also, why are there now so many macros still left that can’t be ported to Scala 3? Why did everybody use those even you could be sure that this will mean trouble updating to a future Scala version?

The answer is imho quite clear: _People desperately need code-gen._

Code-gen is everywhere. Whole frameworks in all kinds of languages are build upon it. Even the Scala compiler requires it. More or less everything prominent in the Java world is highly depended on code-gen (as otherwise Java would be even more boilerplately than it is already). But in Java almost nobody complains. Even Java code-gen is inconvenient and unsafe there. Most people actually praise that Java kluge and love their magic annotations in frameworks like for example Spring.

Rust has a quite “primitive” token stream macro system (not much better than gluing untyped symbols together). Still the Rust macros are hyped as one of the most important features in Rust. For many it’s even one of the absolute killer features that Rust has and others don’t.

Could we please recognize that code-gen is a game changing facility when built into a language? People lining up to use such a feature _because it solves real problems_!

What I finally want in Scala 3 is a safe and convenient way to generate code from code, that works fine in an IDE. I strongly suspect a lot other people also want that. Everybody who needs to port code-gen macros to Scala 3 is waiting for it!

> [@smarter](#):
>
> I’m not trying to rush anything, just proposing something that fits our self-imposed constraints of “macros are not allowed to create new definitions that affect subsequent typechecking” and doesn’t require new language features.

This self-imposed constraint was a good idea to build a very nice _foundation_ for Scala’s new macros. I’m glad it was done this way as it resulted in an very clean solution, so far.

But this constrain needs to be lifted _in some form_ to make code-gen possible. Like said, code-gen is pointless when you can’t generate anything else then implementations of already existing symbols / definitions. Scala still offers _nothing_ in this regard when it comes to meta-programm code-gen.

Also the proposal here at hand seems imho a little bit self contradicting: How does checking whether some types are present and correctly implemented doesn’t affect type checking? What kind of errors should we expect if a, let’s call it “constraining macro annotation” doesn’t find the right types it requires to exist (which the compiler needs to compute anyway, btw.)? My best guess would be this results in type errors at the usage side because expected definitions / implementations are missing… So a “constraining macro annotation” would affect type checking, wouldn’t it?

> [@Sporarum](#):
>
> For me the big upside of this proposal is the following:  
> It shows the user what is going on, so that they can have a mental model of what these macros do  
> Which is useful for example when debugging code
> 
> But in my opinion, this should not be done by editing source files !
> 
> Since we kind-of assume IDE support, I think we should approach the problem from a different angle:  
> Develop tools that allow the user to inspect the generated code with their IDE
> 
> This has the benefit of also applying to already existing constructs like `inline` and macros, or even `case class`es, `for` and `match` !
> 
> I think this would be a very valuable tool for teaching as well, student could write the `for` they want, and see how it is desugarred
> 
> My vision would be for it to work somewhat like code folding:  
> If you click/expand/… on a macro, it displays the code generated by that macro. Probably either as a popup or in a different color, so that it’s always clear what code is “real”, and what code is generated)

I think both points are valid.

Extended editor support to look at desugarings is imho a very good idea, but orthogonal to some code-gen facility.

Code-gen should imho always end up in some generated code _on disk_. Only not in files that are meant to be edited by humans, land in version control, and show up in reviews! That’s the most terrible part of this proposal, imho.

But I’m also dreaming of better introspectability of some magic the compiler does under the hood. Something like that would make tooling really valuable.

One could go even one step further and enable more of this kind of editor magic. I would love if the Scala tooling could implement something like “[code portals](https://www.uni-ulm.de/in/sp/research/projects/inline/)”. This is an ingenious idea nobody ever picked up, which is a shame as it fits especially well with the evaluation by substitution model of Scala. (VSCode code-lenses aren’t interactive, and can’t nest like portals).

Code-gen on the other hand is often a kind of build step. It should be independent of the IDE / editor someone uses.

> [@lihaoyi](#):
>
> But it’s one thing for third party tools to have incomplete best-effort support within all execution environments; these integrations are just icing on the cake making your life easier. But having core language features/workflows be unsupported depending on where you write your code, and _requiring_ special integrations to properly use a language feature at all, is something quite different.

This would just mean that all kinds of tools would become part of Scala the language. We’re back to the 90’s where your language was sold together with an IDE. Moving away form this IDE meant substantial rewrite of your code (if it even was possible to reasonably move away form the IDE; think VB6, or so).

> [@acruise](#):
>
> I’m not advocating that Scala should (or should not!) follow suit, but the approach Kotlin takes is interesting: essentially everything you might want to use macros for is implemented as a compiler plugin. [Here’s](https://twitter.com/relizarov/status/1387833892497932297) a twitter thread from a couple years ago with some rationale.

This doesn’t seem relevant as the Kotlin compiler is tightly bound to the JetBrains IDE.

In Scala an IDE doesn’t “see” anything a compiler pluing does. Quite the contrary…

Also the initial sentiment doesn’t look very honest given this here:

> **[MPS: The Domain-Specific Language Creator by JetBrains](https://www.jetbrains.com/mps/)**
>
> Use the MPS platform to create your own domain-specific language that speaks to your business needs.

They’re literally selling a meta-programming toolkit… So the “it’s too complicated for the tooling developers” argument falls apart.

> [@odersky](#):
>
> First, I believe we should never let unrestricted macro annotations in their old form into Scala again.

That’s a good idea!

Generated “invisible” code is problematic on all kinds of axes. You can’t navigate to it and introspect it, debugging it is a horror, as you can’t even see it to figure out what’s going on.

> [@odersky](#):
>
> If we admit things like that we open all doors again to language fragmentation.

I don’t see this. At least this doesn’t fit my definition of “fragmentation”.

It makes absolutely no difference whether I write some boilerplate code by hand or let a robot do the work. In both cases the result will be vanilla Scala code. Code that can be feed into the currently existing compiler without issues.

> [@odersky](#):
>
> Enforced language subsets are not dialects,

Using code-gen can’t lead to “dialects”. At least this doesn’t fit my definition of “dialect”…

Only if it would be possible to add or modify syntax, or change semantics of build-in language constructs this would result in a “dialects”. But nothing like that is possible through code-gen that is embedded into the language. All you have are the expression and declaration types the language offers anyway. Nothing can be changed or added there. It’s just a robot writing _vanilla Scala_ at the end of the day!

One can’t build a macro that adds for example “do notation” to the language. Or build a macro that would finally allow me to use emojis as symbol names. That would create dialects as such code wouldn’t be recognized by the currently existing Scala compiler. But just letting a robot write some definitions won’t create “dialects” whatsoever.

> [@odersky](#):
>
> The idea of @smarter, which I find quite clever

Yes it’s clever. A little bit too clever for the liking of some here, I think…

> [@odersky](#):
>
> You _could_ manually check that all required definitions are there, but with `@data` the compiler does it for you, and you see at a glance what kind of class this is.
> 
> Then _as an added convenience_ the compiler or IDE can also generate any definitions that are missing for you.

That’s not an “added convince”. That’s what a computer is actually for: It should do the tedious work! That’s the _main reason_ to use a computer, namely to automate things away.

I already know what needs to be there. I don’t need the compiler to check _that_. _I need the machine to do the actual work and implement what needs to be there._ That’s the whole point of automation. It’s nuts when the actual reason to use code-gen gets relabeled as “an added convince”.

> [@odersky](#):
>
> You can freely replace or edit those definitions; the annotation will simply check that even after editing they are still of the right shape.

This cries for trouble.

Someone could change generated code in ways that break intend but doesn’t break it’s interface (which is all the compiler can reliably check). Than have fun debugging.

Generated code would be the last place to look at as it’s usually reasonable to assume that some code-gen tool works fine, as otherwise also other people would have issues at the same time which you get to know easily for example by looking into the bug tracker.

> [@odersky](#):
>
> If the added code is small and easy to understand I can see this working quite well. Sort of like automatically adding getters and setters in Java IDEs.

This doesn’t “work well”. All this generated code needs to be read and maintained together with the handwritten parts. Actually it’s not even clear form looking at that code which parts are auto-generated.

The very next question is how about _updates_ to the generated code? Now you need to use refactoring tools… Because you can’t distinguish the parts that are generated and those that are hand written. Just changing something in the code-gen templates and regenerating code is not possible after the initial generation of code. Alternatively you have `// DO NOT EDIT THIS IT IS GENERATED CODE ANY CHANGES WILL BE LOST` blocks everywhere, so you can see what you shouldn’t edit. Only that’s it’s hard to enforce that. So even more tooling with more complex features is needed…

> [@odersky](#):
>
> If the added code is large and convoluted that’s another matter.

But that’s exactly the scenario code-gen is used for!

Nobody uses such a heavyweight feature to generate a few simple lines.

When you grab code-gen you will usually generate a lot, and often quite complex code. Code that otherwise nobody would like to write by hand. And now exactly this kind of unwieldy code is all over the place… Come on.

> [@odersky](#):
>
> _Then probably you should not do it_.

But that’s the exact reason to use code-gen in the first place!!!

> [@odersky](#):
>
> But at least we won’t have the situation that large and convoluted code gets added under the surface without this being pushed in the face of the developer.

_Just write the generated code to disk._ Problem solved.

That’s also easy for tooling, as tooling almost doesn’t need to be aware of any “magic” going on. It just gets some additional folder full of source files. Java’s annotation processors work that way, and it works fine, is simple, and easy to grasp for developers.

Code-gen is like multi-stage programming. Only that instead of having templates that are embedded in compiler output and than specialized at runtime before the actual execution you move everything a step back and have “templates” (or the-like) in your source code which get “specialized” (filled in) at compile-time into source files on disk, so those can than be picked up in the “next phase of compilation”.

> [@odersky](#):
>
> I am arguing against the very idea of allowing to create language dialects like @data classes. Whether you do it via macro-expansion or via a super-powerful meta-type system is secondary.

But when you write the code out by hand it’s not an “dialect”? Come on…

> [@jeremyrsmith](#):
>
> As an aside, I’m really happy to see all the work that’s gone into cleaning up metaprogramming and making it first-class. But around the edges, I think there’s all too much over-correction around things that, maybe someone said one time confused them about Scala.

THIS!

> [@odersky](#):
>
> Lombok is different since it directly hacks into the _javac_ compiler, changing its AST. So that’s more like an unauthorized dialect of Java. At least it’s not called Java and there is only one of it.

And what’s about other Java compiler plugins? For example:

> **[Java Operator Overloading #](https://artem.melentev.top/java-oo/)**
>
> Java Operator Overloading

Java is really flexible in this regard. You can even change syntax!

Nevertheless nobody ever complained about “Java dialects”.

> [@odersky](#):
>
> Now imagine having dozens of mini Lomboks all masquerading as innocuous annotations, possibly clashing with each other.

That’s not an issue as long as you don’t have to deal with some very low-level data structure representing your code.

But this could easily happen if you need to combine some string based Scala source rewrites when there is no other safe facility to achieve some code-transformation. Back to “meta-programming with sed”.

> [@nafg](#):
>
> not that Monocle `@Lenses` is too magical and weird. Does having `@Lenses` fragment the language?

At least not in Kotlin…

> **[Lenses | Arrow](https://arrow-kt.io/learn/immutable-data/lens/)**
>
> Lenses are the most common type of optic you work with. This section discusses

Implemented as compiler plugin.

> [@Ichoran](#):
>
> In some ways it’s even worse, because it’s language-and-toolset fragmentation. Metals/VSCode Scala looks like this, full of `@data` annotations that have conveniently been filled out; but people with different tools use non-`@data`-heavy Scala because without the convenience, there’s no point.

Exactly! We’re back in the 90’s tied to some special sauce in our IDEs.

> [@jducoeur](#):
>
> I mean, `@tailrec` confuses the bloody _hell_ out of new Scala programmers – doubling down on that is not a good plan.

Exactly!

You put in the annotation and _nothing happens_. It does not do the hard work for you _as expected_. That’s more than confusing. It’s frustrating.

* * *

Of course, it makes no difference how much I write here. I see, the post got way too looong anyway. Maybe because I’m waiting for such a long time for proper code-gen and can’t stand it that this long awaited feature may fall apart on the last few meter before the finish line.

But what I can say for sure: If this “[export macros](https://contributors.scala-lang.org/t/pre-sip-export-macros/6168/)” thingy succeeds to be implemented, but should it be only available on the fork of the compiler, I know what I’m going to use—shouldn’t there be any adequate alternative in the official Scala release. I’m a simple grug brained developer, I will use the tool that solves my problems. (And I guess the average dev out there thinks the same. Otherwise we wouldn’t have all the currently unportable macros everywhere).

At this point than we can start a serious discussion about “fragmentation” of the language, I guess.

---

<div class="post-metadata">

**Author:** ![smarter](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/smarter/32/92_2.png) [@smarter](https://contributors.scala-lang.org/u/smarter)\
**Post date:** [June 14, 2023, 6:06am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/49 "2023-06-14T06:06:31Z")

</div>

> [@lihaoyi](#):
>
> The source files are writable at all (not always true today for ~half of my colleagues, who edit code on one machine and compile/run it on another!) and not shared (not true for most cross built code!)

LSP code actions don’t normally do file i/o, instead they perform editor actions that modify your editor buffers in the same way that a user writing the code by hand would. If regular LSP code actions work in your setup, then the stuff being worked on in [Roadmap for actionable diagnostics](https://contributors.scala-lang.org/t/roadmap-for-actionable-diagnostics/6172) should also work. Notebooks are an issue as always but I just saw that [Jupyter[Lab] Language Server Protocol — Language Server Protocol integration for Jupyter[Lab]](https://jupyterlab-lsp.readthedocs.io/en/latest/#) exists and seems to at least supports renaming, so maybe notebooks won’t be second-class citizens eventually!

Anyway, irrespective of the codegen proposal (which I’m not planning to spend more time on at this point), I encourage you to give feedback on [Roadmap for actionable diagnostics](https://contributors.scala-lang.org/t/roadmap-for-actionable-diagnostics/6172) since we’re still figuring out the details. Also if Databricks is interested in better integration between Databricks notebooks and LSP/BSP, perhaps it’s something the Scala Center could help with (the inability to run tools such as scalafix on notebooks has come up before and I think is something we’d all benefit from solving).

---

<div class="post-metadata">

**Author:** ![smarter](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/smarter/32/92_2.png) [@smarter](https://contributors.scala-lang.org/u/smarter)\
**Post date:** [June 14, 2023, 6:10am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/50 "2023-06-14T06:10:47Z")

</div>

> [@adampauls](#):
>
> do folks think that forbidding macros from synthesizing declarations but allowing them to fill in arbitrary definitions is a reasonable compromise?

For the record, this basically matches what the current experimental support for macro annotations in Scala 3 lets you do (you can in fact add new definitions, but because macro annotations are expanded in a compiler phase that takes place after typer, they’re not visible outside of the macro expansion).

---

<div class="post-metadata">

**Author:** ![kjsingh](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/kjsingh/32/1186_2.png) [@kjsingh](https://contributors.scala-lang.org/u/kjsingh)\
**Post date:** [June 14, 2023, 6:31am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/51 "2023-06-14T06:31:12Z")

</div>

Maybe we need Scala Poet for code gen

> **[KotlinPoet - KotlinPoet](https://square.github.io/kotlinpoet/)**
>
> A Kotlin API for generating .kt source files

---

<div class="post-metadata">

**Author:** ![MateuszKowalewski](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mateuszkowalewski/32/77_2.png) [@MateuszKowalewski](https://contributors.scala-lang.org/u/MateuszKowalewski)\
**Post date:** [June 14, 2023, 6:54am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/52 "2023-06-14T06:54:20Z")

</div>

> [@kjsingh](#):
>
> Maybe we need Scala Poet for code gen

Only that we don’t need any “builders” as we have already `Expr[?]`s.

All that’s needed is to “export” (some of) the output so it can be picked up by the next compiler “stage” (as in multi-stage programming).

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [June 14, 2023, 8:40am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/53 "2023-06-14T08:40:27Z")

</div>

> [@MateuszKowalewski](#):
>
> Using code-gen can’t lead to “dialects”. At least this doesn’t fit my definition of “dialect”…

Using codegen is fine, as long as it does not influence the typing of the rest of the program. Like I said, @main is fine. @data in the original meaning is not fine since it would create a new sort of case class that offers methods different to case classes in the same compilation unit. That’s for all effects and purposes a dialect. Somebody coming new into a Scala codebases that uses @data has to know about what definitions it generates, just like they have to know what definitions a case class generates.

@data can be reasonably supported under the restriction/rewrite model since the definitions it generates are straightforward. In that case, even if you don’t know about @data, you can understand the class just the same by looking at the explicit definitions. But it’s still important that these definitions are there, both for tooling (to have something to navigate to) and for understanding.

Now, if you want to create something much more complicated than that _and_ want it to be hidden from the eyes of the programmer, but you _still_ require that the new definitions are somehow understood to be there, be callable from Scala code, and so on you are in effect creating a dialect: a language that cannot be understood without precise knowledge of what the annotation does. And the tooling experience will be substandard too, because of these hidden definitions.

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [June 14, 2023, 9:07am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/54 "2023-06-14T09:07:15Z")

</div>

> [@lihaoyi](#):
>
> Either the editor integration is “part of Scala”, or it’s not.
> 
> 1. If the editor integration is not “part of Scala”, we do not need to worry about integrating with dozens of different editors, but all we have is a fancy linter. Linters are great, but it’s not a viable replacement for macro annotations at all. We already have plenty of linters, and do not need another one baked into the language. People can write their own linters, and have.

The editor integration is not part of Scala. It can be offered in Scala tooling, just like Github can offer Copilot. It’s not linting baked into the language either. Rather, it’s the code of the macro annotation that can do the checks.

To give some ideas what a macro annotation can do:

- Generate definitions that are not directly accessible from the same Scala program, but that can be used for e.g. FFIs or host embeddings. Example: @main
- Check the code of the annotated definition in some sense. Example: @tailrec
- Change the body of the annotated definition without changing its signature. Example @optimized
- Serve as markers for external tools. Basically that’s what Java annotation processors are. For instance, we could have a codegen tool based on TastyQuery that takes an annotated file and produces companion units that add new definitions. With a bit more effort we could let such a tool even produce Tasty directly, so no string concatenation would be needed to do this form of codegen. That tool does not exist currently, but the foundations to develop it are in place,  
If there’s enough interest, we as a community can try to find the resources to develop it.

---

<div class="post-metadata">

**Author:** ![rssh](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/rssh/32/745_2.png) [@rssh](https://contributors.scala-lang.org/u/rssh)\
**Post date:** [June 14, 2023, 9:08am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/55 "2023-06-14T09:08:44Z")

</div>

With such a definition, I can say that any sufficiently advanced framework defines a language dialect.

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [June 14, 2023, 9:17am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/56 "2023-06-14T09:17:12Z")

</div>

> [@lihaoyi](#):
>
> But there is basically only one way to abstract over _definitions_: you can extend a `trait`. That’s great for some use cases, but not sufficient for others. When you see codegen in Scala, it’s basically always for generating definitions. The Dotty repo itself uses codegen. Many of my own projects use codegen.

I think it would be good to work from concrete examples. Where does the dotty repo use codegen? And how is codegen used in your projects?

---

<div class="post-metadata">

**Author:** ![MateuszKowalewski](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mateuszkowalewski/32/77_2.png) [@MateuszKowalewski](https://contributors.scala-lang.org/u/MateuszKowalewski)\
**Post date:** [June 14, 2023, 9:45am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/57 "2023-06-14T09:45:18Z")

</div>

> [@odersky](#):
>
> Now, if you want to create something much more complicated than that _and_ want it to be hidden from the eyes of the programmer, but you _still_ require that the new definitions are somehow understood to be there, be callable from Scala code, and so on you are in effect creating a dialect: a language that cannot be understood without precise knowledge of what the annotation does. And the tooling experience will be substandard too, because of these hidden definitions.

At least I’m not arguing for any hidden (or like I called it elsewhere “virtual”) code.

Generated code needs to be easily accessible and introspectable for tooling and humans. That’s for sure!

I think that generation of “virtual” invisible code was a flaw in the old macro annotations. In this point I’m fully with you!

But just dumping the generated code into some sources that are otherwise meant to be maintained by humans directly seems just wrong also.

And I don’t buy that “dialect” part. Under such definition almost every Java framework would constitute a “Java dialect”. Nobody ever called it like that; not even something close. Or: Do Rust macros create “Rust dialects”? Honest question.

You always need to know what’s happening under the hood when you use some framework / feature that does seemingly “magic things”. But just having some “magic things” around doesn’t create a language “dialect”. (But in the end it makes no difference to argue this part. Words can be defined arbitrary. So the proposed definition is arbitrary, and “we don’t want ‘dialects’” needs still some concrete justification as _such “dialects”_ are obviously harmless. Almost no language with meta-programming facilities broke because people created meta programs! LISP may be an exception to this rule as it offers very powerful rewriting _on the bare syntax level_ without any safety net of semantic checks, and especially no type checks. But other languages with meta-programming systems don’t suffer form this phenomenon. You can’t call a list as a function by accident in a typed language only because you prepended some symbol to that list that’s bound to a function in some scope. But in LISP exactly this can happen. All you have is s-expression soup. More modern languages have a different types of expressions so messing things up by accident is very unlikely.)

---

<div class="post-metadata">

**Author:** ![MateuszKowalewski](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mateuszkowalewski/32/77_2.png) [@MateuszKowalewski](https://contributors.scala-lang.org/u/MateuszKowalewski)\
**Post date:** [June 14, 2023, 10:08am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/58 "2023-06-14T10:08:30Z")

</div>

> [@odersky](#):
>
> Rather, it’s the code of the macro annotation that can do the checks.

Yeah, checks.

But not the actual work that’s _the sole reason_ to use some facility like that.

> [@odersky](#):
>
> To give some ideas what a macro annotation can do:
> 
> […]
> 
> - Serve as markers for external tools. Basically that’s what Java annotation processors are. For instance, we could have a codegen tool based on TastyQuery that takes an annotated file and produces companion units that add new definitions.

That goes into the direction I’m after.

What I don’t understand: Why external tools? Why TastyQuery?

We have already a very fine DSL built into the language to abstract over code creation : Macros! The new quote stuff is impressive and more advanced than what for example the mentioned Kotlin compiler / tooling offers. All that’s needed now is a possibility to export definitions from the macro scope into the outer program.

Such an export should of course not interfere with type checking inside the compilation unit where it gets imported _in any other way than some regular compilation unit (code in a different file) that gets imported can_. Otherwise we would have the previous mess, with invisible “action at a distance”.

Java is already very dynamic regarding imports, and Scala has excellent support for separate compilation. So one could relatively easy export definitions from macro scope, dump the results to disk, and make them available as an otherwise normal external compilation unit for a “second stage of compilation”. (That’s more or less my understanding of how the mentioned export macros @littlenag is building would work, only that the “dump stuff to disk” part isn’t planed currently afaik; please correct me if I misunderstood).

---

<div class="post-metadata">

**Author:** ![MateuszKowalewski](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mateuszkowalewski/32/77_2.png) [@MateuszKowalewski](https://contributors.scala-lang.org/u/MateuszKowalewski)\
**Post date:** [June 14, 2023, 10:35am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/59 "2023-06-14T10:35:01Z")

</div>

> [@odersky](#):
>
> Where does the dotty repo use codegen?

[I’ve lately linked something](https://contributors.scala-lang.org/t/pre-typer-syntactic-plugins-in-scala-3/5565/23) in another post.

> [@odersky](#):
>
> And how is codegen used in your projects?

I don’t know what he’s doing. But maybe what I had in mind so we can discuss concrete examples that I wanted to build using meta-programming in Scala 3: I’m crying for finally sane code-gen because I want to generated whole client and server stubs with all the marshaling in between just from some simple data definitions. Also I want to abstract away the persistence layer for this data completely. Who ever built some web software where the “business logic” is mostly CRUD knows that most of the code is completely repetitive and differs mostly only by the names and structure of some entity classes. The rest is almost completely mechanical. One could rightly say that +90% of the project consist of boilerplate…

The amount of copy-paste in such projects is hilarious! Because you can’t abstract anything away without resorting to the most dirty “tricks” like creating (string) templates for code files that get filled in by some external scripts.

This kind of code-gen would create a lot of code. The generated code would be one or two orders of magnitude larger than the hand written parts. Of course you need all kinds of definitions. Actually I want to generate whole implementation packages. Likely across Scala platforms. So having Scala.js and Scala JVM code generated that matches each other. The code would be mostly not meant to be touched by humans. (But it needs of course to provide some extension points, so hand written code could be hooked in).

As very large parts of the whole code would be generated a good debugging story is vital. Also being able to read and test the code during development of the “templates” is important. So “virtual” code is no good.

Macro annotations as such play only a small role in this scenario. They would be only the trigger points for code-gen. Convenience of writing “templates” and the tooling support around that are the main concerns here.

OTOH I don’t need any “checking of validity” triggered by the macros.

Is this a workable example?

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [June 14, 2023, 11:13am UTC](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035/60 "2023-06-14T11:13:33Z")

</div>

So if I understand correctly, what you are after is a high-level annotation processor that can produce .scala files and other artifacts? I agree that this would be useful to have. It could probably be implemented as a compiler plugin using quotes.reflect as a base layer.

[Previous page](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035.md?page=2)

[Next page](https://contributors.scala-lang.org/t/scala-3-macro-annotations-and-code-generation/6035.md?page=4)
