TheAptKid
TheAptKid

Reputation: 1571

When is macro expansion performed?

I'm learning about macros in Racket (language successor of Scheme). There is no mentioning of when the macro expansion is performed. On page 17 of this document I found a paragraph that says it happens before type-checking, evaluation and compiling.

So if I understand correctly, macro expansion occurs right after building the abstract syntax tree (AST)?

Upvotes: 6

Views: 481

Answers (1)

Greg Hendershott
Greg Hendershott

Reputation: 16260

Although a Racket expert might correct me, my understanding is that the main stages are:

  1. A read pass that processes the input characters into a syntax object.

  2. An expansion pass that recursively expands the syntax object, including using user-defined macros.

  3. Evaluation. (JIT compilation happens during evaluation, whenever a not-yet-compiled function is called.)

In other words the REPL (read eval print loop) is really more like a REEPL (read expand eval print loop).

For an extreme level of detail see Language Model including e.g. the Syntax Model section.

You mentioned "type-checking".

  • Plain Racket (e.g. #lang racket) is dynamically typed and checking is done at runtime.
  • Typed Racket (e.g. #lang typed/racket) does static type-checking during expansion: the Typed Racket system is implemented via macros. See Section 10, "Implementation", of Sam Tobin-Hochstadt's dissertation.

(Edited to note the JIT is actually part of evaluation, not a separate stage.)

Upvotes: 9

Related Questions