The Role Of Template Engines in Code Generation Terence Parr University of San Francisco

Slides:



Advertisements
Similar presentations
JavaCUP JavaCUP (Construct Useful Parser) is a parser generator
Advertisements

CPSC 388 – Compiler Design and Construction
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Semantics Static semantics Dynamic semantics attribute grammars
ICE1341 Programming Languages Spring 2005 Lecture #6 Lecture #6 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
ANTLR in SSP Xingzhong Xu Hong Man Aug Outline ANTLR Abstract Syntax Tree Code Equivalence (Code Re-hosting) Future Work.
Java Server Pages (JSP)
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
1 JavaCUP JavaCUP (Construct Useful Parser) is a parser generator Produce a parser written in java, itself is also written in Java; There are many parser.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Fall Semantics Juan Carlos Guzmán CS 3123 Programming Languages Concepts Southern Polytechnic State University.
CS 330 Programming Languages 09 / 13 / 2007 Instructor: Michael Eckmann.
CS 330 Programming Languages 09 / 18 / 2007 Instructor: Michael Eckmann.
Slide 1 Chapter 2-b Syntax, Semantics. Slide 2 Syntax, Semantics - Definition The syntax of a programming language is the form of its expressions, statements.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS 330 Programming Languages 09 / 16 / 2008 Instructor: Michael Eckmann.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
CH1 – A 1 st Program Using C#. Program Set of instructions which tell a computer what to do. Machine Language Basic language computers use to control.
StringTemplate Terence Parr University of San Francisco
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
A First Program Using C#
XSLT for Data Manipulation By: April Fleming. What We Will Cover The What, Why, When, and How of XSLT What tools you will need to get started A sample.
Getting Started with ANTLR Chapter 1. Domain Specific Languages DSLs are high-level languages designed for specific tasks DSLs include data formats, configuration.
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
Winter 2007SEG2101 Chapter 71 Chapter 7 Introduction to Languages and Compiler.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
JSTL, XML and XSLT An introduction to JSP Standard Tag Library and XML/XSLT transformation for Web layout.
CS Describing Syntax CS 3360 Spring 2012 Sec Adapted from Addison Wesley’s lecture notes (Copyright © 2004 Pearson Addison Wesley)
Introduction to JavaServer Pages. 2 JSP and Servlet Limitations of servlet  It’s inaccessible to non-programmers JSP is a complement to servlet  focuses.
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
ISBN Chapter 3 Describing Syntax and Semantics.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
CS 363 Comparative Programming Languages Semantics.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Enforcing Strict Model- View Separation in Template Engines Terence Parr University of San Francisco
Introduction to Parsing
CPS 506 Comparative Programming Languages Syntax Specification.
ISBN Chapter 3 Describing Semantics.
Chapter 3 Part II Describing Syntax and Semantics.
Theory of Programming Languages Introduction. What is a Programming Language? John von Neumann (1940’s) –Stored program concept –CPU actions determined.
The Evolution of the StringTemplate Engine Presented to the UC Berkeley Harmonia group 15 December 2004 Terence Parr University of San Francisco
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
Agenda Comments Identifiers Keywords Syntax and Symentics Indentation Variables Datatype Operator.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
1 Programming Languages (CS 550) Lecture 2 Summary Mini Language Interpreter Jeremy R. Johnson.
CMSC 330: Organization of Programming Languages Operational Semantics.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
Prof. Necula CS 164 Lecture 171 Operational Semantics of Cool ICOM 4029 Lecture 10.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
Rendering XML Documents ©NIITeXtensible Markup Language/Lesson 5/Slide 1 of 46 Objectives In this session, you will learn to: * Define rendering * Identify.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
Chapter 3 – Describing Syntax CSCE 343. Syntax vs. Semantics Syntax: The form or structure of the expressions, statements, and program units. Semantics:
Chapter 3 – Describing Syntax
CS 3304 Comparative Languages
Representation, Syntax, Paradigms, Types
Syntax Analysis Sections :.
Mini Language Interpreter Programming Languages (CS 550)
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
CSE401 Introduction to Compiler Construction
Representation, Syntax, Paradigms, Types
Representation, Syntax, Paradigms, Types
Representation, Syntax, Paradigms, Types
Chapter 3 Describing Syntax and Semantics.
Presentation transcript:

The Role Of Template Engines in Code Generation Terence Parr University of San Francisco

