1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
|
use std::clone::Clone;
use std::fmt::{Debug, Formatter, Error};
use std::collections::HashMap;
// This represents a block of Modelica code.
// A valid .mo file will be a sequence of these
#[derive(Clone, PartialEq)]
pub enum ModelicaCode {
Class, // unimpl
Model(ModelicaModel),
Record, // unimpl
Block(ModelicaBlock),
Connector(ModelicaConnector),
Type(ModelicaType),
Package(ModelicaPackage),
Function, // unimpl
}
// A package is basically a namespace; they can be nested and contain any other
// code chunks (models, etc).
// They are optional; models don't need to live in a package to be valid.
#[derive(Clone, PartialEq)]
pub struct ModelicaPackage {
pub name: String,
pub description: Option<String>,
pub children: Vec<ModelicaCode>,
}
#[derive(Clone, PartialEq)]
pub struct ModelicaType {
pub name: String,
pub description: Option<String>,
pub component: ComponentDeclaration,
}
#[derive(Clone, PartialEq)]
pub struct ModelicaBlock {
pub name: String,
pub description: Option<String>,
pub component_clauses: Vec<ComponentClause>,
pub public_component_clauses: Option<Vec<ComponentClause>>,
pub protected_component_clauses: Option<Vec<ComponentClause>>,
pub equations: Vec<SimpleEquation>,
pub connections: Vec<Connection>,
pub extends: Vec<String>,
}
#[derive(Clone, PartialEq)]
pub struct ModelicaConnector {
pub name: String,
pub description: Option<String>,
pub component_clauses: Vec<ComponentClause>,
}
#[derive(Clone, PartialEq)]
pub struct ModelicaModel {
pub name: String,
pub description: Option<String>,
pub component_clauses: Vec<ComponentClause>,
pub equations: Vec<SimpleEquation>,
pub connections: Vec<Connection>,
pub extends: Vec<String>,
}
#[derive(Copy, Clone, PartialEq)]
pub enum ComponentPrefix {
// incomplete: eg, can be parameter and input
Flow,
Stream,
Input,
Output,
Discrete,
Parameter,
Constant,
}
#[derive(Clone, PartialEq)]
pub struct ComponentClause {
pub prefix: Option<ComponentPrefix>,
pub specifier: String,
pub declarations: Vec<ComponentDeclaration>,
}
#[derive(Clone, PartialEq)]
pub struct ComponentDeclaration {
pub name: String,
pub dimensions: Option<Vec<i64>>,
pub value: Option<Expr>,
pub quantity: Option<String>,
pub units: Option<String>,
pub description: Option<String>,
}
// This isn't part of the parse AST; it's a flattened helper type
#[derive(Clone, PartialEq)]
pub struct Component {
pub prefix: Option<ComponentPrefix>,
pub specifier: String,
pub name: String,
pub value: Option<Expr>,
pub units: Option<String>,
pub description: Option<String>,
}
#[derive(Clone, PartialEq)]
pub struct Connection {
pub a: String,
pub b: String,
}
#[derive(Clone, PartialEq)]
pub struct SimpleEquation {
pub lhs: Expr,
pub rhs: Expr,
}
#[derive(Clone, PartialEq)]
pub enum Expr {
Integer(i64),
Float(f64),
Boolean(bool),
Ident(String),
Der(Box<Expr>),
Sign(Box<Expr>),
MathUnaryExpr(MathUnaryFunc, Box<Expr>),
BinExpr(BinOperator, Box<Expr>, Box<Expr>),
Array(Vec<Expr>),
}
#[derive(Copy, Clone, PartialEq)]
pub enum MathUnaryFunc {
Abs,
Sqrt,
Sin,
Cos,
Tan,
Asin,
Acos,
Atan,
// TODO: atan2(x,y)
Sinh,
Cosh,
Tanh,
Exp,
Log,
Log10,
}
#[derive(Copy, Clone, PartialEq)]
pub enum BinOperator {
Multiply,
Divide,
Add,
Subtract,
}
//// Helpers
impl ModelicaModel {
// This flattens the ComponentClause/ComponentDeclaration tree into a flat
// list of Components
// TODO: refactor this into an iterator `components()`?
pub fn get_components(&self) -> Vec<Component> {
let mut vars: Vec<Component> = vec![];
for clause in &self.component_clauses {
vars.extend(clause.declarations.iter().map(|ref dec|
Component {
prefix: clause.prefix.clone(),
specifier: clause.specifier.clone(),
name: dec.name.clone(),
value: dec.value.clone(),
units: dec.units.clone(),
description: dec.description.clone(),
}))
}
vars
}
pub fn get_constant_vars(&self) -> HashMap<String,Option<Expr>> {
let mut binds = HashMap::new();
// XXX: actually implement this...
for c in &self.get_components() {
match c.prefix {
Some(ComponentPrefix::Constant) => { binds.insert(c.name.clone(), Some(Expr::Integer(123))); },
Some(ComponentPrefix::Parameter) => { binds.insert(c.name.clone(), Some(Expr::Float(4.56))); },
_ => (),
}
}
binds
}
// This crude function finds "unbound" variables: those which are not constants, parameters, or
// the sole element on the LHS of an equation.
// Bugs:
// if a var is on LHS and RHS of same equation
pub fn get_free_vars(&self) -> Vec<String> {
// Start with components, and remove constants and parameters
let components = self.get_components();
let vars = components.iter().filter(|v| match v.prefix {
Some(ComponentPrefix::Constant) | Some(ComponentPrefix::Parameter) => false,
_ => true,
});
// Remove LHS (bound) vars
let mut outputs = vec![];
for eq in self.equations.iter() {
// TODO:
if let Expr::Ident(ref symb) = eq.lhs {
outputs.push(symb.to_string());
}
}
let vars = vars.filter(|v| !outputs.contains(&v.name));
vars.map(|c| c.name.clone()).collect()
}
}
fn union_strings(a: &Vec<String>, b: &Vec<String>) -> Vec<String> {
let mut u = a.clone();
for e in b {
if !(u.contains(&e)) {
u.push(e.clone());
}
}
u
}
impl Expr {
// Order is undefined
// TODO: should return a HashSet, not a Vec
pub fn identifiers(&self) -> Vec<String> {
use self::Expr::*;
match *self {
Integer(_) | Float(_) | Boolean(_) => vec![],
Ident(ref s) => vec![s.clone()],
Der(ref e) | Sign(ref e) => e.identifiers(),
MathUnaryExpr(_, ref e) => e.identifiers(),
BinExpr(_, ref e1, ref e2) => {
union_strings(&e1.identifiers(), &e2.identifiers())
},
Array(ref el) => {
let mut all: Vec<String> = vec![];
for e in el {
all.append(&mut e.identifiers());
}
all
}
}
}
pub fn contains(&self, ident: &str) -> bool{
self.identifiers().contains(&ident.to_string())
}
}
impl SimpleEquation {
// Order is undefined
pub fn identifiers(&self) -> Vec<String> {
union_strings(&self.lhs.identifiers(), &self.rhs.identifiers())
}
pub fn contains(&self, ident: &str) -> bool{
let s = &ident.to_string();
self.lhs.identifiers().contains(s) || self.rhs.identifiers().contains(s)
}
}
//// Debug Implementations
impl Debug for ModelicaModel {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
try!(write!(fmt, "model {}\n", self.name));
for e in self.extends.iter() {
try!(write!(fmt, " extends {};\n", e));
}
for v in self.get_components().iter() {
try!(write!(fmt, " {:?};\n", v));
}
try!(write!(fmt, "equation\n"));
for c in self.connections.iter() {
try!(write!(fmt, " {:?};\n", c));
}
for e in self.equations.iter() {
try!(write!(fmt, " {:?};\n", e));
}
write!(fmt, "end {};\n", self.name)
}
}
impl Debug for ComponentPrefix {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::ComponentPrefix::*;
write!(fmt, "{}",
match *self {
Flow => "flow",
Stream => "stream",
Input => "input",
Output => "output",
Discrete => "discrete",
Parameter => "parameter",
Constant => "constant",
})
}
}
impl Debug for Component {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
write!(fmt, "{}{} {}",
match self.prefix {
Some(p) => format!("{:?} ", p),
None => "".to_string(),
},
self.specifier,
self.name,
)
}
}
impl Debug for Connection {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
write!(fmt, "connect({}, {})", self.a, self.b)
}
}
impl Debug for SimpleEquation {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
write!(fmt, "{:?} = {:?}", self.lhs, self.rhs)
}
}
impl Debug for Expr {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::Expr::*;
match *self {
Integer(e) => write!(fmt, "{}", e),
Float(e) => write!(fmt, "{}", e),
Boolean(e) => write!(fmt, "{}", e),
Ident(ref e) => write!(fmt, "{}", e),
Der(ref e) => write!(fmt, "der({:?})", e),
Sign(ref e) => write!(fmt, "sign({:?})", e),
MathUnaryExpr(func, ref e) => write!(fmt, "{:?}({:?})", func, e),
BinExpr(op, ref l, ref r) => write!(fmt, "({:?} {:?} {:?})", l, op, r),
Array(ref el) => {
try!(write!(fmt, "["));
for e in el {
// XXX: not last comma
try!(write!(fmt, "{:?},", e));
}
write!(fmt, "]")
},
}
}
}
impl Debug for BinOperator {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::BinOperator::*;
match *self {
Multiply => write!(fmt, "*"),
Divide => write!(fmt, "/"),
Add => write!(fmt, "+"),
Subtract => write!(fmt, "-"),
}
}
}
impl Debug for MathUnaryFunc {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
use self::MathUnaryFunc::*;
match *self {
Abs => write!(fmt, "abs"),
Sqrt => write!(fmt, "sqrt"),
Sin => write!(fmt, "sin"),
Cos => write!(fmt, "cos"),
Tan => write!(fmt, "tan"),
Asin => write!(fmt, "asin"),
Acos => write!(fmt, "acos"),
Atan => write!(fmt, "atan"),
Sinh => write!(fmt, "sinh"),
Cosh => write!(fmt, "cosh"),
Tanh => write!(fmt, "tanh"),
Exp => write!(fmt, "exp"),
Log => write!(fmt, "log"),
Log10 => write!(fmt, "log10"),
}
}
}
|