Debian Codegraph @

src/tools/qlalr/examples/qparser/qparser.h

raw
1 // Copyright (C) 2016 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4 #ifndef QPARSER_H
5 #define QPARSER_H
6
7 #include <QtCore/QSharedDataPointer>
8 #include <QtCore/QVarLengthArray>
9
10 template <typename _Parser, typename _Table, typename _Value = int>
11 class QParser: protected _Table
12 {
13 public:
14 QParser();
15 ~QParser();
16
17 bool parse();
18
19 inline _Value &sym(int index);
20
21 private:
22 inline int nextToken()
23 {
24 return static_cast<_Parser*> (this)->nextToken();
25 }
26
27 inline void consumeRule(int rule)
28 {
29 static_cast<_Parser*> (this)->consumeRule(rule);
30 }
31
32 enum { DefaultStackSize = 128 };
33
34 struct Data: public QSharedData
35 {
36 Data(): stackSize (DefaultStackSize), tos (0) {}
37
38 QVarLengthArray<int, DefaultStackSize> stateStack;
39 QVarLengthArray<_Value, DefaultStackSize> parseStack;
40 int stackSize;
41 int tos;
42
43 void reallocateStack() {
44 stackSize <<= 1;
45 stateStack.resize(stackSize);
46 parseStack.resize(stackSize);
47 }
48 };
49
50 QSharedDataPointer<Data> d;
51 };
52
53 template <typename _Parser, typename _Table, typename _Value>
54 inline _Value &QParser<_Parser, _Table, _Value>::sym(int n)
55 {
56 return d->parseStack [d->tos + n - 1];
57 }
58
59 template <typename _Parser, typename _Table, typename _Value>
60 QParser<_Parser, _Table, _Value>::QParser():
61 d(new Data())
62 {
63 }
64
65 template <typename _Parser, typename _Table, typename _Value>
66 QParser<_Parser, _Table, _Value>::~QParser()
67 {
68 }
69
70 template <typename _Parser, typename _Table, typename _Value>
71 bool QParser<_Parser, _Table, _Value>::parse()
72 {
73 const int INITIAL_STATE = 0;
74
75 d->tos = 0;
76 d->reallocateStack();
77
78 int act = d->stateStack[++d->tos] = INITIAL_STATE;
79 int token = -1;
80
81 forever {
82 if (token == -1 && - _Table::TERMINAL_COUNT != _Table::action_index[act])
83 token = nextToken();
84
85 act = _Table::t_action(act, token);
86
87 if (d->stateStack[d->tos] == _Table::ACCEPT_STATE)
88 return true;
89
90 else if (act > 0) {
91 if (++d->tos == d->stackSize)
92 d->reallocateStack();
93
94 d->parseStack[d->tos] = d->parseStack[d->tos - 1];
95 d->stateStack[d->tos] = act;
96 token = -1;
97 }
98
99 else if (act < 0) {
100 int r = - act - 1;
101 d->tos -= _Table::rhs[r];
102 act = d->stateStack[d->tos++];
103 consumeRule(r);
104 act = d->stateStack[d->tos] = _Table::nt_action(act, _Table::lhs[r] - _Table::TERMINAL_COUNT);
105 }
106
107 else break;
108 }
109
110 return false;
111 }
112
113
114 #endif // QPARSER_H