-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGenerate.zu
12717 lines (11663 loc) · 451 KB
/
Generate.zu
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
#
# The Zimbu compiler written in Zimbu
#
# Generate module: everything related to generating C code.
# This includes collecting symbols.
#
# Copyright 2009 Bram Moolenaar All Rights Reserved.
# Licensed under the Apache License, Version 2.0. See the LICENSE file or
# obtain a copy at: http://www.apache.org/licenses/LICENSE-2.0
#
# Characters prepended to symbols:
# V variable or member
# M module
# F function or method
# C class
# E array of enum names
# GC Zimbu internal functions
#
IMPORT.PROTO "zui.proto"
IMPORT "Annotator.zu"
IMPORT "ArrayStuff.zu"
IMPORT "BitsType.zu"
IMPORT "BitsValueType.zu"
IMPORT "BlockScope.zu"
IMPORT "Builtin.zu"
IMPORT "CallbackType.zu"
IMPORT "ClassRefType.zu"
IMPORT "ClassScope.zu"
IMPORT "ClassType.zu"
IMPORT "CodeProperties.zu"
IMPORT "Config.zu"
IMPORT "ContainerType.zu"
IMPORT "Debug.zu"
IMPORT "DeclStore.zu"
IMPORT "Declaration.zu"
IMPORT "DictStuff.zu"
IMPORT "EnumType.zu"
IMPORT "EnumValueType.zu"
IMPORT "ExprArg.zu"
IMPORT "ExprEval.zu"
IMPORT "FileScope.zu"
IMPORT "ForLoopInfo.zu"
IMPORT "ListStuff.zu"
IMPORT "MainFile.zu"
IMPORT "MethodRefType.zu"
IMPORT "MethodScope.zu"
IMPORT "MethodType.zu"
IMPORT "ModuleScope.zu"
IMPORT "ModuleType.zu"
IMPORT "MultipleType.zu"
IMPORT "NoAllocType.zu"
IMPORT "Output.zu"
IMPORT "PieceScope.zu"
IMPORT "Pos.zu"
IMPORT "ReferenceType.zu"
IMPORT "Resolve.zu"
IMPORT "SContext.zu"
IMPORT "Scope.zu"
IMPORT "SharedScope.zu"
IMPORT "SwitchScope.zu"
IMPORT "SymUse.zu"
IMPORT "Template.zu"
IMPORT "TopScope.zu"
IMPORT "TupleType.zu"
IMPORT "TryScope.zu"
IMPORT "Type.zu"
IMPORT "TypedefType.zu"
IMPORT "UsedFile.zu"
IMPORT "ValueType.zu"
IMPORT "Visibility.zu"
IMPORT "WriteCommon.zu"
IMPORT "ZimbuFile.zu"
IMPORT "ZuiFile.zu"
IMPORT "ZuiCodeBlockExt.zu"
IMPORT "ZuiDeclarationExt.zu"
IMPORT "ZuiExpressionExt.zu"
IMPORT "ZuiForStatementExt.zu"
IMPORT "ZuiImportExt.zu"
IMPORT "ZuiMethodCallExt.zu"
IMPORT "ZuiMethodTypeExt.zu"
IMPORT "ZuiStatementExt.zu"
IMPORT "ZuiTryStatementExt.zu"
IMPORT "ZuiTypeExt.zu"
IMPORT "genC/WriteC.zu"
IMPORT "lib/TModule.zu"
IMPORT "lib/ZWTLoader.zu"
MODULE Generate @items=public # TODO: restrict visibility
# For debugging: Set to FALSE to enter all scopes even when there were no
# undefined symbols in a previous pass.
ARG.Bool undefinedFlag = NEW("z", "zeroundef", TRUE,
"Skip resolving symbols if there are no undefined symbols")
bool skip_zero_undefined = undefinedFlag.value()
ARG.Bool keepUnusedFlag = NEW(NIL,
"keepunused", FALSE, "Do write unused items")
# For debugging: Mark items as used even when undefined is non-zero
bool usedWhenUndefined = FALSE
# When the number of undefined symbols does not go down to zero this flag is
# set before writing the code. Unused items will be produced so that they
# can generate errors.
bool undefinedNonZero
# When this flag is set we continue compiling files even after an error was
# found.
bool continueAfterError
# When this flag is set we are trying to locate a place where undefined is
# non-zero. That's a bug in the compiler.
bool reportUndef
FUNC skipUnused() bool
RETURN !keepUnusedFlag.get() && !undefinedNonZero
}
# When starting to generate this flag is set to FALSE. Once a file is
# encountered that requires another pass it is set to TRUE.
bool needAnotherPass
# For debugging: In an area with something interesting.
bool verbose
# Call resolve() for |usedFile|. Used at toplevel.
# Return TRUE if another pass is needed.
FUNC resolve(UsedFile usedFile, SContext ctx) bool
needAnotherPass = FALSE
RETURN resolve(usedFile, "", ctx)
}
# Go through the statements of a file to resolve symbols.
# |indent| is used for progress messages.
#
# Return TRUE if another pass is needed.
FUNC resolve(UsedFile usedFile, string indent, SContext ctx) bool
usedFile.zimbuFile.startedPass = ctx.topScope.pass
string leader = indent .. usedFile.zimbuFile.filename
FileScope fileScope = usedFile.scope()
ZuiFile zuiFile = usedFile.zimbuFile.zuiFile
Zui.Statement firstStatement = fileScope.getFirstStatement()
IF firstStatement == NIL
LOG.info("\(leader): Empty file")
IF zuiFile.contents.sizeStatement() != 0
LOG.error("\(leader): Does have statements")
}
RETURN FALSE
}
int previousUndef = fileScope.undefined
# Set the indent on the scope again, it changes when finding builtin
# modules and when skipping files.
fileScope.importIndent = indent
# This may recursively call back for IMPORT statements.
LOG.info("\(leader): Check imports...")
int undef = generateImports(usedFile, ctx)
# No need to resolve symbols when already done this pass level.
# This happens when we want to check the imports.
bool needPass
IF fileScope.topscopePass > ctx.topScope.pass
needPass = previousUndef > 0
ELSE
fileScope.topscopePass = ctx.topScope.pass + 1
LOG.info("\(leader): Pass \(fileScope.pass)...")
int generateUndef = generate(fileScope, ctx)
undef += generateUndef
fileScope.undefined = undef
# Do some inits of this file.
ctx.gen.afterGenerate(usedFile, NIL, ctx)
LOG.info("\(leader): Pass \(fileScope.pass) done.", flags = noNewline)
IF undef > 0
LOG.info(" (\(undef) undefined symbols)", flags = noNewline)
}
LOG.info("")
fileScope.pass++
# We need another pass when there are undefined symbols.
# However, if no symbols were resolved there might be an error, so don't
# do another pass then.
# Sometimes including another module causes the number of undefined
# symbols to increase. Only stop when the number doesn't change.
# Also stop after 20 passes, catches errors in the compiler.
needPass = undef > 0
&& fileScope.pass < 20
&& (fileScope.pass == 2 || undef != previousUndef)
# Debug undefined symbols not going down to zero. Only do this when we
# did not encounter a file that requires another pass, since that means
# something may be undefined and we will get back here later.
IF !needPass && generateUndef > 0 && LOG.isDebug() && !needAnotherPass
Debug.listUndefined(fileScope.statements, ctx)
}
IF needPass
needAnotherPass = TRUE
}
# When we do not do another pass but undefined is not zero, set a flag so
# that we generate all code to see the error messages.
IF needAnotherPass
undefinedNonZero = FALSE
ELSEIF undef > 0
undefinedNonZero = TRUE
}
}
RETURN needPass
}
#
# Write C code for |usedFile|.
#
PROC write(UsedFile usedFile, SContext ctx, Output.Group outputs)
write(usedFile, ctx, outputs, "")
}
#
# Write the code (C or JS) into |outputs|.
#
PROC write(UsedFile usedFile, SContext ctx, Output.Group outputs,
string indent)
string inFileName = usedFile.zimbuFile.filename
FileScope fileScope = usedFile.scope()
int prevUndefined = fileScope.undefined
string leader = indent .. inFileName
LOG.info("\(leader): Generating \(ctx.gen.getLangName()) code...")
fileScope.importIndent = indent
outputs.startWriting()
# Write all the code for imported files.
generateImports(usedFile, ctx)
# Writing is only needed when there is an item that is actually used.
# Also write when the last pass had undefined symbols, report errors.
IF !skipUnused() || usedFile.hasUsedItem(ctx.gen, indent)
|| prevUndefined > 0
# Separate the inits of imports and inits of this file.
ctx.gen.afterImports(fileScope, outputs)
# Write the body of this file.
generate(fileScope, ctx)
# Finish the inits of this file.
ctx.gen.afterGenerate(usedFile, outputs, ctx)
}
LOG.info("\(leader): Done.")
}
#
# The generation function handling imports only: Resolve symbols and
# generate code when writing.
# Returns the number of undefined symbols in the imports.
#
FUNC generateImports(UsedFile usedFile, SContext ctx) int
# Process any builtin module imports. Only for the top file scope.
int undef
IF usedFile.isTopFile
undef = Builtin.generateBuiltins(usedFile, ctx)
}
# Go through the IMPORT statements of this scope.
ZuiFile zf = usedFile.zimbuFile.zuiFile
IF zf.contents.hasImport()
FOR import IN zf.contents.getImportList()
undef += generateImport(usedFile, import, ctx)
}
}
RETURN undef
}
#
# The main generation function: go through the parse tree, resolve symbols
# and generate code when writing.
# Returns the number of undefined symbols.
#
FUNC generate(Scope scope, TopScope topScope,
Resolve gen, Output.Group outs
) int
RETURN generate(scope.statements, NEW(topScope, scope, gen, outs))
}
FUNC generate(Scope scope, SContext ctx, Output.Group outs) int
RETURN generate(scope.statements, NEW(ctx.topScope, scope, ctx.gen, outs))
}
FUNC generate(Scope scope, SContext ctx) int
RETURN generate(scope.statements, ctx)
}
FUNC generate(list<Zui.Statement> statements, SContext ctx) int
int undef = generateStatements(statements, ctx)
IF statements != NIL && statements.Size() > 0
# Write the generated virtual methods.
ctx.gen.writeVirtual(ctx)
}
RETURN undef
}
# Inner part of generate().
FUNC generateStatements(list<Zui.Statement> statements, SContext ctx) int
# Go through the statements of this scope.
int undef
IF statements != NIL
FOR i IN 0 UNTIL statements.Size()
undef += generateOneStatement(
statements[i],
i + 1 < statements.Size() ? statements[i + 1] : NIL,
ctx)
# Dereference intermediate expression results, if any.
ctx.scope.writeAfterStmt(ctx.out)
}
}
RETURN undef
}
# Handle one statement. Return the number of undefined items.
FUNC generateOneStatement(
Zui.Statement stmt, Zui.Statement nextStmt, SContext ctx) int
int undef = -1
VAR stmtExt = ZuiStatementExt.get(stmt)
#
# Handle statements that may appear at the toplevel.
#
SWITCH stmt.getType()
CASE Zui.StatementType.eCBLOCK
undef = generateCBlock(stmt, ctx)
CASE Zui.StatementType.eMODULE_DECL
undef = generateModule(stmt, ctx)
CASE Zui.StatementType.eCLASS_DECL
undef = generateClassWithTemplate(stmt, ctx)
CASE Zui.StatementType.eBITS_DECL
undef = generateBits(stmt, ctx)
CASE Zui.StatementType.eENUM_DECL
undef = generateEnum(stmt, ctx)
CASE Zui.StatementType.eMETHOD_DECL
undef = generateMethodWithTemplate(stmt, ctx)
CASE Zui.StatementType.eVAR_DECL
undef = generateDeclare(stmt, ctx)
CASE Zui.StatementType.eALIAS_DECL
undef = generateAlias(stmt, ctx)
CASE Zui.StatementType.eTYPE_DECL
undef = generateTypedef(stmt, ctx)
CASE Zui.StatementType.eGENERATEIF
undef = generateGenerateIf(stmt, ctx)
CASE Zui.StatementType.eGENERATEERROR
undef = generateGenerateError(stmt, ctx)
CASE Zui.StatementType.eINCLUDE
undef = generateInclude(stmt, ctx)
}
IF undef >= 0
stmtExt.undefined = undef
IF reportUndef && undef != 0
ctx.error("generateOneStatement() "
.. stmt.getType().ToString() .. " undef: " .. undef, stmt)
}
RETURN undef
}
#
# Handle statements that cannot appear at the toplevel.
#
IF !ctx.scope.hasStatements()
ctx.error("Item not allowed here", stmt)
RETURN 0
}
SWITCH stmt.getType()
CASE Zui.StatementType.eBLOCK
undef = generateCodeBlock(stmt.getBlock(), NIL,
ctx, Scope.Stype.block, NIL)
CASE Zui.StatementType.eIF
CASE Zui.StatementType.eIFNIL
undef = generateIf(stmt, ctx)
CASE Zui.StatementType.eTRY
undef = generateTry(stmt, ctx)
CASE Zui.StatementType.eTRYELSE
undef = generateTryElse(stmt, ctx)
CASE Zui.StatementType.eWHILE
undef = generateWhile(stmt, ctx)
CASE Zui.StatementType.eDO
undef = generateDo(stmt, ctx)
CASE Zui.StatementType.eUNTIL
undef = generateUntil(stmt, ctx)
CASE Zui.StatementType.eFOR
undef = generateFor(stmt, ctx)
CASE Zui.StatementType.eRETURN
CASE Zui.StatementType.eEXIT
CASE Zui.StatementType.eTHROW
undef = generateReturnExitThrow(stmt, nextStmt, ctx)
CASE Zui.StatementType.eDEFER
undef = generateDefer(stmt, ctx)
CASE Zui.StatementType.eBREAK
undef = generateBreak(stmt, nextStmt, ctx)
CASE Zui.StatementType.eCONTINUE
undef = generateContinue(stmt, nextStmt, ctx)
CASE Zui.StatementType.eSWITCH
undef = generateSwitch(stmt, ctx)
CASE Zui.StatementType.eCASE
CASE Zui.StatementType.eDEFAULT
undef = generateCase(stmt, nextStmt, ctx)
CASE Zui.StatementType.eNEWCALL
undef = generateNewCall(stmt, ctx)
CASE Zui.StatementType.eCALL
undef = generateCallStatement(stmt, ctx)
CASE Zui.StatementType.eINC
CASE Zui.StatementType.eDEC
undef = generateIncDec(stmt, ctx)
CASE Zui.StatementType.eASSIGN
undef = generateAssign(stmt, ctx)
}
IF undef < 0
ctx.error("INTERNAL: generate(): Statement type \""
.. stmt.getType().ToString() .. "\" not supported", stmt)
undef = 0
}
stmtExt.undefined = undef
IF reportUndef && undef != 0
# For debugging: report information about where the undefined count came
# from. Only supports a few statement types that had problems in the
# past.
ctx.error("generateOneStatement() "
.. stmt.getType().ToString() .. " end undef: " .. undef, stmt)
IF stmt.getType() == Zui.StatementType.eASSIGN
ZuiExpressionExt.reportUndefined("lhs", stmt.getAssign().getLhs())
ZuiExpressionExt.reportUndefined("rhs", stmt.getAssign().getRhs())
ELSEIF stmt.getType() == Zui.StatementType.eRETURN
ZuiExpressionExt.reportUndefined("rhs", stmt.getArguments(0))
ELSEIF stmt.getType() == Zui.StatementType.eCALL
ZuiExpressionExt.reportUndefined("call", stmt.getMethodCall())
}
}
RETURN undef
}
# A list of a >>> copy this %{ expression }% <<<
FUNC generateCBlock(Zui.Statement stmt, SContext ctx) int
int undef
IF stmt.hasCblock()
IF ctx.scope.hasStatements()
ctx.gen.beforeStatement(stmt.getPos(), stmt.getBlockgc(), ctx)
}
FOR block IN stmt.getCblockList()
ctx.out.write(block.getText())
IF block.hasExpr()
Zui.Expression expr = block.getExpr()
VAR exprExt = ZuiExpressionExt.get(expr)
IF block.getLiteral()
SymUse symUse = NEW(expr.getPos(), ctx)
exprExt.undefined = 0
Declaration decl = ctx.scope.findExprDecl(expr, FALSE, TRUE, TRUE,
ctx, symUse)
undef += exprExt.undefined
IF decl == NIL
IF ctx.doError()
ctx.error("Item not found", expr)
}
ELSE
ctx.addUsedItem(decl)
ctx.out.write(decl.pName)
}
ELSE
genExpr(expr, ctx)
}
undef += exprExt.undefined
}
IF block.hasUses()
# Handle the uses(foo) argument.
Builtin.usesDeclarations(block.getUsesList(), stmt, ctx)
}
}
IF ctx.scope.hasStatements()
ctx.gen.afterStatement(stmt, ctx)
}
}
RETURN undef
}
# Generate Main()
FUNC generateMain(Zui.Declaration zuiDecl, SContext ctx) int
Resolve gen = ctx.gen
Scope scope = ctx.scope
Zui.Type type = zuiDecl.getType()
Zui.MethodType zuiMethod = type.getMethodDecl()
VAR declExt = ZuiDeclarationExt.get(zuiDecl)
IF scope.outer != NIL || scope.scopeName != NIL
ctx.error("Main() not at toplevel", zuiDecl)
}
Zui.Expression expr
IF type.getType() == Zui.TypeEnum.eFUNC
expr = zuiMethod.getReturnType(0).getName()
IF expr.getType() != Zui.ExprType.eID || expr.getId().getName() != "int"
expr = NIL
}
}
IF expr == NIL
ctx.error("Main() must return int", zuiDecl)
}
IF zuiMethod.hasArgument()
ctx.error("Main() must not have an argument", zuiDecl)
}
VAR zuiMethodExt = ZuiMethodTypeExt.get(zuiMethod)
IF skip_zero_undefined && !ctx.gen.writing
&& zuiMethodExt.scope != NIL
&& !zuiMethodExt.scope.needPass && declExt.undefined == 0
# No need to process this Main() again.
RETURN 0
}
MethodScope mainScope
MethodType method
IF zuiMethodExt.scope == NIL
# Create the scope for the main function and generate its body.
mainScope = NEW(scope, zuiMethod.getBody().getStatementList())
mainScope.name = "Main()"
mainScope.returnType = Type.anInt
mainScope.scopeName = "FMain"
mainScope.scopeType = Scope.Stype.procDef
mainScope.methodScope = mainScope
zuiMethodExt.scope = mainScope
# Add a MethodType declaration for use in markMainUsed().
method = MethodType.NEW(Type.Enum.func, "Main")
declExt.decl = method
method.zuiDecl = zuiDecl
method.type = declExt.decl
method.returnType = Type.anInt
method.scope = mainScope
method.pName = "main"
mainScope.outerDecl = declExt.decl
ELSE
mainScope = zuiMethodExt.scope
mainScope.initPass(scope)
mainScope.needPass = FALSE
mainScope.returnType = Type.anInt
method = declExt.decl
}
# Write main() and the start of Fmain().
SContext mainCtx = NEW(ctx.topScope, mainScope, ctx.gen, ctx.outs)
gen.mainHead(declExt.decl, mainCtx)
# Adjust outputs to put variable declarations first, body statements
# separately, to be appended after generate(). Set origBodyOut so that a
# method or class defined inside Main() goes to the toplevel, not inside
# the function.
Output.Group newOuts = ctx.outs.startNewBlock()
IF newOuts.origBodyOut == NIL
newOuts.origBodyOut = ctx.outs.bodyOut
}
mainCtx.outs = newOuts
mainCtx.out = newOuts.out
gen.methodBodyStart(method, FALSE, FALSE, NIL, mainCtx)
gen.mainMiddle(mainCtx)
int undef = generate(mainScope.statements, mainCtx)
declExt.undefined = undef
newOuts.endNewBlock()
IF mainScope.wantBacktrace
scope.wantBacktrace = TRUE
}
gen.mainEnd(ctx)
checkMethodHasReturn(zuiMethod, zuiDecl.getPos(), ctx)
RETURN undef
}
# Generate a MODULE.
FUNC generateModule(Zui.Statement stmt, SContext ctx) int
Zui.Declaration zuiDecl = stmt.getDeclaration()
Zui.Type zuiType = zuiDecl.getType()
Zui.ModuleType module = zuiType.getModuleDecl()
Output out = ctx.out # normal generate output
Scope scope = ctx.scope
VAR declExt = ZuiDeclarationExt.get(zuiDecl)
IF scope.scopeName != NIL && scope.scopeName[0] != 'M'
ctx.error("MODULE can only be defined inside a MODULE", stmt)
}
ctx.checkDeclName(zuiDecl, "module")
string name = zuiDecl.getName()
# Declaration
# |- name (name of the module)
# |- type == ModuleType (specifies it's a module)
# |- scope == ModuleScope (scope used during resolving)
# |- declDict (contains the module items)
Declaration decl
ModuleScope moduleScope
IF declExt.decl == NIL
# First time at this module, create the declaration with a ModuleType.
# Store it in Zui.Declaration.decl for the next round.
ModuleType type = NEW(Type.Enum.module, name)
scope.addTypeDecl(type, zuiDecl, FALSE, ctx)
decl = type
declExt.decl = decl
# Create the ModuleScope.
moduleScope = NEW(scope, NIL)
moduleScope.statements = module.getStatementList()
type.scope = moduleScope
IF scope.scopeType == Scope.Stype.libModule
&& (name.endsWith("Module") || name.endsWith("module"))
moduleScope.name = name.slice(0, -7)
moduleScope.builtin = TRUE
ELSE
moduleScope.name = name
}
IF scope.scopeName == NIL
moduleScope.scopeName = "M" .. name
ELSE
moduleScope.scopeName = scope.scopeName .. "__M" .. name
}
moduleScope.depth = 0
moduleScope.returnType = NIL
moduleScope.zuiAttr = zuiType.getAttr()
moduleScope.outerDecl = decl
decl.pName = moduleScope.scopeName
ELSE
# Second round and up: re-use the declaration created in the first round.
decl = declExt.decl
IF !scope.isForwardDeclare()
# Not re-using the scope, need to define the module again
scope.addMember(decl)
}
# Write the module type code when used. Also when the module itself was
# not marked as used (using ZWT module .Type() from non-ZWT code).
IF decl.typeUsed
ctx.gen.moduleType(decl, ctx)
}
moduleScope = decl.type.<ModuleType.C>.scope
IF skip_zero_undefined && !ctx.gen.writing && !moduleScope.needPass
&& ZuiStatementExt.get(stmt).undefined == 0
# No need to parse this module again.
RETURN 0
}
moduleScope.initPass(scope)
moduleScope.needPass = FALSE
}
decl.setVisibilityAttr(zuiDecl, ctx)
# Only generate the module when resolving and when we actually need to
# write the code for the target language.
int undef
IF ctx.gen.doGenerateModule(ctx)
undef = generate(moduleScope, ctx, ctx.outs)
}
RETURN undef
}
# Generate a CLASS or INTERFACE.
# For a templated CLASS |template| is not NIL and contains info about the
# types used in the template.
# Also used for PIECE.
FUNC generateClass(Zui.Statement stmt, SContext ctx, Template template) int
Output out = ctx.out # normal generate output
int undef
Resolve gen = ctx.gen
Scope scope = ctx.scope
Zui.Declaration zuiDecl = stmt.getDeclaration()
VAR stmtExt = ZuiStatementExt.get(stmt)
Zui.Type zuiType = zuiDecl.getType()
Zui.ClassType zuiClassType = zuiType.getClassDecl()
VAR declExt = ZuiDeclarationExt.get(zuiDecl)
bool isInterface = zuiClassType.getIsInterface()
bool isPiece = zuiClassType.getIsPiece()
# Allow any class name in the module that defines "I".
# Specifically, the name is not required to start with "I_".
IF scope.name != "I"
checkTypeName(zuiDecl, isInterface ? "interface" : "class", ctx)
}
string className = zuiDecl.getName()
Declaration classDecl
ClassScope classScope
ClassType classType
IF declExt.decl == NIL
# First round, add a class declaration.
IF isInterface
classType = NEW(Type.Enum.interface, className)
ELSEIF isPiece
classType = NEW(Type.Enum.piece, className)
ELSE
classType = NEW(Type.Enum.class, className)
}
classDecl = classType
scope.addTypeDecl(classType, zuiDecl, FALSE, ctx)
classType.zuiDecl = zuiDecl
classScope = NEW(scope, zuiClassType.getMemberList())
classType.scope = classScope
classScope.name = className
IF scope.scopeName == NIL
classScope.scopeName = "C" .. className
ELSE
classScope.scopeName = scope.scopeName .. "__C" .. className
}
# Put the pName in the Declaration and in the Type.
# TODO: can we put it in the Type only?
classDecl.pName = WriteCommon.getUid(classScope.ToString())
DeclStore.storePName(scope.scopeName ?: "", "C" .. className, classDecl)
classDecl.setAttributes(zuiDecl, ctx)
classScope.flags.insideShared = FALSE
classScope.methodScope = NIL
classScope.depth = 1
classScope.returnType = NIL
classScope.zuiAttr = zuiDecl.getType().getAttr()
classScope.outerDecl = classDecl
IF isInterface
# An interface is always abstract.
classDecl.zuiAttr.setAbstract(TRUE)
}
# Add the class to itself, to be able to compare an alias of the class
# to.
classScope.classType = classType
stmtExt.undefined = 1 # always do another pass
declExt.decl = classDecl
stmtExt.typeObj = classType
ELSE
# Second round, re-use the symbol created in the first round.
classDecl = declExt.decl
IF !scope.isForwardDeclare()
# Not re-using the scope, need to declare the class again
scope.addMember(classDecl)
}
classType = classDecl.type
classScope = classType.scope
classScope.initPass(scope)
# Don't use the class from scope but this one.
classScope.classType = classType
}
# For a PIECE everything happens where it is included, nothing to be done
# here.
IF isPiece
RETURN 0
}
# If this class is used the module or class that contains it must also be
# marked as used.
classDecl.addDependsOn(scope.outerDecl)
IF skip_zero_undefined && !gen.writing
&& !classScope.needPass && stmtExt.undefined == 0
# No need to process this class again in this pass.
RETURN 0
}
classScope.needPass = FALSE
# Note: Even when the class is not marked as used we need to continue,
# individual methods and members in the SHARED section may be marked as
# used.
bool classUsed = !skipUnused() || gen.isDeclUsed(classDecl)
# THIS name depends on ctx.gen, set every pass.
classScope.thisName = gen.thisName(FALSE)
# For a templated class: Add the template types to the scope.
# This is done every pass, in case a type is resolved.
# Must come before EXTENDS and IMPLEMENTS, because interfaces there may
# use the template types.
classScope.template = template
classScope.addTemplateTypes()
# Context that includes the template types.
SContext classCtx = NEW(ctx, classScope, ctx.outs)
# EXTENDS
bool needE_
IF zuiClassType.hasExtends()
Zui.Expression expr = zuiClassType.getExtends()
VAR exprExt = ZuiExpressionExt.get(expr)
exprExt.undefined = 0
SymUse symUse = NEW(stmt.getPos(), classCtx)
Declaration parentDecl = scope.findExprDecl(expr, FALSE, FALSE, TRUE,
classCtx, symUse)
undef += exprExt.undefined
IF ctx.doError()
IF parentDecl == NIL
symUse.doError = TRUE
IF scope.findExprDecl(expr, FALSE, TRUE, TRUE,
classCtx, symUse) == NIL
ctx.error("Class not found", expr)
}
ELSEIF !isInterface && parentDecl.type.getTtype() != Type.Enum.class
ctx.error("Not a class", expr)
ELSEIF isInterface && parentDecl.type.getTtype() != Type.Enum.interface
ctx.error("Not an interface", expr)
ELSEIF parentDecl.type.zuiAttr.getFinal()
ctx.error("Cannot extend " .. parentDecl.name
.. ": it is marked final", expr)
}
}
IF parentDecl != NIL
IF parentDecl.type.getClassType(ctx) != NIL
# In case it's an alias.
parentDecl = parentDecl.type.getClassType(ctx)
}
# Add ourselves as a child to the parent.
parentDecl.type.<ClassType>.addChild(classType, ctx)
# If the parent is marked @earlyInit the child is too.
IF parentDecl.type.zuiAttr.getEarlyInit()
classType.zuiAttr.setEarlyInit(TRUE)
}
# A class extending from E.Exception must start with E_, except when
# it's in the "E" module.
IF !classScope.scopeName.startsWith("MEModule__")
Type etype = Builtin.getExceptionDotIType()
IF etype.getTtype() != Type.Enum.unknown
&& etype.getClassType(ctx).hasSubclass(
parentDecl.type.getClassType(ctx))
needE_ = TRUE
IF !className.startsWith("E_")
ctx.error("Exception class name must start with E_", stmt)
}
}
}
# Mark this class to depend on the parent class, but only when
# abstractClass is marked as used, because it depends on the language.
classDecl.addDependsOnCond(parentDecl, Declaration.abstractClass)
ELSE
# Use a dummy ClassType, so that we know there is a parent.
parentDecl = Declaration.NEW("dummy parent")
parentDecl.type = ClassType.NEW(Type.Enum.class, "dummy parent")
parentDecl.type.pName = "dummy" # needed for imt table name
parentDecl.pName = "dummy"
++undef
}
classType.parent = parentDecl.type
}
IF ctx.doError() && !needE_ && className.startsWith("E_")
ctx.error("Class name must not start with E_, unless it's an exception",
stmt)
}
# IMPLEMENTS
IF zuiClassType.hasImplements()
undef += handleImplements(zuiClassType, classType, classCtx)
}
# Write the struct declaration to a separate output and append it to
# ctx.outs.structOut when done. This handles nested classes.
Output structOut = NEW()
structOut.writing = out.writing
IF gen.writing
SContext structCtx = ctx.copy(structOut)
ClassType parent = classType.parent
WHILE parent != NIL
generateObjectMembers(parent, structCtx)
parent = parent.parent
}
}
IF !classType.isAbstract() && out.writing && classUsed
# TODO: can we add this: && classType.type != Type.Enum.interface
gen.writeClassDef(classType.pName,
scope.scopeName == NIL ? className
: scope.scopeName .. "." .. className,
ctx.outs.typeOut)
}
# At the class level we only write members, these go to structOut.
Output.Group newOuts = ctx.outs.copy()
newOuts.out = structOut
newOuts.varOut = structOut
# If we extended a class redefine the methods from the parent in this
# class scope. That's because the type of the THIS pointer is different
# and a method in the parent may call a method that is replaced in the
# child.
#
# A method that was defined in the parent, or inherited from its parent
# and not replaced, has the original method name. This is used when
# $method() is called in this class.
# We also add this method with "__p1" added to the method name, to be used
# for PARENT.method().
# When encountering this in a child we increment the depth: "__p2", to be
# called by PARENT.PARENT.method().
# etc.
#
# When the function signature changes we need to remove the symbols and
# add them again. Thus when the name is "method" we find and remove
# "method" and also remove "method__1" (they are exactly the same). When
# the name is "method__1" we find and remove "method__2".
#
ClassType parent = classType.parent
IF parent != NIL
&& parent.getObjectDeclDict() != NIL
&& !out.writing
FOR l IN parent.getObjectDeclDict().values()
FOR decl IN l
Type m = decl.type
IF (m.getTtype() == Type.Enum.builtinMethod
|| m.getTtype() == Type.Enum.new
|| m.getTtype() == Type.Enum.func
|| m.getTtype() == Type.Enum.proc)
&& !decl.type.isAbstract()
&& m.defined
&& !isInitName(decl.name) # Skip $Init().
&& !decl.hasLocalAttr() # Skip methods with @local.
string parentName # name of method for PARENT.method()
string findName # name of symbol to possibly remove
string sname = decl.name
string baseName
MethodType method = m.<MethodType>
int endOriginalName = sname.find("__p")
IF endOriginalName < 0
parentName = sname .. "__p1"
findName = sname
baseName = sname
ELSE
baseName = sname.slice(0, endOriginalName - 1)
parentName = baseName .. "__p" .. (method.parentLevel + 1)
findName = parentName
}
# Find the method copied from the parent, it is only added once.
# We can't find it with findMatchingMethod(), the function
# signature may have changed, we have to go through the whole list
# and check parentMethod.
# Also check the end of pName, it may change when a child class is
# found before its parent. Below decl.pName is used for the copy,
# it must match for PARENT.method() to work.
VAR declDict = classType.getObjectDeclDict()
Declaration oldDecl
list<Declaration> allDecl
IF declDict != NIL
FOR valueList IN declDict.values()
FOR prevDecl IN valueList
IF prevDecl.type ISA MethodType
MethodType mt = prevDecl.type.<MethodType>
IF mt.parentLevel == method.parentLevel + 1
&& (mt.parentMethod IS decl.type
|| mt.parentMethod IS method.parentMethod)
&& (prevDecl.name == sname
|| prevDecl.name == parentName)
&& prevDecl.pName.endsWith(decl.pName)
oldDecl = prevDecl
IF allDecl == NIL
allDecl = NEW()
}
allDecl.add(prevDecl)
}
}
}
}
}
# Only add the methods from the parent when not done already.
IF oldDecl == NIL
# Create a Type Declaration that is a copy of the method.
MethodType methodCopy = method.copyType()
Declaration declCopy = methodCopy
declCopy.clearDependencies()