Safe Code Generation with Scala 3 Macros

By Aggelos Biboudis

Elevator Pitch

In this talk we introduce compile-time staging–a mechanism for well-scoped, type-safe, code generation which is part of the new Scala 3 macro system. We show how staging can be used to enhance the runtime performance of existing libraries such as Spire and Shapeless.

Description

Macros in Scala 3 are built on two well-known fundamental operations: quotation and splicing. Quotation converts program code to data, specifically, a (tree-like) representation of this code. It is expressed as '{...} for expressions and as '[...] for types. Splicing, expressed as ${ ... }, goes the other way: it converts a program’s representation to program code. With these operations we can build code-generators either at compile- or run-time. In this talk we will focus on the latter to effectively create a code-generator for two well-known libraries. Our goal will be to demonstrate how we can remove various abstractions that incur performance penalties through:

  • Partial evaluation (e.g., inlining)
  • Various forms of specialization (e.g., remove boxing)

Our examples build on top of minispire, a small, self-contained kernel of Spire presented by Denis Rosset and Shapeless 3 presented by Miles Shabin.