SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Groovy AST Transformations
What is Groovy?
●   A dynamic programming language that runs on
    the JVM
●   Language is essentially a superset of Java, in
    fact grammar to parse Groovy is constructed
    from Java grammar
●   Groovy source code is translated into Java
    bytecode by the Groovy compiler for execution
    on the JVM
Where is Groovy?
●   Groovy as a scripting language
●   Frameworks for application development
    ●   Grails – Web framework
    ●   Griffon – Swing applications
    ●   Gaelyk – Google App Engine
●   Testing
    ●   Easyb – Behavior Driven Development
    ●   Spock – BDD and mocking
    ●   Gmock - Mocking
Where is Groovy? (cont...)
●   Building projects
    ●   Gradle
    ●   Gant
How does Groovy code become
         bytcode?
What is an Abstract Syntax Tree?
●   Rooted tree of nodes
●   Composed of nodes that correspond to Groovy
    language constructs
●   We are interested in Groovy's AST syntax tree
●   Composed of ASTNodes from the
    org.codehaus.groovy.ast package and
    subpackages
●   Tree structure lends itself to processing using
    Visitor design pattern
What is an AST Transformation?
●   Compiler hook Groovy provides into
    compilation process
●   Means of extending language without grammar
    changes
●   Allows manipulation of AST during compilation
    prior to bytecode generation
●   Two types
    ●   Local
    ●   Global
Local AST Transformations
●   More common
●   Applied to specific declarations whose AST is to
    be modified by the transformation
●   Annotation indicates AST transformation should
    be applied to declaration
●   AST is walked and AST transformation applied
    to nodes that are annotated with transformation
    annotation (Visitor design pattern)
●   Many supplied with Groovy distribution
Global AST Transformations
●   Less common
●   Applied to every source unit in compilation
●   Uses jar file service provider mechanism to
    identify global AST transformations
●   Jar file added to classpath of compiler that
    contains service locator file identifying name of
    class that implements AST transformation
Groovy's Built-in AST
               Transformations
●   Code generation
●   Design pattern implementation
●   Simplified logging
●   Concurrency support
●   Cloning and externalization
●   JavaBeans support
●   Script safety
●   Static typing
●   Miscellaneous
Code Generation
●   @ToString
●   @EqualsAndHashCode
●   @TupleConstructor
●   @Canonical
●   @Lazy
●   @InheritConstructors
Example - @ToString
@groovy.transform.ToString
class Person {
    String first, last
}
def person = new Person(first:"Hamlet", last:"D'Arcy")
println "${person.toString()}"



