A Practical Unification of Multi-Stage Programming and Macros GPCE ’18, November 5–6, 2018, Boston, MA, USA

Total Page:16

File Type:pdf, Size:1020Kb

A Practical Unification of Multi-Stage Programming and Macros GPCE ’18, November 5–6, 2018, Boston, MA, USA A Practical Unication of Multi-stage Programming and Macros Nicolas Stucki Aggelos Biboudis Martin Odersky EPFL EPFL EPFL Switzerland Switzerland Switzerland [email protected] [email protected] [email protected] Abstract 1 Introduction Program generation is indispensable. We propose a novel Generative programming [9] is widely used in scenarios such unication of two existing metaprogramming techniques: as code conguration of libraries, code optimizations [43] multi-stage programming and hygienic generative macros. and DSL implementations [8, 41]. There are various kinds The former supports runtime code generation and execution of program generation systems ranging from completely in a type-safe manner while the latter oers compile-time syntax-based and unhygienic, to fully typed [35]. Modern code generation. macro systems, like Racket’s, can extend the syntax of the In this work we draw upon a long line of research on language [11]. On the ipside, other program generation metaprogramming, starting with Lisp, MetaML and MetaO- systems may provide a xed set of constructs oering staged Caml. We provide direct support for quotes, splices and top- evaluation [10, 16] like MetaML [38] and MetaOCaml [6, 20, level splices, all regulated uniformly by a level-counting 21, 23]. Phase Consistency Principle. Our design enables the construc- The latter techniques established a new programming tion and combination of code values for both expressions paradigm, called Multi-stage Programming (MSP) oering and types. Moreover, code generation can happen either at a principled, well-scoped and type-safe approach to code runtime à la MetaML or at compile time, in a macro fashion, generation [37]. Programmers make use of two constructs, à la MacroML. quote and splice, to delay and compose representations of We provide an implementation of our design in Scala and expressions. Conceptually, users are able to manually indi- we present two case studies. The rst implements the Hid- cate which parts of their program are dynamic and which den Markov Model, Shonan Challenge for HPC. The second static. Even though this technique is inspired by advance- implements the staged streaming library Strymonas. ments in partial evaluation [26] it proved useful to have it in a programming language with rst-class support. Part of the CCS Concepts • Software and its engineering → Lan- power of this programming model, comes from a regulation guage features; Macro languages; mechanism that attributes levels to terms [36]; these systems are type-safe in a modular way (type checking the genera- Keywords Macros, Multi-stage programming, Scala tor ensures the validity of the generated code). Nowadays, ACM Reference Format: gaining inspiration from MetaML and MetaOCaml, many Nicolas Stucki, Aggelos Biboudis, and Martin Odersky. 2018. A programming languages provide support for similar mecha- Practical Unication of Multi-stage Programming and Macros. In nisms such as F#, Haskell (Template Haskell [33] and later Proceedings of the 17th ACM SIGPLAN International Conference on Typed Template Haskell [15]), Converge [42] and others. Generative Programming: Concepts and Experiences (GPCE ’18), No- While MSP is primarily a metaprogramming technique for vember 5–6, 2018, Boston, MA, USA. ACM, New York, NY, USA, runtime code generation it has been shown that its semantics 14 pages. hps://doi.org/10.1145/3278122.3278139 can specify compile-time metaprogramming as well. MacroML [12] showed that the treatment of staged evalu- ation can form the basis for generative macros (i.e. macros Permission to make digital or hard copies of all or part of this work for that cannot inspect code) or more precisely, function inlin- personal or classroom use is granted without fee provided that copies are not made or distributed for prot or commercial advantage and that copies bear ing. Theoretically it has been proven that MacroML’s inter- this notice and the full citation on the rst page. Copyrights for components pretation is a denotational semantics where MetaML is the of this work owned by others than ACM must be honored. Abstracting with internal language of the model. Monnier et al.[25] rst ex- credit is permitted. To copy otherwise, or republish, to post on servers or to pressed inlining as staged computation but MacroML oered redistribute to lists, requires prior specic permission and/or a fee. Request a user-level perspective by reusing the same mechanisms of permissions from [email protected]. quotes and splices; where splices can appear at the top-level GPCE ’18, November 5–6, 2018, Boston, MA, USA © 2018 Association for Computing Machinery. (not nested in a quote). Modular Macros [44] prototyped a ACM ISBN 978-1-4503-6045-6/18/11...$15.00 compile-time variant of MetaOCaml which also comprises hps://doi.org/10.1145/3278122.3278139 part of our inspiration. GPCE ’18, November 5–6, 2018, Boston, MA, USA N. Stucki, A. Biboudis, M. Odersky def power_s(x: Expr[Double], n: Int): Expr[Double] = Scala is a multi-paradigm programming language for the if (n == 0) '(1.0) JVM oering a metaprogramming API called scala.reect [5]. else if (n % 2 == 1) '(~x * ~power_s(x, n - 1)) scala.reect supports type-aware, runtime and compile-time else '{ val y = ~x * ~x; ~power_s('(y), n / 2) } code generation providing an expressive and powerful sys- tem to the user (both generative and analytical). Besides the inline def power(x: Double, inline n: Int): Double = ~power_s('(x), n) success of scala.reect, the API exposed compiler internals and gave rise to portability problems between compiler ver- valx=2 sions [24]. We implemented our system for the Dotty [39] // 1) staged, runtime generation compiler for Scala and we believe that the design is portable val power5 = ('{ (x: Double) => ~power_s('(x), 5)}).run in other languages as well. power5(x) // 2) macro, compile-time generation Organization power(x, 5) First, in Section2, we introduce a motivat- // Both generate:{ valy=x*x; val y2=y*y;x* y2} ing example to explain the high-level semantics of quotes and splices. In Section3 we present PCP and the details of multi-staging and macros. In Section4 we discuss how to Figure 1. Power function, staged or inlined implement cross-stage persistence (CSP) in this system. In Section5 we show how to simplify the handling of type splices in quoted code. In Section6 we discuss lifted lambdas While the same line of work inspired many metaprogram- and β-reduction optimizations. Section7 describes the im- ming libraries and language features, to our knowledge built- plementation in Dotty. Section8 presents two case studies 1: in support for both run-time MSP and generative macros (i) we give a sample solution to the Hidden Markov Model has not been implemented previously in a unifying man- challenge as specied in Shonan Challenge for Generative ner. We advocate that such a unication has a two-fold ben- Programming [1] and (ii) we port Strymonas [22], a staged et: 1) users rely on a single abstraction to express code library for streams. In Section9 we discuss the related work generation and 2) having a single subsystem in the com- and conclude in Section 10. piler favors maintainability. Our view regarding top-level splices is on par with the benets of MSP on domain-specic 2 Overview of Quotes and Splices optimizations[7, 21, 22]: in modern programming languages, inlining (à la C++) with a suciently smart partial evaluator Our metaprogramming system is built on two well-known 2 is not necessarily equivalent with domain-specic optimiza- fundamental operations: quotation and splicing. A quota- tions that can be done at compile-time. tion is expressed as '(...) or '{...} for expressions (both In our work a staged library can be used, unaltered, either forms are equivalent) and as '[...] for types. Splicing is as a macro or a run-time code generator. We illustrate stag- expressed with the ~ prex operator. ing and macros via the folklore example of a simple power If e is an expression, then '(e) or '{e} represent the function, which has been used for demonstrating partial opaque typed abstract syntax tree representing e. If T is a evaluation techniques. The power_s, staged function is de- type, then '[T] represents the opaque type structure repre- ned recursively using the basic method of exponentiation senting T. The precise denitions of typed abstract syntax by squaring. The inline function power becomes a macro by tree or type structure do not matter for now, the expressions expanding power_s. In Figure1 we see two dierent ways are used only to give some intuition that they represent code to use it: 1) staged; generation happens at runtime and 2) as a value. Conversely, ~e evaluates the expression e, which inlined generation happens at compile-time. must yield a typed abstract syntax tree or type structure, and embeds the result as an expression (respectively, type) in Contributions In this paper, inspired from MetaML and the enclosing program. Informally, by quoting we delay the MacroML we present a practical implementation of homoge- evaluation of an expression—or we stage, in MSP terms—and neous generative metaprogramming (HGMP) for Scala: by splicing, we evaluate an expression before embedding the • We present a design with quotes, splices, and top-level result in the surrounding quote. splices to support both MSP and macros simultane- Quotes and splices are duals of each other. For arbitrary ously. expressions e: T and types T we have ~'(e) = e and ~'[T] • We extend the operation of splicing to handle terms = T; for arbitrary AST-typed expressions e2: Expr[T] and and types uniformly. t: Type[T] we have '(~e) = e and '(~t) = t. • We present how our system operates under a MetaML- inspired check, Phase Consistency Principle (PCP), that 1The code of the case studies, along with unit tests and benchmarks are at regulates free variable accesses in quoted and spliced hps://github.com/nicolasstucki/doy-staging-gpce-2018 expressions and types uniformly, for both MSP and 2Or more accurately quasiquotation, which represents quotes with unquoted macros.
Recommended publications
  • A New Macro-Programming Paradigm in Data Collection Sensor Networks
    SpaceTime Oriented Programming: A New Macro-Programming Paradigm in Data Collection Sensor Networks Hiroshi Wada and Junichi Suzuki Department of Computer Science University of Massachusetts, Boston Program Insert This paper proposes a new programming paradigm for wireless sensor networks (WSNs). It is designed to significantly reduce the complexity of WSN programming by providing a new high- level programming abstraction to specify spatio-temporal data collections in a WSN from a global viewpoint as a whole rather than sensor nodes as individuals. Abstract SpaceTime Oriented Programming (STOP) is new macro-programming paradigm for wireless sensor networks (WSNs) in that it supports both spatial and temporal aspects of sensor data and it provides a high-level abstraction to express data collections from a global viewpoint for WSNs as a whole rather than sensor nodes as individuals. STOP treats space and time as first-class citizens and combines them as spacetime continuum. A spacetime is a three dimensional object that consists of a two special dimensions and a time playing the role of the third dimension. STOP allows application developers to program data collections to spacetime, and abstracts away the details in WSNs, such as how many nodes are deployed in a WSN, how nodes are connected with each other, and how to route data queries in a WSN. Moreover, STOP provides a uniform means to specify data collections for the past and future. Using the STOP application programming interfaces (APIs), application programs (STOP macro programs) can obtain a “snapshot” space at a given time in a given spatial resolutions (e.g., a space containing data on at least 60% of nodes in a give spacetime at 30 minutes ago.) and a discrete set of spaces that meet specified spatial and temporal resolutions.
    [Show full text]
  • Why Untyped Nonground Metaprogramming Is Not (Much Of) a Problem
    NORTH- HOLLAND WHY UNTYPED NONGROUND METAPROGRAMMING IS NOT (MUCH OF) A PROBLEM BERN MARTENS* and DANNY DE SCHREYE+ D We study a semantics for untyped, vanilla metaprograms, using the non- ground representation for object level variables. We introduce the notion of language independence, which generalizes range restriction. We show that the vanilla metaprogram associated with a stratified normal oljjctct program is weakly stratified. For language independent, stratified normal object programs, we prove that there is a natural one-to-one correspon- dence between atoms p(tl, . , tr) in the perfect Herbrand model of t,he object program and solve(p(tl, , tT)) atoms in the weakly perfect Her\) and model of the associated vanilla metaprogram. Thus, for this class of programs, the weakly perfect, Herbrand model provides a sensible SC mantics for the metaprogram. We show that this result generalizes to nonlanguage independent programs in the context of an extended Hcr- brand semantics, designed to closely mirror the operational behavior of logic programs. Moreover, we also consider a number of interesting exterl- sions and/or variants of the basic vanilla metainterpreter. For instance. WC demonstrate how our approach provides a sensible semantics for a limit4 form of amalgamation. a “Partly supported by the Belgian National Fund for Scientific Research, partly by ESPRlT BRA COMPULOG II, Contract 6810, and partly by GOA “Non-Standard Applications of Ab- stract Interpretation,” Belgium. TResearch Associate of the Belgian National Fund for Scientific Research Address correspondence to Bern Martens and Danny De Schreye, Department of Computer Science, Katholieke Universiteit Leuven, Celestijnenlaan 200A. B-3001 Hevrrlee Belgium E-mail- {bern, dannyd}@cs.kuleuven.ac.be.
    [Show full text]
  • Practical Reflection and Metaprogramming for Dependent
    Practical Reflection and Metaprogramming for Dependent Types David Raymond Christiansen Advisor: Peter Sestoft Submitted: November 2, 2015 i Abstract Embedded domain-specific languages are special-purpose pro- gramming languages that are implemented within existing general- purpose programming languages. Dependent type systems allow strong invariants to be encoded in representations of domain-specific languages, but it can also make it difficult to program in these em- bedded languages. Interpreters and compilers must always take these invariants into account at each stage, and authors of embedded languages must work hard to relieve users of the burden of proving these properties. Idris is a dependently typed functional programming language whose semantics are given by elaboration to a core dependent type theory through a tactic language. This dissertation introduces elabo- rator reflection, in which the core operators of the elaborator are real- ized as a type of computations that are executed during the elab- oration process of Idris itself, along with a rich API for reflection. Elaborator reflection allows domain-specific languages to be imple- mented using the same elaboration technology as Idris itself, and it gives them additional means of interacting with native Idris code. It also allows Idris to be used as its own metalanguage, making it into a programmable programming language and allowing code re-use across all three stages: elaboration, type checking, and execution. Beyond elaborator reflection, other forms of compile-time reflec- tion have proven useful for embedded languages. This dissertation also describes error reflection, in which Idris code can rewrite DSL er- ror messages before presenting domain-specific messages to users, as well as a means for integrating quasiquotation into a tactic-based elaborator so that high-level syntax can be used for low-level reflected terms.
    [Show full text]
  • SQL Processing with SAS® Tip Sheet
    SQL Processing with SAS® Tip Sheet This tip sheet is associated with the SAS® Certified Professional Prep Guide Advanced Programming Using SAS® 9.4. For more information, visit www.sas.com/certify Basic Queries ModifyingBasic Queries Columns PROC SQL <options>; SELECT col-name SELECT column-1 <, ...column-n> LABEL= LABEL=’column label’ FROM input-table <WHERE expression> SELECT col-name <GROUP BY col-name> FORMAT= FORMAT=format. <HAVING expression> <ORDER BY col-name> <DESC> <,...col-name>; Creating a SELECT col-name AS SQL Query Order of Execution: new column new-col-name Filtering Clause Description WHERE CALCULATED new columns new-col-name SELECT Retrieve data from a table FROM Choose and join tables Modifying Rows WHERE Filter the data GROUP BY Aggregate the data INSERT INTO table SET column-name=value HAVING Filter the aggregate data <, ...column-name=value>; ORDER BY Sort the final data Inserting rows INSERT INTO table <(column-list)> into tables VALUES (value<,...value>); INSERT INTO table <(column-list)> Managing Tables SELECT column-1<,...column-n> FROM input-table; CREATE TABLE table-name Eliminating SELECT DISTINCT CREATE TABLE (column-specification-1<, duplicate rows col-name<,...col-name> ...column-specification-n>); WHERE col-name IN DESCRIBE TABLE table-name-1 DESCRIBE TABLE (value1, value2, ...) <,...table-name-n>; WHERE col-name LIKE “_string%” DROP TABLE table-name-1 DROP TABLE WHERE col-name BETWEEN <,...table-name-n>; Filtering value AND value rows WHERE col-name IS NULL WHERE date-value Managing Views “<01JAN2019>”d WHERE time-value “<14:45:35>”t CREATE VIEW CREATE VIEW table-name AS query; WHERE datetime-value “<01JAN201914:45:35>”dt DESCRIBE VIEW view-name-1 DESCRIBE VIEW <,...view-name-n>; Remerging Summary Statistics DROP VIEW DROP VIEW view-name-1 <,...view-name-n>; SELECT col-name, summary function(argument) FROM input table; Copyright © 2019 SAS Institute Inc.
    [Show full text]
  • Rexx to the Rescue!
    Session: G9 Rexx to the Rescue! Damon Anderson Anixter May 21, 2008 • 9:45 a.m. – 10:45 a.m. Platform: DB2 for z/OS Rexx is a powerful tool that can be used in your daily life as an z/OS DB2 Professional. This presentation will cover setup and execution for the novice. It will include Edit macro coding examples used by DBA staff to solve everyday tasks. DB2 data access techniques will be covered as will an example of calling a stored procedure. Examples of several homemade DBA tools built with Rexx will be provided. Damon Anderson is a Senior Technical DBA and Technical Architect at Anixter Inc. He has extensive experience in DB2 and IMS, data replication, ebusiness, Disaster Recovery, REXX, ISPF Dialog Manager, and related third-party tools and technologies. He is a certified DB2 Database Administrator. He has written articles for the IDUG Solutions Journal and presented at IDUG and regional user groups. Damon can be reached at [email protected] 1 Rexx to the Rescue! 5 Key Bullet Points: • Setting up and executing your first Rexx exec • Rexx execs versus edit macros • Edit macro capabilities and examples • Using Rexx with DB2 data • Examples to clone data, compare databases, generate utilities and more. 2 Agenda: • Overview of Anixter’s business, systems environment • The Rexx “Setup Problem” Knowing about Rexx but not knowing how to start using it. • Rexx execs versus Edit macros, including coding your first “script” macro. • The setup and syntax for accessing DB2 • Discuss examples for the purpose of providing tips for your Rexx execs • A few random tips along the way.
    [Show full text]
  • The Semantics of Syntax Applying Denotational Semantics to Hygienic Macro Systems
    The Semantics of Syntax Applying Denotational Semantics to Hygienic Macro Systems Neelakantan R. Krishnaswami University of Birmingham <[email protected]> 1. Introduction body of a macro definition do not interfere with names oc- Typically, when semanticists hear the words “Scheme” or curring in the macro’s arguments. Consider this definition of and “Lisp”, what comes to mind is “untyped lambda calculus a short-circuiting operator: plus higher-order state and first-class control”. Given our (define-syntax and typical concerns, this seems to be the essence of Scheme: it (syntax-rules () is a dynamically typed applied lambda calculus that sup- ((and e1 e2) (let ((tmp e1)) ports mutable data and exposes first-class continuations to (if tmp the programmer. These features expose a complete com- e2 putational substrate to programmers so elegant that it can tmp))))) even be characterized mathematically; every monadically- representable effect can be implemented with state and first- In this definition, even if the variable tmp occurs freely class control [4]. in e2, it will not be in the scope of the variable definition However, these days even mundane languages like Java in the body of the and macro. As a result, it is important to support higher-order functions and state. So from the point interpret the body of the macro not merely as a piece of raw of view of a working programmer, the most distinctive fea- syntax, but as an alpha-equivalence class. ture of Scheme is something quite different – its support for 2.2 Open Recursion macros. The intuitive explanation is that a macro is a way of defining rewrites on abstract syntax trees.
    [Show full text]
  • Concatenative Programming
    Concatenative Programming From Ivory to Metal Jon Purdy ● Why Concatenative Programming Matters (2012) ● Spaceport (2012–2013) Compiler engineering ● Facebook (2013–2014) Site integrity infrastructure (Haxl) ● There Is No Fork: An Abstraction for Efficient, Concurrent, and Concise Data Access (ICFP 2014) ● Xamarin/Microsoft (2014–2017) Mono runtime (performance, GC) What I Want in a ● Prioritize reading & modifying code over writing it Programming ● Be expressive—syntax closely Language mirroring high-level semantics ● Encourage “good” code (reusable, refactorable, testable, &c.) ● “Make me do what I want anyway” ● Have an “obvious” efficient mapping to real hardware (C) ● Be small—easy to understand & implement tools for ● Be a good citizen—FFI, embedding ● Don’t “assume you’re the world” ● Forth (1970) Notable Chuck Moore Concatenative ● PostScript (1982) Warnock, Geschke, & Paxton Programming ● Joy (2001) Languages Manfred von Thun ● Factor (2003) Slava Pestov &al. ● Cat (2006) Christopher Diggins ● Kitten (2011) Jon Purdy ● Popr (2012) Dustin DeWeese ● … History Three ● Lambda Calculus (1930s) Alonzo Church Formal Systems of ● Turing Machine (1930s) Computation Alan Turing ● Recursive Functions (1930s) Kurt Gödel Church’s Lambdas e ::= x Variables λx.x ≅ λy.y | λx. e Functions λx.(λy.x) ≅ λy.(λz.y) | e1 e2 Applications λx.M[x] ⇒ λy.M[y] α-conversion (λx.λy.λz.xz(yz))(λx.λy.x)(λx.λy.x) ≅ (λy.λz.(λx.λy.x)z(yz))(λx.λy.x) (λx.M)E ⇒ M[E/x] β-reduction ≅ λz.(λx.λy.x)z((λx.λy.x)z) ≅ λz.(λx.λy.x)z((λx.λy.x)z) ≅ λz.z Turing’s Machines ⟨ ⟩ M
    [Show full text]
  • Metaprogramming with Julia
    Metaprogramming with Julia https://szufel.pl Programmers effort vs execution speed Octave R Python Matlab time, time, log scale - C JavaScript Java Go Julia C rozmiar kodu Sourcewego w KB Source: http://www.oceanographerschoice.com/2016/03/the-julia-language-is-the-way-of-the-future/ 2 Metaprogramming „Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself while running.” (source: Wikipedia) julia> code = Meta.parse("x=5") :(x = 5) julia> dump(code) Expr head: Symbol = args: Array{Any}((2,)) 1: Symbol x 2: Int64 5 3 Metaprogramming (cont.) julia> code = Meta.parse("x=5") :(x = 5) julia> dump(code) Expr head: Symbol = args: Array{Any}((2,)) 1: Symbol x 2: Int64 5 julia> eval(code) 5 julia> x 5 4 Julia Compiler system not quite accurate picture... Source: https://www.researchgate.net/ publication/301876510_High- 5 level_GPU_programming_in_Julia Example 1. Select a field from an object function getValueOfA(x) return x.a end function getValueOf(x, name::String) return getproperty(x, Symbol(name)) end function getValueOf2(name::String) field = Symbol(name) code = quote (obj) -> obj.$field end return eval(code) end function getValueOf3(name::String) return eval(Meta.parse("obj -> obj.$name")) end 6 Let’s test using BenchmarkTools struct MyStruct a b end x = MyStruct(5,6) @btime getValueOfA($x) @btime getValueOf($x,"a") const getVal2 = getValueOf2("a") @btime
    [Show full text]
  • A Foundation for Trait-Based Metaprogramming
    A foundation for trait-based metaprogramming John Reppy Aaron Turon University of Chicago {jhr, adrassi}@cs.uchicago.edu Abstract We present a calculus, based on the Fisher-Reppy polymorphic Scharli¨ et al. introduced traits as reusable units of behavior inde- trait calculus [FR03], with support for trait privacy, hiding and deep pendent of the inheritance hierarchy. Despite their relative simplic- renaming of trait methods, and a more granular trait typing. Our ity, traits offer a surprisingly rich calculus. Trait calculi typically in- calculus is more expressive (it provides new forms of conflict- clude operations for resolving conflicts when composing two traits. resolution) and more flexible (it allows after-the-fact renaming) In the existing work on traits, these operations (method exclusion than the previous work. Traits provide a useful mechanism for shar- and aliasing) are shallow, i.e., they have no effect on the body of the ing code between otherwise unrelated classes. By adding deep re- other methods in the trait. In this paper, we present a new trait sys- naming, our trait calculus supports sharing code between methods. tem, based on the Fisher-Reppy trait calculus, that adds deep oper- For example, the JAVA notion of synchronized methods can im- ations (method hiding and renaming) to support conflict resolution. plemented as a trait in our system and can be applied to multiple The proposed operations are deep in the sense that they preserve methods in the same class to produce synchronized versions. We any existing connections between the affected method and the other term this new use of traits trait-based metaprogramming.
    [Show full text]
  • Metaprogramming in .NET by Kevin Hazzard Jason Bock
    S AMPLE CHAPTER in .NET Kevin Hazzard Jason Bock FOREWORD BY Rockford Lhotka MANNING Metaprogramming in .NET by Kevin Hazzard Jason Bock Chapter 1 Copyright 2013 Manning Publications brief contents PART 1DEMYSTIFYING METAPROGRAMMING ..............................1 1 ■ Metaprogramming concepts 3 2 ■ Exploring code and metadata with reflection 41 PART 2TECHNIQUES FOR GENERATING CODE ..........................63 3 ■ The Text Template Transformation Toolkit (T4) 65 4 ■ Generating code with the CodeDOM 101 5 ■ Generating code with Reflection.Emit 139 6 ■ Generating code with expressions 171 7 ■ Generating code with IL rewriting 199 PART 3LANGUAGES AND TOOLS ............................................221 8 ■ The Dynamic Language Runtime 223 9 ■ Languages and tools 267 10 ■ Managing the .NET Compiler 287 v Metaprogramming concepts In this chapter ■ Defining metaprogramming ■ Exploring examples of metaprogramming The basic principles of object-oriented programming (OOP) are understood by most software developers these days. For example, you probably understand how encapsulation and implementation-hiding can increase the cohesion of classes. Languages like C# and Visual Basic are excellent for creating so-called coarsely grained types because they expose simple features for grouping and hiding both code and data. You can use cohesive types to raise the abstraction level across a system, which allows for loose coupling to occur. Systems that enjoy loose cou- pling at the top level are much easier to maintain because each subsystem isn’t as dependent on the others as they could be in a poor design. Those benefits are realized at the lower levels, too, typically through lowered complexity and greater reusability of classes. In figure 1.1, which of the two systems depicted would likely be easier to modify? Without knowing what the gray circles represent, most developers would pick the diagram on the right as the better one.
    [Show full text]
  • A Fast, Verified, Cross-Platform Cryptographic Provider
    EverCrypt: A Fast, Verified, Cross-Platform Cryptographic Provider Jonathan Protzenko∗, Bryan Parnoz, Aymeric Fromherzz, Chris Hawblitzel∗, Marina Polubelovay, Karthikeyan Bhargavany Benjamin Beurdouchey, Joonwon Choi∗x, Antoine Delignat-Lavaud∗,Cedric´ Fournet∗, Natalia Kulatovay, Tahina Ramananandro∗, Aseem Rastogi∗, Nikhil Swamy∗, Christoph M. Wintersteiger∗, Santiago Zanella-Beguelin∗ ∗Microsoft Research zCarnegie Mellon University yInria xMIT Abstract—We present EverCrypt: a comprehensive collection prone (due in part to Intel and AMD reporting CPU features of verified, high-performance cryptographic functionalities avail- inconsistently [78]), with various cryptographic providers able via a carefully designed API. The API provably supports invoking illegal instructions on specific platforms [74], leading agility (choosing between multiple algorithms for the same functionality) and multiplexing (choosing between multiple im- to killed processes and even crashing kernels. plementations of the same algorithm). Through abstraction and Since a cryptographic provider is the linchpin of most zero-cost generic programming, we show how agility can simplify security-sensitive applications, its correctness and security are verification without sacrificing performance, and we demonstrate crucial. However, for most applications (e.g., TLS, cryptocur- how C and assembly can be composed and verified against rencies, or disk encryption), the provider is also on the critical shared specifications. We substantiate the effectiveness of these techniques with
    [Show full text]
  • Specialising Dynamic Techniques for Implementing the Ruby Programming Language
    SPECIALISING DYNAMIC TECHNIQUES FOR IMPLEMENTING THE RUBY PROGRAMMING LANGUAGE A thesis submitted to the University of Manchester for the degree of Doctor of Philosophy in the Faculty of Engineering and Physical Sciences 2015 By Chris Seaton School of Computer Science This published copy of the thesis contains a couple of minor typographical corrections from the version deposited in the University of Manchester Library. [email protected] chrisseaton.com/phd 2 Contents List of Listings7 List of Tables9 List of Figures 11 Abstract 15 Declaration 17 Copyright 19 Acknowledgements 21 1 Introduction 23 1.1 Dynamic Programming Languages.................. 23 1.2 Idiomatic Ruby............................ 25 1.3 Research Questions.......................... 27 1.4 Implementation Work......................... 27 1.5 Contributions............................. 28 1.6 Publications.............................. 29 1.7 Thesis Structure............................ 31 2 Characteristics of Dynamic Languages 35 2.1 Ruby.................................. 35 2.2 Ruby on Rails............................. 36 2.3 Case Study: Idiomatic Ruby..................... 37 2.4 Summary............................... 49 3 3 Implementation of Dynamic Languages 51 3.1 Foundational Techniques....................... 51 3.2 Applied Techniques.......................... 59 3.3 Implementations of Ruby....................... 65 3.4 Parallelism and Concurrency..................... 72 3.5 Summary............................... 73 4 Evaluation Methodology 75 4.1 Evaluation Philosophy
    [Show full text]