Debian Codegraph @

src/tools/qlalr/examples/lambda/main.cpp

raw
1 // Copyright (C) 2016 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4 #include "lambda.h"
5
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9 #include "parser_table_p.h"
10
11 class Parser: protected parser_table
12 {
13 public:
14 union Value {
15 int ival;
16 // ### more...
17 };
18
19 public:
20 Parser();
21 ~Parser();
22
23 bool parse();
24
25 protected:
26 inline void reallocateStack();
27
28 inline Value &sym(int index)
29 { return sym_stack [tos + index - 1]; }
30
31 int nextToken();
32 void consumeRule(int ruleno);
33
34 protected:
35 int tos;
36 int stack_size;
37 Value *sym_stack;
38 int *state_stack;
39 int current_char;
40 unsigned in_tag: 1;
41 };
42
43 inline void Parser::reallocateStack()
44 {
45 if (! stack_size)
46 stack_size = 128;
47 else
48 stack_size <<= 1;
49
50 sym_stack = reinterpret_cast<Value*> (::realloc(sym_stack, stack_size * sizeof(Value)));
51 state_stack = reinterpret_cast<int*> (::realloc(state_stack, stack_size * sizeof(int)));
52 }
53
54 Parser::Parser():
55 tos(0),
56 stack_size(0),
57 sym_stack(0),
58 state_stack(0)
59 {
60 }
61
62 Parser::~Parser()
63 {
64 if (stack_size) {
65 ::free(sym_stack);
66 ::free(state_stack);
67 }
68 }
69
70 bool Parser::parse()
71 {
72 const int INITIAL_STATE = 0;
73
74 current_char = 0;
75 in_tag = 0;
76
77 int yytoken = -1;
78 reallocateStack();
79
80 tos = 0;
81 state_stack[++tos] = INITIAL_STATE;
82
83 while (true)
84 {
85 if (yytoken == -1 && - TERMINAL_COUNT != action_index [state_stack [tos]])
86 yytoken = nextToken();
87
88 int act = t_action (state_stack [tos], yytoken);
89
90 if (act == ACCEPT_STATE) {
91 return true;
92 }
93
94 else if (act > 0)
95 {
96 if (++tos == stack_size)
97 reallocateStack();
98
99 sym_stack [tos].ival = current_char; // ### save the token value here
100 state_stack [tos] = act;
101 yytoken = -1;
102 }
103
104 else if (act < 0)
105 {
106 int r = - act - 1;
107
108 tos -= rhs [r];
109 act = state_stack [tos++];
110 consumeRule (r);
111 state_stack [tos] = nt_action (act, lhs [r] - TERMINAL_COUNT);
112 }
113
114 else
115 break;
116 }
117
118 return false;
119 }
120
121
122 int Parser::nextToken()
123 {
124 static int tokens[] = { ID, ID, ID, EOF_SYMBOL };
125 static int *tk = tokens;
126
127 return *tk++;
128 }
129
130 void Parser::consumeRule(int ruleno)
131 {
132 switch (ruleno) {
133 case Symbol:
134 printf("symbol\n");
135 break;
136 case SubExpression:
137 printf("sub-expr\n");
138 break;
139 case Appl:
140 printf("appl\n");
141 break;
142 case Abstr:
143 printf("abstr\n");
144 break;
145 }
146 }
147
148 /////////////////////////////
149 // entry point
150 /////////////////////////////
151 int main()
152 {
153 Parser parser;
154
155 if (parser.parse())
156 printf ("OK\n");
157 else
158 printf ("KO\n");
159 }
160
161