-
Notifications
You must be signed in to change notification settings - Fork 176
Expand file tree
/
Copy pathantlr3baserecognizer.c
More file actions
2245 lines (1904 loc) · 67.4 KB
/
antlr3baserecognizer.c
File metadata and controls
2245 lines (1904 loc) · 67.4 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
/** \file
* Contains the base functions that all recognizers require.
* Any function can be overridden by a lexer/parser/tree parser or by the
* ANTLR3 programmer.
*
* \addtogroup pANTLR3_BASE_RECOGNIZER
* @{
*/
#include <antlr3baserecognizer.h>
// [The "BSD licence"]
// Copyright (c) 2005-2009 Jim Idle, Temporal Wave LLC
// http://www.temporal-wave.com
// http://www.linkedin.com/in/jimidle
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifdef ANTLR3_WINDOWS
#pragma warning( disable : 4100 )
#endif
/* Interface functions -standard implementations cover parser and treeparser
* almost completely but are overridden by the parser or tree parser as needed. Lexer overrides
* most of these functions.
*/
static void beginResync (pANTLR3_BASE_RECOGNIZER recognizer);
static pANTLR3_BITSET computeErrorRecoverySet (pANTLR3_BASE_RECOGNIZER recognizer);
static void endResync (pANTLR3_BASE_RECOGNIZER recognizer);
static void beginBacktrack (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 level);
static void endBacktrack (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 level, ANTLR3_BOOLEAN successful);
static void * match (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 ttype, pANTLR3_BITSET_LIST follow);
static void matchAny (pANTLR3_BASE_RECOGNIZER recognizer);
static void mismatch (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 ttype, pANTLR3_BITSET_LIST follow);
static ANTLR3_BOOLEAN mismatchIsUnwantedToken (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_INT_STREAM is, ANTLR3_UINT32 ttype);
static ANTLR3_BOOLEAN mismatchIsMissingToken (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_INT_STREAM is, pANTLR3_BITSET_LIST follow);
static void reportError (pANTLR3_BASE_RECOGNIZER recognizer);
static pANTLR3_BITSET computeCSRuleFollow (pANTLR3_BASE_RECOGNIZER recognizer);
static pANTLR3_BITSET combineFollows (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_BOOLEAN exact);
static void displayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames);
static void recover (pANTLR3_BASE_RECOGNIZER recognizer);
static void * recoverFromMismatchedToken (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 ttype, pANTLR3_BITSET_LIST follow);
static void * recoverFromMismatchedSet (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_BITSET_LIST follow);
static ANTLR3_BOOLEAN recoverFromMismatchedElement(pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_BITSET_LIST follow);
static void consumeUntil (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 tokenType);
static void consumeUntilSet (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_BITSET set);
static pANTLR3_STACK getRuleInvocationStack (pANTLR3_BASE_RECOGNIZER recognizer);
static pANTLR3_STACK getRuleInvocationStackNamed (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 name);
static pANTLR3_HASH_TABLE toStrings (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_HASH_TABLE);
static ANTLR3_MARKER getRuleMemoization (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_INTKEY ruleIndex, ANTLR3_MARKER ruleParseStart);
static ANTLR3_BOOLEAN alreadyParsedRule (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_MARKER ruleIndex);
static void memoize (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_MARKER ruleIndex, ANTLR3_MARKER ruleParseStart);
static ANTLR3_BOOLEAN synpred (pANTLR3_BASE_RECOGNIZER recognizer, void * ctx, void (*predicate)(void * ctx));
static void reset (pANTLR3_BASE_RECOGNIZER recognizer);
static void freeBR (pANTLR3_BASE_RECOGNIZER recognizer);
static void * getCurrentInputSymbol (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_INT_STREAM istream);
static void * getMissingSymbol (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_INT_STREAM istream, pANTLR3_EXCEPTION e,
ANTLR3_UINT32 expectedTokenType, pANTLR3_BITSET_LIST follow);
static ANTLR3_UINT32 getNumberOfSyntaxErrors (pANTLR3_BASE_RECOGNIZER recognizer);
ANTLR3_API pANTLR3_BASE_RECOGNIZER
antlr3BaseRecognizerNew(ANTLR3_UINT32 type, ANTLR3_UINT32 sizeHint, pANTLR3_RECOGNIZER_SHARED_STATE state)
{
pANTLR3_BASE_RECOGNIZER recognizer;
// Allocate memory for the structure
//
recognizer = (pANTLR3_BASE_RECOGNIZER) ANTLR3_MALLOC((size_t)sizeof(ANTLR3_BASE_RECOGNIZER));
if (recognizer == NULL)
{
// Allocation failed
//
return NULL;
}
// If we have been supplied with a pre-existing recognizer state
// then we just install it, otherwise we must create one from scratch
//
if (state == NULL)
{
recognizer->state = (pANTLR3_RECOGNIZER_SHARED_STATE) ANTLR3_CALLOC(1, (size_t)sizeof(ANTLR3_RECOGNIZER_SHARED_STATE));
if (recognizer->state == NULL)
{
ANTLR3_FREE(recognizer);
return NULL;
}
// Initialize any new recognizer state
//
recognizer->state->errorRecovery = ANTLR3_FALSE;
recognizer->state->lastErrorIndex = -1;
recognizer->state->failed = ANTLR3_FALSE;
recognizer->state->errorCount = 0;
recognizer->state->backtracking = 0;
recognizer->state->following = NULL;
recognizer->state->ruleMemo = NULL;
recognizer->state->tokenNames = NULL;
recognizer->state->sizeHint = sizeHint;
recognizer->state->tokSource = NULL;
recognizer->state->tokFactory = NULL;
// Rather than check to see if we must initialize
// the stack every time we are asked for an new rewrite stream
// we just always create an empty stack and then just
// free it when the base recognizer is freed.
//
recognizer->state->rStreams = antlr3VectorNew(0); // We don't know the size.
if (recognizer->state->rStreams == NULL)
{
// Out of memory
//
ANTLR3_FREE(recognizer->state);
ANTLR3_FREE(recognizer);
return NULL;
}
}
else
{
// Install the one we were given, and do not reset it here
// as it will either already have been initialized or will
// be in a state that needs to be preserved.
//
recognizer->state = state;
}
// Install the BR API
//
recognizer->alreadyParsedRule = alreadyParsedRule;
recognizer->beginResync = beginResync;
recognizer->combineFollows = combineFollows;
recognizer->beginBacktrack = beginBacktrack;
recognizer->endBacktrack = endBacktrack;
recognizer->computeCSRuleFollow = computeCSRuleFollow;
recognizer->computeErrorRecoverySet = computeErrorRecoverySet;
recognizer->consumeUntil = consumeUntil;
recognizer->consumeUntilSet = consumeUntilSet;
recognizer->displayRecognitionError = displayRecognitionError;
recognizer->endResync = endResync;
recognizer->exConstruct = antlr3MTExceptionNew;
recognizer->getRuleInvocationStack = getRuleInvocationStack;
recognizer->getRuleInvocationStackNamed = getRuleInvocationStackNamed;
recognizer->getRuleMemoization = getRuleMemoization;
recognizer->match = match;
recognizer->matchAny = matchAny;
recognizer->memoize = memoize;
recognizer->mismatch = mismatch;
recognizer->mismatchIsUnwantedToken = mismatchIsUnwantedToken;
recognizer->mismatchIsMissingToken = mismatchIsMissingToken;
recognizer->recover = recover;
recognizer->recoverFromMismatchedElement= recoverFromMismatchedElement;
recognizer->recoverFromMismatchedSet = recoverFromMismatchedSet;
recognizer->recoverFromMismatchedToken = recoverFromMismatchedToken;
recognizer->getNumberOfSyntaxErrors = getNumberOfSyntaxErrors;
recognizer->reportError = reportError;
recognizer->reset = reset;
recognizer->synpred = synpred;
recognizer->toStrings = toStrings;
recognizer->getCurrentInputSymbol = getCurrentInputSymbol;
recognizer->getMissingSymbol = getMissingSymbol;
recognizer->debugger = NULL;
recognizer->free = freeBR;
/* Initialize variables
*/
recognizer->type = type;
return recognizer;
}
static void
freeBR (pANTLR3_BASE_RECOGNIZER recognizer)
{
pANTLR3_EXCEPTION thisE;
// Did we have a state allocated?
//
if (recognizer->state != NULL)
{
// Free any rule memoization we set up
//
if (recognizer->state->ruleMemo != NULL)
{
recognizer->state->ruleMemo->free(recognizer->state->ruleMemo);
recognizer->state->ruleMemo = NULL;
}
// Free any exception space we have left around
//
thisE = recognizer->state->exception;
if (thisE != NULL)
{
thisE->freeEx(thisE);
}
// Free any rewrite streams we have allocated
//
if (recognizer->state->rStreams != NULL)
{
recognizer->state->rStreams->free(recognizer->state->rStreams);
}
// Free up any token factory we created (error recovery for instance)
//
if (recognizer->state->tokFactory != NULL)
{
recognizer->state->tokFactory->close(recognizer->state->tokFactory);
}
// Free the shared state memory
//
ANTLR3_FREE(recognizer->state);
}
// Free the actual recognizer space
//
ANTLR3_FREE(recognizer);
}
/**
* Creates a new Mismatched Token Exception and inserts in the recognizer
* exception stack.
*
* \param recognizer
* Context pointer for this recognizer
*
*/
ANTLR3_API void
antlr3MTExceptionNew(pANTLR3_BASE_RECOGNIZER recognizer)
{
/* Create a basic recognition exception structure
*/
antlr3RecognitionExceptionNew(recognizer);
/* Now update it to indicate this is a Mismatched token exception
*/
recognizer->state->exception->name = ANTLR3_MISMATCHED_EX_NAME;
recognizer->state->exception->type = ANTLR3_MISMATCHED_TOKEN_EXCEPTION;
return;
}
ANTLR3_API void
antlr3RecognitionExceptionNew(pANTLR3_BASE_RECOGNIZER recognizer)
{
pANTLR3_EXCEPTION ex;
pANTLR3_LEXER lexer;
pANTLR3_PARSER parser;
pANTLR3_TREE_PARSER tparser;
pANTLR3_INPUT_STREAM ins;
pANTLR3_INT_STREAM is;
pANTLR3_COMMON_TOKEN_STREAM cts;
pANTLR3_TREE_NODE_STREAM tns;
ins = NULL;
cts = NULL;
tns = NULL;
is = NULL;
lexer = NULL;
parser = NULL;
tparser = NULL;
switch (recognizer->type)
{
case ANTLR3_TYPE_LEXER:
lexer = (pANTLR3_LEXER) (recognizer->super);
ins = lexer->input;
is = ins->istream;
break;
case ANTLR3_TYPE_PARSER:
parser = (pANTLR3_PARSER) (recognizer->super);
cts = (pANTLR3_COMMON_TOKEN_STREAM)(parser->tstream->super);
is = parser->tstream->istream;
break;
case ANTLR3_TYPE_TREE_PARSER:
tparser = (pANTLR3_TREE_PARSER) (recognizer->super);
tns = tparser->ctnstream->tnstream;
is = tns->istream;
break;
default:
ANTLR3_FPRINTF(stderr, "Base recognizer function antlr3RecognitionExceptionNew called by unknown parser type - provide override for this function\n");
return;
break;
}
/* Create a basic exception structure
*/
ex = antlr3ExceptionNew(ANTLR3_RECOGNITION_EXCEPTION,
(void *)ANTLR3_RECOGNITION_EX_NAME,
NULL,
ANTLR3_FALSE);
/* Rest of information depends on the base type of the
* input stream.
*/
switch (is->type & ANTLR3_INPUT_MASK)
{
case ANTLR3_CHARSTREAM:
ex->c = is->_LA (is, 1); /* Current input character */
ex->line = ins->getLine (ins); /* Line number comes from stream */
ex->charPositionInLine = ins->getCharPositionInLine (ins); /* Line offset also comes from the stream */
ex->index = is->index (is);
ex->streamName = ins->fileName;
ex->message = "Unexpected character";
break;
case ANTLR3_TOKENSTREAM:
ex->token = cts->tstream->_LT (cts->tstream, 1); /* Current input token */
ex->line = ((pANTLR3_COMMON_TOKEN)(ex->token))->getLine ((pANTLR3_COMMON_TOKEN)(ex->token));
ex->charPositionInLine = ((pANTLR3_COMMON_TOKEN)(ex->token))->getCharPositionInLine ((pANTLR3_COMMON_TOKEN)(ex->token));
ex->index = cts->tstream->istream->index (cts->tstream->istream);
if (((pANTLR3_COMMON_TOKEN)(ex->token))->type == ANTLR3_TOKEN_EOF)
{
ex->streamName = NULL;
}
else
{
ex->streamName = ((pANTLR3_COMMON_TOKEN)(ex->token))->input->fileName;
}
ex->message = "Unexpected token";
break;
case ANTLR3_COMMONTREENODE:
ex->token = tns->_LT (tns, 1); /* Current input tree node */
ex->line = ((pANTLR3_BASE_TREE)(ex->token))->getLine ((pANTLR3_BASE_TREE)(ex->token));
ex->charPositionInLine = ((pANTLR3_BASE_TREE)(ex->token))->getCharPositionInLine ((pANTLR3_BASE_TREE)(ex->token));
ex->index = tns->istream->index (tns->istream);
// Are you ready for this? Deep breath now...
//
{
pANTLR3_COMMON_TREE tnode;
tnode = ((pANTLR3_COMMON_TREE)(((pANTLR3_BASE_TREE)(ex->token))->super));
if (tnode->token == NULL)
{
ex->streamName = ((pANTLR3_BASE_TREE)(ex->token))->strFactory->newStr(((pANTLR3_BASE_TREE)(ex->token))->strFactory, (pANTLR3_UINT8)"-unknown source-");
}
else
{
if (tnode->token->input == NULL)
{
ex->streamName = NULL;
}
else
{
ex->streamName = tnode->token->input->fileName;
}
}
ex->message = "Unexpected node";
}
break;
}
ex->input = is;
ex->nextException = recognizer->state->exception; /* So we don't leak the memory */
recognizer->state->exception = ex;
recognizer->state->error = ANTLR3_TRUE; /* Exception is outstanding */
return;
}
/// Match current input symbol against ttype. Upon error, do one token
/// insertion or deletion if possible.
/// To turn off single token insertion or deletion error
/// recovery, override mismatchRecover() and have it call
/// plain mismatch(), which does not recover. Then any error
/// in a rule will cause an exception and immediate exit from
/// rule. Rule would recover by resynchronizing to the set of
/// symbols that can follow rule ref.
///
static void *
match( pANTLR3_BASE_RECOGNIZER recognizer,
ANTLR3_UINT32 ttype, pANTLR3_BITSET_LIST follow)
{
pANTLR3_PARSER parser;
pANTLR3_TREE_PARSER tparser;
pANTLR3_INT_STREAM is;
void * matchedSymbol;
switch (recognizer->type)
{
case ANTLR3_TYPE_PARSER:
parser = (pANTLR3_PARSER) (recognizer->super);
tparser = NULL;
is = parser->tstream->istream;
break;
case ANTLR3_TYPE_TREE_PARSER:
tparser = (pANTLR3_TREE_PARSER) (recognizer->super);
parser = NULL;
is = tparser->ctnstream->tnstream->istream;
break;
default:
ANTLR3_FPRINTF(stderr, "Base recognizer function 'match' called by unknown parser type - provide override for this function\n");
return ANTLR3_FALSE;
break;
}
// Pick up the current input token/node for assignment to labels
//
matchedSymbol = recognizer->getCurrentInputSymbol(recognizer, is);
if (is->_LA(is, 1) == ttype)
{
// The token was the one we were told to expect
//
is->consume(is); // Consume that token from the stream
recognizer->state->errorRecovery = ANTLR3_FALSE; // Not in error recovery now (if we were)
recognizer->state->failed = ANTLR3_FALSE; // The match was a success
return matchedSymbol; // We are done
}
// We did not find the expected token type, if we are backtracking then
// we just set the failed flag and return.
//
if (recognizer->state->backtracking > 0)
{
// Backtracking is going on
//
recognizer->state->failed = ANTLR3_TRUE;
return matchedSymbol;
}
// We did not find the expected token and there is no backtracking
// going on, so we mismatch, which creates an exception in the recognizer exception
// stack.
//
matchedSymbol = recognizer->recoverFromMismatchedToken(recognizer, ttype, follow);
return matchedSymbol;
}
/// Consumes the next token, whatever it is, and resets the recognizer state
/// so that it is not in error.
///
/// \param recognizer
/// Recognizer context pointer
///
static void
matchAny(pANTLR3_BASE_RECOGNIZER recognizer)
{
pANTLR3_PARSER parser;
pANTLR3_TREE_PARSER tparser;
pANTLR3_INT_STREAM is;
switch (recognizer->type)
{
case ANTLR3_TYPE_PARSER:
parser = (pANTLR3_PARSER) (recognizer->super);
tparser = NULL;
is = parser->tstream->istream;
break;
case ANTLR3_TYPE_TREE_PARSER:
tparser = (pANTLR3_TREE_PARSER) (recognizer->super);
parser = NULL;
is = tparser->ctnstream->tnstream->istream;
break;
default:
ANTLR3_FPRINTF(stderr, "Base recognizer function 'matchAny' called by unknown parser type - provide override for this function\n");
return;
break;
}
recognizer->state->errorRecovery = ANTLR3_FALSE;
recognizer->state->failed = ANTLR3_FALSE;
is->consume(is);
return;
}
///
///
static ANTLR3_BOOLEAN
mismatchIsUnwantedToken(pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_INT_STREAM is, ANTLR3_UINT32 ttype)
{
ANTLR3_UINT32 nextt;
nextt = is->_LA(is, 2);
if (nextt == ttype)
{
if (recognizer->state->exception != NULL)
{
recognizer->state->exception->expecting = nextt;
}
return ANTLR3_TRUE; // This token is unknown, but the next one is the one we wanted
}
else
{
return ANTLR3_FALSE; // Neither this token, nor the one following is the one we wanted
}
}
///
///
static ANTLR3_BOOLEAN
mismatchIsMissingToken(pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_INT_STREAM is, pANTLR3_BITSET_LIST follow)
{
ANTLR3_BOOLEAN retcode;
pANTLR3_BITSET followClone;
pANTLR3_BITSET viableTokensFollowingThisRule;
if (follow == NULL)
{
// There is no information about the tokens that can follow the last one
// hence we must say that the current one we found is not a member of the
// follow set and does not indicate a missing token. We will just consume this
// single token and see if the parser works it out from there.
//
return ANTLR3_FALSE;
}
followClone = NULL;
viableTokensFollowingThisRule = NULL;
// The C bitset maps are laid down at compile time by the
// C code generation. Hence we cannot remove things from them
// and so on. So, in order to remove EOR (if we need to) then
// we clone the static bitset.
//
followClone = antlr3BitsetLoad(follow);
if (followClone == NULL)
{
return ANTLR3_FALSE;
}
// Compute what can follow this grammar reference
//
if (followClone->isMember(followClone, ANTLR3_EOR_TOKEN_TYPE))
{
// EOR can follow, but if we are not the start symbol, we
// need to remove it.
//
//if (recognizer->state->following->vector->count >= 0) ml: always true
{
followClone->remove(followClone, ANTLR3_EOR_TOKEN_TYPE);
}
// Now compute the visiable tokens that can follow this rule, according to context
// and make them part of the follow set.
//
viableTokensFollowingThisRule = recognizer->computeCSRuleFollow(recognizer);
followClone->borInPlace(followClone, viableTokensFollowingThisRule);
}
/// if current token is consistent with what could come after set
/// then we know we're missing a token; error recovery is free to
/// "insert" the missing token
///
/// BitSet cannot handle negative numbers like -1 (EOF) so I leave EOR
/// in follow set to indicate that the fall of the start symbol is
/// in the set (EOF can follow).
///
if ( followClone->isMember(followClone, is->_LA(is, 1))
|| followClone->isMember(followClone, ANTLR3_EOR_TOKEN_TYPE)
)
{
retcode = ANTLR3_TRUE;
}
else
{
retcode = ANTLR3_FALSE;
}
if (viableTokensFollowingThisRule != NULL)
{
viableTokensFollowingThisRule->free(viableTokensFollowingThisRule);
}
if (followClone != NULL)
{
followClone->free(followClone);
}
return retcode;
}
/// Factor out what to do upon token mismatch so tree parsers can behave
/// differently. Override and call mismatchRecover(input, ttype, follow)
/// to get single token insertion and deletion. Use this to turn off
/// single token insertion and deletion. Override mismatchRecover
/// to call this instead.
///
/// \remark mismatch only works for parsers and must be overridden for anything else.
///
static void
mismatch(pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 ttype, pANTLR3_BITSET_LIST follow)
{
pANTLR3_PARSER parser;
pANTLR3_TREE_PARSER tparser;
pANTLR3_INT_STREAM is;
// Install a mismatched token exception in the exception stack
//
antlr3MTExceptionNew(recognizer);
recognizer->state->exception->expecting = ttype;
switch (recognizer->type)
{
case ANTLR3_TYPE_PARSER:
parser = (pANTLR3_PARSER) (recognizer->super);
tparser = NULL;
is = parser->tstream->istream;
break;
default:
ANTLR3_FPRINTF(stderr, "Base recognizer function 'mismatch' called by unknown parser type - provide override for this function\n");
return;
break;
}
if (mismatchIsUnwantedToken(recognizer, is, ttype))
{
// Create a basic recognition exception structure
//
antlr3RecognitionExceptionNew(recognizer);
// Now update it to indicate this is an unwanted token exception
//
recognizer->state->exception->name = ANTLR3_UNWANTED_TOKEN_EXCEPTION_NAME;
recognizer->state->exception->type = ANTLR3_UNWANTED_TOKEN_EXCEPTION;
return;
}
if (mismatchIsMissingToken(recognizer, is, follow))
{
// Create a basic recognition exception structure
//
antlr3RecognitionExceptionNew(recognizer);
// Now update it to indicate this is an unwanted token exception
//
recognizer->state->exception->name = ANTLR3_MISSING_TOKEN_EXCEPTION_NAME;
recognizer->state->exception->type = ANTLR3_MISSING_TOKEN_EXCEPTION;
return;
}
// Just a mismatched token is all we can dtermine
//
antlr3MTExceptionNew(recognizer);
return;
}
/// Report a recognition problem.
///
/// This method sets errorRecovery to indicate the parser is recovering
/// not parsing. Once in recovery mode, no errors are generated.
/// To get out of recovery mode, the parser must successfully match
/// a token (after a resync). So it will go:
///
/// 1. error occurs
/// 2. enter recovery mode, report error
/// 3. consume until token found in resynch set
/// 4. try to resume parsing
/// 5. next match() will reset errorRecovery mode
///
/// If you override, make sure to update errorCount if you care about that.
///
static void
reportError (pANTLR3_BASE_RECOGNIZER recognizer)
{
// Invoke the debugger event if there is a debugger listening to us
//
if (recognizer->debugger != NULL)
{
recognizer->debugger->recognitionException(recognizer->debugger, recognizer->state->exception);
}
if (recognizer->state->errorRecovery == ANTLR3_TRUE)
{
// Already in error recovery so don't display another error while doing so
//
return;
}
// Signal we are in error recovery now
//
recognizer->state->errorRecovery = ANTLR3_TRUE;
// Indicate this recognizer had an error while processing.
//
recognizer->state->errorCount++;
// Call the error display routine
//
recognizer->displayRecognitionError(recognizer, recognizer->state->tokenNames);
}
static void
beginBacktrack (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 level)
{
if (recognizer->debugger != NULL)
{
recognizer->debugger->beginBacktrack(recognizer->debugger, level);
}
}
static void
endBacktrack (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_UINT32 level, ANTLR3_BOOLEAN successful)
{
if (recognizer->debugger != NULL)
{
recognizer->debugger->endBacktrack(recognizer->debugger, level, successful);
}
}
static void
beginResync (pANTLR3_BASE_RECOGNIZER recognizer)
{
if (recognizer->debugger != NULL)
{
recognizer->debugger->beginResync(recognizer->debugger);
}
}
static void
endResync (pANTLR3_BASE_RECOGNIZER recognizer)
{
if (recognizer->debugger != NULL)
{
recognizer->debugger->endResync(recognizer->debugger);
}
}
/// Compute the error recovery set for the current rule.
/// Documentation below is from the Java implementation.
///
/// During rule invocation, the parser pushes the set of tokens that can
/// follow that rule reference on the stack; this amounts to
/// computing FIRST of what follows the rule reference in the
/// enclosing rule. This local follow set only includes tokens
/// from within the rule; i.e., the FIRST computation done by
/// ANTLR stops at the end of a rule.
//
/// EXAMPLE
//
/// When you find a "no viable alt exception", the input is not
/// consistent with any of the alternatives for rule r. The best
/// thing to do is to consume tokens until you see something that
/// can legally follow a call to r *or* any rule that called r.
/// You don't want the exact set of viable next tokens because the
/// input might just be missing a token--you might consume the
/// rest of the input looking for one of the missing tokens.
///
/// Consider grammar:
///
/// a : '[' b ']'
/// | '(' b ')'
/// ;
/// b : c '^' INT ;
/// c : ID
/// | INT
/// ;
///
/// At each rule invocation, the set of tokens that could follow
/// that rule is pushed on a stack. Here are the various "local"
/// follow sets:
///
/// FOLLOW(b1_in_a) = FIRST(']') = ']'
/// FOLLOW(b2_in_a) = FIRST(')') = ')'
/// FOLLOW(c_in_b) = FIRST('^') = '^'
///
/// Upon erroneous input "[]", the call chain is
///
/// a -> b -> c
///
/// and, hence, the follow context stack is:
///
/// depth local follow set after call to rule
/// 0 <EOF> a (from main())
/// 1 ']' b
/// 3 '^' c
///
/// Notice that ')' is not included, because b would have to have
/// been called from a different context in rule a for ')' to be
/// included.
///
/// For error recovery, we cannot consider FOLLOW(c)
/// (context-sensitive or otherwise). We need the combined set of
/// all context-sensitive FOLLOW sets--the set of all tokens that
/// could follow any reference in the call chain. We need to
/// resync to one of those tokens. Note that FOLLOW(c)='^' and if
/// we resync'd to that token, we'd consume until EOF. We need to
/// sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
/// In this case, for input "[]", LA(1) is in this set so we would
/// not consume anything and after printing an error rule c would
/// return normally. It would not find the required '^' though.
/// At this point, it gets a mismatched token error and throws an
/// exception (since LA(1) is not in the viable following token
/// set). The rule exception handler tries to recover, but finds
/// the same recovery set and doesn't consume anything. Rule b
/// exits normally returning to rule a. Now it finds the ']' (and
/// with the successful match exits errorRecovery mode).
///
/// So, you can see that the parser walks up call chain looking
/// for the token that was a member of the recovery set.
///
/// Errors are not generated in errorRecovery mode.
///
/// ANTLR's error recovery mechanism is based upon original ideas:
///
/// "Algorithms + Data Structures = Programs" by Niklaus Wirth
///
/// and
///
/// "A note on error recovery in recursive descent parsers":
/// http://portal.acm.org/citation.cfm?id=947902.947905
///
/// Later, Josef Grosch had some good ideas:
///
/// "Efficient and Comfortable Error Recovery in Recursive Descent
/// Parsers":
/// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
///
/// Like Grosch I implemented local FOLLOW sets that are combined
/// at run-time upon error to avoid overhead during parsing.
///
static pANTLR3_BITSET
computeErrorRecoverySet (pANTLR3_BASE_RECOGNIZER recognizer)
{
return recognizer->combineFollows(recognizer, ANTLR3_FALSE);
}
/// Compute the context-sensitive FOLLOW set for current rule.
/// Documentation below is from the Java runtime.
///
/// This is the set of token types that can follow a specific rule
/// reference given a specific call chain. You get the set of
/// viable tokens that can possibly come next (look ahead depth 1)
/// given the current call chain. Contrast this with the
/// definition of plain FOLLOW for rule r:
///
/// FOLLOW(r)={x | S=>*alpha r beta in G and x in FIRST(beta)}
///
/// where x in T* and alpha, beta in V*; T is set of terminals and
/// V is the set of terminals and non terminals. In other words,
/// FOLLOW(r) is the set of all tokens that can possibly follow
/// references to r in///any* sentential form (context). At
/// runtime, however, we know precisely which context applies as
/// we have the call chain. We may compute the exact (rather
/// than covering superset) set of following tokens.
///
/// For example, consider grammar:
///
/// stat : ID '=' expr ';' // FOLLOW(stat)=={EOF}
/// | "return" expr '.'
/// ;
/// expr : atom ('+' atom)* ; // FOLLOW(expr)=={';','.',')'}
/// atom : INT // FOLLOW(atom)=={'+',')',';','.'}
/// | '(' expr ')'
/// ;
///
/// The FOLLOW sets are all inclusive whereas context-sensitive
/// FOLLOW sets are precisely what could follow a rule reference.
/// For input input "i=(3);", here is the derivation:
///
/// stat => ID '=' expr ';'
/// => ID '=' atom ('+' atom)* ';'
/// => ID '=' '(' expr ')' ('+' atom)* ';'
/// => ID '=' '(' atom ')' ('+' atom)* ';'
/// => ID '=' '(' INT ')' ('+' atom)* ';'
/// => ID '=' '(' INT ')' ';'
///
/// At the "3" token, you'd have a call chain of
///
/// stat -> expr -> atom -> expr -> atom
///
/// What can follow that specific nested ref to atom? Exactly ')'
/// as you can see by looking at the derivation of this specific
/// input. Contrast this with the FOLLOW(atom)={'+',')',';','.'}.
///
/// You want the exact viable token set when recovering from a
/// token mismatch. Upon token mismatch, if LA(1) is member of
/// the viable next token set, then you know there is most likely
/// a missing token in the input stream. "Insert" one by just not
/// throwing an exception.
///
static pANTLR3_BITSET
computeCSRuleFollow (pANTLR3_BASE_RECOGNIZER recognizer)
{
return recognizer->combineFollows(recognizer, ANTLR3_FALSE);
}
/// Compute the current followset for the input stream.
///
static pANTLR3_BITSET
combineFollows (pANTLR3_BASE_RECOGNIZER recognizer, ANTLR3_BOOLEAN exact)
{
pANTLR3_BITSET followSet;
pANTLR3_BITSET localFollowSet;
ANTLR3_UINT32 top;
ANTLR3_UINT32 i;
top = recognizer->state->following->size(recognizer->state->following);
followSet = antlr3BitsetNew(0);
localFollowSet = NULL;
for (i = top; i>0; i--)
{
localFollowSet = antlr3BitsetLoad((pANTLR3_BITSET_LIST) recognizer->state->following->get(recognizer->state->following, i-1));
if (localFollowSet != NULL)
{
followSet->borInPlace(followSet, localFollowSet);
if (exact == ANTLR3_TRUE)
{
if (localFollowSet->isMember(localFollowSet, ANTLR3_EOR_TOKEN_TYPE) == ANTLR3_FALSE)
{
// Only leave EOR in the set if at top (start rule); this lets us know
// if we have to include the follow(start rule); I.E., EOF
//
if (i>1)
{
followSet->remove(followSet, ANTLR3_EOR_TOKEN_TYPE);
}
}
else
{
break; // Cannot see End Of Rule from here, just drop out
}
}
localFollowSet->free(localFollowSet);
localFollowSet = NULL;
}
}
if (localFollowSet != NULL)
{
localFollowSet->free(localFollowSet);
}
return followSet;
}
/// Standard/Example error display method.
/// No generic error message display funciton coudl possibly do everything correctly
/// for all possible parsers. Hence you are provided with this example routine, which
/// you should override in your parser/tree parser to do as you will.
///