institutionen för datavetenskap - diva...

74
Institutionen för datavetenskap Department of Computer and Information Science Master’s Thesis Extending Modelica with High-Level Data Structures: Design and Implementation in OpenModelica Simon Björklén Reg Nr: LIU-IDA/LITH-EX-A--08/030--SE Linköping 2008 Department of Computer and Information Science Linköpings universitet SE-581 93 Linköping, Sweden

Upload: others

Post on 04-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Institutionen för datavetenskapDepartment of Computer and Information Science

Master’s Thesis

Extending Modelica with High-Level DataStructures: Design and Implementation in

OpenModelica

Simon Björklén

Reg Nr: LIU-IDA/LITH-EX-A--08/030--SELinköping 2008

Department of Computer and Information ScienceLinköpings universitet

SE-581 93 Linköping, Sweden

Page 2: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 3: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Institutionen för datavetenskapDepartment of Computer and Information Science

Master’s Thesis

Extending Modelica with High-Level DataStructures: Design and Implementation in

OpenModelica

Simon Björklén

Reg Nr: LIU-IDA/LITH-EX-A--08/030--SELinköping 2008

Supervisor: Adrian Popida, Linköpings universitet

Examiner: Peter Fritzsonida, Linköpings universitet

Department of Computer and Information ScienceLinköpings universitet

SE-581 93 Linköping, Sweden

Page 4: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 5: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Avdelning, InstitutionDivision, Department

PELABDepartment of Computer and Information ScienceLinköpings universitetSE-581 83 Linköping, Sweden

DatumDate

2008-06-12

SpråkLanguage

� Svenska/Swedish� Engelska/English

RapporttypReport category

� Licentiatavhandling� Examensarbete� C-uppsats� D-uppsats� Övrig rapport�

URL för elektronisk version

http://urn.kb.se/resolve?urn=urn:nbn:se:liu:diva-12148

ISBN—

ISRNLIU-IDA/LITH-EX-A--08/030--SE

Serietitel och serienummerTitle of series, numbering

ISSN—

TitelTitle

Extending Modelica with High-Level Data Structures: Design and Implementationin OpenModelicaExtending Modelica with High-Level Data Structures: Design and Implementationin OpenModelica

FörfattareAuthor

Simon Björklén

SammanfattningAbstract

Modelica is an equation-based object-oriented language (EOO). PELAB atLinköping University along with the OpenModelica development group, is devel-oping a meta-modeling extension, MetaModelica, to this language along with acompiler called the OpenModelica Compiler (OMC).

The goal of this thesis was to analyze the compiler, extend it with union typesupport and then write a report about the extension with union types in particularand extension with high level data structures in general, to facilitate further devel-opment. The implementation made by this thesis was implemented with the goalof keeping the current structure intact and extending case-clauses where possible.

The main parts of the extension is implemented by this thesis work but someparts concerning the pattern matching algorithms are still to be extended. Themain goal of this is to bootstrap the OpenModelica Compiler, making it able tocompile itself although this is still a goal for the future.

With this thesis I also introduce some guidelines for implementing a new high-level data structure into the compiler and which modules needs extension.

NyckelordKeywords Modelica, MetaModelica, RML, OpenModelica, High-Level Data Structures

Page 6: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 7: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

AbstractModelica is an equation-based object-oriented language (EOO). PELAB at LinköpingUniversity along with the OpenModelica development group, is developing a meta-modeling extension, MetaModelica, to this language along with a compiler calledthe OpenModelica Compiler (OMC).

The goal of this thesis was to analyze the compiler, extend it with union typesupport and then write a report about the extension with union types in particularand extension with high level data structures in general, to facilitate further devel-opment. The implementation made by this thesis was implemented with the goalof keeping the current structure intact and extending case-clauses where possible.

The main parts of the extension is implemented by this thesis work but someparts concerning the pattern matching algorithms are still to be extended. Themain goal of this is to bootstrap the OpenModelica Compiler, making it able tocompile itself although this is still a goal for the future.

With this thesis I also introduce some guidelines for implementing a new high-level data structure into the compiler and which modules needs extension.

v

Page 8: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 9: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Acknowledgments

I would like to thank Peter Fritzson for making this thesis work possible, AdrianPop for support and help during the whole process and Kristian Stavåker for allhis help, helping me getting started, solving all sorts of problems and pointing mein the right direction when I got stuck. Without you this thesis would not hadbeen finished!

vii

Page 10: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 11: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Contents

1 Introduction 11.1 Intended Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Thesis Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Thesis Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.4.1 Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4.2 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4.3 Design and Implementation . . . . . . . . . . . . . . . . . . 3

2 Background 52.1 Modelica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 RML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2.1 Where to Get the RML-Compiler? . . . . . . . . . . . . . . 82.3 MetaModelica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.3.1 Union Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.3.2 Match-Expressions . . . . . . . . . . . . . . . . . . . . . . . 11

2.4 OpenModelica Compiler . . . . . . . . . . . . . . . . . . . . . . . . 122.4.1 Environment Structure . . . . . . . . . . . . . . . . . . . . . 122.4.2 Translation Stages . . . . . . . . . . . . . . . . . . . . . . . 132.4.3 An Overview of the Compiler . . . . . . . . . . . . . . . . . 142.4.4 A Simplified Version of the Main Function of the Compiler 142.4.5 Parse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4.6 SCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4.7 Inst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4.8 Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.4.9 RTOpts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.4.10 Codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.4.11 DAELow and SimCodeGen . . . . . . . . . . . . . . . . . . 152.4.12 C-Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.4.13 Where to Get the Most Current Version? . . . . . . . . . . 16

2.5 MDT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.5.1 Where to Get the Modelica Development Tooling? . . . . . 17

ix

Page 12: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

x Contents

3 Design and Implementation 193.1 A Short Overview of the Extended Modules . . . . . . . . . . . . . 203.2 The Front-End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.2.1 Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.2.2 Absyn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.2.3 SCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2.4 Inst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.2.5 Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.2.6 Static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.2.7 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293.2.8 Prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.2.9 Patternm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.2.10 DAE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.2.11 Exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.2.12 ClassInf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.3 The Back-End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3.1 Codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3.2 C-Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4 Guidelines for Implementing a New High-Level Data Structure 41

5 Discussion and Related Work 475.1 Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475.2 Performance Measurements . . . . . . . . . . . . . . . . . . . . . . 475.3 Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.4 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.4.1 Getting Union Types and Lists to Work in MatchcontinueExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.4.2 Getting Rid of the RML-Compiler . . . . . . . . . . . . . . 485.4.3 Extending the Comments of the OpenModelica Compiler . 49

6 Conclusions 516.1 Accomplishments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Bibliography 53

A An Overview of the Compiler 55

B Extending the Compiler With a New Type 57

Index 59

Page 13: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

List of Code Examples2.1 A Trivial Modelica Program . . . . . . . . . . . . . . . . . . . . . . 62.2 A Small Expression Evaluator . . . . . . . . . . . . . . . . . . . . . 82.3 The Eval Relation . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.4 A Factorial Program Written in RML . . . . . . . . . . . . . . . . 92.5 A Union Type Declaration . . . . . . . . . . . . . . . . . . . . . . . 92.6 A Union Type Definition Along With Its Matchcontinue Elabora-

tion Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.7 A Simplified Version of the Main Function of the Compiler . . . . 142.8 Some of the Available Data Structure Constructors in the C-Runtime 163.1 Introduction of the Absyn.R_METARECORD . . . . . . . . . . . 223.2 Code Added to SCode . . . . . . . . . . . . . . . . . . . . . . . . . 243.3 AST Union Type Example . . . . . . . . . . . . . . . . . . . . . . . 253.4 Code Extensions to Inst . . . . . . . . . . . . . . . . . . . . . . . . 273.5 Code Extensions to Lookup . . . . . . . . . . . . . . . . . . . . . . 283.6 Example of METARECORDCALL Creation . . . . . . . . . . . . . 293.7 Code Extensions to Static . . . . . . . . . . . . . . . . . . . . . . . 303.8 Extensions to Types . . . . . . . . . . . . . . . . . . . . . . . . . . 313.9 Extensions to the Prefix Module . . . . . . . . . . . . . . . . . . . 323.10 Code Extensions to the DAE Module . . . . . . . . . . . . . . . . . 333.11 Code Extensions to the Exp Module . . . . . . . . . . . . . . . . . 343.16 The typedef Added to modelica.h . . . . . . . . . . . . . . . . . . . 353.12 Generating the Variable Type String . . . . . . . . . . . . . . . . . 363.13 generateSimpleType . . . . . . . . . . . . . . . . . . . . . . . . . . 373.14 generateExpression . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.15 Example of Generated Code . . . . . . . . . . . . . . . . . . . . . . 39

List of Figures2.1 The dependencies between RML, MetaModelica, Modelica and the

OpenModelica Compiler . . . . . . . . . . . . . . . . . . . . . . . . 52.2 plot(x) on the HelloWorld Example . . . . . . . . . . . . . . . . . . 62.3 A Schema of a GTX Gas Turbine Power Cutoff Mechanism Modeled

in MathModelica by MathCore [2] . . . . . . . . . . . . . . . . . . 72.4 An Overview of the OpenModelica Environment Structure . . . . . 122.5 The Different Translation Stages From Modelica Code to Simulation 132.6 MDT in Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.1 An Overview of the Union Type Implementation . . . . . . . . . . 203.2 The New AST for Code 3.3 . . . . . . . . . . . . . . . . . . . . . . 25

A.1 An Overview of the Compiler . . . . . . . . . . . . . . . . . . . . . 56

