Practical Reflection and Metaprogramming for Dependent

Total Page:16

File Type:pdf, Size:1020Kb

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. ii Resumé Indlejrede domænespecifikke sprog er skræddersyede program- meringssprog, som er implementeret inde i eksisterende alment an- vendelige programmeringssprog. Afhængige typer tillader, at stærke invarianter indkodes i datarepræsentationer, herunder repræsenta- tioner af programmeringssprog. Dog kan denne kontrol også be- sværliggøre programmeringsprocessen, da brugeren altid skal de- monstrere, at invarianterne er overholdt. Fortolkere og oversættere skal tage disse invarianter i betragtning i hvert trin. Når indlejrede sprog bliver designet, skal der arbejdes hårdt for at brugerne ikke bebyrdes med tungt bevisarbejde. Idris er et funktionsprogrammeringssprog med afhængige ty- per, hvis semantik er givet ved elaborering til en afhængigt-typet kerneteori ved brug af et taktiksprog. Denne afhandling introdu- cerer elaboratorrefleksion, hvor elaboratorens grundlæggende opera- tioner er realiseret som en type, hvis bereginger bliver afviklet un- der Idris’s egen elaborering. Dertil findes et rigt API for refleksion om termer, datatyper, og andre definitioner. De reflekterede elabore- ringsoperationer muliggør, at domænespecifikke sprog kan imple- menteres med Idris’s elaboreringsteknologi, og således får de elabo- rerede sprog flere muligheder for interaktion med Idris. Desuden bliver Idris anvendelig som sit eget metasprog, hvilket gør Idris til et programmerbart programmeringssprog og muliggør genbrug af kode i alle tre stadier: elaborering, typetjek og afvikling. Udover elaboreringsrefleksion har andre former for statisk re- fleksion vist sig at være nyttige for indlejring af sprog. Denneaf- handling præsenterer desuden refleksion af fejlmeddelelser, hvor kode skrevet i Idris kan omskrive fejlmeddelelser med oprindelse i do- mænespecifikke sprog til domænespecifikke fejlmeddelelser. Deru- dover præsenteres en teknik for integrering af kvasicitering i en tak- tikbaseret elaborator, så højtniveausyntaks kan anvendes for termer i kernesproget. Acknowledgments This dissertation represents the culmination of a long process of learn- ing and hard work that was made possible largely by the generosity and caring of other people. I would like to thank my supervisor, Peter Sestoft, for being a won- derful example of how to communicate clearly and how to let theory and practice inform one another. Even when my work diverged somewhat from our original plans, he has been supportive and helpful, always ready to discuss what I’ve been working on. Our partners at Edlund A/S, especially Henning Niss and Klaus Grue, got me off to a good start and kept me on the right track. Their feedback and good example was immensely valuable. I would also like to thank Edwin Brady for being so helpful as I’ve extended and modified his language, and the #idris channel on Freenode for being such a great community. I would especially like to thank my fellow Ph.D. students Hannes Meh- nert and Ahmad Salim Al-Sibahi. Hannes’s hacker spirit was always an inspiration, and we had many good discussions about both programming languages and wider themes. Ahmad’s encyclopedic knowledge helped me find many papers that I didn’t even know existed, and his feedback on an earlier draft of this dissertation made it much better. If not for the Danish welfare society, I may have never had the chance to go to graduate school. The Danish public sector paid my tuition and stipend while I was working towards my master’s degree, and my work was funded as part of the Actulus project, Danish National Advanced Technology Foundation (Højteknologifonden) grant 017-2010-3. Højteknologi- fonden has since become part of Innovationsfonden. Tusind tak! And thanks, Lisbet, for support both moral and material, and for your patience during the last few months. Contents Acknowledgments iii Contents v 1 Introduction 1 I Background 7 2 Embedding Languages 9 2.1 Embeddings, Deep and Shallow .................... 9 2.2 Representing Binders ......................... 10 2.3 Syntactic Re-Use ........................... 11 2.4 Elaborating Embedded Languages ................... 12 3 Reflection and Metaprogramming 15 3.1 Quasiquotations in Programming Languages .............. 15 3.2 Static Reflection ........................... 17 3.3 Reflection and Dependent Types .................... 18 4 The Idris Elaborator 21 4.1 The Core Language .......................... 23 4.2 Pattern-Matching Definitions and Data Types .............. 24 4.3 The Development Calculus ...................... 25 4.4 Elaboration Example ......................... 26 4.5 Binders in the Elaborator ....................... 34 5 Reflection in Idris 37 vi Contents II Metaprogramming Idris 45 6 A Pretty Printer that Says What it Means 49 6.1 Presentations ............................ 50 6.2 The Idris IDE Protocol ......................... 56 6.3 Annotated Pretty Printing ....................... 57 6.4 Conclusions ............................. 60 7 Quasiquotation 61 7.1 Example ............................... 62 7.2 Idris Quasiquotations ......................... 64 7.3 Elaborating Quasiquotations ..................... 65 7.4 Polymorphic Quotations ........................ 72 7.5 Quoted Names ............................ 73 7.6 Future Extensions .......................... 74 8 Error Reflection 77 8.1 Introduction ............................. 77 8.2 Error Reflection ........................... 78 8.3 Applications ............................. 85 8.4 Argument Error Handlers ....................... 90 8.5 Implementation Considerations .................... 91 8.6 Related Work ............................ 93 8.7 Conclusion and Future Work ...................... 93 9 Elaborator Reflection 95 9.1 Introductory Examples ........................ 96 9.2 Elaborator Reflection, Defined ..................... 103 9.3 Implementation Considerations .................... 111 9.4 The Pruviloj Library .......................... 113 9.5 Other Applications .......................... 117 9.6 Agda-Style Reflection ......................... 135 9.7 Reflections on Elaborator Reflection .................. 140 10 Conclusions 147 Bibliography 149 A Elaborator Tactics 161 Contents vii B The Idris Language 165 Glossary 171 Chapter 1 Introduction Static type systems in programming languages are becoming more and more expressive over time. As type systems get more and more expres- sive, they offer greater abilities to express complex invariants, ruling out more classes of bugs. Additionally, an expressive static type language can enable better programming tools. If the system knows more about what the programmer is trying to build, then it is in a better position to help her get there! As type systems become more and more expressive, the job of the pro- grammer when writing a type begins to resemble the job of the program- mer when writing a program. In other words, types begin to need to do computation. Unfortunately for programmers, most type systems were not designed as programming languages, and systems in which the ability to write programs is accidental tend to not be very pleasant to write pro- grams in. Enter dependent types. Dependently typed languages use the same language for type-level and program-level computation. Because this lan- guage is designed explicitly for programming, type-level programming is no longer a difficult subject reserved for the most advanced users. Ad- ditionally, it becomes possible to re-use code in both stages: the same list datatype that is used to contain run-time values from a database can be used to represent a statically-checked typing context for an embedded domain-specific language. Martin-Löf’s type theory and its descendants have been recognized
Recommended publications
  • Formal Verification of Termination Criteria for First-Order Recursive Functions
    Formal Verification of Termination Criteria for First-Order Recursive Functions Cesar A. Muñoz £ Mauricio Ayala-Rincón £ NASA Langley Research Center, Hampton, VA, Departments of Computer Science and Mathem- USA atics, Universidade de Brasília, Brazil Mariano M. Moscato £ Aaron M. Dutle £ National Institute of Aerospace, Hampton, VA, NASA Langley Research Center, Hampton, VA, USA USA Anthony J. Narkawicz Ariane Alves Almeida £ USA Department of Computer Science, Universidade de Brasília, Brazil Andréia B. Avelar da Silva Thiago M. Ferreira Ramos £ Faculdade de Planaltina, Universidade de Brasília, Department of Computer Science, Universidade Brazil de Brasília, Brazil Abstract This paper presents a formalization of several termination criteria for first-order recursive functions. The formalization, which is developed in the Prototype Verification System (PVS), includes the specification and proof of equivalence of semantic termination, Turing termination, sizechange principle, calling context graphs, and matrix-weighted graphs. These termination criteria are defined on a computational model that consists of a basic functional language called PVS0, which is an embedding of recursive first-order functions. Through this embedding, the native mechanism for checking termination of recursive functions in PVS could be soundly extended with semi-automatic termination criteria such as calling contexts graphs. 2012 ACM Subject Classification Theory of computation → Models of computation; Software and its engineering → Software verification; Computing methodologies → Theorem proving algorithms Keywords and phrases Formal Verification, Termination, Calling Context Graph, PVS Digital Object Identifier 10.4230/LIPIcs.ITP.2021.26 Supplementary Material Other (NASA PVS Library): https://github.com/nasa/pvslib Funding Mariano M. Moscato: corresponding author; research supported by the National Aeronaut- ics and Space Administration under NASA/NIA Cooperative Agreement NNL09AA00A.
    [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]
  • Synthesising Interprocedural Bit-Precise Termination Proofs
    Synthesising Interprocedural Bit-Precise Termination Proofs Hong-Yi Chen, Cristina David, Daniel Kroening, Peter Schrammel and Bjorn¨ Wachter Department of Computer Science, University of Oxford, fi[email protected] Abstract—Proving program termination is key to guaranteeing does terminate with mathematical integers, but does not ter- absence of undesirable behaviour, such as hanging programs and minate with machine integers if n equals the largest unsigned even security vulnerabilities such as denial-of-service attacks. To integer. On the other hand, the following code: make termination checks scale to large systems, interprocedural termination analysis seems essential, which is a largely unex- void foo2 ( unsigned x ) f while ( x>=10) x ++; g plored area of research in termination analysis, where most effort has focussed on difficult single-procedure problems. We present does not terminate with mathematical integers, but terminates a modular termination analysis for C programs using template- with machine integers because unsigned machine integers based interprocedural summarisation. Our analysis combines a wrap around. context-sensitive, over-approximating forward analysis with the A second challenge is to make termination analysis scale to inference of under-approximating preconditions for termination. Bit-precise termination arguments are synthesised over lexico- larger programs. The yearly Software Verification Competition graphic linear ranking function templates. Our experimental (SV-COMP) [6] includes a division in termination analysis, results show that our tool 2LS outperforms state-of-the-art alter- which reflects a representative picture of the state-of-the-art. natives, and demonstrate the clear advantage of interprocedural The SV-COMP’15 termination benchmarks contain challeng- reasoning over monolithic analysis in terms of efficiency, while ing termination problems on smaller programs with at most retaining comparable precision.
    [Show full text]
  • Unfailing Haskell
    The University of York Department of Computer Science Programming Languages and Systems Group Unfailing Haskell Qualifying Dissertation 30th June 2005 Neil Mitchell 2 Abstract Programs written in Haskell may fail at runtime with either a pattern match error, or with non-termination. Both of these can be thought of as giving the value ⊥ as a result. Other forms of failure, for example heap exhaustion, are not considered. The first section of this document reviews previous work, including total functional programming and sized types. Attention is paid to termination checkers for both Prolog and various functional languages. The main result from work so far is a static checker for pattern match errors that allows non-exhaustive patterns to exist, yet ensures that a pattern match error does not occur. It includes a constraint language that can be used to reason about pattern matches, along with mechanisms to propagate these constraints between program components. The proposal deals with future work to be done. It gives an approximate timetable for the design and implementation of a static checker for termination and pattern match errors. 1 Contents 1 Introduction 4 1.1 Total Programming . 4 1.2 Benefits of Totality . 4 1.3 Drawbacks of Totality . 5 1.4 A Totality Checker . 5 2 Field Survey and Review 6 2.1 Background . 6 2.1.1 Bottom ⊥ ........................................... 6 2.1.2 Normal Form . 7 2.1.3 Laziness . 7 2.1.4 Higher Order . 8 2.1.5 Peano Numbers . 8 2.2 Static Analysis . 8 2.2.1 Data Flow Analysis . 9 2.2.2 Constraint Based Analysis .
    [Show full text]
  • Termination Analysis with Compositional Transition Invariants*
    Termination Analysis with Compositional Transition Invariants? Daniel Kroening1, Natasha Sharygina2;4, Aliaksei Tsitovich2, and Christoph M. Wintersteiger3 1 Oxford University, Computing Laboratory, UK 2 Formal Verification and Security Group, University of Lugano, Switzerland 3 Computer Systems Institute, ETH Zurich, Switzerland 4 School of Computer Science, Carnegie Mellon University, USA Abstract. Modern termination provers rely on a safety checker to con- struct disjunctively well-founded transition invariants. This safety check is known to be the bottleneck of the procedure. We present an alter- native algorithm that uses a light-weight check based on transitivity of ranking relations to prove program termination. We provide an exper- imental evaluation over a set of 87 Windows drivers, and demonstrate that our algorithm is often able to conclude termination by examining only a small fraction of the program. As a consequence, our algorithm is able to outperform known approaches by multiple orders of magnitude. 1 Introduction Automated termination analysis of systems code has advanced to a level that permits industrial application of termination provers. One possible way to obtain a formal argument for termination of a program is to rank all states of the pro- gram with natural numbers such that for any pair of consecutive states si; si+1 the rank is decreasing, i.e., rank(si+1) < rank(si). In other words, a program is terminating if there exists a ranking function for every program execution. Substantial progress towards the applicability of procedures that compute ranking arguments to industrial code was achieved by an algorithm called Binary Reachability Analysis (BRA), proposed by Cook, Podelski, and Rybalchenko [1].
    [Show full text]
  • Dynamic Extension of Typed Functional Languages
    Dynamic Extension of Typed Functional Languages Don Stewart PhD Dissertation School of Computer Science and Engineering University of New South Wales 2010 Supervisor: Assoc. Prof. Manuel M. T. Chakravarty Co-supervisor: Dr. Gabriele Keller Abstract We present a solution to the problem of dynamic extension in statically typed functional languages with type erasure. The presented solution re- tains the benefits of static checking, including type safety, aggressive op- timizations, and native code compilation of components, while allowing extensibility of programs at runtime. Our approach is based on a framework for dynamic extension in a stat- ically typed setting, combining dynamic linking, runtime type checking, first class modules and code hot swapping. We show that this framework is sufficient to allow a broad class of dynamic extension capabilities in any statically typed functional language with type erasure semantics. Uniquely, we employ the full compile-time type system to perform run- time type checking of dynamic components, and emphasize the use of na- tive code extension to ensure that the performance benefits of static typing are retained in a dynamic environment. We also develop the concept of fully dynamic software architectures, where the static core is minimal and all code is hot swappable. Benefits of the approach include hot swappable code and sophisticated application extension via embedded domain specific languages. We instantiate the concepts of the framework via a full implementation in the Haskell programming language: providing rich mechanisms for dy- namic linking, loading, hot swapping, and runtime type checking in Haskell for the first time. We demonstrate the feasibility of this architecture through a number of novel applications: an extensible text editor; a plugin-based network chat bot; a simulator for polymer chemistry; and xmonad, an ex- tensible window manager.
    [Show full text]
  • A Flexible Approach to Termination with General Recursion
    Termination Casts: A Flexible Approach to Termination with General Recursion Aaron Stump Vilhelm Sj¨oberg Stephanie Weirich Computer Science Computer and Information Science Computer and Information Science The University of Iowa University of Pennsylvania University of Pennsylvania [email protected] [email protected] [email protected] This paper proposes a type-and-effect system called Teq↓, which distinguishes terminating terms and total functions from possibly diverging terms and partial functions, for a lambda calculus with general recursion and equality types. The central idea is to include a primitive type-form “Terminates t”, expressing that term t is terminating; and then allow terms t to be coerced from possibly diverging to total, using a proof of Terminates t. We call such coercions termination casts, and show how to implement terminating recursion using them. For the meta-theory of the system, we describe a translation from Teq↓ to a logical theory of termination for general recursive, simply typed functions. Every typing judgment of Teq↓ is translated to a theorem expressing the appropriate termination property of the computational part of the Teq↓ term. 1 Introduction Soundly combining general recursion and dependent types is a significant current challenge in the design of dependently typed programming languages. The two main difficulties raised by this combination are (1) type-equivalence checking with dependent types usually depends on term reduction, which may fail to terminate in the presence of general recursion; and (2) under the Curry-Howard isomorphism, non- terminating recursions are interpreted as unsound inductive proofs, and hence we lose soundness of the type system as a logic.
    [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]
  • Proving Conditional Termination
    Proving Conditional Termination Byron Cook1, Sumit Gulwani1, Tal Lev-Ami2,?, Andrey Rybalchenko3,??, and Mooly Sagiv2 1 Microsoft Research 2 Tel Aviv University 3 MPI-SWS Abstract. We describe a method for synthesizing reasonable underap- proximations to weakest preconditions for termination—a long-standing open problem. The paper provides experimental evidence to demonstrate the usefulness of the new procedure. 1 Introduction Termination analysis is critical to the process of ensuring the stability and us- ability of software systems, as liveness properties such “Will Decode() always return back to its call sites?” or “Is every call to Acquire() eventually followed by a call to Release()?” can be reduced to a question of program termina- tion [8,22]. Automatic methods for proving such properties are now well studied in the literature, e.g. [1,4,6,9,16]. But what about the cases in which code only terminates for some inputs? What are the preconditions under which the code is still safe to call, and how can we automatically synthesize these conditions? We refer to these questions as the conditional termination problem. This paper describes a method for proving conditional termination. Our method is based on the discovery of potential ranking functions—functions over program states that are bounded but not necessarily decreasing—and then finding preconditions that promote the potential ranking functions into valid ranking functions. We describe two procedures based on this idea: PreSynth, which finds preconditions to termination, and PreSynthPhase, which extends PreSynth with the ability to identify the phases necessary to prove the termi- nation of phase-transition programs [3].
    [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]