Result with @ToString transformation:
Person(Hamlet, D'Arcy)

Result without @ToString transformation:
Person@175078b
Design Pattern Implementation
●   @Delgate
●   @Singleton
●   @Immutable
●   @Mixin
●   @Category
Example - @Delegate
class Delegate1Class {
   public void method1() {}
   public void method2(String p) {}
}

public class OwnerClass {
    @Delegate Delegate1Class delegate1 = new Delegate1Class()
}


The @Delegate AST transformation implements delegation by
adding all of the public methods from the delegate class to the
owner class.
Simplified Logging
●   @Log
●   @Log4j
●   @Slf4j
●   @Commons
Concurrency Support

●   @Synchronized
●   @WithReadLock
●   @WithWriteLock
Cloning and Externalization
●   @AutoClone
●   @AutoExternalize
JavaBeans Support
●   @Bindable
●   @Vetoable
●   @ListenerList
Scripting Safety
●   @TimedInterrupt
●   @ThreadInterrupt
●   @ConditionalInterrupt
Static Typing
●   @TypeChecked
●   @CompileStatic
Example - @TypeChecked
@groovy.transform.TypeChecked
Number test() {
    // Cannot find matching method
    MyMethod()

    // Variable is undelcared
    println myField

    // Cannot assign String to int
    int object = "myString"

    // Cannot return value of type String on method returning type Number
    return "myString"
}
Miscellaneous
●   @Field
●   @PackageScope
●   @Newify
Location of Built-in AST
             Transformations
●   Annotation definition usually found in
    groovy.transform or groovy.lang
●   Implementation class usually found in
    org.codehaus.groovy.transform
Custom AST Transformations
●   Defined in exactly same manner as built-in AST
    transformations
●   Steps
    1. Create AST transformation implementation class that
       implements the ASTTransformation interface
    2. Create AST transformation annotation declaration and
       link it to the implementation class with the
       @GroovyASTTransformationClass annotation
The Implementation Class
●   Implements the ASTTransformation interface
    ●   Single method
        void visit(ASTNode nodes[], SourceUnit source)
●   Compiler invokes this method on AST of annotated
    element
●   nodes array contains AnnotationNode for AST
    transformation annotation and AnnotatedNode
    corresponding to annotated declaration
HelloWorldASTTransformation
@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
public class HelloWorldASTTransformation implements ASTTransformation {

   public void visit(ASTNode[] nodes, SourceUnit source) {
       MethodNode methodNode = (MethodNode)nodes[1]
       Statement methodCode = methodNode.getCode()

       //
       // Add greeting to beginning of code block.
       //
       methodCode.getStatements().add(0, createPrintlnStatement())
   }
The Annotation Type Declaration
●   Indicate declaration types to which AST
    transformation is applicable with @Target
    annotation
●   Indicate implementation class with
    @GroovyASTTransformationClass
    annotation
HelloWorld
@Target([ElementType.METHOD])
@GroovyASTTransformationClass("HelloWorldASTTransformation")
public @interface HelloWorld {}
HelloWorldExample
@HelloWorld
void myMethod() {
}
myMethod()
The Hard Part – Creating AST
                  objects
●   Tools to help
    ●   AST Browser
    ●   ASTBuilder
●   Ways to create AST objects
    ●   Manually using ASTNode subclass constructors
        (leveraging AST Browser)
    ●   Using ASTBuilder.buildFromSpec
    ●   Using ASTBuilder.buildFromString
    ●   Using ASTBuilder.buildFromCode
Implementing createPrintlnStatement
                 Manually
private Statement createPrintlnStatement() {
    Statement printlnStatement =
          new ExpressionStatement(
            new MethodCallExpression(
                new VariableExpression("this"),
                new ConstantExpression("println"),
                new ArgumentListExpression(
                   new ConstantExpression("Hello World!!!!"))
                ))
    return printlnStatement
}
Implementing createPrintlnStatement using
             buildFromSpec

 private Statement createPrintlnStatement() {
     List<ASTNode> results = new AstBuilder().buildFromSpec {
         expression {
             methodCall {
                 variable "this"
                 constant "println"
                 argumentList {
                      constant "Hello World!!!!"
                 }
             }
         }
     }
     return results[0]
 }
Implementing createPrintlnStatement using
            buildFromString
private Statement createPrintlnStatement() {
    List<ASTNode> result =
      new AstBuilder().buildFromString("println 'Hello World!!!!'; return")
    return result[0]
}
Implementing createPrintlnStatement using
             buildFromCode
private Statement createPrintlnStatement() {

    List<ASTNode> result = new AstBuilder().buildFromCode {
        println "Hello World!!!!"
        return
    }
    return result[0]
}
Resources
●   Groovy code itself provides excellent examples
●   AST Browser is invaluable for seeing what code
    is generated by a transformation
●
    Groovy in Action (2nd edition) in MEAP –
    Chapter 9 written by Hamlet D'Arcy
●   Unit tests for ASTBuilder
●   Shameless plug: Groovy Under the Hood in
    GroovyMag

Weitere ähnliche Inhalte

Was ist angesagt?

Topological Sorting
Topological SortingTopological Sorting
Topological SortingShahDhruv21
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
What Does R7RS Change Programming in Scheme?
What Does R7RS Change Programming in Scheme?What Does R7RS Change Programming in Scheme?
What Does R7RS Change Programming in Scheme?Kazuhiro Hishinuma
 
Interpretability beyond feature attribution quantitative testing with concept...
Interpretability beyond feature attribution quantitative testing with concept...Interpretability beyond feature attribution quantitative testing with concept...
Interpretability beyond feature attribution quantitative testing with concept...MLconf
 
Jupyter, A Platform for Data Science at Scale
Jupyter, A Platform for Data Science at ScaleJupyter, A Platform for Data Science at Scale
Jupyter, A Platform for Data Science at ScaleMatthias Bussonnier
 
Boolean and conditional logic in Python
Boolean and conditional logic in PythonBoolean and conditional logic in Python
Boolean and conditional logic in Pythongsdhindsa
 
20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영Tae Young Lee
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 
Python functions
Python functionsPython functions
Python functionsAliyamanasa
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaEdureka!
 
Python Visual Studio | Edureka
Python Visual Studio | EdurekaPython Visual Studio | Edureka
Python Visual Studio | EdurekaEdureka!
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderMoni Adhikary
 
An introduction to Jupyter notebooks and the Noteable service
An introduction to Jupyter notebooks and the Noteable serviceAn introduction to Jupyter notebooks and the Noteable service
An introduction to Jupyter notebooks and the Noteable serviceJisc
 

Was ist angesagt? (20)

Topological Sorting
Topological SortingTopological Sorting
Topological Sorting
 
Python
PythonPython
Python
 
Overriding
OverridingOverriding
Overriding
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
What Does R7RS Change Programming in Scheme?
What Does R7RS Change Programming in Scheme?What Does R7RS Change Programming in Scheme?
What Does R7RS Change Programming in Scheme?
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Interpretability beyond feature attribution quantitative testing with concept...
Interpretability beyond feature attribution quantitative testing with concept...Interpretability beyond feature attribution quantitative testing with concept...
Interpretability beyond feature attribution quantitative testing with concept...
 
Jupyter, A Platform for Data Science at Scale
Jupyter, A Platform for Data Science at ScaleJupyter, A Platform for Data Science at Scale
Jupyter, A Platform for Data Science at Scale
 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
 
Boolean and conditional logic in Python
Boolean and conditional logic in PythonBoolean and conditional logic in Python
Boolean and conditional logic in Python
 
20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영20150306 파이썬기초 IPython을이용한프로그래밍_이태영
20150306 파이썬기초 IPython을이용한프로그래밍_이태영
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Python functions
Python functionsPython functions
Python functions
 
Python basics
Python basicsPython basics
Python basics
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
 
Python Visual Studio | Edureka
Python Visual Studio | EdurekaPython Visual Studio | Edureka
Python Visual Studio | Edureka
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Awt
AwtAwt
Awt
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladder
 
An introduction to Jupyter notebooks and the Noteable service
An introduction to Jupyter notebooks and the Noteable serviceAn introduction to Jupyter notebooks and the Noteable service
An introduction to Jupyter notebooks and the Noteable service
 

Andere mochten auch

AST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres AlmirayAST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres AlmirayZeroTurnaround
 
Un Paseo por las Transformaciones AST de Groovy
Un Paseo por las Transformaciones AST de GroovyUn Paseo por las Transformaciones AST de Groovy
Un Paseo por las Transformaciones AST de GroovyAndres Almiray
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
groovy transforms
groovy transformsgroovy transforms
groovy transformsPaul King
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 

Andere mochten auch (6)

AST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres AlmirayAST Transformations: Groovy’s best kept secret by Andres Almiray
AST Transformations: Groovy’s best kept secret by Andres Almiray
 
Un Paseo por las Transformaciones AST de Groovy
Un Paseo por las Transformaciones AST de GroovyUn Paseo por las Transformaciones AST de Groovy
Un Paseo por las Transformaciones AST de Groovy
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
groovy transforms
groovy transformsgroovy transforms
groovy transforms
 
Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 

Ähnlich wie Groovy AST Transformations

"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James NelsonGWTcon
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGlobalLogic Ukraine
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
 
Groovy AST Demystified
Groovy AST DemystifiedGroovy AST Demystified
Groovy AST DemystifiedAndres Almiray
 
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGuillaume Laforge
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2JooinK
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Joachim Baumann
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005Tugdual Grall
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 

Ähnlich wie Groovy AST Transformations (20)

"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Ast transformation
Ast transformationAst transformation
Ast transformation
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transforms
 
Groovy AST Demystified
Groovy AST DemystifiedGroovy AST Demystified
Groovy AST Demystified
 
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 

Kürzlich hochgeladen

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 

Kürzlich hochgeladen (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 

Groovy AST Transformations

  • 2. What is Groovy? ● A dynamic programming language that runs on the JVM ● Language is essentially a superset of Java, in fact grammar to parse Groovy is constructed from Java grammar ● Groovy source code is translated into Java bytecode by the Groovy compiler for execution on the JVM
  • 3. Where is Groovy? ● Groovy as a scripting language ● Frameworks for application development ● Grails – Web framework ● Griffon – Swing applications ● Gaelyk – Google App Engine ● Testing ● Easyb – Behavior Driven Development ● Spock – BDD and mocking ● Gmock - Mocking
  • 4. Where is Groovy? (cont...) ● Building projects ● Gradle ● Gant
  • 5. How does Groovy code become bytcode?
  • 6. What is an Abstract Syntax Tree? ● Rooted tree of nodes ● Composed of nodes that correspond to Groovy language constructs ● We are interested in Groovy's AST syntax tree ● Composed of ASTNodes from the org.codehaus.groovy.ast package and subpackages ● Tree structure lends itself to processing using Visitor design pattern
  • 7. What is an AST Transformation? ● Compiler hook Groovy provides into compilation process ● Means of extending language without grammar changes ● Allows manipulation of AST during compilation prior to bytecode generation ● Two types ● Local ● Global
  • 8. Local AST Transformations ● More common ● Applied to specific declarations whose AST is to be modified by the transformation ● Annotation indicates AST transformation should be applied to declaration ● AST is walked and AST transformation applied to nodes that are annotated with transformation annotation (Visitor design pattern) ● Many supplied with Groovy distribution
  • 9. Global AST Transformations ● Less common ● Applied to every source unit in compilation ● Uses jar file service provider mechanism to identify global AST transformations ● Jar file added to classpath of compiler that contains service locator file identifying name of class that implements AST transformation
  • 10. Groovy's Built-in AST Transformations ● Code generation ● Design pattern implementation ● Simplified logging ● Concurrency support ● Cloning and externalization ● JavaBeans support ● Script safety ● Static typing ● Miscellaneous
  • 11. Code Generation ● @ToString ● @EqualsAndHashCode ● @TupleConstructor ● @Canonical ● @Lazy ● @InheritConstructors
  • 12. Example - @ToString @groovy.transform.ToString class Person { String first, last } def person = new Person(first:"Hamlet", last:"D'Arcy") println "${person.toString()}" Result with @ToString transformation: Person(Hamlet, D'Arcy) Result without @ToString transformation: Person@175078b
  • 13. Design Pattern Implementation ● @Delgate ● @Singleton ● @Immutable ● @Mixin ● @Category
  • 14. Example - @Delegate class Delegate1Class { public void method1() {} public void method2(String p) {} } public class OwnerClass { @Delegate Delegate1Class delegate1 = new Delegate1Class() } The @Delegate AST transformation implements delegation by adding all of the public methods from the delegate class to the owner class.
  • 15. Simplified Logging ● @Log ● @Log4j ● @Slf4j ● @Commons
  • 16. Concurrency Support ● @Synchronized ● @WithReadLock ● @WithWriteLock
  • 17. Cloning and Externalization ● @AutoClone ● @AutoExternalize
  • 18. JavaBeans Support ● @Bindable ● @Vetoable ● @ListenerList
  • 19. Scripting Safety ● @TimedInterrupt ● @ThreadInterrupt ● @ConditionalInterrupt
  • 20. Static Typing ● @TypeChecked ● @CompileStatic
  • 21. Example - @TypeChecked @groovy.transform.TypeChecked Number test() { // Cannot find matching method MyMethod() // Variable is undelcared println myField // Cannot assign String to int int object = "myString" // Cannot return value of type String on method returning type Number return "myString" }
  • 22. Miscellaneous ● @Field ● @PackageScope ● @Newify
  • 23. Location of Built-in AST Transformations ● Annotation definition usually found in groovy.transform or groovy.lang ● Implementation class usually found in org.codehaus.groovy.transform
  • 24. Custom AST Transformations ● Defined in exactly same manner as built-in AST transformations ● Steps 1. Create AST transformation implementation class that implements the ASTTransformation interface 2. Create AST transformation annotation declaration and link it to the implementation class with the @GroovyASTTransformationClass annotation
  • 25. The Implementation Class ● Implements the ASTTransformation interface ● Single method void visit(ASTNode nodes[], SourceUnit source) ● Compiler invokes this method on AST of annotated element ● nodes array contains AnnotationNode for AST transformation annotation and AnnotatedNode corresponding to annotated declaration
  • 26. HelloWorldASTTransformation @GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS) public class HelloWorldASTTransformation implements ASTTransformation { public void visit(ASTNode[] nodes, SourceUnit source) { MethodNode methodNode = (MethodNode)nodes[1] Statement methodCode = methodNode.getCode() // // Add greeting to beginning of code block. // methodCode.getStatements().add(0, createPrintlnStatement()) }
  • 27. The Annotation Type Declaration ● Indicate declaration types to which AST transformation is applicable with @Target annotation ● Indicate implementation class with @GroovyASTTransformationClass annotation
  • 30. The Hard Part – Creating AST objects ● Tools to help ● AST Browser ● ASTBuilder ● Ways to create AST objects ● Manually using ASTNode subclass constructors (leveraging AST Browser) ● Using ASTBuilder.buildFromSpec ● Using ASTBuilder.buildFromString ● Using ASTBuilder.buildFromCode
  • 31. Implementing createPrintlnStatement Manually private Statement createPrintlnStatement() { Statement printlnStatement = new ExpressionStatement( new MethodCallExpression( new VariableExpression("this"), new ConstantExpression("println"), new ArgumentListExpression( new ConstantExpression("Hello World!!!!")) )) return printlnStatement }
  • 32. Implementing createPrintlnStatement using buildFromSpec private Statement createPrintlnStatement() { List<ASTNode> results = new AstBuilder().buildFromSpec { expression { methodCall { variable "this" constant "println" argumentList { constant "Hello World!!!!" } } } } return results[0] }
  • 33. Implementing createPrintlnStatement using buildFromString private Statement createPrintlnStatement() { List<ASTNode> result = new AstBuilder().buildFromString("println 'Hello World!!!!'; return") return result[0] }
  • 34. Implementing createPrintlnStatement using buildFromCode private Statement createPrintlnStatement() { List<ASTNode> result = new AstBuilder().buildFromCode { println "Hello World!!!!" return } return result[0] }
  • 35. Resources ● Groovy code itself provides excellent examples ● AST Browser is invaluable for seeing what code is generated by a transformation ● Groovy in Action (2nd edition) in MEAP – Chapter 9 written by Hamlet D'Arcy ● Unit tests for ASTBuilder ● Shameless plug: Groovy Under the Hood in GroovyMag

Hinweis der Redaktion

  1. Grails – MVC framework with controllers and service classes in Groovy Griffon – Grails-like application framework for developing rich desktop applications Gaelyk – lightweight Groovy toolkit for building and deploying applications on Google App Engine Easyb – test specifications written in Groovy
  2. Gant – tool for scripting Ant tasks using Groovy instead of XML to specify logic Gradle – enterprise-grade build system - Groovy build scripts - Dependency management - Used by hibernate, Grails, Groovy
  3. This AST is a rooted tree made up of nodes that describes the various constructs within source code in a form that can be easily processed using the Visitor design pattern ( http://en.wikipedia.org/wiki/Visitor_pattern ). The Visitor design pattern essentially constructs a visitor object that traverses the tree and performs some action on each node in the tree.
  4. Focus on automating repetative task of writing common methods likequals, hashCode and constructors
  5. Verify using javap on OwnerClass
  6. - Shorthand notation for every ASTNode type - API simplified - Helps eliminates some verbosity and complexity - Returns script class node as well - desired AST in first entry