-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathcompiler.c
More file actions
3500 lines (2836 loc) · 112 KB
/
Copy pathcompiler.c
File metadata and controls
3500 lines (2836 loc) · 112 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
/*
* Copyright (c) 2020-2022 Thakee Nathees
* Copyright (c) 2021-2022 Pocketlang Contributors
* Distributed Under The MIT License
*/
#ifndef PK_AMALGAMATED
#include "compiler.h"
#include "core.h"
#include "buffers.h"
#include "utils.h"
#include "vm.h"
#include "debug.h"
#endif
// The maximum number of locals or global (if compiling top level module)
// to lookup from the compiling context. Also it's limited by it's opcode
// which is using a single byte value to identify the local.
#define MAX_VARIABLES 256
// The maximum number of constant literal a module can contain. Also it's
// limited by it's opcode which is using a short value to identify.
#define MAX_CONSTANTS (1 << 16)
// The maximum number of upvaues a literal function can capture from it's
// enclosing function.
#define MAX_UPVALUES 256
// The maximum number of names that were used before defined. Its just the size
// of the Forward buffer of the compiler. Feel free to increase it if it
// require more.
#define MAX_FORWARD_NAMES 256
// Pocketlang support two types of interpolation.
//
// 1. Name interpolation ex: "Hello $name!"
// 2. Expression interpolation ex: "Hello ${getName()}!"
//
// Consider a string: "a ${ b "c ${d}" } e" -- Here the depth of 'b' is 1 and
// the depth of 'd' is 2 and so on. The maximum depth an expression can go is
// defined as MAX_STR_INTERP_DEPTH below.
#define MAX_STR_INTERP_DEPTH 8
// The maximum address possible to jump. Similar limitation as above.
#define MAX_JUMP (1 << 16)
// Max number of break statement in a loop statement to patch.
#define MAX_BREAK_PATCH 256
/*****************************************************************************/
/* TOKENS */
/*****************************************************************************/
typedef enum {
TK_ERROR = 0,
TK_EOF,
TK_LINE,
// symbols
TK_DOT, // .
TK_DOTDOT, // ..
TK_COMMA, // ,
TK_COLLON, // :
TK_SEMICOLLON, // ;
TK_HASH, // #
TK_LPARAN, // (
TK_RPARAN, // )
TK_LBRACKET, // [
TK_RBRACKET, // ]
TK_LBRACE, // {
TK_RBRACE, // }
TK_PERCENT, // %
TK_TILD, // ~
TK_AMP, // &
TK_PIPE, // |
TK_CARET, // ^
TK_ARROW, // ->
TK_PLUS, // +
TK_MINUS, // -
TK_STAR, // *
TK_FSLASH, // /
TK_STARSTAR, // **
TK_BSLASH, // \.
TK_EQ, // =
TK_GT, // >
TK_LT, // <
TK_EQEQ, // ==
TK_NOTEQ, // !=
TK_GTEQ, // >=
TK_LTEQ, // <=
TK_PLUSEQ, // +=
TK_MINUSEQ, // -=
TK_STAREQ, // *=
TK_DIVEQ, // /=
TK_MODEQ, // %=
TK_POWEQ, // **=
TK_ANDEQ, // &=
TK_OREQ, // |=
TK_XOREQ, // ^=
TK_SRIGHT, // >>
TK_SLEFT, // <<
TK_SRIGHTEQ, // >>=
TK_SLEFTEQ, // <<=
// Keywords.
TK_CLASS, // class
TK_FROM, // from
TK_IMPORT, // import
TK_AS, // as
TK_DEF, // def
TK_NATIVE, // native (C function declaration)
TK_FN, // function (literal function)
TK_END, // end
TK_NULL, // null
TK_IN, // in
TK_IS, // is
TK_AND, // and
TK_OR, // or
TK_NOT, // not / !
TK_TRUE, // true
TK_FALSE, // false
TK_SELF, // self
TK_SUPER, // super
TK_DO, // do
TK_THEN, // then
TK_WHILE, // while
TK_FOR, // for
TK_IF, // if
TK_ELIF, // elif
TK_ELSE, // else
TK_BREAK, // break
TK_CONTINUE, // continue
TK_RETURN, // return
TK_NAME, // identifier
TK_NUMBER, // number literal
TK_STRING, // string literal
/* String interpolation
* "a ${b} c $d e"
* tokenized as:
* TK_STR_INTERP "a "
* TK_NAME b
* TK_STR_INTERP " c "
* TK_NAME d
* TK_STRING " e" */
TK_STRING_INTERP,
} _TokenType;
// Winint.h has already defined TokenType which breaks amalgam build so I've
// change the name from TokenType to _TokenType.
typedef struct {
_TokenType type;
const char* start; //< Begining of the token in the source.
int length; //< Number of chars of the token.
int line; //< Line number of the token (1 based).
Var value; //< Literal value of the token.
} Token;
typedef struct {
const char* identifier;
int length;
_TokenType tk_type;
} _Keyword;
// List of keywords mapped into their identifiers.
static _Keyword _keywords[] = {
{ "class", 5, TK_CLASS },
{ "from", 4, TK_FROM },
{ "import", 6, TK_IMPORT },
{ "as", 2, TK_AS },
{ "def", 3, TK_DEF },
{ "native", 6, TK_NATIVE },
{ "fn", 2, TK_FN },
{ "end", 3, TK_END },
{ "null", 4, TK_NULL },
{ "in", 2, TK_IN },
{ "is", 2, TK_IS },
{ "and", 3, TK_AND },
{ "or", 2, TK_OR },
{ "not", 3, TK_NOT },
{ "true", 4, TK_TRUE },
{ "false", 5, TK_FALSE },
{ "self", 4, TK_SELF },
{ "super", 5, TK_SUPER },
{ "do", 2, TK_DO },
{ "then", 4, TK_THEN },
{ "while", 5, TK_WHILE },
{ "for", 3, TK_FOR },
{ "if", 2, TK_IF },
{ "elif", 4, TK_ELIF },
{ "else", 4, TK_ELSE },
{ "break", 5, TK_BREAK },
{ "continue", 8, TK_CONTINUE },
{ "return", 6, TK_RETURN },
{ NULL, 0, (_TokenType)(0) }, // Sentinel to mark the end of the array.
};
/*****************************************************************************/
/* COMPILER INTERNAL TYPES */
/*****************************************************************************/
// Precedence parsing references:
// http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
typedef enum {
PREC_NONE,
PREC_LOWEST,
PREC_LOGICAL_OR, // or
PREC_LOGICAL_AND, // and
PREC_EQUALITY, // == !=
PREC_TEST, // in is
PREC_COMPARISION, // < > <= >=
PREC_BITWISE_OR, // |
PREC_BITWISE_XOR, // ^
PREC_BITWISE_AND, // &
PREC_BITWISE_SHIFT, // << >>
PREC_RANGE, // ..
PREC_TERM, // + -
PREC_FACTOR, // * / %
PREC_UNARY, // - ! ~ not
PREC_EXPONENT, // **
PREC_CALL, // ()
PREC_SUBSCRIPT, // []
PREC_ATTRIB, // .index
PREC_PRIMARY,
} Precedence;
typedef void (*GrammarFn)(Compiler* compiler);
typedef struct {
GrammarFn prefix;
GrammarFn infix;
Precedence precedence;
} GrammarRule;
typedef enum {
DEPTH_GLOBAL = -1, //< Global variables.
DEPTH_LOCAL, //< Local scope. Increase with inner scope.
} Depth;
typedef enum {
FUNC_MAIN, // The body function of the script.
FUNC_TOPLEVEL,
FUNC_LITERAL,
FUNC_METHOD,
FUNC_CONSTRUCTOR,
} FuncType;
typedef struct {
const char* name; //< Directly points into the source string.
uint32_t length; //< Length of the name.
int depth; //< The depth the local is defined in.
bool is_upvalue; //< Is this an upvalue for a nested function.
int line; //< The line variable declared for debugging.
} Local;
typedef struct sLoop {
// Index of the loop's start instruction where the execution will jump
// back to once it reach the loop end or continue used.
int start;
// Index of the jump out address instruction to patch it's value once done
// compiling the loop.
int exit_jump;
// Array of address indexes to patch break address.
int patches[MAX_BREAK_PATCH];
int patch_count;
// The outer loop of the current loop used to set and reset the compiler's
// current loop context.
struct sLoop* outer_loop;
// Depth of the loop, required to pop all the locals in that loop when it
// met a break/continue statement inside.
int depth;
} Loop;
// ForwardName is used for globals that are accessed before defined inside
// a local scope.
// TODO: Since function and class global variables are initialized at the
// compile time we can allow access to them at the global scope.
typedef struct sForwardName {
// Index of the short instruction that has the value of the global's name
// (in the names buffer of the module).
int instruction;
// The function where the name is used, and the instruction is belongs to.
Fn* func;
// Name token that was lexed for this name.
Token tkname;
} ForwardName;
// This struct is used to keep track about the information of the upvaues for
// the current function to generate opcodes to capture them.
typedef struct sUpvalueInfo {
// If it's true the extrenal local belongs to the immediate enclosing
// function and the bellow [index] refering at the locals of that function.
// If it's false the external local of the upvalue doesn't belongs to the
// immediate enclosing function and the [index] will refering to the upvalues
// array of the enclosing function.
bool is_immediate;
// Index of the upvalue's external local variable, in the local or upvalues
// array of the enclosing function.
int index;
} UpvalueInfo;
typedef struct sFunc {
// Type of the current function.
FuncType type;
// Scope of the function. -2 for module body function, -1 for top level
// function and literal functions will have the scope where it declared.
int depth;
Local locals[MAX_VARIABLES]; //< Variables in the current context.
int local_count; //< Number of locals in [locals].
UpvalueInfo upvalues[MAX_UPVALUES]; //< Upvalues in the current context.
int stack_size; //< Current size including locals ind temps.
// The actual function pointer which is being compiled.
Function* ptr;
// If outer function of this function, for top level function the outer
// function will be the module's body function.
struct sFunc* outer_func;
} Func;
// A convenient macro to get the current function.
#define _FN (compiler->func->ptr->fn)
// The context of the parsing phase for the compiler.
typedef struct sParser {
// Parser need a reference of the PKVM to allocate strings (for string
// literals in the source) and to report error if there is any.
PKVM* vm;
// The [source] and the [file_path] are pointers to an allocated string.
// The parser doesn't keep references to that objects (to prevent them
// from garbage collected). It's the compiler's responsibility to keep the
// strings alive alive as long as the parser is alive.
const char* source; //< Currently compiled source.
const char* file_path; //< Path of the module (for reporting errors).
const char* token_start; //< Start of the currently parsed token.
const char* current_char; //< Current char position in the source.
int current_line; //< Line number of the current char.
Token previous, current, next; //< Currently parsed tokens.
// The current depth of the string interpolation. 0 means we're not inside
// an interpolated string.
int si_depth;
// If we're parsing an interpolated string and found a TK_RBRACE (ie. '}')
// we need to know if that's belongs to the expression we're parsing, or the
// end of the current interpolation.
//
// To achieve that We need to keep track of the number of open brace at the
// current depth. If we don't have any open brace then the TK_RBRACE token
// is consumed to end the interpolation.
//
// If we're inside an interpolated string (ie. si_depth > 0)
// si_open_brace[si_depth - 1] will return the number of open brace at the
// current depth.
int si_open_brace[MAX_STR_INTERP_DEPTH];
// Since we're supporting both quotes (single and double), we need to keep
// track of the qoute the interpolation is surrounded by to properly
// terminate the string.
// here si_quote[si_depth - 1] will return the surrunded quote of the
// expression at current depth.
char si_quote[MAX_STR_INTERP_DEPTH];
// When we're parsing a name interpolated string (ie. "Hello $name!") we
// have to keep track of where the name ends to start the interpolation
// from there. The below value [si_name_end] will be NULL if we're not
// parsing a name interpolated string, otherwise it'll points to the end of
// the name.
//
// Also we're using [si_name_quote] to store the quote of the string to
// properly terminate.
const char* si_name_end;
char si_name_quote;
// An array of implicitly forward declared names, which will be resolved once
// the module is completely compiled.
ForwardName forwards[MAX_FORWARD_NAMES];
int forwards_count;
// A syntax sugar to skip call parentheses. Like lua support for number of
// literals. We're doing it for literal functions for now. It'll be set to
// true before exprCall to indicate that the call paran should be skipped.
bool optional_call_paran;
bool repl_mode;
bool parsing_class;
bool need_more_lines; //< True if we need more lines in REPL mode.
// [has_errors] is for all kinds of errors, If it's set we don't terminate
// the compilation since we can cascade more errors by continuing. But
// [has_syntax_error] will set to true if we encounter one and this will
// terminatie the compilation.
bool has_syntax_error;
bool has_errors;
} Parser;
struct Compiler {
// The parser of the compiler which contains all the parsing context for the
// current compilation.
Parser parser;
// Each module will be compiled with it's own compiler and a module is
// imported, a new compiler is created for that module and it'll be added to
// the linked list of compilers at the begining. PKVM will use this compiler
// reference as a root object (objects which won't garbage collected) and
// the chain of compilers will be marked at the marking phase.
//
// Here is how the chain change when a new compiler (compiler_3) created.
//
// PKVM -> compiler_2 -> compiler_1 -> NULL
//
// PKVM -> compiler_3 -> compiler_2 -> compiler_1 -> NULL
//
Compiler* next_compiler;
const CompileOptions* options; //< To configure the compilation.
Module* module; //< Current module that's being compiled.
Loop* loop; //< Current loop the we're parsing.
Func* func; //< Current function we're parsing.
// Current depth the compiler in (-1 means top level) 0 means function
// level and > 0 is inner scope.
int scope_depth;
// True if the last statement is a new local variable assignment. Because
// the assignment is different than regular assignment and use this boolean
// to tell the compiler that dont pop it's assigned value because the value
// itself is the local.
bool new_local;
// Will be true when parsing an "l-value" which can be assigned to a value
// using the assignment operator ('='). ie. 'a = 42' here a is an "l-value"
// and the 42 is a "r-value" so the assignment is consumed and compiled.
// Consider '42 = a' where 42 is a "r-value" which cannot be assigned.
// Similarly 'a = 1 + b = 2' the expression '(1 + b)' is a "r value" and
// the assignment here is invalid, however 'a = 1 + (b = 2)' is valid because
// the 'b' is an "l-value" and can be assigned but the '(b = 2)' is a
// "r-value".
bool l_value;
// We can do a new assignment inside an expression however we shouldn't
// define a new one, since in pocketlang both assignment and definition
// are syntactically the same, we use [can_define] "context" to prevent
// such assignments.
bool can_define;
// This value will be true after parsing a call expression, for every other
// Expressions it'll be false. This is **ONLY** to be used when compiling a
// return statement to check if the last parsed expression is a call to
// perform a tail call optimization (anywhere else this below boolean is
// meaningless).
bool is_last_call;
// Since the compiler manually call some builtin functions we need to cache
// the index of the functions in order to prevent search for them each time.
int bifn_list_join;
};
typedef struct {
int params;
int stack;
} OpInfo;
static OpInfo opcode_info[] = {
#define OPCODE(name, params, stack) { params, stack },
#include "opcodes.h" //<< AMALG_INLINE >>
#undef OPCODE
};
/*****************************************************************************/
/* INITALIZATION FUNCTIONS */
/*****************************************************************************/
// FIXME:
// This forward declaration can be removed once the interpolated string's
// "list_join" function replaced with BUILD_STRING opcode. (The declaration
// needed at compiler initialization function to find the "list_join" function.
static int findBuiltinFunction(const PKVM* vm,
const char* name, uint32_t length);
// This should be called once the compiler initialized (to access it's fields).
static void parserInit(Parser* parser, PKVM* vm, Compiler* compiler,
const char* source, const char* path) {
parser->vm = vm;
parser->source = source;
parser->file_path = path;
parser->token_start = parser->source;
parser->current_char = parser->source;
parser->current_line = 1;
parser->previous.type = TK_ERROR;
parser->current.type = TK_ERROR;
parser->next.type = TK_ERROR;
parser->next.start = NULL;
parser->next.length = 0;
parser->next.line = 1;
parser->next.value = VAR_UNDEFINED;
parser->si_depth = 0;
parser->si_name_end = NULL;
parser->si_name_quote = '\0';
parser->forwards_count = 0;
parser->repl_mode = !!(compiler->options && compiler->options->repl_mode);
parser->optional_call_paran = false;
parser->parsing_class = false;
parser->has_errors = false;
parser->has_syntax_error = false;
parser->need_more_lines = false;
}
static void compilerInit(Compiler* compiler, PKVM* vm, const char* source,
Module* module, const CompileOptions* options) {
memset(compiler, 0, sizeof(Compiler));
compiler->next_compiler = NULL;
compiler->module = module;
compiler->options = options;
compiler->scope_depth = DEPTH_GLOBAL;
compiler->loop = NULL;
compiler->func = NULL;
compiler->can_define = true;
compiler->new_local = false;
compiler->is_last_call = false;
const char* source_path = "@??";
if (module->path != NULL) {
source_path = module->path->data;
} else if (options && options->repl_mode) {
source_path = "@REPL";
}
parserInit(&compiler->parser, vm, compiler, source, source_path);
// Cache the required built functions.
compiler->bifn_list_join = findBuiltinFunction(vm, "list_join", 9);
ASSERT(compiler->bifn_list_join >= 0, OOPS);
}
/*****************************************************************************/
/* ERROR HANDLERS */
/*****************************************************************************/
// Internal error report function for lexing and parsing.
static void reportError(Parser* parser, Token tk,
const char* fmt, va_list args) {
parser->has_errors = true;
PKVM* vm = parser->vm;
if (vm->config.stderr_write == NULL) return;
// If the source is incomplete we're not printing an error message,
// instead return PK_RESULT_UNEXPECTED_EOF to the host.
if (parser->need_more_lines) {
ASSERT(parser->repl_mode, OOPS);
return;
}
reportCompileTimeError(vm, parser->file_path, tk.line, parser->source,
tk.start, tk.length, fmt, args);
}
// Error caused when parsing. The associated token assumed to be last consumed
// which is [parser->previous].
static void syntaxError(Compiler* compiler, Token tk, const char* fmt, ...) {
Parser* parser = &compiler->parser;
// Only one syntax error is reported.
if (parser->has_syntax_error) return;
parser->has_syntax_error = true;
va_list args;
va_start(args, fmt);
reportError(parser, tk, fmt, args);
va_end(args);
}
static void semanticError(Compiler* compiler, Token tk, const char* fmt, ...) {
Parser* parser = &compiler->parser;
// If the parser has synax errors, semantic errors are not reported.
if (parser->has_syntax_error) return;
va_list args;
va_start(args, fmt);
reportError(parser, tk, fmt, args);
va_end(args);
}
// Error caused when trying to resolve forward names (maybe more in the
// future), Which will be called once after compiling the module and thus we
// need to pass the line number the error originated from.
static void resolveError(Compiler* compiler, Token tk, const char* fmt, ...) {
Parser* parser = &compiler->parser;
va_list args;
va_start(args, fmt);
reportError(parser, tk, fmt, args);
va_end(args);
}
// Check if the given [index] is greater than or equal to the maximum constants
// that a module can contain and report an error.
static void checkMaxConstantsReached(Compiler* compiler, int index) {
ASSERT(index >= 0, OOPS);
if (index >= MAX_CONSTANTS) {
semanticError(compiler, compiler->parser.previous,
"A module should contain at most %d unique constants.", MAX_CONSTANTS);
}
}
/*****************************************************************************/
/* LEXING */
/*****************************************************************************/
// Forward declaration of lexer methods.
static Token makeErrToken(Parser* parser);
static char peekChar(Parser* parser);
static char peekNextChar(Parser* parser);
static char eatChar(Parser* parser);
static void setNextValueToken(Parser* parser, _TokenType type, Var value);
static void setNextToken(Parser* parser, _TokenType type);
static bool matchChar(Parser* parser, char c);
static void eatString(Compiler* compiler, bool single_quote, bool is_raw) {
Parser* parser = &compiler->parser;
pkByteBuffer buff;
pkByteBufferInit(&buff);
char quote = (single_quote) ? '\'' : '"';
// For interpolated string it'll be TK_STRING_INTERP.
_TokenType tk_type = TK_STRING;
while (true) {
char c = eatChar(parser);
if (c == quote) break;
if (c == '\0') {
syntaxError(compiler, makeErrToken(parser), "Non terminated string.");
return;
// Null byte is required by TK_EOF.
parser->current_char--;
break;
}
if (c == '$' && !is_raw) {
if (parser->si_depth < MAX_STR_INTERP_DEPTH) {
tk_type = TK_STRING_INTERP;
char c2 = peekChar(parser);
if (c2 == '{') { // Expression interpolation (ie. "${expr}").
eatChar(parser);
parser->si_depth++;
parser->si_quote[parser->si_depth - 1] = quote;
parser->si_open_brace[parser->si_depth - 1] = 0;
} else { // Name Interpolation.
if (!utilIsName(c2)) {
syntaxError(compiler, makeErrToken(parser),
"Expected '{' or identifier after '$'.");
return;
} else { // Name interpolation (ie. "Hello $name!").
// The pointer [ptr] will points to the character at where the
// interpolated string ends. (ie. the next character after name
// ends).
const char* ptr = parser->current_char;
while (utilIsName(*(ptr)) || utilIsDigit(*(ptr))) {
ptr++;
}
parser->si_name_end = ptr;
parser->si_name_quote = quote;
}
}
} else {
semanticError(compiler, makeErrToken(parser),
"Maximum interpolation level reached (can only "
"interpolate upto depth %d).", MAX_STR_INTERP_DEPTH);
}
break;
}
if (c == '\\' && !is_raw) {
switch (eatChar(parser)) {
case '"': pkByteBufferWrite(&buff, parser->vm, '"'); break;
case '\'': pkByteBufferWrite(&buff, parser->vm, '\''); break;
case '\\': pkByteBufferWrite(&buff, parser->vm, '\\'); break;
case 'n': pkByteBufferWrite(&buff, parser->vm, '\n'); break;
case 'r': pkByteBufferWrite(&buff, parser->vm, '\r'); break;
case 't': pkByteBufferWrite(&buff, parser->vm, '\t'); break;
case '\n': break; // Just ignore the next line.
// '$' In pocketlang string is used for interpolation.
case '$': pkByteBufferWrite(&buff, parser->vm, '$'); break;
// Hex literal in string should match `\x[0-9a-zA-Z][0-9a-zA-Z]`
case 'x': {
uint8_t val = 0;
c = eatChar(parser);
if (!utilIsCharHex(c)) {
semanticError(compiler, makeErrToken(parser),
"Invalid hex escape.");
break;
}
val = utilCharHexVal(c);
c = eatChar(parser);
if (!utilIsCharHex(c)) {
semanticError(compiler, makeErrToken(parser),
"Invalid hex escape.");
break;
}
val = (val << 4) | utilCharHexVal(c);
pkByteBufferWrite(&buff, parser->vm, val);
} break;
case '\r':
if (matchChar(parser, '\n')) break;
// Else fallthrough.
default:
semanticError(compiler, makeErrToken(parser),
"Invalid escape character.");
break;
}
} else {
pkByteBufferWrite(&buff, parser->vm, c);
}
}
// '\0' will be added by varNewSring();
Var string = VAR_OBJ(newStringLength(parser->vm, (const char*)buff.data,
(uint32_t)buff.count));
pkByteBufferClear(&buff, parser->vm);
setNextValueToken(parser, tk_type, string);
}
// Returns the current char of the compiler on.
static char peekChar(Parser* parser) {
return *parser->current_char;
}
// Returns the next char of the compiler on.
static char peekNextChar(Parser* parser) {
if (peekChar(parser) == '\0') return '\0';
return *(parser->current_char + 1);
}
// Advance the compiler by 1 char.
static char eatChar(Parser* parser) {
char c = peekChar(parser);
parser->current_char++;
if (c == '\n') parser->current_line++;
return c;
}
// Complete lexing an identifier name.
static void eatName(Parser* parser) {
char c = peekChar(parser);
while (utilIsName(c) || utilIsDigit(c)) {
eatChar(parser);
c = peekChar(parser);
}
const char* name_start = parser->token_start;
_TokenType type = TK_NAME;
int length = (int)(parser->current_char - name_start);
for (int i = 0; _keywords[i].identifier != NULL; i++) {
if (_keywords[i].length == length &&
strncmp(name_start, _keywords[i].identifier, length) == 0) {
type = _keywords[i].tk_type;
break;
}
}
setNextToken(parser, type);
}
// Complete lexing a number literal.
static void eatNumber(Compiler* compiler) {
Parser* parser = &compiler->parser;
#define IS_BIN_CHAR(c) (((c) == '0') || ((c) == '1'))
Var value = VAR_NULL; // The number value.
char c = *parser->token_start;
// Binary literal.
if (c == '0' && ((peekChar(parser) == 'b') || (peekChar(parser) == 'B'))) {
eatChar(parser); // Consume '0b'
uint64_t bin = 0;
c = peekChar(parser);
if (!IS_BIN_CHAR(c)) {
syntaxError(compiler, makeErrToken(parser), "Invalid binary literal.");
return;
} else {
do {
// Consume the next digit.
c = peekChar(parser);
if (!IS_BIN_CHAR(c)) break;
eatChar(parser);
// Check the length of the binary literal.
int length = (int)(parser->current_char - parser->token_start);
if (length > STR_BIN_BUFF_SIZE - 2) { // -2: '-\0' 0b is in both side.
semanticError(compiler, makeErrToken(parser),
"Binary literal is too long.");
break;
}
// "Append" the next digit at the end.
bin = (bin << 1) | (c - '0');
} while (true);
}
value = VAR_NUM((double)bin);
} else if (c == '0' &&
((peekChar(parser) == 'x') || (peekChar(parser) == 'X'))) {
eatChar(parser); // Consume '0x'
uint64_t hex = 0;
c = peekChar(parser);
// The first digit should be hex digit.
if (!utilIsCharHex(c)) {
syntaxError(compiler, makeErrToken(parser), "Invalid hex literal.");
return;
} else {
do {
// Consume the next digit.
c = peekChar(parser);
if (!utilIsCharHex(c)) break;
eatChar(parser);
// Check the length of the binary literal.
int length = (int)(parser->current_char - parser->token_start);
if (length > STR_HEX_BUFF_SIZE - 2) { // -2: '-\0' 0x is in both side.
semanticError(compiler, makeErrToken(parser),
"Hex literal is too long.");
break;
}
// "Append" the next digit at the end.
hex = (hex << 4) | utilCharHexVal(c);
} while (true);
value = VAR_NUM((double)hex);
}
} else { // Regular number literal.
while (utilIsDigit(peekChar(parser))) {
eatChar(parser);
}
if (c != '.') { // Number starts with a decimal point.
if (peekChar(parser) == '.' && utilIsDigit(peekNextChar(parser))) {
matchChar(parser, '.');
while (utilIsDigit(peekChar(parser))) {
eatChar(parser);
}
}
}
// Parse if in scientific notation format (MeN == M * 10 ** N).
if (matchChar(parser, 'e') || matchChar(parser, 'E')) {
if (peekChar(parser) == '+' || peekChar(parser) == '-') {
eatChar(parser);
}
if (!utilIsDigit(peekChar(parser))) {
syntaxError(compiler, makeErrToken(parser), "Invalid number literal.");
return;
} else { // Eat the exponent.
while (utilIsDigit(peekChar(parser))) eatChar(parser);
}
}
errno = 0;
value = VAR_NUM(atof(parser->token_start));
if (errno == ERANGE) {
const char* start = parser->token_start;
int len = (int)(parser->current_char - start);
semanticError(compiler, makeErrToken(parser),
"Number literal is too large (%.*s).", len, start);
value = VAR_NUM(0);
}
}
setNextValueToken(parser, TK_NUMBER, value);
#undef IS_BIN_CHAR
}
// Read and ignore chars till it reach new line or EOF.
static void skipLineComment(Parser* parser) {
char c;
while ((c = peekChar(parser)) != '\0') {
// Don't eat new line it's not part of the comment.
if (c == '\n') return;
eatChar(parser);
}
}
// If the current char is [c] consume it and advance char by 1 and returns
// true otherwise returns false.
static bool matchChar(Parser* parser, char c) {
if (peekChar(parser) != c) return false;
eatChar(parser);
return true;
}
// If the current char is [c] eat the char and add token two otherwise eat
// append token one.
static void setNextTwoCharToken(Parser* parser, char c, _TokenType one,
_TokenType two) {
if (matchChar(parser, c)) {
setNextToken(parser, two);
} else {
setNextToken(parser, one);
}
}