B.1 Extending the Compiler With a New High-Level Datastructure . . 58

Page 14: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Chapter 1

Introduction

In this chapter I will give a brief introduction of this thesis, its prerequisites,outline and goals.

1.1 Intended AudienceTo get the most out of this report about extending Modelica with high level datastructures, the reader should preferably have some knowledge about the Model-ica programming language and the basics about constructing a compiler. SomeC/C++ terminology is also used in some parts of the thesis so some experience ofC/C++ programming is also preferred.

1.2 Thesis ContributionsCurrent equation-based object-oriented languages (EOO) lack support for high-level data structures. Without such support the EOO languages need to rely onexternal tool support or advanced integrated graphical environments (which areonly available commercially) to manipulate models or model data. We believe thatextending EOO with high-level data structures and functional meta-programmingconstructs will highly increase the power of these languages and decrease their tightcoupling and reliance on external tools and graphical environments. To validatethis idea we have extended the Modelica language with support for high-level datastructures. This thesis presents the design and the practical implementation ofthe proposed extension.

1

Page 15: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2 Introduction

1.3 Thesis OutlineThe following is a short outline of the thesis:• Chapter 2, Background - starts off with some background information aboutModelica, RML, MetaModelica, the OpenModelica Compiler and the Model-ica Development Tooling.

• Chapter 3, Design and Implementation - contains a thorough descriptionof the design and implementation of my OpenModelica extension for uniontypes.

• Chapter 4, Guidelines for Implementing a New High-Level Datastructure -contains some guidelines for implementing a new High-Level Datastructureinto the OpenModelica Compiler.

• Chapter 5, Discussion and Related Work - has a discussion about the im-plementation, how it was done, what could have be done differently and whatis left for the future.

• Chapter 6, Conclusions - contains some conclusions about the thesis workand what has been accomplished.

1.4 GoalThe main goal of this thesis work was to extend the OpenModelica Compiler tobe able to handle union types. However, to reach this goal some subgoals werenecessary.

1.4.1 LearningWhen starting the work of this thesis, the first thing necessary was to learn theMetaModelica programming language which was something completely new to me.I did a lot of programming exercises until I felt comfortable with the language.The OpenModelica Users Guide [11] along with Modelica Meta-Programming andSymbolic Transformations [9] gave me the essential information here. The nextstep was to obtain knowledge about the OpenModelica Compiler, how it was built,which modules were used where and to understand the flow of the compiler. TheOpenModelica System Documentation [10] helped me a lot with this. Next someknowledge about the connection between OpenModelica, MetaModelica, Modelica,RML and the C-Runtime was acquired by analyzing the code using the debuggerin MDT (see section 2.5 on page 17 for more information about MDT).

1.4.2 AnalysisThe next step was to analyze the features that were going to be implemented.This was to understand where to make the extensions, and how to do it. This wasactually quite a challenging part since the compiler consists of quite a few modules(almost 40) and a huge amount of code, making it hard to get "the whole picture".

Page 16: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

1.4 Goal 3

1.4.3 Design and ImplementationChoosing a design for the implementation was pretty much straight forward afterthe analysis step. The idea was to keep the structure of the compiler as much aspossible and make the extension in form of case-clause additions. This worked outperfectly in most cases and the resulting implementation is separated in almostevery module.

Page 17: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 18: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Chapter 2

Background

the OpenModelica Compiler

MetaModelica

Modelica RML

Figure 2.1. The dependencies between RML, MetaModelica, Modelica and the Open-Modelica Compiler

This chapter provides a short overview of the Modelica-programming language, theMetaModelica-programming language, the RML-programming language and theOpenModelica Compiler. To give a short overview of the dependency relation be-tween RML, MetaModelica, Modelica and the OpenModelica Compiler (fig. 2.1.):Modelica is an EOO language, MetaModelica a meta extension to Modelica withits compiler written in RML and the OpenModelica Compiler is an open sourcecompiler for Modelica (and a subset of MetaModelica) written in MetaModelica.

2.1 ModelicaModelica [3] is a modeling language used for simulation of complex systems. Whatmakes Modelica so powerful is the way you model systems. The entire system ismodeled using equations, e.g. to model a physical model, just pass the mathemat-ical equations, along with its start/stop values and then the simulation tools takes

5

Page 19: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

6 Background

care of the rest. This also leads to some other nice features:

• Since the behavior of a model in Modelica is specified by acausal equationsthe models can be used in different contexts and it is the job of the compilerto deduce the control flow from the use of the model. This leads to increasedreuse of the models.

Code 2.1 A Trivial Modelica Program

1 class HelloWorld "A s imple equa t ion "2 Real x ( s t a r t =1);3 equation4 der ( x)= −x ;5 end HelloWorld ;

A trivial Modelica program : Code 2.1 creates a class named HelloWorld witha variable x, which have the initial condition x(0)=1. The equation section thenlists the equations which have to be fulfilled. In this case, the derivative of xhas to be -x. To simulate this model in OpenModelica you just have to run:simulate(HelloWorld,stopTime=5), and to get a nice graph of how the value ofx varies over time simply type: plot(x)

The resulting graph is shown in fig. 2.2.

Figure 2.2. plot(x) on the HelloWorld Example

However, the real power of Modelica is not shown until you use it to modela complex system like the one in fig. 2.3, where each element in the schema

Page 20: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2.2 RML 7

corresponds to one Modelica-class.

Figure 2.3. A Schema of a GTX Gas Turbine Power Cutoff Mechanism Modeled inMathModelica by MathCore [2]

2.2 RMLNatural Semantics1 are quite popular among language designers when specifyingnew languages. The problem however, is that the translation from Natural Seman-tics form into executable code is quite exhausting, demanding, and has to be mademanually. This is what Mikael Pettersson realized back in 1995 and he specifiedRML [14, 13] , Relational Meta-Language, to allow easy translation from NaturalSemantics into efficient code.

Some features of RML:

• RML uses features from languages like SML (Standard ML) to allow strongtyping and datatype constructors.

• The RML compiler generates efficient C-Code which is compiled by an ordi-nary C compiler, e.g. generating an executable Modelica translator.

1A popularized style of specification developed by Gilles Kahn’s group at INRIA [14]

Page 21: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

8 Background

Code 2.2 shows a small expression evaluator, which "converts" a mathematicalexpression into the value of the expression.

Code 2.2 A Small Expression Evaluator

1 datatype Exp = NUMBER of r e a l2 | ADD of Exp ∗ Exp3 | MUL of Exp ∗ Exp

E.g. the expression

1 3∗(4+5)

gets translated into the following tree:

