Code Generation

                         Lecture 10
                          May 4, 2010




                                                  Course IN4308
     Eelco Visser
                                       Master Computer Science
http://eelcovisser.org             Delft University of Technology
Coming up
Lecture 8: Context-sensitive transformation
   ★ design 2
   ★ transformation with dynamic rewrite rules

Lecture 9: Static analysis & error checking
   ★ name resolution, reference resolution
   ★ type analysis

Lecture 10: Code generation
   ★ string templates, code generation by model transformation
   ★ concrete object syntax

Lecture 11: Code generation strategies
   ★ customization of generated code
Code Generation
Code Generation: From Model to Code


Model
  ★ structured representation (abstract syntax)
  ★ produced by parser
  ★ checked for consistency
  ★ transformed to core language

Code
  ★ program text
  ★ no structure
  ★ for consumption by interpreter or compiler
Example: Data Model to Database Schema

entity Blog {
  name :: String
  entries :: List<BlogEntry>
}



         CREATE TABLE IF NOT EXISTS ‘Blog‘ (
           ‘id‘ int(11) NOT NULL auto_increment,
           ‘name‘ text,
           PRIMARY KEY (‘id‘)
         ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

         CREATE TABLE IF NOT EXISTS ‘Blog_entries_BlogEntry‘ (
           ‘parent‘ int(11) NOT NULL,
           ‘value‘ int(11) NOT NULL
         ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
Traversing Abstract Syntax Trees


Pattern matching

 Field(name, SimpleType(x))




Accessor Functions

 if(t instanceof Field) {
   name := t.name();
   if(t.type() instanceof SimpleType) {
     ...
   }
 }
Print Statements
Printing Code

entity-to-sql =
  ?Entity(name, fields);
  <printstring> "DROP TABLE IF EXISTS ‘";
  <printstring> name;
  <printstring> "‘;n";
  <printstring> "CREATE TABLE IF NOT EXISTS ‘";
  <printstring> name;
  <printstring> "‘ ( n";
  <printstring> "‘id‘ int(11) NOT NULL auto_increment;n";
  <map(field-to-sql(|name); printstring> fields;
  <printstring> "PRIMARY KEY (‘id‘)n";
  <printstring> ") ENGINE=MyISAM DEFAULT CHARSET=latin1 ";
  <printstring> "AUTO_INCREMENT=1 ;nn"
Printing Code



Advantages
  ★ accessible (easy to implement in any language)
  ★ concrete syntax
  ★ good performance

Disadvantages
  ★ order of evaluation
  ★ code fragments disrupted to splice meta-data
  ★ no formatting
Composing Strings
String Composition

entity-to-sql :
  Entity(name, fields) ->
  <concat-strings>
     ["DROP TABLE IF EXISTS ‘",name,"‘;n",
      "CREATE TABLE IF NOT EXISTS ‘",name,"‘ ( n",
      "‘id‘ int(11) NOT NULL auto_increment, n",
        <map(field-to-sql(|name));concat-strings> fields,
      "PRIMARY KEY (‘id‘)n",
      ") ENGINE=MyISAM DEFAULT AUTO_INCREMENT=1 ;nn"
   ]

field-to-sql(|entity) :
  Field(name, SimpleType(type)) ->
  <concat-strings>["‘",name,"‘ ",<type-to-sqltype> type,",n"]
String Composition


Advantages
  ★ concrete syntax
  ★ assembly of code fragments independent of order of evaluation




Disadvantages
  ★ disrupted code fragments
  ★ quotes
  ★ escapes
Template Engine
Template Engine



<<DEFINE entity_to_sql FOR entity>>
  DROP TABLE IF EXISTS ‘<<entity.name>>‘;
  CREATE TABLE IF NOT EXISTS ‘<<entity.name>>‘ (
    ‘id‘ int(11) NOT NULL auto_increment,
    <<EXPAND type_to_sqltype FOREACH entity.fields>>
    PRIMARY KEY (‘id‘)
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
<<ENDDEFINE>




            DSL for model to text generation
Template Engine

Advantages
  ★ concrete syntax
  ★ less quoting
  ★ long code fragments
  ★ anti-quotation instead of string concatenation
  ★ no escapes of string meta characters

Disadvantages
  ★ no syntax check
  ★ result is string / printed
  ★ no structure
  ★ integrate separate language
String Interpolation
String Interpolation

entity-to-sql :
  Entity(name, fields) ->
    $[DROP TABLE IF EXISTS ‘[name]‘;
       CREATE TABLE IF NOT EXISTS ‘[name]‘ (
       ‘id‘ int(11) NOT NULL auto_increment,
        [<map(field-to-sql(|name))> fields]
       PRIMARY KEY (‘id‘)
       ) ENGINE=MyISAM DEFAULT AUTO_INCREMENT=1;
     ]

field-to-sql(|entity) :
  Field(name, SimpleType(type)) ->
  $[‘[name]‘ [<type-to-sqltype> type]]
String Interpolation


Advantages
  ★ concrete syntax
  ★ assembly of code fragments independent of order of evaluation
  ★ long code fragments
  ★ anti-quotation instead of string concatenation
  ★ no escapes of string meta characters
  ★ formatting, relative indentation

Disadvantages
  ★ escaping of string interpolation meta characters
Composing ASTs
Code Generation by Model Transformation



Code represented as AST
   ★ (typechecked) structured representation

Text generation by pretty-printing
   ★ separate code formatting from code generation

Apply transformations after generation
   ★ aspect weaving
   ★ optimization
Composing Abstract Syntax Trees

grammar-to-signature :
  Grammar(ss, ps) -> Signature(ss, cds)
  where cds := <map(production-to-consdecl)> ps

production-to-consdecl :
  Prod(symbols, sym, annos) -> ConsDecl(x, types, sort)
  where x := <annos-to-constructor> annos
      ; types := <filter(symbol-to-type)> symbols
      ; sort := sym

annos-to-constructor :
  [Anno(Application("cons", [Constant(c)]))] -> constr
  where constr := <unescape; un-double-quote> c
Composing Abstract Syntax Trees




Advantages
  ★ syntax check through type system (if available)
  ★ automatic formatting
  ★ transformation after generation

Disadvantages
  ★ no concrete syntax
Deriving Rewrite Rules
private $name;
    How does this scale?                          function getName(){
                                                    return $this->name;
                                                  }
                                                  function setName($val){
                                                    $this->name = $val;
                                                  }



generate-entity-field-code :
  Field(name, SimpleType(t)) ->
  [ InstanceVariable(Modifiers([Private()]),[Normal(Variable(Simple(name)))])
  , FunctionDecl(get, [], [
      Return(Some(ObjectAccess(Variable(Simple("this")),
             ObjectProperty(Simple(name)))))])
  , FunctionDecl(set, [Param(Variable(Simple("val")))], [
      Expr(Assign(ObjectAccess(Variable(Simple("this")),
                                ObjectProperty(Simple(name))),
                  Variable(Simple("val"))))])
  ]
  with get := <camelcase>["get",name]
  with set := <camelcase>["set",name]
Concrete Object Syntax
Concrete Syntax Patterns


generate-entity-field-code :
  FieldDefinition(str_name, type) -> php-member* |[
     private $str_name ;
     function str_get() {
       return $this->str_name;
     }
     function str_set($val) {
       $this->str_name = $val;
     }
  ]|
  where <is-primitive-type> type
  with str_get := <camelcase>["get",str_name]
  with str_set := <camelcase>["set",str_name]
Concrete Syntax Ingredients



Quotation of code fragment
   ★ |[ .... ]|

Disambiguation through tagging
   ★ php-member*|[ ... ]|

Meta-variables
   ★ $this->str_name = $val
Implementing Concrete Object Syntax



Extending meta-language
  ★ Stratego + PHP



Parsing meta-programs


Normalizing to core syntax
Extending the Meta-Language (1)



module Stratego
exports
  context-free syntax
    Int                               ->   Term   {cons("Int")}
    String                            ->   Term   {cons("Str")}
    Var                               ->   Term   {cons("Var")}
    Id "(" {Term ","}* ")"            ->   Term   {cons("Op")}
    Term "->" Term                    ->   Rule   {cons("RuleNoCond")}
    Term "->" Term "where" Strategy   ->   Rule   {cons("Rule")}
Extending the Meta-Language (2)



module StrategoPHP
imports PHP
exports
  context-free syntax
    "php-member" "|[" ClassMember "]|" -> Term{cons("ToMetaExpr")}
    "php-member*""|[" ClassMember* "]|" -> Term{cons("ToMetaExpr")}
  variables
    "expr_"[A-Za-z0-9_]+ -> Expr {prefer}
    "str_"[A-Za-z0-9_]+ -> String {prefer}
Parsing Concrete Object Syntax

Field(name, SimpleType(t)) -> php-member|[ private $str_name; ]|

==> parse

Rule(Op("Field", [Var("name"), Op("SimpleType",[Var("t")])]),
     ToMetaExpr(InstanceVariable(Modifiers([Private()]),
                  [Normal(Variable(Simple(meta-var("str_name"))))])))

==> meta-explode

Rule(Op("Field", [Var("name"), Op("SimpleType",[Var("t")])]),
     Op("InstanceVariable",[
       Op("Modifiers", [Op("Cons",[Op("Private",[]),Op("Nil",[])])]),
       Op("Cons", [Op("Normal",[Op("Variable",[Op("Simple",
                                       [Var("str_name")])])]),
                   Op("Nil",[])])]))

==> pretty-print

Field(name, SimpleType(t)) ->
InstanceVariable(Modifiers([Private()]),[Normal(Variable(Simple(str_name)))])
Summary of Code Generation Techniques


Print statements              String interpolation
  ★ easy                        ★ template engine built-in

String composition            Abstract syntax
  ★ out of order evaluation     ★ precise, transformation
                                   after generation
Template engines
                              Concrete object syntax
  ★ less quoting
                                ★ precise
                                ★ concrete
Schedule
Case 3
  ★ Deadline extension: May 9 23:59

Case 4
  ★ `take home exam’
  ★ Questions about lectures 11 to 14
  ★ Deadline: June 15

Design 2
  ★ Syntax for your DSL

Next
  ★ No lecture next week (May 11)
  ★ Lecture 11: code generation policies

More Related Content

PDF
Swift, functional programming, and the future of Objective-C
PDF
JavaScript - Chapter 6 - Basic Functions
PPT
For Beginners - C#
PDF
Coding Guidelines - Crafting Clean Code
PDF
Getting rid of backtracking
PPTX
Introduction to Programming Bots
PPTX
Clojure 7-Languages
PDF
Sql functions
Swift, functional programming, and the future of Objective-C
JavaScript - Chapter 6 - Basic Functions
For Beginners - C#
Coding Guidelines - Crafting Clean Code
Getting rid of backtracking
Introduction to Programming Bots
Clojure 7-Languages
Sql functions

What's hot (20)

PDF
Design Patterns in Modern C++
KEY
Scala: functional programming for the imperative mind
PDF
Contracts in-clojure-pete
PDF
Functional Programming in Scala
PDF
JavaScript - Chapter 4 - Types and Statements
PDF
What You Need to Know about Lambdas
PPTX
Front end fundamentals session 1: javascript core
PPT
C#
PDF
Charles Sharp: Java 8 Streams
PDF
Twins: Object Oriented Programming and Functional Programming
ODP
Domain Specific Languages In Scala Duse3
PDF
Introduction To Scala
PDF
Functional Principles for OO Developers
PDF
Lambda Functions in Java 8
PPT
Scala functions
PDF
RESTful API using scalaz (3)
PDF
Java 8 Lambda Built-in Functional Interfaces
PPT
JavaScript Objects
PPTX
Use of Apache Commons and Utilities
PDF
Ponies and Unicorns With Scala
Design Patterns in Modern C++
Scala: functional programming for the imperative mind
Contracts in-clojure-pete
Functional Programming in Scala
JavaScript - Chapter 4 - Types and Statements
What You Need to Know about Lambdas
Front end fundamentals session 1: javascript core
C#
Charles Sharp: Java 8 Streams
Twins: Object Oriented Programming and Functional Programming
Domain Specific Languages In Scala Duse3
Introduction To Scala
Functional Principles for OO Developers
Lambda Functions in Java 8
Scala functions
RESTful API using scalaz (3)
Java 8 Lambda Built-in Functional Interfaces
JavaScript Objects
Use of Apache Commons and Utilities
Ponies and Unicorns With Scala
Ad

Viewers also liked (14)

PDF
Model-Driven Software Development - Context-Sensitive Transformation
PDF
Building DSLs with the Spoofax Language Workbench
PDF
TI1220 Lecture 14: Domain-Specific Languages
PDF
Model-Driven Software Development - Web Abstractions 1
PDF
Type analysis
PDF
Model-Driven Software Development - Web Abstractions 2
PDF
Composing Domain-Specific Languages
PDF
Static Analysis
PDF
Dataflow Analysis
PDF
From Muddling to Modelling
PDF
Domain Analysis & Data Modeling
PDF
Dynamic Semantics
PDF
Software languages
PDF
Programming languages
Model-Driven Software Development - Context-Sensitive Transformation
Building DSLs with the Spoofax Language Workbench
TI1220 Lecture 14: Domain-Specific Languages
Model-Driven Software Development - Web Abstractions 1
Type analysis
Model-Driven Software Development - Web Abstractions 2
Composing Domain-Specific Languages
Static Analysis
Dataflow Analysis
From Muddling to Modelling
Domain Analysis & Data Modeling
Dynamic Semantics
Software languages
Programming languages
Ad

Similar to Code Generation (20)

PDF
Model-Driven Software Development - Language Workbenches & Syntax Definition
KEY
Xtext Eclipse Con
PDF
Extension and Evolution
PDF
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
PDF
Annotating with Annotations - ForumPHP 2012
PPTX
Domain-Specific Languages
PDF
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
PPT
CASE tools and their effects on software quality
DOC
Chapter 1 1
PPTX
Type-safe DSLs
PPTX
Univ of va intentional introduction 2013 01-31
PDF
Overcoming The Impedance Mismatch Between Source Code And Architecture
PDF
Design concerns for concrete syntax
PDF
Harnessing Stack Overflow for the IDE - RSSE 2012
PDF
Implementing Groovy Domain-Specific Languages - S2G Forum - Munich 2010
PDF
The Solar Framework for PHP
KEY
Pure Sign Breakfast Presentations - Drupal FieldAPI
PPT
Design Patterns
KEY
Talking to your IDE
PPTX
1 cc
Model-Driven Software Development - Language Workbenches & Syntax Definition
Xtext Eclipse Con
Extension and Evolution
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
Annotating with Annotations - ForumPHP 2012
Domain-Specific Languages
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
CASE tools and their effects on software quality
Chapter 1 1
Type-safe DSLs
Univ of va intentional introduction 2013 01-31
Overcoming The Impedance Mismatch Between Source Code And Architecture
Design concerns for concrete syntax
Harnessing Stack Overflow for the IDE - RSSE 2012
Implementing Groovy Domain-Specific Languages - S2G Forum - Munich 2010
The Solar Framework for PHP
Pure Sign Breakfast Presentations - Drupal FieldAPI
Design Patterns
Talking to your IDE
1 cc

More from Eelco Visser (20)

PDF
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
PDF
CS4200 2019 | Lecture 4 | Syntactic Services
PDF
CS4200 2019 | Lecture 3 | Parsing
PDF
CS4200 2019 | Lecture 2 | syntax-definition
PDF
CS4200 2019 Lecture 1: Introduction
PDF
A Direct Semantics of Declarative Disambiguation Rules
PDF
Declarative Type System Specification with Statix
PDF
Compiler Construction | Lecture 17 | Beyond Compiler Construction
PDF
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
PDF
Compiler Construction | Lecture 15 | Memory Management
PDF
Compiler Construction | Lecture 14 | Interpreters
PDF
Compiler Construction | Lecture 13 | Code Generation
PDF
Compiler Construction | Lecture 12 | Virtual Machines
PDF
Compiler Construction | Lecture 11 | Monotone Frameworks
PDF
Compiler Construction | Lecture 10 | Data-Flow Analysis
PDF
Compiler Construction | Lecture 9 | Constraint Resolution
PDF
Compiler Construction | Lecture 8 | Type Constraints
PDF
Compiler Construction | Lecture 7 | Type Checking
PDF
Compiler Construction | Lecture 6 | Introduction to Static Analysis
PDF
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 Lecture 1: Introduction
A Direct Semantics of Declarative Disambiguation Rules
Declarative Type System Specification with Statix
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 5 | Transformation by Term Rewriting

Recently uploaded (20)

PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PPTX
The various Industrial Revolutions .pptx
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
CloudStack 4.21: First Look Webinar slides
PDF
August Patch Tuesday
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Modernising the Digital Integration Hub
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
STKI Israel Market Study 2025 version august
PPTX
Benefits of Physical activity for teenagers.pptx
PDF
Architecture types and enterprise applications.pdf
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
Tartificialntelligence_presentation.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
1 - Historical Antecedents, Social Consideration.pdf
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
The various Industrial Revolutions .pptx
O2C Customer Invoices to Receipt V15A.pptx
WOOl fibre morphology and structure.pdf for textiles
Zenith AI: Advanced Artificial Intelligence
CloudStack 4.21: First Look Webinar slides
August Patch Tuesday
Getting started with AI Agents and Multi-Agent Systems
A novel scalable deep ensemble learning framework for big data classification...
Modernising the Digital Integration Hub
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
STKI Israel Market Study 2025 version august
Benefits of Physical activity for teenagers.pptx
Architecture types and enterprise applications.pdf
A contest of sentiment analysis: k-nearest neighbor versus neural network
Hindi spoken digit analysis for native and non-native speakers
Tartificialntelligence_presentation.pptx
Group 1 Presentation -Planning and Decision Making .pptx
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx

Code Generation

  • 1. Code Generation Lecture 10 May 4, 2010 Course IN4308 Eelco Visser Master Computer Science http://eelcovisser.org Delft University of Technology
  • 2. Coming up Lecture 8: Context-sensitive transformation ★ design 2 ★ transformation with dynamic rewrite rules Lecture 9: Static analysis & error checking ★ name resolution, reference resolution ★ type analysis Lecture 10: Code generation ★ string templates, code generation by model transformation ★ concrete object syntax Lecture 11: Code generation strategies ★ customization of generated code
  • 4. Code Generation: From Model to Code Model ★ structured representation (abstract syntax) ★ produced by parser ★ checked for consistency ★ transformed to core language Code ★ program text ★ no structure ★ for consumption by interpreter or compiler
  • 5. Example: Data Model to Database Schema entity Blog { name :: String entries :: List<BlogEntry> } CREATE TABLE IF NOT EXISTS ‘Blog‘ ( ‘id‘ int(11) NOT NULL auto_increment, ‘name‘ text, PRIMARY KEY (‘id‘) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS ‘Blog_entries_BlogEntry‘ ( ‘parent‘ int(11) NOT NULL, ‘value‘ int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
  • 6. Traversing Abstract Syntax Trees Pattern matching Field(name, SimpleType(x)) Accessor Functions if(t instanceof Field) { name := t.name(); if(t.type() instanceof SimpleType) { ... } }
  • 8. Printing Code entity-to-sql = ?Entity(name, fields); <printstring> "DROP TABLE IF EXISTS ‘"; <printstring> name; <printstring> "‘;n"; <printstring> "CREATE TABLE IF NOT EXISTS ‘"; <printstring> name; <printstring> "‘ ( n"; <printstring> "‘id‘ int(11) NOT NULL auto_increment;n"; <map(field-to-sql(|name); printstring> fields; <printstring> "PRIMARY KEY (‘id‘)n"; <printstring> ") ENGINE=MyISAM DEFAULT CHARSET=latin1 "; <printstring> "AUTO_INCREMENT=1 ;nn"
  • 9. Printing Code Advantages ★ accessible (easy to implement in any language) ★ concrete syntax ★ good performance Disadvantages ★ order of evaluation ★ code fragments disrupted to splice meta-data ★ no formatting
  • 11. String Composition entity-to-sql : Entity(name, fields) -> <concat-strings> ["DROP TABLE IF EXISTS ‘",name,"‘;n", "CREATE TABLE IF NOT EXISTS ‘",name,"‘ ( n", "‘id‘ int(11) NOT NULL auto_increment, n", <map(field-to-sql(|name));concat-strings> fields, "PRIMARY KEY (‘id‘)n", ") ENGINE=MyISAM DEFAULT AUTO_INCREMENT=1 ;nn" ] field-to-sql(|entity) : Field(name, SimpleType(type)) -> <concat-strings>["‘",name,"‘ ",<type-to-sqltype> type,",n"]
  • 12. String Composition Advantages ★ concrete syntax ★ assembly of code fragments independent of order of evaluation Disadvantages ★ disrupted code fragments ★ quotes ★ escapes
  • 14. Template Engine <<DEFINE entity_to_sql FOR entity>> DROP TABLE IF EXISTS ‘<<entity.name>>‘; CREATE TABLE IF NOT EXISTS ‘<<entity.name>>‘ ( ‘id‘ int(11) NOT NULL auto_increment, <<EXPAND type_to_sqltype FOREACH entity.fields>> PRIMARY KEY (‘id‘) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1; <<ENDDEFINE> DSL for model to text generation
  • 15. Template Engine Advantages ★ concrete syntax ★ less quoting ★ long code fragments ★ anti-quotation instead of string concatenation ★ no escapes of string meta characters Disadvantages ★ no syntax check ★ result is string / printed ★ no structure ★ integrate separate language
  • 17. String Interpolation entity-to-sql : Entity(name, fields) -> $[DROP TABLE IF EXISTS ‘[name]‘; CREATE TABLE IF NOT EXISTS ‘[name]‘ ( ‘id‘ int(11) NOT NULL auto_increment, [<map(field-to-sql(|name))> fields] PRIMARY KEY (‘id‘) ) ENGINE=MyISAM DEFAULT AUTO_INCREMENT=1; ] field-to-sql(|entity) : Field(name, SimpleType(type)) -> $[‘[name]‘ [<type-to-sqltype> type]]
  • 18. String Interpolation Advantages ★ concrete syntax ★ assembly of code fragments independent of order of evaluation ★ long code fragments ★ anti-quotation instead of string concatenation ★ no escapes of string meta characters ★ formatting, relative indentation Disadvantages ★ escaping of string interpolation meta characters
  • 20. Code Generation by Model Transformation Code represented as AST ★ (typechecked) structured representation Text generation by pretty-printing ★ separate code formatting from code generation Apply transformations after generation ★ aspect weaving ★ optimization
  • 21. Composing Abstract Syntax Trees grammar-to-signature : Grammar(ss, ps) -> Signature(ss, cds) where cds := <map(production-to-consdecl)> ps production-to-consdecl : Prod(symbols, sym, annos) -> ConsDecl(x, types, sort) where x := <annos-to-constructor> annos ; types := <filter(symbol-to-type)> symbols ; sort := sym annos-to-constructor : [Anno(Application("cons", [Constant(c)]))] -> constr where constr := <unescape; un-double-quote> c
  • 22. Composing Abstract Syntax Trees Advantages ★ syntax check through type system (if available) ★ automatic formatting ★ transformation after generation Disadvantages ★ no concrete syntax
  • 24. private $name; How does this scale? function getName(){ return $this->name; } function setName($val){ $this->name = $val; } generate-entity-field-code : Field(name, SimpleType(t)) -> [ InstanceVariable(Modifiers([Private()]),[Normal(Variable(Simple(name)))]) , FunctionDecl(get, [], [ Return(Some(ObjectAccess(Variable(Simple("this")), ObjectProperty(Simple(name)))))]) , FunctionDecl(set, [Param(Variable(Simple("val")))], [ Expr(Assign(ObjectAccess(Variable(Simple("this")), ObjectProperty(Simple(name))), Variable(Simple("val"))))]) ] with get := <camelcase>["get",name] with set := <camelcase>["set",name]
  • 26. Concrete Syntax Patterns generate-entity-field-code : FieldDefinition(str_name, type) -> php-member* |[ private $str_name ; function str_get() { return $this->str_name; } function str_set($val) { $this->str_name = $val; } ]| where <is-primitive-type> type with str_get := <camelcase>["get",str_name] with str_set := <camelcase>["set",str_name]
  • 27. Concrete Syntax Ingredients Quotation of code fragment ★ |[ .... ]| Disambiguation through tagging ★ php-member*|[ ... ]| Meta-variables ★ $this->str_name = $val
  • 28. Implementing Concrete Object Syntax Extending meta-language ★ Stratego + PHP Parsing meta-programs Normalizing to core syntax
  • 29. Extending the Meta-Language (1) module Stratego exports context-free syntax Int -> Term {cons("Int")} String -> Term {cons("Str")} Var -> Term {cons("Var")} Id "(" {Term ","}* ")" -> Term {cons("Op")} Term "->" Term -> Rule {cons("RuleNoCond")} Term "->" Term "where" Strategy -> Rule {cons("Rule")}
  • 30. Extending the Meta-Language (2) module StrategoPHP imports PHP exports context-free syntax "php-member" "|[" ClassMember "]|" -> Term{cons("ToMetaExpr")} "php-member*""|[" ClassMember* "]|" -> Term{cons("ToMetaExpr")} variables "expr_"[A-Za-z0-9_]+ -> Expr {prefer} "str_"[A-Za-z0-9_]+ -> String {prefer}
  • 31. Parsing Concrete Object Syntax Field(name, SimpleType(t)) -> php-member|[ private $str_name; ]| ==> parse Rule(Op("Field", [Var("name"), Op("SimpleType",[Var("t")])]), ToMetaExpr(InstanceVariable(Modifiers([Private()]), [Normal(Variable(Simple(meta-var("str_name"))))]))) ==> meta-explode Rule(Op("Field", [Var("name"), Op("SimpleType",[Var("t")])]), Op("InstanceVariable",[ Op("Modifiers", [Op("Cons",[Op("Private",[]),Op("Nil",[])])]), Op("Cons", [Op("Normal",[Op("Variable",[Op("Simple", [Var("str_name")])])]), Op("Nil",[])])])) ==> pretty-print Field(name, SimpleType(t)) -> InstanceVariable(Modifiers([Private()]),[Normal(Variable(Simple(str_name)))])
  • 32. Summary of Code Generation Techniques Print statements String interpolation ★ easy ★ template engine built-in String composition Abstract syntax ★ out of order evaluation ★ precise, transformation after generation Template engines Concrete object syntax ★ less quoting ★ precise ★ concrete
  • 33. Schedule Case 3 ★ Deadline extension: May 9 23:59 Case 4 ★ `take home exam’ ★ Questions about lectures 11 to 14 ★ Deadline: June 15 Design 2 ★ Syntax for your DSL Next ★ No lecture next week (May 11) ★ Lecture 11: code generation policies