SlideShare a Scribd company logo
1 of 35
Download to read offline
Mixing Sour ce and Bytecode
    A Case for Compilation by Normalization




OOPSLA'08, Nashville, Tennessee

Lennart Kats, TU Delft
Martin Bravenboer, UMass
Eelco Visser, TU Delft
October 21, 2008



Software Engineering Research Group
Language
Extensions
DSLs and Language Extensions

Domain-specific         void browse() {
                          List<Book> books =
• Database queries
                           <| SELECT *
• Regular expressions          FROM books
• XML processing               WHERE price < 100.00
                             |>;
• Matrices
• Complex numbers           …
• ...
                            for (int i = 0; i < books.size(); i++)
                               books.get(i).title =~ s/^The //;
                        }
DSLs and Language Extensions

Domain-specific         General-purpose
• Database queries      • AOP
• Regular expressions   • Traits
• XML processing        • Enums
• Matrices              • Iterators
• Complex numbers       • Case classes
• ...                   • Properties/accessors
                        • ...
Example: The Foreach Statement
                                            Program B: Foo.java
Program A: Foo.mylang                    public class Foo {
                                           void bar(BarList list) {
public class Foo {                           Iterator it = list.iterator();
  void bar(BarList list) {                   while (it.hasNext()) {
    foreach (Bar b in list) {                   Bar b = it.next();
       b.print();                               b.print();
    }                                        }
                            Code generator
  }                                        }
}                                        }




                                                          javac
                                                Program C: Foo.class

                                                (bytecode)
The Preprocessor
   Extended
   language
                             + loosely coupled
                             + small, modular extension
 Preprocessor
                             + no need to know compiler
                               internals
 Host language               – no parser
                             – semantic analysis, errors?
                 INTERFACE
  Compiler


  Bytecode
The Front-end Extensible Compiler
   Extended                  + front-end reuse
   language
                             – tied to the front-end
   Front-end     Extension     internals


 Host language


                 INTERFACE
  Compiler
                                Polyglot           MetaBorg
  Bytecode
                                           ableJ
                                                       OJ
Traits: Composable Units of Behavior
                                      [Schärli, Ducasse, Nierstrasz, Black 2003]



public trait TDrawing {
  void draw() {
    …
  }

    require Vertices getVertices();                    public class Shape {
}                                                        void draw() { … }
                                            Traits
                                                           Vertices getVertices() { … }
public class Shape with TDrawing {                     }
  …

    Vertices getVertices() { … }
}
Foo.java            TBar.java
Traits
 •   Simple idea




                                          Traits
 •   Most libraries are
     distributed as compiled
     code

 → Why not do this for traits?    FooBar.java




                                          javac
                Not extensible


                                  FooBar.class
The
Fully
Extensible
Compiler?
Extended
language


 Parsing


 Name
Parsing
Frontend
                       The
analysis
                       Fully
  Type
 Parsing               Extensible
 analysis
                       Compiler?
  Code
 Parsing
generation
             + reuse everything
Backend
Optimize     + access to back-end
             –– tied to all compiler internals
 Parsing
  Emit       – complexity
             – performance trade-offs
Bytecode
The
          White
          Box
          Model?



–– tied to all compiler internals
– complexity
– performance trade-offs
The Normalizing Compiler
     Extended
     language
                                + simple interface
     Extension
     processor                  + access to back-end
                                ++ not tied to
  Source+bytecode                  compiler internals

                    INTERFACE
Normalizing compiler


     Bytecode
   core language
Foo.java            TBar.class




                               Traits
                        FooBar.java




Traits, Revisited      FooBar.class
Java, and Bytecode, and Backticks,
Oh, My!
class FooBar {
                        Java (Foo.java)
    void hello1() {
      System.out.println(“Hello Java world”);
    }

