forked from fusionlanguage/fut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenC.cs
3027 lines (2894 loc) · 80.7 KB
/
GenC.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
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
// GenC.cs - C code generator
//
// Copyright (C) 2011-2022 Piotr Fusik
//
// This file is part of CiTo, see https://github.com/pfusik/cito
//
// CiTo is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// CiTo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with CiTo. If not, see http://www.gnu.org/licenses/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Foxoft.Ci
{
public class GenC : GenCCpp
{
bool StringAssign;
bool StringSubstring;
bool StringAppend;
bool StringIndexOf;
bool StringLastIndexOf;
bool StringEndsWith;
bool StringFormat;
bool MatchFind;
bool MatchPos;
bool PtrConstruct;
bool SharedMake;
bool SharedAddRef;
bool SharedRelease;
bool SharedAssign;
readonly SortedDictionary<string, string> ListFrees = new SortedDictionary<string, string>();
bool TreeCompareInteger;
bool TreeCompareString;
readonly SortedSet<TypeCode> Compares = new SortedSet<TypeCode>();
readonly SortedSet<TypeCode> Contains = new SortedSet<TypeCode>();
readonly List<CiExpr> CurrentTemporaries = new List<CiExpr>(); // CiExpr or CiType
readonly List<CiVar> VarsToDestruct = new List<CiVar>();
protected CiClass CurrentClass;
protected override void WriteSelfDoc(CiMethod method)
{
if (method.CallType == CiCallType.Static)
return;
Write(" * @param self This <code>");
WriteName(method.Parent);
WriteLine("</code>.");
}
protected override void IncludeStdInt()
{
Include("stdint.h");
}
protected override void IncludeAssert()
{
Include("assert.h");
}
protected override void IncludeMath()
{
Include("math.h");
}
protected virtual void IncludeStdBool()
{
Include("stdbool.h");
}
public override void VisitLiteralNull()
{
Write("NULL");
}
protected override void WritePrintfWidth(CiInterpolatedPart part)
{
base.WritePrintfWidth(part);
if (IsStringSubstring(part.Argument, out bool _, out CiExpr _, out CiExpr _, out CiExpr _)) {
Trace.Assert(part.Precision < 0);
Write(".*");
}
}
protected override void WriteInterpolatedStringArg(CiExpr expr)
{
if (IsStringSubstring(expr, out bool cast, out CiExpr ptr, out CiExpr offset, out CiExpr length)) {
length.Accept(this, CiPriority.Argument);
Write(", ");
if (cast)
Write("(const char *) ");
WriteArrayPtrAdd(ptr, offset);
}
else
base.WriteInterpolatedStringArg(expr);
}
public override CiExpr Visit(CiInterpolatedString expr, CiPriority parent)
{
Include("stdarg.h");
Include("stdio.h");
this.StringFormat = true;
Write("CiString_Format(");
WritePrintf(expr, false);
return expr;
}
protected virtual void WriteCamelCaseNotKeyword(string name)
{
switch (name) {
case "this":
Write("self");
break;
case "Asm":
case "Assert":
case "Auto":
case "Bool":
case "Break":
case "Byte":
case "Case":
case "Char":
case "Class":
case "Const":
case "Continue":
case "Default":
case "Do":
case "Double":
case "Else":
case "Enum":
case "Extern":
case "False":
case "Float":
case "For":
case "Foreach":
case "Goto":
case "If":
case "Inline":
case "Int":
case "Long":
case "Register":
case "Restrict":
case "Return":
case "Short":
case "Signed":
case "Sizeof":
case "Static":
case "Struct":
case "Switch":
case "True":
case "Typedef":
case "Typeof": // gcc extension
case "Union":
case "Unsigned":
case "Void":
case "Volatile":
case "While":
case "asm":
case "auto":
case "char":
case "extern":
case "goto":
case "inline":
case "register":
case "restrict":
case "signed":
case "sizeof":
case "struct":
case "typedef":
case "typeof": // gcc extension
case "union":
case "unsigned":
case "volatile":
WriteCamelCase(name);
Write('_');
break;
default:
WriteCamelCase(name);
break;
}
}
protected override void WriteName(CiSymbol symbol)
{
switch (symbol) {
case CiContainerType _:
Write(this.Namespace);
Write(symbol.Name);
break;
case CiMethod _:
Write(this.Namespace);
Write(symbol.Parent.Name);
Write('_');
Write(symbol.Name);
break;
case CiConst _:
if (symbol.Parent is CiContainerType) {
Write(this.Namespace);
Write(symbol.Parent.Name);
Write('_');
}
WriteUppercaseWithUnderscores(symbol.Name);
break;
default:
WriteCamelCaseNotKeyword(symbol.Name);
break;
}
}
void WriteSelfForField(CiClass fieldClass)
{
Write("self->");
for (CiClass klass = this.CurrentClass; klass != fieldClass; klass = (CiClass) klass.Parent)
Write("base.");
}
protected override void WriteLocalName(CiSymbol symbol, CiPriority parent)
{
if (symbol.Parent is CiForeach forEach && forEach.Collection.Type is CiArrayType array) {
if (array is CiListType) {
if (parent == CiPriority.Primary)
Write('(');
Write('*');
WriteCamelCaseNotKeyword(symbol.Name);
if (parent == CiPriority.Primary)
Write(')');
}
else if (array.ElementType is CiClass klass) {
if (parent > CiPriority.Add)
Write('(');
forEach.Collection.Accept(this, CiPriority.Add);
Write(" + ");
WriteCamelCaseNotKeyword(symbol.Name);
if (parent > CiPriority.Add)
Write(')');
}
else {
forEach.Collection.Accept(this, CiPriority.Primary);
Write('[');
WriteCamelCaseNotKeyword(symbol.Name);
Write(']');
}
return;
}
if (symbol is CiField)
WriteSelfForField((CiClass) symbol.Parent);
WriteName(symbol);
}
void WriteMatchProperty(CiSymbolReference expr, int which)
{
this.MatchPos = true;
Write("CiMatch_GetPos(");
expr.Left.Accept(this, CiPriority.Argument);
Write(", ");
VisitLiteralLong(which);
Write(')');
}
static bool IsDictionaryClassStgIndexing(CiExpr expr)
{
return expr is CiBinaryExpr indexing
&& indexing.Op == CiToken.LeftBracket
&& indexing.Left.Type is CiDictionaryType dict
&& dict.ValueType is CiClass;
}
public override CiExpr Visit(CiSymbolReference expr, CiPriority parent)
{
if (expr.Left == null || expr.Symbol is CiConst)
WriteLocalName(expr.Symbol, parent);
else if (expr.Symbol == CiSystem.CollectionCount) {
switch (expr.Left.Type) {
case CiListType _:
case CiStackType _:
expr.Left.Accept(this, CiPriority.Primary);
Write("->len");
break;
case CiSortedDictionaryType _:
WriteCall("g_tree_nnodes", expr.Left);
break;
case CiHashSetType _:
case CiDictionaryType _:
WriteCall("g_hash_table_size", expr.Left);
break;
default:
throw new NotImplementedException(expr.Left.Type.ToString());
}
}
else if (expr.Symbol == CiSystem.MatchStart)
WriteMatchProperty(expr, 0);
else if (expr.Symbol == CiSystem.MatchEnd)
WriteMatchProperty(expr, 1);
else if (expr.Symbol == CiSystem.MatchLength)
WriteMatchProperty(expr, 2);
else if (expr.Symbol == CiSystem.MatchValue) {
Write("g_match_info_fetch(");
expr.Left.Accept(this, CiPriority.Argument);
Write(", 0)");
}
else if (IsDictionaryClassStgIndexing(expr.Left)) {
expr.Left.Accept(this, CiPriority.Primary);
Write("->");
WriteName(expr.Symbol);
}
else
return base.Visit(expr, parent);
return expr;
}
void WriteGlib(string s)
{
Include("glib.h");
Write(s);
}
protected virtual void WriteStringPtrType()
{
Write("const char *");
}
void WriteArrayPrefix(CiType type)
{
if (type is CiArrayType array) {
WriteArrayPrefix(array.ElementType);
if (type is CiArrayPtrType arrayPtr) {
if (array.ElementType is CiArrayStorageType)
Write('(');
switch (arrayPtr.Modifier) {
case CiToken.EndOfFile:
Write("const *");
break;
case CiToken.ExclamationMark:
case CiToken.Hash:
Write('*');
break;
default:
throw new NotImplementedException(arrayPtr.Modifier.ToString());
}
}
}
}
void WriteDefinition(CiType type, Action symbol, bool promote, bool space)
{
if (type is CiListType) {
WriteGlib("GArray *");
symbol();
return;
}
CiType baseType = type.BaseType;
switch (baseType) {
case CiIntegerType integer:
Write(GetIntegerTypeCode(integer, promote && type == baseType));
if (space)
Write(' ');
break;
case CiStringPtrType _:
WriteStringPtrType();
break;
case CiStringStorageType _:
Write("char *");
break;
case CiClassPtrType classPtr:
if (classPtr.Modifier == CiToken.EndOfFile)
Write("const ");
if (classPtr.Class == CiSystem.RegexClass)
WriteGlib("GRegex");
else if (classPtr.Class == CiSystem.MatchClass)
WriteGlib("GMatchInfo");
else
WriteName(classPtr.Class);
Write(" *");
break;
case CiStackType _:
WriteGlib("GArray *");
break;
case CiHashSetType _:
WriteGlib("GHashTable *");
break;
case CiSortedDictionaryType _:
WriteGlib("GTree *");
break;
case CiDictionaryType _:
WriteGlib("GHashTable *");
break;
case CiContainerType _:
if (baseType == CiSystem.BoolType) {
IncludeStdBool();
Write("bool");
}
else if (baseType == CiSystem.MatchClass) {
WriteGlib("GMatchInfo *");
space = false;
}
else if (baseType == CiSystem.LockClass) {
Include("threads.h");
Write("mtx_t");
}
else
WriteName(baseType);
if (space)
Write(' ');
break;
default:
Write(baseType.Name);
if (space)
Write(' ');
break;
}
WriteArrayPrefix(type);
symbol();
while (type is CiArrayType array) {
if (type is CiArrayStorageType arrayStorage) {
Write('[');
VisitLiteralLong(arrayStorage.Length);
Write(']');
}
else if (array.ElementType is CiArrayStorageType)
Write(')');
type = array.ElementType;
}
}
void WriteSignature(CiMethod method, Action symbol)
{
if (method.Type == CiSystem.VoidType && method.Throws) {
IncludeStdBool();
Write("bool ");
symbol();
}
else
WriteDefinition(method.Type, symbol, true, true);
}
protected override void Write(CiType type, bool promote)
{
WriteDefinition(type, () => {}, promote, type is CiArrayPtrType);
}
protected override void WriteTypeAndName(CiNamedValue value)
{
WriteDefinition(value.Type, () => WriteName(value), true, true);
}
void WriteXstructorPtr(bool need, CiClass klass, string name)
{
if (need) {
Write("(CiMethodPtr) ");
WriteName(klass);
Write('_');
Write(name);
}
else
Write("NULL");
}
void WriteDynamicArrayCast(CiType elementType)
{
Write('(');
WriteDefinition(elementType, () => Write(elementType is CiArrayType ? "(*)" : "*"), false, true);
Write(") ");
}
protected override void WriteNewArray(CiType elementType, CiExpr lengthExpr, CiPriority parent)
{
this.SharedMake = true;
if (parent > CiPriority.Mul)
Write('(');
WriteDynamicArrayCast(elementType);
Write("CiShared_Make(");
if (lengthExpr != null)
lengthExpr.Accept(this, CiPriority.Argument);
else
Write('1');
Write(", sizeof(");
Write(elementType, false);
Write("), ");
if (elementType == CiSystem.StringStorageType) {
this.PtrConstruct = true;
Write("(CiMethodPtr) CiPtr_Construct, free");
}
else if (elementType.IsDynamicPtr) {
this.PtrConstruct = true;
this.SharedRelease = true;
Write("(CiMethodPtr) CiPtr_Construct, CiShared_Release");
}
else if (elementType is CiClass klass) {
WriteXstructorPtr(NeedsConstructor(klass), klass, "Construct");
Write(", ");
WriteXstructorPtr(NeedsDestructor(klass), klass, "Destruct");
}
else
Write("NULL, NULL");
Write(')');
if (parent > CiPriority.Mul)
Write(')');
}
protected override void WriteNew(CiClass klass, CiPriority parent)
{
WriteNewArray(klass, null, parent);
}
void WriteStringStorageValue(CiExpr expr)
{
if (IsStringSubstring(expr, out bool cast, out CiExpr ptr, out CiExpr offset, out CiExpr length)) {
Include("string.h");
this.StringSubstring = true;
Write("CiString_Substring(");
if (cast)
Write("(const char *) ");
WriteArrayPtrAdd(ptr, offset);
Write(", ");
length.Accept(this, CiPriority.Argument);
Write(')');
}
else if (expr is CiInterpolatedString
|| (expr is CiCallExpr call && expr.Type == CiSystem.StringStorageType && !call.Method.IsReferenceTo(CiSystem.StringSubstring)))
expr.Accept(this, CiPriority.Argument);
else {
Include("string.h");
WriteCall("strdup", expr);
}
}
protected override void WriteArrayStorageInit(CiArrayStorageType array, CiExpr value)
{
switch (value) {
case null:
if (array.StorageType == CiSystem.StringStorageType || array.StorageType.IsDynamicPtr)
Write(" = { NULL }");
break;
case CiLiteral literal when literal.IsDefaultValue:
Write(" = { ");
literal.Accept(this, CiPriority.Argument);
Write(" }");
break;
default:
throw new NotImplementedException("Only null, zero and false supported");
}
}
string GetListDestroy(CiType type)
{
if (!(type is CiListType || type is CiStackType))
return null;
CiType elementType = ((CiCollectionType) type).ElementType;
if (elementType == CiSystem.StringStorageType) {
this.ListFrees["String"] = "free(*(void **) ptr)";
return "CiList_FreeString";
}
if (elementType.IsDynamicPtr) {
this.ListFrees["Shared"] = "CiShared_Release(*(void **) ptr)";
return "CiList_FreeShared";
}
if (elementType is CiClass klass && NeedsDestructor(klass))
return $"(GDestroyNotify) {klass.Name}_Destruct";
if (elementType is CiListType || elementType is CiStackType) {
this.ListFrees["List"] = "g_array_free(*(GArray **) ptr, TRUE)";
return "CiList_FreeList";
}
if (elementType is CiDictionaryType) {
if (elementType is CiSortedDictionaryType) {
this.ListFrees["SortedDictionary"] = "g_tree_unref(*(GTree **) ptr)";
return "CiList_FreeSortedDictionary";
}
this.ListFrees["Dictionary"] = "g_hash_table_unref(*(GHashTable **) ptr)";
return "CiList_FreeDictionary";
}
return null;
}
string GetDictionaryDestroy(CiType type)
{
if (type == CiSystem.StringStorageType || type is CiArrayStorageType)
return "free";
if (type.IsDynamicPtr) {
this.SharedRelease = true;
return "CiShared_Release";
}
if (type is CiClass klass)
return NeedsDestructor(klass) ? $"(GDestroyNotify) {klass.Name}_Delete" /* TODO: emit */ : "free";
if (type is CiListType)
return "(GDestroyNotify) g_array_unref";
if (type is CiDictionaryType)
return type is CiSortedDictionaryType ? "(GDestroyNotify) g_tree_unref" : "(GDestroyNotify) g_hash_table_unref";
return "NULL";
}
void WriteHashEqual(CiType keyType)
{
Write(keyType is CiStringType ? "g_str_hash, g_str_equal" : "NULL, NULL");
}
void WriteNewHashTable(CiType keyType, string valueDestroy)
{
Write("g_hash_table_new");
string keyDestroy = GetDictionaryDestroy(keyType);
if (keyDestroy == "NULL" && valueDestroy == "NULL") {
Write('(');
WriteHashEqual(keyType);
}
else {
Write("_full(");
WriteHashEqual(keyType);
Write(", ");
Write(keyDestroy);
Write(", ");
Write(valueDestroy);
}
Write(')');
}
protected override void WriteNewStorage(CiType type)
{
switch (type) {
case CiListType _:
case CiStackType _:
Write("g_array_new(FALSE, FALSE, sizeof(");
Write(((CiCollectionType) type).ElementType, false);
Write("))");
break;
case CiHashSetType set:
WriteNewHashTable(set.ElementType, "NULL");
break;
case CiSortedDictionaryType dict:
string valueDestroy = GetDictionaryDestroy(dict.ValueType);
if (dict.KeyType == CiSystem.StringPtrType && valueDestroy == "NULL")
Write("g_tree_new((GCompareFunc) strcmp");
else {
Write("g_tree_new_full(CiTree_Compare");
switch (dict.KeyType) {
case CiIntegerType _:
this.TreeCompareInteger = true;
Write("Integer");
break;
case CiStringType _:
this.TreeCompareString = true;
Write("String");
break;
default:
throw new NotImplementedException(dict.KeyType.ToString());
}
Write(", NULL, ");
Write(GetDictionaryDestroy(dict.KeyType));
Write(", ");
Write(valueDestroy);
}
Write(')');
break;
case CiDictionaryType dict:
WriteNewHashTable(dict.KeyType, GetDictionaryDestroy(dict.ValueType));
break;
default:
base.WriteNewStorage(type);
break;
}
}
protected override void WriteVarInit(CiNamedValue def)
{
if (def.Value == null && (def.Type == CiSystem.StringStorageType || def.Type.IsDynamicPtr))
Write(" = NULL");
else
base.WriteVarInit(def);
}
int WriteTemporary(CiType type, CiExpr expr)
{
bool assign = expr != null || type is CiListType || type is CiDictionaryType;
int id = this.CurrentTemporaries.IndexOf(type);
if (id < 0) {
id = this.CurrentTemporaries.Count;
WriteDefinition(type, () => { Write("citemp"); VisitLiteralLong(id); }, false, true);
if (assign) {
Write(" = ");
if (expr != null)
WriteCoerced(type, expr, CiPriority.Argument);
else
WriteNewStorage(type);
}
WriteLine(';');
this.CurrentTemporaries.Add(expr);
}
else if (assign) {
Write("citemp");
VisitLiteralLong(id);
Write(" = ");
if (expr != null)
WriteCoerced(type, expr, CiPriority.Argument);
else
WriteNewStorage(type);
WriteLine(';');
this.CurrentTemporaries[id] = expr;
}
return id;
}
void WriteStorageTemporary(CiExpr expr)
{
if (expr is CiCallExpr && expr.Type is CiClass)
WriteTemporary(expr.Type, expr);
}
void WriteTemporaries(CiExpr expr)
{
switch (expr) {
case CiVar def:
if (def.Value != null)
WriteTemporaries(def.Value);
break;
case CiLiteral _:
break;
case CiInterpolatedString interp:
foreach (CiInterpolatedPart part in interp.Parts)
WriteTemporaries(part.Argument);
break;
case CiSymbolReference symbol:
if (symbol.Left != null)
WriteTemporaries(symbol.Left);
break;
case CiUnaryExpr unary:
if (unary.Inner != null) // new C()
WriteTemporaries(unary.Inner);
break;
case CiBinaryExpr binary:
WriteTemporaries(binary.Left);
WriteTemporaries(binary.Right);
break;
case CiSelectExpr select:
WriteTemporaries(select.Cond);
break;
case CiCallExpr call:
if (call.Method.Left != null) {
WriteTemporaries(call.Method.Left);
WriteStorageTemporary(call.Method.Left);
}
int i = 0;
foreach (CiVar param in ((CiMethod) call.Method.Symbol).Parameters) {
if (i >= call.Arguments.Length)
break;
CiExpr arg = call.Arguments[i++];
WriteTemporaries(arg);
if (param.Type is CiClassPtrType)
WriteStorageTemporary(arg);
}
break;
default:
throw new NotImplementedException(expr.GetType().Name);
}
}
static bool IsTemporary(CiExpr expr) => expr is CiCallExpr && expr.Type is CiClass;
static bool HasTemporaries(CiExpr expr)
{
switch (expr) {
case CiLiteral _:
case CiSymbol _:
return false;
case CiInterpolatedString interp:
foreach (CiInterpolatedPart part in interp.Parts)
if (HasTemporaries(part.Argument))
return true;
return false;
case CiSymbolReference symbol:
return symbol.Left != null && HasTemporaries(symbol.Left);
case CiUnaryExpr unary:
return unary.Inner != null && HasTemporaries(unary.Inner);
case CiBinaryExpr binary:
return HasTemporaries(binary.Left) || HasTemporaries(binary.Right);
case CiSelectExpr select:
return HasTemporaries(select.Cond);
case CiCallExpr call:
if (call.Method.Left != null) {
if (call.Method.Left.Type is CiListType && (call.Method.Name == "Add" || call.Method.Name == "Insert"))
return true;
if (call.Method.Left.Type is CiStackType && call.Method.Name == "Push")
return true;
if (IsTemporary(call.Method.Left) || HasTemporaries(call.Method.Left))
return true;
}
int i = 0;
foreach (CiVar param in ((CiMethod) call.Method.Symbol).Parameters) {
if (i >= call.Arguments.Length)
break;
CiExpr arg = call.Arguments[i++];
if (HasTemporaries(arg) || (param.Type is CiClassPtrType && IsTemporary(arg)))
return true;
}
return false;
default:
throw new NotImplementedException(expr.GetType().Name);
}
}
void CleanupTemporaries()
{
for (int i = 0; i < this.CurrentTemporaries.Count; i++) {
if (!(this.CurrentTemporaries[i] is CiType))
this.CurrentTemporaries[i] = this.CurrentTemporaries[i].Type;
}
}
static bool NeedToDestruct(CiSymbol symbol)
{
CiType type = symbol.Type;
while (type is CiArrayStorageType array)
type = array.ElementType;
return type == CiSystem.StringStorageType
|| type.IsDynamicPtr
|| type is CiListType
|| type is CiDictionaryType
|| (type is CiClass klass && (klass == CiSystem.MatchClass || klass == CiSystem.LockClass || NeedsDestructor(klass)));
}
protected override void WriteVar(CiNamedValue def)
{
base.WriteVar(def);
if (NeedToDestruct(def))
this.VarsToDestruct.Add((CiVar) def);
}
void WriteGPointerCast(CiType type, CiExpr expr)
{
if (type is CiNumericType || type is CiEnum) {
Write("GINT_TO_POINTER(");
expr.Accept(this, CiPriority.Argument);
Write(')');
}
else if (type == CiSystem.StringPtrType && expr.Type == CiSystem.StringPtrType) {
Write("(gpointer) ");
expr.Accept(this, CiPriority.Primary);
}
else
WriteCoerced(type, expr, CiPriority.Argument);
}
void WriteGConstPointerCast(CiExpr expr)
{
switch (expr.Type) {
case CiStringType _:
case CiClassPtrType _:
case CiArrayPtrType _:
expr.Accept(this, CiPriority.Argument);
break;
default:
Write("(gconstpointer) ");
expr.Accept(this, CiPriority.Primary);
break;
}
}
void StartDictionaryInsert(CiExpr dict, CiExpr key)
{
Write(dict.Type is CiSortedDictionaryType ? "g_tree_insert(" : "g_hash_table_insert(");
dict.Accept(this, CiPriority.Argument);
Write(", ");
WriteGPointerCast(((CiDictionaryType) dict.Type).KeyType, key);
Write(", ");
}
protected override void WriteAssign(CiBinaryExpr expr, CiPriority parent)
{
if (expr.Left is CiBinaryExpr indexing
&& indexing.Op == CiToken.LeftBracket
&& indexing.Left.Type is CiDictionaryType dict) {
StartDictionaryInsert(indexing.Left, indexing.Right);
WriteGPointerCast(dict.ValueType, expr.Right);
Write(')');
}
else if (expr.Left.Type == CiSystem.StringStorageType) {
if (parent == CiPriority.Statement
&& IsTrimSubstring(expr) is CiExpr length) {
WriteIndexing(expr.Left, length);
Write(" = '\\0'");
}
else {
this.StringAssign = true;
Write("CiString_Assign(&");
expr.Left.Accept(this, CiPriority.Primary);
Write(", ");
WriteStringStorageValue(expr.Right);
Write(')');
}
}
else if (expr.Left.Type.IsDynamicPtr) {
if (expr.Left.Type.IsClass(CiSystem.RegexClass)) {
// TODO: only if previously assigned non-null
// Write("g_regex_unref(");
// expr.Left.Accept(this, CiPriority.Argument);
// WriteLine(");");
base.WriteAssign(expr, parent);
}
else {
this.SharedAssign = true;
Write("CiShared_Assign((void **) &");
expr.Left.Accept(this, CiPriority.Primary);
Write(", ");
if (expr.Right is CiSymbolReference) {
this.SharedAddRef = true;
Write("CiShared_AddRef(");
expr.Right.Accept(this, CiPriority.Argument);
Write(')');
}
else
expr.Right.Accept(this, CiPriority.Argument);
Write(')');
}
}
else
base.WriteAssign(expr, parent);
}
protected override bool HasInitCode(CiNamedValue def)
{
return (def is CiField && (def.Value != null || def.Type.StorageType == CiSystem.StringStorageType || def.Type.IsDynamicPtr || def.Type is CiListType || def.Type is CiDictionaryType))
|| GetThrowingMethod(def.Value) != null
|| (def.Type.StorageType is CiClass klass && (klass == CiSystem.LockClass || NeedsConstructor(klass)))
|| GetListDestroy(def.Type) != null;
}
protected override void WriteInitCode(CiNamedValue def)
{
if (!HasInitCode(def))
return;
CiType type = def.Type;
int nesting = 0;
while (type is CiArrayStorageType array) {
OpenLoop("int", nesting++, array.Length);
type = array.ElementType;
}
if (type is CiClass klass) {
if (klass == CiSystem.LockClass) {
Write("mtx_init(&");
WriteArrayElement(def, nesting);
WriteLine(", mtx_plain | mtx_recursive);");
}
else if (NeedsConstructor(klass)) {
WriteName(klass);
Write("_Construct(&");
WriteArrayElement(def, nesting);
WriteLine(");");
}
}
else {
if (def is CiField) {
WriteArrayElement(def, nesting);
if (nesting > 0) {
Write(" = ");
if (type == CiSystem.StringStorageType || type.IsDynamicPtr)
Write("NULL");
else
def.Value.Accept(this, CiPriority.Argument);
}
else
WriteVarInit(def);
WriteLine(';');
}
CiMethod throwingMethod = GetThrowingMethod(def.Value);
if (throwingMethod != null)
WriteForwardThrow(parent => WriteArrayElement(def, nesting), throwingMethod);
}
if (GetListDestroy(type) is string destroy) {
Write("g_array_set_clear_func(");
WriteArrayElement(def, nesting);
Write(", ");
Write(destroy);
WriteLine(");");
}
while (--nesting >= 0)
CloseBlock();
}
void WriteMemberAccess(CiExpr left, CiClass symbolClass)
{
if (left.Type is CiClass klass)
Write('.');
else {
Write("->");
klass = ((CiClassPtrType) left.Type).Class;
}
for (; klass != symbolClass; klass = (CiClass) klass.Parent)
Write("base.");
}
protected override void WriteMemberOp(CiExpr left, CiSymbolReference symbol)
{