Spoon: a Library for Implementing Analyses and Transformations Of

Total Page:16

File Type:pdf, Size:1020Kb

Spoon: a Library for Implementing Analyses and Transformations Of Spoon: A Library for Implementing Analyses and Transformations of Java Source Code Renaud Pawlak, Martin Monperrus, Nicolas Petitprez, Carlos Noguera, Lionel Seinturier To cite this version: Renaud Pawlak, Martin Monperrus, Nicolas Petitprez, Carlos Noguera, Lionel Seinturier. Spoon: A Library for Implementing Analyses and Transformations of Java Source Code. Software: Practice and Experience, Wiley, 2015, 46, pp.1155-1179. 10.1002/spe.2346. hal-01078532v2 HAL Id: hal-01078532 https://hal.inria.fr/hal-01078532v2 Submitted on 12 Sep 2015 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. Distributed under a Creative Commons Attribution - ShareAlike| 4.0 International License Spoon: A Library for Implementing Analyses and Transformations of Java Source Code Renaud Pawlak Martin Monperrus Nicolas Petitprez Carlos Noguera Lionel Seinturier Abstract This article presents Spoon, a library for the analysis and transfor- mation of Java source code. Spoon enables Java developers to write a large range of domain-specific analyses and transformations in an easy and concise manner. Spoon analyses and transformations are written in plain Java. With Spoon, developers do not need to dive into parsing, to hack a compiler infrastructure, or to master a new formalism. 1 Introduction Compilers and interpreters analyze source code. But source code analysis is used in many more places [6]: it is used to compute metrics [17], to detect bad smells [18], to detect code clones [20]. Companies and open-source projects set up their own metrics and coding conventions [16]. This motivates a library for source code analysis that is usable by the masses of developers and not dedicated to compiler hackers. Beyond source code analysis, there is source code transformation. Source code transformation is a program transformation at the source code level, as opposed to program transformation done on binary code [8]. There are many usages of program transformation: profiling [41], security [11], optimization [28], refactoring [24]. As source code analysis, some source code transformations are written by normal Java developers. For instance, this happens when the transformation uses domain-specific knowledge [5]. This article presents Spoon, a library for the analysis and transformation of Java source code. Spoon enables Java developers to write a large range of domain-specific analyses and transformations in an easy and concise manner. Spoon analyses and transformations are written in plain Java. With Spoon, developers do not need diving to parse, to hack a compiler infrastructure, or to master a new formalism. The main features of Spoon are: 1. a Java metamodel for representing Java abstract syntax trees (AST) which is both easy to understand and easy to manipulate; 2. a first-class intercession programming interface (intercession API) to mod- ify and generate Java source code; 3. the use of generic typing for static checking of the analyses and transfor- mations; 1 4. the native and seamless integration and processing of Java annotations; 5. a pure Java statically-checked templating engine. Taking these features all together, Spoon is unique for the following reasons. Feature #1 and #2 are not the focus of compiler infrastructures. We are not aware of leveraging generics for AST manipulation (Feature #3). Java anno- tations have been extensively discussed [14] but generic annotation processors are scarce (Feature #4). While many templating engines exists (e.g. Apache Velocity1), none provide static checking as our plain Java templates provide. The related work section5 deepens those points. This paper supersedes INRIA technical report #5901 [36], which has been completely rewritten. It contains a better explanation of the concepts using appropriate illustrative examples, the evaluation contains a section of the cor- rectness of Spoon as well as three new case studies, and the related work is thoroughly analyzed (including the most recent papers). This article reads as follows. Section2 discusses the foundations of source code analysis in Spoon (the metamodel and the queries). Section3 presents our mechanisms for transforming source code. Section4 exposes case studies of fruitful usages of Spoon. Section5 discusses the related work. Section6 concludes and discusses future work. 2 Source Code Analysis with Spoon The first goal of Spoon is to enable standard developers to write their own domain-specific analyses on source code. This requires: first, an intuitive meta- model understandable by the mass of Java developers (presented in Section 2.2), second, mechanisms to analyze source code elements. The latter is embodied by queries (Section 2.3) and processors for traversing the program under analysis (Section 2.4). But let us first give an overview of the library before going into the details of the Java metamodel of Spoon. Spoon is a meta-analysis tool, it provides software engineers with the primi- tives to write their own analyses. As such, Spoon does not any specific analysis such as dataflow analysis. 2.1 Overview of Spoon Figure1 gives the overview of our approach. A Java program is given as in- put. It is parsed with an off-the-shelf compiler in order to produce a first abstract syntax tree (AST). Then, Spoon simplifies the AST (deleting and cre- ating nodes), in order to provide users with an intuitive and easy-to-manipulate model of their program. This compile-time (CT) model is an instance of the Spoon metamodel. The analysis and transformation of programs are written as “program processors” and “templates”. A user-defined processor performs a specific action, such as a transformation on a kind of node, under a well-defined processing condition. The processing and templating engine takes them as input and applies them to the Java model as long as elements remain to be processed. Eventually, the Spoon model is translated back to source with a pretty-printer. 1http://velocity.apache.org 2 Java Program (source code) Processors for Analysis & Transformation Parsing Low-Level Abstract Syntactic Tree AST Simplification Processing & instance Spoon Java Model Spoon Meta-Model Templating Engine Java Syntax Printing Transformed Java Program Figure 1: Overview of Spoon: Java Programs are transformed and analyzed as models of the Spoon Java metamodel.. This pretty printer preserves API comments and removed in-body comments (because they are not part of the metamodel). 2.2 The Spoon Metamodel of Java A programming language can have different metamodels. An abstract syntax tree (AST) or model, is an instance of a metamodel. Each metamodel – and consequently each AST – is more or less appropriate depending on the task at hand. In this paper, we focus on Java and consequently on Java metamodels. For instance, the Java metamodel of Sun’s compiler (javac) has been designed and optimized for compilation to bytecode, while, the main purpose of the Java metamodel of the Eclipse IDE (JDT) is to support different tasks of software development in an integrated manner (code completion, quick fix of compilation errors, debug, etc.). Unlike a compiler-based AST (e.g. from javac), the Spoon metamodel of Java is designed to be easily understandable by normal Java developers, so that they can write their own program analyses and transformations. The Spoon metamodel is complete in the sense that it contains all the required information to derive compilable and executable Java programs (hence contains annotations, generics, and method bodies). The Spoon metamodel can be split in three parts. The structural part (Figure2) contains the declarations of the program elements, such as interface, class, variable, method, annotation, and enum declarations. The code part (Figure3) contains the executable Java code, such as the one found in method bodies. The reference part models the references to program elements (for instance a reference to a type). As shown in Figure2, all elements inherit from CtElement which declares a parent element denoting the containment relation in the source file. For instance, the parent of a method node is a class node. All names are prefixed by “CT” 3 Figure 2: Excerpt of the structural part of the Spoon Java 5 metamodel. which means “compile-time”. Figure3 shows the metamodel for Java executable code. Because of the complexity of the Java language, the code metamodel figure contains only an excerpt of all classes. There are two main kinds of code elements. First, the statements (CtStatement) are untyped top-level instructions that can be used directly in a block of code. Second, the expressions (CtExpression) are used inside the statements (for sake of readability, this can not be seen on the figure). For instance, a CtLoop (which is a statement) points to a CtExpression which expresses its boolean condition. Some code elements such as invocations and assignments are both statements and expressions (multiple inheritance links). Concretely, this is translated as an interface CtInvocation inheriting from both interfaces CtStatement and CtExpression. The generic type of CtExpression is used to add static type-checking when transforming programs. This will be explained in details in Section 3.2. The reference part of the metamodel expresses the fact that program refer- ences elements that are not necessarily reified into the metamodel (they may belong to third party libraries). For instance, an expression node returning a String is bound to a type reference to String and not to the compile-time model of String.java since the source code of String is (usually) not part of the application code under analysis. In other terms, references are used by meta- model elements to reference elements in a weak way.
Recommended publications
  • Advanced-Java.Pdf
    Advanced java i Advanced java Advanced java ii Contents 1 How to create and destroy objects 1 1.1 Introduction......................................................1 1.2 Instance Construction.................................................1 1.2.1 Implicit (Generated) Constructor.......................................1 1.2.2 Constructors without Arguments.......................................1 1.2.3 Constructors with Arguments........................................2 1.2.4 Initialization Blocks.............................................2 1.2.5 Construction guarantee............................................3 1.2.6 Visibility...................................................4 1.2.7 Garbage collection..............................................4 1.2.8 Finalizers...................................................5 1.3 Static initialization..................................................5 1.4 Construction Patterns.................................................5 1.4.1 Singleton...................................................6 1.4.2 Utility/Helper Class.............................................7 1.4.3 Factory....................................................7 1.4.4 Dependency Injection............................................8 1.5 Download the Source Code..............................................9 1.6 What’s next......................................................9 2 Using methods common to all objects 10 2.1 Introduction...................................................... 10 2.2 Methods equals and hashCode...........................................
    [Show full text]
  • Plugin Tapestry ​
    PlugIn Tapestry ​ Autor @picodotdev https://picodotdev.github.io/blog-bitix/ 2019 1.4.2 5.4 A tod@s l@s programador@s que en su trabajo no pueden usar el framework, librería o lenguaje que quisieran. Y a las que se divierten programando y aprendiendo hasta altas horas de la madrugada. Non gogoa, han zangoa Hecho con un esfuerzo en tiempo considerable con una buena cantidad de software libre y más ilusión en una región llamada Euskadi. PlugIn Tapestry: Desarrollo de aplicaciones y páginas web con Apache Tapestry @picodotdev 2014 - 2019 2 Prefacio Empecé El blog de pico.dev y unos años más tarde Blog Bitix con el objetivo de poder aprender y compartir el conocimiento de muchas cosas que me interesaban desde la programación y el software libre hasta análisis de los productos tecnológicos que caen en mis manos. Las del ámbito de la programación creo que usándolas pueden resolver en muchos casos los problemas típicos de las aplicaciones web y que encuentro en el día a día en mi trabajo como desarrollador. Sin embargo, por distintas circunstancias ya sean propias del cliente, la empresa o las personas es habitual que solo me sirvan meramente como satisfacción de adquirir conocimientos. Hasta el día de hoy una de ellas es el tema del que trata este libro, Apache Tapestry. Para escribir en el blog solo dependo de mí y de ninguna otra circunstancia salvo mi tiempo personal, es com- pletamente mío con lo que puedo hacer lo que quiera con él y no tengo ninguna limitación para escribir y usar cualquier herramienta, aunque en un principio solo sea para hacer un ejemplo muy sencillo, en el momento que llegue la oportunidad quizá me sirva para aplicarlo a un proyecto real.
    [Show full text]
  • An Easy-To-Use Toolkit for Efficient Java Bytecode Translators
    An Easy-to-Use Toolkit for Efficient Java Bytecode Translators Shigeru Chiba Muga Nishizawa Dept. of Mathematical and Computing Sciences Tokyo Institute of Technology Email: {chiba,muga}@csg.is.titech.ac.jp Abstract. This paper presents our toolkit for developing a Java-bytecode translator. Bytecode translation is getting important in various domains such as generative programming and aspect-oriented programming. To help the users easily develop a translator, the design of our toolkit is based on the reflective architecture. However, the previous implementa- tions of this architecture involved serious runtime penalties. To address this problem, our toolkit uses a custom compiler so that the runtime penalties are minimized. Since the previous version of our toolkit named Javassist has been presented in another paper, this paper focuses on this new compiler support for performance improvement. This feature was not included in the previous version. 1 Introduction Since program translators are key components of generative programming [5], a number of translator toolkits have been developed. For the Java language, some toolkits like EPP [9] and OpenJava [18] allow developers to manipulate a parse tree or an abstract syntax tree for source-level translation. Other toolkits, such as BCEL [6], JMangler [13], and DataScript [1], allow manipulating a class file, which is a compiled binary, for bytecode-level translation. The ease of use and the power of expressiveness are design goals of these toolkits. The latter goal means what kinds of translation are enabled. The former goal is often sacrificed for the latter one. The bytecode-level translation has two advantages against the source-level translation.
    [Show full text]
  • Aspect-Oriented Programming
    Beyond OOP Advanced Separation of Concerns Metaprogramming Reflection Aspect-Oriented Programming Eric Tanter DCC/CWR University of Chile [email protected] Éric Tanter – U.Chile [june | 2005] 1 Contents ● A brief history of programming ● Advanced modularization problems ● Reflection and metaprogramming ● Aspect-oriented programming Éric Tanter – U.Chile [june | 2005] 2 Part I A Quick History of Programming Adapted from Brian Hayes, “The Post-OOP Paradigm”, American Scientist, 91(2), March-April 2003, pp. 106-110 Éric Tanter – U.Chile [june | 2005] 3 Software? ● Real challenge: building the machine ● Software was not important as such ● First programs (40's) ● Written in pure binary: 0s and 1s ● Explicit memory address management Éric Tanter – U.Chile [june | 2005] 4 Then came the assembly... ● Assembly language ● No more raw binary codes ● Symbols: load, store, add, sub ● Converted to a binary program by an assembler ● Calculates memory addresses ● First program to help programming Éric Tanter – U.Chile [june | 2005] 5 ...and then, compilers ● Assembly required knowledge of the specific computer instruction set ● Higher-level languages (e.g. Fortran) ● Think in terms of variables/equations ● Not registers/addresses ● 60's: big projects = late/costly/buggy Éric Tanter – U.Chile [june | 2005] 6 Structured Programming ● Manifesto by Edsger W. Dijkstra: “Go to statement considered harmful” [1968] ● Build programs out of sub-units ● Single entrance point, single exit ● 3 constructs: ● Sequencing, alternation, and iteration ● Proof that
    [Show full text]
  • Middleware Architecture with Patterns and Frameworks
    Middleware Architecture with Patterns and Frameworks Sacha Krakowiak Distributed under a Creative Commons license http://creativecommons.org/licenses/by-nc-nd/3.0/ February 27, 2009 Contents Preface ix References........................................ x 1 An Introduction to Middleware 1-1 1.1 Motivation for Middleware . 1-1 1.2 CategoriesofMiddleware . 1-6 1.3 A Simple Instance of Middleware: Remote Procedure Call . ......... 1-7 1.3.1 Motivations and Requirements . 1-8 1.3.2 Implementation Principles . 1-9 1.3.3 Developing Applications with RPC . 1-11 1.3.4 SummaryandConclusions. .1-13 1.4 Issues and Challenges in Middleware Design . 1-14 1.4.1 DesignIssues ...............................1-14 1.4.2 Architectural Guidelines . 1-15 1.4.3 Challenges ................................1-17 1.5 HistoricalNote .................................. 1-18 References........................................1-19 2 Middleware Principles and Basic Patterns 2-1 2.1 ServicesandInterfaces . 2-1 2.1.1 Basic Interaction Mechanisms . 2-2 2.1.2 Interfaces ................................. 2-3 2.1.3 Contracts and Interface Conformance . 2-5 2.2 ArchitecturalPatterns . 2-9 2.2.1 Multilevel Architectures . 2-9 2.2.2 DistributedObjects . .. .. .. .. .. .. .. .2-12 2.3 Patterns for Distributed Object Middleware . 2-15 2.3.1 Proxy ...................................2-15 2.3.2 Factory ..................................2-16 2.3.3 Adapter..................................2-18 2.3.4 Interceptor ................................2-19 2.3.5 Comparing and Combining Patterns . 2-20 2.4 Achieving Adaptability and Separation of Concerns . ..........2-21 2.4.1 Meta-ObjectProtocols. 2-21 2.4.2 Aspect-Oriented Programming . 2-23 ii CONTENTS 2.4.3 PragmaticApproaches. .2-25 2.4.4 ComparingApproaches .
    [Show full text]
  • Polymorphic Bytecode Instrumentation
    SOFTWARE: PRACTICE AND EXPERIENCE Softw. Pract. Exper. 2016; 46:1351–1380 Published online 18 December 2015 in Wiley Online Library (wileyonlinelibrary.com). DOI: 10.1002/spe.2385 Polymorphic bytecode instrumentation Walter Binder1,*,†, Philippe Moret1, Éric Tanter2 and Danilo Ansaloni1 1Faculty of Informatics, Università della Svizzera Italiana (USI), Lugano, Switzerland 2PLEIAD Lab, Computer Science Department (DCC), University of Chile, Santiago, Chile SUMMARY Bytecode instrumentation is a widely used technique to implement aspect weaving and dynamic analyses in virtual machines such as the Java virtual machine. Aspect weavers and other instrumentations are usu- ally developed independently and combining them often requires significant engineering effort, if at all possible. In this article, we present polymorphic bytecode instrumentation (PBI), a simple but effective tech- nique that allows dynamic dispatch amongst several, possibly independent instrumentations. PBI enables complete bytecode coverage, that is, any method with a bytecode representation can be instrumented. We illustrate further benefits of PBI with three case studies. First, we describe how PBI can be used to imple- ment a comprehensive profiler of inter-procedural and intra-procedural control flow. Second, we provide an implementation of execution levels for AspectJ, which avoids infinite regression and unwanted interference between aspects. Third, we present a framework for adaptive dynamic analysis, where the analysis to be performed can be changed at runtime by the user. We assess the overhead introduced by PBI and provide thorough performance evaluations of PBI in all three case studies. We show that pure Java profilers like JP2 can, thanks to PBI, produce accurate execution profiles by covering all code, including the core Java libraries.
    [Show full text]
  • University of South Wales Abbey Bookbinding Unit 3, Gabalfa Workshops Oat Menter Excelsior Ind
    University of South Wales Abbey Bookbinding Unit 3, Gabalfa Workshops Oat Menter Excelsior Ind. Estate 2059469 CardiffCFI43AY Tel:+44 (0)29 2062 3290 Fax:+44 (0)29 20625420 E: [email protected] www.abbeybookbinding.co.uk A Domain-Specific Aspect Language Approach to Distributed Systems Development Paul Soule Department of Computing and Mathematical Sciences University of Glamorgan A submission presented in partial fulfilment of the requirements of the University of Glamorgan/Prifysgol Morgannwg for the degree of Doctor of Philosophy August 2008 Abstract Distributed applications are difficult to write. Programmers need to adhere to specific distributed systems programming conventions and frameworks, which makes distributed systems development complex and error prone and ties the resultant application to the distributed system because the appli­ cation's code is tangled with the crosscutting concern distribution. Existing mainstream programming languages, such as Java, do not pro­ vide language support for distribution. Rather, programmers must rely on object-oriented distribution frameworks to provide distribution support. Although highly successful, the cost of using these frameworks is that the resultant code is tied to the framework. Object-oriented frameworks in gen­ eral, and distribution frameworks in particular, can therefore be considered crosscutting in nature because the framework's code, either via inheritance or containment, is scattered throughout the application's code thereby tying the application to the framework. This is a particular concern in distributed systems development because dis­ tribution frameworks impose a large code overhead due to the requirements distributed systems impose, such as the need to catch distribution-specific exceptions, locating and binding to distributed objects, locating another server in the event the current server becomes unavailable, and adhering to programming conventions dictated by the framework, such as implementing framework specific interfaces.
    [Show full text]
  • Secure Method Calls by Instrumenting Bytecode with Aspects
    Secure Method Calls by Instrumenting Bytecode with Aspects Xiaofeng Yang and Mohammad Zulkernine School of Computing, Queen’s University Kingston, Ontario, Canada, K7L 3N6 {yang,mzulker}@cs.queensu.ca Abstract. Today most mobile devices embed Java runtime environ- ment for Java programs. Java applications running on mobile devices are mainly MIDP (Mobile Information Device Profile) applications. They can be downloaded from the Internet and installed directly on the device. Although the virtual machine performs type-safety checking or verifies bytecode with signed certificates from third-party, the program still has the possibility of containing risky code. Inappropriate use of sensitive method calls may cause loss of personal assets on mobile devices. More- over, source code is not accessible for most installed applications, making it difficult to analyze the behavior at source-code level. To better protect the device from malicious code, we propose an approach of bytecode in- strumentation with aspects at bytecode level. The instrumentation pin- points the location of statements within methods, rather than at the interface of method calls. The aspects are woven around the statement for tracking. The weaving is performed at bytecode level without requir- ing source code of the program. Keywords: Bytecode instrumentation, aspects, code security. 1 Introduction Mobile technology is very popular nowadays. More and more applications are running on mobile devices such as cellphones and PDAs, etc. Mobile code can easily migrate from one site to another, and even to a personal cellphone. Java applications are popularly running on mobile devices that embed Java Runtime Environments. User’s information may be at risk as they are not usually aware of the programs they are running on their devices, for example, the unauthorized SMS (Short Message Service) sending programs [1] can be executed without any authorization of a user.
    [Show full text]
  • Code Instrumentation with Mod-BEAM
    1 Computer Science Code instrumentation with Mod-BEAM Roman Rinke Armando Wiedijk MSc. Thesis July 18, 2019 Supervisors: dr. A. Fehnker prof.dr.ir. M. Aksit External Supervisor: prof.dr. C. Bockisch Formal Methods and Tools Faculty of Electrical Engineering, Faculty of Mathematics Mathematics and Computer Science and Computer Science University of Twente Philipps University of Marburg P.O. Box 217 35037 Marburg 7500 AE Enschede Germany The Netherlands Abstract There are various methods and techniques for a developer to keep their code read- able and reusable. Design patterns have become important in modern development in order to realise this. There exists code, however, that you would not want in pro- duction. An example of this would be code that is generated by instrumentation tools. Tools might want to generate code to help create performance benchmarks, or to analyse the code-coverage of your test-cases. ”Code instrumentation” is a term commonly used to describe the task of adding such generated code. What we focus on in this thesis is code-instrumentation for Java projects. When a Java file is compiled, the compiler outputs a .class file with the low-level instructions that the Java Virtual Machine can execute. Java code instrumentation can be performed on the actual source-code (before compiling) or on the bytecode itself (after compiling). Multiple frameworks that allow for Java bytecode instrumen- tation. Some of these frameworks are a bit dated, but they all share the common interest to allow for easy, fast and maintainable bytecode manipulation. From the hypothesis that existing tools that make use of bytecode instrumenta- tion have potential overlap, the tool ”Mod-BEAM” is introduced.
    [Show full text]
  • Slides Revision: 20190923-Ea7c311
    Will it blend? Java agents and OSGi Slides revision: 20190923-ea7c311 1 Welcome 2 About me 3 Outline Quick demo Java agents primer Usage scenarios OSGi integration Integration testing Testing demo 4 Quick demo 5 Java agents primer 6 Java instrumentation APIs Provides services that allow Java programming language agents to instrument programs running on the JVM. java.lang.instrument Javadoc, Java SE 8 7 Static agents # loaded at application startup $ java -javaagent:agent.jar -jar app.jar Premain-Class: org.example.my.Agent import java.lang.instrument.*; public class Agent { public static void premain(String args,⏎ Instrumentation inst) { inst.addTransformer(new ClassFileTransformer() { /* implementation elided */ }); } } 8 Dynamic agents // dynamically attached to a running JVM VirtualMachine vm = VirtualMachine.attach(vmPid); vm.loadAgent(agentFilePath); vm.detach(); Agent-Class: org.example.my.Agent import java.lang.instrument.*; public class Agent { public static void agentmain(String args,⏎ Instrumentation inst) { inst.addTransformer(new ClassFileTransformer() { /* implementation elided */ }); } } 9 Class transformation public interface ClassFileTransformer { byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException; } 10 Java bytecode public static void main(java.lang.String[]); Code: 0: getstatic #16⏎ // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #22⏎ // String Hello, world 5: invokevirtual #24⏎ //
    [Show full text]
  • Runtime Code Generation for Interpreted Domain-Specific Modeling Languages
    Proceedings of the 2018 Winter Simulation Conference M. Rabe, A. A. Juan, N. Mustafee, A. Skoogh, S. Jain, and B. Johansson, eds. RUNTIME CODE GENERATION FOR INTERPRETED DOMAIN-SPECIFIC MODELING LANGUAGES Tom Meyer Tobias Helms Tom Warnke Adelinde M. Uhrmacher Institute of Computer Science University of Rostock Albert-Einstein-Straße 22 18059 Rostock, GERMANY ABSTRACT Domain-specific modeling languages (DSMLs) facilitate concise and succinct model descriptions. DSMLs are commonly realized by defining a custom grammar and executing models in an interpreter. This provides flexibility in language design as well as in the implementation of simulation algorithms. However, this type of implementation can lead to a negative impact on simulation performance in comparison to implementing models in general-purpose programming languages (GPL). To mitigate this problem, we propose using runtime code generation. This allows us to replace specific parts of a model at runtime by compiling generated GPL source code. In this paper, we demonstrate the potential benefit of this concept based on ML-Rules, a DSML for modeling and simulating biochemical reaction networks. Using code generation for arithmetic expressions in ML-Rules’ reaction rate functions, we were able to decrease the runtime by up to 40% in complex application scenarios. 1 INTRODUCTION The development of a novel modeling method typically includes a software implementation of the method. One successful approach is to define domain-specific modeling languages (DSMLs) tailored to a specific application domain (Miller et al. 2010). Carefully designed DSMLs are powerful tools and enable modelers to efficiently develop succinct and accessible implementations of complex models. Especially in comparison to general-purpose programming languages (GPLs), using DSMLs results in more readable and compact model definitions.
    [Show full text]
  • Type-Safe Java Bytecode Modification Library Based on Javassist
    TALLINN UNIVERSITY OF TECHNOLOGY Faculty of Information Technology Institute of Computer Science Chair of Theoretical Informatics Type-safe Java bytecode modification library based on Javassist Bachelor thesis Student: Sven Laanela Student code: IAPB020471 Advisor: Pavel Grigorenko Tallinn 2015 I declare that this thesis is the result of my own research except as cited in the references. The thesis has not been accepted for any degree and is not concurrently submitted in candidature of any other degree. Signature Name Sven Laanela Date May 26, 2015 Abstract Dynamic (runtime) Java bytecode modification enables various fra- meworks to greatly enhance Java programs. They can provide logging, caching, dependency injection, object-relational mapping, etc. with- out cluttering the application source code, or even when the source code is not available. Existing Java bytecode modification libraries do not provide compile-time type safety or IDE-assisted code completion capabilities with regard to the class under modification. This thesis researches a problem of type-safe Java bytecode modification, build- ing on top of Javassist { a Java bytecode modification library { and taking into consideration the most common Java bytecode modifica- tion use-cases. Scenarios implemented in Javassist are described and an alternative approach that implements those scenarios in a type-safe manner is proposed. An implementation library is presented as proof of concept for the proposed approach to Java bytecode modification. An analysis of the applicability of the approach is provided, outlining both the benefits and trade-offs when compared to Javassist. Annotatsioon D¨unaamiline(s.t. rakenduse t¨o¨otamiseaegne) Java baitkoodi muut- mine v~oimaldaboluliselt t¨aiendadaJava rakendusi ilma l¨ahtekoodi ris- ustamata.
    [Show full text]