                                          Bytecode (TBar.class)
    `hello2 (void) [
      getstatic java.lang.System.out : java.io.PrintStream;
      ldc “Hello bytecode world”;
      invokevirtual java.io.PrintStream.println(java.lang.String : void);
    ]

}
Java, and Bytecode, and Backticks:
Fine-grained Mixing
class FooBar {

    void hello3() {
      System.out.println(`ldc "Hello mixed world");
    }

                                                                Typechecker
    `hello4 (void) [
      getstatic System.out : java.io.PrintStream;                             P
      push `"Hello ” + “Java".concat("bytecode world");                      SP
      invokevirtual java.io.PrintStream.println (java.lang.String : void);
    ]

}
Typical Applications

              Class-method / Statement / Expression level

Traits                  X

Partial/open classes    X

Iterator generators              X

Finite State Automata            X

Expression-based                          X
extensions
Example: Finite State Automata (DFAs)

Grammar




          States and transitions
                                    Code
Finite State Automata: Generated Java code
    while (true) {
     switch (state) {
         case INSIDE_QUOTE:
           switch (nextToken()) {
               case '"':
                 consume();
                 state = OUTSIDE_QUOTE; // end quote found!
                 break;
               …
               case EOF:
                  return;
               default:
                  consume();
             }
             break;
         case OUTSIDE_QUOTE:
           switch (c) {            + simple Java code
               …                   – performance trade-off
           }
           break;
       }
Finite State Automata: Inline Bytecode
    InsideQuote:
       switch (nextToken()) {
         case '"':
           consume();
           `goto OutsideQuote;
         case EOF:
           return;
         default:
           consume();
           `goto InsideQuote;
         }
       }
    OutsideQuote:
       switch (c) {           + performance
         …                    + low-level when
                                           necessary
       }
                           + minimal changes
                           + maintainable
Method-body Extensions

• Operators: x as T, x ?? y, ...

• Embedded (external) DSLs:
  Database queries, XML, ...

• Closures             No
                          r   m
                               ali
                                     ze

                                          Lower-level
                                             code
Stratego Normalization Rules

desugar-foreach:
  |[ foreach (t x in e) stm ]|
   
  |[ Iterator x_iterator = e.iterator();
     while (x_iterator.hasNext()) {
        t x = x_iterator.next();
        stm;
     }
  ]|
  with x_iterator := <newname> “iterator”
Normalizing ??

String property = readProperty(“x”) ?? “default”;
System.out.println(property);


// In basic Java:

String temp = readProperty(“x”);
if (temp == null) temp = “default”;
String property = temp;
System.out.println(property);
                              Context-sensitive
                               transformation
Normalizing ??

“But placing statements in front of the
 assimilated expressions is easy, isn’t it?”


Requires syntactic knowledge:
   • for, while, return, throw, …
   • other expressions
   • other extensions
Normalizing ??

“But placing statements in front of the
 assimilated expressions is easy, isn’t it?
 … Right?”

Also requires semantic knowledge:

Iterator<String> it = ...;



for (String e = e0; it.hasNext(); e = it.next() ?? “default”) {
  ...
}
Normalizing ??

“But placing statements in front of the
 assimilated expressions is easy, isn’t it?
 … Right?”

Also requires semantic knowledge:

Iterator<String> it = ...;

Integer temp = ...;
for (String e = e0; it.hasNext(); e = temp) {
   ...
}
Normalizing '??' !!

String property = readProperty(“x”) ?? “default”;
System.out.println(property);
Normalizing '??' !! - with Inline Bytecode

