1 1 Strategic Programming in Java Pierre-Etienne Moreau Antoine Reilles Stratego User Day, December, 1 st, 2006.

Slides:



Advertisements
Similar presentations
Parsing 4 Dr William Harrison Fall 2008
Advertisements

JavaCUP JavaCUP (Construct Useful Parser) is a parser generator
UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1.
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Final and Abstract Classes
Classes and Objects in Java
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
12 Copyright © 2005, Oracle. All rights reserved. Structuring Code Using Abstract Classes and Interfaces.
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
Types and Programming Languages Lecture 7 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Formal Models of Computation Part II The Logic Model
Data Structures ADT List
Tom Schrijvers K.U.Leuven, Belgium with Manuel Chakravarty, Martin Sulzmann and Simon Peyton Jones.
Modern Programming Languages, 2nd ed.
1 Lecture 16: Tables and OOP. 2 Tables -- get and put.
Semantic Analysis and Symbol Tables
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Faculty of Sciences and Social Sciences HOPE Structured Problem Solving An Introduction Stewart Blakeway
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Type Inference David Walker COS 320. Criticisms of Typed Languages Types overly constrain functions & data polymorphism makes typed constructs useful.
Bernd Fischer School of Electronics and Computer Science University of Southampton Requirements for an Algebraic-Logic Simplifier.
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Computing Fundamentals 2 Introduction to CafeOBJ Lecturer: Patrick Browne Lecture Room: K408 Lab Room: A308 Based on work by: Nakamura Masaki, João Pascoal.
CS18000: Problem Solving and Object-Oriented Programming.
Abstraction and Modular Reasoning for the Verification of Software Corina Pasareanu NASA Ames Research Center.
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.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
Chapter 1: Computer Systems
Programming with Java. Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the.
The Java Programming Language
Outline Java program structure Basic program elements
Guide To UNIX Using Linux Third Edition
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
CPSC Compiler Tutorial 3 Parser. Parsing The syntax of most programming languages can be specified by a Context-free Grammar (CGF) Parsing: Given.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
Imperative Programming
Notes for Chapter 12 Logic Programming The AI War Basic Concepts of Logic Programming Prolog Review questions.
Java Language and SW Dev’t
The Java Programming Language
COMP Parsing 2 of 4 Lecture 22. How do we write programs to do this? The process of getting from the input string to the parse tree consists of.
CSE Winter 2008 Introduction to Program Verification January 31 proofs through simplification.
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
CS412/413 Introduction to Compilers Radu Rugina Lecture 13 : Static Semantics 18 Feb 02.
Static Techniques for V&V. Hierarchy of V&V techniques Static Analysis V&V Dynamic Techniques Model Checking Simulation Symbolic Execution Testing Informal.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Certifying and Synthesizing Membership Equational Proofs Patrick Lincoln (SRI) joint work with Steven Eker (SRI), Jose Meseguer (Urbana) and Grigore Rosu.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Functional Programming
Parsing 2 of 4: Scanner and Parsing
Working with Java.
Chapter 8: Control Structures
Parsing & Context-Free Grammars Hal Perkins Autumn 2011
An overview of Java, Data types and variables
Chapter 1: Computer Systems
Lecture 7: Introduction to Parsing (Syntax Analysis)
Generating Optimal Linear Temporal Logic Monitors by Coinduction
Interpreter Pattern.
Focus of the Course Object-Oriented Software Development
Sub-system interfaces
OBJ first-order functional language based on equational logic
Presentation transcript:

1 1 Strategic Programming in Java Pierre-Etienne Moreau Antoine Reilles Stratego User Day, December, 1 st, 2006

2 2 Context Protheo group, Nancy (C. Kirchner) 4 permanent researchers 12 PhD students Application domain: improve the quality of software semantics of (rule and graph based) languages: Rho calculus theorem provers: deduction modulo, termination rule based programming: Elan, …, Tom –4 PhD students involved –program analysis –compilation –certification –language design (constraint, business rule)

3 3 Motivations After 20 years of research in rewriting We are convinced that: specifying by rewriting is a nice idea But, we now want to: make rewriting usable in practice integrate rewriting into existing programming environments

4 4 Motivations Our approach: take the best of ASF+SDF, ELAN, Maude, and Stratego design and develop a set of Java tools that offer similar constructs: –algebraic data-type (Gom) –equational pattern matching (Tom) –strategic programming (Java Library + Gom) –simplification rules (Tom + Gom)

