-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPapyrusGenSF1.g
More file actions
1526 lines (1405 loc) · 56.2 KB
/
PapyrusGenSF1.g
File metadata and controls
1526 lines (1405 loc) · 56.2 KB
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
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* MIT License
*
* Copyright 2026 Open Papyrus Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
tree grammar PapyrusGenSF1;
options {
tokenVocab = PapyrusParserSF1;
ASTLabelType = CommonTree;
language = CSharp3;
}
// ============================================================================
// SCOPE DECLARATIONS
// ============================================================================
//
// Each scope class tracks context during tree walking. Scopes are pushed on
// entry to a rule and popped on exit (in finally blocks).
//
// Fields are listed as comments since ANTLR3 tree grammar syntax doesn't
// support inline field declarations (these are implemented in C#).
// ============================================================================
scope script_scope {
// Script metadata and definitions
// string objName - Script name
// string parentName - Parent script name
// List<StringTemplate> objStructDefinitions - Struct definitions
// List<StringTemplate> objVarDefinitions - Variable definitions
// List<StringTemplate> objGuardDefinitions - Guard definitions (SF1)
// List<StringTemplate> objPropDefinitions - Property definitions
// List<StringTemplate> objPropGroupDefinitions - Property groups
// List<string> objUngroupedProps - Properties not in groups
// ScriptObjectStateName initialState - Initial state
// List<StringTemplate> objEmptyState - Empty state definition
// Dictionary<ScriptObjectStateName, string> states - State mappings
// bool hasBeginStateEvent - Has OnBeginState event
// bool hasEndStateEvent - Has OnEndState event
// string modTimeUnix - File modification time
// string compileTimeUnix - Compilation time
// string fileName - Source file name
// string userName - User name
// string computerName - Computer name
// string objFlags - Object flags
// Dictionary<string, int> userFlagsRef - User flag references
// string docString - Documentation string
// string constFlag - Const flag value
}
scope fieldDefinition_scope {
// Field definition context
// string initialValue - Initial value expression
// string constFlag - Const flag value
// string docString - Documentation string
}
scope function_scope {
// Function definition context
// ScriptObjectStateName state - State context
// ScriptFunctionName funcName - Function name
// string propertyName - Property name (if property func)
// string returnType - Return type
// bool isNative - Native flag
// bool isGlobal - Global flag
// List<StringTemplate> funcParams - Parameter definitions
// List<StringTemplate> funcVarDefinitions - Local variable definitions
// List<StringTemplate> statements - Function body statements
// string userFlags - User flags value
// string docString - Documentation string
// ScriptFunctionType funcType - Link to typed function object
}
scope eventFunc_scope {
// Event function context
// ScriptObjectStateName state - State context
// ScriptFunctionName mangledFuncName - Mangled event name
// string returnType - Return type (always None)
// bool isNative - Native flag
// bool isGlobal - Global flag (always false)
// List<StringTemplate> funcParams - Parameter definitions
// List<StringTemplate> funcVarDefinitions - Local variable definitions
// List<StringTemplate> statements - Event body statements
// string userFlags - User flags value
// string docString - Documentation string
// ScriptFunctionType funcType - Link to typed function object
}
scope propertyBlock_scope {
// Property definition context
// string propName - Property name
// string propType - Property type
// string userFlags - User flags value
// string docString - Documentation string
}
scope groupBlock_scope {
// Property group context
// string groupName - Group name
// string userFlags - User flags value
// string docString - Documentation string
// List<string> propEntries - Property names in group
}
scope structBlock_scope {
// Struct definition context
// string name - Struct name
// List<StringTemplate> varDefinitions - Member field definitions
}
scope codeBlock_scope {
// Statement block context
// List<StringTemplate> varDefs - Local variable definitions
// ScriptScope currentScope - Link to type system scope
// int nextScopeChild - Child scope index for navigation
}
scope statement_scope {
// Individual statement context
// string mangledName - Mangled variable name (if needed)
}
scope l_value_scope {
// Assignment target context
// string selfName - Self reference variable name
}
scope basic_l_value_scope {
// Simple assignment target context
// string selfName - Self reference variable name
}
scope lockBlock_scope {
// LockGuard block context (SF1-specific)
// List<StringTemplate> blockStatements - Lock body statements
// ScriptScope childScope - Child scope for nested context
}
scope tryLockBlock_scope {
// TryLockGuard block context (SF1-specific)
// List<StringTemplate> blockStatements - Try-lock body statements
// string endLabel - Control flow end label
// ScriptScope childScope - Child scope for success branch
}
scope elseTryLockBlock_scope {
// ElseTryLockGuard branch context (SF1-specific)
// List<StringTemplate> blockStatements - Else-try-lock body statements
// ScriptScope childScope - Child scope for alternate branch
}
scope ifBlock_scope {
// If statement context
// List<StringTemplate> blockStatements - If body statements
// string endLabel - Control flow end label
// ScriptScope childScope - Child scope for if body
}
scope elseIfBlock_scope {
// ElseIf branch context
// List<StringTemplate> blockStatements - ElseIf body statements
// ScriptScope childScope - Child scope for elseif body
}
scope elseBlock_scope {
// Else branch context
// List<StringTemplate> blockStatements - Else body statements
// ScriptScope childScope - Child scope for else body
}
scope whileBlock_scope {
// While loop context
// List<StringTemplate> blockStatements - While body statements
// string startLabel - Loop start label
// string endLabel - Loop end label
// ScriptScope childScope - Child scope for loop body
}
scope return_stat_scope {
// Return statement context
// List<StringTemplate> scopeExitExpressions - Guard unlocks and cleanup
}
scope array_atom_scope {
// Array access context
// string selfName - Array variable name
}
scope array_func_or_id_scope {
// Array function call context
// string selfName - Array variable name
}
scope func_or_id_scope {
// Function call or identifier context
// string selfName - Object reference for call
}
scope property_set_scope {
// Property setter context
// string selfName - Object reference
}
scope struct_set_scope {
// Struct member assignment context
// string selfName - Struct variable name
}
scope function_call_scope {
// Function call context
// string selfName - Object reference for call
}
// ============================================================================
// TOP-LEVEL SCRIPT STRUCTURE
// ============================================================================
//
// Entry point for code generation. The script rule is called by the compiler
// driver after type checking pass completes.
//
// Parameters (passed from driver, not shown in grammar):
// - aSourceFilename : string - Source file path for metadata
// - aObj : ScriptObjectType - Typed script object from PapyrusType pass
//
// Returns: StringTemplate with complete assembly code
// ============================================================================
script
scope script_scope;
// Initialize script metadata (timestamps, user, computer)
// Process header for script name, parent, flags, docstring
// Process all definitions (guards, vars, structs, properties, functions, events)
// Build final assembly template with all collected definitions
: header definitionOrBlock*
-> template(name={...}, parent={...}, flags={...}, guardDefs={...},
structDefs={...}, varDefs={...}, propDefs={...},
propGroupDefs={...}, states={...}, metadata={...})
;
header
// Extract script name, parent name, user flags, docstring
// Store in script_scope for final assembly generation
: scriptType (scriptType)? userFlags DOCSTRING?
;
// ============================================================================
// DEFINITIONS AND BLOCKS
// ============================================================================
//
// Dispatcher for all script-level definitions. The code generator handles
// 8 definition types (customEventDefinition and import_obj are handled by
// earlier compiler passes and do not appear in the post-optimization AST):
// 1. fieldDefinition - Script-level variables (VAR node)
// 2. guardDefinition - Guard declarations (GUARD node, SF1-specific)
// 3. function - Function definitions (FUNCTION node)
// 4. eventFunc - Event handler definitions (EVENT/REMOTEEVENT node)
// 5. stateBlock - State definitions (STATE node)
// 6. propertyBlock - Property definitions (PROPERTY/AUTOPROP node)
// 7. groupBlock - Property group definitions (GROUP node)
// 8. structBlock - Struct type definitions (STRUCT node)
// ============================================================================
definitionOrBlock
: fieldDefinition
| guardDefinition // SF1-specific: Guard variable for concurrency
| function
| eventFunc
| stateBlock
| propertyBlock
| groupBlock
| structBlock
;
// ----------------------------------------------------------------------------
// FIELD DEFINITION
// ----------------------------------------------------------------------------
// Generates: .variable <name> <type> [<flags>] [= <initialValue>]
// Template: variableDef
// ----------------------------------------------------------------------------
fieldDefinition
scope fieldDefinition_scope;
// Process variable type, name, flags, optional initial value
// Add to script_scope.objVarDefinitions
: anyType ID (constant)? userFlags DOCSTRING?
-> template(name={...}, type={...}, flags={...}, initialValue={...},
docString={...})
;
// ----------------------------------------------------------------------------
// GUARD DEFINITION (SF1-Specific)
// ----------------------------------------------------------------------------
// Generates: .guard <name>
// Template: guardDef
//
// Purpose: Declares a guard object for use in LockGuard/TryLockGuard statements.
// Guards are compile-time constructs - no runtime code is generated for the
// definition itself, only a metadata entry.
//
// Example:
// Guard MyLock ProtectsFunctionLogic
//
// Assembly:
// .guard MyLock
// ----------------------------------------------------------------------------
guardDefinition
// Extract guard name from ID token
// Generate guardDef template
// Add to script_scope.objGuardDefinitions
: ID userFlags
-> template(name={...})
;
// ============================================================================
// FUNCTION DEFINITIONS
// ============================================================================
//
// Functions are the primary executable units in Papyrus. Each function has:
// - Return type (or None for void)
// - Name
// - Parameters
// - User flags (Native, Global, access modifiers, etc.)
// - Body (unless Native)
//
// Code Generation:
// 1. functionHeader: Generate function signature and metadata
// 2. codeBlock: Generate function body (local vars + statements)
//
// Variable Mangling:
// Before generating code, all variables in the function scope are mangled
// to handle shadowing (via MangleFunctionVariables helper).
//
// Parameters (semantic, not shown in grammar):
// - aState : ScriptObjectStateName - State context (empty for script-level)
// - aPropertyName : string - Property name (if this is a property function)
// ============================================================================
function
scope function_scope;
// Initialize function scope
// Call MangleFunctionVariables() to handle variable shadowing
// Process function header for signature and metadata
// Process function body (if not native)
// Generate functionDef template with signature + body
: functionHeader codeBlock?
-> template(signature={...}, localVars={...}, body={...})
;
functionHeader
// Extract return type, name, parameters, flags, docstring
// Store in function_scope for body generation
: anyType? ID callParameters? userFlags DOCSTRING?
;
// ============================================================================
// EVENT DEFINITIONS
// ============================================================================
//
// Events are special functions triggered by game engine. They differ from
// regular functions in several ways:
// - Always have return type None
// - Cannot be Global
// - Can be Remote (cross-script calls)
// - Event names may need mangling for remote events
//
// Remote Event Mangling:
// Remote events are mangled via MangleRemoteEventName():
// "OnActivate" -> "::remote_OnActivate"
//
// The tree grammar dispatches on two root tokens:
// - EVENT : Regular event (aRemoteEvent = false)
// - REMOTEEVENT : Remote event (aRemoteEvent = true)
//
// Parameters (semantic, not shown in grammar):
// - aState : ScriptObjectStateName - State context
// ============================================================================
eventFunc
scope eventFunc_scope;
// Initialize event scope
// Call MangleFunctionVariables() to handle variable shadowing
// Process event header for signature and metadata
// Mangle name if remote event (via MangleRemoteEventName)
// Process event body (if not native)
// Generate functionDef template with signature + body
: ^(EVENT eventHeader codeBlock?)
-> template(signature={...}, localVars={...}, body={...})
| ^(REMOTEEVENT eventHeader codeBlock?)
-> template(signature={...}, localVars={...}, body={...})
;
eventHeader
// Extract event name, parameters, flags, docstring
// Event name may be qualified (scriptType.ID for remote events)
// Store in eventFunc_scope for body generation
// Parameters (semantic): aRemoteEvent : bool
: eventName callParameters? userFlags DOCSTRING?
;
eventName
// Event name (possibly qualified for remote events)
: scriptType? ID
;
// ============================================================================
// CALL PARAMETERS
// ============================================================================
//
// Parameter definitions for functions and events. Each parameter has:
// - Type
// - Name
// - Optional default value
//
// Returns: List<StringTemplate> with parameter definitions
// ============================================================================
callParameters
// Process parameter list
// Return list of parameter templates
: callParameter*
-> { List<StringTemplate> }
;
callParameter
// Extract parameter type, name, optional default value
// Generate parameter template
: anyType ID constant?
-> template(type={...}, name={...}, defaultValue={...})
;
// ============================================================================
// STATE DEFINITIONS
// ============================================================================
//
// States group functions and events that share common behavior. State-specific
// functions override base script functions while in that state.
//
// Special Events:
// - OnBeginState : Called when entering state
// - OnEndState : Called when exiting state
// ============================================================================
stateBlock
// Extract state name
// Process all functions and events in state
// Track OnBeginState/OnEndState events
// Generate state template with all state functions
: ID stateFuncOrEvent*
-> template(name={...}, functions={...}, hasBeginState={...},
hasEndState={...})
;
stateFuncOrEvent
// Dispatch to function or eventFunc with state context
: function
| eventFunc
;
// ============================================================================
// PROPERTY DEFINITIONS
// ============================================================================
//
// Properties are special variables with optional getter/setter functions.
// Two tree forms in the post-optimization AST:
//
// 1. PROPERTY (manual/full property):
// ^(PROPERTY propertyHeader propertyFunc propertyFunc)
// - propertyFunc for get, propertyFunc for set
// - Template: fullProp
//
// 2. AUTOPROP (auto property):
// ^(AUTOPROP propertyHeader ID)
// - ID is the backing variable name (mangled)
// - Template: autoProp
// ============================================================================
propertyBlock
scope propertyBlock_scope;
// Extract property name, type, flags, docstring
// Process optional get/set functions
// Generate propertyDef template
// Track property for grouping (script_scope.objUngroupedProps)
: ^(PROPERTY propertyHeader propertyFunc propertyFunc)
-> template(name={...}, type={...}, get={...}, set={...},
userFlags={...}, docString={...})
| ^(AUTOPROP propertyHeader ID)
-> template(name={...}, type={...}, var={...},
userFlags={...}, docString={...})
;
propertyHeader
// Extract property type, name, flags, docstring
// Store in propertyBlock_scope
: anyType ID userFlags DOCSTRING?
;
propertyFunc
// Property get/set function
// Parameters (semantic): aPropName : string
: codeBlock
;
// ============================================================================
// PROPERTY GROUPS
// ============================================================================
//
// Property groups organize properties in the editor. They are purely metadata
// and do not affect runtime behavior.
//
// Ungrouped Properties:
// Properties not in any group are collected and placed in a default group
// via HandleUngroupedProperties() helper.
// ============================================================================
groupBlock
scope groupBlock_scope;
// Extract group name, flags, docstring
// Process all properties in group
// Generate propertyGroup template
: groupHeader groupProperty*
-> template(name={...}, flags={...}, properties={...}, docString={...})
;
groupHeader
// Extract group name, flags, docstring
// Store in groupBlock_scope
: ID userFlags DOCSTRING?
;
groupProperty
// Property reference within group (just the name)
: ID
-> template(name={...})
;
// ============================================================================
// STRUCT DEFINITIONS
// ============================================================================
//
// Structs are user-defined value types. They consist of named fields with
// types. Structs are passed by value (copied on assignment).
//
// Code Generation:
// .struct <name>
// .variable <field1> <type1>
// .variable <field2> <type2>
// .endstruct
// ============================================================================
structBlock
scope structBlock_scope;
// Extract struct name
// Process all field definitions
// Generate structDef template
// Add to script_scope.objStructDefinitions
: structHeader structField*
-> template(name={...}, fields={...})
;
structHeader
// Extract struct name
: ID
;
structField
// Struct field definition
: anyType ID constant? userFlags DOCSTRING?
-> template(type={...}, name={...}, defaultValue={...})
;
// ============================================================================
// CODE BLOCKS AND STATEMENTS
// ============================================================================
//
// Code blocks contain local variable definitions and statements. They manage
// scope via codeBlock_scope and navigate the ScriptScope tree from the type
// checking pass.
//
// Scope Navigation:
// - codeBlock_scope.currentScope : ScriptScope (from type checker)
// - codeBlock_scope.nextScopeChild : Index for child scope navigation
// - Each nested block increments nextScopeChild to get next child scope
//
// Variable Definitions:
// Local variables are accumulated in codeBlock_scope.varDefs and emitted
// at the beginning of the function body.
// ============================================================================
codeBlock
scope codeBlock_scope;
// Parameters (semantic, passed by caller):
// - aBlockStatements : List<StringTemplate> - Output statement list
// - aVarDefs : List<StringTemplate> - Output variable definition list
// - aScope : ScriptScope - Current scope from type checker
//
// Process all statements in block
// Accumulate variable definitions in aVarDefs
// Accumulate statement code in aBlockStatements
: statement*
;
// ----------------------------------------------------------------------------
// STATEMENT DISPATCHER
// ----------------------------------------------------------------------------
// Dispatches to specific statement types based on AST node type.
//
// SF1 has 9 statement alternatives in the post-optimization AST:
// 1. localDefinition - Local variable declaration (VAR node)
// 2. EQUALS assignment - ^(EQUALS ID l_value expression)
// 3. NOCODEASSIGN - ^(NOCODEASSIGN l_value expression) (optimized out)
// 4. expression - Expression statement (function call, etc.)
// 5. return_stat - Return statement (RETURN node)
// 6. lockBlock - LockGuard block (LOCKGUARD node, SF1-specific)
// 7. tryLockBlock - TryLockGuard block (TRYLOCKGUARD node, SF1-specific)
// 8. ifBlock - If/ElseIf/Else conditional (IF node)
// 9. whileBlock - While loop (WHILE node)
//
// Note: property_set and struct_set are NOT standalone statements.
// They appear inside l_value (via DOT+PAREXPR) or basic_l_value.
// NATIVE is not a statement type in PapyrusGen (it is handled in functionBlock).
// ----------------------------------------------------------------------------
statement
scope statement_scope;
: localDefinition
| ^(EQUALS ID l_value expression)
-> template(target={...}, targetExpressions={...},
source={...}, sourceExpressions={...}, lineNo={...})
| ^(NOCODEASSIGN l_value expression)
-> template(targetExpressions={...}, sourceExpressions={...})
| expression
| return_stat
| lockBlock // SF1-specific
| tryLockBlock // SF1-specific
| ifBlock
| whileBlock
;
// ----------------------------------------------------------------------------
// LOCAL VARIABLE DEFINITION
// ----------------------------------------------------------------------------
// Generates: .local <name> <type> [= <initialValue>]
// Template: variableDef
//
// Local variables are accumulated in codeBlock_scope.varDefs and emitted at
// the beginning of the function body (not inline with statements).
//
// Return Value:
// Custom return type with:
// - VarName : string - Variable name
// - ExprVar : string - Expression result variable (if initialization)
// - ExprST : StringTemplate - Expression code template
// - LineNo : int - Source line number
// ----------------------------------------------------------------------------
localDefinition
// Extract type and name
// Process optional initialization expression
// Generate variable definition template
// Add to codeBlock_scope.varDefs
// If initialized, generate assignment statement
: anyType ID (expression)?
-> template(type={...}, name={...})
;
// ----------------------------------------------------------------------------
// ASSIGNMENT L-VALUE
// ----------------------------------------------------------------------------
// In the post-optimization AST, l_value handles three forms:
//
// 1. ^(DOT ^(PAREXPR expression) (property_set | struct_set))
// - Dotted member access with property/struct setter
// - Template: dot(aTemplate, bTemplate)
//
// 2. ^(ARRAYSET idOrConstant ID ^(PAREXPR expression) expression)
// - Array element assignment
// - Template: arraySet
//
// 3. basic_l_value
// - Simple variable, function call, property/struct set, array set, DOT
// ----------------------------------------------------------------------------
l_value
scope l_value_scope;
: ^(DOT ^(PAREXPR expression) (property_set | struct_set))
-> template(aTemplate={...}, bTemplate={...})
| ^(ARRAYSET idOrConstant ID ^(PAREXPR expression) expression)
-> template(sourceName={...}, selfName={...}, index={...},
arrayExpressions={...}, indexExpressions={...}, lineNo={...})
| basic_l_value
;
// ----------------------------------------------------------------------------
// BASIC L-VALUE
// ----------------------------------------------------------------------------
// In the post-optimization AST, basic_l_value has 6 forms:
//
// 1. ^(DOT array_func_or_id basic_l_value)
// - Dotted access chain (recursive)
// - Template: dot(aTemplate, bTemplate)
//
// 2. function_call
// - Function call as l-value (result discarded or used)
//
// 3. property_set
// - Property setter (PROPSET node)
//
// 4. struct_set
// - Struct member setter (STRUCTSET node)
//
// 5. ^(ARRAYSET idOrConstant ID func_or_id expression)
// - Array element assignment (flattened form)
// - Template: arraySet
//
// 6. ID
// - Simple variable reference
// ----------------------------------------------------------------------------
basic_l_value
scope basic_l_value_scope;
: ^(DOT array_func_or_id basic_l_value)
-> template(aTemplate={...}, bTemplate={...})
| function_call
| property_set
| struct_set
| ^(ARRAYSET idOrConstant ID func_or_id expression)
-> template(sourceName={...}, selfName={...}, index={...},
arrayExpressions={...}, indexExpressions={...}, lineNo={...})
| ID
;
// ----------------------------------------------------------------------------
// LOCK GUARD BLOCK (SF1-Specific)
// ----------------------------------------------------------------------------
// Generates:
// LockGuard <guard1>
// LockGuard <guard2>
// ...
// <block statements>
// ...
// UnlockGuard <guard2> ; Reverse order
// UnlockGuard <guard1>
//
// Template: lockBlock
//
// Key Features:
// - Multiple guards can be locked in sequence
// - Guards are unlocked in LIFO order (reverse acquisition)
// - Scope exit (return) auto-unlocks via GenerateScopeExitExpressions()
//
// Syntax:
// LockGuard Guard1, Guard2
// ; critical section
// EndLockGuard
//
// Implementation:
// 1. Lock all guards in order
// 2. Execute block statements
// 3. Unlock all guards in reverse order
// ----------------------------------------------------------------------------
lockBlock
scope lockBlock_scope;
// Extract list of guard names
// Process codeBlock for critical section
// Generate lockBlock template with:
// - guards: List of guard names
// - blockStatements: Critical section code
// Template automatically generates unlock in reverse order
: ID+ codeBlock
-> template(guards={...}, blockStatements={...}, lineNo={...},
endLineNo={...})
;
// ----------------------------------------------------------------------------
// TRY LOCK GUARD BLOCK (SF1-Specific)
// ----------------------------------------------------------------------------
// Generates:
// TryLockGuard <guard1> <resultVar>
// Jump_if_not <resultVar> label0
// <success block>
// UnlockGuard <guard1>
// Jump endLabel
// label0:
// TryLockGuard <guard2> <resultVar>
// Jump_if_not <resultVar> label1
// <alternate block>
// UnlockGuard <guard2>
// Jump endLabel
// label1:
// <else block>
// endLabel:
//
// Template: tryLockBlock
//
// Key Features:
// - Non-blocking lock acquisition
// - Multiple alternate branches (elseTryLockBlock)
// - Optional final else block if all locks fail
// - Each successful branch unlocks before jumping to end
//
// Syntax:
// TryLockGuard ResultVar Guard1
// ; success branch
// ElseTryLockGuard ResultVar Guard2
// ; alternate branch
// Else
// ; failure branch
// EndTryLockGuard
// ----------------------------------------------------------------------------
tryLockBlock
scope tryLockBlock_scope;
// Extract result variable name
// Extract list of guard names for primary try-lock
// Process success block (codeBlock)
// Process alternate branches (elseTryLockBlock*)
// Process optional final else block
// Generate tryLockBlock template with:
// - resultVar: Boolean result variable
// - guards: Primary guard list
// - blockStatements: Success block
// - eltryBlocks: Alternate branches
// - blockElse: Final else block
// - endLabel: Control flow end label
: ID ID+ codeBlock elseTryLockBlock* elseBlock?
-> template(resultVar={...}, guards={...}, blockStatements={...},
eltryBlocks={...}, blockElse={...}, endLabel={...},
lineNo={...})
;
elseTryLockBlock
scope elseTryLockBlock_scope;
// Extract result variable name
// Extract list of guard names for alternate try-lock
// Process alternate block (codeBlock)
// Generate elseTryLockBlock template with:
// - resultVar: Boolean result variable
// - guards: Alternate guard list
// - blockStatements: Alternate block
// - labelElse: Label for next branch
// - endLabel: Control flow end label (from tryLockBlock_scope)
: ID ID+ codeBlock
-> template(resultVar={...}, guards={...}, blockStatements={...},
labelElse={...}, endLabel={...}, lineNo={...})
;
// ----------------------------------------------------------------------------
// IF STATEMENT
// ----------------------------------------------------------------------------
// Generates:
// <condition expression>
// Jump_if_not <condition> label0
// <if block>
// Jump endLabel
// label0:
// <elseif condition>
// Jump_if_not <condition> label1
// <elseif block>
// Jump endLabel
// label1:
// <else block>
// endLabel:
//
// Template: ifBlock, elseIfBlock, elseBlock
// ----------------------------------------------------------------------------
ifBlock
scope ifBlock_scope;
// Evaluate condition expression
// Process if block (codeBlock)
// Process elseif branches (elseIfBlock*)
// Process optional else block
// Generate ifBlock template with control flow labels
: expression codeBlock elseIfBlock* elseBlock?
-> template(condition={...}, condExpressions={...},
blockStatements={...}, elifBlocks={...}, blockElse={...},
endLabel={...}, lineNo={...})
;
elseIfBlock
scope elseIfBlock_scope;
// Evaluate condition expression
// Process elseif block (codeBlock)
// Generate elseIfBlock template with control flow labels
: expression codeBlock
-> template(condition={...}, condExpressions={...},
blockStatements={...}, labelElse={...},
endLabel={...}, lineNo={...})
;
elseBlock
scope elseBlock_scope;
// Process else block (codeBlock)
// Generate elseBlock template
: codeBlock
-> template(blockStatements={...})
;
// ----------------------------------------------------------------------------
// WHILE LOOP
// ----------------------------------------------------------------------------
// Generates:
// startLabel:
// <condition expression>
// Jump_if_not <condition> endLabel
// <loop block>
// Jump startLabel
// endLabel:
//
// Template: whileBlock
// ----------------------------------------------------------------------------
whileBlock
scope whileBlock_scope;
// Generate start and end labels
// Evaluate condition expression
// Process loop block (codeBlock)
// Generate whileBlock template with control flow labels
: expression codeBlock
-> template(condition={...}, condExpressions={...},
blockStatements={...}, startLabel={...}, endLabel={...},
lineNo={...})
;
// ----------------------------------------------------------------------------
// RETURN STATEMENT
// ----------------------------------------------------------------------------
// Generates:
// <scope exit expressions> ; Guard unlocks (SF1)
// Return <value>
//
// Template: returnStatement
//
// SF1 Guard Unlocking:
// Before returning, all guards held by the current scope (and parent scopes
// up to the function boundary) must be unlocked in LIFO order.
//
// This is handled by GenerateScopeExitExpressions() helper:
// - Calls currentScope.BuildGuardsToUnlockOnExit()
// - Generates unlockGuards templates in reverse order
// - Inserts before return statement
//
// Example:
// Function Test()
// LockGuard Lock1
// LockGuard Lock2
// Return 42 ; Must unlock Lock2, then Lock1
// EndLockGuard
// EndLockGuard
// EndFunction
//
// Generated:
// UnlockGuard Lock2
// UnlockGuard Lock1
// Return ::temp0
// ----------------------------------------------------------------------------
return_stat
scope return_stat_scope;
// Process optional return expression
// Call GenerateScopeExitExpressions() to generate guard unlocks (SF1)
// Generate returnStatement template with:
// - retValue: Expression result (or "None" for void)
// - retExpr: Expression code
// - scopeExitExpressions: Guard unlocks (SF1)
// - lineNo: Source line number
: ^(RETURN expression)
-> template(retVal={...}, extraExpressions={...},
scopeExitExpressions={...}, lineNo={...})
| RETURN
-> template(retVal={...}, scopeExitExpressions={...}, lineNo={...})
;
// ============================================================================
// EXPRESSIONS
// ============================================================================
//
// Expressions are evaluated bottom-up and return two values:
// 1. Template: StringTemplate with code to compute the expression