Skip to content

Commit

Permalink
Improve subscripting of if-expressions (#8396)
Browse files Browse the repository at this point in the history
- If the branches of an if-expression can't be subscripted because they
  have different dimensions, just subscript the whole if-expression
  instead.

Fixes #8341
  • Loading branch information
perost committed Jan 10, 2022
1 parent e47fb56 commit d1bee64
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
24 changes: 19 additions & 5 deletions OMCompiler/Compiler/NFFrontEnd/NFExpression.mo
Expand Up @@ -1406,11 +1406,25 @@ public
Type ty;
algorithm
IF(ty, cond, tb, fb) := exp;
tb := applySubscript(subscript, tb, restSubscripts);
fb := applySubscript(subscript, fb, restSubscripts);
ty := if Type.isConditionalArray(ty) then
Type.setConditionalArrayTypes(ty, typeOf(tb), typeOf(fb)) else typeOf(tb);
outExp := IF(ty, cond, tb, fb);

if Type.isConditionalArray(ty) then
// Subscripting both branches of a conditional array might not be possible
// since they have different dimensions. If it fails just subscript the
// whole if-expression instead.
try
tb := applySubscript(subscript, tb, restSubscripts);
fb := applySubscript(subscript, fb, restSubscripts);
ty := Type.setConditionalArrayTypes(ty, typeOf(tb), typeOf(fb));
outExp := IF(ty, cond, tb, fb);
else
outExp := makeSubscriptedExp(subscript :: restSubscripts, exp);
end try;
else
tb := applySubscript(subscript, tb, restSubscripts);
fb := applySubscript(subscript, fb, restSubscripts);
ty := typeOf(tb);
outExp := IF(ty, cond, tb, fb);
end if;
end applySubscriptIf;

function makeSubscriptedExp
Expand Down
26 changes: 26 additions & 0 deletions testsuite/flattening/modelica/scodeinst/IfExpression13.mo
@@ -0,0 +1,26 @@
// name: IfExpression13
// keywords:
// status: correct
// cflags: -d=newInst
//

record R
constant Boolean cond = false;
constant Real[3] a = if cond then {1.0} else {1.0, 2.0, 3.0};
constant Real[2] b = a[1:end-1];
end R;

model IfExpression13
R r = R();
end IfExpression13;

// Result:
// class IfExpression13
// constant Boolean r.cond = false;
// constant Real r.a[1] = 1.0;
// constant Real r.a[2] = 2.0;
// constant Real r.a[3] = 3.0;
// constant Real r.b[1] = 1.0;
// constant Real r.b[2] = 2.0;
// end IfExpression13;
// endResult
1 change: 1 addition & 0 deletions testsuite/flattening/modelica/scodeinst/Makefile
Expand Up @@ -672,6 +672,7 @@ IfExpression8.mo \
IfExpression10.mo \
IfExpression11.mo \
IfExpression12.mo \
IfExpression13.mo \
IfEquationInvalidCond1.mo \
ih1.mo \
ih2.mo \
Expand Down

0 comments on commit d1bee64

Please sign in to comment.