SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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 mindSander Mak (@Sander_Mak)
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-petejessitron
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 
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 LambdasRyan 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 coreWeb Zhao
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
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 ProgrammingRichardWarburton
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Peter Maas
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaPeter Maas
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 
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 InterfacesGanesh Samarthyam
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With ScalaTomer Gabel
 

Tendances (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
 

En vedette

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 TransformationEelco 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 WorkbenchEelco Visser
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesEelco 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 1Eelco 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 2Eelco Visser
 
Composing Domain-Specific Languages
Composing Domain-Specific LanguagesComposing Domain-Specific Languages
Composing Domain-Specific LanguagesEelco Visser
 
From Muddling to Modelling
From Muddling to ModellingFrom Muddling to Modelling
From Muddling to ModellingJorn Bettin
 
Domain Analysis & Data Modeling
Domain Analysis & Data ModelingDomain Analysis & Data Modeling
Domain Analysis & Data ModelingEelco Visser
 
Software languages
Software languagesSoftware languages
Software languagesEelco Visser
 
Programming languages
Programming languagesProgramming languages
Programming languagesEelco Visser
 

En vedette (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
 

Similaire à Code Generation

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 VerificationKapilRaghunandanTrip
 
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 SQLJerry Yang
 
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 pythonViktor Pyskunov
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful weddingStéphane Wirtel
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScriptDenis Voituron
 
Powershell Tech Ed2009
Powershell Tech Ed2009Powershell Tech Ed2009
Powershell Tech Ed2009rsnarayanan
 
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 JavascriptKamil Toman
 
Sql Patterns
Sql PatternsSql Patterns
Sql Patternsphanleson
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonSiddhi
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET componentsBì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
 
NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#NDC 2011, C++ 프로그래머를 위한 C#
NDC 2011, C++ 프로그래머를 위한 C#tcaesvk
 

Similaire à 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
 

Plus de 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 RewritingEelco Visser
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesEelco Visser
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingEelco Visser
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionEelco 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 RulesEelco Visser
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with StatixEelco 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 ConstructionEelco 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 ManagementEelco Visser
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersEelco Visser
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationEelco Visser
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesEelco Visser
 
Compiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksCompiler Construction | Lecture 11 | Monotone Frameworks
Compiler Construction | Lecture 11 | Monotone FrameworksEelco 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 AnalysisEelco Visser
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingEelco 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 AnalysisEelco 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 RewritingEelco Visser
 

Plus de 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
 

Dernier

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 

Dernier (20)

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 

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