1 MUL(NUMBER(3 ) , ADD(NUMBER(4) ,NUMBER(5 ) )

After this, we describe the eval relation of the expression. This relation relatesexpressions to their evaluated values (see Code 2.3 )

Code 2.3 The Eval Relation

1 relation eva l =2 axiom eva l (NUMBER(x ) ) => x3

4 rule eva l ( x ) => x ’ & eva l ( y ) => y ’ &5 real_add (x ’ , y ’ ) => sum6 −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−7 eva l (ADD(x , y ) ) => sum8

9 rule eva l ( x ) => x ’ & eva l ( y ) => y ’ &10 real_mul (x ’ , y ’ ) => prod11 −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−12 eva l (MUL(x , y ) => prod13 end

Even though RML is mainly meant to be used as a specification language forother languages, it is also possible to use it as a functional language which is shownbelow. Code 2.4 shows a factorial program written in RML.

For more information about RML and its syntax, take a look at Developingefficient language implementations from structural and natural semantics [8] byPeter Fritzson and Compiling Natural Semantics [14] by Mikael Pettersson.

2.2.1 Where to Get the RML-Compiler?The most current version of the source code is always available from the RMLhomepage:

http://www.ida.liu.se/~pelab/rml/

Page 22: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2.3 MetaModelica 9

Code 2.4 A Factorial Program Written in RML

1 relation f a c : i n t => in t =2 rule −−−−−−−−−−−3 f a c (0 ) => 14

5 rule int_gt (n , 0) => true &6 int_sub (n , 1) => n2 &7 f a c ( n2 ) => re s2 &8 int_mult (n , r e s2 ) => r e s u l t9 −−−−−−−−−−−−−−−−−−−−−−−−−−−

10 f a c (n) => r e s u l t11 end

2.3 MetaModelicaTo be able to express the whole Modelica-language in Modelica (e.g. writinga Modelica compiler in Modelica) some extension of the language was required.PELAB made this extension with definitions written in RML and the result isknown as MetaModelica. Some of the necessary extensions were lists, union typesand match-expressions. [15]

2.3.1 Union TypeDeclaring a variable as a union type is like declaring a holder variable [6]. Thetype of the holder variable is a specification of a datastructure. This specificationconsists of a description of a set of values from which only one is active duringexecution.

Another way to see this is to think of the union type variable as a base classand all the types it can hold as classes extended from this base class.

Union types are widely used in the MetaModelica language.Code 2.5 shows a union type declaration and Code 2.6 a union type in use.

Code 2.5 A Union Type Declaration

1 uniontype UT2 record REC13 I n t eg e r in t1 ;4 Real re1 ;5 end REC1;6 record REC27 I n t eg e r in t2 ;8 I n t eg e r in t3 ;9 I n t eg e r in t4 ;

10 end REC2;11 end UT;

Page 23: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

10 Background

Code 2.6 A Union Type Definition Along With Its Matchcontinue ElaborationFunction

1 uniontype EXP2 record NUMBER3 I n t eg e r n ;4 end NUMBER5 record ADD6 EXP e1 ;7 EXP e2 ;8 end ADD;9 record MUL

10 EXP e1 ;11 EXP e2 ;12 end MUL;13 end EXP;14

15 function elabExp ;16 input EXP e ;17 output I n t eg e r out ;18 algorithm19 out := matchcontinue ( e )20 local21 I n t eg e r n1 , n2 ;22 EXP e1 , e2 ;23 case (NUMBER(n1 ) ) then n1 ;24 case (ADD( e1 , e2 ) )25 equation26 n1 = elabExp ( e1 ) ;27 n2 = elabExp ( e2 ) ;28 then n1 + n2 ;29 case (MULT( e1 , e2 ) )30 equation31 n1 = elabExp ( e1 ) ;32 n2 = elabExp ( e2 ) ;33 then n1 ∗ n2 ;34 end matchcontinue35 end elabExp ;

Page 24: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2.3 MetaModelica 11

2.3.2 Match-ExpressionsAnother important part of the MetaModelica extension is the support of match-continue expressions. A matchcontinue expression is similar to switch-statementsin C/C++ with some essential differences. A statement in Modelica can eitherreturn true, false or it may fail where a failure means the statement has failed.

A matchcontinue expression works as follows. First it switches over the case-clauses until it finds the first matching case-expression. Then it executes thestatements within that case-clause until it reaches the then-statement. The inter-esting part happens when a statement within a case fails. What happens in sucha case is that variables previously bounded to values within cases that failed getsroll-backed (reversed) and the search for another matching case-clause proceeds.Code 2.6 shows an example of a matchcontinue expression when used to elaboratean expression.

Page 25: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

12 Background

2.4 OpenModelica CompilerThe OpenModelica Compiler [10] (OMC) is a compiler for Modelica developedat PELAB (IDA, LiU). Most of the compiler is written in MetaModelica exceptexternal functions which are written in C-code. Most of the standard implementa-tion of Modelica is already handled by the compiler and the compiler is currentlybeing extended to handle the MetaModelica extensions as well. That is, addingsupport for lists, union types and match-expressions.

In this section a brief explanation of the the different parts of the compiler willbe given.

2.4.1 Environment StructureThe OpenModelica environment consists of several connected subsystems, shownin fig. 2.4.

Figure 2.4. An Overview of the OpenModelica Environment Structure

A brief explanation of some of the subsystems:

• Eclipse Plugin Editor/Browser - Used as an editor and debugger forModelica/MetaModelica development.

• Emacs Editor/Browser - Used as an editor for Modelica/MetaModelicadevelopment. - No longer supported.

• Interactive session handler - Handles the loading, simulation and plottingof a Modelica model.

• Modelica Compiler - Handles the compilation of Modelica-code to C-code.

• Modelica Debugger - Handles the debugging of Modelica/MetaModelicacode.

Page 26: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2.4 OpenModelica Compiler 13

• Graphical Model Editor/Browser - A graphical model editor, not reallya part of OpenModelica but it is integrated into the system and is availablefrom MathCore Engineering AB [2] without cost for academic use.

The subsystems also includes tools for building simulation executables linked witha given equation-solver, e.g. numerical ODE (Ordinary Differential Equation) orDAE (Differential Algebraic Equation) solvers. The default solver is currentlyDASSL, a differential algebraic equation solver developed by Linda Petzhold in1991 [5].

2.4.2 Translation StagesAs seen in fig. 2.5 the flow from Modelica until simulation is as follow. First theModelica source code-file is fed to the compiler and is, in the first stage, translatedinto a flat model. This stage includes type-checking, import statements, perform-ing object-oriented operations (such as inheritance, modifications etc.) and lookupstatements. The flat model includes a set of equations with its declarations andfunctions. This stage is a partial instantiation of the model, called the elaborationor instantiation stage. The next stages, the Analyzer-stage and the Optimizer-stage, are necessary for analyzing and optimizing models with equations. TheCode Generator stage generates the C-code for the model which is then compiledwith an ordinary C-compiler to produce executable code.

Figure 2.5. The Different Translation Stages From Modelica Code to Simulation

Page 27: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

14 Background

2.4.3 An Overview of the CompilerThe OpenModelica Compiler consists of almost 40 different modules. To under-stand the flow between the modules, take a look at fig. A.1. Note that the flowis not 100% accurate since some functions are used from many modules (e.g. thefunctions in the Dump module), and to show the flow of them all would just beconfusing.

2.4.4 A Simplified Version of the Main Function of the Com-piler

To get an idea of how the flow is controlled from the code, Code 2.7 shows asimplified version of the main function of the compiler.

Code 2.7 A Simplified Version of the Main Function of the Compiler

1 function main2 input St r ing f ; // f i l e name3 algorithm4 as t := Parser . parse ( f ) ;5 scode1 := SCode . e l abo ra t e ( a s t ) ;6 scode2 := In s t . e l abo ra t e ( scode1 ) ;7 dae1 := In s t . i n s t a n t i a t e ( scode2 ) ;8 dae2 := optimizeDae ( dae1 , scode2 ) ;9 simcodegen ( dae2 , scode2 ) ;

10 end main ;

2.4.5 ParseThis module is actually written in C and uses ANTLR [1] (ANother Tool for Lan-guage Recognition) to parse the modelica code and to construct an AST (AbstractSyntax Tree) with definitions from the Absyn module. This module is not reallya part of the OpenModelica developed compiler (external function call) but is animportant part which makes out the base for all the next compilation stages.

2.4.6 SCodeThis module converts the Absyn AST into SCode which is an intermediate form.This form is a little more simplified than the AST and groups together importantinformation into nodes.

2.4.7 InstThis is the most complex module. It takes care of instantiation of the code, typechecking, looking up names in the environment and builds new environments. Ascan be seen in fig. A.1 it calls many different modules and is an important part of

Page 28: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2.4 OpenModelica Compiler 15

the front-end. The output from this module is another intermediate form calledDAE. The purpose of introducing this form is to have a form which holds all thenecessary information which is needed for the code generation.

2.4.8 LookupThis module is responsible for the lookup mechanism. That is looking up classes,types, variables etc. in the environment by following the lookup rules.

2.4.9 RTOptsThis module handles different options passed to the compiler. The most fre-quently used function is the acceptMetaModelicaGrammar() which checks if theMetaModelica extension is allowed during compile time. Turning this flag off turnsoff most of the Meta extension case-clauses.

2.4.10 CodegenThis module takes ordinary Modelica functions (transformed into DAE form), andgenerates C-code.

2.4.11 DAELow and SimCodeGenGenerates code for solving equations and makes it possible to run a simulation oneverything. This part is a very important part of the compiler since it makes theequation-based language possible and this is what makes the Modelica languageso powerful.

2.4.12 C-RuntimeIn order to compile the generated C-Code some external C-modules exists to spec-ify the representation of the Modelica datatypes, reading/writing to files and tohandle the simulation environment. The simulation environment also contains anautomatic garbage-collector which constantly frees unused memory during simu-lation. Something worth mentioning are the special data struct definitions whichare necessary to make the garbage-collector handle the memory correctly (at leastthis is the goal in the future. At the moment there are some memory leaks whenusing mk_box functions.). Code 2.8 shows some of the available data structureconstructors.

For more information about the mk_box constructors take a look at section5.3 on page 48 where the generated code along with the mk_box constructor isdiscussed a little further.

Page 29: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

16 Background

Code 2.8 Some of the Available Data Structure Constructors in the C-Runtime

1 extern void ∗mmc_mk_nil(void ) ; //An empty data s t r u c t u r e2 extern void ∗mmc_mk_cons(void ∗ car , void ∗ cdr ) ; //Cons 2 data s t r u c t u r e s3 extern void ∗mmc_mk_box2(unsigned ctor , void ∗x0 , void ∗x1 ) ;4 // Holder f o r 1 index + 2 data s t r u c t u r e s5

6 extern void ∗mmc_mk_icon( int i ) ; // Holder f o r I n t e g e r7 extern void ∗mmc_mk_rcon(double d ) ; // Holder f o r a Real8 extern void ∗mmc_mk_scon(char ∗ s ) ; // Holder f o r a S t r i ng

2.4.13 Where to Get the Most Current Version?The most current version of the source code is always available from the Open-Modelica homepage:

http://www.openmodelica.org

Page 30: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

2.5 MDT 17

2.5 MDTMDT, or Modelica Development Tooling is an Eclipse-plugin developed by twomaster students a couple of years ago [12] . The goal of their project was to inte-grate the Modelica development environment into Eclipse to allow visual views ofModelica models and to create a less complex environment for debugging. Afterthe end of their thesis work, MDT has been extensively extended by Adrian Popat PELAB (IDA, LiU).

Some features of MDT are:

• Code completion

• Parenthesis matching

• Code coloring

• Automatic code indentation

• Visual browsing for Modelica projects, packages and classes

• Syntax checking

2.5.1 Where to Get the Modelica Development Tooling?This tool is highly recommended for OpenModelica development and is availablewithout cost at:

http://www.ida.liu.se/~pelab/modelica/OpenModelica/MDT/

Fig. 2.6 shows MDT in action.

Page 31: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

18 Background

Figure 2.6. MDT in Action

Page 32: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Chapter 3

Design and Implementation

One of the most challenging part about this thesis work was the analysis of theexisting code, to understand how to modify the code and where to do it. Since Idid not want to modify the existing code, unless I really had to, I tried to extend itby adding more matchcontinue case-clauses where possible. By doing it this way,the code for the union type implementation was separated as much as possiblefrom the existing code which will make it easier to extend the compiler furtherlater on.

In this chapter I will explain the changes I made to all the different modulesprior to making the compiler generate the necessary code for handling the uniontype variables in a simulation environment. For comments about implementationof other data structures take a look at the next chapter.

19

Page 33: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

20 Design and Implementation

3.1 A Short Overview of the Extended Modules

Parser

Absyn

SCode

Inst

Lookup Static Types Prefix Patternm DAE Exp ClassInf

Codegen

Generated C-Code

MetaUtilModelica Source Code

Figure 3.1. An Overview of the Union Type Implementation

Fig. 3.1 shows an overview of the union type implementaton and below is a list ofthe extended modules with a brief explanation:

• Parse - extend the parser to handle the union type keyword (external usingANTLR).

• Absyn - add the necessary tree nodes for R_UNIONTYPE and R_METARECORD.

• SCode - add the necessary intermediate nodes for R_UNIONTYPE and R_METARECORDand extend the AST for union types to contain METARECORDs as well.

• Inst - handle variable declarations of union types.

• Lookup - handle variable lookups of union types.

• Static - handle METARECORDs as function calls.

• Types - code for typechecking union types.

• Prefix - add prefixes to expressions containing METARECORDCALLs.

• Patternm - handle union types as input to matchcontinue expressions.

Page 34: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.1 A Short Overview of the Extended Modules 21

• DAE - add the necessary DAE nodes for UNIONTYPEs and METARECORDs.

• Exp - add the necessary expression node to handle METARECORDCALLs.

• Codegen - generate C-code.

• MetaUtil - helper functions explicit for Modelica extensions.

Page 35: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

22 Design and Implementation

3.2 The Front-EndThe following modules are a part of the front-end of the compiler [7], that is theanalysis part of the compiler which creates the intermediate code to be used as abase for the back-end.

3.2.1 ParserThe parsing process is done with ANTLR [1] so I will not go into any detail aboutthis. For more information about this process take a look at the source code in

<omc-root>/Compiler/absyn_builder/

<omc-root>/modelica_parser

and the ANTLR documentation.

http://www.antlr2.org/doc/index.html

3.2.2 AbsynTo be able to reuse the existing code for looking up names etc. I Introduced a newrestriction type called R_METARECORD (see Code 3.1). This restriction is a totallyinternal one and is defined as a record which holds the name of the union type asa path and an integer which holds the index of the record in the union type. Thisindex number is crucial for pattern matching and fetching data out of a union typelater on.

Note: From now on, when I talk about METARECORDs, I refer to the recordswithin a union type.

Code 3.1 Introduction of the Absyn.R_METARECORD

1 uniontype Re s t r i c t i o n2 // . . . Lots o f r e s t r i c t i o n d e f i n i t i o n s . . .

3 record R_UNIONTYPE4 end R_UNIONTYPE;5 record R_METARECORD6 Path name ; //Name o f the uniontype7 I n t eg e r index ; // Index in the uniontype8 end R_METARECORD;

1 // . . . more r e s t r i c t i o n d e f i n i t i o n s2 end Re s t r i c t i o n ;

Page 36: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.2 The Front-End 23

3.2.3 SCodeThe most important change to this module is the introduction of R_METARECORDand R_UNIONTYPE, and the changes made to the function elaborate. As can beseen in Code 3.2, elabClass now has a case clause which elaborates the classand executes the function MetaUtil.createMetaClasses on it before continuing.Some minor changes were also made to elabRestricton to allow the restrictionsR_METARECORD and R_UNIONTYPE to exist.

Page 37: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

24 Design and Implementation

Code 3.2 Code Added to SCode

1 uniontype Re s t r i c t i o n2 // . . . Lots o f r e s t r i c t i o n d e f i n i t i o n s . . .

3 record R_METARECORD4 Absyn . Path name ; //Name o f the union type5 I n t eg e r index ; // Index in the union type6 end R_METARECORD;7 record R_UNIONTYPE end R_UNIONTYPE;

8 // . . . more r e s t r i c t i o n d e f i n i t i o n s . . .9 end Re s t r i c t i o n ;

10

11 public function e l abo ra t e " f unc t i on : e l a b o r a t e12

13 This function takes an ‘Absyn . Program\ ’ and con s t ru c t s a ‘ Program\ ’14 from i t .15 "16 input Absyn . Program inProgram ;17 output Program outProgram ;18 algorithm19 outProgram:=20 matchcontinue ( inProgram )21 local22 Class c_1 ;23 Program cs_1 ;24 Absyn . Class c ;25 l i s t <Absyn . Class> cs , cs2 ;26 Absyn . Within w;27 Absyn . Program p ;28 case (Absyn .PROGRAM( c l a s s e s = {})) then {} ;29 case (Absyn .PROGRAM( c l a s s e s = ( c : : c s ) , within_ = w) )30 equation31 c_1 = e labCla s s ( c ) ;

32 cs2 = MetaUtil . c reateMetaClasses ( c ) ; // Handle union type s33

34 cs = l istAppend ( cs2 , c s ) ;

35 cs_1 = e l abo ra t e (Absyn .PROGRAM( cs ,w) ) ;36 then37 ( c_1 : : cs_1 ) ;38 case (p)39 equation40 Debug . f p r i n t ( " f a i l t r a c e " , "− e l a b o r a t e f a i l e d \n " ) ;41 then42 f a i l ( ) ;43 end matchcontinue ;44 end e l abo ra t e ;

Page 38: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.2 The Front-End 25

MetaUtil

MetaUtil.createMetaClasses

This function takes the AST tree and translates it to contain the METARECORDs.The code in Code 3.3 inserts the marked area into the resulting AST in fig. 3.2.This translation is done by traversing the AST tree, searching for union types andwhen finding one, copying the whole node to the same level as the union type andchanging its restriction to R_METARECORD.

Code 3.3 AST Union Type Example

1 uniontype UT2 record REC13 I n t eg e r y ;4 end REC1;5

6 record REC27 I n t eg e r z ;8 end REC2;9 end UT;

Nodes added to the AST

LIST_OF_AST_ELEMENTS

Absyn.CLASSAbsyn.CLASSAbsyn.CLASS

name restriction body

UT Absyn.R_UNIONTYPE Absyn.ELEMENT Absyn.ELEMENT

Absyn.CLASS

name restriction

REC1 Absyn.R_RECORD

Absyn.CLASS

name restriction

REC2 Absyn.R_RECORD

name restriction

REC1 Absyn.R_METARECORD

name restriction

REC1 Absyn.R_METARECORD

Figure 3.2. The New AST for Code 3.3

Page 39: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

26 Design and Implementation

3.2.4 InstIn this module most of the changes are case-extensions to the instElement func-tion to handle R_UNIONTYPE elements. Since most of the added code are reusedcode for variable instantiation, and environment updates, I won’t go into muchdetail of this.

The idea of this extension is as follows. First create a case clause to catchthe declaration. Then make any necessary checks to make sure it matches thecorrect declarations. After that look up modifications. update the environmentand instantiate the variable into the environment. Finally create the new type,add it to a new DAE and update the bindings and we are done. Code 3.4 showsthe code for this extension.

Note that R_METARECORDs are not handled here since declaring a variable of arecord in a UNIONTYPE is not allowed.

Page 40: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.2 The Front-End 27

Code 3.4 Code Extensions to Inst

1 public function instElement2 input Env . Cache inCache ;3 input Env inEnv1 ;4 input Mod inMod2 ;5 input Pre f i x i nP r e f i x 3 ;6 input Connect . Set s i nSe t s4 ;7 input Cla s s I n f . State inSta te5 ;8 input tuple<SCode . Element , Mod> inTplSCodeElementMod6 ;9 input InstDims inInstDims7 ;

10 input Boolean inBoolean8 ;11 output Env . Cache outCache ;12 output l i s t <DAE. Element> outDAEElementLst ;13 output Env outEnv ;14 output Connect . Set s outSets ;15 output Cla s s I n f . State outState ;16 output l i s t <Types . Var> outTypesVarLst ;17 algorithm18 ( outCache , outDAEElementLst , outEnv , outSets , outState , outTypesVarLst ):=19 matchcontinue ( /∗ A l l input v a r i a b l e s ∗/ )20 // . . . Lots o f case c l a u s e s to handle a l l t ype s o f d e c l a r a t i o n s . . .21

22 case ( cache , env ,mods , pre , c s e t s , c i_state , comp)23 /∗ NOTE: Case shor tened due to space l i m i t a t i o n s ∗/24 equation25 t rue = RTOpts . acceptMetaModelicaGrammar ( ) ;26

27 ( cache , env_1 ) = getDerivedEnv ( cache , env , bc ) ;28 ( cache , c l , cenv ) = Lookup . lookupClass ( cache , env_1 , t , t rue ) ;

29 // Test i f i t has the UNIONTYPE r e s t r i c t i o n30 t rue = MetaUtil . c l a s sHa sRe s t r i c t i o n ( c l , SCode .R_UNIONTYPE) ;

31 a l l r eadyDec l a r ed = checkMult ip lyDec lared ( . . . ) ;32

33 // . . . Code f o r l o o k i n g up mod i f i ca t i ons , updat ing environment e t c . . . .34

35 // I n s t a n t i a t e the component36 ( cache , compenv , dae , csets_1 , ty ) =37 instVar ( . . . ) ;38 dims_1 = instDimExpLst ( dims , impl ) ;39 cr = Pre f i x . p r e f i xC r e f ( pre , Exp .CREF_IDENT(n , { } ) ) ;

40 ty = MetaUtil . createUnionType ( c l ) ;41 dae = daeDeclare ( cr , C l a s s I n f .UNIONTYPE(n ) , ty , . . . ) ;

42 //The environment i s extended ( updated ) wi th the new v a r i a b l e b ind ing .43 ( cache , b inding ) = makeBinding ( cache , env2_1 , att r , mod_1, ty ) ;44

45 // . . . code f o r adding b ind ing s to the dae . . .46

47 then48 ( cache , dae , env_1 , csets_1 , c i_state , vars ) ;49

50 // . . . more case c l a u s e s . . .51 end matchcontinue ;52 end instElement ;

Page 41: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

28 Design and Implementation

3.2.5 LookupIn this module, the only change necessary was adding a case-clause to the lookupType-routine (see Code 3.5). This was to enable type lookups of METARECORDs.

Code 3.5 Code Extensions to Lookup

1

2 function lookupType3 input Env . Cache inCache ;4 input Env . Env inEnv " environment to search in " ;5 input Absyn . Path inPath " type to l ook f o r " ;6 input Boolean inBoolean7 output Env . Cache outCache ;8 output Types . Type outType " the found type " ;9 output Env . Env outEnv "The environment the type was found in " ;

10 algorithm11 ( outCache , outType , outEnv ):=12 matchcontinue ( inCache , inEnv , inPath , inBoolean )13

14 //Case−c l a u s e s

15 case ( cache , env , path ,msg)16 local St r ing s , ident ;17 SCode . Re s t r i c t i o n r e s t r ;18 Absyn . Path name ;19 I n t eg e r index ;20 equation21 t rue = RTOpts . acceptMetaModelicaGrammar ( ) ;22 ( cache , ( c as23 SCode .CLASS( id ,_, enc f l ag ,24 SCode .R_METARECORD(name , index ) ,_) ) , env_1 )25 = lookupClass2 ( cache , env , path , f a l s e ) ;26

27 i d ent = Absyn . pathLastIdent ( path ) ;28 t = (Types .T_METARECORD( ident , name , index ) ,SOME( path ) ) ;29 then30 ( cache , t , env ) ;

31 //More Case−c l a u s e s32 end matchcontinue ;33 end lookupType ;

3.2.6 StaticTo be able to use a METARECORD as an assignment to a UNIONTYPE where theMETARECORD is initialized with its containing variables (as a function call, seeCode 3.6), an extension to elabCallArgs was necessary. Since I wanted to eas-

Page 42: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.2 The Front-End 29

ily distinguish this call from an ordinary function call, I introduced a specialMETARECORDCALL for this (see Code 3.7).

To aid this process a helperfunction, MetaUtil.createFunctionArgsList, wasintroduced. This function takes a R_METARECORD class, parses it and returns alist of types of its containing types. That is the types of the variables in theMETARECORD. For the complete source of this function take a look in the MetaUtilmodule.

Code 3.6 Example of METARECORDCALL Creation

1 uniontype UT2 record REC13 I n t eg e r in t1 ;4 end REC1;5 end UT;6 model testModel7 I n t eg e r out ;8

9 function t e s t f un c10 input I n t eg e r i ;11 output I n t eg e r o ;12 UT univar ;13 algorithm

14 univar = REC1( 3 2 ) ; /∗ Here i s the , so c a l l e d ,15 METARECORDCALL crea ted ∗/

16 o = i ;17 end t e s t f un c ;18 equation19 out = t e s t f un c ( 1 0 ) ;20 end testModel ;

3.2.7 TypesAs can be seen in Code 3.8 the necessary changes are the definition of the newtypes, T_UNIONTYPE and T_METARECORD, and after that the type checking phasewhich is done in the subtype function. This function takes two types and checksif one of them is a subtype of the other. In the union type case there are twodifferent possibilities here. The first case is when assigning a METARECORD to aunion type variable. In this case check if the METARECORD really is a record of theunion type. The second case is assigning a union type to another union type. Inthis case check all containing records and make sure they contain the same ones.

Page 43: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

30 Design and Implementation

Code 3.7 Code Extensions to Static

1 protected function e labCal lArgs2

3 input Env . Cache inCache ;4 input Env . Env inEnv ;5 input Absyn . Path inPath ;6 input l i s t <Absyn . Exp> inAbsynExpLst ;7 input l i s t <Absyn .NamedArg> inAbsynNamedArgLst ;8 input Boolean inBoolean ;9 input Option <... > in Inte rac t ive In te rac t iveSymbo lTab l eOpt ion ;

10 output Env . Cache outCache ;11 output Exp . Exp outExp ;12 output Types . P rope r t i e s ou tPrope r t i e s ;13 algorithm14 ( outCache , outExp , outPrope r t i e s ) :=15 matchcontinue ( /∗ inpu t v a r i a b l e s ∗/ )16 // . . . Lots o f case c l a u s e s

17 case ( cache , env , fn , args , nargs , impl , s t )18 local19 SCode . Class c ;20 SCode . Re s t r i c t i o n re ;21 SCode . Ident id ;22 SCode . Path name ;23 I n t eg e r index ;24 equation25 t rue = RTOpts . acceptMetaModelicaGrammar ( ) ;26 ( cache , t as (Types .T_METARECORD( id , name , index ) ,_) , env_1 ) =27 Lookup . lookupType ( cache , env , fn , f a l s e ) ;28 ( cache , c , env ) = Lookup . lookupClass2 ( cache , env , fn , f a l s e ) ;29 f a r g s = MetaUtil . c r ea teFunct ionArgsL i s t ( c , cache , env ) ;30 s l o t s = makeEmptySlots ( f a r g s ) ;31 ( cache , args_1 , newslots , c o n s t l i s t ) =32 e labInputArgs ( cache , env , args , nargs ,33 s l o t s , t rue /∗ checkTypes ∗/ , impl ) ;34 const = Ut i l . l i s tReduce ( c o n s t l i s t , Types . constAnd ) ;35 tyconst = elabConsts ( t , const ) ;36 prop = ge tPrope r t i e s ( t , tyconst ) ;37 ( cache , news lot s2 ) =38 f i l l D e f a u l t S l o t s ( cache , newslots , c , env , impl ) ;39 args_2 = expListFromSlots ( news lot s ) ;40 then41 ( cache , Exp .METARECORDCALL( fn , args_2 , name , index ) , prop ) ;

42 /∗ . . . more case−c l a u s e s . . . ∗/43 case ( cache , env , fn , args , nargs , impl , s t )44 equation45 Debug . f p r i n t ( " f a i l t r a c e " , "− e l a bCa l lArg s f a i l e d \n ") ;46 then47 f a i l ( ) ;48 end matchcontinue ;49 end e labCal lArgs ;

Page 44: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.2 The Front-End 31

Code 3.8 Extensions to Types

1 public uniontype TType2 // . . . l o t s o f type records . . .

3 record T_UNIONTYPE4 l i s t <Str ing> reco rd s ; //A l i s t wi th record names .5 end T_UNIONTYPE;6 record T_METARECORD7 Absyn . Ident ident ; //The name o f the record8 Absyn . Path name ; //The name o f the uniontype9 I n t eg e r index ; //The index in the uniontype

10 end T_METARECORD;

11 // . . . more type records . . .12 end TType ;13

14 public function subtype15 input Type inType1 ;16 input Type inType2 ;17 output Boolean outBoolean ;18 algorithm19 outBoolean :=20 matchcontinue ( inType1 , inType2 )21 // . . . l o t s o f type checks . . .

22 // <uniontype> = <metarecord>23 case ( (T_METARECORD( ident , name , index ) ,_) , (T_UNIONTYPE( s l s t ) ,_) )24 local25 l i s t <Str ing> s l s t ;26 Absyn . Ident ident ;27 Absyn . Path name ;28 I n t eg e r index ;29 equation30 t rue = MetaUtil . stringMember ( ident , s l s t ) ;31 then t rue ;32 // <uniontype> = <uniontype>33 case ( (T_UNIONTYPE( s l s t 1 ) ,_) , (T_UNIONTYPE( s l s t 2 ) ,_) )34 local35 l i s t <Str ing> s l s t 1 , s l s t 2 ;36 equation37 t rue = MetaUtil . e qua lL i s t s ( s l s t 1 , s l s t 2 ) ;38 then t rue ;

39 //Types doesn ’ t match40 case ( t1 , t2 ) then f a l s e ;41 end matchcontinue ;42 end subtype ;

Page 45: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

32 Design and Implementation

Code 3.9 Extensions to the Prefix Module

1 public function pref ixExp2 input Env . Cache inCache ;3 input Env . Env inEnv ;4 input Exp . Exp inExp ;5 input Pre f i x i nP r e f i x ;6 output Env . Cache outCache ;7 output Exp . Exp outExp ;8 algorithm9 ( outCache , outExp ) :=

10 matchcontinue ( inCache , inEnv , inExp , i nP r e f i x )11 // . . . case−c l a u s e s f o r o ther exp re s s i on type s . . .

12 case ( cache , env , Exp .METARECORDCALL( f , es , name , index ) , p )13 local Pre f i x p ;14 Exp . Type t ;15 Absyn . Path name ;16 I n t eg e r index ;17 equation18 t rue = RTOpts . acceptMetaModelicaGrammar ( ) ;19 ( cache , es_1 ) = pre f i xExpL i s t ( cache , env , es , p ) ;20 then ( cache , Exp .METARECORDCALL( f , es_1 , name , index ) ) ;

21 // . . . more case−c l a u s e s . . .22 end matchcontinue ;23 end pref ixExp ;

3.2.8 Prefix

In order to find the necessary prefix for the new Exp-type (a prefix is the nameextension to e.g. a variable which makes the name fully qualified and will allowdirect lookups), some small extensions were needed here. As can be seen in Code3.9, this extension was made to the prefixExp function and just prefixes its ownExp list and returns the new Exp with all its Exps prefixed.

3.2.9 Patternm

The changes to this module are still to be made. See 5.4.1 for more informationabout this.

3.2.10 DAE

As seen in Code 3.10 the only extensions necessary in this module was the intro-duction of the new DAE types (UNIONTYPE and METARECORD) .

Page 46: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.2 The Front-End 33

Code 3.10 Code Extensions to the DAE Module

1 uniontype Type2 // . . l o t s o f type d e c l a r a t i o n s . . .

3 record UNIONTYPE end UNIONTYPE;4

5 record METARECORD end METARECORD;

1 // . . . more type d e c l a r a t i o n s . . .2 end Type ;

3.2.11 ExpAs seen in Code 3.11 another type declaration had to be made for the UNIONTYPEand a declaration for the new expression METARECORDCALL was made here.

3.2.12 ClassInfThis module basically creates a state machine to handle instantiation of all pos-sible variable declarations, classes etc. This state-machine is not really used forMetaModelica extensions but states for handling METARECORDs and UNIONTYPEshave been added for future development.

Page 47: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

34 Design and Implementation

Code 3.11 Code Extensions to the Exp Module

1 public uniontype Type2 // . . . Lots o f type d e c l a r a t i o n s . . .

3 record T_UNIONTYPE end T_UNIONTYPE;

4 // . . . more type d e c l a r a t i o n s . . .5 end Type ;6

7 public uniontype Exp8 // . . . l o t s o f e xp r e s s i on d e c l a r a t i o n s . . .

9 /∗10 Holds a metarecord c a l l11 <metarecord >(<args >)12 ∗/13 record METARECORDCALL14 Absyn . Path path ;15 l i s t <Exp> args ;16 SCode . Path name ; //Name o f the union type17 I n t eg e r index ; // Index in the union type18 end METARECORDCALL;

19 // . . . more exp re s s i on d e c l a r a t i o n s . . .20 end Exp ;

Page 48: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.3 The Back-End 35

3.3 The Back-EndThe following modules makes up the back-end of the compiler [7], that is the finalcode generation part. Here the intermediate code from the front-end is used tocreate an output of some compilable code which on the other hand will be compiledinto executable code (together with the C-Runtime).

3.3.1 CodegenThis is the module where all the Modelica code, which now are in the form ofDAE-elements, gets translated into C-Code. Since most of the work is alreadydone in the front-end modules, this translation is pretty much straight forward.Some translations from DAE into Exp elements are done in Code 3.12 and themost important translation, that is from METARECORDCALL into C are done ingenerateExpression (see code 3.14). The last function changed here is thegenerateSimpleType function which generates the type string for a simple type,such as a union type as a function input/output variable (see code 3.13).

Code 3.15 shows an example of generated code for some expressions.

3.3.2 C-RuntimeTo be able to use the simulation environment with the newly implemented uniontype a type definition of the new type was needed to modelica.h in the C-Runtime.The name conventions of the modelica types are on the form modelica_<typename>and since the used mk_box<#> are handled as void pointers the typedef added tomodelica.h can be seen in Code 2.8.

Code 3.16 The typedef Added to modelica.h

1 typedef void∗ modelica_uniontype ;

Page 49: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

36 Design and Implementation

Code 3.12 Generating the Variable Type String

1 protected function daeExpType2 input DAE. Type inType ;3 output Exp . Type outType ;4 algorithm5 outType:=6 matchcontinue ( inType )7 case DAE. INT( ) then Exp . INT ( ) ;8 case DAE.REAL( ) then Exp .REAL( ) ;9 case DAE.STRING( ) then Exp .STRING( ) ;

10 case DAE.BOOL( ) then Exp .BOOL( ) ;11 case DAE.ENUM() then Exp .ENUM( ) ;12 case DAE. LIST ( ) then Exp .T_LIST(Exp .OTHER( ) ) ;

13 case DAE.UNIONTYPE( ) then Exp .T_UNIONTYPE( ) ;

14 case _ then Exp .OTHER( ) ;15 end matchcontinue ;16 end daeExpType ;17

18 protected function expTypeStr19 input Exp . Type inType ;20 input Boolean inBoolean ;21 output St r ing outSt r ing ;22 algorithm23 outSt r ing :=24 matchcontinue ( inType , inBoolean )25 local26 Lib t s t r , s t r ;27 Exp . Type t ;28 case (Exp .T_LIST(_) ,_)29 equation30 s t r = " vo id ∗ " ;31 then s t r ;32 // . . . Lots o f case c l a u s e s . . .

33 case (Exp .T_UNIONTYPE( ) ,_)34 equation35 s t r = " model ica_uniontype " ;36 then s t r ;

37 /∗ Case−c l a u s e s f o r hand l ing arrays and o ther Exps ∗/38 end matchcontinue ;39 end expTypeStr ;

Page 50: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.3 The Back-End 37

Code 3.13 generateSimpleType

1 protected function generateSimpleType2 input Types . Type inType ;3 output St r ing outSt r ing ;4 algorithm5 outSt r ing :=6 matchcontinue ( inType )7 local8 Lib n_1 , n_2 , n , t_str ;9 tuple<Types . TType , Option<Absyn . Path>> t_1 , t , ty ;

10 case ( ( Types .T_INTEGER( varLst Int = _) ,_) ) then " mode l ica_integer " ;11 case ( ( Types .T_REAL( varLstReal = _) ,_) ) then " model ica_real " ;12 case ( ( Types .T_STRING( varLs tSt r ing = _) ,_) ) then " mode l i ca_str ing " ;13 case ( ( Types .T_BOOL( varLstBool = _) ,_) ) then " model ica_boolean " ;14 case ( ( Types .T_LIST(_) ,_) ) then " vo id ∗ " ; // MetaModelica l i s t15 /∗ More code f o r hand l ing complex types , arrays e t c ∗/

16 case ( ( Types .T_UNIONTYPE(_) ,_) ) then " model ica_uniontype " ;

17 end matchcontinue ;18 end generateSimpleType ;

Page 51: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

38 Design and Implementation

Code 3.14 generateExpression

1 public function generateExpres s ion2

3 /∗Function header and match−cont inue case−c l a u s e s ∗/

4 case (Exp .METARECORDCALL( fn , e l i s t , name , index ) , tnr , context )5 local6 Absyn . Path fn , name ;7 I n t eg e r index ;8 equation9 t rue = RTOpts . acceptMetaModelicaGrammar ( ) ;

10 ( cfn1 , vars1 , tnr1 ) = genera teExpre s s i ons ( e l i s t , tnr , context ) ;11 ( dec l , tvar , tnr1_1 ) = generateTempDecl ( " model ica_uniontype " , tnr1 ) ;12 s = MetaUtil . l i s tToBoxes ( vars1 , e l i s t , index ) ;13 cfn1_1 = cAddVariables ( cfn1 , { dec l } ) ;14 ret_type = generateReturnType ( fn ) ;15 fn_name = generateFunctionName ( fn ) ;16 args_str = Ut i l . s t r i n gDe l im i tL i s t ( vars1 , " , " ) ;17 stmt = Ut i l . s t r ingAppendList ({ tvar , " = " , s , " ; " } ) ;18 c fn = cAddStatements ( cfn1_1 , { stmt } ) ;19 then20 ( cfn , tvar , tnr1_1 ) ;

21 /∗ More case−c l a u s e s ∗/22 end generateExpres s ion ;

Page 52: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

3.3 The Back-End 39

Code 3.15 Example of Generated Code

1 uniontype UT2 record REC13 I n t eg e r i 1 ;4 end REC1;5 record REC26 I n t eg e r i 2 ;7 end REC2;8 end UT;9 model Uniontype2

10 I n t eg e r k ;11 UT re ;12 function t e s t 213 input UT r ;14 // func t i on body15 end t e s t 2 ;16 function t e s t17 input I n t eg e r s ;18 output I n t eg e r k ;19 algorithm20 re := REC1( 6 6 ) ;21 re := REC2( 100 ) ;22 k := t e s t 2 ( re ) ;23 end t e s t ;24 equation25 k = t e s t ( 1 ) ;26 end Uniontype2 ;

1 Uniontype2_test_rettype _Uniontype2_test ( mode l i ca_integer s )2 {3 Uniontype2_test_rettype tmp1 ;4 s t a t e tmp2 ;5 model i ca_integer k ;

6 //UT re ;7 modelica_uniontype re ;

8 modelica_uniontype tmp3 ;9 modelica_uniontype tmp4 ;

10 Uniontype2_test2_rettype tmp5 ;11

12 tmp2 = get_memory_state ( ) ;

13 // re := REC1( 6 6 ) ;14 tmp3 = mk_box1(0 ,mmc_mk_icon ( 6 6 ) ) ;15 re = tmp3 ;16 // re := REC2(100) ;17 tmp4 = mk_box1(1 ,mmc_mk_icon ( 1 0 0 ) ) ;18 re = tmp4 ;19 // k := t e s t 2 ( re ) ;20 tmp5 = _Uniontype2_test2 ( re ) ;21 k = tmp5 . Uniontype2_test2_rettype_1 ;

22 _return :23 tmp1 . targ1 = k ;24 restore_memory_state ( tmp2 ) ;25 return tmp1 ;26 }

Page 53: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 54: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Chapter 4

Guidelines for Implementinga New High-Level DataStructure

The implementation of the MetaModelica extension in the OpenModelica Compilerinvolves the addition of several new, high-level, data structures: union types, lists,tuple types and option types. In this chapter I will describe a general course ofaction when adding a new data structure to the compiler.

Generally, a new data structure type must be added to the compiler type sys-tem. If you wish to add a new simply type to a compiler (such as an integertype) this is a relatively straightforward process: the new type is added to thetype system module and rules for matching two expressions of this new type areadded as well. In the back-end the new type should be matched against a cor-responding type in the target language. Minor changes in a few other modulesare needed as well. However in this case we are dealing with high-level and, insome cases, parameterized data types, which leads to more work. As of now thearray parameterized data type, for instance, is treated in a separate manner in theOpenModelica Compiler. One must also consider the fact that this MetaModelicaextension is being added to the compiler in an ad-hoc manner. That is, it is sep-arated with a compiler flag and we have altered the original flow of the compileras little as possible, this also increases the complexity and difficulty.

New data structures may come with new syntax (other than the type keyword).For instance the list data structure comes with syntax for declaring lists as well aslist constructors? syntax for building lists. See the table below. The main workfor the extension with the four high-level data structures mentioned above (uniontypes, lists, tuple types and option types) involves:

• Addition to the parser and the abstract syntax module. Note that lists,tuples and option types variables are parsed as variables of new complextypes and union type variables are parsed as variables of a new restrictedclass.

41

Page 55: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

42 Guidelines for Implementing a New High-Level Data Structure

• The new type should be added to the type system. This includes addingtype matching rules, etc..

• New expressions associated with the new data structure must be handled.For instance the cons-constructor expression - cons or :: - in connection withthe list type or the union type record constructor call - MyRecord(1,2,3,4).

• A union type restricted class declaration must be treated in a special manner,as has been described in this thesis. Lists, tuples, and option types do notinvolve class declarations (tuples and option types can be said to involveclass declarations explicitly).

• These new types should be handled as input and output to functions and inmatchcontinue expressions.

• A declaration of a variable of this new type might have to be treated sepa-rately in the instantiation phase.

Page 56: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

43

Page 57: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

44 Guidelines for Implementing a New High-Level Data Structure

A description of which modules that has to be modified follows.Parser: ANTLR is used as an external OpenModelica parser. From a formal

grammar, ANTLR generates a program that determines whether sentences conformto that language. In other words, it is a program that writes other programs.The Modelica grammar is written in EBNF. EBNF means Extended Backus-NaurForm, the grammar for describing parser grammars. Typically a parser consistsof a lexer and a parser [7]. In the ANTLR case there is also a walker. Thewalker maps the abstract syntax from the parser into the Abstract Syntax of theOMC, given by the constructs in Absyn.h (generated from Absyn.mo). The threefollowing files need to be altered in the parser:

• New keywords in OpenModelica\modelica_parser\src\modelica_lexer.g

• New grammar rules in OpenModelica\modelica_parser\src\modelica_parser.g

• New rules in OpenModelica\absyn_builder\walker.g.

Other modules that should or might have to be altered follows alphabetically.Absyn.mo: New abstract syntax for the new data structures are added to this

module.Ceval.mo: If the new data structure involved a new abstract syntax expression,

such as the list-cons expression then in the function Ceval.ceval new rules couldbe added for constant evaluation (1::2, 3::4, etc.)

ClassInf.mo: If the new data structure involves a new restricted class, suchas the union type, this module should perhaps be altered. For instance in theClassInf.trans function new rules should be added so that we for instance makesure that equations are never declared inside a union type class. However, sincethe union type extension is handled differently and is part of the MetaModelicaextension, it is not unified totally with normal Modelica. This is more of an ad-hocimplementation.

Codegen.mo: The correct type in the source language should be generated.Thus the functions daeExpType, expTypeStr, generateType, generateTypeExternal,etc. should be altered with new rules. In generateExpression we might haveto add rules for generating code (from the Exp-expressions). For instance codeto Exp.CONS, corresponding to the cons-operator expression. Note that in theMetaModelica case, SimCodegen.mo etc. does not need to be altered since we aredealing with time-invariant contexts.

Exp.mo: This module contains expressions after the instantiation phase, that is,expression with type information and that have been, perhaps, constant evaluated.So in the list type case we have a cons-constructor expression,Exp.CONS

Inst.mo: This is one of the most complex modules of the compiler.In the function instElement a new case-branch has been added/will be added

that takes care of variable declaration of the new complex, MetaModelica types.One must also consider the fact that a type may be derived. That is, we may

have for instance:1 type MyListType1 = l i s t <Integer >;2 type MyListType2 = MyListType1 ;3 MyListType1 var1 ;

Page 58: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

45

This could be dealt with in the function instVar (which is called from instElement)where a type component is instantiated. Another issue is arrays, we may have ar-rays of lists, arrays of tuples, etc.

Prefix.mo: New rules for prefixing expressions must be added in functionprefixExp.

Scode.mo: Abstract syntax may have to be added.Static.mo: New rules for elaborating the new expressions should be added in

the function elabExp in this module.Types.mo: In the union type TType a new type record should be added. The

most important function to alter is the subtype function: new rules for typematching should be added to this function.

Fig. B.1 contains a summary of which modules have to be extended in orderto implement a new type into the compiler.

Page 59: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 60: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Chapter 5

Discussion and RelatedWork

In this chapter I will discuss the implemented solution, how it was done andpositive/negative things of the implementation and the process of implementingit. Finally I will write a little about future development, what is under developmentright now and what to expect in the future.

5.1 Test CasesWriting testcases is an important part of an implementation. This is where thefinal solution gets verified to make sure it fulfills the specification. For the uniontypes I have made three different test-cases. The first one just declares a uniontype and assigns a record to it. The second uses a union type as an input toa function. The third one uses a union type both for input and output from afunction. All the above cases passes just fine.

The test suite is available in:

<omc-root>/testsuite/

5.2 Performance MeasurementsWhen extending a compiler it is always interesting to make some performancemeasurements before and after the extension. This was unfortunately not possibleto do for this implementation since one part of the union type is still missing.That is getting the data out from the union type, and without this it is impossibleto make any real use of them. The only assumption I can make about this is thatthe compiler itself will be not noticeable slowed down due to the extension sinceall extensions were made by adding case-clauses in different modules.

47

Page 61: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

48 Discussion and Related Work

5.3 Generated Code

The generated code from this implementation consists of a

mk_box<#>(<index>,<data::data>)

for each assignment to the union type (Where # is the number of variables in therecord, <data:data> the list of variables and index an index number). The idea isto use the index to be able to easily make a switch on the box to find out which ofthe records it consists of at the moment. The only problem with this constructionis that the garbage collector is not able to handle these boxes correctly at themoment and thus will cause a small memory leak every time it is used. Fixingthis is an important thing for the future.

5.4 Future Work

The compiler technology area is an area under heavy development and new theo-ries about generating code is presented almost every other day. Generating codeis also a complex thing making it hard to cover all possible code permutationsand therefore leaving some bugs. The OpenModelica Compiler is of course noexception from this. The changes made are bug fixes and implementation of newfeatures with the goal of making the OpenModelica Compiler able to handle thefull MetaModelica extension. With the implementation of union types this goalis now rather close and will hopefully be reached within the end of this year.However, below are some of the subgoals needed before reaching this milestone.

5.4.1 Getting Union Types and Lists to Work in Matchcon-tinue Expressions

Making it possible to use lists and union types in matchcontinue expressions isan important goal. This is under development by the OpenModelica developmentteam and will probably only require some minor changes to the pattern matchingalgorithm.

5.4.2 Getting Rid of the RML-Compiler

After making the compiler able to handle the full MetaModelica extension, the nextstep is making the OpenModelica Compiler being able to compile itself. The reasonfor this is to eliminate the use of the RML compiler, making the OpenModelicaCompiler standalone and independent. This compiler compilation will be possiblethrough the process of bootstrapping [4] within a near future (as soon as theOpenModelica Compiler is able to handle the full MetaModelica language).

Page 62: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

5.4 Future Work 49

5.4.3 Extending the Comments of the OpenModelica Com-piler

Even though most of the functions in the OpenModelica Compiler already havesome sort of brief comment about its function, a little more extensive commentabout how it was implemented and which other functions are used in order toachieve this, was often something that could had been a real timesaver. To facili-tate further extension of the compiler it is therefore probably a good idea to takesome time to extend these comments.

Page 63: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 64: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Chapter 6

Conclusions

6.1 AccomplishmentsThe goal for this thesis work was to fully implement support for union types intothe OpenModelica Compiler. I believe this goal has mostly been achieved but someminor parts are still needed (see section 5.4.1). The union type implementationas it is now allows you to:

• Declare a Union Type Holder Variable.

• Assign Records of the Union Type to its Holder Variable.

• Reassign the Holder Variable With Another Record.

• Use Union Types as Input to a Function.

• Use Union Types as Output From a Function.

51

Page 65: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science
Page 66: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Bibliography

[1] Another tool for language recognition [online]. 1 2008 [cited 2008-01-23].Available from World Wide Web: http://www.antlr2.org/.

[2] Mathcore homepage [online]. 2 2008 [cited 2008-02-18]. Available from WorldWide Web: http://www.mathcore.com.

[3] Modelica homepage [online]. 1 2008 [cited 2008-01-14]. Available from WorldWide Web: http://www.modelica.org.

[4] Wikipedia: Bootstrapping (compilers) [online]. 02 2008 [cited 2008-02-26]. Available from World Wide Web: http://en.wikipedia.org/wiki/Bootstrapping_(compilers).

[5] Wikipedia: J.h. wilkinson prize for numerical software [online]. 3 2008 [cited2008-03-12]. Available from World Wide Web: http://en.wikipedia.org/wiki/J._H._Wilkinson_Prize_for_Numerical_Software.

[6] Wikipedia: Union (computer science) [online]. 02 2008 [cited 2008-02-29].Available from World Wide Web: http://en.wikipedia.org/wiki/Union_type.

[7] Alfred V. Aho, Monica S. Lam, Ravi Sethi, and Jeffrey D. Ullman. CompilersPrinciples, Techniques, & Tools. Addison Wesley, 2nd edition, 2007.

[8] Peter Fritzson. Developing efficient language implementations from struc-tural and natural semantics [online, cited 2008-01-11]. Available fromWorld Wide Web: http://www.ida.liu.se/~pelab/rml/rml-ftp/papers/rmlguide-v22-pdf-060314.pdf.

[9] Peter Fritzson. Modelica meta-programming and symbolic transforma-tions [online]. 03 2008 [cited 2008-03-05]. Available from World WideWeb: http://www.ida.liu.se/labs/pelab/modelica/OpenModelica/releases/1.4.4/doc/OpenModelicaMetaProgramming.pdf.

[10] Peter Fritzson, Adrian Pop, and other OMC Developers. Openmodelicasystem documentation [online]. June 2007 [cited 2008-01-22]. Availablefrom World Wide Web: http://www.ida.liu.se/labs/pelab/modelica/OpenModelica/releases/1.4.3/doc/OpenModelicaSystem.pdf.

53

Page 67: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

54 Bibliography

[11] Peter Fritzson, Adrian Pop, and other OMC Developers. Openmod-elica users guide [online]. 03 2008 [cited 2008-03-05]. Availablefrom World Wide Web: http://www.ida.liu.se/labs/pelab/modelica/OpenModelica/releases/1.4.4/doc/OpenModelicaUsersGuide.pdf.

[12] Elmir Jagudin and Andreas Remar. Modelica development tooling for eclipse.Master’s thesis, Linköpings Universitet, 2006.

[13] David Kågedal and Peter Fritzson. Generating a modelica compiler fromnatural semantics specifications [online, cited 2008-01-17]. Available fromWorld Wide Web: http://www.ida.liu.se/~pelab/rml/rml-ftp/papers/scs98sem.pdf.

[14] Mikael Pettersson. Compiling Natural Semantics. PhD thesis, LinköpingsUniversitet, 1995.

[15] Adrian Pop and Peter Fritzson. Metamodelica: A unified equation-based se-mantical and mathematical modeling language. 7th Joint Modular LanguagesConference, Oxford, UK, pages 211–229, September 13-15 2006.

Page 68: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Appendix A

An Overview of theCompiler

55

Page 69: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

56 An Overview of the Compiler

Figure A.1. An Overview of the Compiler

Page 70: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Appendix B

Extending the CompilerWith a New Type

57

Page 71: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

58 Extending the Compiler With a New Type

Par

ser

Abs

yn

SC

ode

Inst

Lo

oku

pS

tati

cT

ypes

Pre

fix

DA

EE

xp

Co

deg

en

Ext

end

par

ser

to h

and

le th

e ne

w ty

pe

Ad

d th

e ne

w ty

pe a

s a

rest

rict

ion

Ad

d th

e ne

w ty

pe a

s a

rest

rict

ion

and

ext

end

ela

bRes

tric

tion

Ext

end

inst

Ele

men

t

Ext

end

look

upTy

peE

xten

d e

labC

allA

rgs

to c

reat

e a

new

Exp

nod

eA

dd

the

new

type

to T

Type

and

ext

end

sub

Type

Ext

end

pre

fixE

xp to

han

dle

the

new

Exp

Ext

end

Typ

eE

xten

d T

ype

and

Exp

Ext

end

dae

Exp

Type

, ex

pTyp

eStr

, ge

nera

teS

impl

eTyp

e an

d g

ener

ateE

xpre

ssio

n

Figure B.1. Extending the Compiler With a New High-Level Datastructure

Page 72: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

Index

Abstract Syntax Tree, see ASTAbsyn, 20, 22acceptMetaModelicaGrammar, 15analysis, 19Analyzer, 13ANother Tool for Language Recogni-

tion, see ANTLRANTLR, 14AST, 14, 25

translation, 25

back-end, 35bootstrapping, 48boxes, 48

C-Runtime, 15, 35ClassInf, 33code generation, 13, 15Codegen, 15, 21comments, 49compiler

code generation, 19flow, 14overview, 20translation stages, 13

createFunctionArgsList, 29createMetaClasses, 25

DAE, 13, 15, 21, 32, 35DAELow, 15DASSL, 13debugging, 17dependencies, 5Dump, 14

Eclipse, 12, 17elabCallArgs, 28elabClass, 23

elaborate, 23class, 23

elaboration, 13elabRestriction, 23environment, 14environment updates, 26EOO, 1Equation-based Object-Oriented, see

EOOeval relation, 8executable code, 13Exp, 21, 33, 35extended modules, 20

front-end, 15, 35functional language, 8

garbage collector, 15, 48generateExpression, 35generateSimpleType, 35goals, 1graph, 6

import statements, 13inheritance, 13Inst, 14, 20, 26instantiation, 13, 14instElement, 26intermediate form, 14

language specification, 7Lookup, 15, 20, 28lookup statements, 13lookupType, 28

main function, 14match-expressions, 9matchcontinue, 11, 19, 48

59

Page 73: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

60 Index

MathCore, 13MDT, 17memory leak, 48MetaModelica, 9, 12, 48

matchcontinue, 11METARECORD, 22, 25, 28, 29, 32,

33METARECORDCALL, 29, 33, 35MetaUtil, 21, 25Mikael Pettersson, 8mmc_mk_box2, 16mmc_mk_cons, 16mmc_mk_icon, 16mmc_mk_nil, 16mmc_mk_rcon, 16mmc_mk_scon, 16Modelica, 6, 13

compiler, 12debugger, 12Eclipse, 12Emacs, 12environment structure, 12failure, 11graphical model editor, 13interactive session handler, 12OpenModelica, 12return, 11

modifications, 13

name lookups, 14Natural Semantics, 7

ODE, 13OpenModelica, 6OpenModelica Compiler, 12, 49OpenModelica Tooling, 17optimization, 13Optimizer, 13outline, 1, 2overview, 14

Parse, 14, 20parsing, 14pattern matching, 32, 48Patternm, 20, 32PELAB, 9, 12Peter Fritzson, 8

plot, 6Prefix, 20, 32prefix, 32prefixes , see prefixprefixExp, 32prerequisites, 1Programming Environment Labora-

tory, see PELAB

R_METARECORD, 20, 22, 23, 26R_UNIONTYPE, 20, 23, 26record, 29Relational Meta-Language, see RMLRML, 7–9, 48RML-Compiler, 8RTOpts, 15

SCode, 14, 20, 23SimCodeGen, 15simple type, 35simulate, 6simulation environment, 15SML, 7Standard ML, see SMLStatic, 20, 28subtype, 29subtypes, 29

testcases, 47type checking, 13, 14, 29type lookups, 28Types, 20, 29

union type, 9, 20, 29, 35, 48datastructure specification, 9holder variable, 9index, 22pattern matching, 22

union types, 9UNIONTYPE, 32, 33

variable instantiation, 26

Page 74: Institutionen för datavetenskap - DiVA portalliu.diva-portal.org/smash/get/diva2:18445/FULLTEXT01.pdf · Institutionen för datavetenskap Department of Computer and Information Science

UpphovsrättDetta dokument hålls tillgängligt på Internet — eller dess framtida ersättare —under 25 år från publiceringsdatum under förutsättning att inga extraordinäraomständigheter uppstår.

Tillgång till dokumentet innebär tillstånd för var och en att läsa, ladda ner,skriva ut enstaka kopior för enskilt bruk och att använda det oförändrat för icke-kommersiell forskning och för undervisning. Överföring av upphovsrätten vid ensenare tidpunkt kan inte upphäva detta tillstånd. All annan användning av doku-mentet kräver upphovsmannens medgivande. För att garantera äktheten, säkerhe-ten och tillgängligheten finns det lösningar av teknisk och administrativ art.

Upphovsmannens ideella rätt innefattar rätt att bli nämnd som upphovsmani den omfattning som god sed kräver vid användning av dokumentet på ovan be-skrivna sätt samt skydd mot att dokumentet ändras eller presenteras i sådan formeller i sådant sammanhang som är kränkande för upphovsmannens litterära ellerkonstnärliga anseende eller egenart.

För ytterligare information om Linköping University Electronic Press se förla-gets hemsida http://www.ep.liu.se/

CopyrightThe publishers will keep this document online on the Internet — or its possi-ble replacement — for a period of 25 years from the date of publication barringexceptional circumstances.

The online availability of the document implies a permanent permission foranyone to read, to download, to print out single copies for his/her own use andto use it unchanged for any non-commercial research and educational purpose.Subsequent transfers of copyright cannot revoke this permission. All other uses ofthe document are conditional on the consent of the copyright owner. The publisherhas taken technical and administrative measures to assure authenticity, securityand accessibility.

According to intellectual property law the author has the right to be mentionedwhen his/her work is accessed as described above and to be protected againstinfringement.

For additional information about the Linköping University Electronic Pressand its procedures for publication and for assurance of document integrity, pleaserefer to its www home page: http://www.ep.liu.se/

c© Simon Björklén