Your very first macro method in Apache Groovy

Your very first macro method in Apache Groovy

3329a8ef50ae3388665964637001fcb6?s=128

Sergei Egorov

March 02, 2017
Tweet

Transcript

  1. Macro methods Sergei Egorov @bsideup

  2. About me DevOps Advocate at ZeroTurnaround Apache Groovy Committer Created

    MacroGroovy & groovy macro methods
  3. About me DevOps Advocate at ZeroTurnaround Apache Groovy Committer Created

    MacroGroovy & groovy macro methods Got drunk and fell yesterday at speakers’ dinner, lol :D
  4. Macro Methods And why should you care?

  5. Groovy awesomeness

  6. Groovy awesomeness Runtime
 meta-programming

  7. Groovy awesomeness Runtime
 meta-programming Compile-time
 meta-programming

  8. Groovy awesomeness Runtime
 meta-programming Compile-time
 meta-programming ( ask someone else

    :D )
  9. Groovy awesomeness Runtime
 meta-programming Compile-time
 meta-programming ( ask someone else

    :D ) Local AST transformations
  10. Groovy awesomeness Runtime
 meta-programming Compile-time
 meta-programming ( ask someone else

    :D ) Local AST transformations Global AST transformations
  11. Global AST transformations

  12. Ask him!

  13. GORM’s GlobalDetachedCriteriaASTTransformation

  14. def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' }

    def bartQuery = criteria.build { eq 'firstName', 'Bart' }
  15. def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' }

    def bartQuery = criteria.build { eq 'firstName', 'Bart' } Aha! Macro method!!1
  16. Groovy’s AstBuilder.buildFromCode

  17. def result = new AstBuilder().buildFromCode { while (true) { x++;

    continue } }
  18. def result = new AstBuilder().buildFromCode { while (true) { x++;

    continue } } Macro method!
  19. What’s in common?

  20. They’re global AST transformations

  21. Scenario 1. Find a method call

  22. Scenario 1. Find a method call 2. analyse it

  23. Scenario 1. Find a method call 2. analyse it 3.

    Using its arguments, produce new Expression
  24. Scenario 1. Find a method call 2. analyse it 3.

    Using its arguments, produce new Expression 4. Replace that method call with what we got in #3
  25. Smells like demo

  26. What can you implement?

  27. def fact(num) { return match(num) { String >> fact(num.toInteger()) (0

    | 1) >> 1 2 >> 2 _ >> _ * fact(_ - 1) } } Pattern Matching
  28. def fact(num) { return match(num) { String >> fact(num.toInteger()) (0

    | 1) >> 1 2 >> 2 _ >> _ * fact(_ - 1) } } Pattern Matching Scala? ewww!
  29. None
  30. def fact(num) { return match(num) { when String then fact(num.toInteger())

    when 0 or 1 then 1 when 2 then 2 orElse it * fact(it - 1) } } DSL-like Pattern Matching
  31. doWithData { assert a + b == c where: a

    | b || c 1 | 2 || 3 4 | 5 || 9 7 | 8 || 15 } Spock-like data tables
  32. // your awesome library here ?