String property = `[
   push `readProperty(“x”);
   dup;
   store temp;
   ifnull else;
      push `e2;
      goto end;
   else:
      load temp;
   end:
                       S
];
System.out.println(property);
Normalizing '??' !! - with Inline Bytecode

String property = `[
   `String temp = readProperty(“x”);
   `if (temp == null) temp = “default”;
   push `temp                             S
];
System.out.println(property);
Normalizing '??' !! - with an EBlock

String property = {|
   String temp = readProperty(“x”);
   if (temp == null) temp = “default”;
| temp
|};
System.out.println(property);
desugar-coalescing:
 |[ e1 ?? e2 ]| 
 |[{|
      String x_temp = e1;
      if (x_temp == null) x_temp = e2;
   | x_temp
   |}
 ]|
 with x_temp := <newname> “temp”


                      '??' in a Normalization Rule
desugar-coalescing:
 |[ e1 ?? e2 ]| 
 |[{|
      String x_temp = e1;
      if (x_temp == null) x_temp = e2;
   | x_temp
   |}                Run-time:
                      Exception in thread "main"
 ]|                     java.lang.NullPointerException
                        …
 with x_temp :=   <newname> “temp”
                        at Generated.getVertices(Generated.java:10)


                              Position Information In
                                     Generated Code
desugar-coalescing:
 |[ e1 ?? e2 ]| 
 |[ trace (e1 ?? e2 @ <File>:<Line>:<Column>) {{|
      String x_temp = e1;
      if (x_temp == null) x_temp = e2;
   | x_temp
   |}}
 ]|
 with x_temp := <newname> “temp”

 Run-time:
        Maintaining Position Information With
 Exception in thread "main"
   java.lang.NullPointerException
   …                           Source Tracing
   at Shape.getVertices(Shape.java:10)
Reflection
             Class-method / Statement / Expression level

Traits                  X

Partial/open classes    X

Iterator generators              X

Finite State Automata            X

Expression-based                          X
extensions

Aspect weaving          X        X        X
Concluding Remarks
 •   Extension effort must be proportional to the benefits
 •   Black Boxes vs. White Boxes
 •   Don't throw away your primitives
 •   Normalization rules



Mixing Source and Bytecode. A Case for Compilation by Normalization.
Lennart C. L. Kats, Martin Bravenboer, and Eelco Visser. In OOPSLA'08.
http://www.program­transformation.org/Stratego/TheDryadCompiler
http://www.strategoxt.org

More Related Content

What's hot

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
elliando dias
 
Write Your Own JVM Compiler
Write Your Own JVM CompilerWrite Your Own JVM Compiler
Write Your Own JVM Compiler
Erin Dees
 
F# Type Provider for R Statistical Platform
F# Type Provider for R Statistical PlatformF# Type Provider for R Statistical Platform
F# Type Provider for R Statistical Platform
Howard Mansell
 
Pré Descobrimento Do Brasil
Pré Descobrimento Do BrasilPré Descobrimento Do Brasil
Pré Descobrimento Do Brasil
ecsette
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
Muhammad Abdullah
 

What's hot (20)

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax Definition
 
Strategies to improve embedded Linux application performance beyond ordinary ...
Strategies to improve embedded Linux application performance beyond ordinary ...Strategies to improve embedded Linux application performance beyond ordinary ...
Strategies to improve embedded Linux application performance beyond ordinary ...
 
Write Your Own JVM Compiler
Write Your Own JVM CompilerWrite Your Own JVM Compiler
Write Your Own JVM Compiler
 
Thnad's Revenge
Thnad's RevengeThnad's Revenge
Thnad's Revenge
 
Your Own Metric System
Your Own Metric SystemYour Own Metric System
Your Own Metric System
 
Playfulness at Work
Playfulness at WorkPlayfulness at Work
Playfulness at Work
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
 
F# Type Provider for R Statistical Platform
F# Type Provider for R Statistical PlatformF# Type Provider for R Statistical Platform
F# Type Provider for R Statistical Platform
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Pré Descobrimento Do Brasil
Pré Descobrimento Do BrasilPré Descobrimento Do Brasil
Pré Descobrimento Do Brasil
 
Ebay News 2000 10 19 Earnings
Ebay News 2000 10 19 EarningsEbay News 2000 10 19 Earnings
Ebay News 2000 10 19 Earnings
 
Ebay News 2001 4 19 Earnings
Ebay News 2001 4 19 EarningsEbay News 2001 4 19 Earnings
Ebay News 2001 4 19 Earnings
 
P4 P Update January 2009
P4 P Update January 2009P4 P Update January 2009
P4 P Update January 2009
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Unit VI
Unit VI Unit VI
Unit VI
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 

Viewers also liked

Logical expression and logical operators
Logical expression and logical operatorsLogical expression and logical operators
Logical expression and logical operators
Suneel Dogra
 
Ch4 Boolean Algebra And Logic Simplication1
Ch4 Boolean Algebra And Logic Simplication1Ch4 Boolean Algebra And Logic Simplication1
Ch4 Boolean Algebra And Logic Simplication1
Qundeel
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
Gagan Deep
 

Viewers also liked (16)

Digital logic mohammed salim ch4
Digital logic mohammed salim ch4Digital logic mohammed salim ch4
Digital logic mohammed salim ch4
 
Logical expression and logical operators
Logical expression and logical operatorsLogical expression and logical operators
Logical expression and logical operators
 
Boolean Algebra and Logic Smiplification
Boolean Algebra and Logic SmiplificationBoolean Algebra and Logic Smiplification
Boolean Algebra and Logic Smiplification
 
gujju
gujjugujju
gujju
 
presentation
presentationpresentation
presentation
 
Introduction to digital logic
Introduction to digital logicIntroduction to digital logic
Introduction to digital logic
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
Normalization 1
Normalization 1Normalization 1
Normalization 1
 
Logical and Conditional Operator In C language
Logical and Conditional Operator In C languageLogical and Conditional Operator In C language
Logical and Conditional Operator In C language
 
K Map Simplification
K Map SimplificationK Map Simplification
K Map Simplification
 
BOOLEAN ALGEBRA
BOOLEAN ALGEBRA BOOLEAN ALGEBRA
BOOLEAN ALGEBRA
 
Ch4 Boolean Algebra And Logic Simplication1
Ch4 Boolean Algebra And Logic Simplication1Ch4 Boolean Algebra And Logic Simplication1
Ch4 Boolean Algebra And Logic Simplication1
 
Boolean algebra
Boolean algebraBoolean algebra
Boolean algebra
 
simplification of boolean algebra
simplification of boolean algebrasimplification of boolean algebra
simplification of boolean algebra
 
CBSE XII Boolean Algebra
CBSE XII Boolean AlgebraCBSE XII Boolean Algebra
CBSE XII Boolean Algebra
 
LinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-PresentedLinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-Presented
 

Similar to Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2008)

14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
Tech_MX
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
bwullems
 

Similar to Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2008) (20)

PIL - A Platform Independent Language
PIL - A Platform Independent LanguagePIL - A Platform Independent Language
PIL - A Platform Independent Language
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash Cracking
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
 
Dart
DartDart
Dart
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Introduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IOIntroduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IO
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
The craft of meta programming on JVM
The craft of meta programming on JVMThe craft of meta programming on JVM
The craft of meta programming on JVM
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
Metaprogramming in julia
Metaprogramming in juliaMetaprogramming in julia
Metaprogramming in julia
 
Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 
core java
core javacore java
core java
 

More from lennartkats

Language Engineering in the Cloud
Language Engineering in the CloudLanguage Engineering in the Cloud
Language Engineering in the Cloud
lennartkats
 
Test-driven language development
Test-driven language developmentTest-driven language development
Test-driven language development
lennartkats
 
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
lennartkats
 
Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...
Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...
Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...
lennartkats
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 

More from lennartkats (10)

Docker at Cloud9 IDE
Docker at Cloud9 IDEDocker at Cloud9 IDE
Docker at Cloud9 IDE
 
Remix Your Language Tooling (JSConf.eu 2012)
Remix Your Language Tooling (JSConf.eu 2012)Remix Your Language Tooling (JSConf.eu 2012)
Remix Your Language Tooling (JSConf.eu 2012)
 
Language Engineering in the Cloud
Language Engineering in the CloudLanguage Engineering in the Cloud
Language Engineering in the Cloud
 
Test-driven language development
Test-driven language developmentTest-driven language development
Test-driven language development
 
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
 
The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)
 
Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...
Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...
Providing Rapid Feedback in Generated Modular Language Environments (OOPSLA 2...
 
Decorated Attribute Grammars (CC 2009)
Decorated Attribute Grammars (CC 2009)Decorated Attribute Grammars (CC 2009)
Decorated Attribute Grammars (CC 2009)
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2008)

  • 1. Mixing Sour ce and Bytecode A Case for Compilation by Normalization OOPSLA'08, Nashville, Tennessee Lennart Kats, TU Delft Martin Bravenboer, UMass Eelco Visser, TU Delft October 21, 2008 Software Engineering Research Group
  • 3. DSLs and Language Extensions Domain-specific void browse() { List<Book> books = • Database queries <| SELECT * • Regular expressions FROM books • XML processing WHERE price < 100.00 |>; • Matrices • Complex numbers … • ... for (int i = 0; i < books.size(); i++) books.get(i).title =~ s/^The //; }
  • 4. DSLs and Language Extensions Domain-specific General-purpose • Database queries • AOP • Regular expressions • Traits • XML processing • Enums • Matrices • Iterators • Complex numbers • Case classes • ... • Properties/accessors • ...
  • 5. Example: The Foreach Statement Program B: Foo.java Program A: Foo.mylang public class Foo { void bar(BarList list) { public class Foo { Iterator it = list.iterator(); void bar(BarList list) { while (it.hasNext()) { foreach (Bar b in list) { Bar b = it.next(); b.print(); b.print(); } } Code generator } } } } javac Program C: Foo.class (bytecode)
  • 6. The Preprocessor Extended language + loosely coupled + small, modular extension Preprocessor + no need to know compiler internals Host language – no parser – semantic analysis, errors? INTERFACE Compiler Bytecode
  • 7. The Front-end Extensible Compiler Extended + front-end reuse language – tied to the front-end Front-end Extension internals Host language INTERFACE Compiler Polyglot MetaBorg Bytecode ableJ OJ
  • 8. Traits: Composable Units of Behavior [Schärli, Ducasse, Nierstrasz, Black 2003] public trait TDrawing { void draw() { … } require Vertices getVertices(); public class Shape { } void draw() { … } Traits Vertices getVertices() { … } public class Shape with TDrawing { } … Vertices getVertices() { … } }
  • 9. Foo.java TBar.java Traits • Simple idea Traits • Most libraries are distributed as compiled code → Why not do this for traits? FooBar.java javac Not extensible FooBar.class
  • 11. Extended language Parsing Name Parsing Frontend The analysis Fully Type Parsing Extensible analysis Compiler? Code Parsing generation + reuse everything Backend Optimize + access to back-end –– tied to all compiler internals Parsing Emit – complexity – performance trade-offs Bytecode
  • 12. The White Box Model? –– tied to all compiler internals – complexity – performance trade-offs
  • 13. The Normalizing Compiler Extended language + simple interface Extension processor + access to back-end ++ not tied to Source+bytecode compiler internals INTERFACE Normalizing compiler Bytecode core language
  • 14. Foo.java TBar.class Traits FooBar.java Traits, Revisited FooBar.class
  • 15. Java, and Bytecode, and Backticks, Oh, My! class FooBar { Java (Foo.java) void hello1() { System.out.println(“Hello Java world”); } Bytecode (TBar.class) `hello2 (void) [ getstatic java.lang.System.out : java.io.PrintStream; ldc “Hello bytecode world”; invokevirtual java.io.PrintStream.println(java.lang.String : void); ] }
  • 16. Java, and Bytecode, and Backticks: Fine-grained Mixing class FooBar { void hello3() { System.out.println(`ldc "Hello mixed world"); } Typechecker `hello4 (void) [ getstatic System.out : java.io.PrintStream; P push `"Hello ” + “Java".concat("bytecode world"); SP invokevirtual java.io.PrintStream.println (java.lang.String : void); ] }
  • 17. Typical Applications Class-method / Statement / Expression level Traits X Partial/open classes X Iterator generators X Finite State Automata X Expression-based X extensions
  • 18. Example: Finite State Automata (DFAs) Grammar States and transitions Code
  • 19. Finite State Automata: Generated Java code while (true) { switch (state) { case INSIDE_QUOTE: switch (nextToken()) { case '"': consume(); state = OUTSIDE_QUOTE; // end quote found! break; … case EOF: return; default: consume(); } break; case OUTSIDE_QUOTE: switch (c) { + simple Java code … – performance trade-off } break; }
  • 20. Finite State Automata: Inline Bytecode InsideQuote: switch (nextToken()) { case '"': consume(); `goto OutsideQuote; case EOF: return; default: consume(); `goto InsideQuote; } } OutsideQuote: switch (c) { + performance … + low-level when necessary } + minimal changes + maintainable
  • 21. Method-body Extensions • Operators: x as T, x ?? y, ... • Embedded (external) DSLs: Database queries, XML, ... • Closures No r m ali ze Lower-level code
  • 22. Stratego Normalization Rules desugar-foreach: |[ foreach (t x in e) stm ]|  |[ Iterator x_iterator = e.iterator(); while (x_iterator.hasNext()) { t x = x_iterator.next(); stm; } ]| with x_iterator := <newname> “iterator”
  • 23. Normalizing ?? String property = readProperty(“x”) ?? “default”; System.out.println(property); // In basic Java: String temp = readProperty(“x”); if (temp == null) temp = “default”; String property = temp; System.out.println(property); Context-sensitive transformation
  • 24. Normalizing ?? “But placing statements in front of the assimilated expressions is easy, isn’t it?” Requires syntactic knowledge: • for, while, return, throw, … • other expressions • other extensions
  • 25. Normalizing ?? “But placing statements in front of the assimilated expressions is easy, isn’t it? … Right?” Also requires semantic knowledge: Iterator<String> it = ...; for (String e = e0; it.hasNext(); e = it.next() ?? “default”) { ... }
  • 26. Normalizing ?? “But placing statements in front of the assimilated expressions is easy, isn’t it? … Right?” Also requires semantic knowledge: Iterator<String> it = ...; Integer temp = ...; for (String e = e0; it.hasNext(); e = temp) { ... }
  • 27. Normalizing '??' !! String property = readProperty(“x”) ?? “default”; System.out.println(property);
  • 28. Normalizing '??' !! - with Inline Bytecode String property = `[ push `readProperty(“x”); dup; store temp; ifnull else; push `e2; goto end; else: load temp; end: S ]; System.out.println(property);
  • 29. Normalizing '??' !! - with Inline Bytecode String property = `[ `String temp = readProperty(“x”); `if (temp == null) temp = “default”; push `temp S ]; System.out.println(property);
  • 30. Normalizing '??' !! - with an EBlock String property = {| String temp = readProperty(“x”); if (temp == null) temp = “default”; | temp |}; System.out.println(property);
  • 31. desugar-coalescing: |[ e1 ?? e2 ]|  |[{| String x_temp = e1; if (x_temp == null) x_temp = e2; | x_temp |} ]| with x_temp := <newname> “temp” '??' in a Normalization Rule
  • 32. desugar-coalescing: |[ e1 ?? e2 ]|  |[{| String x_temp = e1; if (x_temp == null) x_temp = e2; | x_temp |} Run-time: Exception in thread "main" ]| java.lang.NullPointerException … with x_temp := <newname> “temp” at Generated.getVertices(Generated.java:10) Position Information In Generated Code
  • 33. desugar-coalescing: |[ e1 ?? e2 ]|  |[ trace (e1 ?? e2 @ <File>:<Line>:<Column>) {{| String x_temp = e1; if (x_temp == null) x_temp = e2; | x_temp |}} ]| with x_temp := <newname> “temp” Run-time: Maintaining Position Information With Exception in thread "main" java.lang.NullPointerException … Source Tracing at Shape.getVertices(Shape.java:10)
  • 34. Reflection Class-method / Statement / Expression level Traits X Partial/open classes X Iterator generators X Finite State Automata X Expression-based X extensions Aspect weaving X X X
  • 35. Concluding Remarks • Extension effort must be proportional to the benefits • Black Boxes vs. White Boxes • Don't throw away your primitives • Normalization rules Mixing Source and Bytecode. A Case for Compilation by Normalization. Lennart C. L. Kats, Martin Bravenboer, and Eelco Visser. In OOPSLA'08. http://www.program­transformation.org/Stratego/TheDryadCompiler http://www.strategoxt.org