SlideShare a Scribd company logo
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

What's hot

Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
jessitron
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
Bassam Abd El Hameed
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
Ryan Knight
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
C#
C#C#
C#
Joni
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
Peter Maas
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Peter Maas
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
jessitron
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
Yeshwanth Kumar
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 

What's hot (20)

Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
C#
C#C#
C#
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Scala functions
Scala functionsScala functions
Scala functions
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 

Viewers also liked

Model-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive TransformationModel-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive Transformation
Eelco Visser
 
Building DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language WorkbenchBuilding DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language Workbench
Eelco Visser
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
Eelco Visser
 
Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1
Eelco Visser
 
Type analysis
Type analysisType analysis
Type analysis
Eelco Visser
 
Model-Driven Software Development - Web Abstractions 2
Model-Driven Software Development - Web Abstractions 2Model-Driven Software Development - Web Abstractions 2
Model-Driven Software Development - Web Abstractions 2
Eelco Visser
 
Composing Domain-Specific Languages
Composing Domain-Specific LanguagesComposing Domain-Specific Languages
Composing Domain-Specific Languages
Eelco Visser
 
Static Analysis
Static AnalysisStatic Analysis
Static Analysis
Eelco Visser
 
Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow Analysis
Eelco Visser
 
From Muddling to Modelling
From Muddling to ModellingFrom Muddling to Modelling
From Muddling to Modelling
Jorn Bettin
 
Domain Analysis & Data Modeling
Domain Analysis & Data ModelingDomain Analysis & Data Modeling
Domain Analysis & Data Modeling
Eelco Visser
 
Dynamic Semantics
Dynamic SemanticsDynamic Semantics
Dynamic Semantics
Eelco Visser
 
Software languages
Software languagesSoftware languages
Software languages
Eelco Visser
 
Programming languages
Programming languagesProgramming languages
Programming languages
Eelco Visser
 

Viewers also liked (14)

Model-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive TransformationModel-Driven Software Development - Context-Sensitive Transformation
Model-Driven Software Development - Context-Sensitive Transformation
 
Building DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language WorkbenchBuilding DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language Workbench
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1Model-Driven Software Development - Web Abstractions 1
Model-Driven Software Development - Web Abstractions 1
 
Type analysis
Type analysisType analysis
Type analysis
 
Model-Driven Software Development - Web Abstractions 2
Model-Driven Software Development - Web Abstractions 2Model-Driven Software Development - Web Abstractions 2
Model-Driven Software Development - Web Abstractions 2
 
Composing Domain-Specific Languages
Composing Domain-Specific LanguagesComposing Domain-Specific Languages
Composing Domain-Specific Languages
 
Static Analysis
Static AnalysisStatic Analysis
Static Analysis
 
Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow Analysis
 
From Muddling to Modelling
From Muddling to ModellingFrom Muddling to Modelling
From Muddling to Modelling
 
Domain Analysis & Data Modeling
Domain Analysis & Data ModelingDomain Analysis & Data Modeling
Domain Analysis & Data Modeling
 
Dynamic Semantics
Dynamic SemanticsDynamic Semantics
Dynamic Semantics
 
Software languages
Software languagesSoftware languages
Software languages
 
Programming languages
Programming languagesProgramming languages
Programming languages
 

Similar to Code Generation

Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and Verification
KapilRaghunandanTrip
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
Jerry Yang
 
Linq intro
Linq introLinq intro
Linq intro
Bình Trọng Án
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Data Con LA
 
Language processor implementation using python
Language processor implementation using pythonLanguage processor implementation using python
Language processor implementation using python
Viktor Pyskunov
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
Denis Voituron
 
Powershell Tech Ed2009
Powershell Tech Ed2009Powershell Tech Ed2009
Powershell Tech Ed2009
rsnarayanan
 
Developing a new Epsilon EMC driver
Developing a new Epsilon EMC driverDeveloping a new Epsilon EMC driver
Developing a new Epsilon EMC driver
Horacio Hoyos Rodríguez
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
Sql Patterns
Sql PatternsSql Patterns
Sql Patterns
phanleson
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi
 
DataMapper
DataMapperDataMapper
DataMapper
Yehuda Katz
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
Bình Trọng Án
 
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo FinochiettiRoslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
.NET Conf UY
 
Roslyn: el futuro de C#
Roslyn: el futuro de C#Roslyn: el futuro de C#
Roslyn: el futuro de C#
Rodolfo Finochietti
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
tcaesvk
 
ASP.NET
ASP.NETASP.NET
ASP.NET
chirag patil
 

Similar to Code Generation (20)

Slickdemo
SlickdemoSlickdemo
Slickdemo
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and Verification
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
 
Linq intro
Linq introLinq intro
Linq intro
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
 
Language processor implementation using python
Language processor implementation using pythonLanguage processor implementation using python
Language processor implementation using python
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
Powershell Tech Ed2009
Powershell Tech Ed2009Powershell Tech Ed2009
Powershell Tech Ed2009
 
Developing a new Epsilon EMC driver
Developing a new Epsilon EMC driverDeveloping a new Epsilon EMC driver
Developing a new Epsilon EMC driver
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
Sql Patterns
Sql PatternsSql Patterns
Sql Patterns
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
DataMapper
DataMapperDataMapper
DataMapper
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo FinochiettiRoslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
 
Roslyn: el futuro de C#
Roslyn: el futuro de C#Roslyn: el futuro de C#
Roslyn: el futuro de C#
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#
 
ASP.NET
ASP.NETASP.NET
ASP.NET
 

More from Eelco Visser

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
Eelco Visser
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
Eelco Visser
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
Eelco Visser
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
Eelco Visser
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
Eelco Visser
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation Rules
Eelco Visser
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
Eelco Visser
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Eelco Visser
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Eelco Visser
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
Eelco Visser
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
Eelco Visser
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code Generation
Eelco Visser
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
Eelco Visser
 
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksCompiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone Frameworks
Eelco Visser
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
Eelco Visser
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
Eelco Visser
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type Constraints
Eelco Visser
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
Eelco Visser
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Eelco Visser
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Eelco Visser
 

More from Eelco Visser (20)

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation Rules
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code Generation
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
 
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksCompiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone Frameworks
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type Constraints
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
 

Recently uploaded

9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
christinelarrosa
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
Vadym Kazulkin
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
Enterprise Knowledge
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 

Recently uploaded (20)

9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 

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