Copyright 2005 Eric Niebler xpressive: Library Design on the Edge or, How I Learned to Stop Worrying and Love Template Meta- Programming.

Slides:



Advertisements
Similar presentations
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Advertisements

Boost Spirit V2 A cookbook style guide to parsing and output generation in C++ Joel de Guzman Hartmut Kaiser
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Advanced microprocessor optimization Kampala August, 2007 Agner Fog
5/10/ Domain-Specific Embedded Languages with Boost.Proto Or, "How I Learned to Stop Worrying and Love Expression Templates"
Type Checking Compiler Design Lecture (02/25/98) Computer Science Rensselaer Polytechnic.
1/18 CS 693/793 Lecture 09 Special Topics in Domain Specific Languages CS 693/793-1C Spring 2004 Mo, We, Fr 10:10 – 11:00 CH 430.
CS 330 Programming Languages 09 / 13 / 2007 Instructor: Michael Eckmann.
Reasons to study concepts of PL
The Scheme Programming Language History and Significance Dmitry Nesvizhsky CIS24 Professor Danny Kopec.
Reference Book: Modern Compiler Design by Grune, Bal, Jacobs and Langendoen Wiley 2000.
Context-sensitive Analysis, II Ad-hoc syntax-directed translation, Symbol Tables, andTypes.
1 Java Grande Introduction  Grande Application: a GA is any application, scientific or industrial, that requires a large number of computing resources(CPUs,
SchemeCOP Introduction to Scheme. SchemeCOP Scheme Meta-language for coding interpreters –“ clean ” semantics Scheme = LISP + ALGOL –simple.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Language Evaluation Criteria
Sumant Tambe, et. al LEESA DSPD 2008 An Embedded Declarative Language for Hierarchical Object Structure Traversal Sumant Tambe* Aniruddha Gokhale Vanderbilt.
Object Oriented Data Structures
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Katanosh Morovat.   This concept is a formal approach for identifying the rules that encapsulate the structure, constraint, and control of the operation.
9/10/ Text Processing With Boost Or, "Anything you can do, I can do better"
Sumant Tambe, et. al LEESA DSPD 2008 An Embedded Declarative Language for Hierarchical Object Structure Traversal Sumant Tambe* Aniruddha Gokhale Vanderbilt.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
Distributed Object Computing Laboratory Washington University St. Louis, MO Rate-Monotonic Analysis in the C++ Type System Morgan Deters Model-Driven Embedded.
CS 403: Programming Languages Lecture 2 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Access Control.
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.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++
C++ Template Metaprogramming Why, When and How? Zoltán Porkoláb Dept. of Programming Languages and Compilers, Faculty of Informatics Eötvös.
Generative Programming. Automated Assembly Lines.
C H A P T E R TWO Syntax and Semantic.
Programming Language Support for Generic Libraries Jeremy Siek and Walid Taha Abstract The generic programming methodology is revolutionizing the way we.
COP 4620 / 5625 Programming Language Translation / Compiler Writing Fall 2003 Lecture 3, 09/11/2003 Prof. Roy Levow.
Lexical and Syntax Analysis
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
(c) 2004, Eric Niebler FOR_EACH by Eric Niebler or, How I Learned to Stop Worrying and Love the Preprocessor.
Meta IFL 2007 Freiburg1 Meta - Towards a Functional-Style Interface for C++ Template Metaprograms * Ádám Sipos, Zoltán Porkoláb, Norbert Pataki, Viktória.
COP4020 Programming Languages Names, Scopes, and Bindings Prof. Xin Yuan.
Semantics for DSL Group Members: Ritu Arora, Diyang Chu, Zekai Demirezen, Jeff Gray, Jacob Gulotta, Luis Pedro, Arturo Sanchez, Greg Sullivan,Ximing Yu.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
D Goforth COSC Translating High Level Languages Note error in assignment 1: #4 - refer to Example grammar 3.4, p. 126.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
1 Future of Abstraction Alexander Stepanov. 2 Outline of the Talk Outline of the Talk  What is abstraction?  Abstraction in programming  OO vs. Templates.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
Advanced Software Development Karl Lieberherr CSG 260 Fall Semester
Presented by: Elena C. Ciobanu Mihai V. Ciobanu Kuntal Ghosh
M.Sc. Seminar - Keren Lenz Supervisor - Dr. Yossi Gil July 1 st 2007 Simple and Safe SQL Queries with C++ Templates A RA R AT -
C H A P T E R T W O Syntax and Semantic. 2 Introduction Who must use language definitions? Other language designers Implementors Programmers (the users.
FUNCTIONAL PROGRAMING AT WORK - HASKELL AND DOMAIN SPECIFIC LANGUAGES Dr. John Peterson Western State Colorado University.
Ada, Scheme, R Emory Wingard. Ada History Department of Defense in search of high level language around Requirements drafted for the language.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
Programming Languages Concepts Chapter 1: Programming Languages Concepts Lecture # 4.
C++ Lesson 1.
Data Types In Text: Chapter 6.
CS 215 Final Review Ismail abumuhfouz Fall 2014.
7. Inheritance and Polymorphism
CS 326 Programming Languages, Concepts and Implementation
Object-Orientated Programming
CS212: Object Oriented Analysis and Design
CSE 3302 Programming Languages
Java Programming Language
Dr. Bhargavi Dept of CS CHRIST
Programming Languages and Paradigms
Presentation transcript:

Copyright 2005 Eric Niebler xpressive: Library Design on the Edge or, How I Learned to Stop Worrying and Love Template Meta- Programming

Copyright 2005 Eric Niebler “Why program by hand in five days what you can spend five years of your life automating?” -- Terrence Parr, author ANTLR/PCCTS

Copyright 2005 Eric Niebler Overview Domain-Specific (Embedded) Languages xpressive and Dual-Mode DSEL Design Programming at the Compile-time / Runtime boundary

Copyright 2005 Eric Niebler Domain-Specific Languages Mini-languages, everywhere! – GNU Make – Backus Naur Form – Regular expressions Syntax, constructs and abstractions for working efficiently in some narrow domain Not general purpose!

Copyright 2005 Eric Niebler Why DSLs? General purpose languages are low-level, procedural DSLs are high-level and declarative Solution space shares concepts with problem space DSL code is easier to write, read, reason about and maintain.

Copyright 2005 Eric Niebler Embedded DSLs A DSL in a library All the wholesome goodness of a DSL in the host language of your choice! C++ is a good host language – operator overloading – low abstraction penalty

Copyright 2005 Eric Niebler Expression Templates (Ab)uses C++ operator overloading to approximate the syntax of the embedded language Must map embedded language syntax and constructs into C++ Used by: – Blitz++ : high-performance scientific computing – Spirit : parser generator (EBNF)

Copyright 2005 Eric Niebler DSEL example: EBNF Calculator group ::= '(' expr ')' fact ::= integer | group term ::= fact (('*' fact) | ('/' fact))* expr ::= term (('+' term) | ('-' term))* rule<> group, fact, term, expr; group = '(' >> expr >> ')'; fact = integer | group; term = fact >> *(('*' >> fact) | ('/' >> fact)); expr = term >> *(('+' >> term) | ('-' >> term));

Copyright 2005 Eric Niebler Types of DSELs: Dynamic Example: SQLCommand c = "SELECT * from Employees"; Advantages: – Unconstrained syntax – Statements can be specified at runtime Disadvantages: – Syntax errors discovered at runtime – Performance costs of interpretation

Copyright 2005 Eric Niebler Types of DSELs: Static Example: double d = (matrix * vector)(3, 4); Advantages: – Syntax errors checked at compile-time – Aggressive inlining, domain-specific codegen Disadvantages: – Constrained by rules for legal C++ expressions – Cannot accept new statements at runtime

Copyright 2005 Eric Niebler Static DSELs... Dynamic DSELs... Can’t I have it both ways? Hrrmmm...

Copyright 2005 Eric Niebler Dual-Mode DSEL Interface Provide both a static and dynamic interface! Sounds good but... – Can we really get the advantages of both? – Can we share the implementation to avoid code duplication?

Copyright 2005 Eric Niebler "\\w" "\\w+" "a\\w" "a|b" "(\\w)\\1" "[^a-z]" "(?=foo)" _w +_w 'a' >> _w as_xpr('a') | 'b' (s1= _w) >> s1 ~range('a', 'z') before("foo") Expression Template Regular Expression

Copyright 2005 Eric Niebler Get a Date // Match a date of the form "\\d\\d?-\\d\\d?-\\d\\d(?:\\d\\d)?"; regex date = _d >> !_d >> '-' // match month >> _d >> !_d >> '-' // match day >> _d >> _d >> !(_d >> _d); // match year # Match a date of the form /\d\d?-\d\d?-\d\d(?:\d\d)?/ // Match a date of the form regex date = regex::compile( "\\d\\d?-\\d\\d?-\\d\\d(?:\\d\\d)?");

Copyright 2005 Eric Niebler Regex aliases, anyone? regex date = /*... */; // A line in a log file is a date followed by a // space, and everything up to the newline. regex log = date >> ' ' >> +~set['\n']; regex date = /*... */; // A line in a log file is a date followed by a // space, and everything up to the newline. regex log = date >> ' ' >> +~set['\n'];

Copyright 2005 Eric Niebler Semantic Constraints // Only match valid dates regex date = (_d >> !_d)[if_is_month()] >> '-' >> (_d >> !_d)[if_is_day()] >> '-' >> (_d >> _d >> !(_d >> _d))[if_is_year()]; // Only match valid dates regex date = (_d >> !_d)[if_is_month()] >> '-' >> (_d >> !_d)[if_is_day()] >> '-' >> (_d >> _d >> !(_d >> _d))[if_is_year()];

Copyright 2005 Eric Niebler Two great tastes that taste great together // A line in a log file is a date followed by a // space, and everything up to the newline. regex date = regex::compile(get_date_pattern()); regex log = date >> ' ' >> +~set['\n'];

Copyright 2005 Eric Niebler “Some people, when confronted with a problem, think, ‘I know, I’ll use regular expressions.’ Now they have two problems.” --Jamie Zawinski, in comp.lang.emacs

Copyright 2005 Eric Niebler Recursive regexen! regex parens; parens // A balanced set of parens... = '(' // is an opening paren... >> // followed by... *( // zero or more... keep( +~(set='(',')') ) // of a bunch of things that are // not parens... | // or... by_ref(parens) // a balanced set of parens ) // (ooh, recursion!)... >> // followed by... ')' // a closing paren ;

Copyright 2005 Eric Niebler A Regex Calculator?! regex group, fact, term, expr; group = '(' >> by_ref(expr) >> ')'; fact = +_d | group; term = fact >> *(('*' >> fact) | ('/' >> fact)); expr = term >> *(('+' >> term) | ('-' >> term));

Copyright 2005 Eric Niebler Wife: It's a floor wax! Husband: No, it's a dessert topping! Announcer: Stop! You're both right. It's a floor wax and a dessert topping! -- Saturday Night Live C++ library design at the edge

Copyright 2005 Eric Niebler STL, MPL and Fusion, Oh My! // Just the data, ma’am std::list integers; // Just the types, ma’am typedef mpl::list types; // Types and data, please! fusion::tuple data = fusion::make_tuple(1, 3.14, "hello");

Copyright 2005 Eric Niebler The Fusion Library Heterogeneous data structures STL-influenced – containers, iterators, algorithms MPL-compatible by Joel de Guzman, part of Boost.Spirit –

Copyright 2005 Eric Niebler A Simple Fusion-esque List struct nil = {}; template struct cons { Car car; Cdr cdr; cons(Car const & a, Cdr const & d = Cdr()) : car(a), cdr(d) {} }; inline cons make_cons(Car const & a, Cdr const & d) { return cons(a, d); }

Copyright 2005 Eric Niebler Simple Fusion-esque List, cont. cons > > data = make_cons(1, make_cons(3.14, make_cons(std::string("hello"))));

Copyright 2005 Eric Niebler Fusion-esque algorithms template void for_each(nil, F) {} template void for_each(cons const & l, F f) { f(l.car); for_each(l.cdr, f); }

Copyright 2005 Eric Niebler Programming challenge!!! Write the type of a std::pair where Second is a pointer to the whole std::pair... std::pair std::pair *>std::pair *> *> std::pair<int, std::pair<int, std::pair<int, std::pair<int,

Copyright 2005 Eric Niebler Dual-Mode DSEL Design Strategy recursive algorithms one modular core two binding policies: static and dynamic acyclic data structures

Copyright 2005 Eric Niebler xpressive Matchers // Match any single character struct any_matcher { template bool match(Iter i1, Iter i2, Next const &n) const { if ( i1 == i2 ) { return false; } return n.match( ++i1, i2 ); } };

Copyright 2005 Eric Niebler xpressive static Scaffold template struct static_xpression { Matcher matcher; Next next; template bool match( Iter i1, Iter i2 ) const { return matcher.match( i1, i2, next ); } };

Copyright 2005 Eric Niebler xpressive dynamic Scaffold template struct matchable { virtual bool match( Iter, Iter ) const = 0; };

Copyright 2005 Eric Niebler xpr: dynamic Scaffold, cont. template struct dynamic_xpression : matchable { Matcher matcher; matchable * pnext; bool match( Iter i1, Iter i2 ) const { return matcher.match( i1, i2, *pnext ); } };

Copyright 2005 Eric Niebler Separation of Concerns Matchers implement core functionality Scaffolds implement binding policy (static or dynamic) Matchers are binding-neutral, reusable Best of both worlds – perf of static binding – flexibility of dynamic dispatch

Copyright 2005 Eric Niebler References xpressive: – Spirit and Fusion – by Joel de Guzman –

Copyright 2005 Eric Niebler Questions?