-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQExpression.cpp
More file actions
1049 lines (944 loc) · 29.3 KB
/
QExpression.cpp
File metadata and controls
1049 lines (944 loc) · 29.3 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
#include <assert.h>
#include <iostream>
#include "FileLexer.h"
#include "Type.h"
#include "Expression.h"
#include "CompilerHelpers.h"
#include "logging.h"
SET_LOG_CAT( LOG_CAT_ALL );
SET_LOG_LEVEL( LOG_LVL_NOISE );
using namespace QLang;
using namespace std;
// Return operator precedence for binary operators (higher = tighter binding).
// Returns -1 if the token is not a binary operator.
static int getOperatorPrec( int sym, const string &symText )
{
if ( sym == Lexer::RANGE ) return 0; // .. (lowest precedence)
if ( sym == Lexer::LOR ) return 1; // ||
if ( sym == Lexer::LAND ) return 2; // &&
if ( sym == '|' ) return 3; // bitwise or
if ( sym == '^' ) return 4; // bitwise xor
if ( sym == '&' ) return 5; // bitwise and
if ( sym == Lexer::EQ ) return 6; // == !=
// < and > as single chars are comparisons
if ( sym == '<' || sym == '>' ) return 7;
// <= and >= come through the lexer as ASSIGN tokens
if ( sym == Lexer::ASSIGN && ( symText == "<=" || symText == ">=" ) ) return 7;
if ( sym == Lexer::SHIFT ) return 8; // << >>
if ( sym == '+' || sym == '-' ) return 9;
if ( sym == '*' || sym == '/' || sym == '%' ) return 10;
return -1;
}
// Convert a token into its string representation for the AST node.
static string getOperatorString( int sym, const string &symText )
{
switch ( sym )
{
case '+': return "+";
case '-': return "-";
case '*': return "*";
case '/': return "/";
case '%': return "%";
case '^': return "^";
case '|': return "|";
case '&': return "&";
case '<': return "<";
case '>': return ">";
default: break;
}
// Multi-character operators: use the lexer text
if ( sym == Lexer::LOR ) return "||";
if ( sym == Lexer::LAND ) return "&&";
if ( sym == Lexer::EQ ) return symText; // "==" or "!="
if ( sym == Lexer::SHIFT ) return symText; // "<<" or ">>"
if ( sym == Lexer::ASSIGN ) return symText; // "<=" or ">="
if ( sym == Lexer::RANGE ) return "..";
return "";
}
// Parse a primary (atomic) expression: constant, variable, function call,
// array literal, or parenthesized sub-expression, followed by optional
// postfix field access, method calls, and indexing.
Expression *Expression::ParsePrimary( Lexer &l, Scope *scope )
{
Expression *result = nullptr;
int sym = l.peekSymbol();
// await expression: await EXPR
if ( sym == Lexer::KEYWORD_AWAIT )
{
l.getSymbol(); // consume 'await'
Expression *operand = ParsePrimary( l, scope );
if ( operand == nullptr )
COMPILE_ERROR( l, "Expected expression after 'await'" );
return new AwaitExpression( operand );
}
// Lambda expression: fn(params) -> RetType { body }
if ( sym == Lexer::KEYWORD_FN )
{
l.getSymbol(); // consume 'fn'
return LambdaExpression::Parse( l, scope );
}
// spawn expression: spawn { ... } returns a Task handle
if ( sym == Lexer::KEYWORD_SPAWN )
{
return SpawnStatement::Parse( l, scope );
}
// Query expressions: query T, insert T, update T, delete T
if ( sym == Lexer::KEYWORD_QUERY )
{
return QueryExpression::Parse( l, scope );
}
if ( sym == Lexer::KEYWORD_INSERT )
{
return InsertExpression::Parse( l, scope );
}
if ( sym == Lexer::KEYWORD_UPDATE )
{
return UpdateExpression::Parse( l, scope );
}
if ( sym == Lexer::KEYWORD_DELETE )
{
return DeleteExpression::Parse( l, scope );
}
// Query field reference: .field (used in query where/order_by/set blocks)
if ( sym == '.' )
{
l.getSymbol(); // consume '.'
int fieldSym = l.getSymbol();
if ( fieldSym != Lexer::SYMBOL )
COMPILE_ERROR( l, "Expected field name after '.'" );
result = new QueryFieldExpression( l.getSymbolText() );
}
// Unary prefix operators: -, !, ~
if ( sym == '-' || sym == '!' || sym == '~' )
{
l.getSymbol(); // consume operator
string opStr( 1, (char)sym );
Expression *operand = ParsePrimary( l, scope );
if ( operand == nullptr )
COMPILE_ERROR( l, "Expected expression after unary operator" );
return new UnaryExpression( opStr, operand );
}
// Parenthesized expression
if ( sym == '(' )
{
l.getSymbol(); // consume '('
Expression *expr = ParseExpr( l, scope, 0 );
if ( expr == nullptr )
COMPILE_ERROR( l, "Expected expression after '('" );
sym = l.getSymbol();
if ( sym != ')' )
COMPILE_ERROR( l, "Expected ')'" );
result = expr;
}
// Array literal: [expr, expr, ...]
else if ( sym == '[' )
{
l.getSymbol(); // consume '['
ArrayLiteralExpression *arr = new ArrayLiteralExpression();
// Empty array literal
if ( l.peekSymbol() == ']' )
{
l.getSymbol(); // consume ']'
}
else
{
// Parse elements until ']'
do {
Expression *elem = ParseExpr( l, scope, 0 );
if ( elem == nullptr )
COMPILE_ERROR( l, "Expected expression in array literal" );
arr->addElement( elem );
sym = l.getSymbol();
} while ( sym == ',' );
if ( sym != ']' )
COMPILE_ERROR( l, "Expected ',' or ']' in array literal" );
}
result = arr;
}
// String constant with possible interpolation
else if ( sym == Lexer::CONSTANT_STRING )
{
int pos = l.getCurrentPos();
l.getSymbol(); // consume to read text
string str = l.getSymbolText();
l.setCurrentPos( pos ); // restore
if ( str.find( '{' ) != string::npos )
{
l.getSymbol(); // consume for real
result = StringInterpolation::Parse( l, scope, str );
}
else
{
result = ConstExpression::Parse( l, scope );
}
}
// Other constants
else if ( sym == Lexer::CONSTANT_NUMBER ||
sym == Lexer::CONSTANT_FLOAT ||
sym == Lexer::CONSTANT_CHAR ||
sym == Lexer::CONSTANT_BOOL )
{
result = ConstExpression::Parse( l, scope );
}
// self keyword: look up as a variable
else if ( sym == Lexer::KEYWORD_SELF )
{
l.getSymbol(); // consume 'self'
SmartPtr<Symbol> selfSym = scope->findSymbol( "self" );
if ( selfSym == nullptr )
COMPILE_ERROR( l, "'self' can only be used inside methods" );
VariableDefinition *def = dynamic_cast<VariableDefinition*>( (Symbol*)selfSym );
if ( def != nullptr )
result = new VariableExpression( def );
}
// Symbol: could be a struct literal, function call, or variable reference
else if ( sym == Lexer::SYMBOL )
{
int pos = l.getCurrentPos();
// Check for struct literal: StructName { field: value, ... }
// Peek at the identifier name and check if it's a known struct
l.getSymbol(); // consume SYMBOL to read its text
string identName = l.getSymbolText();
l.setCurrentPos( pos ); // restore position
// Check for module-qualified access: sys.args, sys.exit(), net.Socket { }
Scope *nsScope = scope->findNamespace( identName );
if ( nsScope != nullptr && scope->isModuleImported( identName ) )
{
// Save position past the module name to check for '.'
l.getSymbol(); // consume module name
if ( l.peekSymbol() == '.' )
{
l.getSymbol(); // consume '.'
int memberSym = l.getSymbol();
if ( memberSym != Lexer::SYMBOL )
COMPILE_ERROR( l, "Expected member name after '" + identName + ".'" );
string memberName = l.getSymbolText();
Symbol *resolved = nsScope->findSymbol( memberName );
if ( resolved == nullptr )
COMPILE_ERROR( l, "Module '" + identName + "' has no member '" + memberName + "'" );
FunctionDefinition *funcDef = dynamic_cast<FunctionDefinition*>( resolved );
StructDefinition *structDef = dynamic_cast<StructDefinition*>( resolved );
if ( funcDef != nullptr )
{
if ( l.peekSymbol() == '(' )
{
// sys.exit(1) → CallExpression with mangled name sys__exit
// Create a call expression referencing the original FunctionDefinition
CallExpression *call = new CallExpression( funcDef );
call->setMangledName( identName + "__" + memberName );
l.getSymbol(); // consume '('
if ( l.peekSymbol() != ')' )
{
do {
Expression *arg = ParseExpr( l, scope, 0 );
if ( arg == nullptr )
COMPILE_ERROR( l, "Expected expression in function call" );
call->addParam( arg );
int s = l.getSymbol();
if ( s == ')' ) break;
if ( s != ',' )
COMPILE_ERROR( l, "Expected ',' or ')' in function call" );
} while ( true );
}
else
{
l.getSymbol(); // consume ')'
}
result = call;
}
else
{
// sys.args → zero-arg getter call (property-style)
CallExpression *call = new CallExpression( funcDef );
call->setMangledName( identName + "__" + memberName );
result = call;
}
}
else if ( structDef != nullptr && l.peekSymbol() == '{' )
{
// net.Socket { fd: 5 } → struct literal
// Restore position to just before the '{' and parse normally
// We need to handle this specially since StructLiteralExpression::Parse
// expects SYMBOL '{' ...
int beforeBrace = l.getCurrentPos();
l.getSymbol(); // consume '{'
StructLiteralExpression *expr = new StructLiteralExpression( memberName );
if ( l.peekSymbol() != '}' )
{
do {
int fSym = l.getSymbol();
if ( fSym != Lexer::SYMBOL )
COMPILE_ERROR( l, "Expected field name in struct literal" );
string fieldName = l.getSymbolText();
int colon = l.getSymbol();
if ( colon != ':' )
COMPILE_ERROR( l, "Expected ':' after field name in struct literal" );
Expression *value = ParseExpr( l, scope, 0 );
if ( value == nullptr )
COMPILE_ERROR( l, "Expected expression for field value" );
expr->addField( fieldName, value );
if ( l.peekSymbol() == ',' )
l.getSymbol();
} while ( l.peekSymbol() != '}' );
}
int closeBrace = l.getSymbol();
if ( closeBrace != '}' )
COMPILE_ERROR( l, "Expected '}' in struct literal" );
result = expr;
}
else if ( structDef != nullptr )
{
// net.Socket used as a type reference — not valid in expression position
COMPILE_ERROR( l, "'" + identName + "." + memberName + "' is a type, not an expression" );
}
else
{
COMPILE_ERROR( l, "Module '" + identName + "' member '" + memberName + "' is not a function or struct" );
}
}
else
{
// Module name without '.', restore and fall through
l.setCurrentPos( pos );
}
}
SmartPtr<Symbol> structSym = scope->findSymbol( identName );
if ( structSym != nullptr &&
dynamic_cast<StructDefinition*>( (Symbol*)structSym ) != nullptr )
{
// Save position again to peek past the identifier
l.getSymbol(); // consume SYMBOL
int nextSym = l.peekSymbol();
if ( nextSym == '{' )
{
l.setCurrentPos( pos ); // restore for Parse method
result = StructLiteralExpression::Parse( l, scope, identName );
}
else if ( nextSym == '<' )
{
// Generic struct literal: Box<int> { ... }
// Save position in case this isn't actually a generic struct literal
int genericPos = l.getCurrentPos();
l.getSymbol(); // consume '<'
// Parse type arguments
std::vector<SmartPtr<Type>> typeArgs;
do {
Type *param = Type::Parse( l, scope, false );
if ( param == nullptr )
{
// Not a valid type — restore and fall through
l.setCurrentPos( pos );
typeArgs.clear();
break;
}
typeArgs.push_back( param );
int next = l.getSymbol();
if ( next == '>' )
break;
if ( next != ',' )
{
l.setCurrentPos( pos );
typeArgs.clear();
break;
}
} while ( true );
if ( !typeArgs.empty() && l.peekSymbol() == '{' )
{
// We have Box<int> { ... } — parse as struct literal with type args
l.setCurrentPos( pos ); // restore for Parse method
result = StructLiteralExpression::Parse( l, scope, identName );
}
else if ( !typeArgs.empty() )
{
// Had type args but no '{' — restore
l.setCurrentPos( pos );
}
// else already restored above
}
else
{
l.setCurrentPos( pos ); // restore, not a struct literal
}
}
// Check for enum variant construction: EnumName.variant or EnumName.variant(args)
if ( result == nullptr && structSym != nullptr )
{
EnumDefinition *enumDef = dynamic_cast<EnumDefinition*>( (Symbol*)structSym );
if ( enumDef != nullptr )
{
// We have an enum name. Peek ahead for '.variant'
l.getSymbol(); // consume SYMBOL (the enum name)
if ( l.peekSymbol() == '.' )
{
l.getSymbol(); // consume '.'
int fieldSym = l.getSymbol();
if ( fieldSym == Lexer::SYMBOL )
{
string variantName = l.getSymbolText();
// Find the variant index
int variantIdx = -1;
const auto &variants = enumDef->getVariants();
for ( size_t v = 0; v < variants.size(); v++ )
{
if ( variants[v].mName == variantName )
{
variantIdx = static_cast<int>( v );
break;
}
}
if ( variantIdx >= 0 )
{
EnumConstructExpression *enumExpr = new EnumConstructExpression( enumDef, variantIdx );
// Check for arguments: variant(args)
if ( l.peekSymbol() == '(' )
{
l.getSymbol(); // consume '('
if ( l.peekSymbol() != ')' )
{
do {
Expression *arg = ParseExpr( l, scope, 0 );
if ( arg == nullptr )
COMPILE_ERROR( l, "Expected expression in enum variant argument" );
enumExpr->addArg( arg );
sym = l.getSymbol();
} while ( sym == ',' );
if ( sym != ')' )
COMPILE_ERROR( l, "Expected ',' or ')' in enum variant arguments" );
}
else
{
l.getSymbol(); // consume ')'
}
}
result = enumExpr;
}
else
{
l.setCurrentPos( pos ); // restore, unknown variant
}
}
else
{
l.setCurrentPos( pos ); // restore
}
}
else
{
l.setCurrentPos( pos ); // restore, no dot after enum name
}
}
}
// Try function call first (save/restore position on failure)
if ( result == nullptr )
{
try {
CallExpression *callExpr = CallExpression::Parse( l, scope );
if ( callExpr != nullptr )
result = callExpr;
} catch ( CompileError & ) {
// Not a valid call — fall through to variable or function ref
}
}
// Check for bare function name used as a value (function reference)
if ( result == nullptr )
{
l.setCurrentPos( pos );
l.getSymbol(); // consume SYMBOL to read name
string symName = l.getSymbolText();
SmartPtr<Symbol> symLookup = scope->findSymbol( symName );
if ( symLookup != nullptr && symLookup->getSymbolType() == Symbol::TypeFunction &&
l.peekSymbol() != '(' )
{
FunctionDefinition *funcDef = dynamic_cast<FunctionDefinition*>( (Symbol*)symLookup );
if ( funcDef != nullptr )
result = new FunctionRefExpression( funcDef );
}
else
{
l.setCurrentPos( pos ); // restore for variable parse
}
}
if ( result == nullptr )
{
l.setCurrentPos( pos );
result = VariableExpression::Parse( l, scope );
// Check for indirect call through function-typed variable
if ( result != nullptr )
{
VariableExpression *varExpr = dynamic_cast<VariableExpression*>( result );
if ( varExpr != nullptr &&
varExpr->getVariable()->getVariableType()->isFunctionType() &&
l.peekSymbol() == '(' )
{
l.getSymbol(); // consume '('
IndirectCallExpression *indCall = new IndirectCallExpression( varExpr->getVariable() );
if ( l.peekSymbol() != ')' )
{
do {
Expression *arg = ParseExpr( l, scope, 0 );
if ( arg == nullptr )
COMPILE_ERROR( l, "Expected expression in indirect call" );
indCall->addParam( arg );
sym = l.getSymbol();
if ( sym == ')' ) break;
if ( sym != ',' )
COMPILE_ERROR( l, "Expected ',' or ')' in indirect call" );
} while ( true );
}
else
{
l.getSymbol(); // consume ')'
}
result = indCall;
}
}
}
}
// Postfix operators: field access (.field), method calls (.method()), indexing ([expr])
while ( result != nullptr )
{
if ( l.peekSymbol() == '.' )
{
l.getSymbol(); // consume '.'
int fieldSym = l.getSymbol();
if ( fieldSym != Lexer::SYMBOL )
COMPILE_ERROR( l, "Expected field name after '.'" );
string fieldName = l.getSymbolText();
// Check if this is a method call: expr.method(args)
if ( l.peekSymbol() == '(' )
{
l.getSymbol(); // consume '('
MethodCallExpression *methodCall = new MethodCallExpression( result, fieldName );
// Empty argument list
if ( l.peekSymbol() == ')' )
{
l.getSymbol(); // consume ')'
}
else
{
// Parse arguments until ')'
do {
Expression *arg = ParseExpr( l, scope, 0 );
if ( arg == nullptr )
COMPILE_ERROR( l, "Expected expression in method call" );
methodCall->addArg( arg );
sym = l.getSymbol();
} while ( sym == ',' );
if ( sym != ')' )
COMPILE_ERROR( l, "Expected ',' or ')' in method call" );
}
result = methodCall;
}
else
{
result = new FieldAccessExpression( result, fieldName );
}
}
else if ( l.peekSymbol() == '[' )
{
l.getSymbol(); // consume '['
Expression *index = ParseExpr( l, scope, 0 );
if ( index == nullptr )
COMPILE_ERROR( l, "Expected expression in index" );
int closeBracket = l.getSymbol();
if ( closeBracket != ']' )
COMPILE_ERROR( l, "Expected ']'" );
result = new IndexExpression( result, index );
}
else if ( l.peekSymbol() == Lexer::QUESTION_MARK )
{
l.getSymbol(); // consume '?'
result = new TryExpression( result );
}
else
{
break;
}
}
return result;
}
// Precedence-climbing binary expression parser.
// Parses a binary expression with operators at or above minPrec.
Expression *Expression::ParseExpr( Lexer &l, Scope *scope, int minPrec )
{
Expression *left = ParsePrimary( l, scope );
if ( left == nullptr )
return nullptr;
while ( true )
{
int nextSym = l.peekSymbol();
string nextText = l.getSymbolText();
// Handle pipeline operator |> at lowest precedence (below range)
// Desugars: expr |> fn -> fn(expr)
// expr |> fn(args) -> fn(expr, args)
if ( nextSym == Lexer::PIPE_ARROW )
{
if ( minPrec > 0 )
break; // |> has precedence 0, below everything except itself
l.getSymbol(); // consume |>
// The RHS of a pipeline can be:
// 1. A function call: expr |> fn(args) -> fn(expr, args)
// 2. A bare function name: expr |> fn -> fn(expr)
int rhsSym = l.peekSymbol();
if ( rhsSym == Lexer::SYMBOL )
{
int pos = l.getCurrentPos();
l.getSymbol(); // consume symbol
string name = l.getSymbolText();
SmartPtr<Symbol> funcSym = scope->findSymbol( name );
if ( funcSym != nullptr && funcSym->getSymbolType() == Symbol::TypeFunction )
{
FunctionDefinition *funcDef = dynamic_cast<FunctionDefinition*>( (Symbol*)funcSym );
CallExpression *call = new CallExpression( funcDef );
call->addParam( left );
// Check if there are additional arguments: fn(args)
if ( l.peekSymbol() == '(' )
{
l.getSymbol(); // consume '('
if ( l.peekSymbol() != ')' )
{
do {
Expression *arg = ParseExpr( l, scope, 0 );
if ( arg == nullptr )
COMPILE_ERROR( l, "Expected expression in pipeline call arguments" );
call->addParam( arg );
int s = l.getSymbol();
if ( s == ')' ) break;
if ( s != ',' )
COMPILE_ERROR( l, "Expected ',' or ')' in pipeline call" );
} while ( true );
}
else
{
l.getSymbol(); // consume ')'
}
}
left = call;
}
else
{
// Not a function — try parsing as a general expression
l.setCurrentPos( pos );
Expression *right = ParsePrimary( l, scope );
if ( right == nullptr )
COMPILE_ERROR( l, "Expected expression after '|>'" );
left = new PipelineExpression( left, right );
}
}
else
{
// RHS starts with something other than a symbol
Expression *right = ParsePrimary( l, scope );
if ( right == nullptr )
COMPILE_ERROR( l, "Expected expression after '|>'" );
left = new PipelineExpression( left, right );
}
continue;
}
int prec = getOperatorPrec( nextSym, nextText );
if ( prec < 0 || prec < minPrec )
break;
// Consume the operator
l.getSymbol();
string opStr = getOperatorString( nextSym, nextText );
// Handle range operator specially: create RangeExpression instead of OperationsExpression
if ( nextSym == Lexer::RANGE )
{
Expression *right = ParseExpr( l, scope, prec + 1 );
if ( right == nullptr )
COMPILE_ERROR( l, "Expected expression after '..'" );
left = new RangeExpression( left, right );
continue;
}
// Parse right-hand side with higher precedence (left-associative)
Expression *right = ParseExpr( l, scope, prec + 1 );
if ( right == nullptr )
COMPILE_ERROR( l, "Expected expression after operator" );
left = new OperationsExpression( opStr, left, right );
}
return left;
}
// Top-level expression parser.
// Parses a full expression (including assignment) and consumes the terminal.
Expression *Expression::Parse( Lexer &l, Scope *scope, char terminal )
{
TRACE_BEGIN( LOG_LVL_INFO );
Expression *exp = ParseExpr( l, scope, 0 );
if ( exp != nullptr )
{
int nextSym = l.peekSymbol();
string nextText = l.getSymbolText();
// Check for assignment: = or compound assignment (+=, -=, etc.)
bool isAssign = false;
string assignOp;
if ( nextSym == '=' )
{
isAssign = true;
assignOp = "=";
}
else if ( nextSym == Lexer::ASSIGN && nextText != "<=" && nextText != ">=" )
{
isAssign = true;
assignOp = nextText;
}
if ( isAssign )
{
VariableExpression *varExpr = dynamic_cast<VariableExpression*>( exp );
FieldAccessExpression *fieldExpr = dynamic_cast<FieldAccessExpression*>( exp );
IndexExpression *indexExpr = dynamic_cast<IndexExpression*>( exp );
if ( varExpr != nullptr )
{
l.getSymbol(); // consume assignment operator
Expression *value = ParseExpr( l, scope, 0 );
if ( value == nullptr )
COMPILE_ERROR( l, "Expected expression after assignment operator" );
exp = new AssignmentExpression( assignOp, varExpr->getVariable(), value );
}
else if ( fieldExpr != nullptr )
{
l.getSymbol(); // consume assignment operator
Expression *value = ParseExpr( l, scope, 0 );
if ( value == nullptr )
COMPILE_ERROR( l, "Expected expression after assignment operator" );
exp = new FieldAssignmentExpression( assignOp, fieldExpr->getObject(), fieldExpr->getFieldName(), value );
}
else if ( indexExpr != nullptr )
{
l.getSymbol(); // consume assignment operator
Expression *value = ParseExpr( l, scope, 0 );
if ( value == nullptr )
COMPILE_ERROR( l, "Expected expression after assignment operator" );
exp = new IndexAssignmentExpression( assignOp, indexExpr->getObject(), indexExpr->getIndex(), value );
}
else
{
COMPILE_ERROR( l, "Left side of assignment must be a variable, field, or index expression" );
}
}
}
// Consume terminal if present
if ( exp != nullptr && l.peekSymbol() == terminal )
l.getSymbol();
return exp;
}
VariableExpression *VariableExpression::Parse( Lexer &l, Scope *scope )
{
TRACE_BEGIN( LOG_LVL_INFO );
VariableExpression *exp = nullptr;
int sym = l.getSymbol();
if ( sym == Lexer::SYMBOL )
{
SmartPtr<Symbol> s = scope->findSymbol( l.getSymbolText() );
if ( s == nullptr )
{
cerr << "Symbol Text " << l.getSymbolText() << endl;
COMPILE_ERROR( l, "Failed to find Symbol" );
}
LOG( "Found symbol type %d", s->getSymbolType() );
if ( s->getSymbolType() == Symbol::TypeVariable )
{
VariableDefinition *def = dynamic_cast<VariableDefinition*>( (Symbol*)s );
if ( def != nullptr )
exp = new VariableExpression( def );
}
}
return exp;
}
CallExpression *CallExpression::Parse( Lexer &l, Scope *scope )
{
CallExpression *exp = nullptr;
int sym = l.getSymbol();
if ( sym == Lexer::SYMBOL )
{
SmartPtr<Symbol> s = scope->findSymbol( l.getSymbolText() );
if ( s == nullptr )
{
COMPILE_ERROR( l, "Failed to find Symbol" );
}
if ( s->getSymbolType() == Symbol::TypeFunction )
{
FunctionDefinition *def = dynamic_cast<FunctionDefinition*>( (Symbol*)s );
exp = new CallExpression( def );
// Check for generic type arguments: fn<int>(args)
if ( l.peekSymbol() == '<' )
{
l.getSymbol(); // consume '<'
do {
Type *param = Type::Parse( l, scope, false );
if ( param == nullptr )
COMPILE_ERROR( l, "Expected type argument in generic function call" );
exp->addTypeArg( param );
int next = l.getSymbol();
if ( next == '>' )
break;
if ( next != ',' )
COMPILE_ERROR( l, "Expected ',' or '>' in generic type arguments" );
} while ( true );
}
sym = l.getSymbol();
if ( sym != '(' )
return nullptr;
// Empty argument list
if ( l.peekSymbol() == ')' )
{
l.getSymbol(); // consume ')'
}
else
{
// Parse arguments until ')'
do {
Expression *param = ParseExpr( l, scope, 0 );
if ( param != nullptr )
exp->mParams.push_back( param );
else
return nullptr;
sym = l.getSymbol();
} while ( sym == ',' );
if ( sym != ')' )
COMPILE_ERROR( l, "Expected ',' or ')' in function call" );
}
}
}
return exp;
}
ConstExpression *ConstExpression::Parse( Lexer &l, Scope *scope )
{
ConstExpression *exp = nullptr;
int sym = l.getSymbol();
switch( sym )
{
case Lexer::CONSTANT_STRING:
exp = new ConstString( l.getSymbolText() );
break;
case Lexer::CONSTANT_CHAR:
exp = new ConstChar( l.getSymbolText() );
break;
case Lexer::CONSTANT_NUMBER:
exp = new ConstInteger( atoi( l.getSymbolText().c_str() ) );
break;
case Lexer::CONSTANT_FLOAT:
exp = new ConstFloat( atof( l.getSymbolText().c_str() ) );
break;
case Lexer::CONSTANT_BOOL:
exp = new ConstInteger( l.getSymbolText() == "true" ? 1 : 0 );
break;
default:
return nullptr;
}
return exp;
}
// Parse string interpolation from a raw string containing {varname} patterns.
// Creates alternating ConstString and VariableExpression parts.
StringInterpolation *StringInterpolation::Parse( Lexer &l, Scope *scope, const string &rawString )
{
StringInterpolation *interp = new StringInterpolation();
size_t pos = 0;
while ( pos < rawString.size() )
{
size_t braceStart = rawString.find( '{', pos );
if ( braceStart == string::npos )
{
// Rest is literal
if ( pos < rawString.size() )
interp->addPart( new ConstString( rawString.substr( pos ) ) );
break;
}
// Literal before brace
if ( braceStart > pos )
interp->addPart( new ConstString( rawString.substr( pos, braceStart - pos ) ) );
// Find closing brace
size_t braceEnd = rawString.find( '}', braceStart );
if ( braceEnd == string::npos )
{
// No closing brace, treat rest as literal
interp->addPart( new ConstString( rawString.substr( braceStart ) ) );
break;
}
// Extract variable name
string varName = rawString.substr( braceStart + 1, braceEnd - braceStart - 1 );
// Look up variable in scope
SmartPtr<Symbol> sym = scope->findSymbol( varName );
if ( sym != nullptr )
{
VariableDefinition *varDef = dynamic_cast<VariableDefinition*>( (Symbol*)sym );
if ( varDef != nullptr )
{
interp->addPart( new VariableExpression( varDef ) );
}
else
{
// Not a variable, treat as literal
interp->addPart( new ConstString( rawString.substr( braceStart, braceEnd - braceStart + 1 ) ) );
}
}
else
{
// Unknown symbol, treat as literal (might be used before declaration)
interp->addPart( new ConstString( rawString.substr( braceStart, braceEnd - braceStart + 1 ) ) );
}
pos = braceEnd + 1;
}
return interp;
}
StructLiteralExpression *StructLiteralExpression::Parse( Lexer &l, Scope *scope, const string &typeName )
{
TRACE_BEGIN( LOG_LVL_INFO );
// Consume the struct type name
int sym = l.getSymbol();
if ( sym != Lexer::SYMBOL )
COMPILE_ERROR( l, "Expected struct type name" );
// Check for generic type arguments: StructName<T1, T2>
std::vector<SmartPtr<Type>> typeArgs;
if ( l.peekSymbol() == '<' )
{
l.getSymbol(); // consume '<'
do {
Type *param = Type::Parse( l, scope, false );
if ( param == nullptr )
COMPILE_ERROR( l, "Expected type argument in generic struct literal" );
typeArgs.push_back( param );
int next = l.getSymbol();
if ( next == '>' )
break;
if ( next != ',' )
COMPILE_ERROR( l, "Expected ',' or '>' in generic type arguments" );
} while ( true );