types in the modelica language

13
The Modelica Association Modelica 2006, September 4 th – 5 th Types in the Modelica Language David Broman Peter Fritzson ebastien Furic Link¨ oping University, Sweden Link¨ oping University, Sweden Imagine, France [email protected] [email protected] Abstract Modelica is an object-oriented language designed for modeling and simulation of complex physical systems. To enable the possibility for an engineer to discover errors in a model, languages and com- pilers are making use of the concept of types and type checking. This paper gives an overview of the concept of types in the context of the Model- ica language. Furthermore, a new concrete syntax for describing Modelica types is given as a starting point to formalize types in Modelica. Finally, it is concluded that the current state of the Modelica language specification is too informal and should in the long term be augmented by a formal defin- ition. Keywords: type system; types; Modelica; simula- tion; modeling; type safety 1 Introduction One long term goal of modeling and simulation languages is to give engineers the possibility to discover modeling errors at an early stage, i.e., to discover problems in the model during design and not after simulation. This kind of verifica- tion is traditionally accomplished by the use of types in the language, where the process of check- ing for such errors by the compiler is called type checking. However, the concept of types is of- ten not very well understood outside parts of the computer science community, which may result in misunderstandings when designing new languages. Why is then types important? Types in program- ming languages serve several important purposes such as naming of concepts, providing the com- piler with information to ensure correct data ma- nipulation, and enabling data abstraction. Almost all programming or modeling languages provide some kind of types. However, few language spec- ifications include precise and formal definitions of types and type systems. This may result in incom- patible compilers and unexpected behavior when using the language. The purpose of this paper is twofold. The first part gives an overview of the concept of types, states concrete definitions, and explains how this relates to the Modelica language. Hence, the first goal is to augment the computer science perspec- tive of language design among the individuals in- volved in the Modelica language design. The long- term objective of this work is to provide aids for further design considerations when developing, en- hancing and simplifying the Modelica language. The intended audience is consequently engineers and computer scientists interested in the founda- tion of the Modelica language. The second purpose and likewise the main con- tribution of this work is the definition of a concrete syntax for describing Modelica types. This syntax together with rules of its usage can be seen as a starting point to more formally describe the type concept in the Modelica language. To the best of our knowledge, no work has previously been done to formalize the type concept of the Modelica lan- guage. The paper is structured as follows: Section 2 outlines the concept of types, subtypes, type sys- tems and inheritance, and how these concepts are used in Modelica and other mainstream languages. Section 3 gives an overview of the three main forms of polymorphism, and how these concepts corre- late with each other and the Modelica language. The language concepts and definitions introduced in Section 2 and 3 are necessary to understand the rest of the paper. Section 4 introduces the type concept of Modelica more formally, where we give a concrete syntax for expressing Modelica types. Finally, Section 5 state concluding remarks and propose future work in the area. 303 Types in the Modelica Language

Upload: others

Post on 22-Jan-2022

8 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

Types in the Modelica Language

David Broman Peter Fritzson Sebastien FuricLinkoping University, Sweden Linkoping University, Sweden Imagine, France

[email protected] [email protected]

Abstract

Modelica is an object-oriented language designedfor modeling and simulation of complex physicalsystems. To enable the possibility for an engineerto discover errors in a model, languages and com-pilers are making use of the concept of types andtype checking. This paper gives an overview ofthe concept of types in the context of the Model-ica language. Furthermore, a new concrete syntaxfor describing Modelica types is given as a startingpoint to formalize types in Modelica. Finally, it isconcluded that the current state of the Modelicalanguage specification is too informal and shouldin the long term be augmented by a formal defin-ition.

Keywords: type system; types; Modelica; simula-tion; modeling; type safety

1 Introduction

One long term goal of modeling and simulationlanguages is to give engineers the possibility todiscover modeling errors at an early stage, i.e.,to discover problems in the model during designand not after simulation. This kind of verifica-tion is traditionally accomplished by the use oftypes in the language, where the process of check-ing for such errors by the compiler is called typechecking. However, the concept of types is of-ten not very well understood outside parts of thecomputer science community, which may result inmisunderstandings when designing new languages.Why is then types important? Types in program-ming languages serve several important purposessuch as naming of concepts, providing the com-piler with information to ensure correct data ma-nipulation, and enabling data abstraction. Almostall programming or modeling languages providesome kind of types. However, few language spec-ifications include precise and formal definitions of

types and type systems. This may result in incom-patible compilers and unexpected behavior whenusing the language.

The purpose of this paper is twofold. The firstpart gives an overview of the concept of types,states concrete definitions, and explains how thisrelates to the Modelica language. Hence, the firstgoal is to augment the computer science perspec-tive of language design among the individuals in-volved in the Modelica language design. The long-term objective of this work is to provide aids forfurther design considerations when developing, en-hancing and simplifying the Modelica language.The intended audience is consequently engineersand computer scientists interested in the founda-tion of the Modelica language.

The second purpose and likewise the main con-tribution of this work is the definition of a concretesyntax for describing Modelica types. This syntaxtogether with rules of its usage can be seen as astarting point to more formally describe the typeconcept in the Modelica language. To the best ofour knowledge, no work has previously been doneto formalize the type concept of the Modelica lan-guage.

The paper is structured as follows: Section 2outlines the concept of types, subtypes, type sys-tems and inheritance, and how these concepts areused in Modelica and other mainstream languages.Section 3 gives an overview of the three main formsof polymorphism, and how these concepts corre-late with each other and the Modelica language.The language concepts and definitions introducedin Section 2 and 3 are necessary to understand therest of the paper. Section 4 introduces the typeconcept of Modelica more formally, where we givea concrete syntax for expressing Modelica types.Finally, Section 5 state concluding remarks andpropose future work in the area.

303

Types in the Modelica Language

Page 2: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

2 Types, Subtyping and

Inheritance

There exist several models of representing types,where the ideal model [3] is one of the most well-known. In this model, there is a universe V of allvalues, containing all values of integers, real num-bers, strings and data structures such as tuples,records and functions. Here, types are defined assets of elements of the universe V . There is infi-nite number of types, but all types are not legaltypes in a programming language. All legal typesholding some specific property, such as being anunsigned integer, are called ideals. Figure 1 givesan example of the universe V and two ideals: realtype and function type, where the latter has thedomain of integer and codomain of boolean.

Figure 1: Schematic illustration of Universe V andtwo ideals.

In most mainstream languages, such as Java andC++, types are explicitly typed by stating infor-mation in the syntax. In other languages, such asStandard ML and Haskell, a large portion of typescan be inferred by the compiler, i.e., the compilerdeduces the type from the context. This process isreferred to as type inference and such a languageis said to be implicitly typed. Modelica is an ex-plicitly typed language.

2.1 Language Safety and Type Systems

When a program is executed, or in the Modelicacase: during simulation, different kinds of execu-tion errors can take place. It is practical to distin-guish between the following two types of runtimeerrors [2].

• Untrapped errors are errors that can go un-noticed and later cause arbitrary behavior ofthe system. For example, writing data out ofbound of an array might not result in an im-mediate error, but the program might crashlater during execution.

• Trapped errors are errors that force the com-putation to stop immediately; for example di-vision by zero. The error can then be handled

by the run-time system or by a language con-struct, such as exception handling.

A programming language is said to be safe if nountrapped errors are allowed to occur. Thesechecks can be performed as compile-time checks,also called static checks, where the compiler findsthe potential errors and reports them to the pro-grammer. Some errors, such as array out of bounderrors are hard to resolve statically. Therefore,most languages are also using run-time checks,also called dynamic checking. However, note thatthe distinction between compile-time and run-timebecomes vaguer when the language is intended forinterpretation.

Typed languages can enforce language safetyby making sure that well-typed programs cannotcause type errors. Such a language is often calledtype safe or strongly typed. This checking processis called type checking and can be carried out bothat run-time and compile-time.

The behavior of the types in a language is ex-pressed in a type system. A type system canbe described informally using plain English text,or formally using type rules. The Modelica lan-guage specification is using the former informalapproach. Formal type rules have much in com-mon with logical inference rules, and might atfirst glance seem complex, but are fairly straight-forward once the basic concepts are understood.Consider the following:

G ` e1 : bool G ` e2 : T G ` e3 : T(t-if)

G ` if e1 then e2 else e3 : T

which illustrates a type rule for the following Mod-elica if-expression:

if e1 then e2 else e3

A type rule is written using a number of premiseslocated above the horizontal line and a conclusionbelow the line. The typing judgement G ` e : Tmeans that expression e has type T with respectto a static typing environment G. Hence, the rule(t-if) states that guard e1 must have the type ofa boolean and that e2 and e3 must have the sametype, which is also the resulting type of the if-expression after evaluation. This resulting type isstated in the last part of the conclusion, i.e., : T .

If the language is described formally, we can at-tempt to prove the type soundness theorem [15].If the theorem holds, the type system is said to besound and the language type safe or or just safe.

304

D. Broman, P. Fritzson, S. Furic

Page 3: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

The concept of type safety can be illustrated byRobin Milner’s famous statement ”Well-typed pro-grams cannot go wrong”[9]. Modern type sound-ness proofs are based on Wright and Felleisen’sapproach where type systems are proven correcttogether with the language’s operational seman-tics [15]. Using this technique, informally stated,type safety hold if and only if the following twostatements holds:

• Preservation - If an expression e has a type Tand e evaluates to a value v, then v also hastype T .

• Progress - If an expression e has a type Tthen either e evaluates to a new expression e′

or e is a value. This means that a well typedprogram never gets ”stuck”, i.e., it cannot gointo a undefined state where no further eval-uations are possible.

Note that the above properties of type safety cor-responds to our previous description of absenceof untrapped errors. For example, if a division byzero error occurs, and the semantics for such eventis undefined, the progress property will not hold,i.e., the evaluation gets ”stuck”, or enters an un-defined state. However, if dynamic semantics aredefined for throwing an exception when the divi-sion by zero operation occurs, the progress prop-erty holds.

For the imperative and functional parts of theModelica language, the safety concept correspondsto the same methodology as other languages,such as Standard ML. However, for the instan-tiation process of models, the correspondence tothe progress and preservation properties are notobvious.

Table 1 lists a number of programming lan-guages and their properties of being type safe[10][2]. The table indicates if the languages areprimarily designed to be checked statically atcompile-time or dynamically at run-time. How-ever, the languages stated to be statically typechecked typically still perform some checking atruntime.

Although many of the languages are commonlybelieved to be safe, few have been formally provento be so. Currently, ML [9] and subsets of the Javalanguage [14] [7] has been proven to be safe.

Language Type Safe CheckingStandard ML yes staticJava yes staticCommon LISP yes dynamicModelica yes static1

Pascal almost staticC/C++ no staticAssembler no -

Table 1: Believed type safety of selected lan-guages.

2.2 Subtyping

Subtyping is a fundamental language concept usedin most modern programming languages. It meansthat if a type S has all the properties of anothertype T , then S can be safely used in all contextswhere type T is expected. This view of subtyp-ing is often called the principle of safe substitution[12]. In this case, S is said to be a subtype of T ,which is written as

S <: T (1)

This relation can be described using the followingimportant type rule called the rule of subsumption.

G ` t : S S <: T(t-sub)

G ` t : T

The rule states that if S<: T , then every term2

t of type S is also a term of type T . This shows aspecial form of polymorphism, which we will fur-ther explore in Section 3.

2.3 Inheritance

Inheritance is a fundamental language conceptfound in basically all class based Object-Oriented(OO) languages. From an existing base class, anew subclass can be created by extending fromthe base class, resulting in the subclass inheritingall properties from the base class. One of the mainpurposes with inheritance is to save programming

1One can argue whether Modelica is statically or dynam-ically checked, depending on how the terms compile-timeand run-time are defined. Furthermore, since no exceptionhandling is currently part of the language, semantics forhandling dynamic errors such as array out of bound is notdefined in the language and is therefore considered a com-piler implementation issue.

2The word term is commonly used in the literature asan interchangeable name for expression.

305

Types in the Modelica Language

Page 4: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

and maintenance efforts of duplicating and readingduplicates of code. Inheritance can in principle beseen as an implicit code duplication which in somecircumstances implies that the subclass becomes asubtype of the type of the base class.

Figure 2 shows an example3 where inheritanceis used in Modelica. A model called Resistorextends from a base class TwoPin, which includestwo elements v for voltage and i for current. Fur-thermore, two instances p and n of connector Pinare public elements of TwoPin. Since Resistorextends from TwoPin, all elements v, i, p andn are ”copied” to class Resistor. In this case,the type of Resistor will also be a subtype ofTwoPin’s type.

connector PinSI.Voltage v;flow SI.Current i;

end Pin;

partial model TwoPinSI.Voltage v;SI.Current i;Pin p, n;

equationv = p.v - n.v;0 = p.i + n.i;i = p.i;

end TwoPin;

model Resistorextends TwoPin;parameter SI.Resistance R=100;

equationR*i = v;

end Resistor;

Figure 2: Example of inheritance in Modelica,where a new subclass Resistor is created by ex-tending the base class TwoPin.

However, a common misunderstanding is that sub-typing and inheritance is the same concept [10].A simple informal distinction is to say that ”sub-typing is a relation on interfaces”, but ”inheri-tance is a relation on implementations”. In theresistor example, not only the public elementsv, i, p and n will be part of class Resistor,but also the meaning of this class, i.e, the equa-tions v = p.v - n.v, 0 = p.i + n.i andi = p.i.

3These classes are available in the Modelica StandardLibrary 2.2, but are slightly modified for reasons of read-ability.

A famous example, originally stated by AlanSnyder [13], illustrates the difference between sub-typing and inheritance. Three common abstractdata types for storing data objects are queue, stackand dequeue. A queue normally has two opera-tions, insert and delete, which stores and returnsobject in a first-in-first-out (FIFO) manner. Astack has the same operations, but are using alast-in-first out (LIFO) principle. A dequeue canoperate as both a stack and a queue, and is nor-mally implemented as a list, which allows insertsand removals at both the front and the end of thelist.

Figure 3 shows two C++ classes modeling theproperties of a dequeue and a stack. Since classDequeue implements the properties also neededfor a stack, it seems natural to create a sub-class Stack that inherits the implementationfrom Dequeue. In C++, it is possible to useso called private inheritance to model inheritancewith an exclude operation, i.e., to inherit some, butnot all properties of a base class. In the exam-ple, the public methods insFront, delFront,and delRear in class Dequeue are inherited tobe private in the subclass Stack. However, byadding new methods insFront and delFrontin class Stack, we have created a subclass, whichhas the property of a stack by excluding themethod delRear. Stack is obviously a subclass

class Dequeue{public:void insFront(int e);int delFront();int delRear();

};

class Stack : private Dequeue{public:void insFront(int e){Dequeue::insFront(e);}

int delFront(){return Dequeue::delFront();}

};

Figure 3: C++ example, where inheritance doesnot imply a subtype relationship.

of Dequeue, but is it a subtype? The answer isno, since an instance of Stack cannot be safelyused when Dequeue is expected. In fact, the op-posite is true, i.e., Dequeue is a subtype of Stackand not the other way around. However, in thefollowing section we will see that C++ does not

306

D. Broman, P. Fritzson, S. Furic

Page 5: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

treat such a subtype relationship as valid, but thetype system of Modelica would do so.

2.4 Structural and Nominal Type Sys-tems

During type checking, regardless if it takes place atcompile-time or run-time, the type checking algo-rithm must control the relations between types tosee if they are correct or not. Two of the most fun-damental relations are subtyping and type equiva-lence.

Checking of type equivalence is the single mostcommon operation during type checking. For ex-ample, in Modelica it is required that the left andright side of the equality in an equation have thesame type, which is shown in the following typerule.

G ` e1 : T G ` e2 : T(t-equ)

G ` e1= e2 : Unit

Note that type equivalence has nothing to do withequivalence of values, e.g., equation 4 = 10 istype correct, since integers 4 and 10 are typeequivalent. However, this is of course not a validequation, since the values on the right and left sideare not the same.

The Unit type (not to confuse with physicalunits), shown as the resulting type of the equa-tion, is often used as a type for uninteresting resultvalues.

A closely related concept to type equivalence istype declaration, i.e., when a type is declared asa specific name or identifier. For example, thefollowing Modelica record declaration

record PersonString name;Integer age;

end Person;

declares a type with name Person. Some lan-guages would treat this as a new unique type thatis not equal to any other type. This is calledopaque type declaration. In other languages, thisdeclaration would simply mean that an alternativename is given to this type. However, the type canalso be expressed by other names or without anyname. This latter concept is commonly referredas transparent type declaration.

In a pure nominal type system, types are com-pared (subtyping and type equivalence) by usingthe names of the declared types, i.e., opaque type

declarations are used. Type equivalence is con-trolled by checking that the same declared nameis used. Furthermore, the subtype relation inOO languages is checked by validating the inheri-tance order between classes. The C++ language ismainly using a nominal type system, even if partsof the language does not obey the strict nominalstructure.

Consider the listing in Figure 4, which illus-trates a C++ model similar to the resistor ex-ample earlier given as Modelica code in Figure 2.In this case, Resistor is a subclass of TwoPinand the type of Resistor is therefore also asubtype of TwoPin’s type. However, the typeof Inductor is not a subtype to the type ofTwoPin, since Inductor does not inherit fromTwoPin. Moreover, Resistor2 is not typeequivalent to Resistor even if they have thesame structure and inherits from the same baseclass, since they are opaquely declared.

class Pin{public:float v, i;

};

class TwoPin{public:TwoPin() : v(0),i(0){};float v, i;Pin p, n;

};

class Resistor : public TwoPin{public:Resistor() : r(100) {};float r;

};

class Resistor2 : public TwoPin{public:Resistor() : r(200) {};float r;

};

class Inductor{public:TwoPin() : v(0),i(0){};float v, i;Pin p, n;const float L;

};

Figure 4: Resistor inheritance example inC++.

307

Types in the Modelica Language

Page 6: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

In a structural type system [12], declarations are

introducing new names for type expressions, butno new types are created. Type equivalence andsubtype relationship is only decided depending onthe structure of the type, not the naming.

The Modelica language is inspired by the typesystem described by Abadi and Cardelli in [1]and is using transparent type declarations, i.e.,Modelica has a structural type system. Con-sider the Resistor example given in Figure 2and the two complementary models Inductorand Resistor2 in Figure 5. Here, the samerelations holds between TwoPin and Resistor,i.e., that the type of Resistor is a subtype ofTwoPin’s type. The same holds between TwoPinand Resistor2. However, now Resistor andResistor2 are type equivalent, since they havethe same structure and naming of their publicelements. Furthermore, the type of Inductoris now a valid subtype of TwoPin’s type, sinceInductor contains all public elements (type andname) of the one available in TwoPin.

model Resistor2extends TwoPin;parameter SI.Resistance R=200;

equationR*i = v;

end Resistor;

model InductorPin p, n;SI.Voltage v;SI.Current i;parameter SI.Inductance L=1;

equationL*der(i) = v;

end Inductor;

Figure 5: Complementary Inductor andResistor2 models to the example in Figure 2.

It is important to stress that classes and types ina structural type system are not the same thing,which also holds for Modelica. The type of a classrepresents the interface of the class relevant to thelanguage’s type rules. The type does not includeimplementation details, such as equations and al-gorithms.

Note that a nominal type system is more re-strictive than a structural type system, i.e., twotypes that have a structured subtype relation canalways have a subtype relation by names (if thelanguage’s semantics allows it). However, the op-

posite is not always true. Recall the Dequeueexample listed in Figure 3. The class Stack hasa subclass relation to Dequeue, but a subtype re-lation cannot be enforced, due to the structure ofthe class. The converse could be true, but thetype system of C++ would not allow it, since itis nominal and subtype relationships are based onnames. Hence, a structural type system can beseen as more expressive and flexible compared toa nominal one, even if both gives the same level oflanguage type safety.

3 Polymorphism

A type system can be monomorphic in which eachvalue can belong to at most one type. A type sys-tem, as illustrated in Figure 1, consisting of thedistinct types function, integer, real, and booleanis a monomorphic type system. Conversely, in apolymorphic type system, each value can belongto many different types. Languages supportingpolymorphism are in general more expressive com-pared to languages only supporting monomorphictypes. The concept of polymorphism can be han-dled in various forms and have different namingdepending on the paradigm where it is used. Fol-lowing John C. Mitchell’s categorization, polymor-phism can be divided into the following three maincategories [10]:

• Subtype Polymorphism

• Parametric Polymorphism

• Ad-hoc Polymorphism

There are other similar categorizations, such asCardelli and Wegner’s [3], where the ad-hoc cat-egory is divided into overloading and coercion atthe top level of categories.

3.1 Subtype Polymorphism

Subtyping is an obvious way that gives polymor-phic behavior in a language. For example, an in-stance of Resistor can be represented both as anTwoPin type and a Resistor type. This state-ment can also be shown according to the rule ofsubsumption (t-sub) described in Section 2.2.

When a value is changed from one type to somesupertype, it is said to be an up-cast. Up-castscan be viewed as a form of abstraction or infor-mation hiding, where parts of the value becomes

308

D. Broman, P. Fritzson, S. Furic

Page 7: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

invisible to the context. For example, an up-castfrom Resistor’s type to TwoPin’s type hidesthe parameter R. Up-casts are always type safe,i.e., the run-time behavior cannot change due tothe upcast.

However, for subtype polymorphism to be use-ful, typically types should be possible to down-cast, i.e., to change to a subtype of a type’s value.Consider function Foo

function Fooinput TwoPin x;output TwoPin y;

end Foo;

where we assume that down-casting is allowed4. Itis in this case valid to pass either a value of typeTwoPin (type equivalence) or a subtype to thetype of TwoPin. Regardless if a value of TwoPin’sor Inductor’s type is sent as input to the func-tion, a value of TwoPin’s type will be returned. Itis not possible for the static type system to knowif this is a TwoPin, Resistor or a Inductortype. However, for the user of the function, itmight be crucial to handle it as an Inductor,which is why a down-cast is necessary.

Down-casting is however not a safe operation,since it might cast down to the wrong subtype.In Java, before version 1.5 when generics were in-troduced, this safety issue was handled using dy-namic checks and raising dynamic exceptions ifan illegal down-cast was made. Subtype polymor-phism is sometimes called ”poor-man’s polymor-phism”, since it enables polymorphic behavior, butthe safety of down-casts must be handled dynam-ically [12].

The Modelica language supports subtyping asexplained previously, but does not have any oper-ation for down-cast. Since the language does notinclude this unsafe operation, only a limited formof subtype polymorphism can be used with func-tions. For example, a function can operate on apolymorphic type as input, such as TwoPin, butit only makes sense to return values of a type thatcan be instantly used by the caller.

However, subtype polymorphism is more exten-sively used when reusing and replacing compo-nents in models, i.e., by using the redeclarekeyword.

4This function type or example is not valid in the cur-rent Modelica standard. It is used only for the purpose ofdemonstrating subtype polymorphism.

3.2 Parametric Polymorphism

The term parametric polymorphism means thatfunctions or classes can have type parameters, towhich types or type expressions can be supplied.The term parametric polymorphism is often usedin functional language communities, while peoplerelated to object-oriented languages tend to usethe term generics.

The C++ template mechanism is an exam-ple of explicit parametric polymorphism, wherethe type parameter must be explicitly declared.Consider for example Figure 6, where a tem-plate function swap is implemented. The typeparameter T must be explicitly stated whendeclaring the function. However, the type ar-gument is not needed when calling the func-tion, e.g., both int x,y; swap(x,y); andfloat i,j; swap(i,j) are valid usage of thefunction.

template<typename T>void swap(T& x, T& y){T tmp = x;x = y;y = tmp;

}

Figure 6: Explicit parametric polymorphism inC++.

Standard ML on the other hand is making useof implicit parametric polymorphism, where thetype parameters do not need to be explicitly statedwhen declaring the function. Instead, the type in-ference algorithm computes when type parametersare needed.

A notable difference of parametric and subtypepolymorphism is that all type checking of para-metric polymorphism can take place at compile-time and no unsafe down-cast operation is needed.

Standard ML and and C++ are internally han-dling parametric polymorphism quite differently.In C++ templates, instantiation to compiled codeof a function is done at link time. If for exam-ple function swap is called both using int andfloat, different code of the function is generatedfor the two function calls. Standard ML on theother hand is using uniform data representation,where all data objects are represented internally aspointers/references to objects. Therefore, there isno need to create different copies of code for dif-ferent types of arguments.

309

Types in the Modelica Language

Page 8: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

Modelica can be seen to support a limited ver-

sion of parametric polymorphism, by using the re-declare construct on local class declarations.

3.3 Ad-hoc Polymorphism

In parametric polymorphism the purpose is to de-clare one implementation that can be used withdifferent types of arguments. Ad-hoc polymor-phism, by contrast, allows a polymorphic value tobe used differently depending on which type thevalue is viewed to have.

There are several language concepts that fallunder the concept of ad-hoc polymorphism [3],where Overloading and Coercion are most notable.Other related concepts that also fall under thiscategory are Java’s instanceOf concept and dif-ferent form of pattern matching [12].

3.3.1 Overloading

A symbol is overloaded if it has two or more mean-ings, which are distinguished by using types. Thatis, a single function symbol or identifier is associ-ated with several implementations.

An example of overloading that exists in manyprogramming languages is operator overloadingfor built in types. For example, the symbol +is using infix notation and have two operands as-sociated with it. The type of these operands de-cide how the operation should be carried out, i.e.,which implementation that should be used.

Overloading can take place at either compile-time or at run-time. Overloading used at run-time is often referred to as dynamic lookup[10], dy-namic dispatch or multi-method dispatch. In mostcases, the single term overloading refers to staticoverloading taking place at compile-time. The dis-tinction becomes of course vague, if the languageis interpreted and not compiled.

Another form of overloading available in somelanguages is user-defined function overloading,where a function identifier can represent sev-eral implementations for different type arguments.Modelica is currently not supporting any form ofuser defined overloading.

3.3.2 Coercion

Another form of ad-hoc polymorphism is coer-cion or implicit type conversion, which is run-timeconversion between types, typically performed bycode automatically inserted by the compiler. The

distinction between overloading and type coer-cion is not always clear, and the two concepts arestrongly related. Consider the following four ex-pressions of multiplication [3]:

7 * 9 //Integer * Integer6.0 * 9.1 //Real * Real6 * 5.2 //Integer * Real6.0 * 8 //Real * Integer

All four of these expressions are valid Modelica ex-pressions, but they can in the context of coercionand overloading be interpreted in three differentways:

• The multiplication operator is overloadedfour times, one for each of the four expres-sions.

• The operator is overloaded twice; one for eachof the the first two expressions. If the argu-ments have different types, i.e., one is Realand the other one Integer, type coercion isfirst performed to convert the arguments toReal.

• Arguments are always implicitly converted toReal, and the operator is only defined forReals.

Type conversions can also be made explicit, i.e.,code is inserted manually by the programmer thatconverts the expression to the correct type.

In Modelica, implicit type conversion is usedwhen converting from Integer to Real. Of thethree different cases listed above, the second oneapplies to the current Modelica 2.2 standard.

4 Modelica Types

In the previous sections we described different as-pects of types for various languages. In this sec-tion we will present a concrete syntax for describ-ing Modelica types, followed by rules stating legaltype expressions for the language.

The current Modelica language specification[11] specifies a formal syntax of the language, butthe semantics including the type system are giveninformally using plain English. There is no ex-plicit definition of the type system, but an implicitdescription can be derived by reading the text de-scribing relations between types and classes in theModelica specification. This kind of implicit spec-ification makes the actual specification open forinterpretation, which may result in incompatible

310

D. Broman, P. Fritzson, S. Furic

Page 9: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

compilers; both between each other, but also tothe specification itself. Our work in this sectionshould be seen as a first step to formalize what atype in Modelica actually is. Previous work hasbeen performed to formally specify the semanticsof the language [8], but without the aim to moreprecisely define the exact meaning of a type in thelanguage.

Why is it then so important to have a precisedefinition of the types in a language? As we havedescribed earlier, a type can be seen as an interfaceto a class or an object. The concept of interfacesforms the basis for the widely accepted approachof separating specification from implementation,which is particularly important in large scale de-velopment projects. To put it in a Modelica mod-eling context, let us consider a modeling projectof a car, where different modeling teams are work-ing on the wheels, gearbox and the engine. Eachteam has committed to provide a set of specific at-tributes for their component, which specifies theinterface. The contract between the teams is notviolated, as long as the individual teams are fol-lowing this commitment of interface (the specifica-tion) by adding / removing equations (the imple-mentation). Since the types state the interfaces ina language with a structural type system, such asModelica, it is obviously decisive that they have aprecise definition.

Our aim here is to define a precise notation oftypes for a subset of the Modelica language, whichcan then further be extended to the whole lan-guage. Since the Modelica language specificationis open for interpretation, the presented type def-inition is our interpretation of the specification.

4.1 Concrete Syntax of Types

Now, let us study the types of some concrete Mod-elica models. Consider the following model B,which is rather uninteresting from a physical pointof view, but demonstrates some key concepts re-garding types.model Bparameter Real s=-0.5;connector Cflow Real p;Real q;

end C;protectedReal x(start=1);

equationder(x) = s*x;

end B;

What is the type of model B? Furthermore, if Bwas used and instantiated as a component in an-other model, e.g., B b;, what would the resultingtype for element b be? Would the type for B andb be the same? The answer to the last question isdefinitely no. Consider the following listing, whichillustrates the type of model B.

model classtype //Class type of model Bpublic parameter Real objtype s;public connector classtypeflow Real objtype p;nonflow Real objtype q;

end C;protected Real objtype x;

end

This type listing follows the grammar syntaxlisted in Figure 7. The first thing to notice is thatthe name of model B is not visible in the type. Re-call that Modelica is using a structural type sys-tem, where the types are determined by the struc-ture and not the names, i.e., the type of model Bhas nothing to do with the name B. However, thenames of the elements in a type are part of thetype, as we can see for parameter s and variablex.

The second thing to observe is that the equa-tion part of the model is missing in the type def-inition. The reason for this is that equations andalgorithms are part of the implementation and notthe model interface. Moreover, all elements s, Cand x are preserved in the type, but the keywordsmodel, connector and basic type Real are fol-lowed by new keywords classtype or objtype.This is one of the most important observations tomake regarding types in a class based system us-ing structural subtyping and type equivalence. Aswe can see in the example, the type of model Bis a class type, but parameter s is an object type.Simply stated: A class type is the type of oneof Modelica’s restricted classes, such as model,connector, record etc., but an object type isthe type of an instance of a class, i.e., an object.Now, the following shows the object type of b,where b represents an instance of model B:

model objtype //Object type of bparameter Real objtype s;

end

Obviously, both the type of connector C andvariable x have been removed from the type of b.The reason is that an object is a run-time entity,where neither local classes (connector C) nor pro-tected elements (variable x) are accessible from

311

Types in the Modelica Language

Page 10: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

outside the instance. However, note that this isnot the same as that variable x does not exist ina instance of B; it only means that it is not visibleto the outside world.

Now, the following basic distinctions can bemade between class types and object types:

• Classes can inherit (using extends) from classtypes, i.e., the type that is bound to the nameused in an extends clause must be a classtype and not an object type.

• Class types can contain both object types andclass types, but object types can only holdother object types.

• Class types can contain types of protected el-ements; object types cannot.

• Class types are used for compile time evalua-tion, such as inheritance and redeclarations.

type ::= (model | record | connector |block | function | package)kindo f type

{{pre f ix} type identi f ier ;} end| (Real | Integer | Boolean |

String) kindo f type

| enumeration kindo f type

enumlist

kindo f type ::= classtype | objtypepre f ix ::= access | causality |

f lowpre f ix | modi f iability |variability | outerinner

enumlist ::= ( identi f ier {, identi f ier} )access ::= public | protected

causality ::= input | output |inputoutput

f lowpre f ix ::= flow | nonflowmodi f iability ::= replaceable | modifiable |

final

variability ::= constant | parameter |discrete | continuous

outerinner ::= outer | inner |notouterinner

Figure 7: Concrete syntax of partial Modelicatypes.

Let us now take a closer look at the grammarlisted in Figure 7. The root non-terminal of thegrammar is type, which can form a class or ob-ject type of the restricted classes or the built intypes Real, Integer, Boolean, String, orenumeration. The grammar is given using avariant of Extended Backus-Naur Form (EBNF),where terms enclosed in brackets {} denote zero,one or more repetitions. Keywords appearing inthe concrete syntax are given in bold font. Allprefixes, such as public, flow, outer etc. canbe given infinitely many times. The correct usageof these prefixes is not enforced by the grammar,and must therefore be handled later in the seman-tic analysis. We will give guidelines for defaultprefixes and restrictions of the usage of prefixes inthe next subsection.

Now, let us introduce another model A, whichextends from model B:

model Aextends B(s=4);C c1;

equationc1.q = -10*der(x);end A;

The question is now what the type of model Ais and if it is instantiated to an object, i.e., A a;,what is then the type of a? The following showsthe type of model A.

model classtype //Class type of Apublic parameter Real objtype s;public connector classtypeflow Real objtype p;nonflow Real objtype q;

end C;public connector objtypeflow Real objtype p;nonflow Real objtype q;

end c1;protected Real objtype x;

end

First of all, we see that the type of model A doesnot include any extends keyword referring to theinherited model B. Since Modelica has a structuraltype system, it is the structure that is interesting,and thus a type only contains the collapsed struc-ture of inherited elements. Furthermore, we cansee that the protected elements from B are stillavailable, i.e., inheritance preserves the protectedelement after inheritance. Moreover, since modelA contains an instance of connector C, this is nowavailable as an object type for element c1 in theclass type of A. Finally, consider the type of an

312

D. Broman, P. Fritzson, S. Furic

Page 11: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

instance a of class A:

model objtype //Object type of aparameter Real objtype s;connector objtypeflow Real objtype p;nonflow Real objtype q;

end c1;end

The protected element is now gone, along withthe elements representing class types. A carefulreader might have noticed that each type defini-tion ends without a semi-colon, but elements de-fined inside a type such as model classtypeends with a semi-colon. A closer look at the gram-mar should make it clear that types themselvesdo not have names, but when part of an elementdefinition, the type is followed by a name and asemi-colon. If type expressions were to be endedwith a semi-colon, this recursive form of definingconcrete types would not be possible.

4.2 Prefixes in Types

Elements of a Modelica class can be prefixed withdifferent notations, such as public, outer orreplaceable. We do not intend to describe thesemantics of these prefixes here, instead we referto the specification [11] and to the more accessibledescription in [5]. Most of the languages prefixeshave been introduced in the grammar in Figure 7.However, not all prefixes are allowed or have anysemantic meaning in all contexts.

In this subsection, we present a partial defini-tion of when different prefixes are allowed to ap-pear in a type. In currently available tools forModelica, such as Dymola [4] and OpenModelica[6], the enforcement of these restrictions is sparse.The reason for this can both be the difficultiesto extract this information from the specificationand the fact that the rules for the type prefixesare very complex.

In Figure 8 several abbreviations are listed. Thelower case abbreviations a, c, c′ etc. define sets ofprefixes. The uppercase abbreviations M, R etc.together with a subscription of c for class typeand o for object type, represents the type of anelement part of another type. For example Mc isa model class type, and Ro is a record object type.

Now, consider the rules for allowed prefixes ofelements shown in the tables given in Figure 9,Figure 10, and Figure 11.

In Figure 9 the intersection between the col-umn (the type of an element) and the row (the

M = modelR = recordC = connectorB = blockF = functionP = packageX = Integer, Boolean,

enumeration, StringY = Reala = {public, protected} Accessa′ = {public}c = {input, output, Causality

inputoutput}c′ = {input, output}f = {flow, nonflow} Flowprefixm = {replaceable, Modifiability

modifiable, final}m′= {modifiable, final}v = {constant, parameter Variability

discrete, continuous}v′ = {constant, parameter

discrete}v′′= {constant}o = {outer, inner, Outerinner

notouterinner}

Figure 8: Abbreviation for describing allowed pre-fixes. Default prefixes are underlined.

Mc Rc Cc Bc Fc Pc Xc Yc

Mc amo amo amo amo amo . amo amoRc . . . . . . . .Cc . . . . . . . .Bc amo amo amo amo amo . amo amoFc . am . . am . am amPc am amv′′ am am am a′m am am

Figure 9: Prefixes allowed for elements of classtype (columns) inside a class type (rows).

Mo Ro Co Bo Fo Po Xo Yo

Mc amo acmo acmo amo amo . acmv′o acmvoRc . mo . . . . mv′o mvoCc . mo mo . . . m mc f voBc amo ac′mo ac′mo amo amo . ac′mv′o ac′mvoFc . ac′m . . am . ac′mv′ ac′mvPc . amv′′ . . . . amv′′ amv′′

Figure 10: Prefixes allowed for elements of objecttype (columns) inside a class type (rows).

type that contains this element) states the al-lowed prefixes for this particular element. Thistable shows which prefixes that are allowed fora class type that is part of another class type.For example, recall the connector C in model A.When looking at the type of A, we have a classtype (the model class type) that contains an-

313

Types in the Modelica Language

Page 12: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

Mo Ro Co Bo Fo Po Xo Yo

Mo o cm′o co o o . cm′v′o cm′voRo . m′o . . . . m′v′o m′voCo . m′o o . . . . c f m′voBo o c′o c′o o o . c′m′v′o c′m′voFo . c′ . . . . m′v′ m′vPo . . . . . . . .

Figure 11: Prefixes allowed for elements of objecttype (columns) inside an object type (rows).

other class type (the connector class type), i.e.,the allowed prefixes are given in the intersec-tion of row 1 and column 3. In this case, ac-cess prefixes public and protected, modifia-bility prefixes replaceable, modifiable, andfinal, and outer/inner prefixes outer, innerand notouterinner are allowed.

We have introduced a number of new prefixes:inputoutput, notouterinner, nonflow,modifiable, and continuous. These new pre-fixes are introduced to enable a complete type de-finition, e.g., it should be possible to explicitlyspecify that a variable in a connector is not a flowvariable by giving a nonflow prefix. However,for simplicity, sometimes it is more convenient toleave out some of the prefixes, and instead usedefault prefixes. The defined default prefixes areshow underlined in Figure 8. If no underlined pre-fix exists in a specific set, this implies that theprefix must be explicitly stated.

Analogous to the description of Figure 9, Fig-ure 10 shows the allowed prefixes for elements ofobject types contained in a class type and Fig-ure 11 shows object types contained in objecttypes. There are no tables given for class typescontained in object types for the simple reasonthat object types are not allowed to contain classtypes.

In some of the cells in the tables describedabove, a dot symbol is shown. This means thatthe specific type of element inside a certain typeis not allowed. Hence, such a combination shouldnot be allowed by the compiler at compile-time.

Now, let us observe some general trends be-tween the allowed attributes. First of all, objecttypes cannot contain class types, which is whythere are only 3 tables. Secondly, access prefixes(public, protected) are only allowed in classtypes, which is why Figure 11 does not containany abbreviation a. Thirdly, the replaceableprefix does not make sense in object types, sinceredeclarations may only occur during object cre-

ation or inheritance, i.e., compile-time evaluation.Then when an object exists, the type informationfor replaceable is of no interest any more. Finally,we can see that package class types can hold anyother class types, but no other class type can holdpackage types.

Note that several aspects described here are ourdesign suggestions for simplifying and making thelanguage more stringent from a type perspective.Currently, there are no limitations for any classto contain packages in the Modelica specification.Furthermore, there are no strict distinctions be-tween object- and class types, since elaborationand type checking are not clearly distinguished.Hence, redeclaration of elements in an object arein fact possible according to the current specifica-tion, even if it does not make sense in a class basedtype perspective.

4.3 Completeness of the Type Syntax

One might ask if this type definition is completeand includes all aspects of the Modelica languageand the answer to that question is no. There areseveral aspects, such as arrays, partial and en-capsulated classes, units, constrained types, con-ditional components and external functions thatare left out on purpose.

The main reason for this work is to pinpoint themain structure of types in Modelica, not to formu-late a complete type definition. As we can see fromthe previous sections, the type concept in the lan-guage is very complex and hard to define, due tothe large number of exceptions and the informaldescription of the semantics and type system inthe language specification.

The completeness and correctness of the allowedtype prefixes described in the previous section de-pend on how the specification is interpreted. How-ever, the notation and structure of the concretetype syntax should be consistent and is intendedto form the basis for incorporating this improvedtype concept tighter into the language.

Finally, we would like to stress that definingtypes of a language should be done in parallel withthe definition of precise semantic and type rules.Since the latter information is currently not avail-able, the precise type definition is obviously notpossible to validate.

314

D. Broman, P. Fritzson, S. Furic

Page 13: Types in the Modelica Language

The Modelica Association Modelica 2006, September 4th – 5th

5 Conclusion

We have in this paper given a brief overview ofthe concept of types and how they relate to theModelica language. The first part of the paperdescribed types in general, and the latter sectionsdetailed a syntax definition of how types can beexpressed for the Modelica language.

The current Modelica specification uses Ex-tended Backus-Naur Form (EBNF) for specify-ing the syntax, but the semantics and the typesystem are informally described. Moreover, theModelica language has become difficult to reasonabout, since it has grown to be fairly large andcomplex. By giving the types for part of the lan-guage we have illustrated that the type conceptis complex in the Modelica language, and that itis non-trivial to extract this information from thelanguage specification.

Consequently, we think that it is important toaugment the language specification by using moreformal techniques to describe the semantics andthe type system. We therefore propose that a sub-set of Modelica should be defined, which modelsthe core concepts of the language. This subsetshould be describe using operational semantics in-cluding formal type rules. For some time, deno-tational semantics has been used as the semanticlanguage of choice, however it has been shown tobe less cumbersome to prove type soundness usingoperational semantics [15].

In the short term, this proposed core languageis supposed to be used as basic data for betterdesign decision-making, not as an alternative orreplacement of the official Modelica specification.However, the long term goal should, in our op-tion, be to describe the entire Modelica languageformally.

Acknowledgments

Thanks to Thomas Schon and Kaj Nystrom formany useful comments of this paper.

This research work was funded by CUGS (theSwedish National Graduate School in ComputerScience), by SSF under the VISIMOD project, andby Vinnova under the NETPROG Safe and SecureModeling and Simulation on the GRID project.

References

[1] Martın Abadi and Luca Cardelli. A Theory ofObjects. Springer-Verlag, New York, USA, 1996.

[2] Luca Cardelli. Type Systems. In The ComputerScience and Engineering Handbook, chapter 97.CRC Press, second edition, 2004.

[3] Luca Cardelli and Peter Wegner. On Understand-ing Types, Data Abstraction, and Polymorphism.ACM Comput. Surv., 17(4):471–523, 1985.

[4] Dynasim. Dymola - Dynamic Modeling Labo-ratory with Modelica (Dynasim AB). http://www.dynasim.se/ [Last accessed: 8 May 2006].

[5] Peter Fritzson. Principles of Object-OrientedModeling and Simulation with Modelica 2.1.Wiley-IEEE Press, New York, USA, 2004.

[6] Peter Fritzson, Peter Aronsson, Hakan Lundvall,Kaj Nystrom, Adrian Pop, Levon Saldamli, andDavid Broman. The OpenModelica Modeling,Simulation, and Development Environment. InProceedings of the 46th Conference on Simulationand Modeling (SIMS’05), pages 83–90, 2005.

[7] Atsushi Igarashi, Benjamin C. Pierce, and PhilipWadler. Featherweight Java: a minimal core cal-culus for Java and GJ. ACM Trans. Program.Lang. Syst., 23(3):396–450, 2001.

[8] David Kagedal and Peter Fritzson. Generating aModelica Compiler from Natural Semantics Speci-fications. In Proceedings of the Summer ComputerSimulation Conference, 1998.

[9] Robin Milner. A Theory of Type Polymorphism inProgramming. Journal of Computer and SystemSciences, 17(3):348–375, 1978.

[10] John C. Mitchell and Krzysztof Apt. Concepts inProgramming Languages. Cambridge UniversityPress, 2003.

[11] Modelica Association. Modelica - A UnifiedObject-Oriented Language for Physical SystemsModeling - Language Specification Version 2.2,February 2005. Available from: http://www.modelica.org [Last accessed: 29 March 2006].

[12] Benjamin C. Pierce. Types and Programming Lan-guages. The MIT Press, 2002.

[13] Alan Snyder. Encapsulation and Inheritance inObject-Oriented Programming Languages. InOOPLSA ’86: Conference proceedings on Object-oriented programming systems, languages and ap-plications, pages 38–45, New York, USA, 1986.ACM Press.

[14] Don Syme. Proving Java Type Soundness. LectureNotes in Computer Science, 1523:83, 1999.

[15] Andrew K. Wright and Matthias Felleisen. A Syn-tactic Approach to Type Soundness. Informationand Computation, 115(1):38–94, 1994.

315

Types in the Modelica Language