/
ann.crk
1988 lines (1698 loc) · 58.4 KB
/
ann.crk
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 2011-2012 Google Inc.
# Copyright 2012 Conrad Steenberg <conrad.steenberg@gmail.com>
# Copyright 2012 Arno Rehn <arno@arnorehn.de>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Implements some basic annotations that no one should be without. Included
# are:
# @define name(arg, ...) { contents }
# defines a macro with the specified arguments (you can then use the macro
# as @name(args...))
# @interface I { ... }
# Defines a class as an interface, allowing you to safely do multiple
# inheritence.
# class A : Object @implements I, J { ... }
# Makes a class implement the list of interfaces that follows them (this
# mainly entails doing normal class derivation and implementing the
# 'get<interface>Object()' method.
# class A @impl I, J { ... }
# Equivalent to "class A : Object I, J { ... }". Shorthand for the most
# common case.
import crack.compiler CrackContext, Location, Token, TokSerializer,
TOK_BREAKKW, TOK_CLASSKW, TOK_COMMA, TOK_CONTINUEKW, TOK_ELSEKW, TOK_FORKW,
TOK_IFKW, TOK_IMPORTKW, TOK_INKW, TOK_ISKW, TOK_LBRACKET, TOK_LCURLY,
TOK_LPAREN, TOK_NULLKW, TOK_ONKW, TOK_OPERKW, TOK_POPERRCTX, TOK_RBRACKET,
TOK_RCURLY, TOK_RETURNKW, TOK_RPAREN, TOK_STRING, TOK_WHILEKW;
import crack.cont.array Array;
import crack.cont.treemap TreeMap;
import crack.io cerr, FStr, Reader, StandardFormatter, StringFormatter,
StringWriter, Writer;
import crack.lang die, AssertionError, CString, Exception, Formatter,
IndexError, InvalidArgumentError, InvalidStateError;
import crack.runtime free;
import crack.serial SerialReader, SerialWriter;
const NOT_FOUND := 0xFFFFFFFF;
## Serial writer with some additional facilities to simplify macro
## serialization.
class MacroSerializer : SerialWriter {
TreeMap[String, uint] sourceNames = {};
uint lastIdx;
oper init(Writer dst) : SerialWriter(dst) {}
void writeSrcName(String name) {
idx := sourceNames.get(name, NOT_FOUND);
if (idx != NOT_FOUND) {
write(idx);
} else {
# new name, write the index and the
sourceNames[name] = lastIdx;
write(lastIdx++);
write(name);
}
}
void writeLocation(Location loc) {
writeSrcName(String(loc.getName()));
write(uint(loc.getLineNumber()));
}
}
## Serial reader with some additional facilities to simplify macro
## deserialization.
class MacroDeserializer : SerialReader {
CrackContext ctx;
Array[String] sourceNames = {4};
oper init(CrackContext ctx, Reader src) : SerialReader(src), ctx = ctx {}
String readSrcName() {
# read the index
idx := readUInt();
count := sourceNames.count();
if (idx > count) {
throw IndexError(FStr() `Invalid source name index: $idx\n`);
} else if (idx == count) {
name := readString();
sourceNames.append(name);
return name;
} else {
return sourceNames[idx];
}
}
Location readLocation() {
return ctx.getLocation(readSrcName().buffer, int(readUInt()));
}
}
class Node;
class NodeIter;
@abstract class NodeList {
@abstract void pushHead(Node node);
@abstract void append(Node node);
@abstract Node popHead();
@abstract void writeTo(MacroSerializer dst);
@abstract NodeIter iter();
@abstract Node getLast();
@abstract Node getFirst();
@abstract void expand(CrackContext ctx, Array[NodeList] args);
@abstract String toString(Array[NodeList] args);
@abstract Location getLocation();
}
@abstract class Node {
Node next;
void expand(CrackContext ctx, Array[NodeList] args) {}
String toString(Array[NodeList] args) {return null;}
@abstract Location getLocation();
@abstract void writeTo(MacroSerializer dst);
}
class NodeIter {
Node node;
oper init(Node node) : node = node {}
void next() { node = node.next; }
bool isTrue() { return node; }
Node elem() { return node; }
}
Node _readNode(MacroDeserializer src);
## A list of tokens. These are typically stored in reverse order of the
## actual order of the tokens so that they can be easily "put back" into the
## token stream (after putBack() they will be in the correct order once again)
class NodeListImpl : NodeList {
Node first, last;
Location loc;
oper init() {}
oper init(Location loc) : loc = loc {}
void pushHead(Node node) {
if (first) {
node.next = first;
first = node;
} else {
first = last = node;
}
}
void append(Node node) {
if (last) {
last.next = node;
last = node;
} else {
first = last = node;
}
}
Node popHead() {
if (first) {
if (last is first)
last = null;
result := first;
first = first.next;
return result;
} else {
return null;
}
}
oper init(MacroDeserializer src) {
# get the number of nodes in the list
count := src.readUInt();
while (count--) {
append(_readNode(src));
#cout `remaining = $count\n`;
}
}
void writeTo(MacroSerializer dst) {
# count the nodes and write the count
node := first;
uint count;
while (node) {
++count;
node = node.next;
}
#cout `writing count $count\n`;
dst.write(count);
# write all of the nodes
node = first;
while (node) {
node.writeTo(dst);
node = node.next;
}
}
void __write(Formatter fmt, Node node) {
if (node.next)
__write(fmt, node.next);
node.formatTo(fmt);
}
void formatTo(Formatter fmt) {
__write(fmt, first);
}
void writeTo(Writer out) {
StandardFormatter fmt = {out};
__write(fmt, first);
}
NodeIter iter() { return NodeIter(first); }
## Node lists are true if they have any contents.
bool isTrue() { return first; }
Node getLast() { return last; }
Node getFirst() { return first; }
void expand(CrackContext context, Array[NodeList] args) {
for (node :in this)
node.expand(context, args);
}
String toString(Array[NodeList] args) {
StringFormatter sf = {};
Array[Node] nodeArray = {};
for (node :in this)
nodeArray.append(node);
bool first = true;
for (int i = nodeArray.count() - 1; i >= 0; --i) {
if (first)
first = false;
else
sf ` `;
sf `$(nodeArray[i].toString(args))`;
}
return sf.string();
}
Location getLocation() {
if (loc !is null)
return loc;
else if (first)
return first.getLocation();
else
throw AssertionError('Location undefined.');
}
}
class Tok : Node {
Token tok;
oper init(Token tok) : tok = tok {}
oper init() {}
void expand(CrackContext ctx, Array[NodeList] args) {
ctx.putBack(tok);
}
String toString(Array[NodeList] args) {
type := tok.getType();
if (tok.isString()) {
return String(tok.getText()).getRepr();
} else if (type == TOK_BREAKKW) {
return 'break';
} else if (type == TOK_CLASSKW) {
return 'class';
} else if (type == TOK_CONTINUEKW) {
return 'continue';
} else if (type == TOK_FORKW) {
return 'for';
} else if (type == TOK_ELSEKW) {
return 'else';
} else if (type == TOK_IFKW) {
return 'if';
} else if (type == TOK_IMPORTKW) {
return 'import';
} else if (type == TOK_INKW) {
return 'in';
} else if (type == TOK_ISKW) {
return 'is';
} else if (type == TOK_NULLKW) {
return 'null';
} else if (type == TOK_ONKW) {
return 'on';
} else if (type == TOK_OPERKW) {
return 'oper';
} else if (type == TOK_RETURNKW) {
return 'return';
} else if (type == TOK_WHILEKW) {
return 'while';
} else {
return String(tok.getText());
}
}
Location getLocation() {
return tok.getLocation();
}
void formatTo(Formatter fmt) {
if (tok.isString()) {
fmt.format(' ');
fmt.format(String(tok.getText()).getRepr());
} else {
fmt.format(' ');
fmt.format(StaticString(tok.getText()));
}
}
void writeTo(Writer out) {
if (tok.isString()) {
out.write(' ');
out.write(String(tok.getText()).getRepr());
} else {
out.write(' ');
out.write(StaticString(tok.getText()));
}
}
void writeTo(MacroSerializer dst) {
# my node type
dst.write(0);
# the token
dst.write(uint(tok.getType()));
dst.write(String(tok.getText()));
dst.writeLocation(tok.getLocation());
}
oper init(MacroDeserializer src) {
type := int(src.readUInt());
text := src.readString();
locName := src.readSrcName();
locLineNum := src.readUInt();
#cout `read token: $type, $text, $locName, $locLineNum\n`;
tok = Token(type, text.buffer,
src.ctx.getLocation(locName.buffer, int(locLineNum))
);
}
}
class Arg : Node {
uint argIndex;
Location loc;
oper init(Location loc, uint argIndex) :
loc = loc,
argIndex = argIndex {
}
oper init() {}
void expand(CrackContext ctx, Array[NodeList] args) {
for (node :in NodeList.cast(args[argIndex]))
node.expand(ctx, args);
}
String toString(Array[NodeList] args) {
StringFormatter sf = {};
argVal := NodeList.cast(args[argIndex]);
# do the last node so we can add a whitespace separator for every
# subsequent node.
if (last := argVal.getLast())
sf.format(last.toString(args));
# do the rest of the nodes
void reverseNodeList(Array[NodeList] args1, StringFormatter out,
Node node
) {
# stop recursing before the last node
if (node.next) {
reverseNodeList(args1, out, node.next);
out ` $(node.toString(args1))`;
}
}
reverseNodeList(args, sf, argVal.getFirst());
return sf.cString();
}
void formatTo(Formatter fmt) { fmt `arg: $argIndex\n`; }
Location getLocation() { return loc; }
oper init(MacroDeserializer src) {
argIndex = src.readUInt();
loc = src.readLocation();
#cout `read arg $argIndex\n`;
}
void writeTo(MacroSerializer dst) {
# write my type id
dst.write(1);
# write the arg id and location fields
dst.write(argIndex);
dst.writeLocation(loc);
}
}
## Concat nodes concatenate a set of tokens into a single token. The type and
## location come from the first non-argument token.
class Concat : Node {
NodeList list;
int type;
Location loc;
oper init(NodeList list, Location loc) :
loc = loc,
list = list {
}
oper init() {}
void expand(CrackContext ctx, Array[NodeList] args) {
StringFormatter concat = {};
for (item :in list)
concat.format(item.toString(args));
concat.format(' \0');
s := concat.string();
ctx.inject(@FILE.buffer, @LINE, s.buffer);
}
String toString(Array[NodeList] args) {
die('Concat.toString() called.');
return null;
}
Location getLocation() {
return loc;
}
oper init(MacroDeserializer src) {
list = NodeListImpl(src);
type = int(src.readUInt());
loc = src.readLocation();
}
void writeTo(MacroSerializer dst) {
dst.write(2);
list.writeTo(dst);
dst.write(uint(type));
dst.writeLocation(loc);
}
}
## A Node that converts its arguments to a string.
class Stringify : Node {
Node node;
oper init(Node node) : node = node {}
void expand(CrackContext ctx, Array[NodeList] args) {
ctx.putBack(Token(TOK_STRING, node.toString(args).buffer,
node.getLocation()
)
);
}
String toString(Array[NodeList] args) {
die('Stringify.toString called.');
return null;
}
Location getLocation() {
return node.getLocation();
}
oper init(MacroDeserializer src) {
node = _readNode(src);
}
void writeTo(MacroSerializer dst) {
# write my type id.
dst.write(3);
node.writeTo(dst);
}
}
Node _readNode(MacroDeserializer src) {
type := src.readUInt();
Node node;
if (type == 0)
node = Tok(src);
else if (type == 1)
node = Arg(src);
else if (type == 2)
node = Concat(src);
else if (type == 3)
node = Stringify(src);
else
throw AssertionError(FStr() `bogus node $type\n`);
return node;
}
## Parse the rest of the i-string (after the ISTR_BEGIN token) into 'result'
## (backwards, of course).
void parseIString(CrackContext ctx, NodeList result) {
int parenCount = 0;
while (true) {
tok := ctx.getToken();
result.pushHead(Tok(tok));
if (tok.isLParen()) {
parenCount++;
} else if (!parenCount && tok.isIdent()) {
ctx.continueIString();
} else if (tok.isRParen()) {
if (!--parenCount)
ctx.continueIString();
} else if (tok.isIstrEnd()) {
break;
}
}
}
## Parse macro arguments, returns them as an array of NodeList objects.
Array[NodeList] parseArgs(CrackContext ctx, uint argCount) {
# extract the arguments from the following tokens
tok := ctx.getToken();
if (!tok.isLParen())
ctx.error(tok, 'left paren expected in macro expansion'.buffer);
const byte PAREN = 1, BRACK = 2, CURL = 3;
uint nesting = 1;
argTokList := NodeListImpl();
Array[NodeList] args = {argCount};
Array[byte] brackStack = {4};
# pop everything on the bracket stack up to the matching value. This
# behavior lets us both respect existing balanced delimiters and ignore
# unbalanced ones.
void popTo(Array[byte] brackStack, byte val) {
for (int i = brackStack.count() - 1; i >= 0; --i) {
if (brackStack[i] == val) {
while (brackStack.count() > i) {
brackStack.delete(brackStack.count() - 1);
}
break;
}
}
}
while (true) {
tok = ctx.getToken();
if (!brackStack && tok.isComma()) {
args.append(argTokList);
argTokList = NodeListImpl();
} else {
if (tok.isLParen()) {
brackStack.append(PAREN);
} else if (tok.isLBracket()) {
brackStack.append(BRACK);
} else if (tok.isLCurly()) {
brackStack.append(CURL);
} else if (tok.isRParen()) {
if (!brackStack)
break;
else
popTo(brackStack, PAREN);
} else if (tok.isRBracket() && brackStack) {
popTo(brackStack, BRACK);
} else if (tok.isRCurly() && brackStack) {
popTo(brackStack, CURL);
} else if (tok.isIstrBegin()) {
argTokList.pushHead(Tok(tok));
parseIString(ctx, argTokList);
continue;
}
argTokList.pushHead(Tok(tok));
}
}
# if we got a non-empty element left over, add it to the list.
if (argTokList.getFirst())
args.append(argTokList);
# verify that the number of arguments provided was correct
if (args.count() != argCount) {
fmt := StringFormatter();
fmt `Incorrect number of arguments for macro: expected \
$(argCount), got $(args.count())\0`;
ctx.error(tok, fmt.string().buffer);
}
return args;
}
class Macro : NodeListImpl {
String name;
uint argCount;
oper init() {}
oper init(MacroDeserializer src) : NodeListImpl(src) {
name = src.readString();
argCount = src.readUInt();
}
void writeTo(MacroSerializer dst) {
NodeListImpl.writeTo(dst);
dst.write(name);
dst.write(argCount);
}
void expand(CrackContext ctx) {
# hold onto the last location
loc := ctx.getLocation();
# parse the args.
args := parseArgs(ctx, argCount);
# install the "pop error context" token so that our error context only
# shows up for the expansion of the macro.
ctx.putBack(Token(TOK_POPERRCTX, '[pop error context]'.buffer,
loc
)
);
# expand the macro
Node node = first;
while (node) {
node.expand(ctx, args);
node = node.next;
}
# push an error context
StringFormatter fmt = {};
fmt `expanded from macro at $(loc.getName()):$(loc.getLineNumber())`;
ctx.pushErrorContext(fmt.cString().buffer);
}
}
## Annotation to expand a macro. This expects a Macro instance as user data.
void expand(CrackContext ctx) {
mac := Macro.unsafeCast(ctx.getUserData());
mac.expand(ctx);
}
# macro parser states
ST_NONE := 0;
ST_ESC := 1; # got a dollar-sign escape
ST_CONCAT := 2; # got a double-dollar-sign concatenation operator
ST_ISTR := 3; # MUST BE THE HIGHEST VALUE STATE. Values greater than this
# indicate levels of nested parens in an i-string.
void define(CrackContext ctx) {
Macro mac = {};
TreeMap[String, uint] args = {};
uint index;
tok := ctx.getToken();
if (!tok.isIdent())
ctx.error(tok, 'Macro name expected after define.'.buffer);
mac.name = String(tok.getText());
# parse the '(' that begins the argument list
tok = ctx.getToken();
if (!tok.isLParen())
ctx.error(tok, 'Left paren expected after macro definition'.buffer);
# read all of the arguments
while (true) {
tok = ctx.getToken();
if (tok.isRParen())
break;
if (!tok.isIdent())
ctx.error(tok, 'identifier expected'.buffer);
args[String(tok.getText())] = index++;
tok = ctx.getToken();
if (tok.isRParen())
break;
else if (!tok.isComma())
ctx.error('comma or end paren expected in macro def'.buffer);
}
mac.argCount = index;
# read the body of the macro
tok = ctx.getToken();
if (!tok.isLCurly())
ctx.error('Expected left bracket'.buffer);
# read everything until the end bracket
uint bracketCount = 1;
int state = ST_NONE;
NodeListImpl lastConcat = {}; # last concatenation sequence.
Node node; # the last node
while (true) {
tok = ctx.getToken();
uint argIndex;
if (tok.isEnd()) {
ctx.error(
'End of file before the end of a macro definition'.buffer
);
} else if (state >= ST_ISTR) {
# keep track of the parens.
if (tok.isLParen())
++state;
else if (tok.isRParen() && --state == ST_ISTR)
# we have to tell the tokenizer to continue parsing the
# i-string.
ctx.continueIString();
else if (tok.isIstrBegin())
ctx.error('Nested interpolation strings may not be used '
'in macros.'.buffer
);
else if (tok.isDollar())
ctx.error('Nested concatenations and stringifications may not '
'be used in a macro.'.buffer
);
else if (tok.isIstrEnd())
state = ST_NONE;
else if (state == ST_ISTR && tok.isIdent())
# an identifier takes us immediately back into the i-string
ctx.continueIString();
} else if (tok.isIstrBegin()) {
if (state != ST_NONE)
ctx.error('An interpolation string may not be used with '
'stringification or concatenation.'.buffer
);
state = ST_ISTR;
# check for brackets, increment or decrement the bracket count.
} else if (tok.isRCurly()) {
if (!--bracketCount)
break;
} else if (tok.isLCurly()) {
++bracketCount;
} else if (tok.isDollar()) {
if (state == ST_NONE) {
state = ST_ESC;
} else if (state == ST_ESC) {
if (!node)
ctx.error('The macro may not begin with a concatenation '
'operator'.buffer
);
else if (node.isa(Tok) &&
Tok.cast(node).tok.isIstrEnd()
)
ctx.error('An interpolation string may not be used with '
'stringification or concatenation'.buffer
);
# if we're starting off a new concatenation sequence, add the
# last node and store the sequence as a new node in the macro.
if (!lastConcat) {
lastConcat.append(node);
mac.popHead();
mac.pushHead(Concat(lastConcat, tok.getLocation()));
}
state = ST_CONCAT;
} else {
ctx.error('One two many dollar signs\n'.buffer);
}
continue;
}
# replace arguments with indices
if (tok.isIdent() &&
(argIndex = args.get(String(tok.getText()), NOT_FOUND)) !=
NOT_FOUND
)
node = Arg(tok.getLocation(), argIndex);
else
node = Tok(tok);
# handle special states
if (state == ST_CONCAT) {
# concatenation state - add the new node to the concatenation
# sequence.
lastConcat.append(node);
state = ST_NONE;
} else if (state == ST_ESC) {
# stringify state - add a stringify node.
mac.pushHead(Stringify(node));
state = ST_NONE;
} else {
mac.pushHead(node);
# reset any last concatenation sequence that we've accumulated
if (lastConcat)
lastConcat = NodeListImpl();
}
}
# store a new annotation for expanding the macro
ctx.storeAnnotation(mac.name.buffer, expand, mac);
mac.oper bind();
}
void export(CrackContext ctx) {
# get the next token, make sure it's an annotation.
tok := ctx.getToken();
if (!tok.isIdent())
ctx.error(tok, 'Identifier expected'.buffer);
name := CString(tok.getText(), false);
ann := ctx.getAnnotation(name.buffer);
Macro mac;
if (ann is null) {
StringFormatter fmt = {};
fmt `$name is not an annotation.\0`;
ctx.error(tok, fmt.string().buffer);
} else {
mac = Macro.unsafeCast(ann.getUserData());
}
# serialize the macro into a string
flatMac := StringWriter();
mac.writeTo(MacroSerializer(flatMac));
StringFormatter code = {};
f := @FILE; l := @LINE; code `
void $name(CrackContext ctx) {
userData :=
ctx.getUserData();
Macro mac;
if (userData is null) {
StringReader reader = { $(flatMac.string().getRepr()) };
mac = Macro(MacroDeserializer(ctx, reader));
ctx.storeAnnotation($(name.getRepr()).buffer, $name,
mac
);
mac.oper bind();
} else {
mac = Macro.unsafeCast(userData);
}
mac.expand(ctx);
}
\n\0`;
ctx.inject(f.buffer, l, code.string().buffer);
}
## Call this annotation at the top of your file if you want to export macros.
## It will import everything you need.
void exporter(CrackContext ctx) {
StringFormatter f = {};
f `import crack.ann Macro, MacroDeserializer, Node, NodeList, Tok, Arg,
Stringify, Concat;
import crack.compiler CrackContext, Token, TOK_STRING;
import crack.io StringReader;`;
ctx.inject(@FILE.buffer, @LINE,
f.cString().buffer);
}
void readIStr(CrackContext ctx, NodeList nodes) {
depth := 0;
while (true) {
tok := ctx.getToken();
nodes.pushHead(Tok(tok));
if (tok.isLParen())
++depth;
else if (tok.isRParen() && !--depth)
ctx.continueIString();
else if (tok.isIdent() && !depth)
ctx.continueIString();
else if (tok.isIstrEnd())
return;
}
}
## Just like the other readDelimited() except that it passes in the 'result'
## list instead of returning it, allowing you to compose on an existing list.
void readDelimited(CrackContext ctx, int left, int right,
bool storeDelimiters,
NodeList result
) {
# get the opening delimiter.
Token tok;
Location start;
if (storeDelimiters) {
tok = ctx.getToken();
start = tok.getLocation();
if (tok.getType() != left)
ctx.error(tok, 'Opening delimiter expected.'.buffer);
result.pushHead(Tok(tok));
}
depth := 1;
while (depth) {
tok = ctx.getToken();
if (start is null)
start = tok.getLocation();
if (tok.isEnd())
ctx.error(
tok,
FStr() `Premature end of file (in block starting at $(
start.getName()):$(start.getLineNumber()))`.buffer
);
if (tok.getType() == left)
++depth;
else if (tok.getType() == right)
--depth;
if (depth || storeDelimiters)
result.pushHead(Tok(tok));
else if (!depth)
# If we're not storing the delimiters, put the last token back.
ctx.putBack(tok);
if (tok.isIstrBegin())
readIStr(ctx, result);
}
}
## Reads a sequence of tokens between a specified left and right delimiter
## which can be nested. For example, if left and right are TOK_LPAREN and
## TOK_RPAREN this function would read the following sequence:
## ( 1 + 2 + (3 + 4) )
## ^ ^
##
## if storeDelimiters is true, parses and processes the beginning and ending
## delimiter and adds them to the returned node list, otherwise the next
## available token should be the one immediately following the opening
## delimiter and the last token will be put back.
NodeList readDelimited(CrackContext ctx, int left, int right,
bool storeDelimiters
) {
NodeListImpl result = {};
readDelimited(ctx, left, right, storeDelimiters, result);
return result;
}
## Read a curly-bracket delimited block. See readDelimited() for details
NodeList readBlock(CrackContext ctx) {
return readDelimited(ctx, TOK_LCURLY, TOK_RCURLY, true);
}
void _parseGenericArgs(CrackContext ctx, NodeList tokens) {
while (true) {
tok := ctx.getToken();
if (!tok.isIdent())
ctx.error(tok, 'Identifier expected in generic definition'.buffer);
tokens.append(Tok(tok));
tok = ctx.getToken();
tokens.append(Tok(tok));
if (tok.isRBracket())
return;
else if (!tok.isComma())
ctx.error(tok,
'Comma or closing bracket expected in generic definition'.
buffer
);
}
}
## Writes a NodeList to an output stream separated by whitespace.
class TokenWriter {
NodeList tokens;
oper init(NodeList tokens) : tokens = tokens {}
void formatTo(Formatter fmt) {
for (tok :in tokens) {
fmt.format(tok.toString(null));
fmt.format(' ');
}
}
void writeTo(Writer out) {
for (tok :in tokens) {
out.write(tok.toString(null));
out.write(' ');
}
}
}
void warn(CrackContext ctx) {
tok := ctx.getToken();
if (!tok.isString())
ctx.error(tok, "String expected after @warn annotation".buffer);
ctx.warn(tok, tok.getText());
}