SlideShare une entreprise Scribd logo
1  sur  22
Implementing Domain-Specific
     Languages for Java
   Sven Efftinge
                     Wilhelm Hasselbring
  Moritz Eysholdt
                     Robert von Massow
   Jan Köhnlein
                       Michael Hanus
Sebastian Zarnekow
Agenda

• What   is Xtext?

• Motivation

• Xbase Architecture

•A   Reusable language - What is the Interface?

• Real World Applications
grammar org.example.domainmodel.DomainModel
                          with org.eclipse.xtext.common.Terminals

                       generate domainmodel
                        "http://www.example.org/domainmodel/Domainmodel"

  example DSL
                       Domainmodel :
                                                                             
                         elements += Type*;                    


                                                       

                       Type:
                                                                                               
                         DataType |                        
datatype String                                                                             
                         Entity;                                                            

entity Person {                                                                                
                                                                           
  name : String
                       DataType:                                        
  givenName : String
                                                                                       
                         'datatype' name = ID;
  address : Address
}

                       Entity:
entity Address {
                         'entity' name = ID
  street : String
                           ('extends' superType = [Entity])? '{'
  zip : String
                                features += Feature*
  city : String
                           '}';
}

                       Feature:
                                                                             object
instance                 name = ID ':' type = [Type];
                                                                            grammar
Adaptability


• grammar    (reuse by choice)

• tool   chain (customize Xtext’s editor-generator)

• runtime   (subclass + exchange via dependency injection)
Motivation
                     How to add behavior to your DSL?


•   Old: Generation Gap Pattern       •   Better: Make DSL more
                                          Powerful
    •   generate abstract class
                                      •   designing expression languages
    •   handwrite concrete subclass       is hard
                                          •   expression grammar
                                          •   type system
                                          •   compiler
                                      •   expressions are very similar
                                          across DSLs
Xbase
 A reusable Expression Language
Grammar (Parser, Lexer)




                                                                                                                                         Operator Overloading
                                                                                                                    Lambda Expressions
                                                                                                Extension Methods
Linker




                                                       Control Structures
                                                                            Arithmetic, Logic
                                  Java Callout / -in
Type System
Interpreter / Compiler
Advanced Editor
Eclipse Workbench Integration
Debugger


              Parser      Serializer                                    Advanced Editor


Eclipse Platform                EMF                                                                                 Antlr
Xbase is fun
                                                              (this is Xbase embedded into Xtend)
class Movies {
	   	
	   @Test def void sumOfVotesOfTop2() {
	   	      val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b]
	   	      assertEquals(47_229, movies)
	   }
	
	   val movies =      new FileReader('data.csv').readLines.map[ line |
	   	      val segments = line.split(' ').iterator
	   	      return new Movie(
	   	      	   segments.next,
	   	      	   Double::parseDouble(segments.next),
	   	      	   Long::parseLong(segments.next),
	   	      )
	   ]
}



                                                       1. Read file into List<Movie>
@Data class Movie {
	   String title
	   double rating
	
}
    long numberOfVotes
                                                       2. Filter/Map/Reduce List

data.csv
A Few Good Men 7.6 68236
Empire Records 6.4 20780
"Rome" 9.2 21278
Witness for the Prosecution   8.4   20202
Xbase is fun
                                                              (this is Xbase embedded into Xtend)
class Movies {
	   	
	
	
    @Test def void sumOfVotesOfTop2() {
    	      val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b]
                                                                                                    Method
	
	
    	
    }
           assertEquals(47_229, movies)
                                                                                                      Body
	
	   val movies =      new FileReader('data.csv').readLines.map[ line |
	
	
    	
    	
           val segments = line.split(' ').iterator
           return new Movie(
                                                                                                         Field
	
	
    	
    	
           	
           	
               segments.next,
               Double::parseDouble(segments.next),
                                                                                                Initialization
	   	      	   Long::parseLong(segments.next),
	   	      )
	   ]
}

@Data class Movie {
	   String title
	   double rating
	   long numberOfVotes
}




data.csv
A Few Good Men 7.6 68236
Empire Records 6.4 20780
"Rome" 9.2 21278
Witness for the Prosecution   8.4   20202
Xbase is fun
                                                              (this is Xbase embedded into Xtend)
class Movies {
	   	
