/
Patternm.mo
2831 lines (2614 loc) · 104 KB
/
Patternm.mo
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package Patternm
" file: Patternm.mo
package: Patternm
description: Patternmatching
RCS: $Id$
This module contains the patternmatch algorithm for the MetaModelica
matchcontinue expression."
public import Absyn;
public import AvlTreeString;
public import ClassInf;
public import ConnectionGraph;
public import DAE;
public import FCore;
public import HashTableStringToPath;
public import SCode;
public import Dump;
public import InnerOuter;
public import GlobalScript;
public import Prefix;
public import Types;
public import UnitAbsyn;
protected import Algorithm;
protected import BaseHashTable;
protected import ComponentReference;
protected import Connect;
protected import DAEUtil;
protected import Debug;
protected import Expression;
protected import ExpressionDump;
protected import Error;
protected import Flags;
protected import FGraph;
protected import Inst;
protected import InstSection;
protected import InstTypes;
protected import InstUtil;
protected import List;
protected import Lookup;
protected import MetaUtil;
protected import SCodeUtil;
protected import Static;
protected import System;
protected import Util;
protected import SCodeDump;
protected function generatePositionalArgs "author: KS
This function is used in the following cases:
v := matchcontinue (x)
case REC(a=1,b=2)
...
The named arguments a=1 and b=2 must be sorted and transformed into
positional arguments (a,b is not necessarely the correct order).
"
input list<Absyn.Ident> fieldNameList;
input list<Absyn.NamedArg> namedArgList;
input list<Absyn.Exp> accList;
output list<Absyn.Exp> outList;
output list<Absyn.NamedArg> outInvalidNames;
algorithm
(outList,outInvalidNames) := match (fieldNameList,namedArgList,accList)
local
list<Absyn.Exp> localAccList;
list<Absyn.Ident> restFieldNames;
Absyn.Ident firstFieldName;
Absyn.Exp exp;
list<Absyn.NamedArg> localNamedArgList;
case ({},_,localAccList) then (listReverse(localAccList),namedArgList);
case (firstFieldName :: restFieldNames,localNamedArgList,localAccList)
equation
(exp,localNamedArgList) = findFieldExpInList(firstFieldName,localNamedArgList);
(localAccList,localNamedArgList) = generatePositionalArgs(restFieldNames,localNamedArgList,exp::localAccList);
then (localAccList,localNamedArgList);
end match;
end generatePositionalArgs;
protected function findFieldExpInList "author: KS
Helper function to generatePositionalArgs
"
input Absyn.Ident firstFieldName;
input list<Absyn.NamedArg> namedArgList;
output Absyn.Exp outExp;
output list<Absyn.NamedArg> outNamedArgList;
algorithm
(outExp,outNamedArgList) := matchcontinue (firstFieldName,namedArgList)
local
Absyn.Exp e;
Absyn.Ident localFieldName,aName;
list<Absyn.NamedArg> rest;
Absyn.NamedArg first;
case (_,{}) then (Absyn.CREF(Absyn.WILD()),{});
case (localFieldName,Absyn.NAMEDARG(aName,e) :: rest)
equation
true = stringEq(localFieldName,aName);
then (e,rest);
case (localFieldName,first::rest)
equation
(e,rest) = findFieldExpInList(localFieldName,rest);
then (e,first::rest);
end matchcontinue;
end findFieldExpInList;
protected function checkInvalidPatternNamedArgs
"Checks that there are no invalid named arguments in the pattern"
input list<Absyn.NamedArg> args;
input list<String> fieldNameList;
input Util.Status status;
input SourceInfo info;
output Util.Status outStatus;
algorithm
outStatus := match (args,fieldNameList,status,info)
local
list<String> argsNames;
String str1,str2;
case ({},_,_,_) then status;
else
equation
(argsNames,_) = Absyn.getNamedFuncArgNamesAndValues(args);
str1 = stringDelimitList(argsNames, ",");
str2 = stringDelimitList(fieldNameList, ",");
Error.addSourceMessage(Error.META_INVALID_PATTERN_NAMED_FIELD, {str1,str2}, info);
then Util.FAILURE();
end match;
end checkInvalidPatternNamedArgs;
public function elabPattern
input FCore.Cache cache;
input FCore.Graph env;
input Absyn.Exp lhs;
input DAE.Type ty;
input SourceInfo info;
output FCore.Cache outCache;
output DAE.Pattern pattern;
algorithm
(outCache,pattern) := elabPattern2(cache,env,lhs,ty,info,Error.getNumErrorMessages());
end elabPattern;
protected function elabPattern2
input FCore.Cache inCache;
input FCore.Graph env;
input Absyn.Exp inLhs;
input DAE.Type ty;
input SourceInfo info;
input Integer numError;
output FCore.Cache outCache;
output DAE.Pattern pattern;
algorithm
(outCache,pattern) := matchcontinue (inCache,env,inLhs,ty,info,numError)
local
list<Absyn.Exp> exps;
list<DAE.Type> tys;
list<DAE.Pattern> patterns;
Absyn.Exp exp,head,tail;
String id,s,str;
Integer i;
Real r;
Boolean b;
DAE.Type ty1,ty2,tyHead,tyTail;
Option<DAE.Type> et;
DAE.Pattern patternHead,patternTail;
Absyn.ComponentRef fcr;
Absyn.FunctionArgs fargs;
Absyn.Path utPath;
FCore.Cache cache;
Absyn.Exp lhs;
DAE.Attributes attr;
case (cache,_,Absyn.INTEGER(i),_,_,_)
equation
et = validPatternType(ty,DAE.T_INTEGER_DEFAULT,inLhs,info);
then (cache,DAE.PAT_CONSTANT(et,DAE.ICONST(i)));
case (cache,_,Absyn.REAL(str),_,_,_)
equation
et = validPatternType(ty,DAE.T_REAL_DEFAULT,inLhs,info);
r = System.stringReal(str);
then (cache,DAE.PAT_CONSTANT(et,DAE.RCONST(r)));
case (cache,_,Absyn.UNARY(Absyn.UMINUS(),Absyn.INTEGER(i)),_,_,_)
equation
et = validPatternType(ty,DAE.T_INTEGER_DEFAULT,inLhs,info);
i = -i;
then (cache,DAE.PAT_CONSTANT(et,DAE.ICONST(i)));
case (cache,_,Absyn.UNARY(Absyn.UMINUS(),Absyn.REAL(str)),_,_,_)
equation
et = validPatternType(ty,DAE.T_REAL_DEFAULT,inLhs,info);
r = System.stringReal(str);
r = realNeg(r);
then (cache,DAE.PAT_CONSTANT(et,DAE.RCONST(r)));
case (cache,_,Absyn.STRING(s),_,_,_)
equation
et = validPatternType(ty,DAE.T_STRING_DEFAULT,inLhs,info);
s = System.unescapedString(s);
then (cache,DAE.PAT_CONSTANT(et,DAE.SCONST(s)));
case (cache,_,Absyn.BOOL(b),_,_,_)
equation
et = validPatternType(ty,DAE.T_BOOL_DEFAULT,inLhs,info);
then (cache,DAE.PAT_CONSTANT(et,DAE.BCONST(b)));
case (cache,_,Absyn.ARRAY({}),_,_,_)
equation
et = validPatternType(ty,DAE.T_METALIST_DEFAULT,inLhs,info);
then (cache,DAE.PAT_CONSTANT(et,DAE.LIST({})));
case (cache,_,Absyn.ARRAY(exps as _::_),_,_,_)
equation
lhs = List.fold(listReverse(exps), Absyn.makeCons, Absyn.ARRAY({}));
(cache,pattern) = elabPattern(cache,env,lhs,ty,info);
then (cache,pattern);
case (cache,_,Absyn.CALL(Absyn.CREF_IDENT("NONE",{}),Absyn.FUNCTIONARGS({},{})),_,_,_)
equation
validPatternType(ty,DAE.T_NONE_DEFAULT,inLhs,info);
then (cache,DAE.PAT_CONSTANT(NONE(),DAE.META_OPTION(NONE())));
case (cache,_,Absyn.CALL(Absyn.CREF_IDENT("SOME",{}),Absyn.FUNCTIONARGS({exp},{})),DAE.T_METAOPTION(ty = ty2),_,_)
equation
(cache,pattern) = elabPattern(cache,env,exp,ty2,info);
then (cache,DAE.PAT_SOME(pattern));
case (cache,_,Absyn.CONS(head,tail),tyTail as DAE.T_METALIST(ty = tyHead),_,_)
equation
tyHead = Types.boxIfUnboxedType(tyHead);
(cache,patternHead) = elabPattern(cache,env,head,tyHead,info);
(cache,patternTail) = elabPattern(cache,env,tail,tyTail,info);
then (cache,DAE.PAT_CONS(patternHead,patternTail));
case (cache,_,Absyn.TUPLE(exps),DAE.T_METATUPLE(types = tys),_,_)
equation
tys = List.map(tys, Types.boxIfUnboxedType);
(cache,patterns) = elabPatternTuple(cache,env,exps,tys,info,inLhs);
then (cache,DAE.PAT_META_TUPLE(patterns));
case (cache,_,Absyn.TUPLE(exps),DAE.T_TUPLE(types = tys),_,_)
equation
(cache,patterns) = elabPatternTuple(cache,env,exps,tys,info,inLhs);
then (cache,DAE.PAT_CALL_TUPLE(patterns));
case (cache,_,lhs as Absyn.CALL(fcr,fargs),DAE.T_COMPLEX(complexClassType = ClassInf.RECORD(_), source = {utPath}),_,_)
equation
(cache,pattern) = elabPatternCall(cache,env,Absyn.crefToPath(fcr),fargs,utPath,info,lhs);
then (cache,pattern);
case (cache,_,lhs as Absyn.CALL(fcr,fargs),DAE.T_METAUNIONTYPE(source = {utPath}),_,_)
equation
(cache,pattern) = elabPatternCall(cache,env,Absyn.crefToPath(fcr),fargs,utPath,info,lhs);
then (cache,pattern);
case (cache,_,lhs as Absyn.CALL(fcr,fargs),DAE.T_METARECORD(utPath = utPath),_,_)
equation
(cache,pattern) = elabPatternCall(cache,env,Absyn.crefToPath(fcr),fargs,utPath,info,lhs);
then (cache,pattern);
case (cache,_,Absyn.AS(id,exp),ty2,_,_)
equation
(cache,DAE.TYPES_VAR(ty = ty1, attributes = attr),_,_,_,_) = Lookup.lookupIdent(cache,env,id);
lhs = Absyn.CREF(Absyn.CREF_IDENT(id, {}));
Static.checkAssignmentToInput(lhs, attr, env, false, info);
et = validPatternType(ty2,ty1,inLhs,info);
(cache,pattern) = elabPattern(cache,env,exp,ty2,info);
pattern = if Types.isFunctionType(ty2) then DAE.PAT_AS_FUNC_PTR(id,pattern) else DAE.PAT_AS(id,et,attr,pattern);
then (cache,pattern);
case (cache,_,Absyn.CREF(Absyn.CREF_IDENT(id,{})),ty2,_,_)
equation
(cache,DAE.TYPES_VAR(ty = ty1, attributes = attr),_,_,_,_) = Lookup.lookupIdent(cache,env,id);
Static.checkAssignmentToInput(inLhs, attr, env, false, info);
et = validPatternType(ty2,ty1,inLhs,info);
pattern = if Types.isFunctionType(ty2) then DAE.PAT_AS_FUNC_PTR(id,DAE.PAT_WILD()) else DAE.PAT_AS(id,et,attr,DAE.PAT_WILD());
then (cache,pattern);
case (cache,_,Absyn.AS(id,_),_,_,_)
equation
failure((_,_,_,_,_,_) = Lookup.lookupIdent(cache,env,id));
Error.addSourceMessage(Error.LOOKUP_VARIABLE_ERROR,{id,""},info);
then fail();
case (cache,_,Absyn.CREF(Absyn.CREF_IDENT("NONE",{})),_,_,_)
equation
failure((_,_,_,_,_,_) = Lookup.lookupIdent(cache,env,"NONE"));
Error.addSourceMessage(Error.META_NONE_CREF,{},info);
then fail();
case (cache,_,Absyn.CREF(Absyn.CREF_IDENT(id,{})),_,_,_)
equation
failure((_,_,_,_,_,_) = Lookup.lookupIdent(cache,env,id));
false = "NONE" == id;
Error.addSourceMessage(Error.LOOKUP_VARIABLE_ERROR,{id,""},info);
then fail();
case (cache,_,Absyn.CREF(Absyn.WILD()),_,_,_) then (cache,DAE.PAT_WILD());
case (_,_,lhs,_,_,_)
equation
true = numError == Error.getNumErrorMessages();
str = Dump.printExpStr(lhs) + " of type " + Types.unparseType(ty);
Error.addSourceMessage(Error.META_INVALID_PATTERN, {str}, info);
then fail();
end matchcontinue;
end elabPattern2;
protected function elabPatternTuple
input FCore.Cache inCache;
input FCore.Graph env;
input list<Absyn.Exp> inExps;
input list<DAE.Type> inTys;
input SourceInfo info;
input Absyn.Exp lhs "for error messages";
output FCore.Cache outCache;
output list<DAE.Pattern> patterns;
algorithm
(outCache,patterns) := match (inCache,env,inExps,inTys,info,lhs)
local
Absyn.Exp exp;
String s;
DAE.Pattern pattern;
DAE.Type ty;
FCore.Cache cache;
list<Absyn.Exp> exps;
list<DAE.Type> tys;
case (cache,_,{},{},_,_) then (cache,{});
case (cache,_,exp::exps,ty::tys,_,_)
equation
(cache,pattern) = elabPattern(cache,env,exp,ty,info);
(cache,patterns) = elabPatternTuple(cache,env,exps,tys,info,lhs);
then (cache,pattern::patterns);
else
equation
s = Dump.printExpStr(lhs);
s = "pattern " + s;
Error.addSourceMessage(Error.WRONG_NO_OF_ARGS, {s}, info);
then fail();
end match;
end elabPatternTuple;
protected function elabPatternCall
input FCore.Cache inCache;
input FCore.Graph env;
input Absyn.Path callPath;
input Absyn.FunctionArgs fargs;
input Absyn.Path utPath;
input SourceInfo info;
input Absyn.Exp lhs "for error messages";
output FCore.Cache outCache;
output DAE.Pattern pattern;
algorithm
(outCache,pattern) := matchcontinue (inCache,env,callPath,fargs,utPath,info,lhs)
local
String s;
DAE.Type t;
Absyn.Path utPath1,utPath2,fqPath;
Integer index,numPosArgs;
list<Absyn.NamedArg> namedArgList,invalidArgs;
list<Absyn.Exp> funcArgsNamedFixed,funcArgs;
list<String> fieldNameList,fieldNamesNamed;
list<DAE.Type> fieldTypeList;
list<DAE.Var> fieldVarList;
list<DAE.Pattern> patterns;
list<tuple<DAE.Pattern,String,DAE.Type>> namedPatterns;
Boolean knownSingleton;
FCore.Cache cache;
Boolean allWild;
case (cache,_,_,Absyn.FUNCTIONARGS(funcArgs,namedArgList),utPath2,_,_)
algorithm
(cache,DAE.T_METARECORD(utPath=utPath1,index=index,fields=fieldVarList,knownSingleton = knownSingleton,source = {fqPath}),_) :=
Lookup.lookupType(cache, env, callPath, NONE());
validUniontype(utPath1,utPath2,info,lhs);
fieldTypeList := List.map(fieldVarList, Types.getVarType);
fieldNameList := List.map(fieldVarList, Types.getVarName);
if Flags.isSet(Flags.PATTERNM_ALL_INFO) then
for namedArg in namedArgList loop
_ := match namedArg
case Absyn.NAMEDARG(argValue=Absyn.CREF(Absyn.WILD()))
equation
Error.addSourceMessage(Error.META_EMPTY_CALL_PATTERN, {namedArg.argName}, info);
then ();
else ();
end match;
end for;
if listEmpty(namedArgList) and not listEmpty(funcArgs) then
allWild := true;
for arg in funcArgs loop
allWild := match arg
case Absyn.CREF(Absyn.WILD()) then true;
else false;
end match;
if not allWild then
break;
end if;
end for;
if allWild then
Error.addSourceMessage(Error.META_ALL_EMPTY, {Absyn.pathString(callPath)}, info);
end if;
end if;
end if;
(funcArgs,namedArgList) := checkForAllWildCall(funcArgs,namedArgList,listLength(fieldNameList));
numPosArgs := listLength(funcArgs);
(_,fieldNamesNamed) := List.split(fieldNameList, numPosArgs);
checkMissingArgs(fqPath,numPosArgs,fieldNamesNamed,listLength(namedArgList),info);
(funcArgsNamedFixed,invalidArgs) := generatePositionalArgs(fieldNamesNamed,namedArgList,{});
funcArgs := listAppend(funcArgs,funcArgsNamedFixed);
Util.SUCCESS() := checkInvalidPatternNamedArgs(invalidArgs,fieldNameList,Util.SUCCESS(),info);
(cache,patterns) := elabPatternTuple(cache,env,funcArgs,fieldTypeList,info,lhs);
then (cache,DAE.PAT_CALL(fqPath,index,patterns,fieldVarList,knownSingleton));
case (cache,_,_,Absyn.FUNCTIONARGS(funcArgs,namedArgList),utPath2,_,_)
equation
(cache,DAE.T_FUNCTION(funcResultType = DAE.T_COMPLEX(complexClassType=ClassInf.RECORD(_),varLst=fieldVarList), source = {fqPath}),_) =
Lookup.lookupType(cache, env, callPath, NONE());
true = Absyn.pathEqual(fqPath,utPath2);
fieldTypeList = List.map(fieldVarList, Types.getVarType);
fieldNameList = List.map(fieldVarList, Types.getVarName);
(funcArgs,namedArgList) = checkForAllWildCall(funcArgs,namedArgList,listLength(fieldNameList));
numPosArgs = listLength(funcArgs);
(_,fieldNamesNamed) = List.split(fieldNameList, numPosArgs);
checkMissingArgs(fqPath,numPosArgs,fieldNamesNamed,listLength(namedArgList),info);
(funcArgsNamedFixed,invalidArgs) = generatePositionalArgs(fieldNamesNamed,namedArgList,{});
funcArgs = listAppend(funcArgs,funcArgsNamedFixed);
Util.SUCCESS() = checkInvalidPatternNamedArgs(invalidArgs,fieldNameList,Util.SUCCESS(),info);
(cache,patterns) = elabPatternTuple(cache,env,funcArgs,fieldTypeList,info,lhs);
namedPatterns = List.thread3Tuple(patterns, fieldNameList, List.map(fieldTypeList,Types.simplifyType));
namedPatterns = List.filter(namedPatterns, filterEmptyPattern);
then (cache,DAE.PAT_CALL_NAMED(fqPath,namedPatterns));
case (cache,_,_,_,_,_,_)
equation
failure((_,_,_) = Lookup.lookupType(cache, env, callPath, NONE()));
s = Absyn.pathString(callPath);
Error.addSourceMessage(Error.META_CONSTRUCTOR_NOT_RECORD, {s}, info);
then fail();
end matchcontinue;
end elabPatternCall;
protected function checkMissingArgs
input Absyn.Path path;
input Integer numPosArgs;
input list<String> missingFieldNames;
input Integer numNamedArgs;
input SourceInfo info;
algorithm
_ := match (path,numPosArgs,missingFieldNames,numNamedArgs,info)
local
String str;
list<String> strs;
case (_,_,{},0,_) then ();
/* Language extension to not have to bind everything...
case (_,_,strs,0,_)
equation
str = stringDelimitList(strs,",");
str = Absyn.pathString(path) + " missing pattern for fields: " + str;
Error.addSourceMessage(Error.META_INVALID_PATTERN,{str},info);
then fail();
*/
/*
case (path,_,_,_,info)
equation
str = Absyn.pathString(path) + " mixing positional and named patterns";
Error.addSourceMessage(Error.META_INVALID_PATTERN,{str},info);
then fail();
*/
else ();
end match;
end checkMissingArgs;
protected function checkForAllWildCall "Converts a call REC(__) to REC(_,_,_,_)"
input list<Absyn.Exp> args;
input list<Absyn.NamedArg> named;
input Integer numFields;
output list<Absyn.Exp> outArgs;
output list<Absyn.NamedArg> outNamed;
algorithm
(outArgs,outNamed) := match (args,named,numFields)
case ({Absyn.CREF(Absyn.ALLWILD())},{},_)
then ({},{});
else (args,named);
end match;
end checkForAllWildCall;
protected function validPatternType
input DAE.Type inTy1;
input DAE.Type inTy2;
input Absyn.Exp lhs;
input SourceInfo info;
output Option<DAE.Type> ty;
algorithm
ty := matchcontinue (inTy1,inTy2,lhs,info)
local
DAE.Type et;
String s,s1,s2;
DAE.ComponentRef cr;
DAE.Exp crefExp;
DAE.Type ty1, ty2;
case (DAE.T_METABOXED(ty = ty1),ty2,_,_)
equation
cr = ComponentReference.makeCrefIdent("#DUMMY#",DAE.T_UNKNOWN_DEFAULT,{});
crefExp = Expression.crefExp(cr);
(_,ty1) = Types.matchType(crefExp,ty1,ty2,true);
et = Types.simplifyType(ty1);
then SOME(et);
case (ty1,ty2,_,_)
equation
cr = ComponentReference.makeCrefIdent("#DUMMY#",DAE.T_UNKNOWN_DEFAULT,{});
crefExp = Expression.crefExp(cr);
(_,_) = Types.matchType(crefExp,ty1,ty2,true);
then NONE();
case (ty1,ty2,_,_)
equation
s = Dump.printExpStr(lhs);
s1 = Types.unparseType(ty1);
s2 = Types.unparseType(ty2);
Error.addSourceMessage(Error.META_TYPE_MISMATCH_PATTERN, {s,s1,s2}, info);
then fail();
end matchcontinue;
end validPatternType;
protected function validUniontype
input Absyn.Path path1;
input Absyn.Path path2;
input SourceInfo info;
input Absyn.Exp lhs;
algorithm
_ := matchcontinue (path1,path2,info,lhs)
local
String s,s1,s2;
case (_,_,_,_)
equation
true = Absyn.pathEqual(path1,path2);
then ();
else
equation
s = Dump.printExpStr(lhs);
s1 = Absyn.pathString(path1);
s2 = Absyn.pathString(path2);
Error.addSourceMessage(Error.META_CONSTRUCTOR_NOT_PART_OF_UNIONTYPE, {s,s1,s2}, info);
then fail();
end matchcontinue;
end validUniontype;
public function patternStr "Pattern to String unparsing"
input DAE.Pattern pattern;
output String str;
algorithm
str := matchcontinue pattern
local
list<DAE.Pattern> pats;
list<String> fields,patsStr;
DAE.Exp exp;
DAE.Pattern pat,head,tail;
String id;
list<tuple<DAE.Pattern,String,DAE.Type>> namedpats;
Absyn.Path name;
case DAE.PAT_WILD() then "_";
case DAE.PAT_AS(id=id,pat=DAE.PAT_WILD()) then id;
case DAE.PAT_AS_FUNC_PTR(id,DAE.PAT_WILD()) then id;
case DAE.PAT_SOME(pat)
equation
str = patternStr(pat);
then "SOME(" + str + ")";
case DAE.PAT_META_TUPLE(pats)
equation
str = stringDelimitList(List.map(pats,patternStr),",");
then "(" + str + ")";
case DAE.PAT_CALL_TUPLE(pats)
equation
str = stringDelimitList(List.map(pats,patternStr),",");
then "(" + str + ")";
case DAE.PAT_CALL(name=name, patterns=pats)
equation
id = Absyn.pathString(name);
str = stringDelimitList(List.map(pats,patternStr),",");
then stringAppendList({id,"(",str,")"});
case DAE.PAT_CALL_NAMED(name=name, patterns=namedpats)
equation
id = Absyn.pathString(name);
fields = List.map(namedpats, Util.tuple32);
patsStr = List.map1r(List.mapMap(namedpats, Util.tuple31, patternStr), stringAppend, "=");
str = stringDelimitList(List.threadMap(fields, patsStr, stringAppend), ",");
then stringAppendList({id,"(",str,")"});
case DAE.PAT_CONS(head,tail) then patternStr(head) + "::" + patternStr(tail);
case DAE.PAT_CONSTANT(exp=exp) then ExpressionDump.printExpStr(exp);
// case DAE.PAT_CONSTANT(SOME(et),exp) then "(" + Types.unparseType(et) + ")" + ExpressionDump.printExpStr(exp);
case DAE.PAT_AS(id=id,pat=pat) then id + " as " + patternStr(pat);
case DAE.PAT_AS_FUNC_PTR(id, pat) then id + " as " + patternStr(pat);
else
equation
Error.addMessage(Error.INTERNAL_ERROR, {"Patternm.patternStr not implemented correctly"});
then "*PATTERN*";
end matchcontinue;
end patternStr;
public function elabMatchExpression
input FCore.Cache inCache;
input FCore.Graph inEnv;
input Absyn.Exp matchExp;
input Boolean impl;
input Option<GlobalScript.SymbolTable> inSt;
input Boolean performVectorization;
input Prefix.Prefix inPrefix;
input SourceInfo info;
output FCore.Cache outCache;
output DAE.Exp outExp;
output DAE.Properties outProperties;
output Option<GlobalScript.SymbolTable> outSt;
protected
Integer numError := Error.getNumErrorMessages();
algorithm
(outCache,outExp,outProperties,outSt) := matchcontinue (inCache,inEnv,matchExp,impl,inSt,performVectorization,inPrefix,info,numError)
local
Absyn.MatchType matchTy;
Absyn.Exp inExp;
list<Absyn.Exp> inExps;
list<Absyn.ElementItem> decls;
list<Absyn.Case> cases;
list<DAE.Element> matchDecls;
Option<GlobalScript.SymbolTable> st;
Prefix.Prefix pre;
list<DAE.Exp> elabExps;
list<DAE.MatchCase> elabCases;
list<DAE.Type> tys;
DAE.Properties prop;
list<DAE.Properties> elabProps;
DAE.Type resType;
DAE.Type et;
String str;
DAE.Exp exp;
HashTableStringToPath.HashTable ht;
DAE.MatchType elabMatchTy;
FCore.Cache cache;
FCore.Graph env;
Integer hashSize;
list<list<String>> inputAliases,inputAliasesAndCrefs;
AvlTreeString.AvlTree declsTree;
case (cache,env,Absyn.MATCHEXP(matchTy=matchTy,inputExp=inExp,localDecls=decls,cases=cases),_,st,_,pre,_,_)
equation
// First do inputs
inExps = MetaUtil.extractListFromTuple(inExp, 0);
(inExps,inputAliases,inputAliasesAndCrefs) = List.map_3(inExps,getInputAsBinding);
(cache,elabExps,elabProps,st) = Static.elabExpList(cache,env,inExps,impl,st,performVectorization,pre,info);
// Then add locals
(cache,SOME((env,DAE.DAE(matchDecls),declsTree))) = addLocalDecls(cache,env,decls,FCore.matchScopeName,impl,info);
tys = List.map(elabProps, Types.getPropType);
env = addAliasesToEnv(env, tys, inputAliases, info);
(cache,elabCases,resType,st) = elabMatchCases(cache,env,cases,tys,inputAliasesAndCrefs,declsTree,impl,st,performVectorization,pre,info);
prop = DAE.PROP(resType,DAE.C_VAR());
et = Types.simplifyType(resType);
(elabExps,inputAliases,elabCases) = filterUnusedPatterns(elabExps,inputAliases,elabCases) "filterUnusedPatterns() First time to speed up the other optimizations.";
elabCases = caseDeadCodeElimination(matchTy, elabCases, {}, {}, false);
// Do DCE before converting mc to m
matchTy = optimizeContinueToMatch(matchTy,elabCases,info);
elabCases = optimizeContinueJumps(matchTy, elabCases);
// hashSize = Util.nextPowerOf2(listLength(matchDecls)) + 1; // faster, but unstable in RML
hashSize = Util.nextPrime(listLength(matchDecls));
ht = getUsedLocalCrefs(Flags.isSet(Flags.PATTERNM_SKIP_FILTER_UNUSED_AS_BINDINGS),DAE.MATCHEXPRESSION(DAE.MATCHCONTINUE(),elabExps,inputAliases,matchDecls,elabCases,et),hashSize);
(matchDecls,ht) = filterUnusedDecls(matchDecls,ht,{},HashTableStringToPath.emptyHashTableSized(hashSize));
(elabExps,inputAliases,elabCases) = filterUnusedPatterns(elabExps,inputAliases,elabCases) "filterUnusedPatterns() again to filter out the last parts.";
elabMatchTy = optimizeMatchToSwitch(matchTy,elabCases,info);
exp = DAE.MATCHEXPRESSION(elabMatchTy,elabExps,inputAliases,matchDecls,elabCases,et);
then (cache,exp,prop,st);
else
equation
true = numError == Error.getNumErrorMessages();
str = Dump.printExpStr(matchExp);
Error.addSourceMessage(Error.META_MATCH_GENERAL_FAILURE, {str}, info);
then fail();
end matchcontinue;
end elabMatchExpression;
protected function optimizeMatchToSwitch
"match str case 'str1' ... case 'str2' case 'str3' => switch hash(str)...
match ut case UT1 ... case UT2 ... case UT3 => switch valueConstructor(ut)...
match int case 1 ... case 17 ... case 2 => switch(int)...
Works if all values are unique. Also works if there is one 'default' case at the end of the list (and there is only 1 pattern):
case (1,_) ... case (_,_) ... works
case (1,2) ... case (_,_) ... does not work
.
"
input Absyn.MatchType matchTy;
input list<DAE.MatchCase> cases;
input SourceInfo info;
output DAE.MatchType outType;
algorithm
outType := matchcontinue (matchTy,cases,info)
local
tuple<Integer,DAE.Type,Integer> tpl;
list<list<DAE.Pattern>> patternMatrix;
list<Option<list<DAE.Pattern>>> optPatternMatrix;
Integer numNonEmptyColumns;
String str;
DAE.Type ty;
case (Absyn.MATCHCONTINUE(),_,_) then DAE.MATCHCONTINUE();
case (_,_,_)
equation
true = listLength(cases) > 2;
patternMatrix = List.transposeList(List.map(cases,getCasePatterns));
(optPatternMatrix,numNonEmptyColumns) = removeWildPatternColumnsFromMatrix(patternMatrix,{},0);
tpl = findPatternToConvertToSwitch(optPatternMatrix,0,numNonEmptyColumns,info);
(_,ty,_) = tpl;
str = Types.unparseType(ty);
Error.assertionOrAddSourceMessage(not Flags.isSet(Flags.PATTERNM_ALL_INFO),Error.MATCH_TO_SWITCH_OPTIMIZATION, {str}, info);
then DAE.MATCH(SOME(tpl));
else DAE.MATCH(NONE());
end matchcontinue;
end optimizeMatchToSwitch;
protected function removeWildPatternColumnsFromMatrix
input list<list<DAE.Pattern>> inPatternMatrix;
input list<Option<list<DAE.Pattern>>> inAcc;
input Integer inNumAcc;
output list<Option<list<DAE.Pattern>>> optPatternMatrix;
output Integer numNonEmptyColumns;
algorithm
(optPatternMatrix,numNonEmptyColumns) := match (inPatternMatrix,inAcc,inNumAcc)
local
Boolean alwaysMatch;
list<DAE.Pattern> pats;
Option<list<DAE.Pattern>> optPats;
list<list<DAE.Pattern>> patternMatrix;
list<Option<list<DAE.Pattern>>> acc;
Integer numAcc;
case ({},acc,numAcc) then (listReverse(acc),numAcc);
case (pats::patternMatrix,acc,numAcc)
equation
alwaysMatch = allPatternsAlwaysMatch(List.stripLast(pats));
optPats = if alwaysMatch then NONE() else SOME(pats);
numAcc = if alwaysMatch then numAcc else numAcc+1;
(acc,numAcc) = removeWildPatternColumnsFromMatrix(patternMatrix,optPats::acc,numAcc);
then (acc,numAcc);
end match;
end removeWildPatternColumnsFromMatrix;
protected function findPatternToConvertToSwitch
input list<Option<list<DAE.Pattern>>> inPatternMatrix;
input Integer index;
input Integer numPatternsInMatrix "If there is only 1 pattern, we can optimize the default case";
input SourceInfo info;
output tuple<Integer,DAE.Type,Integer> tpl;
algorithm
tpl := matchcontinue (inPatternMatrix,index,numPatternsInMatrix,info)
local
list<DAE.Pattern> pats;
DAE.Type ty;
Integer extraarg;
list<Option<list<DAE.Pattern>>> patternMatrix;
case (SOME(pats)::_,_,_,_)
equation
(ty,extraarg) = findPatternToConvertToSwitch2(pats, {}, DAE.T_UNKNOWN_DEFAULT, true, numPatternsInMatrix);
then ((index,ty,extraarg));
case (_::patternMatrix,_,_,_)
then findPatternToConvertToSwitch(patternMatrix,index+1,numPatternsInMatrix,info);
end matchcontinue;
end findPatternToConvertToSwitch;
protected function findPatternToConvertToSwitch2
input list<DAE.Pattern> ipats;
input list<Integer> ixs;
input DAE.Type ity;
input Boolean allSubPatternsMatch;
input Integer numPatternsInMatrix;
output DAE.Type outTy;
output Integer extraarg;
algorithm
(outTy,extraarg) := match (ipats,ixs,ity,allSubPatternsMatch,numPatternsInMatrix)
local
Integer ix;
String str;
list<DAE.Pattern> pats,subpats;
DAE.Type ty;
case (DAE.PAT_CONSTANT(exp=DAE.SCONST(str))::pats,_,_,_,_)
equation
ix = System.stringHashDjb2Mod(str,65536);
false = listMember(ix,ixs);
(ty,extraarg) = findPatternToConvertToSwitch2(pats,ix::ixs,DAE.T_STRING_DEFAULT,allSubPatternsMatch,numPatternsInMatrix);
then (ty,extraarg);
case (DAE.PAT_CALL(index=ix,patterns=subpats)::pats,_,_,_,_)
equation
false = listMember(ix,ixs);
(ty,extraarg) = findPatternToConvertToSwitch2(pats,ix::ixs,DAE.T_METATYPE_DEFAULT,allSubPatternsMatch and allPatternsAlwaysMatch(subpats),numPatternsInMatrix);
then (ty,extraarg);
case (DAE.PAT_CONSTANT(exp=DAE.ICONST(ix))::pats,_,_,_,_)
equation
false = listMember(ix,ixs);
(ty,extraarg) = findPatternToConvertToSwitch2(pats,ix::ixs,DAE.T_INTEGER_DEFAULT,allSubPatternsMatch,numPatternsInMatrix);
then (ty,extraarg);
case ({},_,DAE.T_STRING(),_,_)
equation
true = listLength(ixs)>11; // hashing has a considerable overhead, only convert to switch if it is worth it
ix = findMinMod(ixs,1);
then (DAE.T_STRING_DEFAULT,ix);
case ({_},_,DAE.T_STRING(),_,1)
equation
true = listLength(ixs)>11; // hashing has a considerable overhead, only convert to switch if it is worth it
ix = findMinMod(ixs,1);
then (DAE.T_STRING_DEFAULT,ix);
case ({},_,_,_,_) then (ity,0);
// Sadly, we cannot switch a default uniontype as the previous case in not guaranteed
// to succeed matching if it matches for subpatterns.
case ({_},_,_,true,1) then (ity,0);
end match;
end findPatternToConvertToSwitch2;
protected function findMinMod
input list<Integer> inIxs;
input Integer inMod;
output Integer outMod;
algorithm
outMod := matchcontinue (inIxs,inMod)
local list<Integer> ixs; Integer mod;
case (ixs,mod)
equation
ixs = List.map1(ixs, intMod, mod);
ixs = List.sort(ixs, intLt);
{} = List.sortedDuplicates(ixs, intEq);
// This mod was high enough that all values were distinct
then mod;
else
equation
true = inMod < 65536;
then findMinMod(inIxs,inMod*2);
end matchcontinue;
end findMinMod;
protected function filterUnusedPatterns
"case (1,_,_) then ...; case (2,_,_) then ...; =>"
input list<DAE.Exp> inputs "We can only remove inputs that are free from side-effects";
input list<list<String>> inAliases;
input list<DAE.MatchCase> inCases;
output list<DAE.Exp> outInputs;
output list<list<String>> outAliases;
output list<DAE.MatchCase> outCases;
algorithm
(outInputs,outAliases,outCases) := matchcontinue (inputs,inAliases,inCases)
local
list<list<DAE.Pattern>> patternMatrix;
list<DAE.MatchCase> cases;
case (_,_,cases)
equation
patternMatrix = List.transposeList(List.map(cases,getCasePatterns));
(true,outInputs,outAliases,patternMatrix) = filterUnusedPatterns2(inputs,inAliases,patternMatrix,false,{},{},{});
patternMatrix = List.transposeList(patternMatrix);
cases = setCasePatternsCheckZero(cases,patternMatrix);
then (outInputs,outAliases,cases);
else (inputs,inAliases,inCases);
end matchcontinue;
end filterUnusedPatterns;
protected function setCasePatternsCheckZero
"Handles the case when the pattern matrix becomes empty because no input is matched"
input list<DAE.MatchCase> inCases;
input list<list<DAE.Pattern>> patternMatrix;
output list<DAE.MatchCase> outCases;
algorithm
outCases := match (inCases,patternMatrix)
case ({},{}) then inCases;
case (_,{})
then List.map1(inCases,setCasePatterns,{});
else List.threadMap(inCases,patternMatrix,setCasePatterns);
end match;
end setCasePatternsCheckZero;
protected function filterUnusedPatterns2
"case (1,_,_) then ...; case (2,_,_) then ...; =>"
input list<DAE.Exp> inInputs "We can only remove inputs that are free from side-effects";
input list<list<String>> inAliases;
input list<list<DAE.Pattern>> inPatternMatrix;
input Boolean change "Only rebuild the cases if something changed";
input list<DAE.Exp> inputsAcc;
input list<list<String>> aliasesAcc;
input list<list<DAE.Pattern>> patternMatrixAcc;
output Boolean outChange;
output list<DAE.Exp> outInputs;
output list<list<String>> outAliases;
output list<list<DAE.Pattern>> outPatternMatrix;
algorithm
(outChange,outInputs,outAliases,outPatternMatrix) := matchcontinue (inInputs,inAliases,inPatternMatrix,change,inputsAcc,aliasesAcc,patternMatrixAcc)
local
DAE.Exp e;
list<DAE.Pattern> pats;
list<DAE.Exp> inputs;
list<list<DAE.Pattern>> patternMatrix;
list<String> alias;
list<list<String>> aliases;
case ({},{},{},true,_,_,_)
then (true,listReverse(inputsAcc),listReverse(aliasesAcc),listReverse(patternMatrixAcc));
case (e::inputs,_::aliases,pats::patternMatrix,_,_,_,_)
equation
(_,true) = Expression.traverseExp(e,Expression.hasNoSideEffects,true);
true = allPatternsWild(pats);
(outChange,outInputs,outAliases,outPatternMatrix) = filterUnusedPatterns2(inputs,aliases,patternMatrix,true,inputsAcc,aliasesAcc,patternMatrixAcc);
then (outChange,outInputs,outAliases,outPatternMatrix);
case (e::inputs,alias::aliases,pats::patternMatrix,_,_,_,_)
equation
(outChange,outInputs,outAliases,outPatternMatrix) = filterUnusedPatterns2(inputs,aliases,patternMatrix,change,e::inputsAcc,alias::aliasesAcc,pats::patternMatrixAcc);
then (outChange,outInputs,outAliases,outPatternMatrix);
else (false,{},{},{});
end matchcontinue;
end filterUnusedPatterns2;
protected function getUsedLocalCrefs
input Boolean skipFilterUnusedAsBindings "if true, traverse the whole expression; else only the bodies and results";
input DAE.Exp exp;
input Integer hashSize;
output HashTableStringToPath.HashTable ht;
algorithm
ht := match (skipFilterUnusedAsBindings,exp,hashSize)
local
list<DAE.MatchCase> cases;
case (true,_,_)
equation
(_,ht) = Expression.traverseExp(exp, addLocalCref, HashTableStringToPath.emptyHashTableSized(hashSize));
then ht;
case (false,DAE.MATCHEXPRESSION(cases=cases),_)
equation
(_,ht) = traverseCases(cases, addLocalCref, HashTableStringToPath.emptyHashTableSized(hashSize));
then ht;
end match;
end getUsedLocalCrefs;
protected function filterUnusedAsBindings
input list<DAE.MatchCase> inCases;
input HashTableStringToPath.HashTable ht;
output list<DAE.MatchCase> outCases;
algorithm
outCases := match (inCases,ht)
local
list<DAE.Pattern> patterns;
list<DAE.Element> localDecls;
list<DAE.Statement> body;
Option<DAE.Exp> guardPattern, result;
Integer jump;