-
Notifications
You must be signed in to change notification settings - Fork 35
/
lexer.c
2332 lines (2036 loc) · 88.9 KB
/
lexer.c
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
/* ------------------------------------------------------------------------- */
/* "lexer" : Lexical analyser */
/* */
/* Part of Inform 6.43 */
/* copyright (c) Graham Nelson 1993 - 2024 */
/* */
/* ------------------------------------------------------------------------- */
#include "header.h"
int total_source_line_count, /* Number of source lines so far */
no_hash_printed_yet, /* Have not yet printed the first # */
hash_printed_since_newline, /* A hash has been printed since the
most recent new-line was printed
(generally as a result of an error
message or the start of pass) */
dont_enter_into_symbol_table, /* Return names as text (with
token type UQ_TT) and not as
entries in the symbol table,
when TRUE. If -2, only the
keyword table is searched. */
return_sp_as_variable; /* When TRUE, the word "sp" denotes
the stack pointer variable
(used in assembly language only) */
int next_token_begins_syntax_line; /* When TRUE, start a new syntax
line (for error reporting, etc.)
on the source code line where
the next token appears */
int32 last_mapped_line; /* Last syntax line reported to debugging file */
/* ------------------------------------------------------------------------- */
/* The lexer's output is a sequence of structs, each called a "token", */
/* representing one lexical unit (or "lexeme") each. Instead of providing */
/* "lookahead" (that is, always having available the next token after the */
/* current one, so that syntax analysers higher up in Inform can have */
/* advance knowledge of what is coming), the lexer instead has a system */
/* where tokens can be read in and then "put back again". */
/* The meaning of the number (and to some extent the text) supplied with */
/* a token depends on its type: see "header.h" for the list of types. */
/* For example, the lexeme "$1e3" is understood by Inform as a hexadecimal */
/* number, and translated to the token: */
/* type NUMBER_TT, value 483, text "$1e3" */
/* ------------------------------------------------------------------------- */
/* These three variables are set to the current token on a call to */
/* get_next_token() (but are not changed by a call to put_token_back()). */
/* (It would be tidier to use a token_data structure, rather than having */
/* get_next_token() unpack three values. But this is the way it is.) */
/* ------------------------------------------------------------------------- */
int token_type;
int32 token_value;
char *token_text;
/* ------------------------------------------------------------------------- */
/* The next two variables are the head and tail of a singly linked list. */
/* The tail stores the portion most recently read from the current */
/* lexical block; its end values therefore describe the location of the */
/* current token, and are updated whenever the three variables above are */
/* via set_token_location(...). Earlier vertices, if any, represent the */
/* regions of lexical blocks read beforehand, where new vertices are */
/* only introduced by interruptions like a file inclusion or an EOF. */
/* Vertices are deleted off of the front of the list once they are no */
/* longer referenced by pending debug information records. */
/* ------------------------------------------------------------------------- */
static debug_locations *first_token_locations;
static debug_locations *last_token_location;
extern debug_location get_token_location(void)
{ debug_location result;
debug_location *location = &(last_token_location->location);
result.file_index = location->file_index;
result.beginning_byte_index = location->end_byte_index;
result.end_byte_index = location->end_byte_index;
result.beginning_line_number = location->end_line_number;
result.end_line_number = location->end_line_number;
result.beginning_character_number = location->end_character_number;
result.end_character_number = location->end_character_number;
result.orig_file_index = location->orig_file_index;
result.orig_beg_line_number = location->orig_beg_line_number;
result.orig_beg_char_number = location->orig_beg_char_number;
return result;
}
extern debug_locations get_token_locations(void)
{ debug_locations result;
result.location = get_token_location();
result.next = NULL;
result.reference_count = 0;
return result;
}
static void set_token_location(debug_location location)
{ if (location.file_index == last_token_location->location.file_index)
{ last_token_location->location.end_byte_index =
location.end_byte_index;
last_token_location->location.end_line_number =
location.end_line_number;
last_token_location->location.end_character_number =
location.end_character_number;
last_token_location->location.orig_file_index =
location.orig_file_index;
last_token_location->location.orig_beg_line_number =
location.orig_beg_line_number;
last_token_location->location.orig_beg_char_number =
location.orig_beg_char_number;
} else
{ debug_locations*successor =
my_malloc
(sizeof(debug_locations),
"debug locations of recent tokens");
successor->location = location;
successor->next = NULL;
successor->reference_count = 0;
last_token_location->next = successor;
last_token_location = successor;
}
}
extern debug_location_beginning get_token_location_beginning(void)
{ debug_location_beginning result;
++(last_token_location->reference_count);
result.head = last_token_location;
result.beginning_byte_index =
last_token_location->location.end_byte_index;
result.beginning_line_number =
last_token_location->location.end_line_number;
result.beginning_character_number =
last_token_location->location.end_character_number;
result.orig_file_index = last_token_location->location.orig_file_index;
result.orig_beg_line_number = last_token_location->location.orig_beg_line_number;
result.orig_beg_char_number = last_token_location->location.orig_beg_char_number;
return result;
}
static void cleanup_token_locations(debug_location_beginning*beginning)
{ if (first_token_locations)
{ while (first_token_locations &&
!first_token_locations->reference_count)
{ debug_locations*moribund = first_token_locations;
first_token_locations = moribund->next;
my_free(&moribund, "debug locations of recent tokens");
if (beginning &&
(beginning->head == moribund || !first_token_locations))
{ compiler_error
("Records needed by a debug_location_beginning are no "
"longer allocated, perhaps because of an invalid reuse "
"of this or an earlier beginning");
}
}
} else
{ if (beginning)
{ compiler_error
("Attempt to use a debug_location_beginning when no token "
"locations are defined");
} else
{ compiler_error
("Attempt to clean up token locations when no token locations "
"are defined");
}
}
}
extern void discard_token_location(debug_location_beginning beginning)
{ --(beginning.head->reference_count);
}
extern debug_locations get_token_location_end
(debug_location_beginning beginning)
{ debug_locations result;
cleanup_token_locations(&beginning);
--(beginning.head->reference_count);
/* Sometimes we know what we'll read before we switch to the lexical block
where we'll read it. In such cases the beginning will be placed in the
prior block and last exactly zero bytes there. It's misleading to
include such ranges, so we gobble them. */
if (beginning.head->location.end_byte_index ==
beginning.beginning_byte_index &&
beginning.head->next)
{ beginning.head = beginning.head->next;
result.location = beginning.head->location;
result.location.beginning_byte_index = 0;
result.location.beginning_line_number = 1;
result.location.beginning_character_number = 1;
} else
{ result.location = beginning.head->location;
result.location.beginning_byte_index =
beginning.beginning_byte_index;
result.location.beginning_line_number =
beginning.beginning_line_number;
result.location.beginning_character_number =
beginning.beginning_character_number;
}
result.location.orig_file_index =
beginning.orig_file_index;
result.location.orig_beg_line_number =
beginning.orig_beg_line_number;
result.location.orig_beg_char_number =
beginning.orig_beg_char_number;
result.next = beginning.head->next;
result.reference_count = 0;
return result;
}
/* ------------------------------------------------------------------------- */
/* In order to be able to put tokens back efficiently, the lexer stores */
/* tokens in a "circle": the variable circle_position ranges between */
/* 0 and CIRCLE_SIZE-1. We only need a circle size as large as the */
/* maximum number of tokens ever put back at once, plus 1 (in effect, the */
/* maximum token lookahead ever needed in syntax analysis, plus 1). */
/* */
/* Note that the circle struct type is lexeme_data, whereas the expression */
/* code all works in token_data. They have slightly different needs. The */
/* data is exported through the token_text, token_value, token_type */
/* globals, so there's no need to use the same struct at both levels. */
/* */
/* Unlike some compilers, Inform does not have a context-free lexer: in */
/* fact it has 12288 different possible states. However, the context only */
/* affects the interpretation of "identifiers": lexemes beginning with a */
/* letter and containing up to 32 chars of alphanumeric and underscore */
/* chars. (For example, "default" may refer to the directive or statement */
/* of that name, and which token values are returned depends on the */
/* current lexical context.) */
/* */
/* Along with each token, we also store the lexical context it was */
/* translated under; because if it is called for again, there may need */
/* to be a fresh interpretation of it if the context has changed. */
/* ------------------------------------------------------------------------- */
#define CIRCLE_SIZE 6
/* (The worst case for token lookahead is distinguishing between an
old-style "objectloop (a in b)" and a new "objectloop (a in b ...)".) */
static int circle_position;
static lexeme_data circle[CIRCLE_SIZE];
/* ------------------------------------------------------------------------- */
/* A complication, however, is that the text of some lexemes needs to be */
/* held in Inform's memory for much longer periods: for example, a */
/* dictionary word lexeme (like "'south'") must have its text preserved */
/* until the code generation time for the expression it occurs in, when */
/* the dictionary reference is actually made. We handle this by keeping */
/* all lexeme text until the end of the statement (or, for top-level */
/* directives, until the end of the directive). Then we call */
/* release_token_texts() to start over. The lextexts array will therefore */
/* grow to the largest number of lexemes in a single statement or */
/* directive. */
/* ------------------------------------------------------------------------- */
typedef struct lextext_s {
char *text;
size_t size; /* Allocated size (including terminal null) */
} lextext;
static lextext *lextexts; /* Allocated to no_lextexts */
static memory_list lextexts_memlist;
static int no_lextexts;
static int cur_lextexts; /* Number of lextexts in current use
(cur_lextexts <= no_lextexts) */
static int lex_index; /* Index of lextext being written to */
static int lex_pos; /* Current write position in that lextext */
/* ------------------------------------------------------------------------- */
/* The lexer itself needs up to 3 characters of lookahead (it uses an */
/* LR(3) grammar to translate characters into tokens). */
/* */
/* Past the end of the stream, we fill in zeros. This has the awkward */
/* side effect that a zero byte in a source file will silently terminate */
/* it, rather than producing an "illegal source character" error. */
/* On the up side, we can compile veneer routines (which are null- */
/* terminated strings) with no extra work. */
/* ------------------------------------------------------------------------- */
#define LOOKAHEAD_SIZE 3
static int current, lookahead, /* The latest character read, and */
lookahead2, lookahead3; /* the three characters following it */
/* (zero means end-of-stream) */
static int pipeline_made; /* Whether or not the pipeline of
characters has been constructed
yet (this pass) */
static int (* get_next_char)(void); /* Routine for reading the stream of
characters: the lexer does not
need any "ungetc" routine for
putting them back again. End of
stream is signalled by returning
zero. */
static char *source_to_analyse; /* The current lexical source:
NULL for "load from source files",
otherwise this points to a string
containing Inform code */
static int tokens_put_back; /* Count of the number of backward
moves made from the last-read
token */
/* This gets called for both token_data and lexeme_data structs. It prints
a description of the common part (the text, value, type fields).
*/
extern void describe_token_triple(const char *text, int32 value, int type)
{
/* Many of the token types are not set in this file, but later on in
Inform's higher stages (for example, in the expression evaluator);
but this routine describes them all. */
printf("{ ");
switch(type)
{
/* The following token types occur in lexer output: */
case SYMBOL_TT: printf("symbol ");
describe_symbol(value);
break;
case NUMBER_TT: printf("literal number %d", value);
break;
case DQ_TT: printf("string \"%s\"", text);
break;
case SQ_TT: printf("string '%s'", text);
break;
case UQ_TT: printf("barestring %s", text);
break;
case SEP_TT: printf("separator '%s'", text);
break;
case EOF_TT: printf("end of file");
break;
case STATEMENT_TT: printf("statement name '%s'", text);
break;
case SEGMENT_MARKER_TT: printf("object segment marker '%s'", text);
break;
case DIRECTIVE_TT: printf("directive name '%s'", text);
break;
case CND_TT: printf("textual conditional '%s'", text);
break;
case OPCODE_NAME_TT: printf("opcode name '%s'", text);
break;
case SYSFUN_TT: printf("built-in function name '%s'", text);
break;
case LOCAL_VARIABLE_TT: printf("local variable name '%s'", text);
break;
case MISC_KEYWORD_TT: printf("statement keyword '%s'", text);
break;
case DIR_KEYWORD_TT: printf("directive keyword '%s'", text);
break;
case TRACE_KEYWORD_TT: printf("'trace' keyword '%s'", text);
break;
case SYSTEM_CONSTANT_TT: printf("system constant name '%s'", text);
break;
/* The remaining are etoken types, not set by the lexer */
case OP_TT: printf("operator '%s'",
operators[value].description);
break;
case ENDEXP_TT: printf("end of expression");
break;
case SUBOPEN_TT: printf("open bracket");
break;
case SUBCLOSE_TT: printf("close bracket");
break;
case LARGE_NUMBER_TT: printf("large number: '%s'=%d",text,value);
break;
case SMALL_NUMBER_TT: printf("small number: '%s'=%d",text,value);
break;
case VARIABLE_TT: printf("variable '%s'=%d", text, value);
break;
case DICTWORD_TT: printf("dictionary word '%s'", text);
break;
case ACTION_TT: printf("action name '%s'", text);
break;
default:
printf("** unknown token type %d, text='%s', value=%d **",
type, text, value);
}
printf(" }");
}
/* ------------------------------------------------------------------------- */
/* All but one of the Inform keywords (most of them opcode names used */
/* only by the assembler). (The one left over is "sp", a keyword used in */
/* assembly language only.) */
/* */
/* A "keyword group" is a set of keywords to be searched for. If a match */
/* is made on an identifier, the token type becomes that given in the KG */
/* and the token value is its index in the KG. */
/* */
/* The keyword ordering must correspond with the appropriate #define's in */
/* "header.h" but is otherwise not significant. */
/* ------------------------------------------------------------------------- */
/* This must exceed the total number of keywords across all groups,
including opcodes. */
#define MAX_KEYWORDS (500)
/* The values will be filled in at compile time, when we know
which opcode set to use. */
keyword_group opcode_names =
{ { "" },
OPCODE_NAME_TT, FALSE, TRUE
};
static char *opcode_list_z[] = {
"je", "jl", "jg", "dec_chk", "inc_chk", "jin", "test", "or", "and",
"test_attr", "set_attr", "clear_attr", "store", "insert_obj", "loadw",
"loadb", "get_prop", "get_prop_addr", "get_next_prop", "add", "sub",
"mul", "div", "mod", "call", "storew", "storeb", "put_prop", "sread",
"print_char", "print_num", "random", "push", "pull", "split_window",
"set_window", "output_stream", "input_stream", "sound_effect", "jz",
"get_sibling", "get_child", "get_parent", "get_prop_len", "inc", "dec",
"print_addr", "remove_obj", "print_obj", "ret", "jump", "print_paddr",
"load", "not", "rtrue", "rfalse", "print", "print_ret", "nop", "save",
"restore", "restart", "ret_popped", "pop", "quit", "new_line",
"show_status", "verify", "call_2s", "call_vs", "aread", "call_vs2",
"erase_window", "erase_line", "set_cursor", "get_cursor",
"set_text_style", "buffer_mode", "read_char", "scan_table", "call_1s",
"call_2n", "set_colour", "throw", "call_vn", "call_vn2", "tokenise",
"encode_text", "copy_table", "print_table", "check_arg_count", "call_1n",
"catch", "piracy", "log_shift", "art_shift", "set_font", "save_undo",
"restore_undo", "draw_picture", "picture_data", "erase_picture",
"set_margins", "move_window", "window_size", "window_style",
"get_wind_prop", "scroll_window", "pop_stack", "read_mouse",
"mouse_window", "push_stack", "put_wind_prop", "print_form",
"make_menu", "picture_table", "print_unicode", "check_unicode",
"set_true_colour", "buffer_screen",
""
};
static char *opcode_list_g[] = {
"nop", "add", "sub", "mul", "div", "mod", "neg", "bitand", "bitor",
"bitxor", "bitnot", "shiftl", "sshiftr", "ushiftr", "jump", "jz",
"jnz", "jeq", "jne", "jlt", "jge", "jgt", "jle",
"jltu", "jgeu", "jgtu", "jleu",
"call", "return",
"catch", "throw", "tailcall",
"copy", "copys", "copyb", "sexs", "sexb", "aload",
"aloads", "aloadb", "aloadbit", "astore", "astores", "astoreb",
"astorebit", "stkcount", "stkpeek", "stkswap", "stkroll", "stkcopy",
"streamchar", "streamnum", "streamstr",
"gestalt", "debugtrap", "getmemsize", "setmemsize", "jumpabs",
"random", "setrandom", "quit", "verify",
"restart", "save", "restore", "saveundo", "restoreundo", "protect",
"glk", "getstringtbl", "setstringtbl", "getiosys", "setiosys",
"linearsearch", "binarysearch", "linkedsearch",
"callf", "callfi", "callfii", "callfiii",
"streamunichar",
"mzero", "mcopy", "malloc", "mfree",
"accelfunc", "accelparam",
"hasundo", "discardundo",
"numtof", "ftonumz", "ftonumn", "ceil", "floor",
"fadd", "fsub", "fmul", "fdiv", "fmod",
"sqrt", "exp", "log", "pow",
"sin", "cos", "tan", "asin", "acos", "atan", "atan2",
"jfeq", "jfne", "jflt", "jfle", "jfgt", "jfge", "jisnan", "jisinf",
"numtod", "dtonumz", "dtonumn", "ftod", "dtof", "dceil", "dfloor",
"dadd", "dsub", "dmul", "ddiv", "dmodr", "dmodq",
"dsqrt", "dexp", "dlog", "dpow",
"dsin", "dcos", "dtan", "dasin", "dacos", "datan", "datan2",
"jdeq", "jdne", "jdlt", "jdle", "jdgt", "jdge", "jdisnan", "jdisinf",
""
};
keyword_group opcode_macros =
{ { "" },
OPCODE_MACRO_TT, FALSE, TRUE
};
static char *opmacro_list_z[] = { "" };
static char *opmacro_list_g[] = {
"pull", "push", "dload", "dstore",
""
};
keyword_group directives =
{ { "abbreviate", "array", "attribute", "class", "constant",
"default", "dictionary", "end", "endif", "extend", "fake_action",
"global", "ifdef", "ifndef", "ifnot", "ifv3", "ifv5", "iftrue",
"iffalse", "import", "include", "link", "lowstring", "message",
"nearby", "object", "origsource", "property", "release", "replace",
"serial", "switches", "statusline", "stub", "system_file", "trace",
"undef", "verb", "version", "zcharacter",
"" },
DIRECTIVE_TT, FALSE, FALSE
};
keyword_group trace_keywords =
{ { "dictionary", "symbols", "objects", "verbs",
"assembly", "expressions", "lines", "tokens", "linker",
"on", "off", "" },
TRACE_KEYWORD_TT, FALSE, TRUE
};
keyword_group segment_markers =
{ { "class", "has", "private", "with", "" },
SEGMENT_MARKER_TT, FALSE, TRUE
};
keyword_group directive_keywords =
{ { "alias", "long", "additive",
"score", "time",
"noun", "held", "multi", "multiheld", "multiexcept",
"multiinside", "creature", "special", "number", "scope", "topic",
"reverse", "meta", "only", "replace", "first", "last",
"string", "table", "buffer", "data", "initial", "initstr",
"with", "private", "has", "class",
"error", "fatalerror", "warning",
"terminating", "static", "individual",
"" },
DIR_KEYWORD_TT, FALSE, TRUE
};
keyword_group misc_keywords =
{ { "char", "name", "the", "a", "an", "The", "number",
"roman", "reverse", "bold", "underline", "fixed", "on", "off",
"to", "address", "string", "object", "near", "from", "property", "A", "" },
MISC_KEYWORD_TT, FALSE, TRUE
};
keyword_group statements =
{ { "box", "break", "continue", "default", "do", "else", "font", "for",
"give", "if", "inversion", "jump", "move", "new_line", "objectloop",
"print", "print_ret", "quit", "read", "remove", "restore", "return",
"rfalse", "rtrue", "save", "spaces", "string", "style", "switch",
"until", "while", "" },
STATEMENT_TT, FALSE, TRUE
};
keyword_group conditions =
{ { "has", "hasnt", "in", "notin", "ofclass", "or", "provides", "" },
CND_TT, FALSE, TRUE
};
keyword_group system_functions =
{ { "child", "children", "elder", "eldest", "indirect", "parent", "random",
"sibling", "younger", "youngest", "metaclass", "glk", "" },
SYSFUN_TT, FALSE, TRUE
};
keyword_group system_constants =
{ { "adjectives_table", "actions_table", "classes_table",
"identifiers_table", "preactions_table", "version_number",
"largest_object", "strings_offset", "code_offset",
"dict_par1", "dict_par2", "dict_par3", "actual_largest_object",
"static_memory_offset", "array_names_offset", "readable_memory_offset",
"cpv__start", "cpv__end", "ipv__start", "ipv__end",
"array__start", "array__end",
"lowest_attribute_number", "highest_attribute_number",
"attribute_names_array",
"lowest_property_number", "highest_property_number",
"property_names_array",
"lowest_action_number", "highest_action_number",
"action_names_array",
"lowest_fake_action_number", "highest_fake_action_number",
"fake_action_names_array",
"lowest_routine_number", "highest_routine_number", "routines_array",
"routine_names_array", "routine_flags_array",
"lowest_global_number", "highest_global_number", "globals_array",
"global_names_array", "global_flags_array",
"lowest_array_number", "highest_array_number", "arrays_array",
"array_names_array", "array_flags_array",
"lowest_constant_number", "highest_constant_number", "constants_array",
"constant_names_array",
"lowest_class_number", "highest_class_number", "class_objects_array",
"lowest_object_number", "highest_object_number",
"oddeven_packing",
"grammar_table", "dictionary_table", "dynam_string_table",
"highest_meta_action_number",
"" },
SYSTEM_CONSTANT_TT, FALSE, TRUE
};
keyword_group *keyword_groups[12]
= { NULL, &opcode_names, &directives, &trace_keywords, &segment_markers,
&directive_keywords, &misc_keywords, &statements, &conditions,
&system_functions, &system_constants, &opcode_macros};
/* These keywords are set to point to local_variable_names entries when
a routine header is parsed. See construct_local_variable_tables(). */
keyword_group local_variables =
{ { "" },
LOCAL_VARIABLE_TT, FALSE, FALSE
};
static int lexical_context(void)
{
/* The lexical context is a number representing all of the context
information in the lexical analyser: the same input text will
always translate to the same output tokens whenever the context
is the same.
(For many years, the "dont_enter_into_symbol_table" variable
was omitted from this number. But now we can include it.) */
int c = 0;
if (opcode_names.enabled) c |= 1;
if (directives.enabled) c |= 2;
if (trace_keywords.enabled) c |= 4;
if (segment_markers.enabled) c |= 8;
if (directive_keywords.enabled) c |= 16;
if (misc_keywords.enabled) c |= 32;
if (statements.enabled) c |= 64;
if (conditions.enabled) c |= 128;
if (system_functions.enabled) c |= 256;
if (system_constants.enabled) c |= 512;
if (local_variables.enabled) c |= 1024;
if (return_sp_as_variable) c |= 2048;
if (dont_enter_into_symbol_table) c |= 4096;
return(c);
}
static void print_context(int c)
{
if (c < 0) {
printf("??? ");
return;
}
if ((c & 1) != 0) printf("OPC ");
if ((c & 2) != 0) printf("DIR ");
if ((c & 4) != 0) printf("TK ");
if ((c & 8) != 0) printf("SEG ");
if ((c & 16) != 0) printf("DK ");
if ((c & 32) != 0) printf("MK ");
if ((c & 64) != 0) printf("STA ");
if ((c & 128) != 0) printf("CND ");
if ((c & 256) != 0) printf("SFUN ");
if ((c & 512) != 0) printf("SCON ");
if ((c & 1024) != 0) printf("LV ");
if ((c & 2048) != 0) printf("sp ");
if ((c & 4096) != 0) printf("dontent ");
}
static int *keywords_hash_table;
static int *keywords_hash_ends_table;
static int *keywords_data_table;
static int *local_variable_hash_table;
static int *local_variable_hash_codes;
/* Note that MAX_LOCAL_VARIABLES is the maximum number of local variables
for this VM, *including* "sp" (the stack pointer "local").
This used to be a memory setting. Now it is a constant: 16 for Z-code,
119 for Glulx.
*/
/* The number of local variables in the current routine. */
int no_locals;
/* Names of local variables in the current routine.
The values are positions in local_variable_names_memlist.
This is allocated to MAX_LOCAL_VARIABLES-1. (The stack pointer "local"
is not included in this array.)
(This could be a memlist, growing as needed up to MAX_LOCAL_VARIABLES-1.
But right now we just allocate the max.)
*/
int *local_variable_name_offsets;
static memory_list local_variable_names_memlist;
/* How much of local_variable_names_memlist is used by the no_local locals. */
static int local_variable_names_usage;
static char one_letter_locals[128];
static void make_keywords_tables(void)
{ int i, j, h, tp=0;
char **oplist, **maclist;
if (!glulx_mode) {
oplist = opcode_list_z;
maclist = opmacro_list_z;
}
else {
oplist = opcode_list_g;
maclist = opmacro_list_g;
}
for (j=0; *(oplist[j]); j++) {
if (j >= MAX_KEYWORD_GROUP_SIZE) {
/* Gotta increase MAX_KEYWORD_GROUP_SIZE */
compiler_error("opcode_list has overflowed opcode_names.keywords");
break;
}
opcode_names.keywords[j] = oplist[j];
}
opcode_names.keywords[j] = "";
for (j=0; *(maclist[j]); j++) {
if (j >= MAX_KEYWORD_GROUP_SIZE) {
/* Gotta increase MAX_KEYWORD_GROUP_SIZE */
compiler_error("opmacro_list has overflowed opcode_macros.keywords");
break;
}
opcode_macros.keywords[j] = maclist[j];
}
opcode_macros.keywords[j] = "";
for (i=0; i<HASH_TAB_SIZE; i++)
{ keywords_hash_table[i] = -1;
keywords_hash_ends_table[i] = -1;
}
for (i=1; i<=11; i++)
{ keyword_group *kg = keyword_groups[i];
for (j=0; *(kg->keywords[j]) != 0; j++)
{
if (tp >= MAX_KEYWORDS) {
/* Gotta increase MAX_KEYWORDS */
compiler_error("keywords_data_table has overflowed MAX_KEYWORDS");
break;
}
h = hash_code_from_string(kg->keywords[j]);
if (keywords_hash_table[h] == -1)
keywords_hash_table[h] = tp;
else
*(keywords_data_table + 3*(keywords_hash_ends_table[h]) + 2) = tp;
keywords_hash_ends_table[h] = tp;
*(keywords_data_table + 3*tp) = i;
*(keywords_data_table + 3*tp+1) = j;
*(keywords_data_table + 3*tp+2) = -1;
tp++;
}
}
}
extern void clear_local_variables(void)
{
no_locals = 0;
local_variable_names_usage = 0;
}
extern void add_local_variable(char *name)
{
int len;
if (no_locals >= MAX_LOCAL_VARIABLES-1) {
/* This should have been caught before we got here */
error("too many local variables");
return;
}
len = strlen(name)+1;
ensure_memory_list_available(&local_variable_names_memlist, local_variable_names_usage + len);
local_variable_name_offsets[no_locals++] = local_variable_names_usage;
strcpy((char *)local_variable_names_memlist.data+local_variable_names_usage, name);
local_variable_names_usage += len;
}
extern char *get_local_variable_name(int index)
{
if (index < 0 || index >= no_locals)
return "???"; /* shouldn't happen */
return (char *)local_variable_names_memlist.data + local_variable_name_offsets[index];
}
/* Look at the strings stored in local_variable_names (from 0 to no_locals).
Set local_variables.keywords to point to these, and also prepare the
hash tables.
This must be called after add_local_variable(), but before we start
compiling function code. */
extern void construct_local_variable_tables(void)
{ int i, h;
for (i=0; i<HASH_TAB_SIZE; i++) local_variable_hash_table[i] = -1;
for (i=0; i<128; i++) one_letter_locals[i] = MAX_LOCAL_VARIABLES;
for (i=0; i<no_locals; i++)
{
char *p = (char *)local_variable_names_memlist.data + local_variable_name_offsets[i];
local_variables.keywords[i] = p;
if (p[1] == 0)
{ one_letter_locals[(uchar)p[0]] = i;
if (isupper((uchar)p[0])) one_letter_locals[tolower((uchar)p[0])] = i;
if (islower((uchar)p[0])) one_letter_locals[toupper((uchar)p[0])] = i;
}
h = hash_code_from_string(p);
if (local_variable_hash_table[h] == -1)
local_variable_hash_table[h] = i;
local_variable_hash_codes[i] = h;
}
/* Clear the rest. */
for (;i<MAX_LOCAL_VARIABLES-1;i++) {
local_variables.keywords[i] = "";
local_variable_hash_codes[i] = 0;
}
}
static void interpret_identifier(char *p, int pos)
{ int index, hashcode;
/* An identifier is either a keyword or a "symbol", a name which the
lexical analyser leaves to higher levels of Inform to understand. */
circle[pos].newsymbol = FALSE;
hashcode = hash_code_from_string(p);
/* If dont_enter_into_symbol_table is true, we skip all keywords
(and variables) and just mark the name as an unquoted string.
Except that if dont_enter_into_symbol_table is -2, we recognize
directive keywords (only).
*/
if (dont_enter_into_symbol_table) {
if (dont_enter_into_symbol_table == -2) {
/* This is a simplified version of the keyword-checking loop
below. */
index = keywords_hash_table[hashcode];
while (index >= 0)
{ int *i = keywords_data_table + 3*index;
keyword_group *kg = keyword_groups[*i];
if (kg == &directives)
{ char *q = kg->keywords[*(i+1)];
if (((kg->case_sensitive) && (strcmp(p, q)==0))
|| ((!(kg->case_sensitive)) && (strcmpcis(p, q)==0)))
{ circle[pos].type = kg->change_token_type;
circle[pos].value = *(i+1);
return;
}
}
index = *(i+2);
}
}
circle[pos].type = UQ_TT;
circle[pos].value = 0;
return;
}
/* If this is assembly language, perhaps it is "sp"? */
if (return_sp_as_variable && (p[0]=='s') && (p[1]=='p') && (p[2]==0))
{ circle[pos].value = 0; circle[pos].type = LOCAL_VARIABLE_TT;
return;
}
/* Test for local variables first, quite quickly. */
if (local_variables.enabled)
{ if (p[1]==0)
{ index = one_letter_locals[(uchar)p[0]];
if (index<MAX_LOCAL_VARIABLES)
{ circle[pos].type = LOCAL_VARIABLE_TT;
circle[pos].value = index+1;
return;
}
}
index = local_variable_hash_table[hashcode];
if (index >= 0)
{ for (;index<no_locals;index++)
{ if (hashcode == local_variable_hash_codes[index])
{
char *locname = (char *)local_variable_names_memlist.data + local_variable_name_offsets[index];
if (strcmpcis(p, locname)==0)
{ circle[pos].type = LOCAL_VARIABLE_TT;
circle[pos].value = index+1;
return;
}
}
}
}
}
/* Now the bulk of the keywords. Note that the lexer doesn't recognise
the name of a system function which has been Replaced. */
index = keywords_hash_table[hashcode];
while (index >= 0)
{ int *i = keywords_data_table + 3*index;
keyword_group *kg = keyword_groups[*i];
if (kg->enabled)
{ char *q = kg->keywords[*(i+1)];
if (((kg->case_sensitive) && (strcmp(p, q)==0))
|| ((!(kg->case_sensitive)) && (strcmpcis(p, q)==0)))
{ if ((kg != &system_functions)
|| (system_function_usage[*(i+1)]!=2))
{ circle[pos].type = kg->change_token_type;
circle[pos].value = *(i+1);
return;
}
}
}
index = *(i+2);
}
/* Search for the name; create it if necessary. */
circle[pos].value = symbol_index(p, hashcode, &circle[pos].newsymbol);
circle[pos].type = SYMBOL_TT;
}
/* ------------------------------------------------------------------------- */
/* The tokeniser grid aids a rapid decision about the consequences of a */
/* character reached in the buffer. In effect it is an efficiently stored */
/* transition table using an algorithm similar to that of S. C. Johnson's */
/* "yacc" lexical analyser (see Aho, Sethi and Ullman, section 3.9). */
/* My thanks to Dilip Sequeira for suggesting this. */
/* */
/* tokeniser_grid[c] is (16*n + m) if c is the first character of */
/* separator numbers n, n+1, ..., n+m-1 */
/* or certain special values (QUOTE_CODE, etc) */
/* or 0 otherwise */
/* */
/* Since 1000/16 = 62, the code numbers below will need increasing if the */
/* number of separators supported exceeds 61. */
/* ------------------------------------------------------------------------- */
static int tokeniser_grid[256];
#define QUOTE_CODE 1000
#define DQUOTE_CODE 1001
#define NULL_CODE 1002
#define SPACE_CODE 1003
#define NEGATIVE_CODE 1004
#define DIGIT_CODE 1005
#define RADIX_CODE 1006
#define KEYWORD_CODE 1007
#define EOF_CODE 1008
#define WHITESPACE_CODE 1009
#define COMMENT_CODE 1010
#define IDENTIFIER_CODE 1011
/* This list cannot safely be changed without also changing the header
separator #defines. The ordering is significant in that (i) all entries
beginning with the same character must be adjacent and (ii) that if
X is a an initial substring of Y then X must come before Y.
E.g. --> must occur before -- to prevent "-->0" being tokenised
wrongly as "--", ">", "0" rather than "-->", "0". */
static const char separators[NUMBER_SEPARATORS][4] =
{ "->", "-->", "--", "-", "++", "+", "*", "/", "%",
"||", "|", "&&", "&", "~~",
"~=", "~", "==", "=", ">=", ">",
"<=", "<", "(", ")", ",",
".&", ".#", "..&", "..#", "..", ".",
"::", ":", "@", ";", "[", "]", "{", "}",
"$", "?~", "?",
"#a$", "#g$", "#n$", "#r$", "#w$", "##", "#"
};
static void make_tokeniser_grid(void)
{
/* Construct the grid to the specification above. */
int i, j;
for (i=0; i<256; i++) tokeniser_grid[i]=0;
for (i=0; i<NUMBER_SEPARATORS; i++)
{ j=separators[i][0];
if (tokeniser_grid[j]==0)
tokeniser_grid[j]=i*16+1; else tokeniser_grid[j]++;
}
tokeniser_grid['\''] = QUOTE_CODE;
tokeniser_grid['\"'] = DQUOTE_CODE;
tokeniser_grid[0] = EOF_CODE;
tokeniser_grid[' '] = WHITESPACE_CODE;
tokeniser_grid['\n'] = WHITESPACE_CODE;
tokeniser_grid['\r'] = WHITESPACE_CODE;
tokeniser_grid['$'] = RADIX_CODE;
tokeniser_grid['!'] = COMMENT_CODE;
tokeniser_grid['0'] = DIGIT_CODE;
tokeniser_grid['1'] = DIGIT_CODE;
tokeniser_grid['2'] = DIGIT_CODE;
tokeniser_grid['3'] = DIGIT_CODE;
tokeniser_grid['4'] = DIGIT_CODE;
tokeniser_grid['5'] = DIGIT_CODE;
tokeniser_grid['6'] = DIGIT_CODE;
tokeniser_grid['7'] = DIGIT_CODE;
tokeniser_grid['8'] = DIGIT_CODE;
tokeniser_grid['9'] = DIGIT_CODE;
tokeniser_grid['a'] = IDENTIFIER_CODE;
tokeniser_grid['b'] = IDENTIFIER_CODE;
tokeniser_grid['c'] = IDENTIFIER_CODE;
tokeniser_grid['d'] = IDENTIFIER_CODE;
tokeniser_grid['e'] = IDENTIFIER_CODE;
tokeniser_grid['f'] = IDENTIFIER_CODE;
tokeniser_grid['g'] = IDENTIFIER_CODE;
tokeniser_grid['h'] = IDENTIFIER_CODE;
tokeniser_grid['i'] = IDENTIFIER_CODE;
tokeniser_grid['j'] = IDENTIFIER_CODE;