	   @Test def void sumOfVotesOfTop2() {
	   	      val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b]
	   	      assertEquals(47_229, movies)
	   }
	
	   val movies =      new FileReader('data.csv').readLines.map[ line |
	   	      val segments = line.split(' ').iterator
	   	      return new Movie(
	   	      	   segments.next,
	   	      	   Double::parseDouble(segments.next),
	   	      	   Long::parseLong(segments.next),
	   	      )
	   ]
}

@Data class Movie {
	   String title
	
	
    double rating
    long numberOfVotes
                                                                          Extension Methods
}




data.csv
A Few Good Men 7.6 68236
Empire Records 6.4 20780
"Rome" 9.2 21278
Witness for the Prosecution   8.4   20202
Xbase is fun
                                                              (this is Xbase embedded into Xtend)
class Movies {
	   	
	   @Test def void sumOfVotesOfTop2() {
	   	      val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b]
	   	      assertEquals(47_229, movies)
	   }
	
	   val movies =      new FileReader('data.csv').readLines.map[ line |
	   	      val segments = line.split(' ').iterator
	   	      return new Movie(
	   	      	   segments.next,
	   	      	   Double::parseDouble(segments.next),
	   	      	   Long::parseLong(segments.next),
	   	      )
	   ]
}

@Data class Movie {
	   String title
	
	
    double rating
    long numberOfVotes
                                                                         Lambda Expressions
}




data.csv
A Few Good Men 7.6 68236
Empire Records 6.4 20780
"Rome" 9.2 21278
Witness for the Prosecution   8.4   20202
Xbase is fun
                                                              (this is Xbase embedded into Xtend)
class Movies {
	   	
	   @Test def void sumOfVotesOfTop2() {
	   	      val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b]
	   	      assertEquals(47_229, movies)
	   }
	
	   val movies =      new FileReader('data.csv').readLines.map[ line |
	   	      val segments = line.split(' ').iterator
	   	      return new Movie(
	   	      	   segments.next,
	   	      	   Double::parseDouble(segments.next),
	   	      	   Long::parseLong(segments.next),
	   	      )
	   ]
}

@Data class Movie {
	   String title
	
	
    double rating
    long numberOfVotes
                                                                          Type Inference
}




data.csv
A Few Good Men 7.6 68236
Empire Records 6.4 20780
"Rome" 9.2 21278
Witness for the Prosecution   8.4   20202
REUSE A LANGUAGE??
   How to integrate it? What is the interface?

                     Grammar (Parser, Lexer)
                     Linker
                     Type System
MyLanguage           Interpreter / Compiler
                     Advanced Editor
                     Eclipse Workbench Integration
                     Debugger


    bad, since this is not an abstraction:
it doesn’t hide complexity from the client
REUSE A LANGUAGE??
   How to integrate it? What is the interface?
                grammar inheritance

                     Grammar (Parser, Lexer)
                                  Linker
                                  Type System
                       JvmModel
MyLanguage                        Interpreter / Compiler
                                  Advanced Editor
                                  Eclipse Integration
                                  Debugger

                JvmModelInferrer (M2M transformation)
Grammar Inheritance
                                    grammar org.eclipse.xtext.example.domainmodel.Domainmodel with org.eclipse.xtext.xbase.Xbase
                                    	
               MyLanguage Grammar


                                    generate domainmodel "http://www.xtext.org/example/Domainmodel"
                                    	
                                    DomainModel:
                                    	    elements+=AbstractElement*;
                                    	
My Language Grammar




                                    AbstractElement:
                                    	    PackageDeclaration | Entity | Import;
                                    	
                                    Import:
                                    	    'import' importedNamespace=QualifiedNameWithWildCard;
                                    	
                                    PackageDeclaration:
                                    	    'package' name=QualifiedName '{'
                                    	    	     elements+=AbstractElement*
                                    	    '}';
                                    	
                                    Entity:
                                    	    'entity' name=ValidID ('extends' superType=JvmParameterizedTypeReference)? '{'
                                    	    	     features+=Feature*
                                    	    '}';
                                    	
                                    Feature:
                                    	    Property | Operation;
                                    	
                                    Property:
                                    	    name=ValidID ':' type=JvmTypeReference;
                                    	
                                    Operation:
                                    	    'op' name=ValidID '(' (params+=FullJvmFormalParameter (',' params+=FullJvmFormalParameter)*)? ')' ':'
                                       type=JvmTypeReference body=XBlockExpression;
                                    	
                                    QualifiedNameWithWildCard :
                                    	    QualifiedName ('.' '*')?;
JvmModel Inference
                                       (M2M transformation with trace)



          MyLanguage Instance                          MyLanguage JvmModel (serialized)
                                                          package my.social.network;
package my.social.network {
                                                          (imports)

    import java.util.List                                 public class Person {
                                                            private String firstName;
                                                            private String lastName;
    entity Person {                                         private List<Person> friends;

      firstName : String                                      (getter, setter)
      lastName : String
                                                              public String getFullName() {
      friends : List<Person>                                    String _plus = (this.firstName + " ");
                                                                return (_plus + this.lastName);
        op getFullName() : String {                           }

          return firstName + " " + lastName                   public List<Person> getSortedFriends() {
        }                                                       final Function1<Person,String> _function =
                                                                  new Function1<Person,String>() {
                                                                     public String apply(final Person it) {
        op getSortedFriends() : List<Person> {                         String _fullName = it.getFullName();
                                                                       return _fullName;
          return friends.sortBy[fullName]                            }
        }                                                         };
                                                                return IterableExtensions.<Person, String>
    }                                                                       sortBy(this.friends, _function);
}                                                             }
                                                          }




    Syntax, inherited from Xbase                                     Xbase compiler output
JvmModel Inference

                    MyLanguage JvmModel (serialized)
                     package my.social.network;



Embedding Xbase
                     (imports)

                     public class Person {

  expressions          private String firstName;
                       private String lastName;
                       private List<Person> friends;

into Java methods        (getter, setter)


   gives them a          public String getFullName() {
                           String _plus = (this.firstName + " ");


    context!
                           return (_plus + this.lastName);
                         }

                         public List<Person> getSortedFriends() {
                           final Function1<Person,String> _function =
                             new Function1<Person,String>() {
                                public String apply(final Person it) {
                                  String _fullName = it.getFullName();
                                  return _fullName;
                                }
                             };
                           return IterableExtensions.<Person, String>
                                       sortBy(this.friends, _function);
                         }
                     }
the last slide was really important,
  let us go back one more time.
JvmModel Inference

                    MyLanguage JvmModel (serialized)
                     package my.social.network;



Embedding Xbase
                     (imports)

                     public class Person {

  expressions          private String firstName;
                       private String lastName;
                       private List<Person> friends;

into Java methods        (getter, setter)


   gives them a          public String getFullName() {
                           String _plus = (this.firstName + " ");


    context!
                           return (_plus + this.lastName);
                         }

                         public List<Person> getSortedFriends() {
                           final Function1<Person,String> _function =
                             new Function1<Person,String>() {
                                public String apply(final Person it) {
                                  String _fullName = it.getFullName();
                                  return _fullName;
                                }
                             };
                           return IterableExtensions.<Person, String>
                                       sortBy(this.friends, _function);
                         }
                     }
JvmModel Inference

                                    MyLanguage JvmModel (serialized)
                                     package my.social.network;

                                     (imports)

                                     public class Person {
                                       private String firstName;

         context!                      private String lastName;
                                       private List<Person> friends;

                                         (getter, setter)



         ...for linking                  public String getFullName() {
                                           String _plus = (this.firstName + " ");
                                           return (_plus + this.lastName);
      (as implemented by scoping)        }



•names of method parameters              public List<Person> getSortedFriends() {
                                           final Function1<Person,String> _function =

•names of member fields                       new Function1<Person,String>() {
                                                public String apply(final Person it) {

•names of member methods                          String _fullName = it.getFullName();
                                                  return _fullName;

•names of visible types                      };
                                                }

                                           return IterableExtensions.<Person, String>
                                                       sortBy(this.friends, _function);
                                         }
                                     }
JvmModel Inference

                                    MyLanguage JvmModel (serialized)
                                     package my.social.network;

                                     (imports)


         context!                    public class Person {
                                       private String firstName;
                                       private String lastName;
                                       private List<Person> friends;


  ...for the Type System                 (getter, setter)

                                         public String getFullName() {
                                           String _plus = (this.firstName + " ");
                                           return (_plus + this.lastName);

• a method’s return type is the          }


  expected type of an expression         public List<Person> getSortedFriends() {
                                           final Function1<Person,String> _function =

• fields, variables and parameters
                                             new Function1<Person,String>() {
                                                public String apply(final Person it) {
                                                  String _fullName = it.getFullName();
  have types                                      return _fullName;
                                                }
• generated java classes are                 };
                                           return IterableExtensions.<Person, String>
  available as new types                               sortBy(this.friends, _function);
                                         }
                                     }
JvmModel Inference

                                      MyLanguage JvmModel (serialized)
                                       package my.social.network;

                                       (imports)

                                       public class Person {
                                         private String firstName;
                                         private String lastName;


          context!
                                         private List<Person> friends;

                                           (getter, setter)

                                           public String getFullName() {
                                             String _plus = (this.firstName + " ");

    ...for the Compiler                    }
                                             return (_plus + this.lastName);



                                           public List<Person> getSortedFriends() {
                                             final Function1<Person,String> _function =

• actually, the serialized JvmModel
                                               new Function1<Person,String>() {
                                                  public String apply(final Person it) {
                                                    String _fullName = it.getFullName();
  is the compiler output :)                         return _fullName;
                                                  }
                                               };
                                             return IterableExtensions.<Person, String>
                                                         sortBy(this.friends, _function);
                                           }
                                       }
Real World Applications
•   Learning By Example: 7 Languages For The JVM - http://www.eclipse.org/Xtext/7languages.html
     • Build Language
     • DSL for Guice
     • Template Language
     • Scripting Language
     • DSL for MongoDB
     • HTTP routing language
     • Little Tortoise


•   Xtend - Java-like GPL that also supports functional programming and has powerful type inference
    • http://www.eclipse.org/xtend/


•   DESAGN - textually define 3D models of cutting tools (physical tools)
    • http://www.eclipsecon.org/europe2012/sessions/desagn-xtext-cutting-edge


•   openHAB - open Home Automation Bus - Program the behavior of your house!
     • http://code.google.com/p/openhab/


•   spray - Generate graphical Eclipse editors for the Graphiti framework
     • http://eclipselabs.org/p/spray/


•   Jnario - Executable Specifications for Java (Behavior Driven Development, BDD)
     • http://jnario.org

Contenu connexe

Tendances

Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence APIIlio Catallo
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...GeeksLab Odessa
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 

Tendances (20)

Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Java Generics
Java GenericsJava Generics
Java Generics
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 
Java Generics
Java GenericsJava Generics
Java Generics
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 

Similaire à Xbase - Implementing Domain-Specific Languages for Java

Expressive Design (in 20 minutes)
Expressive Design (in 20 minutes)Expressive Design (in 20 minutes)
Expressive Design (in 20 minutes)Phil Calçado
 
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
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmerselliando dias
 
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 DefinitionEelco Visser
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Xsl Tand X Path Quick Reference
Xsl Tand X Path Quick ReferenceXsl Tand X Path Quick Reference
Xsl Tand X Path Quick ReferenceLiquidHub
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Chapter 6 data types
Chapter 6 data types Chapter 6 data types
Chapter 6 data types Arafat X
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 

Similaire à Xbase - Implementing Domain-Specific Languages for Java (20)

Expressive Design (in 20 minutes)
Expressive Design (in 20 minutes)Expressive Design (in 20 minutes)
Expressive Design (in 20 minutes)
 
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)
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmers
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
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
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Xsl Tand X Path Quick Reference
Xsl Tand X Path Quick ReferenceXsl Tand X Path Quick Reference
Xsl Tand X Path Quick Reference
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Just entity framework
Just entity frameworkJust entity framework
Just entity framework
 
Chapter 6 data types
Chapter 6 data types Chapter 6 data types
Chapter 6 data types
 
Net framework
Net frameworkNet framework
Net framework
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 

Plus de meysholdt

Lightweight Xtext Editors as SWT Widgets
Lightweight Xtext Editors as SWT WidgetsLightweight Xtext Editors as SWT Widgets
Lightweight Xtext Editors as SWT Widgetsmeysholdt
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtextmeysholdt
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Fastermeysholdt
 
Executable specifications for xtext
Executable specifications for xtextExecutable specifications for xtext
Executable specifications for xtextmeysholdt
 
Test-Driven Development of Xtext DSLs
Test-Driven Development  of Xtext DSLsTest-Driven Development  of Xtext DSLs
Test-Driven Development of Xtext DSLsmeysholdt
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodiesmeysholdt
 
Converging Textual and Graphical Editors
Converging Textual  and Graphical EditorsConverging Textual  and Graphical Editors
Converging Textual and Graphical Editorsmeysholdt
 

Plus de meysholdt (7)

Lightweight Xtext Editors as SWT Widgets
Lightweight Xtext Editors as SWT WidgetsLightweight Xtext Editors as SWT Widgets
Lightweight Xtext Editors as SWT Widgets
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtext
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Faster
 
Executable specifications for xtext
Executable specifications for xtextExecutable specifications for xtext
Executable specifications for xtext
 
Test-Driven Development of Xtext DSLs
Test-Driven Development  of Xtext DSLsTest-Driven Development  of Xtext DSLs
Test-Driven Development of Xtext DSLs
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodies
 
Converging Textual and Graphical Editors
Converging Textual  and Graphical EditorsConverging Textual  and Graphical Editors
Converging Textual and Graphical Editors
 

Dernier

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Dernier (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Xbase - Implementing Domain-Specific Languages for Java

  • 1. Implementing Domain-Specific Languages for Java Sven Efftinge Wilhelm Hasselbring Moritz Eysholdt Robert von Massow Jan Köhnlein Michael Hanus Sebastian Zarnekow
  • 2. Agenda • What is Xtext? • Motivation • Xbase Architecture •A Reusable language - What is the Interface? • Real World Applications
  • 3. grammar org.example.domainmodel.DomainModel with org.eclipse.xtext.common.Terminals generate domainmodel "http://www.example.org/domainmodel/Domainmodel" example DSL Domainmodel :    elements += Type*;    Type:  DataType |   datatype String  Entity;  entity Person {    name : String DataType:  givenName : String  'datatype' name = ID; address : Address } Entity: entity Address { 'entity' name = ID street : String ('extends' superType = [Entity])? '{' zip : String features += Feature* city : String '}'; } Feature: object instance name = ID ':' type = [Type]; grammar
  • 4. Adaptability • grammar (reuse by choice) • tool chain (customize Xtext’s editor-generator) • runtime (subclass + exchange via dependency injection)
  • 5. Motivation How to add behavior to your DSL? • Old: Generation Gap Pattern • Better: Make DSL more Powerful • generate abstract class • designing expression languages • handwrite concrete subclass is hard • expression grammar • type system • compiler • expressions are very similar across DSLs
  • 6. Xbase A reusable Expression Language Grammar (Parser, Lexer) Operator Overloading Lambda Expressions Extension Methods Linker Control Structures Arithmetic, Logic Java Callout / -in Type System Interpreter / Compiler Advanced Editor Eclipse Workbench Integration Debugger Parser Serializer Advanced Editor Eclipse Platform EMF Antlr
  • 7. Xbase is fun (this is Xbase embedded into Xtend) class Movies { @Test def void sumOfVotesOfTop2() { val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b] assertEquals(47_229, movies) } val movies = new FileReader('data.csv').readLines.map[ line | val segments = line.split(' ').iterator return new Movie( segments.next, Double::parseDouble(segments.next), Long::parseLong(segments.next), ) ] } 1. Read file into List<Movie> @Data class Movie { String title double rating } long numberOfVotes 2. Filter/Map/Reduce List data.csv A Few Good Men 7.6 68236 Empire Records 6.4 20780 "Rome" 9.2 21278 Witness for the Prosecution 8.4 20202
  • 8. Xbase is fun (this is Xbase embedded into Xtend) class Movies { @Test def void sumOfVotesOfTop2() { val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b] Method } assertEquals(47_229, movies) Body val movies = new FileReader('data.csv').readLines.map[ line | val segments = line.split(' ').iterator return new Movie( Field segments.next, Double::parseDouble(segments.next), Initialization Long::parseLong(segments.next), ) ] } @Data class Movie { String title double rating long numberOfVotes } data.csv A Few Good Men 7.6 68236 Empire Records 6.4 20780 "Rome" 9.2 21278 Witness for the Prosecution 8.4 20202
  • 9. Xbase is fun (this is Xbase embedded into Xtend) class Movies { @Test def void sumOfVotesOfTop2() { val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b] assertEquals(47_229, movies) } val movies = new FileReader('data.csv').readLines.map[ line | val segments = line.split(' ').iterator return new Movie( segments.next, Double::parseDouble(segments.next), Long::parseLong(segments.next), ) ] } @Data class Movie { String title double rating long numberOfVotes Extension Methods } data.csv A Few Good Men 7.6 68236 Empire Records 6.4 20780 "Rome" 9.2 21278 Witness for the Prosecution 8.4 20202
  • 10. Xbase is fun (this is Xbase embedded into Xtend) class Movies { @Test def void sumOfVotesOfTop2() { val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b] assertEquals(47_229, movies) } val movies = new FileReader('data.csv').readLines.map[ line | val segments = line.split(' ').iterator return new Movie( segments.next, Double::parseDouble(segments.next), Long::parseLong(segments.next), ) ] } @Data class Movie { String title double rating long numberOfVotes Lambda Expressions } data.csv A Few Good Men 7.6 68236 Empire Records 6.4 20780 "Rome" 9.2 21278 Witness for the Prosecution 8.4 20202
  • 11. Xbase is fun (this is Xbase embedded into Xtend) class Movies { @Test def void sumOfVotesOfTop2() { val movies = movies.sortBy[-rating].take(2).map[numberOfVotes].reduce[a, b| a + b] assertEquals(47_229, movies) } val movies = new FileReader('data.csv').readLines.map[ line | val segments = line.split(' ').iterator return new Movie( segments.next, Double::parseDouble(segments.next), Long::parseLong(segments.next), ) ] } @Data class Movie { String title double rating long numberOfVotes Type Inference } data.csv A Few Good Men 7.6 68236 Empire Records 6.4 20780 "Rome" 9.2 21278 Witness for the Prosecution 8.4 20202
  • 12. REUSE A LANGUAGE?? How to integrate it? What is the interface? Grammar (Parser, Lexer) Linker Type System MyLanguage Interpreter / Compiler Advanced Editor Eclipse Workbench Integration Debugger bad, since this is not an abstraction: it doesn’t hide complexity from the client
  • 13. REUSE A LANGUAGE?? How to integrate it? What is the interface? grammar inheritance Grammar (Parser, Lexer) Linker Type System JvmModel MyLanguage Interpreter / Compiler Advanced Editor Eclipse Integration Debugger JvmModelInferrer (M2M transformation)
  • 14. Grammar Inheritance grammar org.eclipse.xtext.example.domainmodel.Domainmodel with org.eclipse.xtext.xbase.Xbase MyLanguage Grammar generate domainmodel "http://www.xtext.org/example/Domainmodel" DomainModel: elements+=AbstractElement*; My Language Grammar AbstractElement: PackageDeclaration | Entity | Import; Import: 'import' importedNamespace=QualifiedNameWithWildCard; PackageDeclaration: 'package' name=QualifiedName '{' elements+=AbstractElement* '}'; Entity: 'entity' name=ValidID ('extends' superType=JvmParameterizedTypeReference)? '{' features+=Feature* '}'; Feature: Property | Operation; Property: name=ValidID ':' type=JvmTypeReference; Operation: 'op' name=ValidID '(' (params+=FullJvmFormalParameter (',' params+=FullJvmFormalParameter)*)? ')' ':' type=JvmTypeReference body=XBlockExpression; QualifiedNameWithWildCard : QualifiedName ('.' '*')?;
  • 15. JvmModel Inference (M2M transformation with trace) MyLanguage Instance MyLanguage JvmModel (serialized) package my.social.network; package my.social.network { (imports) import java.util.List public class Person { private String firstName; private String lastName; entity Person { private List<Person> friends; firstName : String (getter, setter) lastName : String public String getFullName() { friends : List<Person> String _plus = (this.firstName + " "); return (_plus + this.lastName); op getFullName() : String { } return firstName + " " + lastName public List<Person> getSortedFriends() { } final Function1<Person,String> _function = new Function1<Person,String>() { public String apply(final Person it) { op getSortedFriends() : List<Person> { String _fullName = it.getFullName(); return _fullName; return friends.sortBy[fullName] } } }; return IterableExtensions.<Person, String> } sortBy(this.friends, _function); } } } Syntax, inherited from Xbase Xbase compiler output
  • 16. JvmModel Inference MyLanguage JvmModel (serialized) package my.social.network; Embedding Xbase (imports) public class Person { expressions private String firstName; private String lastName; private List<Person> friends; into Java methods (getter, setter) gives them a public String getFullName() { String _plus = (this.firstName + " "); context! return (_plus + this.lastName); } public List<Person> getSortedFriends() { final Function1<Person,String> _function = new Function1<Person,String>() { public String apply(final Person it) { String _fullName = it.getFullName(); return _fullName; } }; return IterableExtensions.<Person, String> sortBy(this.friends, _function); } }
  • 17. the last slide was really important, let us go back one more time.
  • 18. JvmModel Inference MyLanguage JvmModel (serialized) package my.social.network; Embedding Xbase (imports) public class Person { expressions private String firstName; private String lastName; private List<Person> friends; into Java methods (getter, setter) gives them a public String getFullName() { String _plus = (this.firstName + " "); context! return (_plus + this.lastName); } public List<Person> getSortedFriends() { final Function1<Person,String> _function = new Function1<Person,String>() { public String apply(final Person it) { String _fullName = it.getFullName(); return _fullName; } }; return IterableExtensions.<Person, String> sortBy(this.friends, _function); } }
  • 19. JvmModel Inference MyLanguage JvmModel (serialized) package my.social.network; (imports) public class Person { private String firstName; context! private String lastName; private List<Person> friends; (getter, setter) ...for linking public String getFullName() { String _plus = (this.firstName + " "); return (_plus + this.lastName); (as implemented by scoping) } •names of method parameters public List<Person> getSortedFriends() { final Function1<Person,String> _function = •names of member fields new Function1<Person,String>() { public String apply(final Person it) { •names of member methods String _fullName = it.getFullName(); return _fullName; •names of visible types }; } return IterableExtensions.<Person, String> sortBy(this.friends, _function); } }
  • 20. JvmModel Inference MyLanguage JvmModel (serialized) package my.social.network; (imports) context! public class Person { private String firstName; private String lastName; private List<Person> friends; ...for the Type System (getter, setter) public String getFullName() { String _plus = (this.firstName + " "); return (_plus + this.lastName); • a method’s return type is the } expected type of an expression public List<Person> getSortedFriends() { final Function1<Person,String> _function = • fields, variables and parameters new Function1<Person,String>() { public String apply(final Person it) { String _fullName = it.getFullName(); have types return _fullName; } • generated java classes are }; return IterableExtensions.<Person, String> available as new types sortBy(this.friends, _function); } }
  • 21. JvmModel Inference MyLanguage JvmModel (serialized) package my.social.network; (imports) public class Person { private String firstName; private String lastName; context! private List<Person> friends; (getter, setter) public String getFullName() { String _plus = (this.firstName + " "); ...for the Compiler } return (_plus + this.lastName); public List<Person> getSortedFriends() { final Function1<Person,String> _function = • actually, the serialized JvmModel new Function1<Person,String>() { public String apply(final Person it) { String _fullName = it.getFullName(); is the compiler output :) return _fullName; } }; return IterableExtensions.<Person, String> sortBy(this.friends, _function); } }
  • 22. Real World Applications • Learning By Example: 7 Languages For The JVM - http://www.eclipse.org/Xtext/7languages.html • Build Language • DSL for Guice • Template Language • Scripting Language • DSL for MongoDB • HTTP routing language • Little Tortoise • Xtend - Java-like GPL that also supports functional programming and has powerful type inference • http://www.eclipse.org/xtend/ • DESAGN - textually define 3D models of cutting tools (physical tools) • http://www.eclipsecon.org/europe2012/sessions/desagn-xtext-cutting-edge • openHAB - open Home Automation Bus - Program the behavior of your house! • http://code.google.com/p/openhab/ • spray - Generate graphical Eclipse editors for the Graphiti framework • http://eclipselabs.org/p/spray/ • Jnario - Executable Specifications for Java (Behavior Driven Development, BDD) • http://jnario.org

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n