StringTemplate Terence Parr University of San Francisco

Slides:



Advertisements
Similar presentations
Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Advertisements

CPSC 388 – Compiler Design and Construction
Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
ANTLR in SSP Xingzhong Xu Hong Man Aug Outline ANTLR Abstract Syntax Tree Code Equivalence (Code Re-hosting) Future Work.
The Role Of Template Engines in Code Generation Terence Parr University of San Francisco
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.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.1 Introduction to Java.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
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.
DT228/3 Web Development JSP: Directives and Scripting elements.
Guide To UNIX Using Linux Third Edition
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
ANTLR.
ANTLR Andrew Pangborn & Zach Busser. ANTLR in a Nutshell ANother Tool for Language Recognition generates lexers generates parsers (and parse trees)‏ Java-based,
Attribute Grammars They extend context-free grammars to give parameters to non-terminals, have rules to combine attributes Attributes can have any type,
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
WEB DESIGN AND PROGRAMMING Introduction to Javascript.
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.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Java Server Pages (JSPs) Robert Thornton.
{ Graphite Grigory Arashkovich, Anuj Khanna, Anirban Gangopadhyay, Michael D’Egidio, Laura Willson.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
CSC204 – Programming I Lecture 4 August 28, 2002.
7-1 7 Contextual analysis  Aspects of contextual analysis  Scope checking  Type checking  Case study: Fun contextual analyser  Representing types.
1 Top Down Parsing. CS 412/413 Spring 2008Introduction to Compilers2 Outline Top-down parsing SLL(1) grammars Transforming a grammar into SLL(1) form.
Using CookCC.  Use *.l and *.y files.  Proprietary file format  Poor IDE support  Do not work well for some languages.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Chapter 1 Section 1.1 Introduction to Java Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CS453 LectureIntroduction1 CS453 Compiler Construction Instructor:Wim Bohm Computer Science Building 470 TA: tba
COP4020 Programming Languages Names, Scopes, and Bindings Prof. Xin Yuan.
Enforcing Strict Model- View Separation in Template Engines Terence Parr University of San Francisco
CPS 506 Comparative Programming Languages Syntax Specification.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
The Evolution of the StringTemplate Engine Presented to the UC Berkeley Harmonia group 15 December 2004 Terence Parr University of San Francisco
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
By Mr. Muhammad Pervez Akhtar
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
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.
A High Flying Overview CS139 – Fall 2006 How far we have come.
 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,
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Computer Science A 1. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated editor,
Chapter 7 User-Defined Methods.
CS 3304 Comparative Languages
2.5 Another Java Application: Adding Integers
Java Programming: From Problem Analysis to Program Design, 4e
Compiler Design 22. ANTLR AST Traversal (AST as Input, AST Grammars)
Mini Language Interpreter Programming Languages (CS 550)
Interface.
Chapter 2: Basic Elements of Java
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
CSE401 Introduction to Compiler Construction
Syntax-Directed Translation
ANTLR v3 Overview (for ANTLR v2 users)
6.001 SICP Variations on a Scheme
Presentation transcript:

StringTemplate Terence Parr University of San Francisco

Outline What is StringTemplate What is StringTemplate Operations Operations Semantics Semantics Example Java/XML Generation Example Java/XML Generation ANTLR 3.0 template ANTLR 3.0 template

What is StringTemplate? Template engine designed with Tom Burns (CEO, jGuru.com) while building commercial sites over many years in response to JSP Template engine designed with Tom Burns (CEO, jGuru.com) while building commercial sites over many years in response to JSP small: 170k uncompressed binary (w/o test rig) small: 170k uncompressed binary (w/o test rig) Evolved from simple “document with holes” into a functional language capable of generating large class of languages Evolved from simple “document with holes” into a functional language capable of generating large class of languages Well suited to generative programming as well as dynamic page generation; being used in new ANTLR parser generator for code generation Well suited to generative programming as well as dynamic page generation; being used in new ANTLR parser generator for code generation Distinguishing characteristic: strictly enforces separation of model and view Distinguishing characteristic: strictly enforces separation of model and view

Argument for StringTemplate 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

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 Name: Guest Conditional include: extends Name: Guest

Semantics Side-effect free expressions Side-effect free expressions No “state” No “state” No defined order of execution No defined order of execution Lazy evaluation (crucial!) Lazy evaluation (crucial!) Dynamically scoped; values inherited Dynamically scoped; values inherited Template inheritance: group to subgroup Template inheritance: group to subgroup Recursive template instantiation Recursive template instantiation

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) ::= “ ( );” …

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 …

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

ANTLR 3.0 Error Templates Internationalization: use a template group for each locale; load appropriate templates Internationalization: use a template group for each locale; load appropriate templates RULE_REDEFINITION(file,line,col,arg) ::= " rule redefinition” UNDEFINED_RULE_REF(file,line,col,arg) ::= " reference to undefined rule: ” loc() ::= " : : : " inherits file, line, col attributes from enclosing template

Language Translation MVC (parser + “unparser”) MVC (parser + “unparser”) model -- input stream and/or ASTs model -- input stream and/or ASTs view -- templates view -- templates controller -- parser controller -- parser Controller extracts data from model, provides to view without worrying about details of output structure Controller extracts data from model, provides to view without worrying about details of output structure Maps abstract input concept to output concept like assignment to assignment. Maps abstract input concept to output concept like assignment to assignment. Abstract concepts represented by one or more rules in parser grammar and one or more templates in template file Abstract concepts represented by one or more rules in parser grammar and one or more templates in template file

Translation grammar+ST variable returns [StringTemplate code=null] {StringTemplate t=null,d=null;} : t=type d=declarator SEMI { if ( currentFunctionName==null ) { code = template("globalVariable"); } else { code = template("variable"); } code.setAttribute("type", t); code.setAttribute("name", d); } ; declarator returns [StringTemplate code=null] : id:ID {code=text(id.getText());} ;

Translation Templates Java variable(type,name)::=" ;” globalVariable ::= variable Java variable(type,name)::=" ;” globalVariable ::= variable Python variable(type,name) ::= " ” globalVariable ::= variable Python variable(type,name) ::= " ” globalVariable ::= variable Bytecodes variable(type,name) ::= ".var is " globalVariable(type,name) ::= ".field " Bytecodes variable(type,name) ::= ".var is " globalVariable(type,name) ::= ".field "

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; python coming) Open-source Java, BSD license (also a C# port; python coming) Links Links