5 5 Short presentation of Tom A Java program is a Tom program import pil.term.types.*; import java.util.*; public class Pil { … public final static void main(String[] args) { Expr p1 = …; System.out.println("p1 = " + p1); … }

6 6 Tom adds algebraic data-types to Java Gom supports many-sorted first order signature import pil.term.types.*; import java.util.*; public class Pil { … public final static void main(String[] args) { Expr p1 = …; System.out.println("p1 = " + p1); … } %gom { module Term imports int String abstract syntax Bool = | True() | False() | Eq(e1:Expr, e2:Expr) Expr = | Var(name:String) | Let(var:Expr, e:Expr, body:Expr) | Seq(i1:Expr, i2:Expr) | If(cond:Bool, e1:Expr, e2:Expr) | a() | b() }

7 7 An algebraic term is a Java object Back-quote (`) to build a term import pil.term.types.*; import java.util.*; public class Pil { … public final static void main(String[] args) { Expr p1 = System.out.println("p1 = " + p1); … } %gom { module Term imports int String abstract syntax Bool = | True() | False() | Eq(e1:Expr, e2:Expr) Expr = | Var(name:String) | Let(var:Expr, e:Expr, body:Expr) | Seq(i1:Expr, i2:Expr) | If(cond:Bool, e1:Expr, e2:Expr) | a() | b() } `Let(Var("x"),a(), Let(Var("y"),b(),Var("x")));

8 8 Tom adds pattern matching to Java %match supports syntactic and associative pattern matching import pil.term.types.*; import java.util.*; public class Pil { … public final static void main(String[] args) { Expr p1 = …; System.out.println("p1 = " + p1); …(pretty(p1)); } … } public static String pretty(Object o) { %match(o) { Var(name) -> { return `name; } Let(var,expr,body) -> { return "let " + pretty(`var) + " <- " + pretty(`expr) + " in " + pretty(`body); } … } return o.toString(); }

9 9 Summary Tom offers 3 new constructs: %gom: generate a typed data structure `: build a term %match: syntactic matching and list-matching Gom Tom Java Tom+Java Data structure Pattern matching

10 Demo

Strategies in Tom Tom is powerful, but clearly not enough There is no separation between Transformation and Control Question: s tarting from the JJTraveler library (J. Visser, OOPSLA 2001) s tudying ASF+SDF, ELAN and Stratego c an we design a powerful strategy language, usable in Java ? The answer is Yes

First inspiration: Stratego [E. Visser] Elementaty strategies Id Fail Transformation rule Basic strategies Sequence Choice All One Not Parameterized and recursive strategies Try(s) = Choice(s,Identity) Repeat(s) = Try(Sequence(s,Repeat(s))) Repeat(s) = mu x. Try(Sequence(s,x)) BottomUp(s) = mu x. Sequence(All(x),s)

Second inspiration: JJTraveler [J. Visser] public interface Visitor { /** Pay a visit to any visitable object. */ public Visitable visit(Visitable any) throws VisitFailure; } public interface Visitable { /** Returns the number of children of any visitable. */ public abstract int getChildCount(); /** Returns the ith child of any visitable. */ public abstract Visitable getChildAt(int i); /** Replaces the ith child of any visitable, and returns this visitable. */ public abstract Visitable setChildAt(int i, Visitable child); }

Visitor combination and traversal control module term T1 = a() | b() | f(arg:T1) T2 = … class T1 extends termAbstractType { termAbstractType accept(termVisitor v) { v.visit_T1(this); } interface termVisitor { T1 visit_T1(T1 arg); T2 visit_T2(T2 arg); } abstract class termAbstractType { termAbstractType accept(termVisitor v); } class termForward { Visitable visit(Visitable v) { return ((termAbstractType)v).accept(this); } T1 visit_T1(T1 arg) { return default.visit(arg); } T2 visit_T2(T2 arg) { return default.visit(arg); } } class Rule extends termForward { public Rule() { super(new Fail()); } T1 visit_T1(T1 arg) { // code that implements lhs -> rhs // … return new Fail().visit(arg); } This is a Strategy!

public class TopDown extends Sequence { public TopDown(Visitor s) { super(s,new All(this)); } TopDown(Rule) TopDown(s) = mu x. Sequence(s,All(x)) T1 t = `f(a,f(a,b)); Visitor v = new TopDown(new Rule()); v.visit(t); public class TopDown extends Sequence { public TopDown(Visitor s) { super(s,null); then = new All(this); } public class Sequence implements Visitor { public Visitor first; public Visitor then; … public Visitable visit(Visitable any) throws VisitFailure { return then.visit(first.visit(any)); } Sequence s All

Comparison with Stratego Each elementary strategy is an object Execution is done via interpretation (method call) Failure is implemented via Java exception

Elementary strategies in Tom A Rule is an elementary strategy Identity and Fail are also elementary strategies a strategy is built using ` “x” and “z” are parameters of sort String the rule is applied once, at root position %strategy RenameVar(n1:String,n2:String) extends Identity() { visit Expr { Var(n) -> { if(`n==n1) return `Var(n2); } } Expr p1 = `Let(Var("x"),a(), Let(Var("y"),b(),Var("x"))); Expr p2 = `RenameVar("x","z").visit(p1); > Let(Var("x"),a(), Let(Var("y"),b(),Var("x")))

Basic strategies Big difference wrt. JJTraveler: BottomUp is user defined using the mu operator Expr p1 = `Let(Var("x"),a(), Let(Var("y"),b(),Var("x"))); Expr p2 = `BottomUp(RenameVar("x","z”)).visit(p1); > Let(Var(”z"),a(), Let(Var("y"),b(),Var(”z"))) public Strategy BottomUp(Strategy s) { return `mu(MuVar("x"),Sequence(All(MuVar("x")),s)); }

Key ingredients A strategy is a term can be built matched traversed Mu-expansion is done by applying a BottomUp Sequence Mu x Rule All x Sequence Mu x Rule All

How does it work? %typeterm Strategy { implement equals(t1,t2) } %op Strategy Fail() { is_fsym(t) make() } %op Strategy Choice(s1, s2) { is_fsym(t) get_slot(s1,t) get_slot(s2,t) make(first,then) } { VisitableVisitor } { t1.equals(t2) } { t instanceof Fail } { new Fail() } { t instanceof Choice} { t.getChildAt(FIRST) } { t.getChildAt(THEN) } { new Choice(first,then) } `Choice(Rule(),Fail()); is equivalent to: new Choice(new Rule(), new Fail()) We have Choice(x,y) << s `BottomUp(Expand()).apply(s) returns a new Strategy

21 Current library: basic.tom composed.tom

Parameterized strategies a strategy can be parameterized by values: a strategy can do side effects: %strategy RenameVar(n1:String,n2:String) extends Identity() { … } %strategy CollectVar(c:Collection) extends Identity() { visit Expr { -> { c.add(v) } } Collection set = new HashSet(); `BottomUp(CollectVar(set)).apply(p1);

sometimes we need to recursively call the current calling strategy this breaks separation between rules and control solution: give the calling context as argument Strategies parameterized by a strategy `mu(MuVar(“s”),BottomUp(Rule(MuVar(“s”)).visit() %strategy Rule(s:Strategy) extends Identity() { visit Expr { Let(v,e,body) -> { … `s.apply(body); } } `BottomUp(Rule()).visit() %strategy Rule() extends Identity() { visit Expr { Let(v,e,body) -> { … `BottomUp(Rule()).visit(body); … } } %strategy Rule(s:Strategy) extends Identity() { visit Expr { Let(v,e,body) -> { %match(s) { Mu(x, Choice(…)) -> { Strategy ds = `debugWeaver().visit(s); … `ds.visit(body); } Sequence Mu x All Sequence Debug Rule

24 Demo

From ASF+SDF, ELAN, Maude and Stratego From ASF+SDF list-matching (associative matching with neutral element) From Stratego traversal strategies (All, One) naming and semantics of operators From ELAN statically typed rules and strategies non-determinism experience no AC, no backtracking strategy as a term New in Tom identity based strategies strategy can be applied on a strategy notion of position

Identity based strategies %strategy Rule() extends Fail() { // a -> b // default: failure } Innermost(s) = mu x. All(x) ; ((s ; x) <+ Id) `Innermost(Rule()).visit(t); %strategy RuleId() extends Identity() { // a -> b // default: x -> x } InnermostId(s) = mu x. All(x) ; SequenceId(s,x) `InnermostId(RuleId()).visit(t);

Other nice features A strategy knows where it is applied (global information) useful to implement non-deterministic search (prover, model checker) Gom provides a hook mechanism useful to maintain terms in canonical form (sorted list) Anti-pattern matching car(white,!ecological) XML pattern matching (_*, x, _*, x, _*) -> { … } Strategy library for graphs useful for bytecode analysis

Conclusion There are many similarities with Stratego Integration of rules and strategies in a Java environment Pure Java implementation Main advantages: Tom and Java data-structures are compliant makes debugging easier any Java program is a Tom program no deployment problem Room for improvements: better integration into Java connection to SDF support for concrete syntax