Introduction Car aerodynamics mostly trumps style today Car aerodynamics mostly trumps style today Similarly, the nature of generating text should dominate design decisions: use an output grammar Similarly, the nature of generating text should dominate design decisions: use an output grammar Don’t have output grammars, we have programs with print statements; template engines arose to encourage separation of logic/display. Don’t have output grammars, we have programs with print statements; template engines arose to encourage separation of logic/display. Enforcing strict separation also leads to similar grammar-like mechanism Enforcing strict separation also leads to similar grammar-like mechanism Conclusion: if you’re generating text, you should be using something akin to StringTemplate Conclusion: if you’re generating text, you should be using something akin to StringTemplate

Outline Define and motivate model-view separation; give enforcement rules, show equivalence to CFGs Define and motivate model-view separation; give enforcement rules, show equivalence to CFGs Describe StringTemplate, provide example Describe StringTemplate, provide example Relate experience building ANTLR 3.0 code generator with StringTemplate Relate experience building ANTLR 3.0 code generator with StringTemplate

HTML Generation out.println(" "); out.println(" Servlet test "); String name = request.getParameter("name"); out.println("Hello, "+name+"."); out.println(" "); JSP test Hello,. Servlet: JSP:

Example Entanglements $if(user==“parrt” && machine=“yoda”)$ $if(user==“parrt” && machine=“yoda”)$ $price*.90$, $bloodPressure>130$ $price*.90$, $bloodPressure>130$ $a=db.query(“select subject from ”)$ $a=db.query(“select subject from ”)$ $model.pageRef(getURL())$ $model.pageRef(getURL())$ $ClassLoader.loadClass(somethingEvil)$ $ClassLoader.loadClass(somethingEvil)$ $names[ID]$ $names[ID]$ st.setAttribute(“color”, “Red”); st.setAttribute(“color”, “Red”);

Motivation For Separation Encapsulation Encapsulation Clarity Clarity Division of labor Division of labor Component reuse Component reuse Single point-of-change Single point-of-change Maintenance Maintenance Interchangeable views, retargeting Interchangeable views, retargeting Security Security

Existing Engines Problem: engines don’t enforce separation, they only encourage separation (Murphy, IBM keybrd, etc…) Problem: engines don’t enforce separation, they only encourage separation (Murphy, IBM keybrd, etc…) Reason: engine builders and users fear that enforcement implies fatal weakness Reason: engine builders and users fear that enforcement implies fatal weakness Result: developers exploit loopholes, encoding logic in templates, thus, entangling model/view Result: developers exploit loopholes, encoding logic in templates, thus, entangling model/view We can enforce separation without emasculating the power of a template engine We can enforce separation without emasculating the power of a template engine empirical evidence and theoretical support empirical evidence and theoretical support

Template Definition Unrestricted template: t 0 e 0 …t i e i t i+1 …t n e m where t i is a literal and e i is unrestricted computationally and syntactically Unrestricted template: t 0 e 0 …t i e i t i+1 …t n e m where t i is a literal and e i is unrestricted computationally and syntactically Notes: Notes: unrestricted templates do not enforce separation unrestricted templates do not enforce separation XSLT is not a template engine XSLT is not a template engine

Rules of Separation 1. the view cannot modify the model 2. cannot perform computations upon dependent data values 3. cannot compare dependent data values 4. cannot make type assumptions 5. data from model cannot contain display, layout information

Restricted Templates Restrict template to operate on read-only data values, attributes (single or multi-valued), to prevent side-effects Restrict template to operate on read-only data values, attributes (single or multi-valued), to prevent side-effects e i are attribute or template references e i are attribute or template references Even restricted templates can generate the context-free languages Even restricted templates can generate the context-free languages By allowing conditional inclusion (predicates), reaches into context-sensitive languages By allowing conditional inclusion (predicates), reaches into context-sensitive languages XML DTDs are essentially CFGs, therefore, restricted template can generate syntax of any XML document XML DTDs are essentially CFGs, therefore, restricted template can generate syntax of any XML document

Equivalence to CFGs Attributes = terminals, templates = rules Attributes = terminals, templates = rules Can show grammar’s derivation tree for any sentence maps to a nested template tree structure Can show grammar’s derivation tree for any sentence maps to a nested template tree structure prog : decl func ; decl : type ID ; func : type ID “()” “{“ body “}” … prog ::= “ ” decl ::= “ ;” func : << () { } >> … GrammarTemplate

StringTemplate Evolved from simple “document with holes” while building jGuru.com, after dumping JSP Evolved from simple “document with holes” while building jGuru.com, after dumping JSP Side-effect free expressions Side-effect free expressions No order of evaluation No order of evaluation Recursion (recall output structures are nested) Recursion (recall output structures are nested) Dynamic scoping Dynamic scoping Lazy-evaluation Lazy-evaluation Template inheritance/polymorphism Template inheritance/polymorphism Simple enough for nonprogrammers Simple enough for nonprogrammers Strictly enforces separation of model/view Strictly enforces separation of model/view No assignments, loops, … No assignments, loops, …

Canonical Operations Attribute reference: Attribute reference: Template references (possibly recursive): Template references (possibly recursive): Apply template to multi-valued attribute: or ;}> Apply template to multi-valued attribute: or ;}> Conditional include: extends Conditional include: extends

Template Groups Set of mutually-referential templates with formal arguments Set of mutually-referential templates with formal arguments group javaTemplates; method(type,name,args,body) ::= << public ( ) { } >> assign(lhs,expr) ::= “ = ;” if(expr,stat) ::= “if ( ) ” call(name,args) ::= “ ( );” …

Template Polymorphism Output: “ y=1; ” not “ x=1; ” because template instance’s group is subGroup Output: “ y=1; ” not “ x=1; ” because template instance’s group is subGroup sub.setSuperGroup(sup); StringTemplate st = sub.getInstanceOf(”slist"); System.out.println(st.toString()); Late bind group sup; slist() ::= “ ” assign() ::= “x=1;” group sub; assign() ::= “y=1;” Group determines symbol resolution

Example: Dump Java Class Expected output: Expected output: class Dump { public int i; public java.lang.String name; public int[] data; public void main(class java.lang.String[] arg1); public void foo(int arg1, float[] arg2); public class java.lang.String bar(); }

Dump Java Class Templates group Java; class(name,fields,methods) ::= << class { } >> field() ::= "public ;" method() ::= << public ( arg }; separator=", ">); >> type(t) ::= << [] >>

Dump Java Class Code public class Dump { public int i; public String name; public int[] data; public static void main(String[] args) throws IOException { StringTemplateGroup group = new StringTemplateGroup(new FileReader("Java.stg"), AngleBracketTemplateLexer.class); Class c = Dump.class; Field[] fields = c.getFields(); Method[] methods = c.getDeclaredMethods(); StringTemplate classST = group.getInstanceOf("class"); classST.setAttribute("name", c.getName()); classST.setAttribute("fields", fields); classST.setAttribute("methods", methods); System.out.println(classST); } public void foo(int x, float[] y) {;} public String bar() {return "";} }

Dump XML Instead group XML; class(name,fields,methods) ::= << $name$ $fields:field()$ $methods:method()$ >> field() ::= << $type(t=it.type)$ $it.name$ >> … Dump int i …

Experience with ANTLR 3.0 Tree walker (controller) collects data from AST (model), pushes data into templates (view) Tree walker (controller) collects data from AST (model), pushes data into templates (view) Decouples order of computation from order of display (this is huge) Decouples order of computation from order of display (this is huge) Enforced separation guarantees easy retargeting, no code duplication, … Enforced separation guarantees easy retargeting, no code duplication, … no code in template no code in template no output strings in code generator no output strings in code generator Previous code generator hopelessly entangled Previous code generator hopelessly entangled Group file format (output grammar) is great! “Executable documentation” Group file format (output grammar) is great! “Executable documentation”

Sample ANTLR 3.0 Template parser(name, tokens, rules, DFAs) ::= << class extends Parser { <tokens: {public static final int = ;} > public (TokenStream input) { super(input); } } >>

Summary The nature of text generation and the enforcement of model-view separation dominate tool design-decisions: The nature of text generation and the enforcement of model-view separation dominate tool design-decisions: tools should resemble output grammars tools should resemble output grammars StringTemplate is a simple template engine that evolved while building dynamic sites. It is proving exceptionally well suited to code generation tasks including ANTLR 3.0 StringTemplate is a simple template engine that evolved while building dynamic sites. It is proving exceptionally well suited to code generation tasks including ANTLR 3.0 open-source Java, BSD license (also a C# port) open-source Java, BSD license (also a C# port)