Skip to content

Instantly share code, notes, and snippets.

@yloiseau
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yloiseau/3769078f4daeb7e95731 to your computer and use it in GitHub Desktop.
Save yloiseau/3769078f4daeb7e95731 to your computer and use it in GitHub Desktop.
Macro usage

Since the plumbing behind macro compilation in Golo is not finished yet, here is some instructions to test your first macros.

File MyTestMacro.class

module MyTestMacro

import gololang.macros.CodeBuilder

macro sayHello = |name| {
  let msg = constant("Hello " + name: getValue())
  return quote { println(~msg) }
}

Note that here, we could have use function instead of macro since it's in a different module. Or, for such simple macros, we could have named the module the same as below, but in a different file... to understant why, use the source Luke. (this is temporary, I plan to ease the compilation step, but it's not done yet).

This module must be compiled before any other module using the macro. The compilation will generate a MyTestMacro/Macros.class that is a “normal” Golo module containing only the macro functions. (I'll try to change that to MyTestMacro$Macros.class, but I have issues here since the inner class will be compiled before the outer one, it's more or less what is done with augmentation, but compile time.)

File myTest.golo

module MyTest

&use("MyTestMacro")

function main = |args| {
  &sayHello("world")
}

Note: if you have named your macro module the same as this module, you can remove the "&use" since the current module class and macro class (i.e. MyTest.class and MyTest/Macros.class) are automatically used in the macro lookup process.

To interpret or compile this module, that is to expand macros, the class containing the macros must be in the classpath of the compiler thread. Currently, you have to set CLASSPATH_PREFIX (the --classpath option of the golo golo command does not do the right thing here, and golo compile does not have such option yet)

So to exec this code:

export CLASSPATH_PREFIX=.
golo compile myTestMacro.golo && golo golo --files myTest.golo

or to decompose:

golo compile myTestMacro.golo
CLASSPATH_PREFIX=. golo compile myTest.golo
golo run --module MyTest

or even

CLASSPATH_PREFIX=. golo compile  myTestMacro.golo myTest.golo
golo run --module MyTest

with a recent version of my branch you can see the result of the macro expansion using

CLASSPATH_PREFIX=. golo diagnose --tool ppe myTest.golo

(for pretty print expanded) which print the code corresponding to the expanded IR. This code is not re-parsable, since it is just a view of the IR, with some magic applied. Interesting to see the result of a match or a foreach for example 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment