institutionen för datavetenskap - diva portal752811/fulltext01.pdf · institutionen för...

248
1 Institutionen för datavetenskap Department of Computer and Information Science Final Thesis Type Inferencing and MATLAB to Modelica Translation by Mohammad Jahanzeb LIU-IDA/LITH-EX-A--14/051-SE 2014-09-09 Linköpings universitet 581 83 Linköping Linköpings universitet SE-581 83 Linköping, Sweden

Upload: doannguyet

Post on 14-Jul-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

1

Institutionen för datavetenskap Department of Computer and Information Science

Final Thesis

Type Inferencing and MATLAB to Modelica Translation

by

Mohammad Jahanzeb

LIU-IDA/LITH-EX-A--14/051-SE

2014-09-09

Linköpings universitet

581 83 Linköping Linköpings universitet

SE-581 83 Linköping, Sweden

2

Linköping University

Department of Computer and Information Science

Master's Thesis

Type Inferencing and MATLAB to Modelica Translation

by

Mohammad Jahanzeb

LIU-IDA/LITH-EX-A--14/051-SE

2014-09-09

Supervisor: Lena Buffoni Department of Computer and Information Science

Examiner: Peter Fritzson Department of Computer and Information Science

3

På svenska Detta dokument hålls tillgängligt på Internet – eller dess framtida ersättare –

under en längre tid från publiceringsdatum under förutsättning att inga extra-ordinära omstä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 ickekommersiell forskning och för undervisning. Överföring av upphovsrätten vid en senare tidpunkt kan inte upphäva detta tillstånd. All annan användning av dokumentet kräver upphovsmannens medgivande. För att garantera äktheten, säkerheten och tillgängligheten finns det lösningar av teknisk och administrativ art.

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

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

In English The publishers will keep this document online on the Internet - or its possible

replacement - for a considerable time from the date of publication barring exceptional circumstances.

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

According to intellectual property law the author has the right to be mentioned when his/her work is accessed as described above and to be protected against infringement.

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

© [Mohammad Jahanzeb]

4

Abstract

Matlab is a proprietary, interactive, dynamically-typed language for technical computing. It is

widely used for prototyping algorithms and applications of scientific computations. Since it is a

dynamically typed language, the execution of programs has to be analyzed and interpreted which

results in lower computational performance. In order to increase the performance and integrate

with Modelica applications it is useful to be able to translate Matlab programs to statically typed

Modelica programs. This project presents the design and implementation of Matlab to Modelica

translator. The Lexical and Syntax analysis is done with the help of the OMCCp (OpenModelica

Compiler Compiler parser generator) tool which generates the Matlab AST, which is later used

by the translator for generating readable and reusable Modelica code.

5

Acknowledgements

I would like to express my deep gratitude to Professor Peter Fritzson and my supervisor Dr.

Olena Rogovchenko for their guidance, enthusiastic encouragement and useful critiques of this

research work. I would also like to thank my technical supervisor Mr. Arunkumar Palanisamy for

his advice and assistance in keeping my progress on schedule and helping me with the

difficulties I encountered.

I would also like to extend my thanks to IDA (Department of Computer and Information

Science) for offering its location and resources.

Finally, I wish to thank my parents for their support and encouragement throughout my study.

6

Table of Contents Chapter 1 ....................................................................................................................................... 10

Introduction ................................................................................................................................... 10

1.1 Introduction ......................................................................................................................... 10

1.2 Thesis Objective.................................................................................................................. 12

1.3 Intended Audience .............................................................................................................. 12

1.4 Thesis Organization ............................................................................................................ 12

Chapter 2 ....................................................................................................................................... 14

Related Work ................................................................................................................................ 14

2.1 FALCON............................................................................................................................. 14

2.2 McFOR ............................................................................................................................... 14

2.3 Taming MATLAB .............................................................................................................. 15

2.4 MATLAB Alternatives ....................................................................................................... 15

2.4.1 GNU Octave................................................................................................................. 15

2.4.2 FreeMat ........................................................................................................................ 16

2.4.3 Scilab............................................................................................................................ 16

Chapter 3 ....................................................................................................................................... 18

Theoretical Background ................................................................................................................ 18

3.1 What is MATLAB?............................................................................................................. 18

3.2 Type System........................................................................................................................ 18

3.3 Matlab Language ................................................................................................................ 19

3.4 Vector .................................................................................................................................. 19

Listing 3.4.b Column vector .................................................................................................... 19

3.5 Matrix .................................................................................................................................. 19

3.6 Matrix indexing ................................................................................................................... 20

3.7 Colon operator (:) ................................................................................................................ 20

3.8 Colon operator in a Matlab matrix ...................................................................................... 20

3.9 Matrix generators ................................................................................................................ 21

3.10 Array operations................................................................................................................ 21

3.10.1 Matrix arithmetic operations ...................................................................................... 21

3.10.1 Array arithmetic operations ....................................................................................... 22

3.11 Functions ........................................................................................................................... 22

3.11.1 Primary Function/Function ........................................................................................ 22

Listing 3.11.1 Matlab function.................................................................................................. 23

7

3.11.2 Sub-function ................................................................................................................... 23

3.11.3 Anonymous Functions ................................................................................................... 24

3.12 Control Flow ..................................................................................................................... 24

3.13 Operators ........................................................................................................................... 24

3.13.1 Arithmetic operators ...................................................................................................... 25

3.13.2 Relational operators ....................................................................................................... 25

3.13.3 Logical operators ........................................................................................................... 26

3.14 The OpenModelica Project ............................................................................................... 26

3.15 Modelica ........................................................................................................................... 27

3.16 MetaModelica ................................................................................................................... 27

3.16.1 uniontype.................................................................................................................... 28

Listing 3.16.1 MetaModelica uniontype ............................................................................... 28

3.16.2 match .......................................................................................................................... 28

3.16.3 list ............................................................................................................................... 29

Chapter 4 ....................................................................................................................................... 30

Design and Implementation of a Matlab Scanner and Parser ....................................................... 30

4.1 Lexical Analysis: Scanner................................................................................................... 31

Listing 4.1: Lexical analysis ..................................................................................................... 33

4.2 Flex ..................................................................................................................................... 33

4.3 Syntax Analysis: Parser ...................................................................................................... 36

4.4 GNU Bison.......................................................................................................................... 37

4.5 OMCCp ............................................................................................................................... 39

4.6 Abstract Syntax of the MATLAB- AbsynMat.mo "MATLAB AST" ................................ 41

Chapter 5 ....................................................................................................................................... 44

Design and Implementation of the Translator .............................................................................. 44

5.1 Type Inference .................................................................................................................... 46

Type Inference ...................................................................................................................... 47

5.1.1 Statement where the Right Hand Side is a constant .................................................... 48

5.1.2 Statement where the Right Hand Side is Built-in function .......................................... 49

5.1.3 Statement where the Right Hand Side is a computational expression and contains

arithmetic operator (array) .................................................................................................... 51

5.1.4 Statement where the Right Hand Side is a computational expression and contains an

arithmetic operator (scalar) ................................................................................................... 51

5.1.5 Statement where the Right Hand Side is a computational expression and contains a

relational operator ................................................................................................................. 52

8

5.1.6 The Right Hand Side is not equal to the Left Hand Side ............................................. 52

5.2 Translator ............................................................................................................................ 54

5.2.1 Primary Functions ........................................................................................................ 54

5.2.2 Translation of function declaration statements ............................................................ 57

5.2.3 Identification and Translation of Local identifiers ...................................................... 58

5.2.4 Identification and Translation of constant identifiers .................................................. 60

5.3 Translation of Function Body ............................................................................................. 63

5.3.1 Identification and Translation of Function Call ........................................................... 63

5.3.2 Identification and Translation of Anonymous function to sub-function ..................... 66

5.4 Translation of looping statements ....................................................................................... 68

5.5 Translation of if statements ................................................................................................. 69

5.6 Translation of Switch Statement ......................................................................................... 70

5.7 Sub-function ........................................................................................................................ 72

Chapter 6 ....................................................................................................................................... 73

Testing and Performance Evaluation ............................................................................................ 73

6.1 Testing Lexer and Parser .................................................................................................... 73

6.2 Testing Translator ............................................................................................................... 75

6.3 Performance ........................................................................................................................ 78

Chapter 7 ....................................................................................................................................... 80

Conclusion and Future work ......................................................................................................... 80

7.1 Conclusion .......................................................................................................................... 80

7.2 Supported Subset Features .................................................................................................. 80

7.3 Future work ......................................................................................................................... 81

7.3.1 Dimensions determination at Runtime ............................................................................. 81

7.3.2 Variable type determination at Runtime .......................................................................... 82

Chapter 8 ....................................................................................................................................... 84

User Guide .................................................................................................................................... 84

8.1 Getting Started .................................................................................................................... 84

8.2 Commands to Run the Code ............................................................................................... 84

References ..................................................................................................................................... 86

Appendix A ................................................................................................................................... 89

Appendix B ................................................................................................................................... 92

Appendix C ................................................................................................................................. 105

Appendix D ................................................................................................................................. 114

9

10

Chapter 1

Introduction

1.1 Introduction

Matlab1 is a high-performance interactive language for technical computing. It integrates

computation, visualization, and programming in an easy-to-use environment where problems and

solutions are expressed in familiar mathematical notation.[1] It is a dynamically typed language

and thus it doesn't require any type declarations. A variable’s type is implicit from the semantics

of its operations and the type is allowed to dynamically change at runtime. These features

improves ease of use for prototyping and interactive use, but add heavy run-time overheads, such

as runtime type checking, array bounds checking and dynamic resizing, to its interpretive

execution. Therefore programs written in the Matlab often run slower than their counterparts

which are written in conventional statically typed programming languages.

The main goal of this work is the development of a translator that accepts Matlab programs as

input and generates Modelica code as output which is suitable for static compilation. Due to the

complexity of the Matlab language, a realistic goal is to develop a translator for a subset of

Matlab.

The translation task of Matlab to Modelica code mainly involves the front-end implementation of

the Matlab to Modelica compiler. The OMCC (OpenModelica Compiler Compiler) compiler

generation tool, which has been developed as a part of the OpenModelica project, can be used as

a parser and translator generator extended with advanced error handling facilities. The tool is

implemented in MetaModelica and integrated with the MetaModelica semantics specification

language based on operational semantics for generating executable compiler and interpreter

modules. The OMCCp part of the OMCC tool makes the implementation of the first two stages

of a compiler much easier. We have to write the lexer and parser rules for the Matlab language

and input them to the OMCCp to generate the appropriate lexer and parser modules in

MetaModelica. The generated parser builds the Abstract Syntax Tree (AST) for the Matlab

source code that is parsed. The Matlab AST is later used by the second phase of the Matlab-to-

Modelica translator which performs a series of internal transformations and finally generates the

1MATLAB is a registered trademark of the MathWorks, Inc.

11

Modelica-AST which is unparsed to readable Modelica code. Hence the implementation of

translator consists of two main parts. First the implementation of lexer & parser and second the

implementation of translator.

Figure 1.1: Overview of our Translator.

The overall goal of the translator is to take the Matlab programs m files as input and produce

output in Modelica language which is suitable for static compilation.

There exists a large body of computational algorithms which are programmed in the Matlab

language. They need to have an easy way of using and incorporating such algorithms within

Modelica models, as well as achieving improved performance, motivated the development of the

Matlab to Modelica translator in the OpenModelica project.[2]

Scanner

Parser

Translator

Unparser

OMCCp

Matlab program

.m files

Tokens

Matlab AST

Modelica AST

Modelica source

code

Lexer

Generator Parser

Generator

12

1.2 Thesis Objective

The objective of this master thesis project is to design and implement a translator for the

MATLAB language which not only enables the translation of the MATLAB programs to

Modelica code but also perform type inference to construct the type information. Moreover the

generated code is in readable & reusable form and maintain the original structure of code.

1.3 Intended Audience

The reader of this thesis report could be someone who has an interest in source to source

compiler specifically translating from dynamic to static language.

1.4 Thesis Organization

This thesis describes the design and implementation of Matlab to Modelica Translator. The rest

of the thesis is organized as follows. Chapter 2 covers the related work and alternatives of

Matlab Chapter 3 covers the theoretical background of Matlab, OpenModelica, Modelica and

MetaModelica language Chapter 4 covers the design and implementation of scanner and parse

Chapter 5 covers the design and implementation of translator Chapter 6 testing and performance

evaluation and finally Chapter 7 conclusion, supported subset features and future work.

13

14

Chapter 2

Related Work

In this chapter we discuss some previous related work in the area of compilers where the

attempts have been made for the performance improvement of Matlab programs. These projects

helped a lot in the development of our translator specially in the designing and implementing of

type inference algorithm. These research works include FALCON, McFor and MATLAB Tamer.

We also discuss some open source Matlab similar languages, which includes Octave, FreeMat

and Scilab.

2.1 FALCON

FALCON is a Matlab to Fortan 90 translator.

FALCON presented an excellent and simple algorithm to differentiate the Matlab functions from

an identifiers. [3] [4] We acquired a good idea from the algorithm presented for identification of

Matlab functions in FALCON project therefore we used similar approach in our translator and

discussed in detail about our approach in section 5.3.1 Identification and Translation of Function

Calls.

FALCON also presented the techniques for static inference method and dynamic inference

method to translate Matlab programs into Fortran 90. The approach they used for type

inferencing, is to process only one function at time and avoids the complexity of using Fortran to

simulate passing dynamically allocated arrays between functions. This is simple approach but the

problem with this approach is that, the generated code is less readable and thus difficult to reuse.

Since our goal is to generate readable and reusable code therefore we avoided this technique.

FALCON also inlines all the Matlab scripts and user-defined functions into single function thus

the generated Fortran code has only one function without any sub-functions.

2.2 McFOR

McFOR is a Matlab to Fortran 95 translator. McFor extracts information from the high-level

semantics of the Matlab programs to produce efficient, reusable and readable Fortran code. [5]

15

McFOR presented techniques for type inference which includes evaluation of basic types and

dimensions of an array variables and uses a value propagation analysis to precisely estimate the

sizes of arrays. We adopted a similar approach in our translator which is discussed in detail in

Section 5.1 Type Inference. [5]

McFOR generates readable Fortran code by translating the user-defined functions of the

MATLAB program into sub functions and keep the function declaration same as the original

MATLAB functions. The problem with McFOR is that it has an incomplete approach to the

builtin functions. Since built-in functions in the Matlab are well defined they play a very vital

role during type evaluation process. We tried to provide maximum support for built-in functions

specially functions for array generators, like zeros and ones. Further details about our approach is

in section 5.1.2 Statement where Right Hand Side is Built-in function.

2.3 Taming MATLAB

The Matlab tamer is an open source extensible object-oriented framework for generation of static

programs from dynamic Matlab programs implemented in Java. The Matlab Tamer supports a

large subset of Matlab. It builds a complete call graph, transforms every function into a reduced

intermediate representation, and provides typing information to aid the generation of static code.

[6]

2.4 MATLAB Alternatives

There are three alternatives. GUN Octave, FreeMat and Scilab.

2.4.1 GNU Octave

GNU Octave is a high-level language, primarily intended for numerical computations. [12] The

Octave language is almost similar to MATLAB and it is written in the C++ language where they

used polymorphism for type checking. This package was developed by John W. Eaton and

named after Octave Levenspiel, a professor at Oregon State University. GUN Octave also uses

BLAS (Basic Linear Algebra Subprograms), LAPACK (Linear Algebra Package) and other

Fortran packages. [7] The Octave language is quite similar to Matlab so that most programs are

easily portable. Since it is an open source language and the Octave grammar is available online

we got much help in writing the Matlab grammar for our translator, only we had to figure out the

16

differences between the Octave and Matlab languages. We identified the differences first and

made modification accordingly in the grammar file. We discuss this in detail in the section 4.3

Syntax Analysis.

2.4.2 FreeMat

FreeMat is a free environment for rapid engineering, scientific prototyping and data processing.

[13] It is an open source and similar to MATLAB and GUN Octave. FreeMat is available under

the GPL license. The supported operating systems for FreeMat include Windows, Linux, and

Mac.

The installation of FreeMat is user friendly. A Built-in editor is available for writing FreeMat

programs. The FreeMat system was developed by Samit Basu with the hope of constructing a

free numerical computational package that is Matlab compatible. Features for FreeMat include

eigenvalue and singular value decompositions, 2D/3D plotting, parallel processing with MPI,

handle-based graphics, function pointers, etc. [7]

2.4.3 Scilab

"Scilab is free and open source software for numerical computation providing a powerful

computing environment for engineering and scientific applications."[14] Scilab was written by

a group at INRIA, the French National Research Institution, in 1990.

The syntax is largely based on Matlab language and also supports hundreds of functions. The

supported functionalities include the following.

Maths & Simulation

For usual engineering and science applications including mathematical operations and data

analysis.

2-D & 3-D Visualization

Graphics functions to visualize, annotate and export data and many ways to create and customize

various types of plots and charts.

17

Optimization

Algorithms to solve constrained and unconstrained continuous and discrete optimization

problems.

Statistics

Tools to perform data analysis and modeling

Control System Design & Analysis

Standard algorithms and tools for control system study

Signal Processing

Visualize, analyze and filter signals in time and frequency domains.

Application Development

Increase Scilab native functionalities and manage data exchanges with external tools.

Xcos - Hybrid dynamic systems modeler and simulator

Modeling mechanical systems, hydraulic circuits and control systems

18

Chapter 3

Theoretical Background

In this chapter we present an overview of the Matlab language and cover the main differences

between the Matlab and Modelica languages. The next part present an overview of the

OpenModelica project including the Modelica and MetaModelica languages.

3.1 What is MATLAB?

The MATLAB (short for matrix laboratory) is a high-performance interactive language for

technical computing. It integrates computation, visualization, and programming in an easy-to-use

environment where problems and solutions are expressed in familiar mathematical notation. [1]

Typical uses include: Math and computation, Algorithm development, Modeling, Simulation,

and prototyping etc.

Some important features of the language are: Efficient matrix and vector computations, Easy

creation of scientific and engineering graphics, Application development, including graphical

user interface building and Object-oriented programming.

MATLAB was originally designed in the 1970s by Cleve Moler, then chairman of the computer

science department at the University of New Mexico. His main purpose was to give his students

access to LINPACK "LINear equations software PACKage" and EISPACK "Eigensystem

Package Subroutine Computing Facility" without learning Fortran. It almost immediately spread

to other universities and found a strong audience within the applied mathematics community. [8]

3.2 Type System

As we already discussed in the introduction part that Matlab is a dynamically typed language.

Variables are not declared while writing a program and the variable types are determined at the

runtime. Matlab automatically allocates the right amount of storage whenever it encounters a

new variable and if a variable changes it re-allocates memory.

It is also weakly typed language. Here the type of variables are not enforced. For example; we

can concatenate string "55" and the integer 6 to get "556" and then treat it as an integer without

stating any explicit conversions. Instead, conversions are made implicitly.

19

3.3 Matlab Language

Matlab is a high-level array language with control flow statements, functions, data structures,

input/output, and object-oriented programming features. [1]

Matlab is also one of the few languages in which each variable is a matrix. A matrix is a two-

dimensional array consisting of m rows and n columns. Every value is a Matrix with some

number of dimensions, even scalar values are 1×1 matrices. Vectors are either 1×n or n×1

matrices and strings are just vectors of characters.

3.4 Vector

A vector in Matlab is a matrix with either one row or one column. The distinction between row

vectors and column vectors is important because Modelica declares such vectors differently. An

array of dimension 1 x n is called a row vector whereas an array of dimension m x 1 is called a

column vector. The elements of vectors are enclosed by square brackets and are separated by

spaces or by commas. Listing 3.4 shows the example of vector declaration in both languages.

Matlab - vec = [5,7,9,14,18]

Modelica - Integer[5] vec = array(5,7,9,14,18)

Listing 3.4. Vector

Column vectors are created in a similar way but we must separate the elements of column by

placing a semicolon (;). Listing 3.4.b shows the example of column vector in both languages.

Matlab - col_vec = [5;7;9;14;18]

Modelica - Integer[5,1] = [5;7;9;14;18]

Listing 3.4.b Column vector

3.5 Matrix

A matrix is a two-dimensional array consisting of m rows and n columns. The elements of matrix

are enclosed by square brackets same as vector and the elements in a row are separated with

commas or spaces. Since matrix contains more than one row thus semicolon (;) is used to

separate a rows. Listing 3.5. shows the example of matrix in both languages.

20

Matlab - matx = [1,2,3;4,5,6;7,8,9]

Modelica - Integer[3,3] matx = [1,2,3;4,5,6;7,8,9]

Listing 3.5. Matrix

Note: In Modelica, a column vector and a matrix have same declaration syntax.

3.6 Matrix indexing

Indexing into a matrix is a means of selecting a subset of elements from the matrix. The element

of row i and column j of the matrix Z is denoted by Z(i,j) therefore index Z(i,j) refers to the

element Zij of matrix Z. The first index refers the row number and the second index refers the

column number.

For example; A(1,3) is an element of first row and third column.

As shown above the Matlab uses parentheses () brackets for indexing however in Modelica

square brackets are used for matrix indexing.

For example; A[1,3]

3.7 Colon operator (:)

The colon operator is one of the most useful operator in the Matlab. It is used to create vectors,

subscript arrays, and specifying for iterations but often we deal with matrices or vectors that are

too large to enter one element at a time.

For example; If we want to enter a vector Z consisting of points (0,1,2,3,··· ,50). We can use the

command Z = 0:1:50;

The resulting row vector Z will have 51 elements.

3.8 Colon operator in a Matlab matrix

The colon operator can also be used to choose a certain row or column in a matrix.

For example; the statement Z(m:n,k:l) specifies rows m to n and column k to l. Subscript

expressions refer to portions of a matrix.

For example; A(2,:) is the second row elements of A.

21

The colon operator can also be used to extract a sub-matrix from a matrix A.

A(:,2:3)

3.9 Matrix generators

Matlab provides builtin functions that generates elementary matrices such as the matrix of zeros

and the matrix of ones. The matrix zeros(m,n) returns an m-by-n matrix of zeros and the matrix

ones(m,n) returns an m-by-n matrix of ones.

For example; Z=ones(1,3)

The resulting row vector Z will have 3 elements of 1. The above statement is equivalent as

Z=[1,1,1]

X=zeros(2,3)

The resulting matrix X will have 2x3 dimensions. The above is equivalent to:

Z=[0 0 0;0 0 0]

Both zeros and ones functions are also used in Modelica for generation of matrices.

3.10 Array operations

There are two types of arithmetic operations.

Matrix arithmetic operations and Array arithmetic operations.

You can use these arithmetic operations to perform numeric computations, for example, adding

two numbers, raising the elements of an array to a given power, or multiplying two matrices.[8]

3.10.1 Matrix arithmetic operations

Matrix operations follow the rules of linear algebra and operate on whole matrices at once unless

an argument is a scalar. These include the matrix multiplication (*), and matrix division (\, /).

For example;

Matrix multiplication: C = A*B is the linear algebraic product of the matrices A and B. The

number of columns of A must equal the number of rows of B.

22

Matrix power: A^B is A to the power B, if B is a scalar. For other values of B, the calculation

involves eigenvalues and eigenvectors.

3.10.1 Array arithmetic operations

An array operations execute element by element operations and support multidimensional arrays.

The period character (.) distinguishes the array operations from the matrix operations. However,

since the matrix and array operations are the same for addition and subtraction, the character

pairs .+ and .- are unnecessary.

Array operators;

.* Element-by-element multiplication

./ Element-by-element division

.^ Element-by-element exponentiation

Modelica uses same operators as the Matlab for array operations but the only difference is in

array addition and array subtraction. They must required period character. .+ and .- in the

Modelica language.

3.11 Functions

We discussed in detail the differences between Matlab and Modelica function in the section 5.2.1

Primary Function. Functions are an important feature of the Matlab. Besides builtin functions

Matlab also support primary functions, sub-functions and anonymous functions. All user built

functions are stored in M-files. Since these files have an extension .m thus these files are called

M-files and these files are input for our translator.

3.11.1 Primary Function/Function

A primary function allows us to create a user-defined function. The function definition states

how many inputs and outputs the function can accept and returned.

A function starts with the keyword function followed by output parameters, the function name

and the input parameters. The name of a function should be the same as the file name without

the .m extension.

23

In the listing 3.11.1 the function fnc should be placed in the file named as fnc which has an

extension .m. The given function calculates the mean and standard deviation of a vector and it

accepts a single input argument x, and returns the mean and stdev in the output argument. The

variables within the function body are local variables.

function [mean,stdev] = fnc(x)

n = length(x);

mean = sum(x)/n;

stdev = sqrt(sum((x-mean).^2/n));

end

Listing 3.11.1 Matlab function

3.11.2 Sub-function

If a M-file contains more than one function then the secondary function is called a sub-function.

A sub-function is visible only to the other functions in the same file. It is created by defining a

new function with the function keyword after the body of the preceding function or subfunction.

Example of primary and sub-function is given in the listing 3.11.2.

Listing 3.11.2. Primary function and sub-function

function [mean,stdev] = fnc(x)

n = length(x);

mean = avg(x,n);

stdev = sqrt(sum((x-avg(x,n)).^2)/n);

end

function mean = avg(x,n)

mean = sum(x)/n;

end

24

3.11.3 Anonymous Functions

An anonymous function is a function that is not stored in a program file but is associated with a

variable whose data type is a function_handle. Anonymous functions can accept inputs and

return outputs just as standard functions do. However they can contain only a single executable

statement. [8]

For example, create a handle to an anonymous function that finds the square of a number:

sqr = @(x) x.^2;

The variable sqr is a function handle. The @ operator creates the handle, and the

parentheses () immediately after the @operator include the function input arguments. This

anonymous function accepts a single input x, and implicitly returns a single output, an array the

same size as x that contains the squared values.

Since Modelica does not support such functions, as an alternate we translate anonymous

functions to sub-functions in Modelica. We cover anonymous functions in detail in section 5.3.2

Identification and Translation of anonymous function to sub functions.

3.12 Control Flow

Matlab supports four different types of control flow structures. If statement, For loop, While loop

and Switch statement.

Modelica has almost similar control flow structure however it does not support the switch

statement so far, thus as an alternate we translate all switch statements to If Else statements in

Modelica. Note that MetaModelica has match expressions, which are generalized switch

expressions.

3.13 Operators

Matlab and Modelica operators are almost similar except the following:

Element wise addition: The translator converts the Matlab "+" to Modelica ".+"

Element wise and subtraction: The translator converts the Matlab "-" to Modelica ".-"

Relational operator NOT EQUAL: The translator converts the Matlab ~= to Modelica <>

25

Logical operator AND: The translator converts the Matlab & to Modelica keyword "and"

Logical operator OR: The translator converts the Matlab | to Modelica keyword "or"

Logical operator NOT: The translator converts the Matlab ~ to Modelica keyword "not"

3.13.1 Arithmetic operators

Arithmeticd in MATLAB follows all the usual rules and uses the standard computer symbols

for its arithmetic operation signs.

plus - Plus +

uplus - Unary plus +

minus - Minus -

uminus - Unary minus -

mtimes - Matrix multiply *

times - Array multiply .*

mpower - Matrix power ^

power - Array power .^

mldivide - Backslash or left matrix divide \

mrdivide - Slash or right matrix divide /

ldivide - Left array divide .\

rdivide - Right array divide ./

3.13.2 Relational operators

eq - Equal = =

ne - Not equal ~=

lt - Less than <

gt - Greater than >

26

le - Less than or equal <=

ge - Greater than or equal >=

Note especially the double = = for logical testing of equality. The single = is only used in

MATLAB for assignments.

3.13.3 Logical operators

and - Element-wise logical AND &

or - Element-wise logical OR |

not - Logical NOT ~

3.14 The OpenModelica Project

OpenModelica2 is an open-source Modelica-based modeling and simulation environment

intended for industrial and academic usage. Its long-term development is supported by a non-

profit organization – the Open Source Modelica Consortium3 (OSMC)

The goal with the OpenModelica effort is to create a comprehensive Open Source Modelica

modeling, compilation and simulation environment based on free software distributed in binary

and source code form for research, teaching, and industrial usage.

OpenModelica contains different tools that contribute with the design and construction of

simulation projects in OpenModelica. These tools are OMEdit, ModelicaML - UML-Modelica,

OMShell, OMNotebook, DrControl and DrModelica which are OMNote-book tutorial

documents, and Modelica Development Tooling (MDT).

2OpenModelica: http://www.openmodelica.org

3OSMC: http://www.openmodelica.org/index.php/home/consortium

27

Figure 3.1: The architecture of the OpenModelica environment.

Detailed information about tools shown in above picture can be find in the given link;

https://openmodelica.org/index.php/openmodelicaworld/tools

3.15 Modelica

Modelica is an open standard and a statically strongly typed language. It is a non-proprietary,

object-oriented, equation based language to conveniently model complex physical systems

containing, e.g., mechanical, electrical, electronic, hydraulic, thermal, control, electric power or

process-oriented subcomponents. [9]

The design of the Modelica Language was started in the fall 1996 for standardization and

unification of multi-domain (multi-physics) modeling based on object oriented mathematical

modeling techniques by defining a model description language Modelica for modeling dynamic

behavior of engineering systems, intended to become a de facto standard.[9]

3.16 MetaModelica

MetaModelica is an extension of Modelica language which is used to model the semantics of the

Modelica language and other languages, and be able to express symbolic transformations of

models. MetaModelica has been developed as a part of OpenModelica project to provide a

platform for developing the OpenModelica compiler. MetaModelica adds new operators and

28

types to the Modelica language. We cover in this report the constructs uniontype, record, match

and list. [10]

3.16.1 uniontype

The uniontype is a construct that allows MetaModelica to declare types based on the union of 2

or more record types. It can be recursive and include other uniontypes. See the listing 3.16.1 as

an example of uniontype.

uniontype Exp

record INT

Integer integer ;

end INT;

record IDENT

String ident ;

end IDENT;

end Exp ;

Listing 3.16.1 MetaModelica uniontype

3.16.2 match

Match-expressions can be used either with the match or the mathcontinue keywords. The match

keyword refers that after a successful matching against a pattern in one of the case-branches no

more patterns will be matched. The matchcontinue keyword refers that even if there is a

successful match followed by a failed computation in the same case-branch, the matching will

continue with the subsequent case-branches. In our implementation we used only matchcontinue

expression. An example of the syntax for matchcontinue is presented in the listing 3.16.2.

matchcontinue s

case "one" then 1;

case "two" then 2;

case "three" then 3;

case _ then 0;

end matchcontinue;

Listing 3.16.2: matchcontinue construct in MetaModelica

29

3.16.3 list

The list operator is used to create linked lists of objects. The brackets are a constructor used to

define the list from the list elements. The operand ‘::’ is used to add items or to retrieve items

from a list. An example of the syntax for list is presented in listing 3.16.3.

list <Integer> z={1 ,2 ,3};

Listing 3.16.3: List

30

Chapter 4

Design and Implementation of a Matlab Scanner and Parser

In this chapter we discuss the design and implementation of a Matlab scanner and parser. We

also present an overview of GNU Bison and Flex that have been used for parser generator.

The main tools that have been used in the implementation of a scanner and parser are GUN

Bison and Flex. GNU Bison is an automatic parser generator in the style of yacc whereas Flex

"Fast Lexical Analyzer" is an automatic scanner generator lex tool. [11]

Figure 4.1: Structure of Translator

Scanner

Parser

Translator

Unparser

OMCCp

Matlab source

code

Tokens

Matlab AST

Modelica AST

Modelica source

code

Lexer

Generator Parser

Generator

31

4.1 Lexical Analysis: Scanner

Lexical analysis or scanner is the process of converting a sequence of characters into a sequence

of tokens. Tokens are sequences of characters with a collective meaning. It identifies the special

tokens specified by a language making it more simple for the next phase i.e. syntax analysis of

the compiler. A program which performs lexical analysis or scanning is called a lexical analyzer

or lexer. A lexical analyzer or lexer is a program that runs a Finite Automata which recognizes a

valid language based on a regular expression. The tool which we have been using for lexical

analyzer is Flex "Fast Lexical Analyzer". The detail about Flex is described in next section.

The lexical analysis is our starting phase for translator. We wrote the lexical specification from

scratch and it supports the entire Matlab vocabulary including object oriented features. Before

implementing a lexer or scanner we had to identify the Matlab identifiers, digits, number,

keywords, arithmetic, relational & logical operators and special characters. Thus we identified;

The Matlab identifier consists of a letter followed by zero or more underscores, letters or

digits.

IDENTIFIER [a-zA-Z] [_a-zA-Z0-9]*

The Matlab number can be Integer or can have decimal point and an exponent or both

decimal and exponent.

DIGIT [0-9]

DIGITS {DIGIT}+

EXPON ([DdEe][+-]?{DIGIT}+)

NUMBER (({DIGIT}+\.?{DIGIT}*{EXPON}?)|(\.{DIGIT}+{EXPON}?)|(0[xX][0-

9a-fA-F]+))

Matlab uses i and j as a reserved characters for Imaginary units

Im [iIjJ]

Horizontal Spaces and Newlines

HSPACE [ \t]

HSPACES {HSPACE}+

32

NEWLINE ((\n)|(\r)|(\r\n))

NEWLINES {NEWLINE}+

Matlab breaks a long statement by using contiguous sequence of three periods followed

by new line, carriage return or form feed character.

ELLIPSIS \.\.\.

CONTINUATION {ELLIPSIS}[^\n\r\f]*{NEWLINE}?

Comments starts with percent character '%' and continue until NEWLINE character or

end of the input.

COMMENT \%[^\n\r\f]*{NEWLINE}?

The scanner also identifies all keywords such as Function, End, While and If.

All arithmetic operators, logical operators, relational operators and special characters.

The complete lexerModelica.l file is available in appendix A.

The process of lexical analysis is shown in the listing 4.1. Lexer takes a source code as character

stream which in our case is the Matlab function and outputs a sequence of tokens. In the listing

4.1. the lexer recognized the tokens in the header line of the Matlab function keyword function,

an identifier perfect, assignment operator =, left parenthesis (, an identifier test_value and right

parenthesis ).

33

Listing 4.1: Lexical analysis

4.2 Flex

FLEX (Fast LEXical analyzer generator) is a tool for generating scanners, is a program which

recognize lexical patterns in text. It is also called a tokenizer. The Flex tool makes creating the

first stage of the compiler easier.

In order to construct a scanner, we only need to identify the vocabulary of the MATLAB

language and write a specification of patterns using regular expressions (e.g. DIGIT [0-9]) which

we already discussed in previous section.

A Flex file has three main sections, delimited by double percent sign "%%";

definitions //1st section

%%

rules //2nd section

%%

user code //3rd section "optional section"

Definition:- The definitions section contains declarations of simple name, definitions to simplify

the scanner specification, and declarations of start conditions.

34

Rules:- The rules section of the flex input contains a series of rules of the form;

pattern action

where the pattern must be unintended and the action must begin on the same line.

User Code:- The user code section is simply copied to lex.yy.c. It is used for companion routines

which call or are called by the scanner.

The flex program reads lexerModelica.l input file for a description of a scanner to generate. The

description is available in rules section in the form of pairs of regular expressions. In above

process we see that Flex generates a C source file named "lex.yy.c", which defines the function

yylex(). We require "lex.yy.c" file in order to generate lexer in MetaModelica languague. Which

we discuss in OMCCp section.

FLEX lexerMatlab.yy.c lexerMatlab.l

35

HSPACE [ \t]

HSPACES {HSPACE}+

NEWLINE ((\n)|(\r)|(\r\n))

NEWLINES {NEWLINE}+

IDENTIFIER [a-zA-Z][_a-zA-Z0-9]*

CONT (\.\.\.)

Im [iIjJ]

DIGIT [0-9]

DIGITS {DIGIT}+

EXPON ([DdEe][+-]?{DIGIT}+)

NUMBER (({DIGIT}+\.?{DIGIT}*{EXPON}?)|(\.{DIGIT}+{EXPON}?)|(0[xX][0-

9a-fA-F]+))

%%

"function" return FUNCTION;

"end" return END;

"if" return IF;

"elseif" return ELSEIF;

"else" return ELSE;

"while" return WHILE;

"for" return FOR;

{DIGITS} return INTEGER;

{NUMBER} return NUMBER;

{NUMBER}{Im} return IMAG_NUM;

{IDENTIFIER} return IDENT;

{COMMENT} ;

{HSPACES} ;

{NEWLINES} return NEWLINES;

"\+" return ADD;

"-" return SUB;

"\*" return MUL;

"\/" return DIV;

"\^" return POW;

".*" return EMUL;

"./" return EDIV;

"\.\\" return ELEFTDIV;

"\.^" return EPOW;

"\<" return EXPR_LT;

">" return EXPR_GT;

"\<=" return EXPR_LE;

">=" return EXPR_GE;

"==" return EXPR_EQ;

"~=" return EXPR_NE;

%%

The content of the lexerModelica.l file is above which contains all the keywords and tokens of

the MATLAB language. The complete lexerModelica.l file is available in appendix A.

Definition

Rules

36

4.3 Syntax Analysis: Parser

The second phase of the translator is Syntax Analysis. In the previous phase "lexical analysis"

the input is split into tokens and which are provided as input to syntax analysis "parsing" to

recombine these tokens to form a syntax tree that reflects the structure of the text. The leaves of

the syntax tree are the tokens.

Since the Matlab is not a free software thus we couldn't find a Matlab grammar.Writing the

whole grammar from scratch is a tedious task. However, we managed to find an alternative of the

Matlab which is GNU octave.

GNU Octave is a high-level interpreted language, primarily intended for numerical

computations.[12] The GNU Octave language is quite similar to Matlab but still the grammar of

Octave is not fully supported therefore we identified the dissimilarities between both languages

first and made changes accordingly in our Matlab grammar file. Currently the Matlab translator

parser supports for the entire Matlab syntax including classes.

Sample grammar rules for the Matlab function is given below. The complete parserModelica.y

file is available in Appendix B section.

Matlab support function with or without output.

function_list: function1 {} % without output %

| return_list EQ function1 {} % output handles in return list %

Function name as identifier

fcn_name : identifier {}

Function can be with or without parameters.

opt_sep "operator separator": Statements in the Matlab are separated from each

other by delimiters. Delimiters can be semicolon ';', can be comma ','.

function1 : fcn_name param_list opt_sep opt_list function_end {}

% with parameter %

| fcn_name opt_sep opt_list function_end {} % without parameters %

37

Function can be ended with or without an End keyword, since its optional in

Matlab.

function_end: {} /* empty */ % without End keyword %

| END {} % with End keyword %

4.4 GNU Bison

GNU Bison is free software and is available under the GNU General Public License. GNU

Bison is a general purpose parser generator that converts a grammar description for an LALR(1)

context free grammar into a C program to parse that grammar. Bison is a bottom up parser

generator. The parser accepts strings belonging to the language generated by the grammar and

rejects all other strings. The grammar can be ambiguous and precedence is used to resolved the

resulting conflicts.

A Bison grammar file has four main sections, shown in the listing 4.4. with the appropriate

delimiters:

%{

Prologue // 1st section

%}

Bison declarations //2nd section

%%

Grammar rules //3rd section

%%

Epilogue //4th section "optional section"

Listing 4.4: Bison Grammar

Prologue:- The prologue section usually contains #include lines, macro definitions and C

declarations.

Bison Declaration:- Declarations related to bison or yacc comes under this section.

Grammar rules:- This section contain actual grammar rules and their associated semantic actions.

Epilogue:- Additional C code that commonly corresponds to functions invoked from the

semantic actions.

Bison parserMatlab.tab.c parserMatlab.y

38

Bison receives as an input a parserModelica.y file with the grammar rules. The output of the

process is a parser written in C that communicates with a lexer. We require the

"parserModelica.tab.c" file in order to generate a parser in the MetaModelica language. This we

discuss in the OMCCp section.

%{

import AbsynMat;

/* Type Declarations */

type AstTree = AbsynMat.Start;

type Token = Types.Token;

constant list<String> lstSemValue3 = {};

constant list<String> lstSemValue = {

"error", "$undefined", "FUNCTION", "END", "IF", "ELSEIF", "ELSE", "WHILE",

"FOR", "SWITCH", "CASE", "OTHERWISE", "GLOBAL", "BREAK", "CONTINUE",

"RETURN", "CLASSDEF", "PROPERTIES", "simple_list1", "list", "list1",

"opt_list", "input1"};

%}

%token FUNCTION

%token END

%token IF

%token ELSEIF

%token ELSE

%token WHILE

%token FOR

%token SWITCH

%%

/* Looping */

loop_command: WHILE stash_comment expression opt_sep opt_list END

{ $$[Command] = AbsynMat.WHILE_COMMAND ($3[Expression],

SOME($4[Separator]), $5[Statements], SOME($2[Mat_Comment])); }

| FOR stash_comment assign_lhs EQ expression opt_sep

opt_list END

{ $$[Command] = AbsynMat.FOR_COMMAND ($3[Arguments],

$5[Expression], SOME($6[Separator]), $7[Statements], SOME($2[Mat_Comment]));

}

/* Function file */

function_file: FUNCTION function_list opt_sep opt_list

{ $$[Start] = AbsynMat.START($2[User_Function], $3[Separator],

$4[Statements]); }

/* Function definition */

$1[User_Function]::$3[User_Functions]; }

Prologue

Bison Declaration

Grammer Rules

39

function_list: function1 { $$[User_Function] = AbsynMat.FINISH_FUNCTION

({},$1[User_Function]); }

%%

Regarding the content of parserMatlab.y file, the complete file is available in Appendix B

section.

This file includes the Matlab tokens in the Bison declaration section and Grammar rules for the

Matlab language. The rules are written in the form of context free grammar. The lower-case

letters denote non-terminals and upper-case letters denote terminals. Bison performs parsing

according to rules one at a time and if a rule succeed the corresponding AST part is created.

4.5 OMCCp

The OpenModelica Compiler-Compiler parser generator (OMCCp) is the tool that generates a

Lexer and Parser in the MetaModelica language based on the grammar file. OMCCp is

composed of two packages, the Lexer Generator and the Parser Generator.

LexerCode.tmo ParseCode.tmo

40

Figure 4.2: Structure of OMCCp

The OMCCp tool is used for the generation of Lexers and Parsers in MetaModelica which is then

compiled with OpenModelica compiler (OMC). The Parser and Lexer Generator are based on the

generated files by FLEX and BISON from the grammar files lexerMatlab.l and parserMatlab.y.

The two packages LexerGenerator.mo and ParserGenerator.mo are responsible for the generation

of the complete Compiler Compiler in MetaModelica code.

Lexer.mo:- The main purpose of this file is to load the source code file and

recognize all the tokens described by the grammar and returns as an output to the

parser either a list of tokens or an error if no tokens were found.

LexerGenerator.mo:- The Lexer Generator for OMCCp is implemented in the file

LexerGenerator.mo. It receives a FLEX generated lexerMatlab.c file as input. The

FLEX generated file contains the required information to be used by the Lexer.mo

file. There are in total three files generated by the Lexer Generator.

LexerModelica.mo, LexTableModelica.mo and LexerCodeModelica.mo.

Parser.mo:- The main purpose of this module is to efficiently convert a list of

tokens received by the Lexer into the Matlab AST "Abstract Syntax Tree"

described in the Absyn.mo file. This converted Matlab AST is required as Input

by our translator to preform translation of Matlab AST to Modelica AST which

we will discuss in next chapter "Implementation and Design of Translator".

ParserGenerator.mo:- The Parser Generator for OMCCp is implemented in the

file ParserGenerator.mo. It receives Bison generated parserMatlab.c file as a

input. The Bison generated file contains the required information to be used by

Parser.mo file. There are four files generated by the Parser Generator.

ParseModelica.mo, ParseTableModelica.mo, ParseCodeModelica.mo and

TokenModelica.mo

TokenModelica.mo:- This file is the link between the lexer and the parser and it is

used by both to identify the tokens.

41

4.6 Abstract Syntax of the MATLAB- AbsynMat.mo "MATLAB AST"

Abstract Syntax Tree:- The representation of Source Code as a tree of nodes, representing

constants or variables (leaves) and operators or statements (inner nodes) is called an AST.

An AST is the output of a parser thus It is also known as parse tree.

uniontype Start

record START

User_Function usr_fun;

Separator sep;

list<Statement> stmt_lst;

end START;

end Start;

Listing 4.6: AST

In the listing 4.6 the uniontype “Start” is the main AST construct of the Matlab. The Matlab

language always start from the function and can be separated by operator, if file contains more

than one function. The first function is called primary function and the rests are called secondary

functions. Thus our record "START" contains three uniontypes. The first uniontype is the

User_Function which handles the Matlab function, which could be single or primary function

then Separator uniontype, in case file contains more than one function thus we separate more

functions by separator and finally Statement uniontype which is list of statements. This list

contains secondary function.

function_file: FUNCTION function_list opt_sep opt_list

{ $$[Start] = AbsynMat.START($2[User_Function], $3[Separator], $4[Statements]); }

The above code is taken from parserMatlab.y which is relevant to the above Start AST

construct. The first line is the grammar rule where the letters in small are terminals and letters in

large are non terminals or tokens. In second line "AbsynMat" is the file which contains the entire

Matlab AST, here the letters in the capital are the record types and letters in normal are the

uniontypes. If above grammar rule parsed then it creates the AST accordingly define in

AbsynMat.mo file. The complete Matlab-AST constructs refer the Appendix C section.

42

uniontype User_Function

// Begin defining a function.

record START_FUNCTION

Ident fname;

list<Parameter> prm;

Option<Separator> sep;

list<Statement> stmt_lst;

Statement stmt_2nd;

end START_FUNCTION;

// Finish defining a function.

record FINISH_FUNCTION

list<Decl_Elt> ret;

User_Function usr;

end FINISH_FUNCTION;

end User_Function;

Listing 4.6.b: AST

In the listing 4.6.b uniontype “User_Function” is the AST for the Matlab function. This

uniontype contains two records. The first is called START_FUNCTION and the second is called

FINISH_FUNCTION.

The first record is composed of Ident, Parameter list, Optional separator, Statement list and

finally Statement. The START_FUNCTION record handles function name, input parameters of

the function which can be zero "empty/{}" or more, separator operator such as semi colon, colon,

new line etc and then function body which is list of statements and finally function ends on

Statement uniontype with the keyword end.

function1 : fcn_name param_list opt_sep opt_list function_end

{ $$[User_Function] = AbsynMat.START_FUNCTION ($1[Ident],$2[Parameters],

SOME($3[Separator]), $4[Statements], $5[Statement]); }

| fcn_name opt_sep opt_list function_end

{ $$[User_Function] = AbsynMat.START_FUNCTION ($1[Ident],{}, SOME($2[Separator]),

$3[Statements], $4[Statement]); }

Second record composed of Decl_Elt list uniontype and recursive User_Function

uniontype. The Decl_Elt list uniontype handles the output of the function which could be zero

43

"empty/{}" or more. We used recursive User_Function uiontype because it recalls itself again for

constructing the further part of the function, which is the START_FUNCTION record.

function_list: function1

{ $$[User_Function] = AbsynMat.FINISH_FUNCTION ({},$1[User_Function]); }

| return_list EQ function1

{ $$[User_Function] = AbsynMat.FINISH_FUNCTION ($1[Decl_Elts],$3[User_Function]); }

44

Chapter 5

Design and Implementation of the Translator

This chapter covers the design and implementation of the translator. We first discuss our type

inference algorithm and later the actual translator.

The main challenge of the MATLAB to Modelica translator is to perform inference on the input

programs to determine each variable’s type and size and transform them into compatible forms

for easily and effectively generating Modelica code.

Our translator is built around the following requirements:

1. The translator supports a subset of the MATLAB features that are commonly used for

scientific computations: All supported subset features are available in section 7.2 Supported

Subset Features..

2. The translator is designed to be used for translating existing MATLAB programs into

Modelica code, so we assumes that the input MATLAB programs are syntactically and

semantically correct though translator still detected lexical errors during the process of the

lexical analysis and syntax error while parsing.

Matlab AST

Modelica AST

The translator performs type inference before transformation of code and takes the Matlab AST

as input and output the Modelica AST. In order to compile the generated code using OMC we

Translator

45

have to accurately analyze the Matlab code, evaluate proper types including size of arrays and

map to the AST of Modelica. Both languages are very different in nature and Matlab has

comparatively simple syntax with no variable declaration. These features make Matlab very easy

to write code in but associated with the simple syntax there is much more complex semantics

that relies on the actual types of the operands and variables thus we identify the main differences

first.

Identification of variable identifiers and declaration with proper data type.

Identification of array identifiers and declaration with proper size and data type.

Identification of local identifiers and declaration under the protected section along

with data type.

Identification of constant identifiers.

Identification of function calls.

Identification of index operation.

Identification of built-in functions.

Identification of Anonymous functions.

46

Figure 5.1: Structure of the Translator

5.1 Type Inference

We have adopted the McFOR "A Matlab To Fortran95 Compiler" approach for evaluating the

types in our translator. It starts by analyzing each assignment statement on the right hand side

(RHS) of the expression and assign types. [16]. The type inference process starts by analyzing

each assignment statement in the AST, the translator saves all the assignment statements in a

single list with a delimiter string. Delimiter string i.e. "nstmt" assists translator while splitting the

list to identify the end of previous and start of new statement.

For example; if the Matlab function contains the assignment statements below:

radius = 10.5;

num_boxes = 4;

box_length = (2.0*radius)/num_boxes;

Scanner

Parser

Translator

Unparser

OMCCp

Matlab source

code

Tokens

Matlab AST

Modelica AST

Modelica source

code

Lexer

Generator Parser

Generator

47

After traversing the entire AST, we have a list of given strings but here each identifier contains

three additional strings which we appended during the process of traversing. The detail about

these strings are explained in the next section.

{Scalar, 1, 1, radius, Real, nstmt, Scalar, 1, 1, num_boxes, Integer, nstmt, Scalar, 1, 1,

box_length, Unknown, Scalar, 1, 1, rconstant ,Real, MUL, Scalar, 1, 1, radius, Unknown, DIV,

Scalar, 1, 1, num_boxes, Unknown}

Once the translator collected all the assignment statements from the provided Matlab function we

start the process of evaluating the types by examining each assignment statement but first we

split each statement with the help of delimiter sign i.e. "nstmt". After splitting the whole list then

the translator examine the Right Hand Side of each statement on the basis on the following

sources.

Type Inference

48

5.1.1 Statement where the Right Hand Side is a constant

We found that constant values are very precise sources for accessing data types. They provide a

good source to start the process of type inference. During the process of analyzing, we append

three extra strings to each identifier. The first represents either the identifier is a Scalar or an

Array and the second & third represents the dimensions of an array. How does the translator

knows which string to append depends on the right hand side of the constant identifier. The

translator examine the right hand side of a constant statement to assess either the identifier on the

left hand side is a scalar or an array. Since the scalar identifier has 1 dimension we appended "1"

in the case of an array the translator count the elements first and then append the dimension.

For instance if the translator finds an assignment statement where the right hand side is a

constant (e.g.) temp = 10 we append the string scalar and dimension 1,1 with a temp identifier.

Since 10 is an integer value we assess the type Integer.

temp = 10

i_lst3 = listAppend({"Scalar"},{"1"},{"1"});

Scalar, 1,1, temp, Integer

- right hand side contains a real value.

temp = 10.5

i_lst3 = listAppend({"Scalar"},{"1"},{"1"});

Scalar, 1,1, temp, Real

- right hand side contains a vector or row vector

temp = [1,2,3,4] // 1 x 4

i_lst3 = listAppend({"vector"},{"1"},{dim});

vector, 1,4, temp, Integer- right hand side contains a column vector

temp = [1;2;3;4] // 4 x 1

i_lst3 = listAppend({"column_vector"},{dim},{"1"});

column_vector, 4,1, temp, Integer

- right hand side contains a matrix

49

temp = [1,2;3,4] // 2 x 2

i_lst3 = listAppend({"matrix"},{dim},{dim});

matrix, 2,2, temp, Integer

Since the size of above matrix is 2x2 we append a strings 2, 2, the first character represents 2

columns and the second character represents the 2 rows.

5.1.2 Statement where the Right Hand Side is Built-in function

Our next main source to evaluate the types are the Matlab Built-in functions because built-in

functions are well defined. Therefore these functions also provide enough information for

accessing data types.

If the translator finds an assignment statement where the right hand side is a built-in function,

then the translator accesses its type from the database where we have a list of all the built-in

functions supported by Modelica with their return type. (e.g.) zeros(n,m) is an n-by-m matrix of

zeros thus return type is matrix nxm size. As we appended help strings during the process of

analyzing constant values above, here we do the same on the basis of the built-in function.

We created a separate file containing all Matlab built-in function. The file is divided into two

main functions; one responsible for array built-in function such as zeros and ones and other

responsible for non-array built-in function such as sqrt etc.

For instance if the translator encounters the following assignment statement temp = ones(2,2),

first the translator discovers either the function is built-in or not.

In the listing 5.1.2 the builtInArray function is responsible to identify either that the function

identifier is an array built-in function or not. The function builtInArray returns true if the case

matches otherwise false.

50

public function builtInArray

input String fnc_name;

output Boolean tf;

algorithm

tf := matchcontinue (fnc_name)

local

String fnc_name1;

Boolean tf1; case("ones") then true; // Create array of all ones

case("zeros") then true; // Create array of all zeros

end matchcontinue;

end builtInArray;

Listing 5.1.2: builtInArray function

Since the function returns true then the translator appends matrix string and its dimensions with

the identifier on left hand side.

temp = ones(3,3)

i_lst3 = listAppend({"matrix"},{dim},{dim});

matrix, 3,3, temp, Integer

If the translator encounters a non array built-in function such as temp = sqrt(4), then the listing

5.1.2.b builtInNonArray function is responsible to identify that the built-in function is a built-in

scalar function or not. The function builtInNonArray returns true if the case matches otherwise

false.

public function builtInNonArray

input String fnc_name;

output Boolean tf;

algorithm

tf := matchcontinue (fnc_name)

local

String fnc_name1;

Boolean tf1; case("sqrt") then true; // Square root

case("ceil") then true; // Round toward positive infinity

case("floor") then true; // Round toward negative infinity

end matchcontinue;

end builtInNonArray;

Listing 5.1.2.b: builtInNonArray function

Since the function returns true then the translator appends the Scalar string and 1 as its dimension

with the identifier on the left hand side.

51

temp = sqrt(5)

i_lst3 = listAppend({"Scalar"},{"1"},{"1"});

Scalar, 1,1, temp, Real

5.1.3 Statement where the Right Hand Side is a computational expression and

contains arithmetic operator (array)

The third main source is an arithmetic operators. Matlab operators not only provide the shape

and size information for the result but also provide constraints on the type and shape of operand.

The assignment statement where right hand side is a matrix computational expression, c = a*b

where a & b are matrices. In order to evaluate such an expression in Matlab the inner dimensions

must agree. If a & b have a shape of n-by-m and p-by-q, then m must be equal to p. The

generated result will have the shape of n-by-q.

For instance if the translator encounters with an assignment statement where right hand side

statement is an array multiplication (e.g.) temp = a * b, where dimension size of a is 1x3 and b is

3x3 then translator evaluates the dimensions of temp as 1x3 with help of arithmetic operator and

the dimensions of operands.

a = [1,2,3] // size of a is 1x3

b = [1,2,3;4,5,6;7,8,9] // size of b is 3x3

temp = a * b // size of c is 1x3

If the translator encounters with an assignment statement where right hand side statement is an

array addition (e.g.) temp = a + b, where dimension size of a is 2x2 and b is 2x2 then translator

evaluates the dimensions of temp as 2x2.

5.1.4 Statement where the Right Hand Side is a computational expression and

contains an arithmetic operator (scalar)

The arithmetic scalar operation also provides information for evaluation of the types. For

instance if the translator encounters an assignment statement where the right hand side is a divide

52

arithmetic operation (e.g.) temp = a / b where a & b are Integer scalar variables. To avoid data

loss the translator always promotes the left hand side variable as real data type.

Another example where the translator provides data type to real where right hand side contains

both integer and real scalar variables. (e.g.) temp = a + b where a is an Integer scalar variable and

b is a real scalar variable.

In the listing 5.1.4. the MetaModelica function rhs_type solves the above task. The function

rhs_type takes two Boolean Inputs. The inputs for the rhs_type depends on other function where

translator scan the list of right hand side statement with the help of MetaModelica built-in

functions listMember() to discover either Real or Integer are the members of the list or not. The

function rhs_type returns Real in cases where it finds Real only in the list or both Real and

Integer. If it finds only Integer then it returns Integer else type is Unknown.

rl = listMember("Real",idtypes1);

int = listMember("Integer",idtypes1);

public function rhs_type

input Boolean rl;

input Boolean int;

output String otype;

algorithm

otype := matchcontinue(rl,int)

local

case(true,true)

then ("Real");

case(true,false)

then ("Real");

case(false,true)

then ("Integer");

case(false,false)

then ("Unknown");

end matchcontinue;

end rhs_type;

Listing 5.1.4: rhs_type function

5.1.5 Statement where the Right Hand Side is a computational expression and

contains a relational operator

Relational operators always return the results of the logical type. (e.g.) c = a < b.

5.1.6 The Right Hand Side is not equal to the Left Hand Side

53

In Matlab we can re-create any variable with different type assignment and every assignment can

create a type conflict where left hand side variable is different from the type of the right hand

side expression. We explain with help of a given Matlab function. The given Matlab function

calculates the area inside.

1 function area_sum = area_inside(radius, num_boxes)

2 box_length = (2.0*radius)/num_boxes;

3 box_rad = box_length*0.5;

4 box_area = box_length*box_length;

5 area_sum = 0; % Integer

6 for (xi = 1 : num_boxes)

7 xc = - 1 + box_rad + box_length*(xi - 1);

8 for (yi = 1 : num_boxes)

9 yc = 1 + box_rad + box_length*(yi - 1);

10 dist = sqrt((xc*xc) + (yc*yc));

11 if (dist < radius)

12 area_sum = area_sum + box_area; % Integer + Real

13 end %end of if

14 end %end of nested for

15 end %end for

16 end %end of function

Listing 5.1.6: area_sum function

In the listing 5.1.6 at line 5 where area_sum = 0 and at line 12 where area_sum = area_sum +

box_area creates a type conflict because at line 5 we are assigning constant integer value i.e. 0

and later at line 12 we are assigning Integer + Real which generates the result Real type. Since

constant identifiers are the starting point for evaluating types in our translator, during traversing

the AST of the above function translator evaluate area_sum as an integer data type due to

constant integer value on the right hand side but when translator reaches at line 12 where we

have area_sum = area_sum + box_area, the area_sum on both sides are an integer data type

evaluated already and box_area is a real data type due to box_length which involves real

arithmetic operation at line 2 because of 2.0 and divide arithmetic operator. At this stage the type

conflict is created because the translator already evaluated area_sum as an integer data type but

at line 12 the translator assigns other type i.e. real due to involvement of real and integer

operands since translator promotes to real whenever it encounters with both at time. Thus

translator declares area_sum as a real type instead integer data type.

54

5.2 Translator

In this section we discuss the actual translator. The transformation "translator" is the third stage

of implementation which takes the Matlab AST as the input and performs a series of internal

transformation and finally generates the Modelica AST. The translator package contains several

functions which perform a translation by finding a possible mapping to a Modelica AST data

structure. The main function which takes the Matlab AST as input and outputs a Modelica AST

is shown in listing 5.2. the function transform shows that it takes AbsynMat.Start as input which

is the Matlab AST and outputs a Modelica AST Absyn.Program.

public function transform

input AbsynMat.Start inprogram;

output Absyn.Program outprogram;

algorithm

outprogram:= matchcontinue(inprogram)

local

AbsynMat.Start ast;

Absyn.Program astNew;

case(ast)

equation

print("\n Successfully Translated \n");

astNew=transform_start(ast);

then

astNew;

end matchcontinue;

end transform;

Listing 5.2: function transform

The implemented translator supports a particular subset of the Matlab language which is

discussed in more detail in section 5.2.1.

5.2.1 Primary Functions

A Matlab program consists of a list of files called M-files, which include a sequence of Matlab

commands and statements. The syntax of the Matlab function can be separated into two main

parts: Function declaration and Function body.

Function Declaration:- This part consists of function keyword, function name, the input and

output formal parameters.

Function Body:- This is a core part of function and it starts right after function declaration line.

This part consists of a list of statements and commands which ends with the keyword end.

55

In the listing 5.2.1 a sample function of Matlab is given below.

function perfect = isperfect(value) % declaration of function

sum = 0; % start of function body

for (divisor = 1 : value - 1)

result = value / divisor;

if (result == floor(result))

sum = sum + divisor;

end

end

if (sum == value)

perfect = 1;

else

perfect = 0;

end

end % end of function body

Listing 5.2.1: Matlab function

The function name is isperfect which is defined in the declaration section. The input and output

parameters are value and perfect respectively. Since the nature of the Matlab language is

dynamic therefore we don't see any variable type declaration. All variables inside the function

body are local to the isperfect function.

Whereas, the syntax of a Modelica function can be divided into three parts: Function declaration,

Protected and Function body.

Function Declaration:- The declaration of Modelica function is similar to the Matlab function

as it also contains the function name, input, and output formal parameters. The main difference is

the declaration of type. Since the Modelica language has static typing we have to define each

function formal parameter with its proper data type and in addition to that an Input keyword to

mention input formal parameter and Output keyword to mention output formal parameters are

required.

Protected:- The next part of a Modelica function is protected. All local variables apart from

input and output formal parameters have to be declared inside protected section with proper data

types.

Function body:- Finally the body of function which contains a list of statements and commands.

The function starts with the keyword algorithm and ends with end keyword.

In the listing 5.2.1.b the translated Matlab function isperfect to Modelica is described.

56

function isperfect % function declaration

input Real value; % formal input parameter with the Input keyword and type

output Real perfect; % formal output parameter with the Output keyword and type

protected % protected section

Integer sum; % local variable sum

Real result; % local variable result

algorithm % start of function body with keyword algorithm

sum:=0;

for divisor in 1:value - 1 loop

result:=value / divisor;

if result == floor(result) then

sum:=sum + divisor;

end if;

end for;

if sum == value then

perfect:=1;

else

perfect:=0;

end if;

end isperfect; % end of function body

Listing 5.2.1.b: Modelica function

In the Listing 5.2.1.c user function is used to perform the translation of a primary function. We

used two cases here, former handles function name, input formal parameters and statement list

which formed the function body and later handles function output formal parameter and

recursive function call. As discussed above, a Modelica function consists of three main parts,

these parts are handled in the first case. The Absyn.PUBLIC() is used to structure a function

declaration part, Absyn.PROTECTED() is used to structure a function protected section and

Absyn.ALGORITHMS() is used to structure a function body.

public function user_function

case(inout, AbsynMat.START_FUNCTION(fname,prm,sep,stmt,stmt_2nd),io_lst1,

f_call1, fnc_hdl_ident1)

equation

in_cp = Absyn.PUBLIC(inout1);

prt_cp = Absyn.PROTECTED(prtVar3);

cls_stmt = Absyn.ALGORITHMS(alg);

prm_stmt = listAppend(cls_stmt::{},prt_cp::{});

prm_stmt2 = listAppend(prm_stmt,in_cp::{});

then

(fname, prm_stmt2,d_type_lst);

case({}, bsynMat.FINISH_FUNCTION(ret,usr_fnc2),{},f_call1,fnc_hdl_ident1)

equation

(out_put,io_lst3) = create_out_list(ret,false);

(fname, cls_prt,d_type_lst) = user_function(out_put, usr_fnc2,

io_lst3, f_call1,fnc_hdl_ident1);

then

(fname, cls_rev,d_type_lst);

end user_function;

57

Listing 5.2.1.c: User function

5.2.2 Translation of function declaration statements

The function declaration is similar for both languages wherein it starts with function keyword

and is composed of three main sections. These are function name, input and output formal

parameters. The names of all identifiers remain unchanged but care must be taken when

assigning proper data types to the input and output formal parameters. The translator receives the

input and output identifier with their proper data types from type inference engine. The

identifiers have already been evaluated during the process of type inference as discussed

previously in 5.1. In the listing 5.2.2. a function header of Matlab is translated to Modelica,,

where the function name isperfect and value is an input identifier and perfect is an output

identifier.

Thus translator receives input and output identifiers with evaluated types.

Matlab

function perfect = isperfect(value)

Modelica

function isperfect

input Real value;

output Real perfect;

Listing 5.2.2: isperfect

In the listing 5.2.2.b the given segment of function create_in_out is used to structure the input

and output formal parameters. This function contains two cases . The first case forms input

formal parameters and the second one forms output formal parameters. Both case statements

require three main arguments, identifier name, data type and dimensions.

58

public function create_in_out

case(AbsynMat.DECL(ident,NONE()),typ,dim,true)

equation

attr = Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),

Absyn.INPUT(),{});

tSpec = Absyn.TPATH(Absyn.IDENT(typ),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident,{},NONE()),NONE(),NONE())::{};

eli =

then (eli,ident);

case(AbsynMat.DECL(ident,NONE()),typ,dim,false)

equation

attr1 = Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),

Absyn.OUTPUT(),{});

tSpec1 = Absyn.TPATH(Absyn.IDENT(typ),NONE());

com1 =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident,{},NONE()),NONE(),NONE())::{};

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),

Absyn.COMPONENTS(attr1,tSpec1,com1),info1,NONE())))::{};

then

(eli,ident);

end matchcontinue;

end create_in_out;

Listing 5.2.2.a: creat in out

5.2.3 Identification and Translation of Local identifiers

The identifiers inside the function body of the Matlab are local to that function but in Modelica

the identifiers are either public or protected. The input and output formal parameters comes

under the public heading while all other identifiers inside a function body comes under protected

heading. Modelica does not support re-declaration of variables therefore we have to identify all

protected identifiers first and then assign proper data types through type inference engine.

The process of identifying the local identifiers are depicted in Figure 3.

59

Figure 5.2: Declaration of protected variables

To perform this task we declare two lists of strings. Assume that these are: param and an ident

list. The former contains input and output parameters and the latter contains all identifiers of the

function including input and output formal parameters. The translator compares both lists first

and removes all the identifiers from the ident list which are available in the param list. Now the

ident list only contains local identifiers however this list may contain the duplicate. To avoid re-

declaration of variables in translated code, we re-compare the list with itself and remove all the

repeated identifiers from the ident list.

In the listing 5.2.3 the segment of function protectVariable is used to return the protected

identifiers. This function takes two inputs list of string, one list contain all the identifiers of

function and other list contain only input and output identifiers. We then match one string at a

time with all ident list through listMember MetaModelica built-in function. The ident is removed

from the all ident list if listMember returns true. As this process is recursive and the remaining

list needed to be rechecked with other ident thus we recall proctectVariable function inside the

case. Once all the input and output idents have been removed from all ident list next

rmvDuplicate function is called for removing identical identifiers.

60

public function protectVariable

input list<String> all_ident;

input list<String> io_ident;

output list<String> prt_ident;

algorithm

prt_ident := matchcontinue(all_ident,io_ident)

case(all_ident1,asg_ident2::asg_ident1)

equation

chk = listMember(io_ident2,all_ident1);

prt_var = prtVariable(chk,asg_ident2);

ident = protectVariable(all_ident1,asg_ident1);

all_ident2 = listAppend(ident,prt_var);

all = rmvDuplicate(all_ident2);

then (all);

end matchcontinue;

end protectVariable;

Listing 5.2.3: Protect Variable

5.2.4 Identification and Translation of constant identifiers

The constant identifiers mean those assignment statements where the right hand side is equal to

any constant value not any identifier. The constant identifiers may contain either real, integer,

logical or an array on the right hand side of the statement. For example, sum = 10 where 10 is an

integer scalar. All these identifiers are declared under the protected heading with their relevant

data types. For example:

Matlab

function [sum] = add_scl_mat(scl1)

real1 = 10.5;

mat2 = [1,2,3;4,5,6];

sum = mat2 + scl1 + real1;

end

Modelica

function add_scl_mat

input Real scl1;

output Real sum[:,:];

protected

Real real1;

Integer mat2[:,:] = [1,2,3;4,5,6];

algorithm

real1:=10.5;

sum:=mat2 .+ scl1 .+ real1;

end add_scl_mat;

Listing 5.2.4: Constant Identifiers

61

The translator identifies two local variables. The first identifier is real1 where right hand side is a

real number, i.e., 10.5. The next one is mat2 where right hand side is a two dimensional integer

array, i.e., [1,2,3;4,5,6].

The translator evaluate the respective data types from the right hand side of the value. Notice, in

generated code the translated scalar identifiers only have type declaration in the protected

section. The assignment of value is under the algorithm section which is the actual body of the

function whereas arrays have both declaration and assignment in the protected section.

In the listing 5.2.4.b the segment of MetaModelica protectTransform function performs the

above task by taking optional Matlab expression as input. Since protected section of Modelica

functions are optional and function may not contain any local variables, thus, to handle such

cases input is an optionsal requirement . The local variables can be an array variable or scalar

variable, therefore, we have two cases to handle them both differently. The first case handles the

array variables, since Modelica declares row vectors and matrix in a different way thus we have

one more prt_mtx_vec function to separate both. The prt_mtx_vec function is given in listing

5.2.4.b where among two cases, one handles row vector and other matrix and column vector.

62

public function protectTransform

input Option<String> ident;

input Option<AbsynMat.Expression> exp;

input list<String> type_lst;

output list<Absyn.ElementItem> elitem;

algorithm

elitem := matchcontinue(ident,exp,type_lst)

case(NONE(),SOME(exp1),type_lst1) // Array

equation

(ident2,modfic,mtx_vec) = modification(exp1);

ary_type = asg_type(ident2,type_lst1);

eli = prt_mtx_vec(ary_type,ident2,modfic,mtx_vec);

then

eli;

case(SOME(ident1),NONE(),type_lst1) // Scalar

equation

ary_type = asg_type(ident1,type_lst1);

ary_type1 = lsttostring(ary_type);

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),{});

tSpec = Absyn.TPATH(Absyn.IDENT(ary_type1),NONE());

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),

Absyn.COMPONENTS(attr,tSpec,com),info,NONE())))::{};

then

eli;

end matchcontinue;

end protectTransform;

Listing 5.2.4.b: protect transform

63

public function prt_mtx_vec

input Absyn.Modification modfic;

output list<Absyn.ElementItem> eli;

algorithm

eli := matchcontinue(ary_type,ident,modfic,mtx_vec)

local

case(ary_type1::ary_type_lst,ident1,modfic1,"vector"::type_lst)

equation

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),

Absyn.NOSUB()::{}); // Absyn.NOSUB()::{} = Real[:]

tSpec = Absyn.TPATH(Absyn.IDENT(ary_type1),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident1,{},SOME(modfic)),NONE(),

NONE())::{}; //modification

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),

Absyn.COMPONENTS(attr,tSpec,com),info,NONE())))::{};

then eli;

case(ary_type1::ary_type_lst,ident1,modfic1,"matrix"::type_lst)

equation

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),{});

tSpec = Absyn.TPATH(Absyn.IDENT(ary_type1),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident1,{Absyn.NOSUB(),Absyn.NOSUB()},

SOME(modfic)),NONE(),NONE())::{}; // Absyn.NOSUB() = Real[:,:]

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),

Absyn.COMPONENTS(attr,tSpec,com),info,NONE())))::{};

then eli;

end matchcontinue

end prt_mtx_vec;

5.3 Translation of Function Body

The function body of Matlab is translated into a Modelica algorithm section. The body is

composed of a list of statements where every statement is translated to the relevant Modelica

statement. The statement list includes function call, anonymous function, sub function, if

statements, loops, arithmetic operations etc.

5.3.1 Identification and Translation of Function Call

64

The syntax for function call and array index operation is the same in Matlab using round

parentheses, i.e. sqrt(i). Thus sqrt can be a function call or an index operation. Matlab decides

this during execution time. However, Modelica has different syntax for index operations. It uses

brackets [] instead of parentheses (). Thus, sqrt[i] should be used if the sqrt is an array that

should be indexed. The function calls have the same syntax as in Matlab, i.e., sqrt(i).

Figure 5.3. Process of Identifying function call

Figure 5.3 presents the process where a function call is identified. The translator must

differentiate between function call and index operation.

The function call in the original Matlab code can either be an index operation, a built-in function,

a sub-function, or a recursive function. For the solution of this task we first discover the common

functions between the Matlab and a Modelica and saved the names of those functions in a file

Mat_Builtin.mo. While discovering the similar functions we also found that there are few

functions which have similar purpose but have different names. We saved those functions in

another file called Mod_Builtin.mo.

The translator first copies the names of index operation, built-in functions, main function and

sub-functions into a list of strings. While translating, if it finds any function call it then compares

the name of the function call first in the file Mat_Builtin.mo and then in the list containing all the

names. If there is a match in any of list then the translator looks for a similar function in

Mod_Builtin.mo file. If there is a match translator replaces the Matlab function name to a

Modelica function else function name remains unchanged.

For example, the disp('text here') function is used in Matlab for print/display purpose is replaced

to a print("text here") function in OpenModelica because these functions have a similar purpose.

65

Similarly rdivide() to div(), diag() to diagonal() etc. If the translator does not find in any of list it

interprets the identifier as an array that should be indexed and the translator replaces parenthesis

() by brackets [].

In the listing 5.3.1 the segment of MetaModelica expression function is used to handle the above

cases. It takes Matlab expression as an input and outputs the Modelica expression. If input

contain any array generator function such as zeros and ones in that case we need to evaluate the

dimensions thus the mat_builtin function takes input expression and returns the dimension. The

mat_builtin function also returns the return type of scalar Matlab builtin function. The

mat_builtin function is given below. The sqrt, ceil and floor are the example of cases where the

return type is Real.

public function expression

input AbsynMat.Expression exp;

output Absyn.Exp mod_exp;

algorithm

(mod_exp,stmt_ident) := matchcontinue(exp,f_call,fnc_hdl_idents_i)

local

case(AbsynMat.INDEX_EXPRESSION(mat_exp,arg_lst),f_call1,fnc_hdl_idents)

equation

cref = expression_cref(mat_exp);

(mod_exp6,dims) = argument_lst(arg_lst,false);

(dim_str,fnc_dim) = mat_builtin(cref,mod_exp6);

blt_chk = Mat_Builtin.builtIn(cref);

fnc_chk = fnc_call(cref,f_call1);

fnc_hdl_chk = fnc_call(cref,fnc_hdl_idents);

out =

arg_fnc_hdl(fnc_hdl_chk,fnc_hdl_idents,cref,arg_lst,blt_chk,fnc_chk);

then

(out,{cref,fnc_dim});

end matchcontinue;

end expression;

Listing 5.3.1: expression

66

function mat_builtin

input list<Absyn.Exp> mod_exp;

output String dim;

output String dim2;

algorithm

(dim,dim2):=matchcontinue (cref,mod_exp)

case (("zeros",Absyn.INTEGER(i)::mod_exp3))

equation

fnc_dim = intString(i);

then ("zeros",fnc_dim);

case (("ones",Absyn.INTEGER(i)::mod_exp3))

equation

fnc_dim = intString(i);

then ("ones",fnc_dim);

case (("sqrt",mod_exp2)) then (ret_str,"Real");

case (("ceil",mod_exp2)) then (ret_str,"Real");

case (("floor",mod_exp2)) then (ret_str,"Real");

case (("abs",mod_exp2)) then (ret_str,"Real");

case (("mod",mod_exp2)) then (ret_str,"Real");

case ((ret_str,mod_exp2)) then (ret_str,"empty");

end matchcontinue;

end mat_builtin;

Listing 5.3.1.b: User function

5.3.2 Identification and Translation of Anonymous function to sub-function

An anonymous function is just like a standard Matlab function. It is located inside the function

body and accepts inputs and return output as standard Matlab functions. However, it contains

only a single executable statement.

An example of an Anonymous function to sub-function translation is presented in listing 5.3.2.

67

Matlab

function [result] = fnc(x) y = 2;

sqrt= @(x) x^y;

result = sqrt(x);

end

Modelica

function fnc //primary function

input Real x;

output Real result;

protected

Real y;

algorithm

y:=2;

result:=sqrt(x, y);

end fnc;

function sqrt //sub-function

input Real x;

input Real y;

output Real sqrt;

algorithm

sqrt:=x ^ y;

end sqrt;

Listing 5.3.2: Anonymous function

Modelica does not support any such functions so far, therefore, alternatively we can convert

anonymous function into sub-functions. Whenever, translator finds anonymous function in a

given Matlab code it translates to a sub-function in Modelica.

The translator traverses the whole AST to find out whether the body of a function contains any

anonymous function or not. If the check is true, then translator copies the whole anonymous

statement from the original code and removes that node from the AST. Afterwards, it converts it

into a sub-function in Modelica. In a function call the translator replaces the input parameters

with sub-function input formal parameters. As we see in the code sqrt(x) has only one formal

parameter but in translated Modelica code we find two parameters, x and y.

68

5.4 Translation of looping statements

Both languages have almost similar syntax for looping statements. While translating the header

statements of loops the translator replaces = sign to in keyword in for loop and postfix the loop

keyword in both while and for loop.

Also, the square brackets [] replaces to the braces or curly brackets {}. Matlab ends a for loop

with an end keyword but Modelica uses for and while keyword with end keyword. Therefore,

translator adds the end for keywords at the end of for loop. The same ending procedure is

followed for while loops and if statements as end while and end if. An example of the translation

is presented in listing 5.4.

Matlab

for m = 1:14

end

Modelica

for m in 1:14 loop

end for;

Matlab

while nFactorial < 100

end

Modelica

while nFactorial < 100 loop

end while;

Listing 5.4: Loops

In the listing 5.4.b the segment of MetaModelica function command takes optional Matlab

command and outputs the Modelica algorithm item, since these loops come under section

Algorithm in Modelica thus we output Algorithm Item. The Matlab command may contain

commands like for loop, while loop, if and switch statements. The cases for For loop and while

are shown in listing 5.4.b. and the remaining cases are presented in section 5.5.

69

public function command

input Option<AbsynMat.Command> cmd;

output list<Absyn.AlgorithmItem> alg;

algorithm

(alg,for_ident,asg_ident,idents_rhs0) :=

matchcontinue(cmd,f_call,fnc_hdl_ident)

local

case(SOME(AbsynMat.FOR_COMMAND(arg,exp1,sep,mat_stmt,m_cmt_lst)),f_call1,

fnc_hdl_ident1)

equation

in_ident = for_ident(arg,NONE());

(mod_stmt,for_ident2,asg_ident1,no_exp,idents_rhs,no_str) =

stmt_lst(mat_stmt,f_call1,fnc_hdl_ident1,{});

foriterator = iterator(in_ident,{exp1});

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_FOR(foriterator,mod_stmt),NONE(),info)::{};

for_ident1 = listAppend(for_ident2,{in_ident});

then

(mod_alg, for_ident1,asg_ident1,idents_rhs);

case(SOME(AbsynMat.WHILE_COMMAND(w_exp,w_sep,w_stmt,w_cmt_lst)),f_call1,

fnc_hdl_ident1)

equation

mod_w_exp = expression(w_exp,f_call1,fnc_hdl_ident1);

(mod_w_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(w_stmt,f_call1,fnc_hdl_ident1,{});

then

(mod_alg, {}, {},idents_rhs);

end matchcontinue;

end command;

Listing 5.4.b: Loops

5.5 Translation of if statements

The if statement is also similar in both languages. The translator adds the then keyword in the

header statement of if expression and end if keyword to the end the expression. An example of

the translation is presented in Listing 5.5.

Matlab

if(result == floor(result))

sum = sum + divisor;

end

Modelica

if result == floor(result) then

sum:=sum + divisor;

end if;

Listing 5.5: if statement

70

In the listing 5.5.b the the segement of command MetaModelica function. In these case

statements we convert the Matlab If statements to Modelica If statements. Since If statement

involves optional else and else if statements in both languages thus we needed two separate

cases. The first case handles only if statement and convert it into Modelica If without else part

and the second case handles else and else if part and converts it into Modelica else and else If.

case(SOME(AbsynMat.IF_COMMAND (if_ex,if_sep,if_stmt,{},NONE(),{},

if_cmt_lst, NONE())),f_call1, fnc_hdl_ident1)

equation

mod_if_exp = expression(if_ex,f_call1,fnc_hdl_ident1);

(mod_if_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(if_stmt,f_call1,fnc_hdl_ident1,{});

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,mod_if_stmt,{},{}),NONE(),info)

::{};

then

(mod_alg, {},{},idents_rhs);

case(SOME(AbsynMat.IF_COMMAND

(if_ex,if_sep,if_stmt,else_ifs,if_sep2,if_stmt2,if_cmt_lst,if_cmt_lst2)),

f_call1,fnc_hdl_ident1)

equation

mod_if_exp = expression(if_ex,f_call1,fnc_hdl_ident1);

(mod_if_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(if_stmt,f_call1,fnc_hdl_ident1,{});

(mod_else_if,idents_rhs1) = trs_else_ifs(else_ifs,f_call1);

idents_rhs2 = listAppend(idents_rhs,idents_rhs1);

(mod_if_stmt2,no_for,no_str,no_exp,idents_rhs3,no_str1) =

stmt_lst(if_stmt2,f_call1,fnc_hdl_ident1,{});

idents_rhs4 = listAppend(idents_rhs3,idents_rhs2);

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,mod_if_stmt,mod_else_if,

mod_if_stmt2),NONE(),info)::{};

then

(mod_alg,{},{},idents_rhs4);

Listing 5.5.b: if statement

5.6 Translation of Switch Statement

Modelica does not currently support the switch statement. Thus we translate it into if statement.

When the translator finds a switch statement in the original Matlab code it translates it into if-

else statements with possible else if branches. An example of the translation is presented in

listing 5.6.

71

Matlab

switch mynumber

case -1

disp('negative one');

case 0

disp('zero');

case 1

disp('positive one');

otherwise

disp('other value');

end

Modelica

if mynumber == -1 then

print("negative one");

elseif mynumber == 0 then

print("zero");

elseif mynumber == 1 then

print("positive one");

end if;

Listing 5.6: switch

The given case is the segement of command MetaModelica function, presented in 5.4

Translation of looping statement. This case convert the Matlab switch statement to Modelica

Algorithm item.

case(SOME(AbsynMat.SWITCH_COMMAND(swt_ex,swt_sep,swcse_lst,if_cmt_lst)),

f_call1,fnc_hdl_ident1)

equation

mod_exp1 = expression(swt_ex,f_call1,fnc_hdl_ident1);

(swt_exp_lst,swt_stmt_lst,idents_rhs1) = switch_tpl(swcse_lst);

swt_exp::swt_exp_lst2 = swt_exp_lst;

swt_stmt::swt_stmt_lst2 = swt_stmt_lst;

mod_if_exp = Absyn.BINARY(mod_exp1,Absyn.EQUAL(),swt_exp);

(mod_else_ifs,mod_else) =

swt_else_ifs(mod_exp1,swt_exp_lst2,swt_stmt_lst2);

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,{swt_stmt},mod_else_ifs,mod_els

e),NONE(),

info)::{};

then

(mod_alg,{},{},{});

72

5.7 Sub-function

A Matlab file can contain more than one function. If it contains multiple functions, then the first

function is the primary function which can be accessed in other M files and the rest of the

functions are secondary functions which are called as sub-functions.

A sub-function is only accessed by its primary function. All sub-functions are translated into

sub-functions in Modelica and the procedure for translating sub-function is similar as primary

function.

public function sub_function

input list<AbsynMat.Statement> stmt_lst;

output list<Absyn.Class> mod_class;

algorithm

(mod_class,f_call) := matchcontinue(stmt_lst,in_f_call,fnc_hdl_ident)

local

case(AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(NONE(),NONE(),

SOME(AbsynMat.START(usr_fnc,sep,stmt_lst2)),NONE()),sep)::{},f_call4,

fnc_hdl_ident1)

equation

(mod_class2,f_call1) = sub_function(stmt_lst2,f_call4,fnc_hdl_ident1);

f_call3 = listAppend(f_call1,f_call4);

(fname, cp, no_ident) = user_function({},usr_fnc,{},f_call3,

fnc_hdl_ident1);

f_call2 = listAppend(f_call1,fname::{});

cd = Absyn.PARTS({},{},cp,{},NONE());

class1 =

Absyn.CLASS(fname,false,false,false,Absyn.R_FUNCTION(Absyn.FR_NORMAL_FUNCTION

(Absyn.NO_PURITY())),cd,info);

class2 = listAppend(class1::{},mod_class2);

then (class2,f_call2);

case({},f_call4,fnc_hdl_ident1)

then ({},{});

end matchcontinue;

end sub_function;

Listing 5.7: Sub function

73

Chapter 6 Testing and Performance Evaluation

In this chapter testing and performance evaluation are described. In first part we present testing

on Matlab programs. The testing section is further divided into two parts. First discusses testing

on lexer & parser and afterwards testing on translator. The second part of this chapter covers the

evaluation performance, where we compare a performance of compiled code in execution times

with their original Matlab programs in the MATLAB.

6.1 Testing Lexer and Parser

As we already defined in chapter 3 that lexical analysis or scanner is the process of converting a

sequence of characters into a sequence of tokens. Thus, we can inspect here either the lexer

generates the required tokens by giving input Matlab program. Therefore, we provide the given

Matlab function as input which contain keywords, arithmetic operators, identifiers etc.

function result = add_subtract_together(input_val, num_iter)

result = input_val;

one_third = 1.0/3.0;

for (icount = 1 : num_iter)

result = result + one_third;

result = result - one_third;

end

end

In generated tokes below we can observe that first token is the keyword "TOKEN:FUNCTION"

which is identified by lexer in function declaration section followed by an identifier result as

TOKEN:IDENT and then equal sign identified by TOKEN:EQ and soon on. The total identified

tokens in above function are 48 which includes new lines as well.

74

Parsing Modelica with file Test1.txt

starting lexer

[TOKEN:FUNCTION 'function' (1:1-1:9)][TOKEN:IDENT 'result' (1:10-1:16)]

[TOKEN:EQ '=' (1:17-1:18)] [TOKEN:IDENT 'add_subtract_together' (1:19-1:40)]

[TOKEN:LPAR '(' (1:40-1:41)] [TOKEN:IDENT 'input_val' (1:41-1:50)]

[TOKEN:COMMA ',' (1:50-1:51)][TOKEN:IDENT 'num_iter' (1:52-1:60)]

[TOKEN:RPAR ')' (1:60-1:61)][TOKEN:NEWLINES '' (1:1-2:1)]

[TOKEN:IDENT 'result' (2:3-2:9)][TOKEN:EQ '=' (2:10-2:11)]

[TOKEN:IDENT 'input_val' (2:12-2:21)][TOKEN:SEMI_COLON ';' (2:21-2:22)]

[TOKEN:NEWLINES '' (2:1-3:1)][TOKEN:IDENT 'one_third' (3:3-3:12)]

[TOKEN:EQ '=' (3:13-3:14)][TOKEN:NUMBER '1.0' (3:15-3:18)]

[TOKEN:DIV '/' (3:18-3:19)][TOKEN:NUMBER '3.0' (3:19-3:22)]

[TOKEN:SEMI_COLON ';' (3:22-3:23)][TOKEN:NEWLINES '' (3:1-4:1)]

[TOKEN:FOR 'for' (4:3-4:6)][TOKEN:LPAR '(' (4:7-4:8)]

[TOKEN:IDENT 'icount' (4:8-4:14)][TOKEN:EQ '=' (4:15-4:16)]

[TOKEN:INTEGER '1' (4:17-4:18)][TOKEN:COLON ':' (4:19-4:20)]

[TOKEN:IDENT 'num_iter' (4:21-4:29)][TOKEN:RPAR ')' (4:29-4:30)]

[TOKEN:NEWLINES '' (4:1-5:1)][TOKEN:IDENT 'result' (5:5-5:11)]

[TOKEN:EQ '=' (5:12-5:13)][TOKEN:IDENT 'result' (5:14-5:20)]

[TOKEN:ADD '+' (5:21-5:22)][TOKEN:IDENT 'one_third' (5:23-5:32)]

[TOKEN:SEMI_COLON ';' (5:32-5:33)][TOKEN:NEWLINES '' (5:1-6:1)]

[TOKEN:IDENT 'result' (6:5-6:11)][TOKEN:EQ '=' (6:12-6:13)]

[TOKEN:IDENT 'result' (6:14-6:20)][TOKEN:SUB '-' (6:21-6:22)]

[TOKEN:IDENT 'one_third' (6:23-6:32)][TOKEN:SEMI_COLON ';' (6:32-6:33)]

[TOKEN:NEWLINES '' (6:1-7:1)][TOKEN:END 'end' (7:3-7:6)]

[TOKEN:NEWLINES '' (7:1-8:1)][TOKEN:END 'end' (8:1-8:4)]

Tokens processed:48

Second phase of translator is the parsing, once the tokens have been generated properly then the

OMCCp makes the call to the parser. The parser begins the process by identifying the tokens

generated by lexer and afterwards start constructing the AST accordingly. For each Token, it

queries the parsing table generated by the GNU bison and performs two operations, namely, shift

or reduce. In the process of reduce operation it constructs the AST. The constructed AST of

above function is given below.

75

Parser outputs the Matlab AST

AbsynMat.Start.START(usr_fun = AbsynMat.User_Function.FINISH_FUNCTION(ret =

{AbsynMat.Decl_Elt.DECL(identifier = result, exp = NONE())},

usr = AbsynMat.User_Function.START_FUNCTION(fname = add_subtract_together, prm

= {AbsynMat.Parameter.PARM(dec_elt = {AbsynMat.Decl_Elt.DECL(identifier

= input_val, exp = NONE()), AbsynMat.Decl_Elt.DECL(identifier = num_iter,

exp = NONE())})}, sep = SOME(AbsynMat.Separator.NEWLINES()), stmt_lst =

{AbsynMat.Statement.STATEMENT_APPEND(stmt_apd = AbsynMat.Statement.STATEMENT(

cmd = NONE(), exp = SOME(AbsynMat.Expression.ASSIGN_OP(arg_lst =

{AbsynMat.Argument.ARGUMENT(exp = AbsynMat.Expression.FINISH_COLON_EXP(exp =

{AbsynMat.Expression.IDENTIFIER(identifier = result)}))}, op1 =

AbsynMat.Operator.EQ(), exp = AbsynMat.Expression.FINISH_COLON_EXP(exp =

{AbsynMat.Expression.IDENTIFIER(identifier = input_val)}))),

usr_fun = NONE(), m_cmt = NONE()), sep = AbsynMat.Separator.SEMI_COLON()),

AbsynMat.Statement.STATEMENT_APPEND(stmt_apd = AbsynMat.Operator.EQ(),

exp = AbsynMat.Statement.STATEMENT_APPEND(stmt_apd =

AbsynMat.Statement.STATEMENT(cmd = NONE(), exp =

SOME(AbsynMat.Expression.ASSIGN_OP(arg_lst = {AbsynMat.Argument.ARGUMENT(exp =

AbsynMat.Expression.FINISH_COLON_EXP(exp =

{AbsynMat.Expression.IDENTIFIER(identifier = result)}))},

op1 = AbsynMat.Operator.EQ(), exp = AbsynMat.Expression.FINISH_COLON_EXP(exp =

{AbsynMat.Expression.BINARY_EXPRESSION(exp1 =

AbsynMat.Expression.IDENTIFIER(identifier = result),

exp2 = AbsynMat.Expression.IDENTIFIER(identifier = one_third),

b_op = AbsynMat.Operator.SUB())}))), usr_fun = NONE(), m_cmt = NONE()),

sep = AbsynMat.Separator.SEMI_COLON())}, m_cmd_lst =

SOME(AbsynMat.Mat_Comment.COMMENT(comment = NONE())))), exp = NONE(),

usr_fun = NONE(), m_cmt = NONE()), sep = AbsynMat.Separator.NEWLINES())},

stmt_2nd = AbsynMat.Statement.MAKE_END())), sep = AbsynMat.Separator.EMPTY(),

stmt_lst = {NIL})

6.2 Testing Translator

The translator takes the Matlab-AST as the input and generates the MetaModelica AST which is

unparsed by the “Dump.mo” package to generate the Modelica code. Here we present another

function engine_model as test case. This test case contains both scalar and array type variables.

function [dmf,dwice,dpim]=engine_model(W_ice,P_im,U_mf,T_load)

%W_ice engine speed ,[round/sec], range 60<W_ice<200

%P_im intake manifold pressure, [Pa], range

100e3<P_im<300e3

%U_mf fuel injection per woking cycle [kg/cycle], range 0<U_mf<260

%T_load load on engine [N.m], range 0<T_load<2000

%constants

I_ice = 3;

nr = 2;

76

Q_lhv = 42.9e6;

n_cyl = 6;

cfr1 = 7.195e-1;

cfr2 = -1.414e-1;

cfr3 = 3.59e-1;

Vd = 12.7e-3;

Eta_igch = 0.6877;

gamma_cyl = 1.35004;

rc = 17.3;

Eta_ig = Eta_igch*(1-(1/(rc^(gamma_cyl-1))));

c_pim = [-0.328 -121.519 0.057 971791.699];

c_tau = [38.5857 -0.6869];

P_atm = 101574.2;

%model

T_fric=(Vd*100000/4/pi)*( cfr1*(W_ice*60/2000/pi)^2 +

cfr2*(W_ice*60/2000/pi) + cfr3 );

T_ig = U_mf*1e-6*n_cyl*Q_lhv*Eta_ig/(2*pi*nr);

T_ice = (T_ig - T_fric);

pim_model = (c_pim(1).*(W_ice).^2 + c_pim(2).*(T_ice) +

c_pim(3)*(T_ice).*(W_ice).^2 + c_pim(4))*1e-1; %[Pa],[rps],[Nm]

pim_model= max(P_atm,pim_model);

tau_model = c_tau(1)*W_ice^(c_tau(2));

dmf = 1e-6*U_mf*W_ice*n_cyl/4/pi;%dmf mass of fuel, kg

%differential equations for engine states

dwice = (T_ice-T_load)/I_ice;

dpim = (1/tau_model)*(pim_model-P_im);

end

Function Declaration; First we test the function declaration section.

function [dmf,dwice,dpim]=engine_model(W_ice,P_im,U_mf,T_load)

We observe in generated code below that function keyword, function name engine_model,

function input parameters, W_ice, P_im, U_mf, T_load and function output parameters dmf,

dwice, dpim are translated correctly with their appropriate data types.

Protected Section; As we know that protected section in Modelica function contains all the local

variables. We identify local variables in above Matlab function are; I_ice, nr, Q_lhv, n_cyl,

cfr1, cfr2, cfr3, Vd, Eta_igch, gamma_cyl, rc, Eta_ig, c_pim, c_tau, P_atm, pi, T_fric, T_ig,

T_ice, pim_model, tau_model. We can observe all local variables are translated correctly with

their appropriate data types such as: I_ice and nr are Integers, c_pim, c_tau are vectors etc.

77

Algorithm Section; This section contains the rest of the code such as assignment statements,

arithmetic operations etc. We examine the given assignment statement here, which includes

index operation, multiplication and power operator.

tau_model = c_tau(1)*W_ice^(c_tau(2));

We observe assignment operator = to := and index sign () to [] are converted properly. The

remaining operators and brackets are similar in both languages hence they remain unchanged in

translated code.

tau_model:=c_tau[1] * W_ice ^ (c_tau[2]);

function engine_model

input Real W_ice;

input Real P_im;

input Real U_mf;

input Real T_load;

output Real dmf;

output Real dwice;

output Real dpim;

protected

Integer I_ice;

Integer nr;

Real Q_lhv;

Real n_cyl;

Real cfr1;

Real cfr2;

Real cfr3;

Real Vd;

Real Eta_igch;

Real gamma_cyl;

Real rc;

Real Eta_ig;

Real[4] c_pim = array(-0.328,-121.519,0.057,971791.699);

Real[2] c_tau = array(38.5857,-0.6869);

Real P_atm;

Real pi;

Real T_fric;

Real T_ig;

Real T_ice;

Real pim_model;

Real tau_model;

algorithm

I_ice:=3;

nr:=2;

Q_lhv:=42900000.0;

n_cyl:=6;

cfr1:=0.7195;

78

cfr2:=-0.1414;

cfr3:=0.359;

Vd:=0.0127;

Eta_igch:=0.6877;

gamma_cyl:=1.35004;

rc:=17.3;

pi := 3.14;

Eta_ig:=Eta_igch * (1 - (1 / (rc ^ (gamma_cyl - 1))));

P_atm:=101574.2;

T_fric:=(Vd * 100000 / 4 / pi) * (cfr1 * (W_ice * 60 / 2000 / pi)^2+

cfr2 * (W_ice * 60 / 2000 / pi) + cfr3);

T_ig:=U_mf * 1e-006 * n_cyl * Q_lhv * Eta_ig / (2 * pi * nr);

T_ice:=(T_ig - T_fric);

pim_model:=(c_pim[1] .*(W_ice) .^2 + c_pim[2] .* (T_ice)+ c_pim[3]*

(T_ice) .* (W_ice) .^2 + c_pim[4]) * 0.1;

pim_model:=max(P_atm, pim_model);

tau_model:=c_tau[1] * W_ice ^ (c_tau[2]);

dmf:=1e-006 * U_mf * W_ice * n_cyl / 4 / pi;

dwice:=(T_ice - T_load) / I_ice;

dpim:=1 / tau_model * (pim_model - P_im);

end engine_model;

6.3 Performance

All experiments were performed on a Windows 8, 64 bit operating system with 2 x 2.0 GHz Intel

core i7 - 3632QM CPU and 8 GB RAM. In table 6.1 the execution times of actual Matlab

models and generated Modelica models are presented. The execution times are the average of 5

runs each model.

Our experiments shows that the compiled Modelica programs perform better than their

respective interpreted Matlab programs however the performance varies from program to

program, depending on the nature of the Matlab program.

Model Scalar/Array Matlab(ms) Modelica(ms)

Closure 2D-array 185.90 26.49

IsPerfect Scalar 198.60 11.65

79

Finite 2D-array 69.98 55.25

AreaInside Scalar 180.05 16.72

MySort 1D-array 218.45 26.49

SwapVector 1D-array 80.67 18.02

BubbleSort 1D-array 109.34 81.96

Table 6.1. Execution times in milliseconds of Matlab and generated Modelica models

Table 6.2. Execution times in milliseconds of Matlab and generated Modelica models

80

Chapter 7 Conclusion and Future work

7.1 Conclusion

We designed and implemented a translator which takes the Matlab program as input and

produces Modelica code as output and performs type inference on input program to construct

type information.

The benefits and results of this translator are:

1- The translator generates programmer friendly Modelica code which is in readable and

reusable form.

2- The translator maintains the program structure of the Matlab programs.

3- With our implemented translator, we can provide the benefit of both the power of interactive

array languages and the performance of compiled languages.

4- As expected and shown in pervious chapter the results of our generated code demonstrate that

the compiled Modelica programs perform better than their respective interpreted Matlab

programs however the performance varies from program to program, depending on the nature of

the Matlab program.

7.2 Supported Subset Features

The translator handles the following subset features:

1- Functions: Simple and Sub-functions.

2- Loops: For, Nested For, While, Nested While, continue and break.

3- Statements: If, If else, If elseif else and Switch.

4- Program Termination: return.

5- Arithmetic Operators: Plus +, Unary plus +, Minus -, Unary minus -, Matrix multiply *,

Array multiply .*, Matrix power ^, Array power .^, Backslash or left matrix divide \, Slash or

right matrix divide /, Left array divide .\, and Right array divide ./.

81

6- Relational Operators: Equal ==, Not equal ~=, Less than <, Greater than >, Less than or

equal <= and greater than or equal >=.

7- Special Character: Colon :, Parentheses and subscripting ( ), Brackets [ ], Braces and

subscripting { }, Continuation ..., Separator Comma',', Semicolon ;,Comment %, Assignment =,

Quote ', Transpose .', Complex conjugate transpose ', Horizontal concatenation [,] and Vertical

concatenation [;].

8- Logical Operators: Short-circuit logical AND &&, Short-circuit logical OR ||, Element-wise

logical AND &, Element-wise logical OR | and Logical NOT ~.

7.3 Future work

The scanner and parser have been implemented to support full features of the Matlab but the

translator supports only a subset of features. Thus further improvement can be made in the

translator by implementing more features and advanced type estimation techniques .

Although type inference is a powerful optimization technique we can never find out all the

missing type information through this technique.

In the listing 7.3 where a Matlab program defines a function in a file named stat.m that returns

the mean and standard deviation of an input vector but this program also takes scalar input, such

programs cannot be estimated. However, we can generate two outputs: one supporting scalar

inputs and the other for array inputs.

function [m,s] = stat(x)

n = length(x);

m = sum(x)/n;

s = sqrt(sum((x-m).^2/n));

end

Listing 7.3

7.3.1 Dimensions determination at Runtime

The built-in functions and matrix operators in the Matlab are well defined, these features is quite

helpful in resolving the number of dimensions of the end result matrices. Hence, in all such cases

82

the translator can resolve the number of dimensions of the matrices . However, if the size of an

array is not constant but contains variables and variables values are not placed as constant in that

case the translator may not determine the array dimensions. For example:

A = rand(m,n)

B = rand(p,q)

C = A * B

For example: in the code segment shown above the rand built-in function returns an m-by-n

matrix A and a p-by-q matrix B. If the translator is unable to find the values of the variables m,

n, p, and q, then the meaning of the express A * B and shape of C are also undeterminable at

compile time. In order to solve this problem, the translator needs to generate extra code to handle

all possible cases at runtime. These extra code could contain conditions like;

case 1: A and B are Scalars

case 2: A is a matrix and B is a Scalar

case 3: A is a Scalar and B is a matrix

case 4: A and B are matrices

7.3.2 Variable type determination at Runtime

The goal of variable type determination at runtime is to determine the actual type of an variable.

In the listing 7.3.2 the segment of user defined function where inside if statement scl returns

scalar values to x whereas in else statement the user defined function vec returns vectors thus

translator is unable to solve the final type. Such cases could be translated by generating an extra

variable.

83

x = 0;

for i = 1:15

if (i>10)

x = scl(i);

else

x = vec(i);

end

z = x;

Listing 7.3.2: Type determination

84

Chapter 8 User Guide

In this chapter we will discuss about the tools and software that are needed to be installed and

run the translator.

8.1 Getting Started The tools needed for this implementation are tortoise SVN, Eclipse IDE with MDT plug in,

OMDEV.

Follow the below steps for setting up the environment.

1) Install the latest version of tortoise svn from http://tortoisesvn.net/

2) Create a new folder named OpenModelica in any of your drive (eg: c:/OpenModelica)

and right click on that folder and perform latest svn checkout from

https://www.openmodelica.org/index.php/developer/source-code

3) Install OMDEV from https://www.openmodelica.org/index.php/developer/courses and

follow the instruction steps found in install.txt

4) Install latest version of Eclipse from www.eclipse.org

5) Install the MDT plug-in from

https://www.openmodelica.org/index.php/developer/courses and follow the installation

step.

6) Note: the installation steps may vary for windows, Linux and MAC users so be aware of

the steps to be followed. All the information is provided in www.openmodelica.org main

website under downloads.

8.2 Commands to Run the Code After downloading the latest version of OpenModelica source code from the SVN repository.

Check for the folder “Matlab” in the testsuite directory (eg:

c:/openmodelica/testsuite/openmodelica/Matlab). The folder contains the main implementation

and test cases to run our parser and translator. After checking the folder in the test suite, now we

are ready to compile the “parser” and “translator”. Follow the below step to successfully test the

parser and the translator.

1) Open the mingw terminal if you are a windows user and shell terminal for Linux user

85

2) In the terminal window go to the following path

(eg: cd c:/openmodelica/testsuite/openmodelica/omcc)

3) You can test the translator typing the following command(../../../build/bin/omc

+g=MetaModelica=rml SCRIPT.mos ) and can pass the output to a text file by doing

../../../build/bin/omc +g=MetaModelica +d=rml SCRIPT.mos >output.txt

4) If you want to translate your own matlab programs, look for the file "SCRIPT.mos" in the

folder Matlab.

5) Open the file "SCRIPT.mos" and look for the line below:

Replace the Matlab program with your program inside Test1.txt.

Main.main({"Test1.txt","Modelica"});

For translating multiple programs, use below code and replace Matlab programs with

your programs or you can create your own files and replace names of files with yours in

SCRIPT.mos file.

{ Main.main({"./MatCode/" + file,"Modelica"}) for file in

{"Test1.txt","Test2.txt", "Test3.txt"}};

86

References

[1] MathWorks Inc. MATLAB Documentation, R2014a.

< http://www.mathworks.se/products/matlab/ >

[2] Mohammad Jahanzeb, Arunkumar Palanisamy, Martin Sjölund, Peter Fritzson.

A MATLAB to Modelica Translator, 10th International Modelica Conference,

Lund University, Sweden. 2014.

[3] Jun Li. McFor. A MATLAB to FORTRAN 95 Compiler. McGill University, August 2009

[4] Luiz De Rose and David Padua. A MATLAB to Fortran 90 translator and its effectiveness. In

ICS ’96: Proceedings of the 10th international conference on Supercomputing, Philadelphia,

Pennsylvania, United States, 1996, pages 309–316. ACM, New York, NY, USA.

[5] Luiz De Rose and David Padua. Techniques for the translation of MATLAB programs into

Fortran 90. ACM Trans. Program. Lang. Syst., 21(2):286–323, 1999.

[6] Anton Dubrau and Laurie Hendren. Taming Matlab, Sable Technical Report No. sable-2011-

04. McGill University, School of Computer Science, April, 2011.

[7] Ecaterina Coman, Matthew W. Brewster, Sai K. Popuri, Andrew M. Raim, and Matthias K.

Gobbert. A Comparative Evaluation of Matlab, Octave, FreeMat, Scilab, R, and IDL on Tara.

Technical Report HPCF–2012–15, Department of Mathematics and Statistics, University of

Maryland, Baltimore County.

[8] MathWorks Inc. Article: The origins of MATLAB.

< http://www.mathworks.se/company/newsletters/articles/the-origins-of-matlab.html >

[9] Modelica - A Unified Object-Oriented Language for Systems Modeling, Version 3.3

< https://modelica.org/documents >

[10] Peter Fritzson and Adrian Pop. Meta-programming and language Modeling with

MetaModelica 1.0. Technical Report 9, Linköping University, PELAB - Programming

Environment Laboratory, The Institute of Technology, 2011.

[11] AA Aaby. Compiler Construction using Flex and Bison. Walla Walla College, 2003.

< http://foja.dcs.fmph.uniba.sk/kompilatory/docs/compiler.pdf >

[12] GUN Octave

< http://www.gnu.org/software/octave/index.html >

[13] Scilab

< http://www.scilab.org/platform/ >

87

[14] FreeMat

< http://freemat.sourceforge.net/ >

88

Appendices

89

Appendix A

LexerModelica.l

%{

%}

%option noyywrap

%s QuoteSC

%x B_COMMENT

%x S_COMMENT

HSPACE [ \t]

HSPACES {HSPACE}+

NEWLINE ((\n)|(\r)|(\r\n))

NEWLINES {NEWLINE}+

IDENTIFIER [a-zA-Z][_a-zA-Z0-9]*

CONT (\.\.\.)

Im [iIjJ]

DIGIT [0-9]

DIGITS {DIGIT}+

EXPON ([DdEe][+-]?{DIGIT}+)

NUMBER (({DIGIT}+\.?{DIGIT}*{EXPON}?)|(\.{DIGIT}+{EXPON}?)|(0[xX][0-

9a-fA-F]+))

COMMENT \%[^\n\r\f]*{NEWLINE}?

ELLIPSIS \.\.\.

CONTINUATION {ELLIPSIS}[^\n\r\f]*{NEWLINE}?

%%

"function" return FUNCTION;

"end" return END;

"if" return IF;

"elseif" return ELSEIF;

"else" return ELSE;

"while" return WHILE;

"for" return FOR;

"switch" return SWITCH;

"case" return CASE;

"otherwise" return OTHERWISE;

"global" return GLOBAL;

"break" return BREAK;

"continue" return CONTINUE;

"return" return RETURN;

"classdef" return CLASSDEF;

"properties" return PROPERTIES;

"methods" return METHODS;

"events" return EVENTS;

"get" return GET;

90

"set" return SET;

"try" return TRY;

"catch" return CATCH;

{DIGITS} return INTEGER;

{NUMBER} return NUMBER;

{NUMBER}{Im} return IMAG_NUM;

{IDENTIFIER} return IDENT;

{COMMENT} ;

{HSPACES} ;

{NEWLINES} return NEWLINES;

<INITIAL>'[^'\n\r\f]*'/' {

yymore();

}

<INITIAL>'[^'\r\f\n]*' return STRING;

"\+" return ADD;

"-" return SUB;

"\*" return MUL;

"\/" return DIV;

"\^" return POW;

".*" return EMUL;

"./" return EDIV;

"\.\\" return ELEFTDIV;

"\.^" return EPOW;

"\<" return EXPR_LT;

">" return EXPR_GT;

"\<=" return EXPR_LE;

">=" return EXPR_GE;

"==" return EXPR_EQ;

"~=" return EXPR_NE;

"&" return EXPR_AND;

"\|" return EXPR_OR;

"\\" return LEFTDIV;

"&&" return EXPR_AND_AND;

"||" return EXPR_OR_OR;

"~" return EXPR_NOT;

"," return COMMA;

"=" return EQ;

":" return COLON;

";" return SEMI_COLON;

"]" return RBRACK;

"[" return LBRACK;

"(" return LPAR;

")" return RPAR;

"}" return RBRACE;

"{" return LBRACE;

"." return DOT;

"\@" return AT;

91

{IDENTIFIER}@{IDENTIFIER}{HSPACE}* return SUPERCLASSREF;

{IDENTIFIER}@{IDENTIFIER}.{IDENTIFIER}{HSPACE}* return SUPERCLASSREF;

\?{IDENTIFIER}{HSPACE}* return METAQUERY;

\?{IDENTIFIER}.{IDENTIFIER}{HSPACE}* return METAQUERY;

"%{" {

BEGIN(B_COMMENT);

}

<B_COMMENT>

{

"%}" {

BEGIN(INITIAL);

}

}

"%" {

BEGIN(S_COMMENT);

}

<S_COMMENT>

{

\n {

BEGIN(INITIAL);

}

}

\.' {

BEGIN(QuoteSC);

return TRANSPOSE;

}

<QuoteSC>' {

return CTRANSPOSE;

}

{CONTINUATION} {

}

%%

92

Appendix B

ParserModelica.y

%{

import AbsynMat;

/* Type Declarations */

type AstTree = AbsynMat.Start;

type Token = Types.Token;

type Ident = AbsynMat.Ident;

type Expression = AbsynMat.Expression;

type Expressions = list<AbsynMat.Expression>;

type Argument = AbsynMat.Argument;

type Arguments = list<AbsynMat.Argument>;

type Command = AbsynMat.Command;

type Return_List = AbsynMat.Return_List;

type Return = AbsynMat.Return;

type Parameter = AbsynMat.Parameter;

type Parameters = list<AbsynMat.Parameter>;

type Decl_Elt = AbsynMat.Decl_Elt;

type Decl_Elts = list<AbsynMat.Decl_Elt>;

type Mat_Comment = AbsynMat.Mat_Comment;

type Mat_Comments = list<AbsynMat.Mat_Comment>;

type Switch_Case = AbsynMat.Switch_Case;

type Switch_Cases = list<AbsynMat.Switch_Case>;

type Function_Name = AbsynMat.Function_Name;

type Switch_t = tuple<Switch_Cases, Option<Switch_Case>>;

type Statement = AbsynMat.Statement;

type Statements = list<AbsynMat.Statement>;

type Stmt = AbsynMat.Stmt;

type Stmts = list<AbsynMat.Stmt>;

type Start = AbsynMat.Start;

type Starts = list<AbsynMat.Start>;

type User_Function = AbsynMat.User_Function;

type User_Functions = list<AbsynMat.User_Function>;

type Operator = AbsynMat.Operator;

type Compound_Binary_Op = AbsynMat.Compound_Binary_Op;

type Separator = AbsynMat.Separator;

type Separators = list<AbsynMat.Separator>;

type Index_Exp = AbsynMat.Index_Exp;

93

type Elseif = AbsynMat.Elseif;

type Elseifs = list<AbsynMat.Elseif>;

type Statement_Append = AbsynMat.Statement_Append;

type Statement_Appends = list<AbsynMat.Statement_Append>;

type Function = list<AbsynMat.Function>;

type Class = AbsynMat.Class;

type Classes = list<AbsynMat.Class>;

type Cell = AbsynMat.Cell;

type Cells = list<AbsynMat.Cell>;

type Matrix = AbsynMat.Matrix;

type Matrixs = list<AbsynMat.Matrix>;

type Colon_Exp = AbsynMat.Colon_Exp;

type Colon_Exps = list<AbsynMat.Colon_Exp>;

constant list<String> lstSemValue3 = {};

constant list<String> lstSemValue = {

"error", "$undefined", "FUNCTION", "END", "IF", "ELSEIF", "ELSE", "WHILE",

"FOR",

"SWITCH", "CASE", "OTHERWISE", "GLOBAL", "BREAK", "CONTINUE", "RETURN",

"CLASSDEF", "PROPERTIES",

"METHODS", "EVENTS", "GET", "SET", "TRY", "CATCH", "INTEGER" ,"NUMBER",

"IMAG_NUM",

"IDENT", "NEWLINES", "STRING", "+", "-", "*", "/", "^", ".*", "./",

"ELEFTDIV", ".^",

"<", ">", "<=", ">=", "==", "~=", "&", "|", "LEFTDIV", "&&", "||", "~",

"UNARY", "CTRANSPOSE", "TRANSPOSE", ",", "=", ":", ";",

"]", "[", "(", ")", "}", "{", ".", "AT", "SUPERCLASSREF", "METAQUERY",

"$accept", "stash_comment", "function_beg", "classdef_beg",

"properties_beg", "methods_beg", "events_beg", "sep_no_nl",

"opt_sep_no_nl", "sep", "opt_sep",

"input", "string", "constant", "magic_colon", "anon_fcn_handle",

"fcn_handle", "cell_rows", "cell_rows1",

"matrix_rows", "matrix_rows1", "matrix", "cell", "primary_expr",

"postfix_expr",

"prefix_expr", "binary_expr", "simple_expr", "colon_expr", "assign_expr",

"expression", "identifier",

"fcn_name", "magic_tilde", "superclass_identifier", "meta_identifier",

"function1", "function2",

"classdef1", "word_list_cmd", "colon_expr1", "arg_list", "word_list",

"assign_lhs", "cell_or_matrix_row",

"param_list", "param_list1", "param_list2", "return_list", "return_list1",

"superclasses", "opt_superclasses",

"command", "select_command", "loop_command", "jump_command",

"except_command", "function",

"script_file", "classdef", "function_file", "function_list", "if_command",

"elseif_clauses", "elseif_clause", "switch_command",

"switch_case", "default_case", "case_list1", "case_list", "decl2",

"decl1", "declaration", "statement", "function_end", "classdef_end",

"simple_list", "simple_list1",

"list", "list1", "opt_list", "input1"};

%}

%token FUNCTION

%token END

%token IF

94

%token ELSEIF

%token ELSE

%token WHILE

%token FOR

%token SWITCH

%token CASE

%token OTHERWISE

%token GLOBAL

%token BREAK

%token CONTINUE

%token RETURN

%token CLASSDEF;

%token PROPERTIES;

%token METHODS;

%token EVENTS;

%token GET;

%token SET;

%token TRY;

%token CATCH;

%token INTEGER;

%token NUMBER

%token IMAG_NUM

%token IDENT

%token NEWLINES

%token STRING

%left ADD

%left SUB

%left MUL

%left DIV

%token POW

%token EMUL

%token EDIV

%token ELEFTDIV

%token EPOW

%token EXPR_LT

%token EXPR_GT

%token EXPR_LE

%token EXPR_GE

%token EXPR_EQ

%token EXPR_NE

%token EXPR_AND

%token EXPR_OR

%token LEFTDIV

%token EXPR_AND_AND

%token EXPR_OR_OR

%token EXPR_NOT

%left UNARY

%token CTRANSPOSE

%token TRANSPOSE

95

%token COMMA

%right EQ

%token COLON

%token SEMI_COLON

%token RBRACK

%token LBRACK

%token LPAR

%token RPAR

%token RBRACE

%token LBRACE

%token DOT

%token AT;

%token SUPERCLASSREF;

%token METAQUERY;

%token FCN_HANDLE;

%%

/* Statements and statement lists */

input : input1 { $$ = $1; }

| function_file { (absyntree)[Start] = $1[Start]; }

// | input function_file { $$ = $1; } // $$[Starts] =

$1[Start]::$2[Starts];

input1 : NEWLINES { $$ = $1; }

// | simple_list { $$ = $1; }

// | simple_list '\n' { $$ = $1; }

//simple_list : simple_list1 opt_sep { $$ = $1; }

//simple_list1 : statement { $$ = $1; }

// | simple_list1 sep statement { $$ = $1; }

opt_list : // empty

{ $$[Statements] = {}; }

| list opt_list

{ $$[Statements] = $1[Statement]::$2[Statements]; }

//list : list1 opt_sep

// { $$[Statement] = AbsynMat.SET_STMT_PRINT_FLAG($1[Statement],

SOME($2[Separator])); }

//list1 : statement { $$[Statement] = $1[Statement]; }

// | statement sep opt_list { $$[Statement] =

AbsynMat.STATEMENT_APPEND($1[Statement], $2[Separator], $3[Statements]); }

//$$[Statements] = $1[Statement]::$3[Statements];

list : statement opt_sep { $$[Statement] =

AbsynMat.STATEMENT_APPEND($1[Statement], $2[Separator]); }

statement : expression { $$[Statement] =

AbsynMat.STATEMENT(NONE(), SOME($1[Expression]), NONE(), NONE()); }

| command { $$[Statement] =

AbsynMat.STATEMENT(SOME($1[Command]), NONE(), NONE(), NONE()); }

96

| function_file { $$[Statement] =

AbsynMat.STATEMENT(NONE(), NONE(), SOME($1[Start]), NONE()); }

/* Expressions */

identifier : IDENT { $$[Ident] = $1; }

superclass_identifier : SUPERCLASSREF { $$ = $1; }

meta_identifier : METAQUERY { $$ = $1;}

constant : INTEGER { $$[Expression] = AbsynMat.INT(stringInt($1)); }

| NUMBER { $$[Expression] = AbsynMat.NUM(stringReal($1)); }

| IMAG_NUM { $$[Expression] = AbsynMat.INUM

(stringReal($1)); }

| STRING { $$[Expression] = AbsynMat.STR ($1[String]); }

cell : LBRACE RBRACE { $$[Expression] = AbsynMat.FINISH_CELL({}); }

| LBRACE SEMI_COLON RBRACE { $$[Expression] =

AbsynMat.FINISH_CELL({}); }

| LBRACE cell_rows RBRACE { $$[Expression] =

AbsynMat.FINISH_CELL($2[Cells]); }

cell_rows : cell_rows1 { $$[Cells] = $1[Cells]; }

| cell_rows1 SEMI_COLON /* Ignore trailing semicolon */ {

$$[Cells] = $1[Cells]; }

cell_rows1 : cell_or_matrix_row { $$[Cells] = $1[Cell]::{}; }

| cell_or_matrix_row SEMI_COLON cell_rows1 { $$[Cells] =

$1[Cell]::$3[Cells]; }

matrix : LBRACK RBRACK { $$[Expression] =

AbsynMat.FINISH_MATRIX({}); }

| LBRACK SEMI_COLON RBRACK { $$[Expression] =

AbsynMat.FINISH_MATRIX({}); }

| LBRACK COMMA RBRACK { $$[Expression] =

AbsynMat.FINISH_MATRIX({}); }

| LBRACK matrix_rows RBRACK { $$[Expression] =

AbsynMat.FINISH_MATRIX($2[Matrixs]); }

matrix_rows: matrix_rows1 { $$[Matrixs] = $1[Matrixs]; }

| matrix_rows1 SEMI_COLON /* Ignore trailing semicolon */ {

$$[Matrixs] = $1[Matrixs]; }

matrix_rows1: cell_or_matrix_row1 { $$[Matrixs] = $1[Matrix]::{}; }

| cell_or_matrix_row1 SEMI_COLON matrix_rows1 { $$[Matrixs]

= $1[Matrix]::$3[Matrixs]; }

cell_or_matrix_row : arg_list { $$[Cell] = AbsynMat.CELL($1[Arguments]); }

// $$[Argument] = AbsynMat.VALIDATE_MATRIX_ROW ($1[Argument]);

| arg_list COMMA /* Ignore trailing comma */

{ $$[Cell] = AbsynMat.CELL($1[Arguments]); } //

$$[Argument] = AbsynMat.VALIDATE_MATRIX_ROW ($1[Argument]);

cell_or_matrix_row1 : arg_list { $$[Matrix] = AbsynMat.MATRIX($1[Arguments]);

}

| arg_list COMMA /* Ignore trailing comma */

97

{ $$[Matrix] = AbsynMat.MATRIX($1[Arguments]); }

fcn_handle : AT identifier { $$[Expression] = AbsynMat.FCN_HANDLE($2[Ident]);

}

anon_fcn_handle : AT param_list statement { $$[Expression] =

AbsynMat.ANON_FCN_HANDLE($2[Parameters],$3[Statement]); }

primary_expr: identifier { $$[Expression] = AbsynMat.IDENTIFIER($1[Ident]); }

| constant { $$[Expression] = $1[Expression]; }

| matrix { $$[Expression] = $1[Expression]; }

| cell { $$[Expression] = $1[Expression]; }

| fcn_handle { $$[Expression] = $1[Expression]; }

| superclass_identifier { $$ = $1; }

| meta_identifier { $$ = $1; }

| LPAR expression RPAR { $$[Expression] = $2[Expression]; }

magic_colon : COLON { $$[Expression] = AbsynMat.CONSTANT(); }

magic_tilde : EXPR_NOT { $$ = $1; }

expression1 : expression { $$[Argument] = AbsynMat.ARGUMENT($1[Expression]);

}

magic_colon1 : magic_colon { $$[Argument] =

AbsynMat.ARGUMENT($1[Expression]); }

magic_tilde1 : magic_tilde { $$[Argument] =

AbsynMat.ARGUMENT($1[Expression]); }

arg_list : expression1 { $$[Arguments] = $1[Argument]::{}; }

| magic_colon1 { $$[Arguments] = $1[Argument]::{}; }

| magic_tilde1 { $$[Arguments] = $1[Argument]::{}; }

| magic_colon1 COMMA arg_list { $$[Arguments] =

$1[Argument]::$3[Arguments]; }

| magic_tilde1 COMMA arg_list { $$[Arguments] =

$1[Argument]::$3[Arguments]; }

| expression1 COMMA arg_list { $$[Arguments] =

$1[Argument]::$3[Arguments]; }

postfix_expr: primary_expr { $$[Expression] = $1[Expression]; }

| postfix_expr LPAR RPAR { $$[Expression] =

AbsynMat.INDEX_EXPRESSION ($1[Expression], {}); }

| postfix_expr LPAR arg_list RPAR { $$[Expression] =

AbsynMat.INDEX_EXPRESSION ($1[Expression], $3[Arguments]); }

| postfix_expr LBRACE RBRACE { $$[Expression] =

AbsynMat.INDEX_EXPRESSION ($1[Expression], {}); }

| postfix_expr LBRACE arg_list RBRACE { $$[Expression] =

AbsynMat.INDEX_EXPRESSION ($1[Expression], $3[Arguments]); }

| postfix_expr CTRANSPOSE { $$[Expression] =

AbsynMat.POSTFIX_EXPRESSION ($1[Expression], AbsynMat.OP_HERMITIAN()); }

| postfix_expr TRANSPOSE { $$[Expression] =

AbsynMat.POSTFIX_EXPRESSION ($1[Expression], AbsynMat.OP_TRANSPOSE()); }

prefix_expr : postfix_expr { $$[Expression] = $1[Expression]; }

| binary_expr { $$[Expression] = $1[Expression]; }

98

| EXPR_NOT prefix_expr %prec UNARY { $$[Expression] =

AbsynMat.PREFIX_EXPRESSION ($2[Expression], AbsynMat.EXPR_NOT()); }

| ADD prefix_expr %prec UNARY { $$[Expression] =

AbsynMat.PREFIX_EXPRESSION ($2[Expression], AbsynMat.UPLUS()); }

| SUB prefix_expr %prec UNARY { $$[Expression] =

AbsynMat.PREFIX_EXPRESSION ($2[Expression], AbsynMat.UMINUS()); }

binary_expr : prefix_expr ADD prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.ADD());

}

| prefix_expr SUB prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.SUB());

}

| prefix_expr MUL prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.MUL());

}

| prefix_expr DIV prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.DIV());

}

| prefix_expr POW prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.POW());

}

| prefix_expr EPOW prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.EPOW());

}

| prefix_expr EMUL prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.EMUL());

}

| prefix_expr EDIV prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.EDIV());

}

| prefix_expr LEFTDIV prefix_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression], AbsynMat.LDIV());

}

| prefix_expr ELEFTDIV prefix_expr{ $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.ELEFTDIV()); }

colon_expr : prefix_expr { $$[Expressions] = $1[Expression]::{}; } //

$$[Colon_Exp] = AbsynMat.COLON_EXP ($1[Expression]);

| prefix_expr COLON colon_expr { $$[Expressions] =

$1[Expression]::$3[Expressions]; } // $$[Colon_Exps] =

$1[Colon_Exp]::$3[Colon_Exps];

// colon_expr : colon_expr1 { $$[Expression] =

AbsynMat.FINISH_COLON_EXP($1[Colon_Exp]); }

simple_expr : colon_expr { $$[Expression] =

AbsynMat.FINISH_COLON_EXP($1[Expressions]); }

| simple_expr EXPR_LT simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_LT()); }

| simple_expr EXPR_LE simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_LE()); }

99

| simple_expr EXPR_EQ simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_EQ()); }

| simple_expr EXPR_GE simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_GE()); }

| simple_expr EXPR_GT simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_GT()); }

| simple_expr EXPR_NE simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_NE()); }

| simple_expr EXPR_AND simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_AND()); }

| simple_expr EXPR_OR simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_OR()); }

| simple_expr EXPR_AND_AND simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_AND_AND()); }

| simple_expr EXPR_OR_OR simple_expr { $$[Expression] =

AbsynMat.BINARY_EXPRESSION ($1[Expression], $3[Expression],

AbsynMat.EXPR_OR_OR()); }

/* Arrange for the lexer to return CLOSE_BRACE for `]' by looking ahead */

/* one token for an assignment op */

simple_expr2 : simple_expr { $$[Argument] =

AbsynMat.ARGUMENT($1[Expression]); }

assign_lhs : simple_expr2 { $$[Arguments] = $1[Argument]::{}; }

// | LBRACK arg_list RBRACK { $$[Arguments] = $2[Arguments]; }

assign_expr : assign_lhs EQ expression { $$[Expression] =

AbsynMat.ASSIGN_OP ($1[Arguments], AbsynMat.EQ(), $3[Expression]); }

expression : simple_expr { $$[Expression] = $1[Expression]; }

| assign_expr { $$[Expression] = $1[Expression]; }

| anon_fcn_handle { $$[Expression] = $1[Expression]; }

/* Selection statements */

select_command: if_command { $$[Command] = $1[Command]; }

| switch_command { $$[Command] = $1[Command]; }

/* If statement */

if_command : IF stash_comment expression opt_sep opt_list END

{ $$[Command] = AbsynMat.IF_COMMAND ($3[Expression],

$4[Separator], $5[Statements], {}, NONE(), {}, SOME($2[Mat_Comment]),

NONE()); }

| IF stash_comment expression opt_sep opt_list ELSE

stash_comment opt_sep opt_list END

{ $$[Command] = AbsynMat.IF_COMMAND ($3[Expression],

$4[Separator], $5[Statements], {}, SOME($8[Separator]), $9[Statements],

SOME($2[Mat_Comment]), SOME($7[Mat_Comment])); }

100

| IF stash_comment expression opt_sep opt_list elseif_clauses

ELSE stash_comment opt_sep opt_list END

{ $$[Command] = AbsynMat.IF_COMMAND ($3[Expression],

$4[Separator], $5[Statements], $6[Elseifs], SOME($9[Separator]),

$10[Statements], SOME($2[Mat_Comment]), SOME($7[Mat_Comment])); }

elseif_clauses : elseif_clause { $$[Elseifs] = $1[Elseif]::{}; }

| elseif_clause elseif_clauses { $$[Elseifs] =

$1[Elseif]::$2[Elseifs]; }

elseif_clause : ELSEIF stash_comment opt_sep expression opt_sep opt_list

{ $$[Elseif] = AbsynMat.ELSEIF_CLAUSE ($3[Separator],

$4[Expression], $5[Separator], $6[Statements], SOME($2[Mat_Comment])); }

/* Switch statement */

switch_command: SWITCH stash_comment expression opt_sep case_list END

{ $$[Command] = AbsynMat.SWITCH_COMMAND ($3[Expression],

$4[Separator], $5[Switch_t], SOME($2[Mat_Comment])); }

case_list : /* empty */ { $$[Switch_t] = ({}, NONE()); }

| default_case { $$[Switch_t] = ({},

SOME($1[Switch_Case])); }

| case_list1 { $$[Switch_t] = ($1[Switch_Cases], NONE()); }

| case_list1 default_case { $$[Switch_t] =

($1[Switch_Cases], SOME($2[Switch_Case])); }

case_list1 : switch_case { $$[Switch_Cases] = $1[Switch_Case]::{}; }

| switch_case case_list1 { $$[Switch_Cases] =

$1[Switch_Case]::$2[Switch_Cases]; }

switch_case : CASE stash_comment opt_sep expression opt_sep opt_list

{ $$[Switch_Case] = AbsynMat.SWITCH_CASE

($3[Separator],$4[Expression], $5[Separator], $6[Statements],

SOME($2[Mat_Comment])); }

default_case: OTHERWISE stash_comment opt_sep opt_list

{ $$[Switch_Case] = AbsynMat.DEFAULT_CASE($3[Separator],

$4[Statements], SOME($2[Mat_Comment])); }

/* Looping */

loop_command: WHILE stash_comment expression opt_sep opt_list END

{ $$[Command] = AbsynMat.WHILE_COMMAND ($3[Expression],

SOME($4[Separator]), $5[Statements], SOME($2[Mat_Comment])); }

| FOR stash_comment assign_lhs EQ expression opt_sep

opt_list END

{ $$[Command] = AbsynMat.FOR_COMMAND ($3[Arguments],

$5[Expression], SOME($6[Separator]), $7[Statements], SOME($2[Mat_Comment]));

}

| FOR stash_comment LPAR assign_lhs EQ expression

RPAR opt_sep opt_list END

{ $$[Command] = AbsynMat.FOR_COMMAND ($4[Arguments],

$6[Expression], SOME($8[Separator]), $9[Statements], SOME($2[Mat_Comment]));

}

/* Jumping */

101

jump_command: BREAK { $$[Command] = AbsynMat.BREAK_COMMAND (); }

| CONTINUE { $$[Command] = AbsynMat.CONTINUE_COMMAND (); }

| RETURN { $$[Command] = AbsynMat.RETURN_COMMAND (); }

/* Commands, declarations, and function definitions */

command : declaration { $$[Command] = $1[Command]; } //

$$[Decl_Command] = $1[Decl_Command];

| select_command { $$[Command] = $1[Command]; }

| loop_command { $$[Command] = $1[Command]; }

| jump_command { $$[Command] = $1[Command]; }

| except_command { $$ = $1; }

| classdef { $$ = $1; }

/* Declaration statemnts */

//parsing_decl_list : /* empty */ { $$[Decl_Elts] = {}; } //??

// declaration : GLOBAL parsing_decl_list decl1 { $$[Command] =

AbsynMat.MAKE_DECL_COMMAND($3[Decl_Elts]); } // $$[Decl_Command] =

AbsynMat.MAKE_DECL_COMMAND($3[Decl_Elts]);

declaration : GLOBAL decl1 { $$[Command] =

AbsynMat.MAKE_DECL_COMMAND($2[Decl_Elts]); }

decl1 : decl2 { $$[Decl_Elts] = $1[Decl_Elt]::{}; }

| decl2 decl1 { $$[Decl_Elts] =

$1[Decl_Elt]::$2[Decl_Elts]; }

decl_param_init : /* empty */ { $$[Decl_Elts] = {}; }

decl2 : identifier { $$[Decl_Elt] = AbsynMat.DECL($1[Ident],NONE()); }

// | identifier EQ decl_param_init expression { $$[Decl_Elt] =

AbsynMat.DECL($1[Ident],SOME($4[Expression])); }

| identifier EQ expression { $$[Decl_Elt] =

AbsynMat.DECL($1[Ident],SOME($3[Expression])); }

| magic_tilde { $$[Decl_Elt] =

AbsynMat.DECL($1[Ident],NONE()); }

/* Exceptions */

except_command : TRY stash_comment opt_sep opt_list CATCH stash_comment

opt_sep opt_list END

{ $$[Command] =

AbsynMat.TRY_CATCH_COMMAND($3[Separator],$4[Statements],$8[Statements],$2[Mat

_Comments],$6[Mat_Comments]); }

| TRY stash_comment opt_sep opt_list END

{ $$[Command] =

AbsynMat.TRY_CATCH_COMMAND($3[Separator],$4[Statements],{},$2[Mat_Comments],{

}); }

/* Some `subroutines' for function definitions */

/* push_fcn_symtab : */ /* empty */

/* { printf("\n push_fcn_symtab : empty"); } */

102

/* List of function parameters */

//param_list_beg: LPAR { $$ = $1; }

//param_list_end: RPAR { $$ = $1; }

//param_list : param_list_beg param_list1 param_list_end {

$$[Parameters] = $2[Parameters]; }

// | param_list_beg error { $$ = $1; }

param_list : LPAR param_list1 RPAR { $$[Parameters] = $2[Parameter]::{}; }

param_list1 : /* empty */ { $$[Parameters] = {}; }

| param_list2 { $$[Parameter] =

AbsynMat.PARM($1[Decl_Elts]); }

param_list2 : decl3 { $$[Decl_Elts] = $1[Decl_Elt]::{}; }

| decl3 COMMA param_list2 { $$[Decl_Elts] =

$1[Decl_Elt]::$3[Decl_Elts]; }

/* List of function return value names */

return_list : LBRACK RBRACK { $$[Decl_Elts] = {}; }

| return_list1 { $$[Decl_Elts] = $1[Decl_Elts]; }

| LBRACK return_list1 RBRACK { $$[Decl_Elts] =

$2[Decl_Elts]; }

return_list1: decl3 { $$[Decl_Elts] = $1[Decl_Elt]::{}; }

| decl3 COMMA return_list1 { $$[Decl_Elts] =

$1[Decl_Elt]::$3[Decl_Elts]; }

decl3 : identifier { $$[Decl_Elt] =

AbsynMat.DECL($1[Ident],NONE()); }

/* Function file */

function_file: FUNCTION function_list opt_sep opt_list

{ $$[Start] = AbsynMat.START($2[User_Function], $3[Separator],

$4[Statements]); }

/* Function definition */

//function_list: function { $$[User_Functions] = $1[User_Function]::{}; }

// | function sep function_list { $$[User_Functions] =

$1[User_Function]::$3[User_Functions]; }

function_list: function1 { $$[User_Function] = AbsynMat.FINISH_FUNCTION

({},$1[User_Function]); }

| return_list EQ function1 { $$[User_Function] =

AbsynMat.FINISH_FUNCTION ($1[Decl_Elts],$3[User_Function]); }

fcn_name : identifier { $$[Ident] = $1[Ident]; }

| GET DOT identifier { $$ = $3; }

| SET DOT identifier { $$ = $3; }

103

//function1 : fcn_name function2 { $$[User_Function] =

AbsynMat.FROB_FUNCTION ($1[Ident], $2[User_Function]); } //faced problem for

fetching fname in translation phase

function1 : fcn_name param_list opt_sep opt_list function_end

{ $$[User_Function] = AbsynMat.START_FUNCTION

($1[Ident],$2[Parameters], SOME($3[Separator]), $4[Statements],

$5[Statement]); }

| fcn_name opt_sep opt_list function_end {

$$[User_Function] = AbsynMat.START_FUNCTION ($1[Ident],{},

SOME($2[Separator]), $3[Statements], $4[Statement]); }

function_end: /* empty */ { $$[Statement] = AbsynMat.WITHOUT_END (); }

| END { $$[Statement] = AbsynMat.MAKE_END (); }

| function_end END { $$[Statement] = $1[Statement]; }

/* Classdef */

classdef_beg : CLASSDEF stash_comment { $$ = $1; }

classdef_end : END { $$ = $1; }

classdef1 : classdef_beg opt_attr_list identifier opt_superclasses {

$$ = $1; }

classdef : classdef1 '\n' class_body '\n' stash_comment classdef_end

{ $$ = $1; }

opt_attr_list : /* empty */ { $$[Classes] = {}; }

| LPAR attr_list RPAR { $$ = $1; }

attr_list : attr { $$ = $1; }

| attr_list COMMA attr { $$ = $1; }

attr : identifier { $$ = $1; }

| identifier EQ decl_param_init expression { $$ = $1; }

| EXPR_NOT identifier { $$ = $1; }

opt_superclasses : /* empty */ { $$[Classes] = {}; }

| superclasses { $$ = $1; }

superclasses : EXPR_LT identifier DOT identifier { $$ = $1; }

| EXPR_LT identifier { $$ = $1; }

| superclasses EXPR_AND identifier DOT identifier { $$ =

$1; }

| superclasses EXPR_AND identifier { $$ = $1; }

class_body : properties_block { $$ = $1; }

| methods_block { $$ = $1; }

| events_block { $$ = $1; }

| class_body '\n' properties_block { $$ = $1; }

| class_body '\n' methods_block { $$ = $1; }

| class_body '\n' events_block { $$ = $1; }

properties_beg : PROPERTIES stash_comment { $$ = $1; }

104

properties_block : properties_beg opt_attr_list '\n' properties_list '\n'

END { $$ = $1; }

properties_list : class_property { $$ = $1; }

| properties_list '\n' class_property { $$ = $1; }

class_property : identifier { $$ = $1; }

| identifier '=' decl_param_init expression ';' { $$ = $1;

}

methods_beg : METHODS stash_comment { $$ = $1; }

methods_block : methods_beg opt_attr_list '\n' methods_list '\n' END { $$

= $1; }

methods_list : function_file { $$ = $1; }

| methods_list '\n' function_file { $$ = $1; }

events_beg : EVENTS stash_comment { $$ = $1; }

events_block : events_beg opt_attr_list '\n' events_list '\n' END { $$ =

$1; }

events_list : class_event { $$ = $1; }

| events_list '\n' class_event { $$ = $1; }

class_event : identifier { $$ = $1; }

/* Miscellaneous */

stash_comment: /* empty */ { $$[Mat_Comment] = AbsynMat.COMMENT(NONE()); }

sep : COMMA { $$[Separator] = AbsynMat.COMMA(); }

| SEMI_COLON { $$[Separator] = AbsynMat.SEMI_COLON(); }

| NEWLINES { $$[Separator] = AbsynMat.NEWLINES(); }

| sep COMMA { $$ = $1; }//$$[Separators] =

$1[Separator]::$2[Separators];

| sep SEMI_COLON { $$ = $1; }//$$[Separators] =

$1[Separator]::$2[Separators];

| sep NEWLINES { $$ = $1; }//$$[Separators] =

$1[Separator]::$2[Separators];

opt_sep : /* empty */ { $$[Separator] = AbsynMat.EMPTY(); }

| sep { $$[Separator] = $1[Separator]; }

//| function_file { $$[Separator] =

AbsynMat.START_FUN($1[Start]); }

%%

105

Appendix C

AbsynMat.mo

encapsulated package AbsynMat

public type Ident = String;

uniontype Start

record START

User_Function usr_fun;

Separator sep;

list<Statement> stmt_lst;

end START;

end Start;

uniontype User_Function

// Begin defining a function.

record START_FUNCTION

Ident fname;

list<Parameter> prm;

Option<Separator> sep;

list<Statement> stmt_lst;

Statement stmt_2nd;

end START_FUNCTION;

// Do most of the work for defining a function.

/* record FROB_FUNCTION

Function_Name fname;

User_Function usr;

end FROB_FUNCTION;

*/

// Finish defining a function.

record FINISH_FUNCTION

list<Decl_Elt> ret;

User_Function usr;

end FINISH_FUNCTION;

end User_Function;

uniontype Argument

record ARGUMENT

Expression exp;

end ARGUMENT;

record VALIDATE_MATRIX_ROW

106

Argument arg_lst;

end VALIDATE_MATRIX_ROW;

end Argument;

uniontype Command

record NO_OP_COMMAND

//string

end NO_OP_COMMAND;

record TRY_CATCH_COMMAND

Separator sep;

list<Statement> stmt_lst1;

list<Statement> stmt_lst2;

list<Mat_Comment> m_cmd_lst;

list<Mat_Comment> m_cmd_lst2;

end TRY_CATCH_COMMAND;

record UNWIND_PROTECCOMMAND

list<Statement> stmt_lst1;

list<Statement> stmt_lst2;

list<Mat_Comment> m_cmd_lst;

end UNWIND_PROTECCOMMAND;

record DECL_COMMAND

Ident identifer;

list<Decl_Elt> decl_elt;

end DECL_COMMAND;

record BREAK_COMMAND

end BREAK_COMMAND;

record CONTINUE_COMMAND

end CONTINUE_COMMAND;

record RETURN_COMMAND

end RETURN_COMMAND;

record SWITCH_COMMAND

Expression exp;

Separator sep;

tuple<list<Switch_Case>, Option<Switch_Case>> swcse_lst;

Option<Mat_Comment> m_cmd_lst;

end SWITCH_COMMAND;

record WHILE_COMMAND

Expression exp;

Option<Separator> sep;

list<Statement> stmt_lst;

Option<Mat_Comment> m_cmd_lst;

end WHILE_COMMAND;

record FOR_COMMAND

list<Argument> arg;

Expression exp1;

Option<Separator> sep;

107

list<Statement> stmt_lst;

Option<Mat_Comment> m_cmd_lst;

end FOR_COMMAND;

record IF_COMMAND

Expression exp;

Separator sep;

list<Statement> stmts;

list<Elseif> elifs;

Option<Separator> sep2;

list<Statement> stmts2;

Option<Mat_Comment> cmts;

Option<Mat_Comment> cmts2;

end IF_COMMAND;

// Make a declaration command.

record MAKE_DECL_COMMAND

list<Decl_Elt> decl_elts;

end MAKE_DECL_COMMAND;

end Command;

uniontype Elseif

record ELSEIF_CLAUSE

Separator sep;

Expression exp;

Separator sep2;

list<Statement> stmt_lst;

Option<Mat_Comment> m_cmd_lst;

end ELSEIF_CLAUSE;

end Elseif;

uniontype Class

record CLASS

end CLASS;

end Class;

uniontype Parameter

record PARM

list<Decl_Elt> dec_elt;

end PARM;

end Parameter;

uniontype Decl_Elt

record DECL

Ident identifier;

Option<Expression> exp;

end DECL;

108

end Decl_Elt;

uniontype Switch_Case

record SWITCH_CASE

Separator sep;

Expression exp;

Separator sep2;

list<Statement> stmt;

Option<Mat_Comment> m_cmt;

end SWITCH_CASE;

record DEFAULT_CASE

Separator sep;

list<Statement> stmt;

Option<Mat_Comment> m_cmt;

end DEFAULT_CASE;

end Switch_Case;

uniontype Statement

record STATEMENT

Option<Command> cmd;

Option<Expression> exp;

Option<Start> usr_fun;

Option<Mat_Comment> m_cmt;

end STATEMENT;

record SET_STMT_PRINT_FLAG

Statement stmt_apd;

Option<Separator> set_sep;

end SET_STMT_PRINT_FLAG;

record STATEMENT_APPEND

Statement stmt_apd;

Separator sep;

// list<Statement> stmt_lst;

end STATEMENT_APPEND;

record MAKE_END

end MAKE_END;

record WITHOUT_END

end WITHOUT_END;

end Statement;

uniontype Separator

record COMMA

end COMMA;

record SEMI_COLON

end SEMI_COLON;

record NEWLINES

end NEWLINES;

record EMPTY

109

end EMPTY;

end Separator;

uniontype Expression

record INT

Integer int;

end INT;

record NUM

Real number;

end NUM;

record INUM

Real real;

end INUM;

record STR

String str;

end STR;

record CONSTANT

end CONSTANT;

record IDENTIFIER

Ident identifier;

// TypeCheck.ComType ty;

end IDENTIFIER;

record SIMPLE_ASSIGNMENT

Expression exp1;

Expression exp2;

Operator a_op;

end SIMPLE_ASSIGNMENT;

record MULTI_ASSIGNMENT

list<Argument> arg_lst;

Expression exp;

end MULTI_ASSIGNMENT;

record UNARY_EXPRESSION

Option<Expression> exp;

Operator u_op;

end UNARY_EXPRESSION;

record BINARY_EXPRESSION

Expression exp1;

Expression exp2;

Operator b_op;

end BINARY_EXPRESSION;

record BOOLEAN_EXPRESSION

Expression exp1;

Expression exp2;

end BOOLEAN_EXPRESSION;

110

record PREFIX_EXPRESSION

Expression exp;

Operator u_op;

end PREFIX_EXPRESSION;

record POSTFIX_EXPRESSION

Expression exp;

Operator u_op;

end POSTFIX_EXPRESSION;

/*

record COMPOUND_BINARY_EXPRESSION

Expression exp1;

Expression exp2;

Operator b_op;

Expression exp3;

Expression exp4;

Com_Binary_Op c_b_op;

end COMPOUND_BINARY_EXPRESSION;

*/

/* record COLON_EXPRESSION

Expression exp1;

Expression exp2;

Expression exp3;

end COLON_EXPRESSION;

*/

record FINISH_COLON_EXP

list<Expression> exp;

//Colon_Exp cln_exp;

end FINISH_COLON_EXP;

record FCN_HANDLE

Ident identifier;

end FCN_HANDLE;

record ANON_FCN_HANDLE

list<Parameter> par_lst2;

Statement stmt_lst;

end ANON_FCN_HANDLE;

// Finish building a matrix list.

record FINISH_MATRIX

list<Matrix> arg_lst;

end FINISH_MATRIX;

// Finish building a cell list.

record FINISH_CELL

list<Cell> cel;

end FINISH_CELL;

// Build an assignment to a variable.

record ASSIGN_OP

list<Argument> arg_lst;

Operator op1;

Expression exp;

end ASSIGN_OP;

record INDEX_EXPRESSION

111

Expression exp1;

list<Argument> arg_lst;

end INDEX_EXPRESSION;

end Expression;

uniontype Colon_Exp

record COLON_EXP

Expression exp;

end COLON_EXP;

end Colon_Exp;

uniontype Cell

record CELL

list<Argument> arg_lst;

end CELL;

end Cell;

uniontype Matrix

record MATRIX

list<Argument> arg_lst;

end MATRIX;

end Matrix;

uniontype Return

record RET

Index_Exp idx_exp;

end RET;

end Return;

uniontype Mat_Comment

record COMMENT

Option<String> comment;

end COMMENT;

end Mat_Comment;

uniontype Operator

record UPLUS // Unary Plus

end UPLUS;

record UMINUS // Unary Minus

end UMINUS;

record ADD // PLUS

end ADD;

record SUB // MINUS

end SUB;

record MUL // MTIMES

112

end MUL;

record DIV // MRDIVIDE

end DIV;

record POW // MPOWER

end POW;

record LDIV //MLDIVIDE

end LDIV;

record EXPR_LT //LT

end EXPR_LT;

record EXPR_LE //LE

end EXPR_LE;

record EXPR_EQ //EQ

end EXPR_EQ;

record EXPR_GE //GE

end EXPR_GE;

record EXPR_GT //GT

end EXPR_GT;

record EXPR_NE //NE

end EXPR_NE;

record EMUL //TIMES

end EMUL;

record EDIV //RDIVIDE

end EDIV;

record EPOW //POWER

end EPOW;

record ELEFTDIV //LDIVIDE

end ELEFTDIV;

record EXPR_AND //AND

end EXPR_AND;

record EXPR_OR //OR

end EXPR_OR;

record EXPR_AND_AND //AND AND

end EXPR_AND_AND;

record EXPR_OR_OR //OR OR

end EXPR_OR_OR;

record EXPR_NOT //NOT

end EXPR_NOT;

record OP_TRANSPOSE //TRANSPOSE

end OP_TRANSPOSE;

record OP_HERMITIAN //CTRANSPOSE

end OP_HERMITIAN;

record EQ // =

end EQ;

end Operator;

/*

uniontype Compound_Binary_Op

// ** compound operations **

record OP_TRANS_MUL

end OP_TRANS_MUL;

record OP_MUL_TRANS

end OP_MUL_TRANS;

record OP_HERM_MUL

end OP_HERM_MUL;

record OP_MUL_HERM

113

end OP_MUL_HERM;

record OP_TRANS_LDIV

end OP_TRANS_LDIV;

record OP_HERM_LDIV

end OP_HERM_LDIV;

record OP_EL_NOAND

end OP_EL_NOAND;

record OP_EL_NOOR

end OP_EL_NOOR;

record OP_EL_AND_NOT

end OP_EL_AND_NOT;

record OP_EL_OR_NOT

end OP_EL_OR_NOT;

end Compound_Binary_Op;

*/

end AbsynMat;

114

Appendix D

Main.mo

class Main

import Lexer;

import Parser;

import LexerModelica;

import ParserModelica;

import Util;

import RTOpts;

import System;

import Types;

public function main

"function: main

This is the main function that the MetaModelica Compiler (MMC) runtime

system calls to

start the translation."

input list<String> inStringLst;

protected

list<Types.Token> tokens;

ParserModelica.AstTree astTreeModelica;

type Mcode_MCodeLst = list<Mcode.MCode>;

algorithm

_ := matchcontinue (inStringLst)

local

String ver_str,errstr,filename,parser,unparsed;

list<String> args_1,args,chars;

Absyn.Program modast;

String s,str;

Boolean result;

Real tp,tl,tt;

case args as _::_

equation

{filename,parser} = Flags.new(args);

"Modelica" = parser;

false=(0==stringLength(filename));

print("\nParsing Modelica with file " + filename + "\n");

// call the lexer

print("\nstarting lexer");

tokens = LexerModelica.scan(filename,false);

print("\n");

//print(Types.printTokens(tokens,""));

print("\n Tokens processed:");

print(intString(listLength(tokens)));

// call the parser

print("\nstarting parser");

(result,astTreeModelica) =

ParserModelica.parse(tokens,filename,false);

115

print(anyString(astTreeModelica));

print("\n");

print("\n");

// printing the AST

/******************** Pass the AST to MATLAB Translator

****************************/

print("\n MATLAB to Modelica translator with file " + filename +

"\n");

modast=Translate.transform(astTreeModelica);

print("\n TESTING:");

print(anyString(modast));

unparsed=Dump.unparseStr(modast,true);

print("\n");

print("\n");

print("\n");

print(unparsed);

if (result) then

print("\nSUCCEED");

else

print("\n" +Error.printMessagesStr());

end if;

print("\nargs:" + filename);

printUsage();

then ();

case {}

equation

print("no args");

printUsage();

then ();

case _

equation

print("\n**********Error*************");

print("\n" +Error.printMessagesStr());

printUsage();

then ();

end matchcontinue;

end main;

public function printUsage

protected

Integer n;

List<String> strs;

algorithm

print("\nOMCCp v0.9.2 (OpenModelica compiler-compiler Parser generator)

Lexer and Parser Generator-2012");

end printUsage;

protected function readSettings

116

"function: readSettings

author: x02lucpo

Checks if 'settings.mos' exist and uses handleCommand with runScript(...) to

execute it.

Checks if '-s <file>.mos' has been

returns Interactive.InteractiveSymbolTable which is used in the rest of the

loop"

input list<String> inStringLst;

output String str;

algorithm

str:=

matchcontinue (inStringLst)

local

list<String> args;

case (args)

equation

outSymbolTable = Interactive.emptySymboltable;

"" = Util.flagValue("-s",args);

// this is out-commented because automatically reading settings.mos

// can make a system bad

// outSymbolTable = readSettingsFile("settings.mos",

Interactive.emptySymboltable);

then

outSymbolTable;

case (args)

equation

str = Util.flagValue("-s",args);

str = System.trim(str," \"");

outSymbolTable = readSettingsFile(str, Interactive.emptySymboltable);

then

outSymbolTable;

end matchcontinue;

end readSettings;

end Main;

117

Translate.mo

encapsulated package Translate

import List;

import Absyn;

import AbsynMat;

import System;

import Mat_Builtin;

import Mod_Builtin;

import Fnc_Handle;

public function escape_modkeywords

"This function is used to differentiate modelica keywords with underscore

added at the end if any modelica keyword

found in rml relations or statements"

input String instring;

output String outstring;

algorithm

outstring:= matchcontinue(instring)

local

String id;

case("match") then "match_";

case("algorithm") then "algorithm_";

case("annotation") then "annotation_";

case("as") then "as_";

case("block") then "block_";

case("case") then "case_";

case("class") then "class_";

case("connect") then "connect_";

case("connector") then "connector_";

case("constant") then "constant_";

case("discrete") then "discrete_";

case("each") then "each_";

case("else") then "else_";

case("elseif") then "elseif_";

case("elsewhen") then "elsewhen_";

case("encapsulated") then "encapsulated_";

case("end") then "end_";

case("enumeration") then "enumeration_";

case("equation") then "equation_";

case("extends") then "extends_";

case("external") then "external_";

case("final") then "final_";

case("flow") then "flow_";

case("for") then "for_";

case("function") then "function_";

case("if") then "if_";

case("import") then "import_";

case("in") then "in_";

case("initial") then "initial_";

case("inner") then "inner_";

case("input") then "input_";

case("list") then "list_";

case("loop") then "loop_";

case("local") then "local_";

118

case("model") then "model_";

case("matchcontinue") then "matchcontinue_";

case ("not") then "not_";

case("or") then "or_";

case("outer") then "outer_";

case("output") then "output_";

case("overload") then "overload_";

case("package") then "package_";

case("parameter") then "parameter_";

case("partial") then "partial_";

case("protected") then "protected_";

case("public") then "public_";

case("record") then "record_";

case("redeclare") then "redeclare_";

case("replaceable") then "replaceable_";

case("relation") then "relation_";

case("then") then "then_";

case("tuple") then "tuple_";

case("type") then "type_";

case("uniontype") then "uniontype_";

case("when") then "when_";

case("while") then "while_";

case("within") then "within_";

case(id) then id;

end matchcontinue;

end escape_modkeywords;

public function create_standard_elementitem

input Absyn.ElementSpec inelementspec;

output Absyn.ElementItem outelement;

algorithm

outelement:= matchcontinue(inelementspec)

local

Absyn.Info info;

Absyn.ElementSpec elementspec;

case(elementspec)

equation

print("\n create_standard_elementitem");

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

then

Absyn.ELEMENTITEM(Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),elements

pec,info,NONE()));

end matchcontinue;

end create_standard_elementitem;

public function create_pubclasspart

"function to create public classpart"

input list<Absyn.ElementItem> initem;

input Boolean inbool;

output Absyn.ClassPart outclasspart;

algorithm

outclasspart:= matchcontinue(initem,inbool)

119

local

list<Absyn.ElementItem> eitems;

Boolean b;

case(eitems,true)

equation

print("\n create_pubclasspart");

then

Absyn.PUBLIC(eitems);

case(eitems,false)

then

Absyn.PROTECTED(eitems);

end matchcontinue;

end create_pubclasspart;

public function create_class_parts

input Ident inident;

input Absyn.Restriction inrestriction;

input Boolean inbool;

input list<Absyn.ClassPart> inclasspart;

input list<String> incomment;

input Boolean inbool1;

output Absyn.Class outclass;

algorithm

outclass:=

matchcontinue(inident,inrestriction,inbool,inclasspart,incomment,inbool1)

local

Ident id;

Absyn.Restriction restriction;

Boolean partial1;

list<Absyn.ClassPart> classparts;

Absyn.Info info;

list<String> com;

String mcom;

Boolean b;

case(id,restriction,partial1,classparts,com,b)

equation

print("\n create_class_parts");

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mcom="empty";

then

Absyn.CLASS(id,partial1,false,false,restriction,Absyn.PARTS({},{},classparts,

mcom),info);

end matchcontinue;

end create_class_parts;

public function separator

input AbsynMat.Separator sep;

output Boolean sep2;

algorithm

sep2 := matchcontinue(sep)

/* case(AbsynMat.COMMA()

then

case(AbsynMat.COMMA())

then

120

case (AbsynMat.SEMI_COLON())

then

case(AbsynMat.NEWLINES())

then

*/

case(AbsynMat.EMPTY())

then true;

end matchcontinue;

end separator;

public function mat_operator

input AbsynMat.Operator op;

output Absyn.Operator mod_op;

output String str_op;

algorithm

(mod_op,str_op) := matchcontinue(op)

local

case(AbsynMat.UPLUS())

then (Absyn.UPLUS(),("UPLUS"));

case(AbsynMat.UMINUS())

then (Absyn.UMINUS(),("UMINUS"));

case(AbsynMat.ADD())

then (Absyn.ADD(),("ADD"));

case(AbsynMat.SUB())

then (Absyn.SUB(),("SUB"));

case(AbsynMat.MUL())

then (Absyn.MUL(),("MUL"));

case(AbsynMat.DIV())

then (Absyn.DIV(),("DIV"));

case(AbsynMat.POW())

then (Absyn.POW(),("POW"));

case(AbsynMat.EXPR_LT())

then (Absyn.LESS(),("EXPR_LT"));

case(AbsynMat.EXPR_LE())

then (Absyn.LESSEQ(),("EXPR_LE"));

case(AbsynMat.EXPR_EQ())

then (Absyn.EQUAL(),("EXPR_EQ")); ///???

case(AbsynMat.EXPR_GE())

then (Absyn.GREATEREQ(),("EXPR_GE"));

case(AbsynMat.EXPR_GT())

then (Absyn.GREATER(),("EXPR_GT"));

case(AbsynMat.EXPR_NE())

then (Absyn.NEQUAL(),("EXPR_NE"));

case(AbsynMat.EMUL())

then (Absyn.MUL_EW(),("EMUL"));

case(AbsynMat.EDIV())

then (Absyn.DIV_EW(),("EDIV"));

case(AbsynMat.EPOW())

then (Absyn.POW_EW(),("EPOW"));

case(AbsynMat.EXPR_AND())

then (Absyn.AND(),("EXPR_AND"));

case(AbsynMat.EXPR_OR())

then (Absyn.OR(),("EXPR_OR"));

case(AbsynMat.EXPR_AND_AND())

then (Absyn.AND(),("EXPR_AND_AND"));

case(AbsynMat.EXPR_OR_OR())

121

then (Absyn.OR(),("EXPR_OR_OR"));

case(AbsynMat.EXPR_NOT())

then (Absyn.NOT(),("EXPR_NOT"));

end matchcontinue;

end mat_operator;

public function vec_or_mtx

input list<list<Absyn.Exp>> exp_lst_lst;

output Boolean vec_mtx;

algorithm

vec_mtx := matchcontinue(exp_lst_lst)

local

list<list<Absyn.Exp>> exp_lst_lst1;

case({}) // Vector

equation

print("\n False False \n");

then false;

case(exp_lst_lst1) // Matrix

equation

print("\n True True 1\n");

print(anyString(exp_lst_lst1));

then true;

end matchcontinue;

end vec_or_mtx;

public function bool_chk

input Boolean chk;

input Boolean chk2;

output String o_str;

algorithm

o_str := matchcontinue (chk,chk2)

local

case(true,false)

then "vector";

case(false,false)

then "column_vector";

case(false,true)

then "matrix";

end matchcontinue;

end bool_chk;

public function chk_column_vet

input Integer int;

input Boolean chk;

output Boolean chko;

algorithm

chko := matchcontinue(int,chk)

local

Integer int1;

Boolean chk1;

case(1,chk1)

then chk1;

case(int1,chk1)

then false;

end matchcontinue;

end chk_column_vet;

122

public function cmp_lst1_lst2

input Integer lst1;

input Integer lst2;

output String ary;

algorithm

ary := matchcontinue(lst1,lst2)

local

String ary2;

Integer lst11, lst22;

Boolean chk, chk2, chk3;

/* case(lst11,lst22)

equation

chk = intGt(lst11,lst22);

chk3 = chk_column_vet(lst11,chk);

chk2 = intEq(lst11,lst22);

ary2 = bool_chk(chk,chk2);

then ary2; */

case(1,lst22)

then "column_vector";

case(lst11,0)

then "vector";

case(lst11,lst22)

then "matrix";

end matchcontinue;

end cmp_lst1_lst2;

public function dtype

input String typ;

input list<String> dnum;

output String outtyp;

algorithm

outtyp := matchcontinue(typ,dnum)

local

list<String> dnum1;

String typ1, dnum0, outtyp1;

Integer i, i2;

case(typ1,dnum0::dnum1)

equation

i = stringInt(dnum0);

i2 = i + 1;

outtyp1 = intString(i2);

then outtyp1;

end matchcontinue;

end dtype;

public function dtype_to_num

input list<String> d_type;

input list<String> dnum;

output list<String> outnum;

algorithm

outnum := matchcontinue(d_type,dnum)

local

list<String> d_type1, d_type2, dnum1, outnum1;

String typ, typ1;

Integer lth;

case({},dnum1)

then {};

123

case(typ::d_type1,dnum1)

equation

typ1 = dtype(typ,dnum1);

d_type2 = dtype_to_num(d_type1,dnum1);

outnum1 = listAppend({typ1},d_type2);

then outnum1;

end matchcontinue;

end dtype_to_num;

public function mat_matrix

input list<AbsynMat.Matrix> agr_lst;

input list<String> dnum;

output list<list<Absyn.Exp>> exp_lst;

output list<String> d_type;

output Boolean vec_mtx;

output String ary_info;

output list<String> d_type7;

algorithm

(exp_lst,d_type,vec_mtx,ary_info,d_type7) := matchcontinue(agr_lst,dnum)

local

list<AbsynMat.Argument> arg_lst1;

list<AbsynMat.Matrix> mtx_lst;

list<Absyn.Exp> exp, exp2, exp3;

list<String> d_type1, d_type2, d_type3, d_type6, d_type8, d_type9, dnum1,

dnum2;

list<list<Absyn.Exp>> mat;

Integer lst1, lst2;

Boolean vec_mtx1;

String ary;

case(AbsynMat.MATRIX(arg_lst1)::mtx_lst,dnum1)

equation

print("\n Expression MATRIX \n");

print(anyString(arg_lst1));

(exp,d_type1) = argument_lst(arg_lst1,true);

print("\n Expression MATRIX 0\n");

print(anyString(d_type1));

d_type6 = d_type1;

dnum2 = dtype_to_num(d_type1,dnum1);

print("\n Expression MATRIX 0001\n");

print(anyString(d_type6));

(mat, d_type2,vec_mtx1,ary,d_type8)= mat_matrix(mtx_lst,dnum2);

vec_mtx1 = vec_or_mtx(mat); //either variable is Vector or Matrix

d_type3 = listAppend(dnum2,d_type2);

d_type9 = listAppend(d_type6,d_type8);

print("\n Expression MATRIX 1 \n");

lst1 = listLength(d_type6);

print(anyString(lst1));

print("\n Expression MATRIX 2 \n");

lst2 = listLength(d_type8);

print(anyString(lst2));

ary = cmp_lst1_lst2(lst1,lst2);

print("\n Expression MATRIX 3 \n");

print(anyString(ary));

then

(exp::mat,d_type3,vec_mtx1,ary,d_type9);

124

case({},dnum1)

then ({},{},false,ary,{});

end matchcontinue;

end mat_matrix;

public function expression_cref

input AbsynMat.Expression exp;

output String cref;

algorithm

cref := matchcontinue(exp)

local

AbsynMat.Expression exp1;

String cref1;

AbsynMat.Ident ident;

case(AbsynMat.IDENTIFIER(ident))

equation

cref1 = ident;

then

cref1;

end matchcontinue;

end expression_cref;

public function fnc_call

input String cref;

input list<String> f_call;

output Boolean fnc_chk;

algorithm

fnc_chk := matchcontinue(cref,f_call)

local

list<String> f_call1;

String cref1;

Boolean fnc_chk1;

case(cref1,f_call1)

equation

fnc_chk1 = listMember(cref1,f_call1);

then fnc_chk1;

end matchcontinue;

end fnc_call;

public function fnc_ident

input String fnc_hdl_ident;

output Absyn.Exp mod_exp;

algorithm

mod_exp := matchcontinue(fnc_hdl_ident)

local

String fnc_hdl_ident1;

Absyn.Exp mod_exp1;

case(fnc_hdl_ident1)

equation

print("\n FNC_IDENT 0 \n");

then (Absyn.CREF(Absyn.CREF_IDENT(fnc_hdl_ident1,{})));

end matchcontinue;

end fnc_ident;

public function ident_lst

input list<String> fnc_hdl_idents;

output list<Absyn.Exp> mod_lst;

125

algorithm

mod_lst := matchcontinue(fnc_hdl_idents)

local

list<String> fnc_hdl_idents1;

Absyn.Exp mod_exp;

list<Absyn.Exp> mod_lst2, mod_lst3;

String fnc_hdl_ident,fname;

case(fnc_hdl_ident::fnc_hdl_idents1)

equation

mod_exp = fnc_ident(fnc_hdl_ident);

mod_lst2 = ident_lst(fnc_hdl_idents1);

mod_lst3 = listAppend(mod_exp::{},mod_lst2);

then mod_lst3;

case({})

then {};

end matchcontinue;

end ident_lst;

public function rpl_arg_fnc_hdl

input list<String> fnc_hdl_idents;

input String cref;

output Absyn.Exp out;

algorithm

out := matchcontinue(fnc_hdl_idents,cref)

local

list<String> fnc_hdl_idents1;

String cref1, fname;

list<Absyn.Exp> mod_lst;

case(fname::fnc_hdl_idents1,cref1) //drop first ident because its a

function name and rest of ident is declared as a function arguments

equation

mod_lst = ident_lst(fnc_hdl_idents1);

out =

Absyn.CALL(Absyn.CREF_IDENT(cref1,{}),Absyn.FUNCTIONARGS(mod_lst,{}));

print("\n rpl_arg_fnc_hdl \n");

print(anyString(out));

then out;

end matchcontinue;

end rpl_arg_fnc_hdl;

public function fnc_or_index

input list<AbsynMat.Argument> arg_lst;

input String cref;

input Boolean blt_chk;

input Boolean fnc_chk;

output Absyn.Exp out;

algorithm

out := matchcontinue(arg_lst,cref,blt_chk,fnc_chk)

local

list<Absyn.Subscript> sub_lst;

list<AbsynMat.Argument> arg_lst1;

list<Absyn.Exp> mod_lst;

String cref1;

Absyn.Exp out1;

case(arg_lst1,cref1,true,true)

equation

mod_lst = argument_lst(arg_lst1,false);

126

out1 =

Absyn.CALL(Absyn.CREF_IDENT(cref1,{}),Absyn.FUNCTIONARGS(mod_lst,{}));

then out1;

case(arg_lst1,cref1,true,false)

equation

mod_lst = argument_lst(arg_lst1,false);

out1 =

Absyn.CALL(Absyn.CREF_IDENT(cref1,{}),Absyn.FUNCTIONARGS(mod_lst,{}));

then out1;

case(arg_lst1,cref1,false,true)

equation

mod_lst = argument_lst(arg_lst1,false);

out1 =

Absyn.CALL(Absyn.CREF_IDENT(cref1,{}),Absyn.FUNCTIONARGS(mod_lst,{}));

then out1;

case(arg_lst1,cref1,false,false)

equation

print("\n arg_lst1,cref1,false,false \n");

print(anyString(arg_lst1));

sub_lst = array_lst(arg_lst1);

print("\n SUB LIST \n");

print(anyString(sub_lst));

out1 = Absyn.CREF(Absyn.CREF_IDENT(cref1,sub_lst));

then out1;

end matchcontinue;

end fnc_or_index;

public function tslat_vec_mtx

input list<list<Absyn.Exp>> mod_exp_lst;

input Boolean vec_mtx;

output Absyn.Exp mod_exp;

algorithm

mod_exp := matchcontinue(mod_exp_lst,vec_mtx)

local

list<list<Absyn.Exp>> mod_exp_lst1, mod_exp_lst2;

Boolean vec_mtx1;

list<Absyn.Exp> mod_exp1, mod_exp3, mod_exp4;

Absyn.Exp mod_exp2, out, out2;

Absyn.FunctionArgs fnc_args;

list<list<Absyn.Exp>> mod_exp_lst_lst;

case(mod_exp1::mod_exp_lst1,true)

equation

print("\n tslat_vec_mtx 0 \n");

print(anyString(mod_exp1));

out = Absyn.MATRIX({mod_exp1});

print(anyString(out));

mod_exp2 = tslat_vec_mtx(mod_exp_lst1,true);

{out2} = listAppend({out},{mod_exp2});

then out2;

case(mod_exp_lst1,true)

equation

print("\n tslat_vec_mtx 1 \n");

out = Absyn.MATRIX(mod_exp_lst1);

then out;

case(mod_exp_lst1,false)

equation

print("\n tslat_vec_mtx 2 \n");

127

{mod_exp4} = mod_exp_lst1;

fnc_args = Absyn.FUNCTIONARGS(mod_exp4,{});

out = Absyn.CALL(Absyn.CREF_IDENT("array",{}),fnc_args);

then out;

end matchcontinue;

end tslat_vec_mtx;

public function bool_String

input Boolean bool;

output String mtx_vec;

algorithm

mtx_vec := matchcontinue(bool)

local

String mtx_vec1;

case(true)

then "matrix";

case(false)

then "vector";

end matchcontinue;

end bool_String;

public function fnc_hdl_stmt

input AbsynMat.Statement fnc_stmt;

output Absyn.Exp mod_exp;

output list<String> ident_lst;

algorithm

(mod_exp,ident_lst) := matchcontinue(fnc_stmt)

local

AbsynMat.Expression exp;

Absyn.Exp mod_exp1;

list<String> stmt_ident;

case(AbsynMat.STATEMENT(NONE(),SOME(exp),NONE(),NONE()))

equation

print("\n fnc_hdl_stmt exp \n");

print(anyString(exp));

(mod_exp1,stmt_ident) = expression(exp,{},{});

print("\n fnc_hdl_stmt \n");

print(anyString(stmt_ident));

then (mod_exp1,stmt_ident);

end matchcontinue;

end fnc_hdl_stmt;

public function arg_fnc_hdl

input Boolean fnc_hdl_chk;

input list<String> fnc_hdl_idents;

input String cref;

input list<AbsynMat.Argument> arg_lst;

input Boolean blt_chk;

input Boolean fnc_chk;

output Absyn.Exp mod_exp;

algorithm

mod_exp :=

matchcontinue(fnc_hdl_chk,fnc_hdl_idents,cref,arg_lst,blt_chk,fnc_chk)

local

Boolean blt_chk1,fnc_chk1;

list<String> fnc_hdl_idents1;

String cref1;

128

list<AbsynMat.Argument> arg_lst1;

Absyn.Exp mod_exp1;

case(true,fnc_hdl_idents1,cref1,arg_lst1,blt_chk1,fnc_chk1)

equation

print("\n rpl_arg_fnc_hdl(fnc_hdl_idents1,cref1); \n");

mod_exp1 = rpl_arg_fnc_hdl(fnc_hdl_idents1,cref1); // replaces fnc arg

with fnd hdl idents for proper fnc call

then mod_exp1;

case(false,fnc_hdl_idents1,cref1,arg_lst1,blt_chk1,fnc_chk1)

equation

print("\n fnc_or_index(arg_lst1,cref1,blt_chk1,fnc_chk1); \n");

mod_exp1 = fnc_or_index(arg_lst1,cref1,blt_chk1,fnc_chk1);

then mod_exp1;

end matchcontinue;

end arg_fnc_hdl;

public function decl

input AbsynMat.Decl_Elt decl_elt;

output String ident;

algorithm

ident := matchcontinue(decl_elt)

local

String ident2, ident_in;

case(AbsynMat.DECL(ident_in,NONE()))

equation

print("\n Declaration \n");

print(anyString(ident_in));

then ident_in;

end matchcontinue;

end decl;

public function decl_lst

input list<AbsynMat.Decl_Elt> decl_elt_lst;

output list<String> ident_lst;

algorithm

ident_lst := matchcontinue(decl_elt_lst)

local

list<AbsynMat.Decl_Elt> decl_elt_lst2;

AbsynMat.Decl_Elt decl_elt;

list<String> ident_out, ident2;

String ident;

case(decl_elt::decl_elt_lst2)

equation

print("\n Declaration List \n");

ident = decl(decl_elt);

ident2 = decl_lst(decl_elt_lst2);

ident_out = listAppend({ident},ident2);

print("\n Declaration List OUT \n");

print(anyString(ident_out));

then ident_out;

case({})

then {};

end matchcontinue;

end decl_lst;

/*

public function loop_heading // transform for s = [1,2,3] to for s in

{1,2,3}

129

input list<AbsynMat.Matrix> mtx;

input list<String> lp_chk;

output Absyn.Exp mod_exp;

output list<String> mat_vet;

algorithm

(mod_exp,mat_vet) := matchcontinue (mtx,lp_chk)

local

String mv;

list<String> arg_str, d_type, arg_str, f_call, ary_n_type;

Absyn.Exp out;

list<Absyn.Exp> mod_lst;

list<list<Absyn.Exp>> mod_lst_lst;

Boolean vec_mtx;

list<AbsynMat.Matrix> mtx1;

list<AbsynMat.Argument> arg_lst;

case(AbsynMat.MATRIX(arg_lst)::{},{"for_loop"})

equation

(mod_lst,arg_str) = argument_lst(arg_lst,false);

out = Absyn.ARRAY(mod_lst);

print("\n Heading for loop \n");

then

(out,arg_str);

case(mtx1,f_call)

equation

(mod_lst_lst,d_type,vec_mtx) = mat_matrix(mtx);

print("\n Expression FINISH_MATRIX 3\n");

print(anyString(d_type));

out = tslat_vec_mtx(mod_lst_lst,vec_mtx);

mv = bool_String(vec_mtx);

ary_n_type = listAppend({mv},d_type);

then

(out,ary_n_type);

end matchcontinue;

end loop_heading;

*/

public function ident_subscript2

input Absyn.Exp mod_exp;

output String dim;

algorithm

dim := matchcontinue(mod_exp)

local

Integer i;

Real r;

String dim1, dim2;

case(Absyn.INTEGER(i))

equation

dim1 = intString(i);

dim2 = "1" + "x";

then dim2;

case(Absyn.REAL(r))

equation

dim1 = realString(r);

dim2 = dim1 + "x";

then dim2;

case(Absyn.CREF(Absyn.CREF_IDENT(dim1,{})))

equation

130

dim2 = "ARYIDENT";

then dim2;

case(Absyn.BINARY(Absyn.CREF(Absyn.CREF_IDENT(dim1,{})),Absyn.ADD(),Absyn.INT

EGER(i)))

equation

dim2 = "ARYIDENT";

then dim2;

case(Absyn.BINARY(Absyn.CREF(Absyn.CREF_IDENT(dim1,{})),Absyn.SUB(),Absyn.INT

EGER(i)))

equation

dim2 = "ARYIDENT";

then dim2;

case(Absyn.BINARY(Absyn.CREF(Absyn.CREF_IDENT(dim1,{})),Absyn.ADD(),Absyn.CRE

F(Absyn.CREF_IDENT(dim2,{}))))

equation

dim2 = "ARYIDENT";

then dim2;

case(Absyn.BINARY(Absyn.CREF(Absyn.CREF_IDENT(dim1,{})),Absyn.SUB(),Absyn.CRE

F(Absyn.CREF_IDENT(dim2,{}))))

equation

dim2 = "ARYIDENT";

then dim2;

end matchcontinue;

end ident_subscript2;

public function ident_subscript

input list<Absyn.Exp> mod_exp;

output String dim;

algorithm

dim := matchcontinue(mod_exp)

local

Absyn.Exp mod;

list<Absyn.Exp> mod_exp1;

String dim1, dim2, dim0;

case({})

then "0";

case(mod::mod_exp1)

equation

print("\n ident_subscript \n");

print(anyString(mod));

dim1 = ident_subscript2(mod);

dim2 = ident_subscript(mod_exp1);

dim0 = stringAppend(dim1,dim2);

then dim0;

end matchcontinue;

end ident_subscript;

public function length

input Integer lgth;

input String dim;

output String string;

algorithm

string := matchcontinue(lgth,dim)

131

local

Integer lgth1;

String dim1;

case(3,dim1)

then "empty";

case(lgth1,dim1)

then dim1;

end matchcontinue;

end length;

public function vec_mtx

input list<String> stringlist;

input String dim;

output String dimo;

algorithm

dimo := matchcontinue(stringlist,dim)

local

list<String> stringlist1;

String dim1, dim2;

Integer lgth;

case(stringlist1,dim1)

equation

lgth = listLength(stringlist1);

dim2 = length(lgth,dim1);

then dim2;

end matchcontinue;

end vec_mtx;

public function mat_builtin

input String cref;

input list<Absyn.Exp> mod_exp;

output String dim;

output String dim2;

algorithm

(dim,dim2) := matchcontinue(cref,mod_exp)

local

list<Absyn.Exp> mod_exp2,mod_exp3;

String dim0, ret_str,fnc_dim, fnc_dim2, fnc_dim3, dim1;

Integer i,j;

list<String> stringlist;

case("zeros",Absyn.INTEGER(i)::mod_exp3)

equation

Absyn.INTEGER(j)::{}=mod_exp3;

print("\n PRINT zeros dim \n");

print(anyString(j));

fnc_dim = intString(i);

fnc_dim2 = intString(j);

fnc_dim3 = stringAppend(fnc_dim,fnc_dim2);

then ("zeros",fnc_dim3);

case("ones",Absyn.INTEGER(i)::mod_exp3)

equation

Absyn.INTEGER(j)::{}=mod_exp3;

print("\n PRINT I \n");

print(anyString(j));

fnc_dim = intString(i);

fnc_dim2 = intString(j);

fnc_dim3 = stringAppend(fnc_dim,fnc_dim2);

132

then ("ones",fnc_dim3);

case("sqrt",mod_exp2)

then (ret_str,"Real");

case("ceil",mod_exp2)

then (ret_str,"Real");

case("floor",mod_exp2)

then (ret_str,"Real");

case("abs",mod_exp2) //real or integer, depends on input

then (ret_str,"Real");

case("mod",mod_exp2) //real or integer, depends on input

then (ret_str,"Real");

case(ret_str,mod_exp2)

equation

print("\n MODE EXP2 \n");

print(anyString(mod_exp2));

dim0 = ident_subscript(mod_exp2);

print("\n MODE EXP2 2 \n");

print(anyString(dim0));

stringlist = stringListStringChar(dim0);

print("\n MODE EXP2 3 \n");

print(anyString(stringlist));

dim1 = vec_mtx(stringlist,dim0);

print("\n MODE EXP2 4 \n");

print(anyString(dim1));

then (ret_str,dim1);

end matchcontinue;

end mat_builtin;

public function expression

input AbsynMat.Expression exp;

input list<String> f_call;

input list<String> fnc_hdl_idents_i;

output Absyn.Exp mod_exp;

output list<String> stmt_ident;

algorithm

(mod_exp,stmt_ident) := matchcontinue(exp,f_call,fnc_hdl_idents_i)

local

list<AbsynMat.Argument> arg, arg_lst;

list<AbsynMat.Expression> exp_lst;

list<Absyn.Exp> mod_exp6;

AbsynMat.Operator op;

AbsynMat.Expression exp1,exp2, exp3, mat_exp;

AbsynMat.Ident ident;

String mv, vname, str, cref, ident1, strop;

AbsynMat.Operator mat_op;

Absyn.Operator mod_op;

Absyn.Exp out, out1, outexp1, outexp2, outexp3, out_name;

list<AbsynMat.Matrix> mtx;

list<list<Absyn.Exp>> mod_lst;

String ary_info, dim_str, fnc_dim;

Real number;

Integer int;

list<String> d_type9, dims, ident_op, strop_lst, ident2, ident3, ident4,

f_call1,f_call2, ary, d_type, ary_n_type, fnc_hdl_idents;

Boolean blt_chk, fnc_chk, vec_mtx, fnc_hdl_chk;

Absyn.FunctionArgs fnc_args;

AbsynMat.Statement fnc_stmt;

133

list<AbsynMat.Parameter> prm_lst;

list<AbsynMat.Decl_Elt> decl_elt_lst;

case(AbsynMat.FINISH_COLON_EXP(exp_lst),f_call1,fnc_hdl_idents)

equation

print("\n Expression FINISH_COLON_EXP \n");

print(anyString(f_call1));

print("\n Expression FINISH_COLON_EXP \n");

print(anyString(fnc_hdl_idents));

(SOME(outexp3),f_call2) =

expression_lst(exp_lst,f_call1,fnc_hdl_idents);

print("\n Expression FINISH_COLON_EXP 2 \n");

print(anyString(f_call2));

// {exp3} = exp_lst;

// (outexp3,ident2) = expression(exp3,f_call2,fnc_hdl_idents);

print("\n Expression FINISH_COLON_EXP 4 \n");

// print(anyString(ident2));

print("\n Expression FINISH_COLON_EXP 5 \n");

print(anyString(outexp3));

then

(outexp3,f_call2);

case(AbsynMat.BINARY_EXPRESSION(exp1,exp2,op),f_call1,fnc_hdl_idents)

equation

(outexp1,ident2) = expression(exp1,{},fnc_hdl_idents);

(outexp2,ident3) = expression(exp2,{},fnc_hdl_idents);

(mod_op,strop) = mat_operator(op);

out = Absyn.BINARY(outexp1,mod_op,outexp2);

strop_lst = {strop};

ident_op = listAppend(ident2,strop_lst);

ident4 = listAppend(ident_op,ident3); //ident4 =

listAppend(ident2,ident3);

print("\n Expression BINARY_EXPRESSION \n");

print(anyString(strop));

print("\n Expression BINARY_EXPRESSION 2\n");

print(anyString(ident_op));

print("\n Binary Idents \n");

print(anyString(ident4));

then

(out,ident4);

case(AbsynMat.ANON_FCN_HANDLE(AbsynMat.PARM(decl_elt_lst)::{},fnc_stmt),f_cal

l1,fnc_hdl_idents)

equation

ident2 = decl_lst(decl_elt_lst);

print("\n AbsynMat.ANON_FCN_HANDLE \n");

print(anyString(f_call1));

(out,ident3) = fnc_hdl_stmt(fnc_stmt);

print("\n AbsynMat.ANON_FCN_HANDLE 2 \n");

print(anyString(ident2));

ident4 = listAppend(ident2,ident3);

then (out,ident4);

case(AbsynMat.FINISH_MATRIX(mtx),f_call1,fnc_hdl_idents)

equation

print("\n Expression FINISH_MATRIX 0\n");

print(anyString(mtx));

print("\n Expression FINISH_MATRIX 1\n");

print(anyString(f_call1));

134

//(out,mv) = loop_heading(mtx,f_call1);

(mod_lst,d_type,vec_mtx,ary_info,d_type9) = mat_matrix(mtx,{"0"});

print("\n Expression FINISH_MATRIX 3\n");

print(anyString(mod_lst));

print("\n Expression FINISH_MATRIX 33\n");

print(anyString(d_type));

print("\n Expression FINISH_MATRIX 333\n");

print(anyString(vec_mtx));

print("\n Expression FINISH_MATRIX 3333\n");

print(anyString(ary_info));

out = tslat_vec_mtx(mod_lst,vec_mtx);

// mv = bool_String(vec_mtx);

//out = Absyn.ARRAY(mod_lst);

//out = Absyn.SUBSCRIPT(mod_lst);

print("\n Data Type \n");

print(anyString(out));

// ary = {mv};

ary_n_type = listAppend({ary_info},d_type);

print("\n Expression FINISH_MATRIX 5 \n");

print(anyString(ary_n_type));

then

(out,ary_n_type);

case(AbsynMat.PREFIX_EXPRESSION(mat_exp, mat_op),f_call1,fnc_hdl_idents)

equation

print("\n Expression PREFIX_EXPRESSION \n");

print(anyString(mat_op));

(mod_op,strop) = mat_operator(mat_op);

(outexp1,ident2) = expression(mat_exp,{},fnc_hdl_idents);

print("\n Expression PREFIX_EXPRESSION 2 \n");

print(anyString(ident2));

strop_lst = {strop};

ident_op = listAppend(strop_lst,ident2);

out = Absyn.UNARY(mod_op,outexp1);

then

(out,ident_op);

case(AbsynMat.INDEX_EXPRESSION(mat_exp,arg_lst),f_call1,fnc_hdl_idents)

equation

cref = expression_cref(mat_exp);

print("\n Expression INDEX_EXPRESSION 0 \n");

print(anyString(arg_lst));

(mod_exp6,dims) = argument_lst(arg_lst,false);

print("\n Expression INDEX_EXPRESSION 01 \n");

print(anyString(mod_exp6));

(dim_str,fnc_dim) = mat_builtin(cref,mod_exp6);

print("\n Expression INDEX_EXPRESSION 1 \n");

print(anyString(dim_str));

print("\n Expression INDEX_EXPRESSION 2 \n");

print("\n Expression INDEX_EXPRESSION 3 \n");

print(anyString(mat_exp));

blt_chk = Mat_Builtin.builtIn(cref);

fnc_chk = fnc_call(cref,f_call1);

fnc_hdl_chk = fnc_call(cref,fnc_hdl_idents); // return true if fnc

name matches the list of fnc hdl idents

print("\n Expression INDEX_EXPRESSION 1 \n");

print(anyString(fnc_hdl_chk));

print("\n Expression INDEX_EXPRESSION 2 \n");

135

print(anyString(fnc_hdl_idents));

out =

arg_fnc_hdl(fnc_hdl_chk,fnc_hdl_idents,cref,arg_lst,blt_chk,fnc_chk);

// out = rpl_arg_fnc_hdl(fnc_hdl_idents,cref); // replaces fnc arg

with fnd hdl idents for proper fnc call

// out = fnc_or_index(arg_lst,cref,blt_chk,fnc_chk);

print("\n Class Reference 1 \n");

print(anyString(cref));

print("\n Class Reference 2 \n");

print(anyString(out));

print("\n Class Reference 3 \n");

print(anyString(fnc_dim));

then

(out,{cref,fnc_dim});

case(AbsynMat.STR(str),f_call1,fnc_hdl_idents)

then (Absyn.STRING(str),{});

case(AbsynMat.IDENTIFIER(ident),f_call1,fnc_hdl_idents)

equation

print("\n Expression IDENTIFIER \n");

print(anyString(ident));

then (Absyn.CREF(Absyn.CREF_IDENT(ident,{})),{ident});

case(AbsynMat.INT(int),f_call1,fnc_hdl_idents)

equation

print("\n MATLAB INTEGER \n");

then (Absyn.INTEGER(int),{"Integer"});

case(AbsynMat.NUM(number),f_call1,fnc_hdl_idents)

equation

print("\n MATLAB REAL \n");

then (Absyn.REAL(number),{"Real"});

case(AbsynMat.CONSTANT(),f_call1,fnc_hdl_idents)

equation

print("\n COLON CONSTANT \n");

then (Absyn.REAL(0.000),{"Constants"});

end matchcontinue;

end expression;

public function expression_lst

input list<AbsynMat.Expression> exp_lst;

input list<String> f_call;

input list<String> fnc_hdl_ident;

output Option<Absyn.Exp> out_exp;

output list<String> f_call1;

algorithm

(out_exp,f_call1) := matchcontinue(exp_lst,f_call,fnc_hdl_ident)

local

list<AbsynMat.Expression> exp_lst1;

AbsynMat.Expression exp1, exp2, exp3, exp4;

Absyn.Exp mod_exp1, mod_exp2, mod_exp3;

Option<Absyn.Exp> out_exp1;

Absyn.Exp out_exp2;

list<String> f_call2, fnc_hdl_ident1;

case(AbsynMat.FINISH_COLON_EXP(exp_lst1)::{},f_call2,fnc_hdl_ident1)

equation

print("\n Expression_lst FINISH_COLON_EXP(exp_lst1)::{} \n");

print(anyString(f_call2));

(out_exp1,{}) = expression_lst(exp_lst1,f_call2,fnc_hdl_ident1);

then

136

(out_exp1,{});

case(AbsynMat.FINISH_COLON_EXP(exp4::{})::{},{},fnc_hdl_ident1)

equation

print("\n Expression_lst FINISH_COLON_EXP(exp4::{})::{}");

(out_exp2,f_call2) = expression(exp4,{},fnc_hdl_ident1);

print("\n Expression_lst FINISH_COLON_EXP(exp4.1::{})::{} \n");

print(anyString(f_call2));

print("\n Expression_lst FINISH_COLON_EXP(exp4.2::{})::{} \n");

print(anyString(out_exp2));

then

(SOME(out_exp2),f_call2);

case(exp1::exp2::exp3::{},{},fnc_hdl_ident1)

equation

print("\n Expression_lst exp1::exp2::exp3::{}");

// print(anyString(exp2));

mod_exp1 = expression(exp1,{},{});

mod_exp2 = expression(exp2,{},{});

mod_exp3 = expression(exp3,{},{});

out_exp2 = Absyn.RANGE(mod_exp1,SOME(mod_exp2),mod_exp2);

out_exp1 = SOME(out_exp2);

then

(out_exp1,{});

case(exp1::exp2::{},{},fnc_hdl_ident1)

equation

print("\n Expression_lst exp1::exp2::{}");

// print(anyString(exp2));

mod_exp1 = expression(exp1,{},{});

mod_exp2 = expression(exp2,{},{});

out_exp2 = Absyn.RANGE(mod_exp1,NONE(),mod_exp2);

out_exp1 = SOME(out_exp2);

then

(out_exp1,{});

case(exp1::{},f_call2,fnc_hdl_ident1)

equation

print("\n Expression_lst exp1::{} \n");

print(anyString(exp1));

(mod_exp1,f_call2) = expression(exp1,f_call2,fnc_hdl_ident1);

print("\n Expression exp1::{} \n");

print(anyString(mod_exp1));

print("\n Expression exp1::{} 2\n");

print(anyString(f_call2));

then

(SOME(mod_exp1),f_call2);

case({},{},fnc_hdl_ident1)

then (NONE(),{});

end matchcontinue;

end expression_lst;

public function for_ident

input list<AbsynMat.Argument> arg;

input Option<AbsynMat.Expression> mod_exp;

output String out_ident;

algorithm

(out_ident) := matchcontinue(arg,mod_exp)

local

AbsynMat.Ident ident;

String ident1;

137

AbsynMat.Argument arg1;

Option<AbsynMat.Expression> exp;

case(arg1::{},NONE())

equation

print("\n FOR IDENT arg1::{},NONE()");

exp = for_argument(arg1);

ident1 = for_ident({},exp);

then

ident1;

case({},SOME(AbsynMat.FINISH_COLON_EXP(AbsynMat.IDENTIFIER(ident)::{})))

equation

print("\n FOR IDENT

AbsynMat.FINISH_COLON_EXP(AbsynMat.IDENTIFIER(ident)::{}))");

ident1 = ident;

then ident1;

end matchcontinue;

end for_ident;

public function for_argument

input AbsynMat.Argument arg;

output Option<AbsynMat.Expression> mod_exp;

algorithm

mod_exp := matchcontinue(arg)

local

AbsynMat.Expression exp;

case(AbsynMat.ARGUMENT(exp))

then SOME(exp);

end matchcontinue;

end for_argument;

public function argument

input AbsynMat.Argument arg;

input Boolean tf; //true

output Absyn.Exp mod_exp;

output list<String> arg_ident;

algorithm

(mod_exp,arg_ident) := matchcontinue(arg,tf)

local

String var_name,ident;

AbsynMat.Expression exp;

Absyn.Exp exp1;

list<String> ident2;

Integer int;

Real number;

AbsynMat.Matrix mtx;

case(AbsynMat.ARGUMENT(exp),false)

equation

print("\n Argument AbsynMat.ARGUMENT(exp) \n");

print(anyString(exp));

(exp1,ident2) = expression(exp,{},{});

print("\n AbsynMat.ARGUMENT(exp),false \n");

print(anyString(exp1));

print("\n AbsynMat.ARGUMENT(exp),false \n");

print(anyString(ident2));

then

(exp1,ident2);

138

case(AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP(AbsynMat.INT(int)::{})),true

)

equation

ident = intString(int);

then (Absyn.CREF(Absyn.CREF_IDENT(ident,{})),{"Integer"});

case(AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP(AbsynMat.NUM(number)::{})),t

rue)

equation

ident = realString(number);

then (Absyn.CREF(Absyn.CREF_IDENT(ident,{})),{"Real"});

case(AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP(AbsynMat.IDENTIFIER(ident)::

{})),true)

then (Absyn.CREF(Absyn.CREF_IDENT(ident,{})),{ident});

case(AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP(AbsynMat.PREFIX_EXPRESSION(A

bsynMat.INT(int), AbsynMat.UMINUS())::{})),true)

equation // dealing with unary elements in array e.g. a = [-1, 2 3

4]

ident = intString(-int);

then (Absyn.CREF(Absyn.CREF_IDENT(ident,{})),{"Integer"});

case(AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP(AbsynMat.PREFIX_EXPRESSION(A

bsynMat.NUM(number), AbsynMat.UMINUS())::{})),true)

equation // dealing with unary elements in array e.g. a = [-1, 2 3

4]

ident = realString(-number);

then (Absyn.CREF(Absyn.CREF_IDENT(ident,{})),{"Real"});

end matchcontinue;

end argument;

public function argument_lst

input list<AbsynMat.Argument> arg;

input Boolean mat_mtx;

output list<Absyn.Exp> mod_exp;

output list<String> arg_ident;

algorithm

(mod_exp,arg_ident) := matchcontinue(arg,mat_mtx)

local

list<AbsynMat.Argument> arglst2;

Absyn.Exp exp;

list<Absyn.Exp> mod_lst, mod_lst1;

AbsynMat.Argument arg1;

list<String> ident, ident1, ident2;

Boolean tf;

case(arg1::arglst2,tf)

equation

print("\n ARGUMENT LIST \n");

print(anyString(arg1));

print("\n ARGUMENT LIST tf\n");

print(anyString(tf));

(exp,ident) = argument(arg1,tf);

print("\n ARGUMENT LIST 1\n");

print(anyString(ident));

(mod_lst,ident1) = argument_lst(arglst2,tf);

139

ident2 = listAppend(ident,ident1);

mod_lst1 = listAppend({exp},mod_lst);

print("\n ARGUMENT LIST 1.1\n");

print(anyString(ident2));

print("\n ARGUMENT LIST 1.2\n");

print(anyString(mod_lst1));

then

(mod_lst1,ident2);

case(arg1::{},tf)

equation

print("\n Argument_lst arg1::{},tf \n");

print(anyString(arg1));

print("\n Argument_lst arg1::{},tf \n");

print(anyString(tf));

(exp,ident1) = argument(arg1,tf);

then

({exp},ident1);

case({},tf)

then ({},{});

end matchcontinue;

end argument_lst;

public function modExp

input Absyn.Exp exp;

output Absyn.Subscript sub;

algorithm

sub := matchcontinue(exp)

local

Absyn.Exp exp1;

case(Absyn.REAL(0.000))

equation

print("\n modeExp 333 \n");

then Absyn.NOSUB();

case(exp1)

equation

print("\n modeExp 123 \n");

print(anyString(exp1));

then Absyn.SUBSCRIPT(exp1);

end matchcontinue;

end modExp;

public function modExpLst

input list<Absyn.Exp> exp_lst;

output list<Absyn.Subscript> sub_lst;

algorithm

sub_lst := matchcontinue(exp_lst)

local

list<Absyn.Exp> exp_lst1;

list<Absyn.Subscript> sub_lst1, sub_lst2;

Absyn.Subscript sub;

Absyn.Exp exp;

case(exp::exp_lst1)

equation

sub = modExp(exp);

sub_lst1 = modExpLst(exp_lst1);

sub_lst2 = listAppend({sub},sub_lst1);

then

140

sub_lst2;

case({})

then ({});

end matchcontinue;

end modExpLst;

public function array_lst

input list<AbsynMat.Argument> arg;

output list<Absyn.Subscript> mod_exp;

algorithm

mod_exp := matchcontinue(arg)

local

list<AbsynMat.Argument> arglst;

Absyn.Exp exp;

list<Absyn.Exp> mod_lst, mod_lst1;

list<Absyn.Subscript> sub_lst;

AbsynMat.Argument arg1;

Absyn.Subscript sub;

case(arg1::arglst)

equation

print("\n Argument_lst arg1::arglst \n");

print(anyString(arg1));

print("\n Argument_lst arg1::arglst 2\n");

print(anyString(arg));

exp = argument(arg1,false);

mod_lst = argument_lst(arglst,false);

mod_lst1 = listAppend({exp},mod_lst);

sub_lst = modExpLst(mod_lst1);

then

sub_lst;

case(arg1::{})

equation

print("\n Argument_lst arg1::{} \n");

print(anyString(arg1));

exp = argument(arg1,false);

sub = Absyn.SUBSCRIPT(exp);

then

{sub};

case({})

then {Absyn.NOSUB()};

end matchcontinue;

end array_lst;

public function sclr_ary

input String ary;

input list<Absyn.AlgorithmItem> alg_exp;

output Boolean tf;

output list<Absyn.AlgorithmItem> alg_exp_o;

algorithm

(tf,alg_exp_o) := matchcontinue(ary,alg_exp)

local

list<Absyn.AlgorithmItem> alg_exp1;

String ary1;

case("matrix",alg_exp1)

then (true,{});

case("vector",alg_exp1)

then (true,{});

141

case("Integer",alg_exp1)

then (false,alg_exp1);

case("Real",alg_exp1)

then (false,alg_exp1);

case(ary1,alg_exp1)

then (false,alg_exp1);

end matchcontinue;

end sclr_ary;

public function sclr_ary_lst

input list<String> i_type;

input list<String> i_type2;

input list<Absyn.AlgorithmItem> alg_exp;

output Boolean tf;

output list<Absyn.AlgorithmItem> alg_exp2;

output list<String> o_type;

algorithm

(tf,alg_exp2,o_type) := matchcontinue (i_type,i_type2,alg_exp)

local

list<String> type_lst,type_lst2;

String d_type;

Boolean tf1;

list<Absyn.AlgorithmItem> alg_exp1;

case(d_type::type_lst,type_lst2,alg_exp1)

equation

print("\n sclr_ary_lst d_type \n");

print(anyString(d_type));

print("\n sclr_ary_lst d_type 2\n");

print(anyString(alg_exp1));

(tf1,alg_exp2) = sclr_ary(d_type,alg_exp1);

then (tf1,alg_exp2,type_lst2);

case({},{},alg_exp1)

then (false,alg_exp1,{});

end matchcontinue;

end sclr_ary_lst;

public function ary_decl

input Absyn.Exp mod_exp;

output list<Absyn.Subscript> sub_lst;

algorithm

sub_lst := matchcontinue(mod_exp)

local

list<Absyn.Subscript> sub_lst1;

list<Absyn.Exp> exp_lst;

case(Absyn.ARRAY(exp_lst))

equation

sub_lst1 = modExpLst(exp_lst);

then sub_lst1;

end matchcontinue;

end ary_decl;

public function modification

input AbsynMat.Expression exp;

output String ary_ident;

output Absyn.Modification modfic;

output list<String> mtx_vec;

142

algorithm

(ary_ident,modfic,mtx_vec) := matchcontinue(exp)

local

AbsynMat.Expression exp1;

list<Absyn.Exp> exp_lst;

Absyn.Exp mod_exp;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op;

list<Absyn.Subscript> sub_lst1;

String ary_ident1;

list<String> mtx_vec1;

Absyn.Modification modfic1;

Absyn.Info info;

case(AbsynMat.ASSIGN_OP(arg1,op,exp1))

equation

(exp_lst,{ary_ident1}) = argument_lst(arg1,false);

print("\n Array Dim modification \n");

print(anyString(ary_ident1));

(mod_exp,mtx_vec1) = expression(exp1,"empty"::{},{});

print("\n modification 2222\n");

print(anyString(mod_exp));

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

modfic1 = Absyn.CLASSMOD({},Absyn.EQMOD(mod_exp,info));

print("\n Expression ArrayDim \n");

print(anyString(mtx_vec1));

then

(ary_ident1,modfic1,mtx_vec1);

end matchcontinue;

end modification;

public function arrayDim

input AbsynMat.Expression exp;

output String ary_ident;

output list<Absyn.Subscript> sub_lst;

algorithm

(ary_ident,sub_lst) := matchcontinue(exp)

local

AbsynMat.Expression exp1;

list<Absyn.Exp> exp_lst;

Absyn.Exp mod_exp;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op;

list<Absyn.Subscript> sub_lst1;

String ary_ident1;

list<String> emt_str;

case(AbsynMat.ASSIGN_OP(arg1,op,exp1))

equation

(exp_lst,{ary_ident1}) = argument_lst(arg1,false);

print("\n Array Dim \n");

print(anyString(exp1));

// sub_lst1 = array_lst(arg1); ??

(mod_exp,emt_str) = expression(exp1,"empty"::{},{});

sub_lst1 = ary_decl(mod_exp);

print("\n Expression ArrayDim \n");

143

print(anyString(sub_lst1));

then

(ary_ident1,sub_lst1);

end matchcontinue;

end arrayDim;

public function rmv_non_protected

input list<String> in1;

input list<String> in2;

output list<String> out1;

algorithm

out1 := matchcontinue(in1,in2)

local

list<String> in_lst;

list<String> in_lst2;

list<String> types;

case(in_lst,{})

then {};

case(in_lst,in_lst2)

equation

types = listAppend(in_lst,in_lst2);

then types;

end matchcontinue;

end rmv_non_protected;

public function anon_fcn_handle

input list<AbsynMat.Argument> arg;

input AbsynMat.Expression exp;

output Boolean tf;

algorithm

(tf) := matchcontinue(arg,exp)

local

AbsynMat.Expression exp1;

list<AbsynMat.Parameter> prm_lst;

list<AbsynMat.Argument> arg1;

AbsynMat.Statement stmt;

Absyn.Exp out;

list<Absyn.Exp> arg_exp;

list<String> ident, ident1, fname, all;

case(arg1, AbsynMat.ANON_FCN_HANDLE(prm_lst,stmt))

equation

(arg_exp,fname) = argument_lst(arg1,false);

(out,ident) = fnc_hdl_stmt(stmt);

ident1 = Fnc_Handle.rmvKeywords_lst(ident);

all = listAppend(fname,ident1);

then (true);

case(arg1,exp1)

then (false);

end matchcontinue;

end anon_fcn_handle;

public function anon_fcn_handle_ept

input Boolean fnc_hdl_tf;

input list<Absyn.AlgorithmItem> alg_exp2;

input list<String> arg_ident;

input Boolean tf;

input list<String> types;

144

input list<String> fnc_hdl_ident;

output list<Absyn.AlgorithmItem> alg_exp2_o;

output list<String> arg_ident_o;

output Boolean tf_o;

output list<String> types_o;

output list<String> fnc_hdl_ident_o;

algorithm

(alg_exp2_o,arg_ident_o,tf_o,types_o,fnc_hdl_ident_o) :=

matchcontinue(fnc_hdl_tf,alg_exp2,arg_ident,tf,types,fnc_hdl_ident)

local

list<Absyn.AlgorithmItem> alg_exp3;

list<String> arg_ident1;

Boolean tf1;

list<String> types1, fnc_hdl_ident1;

case(true,alg_exp3,arg_ident1,tf1,types1,fnc_hdl_ident1) //if true send

send only fnc hdl idents to stmt

then ({},{},false,{},fnc_hdl_ident1);

case(false,alg_exp3,arg_ident1,tf1,types1,fnc_hdl_ident1)

then (alg_exp3,arg_ident1,tf1,types1,{});

end matchcontinue;

end anon_fcn_handle_ept;

public function lhs_ident

input String ident;

output list<String> otype;

algorithm

otype := matchcontinue(ident)

local

list<String> unkn;

String ident1;

case("Real")

then({"Real"});

case("Integer")

then({"Integer"});

case("UPLUS")

then({"UPLUS"});

case("UMINUS")

then({"UMINUS"});

case("ADD")

then({"ADD"});

case("SUB")

then({"SUB"});

case("MUL")

then({"MUL"});

case("DIV")

then({"DIV"});

case("POW")

then({"POW"});

case("EXPR_LT")

then({"EXPR_LT"});

case("EXPR_LE")

then({"EXPR_LE"});

case("EXPR_EQ")

then({"EXPR_EQ"});

case("EXPR_GE")

then({"EXPR_GE"});

case("EXPR_GT")

145

then({"EXPR_GT"});

case("EXPR_NE")

then({"EXPR_NE"});

case("EMUL")

then({"EMUL"});

case("EDIV")

then({"EDIV"});

case("EPOW")

then({"EPOW"});

case("EXPR_AND")

then({"EXPR_AND"});

case("EXPR_OR")

then({"EXPR_OR"});

case("EXPR_AND_AND")

then({"EXPR_AND_AND"});

case("EXPR_OR_OR")

then({"EXPR_OR_OR"});

case("EXPR_NOT")

then({"EXPR_NOT"});

case(ident1)

equation

unkn = listAppend({ident1},{"Unknown"});

then(unkn);

end matchcontinue;

end lhs_ident;

public function lhs_ident_lst

input list<String> ident_lst;

output list<String> otype;

algorithm

otype := matchcontinue(ident_lst)

local

list<String> i_lst, ident_lst1, ident_lst2, ident_lst3;

String ident;

case(ident::ident_lst1)

equation

print("\n lhs_ident_lst \n");

print(anyString(ident));

i_lst = lhs_ident(ident);

ident_lst2 = lhs_ident_lst(ident_lst1);

ident_lst3 = listAppend(i_lst,ident_lst2);

then ident_lst3;

case({})

then {};

end matchcontinue;

end lhs_ident_lst;

public function assign_types_lst

input list<String> types;

input Boolean chk;

output list<String> otypes;

algorithm

otypes := matchcontinue(types,chk)

local

list<String> types1, idtypes, idtypes1, idtypes2;

String stype, stype1;

case(stype::types1,false)

146

equation

print("\n assign_types_lst \n");

idtypes1 = listAppend({stype},{"Unknown"});

idtypes = lhs_ident_lst(types1);

idtypes2 = listAppend(idtypes1,idtypes);

then idtypes2;

case(stype::types1,true)

equation

idtypes1 = listAppend({stype},{"Unknown"});

idtypes2 = listAppend(idtypes1,types1);

then idtypes2;

case({},false)

then {};

end matchcontinue;

end assign_types_lst;

public function rhs_real

input Boolean rl;

input Boolean int;

output String otype;

algorithm

otype := matchcontinue(rl,int)

local

case(true,true)

then ("Real");

case(true,false)

then ("Real");

case(false,true)

then ("Integer");

case(false,false)

then ("Unknown");

end matchcontinue;

end rhs_real;

public function ident_typelst

input list<String> idtypes;

output list<String> odtypes;

algorithm

odtypes := matchcontinue(idtypes)

local

list<String> idtypes1,idtypes2;

String idtype,idtype2, dim;

Boolean rl,int,vec,mtx,cvec;

case(idtype::idtypes1)

equation

// print("\n ident_typelst \n");

// print(anyString(idtypes1));

rl = listMember("Real",idtypes1);

// print("\n ident_typelst real \n");

// print(anyString(rl));

int = listMember("Integer",idtypes1);

// print("\n ident_typelst int \n");

// print(anyString(int));

idtype2 = rhs_real(rl,int);

147

idtypes2 = listAppend({idtype},{idtype2});

then idtypes2;

case({})

then {};

end matchcontinue;

end ident_typelst;

public function chk_bol

input Boolean b1;

input Boolean b2;

input Boolean b3;

output Boolean bout;

algorithm

bout := matchcontinue(b1,b2,b3)

case(true,false,false)

then true;

case(false,true,false)

then true;

case(false,false,true)

then true;

case(false,false,false)

then false;

end matchcontinue;

end chk_bol;

public function chk_ary_scl

input list<String> types;

output Boolean chk;

algorithm

chk := matchcontinue(types)

local

list<String> lst;

Boolean b1,b2,b3,b4;

case(lst)

equation

b1 = listMember("vector",lst);

b2 = listMember("matrix",lst);

b3 = listMember("column_vector",lst);

b4 = chk_bol(b1,b2,b3);

then b4;

end matchcontinue;

end chk_ary_scl;

public function assign_operator

input Option<AbsynMat.Expression> exp;

input list<String> f_call;

input list<String> fnc_hdl_ident_i;

input list<String> io_lstun;

output list<Absyn.AlgorithmItem> alg;

output list<String> agn_ident;

output Boolean ary_true;

output list<String> d_type_lst;

output list<String> fnc_hdl_ident_o; //list of fnc hdl idents

algorithm

(alg,agn_ident,ary_true,d_type_lst,fnc_hdl_ident_o) :=

matchcontinue(exp,f_call,fnc_hdl_ident_i,io_lstun)

local

148

AbsynMat.Expression exp1, exp2, mat_exp;

list<AbsynMat.Argument> arg1, arg2;

Absyn.Exp exp3, exp4;

Absyn.Algorithm alg3;

AbsynMat.Operator op;

list<Absyn.AlgorithmItem> alg_exp, alg_exp2, alg_exp3;

Absyn.Info info;

Option<AbsynMat.Expression> exp5;

list<String> idtypes, arg_ident, arg_ident1, var_lst1, f_call1, ary1,

d_type, types, types1, fnc_hdl_ident;

list<String> io_lstun1, fnc_hdl_ident1, fnc_hdl_ident2, itypes;

Boolean tf, fnc_hdl_tf, tf1, chk;

list<Absyn.Subscript> mod_exp;

String mod_fname, mat_fname;

case(SOME(AbsynMat.ASSIGN_OP(arg1,op,exp1)),f_call1,fnc_hdl_ident1,io_lstun1)

equation

print("\n TTTTTTTTTTTTT Assign Operator TTTTTTTTTTTTT \n");

print(anyString(f_call1));

print("\n Assign Operator exp1 \n");

print(anyString(exp1));

(fnc_hdl_tf) = anon_fcn_handle(arg1,exp1); // confirm whether matlab

expression is anonymous function or not

({exp3},arg_ident) = argument_lst(arg1,false);

print("\n Assign Arg 1 \n");

print(anyString(exp3));

print("\n Assign Arg 2 \n");

print(anyString(arg_ident));

(exp4,ary1) = expression(exp1,f_call1,fnc_hdl_ident1);

print("\n Assign Exp 1 \n");

print(anyString(arg_ident));

print("\n Assign Exp 2 \n");

print(anyString(ary1));

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

alg_exp =

Absyn.ALGORITHMITEM(Absyn.ALG_ASSIGN(exp3,exp4),NONE(),info)::{};

print("\n Modelica Output \n");

print(anyString(ary1));

print("\n Modelica Output 2 \n");

print(anyString(alg_exp));

(tf,alg_exp2,d_type) = sclr_ary_lst(ary1,ary1,alg_exp); //tf = true

if variable is Array else false

types = rmv_non_protected(arg_ident,ary1); // remove all non

protected variables.

print("\n Test 999 \n");

print(anyString(types));

chk = chk_ary_scl(types);

idtypes = assign_types_lst(types,chk);

itypes = ident_typelst(idtypes);

print("\n Test 000 \n");

print(anyString(itypes));

print("\n Test 111 \n");

print(anyString(idtypes));

print("\n Test 222 \n");

print(anyString(types));

149

print("\n Test 333 \n");

print(anyString(d_type));

(alg_exp3,arg_ident1,tf1,types1,fnc_hdl_ident2) =

anon_fcn_handle_ept(fnc_hdl_tf,alg_exp2,arg_ident,tf,idtypes,fnc_hdl_ident1);

then

(alg_exp3,arg_ident1,tf1,types1,fnc_hdl_ident2);

case(SOME(AbsynMat.FINISH_COLON_EXP(AbsynMat.INDEX_EXPRESSION(AbsynMat.IDENTI

FIER(mat_fname),arg1)::{})),f_call1,fnc_hdl_ident1,io_lstun1)

equation

print("\n Mod_Builin \n");

print(anyString(mat_fname));

mod_fname = Mod_Builtin.builtIn(mat_fname);

({exp3},arg_ident) = argument_lst(arg1,false);

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

alg_exp =

Absyn.ALGORITHMITEM(Absyn.ALG_NORETCALL(Absyn.CREF_IDENT(mod_fname,{}),Absyn.

FUNCTIONARGS(exp3::{},{})),NONE(),info)::{};

then (alg_exp,arg_ident,false,{},{});

case(NONE(),f_call1,fnc_hdl_ident1,io_lstun1)

then ({},{},false,{},{});

end matchcontinue;

end assign_operator;

public function trs_else_if

input AbsynMat.Elseif els_if;

input list<String> f_call;

output list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_if;

output list<String> idents_rhs0;

algorithm

(mod_else_if,idents_rhs0) := matchcontinue(els_if,f_call)

local

AbsynMat.Separator sep, sep2;

AbsynMat.Expression exp;

Absyn.Exp mod_exp;

list<AbsynMat.Statement> stmtlst;

Option<AbsynMat.Mat_Comment> cmt;

list<Absyn.AlgorithmItem> mod_stmt;

list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_if1;

list<String> f_call1, idents_rhs;

case(AbsynMat.ELSEIF_CLAUSE (sep,exp,sep2,stmtlst,cmt),f_call1)

equation

print("\n Else_If AbsynMat.ELSEIF_CLAUSE

(sep,exp,sep2,stmtlst,cmt)");

mod_exp = expression(exp,f_call1,{});

(mod_stmt,{},{},{},idents_rhs,{}) = stmt_lst(stmtlst,f_call1,{},{});

mod_else_if1 = (mod_exp,mod_stmt)::{};

then

(mod_else_if1,idents_rhs);

end matchcontinue;

end trs_else_if;

150

public function trs_else_ifs

input list<AbsynMat.Elseif> els_if;

input list<String> f_call;

output list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_if;

output list<String> ident_rhs0;

algorithm

(mod_else_if,ident_rhs0) := matchcontinue(els_if,f_call)

local

list<AbsynMat.Elseif> else_ifs;

AbsynMat.Elseif else_if;

list<Absyn.Exp> exp, exp2, exp3, exp4, exp_if1, exp_ifs, exp_if2;

list<Absyn.AlgorithmItem> alg_itm1, alg_itms, alg_itm2;

list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_if1,

mod_else_if2, mod_else_if3;

list<String> f_call1,ident_rhs,ident_rhs1,ident_rhs2;

case(else_if::else_ifs,f_call1)

equation

print("\n else_if::else_ifs");

(mod_else_if1,ident_rhs) = trs_else_if(else_if,f_call1);

(mod_else_if2,ident_rhs1) = trs_else_ifs(else_ifs,f_call1);

ident_rhs2 = listAppend(ident_rhs,ident_rhs1);

mod_else_if3 = listAppend(mod_else_if1,mod_else_if2);

then

(mod_else_if3,ident_rhs2);

case({},f_call1)

then ({},{});

end matchcontinue;

end trs_else_ifs;

public function iterator

input String mod_exp;

input list<AbsynMat.Expression> mod_exp1;

output list<Absyn.ForIterator> foriterator;

algorithm

foriterator := matchcontinue(mod_exp, mod_exp1)

local

String mod_ident;

list<String> f_call, arg_str;

Option<Absyn.Exp> mod_exp3;

Absyn.Exp mod_exp4;

list<AbsynMat.Expression> mat_exp;

list<Absyn.ForIterator> foriterator1, foriterator2;

list<AbsynMat.Argument> arg_lst;

list<Absyn.Exp> mod_lst;

case(mod_ident,AbsynMat.FINISH_COLON_EXP(AbsynMat.FINISH_MATRIX(AbsynMat.MATR

IX(arg_lst)::{})::{})::{}) //transform for s = [1,2,3] to for s in {1,2,3}

equation

(mod_lst,arg_str) = argument_lst(arg_lst,false);

mod_exp4 = Absyn.ARRAY(mod_lst);

print("\n Heading for loop \n");

foriterator1 = Absyn.ITERATOR(mod_ident,NONE(),SOME(mod_exp4))::{};

then foriterator1;

case(mod_ident,{})

equation

151

print("\n mod_ident,{}");

foriterator2 = Absyn.ITERATOR(mod_ident,NONE(),NONE())::{};

then

foriterator2;

case(mod_ident,mat_exp)

equation

print("\n iterator mod_ident,mat_exp \n");

print(anyString(mat_exp));

(mod_exp3,f_call) = expression_lst(mat_exp,{},{});

print("\n iterator mod_ident,mat_exp 1\n");

print(anyString(mod_exp3));

foriterator1 = Absyn.ITERATOR(mod_ident,NONE(),mod_exp3)::{};

then

foriterator1;

end matchcontinue;

end iterator;

public function swt_else_if

input Absyn.Exp mod_exp1;

input Absyn.Exp mod_exp2;

input Absyn.AlgorithmItem swt_stmt;

output list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_ifs;

algorithm

mod_else_ifs := matchcontinue(mod_exp1,mod_exp2,swt_stmt)

local

Absyn.Exp mod_exp11, mod_exp22, mod_els_if;

Absyn.AlgorithmItem swt_stmt1;

list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_ifs2;

case(mod_exp11,mod_exp22,swt_stmt1)

equation

print("\n SWITCH STMT 1 \n");

print(anyString(mod_exp1));

mod_els_if = Absyn.BINARY(mod_exp11,Absyn.EQUAL(),mod_exp22);

mod_else_ifs2 = (mod_els_if,{swt_stmt1})::{};

print("\n SWITCH STMT 2 \n");

print(anyString(mod_else_ifs2));

then

mod_else_ifs2;

end matchcontinue;

end swt_else_if;

public function swt_else_ifs

input Absyn.Exp mod_exp;

input list<Absyn.Exp> swt_exp_lst;

input list<Absyn.AlgorithmItem> swt_stmt_lst;

output list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_ifs;

output list<Absyn.AlgorithmItem> else_stmt;

algorithm

(mod_else_ifs,else_stmt) := matchcontinue (mod_exp,swt_exp_lst,swt_stmt_lst)

local

Absyn.Exp mod_exp1,mod_exp2;

list<Absyn.Exp> mod_exp_lst1;

Absyn.AlgorithmItem swt_stmt;

list<Absyn.AlgorithmItem> swt_stmt_lst1, swt_stmt_lst2;

list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_ifs2,

mod_else_ifs3, mod_else_ifs4;

152

list<String> a,b;

case(mod_exp1,mod_exp2::mod_exp_lst1,swt_stmt::swt_stmt_lst1)

equation

print("\n SWITCH STMT Ifs \n");

print(anyString(mod_exp1));

mod_else_ifs2 = swt_else_if(mod_exp1,mod_exp2,swt_stmt);

print("\n SWITCH STMT Ifs 2 \n");

print(anyString(mod_exp_lst1));

print("\n SWITCH STMT Ifs 3 \n");

print(anyString(swt_stmt_lst1));

(mod_else_ifs3,swt_stmt_lst2) =

swt_else_ifs(mod_exp1,mod_exp_lst1,swt_stmt_lst1);

print("\n SWITCH STMT Ifs 4 \n");

print(anyString(mod_else_ifs3));

mod_else_ifs4 = listAppend(mod_else_ifs2,mod_else_ifs3);

then (mod_else_ifs4,swt_stmt_lst2);

case(mod_exp1,{},swt_stmt_lst1)

equation

print("\n Else Stmt 4 \n");

print(anyString(swt_stmt_lst1));

then ({},swt_stmt_lst1);

case(mod_exp1,{},{})

then ({},{});

end matchcontinue;

end swt_else_ifs;

public function switch

input AbsynMat.Switch_Case swt;

output list<Absyn.Exp> exp_lst;

output list<Absyn.AlgorithmItem> mod_lst;

output list<String> idents_rhs;

algorithm

(exp_lst,mod_lst,idents_rhs) := matchcontinue(swt)

local

AbsynMat.Separator sep;

AbsynMat.Expression exp;

AbsynMat.Separator sep2;

list<AbsynMat.Statement> stmt_list;

Option<AbsynMat.Mat_Comment> m_cmt;

list<Absyn.AlgorithmItem> mod_if_stmt;

Absyn.Exp mod_if_exp;

list<String> idents_rhs1;

case(AbsynMat.SWITCH_CASE(sep,exp,sep2,stmt_list,m_cmt))

equation

print("\n SWTICH ELSE TEST \n");

print(anyString(stmt_list));

mod_if_exp = expression(exp,{},{});

(mod_if_stmt,{},{},{},idents_rhs1,{}) = stmt_lst(stmt_list,{},{},{});

then ({mod_if_exp},mod_if_stmt,idents_rhs1);

case(AbsynMat.DEFAULT_CASE(sep,stmt_list,m_cmt))

equation

(mod_if_stmt,{},{},{},idents_rhs1,{}) = stmt_lst(stmt_list,{},{},{});

then ({},mod_if_stmt,idents_rhs1);

end matchcontinue;

end switch;

public function switch_lst

153

input list<AbsynMat.Switch_Case> swt_lst;

output list<Absyn.Exp> exp;

output list<Absyn.AlgorithmItem> mod_lst;

output list<String> idents_rhs;

algorithm

(exp,mod_lst,idents_rhs) := matchcontinue(swt_lst)

local

list<AbsynMat.Switch_Case> swt_lst1;

list<Absyn.Exp> exp_lst,exp_lst2,exp_lst3;

list<Absyn.AlgorithmItem> mod_lst2,mod_lst3,mod_lst4;

list<String> idents_rhs1, idents_rhs2, idents_rhs3;

AbsynMat.Switch_Case swt;

case(swt::swt_lst1)

equation

(exp_lst,mod_lst2,idents_rhs1) = switch(swt);

(exp_lst2,mod_lst3,idents_rhs2) = switch_lst(swt_lst1);

exp_lst3 = listAppend(exp_lst,exp_lst2);

mod_lst4 = listAppend(mod_lst2,mod_lst3);

idents_rhs3 = listAppend(idents_rhs1,idents_rhs2);

then (exp_lst3, mod_lst4,idents_rhs3);

case({})

then ({},{},{});

end matchcontinue;

end switch_lst;

public function switch_tpl

input tuple<list<AbsynMat.Switch_Case>, Option<AbsynMat.Switch_Case>>

swcse_lst;

output list<Absyn.Exp> exp;

output list<Absyn.AlgorithmItem> mod_lst;

output list<String> idents_rhs;

algorithm

(exp,mod_lst,idents_rhs) := matchcontinue(swcse_lst)

local

list<AbsynMat.Switch_Case> swt_lst;

AbsynMat.Switch_Case swt_op;

list<Absyn.Exp> exp1,exp2,exp3;

list<Absyn.AlgorithmItem> mod_lst1,mod_lst2,mod_lst3;

list<String> idents_rhs1, idents_rhs2, idents_rhs3;

tuple<list<AbsynMat.Switch_Case>, Option<AbsynMat.Switch_Case>>

swcse_lst1;

case(swcse_lst1)

equation

(swt_lst,SOME(swt_op)) = swcse_lst1;

(exp1,mod_lst1,idents_rhs1) = switch_lst(swt_lst);

(exp2,mod_lst2,idents_rhs2) = switch(swt_op);

idents_rhs3 = listAppend(idents_rhs1, idents_rhs2);

exp3 = listAppend(exp1,exp2);

mod_lst3 = listAppend(mod_lst1,mod_lst2);

then (exp3,mod_lst3,idents_rhs3);

end matchcontinue;

end switch_tpl;

public function command

input Option<AbsynMat.Command> cmd;

input list<String> f_call;

input list<String> fnc_hdl_ident;

154

output list<Absyn.AlgorithmItem> alg;

output list<String> for_ident;

output list<String> asg_ident;

output list<String> idents_rhs0;

algorithm

(alg,for_ident,asg_ident,idents_rhs0) :=

matchcontinue(cmd,f_call,fnc_hdl_ident)

local

list<AbsynMat.Argument> arg;

AbsynMat.Expression exp1, w_exp, if_ex, swt_ex;

Option<AbsynMat.Separator> sep, w_sep, if_sep2;

AbsynMat.Separator if_sep, swt_sep;

list<AbsynMat.Elseif> else_ifs;

list<AbsynMat.Statement> mat_stmt, w_stmt, if_stmt, if_stmt2,

mat_stmt_out;

Option<AbsynMat.Mat_Comment> m_cmt_lst, w_cmt_lst, if_cmt_lst,

if_cmt_lst2;

Absyn.Algorithm mod_while;

list<Absyn.AlgorithmItem> mod_alg, mod_stmt, mod_w_stmt, mod_w_stmt1,

mod_if_stmt, mod_if_stmt2, swt_stmt_lst, swt_stmt_lst2, mod_else;

Absyn.Exp mod_exp1,mod_w_exp, mod_if_exp, mod_exp2, swt_exp;

Absyn.AlgorithmItem swt_stmt;

list<Absyn.Exp> swt_exp_lst, swt_exp_lst2;

String in_ident;

Absyn.Info info;

list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_if;

list<Absyn.ForIterator> foriterator;

list<String> for_ident1, for_ident2, asg_ident1, f_call1, fnc_hdl_ident1;

tuple<list<AbsynMat.Switch_Case>, Option<AbsynMat.Switch_Case>>

swcse_lst;

list<tuple<Absyn.Exp,list<Absyn.AlgorithmItem>>> mod_else_ifs;

list<AbsynMat.Expression> exp_lst1, no_exp;

list<String> idents_rhs, idents_rhs1, idents_rhs2, idents_rhs3,

idents_rhs4, no_str, no_str1, no_for;

Boolean bool_loop;

case(SOME(AbsynMat.FOR_COMMAND(arg,exp1,sep,mat_stmt,m_cmt_lst)),f_call1,fnc_

hdl_ident1)

equation

print("\n Command

AbsynMat.FOR_COMMAND(arg,exp1,sep,mat_stmt,m_cmt_lst) \n");

in_ident = for_ident(arg,NONE());

print("\n in_ident \n");

print(anyString(mat_stmt));

// (exp_lst1,mat_stmt_out,bool_loop) =

Fnc_Handle.stmt_lst(mat_stmt,SOME(in_ident),false);

print("\n FOR LOOP \n");

print(anyString(mat_stmt));

print("\n FOR LOOP 2 \n");

// print(anyString(mat_stmt_out));

(mod_stmt,for_ident2,asg_ident1,no_exp,idents_rhs,no_str) =

stmt_lst(mat_stmt,f_call1,fnc_hdl_ident1,{});

print("\n FOR LOOP 3 \n");

print(anyString(idents_rhs));

foriterator = iterator(in_ident,{exp1});

155

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_FOR(foriterator,mod_stmt),NONE(),info)::{};

for_ident1 = listAppend(for_ident2,{in_ident});

print("\n End FOR 2 \n");

then

(mod_alg, for_ident1,asg_ident1,idents_rhs);

case(SOME(AbsynMat.WHILE_COMMAND(w_exp,w_sep,w_stmt,w_cmt_lst)),f_call1,fnc_h

dl_ident1)

equation

mod_w_exp = expression(w_exp,f_call1,fnc_hdl_ident1);

print("\n Command

AbsynMat.WHILE_COMMAND(w_exp,w_sep,w_stmt,w_cmt_lst) \n");

//print(anyString(w_stmt));

(mod_w_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(w_stmt,f_call1,fnc_hdl_ident1,{});

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_WHILE(mod_w_exp,mod_w_stmt),NONE(),info)::{};

then

(mod_alg, {}, {},idents_rhs);

case(SOME(AbsynMat.IF_COMMAND

(if_ex,if_sep,if_stmt,{},NONE(),{},if_cmt_lst, NONE())),f_call1,

fnc_hdl_ident1)

equation

print("\n command AbsynMat.IF_COMMAND

(if_ex,if_sep,if_stmt,{},NONE(),{},if_cmt_lst, NONE()) \n");

mod_if_exp = expression(if_ex,f_call1,fnc_hdl_ident1);

print("\n IF COMMAND 1\n");

print(anyString(mod_if_exp));

(mod_if_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(if_stmt,f_call1,fnc_hdl_ident1,{});

print("\n IF COMMAND IF Stmt\n");

print(anyString(mod_if_stmt));

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,mod_if_stmt,{},{}),NONE(),info)::

{};

print("\n IF COMMAND END 1 \n");

then

(mod_alg, {},{},idents_rhs);

case(SOME(AbsynMat.IF_COMMAND (if_ex,if_sep,if_stmt,{},if_sep2,if_stmt2

,if_cmt_lst,if_cmt_lst2)),f_call1,fnc_hdl_ident1)

equation

print("\n command AbsynMat.IF_COMMAND

(if_ex,if_sep,if_stmt,{},if_sep2,if_stmt2 ,if_cmt_lst,if_cmt_lst2) \n");

print("\n IF COMMAND 21 \n");

print(anyString(if_sep2));

mod_if_exp = expression(if_ex,f_call1,fnc_hdl_ident1);

print("\n IF COMMAND 2 \n");

156

print(anyString(mod_if_exp));

(mod_if_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(if_stmt,f_call1,fnc_hdl_ident1,{});

(mod_if_stmt2,no_for,no_str,no_exp,idents_rhs2,no_str1) =

stmt_lst(if_stmt2,f_call1,fnc_hdl_ident1,{});

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,mod_if_stmt,{},mod_if_stmt2),NONE

(),info)::{};

idents_rhs3 = listAppend(idents_rhs,idents_rhs2);

print("\n IF COMMAND END 2\n");

then

(mod_alg, {},{},idents_rhs3);

case(SOME(AbsynMat.IF_COMMAND

(if_ex,if_sep,if_stmt,else_ifs,if_sep2,if_stmt2,if_cmt_lst,if_cmt_lst2)),f_ca

ll1,fnc_hdl_ident1)

equation

print("\n command AbsynMat.IF_COMMAND

(if_ex,if_sep,if_stmt,else_ifs,if_sep2,if_stmt2,if_cmt_lst,if_cmt_lst2) \n");

print("\n IF COMMAND 3 \n");

mod_if_exp = expression(if_ex,f_call1,fnc_hdl_ident1);

(mod_if_stmt,no_for,no_str,no_exp,idents_rhs,no_str1) =

stmt_lst(if_stmt,f_call1,fnc_hdl_ident1,{});

(mod_else_if,idents_rhs1) = trs_else_ifs(else_ifs,f_call1);

idents_rhs2 = listAppend(idents_rhs,idents_rhs1);

(mod_if_stmt2,no_for,no_str,no_exp,idents_rhs3,no_str1) =

stmt_lst(if_stmt2,f_call1,fnc_hdl_ident1,{});

idents_rhs4 = listAppend(idents_rhs3,idents_rhs2);

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,mod_if_stmt,mod_else_if,mod_if_st

mt2),NONE(),info)::{};

then

(mod_alg,{},{},idents_rhs4);

case(SOME(AbsynMat.SWITCH_COMMAND(swt_ex,swt_sep,swcse_lst,if_cmt_lst)),f_cal

l1,fnc_hdl_ident1)

equation

print("\n SWITCH COMMAND \n");

print(anyString(swt_ex));

mod_exp1 = expression(swt_ex,f_call1,fnc_hdl_ident1);

(swt_exp_lst,swt_stmt_lst,idents_rhs1) = switch_tpl(swcse_lst);

print("\n SWITCH STATEMENT \n");

print(anyString(swt_exp_lst));

print("\n SWITCH STATEMENT 2 \n");

print(anyString(swt_stmt_lst));

swt_exp::swt_exp_lst2 = swt_exp_lst;

swt_stmt::swt_stmt_lst2 = swt_stmt_lst;

mod_if_exp = Absyn.BINARY(mod_exp1,Absyn.EQUAL(),swt_exp);

print("\n SWITCH STATEMENT 3 \n");

print(anyString(mod_if_exp));

(mod_else_ifs,mod_else) =

swt_else_ifs(mod_exp1,swt_exp_lst2,swt_stmt_lst2);

157

print("\n SWITCH STATEMENT 4 \n");

print(anyString(mod_else));

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg =

Absyn.ALGORITHMITEM(Absyn.ALG_IF(mod_if_exp,{swt_stmt},mod_else_ifs,mod_else)

,NONE(),info)::{};

then

(mod_alg,{},{},{});

case(SOME(AbsynMat.BREAK_COMMAND()),f_call1,fnc_hdl_ident1)

equation

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg = Absyn.ALGORITHMITEM(Absyn.ALG_BREAK(),NONE(),info)::{};

then

(mod_alg,{},{},{});

case(SOME(AbsynMat.RETURN_COMMAND()),f_call1,fnc_hdl_ident1)

equation

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

mod_alg = Absyn.ALGORITHMITEM(Absyn.ALG_RETURN(),NONE(),info)::{};

then

(mod_alg, {},{},{});

case(NONE(),f_call1,fnc_hdl_ident1)

then ({},{},{},{});

end matchcontinue;

end command;

public function mtx_vtr

input Boolean tf;

input Option<AbsynMat.Expression> exp;

input list<String> ident;

output list<AbsynMat.Expression> exp_out;

output list<String> ident1;

algorithm

(exp_out,ident1) := matchcontinue(tf,exp,ident)

local

Option<AbsynMat.Expression> exp1;

AbsynMat.Expression exp2;

list<AbsynMat.Expression> exp_lst;

list<String> ident2;

case(true,exp1,ident2)

equation

SOME(exp2) = exp1;

exp_lst = {exp2};

then (exp_lst,{});

case(false,exp1,ident2)

then ({},ident2);

end matchcontinue;

end mtx_vtr;

public function stmt

input AbsynMat.Statement stmt;

input list<String> f_call;

158

input list<String> fnc_hdl;

input list<String> io_lstun;

output list<Absyn.AlgorithmItem> outclasspart;

output list<String> for_ident;

output list<String> asg_ident;

output list<AbsynMat.Expression> exp_lst;

output list<String> d_type_lst;

output list<String> fnc_hdl_idents_o;

algorithm

(outclasspart,for_ident,asg_ident,exp_lst,d_type_lst,fnc_hdl_idents_o) :=

matchcontinue(stmt, f_call,fnc_hdl,io_lstun)

local

Option<AbsynMat.Expression> exp;

list<AbsynMat.Expression> exp1, exp2;

Option<AbsynMat.Command> cmd;

Option<AbsynMat.Start> fnc_str;

Option<AbsynMat.Mat_Comment> m_cmt;

Option<AbsynMat.Separator> sep_op;

AbsynMat.Separator sep;

list<AbsynMat.Statement> stmt_lst;

Absyn.Algorithm asg_exp, mod_cmd;

Absyn.Info info;

list<Absyn.AlgorithmItem> alg_lst, alg_lst1, alg_exp, alg_cmd,

alg_exp9;

Absyn.Exp mod_exp;

list<String> io_lstun1, for_ident1, for_ident2, asg_ident1, asg_ident2,

asg_ident3, asg_ident4, fnc_hdl_idents;

list<String> idents_rhs, idents_rhs1, itypes, var_lst1, f_call1,

f_call2, asg_ident9, asg_ident4, d_type, d_type0, d_type1, d_type2,

fnc_hdl_idents_i;

Boolean ary, fnc_hdl_tf, fnc_hdl_tf1;

case(AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

,f_call1,fnc_hdl_idents_i,io_lstun1)

equation

print("\n stmt

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

\n");

print("\n Matlab Expression \n");

print(anyString(exp));

print("\n Matlab Expression 2\n");

print(anyString(f_call1));

print("\n Matlab Expression 3\n");

print(anyString(fnc_hdl_idents_i));

//(alg_exp9,asg_ident9,fnc_hdl_tf) = assign_operator(exp,f_call1);

//alg_exp9, asg_ident9 extra

//(alg_exp9,asg_ident9,ary,d_type,fnc_hdl_idents) =

assign_operator(exp,f_call1,fnc_hdl_idents_i); //alg_exp9, asg_ident9 extra

(alg_exp,asg_ident1,ary,d_type,fnc_hdl_idents) =

assign_operator(exp,f_call1,fnc_hdl_idents_i,io_lstun1);

print("\n Matlab Expression 4 \n");

print(anyString(d_type));

(exp1,asg_ident4) = mtx_vtr(ary,exp,asg_ident1);

print("\n Matlab Ident \n");

print(anyString(cmd));

(alg_cmd,for_ident1,asg_ident2,d_type0) =

command(cmd,f_call1,fnc_hdl_idents_i);

159

print("\n Matlab Command RHS \n");

print(anyString(d_type0));

d_type1 = listAppend({"nStatement"},d_type0);

d_type2 = listAppend(d_type,d_type1);

alg_lst = listAppend(alg_exp,alg_cmd);

asg_ident3 = listAppend(asg_ident4,asg_ident2);

then

(alg_lst,for_ident1,asg_ident3,exp1,d_type2,fnc_hdl_idents);

end matchcontinue;

end stmt;

public function stmt_lst

input list<AbsynMat.Statement> stmtlst;

input list<String> f_call;

input list<String> fnc_hdl_ident_i;

input list<String> io_lstun;

output list<Absyn.AlgorithmItem> outclasspart;

output list<String> for_ident;

output list<String> asg_ident;

output list<AbsynMat.Expression> exp_lst;

output list<String> d_type_lst;

output list<String> fnc_hdl_ident_o;

algorithm

(outclasspart,for_ident, asg_ident,exp_lst,d_type_lst,fnc_hdl_ident_o) :=

matchcontinue(stmtlst, f_call,fnc_hdl_ident_i,io_lstun)

local

list<AbsynMat.Statement> stmtlst1, stmtlst2;

AbsynMat.Statement stmt1;

list<Absyn.AlgorithmItem> alg_itm, alg_lst, alg_lst2, alg_lst3,

alg_itm, alg_itm2;

list<String> for_ident1, for_ident2, for_ident3, for_ident4,

asg_ident1, asg_ident2, asg_ident3, asg_ident4, var_lst1;

list<String> io_lstun1, f_call1, d_type, d_type0, d_type1, d_type2,

d_type3, fnc_hdl_idents, fnc_hdl_idents1, fnc_hdl_idents2, fnc_hdl;

list<AbsynMat.Expression> exp_lst1,exp_lst2,exp_lst3,exp_lst4;

Boolean fnc_hdl_tf, fnc_hdl_tf1;

case(stmt1::stmtlst1,f_call1,fnc_hdl,io_lstun1)

equation

print("\n stmt_lst

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

\n");

print(anyString(io_lstun1));

(alg_itm,for_ident1,asg_ident1,exp_lst1,d_type,fnc_hdl_idents) =

stmt(stmt1,f_call1,fnc_hdl,io_lstun);

(alg_lst,for_ident2,asg_ident2,exp_lst2,d_type0,fnc_hdl_idents1) =

stmt_lst(stmtlst1,f_call1,fnc_hdl,io_lstun);

for_ident3 = listAppend(for_ident1,for_ident2);

asg_ident3 = listAppend(asg_ident1,asg_ident2);

alg_lst2 = listAppend(alg_itm,alg_lst);

exp_lst3 = listAppend(exp_lst1,exp_lst2);

d_type1 = listAppend({"nStatement"},d_type0);

d_type2 = listAppend(d_type,d_type1);

print("\n IDENTS RHS \n ");

print(anyString(d_type2));

fnc_hdl_idents2 = listAppend(fnc_hdl_idents,fnc_hdl_idents1);

print("\n LIST FNC HDL 1\n ");

print(anyString(alg_lst2));

160

then

(alg_lst2,for_ident3,asg_ident3,exp_lst3,d_type2,fnc_hdl_idents2);

case({},f_call1,fnc_hdl_idents2,io_lstun1)

then ({},{},{},{},{},{});

end matchcontinue;

end stmt_lst;

public function scl_ary_type

input String identtype;

input String typ;

input String dim0;

input String dim;

input String ident;

output list<Absyn.Subscript> subscp;

algorithm

subscp := matchcontinue(identtype,typ,dim0,dim,ident)

local

list<Absyn.Subscript> subscp1, subscp2, subscp3;

String dim1, dim2, ident1, typ1;

Integer intdim, intdim2;

case("Scalar",typ1,dim1,dim2,ident1)

then {};

case("vector",typ1,dim1,dim2,ident1) // "vector","Integer"

equation

intdim = stringInt(dim1);

subscp1 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim))::{};

then subscp1;

case("vector","Real",dim1,dim2,ident1)

equation

intdim = stringInt(dim1);

subscp1 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim))::{};

then subscp1;

case("matrix",typ1,dim1,dim2,ident1) //"matrix","Integer"

equation

intdim = stringInt(dim1);

intdim2 = stringInt(dim2);

subscp1 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim2))::{};

subscp2 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim))::{};

subscp3 = listAppend(subscp1,subscp2);

then subscp3;

case("matrix","Real",dim1,dim2,ident1)

equation

intdim = stringInt(dim1);

intdim2 = stringInt(dim2);

subscp1 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim))::{};

subscp2 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim2))::{};

subscp3 = listAppend(subscp1,subscp2);

then subscp3;

case("column_vector",typ1,dim1,dim2,ident1) //"column_vector","Integer"

equation

intdim = stringInt(dim2);

subscp1 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim))::{};

subscp2 = Absyn.SUBSCRIPT(Absyn.INTEGER(1))::{};

subscp3 = listAppend(subscp1,subscp2);

then subscp3;

case("column_vector","Real",dim1,dim2,ident1)

equation

161

intdim = stringInt(dim2);

subscp1 = Absyn.SUBSCRIPT(Absyn.INTEGER(intdim))::{};

subscp2 = Absyn.SUBSCRIPT(Absyn.INTEGER(1))::{};

subscp3 = listAppend(subscp1,subscp2);

then subscp3;

end matchcontinue;

end scl_ary_type;

public function match_type

input Boolean tf;

input String ident;

input list<String> all_idents;

input list<String> appident;

output list<String> typ;

output list<String> all_idents_o;

output list<Absyn.Subscript> subscp;

algorithm

(typ,all_idents_o,subscp) := matchcontinue(tf,ident,all_idents,appident)

local

String typ1,ident1, identtype, dim, dim2;

list<String> all_idents1, appident1;

list<Absyn.Subscript> subscp1;

case(true,ident1,typ1::all_idents1,appident1)

equation

print("\n Append LIST 0\n");

print(anyString(appident1));

identtype = listGet(appident1,4);

dim = listGet(appident1,2);

dim2 = listGet(appident1,3);

print("\n Append LIST 1\n");

print(anyString(dim));

print("\n Append LIST 2\n");

print(anyString(identtype));

print("\n Append LIST 3\n");

print(anyString(typ1));

print("\n Append LIST 4\n");

print(anyString(ident1));

subscp1 = scl_ary_type(identtype,typ1,dim,dim2,ident1);

print("\n Append LIST 4 \n");

print(anyString(subscp1));

then ({typ1},{},subscp1);

case(false,ident1,all_idents1,appident1)

then ({ident1},all_idents1,{});

end matchcontinue;

end match_type;

public function match_ident_type

input String ident;

input list<String> all_idents;

input list<String> appident;

output list<String> typ;

output list<Absyn.Subscript> subscp;

algorithm

(typ,subscp) := matchcontinue(ident,all_idents,appident)

local

String ident1,ident2;

162

list<String> ident3, ident4, ident5, appident1,appident2,all_idents1,

all_idents2, all_idents3;

Boolean tf;

list<Absyn.Subscript> subscp1, subscp2, subscp3;

case(ident1,{},appident1)

then ({},{});

case(ident1,ident2::all_idents1,appident1)

equation

print("\n Match OUTPUT 0 \n");

print(anyString(ident1));

print("\n Match OUTPUT 1 \n");

print(anyString(ident2));

print("\n Match OUTPUT 3 \n");

print(anyString(all_idents1));

print("\n Match OUTPUT 4 \n");

print(anyString(appident1));

appident2 = listAppend({ident2},appident1);

tf = stringEqual(ident1,ident2);

(ident3,all_idents2,subscp1) =

match_type(tf,ident1,all_idents1,appident2);

(ident4,subscp2) = match_ident_type(ident1,all_idents2,appident2);

ident5 = listAppend(ident3,ident4);

subscp3 = listAppend(subscp1,subscp2);

then (ident5,subscp3);

end matchcontinue;

end match_ident_type;

public function output_type

input String ident;

input list<String> all_idents;

output list<String> typ;

output list<Absyn.Subscript> subscp;

algorithm

(typ,subscp) := matchcontinue (ident, all_idents)

local

String ident1;

list<String> all_idents1, typ1;

list<Absyn.Subscript> subscp1;

case(ident1, all_idents1)

equation

print("\n Check Data Type 0 \n");

print(anyString(ident1));

print("\n Check Data Type 1 \n");

print(anyString(all_idents1));

(typ1,subscp1) = match_ident_type(ident1,all_idents1,{});

print("\n Check Data Type 2 \n");

print(anyString(typ1));

print("\n Check Data Type 3 \n");

print(anyString(subscp1));

then (typ1,subscp1);

end matchcontinue;

end output_type;

public function ret_typ

input list<String> typ;

output String data_type;

algorithm

163

data_type := matchcontinue(typ)

local

String data_type1;

list<String> typ1, lstRev;

case({})

then "empty";

case(typ1)

equation

lstRev = listReverse(typ1);

data_type1 = listGet(lstRev,1);

then data_type1;

end matchcontinue;

end ret_typ;

public function create_out

input AbsynMat.Decl_Elt ret;

input Boolean tf;

input list<String> all_idents;

output list<Absyn.ElementItem> outclasspart;

output String in_out_ident;

algorithm

(outclasspart,in_out_ident) := matchcontinue(ret,tf,all_idents)

local

Absyn.ElementAttributes attr, attr1;

Absyn.TypeSpec tSpec, tSpec1;

list<Absyn.ElementItem> eli;

list<Absyn.ComponentItem> com, com1;

Absyn.ClassPart in1, out1;

Absyn.Info info, info1;

AbsynMat.Ident ident;

String in_put, out_put, data_type;

list<String> all_idents1, typ, typ1;

Integer lth;

list<Absyn.Subscript> subscp1;

case(AbsynMat.DECL(ident,NONE()),true,all_idents1)

equation

print("\n create_out AbsynMat.DECL(ident,NONE()),true");

in_put = ident;

attr = Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),

Absyn.INPUT(),{});

tSpec = Absyn.TPATH(Absyn.IDENT("Real"),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(in_put,{},NONE()),NONE(),NONE())::{};

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

then

(eli,ident);

case(AbsynMat.DECL(ident,NONE()),false,all_idents1)

equation

print("\n create_out AbsynMat.DECL(ident,NONE()),false ");

print(anyString(all_idents1));

print("\n create_out AbsynMat.DECL(ident,NONE()),false 1");

print(anyString(ident));

164

(typ,subscp1) = output_type(ident,all_idents);

print("\n Subscript 0000 \n");

print(anyString(subscp1));

data_type = ret_typ(typ);

out_put = ident;

attr1 = Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),

Absyn.OUTPUT(),{});

tSpec1 = Absyn.TPATH(Absyn.IDENT(data_type),NONE());

com1 =

Absyn.COMPONENTITEM(Absyn.COMPONENT(out_put,subscp1,NONE()),NONE(),NONE())::{

};

info1=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Sys

tem.getCurrentTime()));

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr1,tSpec1,com1),info1,NONE())))::{};

then

(eli,ident);

end matchcontinue;

end create_out;

public function create_in

input AbsynMat.Parameter prm;

output list<Absyn.ElementItem> outspec;

output list<String> io_lst;

algorithm

(outspec,io_lst):= matchcontinue(prm)

local

list<AbsynMat.Decl_Elt> prm1;

list<Absyn.ElementItem> outspec1;

list<String> io_lst1;

case(AbsynMat.PARM(prm1))

equation

print("\n create_in AbsynMat.PARM(prm1)");

(outspec1,io_lst1) = create_out_list(prm1,true,{});

then

(outspec1,io_lst1);

end matchcontinue;

end create_in;

public function create_in_list

input list<AbsynMat.Parameter> prm;

output list<Absyn.ElementItem> outspec;

output list<String> io_lst;

algorithm

(outspec,io_lst):= matchcontinue(prm)

local

list<AbsynMat.Parameter> prm2;

AbsynMat.Parameter prm1;

list<Absyn.ElementItem> outspec1, outspec2, out;

list<String> io_lst1, io_lst2, io_lst3;

case(prm1::prm2)

equation

165

print("\n create_in_list prm1::prm2");

(outspec1,io_lst1) = create_in(prm1);

(outspec2,io_lst2) = create_in_list(prm2);

io_lst3 = listAppend(io_lst1,io_lst2);

out = listAppend(outspec1,outspec2);

then

(out,io_lst3);

case({})

then ({},{});

end matchcontinue;

end create_in_list;

public function create_out_list

input list<AbsynMat.Decl_Elt> retlst;

input Boolean bln;

input list<String> all_idents;

output list<Absyn.ElementItem> outspec;

output list<String> io_lst;

algorithm

(outspec,io_lst) := matchcontinue(retlst,bln,all_idents)

local

list<AbsynMat.Decl_Elt> retlst1;

AbsynMat.Decl_Elt ret;

list<Absyn.ElementItem> out, eli, eli2;

Boolean bln1;

String in_out_ident;

list<String> io_lst1, io_lst2, all_idents1;

case(ret::retlst1,bln1,all_idents1)

equation

print("\n create_out_list ret::retlst1,bln1");

(eli,in_out_ident) = create_out(ret,bln1,all_idents1);

(eli2,io_lst1) = create_out_list(retlst1,bln1,all_idents);

io_lst2 = listAppend(io_lst1,in_out_ident::{});

out = listAppend(eli,eli2);

then

(out,io_lst2);

case({},bln1,all_idents1)

then ({},{});

end matchcontinue;

end create_out_list;

public function array_rmv

input String ident;

input list<String> lst;

output String ident1;

algorithm

ident1 := matchcontinue(ident,lst)

local

String ident2;

list<String> lst1;

case("matrix",ident2::lst1)

then ident2;

case("vector",ident2::lst1)

then ident2;

case(ident2,lst1)

166

then ident2;

case(ident2,{})

then ident2;

end matchcontinue;

end array_rmv;

public function var_match

input Boolean tf;

input list<String> type_lst;

output list<String> d_type;

algorithm

d_type := matchcontinue(tf,type_lst)

local

Boolean tf1;

list<String> type_lst1;

String d_type1, d_type2;

case(true,d_type1::type_lst1)

equation

print("\n Check var_match true \n");

d_type2 = array_rmv(d_type1,type_lst1); //this fnc removes the

matrix or vector string from list

print(anyString(d_type2));

then {d_type2};

case(true,{})

then {};

case(false,type_lst1)

equation

print("\n Check var_match false \n");

then {};

end matchcontinue;

end var_match;

public function asg_type

input String ident;

input list<String> type_lst;

output list<String> ary_type;

algorithm

ary_type := matchcontinue(ident,type_lst)

local

String ident1,ident2;

list<String> type_lst1, ident3, ident4, ident5;

Boolean tf;

case(ident1,ident2::type_lst1)

equation

print("\n Var Match \n");

tf = stringEqual(ident1,ident2);

ident3 = var_match(tf,type_lst1);

ident4 = asg_type(ident1,type_lst1);

ident5 = listAppend(ident3,ident4);

print("\n Protected Var \n");

print(anyString(ident1));

print("\n Protected Type \n");

print(anyString(ident5));

then ident5;

case(ident1,{})

then {};

167

end matchcontinue;

end asg_type;

public function real_integer

input Boolean chk_real;

output String type_o;

algorithm

type_o := matchcontinue(chk_real)

local

String type_o1;

case(true)

then "Real";

case(false)

then "Integer";

end matchcontinue;

end real_integer;

public function prt_mtx_vec_type

input list<String> type_lst;

output String type_out;

algorithm

type_out := matchcontinue(type_lst)

local

list<String> type_lst1;

String type1, type2;

Boolean chk_real;

case(type1::type_lst1) //doesn't handle 1,1,1.0, if list contain mix of

Integer and Real

equation

chk_real = listMember("Real",type_lst1);

type2 = real_integer(chk_real);

then type2;

case("Real"::type_lst1)

then "Real";

end matchcontinue;

end prt_mtx_vec_type;

public function prt_mtx_vec

input list<String> ary_type;

input String ident;

input Absyn.Modification modfic;

input list<String> mtx_vec;

input list<String> all_idents;

output list<Absyn.ElementItem> eli;

algorithm

eli := matchcontinue(ary_type,ident,modfic,mtx_vec,all_idents)

local

list<Absyn.ElementItem> eli1;

String ary_type1, ident1, data_type;

list<String> type_lst, ary_type_lst;

Absyn.Modification modfic1;

Absyn.ElementAttributes attr;

Absyn.TypeSpec tSpec;

list<Absyn.ComponentItem> com;

Absyn.Info info;

list<String> all_idents1, typ;

list<Absyn.Subscript> subscp1;

168

case(ary_type1::ary_type_lst,ident1,modfic1,"vector"::type_lst,all_idents1)

equation

print("\n Modification 2 Vector \n");

ary_type1 = prt_mtx_vec_type(type_lst);

(typ,subscp1) = output_type(ident1,all_idents1);

print("\n Expression Test Matrix \n");

print(anyString(typ));

print("\n Expression Test Matrix 2 \n");

print(anyString(subscp1));

data_type = ret_typ(typ);

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),Absyn.N

OSUB()::{}); // Absyn.NOSUB()::{} = Real[:]

tSpec = Absyn.TPATH(Absyn.IDENT(data_type),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident1,{},SOME(modfic)),NONE(),NONE())::{

}; //modification

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

then eli;

/* case(ary_type1::{},ident1,modfic1,"vector"::type_lst)

equation

print("\n Modification 2 Vector \n");

ary_type1 = prt_mtx_vec_type(type_lst);

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),Absyn.N

OSUB()::{}); // Absyn.NOSUB()::{} = Real[:]

tSpec = Absyn.TPATH(Absyn.IDENT(ary_type1),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident1,{},SOME(modfic)),NONE(),NONE())::{

}; //modification

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

then eli; */

case(ary_type1::ary_type_lst,ident1,modfic1,"matrix"::type_lst,all_idents1)

equation

print("\n Modification 2 Matrix \n");

(typ,subscp1) = output_type(ident1,all_idents1);

print("\n Expression Test Matrix \n");

print(anyString(typ));

print("\n Expression Test Matrix 2 \n");

print(anyString(subscp1));

data_type = ret_typ(typ);

169

ary_type1 = prt_mtx_vec_type(type_lst);

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),{});

tSpec = Absyn.TPATH(Absyn.IDENT(data_type),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident1,subscp1,SOME(modfic)),NONE(),NONE(

))::{}; // Absyn.NOSUB() = Real[:,:]

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

then eli;

end matchcontinue;

end prt_mtx_vec;

public function typcheck

input String typ;

output String otyp;

algorithm

otyp := matchcontinue(typ)

local

String typ1;

case("Integer")

then ("Integer");

case("Real")

then ("Real");

case(typ1)

then("Unknown");

end matchcontinue;

end typcheck;

public function lsttostring

input list<String> ary_type;

output String prt_type;

algorithm

prt_type := matchcontinue(ary_type)

local

list<String> ary_type1;

String typ,typ2;

case(typ::ary_type1)

equation

typ2 = typcheck(typ);

then typ2;

case(typ::{})

equation

typ2 = typcheck(typ);

then typ2;

case({})

then ("Unknown");

end matchcontinue;

end lsttostring;

public function protectTransform

input Option<String> ident;

170

input Option<AbsynMat.Expression> exp;

input list<String> type_lst;

input list<String> all_idents;

output list<Absyn.ElementItem> elitem;

algorithm

elitem := matchcontinue(ident,exp,type_lst,all_idents)

local

list<Absyn.ElementItem> outspec;

String ident1, ident2, ary_type1, data_type;

list<String> typ, type_lst1, ary_type, mtx_vec, all_idents1;

Absyn.ElementAttributes attr;

Absyn.TypeSpec tSpec;

list<Absyn.ElementItem> eli;

list<Absyn.ComponentItem> com;

Absyn.Info info;

AbsynMat.Expression exp1;

Absyn.Modification modfic;

list<Absyn.Subscript> subscp1;

case(NONE(),SOME(exp1),type_lst1,all_idents1) // Array

equation

print("\n Modification 0 \n");

print(anyString(type_lst1));

print("\n Modification exp \n");

print(anyString(exp1));

(ident2,modfic,mtx_vec) = modification(exp1);

print("\n Modification \n");

print(anyString(ident2));

ary_type = asg_type(ident2,type_lst1);

print("\n Data Type 2 \n");

print(anyString(ary_type));

print("\n Modification 2 \n");

print(anyString(ident2));

print("\n Modification 22 \n");

print(anyString(modfic));

print("\n Modification 23 \n");

print(anyString(mtx_vec));

eli = prt_mtx_vec(ary_type,ident2,modfic,mtx_vec,all_idents1);

then

eli;

case(SOME(ident1),NONE(),type_lst1,all_idents1) // Scalar

equation

(typ,subscp1) = output_type(ident1,all_idents1);

print("\n Expression Test Scalar \n");

print(anyString(typ));

print("\n Expression Test Scalar 2 \n");

print(anyString(subscp1));

data_type = ret_typ(typ);

ary_type = asg_type(ident1,type_lst1);

print("\n Data Type Scalar \n");

print(anyString(ary_type));

ary_type1 = lsttostring(ary_type);

attr =

Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),Absyn.BIDIR(),{});

tSpec = Absyn.TPATH(Absyn.IDENT(data_type),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(ident1,subscp1,NONE()),NONE(),NONE())::{}

;

171

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

eli =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

then

eli;

end matchcontinue;

end protectTransform;

public function protect_lst2 //function declaration for array constant only

in protected e.g. Real C[1,2,3];

input list<AbsynMat.Expression> exp_lst;

input list<String> type_lst;

input list<String> all_idents;

output list<Absyn.ElementItem> outspec;

algorithm

outspec := matchcontinue(exp_lst,type_lst,all_idents)

local

list<String> all_ident1, type_lst1;

String ident;

list<Absyn.ElementItem> outspec1, outspec2, outspec3;

list<AbsynMat.Expression> exp_lst1;

AbsynMat.Expression exp;

list<String> all_idents1;

case(exp::exp_lst1,type_lst1,all_idents1)

equation

outspec1 = protectTransform(NONE(),SOME(exp),type_lst1,all_idents1);

outspec2 = protect_lst2(exp_lst1,type_lst1,all_idents1);

outspec3 = listAppend(outspec1,outspec2);

then (outspec3);

case({},type_lst1,all_idents1)

then ({});

end matchcontinue;

end protect_lst2;

public function protect_lst //function declaration for scalar constants only

in protected e.g. Real C;

input list<String> all_ident;

input list<String> type_lst;

input list<String> all_idents;

output list<Absyn.ElementItem> outspec;

algorithm

outspec := matchcontinue(all_ident,type_lst,all_idents)

local

list<String> all_ident1, type_lst1, all_idents1;

String ident;

list<Absyn.ElementItem> outspec1, outspec2, outspec3;

list<AbsynMat.Expression> exp_lst1;

AbsynMat.Expression exp;

case(ident::all_ident1,type_lst1,all_idents1)

equation

outspec1 =

protectTransform(SOME(ident),NONE(),type_lst1,all_idents1);

outspec2 = protect_lst(all_ident1,type_lst1,all_idents1);

outspec3 = listAppend(outspec1,outspec2);

172

then (outspec3);

case({},type_lst1,all_idents1)

then ({});

end matchcontinue;

end protect_lst;

public function prtVariable

input Boolean chk;

input String prt_ident;

output list<String> out_ident;

algorithm

out_ident := matchcontinue(chk,prt_ident)

local

String prt_ident1;

case(false,prt_ident1)

then ({prt_ident1});

case(true,prt_ident1)

then ({});

end matchcontinue;

end prtVariable;

public function rmvIdent

input String ident;

input Boolean chk;

output list<String> out;

algorithm

out := matchcontinue(ident,chk)

local

String ident1;

Boolean chk1;

case(ident1,false)

then {ident1};

case(ident1,true)

then ({});

end matchcontinue;

end rmvIdent;

public function rmvIdent2

input String ident;

input Boolean chk;

output list<String> out;

algorithm

out := matchcontinue(ident,chk)

local

String ident1;

Boolean chk1;

case(ident1,false)

then {ident1};

case("vector",true)

then ({"vector"});

case("matrix",true)

then ({"matrix"});

case("Integer",true)

then ({"Integer"});

case("Real",true)

then ({"Real"});

173

case(ident1,true)

then ({});

end matchcontinue;

end rmvIdent2;

public function rmvDuplicate

input list<String> all;

output list<String> out;

algorithm

out := matchcontinue(all)

local

list<String> lst_ident, lst_ident1, lst_ident2, lst_ident3;

String ident;

Boolean chk;

case(ident::lst_ident)

equation

chk = listMember(ident,lst_ident);

lst_ident1 = rmvIdent(ident,chk);

lst_ident2 = rmvDuplicate(lst_ident);

lst_ident3 = listAppend(lst_ident1, lst_ident2);

then lst_ident3;

case({})

then ({});

end matchcontinue;

end rmvDuplicate;

public function rmvDuplicate2

input list<String> all; //remove duplicate idents only,, not datatypes

such as Integer, Real, vector, matrix

output list<String> out;

algorithm

out := matchcontinue(all)

local

list<String> lst_ident, lst_ident1, lst_ident2, lst_ident3;

String ident;

Boolean chk;

case(ident::lst_ident)

equation

chk = listMember(ident,lst_ident);

lst_ident1 = rmvIdent2(ident,chk);

lst_ident2 = rmvDuplicate2(lst_ident);

lst_ident3 = listAppend(lst_ident1, lst_ident2);

then lst_ident3;

case({})

then ({});

end matchcontinue;

end rmvDuplicate2;

public function rmvInOut

input list<String> all;

input list<String> prt;

output list<String> out;

algorithm

out := matchcontinue(all,prt)

local

list<String> lst_ident, lst_ident1, lst_ident2, lst_ident3, prt2;

String ident;

174

Boolean chk;

case(ident::lst_ident,prt2)

equation

chk = listMember(ident,prt2);

lst_ident1 = rmvIdent(ident,chk);

lst_ident2 = rmvInOut(lst_ident,prt2);

lst_ident3 = listAppend(lst_ident1, lst_ident2);

then lst_ident3;

case({},prt2)

then ({});

end matchcontinue;

end rmvInOut;

public function protectVariable

input list<String> all_ident;

input list<String> asg_ident;

output list<String> prt_ident;

algorithm

prt_ident := matchcontinue(all_ident,asg_ident)

local

list<String> all_ident1, asg_ident1, ident, prt_var, all_ident1,

all_ident2, all;

String asg_ident2, chk_ident;

Boolean chk;

case(all_ident1,asg_ident2::asg_ident1)

equation

chk = listMember(asg_ident2,all_ident1);

prt_var = prtVariable(chk,asg_ident2);

ident = protectVariable(all_ident1,asg_ident1);

all_ident2 = listAppend(ident,prt_var);

all = rmvDuplicate(all_ident2);

then (all);

case(all_ident1,{})

then ({});

end matchcontinue;

end protectVariable;

public function unknowntype

input String io;

output list<String> io_o;

algorithm

io_o := matchcontinue(io)

local

String io_i, io_i2;

list<String> io_lst,io_lst2,io_lst3;

case(io_i)

equation

io_i2 = "Unknown";

io_lst = {io_i2};

io_lst2 = {io_i};

io_lst3 = listAppend(io_lst,io_lst2);

then (io_lst3);

end matchcontinue;

end unknowntype;

public function unknowntype_lst

input list<String> io_lst;

175

output list<String> io_olst;

algorithm

io_olst := matchcontinue(io_lst)

local

list<String> io_lst1, io_lst2, io_lst3, io_lst4;

String io;

case(io::io_lst1)

equation

print("\n UNKNOWNTYPE_LST \n");

io_lst2 = unknowntype(io);

io_lst3 = unknowntype_lst(io_lst1);

io_lst4 = listAppend(io_lst2,io_lst3);

then io_lst4;

case({})

then {};

end matchcontinue;

end unknowntype_lst;

public function user_function

input list<Absyn.ElementItem> in_out;

input AbsynMat.User_Function uf;

input list<String> io_lst;

input list<String> f_call;

input list<String> fnc_hdl_ident;

input list<String> all_idents;

output String fnc_name;

output list<Absyn.ClassPart> outclasspart;

output list<String> d_type1;

algorithm

(fnc_name,outclasspart,d_type1) :=

matchcontinue(in_out,uf,io_lst,f_call,fnc_hdl_ident,all_idents)

local

AbsynMat.User_Function usr_fnc, usr_fnc1, usr_fnc2;

list<AbsynMat.Parameter> prm;

Option<AbsynMat.Separator> sep;

list<AbsynMat.Statement> stmt, stmt_end;

AbsynMat.Statement stmt_2nd;

list<AbsynMat.Decl_Elt> ret;

list<Absyn.AlgorithmItem> alg;

list<Absyn.ClassPart> cls_prt, cls_prt2, cls_prt3, cls_rev, cls_rev2,

prm_stmt, prm_stmt2, prm_stmt3;

Absyn.ClassPart cls_stmt, in_cp, out_cp, prt_cp;

list<Absyn.ElementItem> inout, inout1, in_put, out_put, prtVar,

prtVar2, prtVar3;

Absyn.Ident fname, fname1;

list<String> un_rdtype, un_dtype, un_dtype2, io_lst3, io_lst1, io_lst2,

for_ident, all_ident, asg_ident;

list<String> all_idents1, io_lstun, all, all2, f_call1, d_type_lst,

fnc_hdl_ident1, fnc_hdl_ident2;

list<AbsynMat.Expression> exp_lst, exp_lst2, exp_lst3;

case(inout, AbsynMat.START_FUNCTION(fname,prm,sep,stmt,stmt_2nd),io_lst1,

f_call1, fnc_hdl_ident1, all_idents1)

equation

print("\n user_function

AbsynMat.START_FUNCTION(fname,prm,sep,stmt,stmt_2nd) \n");

print(anyString(all_idents1));

f_call1 = listAppend(fname::{},f_call1);

176

(in_put,io_lst3) = create_in_list(prm);

io_lst2 = listAppend(io_lst3,io_lst1);

inout1 = listAppend(in_put,inout);

io_lstun = unknowntype_lst(io_lst2);

print("\n Unknown List \n");

print(anyString(io_lstun));

(alg,for_ident,asg_ident,exp_lst,d_type_lst,fnc_hdl_ident2) =

stmt_lst(stmt, f_call1, fnc_hdl_ident1, io_lstun);

print("\n INPUT OUTPUT INPUT OUTPUT INPUT OUTPUT INPUT OUTPUT \n

");

print(anyString(d_type_lst));

print("\n STMT IDENT STMT IDENT STMT IDENT STMT IDENT STMT IDENT STMT

IDENT \n ");

print(anyString(asg_ident));

all_ident = listAppend(io_lst2,for_ident);

print("\n Protected 1 \n");

print(anyString(all_ident));

print("\n Protected 2 \n");

print(anyString(asg_ident));

all = protectVariable(all_ident,asg_ident);

print("\n ALL IDENT ALL IDENT ALL IDENT ALL IDENT ALL IDENT ALL

IDENT \n ");

print(anyString(all));

all2 = listReverse(all);

print("\n All Array Protected Expression \n");

print(anyString(exp_lst));

print("\n All Protected Variables with there dataytpes \n");

print(anyString(all2));

print("\n All Protected Variables with there datatypes 2 \n");

print(anyString(d_type_lst));

prtVar = protect_lst(all2,d_type_lst,all_idents1);

print("\n Protected 0 \n");

print(anyString(prtVar));

//un_dtype = rmv_non_protected(d_type_lst,io_lst2);

un_dtype = rmvInOut(d_type_lst,io_lst2);

un_rdtype = listReverse(un_dtype);

un_dtype2 = rmvDuplicate2(un_rdtype);

un_rdtype = listReverse(un_dtype2);

print("\n Protected 1st \n");

print(anyString(un_rdtype));

print("\n Protected 2nd \n");

print(anyString(un_dtype2));

print("\n Protected 3rd \n");

print(anyString(exp_lst));

prtVar2 = protect_lst2(exp_lst,un_rdtype,all_idents1);

prtVar3 = listAppend(prtVar,prtVar2);

in_cp = Absyn.PUBLIC(inout1);

prt_cp = Absyn.PROTECTED(prtVar3);

cls_stmt = Absyn.ALGORITHMS(alg);

prm_stmt = listAppend(cls_stmt::{},prt_cp::{});

prm_stmt2 = listAppend(prm_stmt,in_cp::{});

then

(fname, prm_stmt2,d_type_lst);

case({},

AbsynMat.FINISH_FUNCTION(ret,usr_fnc2),{},f_call1,fnc_hdl_ident1,

all_idents1)

equation

177

print("\n user_function AbsynMat.FINISH_FUNCTION(ret,usr_fnc2)");

(out_put,io_lst3) = create_out_list(ret,false,all_idents);

(fname, cls_prt,d_type_lst) = user_function(out_put, usr_fnc2,

io_lst3, f_call1,fnc_hdl_ident1,all_idents1);

cls_rev = listReverse(cls_prt);

then

(fname, cls_rev,d_type_lst);

case({},_,{},{},{},{})

then ("",{},{});

end matchcontinue;

end user_function;

public function sub_function

input list<AbsynMat.Statement> stmt_lst;

input list<String> in_f_call;

input list<String> fnc_hdl_ident;

output list<Absyn.Class> mod_class;

output list<String> f_call;

algorithm

(mod_class,f_call) := matchcontinue(stmt_lst,in_f_call,fnc_hdl_ident)

local

AbsynMat.User_Function usr_fnc;

AbsynMat.Separator sep;

Absyn.ClassDef cd;

list<Absyn.ClassPart> cp;

Absyn.Class class1;

list<Absyn.Class> class2, mod_class2;

String fname;

list<String> f_call1, f_call2, f_call3, f_call4, fnc_hdl_ident1,

no_ident;

Absyn.Info info;

list<AbsynMat.Statement> stmt_lst2;

case(AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(NONE(),NONE(),SOME(AbsynMat

.START(usr_fnc,sep,stmt_lst2)),NONE()),sep)::{},f_call4,fnc_hdl_ident1)

equation

(mod_class2,f_call1) = sub_function(stmt_lst2,f_call4,fnc_hdl_ident1);

f_call3 = listAppend(f_call1,f_call4);

(fname, cp, no_ident) =

user_function({},usr_fnc,{},f_call3,fnc_hdl_ident1,{});

f_call2 = listAppend(f_call1,fname::{});

cd = Absyn.PARTS({},{},cp,{},NONE());

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

class1 =

Absyn.CLASS(fname,false,false,false,Absyn.R_FUNCTION(Absyn.FR_NORMAL_FUNCTION

(Absyn.NO_PURITY())),cd,info);

class2 = listAppend(class1::{},mod_class2);

then (class2,f_call2);

case({},f_call4,fnc_hdl_ident1)

then ({},{});

end matchcontinue;

end sub_function;

public function rem_nStatement

input list<String> nstmt;

178

output list<String> o_stmt;

algorithm

o_stmt := matchcontinue(nstmt)

local

list<String> nstmt1, nstmt2, nstmt3;

String nstring;

case("nStatement"::nstmt1)

equation

nstmt2 = rem_nStatement(nstmt1);

then nstmt2;

case(nstmt1)

then nstmt1;

end matchcontinue;

end rem_nStatement;

public function chk_lst

input list<String> i_typelst1;

input list<String> i_typelst2;

output list<String> o_typelst;

algorithm

o_typelst := matchcontinue(i_typelst1,i_typelst2)

local

list<String> i_typelst3,i_typelst4;

case(i_typelst3,{})

then i_typelst3;

case({},i_typelst3)

then i_typelst3;

case(i_typelst3,i_typelst4)

then i_typelst4;

case({},{})

then {};

end matchcontinue;

end chk_lst;

public function update_lst

input String ident;

input String upd_type;

input list<String> u_typelst;

input Boolean tf;

input list<String> u2_typelst;

output list<String> o_typelst;

algorithm

o_typelst := matchcontinue(ident,upd_type,u_typelst,tf,u2_typelst)

local

String ident1, add_type1, u_type, upd_type1;

list<String> u_typelst1, u2_typelst2, o_typelst2, o_typelst3, o_typelst4,

o_typelst5;

Boolean tf1;

case(ident1,upd_type1,u_type::u_typelst1,false,u2_typelst2)

equation

/* print("\n update_lst false 0\n");

print(anyString(ident1));

print("\n update_lst false 1\n");

print(anyString(upd_type1));

print("\n update_lst false 2\n");

print(anyString(u_type));

print("\n update_lst false 3\n");

179

print(anyString(u_typelst1));

print("\n update_lst false 4\n");

print(anyString(u2_typelst2));

*/ tf1 = stringEqual(ident1,u_type);

o_typelst3 = listAppend(u2_typelst2,{u_type});

// print("\n update_lst false 5\n");

// print(anyString(o_typelst3));

o_typelst2 = update_lst(ident1,upd_type1,u_typelst1,tf1,o_typelst3);

then o_typelst2;

case(ident1,upd_type1,u_type::u_typelst1,true,u2_typelst2)

equation

/* print("\n update_lst true 0\n");

print(anyString(upd_type1));

print("\n update_lst true 1\n");

print(anyString(u_type));

print("\n update_lst true 2\n");

print(anyString(u_typelst1));

print("\n update_lst true 3\n");

print(anyString(u2_typelst2));

*/ o_typelst2 = listAppend({upd_type1},u_typelst1);

o_typelst3 = listAppend(u2_typelst2, o_typelst2);

// print("\n update_lst true 4\n");

// print(anyString(o_typelst3));

o_typelst4 =

update_lst(ident1,upd_type1,o_typelst2,false,u2_typelst2);

o_typelst5 = chk_lst(o_typelst3,o_typelst4);

/* print("\n update_lst true 3\n");

print(anyString(o_typelst3));

print("\n update_lst true 4\n");

print(anyString(o_typelst4));

*/ then o_typelst5;

case(ident1,upd_type1,{},false,u2_typelst2)

then {};

end matchcontinue;

end update_lst;

public function chk_ept

input list<String> i_typelst;

input list<String> f_lst;

output list<String> o_typelst;

algorithm

o_typelst := matchcontinue(i_typelst,f_lst)

local

list<String> i_typelst1,f_lst1;

case({},f_lst1)

then f_lst1;

case(i_typelst1,{})

then i_typelst1;

case(i_typelst1,f_lst1)

then i_typelst1;

case({},{})

then {};

end matchcontinue;

end chk_ept;

public function update_type

input Boolean bool;

180

input String u_type;

input list<String> u_typelst;

input Boolean tf;

input list<String> upd_type;

input list<String> f_lst;

output list<String> o_typelst;

algorithm

o_typelst := matchcontinue(bool,u_type,u_typelst,tf,upd_type,f_lst)

local

list<String> o_typelst1,upd_typelst;

String u_type1,u_type2, rmv_ident, upd_type1;

list<String> u_typelst1,u_typelst2, f_lst1;

Boolean tf1;

case(true,u_type1,u_typelst1,false,upd_typelst,f_lst1)

then u_typelst1;

case(false,u_type1,u_typelst1,false,{},f_lst1)

then {};

case(false,u_type1,{},false,upd_typelst,f_lst1)

then {};

case(false,u_type1,{},false,{},f_lst1)

then {};

case(false,u_type1,u_type2::u_typelst1,false,{},f_lst1)

equation

// print("\n update_type false {}\n");

tf1 = stringEqual(u_type1,u_type2);

o_typelst = update_type(false,u_type1,u_typelst1,tf1,{},f_lst1);

then o_typelst;

case(false,u_type1,u_type2::u_typelst1,false,upd_typelst,f_lst1)

equation

print("\n update_type false 1\n");

print(anyString(u_type1));

print("\n update_type false 2\n");

print(anyString(u_type2));

tf1 = stringEqual(u_type1,u_type2);

o_typelst =

update_type(false,u_type1,u_typelst1,tf1,upd_typelst,f_lst1);

o_typelst1 = chk_ept(o_typelst,f_lst1);

// print("\n update_type false 3\n");

// print(anyString(o_typelst));

then o_typelst1;

case(false,u_type1,u_typelst1,true,upd_type1::upd_typelst,f_lst1)

equation

print("\n update_type true 0\n");

print(anyString(u_type1));

print("\n update_type true 1\n");

print(anyString(upd_type1));

print("\n update_type true 2\n");

print(anyString(f_lst1));

u_typelst2 = update_lst(u_type1,upd_type1,f_lst1,false,{});

print("\n update_type true 1 \n");

print(anyString(u_typelst2));

then u_typelst2;

end matchcontinue;

end update_type;

public function chk_keywords

input list<String> type22;

181

output Boolean bool;

algorithm

bool := matchcontinue(type22)

local

String ident;

list<String> type221,lst_numbers;

Boolean num_bool;

case("vector"::type221)

then true;

case("matrix"::type221)

then true;

case("column_vector"::type221)

then true;

case("empty"::type221)

then true;

case("Real"::type221)

then true;

case("Integer"::type221)

then true;

case(ident::type221) //check for numbers 0 1 2 3 4 5 6 7 8 9

equation

lst_numbers = {"0","1","2","3","4","5","6","7","8","9"};

num_bool = listMember(ident,lst_numbers);

then num_bool;

end matchcontinue;

end chk_keywords;

public function update_typelst

input list<String> u_type1;

input list<String> u_type2;

input Boolean chk_1st;

output list<String> type_lst;

output Boolean o_chk_1st;

algorithm

(type_lst,o_chk_1st) := matchcontinue(u_type1,u_type2,chk_1st)

local

Boolean chk_1st1, chk_key;

list<String> type11, type22, type33, type44, type_lst2, type_lst3,

type_lst4, type_lst5, type_lst6;

String stype, stype1, stype2;

case(type11,{},true)

equation

type_lst2 = ident_typelst(type11);

chk_1st1 = false;

then (type_lst2,chk_1st1);

case(type11,{},chk_1st1)

equation

// print("\n update_typelst type11 \n");

// print(anyString(type11));

then ({},chk_1st);

case({},type22,chk_1st1)

equation

// print("\n update_typelst type22 \n");

then ({},chk_1st1);

case({},{},chk_1st1)

equation

// print("\n update_typelst end \n");

182

then ({},chk_1st1);

case(type11,stype::{},chk_1st1)

equation

// print("\n update_typelst stype::{}\n");

type_lst2 = update_type(true,stype, type11, false,{},type11);

(type_lst3,chk_1st1) = update_typelst(type11,{},false);

type_lst4 = listAppend(type_lst2,type_lst3);

// print("\n update_typelst 1 {} \n");

// print(anyString(type_lst4));

then (type_lst4,chk_1st1);

case(type11,type22,chk_1st1)

equation

print("\n update_typelst 0\n");

print(anyString(type11));

// print("\n update_typelst 1\n");

// print(anyString(stype));

print("\n update_typelst 2\n");

print(anyString(type22));

chk_key = chk_keywords(type22); //return true if first element is

ident else false for keywords and numbers

stype1::type33 = type22;

// stype2::type44 = type33;

print("\n update_typelst 3 \n");

print(anyString(chk_key));

print("\n update_typelst 4 \n");

print(anyString(stype1));

print("\n update_typelst 5 \n");

print(anyString(type33));

type_lst2 = update_type(chk_key,stype1, type11, false,type33,type11);

//if chk_key is true then ignore comparing else search for ident

(type_lst3,chk_1st1) = update_typelst(type_lst2,type33,false);

// type_lst4 = listAppend({"nstmt"},type_lst3);

// type_lst5 = listAppend(type_lst2,type_lst4);

type_lst6 = rtn_sgl(type_lst2,type_lst3);

/* print("\n update_typelst 2 \n");

print(anyString(type_lst2));

print("\n update_typelst 3 \n");

print(anyString(type_lst3));

*/ then (type_lst6,chk_1st1);

end matchcontinue;

end update_typelst;

public function split //not in use

input String d_type;

input list<String> stmt;

input list<String> sep_lst0;

input list<String> ident_type;

output list<String> o_stmt;

output list<String> o_stmt2;

algorithm

(o_stmt,o_stmt2) := matchcontinue(d_type,stmt,sep_lst0, ident_type)

local

String d_type1;

list<String> stmt2, d_type2,d_type3, sep_lst, ret_type, ret_type2,

ident_type1, ident_type2, u_type, u_type2;

case("nstmt",{"nstmt","nstmt"}, sep_lst, ident_type1)

183

equation

ident_type2 = listAppend(sep_lst,ident_type1);

/* print("\n sep nstmt 1\n");

print(anyString(sep_lst));

print("\n sep nstmt 11\n");

print(anyString(ident_type1));

*/ then ({},ident_type2);

case("nstmt",d_type2, sep_lst, ident_type1)

equation

// print("\n sep no nstmt 2\n");

// print(anyString(sep_lst));

then ({},sep_lst);

case(d_type1,stmt2,sep_lst,ident_type1)

equation

// print("\n sep no nstmt 3\n");

// print(anyString(ident_type1));

// print("\n sep no nstmt 2\n");

// print(anyString(stmt2));

d_type2 = listAppend(sep_lst,{d_type1});

then (d_type2,{});

end matchcontinue;

end split;

public function rtn_sgl

input list<String> ident_type2;

input list<String> d_type_lst2;

output list<String> o_type;

algorithm

o_type := matchcontinue(ident_type2,d_type_lst2)

local

list<String> i_ident,i_ident2;

case(i_ident,{})

equation

// print("\n rtn 1 \n");

// print(anyString(i_ident));

then i_ident;

case({},i_ident2)

equation

// print("\n rtn 2\n");

// print(anyString(i_ident2));

then i_ident2;

case(i_ident,i_ident2)

equation

// print("\n rtn 3\n");

// print(anyString(i_ident2));

then i_ident2;

end matchcontinue;

end rtn_sgl;

public function split_lst //not in use

input list<String> d_type_lst;

input list<String> sep_lst;

input list<String> ident_type;

output list<String> f_type_lst;

algorithm

f_type_lst := matchcontinue (d_type_lst,sep_lst,ident_type)

local

184

list<String> d_type_lst1, o_type_lst1, d_type_lst2, d_type_lst3,

o_type_lst2, o_type_lst3, sep_lst1, ident_type1, ident_type2;

String d_type,d_type2;

case({},sep_lst1,ident_type1)

equation

// print("\n Empty \n");

then {};

case(d_type::{},sep_lst1,ident_type1)

then sep_lst1;

case(d_type::d_type_lst1,sep_lst1,ident_type1)

equation

// print("\n split_type 1\n");

// print(anyString(d_type_lst1));

d_type2::d_type_lst3 = d_type_lst1;

// print("\n split_type 2\n");

// print(anyString(d_type2));

// print("\n split_type 3 \n");

// print(anyString(d_type_lst3));

(o_type_lst1,ident_type2) =

split(d_type,{d_type,d_type2},sep_lst1,ident_type1);

d_type_lst2 = split_lst(d_type_lst1,o_type_lst1,ident_type2);

o_type_lst2 = rtn_sgl(ident_type2,d_type_lst2);

// o_type_lst2 = listAppend(ident_type2,d_type_lst2);

// print("\n split_type 3 \n");

// print(anyString(o_type_lst2));

then o_type_lst2;

end matchcontinue;

end split_lst;

public function chk_emp

input list<String> u_type;

input list<String> ret_type;

output list<String> o_type;

algorithm

o_type := matchcontinue(u_type,ret_type)

local

list<String> u_type1, ret_type1;

case({},ret_type1)

then ret_type1;

case(u_type1,ret_type1)

then u_type1;

end matchcontinue;

end chk_emp;

public function ary_fnc

input Boolean zeros;

input Boolean ones;

input list<String> i_lst;

output list<String> o_lst;

output Boolean zos;

algorithm

(o_lst,zos) := matchcontinue(zeros,ones,i_lst)

local

list<String> i_lst1,i_lst2,i_lst3,i_lst4,i_lst5, i_lst6, lst_ap, lst_ap1,

lst_ap2;

String str, str2, dim, dim1, dim2;

185

Integer dim_length, total_length;

case(true,false,i_lst1)

equation

dim = listGet(i_lst1,5);

print("\n Zeros DIM \n");

print(anyString(dim));

dim1 = stringGetStringChar(dim,1);

dim2 = stringGetStringChar(dim,2);

print("\n Zeros DIM 2\n");

print(anyString(dim1));

print("\n Zeros DIM 22\n");

print(anyString(dim2));

str::i_lst2=i_lst1;

i_lst3 = listDelete(i_lst2,0);

i_lst4 = listDelete(i_lst3,0);

i_lst5 = listDelete(i_lst4,0);

str2::i_lst6 = i_lst5;

lst_ap = {"matrix",dim1,dim2};

lst_ap1 = listAppend(lst_ap,{str});

lst_ap2 = listAppend(lst_ap1,{"Real"});

then (lst_ap2,true);

case(false,true,i_lst1)

equation

dim = listGet(i_lst1,5);

print("\n Zeros DIM \n");

print(anyString(dim));

dim1 = stringGetStringChar(dim,1);

dim2 = stringGetStringChar(dim,2);

print("\n Zeros DIM 2\n");

print(anyString(dim1));

print("\n Zeros DIM 22\n");

print(anyString(dim2));

str::i_lst2=i_lst1;

i_lst3 = listDelete(i_lst2,0);

i_lst4 = listDelete(i_lst3,0);

i_lst5 = listDelete(i_lst4,0);

str2::i_lst6 = i_lst5;

lst_ap = {"matrix",dim1,dim2};

lst_ap1 = listAppend(lst_ap,{str});

lst_ap2 = listAppend(lst_ap1,{"Real"});

then (lst_ap2,true);

case(false,false,i_lst1)

equation

i_lst2 = ident_typelst(i_lst1);

i_lst3 = listAppend({"Scalar"},{"1"});

i_lst4 = listAppend(i_lst3,{"1"});

i_lst5 = listAppend(i_lst4,i_lst2);

then (i_lst5,false);

end matchcontinue;

end ary_fnc;

public function ary_dims

input list<String> lst;

output String dim;

algorithm

dim := matchcontinue(lst)

local

186

list<String> lst1,lst2;

String ident;

case(lst1)

equation

lst2 = listReverse(lst1);

ident = listGet(lst2,1);

then ident;

end matchcontinue;

end ary_dims;

public function chk_type

input Boolean vet;

input Boolean mtr;

input Boolean cln_vet;

input list<String> i_lst;

output list<String> o_lst;

output Boolean ary_scl;

algorithm

(o_lst,ary_scl) := matchcontinue(vet,mtr,cln_vet,i_lst)

local

list<String> i_lst1, i_lst2, i_lst3, i_lst4, i_lst5, o_lst1, upd_lst,

upd_lst2, upd_lst3, upd_lst4;

String ident,dim, dim2, dim5, fident;

Integer dim_length, total_length, dim4, dim3, dim0;

Boolean zeros, ones, zos;

case(true,false,false,i_lst1)

equation

fident::upd_lst=i_lst1;

upd_lst2 = listDelete(upd_lst,0);

upd_lst3 = listAppend({"Real"},upd_lst2);

upd_lst4 = listAppend({fident},upd_lst3);

total_length = listLength(i_lst1);

dim_length = total_length - 3;

dim = intString(dim_length);

i_lst2 = ident_typelst(upd_lst4);

i_lst3 = listAppend({"vector"},{"1"});

i_lst4 = listAppend(i_lst3,{dim});

i_lst5 = listAppend(i_lst4,i_lst2);

then (i_lst5,true);

case(false,true,false,i_lst1)

equation

print("\n MATRIX MATRIX \n");

print(anyString(i_lst1));

fident::upd_lst=i_lst1;

upd_lst2 = listDelete(upd_lst,0);

upd_lst3 = listAppend({"Real"},upd_lst2);

upd_lst4 = listAppend({fident},upd_lst3);

print("\n MATRIX MATRIX 1\n");

print(anyString(upd_lst4));

total_length = listLength(i_lst1);

dim_length = total_length - 3;

dim = intString(dim_length);

dim2 = ary_dims(i_lst1);

dim3 = stringInt(dim2);

dim0 = stringInt(dim);

dim4 = realInt(dim0/dim3);

dim5 = intString(dim4);

187

print("\n MATRIX MATRIX 2 \n");

print(anyString(dim2));

i_lst2 = ident_typelst(upd_lst4);

i_lst3 = listAppend({"matrix"},{dim2});

i_lst4 = listAppend(i_lst3,{dim5});

i_lst5 = listAppend(i_lst4,i_lst2);

print("\n MATRIX MATRIX 3 \n");

print(anyString(i_lst5));

then (i_lst5,true);

case(false,false,true,i_lst1)

equation

fident::upd_lst=i_lst1;

upd_lst2 = listDelete(upd_lst,0);

upd_lst3 = listAppend({"Real"},upd_lst2);

upd_lst4 = listAppend({fident},upd_lst3);

total_length = listLength(i_lst1);

dim_length = total_length - 3;

dim = intString(dim_length);

i_lst2 = ident_typelst(upd_lst4);

i_lst3 = listAppend({"column_vector"},{dim});

i_lst4 = listAppend(i_lst3,{"1"});

i_lst5 = listAppend(i_lst4,i_lst2);

then (i_lst5,true);

case(false,false,false,i_lst1)

equation

print("\n Zeros Zeros Zeros \n");

print(anyString(i_lst1));

zeros = listMember("zeros",i_lst1);

ones = listMember("ones",i_lst1);

(i_lst4,zos) = ary_fnc(zeros,ones,i_lst1);

then (i_lst4,zos);

end matchcontinue;

end chk_type;

public function scl_ary

input list<String> i_lst;

output list<String> o_lst;

output Boolean ary_scl;

algorithm

(o_lst,ary_scl) := matchcontinue(i_lst)

local

list<String> i_lst1, ary_scl_lst;

Boolean vet,mtr,clm_vet,ary_scl1;

case(i_lst1)

equation

vet = listMember("vector",i_lst1);

mtr = listMember("matrix",i_lst1);

clm_vet = listMember("column_vector",i_lst1);

(ary_scl_lst,ary_scl1) = chk_type(vet,mtr,clm_vet,i_lst1);

then (ary_scl_lst,ary_scl1);

case({})

then ({},false);

end matchcontinue;

end scl_ary;

public function merge_lst

input list<String> scl_ary_lst;

188

input list<String> ident_type;

input list<String> ret_type;

input Boolean ary_scl;

output list<String> merg_lst;

algorithm

merg_lst := matchcontinue(scl_ary_lst,ident_type,ret_type,ary_scl)

local

list<String> add_scl, add_scl1 ,merg_lst1,

scl_ary_lst1,ident_type1,ret_type1;

case(scl_ary_lst1,ident_type1,ret_type1,true)

equation

merg_lst1 = listAppend(scl_ary_lst1,ident_type1);

then merg_lst1;

case(scl_ary_lst1,ident_type1,ret_type1,false)

equation

// add_scl = listAppend({"Scalar"},{"1"});

// add_scl1 = listAppend(add_scl,ret_type1);

merg_lst1 = listAppend(ret_type1,ident_type1);

then merg_lst1;

end matchcontinue;

end merge_lst;

public function chk_vet_mtx

input list<String> typ;

output Boolean tf11;

output Boolean tf22;

output Boolean tf33;

output Boolean tf44;

output Boolean tf55;

algorithm

(tf11,tf22,tf33,tf44,tf55) := matchcontinue(typ)

local

list<String> typ1;

Boolean tf1,tf2,tf3,tf4,tf5;

case(typ1)

equation

tf1 = listMember("vector",typ1);

tf2 = listMember("matrix",typ1);

tf3 = listMember("column_vector",typ1);

tf4 = listMember("zeros",typ1);

tf5 = listMember("ones",typ1);

then (tf1,tf2,tf3,tf4,tf5);

end matchcontinue;

end chk_vet_mtx;

public function chk_string

input String ident1;

input String ident2;

output Boolean tf;

algorithm

tf := matchcontinue(ident1,ident2)

local

String ident3,ident4;

Boolean chk2;

case("vector",ident4)

then false;

case("matrix",ident4)

189

then false;

case("column_vector",ident4)

then false;

case("Scalar",ident4)

then false;

case("Integer",ident4)

then false;

case("Real",ident4)

then false;

case(ident3,ident4)

equation

chk2 = stringEqual(ident3,ident4);

then chk2;

end matchcontinue;

end chk_string;

public function chk_mat_vet_cvet

input String ident3;

input String ident4;

input String ident5;

output list<String> lst;

algorithm

lst := matchcontinue(ident3,ident4,ident5)

local

String ident6,ident7,ident8;

list<String> lst2, lst3, lst4;

case("matrix",ident6,ident7)

equation

print("\n MATRIX 123123 \n");

lst2 = listAppend({"matrix"},{ident7});

lst3 = listAppend(lst2,{ident6});

then lst3;

case(ident6,ident7,ident8)

equation

print("\n OTHERs 0 \n");

print(anyString(ident6));

print("\n OTHERs 1 \n");

print(anyString(ident7));

print("\n OTHERs 2 \n");

print(anyString(ident8));

lst2 = listAppend({ident6},{ident8});

lst3 = listAppend(lst2,{ident7});

print("\n OTHERs 3 \n");

print(anyString(lst3));

then lst3;

end matchcontinue;

end chk_mat_vet_cvet;

public function upd_scl_ary4

input list<String> ident_type;

input String ident;

input list<String> ident_lst;

input list<String> prv_lst;

input list<String> nxt_lst;

input Boolean tf;

output list<String> ful_info;

output Boolean tfo;

190

algorithm

(ful_info,tfo) :=

matchcontinue(ident_type,ident,ident_lst,prv_lst,nxt_lst,tf)

local

list<String> ful2, ident_type1, ful_lst, prv_lst1, prv_upt, prv_upt2,

prv_lst2, prv_lst3, nxt_lst1, ident_lst1, ident_lst2, ident_lst3, ident_lst4,

ident_lst5, ful_info1, ful;

String ident1,ident2, ident3, ident4, ident5;

Boolean tf1;

Integer lgt;

case({},ident2,ident_lst1,prv_lst1,nxt_lst1,false)

equation

// print("\n upd_scl_ary4 false \n");

then (prv_lst1,false);

case(ident1::ident_type1,ident2,ident_lst1,prv_lst1,nxt_lst1,false)

equation

// print("\n upd_scl_ary4 \n");

// print(anyString(ident1));

// print("\n upd_scl_ary41 \n");

// print(anyString(ident_type1));

// print("\n upd_scl_ary42 \n");

// print(anyString(ident2));

// print("\n upd_scl_ary43 \n");

// print(anyString(ident_lst1));

tf1 = chk_string(ident1,ident2);

ident_lst2 = listAppend(ident_lst1,{ident1});

ful_info1 =

upd_scl_ary4(ident_type1,ident2,ident_lst2,prv_lst1,nxt_lst1,tf1);

then (ful_info1,tf1);

case(ident_type1,ident2,ident_lst1,prv_lst1,nxt_lst1,true)

equation

/* print("\n upd_scl_ary 00 \n");

print(anyString(ident_lst1));

print("\n upd_scl_ary 01 \n");

print(anyString(prv_lst1));

*/ ident_lst3 = listReverse(ident_lst1);

// prv_lst2 = listReverse(prv_lst1);

lgt = listLength(prv_lst1);

prv_lst3 = listDelete(prv_lst1,lgt-1);

/* print("\n upd_scl_ary 1 \n");

print(anyString(prv_lst3));

print("\n upd_scl_ary 2 \n");

print(anyString(nxt_lst1));

print("\n upd_scl_ary 3 \n");

print(anyString(ident_lst3));

print("\n upd_scl_ary 4 \n");

print(anyString(ident2));

print("\n upd_scl_ary 5 \n");

print(anyString(ident_type1));

print("\n upd_scl_ary 6 \n");

print(anyString(ident_lst1));

*/ ident3 = listGet(ident_lst3,2);

ident4 = listGet(ident_lst3,3);

ident5 = listGet(ident_lst3,4);

ful2 = chk_mat_vet_cvet(ident5,ident3,ident4);

print("\n upd_scl_ary 01010 \n");

191

print(anyString(ful2));

// ful = listAppend({ident5},{ident3});

// ful2 = listAppend(ful,{ident4});

prv_upt = listAppend(prv_lst3,ful2);

prv_upt2 = listAppend(prv_upt,{ident2});

ful_lst = listAppend(prv_upt2,nxt_lst1);

//ful_info1 = listAppend(ful_lst,{ident2});

print("\n upd_scl_ary prv_upt2 \n");

print(anyString(ful2));

print("\n upd_scl_ary ful_info1 \n");

print(anyString(ful_lst));

//ful_info1 = upd_scl_ary3(ident_lst1, nxt_lst1,prv_upt2);

then (prv_upt2,true);

end matchcontinue;

end upd_scl_ary4;

public function update_prv

input String ident;

input list<String> identi;

input Boolean tf1;

output list<String> idento;

algorithm

idento := matchcontinue(ident,identi,tf1)

local

list<String> idento1, identi1;

String ident1;

case(ident1,identi1,false)

equation

idento1 = listAppend(identi1,{ident});

then idento1;

case(ident1,identi1,true)

then identi1;

end matchcontinue;

end update_prv;

public function upd_scl_ary3

input list<String> ident_type;

input list<String> u_type;

input list<String> ident_lst;

input Boolean tf;

output list<String> ful_info;

algorithm

ful_info := matchcontinue(ident_type, u_type, ident_lst,tf)

local

list<String> ident_type1, u_type1, ful_info1, ful_info2, ful_info3,

ful_info4, ident_lst1, ident_lst2;

String ident;

Boolean tf1;

case(ident_type1,{},ident_lst1,tf1)

equation

// print("\n upd_scl_ary3 blank \n");

then {};

case(ident_type1,ident::u_type1,ident_lst1,tf1)

equation

/* print("\n upd_scl_ary30 return \n");

print(anyString(ident_type1));

print("\n upd_scl_ary31 \n");

192

print(anyString(u_type1));

print("\n upd_scl_ary32 \n");

print(anyString(ident_lst1));

*/ ident_lst2 = update_prv(ident,ident_lst1,tf1);

// print("\n upd_scl_ary33 \n");

// print(anyString(ident_lst2));

ful_info1 = upd_scl_ary4(ident_type1,ident,{},ident_lst2,u_type1,false);

// print("\n upd_scl_ary34 \n");

// print(anyString(ful_info1));

ful_info2 = upd_scl_ary3(ident_type1,u_type1,ful_info1,tf1);

ful_info3 = rtn_sgl(ful_info1,ful_info2);

// ful_info3 = listAppend(ful_info1,ful_info2);

// print("\n upd_scl_ary35 \n");

// print(anyString(ful_info3));

then ful_info3;

case({},u_type1,ident_lst1,tf1)

then {};

end matchcontinue;

end upd_scl_ary3;

public function chk_ful_info

input list<String> ful_info;

input list<String> scl_ary_lst;

output list<String> ful_info_o;

algorithm

ful_info_o := matchcontinue(ful_info, scl_ary_lst)

local

list<String> scl_ary_lst1, ful_info1;

case({}, scl_ary_lst1)

then scl_ary_lst1;

case(ful_info1, scl_ary_lst1)

then ful_info1;

end matchcontinue;

end chk_ful_info;

public function upd_scl_ary2

input Boolean tf;

input list<String> scl_ary_lst;

input list<String> ident_type;

input list<String> u_type;

output list<String> ful_info;

algorithm

ful_info := matchcontinue(tf,scl_ary_lst,ident_type,u_type)

local

list<String> scl_ary_lst1,ident_type1,u_type1, u_type2, u_type3,

ful_info1, ful_info2;

String ident, ident1;

case(true,scl_ary_lst1,ident_type1,u_type1)

then scl_ary_lst1;

case(false,scl_ary_lst1,{},u_type1)

then scl_ary_lst1;

case(false,scl_ary_lst1,ident_type1,u_type1)

equation

// print("\n upd_scl_ary2 \n");

ful_info1 = upd_scl_ary3(ident_type1,u_type1,{},false);

ful_info2 = chk_ful_info(ful_info1,scl_ary_lst1);

// u_type3 = listAppend(scl_ary_lst1,ful_info1);

193

then ful_info2;

end matchcontinue;

end upd_scl_ary2;

public function chk_bool

input Boolean tf1;

input Boolean tf2;

input Boolean tf3;

input Boolean tf4;

input Boolean tf5;

output Boolean tf6;

algorithm

tf6 := matchcontinue(tf1,tf2,tf3,tf4,tf5)

case(true,false,false,false,false)

then true;

case(false,true,false,false,false)

then true;

case(false,false,true,false,false)

then true;

case(false,false,false,true,false)

then true;

case(false,false,false,false,true)

then true;

case(false,false,false,false,false)

then false;

end matchcontinue;

end chk_bool;

public function upd_scl_ary

input list<String> scl_ary_lst;

input list<String> ident_type;

input list<String> u_type;

output list<String> ful_info;

algorithm

ful_info := matchcontinue(scl_ary_lst,ident_type,u_type)

local

list<String> scl_ary_lst1,ident_type1,u_type1, ful_info1, u_type2;

Boolean tf1, tf2, tf3, tf4,tf5,tf6;

case(scl_ary_lst1,ident_type1,u_type1)

equation

(tf1,tf2,tf3,tf4,tf5) = chk_vet_mtx(u_type1);

tf6 = chk_bool(tf1,tf2,tf3,tf4,tf5);

ful_info1 = upd_scl_ary2(tf6,scl_ary_lst1,ident_type1,u_type1);

then ful_info1;

end matchcontinue;

end upd_scl_ary;

/*

public function update_string

input String identi;

output list<String> idento;

algorithm

idento := matchcontinue(identi)

local

String ident1;

list<String> ident_upd;

case("Unknown")

194

equation

ident_upd = listAppend({"Unknown,0"},{"Unknown"});

then ident_upd;

case(ident1)

equation

ident_upd = {ident1};

then {};

end matchcontinue;

end update_string;

public function ret_dim

input String ident;

output String dim;

output String ary_scl;

algorithm

(dim,ary_scl) := matchcontinue(ident)

local

String ident1,dim1,ary_scl1;

case(ident1)

end ret_dim;

public function update_unknown

input list<String> ful_info;

input list<String> prv0;

output list<String> ful_info_o;

algorithm

ful_info_o := matchcontinue(ful_info,prv0)

local

list<String> prv, prv_lst, prv_lst1 ,ful_info1, ful_info_o1, ful_lst,

ful_lst1;

String ident,dim,ary_scl;

case({},{})

then {};

case(ident::ful_info1,prv)

equation

print("\n update_unknown \n");

print(anyString(ident));

listMember("vector");

(ary_scl,dim) = ret_dim(ident);

// prv_lst = listAppend({ident},prv);

// ful_info_o1 = update_string(ident);

// prv_lst1 = listAppend(prv_lst,ful_info_o1);

// ful_lst = update_unknown(ful_info1,prv_lst1);

// ful_lst1 = listAppend(prv_lst1,ful_lst);

then ful_lst;

end matchcontinue;

end update_unknown;

*/

public function get_dim1

input String ident;

input list<String> idtypes;

output list<String> dim;

output Boolean tf;

algorithm

(dim,tf) := matchcontinue(ident,idtypes)

195

local

list<String> idtypes1, idtypes2, dim3;

String dim1, dim2;

case("vector",idtypes1)

equation

print("\n GET DIM Vector \n");

print(anyString(idtypes1));

dim1 = listGet(idtypes1,2);

dim3 = listAppend({"1"},{dim1});

then (dim3,true);

case("matrix",idtypes1)

equation

print("\n GET DIM Matrix \n");

print(anyString(idtypes1));

dim1 = listGet(idtypes1,1);

dim2 = listGet(idtypes1,2);

dim3 = listAppend({dim1},{dim2});

then (dim3,true);

case("column_vector",idtypes1)

equation

print("\n GET DIM Column Vector \n");

print(anyString(idtypes1));

dim1 = listGet(idtypes1,1);

dim3 = listAppend({dim1},{"1"});

then (dim3,true);

case(dim2,idtypes1)

then ({},false);

end matchcontinue;

end get_dim1;

public function get_dimlst

input list<String> idtypes;

input Boolean tf;

output list<String> idtypeso;

algorithm

idtypeso := matchcontinue(idtypes,tf)

local

String ident;

list<String> dim, idtypes1, dim_lst, dim_lst1;

Boolean tf1;

case({},false)

then {};

case({},true)

then {};

case(idtypes1,true)

then {};

case(ident::idtypes1,false)

equation

(dim,tf1) = get_dim1(ident,idtypes1);

dim_lst = get_dimlst(idtypes1,tf1);

dim_lst1 = listAppend(dim,dim_lst);

then dim_lst1;

end matchcontinue;

end get_dimlst;

public function get_dim

input Boolean vec;

196

input Boolean mtx;

input Boolean cvec;

input Boolean emp;

input list<String> idtypes;

output list<String> dim;

algorithm

dim := matchcontinue(vec,mtx,cvec,emp,idtypes)

local

list<String> idtypes1, dim1,dim2, dim3;

case(true,false,false,false,idtypes1)

equation

dim1 = get_dimlst(idtypes,false);

dim2 = listAppend({"vector"},dim1);

then dim2;

case(true,false,false,true,idtypes1)

equation

dim1 = get_dimlst(idtypes,false);

dim2 = listAppend({"vector"},dim1);

then dim2;

case(false,true,false,false,idtypes1)

equation

dim1 = get_dimlst(idtypes,false);

dim2 = listAppend({"matrix"},dim1);

then dim2;

case(false,true,false,true,idtypes1)

equation

dim1 = get_dimlst(idtypes,false);

dim2 = listAppend({"matrix"},dim1);

then dim2;

case(false,false,true,false,idtypes1)

equation

dim1 = get_dimlst(idtypes,false);

dim2 = listAppend({"column_vector"},dim1);

then dim2;

case(false,false,true,true,idtypes1)

equation

dim1 = get_dimlst(idtypes,false);

dim2 = listAppend({"column_vector"},dim1);

then dim2;

case(false,false,false,false,idtypes1)

equation

dim2 = listAppend({"Scalar"},{"1"});

dim3 = listAppend(dim2,{"1"});

then dim3;

case(false,false,false,true,idtypes1)

equation

dim2 = listAppend({"Scalar"},{"1"});

dim3 = listAppend(dim2,{"1"});

then dim3;

end matchcontinue;

end get_dim;

public function get_dim_ary

input list<String> u_type;

output list<String> dim_out;

algorithm

dim_out := matchcontinue(u_type)

197

local

list<String> u_type1, dim;

Boolean vec, mtx, cvec, emp;

case({})

then {};

case(u_type1)

equation

print("\n Print List \n");

print(anyString(u_type1));

emp = listMember("empty",u_type1);

vec = listMember("vector",u_type1);

mtx = listMember("matrix",u_type1);

cvec = listMember("column_vector",u_type1);

dim = get_dim(vec,mtx,cvec,emp,u_type1);

then dim;

end matchcontinue;

end get_dim_ary;

public function chk_index2

input Boolean emp;

input Boolean vec;

input Boolean mat;

input Boolean cvec;

input list<String> ful_info;

output list<String> ful_info_o;

algorithm

ful_info_o := matchcontinue(emp,vec,mat,cvec,ful_info)

local

list<String> ful_info1, f2, f3, f4, f5, f6, f7, f8, ful_info2;

String ident, ident1;

case(true,false,false,false,ful_info1)

equation

ident = listGet(ful_info,1);

ident1 = listGet(ful_info,2);

f2 = listDelete(ful_info1,0);

f3 = listDelete(f2,0);

f4 = listDelete(f3,0);

f5 = listDelete(f4,0);

f6 = listAppend({ident},{ident1});

f7 = listAppend(f6,{"Scalar"});

f8 = listAppend(f7,{"1"});

ful_info2 = listAppend(f8,f5);

then ful_info2;

case(true,true,false,false,ful_info1)

then ful_info1;

case(false,true,false,false,ful_info1)

then ful_info1;

case(true,false,true,false,ful_info1)

then ful_info1;

case(false,false,true,false,ful_info1)

then ful_info1;

case(true,false,false,true,ful_info1)

then ful_info1;

case(false,false,false,true,ful_info1)

then ful_info1;

case(false,false,false,false,ful_info1)

then ful_info1;

198

end matchcontinue;

end chk_index2;

/*

public function convert

input String string;

input list<String> prv_lst;

output list<String> nxt_lst;

algorithm

nxt_lst := matchcontinue(string,prv_lst)

local

case("empty",prv_lst)

equation

then {};

end matchcontinue;

end convert;

public function convert_idx_subscp

input list<String> ful_info;

output list<String> cov_lst;

algorithm

cov_lst := matchcontinue(ful_info)

local

list<String> ful_info1,prv_lst, prv_lst1;

String string;

case(string::ful_info1,prv_lst)

equation

prv_lst1 = listAppend(prv_lst,{string});

convert(string,prv_lst1);

then

end matchcontinue;

end convert_idx_subscp;

*/

public function chk_length

input Integer lth;

input list<String> ful_info;

output list<String> ful_info_o;

algorithm

ful_info_o := matchcontinue(lth,ful_info)

local

list<String> cov_lst, ful_info1, ful_info2, ful_info3, ful_info4,

ful_info5, ful_info6, ful_info9;

Integer lth1;

Boolean emp,vec,mat,cvec;

case(4,ful_info1)

then ful_info1;

case(lth1,ful_info1)

equation

ful_info9 = ful_info1;

print("\n FALSE EMPTY \n");

print(anyString(ful_info1));

// cov_lst = convert_idx_subscp(ful_info1);

ful_info2 = listDelete(ful_info1,0);

ful_info3 = listDelete(ful_info2,0);

ful_info4 = listDelete(ful_info3,0);

199

ful_info5 = listDelete(ful_info4,0);

emp = listMember("empty",ful_info5);

vec = listMember("vector",ful_info5);

mat = listMember("matrix",ful_info5);

cvec = listMember("column_vector",ful_info5);

ful_info6 = chk_index2(emp,vec,mat,cvec,ful_info9);

print("\n FALSE EMPTY 1\n");

print(anyString(ful_info6));

then ful_info6;

end matchcontinue;

end chk_length;

public function chk_key_string2

input String ident0;

input String ident;

input list<String> nxt_lst;

output list<String> nxt_lst0;

output list<String> new_lst0;

algorithm

(nxt_lst0,new_lst0) := matchcontinue(ident0,ident,nxt_lst)

local

String ident1,dim1,dim2,dim3,dim4,dim5,ident2;

list<String> nxt_lst1, nxt_lst2, nxt_lst3, nxt_lst4, nxt_lst5, nxt_lst6,

new_lst, new_lst1, new_lst2;

case("empty",ident2,nxt_lst1)

equation

print("\n empty list \n");

print(anyString(nxt_lst1));

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"Scalar","1",dim3,dim4,dim5};

new_lst1 = listAppend(new_lst,{"1"});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

// new_lst2 = listAppend(new_lst1,nxt_lst3);

then (nxt_lst6,new_lst);

case("ARYIDENT0",ident2,nxt_lst1)

equation

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"Scalar","1",dim3,dim4,dim5};

new_lst1 = listAppend(new_lst,{"1"});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

// new_lst2 = listAppend(new_lst1,nxt_lst3);

then (nxt_lst6,new_lst);

case("0.0x0",ident2,nxt_lst1)

equation

200

print("\n CHK KEY 0.0x0 \n");

print(anyString(nxt_lst1));

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"column_vector",dim2,dim1,dim3,dim4,dim5};

// new_lst1 = listAppend(new_lst,{dim1});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

// new_lst2 = listAppend(new_lst1,nxt_lst3);

print("\n CHK KEY 0.0x0 1\n");

print(anyString(new_lst));

then (nxt_lst6,new_lst);

case("ARYIDENT0.0x0",ident2,nxt_lst1)

equation

print("\n matrix 1x0.0x0 \n");

print(anyString(nxt_lst1));

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"vector","1",dim2,dim3,dim4,dim5};

// new_lst1 = listAppend(new_lst,{dim2});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

// print("\n CHK KEY 0.0x0 1\n");

// print(anyString(nxt_lst3));

// new_lst2 = listAppend(new_lst1,nxt_lst3);

then (nxt_lst6,new_lst);

case("1x0.0x0",ident2,nxt_lst1)

equation

print("\n matrix 1x0.0x0 \n");

print(anyString(nxt_lst1));

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"vector","1",dim2,dim3,dim4,dim5};

// new_lst1 = listAppend(new_lst,{dim2});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

// print("\n CHK KEY 0.0x0 1\n");

// print(anyString(nxt_lst3));

// new_lst2 = listAppend(new_lst1,nxt_lst3);

201

then (nxt_lst6,new_lst);

case("0.0xARYIDENT0",ident2,nxt_lst1)

equation

print("\n matrix 0.0x1x0 \n");

print(anyString(nxt_lst1));

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"column_vector",dim1,"1",dim3,dim4,dim5};

// new_lst1 = listAppend(new_lst,{"1"});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

print("\n NXT LST 0.0x1x0 \n");

print(anyString(nxt_lst6));

print("\n NXT LST 0.0x1x0 2\n");

print(anyString(new_lst));

// new_lst2 = listAppend(new_lst1,nxt_lst3);

then (nxt_lst6,new_lst);

case("0.0x1x0",ident2,nxt_lst1)

equation

print("\n matrix 0.0x1x0 \n");

print(anyString(nxt_lst1));

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"column_vector",dim1,"1",dim3,dim4,dim5};

// new_lst1 = listAppend(new_lst,{"1"});

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

print("\n NXT LST 0.0x1x0 \n");

print(anyString(nxt_lst6));

print("\n NXT LST 0.0x1x0 2\n");

print(anyString(new_lst));

// new_lst2 = listAppend(new_lst1,nxt_lst3);

then (nxt_lst6,new_lst);

case("1x1x0",ident2,nxt_lst1)

equation

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"Scalar","1","1",dim3,dim4,dim5};

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

202

nxt_lst6 = listDelete(nxt_lst5,0);

print("\n matrix 0.0x0.0x0 \n");

print(anyString(new_lst));

then (nxt_lst6,new_lst);

case("ARYIDENTARYIDENT0",ident2,nxt_lst1)

equation

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"Scalar","1","1",dim3,dim4,dim5};

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

print("\n matrix 0.0x0.0x0 \n");

print(anyString(new_lst));

then (nxt_lst6,new_lst);

case("0.0x0.0x0",ident2,nxt_lst1)

equation

dim1 = listGet(nxt_lst1,1);

dim2 = listGet(nxt_lst1,2);

dim3 = listGet(nxt_lst1,3);

dim4 = listGet(nxt_lst1,4);

dim5 = listGet(nxt_lst1,5);

new_lst = {"matrix",dim1,dim2,dim3,dim4,dim5};

nxt_lst2 = listDelete(nxt_lst1,0);

nxt_lst3 = listDelete(nxt_lst2,0);

nxt_lst4 = listDelete(nxt_lst3,0);

nxt_lst5 = listDelete(nxt_lst4,0);

nxt_lst6 = listDelete(nxt_lst5,0);

print("\n matrix 0.0x0.0x0 \n");

print(anyString(new_lst));

then (nxt_lst6,new_lst);

case(ident1,ident2,nxt_lst1)

equation

nxt_lst2 = listAppend({ident2},nxt_lst1);

then ({},nxt_lst2);

end matchcontinue;

end chk_key_string2;

public function chk_colon

input String ident;

input list<String> nxt_lst;

input list<String> prv_lst;

output list<String> new_lst;

output list<String> prv_lst0;

algorithm

(new_lst,prv_lst0) := matchcontinue(ident,nxt_lst,prv_lst)

local

String ident1,ident4;

list<String> prv_lst1, prv_lst2, prv_lst3, prv_lst4, nxt_lst1, nxt_lst2;

case("empty",nxt_lst1,prv_lst1)

equation

ident4 = "empty";

203

print("\n Column Vector empty \n");

(nxt_lst2,prv_lst2) = chk_key_string2("empty",ident4,nxt_lst1);

prv_lst3 = listAppend(prv_lst1,prv_lst2);

print("\n Column Vector empty 2\n");

print(anyString(prv_lst3));

then (nxt_lst2,prv_lst3);

case("ARYIDENT0",nxt_lst1,prv_lst1)

equation

ident4 = "empty";

print("\n Column Vector empty \n");

(nxt_lst2,prv_lst2) = chk_key_string2("empty",ident4,nxt_lst1);

prv_lst3 = listAppend(prv_lst1,prv_lst2);

print("\n Column Vector empty 2\n");

print(anyString(prv_lst3));

then (nxt_lst2,prv_lst3);

case("0.0x0",nxt_lst1,prv_lst1)

equation

print("\n Column Vector 0.0x0 \n");

print(anyString(prv_lst1));

prv_lst2 = listAppend(prv_lst1,{"column_vector"});

//prv_lst3 = listAppend(prv_lst1,prv_lst2);

print("\n Column Vector 0.0x0 2\n");

print(anyString(prv_lst2));

then (nxt_lst1,prv_lst2);

case(ident1,nxt_lst1,prv_lst1)

equation

(nxt_lst2,prv_lst2) = chk_key_string2(ident1,"abc",nxt_lst1);

prv_lst3 = listAppend(prv_lst2,{"column_vector"});

prv_lst4 = listAppend(prv_lst1,prv_lst3);

then (nxt_lst2,prv_lst4);

end matchcontinue;

end chk_colon;

public function chk_key_string

input String ident;

input list<String> nxt_lst;

input list<String> prv_lst;

output list<String> new_lst;

output list<String> prv_lst9;

algorithm

(new_lst,prv_lst9) := matchcontinue(ident,nxt_lst,prv_lst)

local

String ident1,ident4,ident5;

list<String> nxt_lst1, nxt_lst2, new_lst0, new_lst1, prv_lst1, prv_lst2;

case("matrix",nxt_lst1,prv_lst1)

equation

ident4 = "matrix";

ident5 = listGet(nxt_lst1,5);

print("\n listGET matrix \n");

print(anyString(nxt_lst1));

print("\n listGET matrix 1\n");

print(anyString(prv_lst1));

(nxt_lst2,new_lst1) = chk_key_string2(ident5,ident4,nxt_lst1);

prv_lst2 = listAppend(prv_lst1,new_lst1);

print("\n listGET matrix 2\n");

print(anyString(prv_lst2));

print("\n listGET matrix 2\n");

204

print(anyString(nxt_lst2));

then (nxt_lst2,prv_lst2);

case("vector",nxt_lst1,prv_lst1)

equation

ident4 = "vector";

ident1 = listGet(nxt_lst1,5);

print("\n listGET vector\n");

print(anyString(ident1));

(nxt_lst2,new_lst1) = chk_key_string2(ident1,ident4,nxt_lst1);

prv_lst2 = listAppend(prv_lst1,new_lst1);

print("\n listGET matrix 2\n");

print(anyString(prv_lst2));

print("\n listGET matrix 2\n");

print(anyString(nxt_lst2));

then (nxt_lst2,prv_lst2);

case("column_vector",nxt_lst1,prv_lst1)

equation

ident1 = listGet(nxt_lst1,5);

print("\n listGET column_vector 111 \n");

print(anyString(ident1));

print("\n listGET column_vector 112 \n");

print(anyString(prv_lst1));

(nxt_lst2,prv_lst2) = chk_colon(ident1,nxt_lst1,prv_lst1);

print("\n listGET 2\n");

print(anyString(nxt_lst2));

print("\n listGET 22\n");

print(anyString(prv_lst2));

then (nxt_lst2,prv_lst2);

case(ident1,nxt_lst1,prv_lst1)

equation

prv_lst2 = listAppend(prv_lst1,{ident1});

/* print("\n PRV LIST \n");

print(anyString(prv_lst2));

print("\n NEX LIST \n");

print(anyString(nxt_lst1));

*/ then (nxt_lst1,prv_lst2);

end matchcontinue;

end chk_key_string;

public function chk_key_arys

input list<String> ful_info;

input list<String> prv_lst;

output list<String> upd_lst;

algorithm

upd_lst := matchcontinue(ful_info,prv_lst)

local

String ident, ident1;

list<String> ful_info1, prv_lst1, prv_lst2, prv_lst3, prv_lst4, new_lst;

case({},prv_lst1)

equation

print("\n UPDATE LIST 10000000\n");

then prv_lst1;

case(ident::ful_info1,prv_lst1)

equation

print("\n PRV LIST \n");

print(anyString(prv_lst));

print("\n NXT LIST \n");

205

print(anyString(ful_info1));

(new_lst,prv_lst2) = chk_key_string(ident,ful_info1,prv_lst1);

prv_lst3 = chk_key_arys(new_lst,prv_lst2);

// prv_lst4 = listAppend(prv_lst3,prv_lst2);

/* print("\n UPDATE LIST 0\n");

print(anyString(prv_lst2));

print("\n UPDATE LIST 1\n");

print(anyString(prv_lst3));

*/ then prv_lst3;

end matchcontinue;

end chk_key_arys;

public function chk_index

input list<String> ful_info;

output list<String> ful_info_o;

algorithm

ful_info_o := matchcontinue(ful_info)

local

list<String> ful_info1, ful_info2, ful_info3;

Integer lth;

case("vector"::ful_info1)

equation

ful_info2 = listAppend({"vector"},ful_info1);

then ful_info2;

case("matrix"::ful_info1)

equation

ful_info2 = listAppend({"matrix"},ful_info1);

then ful_info2;

case("column_vector"::ful_info1)

equation

ful_info2 = listAppend({"column_vector"},ful_info1);

then ful_info2;

case("Scalar"::ful_info1)

equation

ful_info2 = listAppend({"Scalar"},ful_info1);

then ful_info2;

case(ful_info1)

equation

print("\n UPDATE LIST 0 \n");

print(anyString(ful_info1));

ful_info2 = chk_key_arys(ful_info1,{}); // find index and convert

such as vector, 4, 1, C, Real, 0.0x0 to column_vector, 4,1, C etc

print("\n UPDATE LIST 1 \n");

print(anyString(ful_info2));

lth = listLength(ful_info2);

ful_info3 = chk_length(lth,ful_info2);

then ful_info3;

end matchcontinue;

end chk_index;

public function make_real

input Integer lth;

output list<String> ret_rel;

algorithm

ret_rel := matchcontinue(lth)

local

list<String> ret_rel1;

206

Integer lth1;

case(lth1)

then {"Real"};

end matchcontinue;

end make_real;

public function make_real_lst

input Integer lth;

output list<String> rel_lst;

algorithm

rel_lst := matchcontinue(lth)

local

list<String> rel_lst1,rel_lst2, rel_lst3;

Integer lth1;

case(0)

then {};

case(lth1)

equation

rel_lst1 = make_real(lth1);

rel_lst2 = make_real_lst(lth1-1);

rel_lst3 = listAppend(rel_lst1,rel_lst2);

then rel_lst3;

end matchcontinue;

end make_real_lst;

public function chk_ary_lst

input Boolean chk;

input Boolean chk1;

input Boolean chk2;

input list<String> ident_lst;

output list<String> upd_lst;

algorithm

upd_lst := matchcontinue(chk,chk1,chk2,ident_lst)

local

list<String> ident_lst1, rel_lst, rel_lst2;

String ident;

Integer lth;

case(true,false,false,ident::ident_lst1)

equation

lth = listLength(ident_lst1);

rel_lst = make_real_lst(lth);

rel_lst2 = listAppend({ident},rel_lst);

then rel_lst2;

case(false,true,false,ident::ident_lst1)

equation

lth = listLength(ident_lst1);

rel_lst = make_real_lst(lth);

rel_lst2 = listAppend({ident},rel_lst);

then rel_lst2;

case(false,false,true,ident::ident_lst1)

equation

lth = listLength(ident_lst1);

rel_lst = make_real_lst(lth);

rel_lst2 = listAppend({ident},rel_lst);

then rel_lst2;

case(false,false,false,ident_lst1)

then ident_lst1;

207

end matchcontinue;

end chk_ary_lst;

public function cov_num_to_real

input list<String> ident_lst;

output list<String> upd_lst;

algorithm

upd_lst := matchcontinue(ident_lst)

local

list<String> ident_lst1, ident_lst2, upd_lst1, upd_lst2, upd_lst3;

String ident, ident1;

Boolean chk, chk1, chk2;

case(ident::ident_lst1)

equation

ident1::ident_lst2 = ident_lst1;

chk = listMember("vector",ident_lst2);

chk1 = listMember("matrix",ident_lst2);

chk2 = listMember("column_vector",ident_lst2);

upd_lst1 = chk_ary_lst(chk,chk1,chk2,ident_lst2);

upd_lst2 = listAppend({ident1},upd_lst1);

upd_lst3 = listAppend({ident},upd_lst2);

then upd_lst3;

end matchcontinue;

end cov_num_to_real;

public function sep_statement

input String d_type;

input list<String> sep_lst0;

input list<String> ident_type;

input Boolean chk_1st;

output list<String> o_stmt;

output list<String> o_stmt2;

output Boolean o_chk_1st;

algorithm

(o_stmt,o_stmt2,o_chk_1st) := matchcontinue(d_type,sep_lst0,

ident_type,chk_1st)

local

String d_type1;

Boolean chk_1st1,ary_scl;

list<String> ident_type0, dim_ary1, upd_unk, ful_info, ful_info1,

scl_ary_lst, d_type2,d_type3, sep_lst, ret_type, ret_type2, ret_type3,

ident_type1, ident_type2, ident_type3,u_type, u_type2, upd_lst;

case("nStatement", {}, ident_type1,chk_1st1)

then ({},ident_type1,chk_1st1);

case("nStatement", sep_lst, ident_type1,chk_1st1)

equation

ret_type = rem_nStatement(sep_lst);

print("\n sep nStatement 0 \n");

print(anyString(ret_type));

ident_type0 = cov_num_to_real(ret_type);

print("\n sep nStatement 00 \n");

print(anyString(ident_type0));

(scl_ary_lst,ary_scl) = scl_ary(ret_type); // ret_type

print("\n sep nStatement 01 \n");

print(anyString(scl_ary_lst));

print("\n sep nStatement 1 \n");

208

print(anyString(ident_type1));

(u_type,chk_1st1) = update_typelst(ret_type,ident_type1,chk_1st1);

//ident_type0 replaces ret_type

print("\n sep nStatement 2 \n");

print(anyString(u_type));

ful_info = upd_scl_ary(scl_ary_lst,ident_type1,u_type);

print("\n sep nStatement 22 \n");

print(anyString(ful_info));

ful_info1 = chk_index(ful_info);

print("\n sep nStatement 2220 \n");

print(anyString(ful_info1));

dim_ary1 = get_dim_ary(ful_info1);

print("\n sep nStatement 2221 \n");

print(anyString(dim_ary1));

u_type2 = chk_emp(u_type,ret_type); //ident_type0 replaces ret_type

// upd_lst = split_lst(u_type,{},{});

print("\n sep nStatement 21 \n");

print(anyString(u_type2));

ret_type2 = ident_typelst(u_type2);

print("\n sep nStatement 3 \n");

print(anyString(ret_type2));

ret_type3 = listAppend(dim_ary1,ret_type2);

ident_type2 = merge_lst(scl_ary_lst,ident_type1,ret_type3,ary_scl);

// ident_type2 = listAppend(ident_type1,ret_type2);

print("\n sep nStatement 4 \n");

print(anyString(ident_type2));

then ({},ident_type2,chk_1st1);

case(d_type1, sep_lst, ident_type1,chk_1st1)

equation

// print("\n sep_statement d_type1\n");

d_type2 = listAppend(sep_lst,{d_type1});

then (d_type2,ident_type1,chk_1st1);

end matchcontinue;

end sep_statement;

public function ret_lst_final

input list<String> ident_type;

input list<String> o_type_lst;

output list<String> o_lst;

algorithm

o_lst :=matchcontinue(ident_type,o_type_lst)

local

list<String> lst1, lst2;

case(lst1,{})

then lst1;

case({},lst2)

then lst2;

case(lst1,lst2)

then lst2;

end matchcontinue;

end ret_lst_final;

public function assign_type

input list<String> d_type_lst;

input list<String> sep_lst;

input list<String> ident_type;

input Boolean chk_1st;

209

input list<String> ident_type33;

output list<String> f_type_lst;

output list<String> ident_type13;

algorithm

(f_type_lst,ident_type13) := matchcontinue

(d_type_lst,sep_lst,ident_type,chk_1st,ident_type33)

local

list<String> final_lst, d_type_lst1, o_type_lst1, d_type_lst2,

o_type_lst2, o_type_lst3, sep_lst1, ident_type1, ident_type2, ident_type3,

ident_type4;

String d_type;

Boolean chk_1st1;

case(d_type::d_type_lst1,sep_lst1,ident_type1,chk_1st1,ident_type3)

equation

// print("\n assign_type \n");

(o_type_lst1,ident_type2,chk_1st1) = sep_statement(d_type,

sep_lst1,ident_type1,chk_1st1);

(d_type_lst2,ident_type4) =

assign_type(d_type_lst1,o_type_lst1,ident_type2,chk_1st1,ident_type3);

o_type_lst2 = listAppend(o_type_lst1,d_type_lst2);

final_lst = ret_lst_final(ident_type2,ident_type4);

print("\n Print Assign_Type 0 \n");

print(anyString(ident_type2));

/* print("\n Print Assign_Type 1 \n");

print(anyString(o_type_lst2));

print("\n Print Assign_Type 2 \n");

print(anyString(d_type_lst2));

*/ then (ident_type2,final_lst);

case({},sep_lst1,ident_type1,chk_1st1,ident_type3)

then ({},ident_type3);

end matchcontinue;

end assign_type;

public function Scl

input Boolean tf;

output String scl;

algorithm

scl := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end Scl;

public function Vec

input Boolean tf;

output String vec;

algorithm

vec := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end Vec;

210

public function Mat

input Boolean tf;

output String mat;

algorithm

mat := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end Mat;

public function CVec

input Boolean tf;

output String cvec;

algorithm

cvec := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end CVec;

public function Int

input Boolean tf;

output String int;

algorithm

int := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end Int;

public function Re

input Boolean tf;

output String re;

algorithm

re := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end Re;

public function Chk

input Boolean tf;

output String str;

algorithm

str := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

211

end matchcontinue;

end Chk;

public function Chk2

input Boolean tf;

output String str;

algorithm

str := matchcontinue(tf)

case(true)

then "1";

case(false)

then "0";

end matchcontinue;

end Chk2;

public function chk_number

input Boolean scl;

input Boolean vec;

input Boolean mat;

input Boolean cvec;

output Boolean tf;

algorithm

(tf) := matchcontinue(scl,vec,mat,cvec)

local

Boolean scl1,vec1,mat1,cvec1, tf1;

list<String> lst_ident1, bools, bools1, bools2, lst_ident2;

String s,v,m,c;

case(scl1,vec1,mat1,cvec1)

equation

s = Scl(scl1);

v = Vec(vec1);

m = Mat(mat1);

c = CVec(cvec1);

bools = listAppend({s},{v});

bools1 = listAppend({m},{c});

bools2 = listAppend(bools,bools1);

tf1 = listMember("1",bools2);

then tf1;

end matchcontinue;

end chk_number;

public function deleteDup3

input Boolean chk;

input String ident;

input list<String> prv_lst;

input list<String> nxt_lst;

output list<String> prv_upt;

output list<String> nxt_upt;

algorithm

(prv_upt,nxt_upt) := matchcontinue(chk,ident,prv_lst,nxt_lst)

local

list<String> prv_lst1, nxt_lst1, prv_lst2, prv_lst3, prv_lst4, prv_lst5,

nxt_lst2, nxt_lst3;

String ident2;

case(true,ident2,prv_lst1,nxt_lst1)

equation

print("\n TEST DeleteDup 0\n");

212

print(anyString(prv_lst1));

print("\n TEST DeleteDup 00\n");

print(anyString(nxt_lst1));

// prv_lst2 = listReverse(prv_lst1);

prv_lst2 = listDelete(prv_lst1,0);

prv_lst3 = listDelete(prv_lst2,0);

// prv_lst5 = listReverse(prv_lst4);

nxt_lst2 = listDelete(nxt_lst1,0);

// nxt_lst3 = listReverse(nxt_lst2);

print("\n TEST DeleteDup 000\n");

print(anyString(prv_lst3));

print("\n TEST DeleteDup 0000\n");

print(anyString(nxt_lst2));

// nxt_lst3 = listAppend({ident2},nxt_lst2);

then (prv_lst3,nxt_lst2);

case(false,ident2,prv_lst1,nxt_lst1)

equation

print("\n TEST DeleteDup 1\n");

prv_lst2 = listAppend({ident2},prv_lst1);

then (prv_lst2,nxt_lst1);

end matchcontinue;

end deleteDup3;

public function deleteDup2

input String ident;

input list<String> lst_ident;

input list<String> prv_lst;

output list<String> prv_lsto;

output list<String> nxt_lsto;

algorithm

(prv_lsto,nxt_lsto) := matchcontinue(ident,lst_ident,prv_lst)

local

String ident1,ident2;

list<String> lst_ident1, lst_ident2, prv_lst1, prv_lst2, prv_lst3,

prv_lst4, prv_lst5, nxt_lst2, nxt_lst3;

Boolean chk;

case(ident1,{},prv_lst1)

then (prv_lst1,{});

case(ident1,ident2::lst_ident1,prv_lst1)

equation

print("\n TEST DeleteDup2 22\n");

print(anyString(ident1));

print("\n TEST DeleteDup2 222 \n");

print(anyString(ident2));

print("\n TEST DeleteDup2 2222 \n");

print(anyString(prv_lst1));

print("\n TEST DeleteDup2 22222 \n");

print(anyString(lst_ident1));

//prv_lst2 = listAppend({ident2},prv_lst1);

chk = stringEqual(ident1,ident2);

(prv_lst3,nxt_lst2) = deleteDup3(chk,ident2,prv_lst1,lst_ident1);

print("\n TEST DeleteDup2 22222 \n");

print(anyString(prv_lst3));

print("\n TEST DeleteDup2 222222 \n");

print(anyString(nxt_lst2));

// prv_lst4 = listReverse(prv_lst3);

(prv_lst4,nxt_lst3) = deleteDup2(ident1,nxt_lst2,prv_lst3);

213

then (prv_lst4,nxt_lst3);

end matchcontinue;

end deleteDup2;

public function deleteDup

input Boolean chk;

input String ident;

input list<String> lst_ident;

output list<String> prv_lst;

output list<String> nxt_lst;

algorithm

(prv_lst,nxt_lst) := matchcontinue(chk,ident,lst_ident)

local

Boolean chk1;

String ident1;

list<String> lst_ident1, prv_lst1, prv_lst2, nxt_lst1;

case(true,ident1,lst_ident1)

equation

(prv_lst1,nxt_lst1) = deleteDup2(ident1,lst_ident1,{});

print("\n TEST DeleteDup 11 \n");

print(anyString(prv_lst1));

prv_lst2 = listReverse(prv_lst1);

print("\n TEST DeleteDup 111 \n");

print(anyString(nxt_lst1));

then (prv_lst2,nxt_lst1);

case(false,ident1,lst_ident1)

then ({},lst_ident1);

end matchcontinue;

end deleteDup;

public function rmvDuplicate4

input Boolean chk;

input Boolean chk1;

input String ident;

input list<String> lst_ident;

input Boolean num;

output list<String> prv_lst;

output list<String> nxt_lst;

algorithm

(prv_lst,nxt_lst) := matchcontinue(chk,chk1,ident,lst_ident,num)

local

list<String> lst_ident2, lst_ident3, prv_lst1, nxt_lst1;

String ident1;

Boolean chk2;

case(true,true,ident1,lst_ident2,false)

equation

print("\n TEST DeleteDup 0\n");

//lst_ident3 = listAppend({ident1},lst_ident2);

then ({},lst_ident2);

case(false,true,ident1,lst_ident2,false)

equation

print("\n TEST DeleteDup 1\n");

//lst_ident3 = listAppend({ident1},lst_ident2);

then ({},lst_ident2);

case(false,false,ident1,lst_ident2,true)

equation

print("\n TEST DeleteDup 2\n");

214

//lst_ident3 = listAppend({ident1},lst_ident2);

then ({},lst_ident2);

case(false,false,ident1,lst_ident2,false)

equation

print("\n TEST DeleteDup 3\n");

print(anyString(lst_ident2));

print("\n TEST DeleteDup 33\n");

print(anyString(ident1));

chk2 = listMember(ident1,lst_ident);

(prv_lst1,nxt_lst1) = deleteDup(chk2,ident1,lst_ident2);

print("\n TEST DeleteDup 333\n");

print(anyString(prv_lst1));

print("\n TEST DeleteDup 3333\n");

print(anyString(nxt_lst1));

print("\n TEST DeleteDup 33333\n");

print(anyString(ident1));

then (prv_lst1,nxt_lst1);

end matchcontinue;

end rmvDuplicate4;

public function chk_lsts

input list<String> prv_lst;

input list<String> nxt_lst;

input list<String> prv;

input Boolean chk;

output list<String> lst;

algorithm

lst := matchcontinue(prv_lst, nxt_lst, prv,chk)

local

list<String> prv_lst0, prv_lst1, nxt_lst1, nxt_lst2, ful_lst;

Boolean chk1;

case(prv_lst1,{},prv_lst0,chk1)

equation

print("\n CHK LIST 0 \n");

print(anyString(prv_lst1));

print("\n CHK LIST 1 \n");

print(anyString(prv_lst0));

nxt_lst1 = rmvDuplicate3(prv_lst1,chk1,prv_lst0);

print("\n CHK LIST 2 \n");

print(anyString(nxt_lst1));

then nxt_lst1;

case(prv_lst1,nxt_lst1,prv_lst0,chk1)

equation

nxt_lst2 = rmvDuplicate3(nxt_lst1,chk1,prv_lst0);

ful_lst = listAppend(prv_lst1, nxt_lst2);

then ful_lst;

end matchcontinue;

end chk_lsts;

public function rmvDuplicate3

input list<String> all;

input Boolean num;

input list<String> prv;

output list<String> out;

algorithm

out := matchcontinue(all,num,prv)

local

215

list<String> lst_numbers, ful_lst, ful_lst2, lst_ident, lst_ident1,

lst_ident2, lst_ident3, intre_lst, all_bools,prv_lst0,prv_lst9, prv_lst1,

nxt_lst1, nxt_lst2;

String ident, ints, rel, str_chk, str_chk2;

Boolean num_bool,num1,chk,chk1,chk2,scl,vec,mat,cvec,int, re;

case(ident::lst_ident,num1,prv_lst0)

equation

lst_numbers = {"0","1","2","3","4","5","6","7","8","9"};

num_bool = listMember(ident,lst_numbers);

prv_lst9 = listAppend({ident},prv_lst0);

print("\n All IDENTs 0 \n");

print(anyString(ident));

print("\n All IDENTs 1 \n");

print(anyString(lst_ident));

print("\n All IDENTs 2 \n");

print(anyString(prv_lst9));

scl = stringEqual("Scalar",ident);

vec = stringEqual("vector",ident);

mat = stringEqual("matrix",ident);

cvec = stringEqual("column_vector",ident);

chk = chk_number(scl,vec,mat,cvec);

int = stringEqual("Integer",ident);

re = stringEqual("Real",ident);

ints = Int(int);

rel = Re(re);

intre_lst = listAppend({ints},{rel});

chk1 = listMember("1",intre_lst);

str_chk = Chk(chk1);

str_chk2 = Chk2(chk);

all_bools = listAppend({str_chk},{str_chk2});

chk2 = listMember("1",all_bools);

print("\n TEST 0 \n");

print(anyString(chk));

print("\n TEST 1 \n");

print(anyString(chk2));

print("\n TEST 2 \n");

print(anyString(num1));

(prv_lst1,nxt_lst1) =

rmvDuplicate4(chk,chk2,ident,lst_ident,num_bool);

print("\n TEST 3 \n");

print(anyString(prv_lst1));

print("\n TEST 4 \n");

print(anyString(nxt_lst1));

ful_lst = chk_lsts(prv_lst1,nxt_lst1,prv_lst9,chk);

print("\n TEST 50 \n");

print(anyString(ful_lst));

ful_lst2 = listAppend(prv_lst9,ful_lst);

print("\n TEST 51 \n");

print(anyString(ful_lst2));

then ful_lst;

case({},num1,prv_lst0)

then (prv_lst0);

end matchcontinue;

end rmvDuplicate3;

public function transform_start

"special function to translate module to package in MetaModelica"

216

input AbsynMat.Start inprogram;

output Absyn.Program outprogram;

algorithm

outprogram:=matchcontinue(inprogram)

local

AbsynMat.User_Function uf,uf2,uf3;

AbsynMat.Separator sep;

Absyn.Program ast;

Absyn.Class class1;

list<Absyn.Class> class2, class3, sub_class, sub_class1;

String fname, no_fname;

list<String> upd_lst, all_idents, ident_type4, final_types, f_call,

f_call1, f_call2, fnc_hdl_ident, idents_rhs, d_type_lst, io_lst, f_call,

fnc_hdl_ident, no_ident;

Absyn.Info info;

Absyn.ClassDef cd;

list<Absyn.ClassPart> cp, no_cp;

list<AbsynMat.Statement> stmt_lst;

list<AbsynMat.Expression> exp, exp2, exp3;

Boolean fnc_hdl;

list<Absyn.ElementItem> in_out;

case(AbsynMat.START(uf,sep,stmt_lst))

equation

(no_fname, no_cp,d_type_lst) = user_function({}, uf, {}, {}, {}, {});

print("\n User Function Function Handle \n");

print(anyString(uf));

print("\n All Ident List \n");

print(anyString(d_type_lst));

(final_types,ident_type4) = assign_type(d_type_lst,{},{},true,{});

//type evaluation

print("\n All Ident List 1 \n");

print(anyString(final_types));

print("\n All Ident List 2 \n");

print(anyString(ident_type4));

upd_lst = rmvDuplicate3(ident_type4,false,{});

all_idents = listReverse(upd_lst);

print("\n All Ident List 3 \n");

print(anyString(all_idents));

exp = Fnc_Handle.user_function(uf);

exp2 = Fnc_Handle.sub_function(stmt_lst);

exp3 = listAppend(exp,exp2);

print("\n transform_start AbsynMat.START(uf,sep,{}) \n");

print(anyString(exp3));

(sub_class1,f_call1,fnc_hdl_ident) =

Fnc_Handle.fnc_hdl_to_sub_fnc_lst(exp3); // converting anonymous function to

sub function

(sub_class,f_call) = sub_function(stmt_lst,f_call1,fnc_hdl_ident); //

sub function

print("\n Fnc_Handle START 2 \n");

print(anyString(f_call1));

f_call2 = listAppend(f_call,f_call1);

(fname, cp, no_ident) =

user_function({},uf,{},f_call2,fnc_hdl_ident,all_idents);

cd = Absyn.PARTS({},{},cp,{},NONE());

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

217

class1 =

Absyn.CLASS(fname,false,false,false,Absyn.R_FUNCTION(Absyn.FR_NORMAL_FUNCTION

(Absyn.NO_PURITY())),cd,info);

class2 = listAppend(class1::{},sub_class);

class3 = listAppend(class2,sub_class1);

then

Absyn.PROGRAM(class3,Absyn.TOP(),Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

// case(ast) then ast;

end matchcontinue;

end transform_start;

public function transform

"Main function which starts the rml translation to MEtaModelica AST , get

the RML AST as input and passes the

AST to different functions to get the MEtaModelica AST"

input AbsynMat.Start inprogram;

output Absyn.Program outprogram;

algorithm

outprogram:= matchcontinue(inprogram)

local

AbsynMat.Start ast;

Absyn.Program astNew;

case(ast)

equation

print("\n transform");

astNew=transform_start(ast);

then

astNew;

end matchcontinue;

end transform;

end Translate;

218

FunctionHandle.mo

encapsulated package Fnc_Handle

import Absyn;

import AbsynMat;

import System;

import Mat_Builtin;

import Mod_Builtin;

import Translate;

public function transform_in_put

input String in_put;

output list<Absyn.ElementItem> eli_lst;

algorithm

eli_lst := matchcontinue(in_put)

local

String in_put1;

list<Absyn.ElementItem> eli_lst1;

Absyn.Info info;

Absyn.ElementAttributes attr;

Absyn.TypeSpec tSpec;

list<Absyn.ElementItem> eli;

list<Absyn.ComponentItem> com;

case(in_put1)

equation

attr = Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),

Absyn.INPUT(),{});

tSpec = Absyn.TPATH(Absyn.IDENT("Real"),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(in_put1,{},NONE()),NONE(),NONE())::{};

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

eli_lst1 =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

then eli_lst1;

end matchcontinue;

end transform_in_put;

public function transform_in_put_lst

input list<String> in_lst;

output list<Absyn.ElementItem> eli_lst;

algorithm

eli_lst := matchcontinue(in_lst)

local

list<String> in_lst1;

String in_put;

list<Absyn.ElementItem> eli_lst1, eli_lst2, eli_lst3;

219

case(in_put::in_lst1)

equation

print("\n NEW TEST \n");

eli_lst1 = transform_in_put(in_put);

eli_lst2 = transform_in_put_lst(in_lst1);

eli_lst3 = listAppend(eli_lst1,eli_lst2);

then eli_lst3;

case({})

then {};

end matchcontinue;

end transform_in_put_lst;

public function rmvKeywords

input String in_put;

output list<String> out_put;

algorithm

out_put := matchcontinue(in_put)

local

list<String> in_put1;

String in_string;

case("Integer")

then {};

case("Real")

then {};

case(in_string)

equation

in_put1 = in_string::{};

then in_put1;

end matchcontinue;

end rmvKeywords;

public function rmvKeywords_lst

input list<String> in_lst;

output list<String> out_lst;

algorithm

out_lst := matchcontinue(in_lst)

local

list<String> in_lst1, in_lst2, in_lst3, in_put1;

String in_put;

case(in_put::in_lst1)

equation

in_put1 = rmvKeywords(in_put);

in_lst2 = rmvKeywords_lst(in_lst1);

in_lst3 = listAppend(in_put1,in_lst2);

then in_lst3;

case({})

then {};

end matchcontinue;

end rmvKeywords_lst;

public function fnc_hdl_to_sub_fnc

input AbsynMat.Expression exp_lst;

output list<Absyn.Class> mod_class;

output list<String> f_call;

output list<String> fnc_hdl_ident;

algorithm

220

(mod_class,f_call,fnc_hdl_ident) := matchcontinue(exp_lst)

local

AbsynMat.Expression exp1;

Absyn.Exp mod_exp1,mod_exp2;

list<AbsynMat.Argument> arg_lst;

AbsynMat.Operator op;

String fname, out_put;

list<String> ary1, in_ident, f_call1, in_ident1, fnc_hdl_ident1,

fnc_hdl_ident2;

Absyn.ClassDef cd;

list<Absyn.ClassPart> cp;

Absyn.ClassPart cls_stmt, in_cp;

list<Absyn.Class> class1;

Absyn.Info info;

Absyn.ElementAttributes attr;

Absyn.TypeSpec tSpec;

list<Absyn.ElementItem> eli_out_lst, eli_in_lst, eli_in_out;

list<Absyn.ComponentItem> com;

list<Absyn.AlgorithmItem> alg_exp;

case (AbsynMat.ASSIGN_OP(arg_lst,op,exp1))

equation

print("\n Fnc_Handle AbsynMat.ASSIGN_OP \n");

print(anyString(arg_lst));

({mod_exp1},{fname}) = Translate.argument_lst(arg_lst,false);

print("\n Fnc_Handle AbsynMat.ASSIGN_OP 1\n");

print(anyString(exp1));

print("\n Fnc_Handle AbsynMat.ASSIGN_OP 2\n");

// print(anyString(f_call1));

(mod_exp2,ary1) = Translate.expression(exp1,{},{});

print("\n TEST TEST TEST TEST \n");

print(anyString(fname));

print("\n TEST TEST TEST TEST 2\n");

print(anyString(mod_exp2));

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

alg_exp =

Absyn.ALGORITHMITEM(Absyn.ALG_ASSIGN(mod_exp1,mod_exp2),NONE(),info)::{};

in_ident = Translate.rmvDuplicate(ary1);

in_ident1 = rmvKeywords_lst(in_ident);

print("\n TEST TEST TEST TEST 3\n");

print(anyString(in_ident1));

eli_in_lst = transform_in_put_lst(in_ident1);

info=Absyn.INFO("",false,0,0,0,0,Absyn.TIMESTAMP(System.getCurrentTime(),Syst

em.getCurrentTime()));

attr = Absyn.ATTR(false,false,Absyn.NON_PARALLEL(),Absyn.VAR(),

Absyn.OUTPUT(),{});

tSpec = Absyn.TPATH(Absyn.IDENT("Real"),NONE());

com =

Absyn.COMPONENTITEM(Absyn.COMPONENT(fname,{},NONE()),NONE(),NONE())::{};

221

eli_out_lst =

Absyn.ELEMENTITEM((Absyn.ELEMENT(false,NONE(),Absyn.NOT_INNER_OUTER(),Absyn.C

OMPONENTS(attr,tSpec,com),info,NONE())))::{};

eli_in_out = listAppend(eli_in_lst,eli_out_lst);

in_cp = Absyn.PUBLIC(eli_in_out);

cls_stmt = Absyn.ALGORITHMS(alg_exp);

cp = listAppend(in_cp::{},cls_stmt::{});

cd = Absyn.PARTS({},{},cp,{},NONE());

class1 =

Absyn.CLASS(fname,false,false,false,Absyn.R_FUNCTION(Absyn.FR_NORMAL_FUNCTION

(Absyn.NO_PURITY())),cd,info)::{};

fnc_hdl_ident2 = listAppend(fname::{},in_ident1);

then (class1,{fname},fnc_hdl_ident2);

end matchcontinue;

end fnc_hdl_to_sub_fnc;

public function fnc_hdl_to_sub_fnc_lst

input list<AbsynMat.Expression> exp_lst;

output list<Absyn.Class> mod_class;

output list<String> f_call;

output list<String> fnc_hdl_ident;

algorithm

(mod_class,f_call,fnc_hdl_ident) := matchcontinue(exp_lst)

local

list<AbsynMat.Expression> exp_lst1;

AbsynMat.Expression exp;

list<Absyn.Class> mod_class1, mod_class2, mod_class3;

list<String> f_call1, f_call2, f_call3, fnc_hdl_ident1, fnc_hdl_ident2,

fnc_hdl_ident3;

case(exp::exp_lst1)

equation

(mod_class1,f_call1,fnc_hdl_ident1) = fnc_hdl_to_sub_fnc(exp);

(mod_class2,f_call2,fnc_hdl_ident2) = fnc_hdl_to_sub_fnc_lst(exp_lst1);

f_call3 = listAppend(f_call1,f_call2);

mod_class3 = listAppend(mod_class1,mod_class2);

fnc_hdl_ident3 = listAppend(fnc_hdl_ident1,fnc_hdl_ident2);

then

(mod_class3,f_call3,fnc_hdl_ident3);

case({})

then ({},{},{});

end matchcontinue;

end fnc_hdl_to_sub_fnc_lst;

public function anon_fcn_handle

input AbsynMat.Expression exp;

output Boolean tf;

algorithm

tf := matchcontinue(exp)

local

AbsynMat.Expression exp1;

list<AbsynMat.Parameter> prm_lst;

AbsynMat.Statement stmt;

case(AbsynMat.ANON_FCN_HANDLE(prm_lst,stmt))

then true;

case(exp1)

then false;

222

end matchcontinue;

end anon_fcn_handle;

public function stmt_fnc_handle

input Boolean fnc_hdl_tf;

input Option<AbsynMat.Expression> exp;

output list<AbsynMat.Expression> exp1_o;

algorithm

(exp1_o) := matchcontinue (fnc_hdl_tf,exp)

local

list<AbsynMat.Expression> exp2;

Option<AbsynMat.Expression> exp1;

AbsynMat.Expression exp3;

case(true,exp1)

equation

SOME(exp3) = exp1;

exp2 = exp3::{};

then (exp2);

case(false,exp1)

then ({});

case(false,NONE())

then ({});

end matchcontinue;

end stmt_fnc_handle;

public function in_var

input String in_ident;

input Boolean tf1;

output list<String> in_idt;

output Option<AbsynMat.Expression> exp_out;

algorithm

(in_idt,exp_out) := matchcontinue(in_ident,tf1)

local

String in_ident1, in_ident2;

Option<AbsynMat.Expression> exp;

AbsynMat.Expression exp1;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op;

case(in_ident1,true)

equation

print("\n in_ident1,true,false \n");

in_ident2 = in_ident1 + "trans";

arg1 =

{AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP({AbsynMat.IDENTIFIER(in_ident2)}

))};

op = AbsynMat.EQ();

exp1 = AbsynMat.FINISH_COLON_EXP({AbsynMat.IDENTIFIER(in_ident1)});

exp = SOME(AbsynMat.ASSIGN_OP(arg1,op,exp1)); //here we add new

for loop statment e.g. jtrans = j;

then ({in_ident1},exp);

case(in_ident1,false)

equation

print("\n in_ident1,false,false \n");

then ({},NONE());

end matchcontinue;

end in_var;

223

public function in_add

input list<String> ary;

input Option<String> in_ident;

output list<String> in_idt;

output Option<AbsynMat.Expression> exp;

algorithm

(in_idt,exp) := matchcontinue(ary,in_ident)

local

list<String> ary1, in_idt1;

Option<String> in_ident1;

String in_ident2;

Boolean tf1;

Option<AbsynMat.Expression> exp1;

case(ary1,in_ident1)

equation

print("\n in_right ary1\n");

print(anyString(ary1));

print("\n in_right in_ident1\n");

print(anyString(in_ident1));

SOME(in_ident2) = in_ident1;

tf1 = listMember(in_ident2, ary1);

print("\n in_right in_left truefalse \n");

print(anyString(tf1));

(in_idt1,exp1) = in_var(in_ident2,tf1);

then (in_idt1,exp1);

case(ary1,NONE())

then ({},NONE());

end matchcontinue;

end in_add;

public function in_left_var

input Option<String> in_ident;

input list<String> ident;

input Boolean tf1;

output list<AbsynMat.Argument> arg;

algorithm

(arg) := matchcontinue(in_ident,ident,tf1)

local

Option<String> in_ident1;

String in_ident2, in_ident3, ident3;

list<String> ident2;

Option<AbsynMat.Expression> exp;

AbsynMat.Expression exp1;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op;

case(in_ident1,ident2,true)

equation

print("\n LOOP FOR LOOP LEFT \n");

SOME(in_ident2) = in_ident1;

in_ident3 = in_ident2 + "trans";

arg1 =

{AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP({AbsynMat.IDENTIFIER(in_ident3)}

))};

then (arg1);

case(in_ident1,ident2,false)

equation

print("\n LOOP FOR LOOP LEFT 2 \n");

224

{ident3} = ident2;

arg1 =

{AbsynMat.ARGUMENT(AbsynMat.FINISH_COLON_EXP({AbsynMat.IDENTIFIER(ident3)}))}

;

then (arg1);

end matchcontinue;

end in_left_var;

public function in_left

input list<String> ary;

input Option<String> in_ident;

output list<AbsynMat.Argument> arg;

algorithm

(arg) := matchcontinue(ary,in_ident)

local

list<String> ary1;

Option<String> in_ident1;

String in_ident2;

Boolean tf1;

list<AbsynMat.Argument> arg1;

case(ary1,in_ident1)

equation

print("\n in_left ary1\n");

print(anyString(ary1));

print("\n in_left in_ident1\n");

print(anyString(in_ident1));

SOME(in_ident2) = in_ident1;

tf1 = listMember(in_ident2, ary1);

print("\n in_right in_left truefalse \n");

print(anyString(tf1));

print("\n in_right in_left truefalse 1\n");

print(anyString(in_ident1));

print("\n in_right in_left truefalse 2\n");

print(anyString(ary1));

(arg1) = in_left_var(in_ident1,ary1,tf1);

then (arg1);

case(ary1,NONE())

then ({});

end matchcontinue;

end in_left;

public function var_append

input String ident;

input Boolean tf;

output AbsynMat.Expression exp_o;

algorithm

exp_o := matchcontinue(ident,tf)

local

String ident1;

case(ident1,true)

equation

then AbsynMat.IDENTIFIER(ident1+"trans");

case(ident1,false)

equation

then AbsynMat.IDENTIFIER(ident1);

end matchcontinue;

end var_append;

225

public function var_rpl

input Option<String> ident;

input AbsynMat.Expression exp;

output AbsynMat.Expression exp_o;

algorithm

exp_o := matchcontinue(ident,exp)

local

Boolean tf;

Integer i;

Real r;

String idt;

Option<String> ident1;

AbsynMat.Ident ident2;

AbsynMat.Expression exp1,exp2, exp_o1, exp_o2;

list<AbsynMat.Expression> exp_lst, exp_lst2, exp_lst3;

AbsynMat.Operator op;

case (ident1, AbsynMat.INT(i))

then AbsynMat.INT(i);

case (ident1, AbsynMat.NUM(r))

then AbsynMat.NUM(r);

case (ident1, AbsynMat.IDENTIFIER(ident2))

equation

SOME(idt) = ident1;

tf = stringEqual(idt,ident2);

exp1 = var_append(ident2,tf);

then exp1;

case (ident1, AbsynMat.BINARY_EXPRESSION(exp1,exp2,op))

equation

print("\n expression var_rpl \n");

print(anyString(exp1));

print("\n expression var_rpl 2\n");

print(anyString(exp2));

exp_o1 = var_rpl(ident1,exp1);

print("\n expression var_rpl 3\n");

print(anyString(exp_o1));

exp_o2 = var_rpl(ident1,exp2);

print("\n expression var_rpl 4\n");

print(anyString(exp_o2));

then AbsynMat.BINARY_EXPRESSION(exp_o1,exp_o2,op);

end matchcontinue;

end var_rpl;

public function var_rpl_lst

input Option<String> in_ident;

input list<AbsynMat.Expression> iexp_lst;

output list<AbsynMat.Expression> oexp_lst;

algorithm

oexp_lst := matchcontinue(in_ident,iexp_lst)

local

Option<String> in_ident1;

AbsynMat.Expression exp1,exp2;

list<AbsynMat.Expression> exp_lst, exp_lst2, exp_lst3;

case(in_ident1, exp1::exp_lst)

equation

exp2 = var_rpl(in_ident1,exp1);

print("\n expression var_rpl_lst \n");

226

print(anyString(exp_lst));

exp_lst2 = var_rpl_lst(in_ident1,exp_lst);

exp_lst3 = listAppend({exp2},exp_lst2);

then exp_lst3;

case(in_ident1,{})

then {};

case(NONE(),{})

then {};

end matchcontinue;

end var_rpl_lst;

public function in_right_var

input Option<String> in_ident;

input Boolean tf;

input AbsynMat.Expression exp;

output AbsynMat.Expression exp_o;

algorithm

(exp_o) := matchcontinue(in_ident,tf,exp)

local

Option<String> in_ident1;

AbsynMat.Expression exp1, exp2;

list<AbsynMat.Expression> exp_lst, exp_lst2;

case (in_ident1,true,AbsynMat.FINISH_COLON_EXP(exp_lst))

equation

print("\n expression in_right_var \n");

exp_lst2 = var_rpl_lst(in_ident1,exp_lst);

then AbsynMat.FINISH_COLON_EXP(exp_lst2);

end matchcontinue;

end in_right_var;

public function in_right

input list<String> ary;

input Option<String> in_ident;

input AbsynMat.Expression exp;

output AbsynMat.Expression exp_o;

algorithm

(exp_o) := matchcontinue(ary,in_ident,exp)

local

list<String> ary1, in_idt1;

Option<String> in_ident1;

String ident;

AbsynMat.Expression exp1,exp2;

Boolean tf;

case(ary1,in_ident1,exp1)

equation

print("\n expression in_right \n");

print(anyString(in_ident1));

SOME(ident) = in_ident1;

tf = listMember(ident, ary1);

print("\n expression in_right 2 \n");

print(anyString(tf));

(exp2) = in_right_var(in_ident1,tf,exp1);

then exp2;

end matchcontinue;

end in_right;

public function prf_rpl

227

input list<String> arg_ident;

input Option<String> in_ident;

input list<AbsynMat.Argument> arg;

input AbsynMat.Operator op;

input AbsynMat.Expression exp;

input Boolean bool_i;

input Boolean in_tf;

output Option<AbsynMat.Expression> exp_out;

output Option<AbsynMat.Expression> exp_out2;

output Boolean bool_o;

algorithm

(exp_out,exp_out2,bool_o) :=

matchcontinue(arg_ident,in_ident,arg,op,exp,bool_i,in_tf)

local

Option<String> in_ident1;

list<String> ary1, in_idt1, in_idt2, arg_ident1, arg_ident2;

String in_ident2, arg_ident3;

list<AbsynMat.Argument> arg1;

Boolean tf1, in_tf1, ryt_tf;

AbsynMat.Expression exp1, exp2;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op1;

Absyn.Exp exp3, exp4;

Option<AbsynMat.Expression> exp_out1, exp_out3;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op1;

case(arg_ident1,in_ident1,arg1,op1,exp1,true,true)

equation

print("\n True True \n");

(in_idt1,exp_out1) = in_add(arg_ident1,in_ident1); // check for loop

variable wheather its available at LHS e.g. j = 2 * j then generate new

statement j1 = j;;

(exp4,ary1) = Translate.expression(exp1,{},{});

(arg1) = in_left(arg_ident1,in_ident1);

(exp2) = in_right(ary1,in_ident1,exp1);

print("\n For LOOP IDENT 2 \n");

print(anyString(arg1));

exp_out3 = SOME(AbsynMat.ASSIGN_OP(arg1,op1,exp2));

print("\n Operator 1 \n");

print(anyString(op1));

print("\n For LOOP IDENT 3 \n");

print(anyString(exp_out3));

then (exp_out1,exp_out3,true);

case(arg_ident1,in_ident1,arg1,op1,exp1,true,false)

equation

print("\n True False \n");

(in_idt1,exp_out1) = in_add(arg_ident1,in_ident1); // check for loop

variable wheather its available at LHS e.g. j = 2 * j then generate new

statement j1 = j;;

(exp4,ary1) = Translate.expression(exp1,{},{});

(arg1) = in_left(arg_ident1,in_ident1);

(exp2) = in_right(ary1,in_ident1,exp1);

print("\n For LOOP IDENT 2 \n");

print(anyString(arg1));

exp_out3 = SOME(AbsynMat.ASSIGN_OP(arg1,op1,exp2));

print("\n For LOOP IDENT 3 \n");

print(anyString(exp_out3));

228

then (exp_out1,exp_out3,true);

case(arg_ident1,in_ident1,arg1,op1,exp1,false,true)

equation

print("\n False True \n");

(in_idt1,exp_out1) = in_add(arg_ident1,in_ident1); // check for loop

variable wheather its available at LHS e.g. j = 2 * j then generate new

statement j1 = j;;

(exp4,ary1) = Translate.expression(exp1,{},{});

(arg1) = in_left(arg_ident1,in_ident1);

(exp2) = in_right(ary1,in_ident1,exp1);

print("\n For LOOP IDENT 2 \n");

print(anyString(arg1));

exp_out3 = SOME(AbsynMat.ASSIGN_OP(arg1,op1,exp2));

print("\n For LOOP IDENT 3 \n");

print(anyString(exp_out3));

then (exp_out1,exp_out3,false);

case(arg_ident1,in_ident1,arg1,op1,exp1,false,false)

equation

print("\n False False \n");

exp_out3 = SOME(AbsynMat.ASSIGN_OP(arg1,op1,exp1));

print(anyString(exp_out3));

then (NONE(),exp_out3,false);

end matchcontinue;

end prf_rpl;

public function assign_operator_fhdl

input Option<AbsynMat.Expression> exp;

output Boolean fnc_hdl;

algorithm

(fnc_hdl) := matchcontinue(exp)

local

Boolean fnc_hdl_tf;

AbsynMat.Expression exp1;

Option<AbsynMat.Expression> exp2;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op;

AbsynMat.Ident ident;

case(SOME(AbsynMat.ASSIGN_OP(arg1,op,exp1)))

equation

print("\n FNC HANDLE Assign Operator \n");

fnc_hdl_tf = anon_fcn_handle(exp1); // determine whether matlab

expression is anonymous function or not

print("\n Function Handle \n");

print(anyString(fnc_hdl_tf));

then

(fnc_hdl_tf);

case(NONE())

then (false);

end matchcontinue;

end assign_operator_fhdl;

public function assign_operator

input Option<AbsynMat.Expression> exp;

input Option<String> in_ident;

input Boolean bool_i;

output Option<AbsynMat.Expression> exp_out;

output Option<AbsynMat.Expression> exp_out2;

229

output Boolean bool_o;

algorithm

(exp_out,exp_out2,bool_o) := matchcontinue (exp,in_ident,bool_i)

local

Option<String> in_ident1;

list<String> ary1, in_idt1, in_idt2, arg_ident, arg_ident2;

String in_ident2, arg_ident3;

Boolean tf1, in_tf1, ryt_tf, bool_loop1;

AbsynMat.Expression exp1, exp2;

list<AbsynMat.Argument> arg1;

AbsynMat.Operator op;

Absyn.Exp exp3, exp4;

Option<AbsynMat.Expression> exp_out1, exp_out3;

list<AbsynMat.Argument> arg1;

case(SOME(AbsynMat.ASSIGN_OP(arg1,op,exp1)),in_ident1,in_tf1)

equation

print("\n For LOOP IDENT 1 \n");

print(anyString(op));

({exp3},arg_ident) = Translate.argument_lst(arg1,false);

SOME(in_ident2) = in_ident1;

{arg_ident3} = arg_ident;

ryt_tf = stringEqual(in_ident2,arg_ident3);

(exp_out1,exp_out3,bool_loop1) =

prf_rpl(arg_ident,in_ident1,arg1,op,exp1,ryt_tf,in_tf1);

then (exp_out1,exp_out3,bool_loop1);

case(SOME(AbsynMat.ASSIGN_OP(arg1,op,exp1)),NONE(),false)

then (NONE(),NONE(),false);

case(NONE(),in_ident1,false)

then (NONE(),NONE(),false);

case(NONE(),NONE(),false)

then (NONE(),NONE(),false);

end matchcontinue;

end assign_operator;

public function stmt

input AbsynMat.Statement stmt;

input Option<String> in_ident;

input Boolean bool_i;

output list<AbsynMat.Expression> exp_lst;

output list<AbsynMat.Statement> stmt_out;

output Boolean bool_o;

algorithm

(exp_lst,stmt_out,bool_o) := matchcontinue(stmt,in_ident,bool_i)

local

Option<AbsynMat.Expression> exp, exp_out1, exp_out2;

list<AbsynMat.Expression> exp2;

Boolean fnc_hdl_tf, tf1, bool_loop, bool_loop1;

AbsynMat.Separator sep;

Option<AbsynMat.Mat_Comment> m_cmt;

Option<AbsynMat.Command> cmd;

Option<AbsynMat.Start> fnc_str;

Option<String> in_ident1;

list<String> in_idt1;

list<AbsynMat.Statement> stmt_out1, stmt_out2, stmt_out3;

case(AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

,in_ident1,bool_loop)

230

equation

print("\n fnc_handle stmt

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

1\n");

print(anyString(bool_loop));

print("\n fnc_handle stmt

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep) 1.1

\n");

print(anyString(exp));

fnc_hdl_tf = assign_operator_fhdl(exp);

print("\n fnc_handle stmt

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

1.1.1\n");

print(anyString(in_ident1));

(exp2) = stmt_fnc_handle(fnc_hdl_tf,exp);

print("\n fnc_handle stmt

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(cmd,exp,fnc_str,m_cmt),sep)

1.1.1\n");

print(anyString(exp2));

(exp_out1,exp_out2,bool_loop1) =

assign_operator(exp,in_ident1,bool_loop);

stmt_out1 =

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(NONE(),exp_out1,NONE(),NONE()),A

bsynMat.SEMI_COLON())::{};

stmt_out2 =

AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(NONE(),exp_out2,NONE(),NONE()),A

bsynMat.SEMI_COLON())::{};

stmt_out3 = listAppend(stmt_out1,stmt_out2);

print("\n IN LOOP Varaible \n");

print(anyString(exp2));

print("\n IN LOOP Varaible 2 \n");

print(anyString(stmt_out3));

then

(exp2,stmt_out3,bool_loop1);

end matchcontinue;

end stmt;

public function stmt_lst

input list<AbsynMat.Statement> stmtlst;

input Option<String> in_ident;

input Boolean bool_i;

output list<AbsynMat.Expression> exp_lst;

output list<AbsynMat.Statement> stmtlst_out;

output Boolean bool_o;

algorithm

(exp_lst,stmtlst_out,bool_o) := matchcontinue(stmtlst, in_ident, bool_i)

local

list<AbsynMat.Statement> stmt_out1, stmt_out2, stmtlst1, stmtlst_out1;

AbsynMat.Statement stmt1;

Boolean fnc_hdl_tf, fnc_hdl_tf1, bool_loop, bool_loop1, bool_loop2;

list<AbsynMat.Expression> exp_lst1, exp_lst2, exp_lst3;

Option<String> in_ident1;

Option<AbsynMat.Expression> exp_out1;

case(stmt1::stmtlst1, in_ident1, bool_loop)

equation

print("\n Function Handle stmt \n");

231

print(anyString(stmt1));

(exp_lst1,stmt_out1,bool_loop1) = stmt(stmt1,in_ident1,bool_loop);

(exp_lst2,stmt_out2,bool_loop2) = stmt_lst(stmtlst1, in_ident1,

bool_loop1);

exp_lst3 = listAppend(exp_lst1,exp_lst2);

stmtlst_out1 = listAppend(stmt_out1,stmt_out2);

then

(exp_lst3,stmtlst_out1,bool_loop2);

case({},in_ident1,bool_loop)

then ({},{},bool_loop);

case({},NONE(),bool_loop)

then ({},{},bool_loop);

end matchcontinue;

end stmt_lst;

public function user_function

input AbsynMat.User_Function uf;

output list<AbsynMat.Expression> exp_lst;

algorithm

(exp_lst) := matchcontinue(uf)

local

AbsynMat.User_Function usr_fnc;

list<AbsynMat.Parameter> prm;

Option<AbsynMat.Separator> sep;

list<AbsynMat.Statement> sstmt_lst, sstmt_lst2;

AbsynMat.Statement stmt_2nd;

list<AbsynMat.Decl_Elt> ret;

Absyn.Ident fname, fname1;

list<AbsynMat.Expression> exp_lst1;

list<String> ept;

case(AbsynMat.START_FUNCTION(fname,prm,sep,sstmt_lst,stmt_2nd))

equation

print("\n user_function

AbsynMat.START_FUNCTION(fname,prm,sep,stmt,stmt_2nd) \n");

print(anyString(sstmt_lst));

(exp_lst1,sstmt_lst2,false) = stmt_lst(sstmt_lst,NONE(),false);

then

(exp_lst1);

case(AbsynMat.FINISH_FUNCTION(ret,usr_fnc))

equation

print("\n user_function AbsynMat.FINISH_FUNCTION(ret,usr_fnc2) \n");

(exp_lst1) = user_function(usr_fnc);

print("\n Fnc Handle User Function \n");

print(anyString(exp_lst1));

then

(exp_lst1);

end matchcontinue;

end user_function;

public function sub_function

input list<AbsynMat.Statement> stmt_lst;

output list<AbsynMat.Expression> exp_lst1;

algorithm

(exp_lst1) := matchcontinue(stmt_lst)

local

AbsynMat.User_Function usr_fnc;

232

AbsynMat.Separator sep;

String fname;

list<AbsynMat.Statement> stmt_lst2;

list<AbsynMat.Expression> exp_lst2, exp_lst3, exp_lst4;

case(AbsynMat.STATEMENT_APPEND(AbsynMat.STATEMENT(NONE(),NONE(),SOME(AbsynMat

.START(usr_fnc,sep,stmt_lst2)),NONE()),sep)::{})

equation

(exp_lst2) = sub_function(stmt_lst2);

(exp_lst3) = user_function(usr_fnc);

exp_lst4 = listAppend(exp_lst2,exp_lst3);

then (exp_lst4);

case({})

then ({});

end matchcontinue;

end sub_function;

end Fnc_Handle;

233

Mat_Builtin.mo

encapsulated package Mat_Builtin

public function builtIn

input String fnc_name;

output Boolean tf;

algorithm

tf := matchcontinue (fnc_name)

local

String fnc_name1;

Boolean tf1;

// Matrices and Arrays

//Array Creation and Concatenation

case("accumarray") then true; // Construct array with accumulation

case("blkdiag") then true; // Construct block diagonal matrix

from input arguments

case("diag") then true; // Diagonal matrices and diagonals of matrix

case("eye") then true; // Identity matrix

case("false") then true; // Logical 0 (false)

case("freqspace") then true; // Frequency spacing for frequency

response

case("linspace") then true; // Generate linearly spaced vectors

case("logspace") then true; // Generate logarithmically

spaced vectors

case("meshgrid") then true; // Rectangular grid in 2-D and 3-D

space

case("ndgrid") then true; // Rectangular grid in N-D space

case("ones") then true; // Create array of all ones

case("rand") then true; // Uniformly distributed pseudorandom

numbers

case("true") then true; // Logical 1 (true)

case("zeros") then true; // Create array of all zeros

case("cat") then true; // Concatenate arrays along

specified dimension

case("horzcat") then true; // Concatenate arrays

horizontally

case("vertcat") then true; // Concatenate arrays vertically

// Indexing

case("ind2sub") then true; // Subscripts from linear

index

case("sub2ind") then true; // Convert subscripts to

linear indices

// Array Dimensions

case("length") then true; // Length of vector or largest

array dimension

case("ndims") then true; // Number of array dimensions

case("numel") then true; // Number of array elements

case("size") then true; // Array dimensions

case("height") then true; // Number of table rows

case("width") then true; // Number of table variables

case("iscolumn") then true; // Determine whether input is

column vector

234

case("isempty") then true; // Determine whether array is

empty

case("ismatrix") then true; // Determine whether input is

matrix

case("isrow") then true; // Determine whether input is

row vector

case("isscalar") then true; // Determine whether input is

scalar

case("isvector") then true; // Determine whether input is

vector

// Sorting and Reshaping Arrays

case("circshift") then true; // Shift array circularly

case("ctranspose") then true; // Complex conjugate transpose

case("diag") then true; // Diagonal matrices and diagonals of

matrix

case("flip") then true; // Flip order of elements

case("flipdim") then true; // Flip array along specified

dimension

case("fliplr") then true; // Flip matrix left to right

case("flipud") then true; // Flip matrix up to down

case("ipermute") then true; // Inverse permute dimensions of

N-D array

case("permute") then true; // Rearrange dimensions of N-D

array

case("repmat") then true; // Replicate and tile array

case("reshape") then true; // Reshape array

case("rot90") then true; // Rotate matrix 90 degrees

case("shiftdim") then true; // Shift dimensions

case("issorted") then true; // Determine whether set

elements are in sorted order

case("sort") then true; // Sort array elements in ascending or

descending order

case("sortrows") then true; // Sort rows in ascending order

case("squeeze") then true; // Remove singleton dimensions

case("transpose") then true; // Transpose

case("vectorize") then true; // Vectorize expression

// Operators and Elementary Operations

// Arithmetic

case("plus") then true; // Addition

case("uplus") then true; // Unary plus

case("minus") then true; // Subtraction

case("uminus") then true; // Unary minus

case("times") then true; // Element-wise multiplication

case("rdivide") then true; // Right array division

case("ldivide") then true; // Left array division

case("power") then true; // Element-wise power

case("mtimes") then true; // Matrix Multiplication

case("mrdivide") then true; // Solve systems of linear

equations xA = B for x

case("mldivide") then true; // Solve systems of linear

equations Ax = B for x

case("mpower") then true; // Matrix power

case("cumprod") then true; // Cumulative product

case("cumsum") then true; // Cumulative sum

case("diff") then true; // Differences and Approximate

Derivatives

case("prod") then true; // Product of array elements

235

case("sum") then true; // Sum of array elements

case("ceil") then true; // Round toward positive infinity

case("fix") then true; // Round toward zero

case("floor") then true; // Round toward negative

infinity

case("idivide") then true; // Integer division with

rounding option

case("mod") then true; // Modulus after division

case("rem") then true; // Remainder after division

case("round") then true; // Round to nearest integer

// Relational Operations

case("eq") then true; // Determine equality

case("ge") then true; // Determine greater than or

equal to

case("gt") then true; // Determine greater than

case("le") then true; // Determine less than or equal

to

case("lt") then true; // Determine less than

case("ne") then true; // Determine inequality

case("isequal") then true; // Determine array

equality

case("isequaln") then true; // Determine array

equality, treating NaN values as equal

// Logical Operations

case("xor") then true; // Logical exclusive-OR

case("all") then true; // Determine if all array

elements are nonzero or true

case("any") then true; // Determine if any array

elements are nonzero

case("false") then true; // Logical 0 (false)

case("find") then true; // Find indices and values of

nonzero elements

case("islogical") then true; // Determine if input is

logical array

case("logical") then true; // Convert numeric values

to logicals

case("true") then true; // Logical 1 (true)

// Set Operations

case("intersect") then true; // Set intersection

of two arrays

case("ismember") then true; // Array elements

that are members of set array

case("issorted") then true; // Determine whether

set elements are in sorted order

case("setdiff") then true; // Set difference of

two arrays

case("setxor") then true; // Set exclusive OR

of two arrays

case("union") then true; // Set union of two

arrays

case("unique") then true; // Unique values in

array

case("join") then true; // Merge two tables by

matching up rows using key variables

case("innerjoin") then true; // Inner join

between two tables

236

case("outerjoin") then true; // Outer join

between two tables

// Bit-Wise Operations

case("bitand") then true; // Bit-wise AND

case("bitcmp") then true; // Bit-wise

complement

case("bitget") then true; // Get bit at

specified position

case("bitor") then true; // Bit-wise OR

case("bitset") then true; // Set bit at

specific location

case("bitshift") then true; // Shift bits

specified number of places

case("bitxor") then true; // Bit-wise XOR

case("swapbytes") then true; // Swap byte ordering

// Data Types

// Numeric Types

case("double") then true; // Convert to double precision

case("single") then true; // Convert to single precision

case("int8") then true; // Convert to 8-bit signed integer

case("int16") then true; // Convert to 16-bit signed

integer

case("int32") then true; // Convert to 32-bit signed

integer

case("int64") then true; // Convert to 64-bit signed

integer

case("uint8") then true; // Convert to 8-bit unsigned

integer

case("uint16") then true; // Convert to 16-bit unsigned

integer

case("uint32") then true; // Convert to 32-bit unsigned

integer

case("uint64") then true; // Convert to 64-bit unsigned

integer

case("cast") then true; // Cast variable to different data

type

case("typecast") then true; // Convert data types without

changing underlying data

case("isinteger") then true; // Determine if input is integer

array

case("isfloat") then true; // Determine if input is

floating-point array

case("isnumeric") then true; // Determine if input is numeric

array

case("isreal") then true; // Check if input is real array

case("isfinite") then true; // Array elements that are

finite

case("isinf") then true; // Array elements that are

infinite

case("isnan") then true; // Array elements that are NaN

case("eps") then true; // Floating-point relative accuracy

case("flintmax") then true; // Largest consecutive integer

in floating-point format

case("Inf") then true; // Infinity

case("intmax") then true; // Largest value of specified

integer type

237

case("intmin") then true; // Smallest value of specified

integer type

case("NaN") then true; // Not-a-Number

case("realmax") then true; // Largest positive floating-

point number

case("realmin") then true; // Smallest positive normalized

floating-point number

// Characters and Strings

// Create and Concatenate Strings

case("blanks") then true; // Create string of blank

characters

case("cellstr") then true; // Create cell array of strings

from character array

case("char") then true; // Convert to character array (string)

case("iscellstr") then true; // Determine whether input is

cell array of strings

case("ischar") then true; // Determine whether item is

character array

case("sprintf") then true; // Format data into string

case("strcat") then true; // Concatenate strings

horizontally

case("strjoin") then true; // Join strings in cell array

into single string

// Parse Strings

case("ischar") then true; // Determine whether item is

character array

case("isletter") then true; // Array elements that are

alphabetic letters

case("isspace") then true; // Array elements that are space

characters

case("isstrprop") then true; // Determine whether string is

of specified category

case("sscanf") then true; // Read formatted data from

string

case("strfind") then true; // Find one string within

another

case("strrep") then true; // Find and replace substring

case("strsplit") then true; // Split string at specified

delimiter

case("strtok") then true; // Selected parts of string

case("validatestring") then true; // Check validity of text

string

case("symvar") then true; // Determine symbolic variables

in expression

case("regexp") then true; // Match regular expression

(case sensitive)

case("regexpi") then true; // Match regular expression

(case insensitive)

case("regexprep") then true; // Replace string using regular

expression

case("regexptranslate") then true; // Translate string into

regular expression

// Compare Strings

case("strcmp") then true; // Compare strings with case

sensitivity

case("strcmpi") then true; // Compare strings (case

insensitive)

238

case("strncmp") then true; // Compare first n characters of

strings (case sensitive)

case("strncmpi") then true; // Compare first n characters of

strings (case insensitive)

// Change String Case, Blanks, and Justification

case("blanks") then true; // Create string of blank

characters

case("deblank") then true; // Strip trailing blanks from

end of string

case("strtrim") then true; // Remove leading and trailing

white space from string

case("lower") then true; // Convert string to lowercase

case("upper") then true; // Convert string to uppercase

case("strjust") then true; // Justify character array

// Categorical Arrays

case("categorical") then true; // Create categorical

array

case("iscategorical") then true; // Determine whether input

is categorical array

case("categories") then true; // Categories of categorical

array

case("iscategory") then true; // Test for categorical array

categories

case("isordinal") then true; // Determine whether input is

ordinal categorical array

case("isprotected") then true; // Determine whether

categories of categorical array are protected

case("addcats") then true; // Add categories to categorical

array

case("mergecats") then true; // Merge categories in

categorical array

case("removecats") then true; // Remove categories from

categorical array

case("renamecats") then true; // Rename categories in

categorical array

case("reordercats") then true; // Reorder categories in

categorical array

case("summary") then true; // Print summary of table or

categorical array

case("countcats") then true; // Count occurrences of

categorical array elements by category

case("isundefined") then true; // Find undefined elements

in categorical array

// Tables

case("table") then true; // Create table from workspace

variables

case("array2table") then true; // Convert homogeneous

array to table

case("cell2table") then true; // Convert cell array to table

case("struct2table") then true; // Convert structure array

to table

case("table2array") then true; // Convert table to

homogenous array

case("table2cell") then true; // Convert table to cell array

case("table2struct") then true; // Convert table to

structure array

case("readtable") then true; // Create table from file

239

case("writetable") then true; // Write table to file

case("istable") then true; // Determine whether input is

table

case("height") then true; // Number of table rows

case("width") then true; // Number of table variables

case("summary") then true; // Print summary of table or

categorical array

case("intersect") then true; // Set intersection of two

arrays

case("ismember") then true; // Array elements that are

members of set array

case("setdiff") then true; // Set difference of two arrays

case("setxor") then true; // Set exclusive OR of two

arrays

case("unique") then true; // Unique values in array

case("union") then true; // Set union of two arrays

case("join") then true; // Merge two tables by matching up

rows using key variables

case("innerjoin") then true; // Inner join between two tables

case("outerjoin") then true; // Outer join between two tables

case("sortrows") then true; // Sort rows in ascending order

case("stack") then true; // Stack data from multiple

variables into single variable

case("unstack") then true; // Unstack data from single

variable into multiple variables

case("ismissing") then true; // Find table elements with

missing values

case("standardizeMissing") then true; // Insert missing

value indicators into table

case("varfun") then true; // Apply function to table

variables

case("rowfun") then true; // Apply function to table rows

// Structures

case("struct") then true; // Create structure array

case("fieldnames") then true; // Field names of

structure, or public fields of object

case("getfield") then true; // Field of structure

array

case("isfield") then true; // Determine whether input

is structure array field

case("isstruct") then true; // Determine whether input

is structure array

case("orderfields") then true; // Order fields of

structure array

case("rmfield") then true; // Remove fields from

structure

case("setfield") then true; // Assign values to

structure array field

case("arrayfun") then true; // Apply function to each

element of array

case("structfun") then true; // Apply function to each

field of scalar structure

case("cell2struct") then true; // Convert cell

array to structure array

case("struct2cell") then true; // Convert structure

to cell array

// Cell Arrays

240

case("cell") then true; // Create cell array

case("cell2mat") then true; // Convert cell array to

numeric array

case("cell2struct") then true; // Convert cell

array to structure array

case("celldisp") then true; // Cell array contents

case("cellfun") then true; // Apply function to each

cell in cell array

case("cellplot") then true; // Graphically display

structure of cell array

case("cellstr") then true; // Create cell array of

strings from character array

case("iscell") then true; // Determine whether input

is cell array

case("iscellstr") then true; // Determine whether input

is cell array of strings

case("mat2cell") then true; // Convert array to cell

array with potentially different sized cells

case("num2cell") then true; // Convert array to cell

array with consistently sized cells

case("strjoin") then true; // Join strings in cell

array into single string

case("strsplit") then true; // Split string at

specified delimiter

case("struct2cell") then true; // Convert structure

to cell array

// Function Handles

case("feval") then true; // Evaluate function

case("func2str") then true; // Construct function name

string from function handle

case("str2func") then true; // Construct function

handle from function name string

case("localfunctions") then true; // Function handles

to all local functions in MATLAB file

// functions Information about function handle

// Map Containers

case("isKey") then true; // Determine if

containers.Map object contains key

case("keys") then true; // Identify keys of

containers.Map object

case("remove") then true; // Remove key-value pairs

from containers.Map object

case("values") then true; // Identify values in

containers.Map object

// Time Series

// Time Series Basics

case("append") then true; // Concatenate time series

objects in time dimension

case("get") then true; // Query timeseries object

property values

case("getdatasamplesize") then true; // Size of

data sample in timeseries object

case("getqualitydesc") then true; // Data quality

descriptions

case("getsamples") then true; // Subset of time series

samples using subscripted index array

case("plot") then true; // Plot time series

241

case("set") then true; // Set properties of timeseries

object

case("tsdata.event") then true; // Construct event

object for timeseries object

case("timeseries") then true; // Create timeseries

object

// Data Manipulation

case("addsample") then true; // Add data sample to

timeseries object

case("ctranspose") then true; // Transpose timeseries

object

case("delsample") then true; // Remove sample from

timeseries object

case("detrend") then true; // Subtract mean or best-

fit line and all NaNs from timeseries object

case("filter") then true; // Shape frequency content

of time-series

case("getabstime") then true; // Extract date-string

time vector into cell array

case("getinterpmethod") then true; // Interpolation

method for timeseries object

case("getsampleusingtime") then true; // Extract

data samples into new timeseries object

case("idealfilter") then true; // Apply ideal

(noncausal) filter to timeseries object

case("resample") then true; // Select or interpolate

timeseries data using new time vector

case("setabstime") then true; // Set times of timeseries

object as date strings

case("setinterpmethod") then true; // Set default

interpolation method for timeseries object

case("synchronize") then true; // Synchronize and

resample two timeseries objects using common time vector

case("transpose") then true; // Transpose timeseries

object

// Event Data

case("addevent") then true; // Add event to timeseries

object

case("delevent") then true; // Remove tsdata.event

objects from timeseries object

case("gettsafteratevent") then true; // New

timeseries object with samples occurring at or after event

case("gettsafterevent") then true; // New timeseries

object with samples occurring after event

case("gettsatevent") then true; // New timeseries

object with samples occurring at event

case("gettsbeforeatevent") then true; // New

timeseries object with samples occurring before or at event

case("gettsbeforeevent") then true; // New timeseries

object with samples occurring before event

case("gettsbetweenevents") then true; // New

timeseries object with samples occurring between events

// Descriptive Statistics

case("iqr") then true; // Interquartile range of

timeseries data

case("max") then true; // Maximum value of timeseries

data

242

case("mean") then true; // Mean value of timeseries data

case("median") then true; // Median value of

timeseries data

case("min") then true; // Minimum value of timeseries

data

case("std") then true; // Standard deviation of

timeseries data

case("sum") then true; // Sum of timeseries data

case("var") then true; // Variance of timeseries data

// Time Series Collections

case("get") then true; // (tscollection) Query

tscollection object property values

case("isempty") then true; // (tscollection) Determine

whether tscollection object is empty

case("length") then true; // (tscollection) Length of

time vector

case("set") then true; // (tscollection) Set properties of

tscollection object

case("size") then true; // (tscollection) Size of

tscollection object

case("tscollection") then true; // Create

tscollection object

case("addsampletocollection") then true; // Add sample

to tscollection object

case("addts") then true; // Add timeseries object

to tscollection object

case("delsamplefromcollection") then true; //

Remove sample from tscollection object

case("getabstime") then true; // (tscollection) Extract

date-string time vector into cell array

case("getsampleusingtime") then true; // (tscollection)

Extract data samples into new tscollection object

case("gettimeseriesnames") then true; // Cell array

of names of timeseries objects in tscollection object

case("horzcat") then true; // (tscollection) Horizontal

concatenation for tscollection objects

case("removets") then true; // Remove timeseries

objects from tscollection object

case("resample") then true; // (tscollection) Select or

interpolate data in tscollection using new time vector

case("setabstime") then true; // (tscollection) Set times

of tscollection object as date strings

case("settimeseriesnames") then true; // Change name

of timeseries object in tscollection

case("vertcat") then true; // (tscollection) Vertical

concatenation for tscollection objects

// Data Type Identification

case("isa") then true; // Determine if input is object

of specified class

case("iscategorical") then true; // Determine whether

input is categorical array

case("iscell") then true; // Determine whether input

is cell array

case("iscellstr") then true; // Determine whether input

is cell array of strings

case("ischar") then true; // Determine whether item

is character array

243

case("isfield") then true; // Determine whether input

is structure array field

case("isfloat") then true; // Determine if input is

floating-point array

case("ishghandle") then true; // True for Handle

Graphics object handles

case("isinteger") then true; // Determine if input is

integer array

case("isjava") then true; // Determine if input is

Java object

case("islogical") then true; // Determine if input is

logical array

case("isnumeric") then true; // Determine if input is

numeric array

case("isobject") then true; // Determine if input is

MATLAB object

case("isreal") then true; // Check if input is real

array

case("isscalar") then true; // Determine whether input

is scalar

case("isstr") then true; // Determine whether input

is character array

case("isstruct") then true; // Determine whether input

is structure array

case("istable") then true; // Determine whether input

is table

case("isvector") then true; // Determine whether input

is vector

case("class") then true; // Determine class of

object

case("validateattributes") then true; // Check

validity of array

// Data Type Conversion

case("char") then true; // Convert to character array

(string)

case("int2str") then true; // Convert integer to

string

case("mat2str") then true; // Convert matrix to

string

case("num2str") then true; // Convert number to

string

case("str2double") then true; // Convert string to

double-precision value

case("str2num") then true; // Convert string to

number

case("native2unicode") then true; // Convert numeric

bytes to Unicode character representation

case("unicode2native") then true; // Convert Unicode

character representation to numeric bytes

case("base2dec") then true; // Convert base N number

string to decimal number

case("bin2dec") then true; // Convert binary number

string to decimal number

case("dec2base") then true; // Convert decimal to base

N number in string

case("dec2bin") then true; // Convert decimal to

binary number in string

244

case("dec2hex") then true; // Convert decimal to

hexadecimal number in string

case("hex2dec") then true; // Convert hexadecimal

number string to decimal number

case("hex2num") then true; // Convert hexadecimal

number string to double-precision number

case("num2hex") then true; // Convert singles and

doubles to IEEE hexadecimal strings

case("table2array") then true; // Convert table to

homogenous array

case("table2cell") then true; // Convert table to cell

array

case("table2struct") then true; // Convert table to

structure array

case("array2table") then true; // Convert

homogeneous array to table

case("cell2table") then true; // Convert cell array to

table

case("struct2table") then true; // Convert structure

array to table

case("cell2mat") then true; // Convert cell array to

numeric array

case("cell2struct") then true; // Convert cell

array to structure array

case("cellstr") then true; // Create cell array of

strings from character array

case("mat2cell") then true; // Convert array to cell

array with potentially different sized cells

case("num2cell") then true; // Convert array to cell

array with consistently sized cells

case("struct2cell") then true; // Convert structure

to cell array

// Dates and Time

case("datenum") then true; // Convert date and time

to serial date number

case("datevec") then true; // Convert date and time

to vector of components

case("datestr") then true; // Convert date and time

to string format

case("now") then true; // Current date and time as

serial date number

case("clock") then true; // Current date and time

as date vector

case("date") then true; // Current date string

case("calendar") then true; // Calendar for specified

month

case("eomday") then true; // Last day of month

case("weekday") then true; // Day of week

case("addtodate") then true; // Modify date number by

field

case("etime") then true; // Time elapsed between

date vectors

// Mathematics

// Elementary Math

// Arithmetic

case("plus") then true; // Addition

245

case("uplus") then true; // Unary plus

case("minus") then true; // Subtraction

case("uminus") then true; // Unary minus

case("times") then true; // Element-wise

multiplication

case("rdivide") then true; // Right array division

case("ldivide") then true; // Left array division

case("power") then true; // Element-wise power

case("mtimes") then true; // Matrix Multiplication

case("mrdivide") then true; // Solve systems of linear

equations xA = B for x

case("mldivide") then true; // Solve systems of linear

equations Ax = B for x

case("mpower") then true; // Matrix power

case("cumprod") then true; // Cumulative product

case("cumsum") then true; // Cumulative sum

case("diff") then true; // Differences and Approximate

Derivatives

case("prod") then true; // Product of array elements

case("sum") then true; // Sum of array elements

case("ceil") then true; // Round toward positive

infinity

case("fix") then true; // Round toward zero

case("floor") then true; // Round toward negative

infinity

case("idivide") then true; // Integer division with

rounding option

case("mod") then true; // Modulus after division

case("rem") then true; // Remainder after division

case("round") then true; // Round to nearest

integer

// Trigonometry

case("sin") then true; // Sine of argument in radians

case("sind") then true; // Sine of argument in degrees

case("asin") then true; // Inverse sine in radians

case("asind") then true; // Inverse sine in degrees

case("sinh") then true; // Hyperbolic sine of argument

in radians

case("asinh") then true; // Inverse hyperbolic sine

case("cos") then true; // Cosine of argument in radians

case("cosd") then true; // Cosine of argument in degrees

case("acos") then true; // Inverse cosine in radians

case("acosd") then true; // Inverse cosine in

degrees

case("cosh") then true; // Hyperbolic cosine

case("acosh") then true; // Inverse hyperbolic

cosine

case("tan") then true; // Tangent of argument in

radians

case("tand") then true; // Tangent of argument in

degrees

case("atan") then true; // Inverse tangent in radians

case("atand") then true; // Inverse tangent in

degrees

case("atan2") then true; // Four-quadrant inverse

tangent

246

case("atan2d") then true; // Four-quadrant inverse

tangent in degrees

case("tanh") then true; // Hyperbolic tangent

case("atanh") then true; // Inverse hyperbolic

tangent

case("csc") then true; // Cosecant of argument in

radians

case("cscd") then true; // Cosecant of argument in

degrees

case("acsc") then true; // Inverse cosecant in radians

case("acscd") then true; // Inverse cosecant in

degrees

case("csch") then true; // Hyperbolic cosecant

case("acsch") then true; // Inverse hyperbolic

cosecant

case("sec") then true; // Secant of argument in radians

case("secd") then true; // Secant of argument in degrees

case("asec") then true; // Inverse secant in radians

case("asecd") then true; // Inverse secant in

degrees

case("sech") then true; // Hyperbolic secant

case("asech") then true; // Inverse hyperbolic

secant

case("cot") then true; // Cotangent of argument in

radians

case("cotd") then true; // Cotangent of argument in

degrees

case("acot") then true; // Inverse cotangent in radians

case("acotd") then true; // Inverse cotangent in

degrees

case("coth") then true; // Hyperbolic cotangent

case("acoth") then true; // Inverse hyperbolic

cotangent

case("hypot") then true; // Square root of sum of

squares

// Exponents and Logarithms

case("exp") then true; // Exponential

case("expm1") then true; // Compute exp(x)-1

accurately for small values of x

case("log") then true; // Natural logarithm

case("log10") then true; // Common (base 10)

logarithm

case("log1p") then true; // Compute log(1+x)

accurately for small values of x

case("log2") then true; // Base 2 logarithm and dissect

floating-point numbers into exponent and mantissa

case("nextpow2") then true; // Exponent of next higher

power of 2

case("nthroot") then true; // Real nth root of real

numbers

case("pow2") then true; // Base 2 power and scale

floating-point numbers

case("reallog") then true; // Natural logarithm for

nonnegative real arrays

case("realpow") then true; // Array power for real-

only output

247

case("realsqrt") then true; // Square root for

nonnegative real arrays

case("sqrt") then true; // Square root

case("abx") then true; //absolute value

case(_) then false;

end matchcontinue;

end builtIn;

end Mat_Builtin;

248

Mod_Builtin.mo

encapsulated package Mod_Builtin

public function builtIn

input String mat_fname;

output String mod_fname;

algorithm

mod_fname := matchcontinue (mat_fname)

local

String fname;

case("disp") equation fname = "print"; then fname;

case("error") equation fname = "print"; then fname;

case("diag") equation fname = "diagonal"; then fname;

case("rdivide") equation fname = "rdivide"; then fname;

end matchcontinue;

end builtIn;

end Mod_Builtin;