Application of Model-Driven Engineering and Metaprogramming to DEVS Modeling & Simulation

Total Page:16

File Type:pdf, Size:1020Kb

Application of Model-Driven Engineering and Metaprogramming to DEVS Modeling & Simulation Application of Model-Driven Engineering and Metaprogramming to DEVS Modeling & Simulation Luc Touraille To cite this version: Luc Touraille. Application of Model-Driven Engineering and Metaprogramming to DEVS Model- ing & Simulation. Other. Université Blaise Pascal - Clermont-Ferrand II, 2012. English. NNT : 2012CLF22308. tel-00914327 HAL Id: tel-00914327 https://tel.archives-ouvertes.fr/tel-00914327 Submitted on 5 Dec 2013 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. D.U.: 2308 E.D.S.P.I.C: 594 Ph.D. Thesis submitted to the École Doctorale des Sciences pour l’Ingénieur to obtain the title of Ph.D. in Computer Science Submitted by Luc Touraille Application of Model-Driven Engineering and Metaprogramming to DEVS Modeling & Simulation Thesis supervisors: Prof. David R.C. Hill Dr. Mamadou K. Traoré Publicly defended on December 7th, 2012 in front of an examination committee composed of: Reviewers: Prof. Jean-Pierre Müller, Cirad, Montpellier Prof. Gabriel A. Wainer, Carleton University, Ottawa Supervisors: Prof. David R.C. Hill, Université Blaise Pascal, Clermont-Ferrand Dr. Mamadou K. Traoré, Université Blaise Pascal, Clermont- Ferrand Examiners Dr. Alexandre Muzy, Università di Corsica Pasquale Paoli, Corte Prof. Bernard P. Zeigler, University of Arizona, Tucson D.U.: 2308 E.D.S.P.I.C: 594 Ph.D. Thesis submitted to the École Doctorale des Sciences pour l’Ingénieur to obtain the title of Ph.D. in Computer Science Submitted by Luc Touraille Application of Model-Driven Engineering and Metaprogramming to DEVS Modeling & Simulation Thesis supervisors: Prof. David R.C. Hill Dr. Mamadou K. Traoré Publicly defended on December 7th, 2012 in front of an examination committee composed of: Reviewers: Prof. Jean-Pierre Müller, Cirad, Montpellier Prof. Gabriel A. Wainer, Carleton University, Ottawa Supervisors: Prof. David R.C. Hill, Université Blaise Pascal, Clermont-Ferrand Dr. Mamadou K. Traoré, Université Blaise Pascal, Clermont- Ferrand Examiners Dr. Alexandre Muzy, Università di Corsica Pasquale Paoli, Corte Prof. Bernard P. Zeigler, University of Arizona, Tucson Abstract The multiplication of software environments supporting DEVS Modeling & Simulation is becoming a hindrance to scientific collaboration. Indeed, the use of disparate tools in the community makes the exchange, reuse and comparison of models very difficult, preventing practitioners from building on previous works to devise models of ever-increasing complexity. Tool interoperability is not the only issue raised by the need for models of higher and higher complexity. As models grow, their development becomes more error-prone, and their simulation becomes more resource-consuming. Consequently, it is necessary to devise techniques for improving simulators performance and for providing thorough model verification to assist the practitioner during model design. In this thesis, we propose two innovative approaches for DEVS Modeling & Simulation that tackle the aforementioned issues. The first contribution described in this document is a model-driven environment for modeling systems with the DEVS formalism, named SimStudio. This environment relies on Model-Driven Engineering to provide a high-level framework where practitioners can create, edit and visualize models, and automatically generate multiple artifacts, most notably model specifications compatible with various DEVS simulators. The core of SimStudio is a platform-independent metamodel of the DEVS formalism, which provides a pivot format for DEVS models. Based on this metamodel, we developed several model verification features as well as many model transformations that can be used to automatically generate documentation, diagrams or code targeting various DEVS platforms. Thus, SimStudio gives a proof of concept of the integration capabilities that a DEVS standard would provide; as a matter of fact, the metamodel presented in this thesis could possibly serve as a basis for such a standard. The second contribution of this thesis is DEVS-MetaSimulator (DEVS-MS), a DEVS library relying on metaprogramming to generate simulation executables that are specialized and optimized for the model they handle. To do so, the library performs many computations during compilation, resulting in a simulation code where most overhead have been eliminated. The tests we conducted showed that the generated programs were very 5 efficient, but the performance gain is not the only feature of DEVS-MS. Indeed, through metaprogramming, DEVS-MS can also assert the correctness of models by verifying model characteristics at compile-time, detecting and reporting modeling errors very early in the development cycle and with better confidence than what could be achieved with classical testing. Keywords: DEVS, Modeling & Simulation, Model-Driven Engineering, Metaprogramming 6 Résumé La multiplication des environnements logiciels pour la Modélisation & Simulation DEVS pose un problème de collaboration à la communauté scientifique. En effet, l'utilisation d'outils disparates rend l'échange, la réutilisation et la comparaison de modèles très difficiles, empêchant les scientifiques de s'appuyer sur des travaux précédents pour construire leurs modèles. L'interopérabilité des outils n'est pas le seul problème soulevé par le besoin de modèles toujours plus complexes. Au fur et à mesure que les modèles grossissent, leur développement devient plus difficile, notamment en termes de détection des erreurs de conception. D'autre part, la simulation de ces modèles demande de plus en plus de ressources. Par conséquent, il est nécessaire de concevoir des techniques pour améliorer la performance des simulateurs et pour fournir des fonctionnalités de vérification de modèle afin d'assister les scientifiques dans la conception de leurs modèles. Dans cette thèse, nous proposons deux approches innovantes pour la M&S DEVS qui s'attaquent aux problèmes susmentionnés. La première contribution décrite dans ce document est un environnement basé sur les modèles pour modéliser des systèmes avec le formalisme DEVS, intitulé SimStudio. Cet environnement repose sur l'Ingénierie Dirigée par les Modèles pour fournir un cadriciel de haut niveau dans lequel les scientifiques peuvent créer, éditer et visualiser des modèles, et générer automatiquement un ensemble d’artefacts, notamment des spécifications de modèles compatibles avec différents simulateurs DEVS. Le noyau de SimStudio est un métamodèle de DEVS, indépendant de toute plateforme, qui fournit un format pivot pour la représentation des modèles DEVS. En se basant sur ce métamodèle, nous avons développé plusieurs fonctionnalités de vérification de modèle ainsi que plusieurs transformations de modèle pouvant être utilisées pour générer automatiquement de la documentation, des diagrammes ou du code ciblant diverses plateformes DEVS. Ainsi, SimStudio fournit une preuve de concept des capacités d’intégration qu’un standard DEVS pourrait fournir ; en fait, le métamodèle présenté dans cette thèse pourrait potentiellement servir de base de réflexion pour un tel standard. 7 La seconde contribution de cette thèse est DEVS-MetaSimulateur (DEVS-MS), une bibliothèque DEVS qui utilise la métaprogrammation pour générer des exécutables de simulation spécialisés et optimisés pour le modèle qu’ils traitent. Pour ce faire, la bibliothèque effectue un grand nombre d’opérations durant la compilation, résultant en un code de simulation où une grande partie de l’overhead de simulation a été éliminé. Les tests que nous avons effectués ont montré que les programmes générés étaient très efficaces, mais le gain de performance n’est pas la seule caractéristique intéressante de DEVS-MS. En effet, grâce à la métaprogrammation, DEVS-MS peut également partiellement vérifier à la compilation que les modèles sont corrects, c’est-à-dire que leurs caractéristiques sont bien conformes au formalisme DEVS. Les erreurs de modélisation sont ainsi détectées et signalées très tôt dans le cycle de développement, et avec un taux de détection bien meilleur que ne le permettrait des tests classiques. Mots-clés : DEVS, Modélisation & Simulation, Ingénierie Dirigée par les Modèles, Métaprogrammation 8 Acknowledgments/Remerciements First of all, I would like to thank Jean-Pierre, Gabriel and Bernie for their accessibility and of course for doing me the honor of being part of my committee. J’adresse également un grand merci à l’enthousiaste Lisandru, non seulement pour m’avoir fait découvrir la beauté de Cargese mais aussi pour les multiples collaborations que nous avons pu effectuer ensemble, et les trop peu nombreuses soirées que nous avons partagés. Ce travail n’aurait bien sûr pas été possible sans l’indefectible soutien de Benny et Mams, qui ont su me guider durant ces années tout en me laissant une grande liberté. Chaque discussion avec Mamadou aura été une source d’inspiration pour mes travaux, et de bonne humeur pour ma journée (notamment grâce à ce sourire communicatif qui le caractérise !). Quant à Benny, je n’aurais probablement jamais fini cette thèse sans son « coaching » (en
Recommended publications
  • 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]
  • Executable Formal Specifications in Game Development
    TIMO NUMMENMAA Executable Formal Specifications in Game Development Design, Validation and Evolution ACADEMIC DISSERTATION To be presented, with the permission of the Board of the School of Information Sciences of the University of Tampere, for public discussion in the Auditorium A1 of the Main Building, Kalevantie 4, Tampere, on November 30th, 2013, at 12 o’clock. UNIVERSITY OF TAMPERE ACADEMIC DISSERTATION University of Tampere, School of Information Sciences Finland Copyright ©2013 Tampere University Press and the author Cover design by Mikko Reinikka Acta Universitatis Tamperensis 1875 Acta Electronica Universitatis Tamperensis 1356 ISBN 978-951-44-9275-4 (print) ISBN 978-951-44-9276-1 (pdf) ISSN-L 1455-1616 ISSN 1456-954X ISSN 1455-1616 http://tampub.uta.fi Suomen Yliopistopaino Oy – Juvenes Print Tampere 2013 Abstract Games provide players with enjoyment, escapism, unique experiences and even a way to socialise. Software based games played on electronic devices such as computers and games consoles are a huge business that is still growing. New games are con- tinually developed as demand for these digital games is high. Digital games are often complex and have high requirements for quality. The complexity is especially ap- parent in complex multiplayer games and games that are constantly evolving. This complexity can be problematic in various stages of development. For example, under- standing if a design of a game works as intended can be difficult. Managing changes that need to be made to a game during its lifetime, even after its initial release, is also challenging from both a design and an implementation standpoint. In this thesis these problems are addressed by presenting a method of utilising formal methods for simulations of game designs as a way of development, commu- nication, documentation and design.
    [Show full text]
  • Answer Set Programming
    ANSWER SET PROGRAMMING Tran Cao Son Department of Computer Science New Mexico State University Las Cruces, NM 88011, USA [email protected] http://www.cs.nmsu.edu/~tson October 2005 Answer Set Programming. Acknowledgement This tutorial contains some materials from tutorials on answer set programming and on knowledge representation and logic programming from those provided by • Chitta Baral, available at www.public.asu.edu/~cbaral. • Michael Gelfond, available at www.cs.ttu.ued/~mgelfond. Tran Cao Son 1 Answer Set Programming. Introduction — Answer Set Programming Answer set programming is a new programming paradigm. It is introduced in the late 90’s and manages to attracts the intention of different groups of researchers thanks to its: • declarativeness: programs do not specify how answers are computed; • modularity: programs can be developed incrementally; • expressiveness: answer set programming can be used to solve problems in high 2 complexity classes (e.g. ΣP , Π2P , etc.) Answer set programming has been applied in several areas: reasoning about actions and changes, planning, configuration, wire routing, phylogenetic inference, semantic web, information integration, etc. Tran Cao Son 2 Answer Set Programming. Purpose • Introduce answer set programming • Provide you with some initial references, just in case • ...you get excited about answer set programming Tran Cao Son 3 Answer Set Programming. Outline • Foundation of answer set programming: logic programming with answer set semantics (syntax, semantics, early application). • Answer set programming: general ideas and examples • Application of answer set programming in – Knowledge representation – Constraint satisfaction problem – Combinatoric problems – Reasoning about action and change – Planning and diagnostic reasoning • Current issues Tran Cao Son 4 LOGIC PROGRAMMING AND ANSWER SET SEMANTICS Answer Set Programming.
    [Show full text]
  • Action Language for Foundational UML (Alf) Concrete Syntax for a UML Action Language Version 1.1 ______
    An OMG® Action Language for Foundational UML™ Publication Action Language for Foundational UML (Alf) Concrete Syntax for a UML Action Language Version 1.1 ____________________________________________________ OMG Document Number: formal/2017-07-04 Date: July 2017 Normative reference: http://www.omg.org/spec/ALF/1.1 Machine readable file(s): Normative: http://www.omg.org/spec/ALF/20170201/Alf-Syntax.xmi http://www.omg.org/spec/ALF/20170201/Alf-Library.xmi http://www.omg.org/spec/ALF/20120827/ActionLanguage-Profile.xmi ____________________________________________________ Copyright © 2010-2013 88solutions Corporation Copyright © 2013 Commissariat à l’Energie Atomique et aux Energies Alternatives (CEA) Copyright © 2010-2017 Data Access Technologies, Inc. (Model Driven Solutions) Copyright © 2010-2013 International Business Machines Copyright © 2010-2013 Mentor Graphics Corporation Copyright © 2010-2013 No Magic, Inc. Copyright © 2010-2013 Visumpoint Copyright © 2010-2017 Object Management Group USE OF SPECIFICATION - TERMS, CONDITIONS & NOTICES The material in this document details an Object Management Group specification in accordance with the terms, conditions and notices set forth below. This document does not represent a commitment to implement any portion of this specification in any company's products. The information contained in this document is subject to change without notice. LICENSES The companies listed above have granted to the Object Management Group, Inc. (OMG) a nonexclusive, royalty- free, paid up, worldwide license to copy and distribute this document and to modify this document and distribute copies of the modified version. Each of the copyright holders listed above has agreed that no person shall be deemed to have infringed the copyright in the included material of any such copyright holder by reason of having used the specification set forth herein or having conformed any computer software to the specification.
    [Show full text]
  • Planning in Action Language BC While Learning Action Costs for Mobile Robots
    Planning in Action Language BC while Learning Action Costs for Mobile Robots Piyush Khandelwal, Fangkai Yang, Matteo Leonetti, Vladimir Lifschitz and Peter Stone Department of Computer Science The University of Texas at Austin 2317 Speedway, Stop D9500 Austin, TX 78712, USA fpiyushk,fkyang,matteo,vl,[email protected] Abstract 1999). Furthermore, the action language BC (Lee, Lifschitz, and Yang 2013) can easily formalize recursively defined flu- The action language BC provides an elegant way of for- ents, which can be useful in robot task planning. malizing dynamic domains which involve indirect ef- fects of actions and recursively defined fluents. In com- The main contribution of this paper is a demonstration plex robot task planning domains, it may be necessary that the action language BC can be used for robot task for robots to plan with incomplete information, and rea- planning in realistic domains, that require planning in the son about indirect or recursive action effects. In this presence of missing information and indirect action effects. paper, we demonstrate how BC can be used for robot These features are necessary to completely describe many task planning to solve these issues. Additionally, action complex tasks. For instance, in a task where a robot has to costs are incorporated with planning to produce opti- collect mail intended for delivery from all building residents, mal plans, and we estimate these costs from experience the robot may need to visit a person whose location it does making planning adaptive. This paper presents the first not know. To overcome this problem, it can plan to complete application of BC on a real robot in a realistic domain, its task by asking someone else for that person’s location, which involves human-robot interaction for knowledge acquisition, optimal plan generation to minimize navi- thereby acquiring this missing information.
    [Show full text]
  • REBA: a Refinement-Based Architecture for Knowledge Representation and Reasoning in Robotics
    Journal of Artificial Intelligence Research 65 (2019) 1-94 Submitted 10/2018; published 04/2019 REBA: A Refinement-Based Architecture for Knowledge Representation and Reasoning in Robotics Mohan Sridharan [email protected] School of Computer Science University of Birmingham, UK Michael Gelfond [email protected] Department of Computer Science Texas Tech University, USA Shiqi Zhang [email protected] Department of Computer Science SUNY Binghamton, USA Jeremy Wyatt [email protected] School of Computer Science University of Birmingham, UK Abstract This article describes REBA, a knowledge representation and reasoning architecture for robots that is based on tightly-coupled transition diagrams of the domain at two different levels of granu- larity. An action language is extended to support non-boolean fluents and non-deterministic causal laws, and used to describe the transition diagrams, with the domain’s fine-resolution transition diagram being defined as a refinement of the coarse-resolution transition diagram. The coarse- resolution system description, and a history that includes prioritized defaults, are translated into an Answer Set Prolog (ASP) program. For any given goal, inference in the ASP program provides a plan of abstract actions. To implement each such abstract action, the robot automatically zooms to the part of the fine-resolution transition diagram relevant to this action. A probabilistic representa- tion of the uncertainty in sensing and actuation is then included in this zoomed fine-resolution sys- tem description, and used to construct a partially observable Markov decision process (POMDP). The policy obtained by solving the POMDP is invoked repeatedly to implement the abstract ac- tion as a sequence of concrete actions, with the corresponding observations being recorded in the coarse-resolution history and used for subsequent coarse-resolution reasoning.
    [Show full text]
  • C++ Metastring Library and Its Applications⋆
    C++ Metastring Library and its Applications! Zal´anSz˝ugyi, Abel´ Sinkovics, Norbert Pataki, and Zolt´anPorkol´ab Department of Programming Languages and Compilers, E¨otv¨osLor´andUniversity P´azm´any P´eter s´et´any 1/C H-1117 Budapest, Hungary {lupin, abel, patakino, gsd}@elte.hu Abstract. C++ template metaprogramming is an emerging direction of generative programming: with proper template definitions wecanenforce the C++ compiler to execute algorithms at compilation time. Template metaprograms have become essential part of today’s C++ programs of industrial size; they provide code adoptions, various optimizations, DSL embedding, etc. Besides the compilation time algorithms, template metaprogram data-structures are particularly important. From simple typelists to more advanced STL-like data types there are a variety of such constructs. Interesting enough, until recently string, as one of the most widely used data type of programming, has not been supported. Al- though, boost::mpl::string is an advance in this area, it still lacks the most fundamental string operations. In this paper, we analysed the pos- sibilities of handling string objects at compilation time with a metastring library. We created a C++ template metaprogram library that provides the common string operations, like creating sub-strings, concatenation, replace, and similar. To provide real-life use-cases we implemented two applications on top of our Metastring library. One use case utilizes com- pilation time inspection of input in the domain of pattern matching al- gorithms, thus we are able to select the more optimal search method at compilation time. The other use-case implements safePrint, a type-safe version of printf –awidelyinvestigatedproblem.Wepresentboththe performance improvements and extended functionality we haveachieved in the applications of our Metastring library.
    [Show full text]
  • 13 Templates-Generics.Pdf
    CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 – 5 Gilad Bracha, Generics in the Java Programming Language Questions • If subtyping and inheritance are so great, why do we need type parameterization in object- oriented languages? • The great polymorphism debate – Subtype polymorphism • Apply f(Object x) to any y : C <: Object – Parametric polymorphism • Apply generic <T> f(T x) to any y : C Do these serve similar or different purposes? Outline • C++ Templates – Polymorphism vs Overloading – C++ Template specialization – Example: Standard Template Library (STL) – C++ Template metaprogramming • Java Generics – Subtyping versus generics – Static type checking for generics – Implementation of Java generics Polymorphism vs Overloading • Parametric polymorphism – Single algorithm may be given many types – Type variable may be replaced by any type – f :: tt => f :: IntInt, f :: BoolBool, ... • Overloading – A single symbol may refer to more than one algorithm – Each algorithm may have different type – Choice of algorithm determined by type context – Types of symbol may be arbitrarily different – + has types int*intint, real*realreal, ... Polymorphism: Haskell vs C++ • Haskell polymorphic function – Declarations (generally) require no type information – Type inference uses type variables – Type inference substitutes for variables as needed to instantiate polymorphic code • C++ function template – Programmer declares argument, result types of fctns – Programmers
    [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]