/
CodegenUtil.tpl
498 lines (431 loc) · 17.1 KB
/
CodegenUtil.tpl
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// This file defines util functions for templates for transforming Modelica/MetaModelica code to C like
// code. They are used in the code generator phase of the compiler to write
// target code.
//
// There are two root templates intended to be called from the code generator:
// translateModel and translateFunctions. These templates do not return any
// result but instead write the result to files. All other templates return
// text and are used by the root templates (most of them indirectly).
//
// To future maintainers of this file:
//
// - A line like this
// # var = "" /*BUFD*/
// declares a text buffer that you can later append text to. It can also be
// passed to other templates that in turn can append text to it. In the new
// version of Susan it should be written like this instead:
// let &var = buffer ""
//
// - A line like this
// ..., Text var /*BUFP*/, ...
// declares that a template takes a text buffer as input parameter. In the
// new version of Susan it should be written like this instead:
// ..., Text &var, ...
//
// - A line like this:
// ..., var /*BUFC*/, ...
// passes a text buffer to a template. In the new version of Susan it should
// be written like this instead:
// ..., &var, ...
//
// - Style guidelines:
//
// - Try (hard) to limit each row to 80 characters
//
// - Code for a template should be indented with 2 spaces
//
// - Exception to this rule is if you have only a single case, then that
// single case can be written using no indentation
//
// This single case can be seen as a clarification of the input to the
// template
//
// - Code after a case should be indented with 2 spaces if not written on the
// same line
package CodegenUtil
import interface SimCodeTV;
/* public */ template symbolName(String modelNamePrefix, String symbolName)
"Creates a unique name for the function"
::=
modelNamePrefix + "_" + symbolName
end symbolName;
template replaceDotAndUnderscore(String str)
"Replace _ with __ and dot in identifiers with _"
::=
match str
case name then
let str_dots = System.stringReplace(name,".", "_")
let str_underscores = System.stringReplace(str_dots, "_", "__")
System.unquoteIdentifier(str_underscores)
end replaceDotAndUnderscore;
template underscorePath(Path path)
"Generate paths with components separated by underscores.
Replaces also the . in identifiers with _.
The dot might happen for world.gravityAccleration"
::=
match path
case QUALIFIED(__) then
'<%replaceDotAndUnderscore(name)%>_<%underscorePath(path)%>'
case IDENT(__) then
replaceDotAndUnderscore(name)
case FULLYQUALIFIED(__) then
underscorePath(path)
end underscorePath;
template modelNamePrefix(SimCode simCode)
::=
match simCode
case simCode as SIMCODE(__) then
System.stringReplace(fileNamePrefix,".", "_")
// underscorePath(mi.name)
// case simCode as SIMCODE(modelInfo=mi as MODELINFO(__)) then
// underscorePath(mi.name)
end modelNamePrefix;
template crefStr(ComponentRef cr)
"Generates the name of a variable for variable name array. Uses underscores for qualified names.
a._b not a.b"
::=
match cr
case CREF_IDENT(__) then '<%System.unquoteIdentifier(ident)%><%subscriptsStr(subscriptLst)%>'
// Are these even needed? Function context should only have CREF_IDENT :)
case CREF_QUAL(ident = "$DER") then 'der(<%crefStr(componentRef)%>)'
case CREF_QUAL(__) then '<%System.unquoteIdentifier(ident)%><%subscriptsStr(subscriptLst)%>._<%crefStr(componentRef)%>'
else "CREF_NOT_IDENT_OR_QUAL"
end crefStr;
template crefStrNoUnderscore(ComponentRef cr)
"Generates the name of a variable for variable name array. However does not use underscores on qualified names.
a.b not a._b. Used for generating variable names that are exported e.g. xml files"
::=
match cr
case CREF_IDENT(__) then '<%ident%><%subscriptsStr(subscriptLst)%>'
case CREF_QUAL(ident = "$DER") then 'der(<%crefStrNoUnderscore(componentRef)%>)'
case CREF_QUAL(__) then '<%ident%><%subscriptsStr(subscriptLst)%>.<%crefStrNoUnderscore(componentRef)%>'
else "CREF_NOT_IDENT_OR_QUAL"
end crefStrNoUnderscore;
template subscriptsStr(list<Subscript> subscripts)
"Generares subscript part of the name."
::=
if subscripts then
'[<%subscripts |> s => subscriptStr(s) ;separator=","%>]'
end subscriptsStr;
template subscriptStr(Subscript subscript)
"Generates a single subscript.
Only works for constant integer indicies."
::=
match subscript
case INDEX(exp=ICONST(integer=i)) then i
case INDEX(exp=ENUM_LITERAL(name=n)) then dotPath(n)
case SLICE(exp=ICONST(integer=i)) then i
case WHOLEDIM(__) then "WHOLEDIM"
else "UNKNOWN_SUBSCRIPT"
end subscriptStr;
/*********************** Comments ************************/
template escapeCComments(String stringWithCComments)
"escape the C comments inside a string, replaces them with /* */->(* *)"
::= '<%System.stringReplace(System.stringReplace(stringWithCComments, "/*", "(*"), "*/", "*)")%>'
end escapeCComments;
/*********************************************************/
template initDefaultValXml(DAE.Type type_)
::=
match type_
case T_INTEGER(__) then '0'
case T_REAL(__) then '0.0'
case T_BOOL(__) then 'false'
case T_STRING(__) then ''
case T_ENUMERATION(__) then '0'
else error(sourceInfo(), 'initial value of unknown type: <%unparseType(type_)%>')
end initDefaultValXml;
template initValXml(Exp exp)
::=
match exp
case ICONST(__) then integer
case RCONST(__) then real
case SCONST(__) then '<%Util.escapeModelicaStringToXmlString(string)%>'
case BCONST(__) then if bool then "true" else "false"
case ENUM_LITERAL(__) then '<%index%>'
else error(sourceInfo(), 'initial value of unknown type: <%printExpStr(exp)%>')
end initValXml;
/*********************************************************************
*********************************************************************
* Common XML Functions
*********************************************************************
*********************************************************************/
template getVariablity(VarKind varKind)
"Returns the variablity Attribute of ScalarVariable."
::=
match varKind
case DISCRETE(__) then "discrete"
case PARAM(__) then "parameter"
case CONST(__) then "constant"
else "continuous"
end getVariablity;
template getAliasVar(AliasVariable aliasvar)
"Returns the alias Attribute of ScalarVariable."
::=
match aliasvar
case NOALIAS(__) then '"noAlias"'
case ALIAS(__) then '"alias" aliasVariable="<%crefStrNoUnderscore(varName)%>"'
case NEGATEDALIAS(__) then '"negatedAlias" aliasVariable="<%crefStrNoUnderscore(varName)%>"'
else '"noAlias"'
end getAliasVar;
template ScalarVariableType(String unit, String displayUnit, Option<DAE.Exp> minValue, Option<DAE.Exp> maxValue, Option<DAE.Exp> startValue, Option<DAE.Exp> nominalValue, Boolean isFixed, DAE.Type type_)
"Generates code for ScalarVariable Type file for FMU target."
::=
match type_
case T_INTEGER(__) then '<Integer <%ScalarVariableTypeStartAttribute(startValue, type_)%><%ScalarVariableTypeFixedAttribute(isFixed)%><%ScalarVariableTypeIntegerMinAttribute(minValue)%><%ScalarVariableTypeIntegerMaxAttribute(maxValue)%><%ScalarVariableTypeUnitAttribute(unit)%><%ScalarVariableTypeDisplayUnitAttribute(displayUnit)%> />'
case T_REAL(__) then '<Real <%ScalarVariableTypeStartAttribute(startValue, type_)%><%ScalarVariableTypeFixedAttribute(isFixed)%><%ScalarVariableTypeNominalAttribute(nominalValue)%><%ScalarVariableTypeRealMinAttribute(minValue)%><%ScalarVariableTypeRealMaxAttribute(maxValue)%><%ScalarVariableTypeUnitAttribute(unit)%><%ScalarVariableTypeDisplayUnitAttribute(displayUnit)%> />'
case T_BOOL(__) then '<Boolean <%ScalarVariableTypeStartAttribute(startValue, type_)%><%ScalarVariableTypeFixedAttribute(isFixed)%><%ScalarVariableTypeUnitAttribute(unit)%><%ScalarVariableTypeDisplayUnitAttribute(displayUnit)%> />'
case T_STRING(__) then '<String <%ScalarVariableTypeStartAttribute(startValue, type_)%><%ScalarVariableTypeFixedAttribute(isFixed)%><%ScalarVariableTypeUnitAttribute(unit)%><%ScalarVariableTypeDisplayUnitAttribute(displayUnit)%> />'
case T_ENUMERATION(__) then '<Integer <%ScalarVariableTypeStartAttribute(startValue, type_)%><%ScalarVariableTypeFixedAttribute(isFixed)%><%ScalarVariableTypeUnitAttribute(unit)%><%ScalarVariableTypeDisplayUnitAttribute(displayUnit)%> />'
case T_COMPLEX(complexClassType = ci as ClassInf.EXTERNAL_OBJ(__)) then '<ExternalObject path="<%escapeModelicaStringToXmlString(dotPath(ci.path))%>" />'
else error(sourceInfo(), 'ScalarVariableType: <%unparseType(type_)%>')
end ScalarVariableType;
template StartString(DAE.Exp exp)
::=
match exp
case ICONST(__) then ' start="<%initValXml(exp)%>"'
case RCONST(__) then ' start="<%initValXml(exp)%>"'
case SCONST(__) then ' start="<%initValXml(exp)%>"'
case BCONST(__) then ' start="<%initValXml(exp)%>"'
case ENUM_LITERAL(__) then ' start="<%initValXml(exp)%>"'
else ''
end StartString;
template ScalarVariableTypeStartAttribute(Option<DAE.Exp> startValue, DAE.Type type_)
"generates code for start attribute"
::=
match startValue
case SOME(exp) then 'useStart="true"<%StartString(exp)%>'
case NONE() then 'useStart="false"'
end ScalarVariableTypeStartAttribute;
template ScalarVariableTypeFixedAttribute(Boolean isFixed)
"generates code for fixed attribute"
::=
' fixed="<%isFixed%>"'
end ScalarVariableTypeFixedAttribute;
template NominalString(DAE.Exp exp)
::=
match exp
case ICONST(__) then ' nominal="<%initValXml(exp)%>"'
case RCONST(__) then ' nominal="<%initValXml(exp)%>"'
case SCONST(__) then ' nominal="<%initValXml(exp)%>"'
case BCONST(__) then ' nominal="<%initValXml(exp)%>"'
else ''
end NominalString;
template ScalarVariableTypeNominalAttribute(Option<DAE.Exp> nominalValue)
"generates code for nominal attribute"
::=
match nominalValue
case SOME(exp)
then ' useNominal="true"<%NominalString(exp)%>'
case NONE() then ' useNominal="false"'
end ScalarVariableTypeNominalAttribute;
template ScalarVariableTypeUnitAttribute(String unit)
"generates code for unit attribute"
::=
'<% if unit then ' unit="<%unit%>"' %>'
end ScalarVariableTypeUnitAttribute;
template ScalarVariableTypeDisplayUnitAttribute(String displayUnit)
"generates code for displayUnit attribute"
::=
'<% if displayUnit then ' displayUnit="<%displayUnit%>"' %>'
end ScalarVariableTypeDisplayUnitAttribute;
template MinString(DAE.Exp exp)
::=
match exp
case ICONST(__) then ' min="<%initValXml(exp)%>"'
case RCONST(__) then ' min="<%initValXml(exp)%>"'
case SCONST(__) then ' min="<%initValXml(exp)%>"'
case BCONST(__) then ' min="<%initValXml(exp)%>"'
case ENUM_LITERAL(__) then ' min="<%initValXml(exp)%>"'
else ''
end MinString;
template ScalarVariableTypeIntegerMinAttribute(Option<DAE.Exp> minValue)
"generates code for min attribute"
::=
match minValue
case SOME(exp) then '<%MinString(exp)%>'
// case NONE() then ' min="-2147483648"'
end ScalarVariableTypeIntegerMinAttribute;
template MaxString(DAE.Exp exp)
::=
match exp
case ICONST(__) then ' max="<%initValXml(exp)%>"'
case RCONST(__) then ' max="<%initValXml(exp)%>"'
case SCONST(__) then ' max="<%initValXml(exp)%>"'
case BCONST(__) then ' max="<%initValXml(exp)%>"'
case ENUM_LITERAL(__) then ' max="<%initValXml(exp)%>"'
else ''
end MaxString;
template ScalarVariableTypeIntegerMaxAttribute(Option<DAE.Exp> maxValue)
"generates code for max attribute"
::=
match maxValue
case SOME(exp) then '<%MaxString(exp)%>'
// case NONE() then ' max="2147483647"'
end ScalarVariableTypeIntegerMaxAttribute;
template ScalarVariableTypeRealMinAttribute(Option<DAE.Exp> minValue)
"generates code for min attribute"
::=
match minValue
case SOME(exp) then '<%MinString(exp)%>'
// case NONE() then ' min="-1.7976931348623157E+308"'
end ScalarVariableTypeRealMinAttribute;
template ScalarVariableTypeRealMaxAttribute(Option<DAE.Exp> maxValue)
"generates code for max attribute"
::=
match maxValue
case SOME(exp) then '<%MaxString(exp)%>'
// case NONE() then ' max="1.7976931348623157E+308"'
end ScalarVariableTypeRealMaxAttribute;
/********* Equation Dumps *****************************/
template equationIndex(SimEqSystem eq)
"Generates an equation."
::=
match eq
case SES_RESIDUAL(__)
case SES_SIMPLE_ASSIGN(__)
case SES_ARRAY_CALL_ASSIGN(__)
case SES_IFEQUATION(__)
case SES_ALGORITHM(__)
case SES_LINEAR(__)
case SES_NONLINEAR(__)
case SES_MIXED(__)
case SES_WHEN(__)
case SES_FOR_LOOP(__)
then index
end equationIndex;
template dumpEqs(list<SimEqSystem> eqs)
::= eqs |> eq hasindex i0 =>
match eq
case e as SES_RESIDUAL(__) then
<<
equation index: <%equationIndex(eq)%>
type: RESIDUAL
<%escapeCComments(printExpStr(e.exp))%>
>>
case e as SES_SIMPLE_ASSIGN(__) then
<<
equation index: <%equationIndex(eq)%>
type: SIMPLE_ASSIGN
<%crefStr(e.cref)%> = <%escapeCComments(printExpStr(e.exp))%>
>>
case e as SES_ARRAY_CALL_ASSIGN(lhs=lhs as CREF(__)) then
<<
equation index: <%equationIndex(eq)%>
type: ARRAY_CALL_ASSIGN
<%crefStr(lhs.componentRef)%> = <%escapeCComments(printExpStr(e.exp))%>
>>
case e as SES_ALGORITHM(statements={}) then
<<
empty algorithm
>>
case e as SES_ALGORITHM(statements=first::_) then
<<
equation index: <%equationIndex(eq)%>
type: ALGORITHM
<%e.statements |> stmt => escapeCComments(ppStmtStr(stmt,2))%>
>>
case e as SES_LINEAR(__) then
<<
equation index: <%equationIndex(eq)%>
type: LINEAR
<%e.vars |> SIMVAR(name=cr) => '<var><%crefStr(cr)%></var>' ; separator = "\n" %>
<row>
<%beqs |> exp => '<cell><%escapeCComments(printExpStr(exp))%></cell>' ; separator = "\n" %><%\n%>
</row>
<matrix>
<%simJac |> (i1,i2,eq) =>
<<
<cell row="<%i1%>" col="<%i2%>">
<%match eq case e as SES_RESIDUAL(__) then
<<
<residual><%escapeCComments(printExpStr(e.exp))%></residual>
>>
%>
</cell>
>>
%>
</matrix>
>>
case e as SES_NONLINEAR(__) then
<<
equation index: <%equationIndex(eq)%>
indexNonlinear: <%indexNonLinearSystem%>
type: NONLINEAR
vars: {<%e.crefs |> cr => '<%crefStr(cr)%>' ; separator = ", "%>}
eqns: {<%e.eqs |> eq => '<%equationIndex(eq)%>' ; separator = ", "%>}
>>
case e as SES_MIXED(__) then
<<
equation index: <%equationIndex(eq)%>
type: MIXED
<%dumpEqs(fill(e.cont,1))%>
<%dumpEqs(e.discEqs)%><%\n%>
<mixed>
<continuous index="<%equationIndex(e.cont)%>" />
<%e.discVars |> SIMVAR(name=cr) => '<var><%crefStr(cr)%></var>' ; separator = ","%>
<%e.discEqs |> eq => '<discrete index="<%equationIndex(eq)%>" />'%>
</mixed>
>>
case e as SES_WHEN(__) then
<<
equation index: <%equationIndex(eq)%>
type: WHEN
when {<%conditions |> cond => '<%crefStr(cond)%>' ; separator=", " %>} then
<%crefStr(e.left)%> = <%escapeCComments(printExpStr(e.right))%>;
end when;
>>
case e as SES_IFEQUATION(__) then
let branches = ifbranches |> (_,eqs) => dumpEqs(eqs)
let elsebr = dumpEqs(elsebranch)
<<
equation index: <%equationIndex(eq)%>
type: IFEQUATION
<%branches%>
<%elsebr%>
>>
else
<<
unknown equation
>>
end dumpEqs;
/************************************************************************************************/
/*********************************************************************
*********************************************************************
* Paths
*********************************************************************
*********************************************************************/
template dotPath(Path path)
"Generates paths with components separated by dots."
::=
match path
case QUALIFIED(__) then '<%name%>.<%dotPath(path)%>'
case IDENT(__) then name
case FULLYQUALIFIED(__) then dotPath(path)
end dotPath;
/*********************************************************************
*********************************************************************
* Error
*********************************************************************
*********************************************************************/
template error(SourceInfo srcInfo, String errMessage)
"Example source template error reporting template to be used together with the sourceInfo() magic function.
Usage: error(sourceInfo(), <<message>>) "
::=
let() = Tpl.addSourceTemplateError(errMessage, srcInfo)
<<
#error "<% Error.infoStr(srcInfo) %> <% errMessage %>"<%\n%>
>>
end error;
//for completeness; although the error() template above is preferable
template errorMsg(String errMessage)
"Example template error reporting template
that is reporting only the error message without the usage of source infotmation."
::=
let() = Tpl.addTemplateError(errMessage)
<<
#error "<% errMessage %>"<%\n%>
>>
end errorMsg;
annotation(__OpenModelica_Interface="backend");
end CodegenUtil;
// vim: filetype=susan sw=2 sts=2