-
Notifications
You must be signed in to change notification settings - Fork 0
/
Syntax.cs
946 lines (754 loc) · 25.7 KB
/
Syntax.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Globalization;
namespace MkFn {
/*
フィールドの種類
*/
public enum FieldKind {
Unknown,
DomainField,
CalculatedField,
ParameterField,
}
/*
クラス
*/
public class Class {
// 親
public Class Parent;
// クラス名
public string Name;
// フィールドのリスト
public List<Variable> Fields = new List<Variable>();
// 関数のリスト
public List<Function> Functions = new List<Function>();
// 次元 (スカラーは0, 1次元配列は1, 2次元配列は2, ... )
public int DimCnt;
public Class(string name) {
Name = name;
}
public void AddField(Variable fld) {
Fields.Add(fld);
fld.ParentVar = this;
}
public virtual Class ValueType() {
return this;
}
public override string ToString() {
return Name;
}
public bool IsSubClass(Class cls) {
return Parent == cls;
}
}
/*
配列の型
*/
public class ArrayType : Class {
// 要素の型
public Class ElementType;
public ArrayType(Class element_type, int dim_cnt) : base(element_type.Name) {
ElementType = element_type;
DimCnt = dim_cnt;
}
public override Class ValueType() {
return ElementType;
}
public override string ToString() {
switch (MkFn.OutputLanguage) {
case Language.CPP:
case Language.CUDA:
return Name + "*";
case Language.CS:
case Language.MathJax:
return Name + "[" + new string(',', DimCnt - 1) + "]";
default:
throw new Exception();
}
}
}
/*
変数
*/
public class Variable {
// 親
public object ParentVar;
// 変数名
public string Name;
// 変数の型
public Class TypeVar;
// 定義域
public Term Domain;
// フィールドの種類
public FieldKind Kind = FieldKind.Unknown;
public bool IsField() {
return !(this is Function) && ParentVar is Class;
}
public Variable(string name, Class type, Term domain, FieldKind kind = FieldKind.Unknown) {
Name = name;
TypeVar = type;
Domain = domain;
Kind = kind;
if (Domain != null) {
Domain.Parent = this;
}
}
/*
コピーを返します。
*/
public Variable Clone(Dictionary<Variable, Variable> var_tbl = null) {
if (this is Function) {
return (this as Function).Clone(var_tbl);
}
if(var_tbl == null) {
var_tbl = new Dictionary<Variable, Variable>();
}
Term domain = (Domain == null ? null : Domain.Clone(var_tbl));
Variable v1 = new Variable(Name, TypeVar, domain);
var_tbl.Add(this, v1);
return v1;
}
public virtual string Code() {
return ToString();
}
public override string ToString() {
if (TypeVar == null) {
return Name;
}
return TypeVar.ToString() + " " + Name;
}
}
/*
関数
*/
public class Function : Variable {
// 仮引数
public List<Variable> Params = new List<Variable>();
// 関数の本体
public BlockStatement BodyStatement;
public Function(string name, Class type) : base(name, type, null) {
}
/*
コピーを返します。
*/
public new Function Clone(Dictionary<Variable, Variable> var_tbl = null) {
if (var_tbl == null) {
var_tbl = new Dictionary<Variable, Variable>();
}
Term domain = (Domain == null ? null : Domain.Clone(var_tbl));
Function fnc = new Function(Name, TypeVar);
var_tbl.Add(this, fnc);
fnc.Params = (from x in Params select x.Clone(var_tbl)).ToList();
fnc.BodyStatement = BodyStatement.Clone(var_tbl);
return fnc;
}
/*
コンストラクターならtrueを返します。
*/
public bool IsConstructor() {
return Name == MkFn.ConstructorName(ParentVar as Class);
}
}
/*
文
*/
public class Statement {
// 親
public object ParentStmt;
/*
コピーを返します。
*/
public Statement Clone(Dictionary<Variable, Variable> var_tbl = null) {
if (this is Assignment) {
// 変数参照の場合
return (this as Assignment).Clone(var_tbl);
}
else if (this is Return) {
// 数値定数の場合
return (this as Return).Clone(var_tbl);
}
else if (this is ForEach) {
// 関数適用の場合
return (this as ForEach).Clone(var_tbl);
}
else if (this is BlockStatement) {
// LINQの場合
return (this as BlockStatement).Clone(var_tbl);
}
else {
Debug.Assert(false);
return null;
}
}
}
/*
代入文
*/
public class Assignment : Statement {
// 左辺
public Reference Left;
// 右辺
public Term Right;
public Assignment(Reference left, Term right) {
Left = left;
Right = right;
Left.Parent = this;
Right.Parent = this;
}
public override string ToString() {
return Left.ToString() + " = " + Right.ToString();
}
/*
コピーを返します。
*/
public new Assignment Clone(Dictionary<Variable, Variable> var_tbl = null) {
return new Assignment(Left.Clone(var_tbl), Right.Clone(var_tbl));
}
}
/*
return文
*/
public class Return : Statement {
// 戻り値
public Term Value;
public Return(Term value) {
Value = value;
}
/*
コピーを返します。
*/
public new Return Clone(Dictionary<Variable, Variable> var_tbl) {
return new Return(Value == null ? null : Value.Clone(var_tbl));
}
}
/*
ブロック文
*/
public class BlockStatement : Statement {
// 文のリスト
public List<Statement> Statements;
public BlockStatement(List<Statement> statements) {
Statements = statements;
foreach (Statement s in Statements) {
s.ParentStmt = this;
}
}
public void AddStatement(Statement stmt) {
Statements.Add(stmt);
stmt.ParentStmt = this;
}
/*
コピーを返します。
*/
public new BlockStatement Clone(Dictionary<Variable, Variable> var_tbl) {
return new BlockStatement( (from x in Statements select x.Clone(var_tbl)).ToList() );
}
}
/*
foreach文
*/
public class ForEach : BlockStatement {
// ループ変数
public List<Variable> LoopVariables = new List<Variable>();
public ForEach(IEnumerable<Variable> variables, List<Statement> statements) : base(statements) {
LoopVariables.AddRange(variables);
foreach(Variable va in variables) {
va.ParentVar = this;
}
foreach (Statement s in Statements) {
s.ParentStmt = this;
}
}
/*
コピーを返します。
*/
public new ForEach Clone(Dictionary<Variable, Variable> var_tbl) {
if (var_tbl == null) {
var_tbl = new Dictionary<Variable, Variable>();
}
return new ForEach(from va in LoopVariables select va.Clone(var_tbl), (from x in Statements select x.Clone(var_tbl)).ToList());
}
}
/*
項
*/
public abstract class Term {
public static int TermCnt;
public int TermIdx;
// 親
public object Parent;
// 係数
public double Value = 1;
// 項の型
public Class TypeTerm;
public Term() {
TermCnt++;
TermIdx = TermCnt;
//if (TermIdx == 1666) {
// Debug.Write("");
//}
}
/*
係数を除く本体が同じならtrueを返します。
*/
public abstract bool EqBody(object obj);
/*
係数と本体が同じならtrueを返します。
*/
public virtual bool Eq(object obj) {
return obj is Term && Value == (obj as Term).Value && EqBody(obj);
}
/*
コピーを返します。
*/
public Term Clone(Dictionary<Variable, Variable> var_tbl = null) {
if (this is Reference) {
// 変数参照の場合
return (this as Reference).Clone(var_tbl);
}
else if (this is Number) {
// 数値定数の場合
return (this as Number).Clone(var_tbl);
}
else if (this is Apply) {
// 関数適用の場合
return AsApply().Clone(var_tbl);
}
else if (this is LINQ) {
// LINQの場合
return (this as LINQ).Clone(var_tbl);
}
else {
Debug.Assert(false);
return null;
}
}
public Term Minus() {
Value *= -1;
return this;
}
/*
Applyにキャストします。
*/
public Apply AsApply() {
return this as Apply;
}
/*
Referenceにキャストします。
*/
public Reference AsReference() {
return this as Reference;
}
/*
加算ならtrueを返します。
*/
public bool IsAdd() {
return this is Apply && AsApply().FunctionApp.VarRef == MkFn.Singleton.AddFnc;
}
/*
乗算ならtrueを返します。
*/
public bool IsMul() {
return this is Apply && AsApply().FunctionApp.VarRef == MkFn.Singleton.MulFnc;
}
public virtual string Code() {
return ToString();
}
public override string ToString() {
if (!(this is Number)) {
// 数値定数でない場合
if (Value == 1) {
return ToStringBody();
}
else if (Value == -1) {
return "- " + ToStringBody();
}
else {
return Value.ToString() + " * " + ToStringBody();
}
}
else {
return ToStringBody();
}
}
public abstract string ToStringBody();
public virtual int HashCode() {
return GetHashCode();
}
}
/*
数値定数
*/
public class Number : Term {
public Number(string text, TokenSubType sub_type) {
switch (sub_type) {
case TokenSubType.Integer:
int n;
if (!int.TryParse(text, out n)) {
throw new SyntaxException();
}
Value = n;
TypeTerm = MkFn.Singleton.IntClass;
break;
case TokenSubType.Float:
float f;
if (text.Last() == 'f') {
text = text.Substring(0, text.Length - 1);
}
if (!float.TryParse(text, out f)) {
throw new SyntaxException();
}
Value = f;
TypeTerm = MkFn.Singleton.FloatClass;
break;
case TokenSubType.Double:
if (!double.TryParse(text, out Value)) {
throw new SyntaxException();
}
TypeTerm = MkFn.Singleton.DoubleClass;
break;
}
}
public Number(double d, Class type = null) {
Value = d;
if (type == null) {
Debug.Assert(Value == Math.Floor(Value));
TypeTerm = MkFn.Singleton.IntClass;
}
else {
TypeTerm = type;
}
}
/*
コピーを返します。
*/
public new Number Clone(Dictionary<Variable, Variable> var_tbl) {
return new Number(Value, TypeTerm);
}
/*
係数を除く本体が同じならtrueを返します。
*/
public override bool EqBody(object obj) {
return obj is Number;
}
public override string ToStringBody() {
return Value.ToString();
}
public override int HashCode() {
return GetType().GetHashCode() + (int)Value;
}
}
/*
変数参照
*/
public class Reference : Term {
// 変数名
public string Name;
// 参照している変数
public Variable VarRef;
// 配列の添え字
public Term[] Indexes;
public Reference(string name, Variable ref_var, Term[] idx, double val = 1) {
Name = name;
VarRef = ref_var;
Indexes = idx;
Value = val;
if (Indexes != null) {
foreach (Term t in Indexes) {
t.Parent = this;
}
}
}
public Reference(Variable v, double val = 1) {
Name = v.Name;
VarRef = v;
Indexes = null;
}
/*
コピーを返します。
*/
public new Reference Clone(Dictionary<Variable, Variable> var_tbl = null) {
Variable v1;
Reference clone_ref;
if (var_tbl == null || !var_tbl.TryGetValue(VarRef, out v1)) {
v1 = VarRef;
}
if (Indexes == null) {
clone_ref = new Reference(Name, v1, null, Value);
}
else {
Term[] idx = (from t in Indexes select t.Clone(var_tbl)).ToArray();
clone_ref = new Reference(Name, v1, idx, Value);
if (MkFn.Singleton.CloneTable != null && MkFn.Singleton.CloneTable.ContainsKey(this)) {
MkFn.Singleton.CloneTable[this] = clone_ref;
}
}
clone_ref.TypeTerm = TypeTerm;
return clone_ref;
}
/*
係数を除く本体が同じならtrueを返します。
*/
public override bool EqBody(object obj) {
if (!(obj is Reference)) {
// 変数参照でない場合
return false;
}
Reference r = obj as Reference;
if (r.VarRef != VarRef) {
return false;
}
if ((Indexes == null) != (r.Indexes == null)) {
return false;
}
if (Indexes == null) {
return true;
}
else {
Debug.Assert(Indexes.Length == r.Indexes.Length);
for (int i = 0; i < Indexes.Length; i++) {
if (!Indexes[i].Eq(r.Indexes[i])) {
return false;
}
}
return true;
}
}
/*
値の定義ならtrueを返します。
*/
public bool Defined() {
return Parent is Assignment && (Parent as Assignment).Left == this;
}
/*
値の使用ならtrueを返します。
*/
public bool Used() {
return !Defined();
}
public override string ToStringBody() {
if (Indexes == null) {
return Name;
}
else {
string idx;
if (MkFn.OutputLanguage == Language.CUDA || MkFn.OutputLanguage == Language.CPP) {
idx = MkFn.OffsetFromIndexes(this);
string str = Name + "[" + idx + "]";
if (MkFn.Singleton.t_var != null && Indexes.Any(x => MkFn.Is_t_plus(x))) {
return "(t + 1 < T ? " + str + " : 0)";
}
else if (MkFn.Singleton.t_var != null && Indexes.Any(x => MkFn.Is_t_minus(x))) {
return "(0 <= t - 1 ? " + str + " : 0)";
}
else {
return str;
}
}
else {
idx = string.Join(", ", from x in Indexes select x.ToString());
return Name + "[" + idx + "]";
}
}
}
public override int HashCode() {
int n = GetType().GetHashCode() + ((int)Value) + Name.GetHashCode();
if(Indexes != null) {
n += Indexes.Sum(x => x.HashCode());
}
return n;
}
}
/*
関数適用
*/
public class Apply : Term {
// 関数
public Reference FunctionApp;
public Class NewClass;
// 引数
public Term[] Args;
public Class Cast;
public Apply(Reference function, Term[] args) {
FunctionApp = function;
Args = args;
FunctionApp.Parent = this;
foreach (Term t in Args) {
t.Parent = this;
}
}
public Apply(Variable function, params Term[] args) : this(new Reference(function), args) {
}
public Apply(Variable function, Class new_class, params Term[] args) : this(new Reference(function), args) {
Debug.Assert(new_class != null);
NewClass = new_class;
}
/*
コピーを返します。
*/
public new Apply Clone(Dictionary<Variable, Variable> var_tbl = null) {
Term[] args = (from t in Args select t.Clone(var_tbl)).ToArray();
Apply app = new Apply(FunctionApp.Clone(var_tbl), args);
app.NewClass = NewClass;
app.Value = Value;
app.TypeTerm = TypeTerm;
return app;
}
public override string ToStringBody() {
if ("+-*/%".Contains(FunctionApp.Name[0])) {
string s;
Debug.Assert(Args.Length != 1);
if (IsAdd()) {
// 加算の場合
//s = string.Join(" ", from x in Args select (x == Args[0] || x.Value < 0 ? "" : "+ ") + (Math.Abs(x.Value) == 1 ? x.ToStringBody() : x.ToString()));
s = string.Join(" ", from x in Args select (x == Args[0] || x.Value < 0 ? "" : "+ ") + x.ToString());
}
else {
// 加算でない場合
s = string.Join(" " + FunctionApp.Name + " ", from x in Args select x.ToString());
}
if (Parent is Apply && (Parent as Apply).Precedence() <= Precedence()) {
// 親の演算子の優先順位が高い場合
// カッコで囲みます。
return "(" + s + ")";
}
else {
return s;
}
}
else {
// 演算子でない場合
if (FunctionApp.VarRef == MkFn.Singleton.DiffFnc && Args[0] is Reference && (Args[0] as Reference).VarRef == MkFn.Singleton.EFnc) {
return "δ_" + Args[1].ToString();
}
else if (FunctionApp.VarRef == MkFn.Singleton.MaxPoolPrimeFnc) {
Reference x = Args[0] as Reference;
Reference y = Args[1] as Reference;
string x_idx = MkFn.OffsetFromIndexes(x);
string y_idx = MkFn.OffsetFromIndexes(y);
return string.Format("({0}[{1}] == {2} ? {3}[{2}] : 0)", MkFn.IndexName(x.VarRef), y_idx, x_idx, x.Name);
}
else if (MkFn.IsNew(this)) {
return FunctionApp.Name + " " + NewClass.Name + "[" + string.Join(", ", from x in Args select x.ToString()) + "]";
}
else {
return FunctionApp.Name + "(" + string.Join(", ", from x in Args select x.ToString()) + ")";
}
}
}
/*
係数を除く本体が同じならtrueを返します。
*/
public override bool EqBody(object obj) {
if (!(obj is Apply)) {
// 関数適用でない場合
return false;
}
Apply app = obj as Apply;
if ( ! FunctionApp.Eq(app.FunctionApp) ) {
// 関数が違う場合
return false;
}
if (Args.Length != app.Args.Length) {
// 引数の数が違う場合
return false;
}
for (int i = 0; i < Args.Length; i++) {
if (!Args[i].Eq(app.Args[i])) {
// 引数が違う場合
return false;
}
}
return true;
}
/*
演算子の優先順位を返します。
*/
public int Precedence() {
if (Char.IsLetter(FunctionApp.Name[0])) {
return 20;
}
if ("*/%".Contains(FunctionApp.Name[0])) {
return 1;
}
if (Args.Length == 1 && "+-!".Contains(FunctionApp.Name[0])) {
return 2;
}
return 10;
}
public override int HashCode() {
int n = GetType().GetHashCode() + ((int)Value) + FunctionApp.HashCode();
n += (int)Args.Sum(x => (double)x.HashCode());
return n;
}
}
/*
LINQ
*/
public class LINQ : Term {
// ループ変数
public Variable[] Variables;
// select句
public Term Select;
// 集計関数
public Reference Aggregate;
public LINQ(Variable[] variables, Term select1, Reference aggregate, double val = 1) {
Variables = variables;
Select = select1;
Aggregate = aggregate;
Value = val;
foreach (Variable v in Variables) {
v.ParentVar = this;
}
Select.Parent = this;
if (Aggregate != null) {
Aggregate.Parent = this;
}
}
/*
係数を除く本体が同じならtrueを返します。
*/
public override bool EqBody(object obj) {
return this == obj;
}
/*
コピーを返します。
*/
public new LINQ Clone(Dictionary<Variable, Variable> var_tbl) {
if (var_tbl == null) {
var_tbl = new Dictionary<Variable, Variable>();
}
Variable[] vars = (from v in Variables select v.Clone(var_tbl)).ToArray();
LINQ lnq = new LINQ(vars, Select.Clone(var_tbl), (Aggregate == null ? null : Aggregate.Clone(var_tbl)), Value);
lnq.TypeTerm = TypeTerm;
return lnq;
}
public override string ToStringBody() {
if (MkFn.LinqValue != null) {
return MkFn.LinqValue[this];
}
string list = string.Join(" ", from x in Variables select "from " + x.Name + " in " + x.Domain.ToString()) + " select " + Select.ToString();
if (Aggregate == null) {
return list;
}
return "(" + list + ")." + Aggregate.Name + "()";
}
}
/*
構文エラー
*/
public class SyntaxException : Exception {
public SyntaxException() {
Token tkn = MkFn.Singleton.CurrentToken;
string line = MkFn.Singleton.Lines[tkn.LineIndex];
Debug.WriteLine("Err {0}行: {1} ^ {2}", tkn.LineIndex + 1, line.Substring(0, tkn.CharPos), line.Substring(tkn.CharPos));
Debug.Write("");
}
}
}