Skip to content

Instantly share code, notes, and snippets.

@melix
Created October 17, 2014 22:19
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 melix/c02227081dd60f5cedaa to your computer and use it in GitHub Desktop.
Save melix/c02227081dd60f5cedaa to your computer and use it in GitHub Desktop.
AST Pattern matching
// "macro" builds the AST of the corresponding block
def ast1 = macro { foo(a) + foo(a) }
def ast2 = macro { foo(a) + foo(foo(a)) }
// we build another AST which will be used as a pattern
def pattern = macro {
x + foo(x)
}.withConstraints {
// declare that x is not a variable, but a placeholder
placeholder x
}
assert !ast1.matches(pattern) // then the first AST doesn't match the pattern
assert ast2.matches(pattern) // but the second one does!
@chensb
Copy link

chensb commented Oct 23, 2014

It's awesome!

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