forked from mideind/GreynirServer
/
eparser.cpp
executable file
·1349 lines (1132 loc) · 34.8 KB
/
eparser.cpp
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
/*
Reynir: Natural language processing for Icelandic
C++ Earley parser module
Copyright (c) 2015 Vilhjalmur Thorsteinsson
All rights reserved
See the accompanying README.md file for further licensing and copyright information.
This module implements an optimized Earley parser in C++.
It is designed to be called from Python code with
already parsed and packed grammar structures.
*/
// #define DEBUG
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <time.h>
#include "eparser.h"
// Local implementation classes
class AllocReporter {
// A debugging aid to diagnose and report memory leaks
private:
protected:
public:
AllocReporter(void);
~AllocReporter(void);
void report(void) const;
};
void printAllocationReport(void)
{
AllocReporter reporter;
reporter.report();
}
class State {
// Parser state, contained within a Column
friend class AllocReporter;
private:
INT m_iNt; // Nonterminal (negative index)
Production* m_pProd; // Production
UINT m_nDot; // Dot (position in production)
UINT m_nStart; // Start token index
Node* m_pw; // Tree node
State* m_pNext; // Next state within column
State* m_pNtNext; // Next state with same Nt at prod[dot]
static AllocCounter ac;
protected:
public:
State(INT iNt, UINT nDot, Production* pProd, UINT nStart, Node* pw);
State(State*, Node* pw);
~State(void);
void increment(Node* pwNew);
void setNext(State*);
void setNtNext(State*);
State* getNext(void) const
{ return this->m_pNext; }
State* getNtNext(void) const
{ return this->m_pNtNext; }
UINT getHash(void) const
{
return ((UINT)this->m_iNt) ^
((UINT)((uintptr_t)this->m_pProd) & 0xFFFFFFFF) ^
(this->m_nDot << 7) ^ (this->m_nStart << 9) ^
(((UINT)((uintptr_t)this->m_pw) & 0xFFFFFFFF) << 1);
}
BOOL operator==(const State& other) const
{
const State& t = *this;
return t.m_iNt == other.m_iNt &&
t.m_pProd == other.m_pProd &&
t.m_nDot == other.m_nDot &&
t.m_nStart == other.m_nStart &&
t.m_pw == other.m_pw;
}
// Get the terminal or nonterminal at the dot
INT prodDot(void) const
{ return (*this->m_pProd)[this->m_nDot]; }
INT getNt(void) const
{ return this->m_iNt; }
UINT getStart(void) const
{ return this->m_nStart; }
UINT getDot(void) const
{ return this->m_nDot; }
Production* getProd(void) const
{ return this->m_pProd; }
Node* getNode(void) const
{ return this->m_pw; }
Node* getResult(INT iStartNt) const;
};
class Column {
// An Earley column
// A Parser cointains one Column for each token in the input, plus a sentinel
friend class AllocReporter;
private:
// The contained States are stored an array of hash bins
static const UINT HASH_BINS = 499; // Prime number
struct HashBin {
State* m_pHead; // The first state in this hash bin
State* m_pTail; // The last state in this hash bin
State* m_pEnum; // The last enumerated state in this hash bin
};
UINT m_nToken; // The input token associated with this column
State** m_pNtStates; // States linked by the nonterminal at their prod[dot]
MatchingFunc m_pMatchingFunc; // Pointer to the token/terminal matching function
BYTE* m_abCache; // Matching cache, a true/false flag for every terminal in the grammar
BYTE* m_abSeen; // Flag whether each nonterminal's productions have already been added
HashBin m_aHash[HASH_BINS]; // The hash bin array
UINT m_nEnumBin; // Round robin used during enumeration of states
static AllocCounter ac;
protected:
public:
Column(Parser*, UINT nToken);
~Column(void);
UINT getToken(void) const
{ return this->m_nToken; }
// Add a state to the column, at the end of the state list
BOOL addState(State* p);
State* nextState(void);
void resetEnum(void);
State* getNtHead(INT iNt) const;
BOOL markSeen(INT iNt);
BOOL matches(UINT nHandle, UINT nTerminal) const;
};
class HNode {
// Represents an element in the H set,
// corresponding to a completed nullable
// production of the associated nonterminal
friend class AllocReporter;
private:
INT m_iNt;
Node* m_pv;
HNode* m_pNext;
static AllocCounter ac;
protected:
public:
HNode(INT iNt, Node* pv)
: m_iNt(iNt), m_pv(pv)
{ HNode::ac++; }
~HNode()
{ HNode::ac--; }
INT getNt(void) const
{ return this->m_iNt; }
Node* getV(void) const
{ return this->m_pv; }
HNode* getNext(void) const
{ return this->m_pNext; }
void setNext(HNode* ph)
{ this->m_pNext = ph; }
};
AllocCounter HNode::ac;
class NodeDict {
// Dictionary to map labels to node pointers
friend class AllocReporter;
private:
struct NdEntry {
Node* pNode;
NdEntry* pNext;
};
NdEntry* m_pHead;
static AllocCounter acLookups;
protected:
public:
NodeDict(void);
~NodeDict(void);
Node* lookupOrAdd(const Label&);
void reset(void);
};
AllocCounter NodeDict::acLookups;
AllocCounter Nonterminal::ac;
Nonterminal::Nonterminal(const WCHAR* pwzName)
: m_pwzName(NULL), m_pProd(NULL)
{
Nonterminal::ac++;
this->m_pwzName = pwzName ? ::wcsdup(pwzName) : NULL;
}
Nonterminal::~Nonterminal(void)
{
if (this->m_pwzName)
free(this->m_pwzName);
// Delete the associated productions
Production* p = this->m_pProd;
while (p) {
Production* pNext = p->getNext();
delete p;
p = pNext;
}
Nonterminal::ac--;
}
void Nonterminal::addProduction(Production* p)
{
// Add a production at the head of the linked list
p->setNext(this->m_pProd);
this->m_pProd = p;
}
AllocCounter Production::ac;
Production::Production(UINT nId, UINT nPriority, UINT n, const INT* pList)
: m_nId(nId), m_nPriority(nPriority), m_n(n), m_pList(NULL), m_pNext(NULL)
{
Production::ac++;
if (n > 0) {
this->m_pList = new INT[n];
::memcpy((void*)this->m_pList, (void*)pList, n * sizeof(INT));
}
}
Production::~Production(void) {
// Destructor
if (this->m_pList)
delete [] this->m_pList;
Production::ac--;
}
void Production::setNext(Production* p)
{
this->m_pNext = p;
}
INT Production::operator[] (UINT nDot) const
{
// Return the terminal or nonterminal at prod[dot]
// or 0 if indexing past the end of the production
return nDot < this->m_n ? this->m_pList[nDot] : 0;
}
// States are allocated in chunks, rather than individually
static const UINT CHUNK_SIZE = 2048 * sizeof(State);
struct StateChunk {
StateChunk* m_pNext;
UINT m_nIndex;
BYTE m_ast[CHUNK_SIZE];
StateChunk(StateChunk* pNext)
: m_pNext(pNext), m_nIndex(0)
{ memset(this->m_ast, 0, CHUNK_SIZE); }
};
static AllocCounter acChunks;
void* operator new(size_t nBytes, StateChunk*& pChunkHead)
{
ASSERT(nBytes == sizeof(State));
// Allocate a new place for a state in a state chunk
StateChunk* p = pChunkHead;
if (!p || (p->m_nIndex + nBytes >= CHUNK_SIZE)) {
StateChunk* pNew = new StateChunk(p);
acChunks++;
pChunkHead = p = pNew;
}
void* pPlace = (void*)(p->m_ast + p->m_nIndex);
p->m_nIndex += nBytes;
ASSERT(p->m_nIndex <= CHUNK_SIZE);
return pPlace;
}
static void freeStates(StateChunk*& pChunkHead)
{
StateChunk* pChunk = pChunkHead;
while (pChunk) {
StateChunk* pNext = pChunk->m_pNext;
delete pChunk;
acChunks--;
pChunk = pNext;
}
pChunkHead = NULL;
}
static UINT nDiscardedStates = 0;
static void discardState(StateChunk* pChunkHead, State* pState)
{
ASSERT(pChunkHead->m_nIndex >= sizeof(State));
ASSERT(pChunkHead->m_ast + pChunkHead->m_nIndex - sizeof(State) == (BYTE*)pState);
pState->~State();
// Go back one location in the chunk
pChunkHead->m_nIndex -= sizeof(State);
nDiscardedStates++;
}
AllocCounter State::ac;
State::State(INT iNt, UINT nDot, Production* pProd, UINT nStart, Node* pw)
: m_iNt(iNt), m_pProd(pProd), m_nDot(nDot), m_nStart(nStart), m_pw(pw),
m_pNext(NULL), m_pNtNext(NULL)
{
State::ac++;
if (pw)
pw->addRef();
}
State::State(State* ps, Node* pw)
: m_iNt(ps->m_iNt), m_pProd(ps->m_pProd), m_nDot(ps->m_nDot + 1),
m_nStart(ps->m_nStart), m_pw(pw), m_pNext(NULL), m_pNtNext(NULL)
{
// Create a new state by advancing one item forward from an existing state
State::ac++;
if (pw)
pw->addRef();
}
State::~State(void)
{
if (this->m_pw) {
this->m_pw->delRef();
this->m_pw = NULL;
}
State::ac--;
}
void State::increment(Node* pwNew)
{
// 'Increment' the state, i.e. move the dot right by one step
// and put in a new node pointer
this->m_nDot++;
this->m_pNext = NULL;
ASSERT(this->m_pNtNext == NULL);
if (pwNew)
pwNew->addRef(); // Do this first, for safety
if (this->m_pw)
this->m_pw->delRef();
this->m_pw = pwNew;
}
void State::setNext(State* p)
{
this->m_pNext = p;
}
void State::setNtNext(State* p)
{
this->m_pNtNext = p;
}
Node* State::getResult(INT iStartNt) const
{
if (this->m_iNt == iStartNt && this->prodDot() == 0 &&
this->m_nStart == 0)
return this->m_pw;
return NULL;
}
AllocCounter Column::ac;
Column::Column(Parser* pParser, UINT nToken)
: m_nToken(nToken),
m_pNtStates(NULL),
m_pMatchingFunc(pParser->getMatchingFunc()),
m_abCache(NULL),
m_abSeen(NULL),
m_nEnumBin(0)
{
Column::ac++;
ASSERT(this->m_pMatchingFunc != NULL);
UINT nNonterminals = pParser->getNumNonterminals();
UINT nTerminals = pParser->getNumTerminals();
// Initialize array of linked lists by nonterminal at prod[dot]
this->m_pNtStates = new State* [nNonterminals];
memset(this->m_pNtStates, 0, nNonterminals * sizeof(State*));
// Initialize the matching cache to zero
this->m_abCache = new BYTE[nTerminals + 1];
memset(this->m_abCache, 0, (nTerminals + 1) * sizeof(BYTE));
// Initialize the seen array to zero
this->m_abSeen = new BYTE[nNonterminals];
memset(this->m_abSeen, 0, nNonterminals * sizeof(BYTE));
// Initialize the hash bins to zero
memset(this->m_aHash, 0, sizeof(HashBin) * HASH_BINS);
}
Column::~Column(void)
{
// Destroy the states still owned by the column
for (UINT i = 0; i < HASH_BINS; i++) {
// Clean up each hash bin in turn
HashBin* ph = &this->m_aHash[i];
State* q = ph->m_pHead;
while (q) {
State* pNext = q->getNext();
ASSERT(pNext != NULL || q == ph->m_pTail);
// The states are allocated via placement new, so
// they are not deleted ordinarily - we just run their destructor
q->~State();
q = pNext;
}
ph->m_pHead = NULL;
ph->m_pTail = NULL;
}
// Delete array of linked lists by nonterminal at prod[dot]
delete [] this->m_pNtStates;
// Delete matching cache
delete [] this->m_abCache;
// Delete seen array
delete [] this->m_abSeen;
Column::ac--;
}
BOOL Column::addState(State* p)
{
// Check to see whether an identical state is
// already present in the hash bin
UINT nBin = p->getHash() % HASH_BINS;
HashBin* ph = &this->m_aHash[nBin];
State* q = ph->m_pHead;
while (q) {
if ((*q) == (*p))
// Identical state: we're done
return false;
q = q->getNext();
}
// Not already found: link into place within the hash bin
p->setNext(NULL);
if (!ph->m_pHead) {
// Establish linked list with one item
ph->m_pHead = ph->m_pTail = p;
}
else {
// Link the new element at the tail
ph->m_pTail->setNext(p);
ph->m_pTail = p;
}
// Get the item at prod[dot]
INT iItem = p->prodDot();
if (iItem < 0) {
// Nonterminal: add to linked list
UINT nIndex = ~((UINT)iItem);
State*& psHead = this->m_pNtStates[nIndex];
p->setNtNext(psHead);
psHead = p;
}
return true;
}
State* Column::nextState(void)
{
// Start our enumeration attempt from the last bin we looked at
UINT n = this->m_nEnumBin;
do {
HashBin* ph = &this->m_aHash[n];
if (!ph->m_pEnum && ph->m_pHead) {
// Haven't enumerated from this one before,
// but it has an entry: return it
ph->m_pEnum = ph->m_pHead;
this->m_nEnumBin = n;
return ph->m_pEnum;
}
// Try the next item after the one we last returned
State* pNext = ph->m_pEnum ? ph->m_pEnum->getNext() : NULL;
if (pNext) {
// There is such an item: return it
ph->m_pEnum = pNext;
this->m_nEnumBin = n;
return pNext;
}
// Can't enumerate any more from this bin: go to the next one
n = (n + 1) % HASH_BINS;
} while (n != this->m_nEnumBin);
// Gone full circle: Nothing more to enumerate
return NULL;
}
void Column::resetEnum(void)
{
// Start a fresh enumeration
for (UINT i = 0; i < HASH_BINS; i++)
this->m_aHash[i].m_pEnum = NULL;
this->m_nEnumBin = 0;
}
State* Column::getNtHead(INT iNt) const
{
UINT nIndex = ~((UINT)iNt);
return this->m_pNtStates[nIndex];
}
BOOL Column::matches(UINT nHandle, UINT nTerminal) const
{
if (this->m_nToken == (UINT)-1)
// Sentinel token in last column: never matches
return false;
if (this->m_abCache[nTerminal] & 0x80)
// We already have a cached result for this terminal
return (BOOL)(this->m_abCache[nTerminal] & 0x01);
// Not cached: obtain a result and store it in the cache
BOOL b = this->m_pMatchingFunc(nHandle, this->m_nToken, nTerminal) != 0;
// Mark our cache
this->m_abCache[nTerminal] = b ? (BYTE)0x81 : (BYTE)0x80;
return b;
}
BOOL Column::markSeen(INT iNt)
{
// Guard to ensure that each nonterminal is only added once to the column
ASSERT(iNt < 0);
UINT nIndex = ~((UINT)iNt);
BOOL b = this->m_abSeen[nIndex] == 0;
this->m_abSeen[nIndex] = 1;
return b;
}
class File {
// Safe wrapper for FILE*
private:
FILE* m_f;
public:
File(const CHAR* pszFilename, const CHAR* pszMode)
{ this->m_f = fopen(pszFilename, pszMode); }
~File(void)
{ if (this->m_f) fclose(this->m_f); }
operator FILE*() const
{ return this->m_f; }
operator BOOL() const
{ return this->m_f != NULL; }
UINT read(void* pb, UINT nLen)
{ return this->m_f ? fread(pb, 1, nLen, this->m_f) : 0; }
UINT write(void* pb, UINT nLen)
{ return this->m_f ? fwrite(pb, 1, nLen, this->m_f) : 0; }
BOOL read_UINT(UINT& n)
{ return this->read(&n, sizeof(UINT)) == sizeof(UINT); }
BOOL read_INT(INT& i)
{ return this->read(&i, sizeof(INT)) == sizeof(INT); }
};
AllocCounter Grammar::ac;
Grammar::Grammar(UINT nNonterminals, UINT nTerminals, INT iRoot)
: m_nNonterminals(nNonterminals), m_nTerminals(nTerminals), m_iRoot(iRoot), m_nts(NULL)
{
Grammar::ac++;
this->m_nts = new Nonterminal*[nNonterminals];
memset(this->m_nts, 0, nNonterminals * sizeof(Nonterminal*));
}
Grammar::Grammar(void)
: m_nNonterminals(0), m_nTerminals(0), m_iRoot(0), m_nts(NULL)
{
Grammar::ac++;
}
Grammar::~Grammar(void)
{
this->reset();
Grammar::ac--;
}
void Grammar::reset(void)
{
for (UINT i = 0; i < this->m_nNonterminals; i++)
if (this->m_nts[i])
delete this->m_nts[i];
if (this->m_nts) {
delete [] this->m_nts;
this->m_nts = NULL;
}
this->m_nNonterminals = 0;
this->m_nTerminals = 0;
this->m_iRoot = 0;
}
class GrammarResetter {
// Resets a grammar to a known zero state unless
// explicitly disarmed
private:
Grammar* m_pGrammar;
public:
GrammarResetter(Grammar* pGrammar)
: m_pGrammar(pGrammar)
{ }
~GrammarResetter(void)
{ if (this->m_pGrammar) this->m_pGrammar->reset(); }
void disarm(void)
{ this->m_pGrammar = NULL; }
};
BOOL Grammar::readBinary(const CHAR* pszFilename)
{
// Attempt to read grammar from binary file.
// Returns true if successful, otherwise false.
#ifdef DEBUG
printf("Reading binary grammar file %s\n", pszFilename);
#endif
this->reset();
File f(pszFilename, "rb");
if (!f)
return false;
const UINT SIGNATURE_LENGTH = 16;
BYTE abSignature[SIGNATURE_LENGTH];
UINT n = f.read(abSignature, sizeof(abSignature));
if (n < sizeof(abSignature))
return false;
// Check the signature - should start with 'Reynir '
if (memcmp(abSignature, "Reynir ", 7) != 0) {
#ifdef DEBUG
printf("Signature mismatch\n");
#endif
return false;
}
UINT nNonterminals, nTerminals;
if (!f.read_UINT(nTerminals))
return false;
if (!f.read_UINT(nNonterminals))
return false;
#ifdef DEBUG
printf("Reading %u terminals and %u nonterminals\n", nTerminals, nNonterminals);
#endif
if (!nNonterminals)
// No nonterminals to read: we're done
return true;
INT iRoot;
if (!f.read_INT(iRoot))
return false;
#ifdef DEBUG
printf("Root nonterminal index is %d\n", iRoot);
#endif
// Initialize the nonterminals array
Nonterminal** ppnts = new Nonterminal*[nNonterminals];
memset(ppnts, 0, nNonterminals * sizeof(Nonterminal*));
this->m_nts = ppnts;
this->m_nNonterminals = nNonterminals;
this->m_nTerminals = nTerminals;
this->m_iRoot = iRoot;
// Ensure we clean up properly in case of exit with error
GrammarResetter resetter(this);
// Loop through the nonterminals
for (n = 0; n < nNonterminals; n++) {
// How many productions?
UINT nLenPlist;
if (!f.read_UINT(nLenPlist))
return false;
Nonterminal* pnt = new Nonterminal(L"");
// Loop through the productions
for (UINT j = 0; j < nLenPlist; j++) {
UINT nId;
if (!f.read_UINT(nId))
return false;
UINT nPriority;
if (!f.read_UINT(nPriority))
return false;
UINT nLenProd;
if (!f.read_UINT(nLenProd))
return false;
const UINT MAX_LEN_PROD = 256;
if (nLenProd > MAX_LEN_PROD) {
// Production too long
#ifdef DEBUG
printf("Production too long\n");
#endif
return false;
}
// Read the production
INT aiProd[MAX_LEN_PROD];
f.read(aiProd, nLenProd * sizeof(INT));
// Create a fresh production object
Production* pprod = new Production(nId, nPriority, nLenProd, aiProd);
// Add it to the nonterminal
pnt->addProduction(pprod);
}
// Add the nonterminal to the grammar
this->setNonterminal(-1 -(INT)n, pnt);
}
#ifdef DEBUG
printf("Reading completed\n");
fflush(stdout);
#endif
// No error: we disarm the resetter
resetter.disarm();
return true;
}
void Grammar::setNonterminal(INT iIndex, Nonterminal* pnt)
{
// iIndex is negative
ASSERT(iIndex < 0);
UINT nIndex = ~((UINT)iIndex); // -1 becomes 0, -2 becomes 1, etc.
ASSERT(nIndex < this->m_nNonterminals);
if (nIndex < this->m_nNonterminals)
this->m_nts[nIndex] = pnt;
}
Nonterminal* Grammar::operator[] (INT iIndex) const
{
// Return the nonterminal with index nIndex (1-based)
ASSERT(iIndex < 0);
UINT nIndex = ~((UINT)iIndex); // -1 becomes 0, -2 becomes 1, etc.
return (nIndex < this->m_nNonterminals) ? this->m_nts[nIndex] : NULL;
}
const WCHAR* Grammar::nameOfNt(INT iNt) const
{
Nonterminal* pnt = (*this)[iNt];
return pnt ? pnt->getName() : L"[None]";
}
AllocCounter Node::ac;
Node::Node(const Label& label)
: m_label(label), m_pHead(NULL), m_nRefCount(1)
{
Node::ac++;
}
Node::~Node(void)
{
FamilyEntry* p = this->m_pHead;
while (p) {
FamilyEntry* pNext = p->pNext;
if (p->p1)
p->p1->delRef();
if (p->p2)
p->p2->delRef();
delete p;
p = pNext;
}
Node::ac--;
}
void Node::delRef(void)
{
ASSERT(this->m_nRefCount > 0);
if (!--this->m_nRefCount)
delete this;
}
void Node::addFamily(Production* pProd, Node* pW, Node* pV)
{
// pW may be NULL, or both may be NULL if epsilon
FamilyEntry* p = this->m_pHead;
while (p) {
if (p->pProd == pProd && p->p1 == pW && p->p2 == pV)
// We already have the same family entry
return;
p = p->pNext;
}
// Not already there: create a new entry
p = new FamilyEntry();
p->pProd = pProd;
p->p1 = pW;
p->p2 = pV;
if (pW)
pW->addRef();
if (pV)
pV->addRef();
p->pNext = this->m_pHead;
this->m_pHead = p;
}
void Node::_dump(Grammar* pGrammar, UINT nIndent)
{
for (UINT i = 0; i < nIndent; i++)
printf(" ");
Production* pProd = this->m_label.m_pProd;
UINT nDot = this->m_label.m_nDot;
INT iDotProd = pProd ? (*pProd)[nDot] : 0;
INT iNt = this->m_label.m_iNt;
const WCHAR* pwzName;
WCHAR wchBuf[16];
if (iNt < 0) {
// Nonterminal
pwzName = pGrammar->nameOfNt(iNt);
if (!pwzName || wcslen(pwzName) == 0) {
swprintf(wchBuf, 16, L"[Nt %d]", iNt);
pwzName = wchBuf;
}
}
else {
// Token
swprintf(wchBuf, 16, L"[Token %u]", (UINT)iNt);
pwzName = wchBuf;
}
printf("Label: %ls %u %d %u %u\n",
pwzName,
nDot,
iDotProd,
this->m_label.m_nI,
this->m_label.m_nJ);
FamilyEntry* p = this->m_pHead;
UINT nOption = 0;
while (p) {
if (nOption || p->pNext) {
// Don't print 'Option 1' if there is only one option
for (UINT i = 0; i < nIndent; i++)
printf(" ");
printf("Option %u\n", nOption + 1);
}
if (p->p1)
p->p1->_dump(pGrammar, nIndent + 1);
if (p->p2)
p->p2->_dump(pGrammar, nIndent + 1);
p = p->pNext;
nOption++;
}
fflush(stdout);
}
void Node::dump(Grammar* pGrammar)
{
this->_dump(pGrammar, 0);
}
UINT Node::numCombinations(Node* pNode)
{
if (!pNode || pNode->m_label.m_iNt >= 0)
return 1;
UINT nComb = 0;
FamilyEntry* p = pNode->m_pHead;
while (p) {
UINT n1 = p->p1 ? Node::numCombinations(p->p1) : 1;
UINT n2 = p->p2 ? Node::numCombinations(p->p2) : 1;
nComb += n1 * n2;
p = p->pNext;
}
return nComb == 0 ? 1 : nComb;
}
NodeDict::NodeDict(void)
: m_pHead(NULL)
{
}
NodeDict::~NodeDict(void)
{
this->reset();
}
Node* NodeDict::lookupOrAdd(const Label& label)
{
// If the label is already found in the NodeDict,
// return the corresponding node.
// Otherwise, create a new node, add it to the dict
// under the label, and return it.
NodeDict::acLookups++;
NdEntry* p = this->m_pHead;
while (p) {
if (p->pNode->hasLabel(label))
return p->pNode;
p = p->pNext;
}
// Not found: add to the dict
p = new NdEntry();
p->pNode = new Node(label);
p->pNext = this->m_pHead;
this->m_pHead = p;
return p->pNode;
}
void NodeDict::reset(void)
{
NdEntry* p = this->m_pHead;
while (p) {
NdEntry* pNext = p->pNext;
p->pNode->delRef();
delete p;
p = pNext;
}
this->m_pHead = NULL;
}
Parser::Parser(Grammar* p, MatchingFunc pMatchingFunc)
: m_pGrammar(p), m_pMatchingFunc(pMatchingFunc)
{
ASSERT(this->m_pGrammar != NULL);
ASSERT(this->m_pMatchingFunc != NULL);
}
Parser::~Parser(void)
{
}
Node* Parser::makeNode(State* pState, UINT nEnd, Node* pV, NodeDict& ndV)
{
UINT nDot = pState->getDot() + 1;
Production* pProd = pState->getProd();
UINT nLen = pProd->getLength();
if (nDot == 1 && nLen >= 2)
return pV;
INT iNtB = pState->getNt();
UINT nStart = pState->getStart();
Node* pW = pState->getNode();
Production* pProdLabel = pProd;
if (nDot >= nLen) {
// Completed production: label by nonterminal only
nDot = 0;
pProdLabel = NULL;
}
Label label(iNtB, nDot, pProdLabel, nStart, nEnd);
Node* pY = ndV.lookupOrAdd(label);
pY->addFamily(pProd, pW, pV); // pW may be NULL
return pY;
}