parser: add Parser::concat to factorize code
[nit.git] / src / parser / xss / parser.xss
1 $ // This file is part of NIT ( http://www.nitlanguage.org ).
2 $ //
3 $ // Copyright 2008 Jean Privat <jean@pryen.org>
4 $ // Based on algorithms developped for ( http://www.sablecc.org/ ).
5 $ //
6 $ // Licensed under the Apache License, Version 2.0 (the "License");
7 $ // you may not use this file except in compliance with the License.
8 $ // You may obtain a copy of the License at
9 $ //
10 $ //     http://www.apache.org/licenses/LICENSE-2.0
11 $ //
12 $ // Unless required by applicable law or agreed to in writing, software
13 $ // distributed under the License is distributed on an "AS IS" BASIS,
14 $ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 $ // See the License for the specific language governing permissions and
16 $ // limitations under the License.
17
18 $ template make_parser()
19
20 # State of the parser automata as stored in the parser stack.
21 private class State
22         # The internal state number
23         readable writable var _state: Int
24
25         # The node stored with the state in the stack
26         readable writable var _nodes: nullable Object
27
28         init(state: Int, nodes: nullable Object)
29         do
30                 _state = state
31                 _nodes = nodes
32         end
33 end
34
35 class Parser
36 special ParserTable
37         # Associated lexer
38         var _lexer: Lexer
39
40         # Stack of pushed states and productions
41         var _stack: Array[State]
42
43         # Position in the stack
44         var _stack_pos: Int
45
46         # Create a new parser based on a given lexer
47         init(lexer: Lexer)
48         do
49                 _lexer = lexer
50                 _stack = new Array[State]
51                 _stack_pos = -1
52                 build_goto_table
53                 build_action_table
54                 build_reduce_table
55         end
56
57         # Do a transition in the automata
58         private fun go_to(index: Int): Int
59         do
60                 var state = state
61                 var table = _goto_table[index]
62                 var low = 1
63                 var high = table.length/2 - 1
64
65                 while low <= high do
66                         var middle = (low + high) / 2
67                         var subindex = middle * 2
68
69                         if state < table[subindex] then
70                                 high = middle - 1
71                         else if state > table[subindex] then
72                                 low = middle + 1
73                         else
74                                 return table[subindex + 1]
75                         end
76                 end
77
78                 return table[1] # Default value
79         end
80
81         # Push someting in the state stack
82         private fun push(numstate: Int, list_node: nullable Object)
83         do
84                 var pos = _stack_pos + 1
85                 _stack_pos = pos
86                 if pos < _stack.length then
87                         var state = _stack[pos]
88                         state.state = numstate
89                         state.nodes = list_node
90                 else
91                         _stack.push(new State(numstate, list_node))
92                 end
93         end
94
95         # The current state
96         private fun state: Int
97         do
98                 return _stack[_stack_pos].state
99         end
100
101         # Pop something from the stack state
102         private fun pop: nullable Object
103         do
104                 var res = _stack[_stack_pos].nodes
105                 _stack_pos = _stack_pos -1
106                 return res
107         end
108
109         # Build and return a full AST.
110         fun parse: Start
111         do
112                 push(0, null)
113
114                 var lexer = _lexer
115                 loop
116                         var token = lexer.peek
117                         if token isa PError then
118                                 return new Start(null, token)
119                         end
120
121                         var index = token.parser_index
122                         var table = _action_table[state]
123                         var action_type = table[1]
124                         var action_value = table[2]
125
126                         var low = 1
127                         var high = table.length/3 - 1
128
129                         while low <= high do
130                                 var middle = (low + high) / 2
131                                 var subindex = middle * 3
132
133                                 if index < table[subindex] then
134                                         high = middle - 1
135                                 else if index > table[subindex] then
136                                         low = middle + 1
137                                 else
138                                         action_type = table[subindex + 1]
139                                         action_value = table[subindex + 2]
140                                         high = low -1 # break
141                                 end
142                         end
143
144                         if action_type == 0 then # SHIFT
145                                 push(action_value, lexer.next)
146                         else if action_type == 1 then # REDUCE
147                                 _reduce_table[action_value].action(self)
148                         else if action_type == 2 then # ACCEPT
149                                 var node2 = lexer.next
150                                 assert node2 isa EOF
151                                 var node1 = pop
152                                 assert node1 isa ${/parser/prods/prod/@ename}
153                                 var node = new Start(node1, node2)
154                                 (new ComputeProdLocationVisitor).enter_visit(node)
155                                 return node
156                         else if action_type == 3 then # ERROR
157                                 var node2 = new PError.init_error("Syntax error: unexpected token.", token.location)
158                                 var node = new Start(null, node2)
159                                 return node
160                         end
161                         if false then break # FIXME remove once unreach loop exits are in c_src
162                 end
163                 abort # FIXME remove once unreach loop exits are in c_src
164         end
165
166         var _reduce_table: Array[ReduceAction]
167         private fun build_reduce_table
168         do
169                 _reduce_table = new Array[ReduceAction].with_items(
170 $ foreach {rules/rule}
171                         new ReduceAction@index[-sep ','-]
172 $ end foreach
173                 )
174         end
175 end
176
177 redef class Prod
178         # Location on the first token after the start of a production
179         # So outside the production for epilon production
180         var _first_location: nullable Location
181
182         # Location of the last token before the end of a production
183         # So outside the production for epilon production
184         var _last_location: nullable Location
185 end
186
187 # Find location of production nodes
188 # Uses existing token locations to infer location of productions.
189 private class ComputeProdLocationVisitor
190 special Visitor
191         # Currenlty visited productions that need a first token
192         var _need_first_prods: Array[Prod] = new Array[Prod]
193
194         # Already visited epsilon productions that waits something after them
195         var _need_after_epsilons: Array[Prod] = new Array[Prod]
196
197         # Already visited epsilon production that waits something before them
198         var _need_before_epsilons: Array[Prod] = new Array[Prod]
199
200         # Location of the last visited token in the current production
201         var _last_location: nullable Location = null
202
203         redef fun visit(n: nullable PNode)
204         do
205                 if n == null then
206                         return
207                 else if n isa Token then
208                         var loc = n.location
209                         _last_location = loc
210
211                         # Add a first token to productions that need one
212                         for no in _need_first_prods do
213                                 no._first_location = loc
214                         end
215                         _need_first_prods.clear
216
217                         # Find location for already visited epsilon production that need one
218                         for no in _need_after_epsilons do
219                                 # Epsilon production that is in the middle of a non-epsilon production
220                                 # The epsilon production has both a token before and after it
221                                 var endl = loc
222                                 var startl = no._last_location
223                                 no.location = new Location(endl.file, startl.line_end, endl.line_start, startl.column_end, endl.column_start)
224                         end
225                         _need_after_epsilons.clear
226                 else
227                         assert n isa Prod
228                         _need_first_prods.add(n)
229
230                         var old_last = _last_location
231                         _last_location = null
232                         n.visit_all(self)
233                         var endl = _last_location
234                         if endl == null then _last_location = old_last
235
236                         n._last_location = endl
237                         var startl = n._first_location
238                         if startl != null then
239                                 # Non-epsilon production
240                                 assert endl != null
241
242                                 n.location = new Location(startl.file, startl.line_start, endl.line_end, startl.column_start, endl.column_end)
243
244                                 for no in _need_before_epsilons do
245                                         # Epsilon production that starts the current non-epsilon production
246                                         #var startl = n.location
247                                         no.location = new Location(startl.file, startl.line_start, startl.line_start, startl.column_start, startl.column_start)
248                                 end
249                                 _need_before_epsilons.clear
250
251                                 for no in _need_after_epsilons do
252                                         # Epsilon production that finishes the current non-epsilon production
253                                         #var endl = n.location
254                                         no.location = new Location(endl.file, endl.line_end, endl.line_end, endl.column_end, endl.column_end)
255                                 end
256                                 _need_after_epsilons.clear
257                         else
258                                 # No first token means epsilon production (or "throw all my tokens" production)
259                                 # So, it must be located it later
260                                 if endl == null then
261                                         # Epsilon production that starts a parent non-epsilon production
262                                         _need_before_epsilons.add(n)
263                                 else
264                                         # Epsilon production in the middle or that finishes a parent non-epsilon production
265                                         _need_after_epsilons.add(n)
266                                 end
267                         end
268                 end
269         end
270
271         init do end
272 end
273
274 # Each reduca action has its own class, this one is the root of the hierarchy.
275 private abstract class ReduceAction
276         fun action(p: Parser) is abstract
277         fun concat(l1, l2 : Array[Object]): Array[Object]
278         do
279                 if l1.is_empty then return l2
280                 l1.append(l2)
281                 return l1
282         end
283 end
284
285 $ foreach {rules/rule}
286 private class ReduceAction@index
287 special ReduceAction
288         redef fun action(p: Parser)
289         do
290                                         var node_list: nullable Object = null
291 $   foreach {action}
292 $   choose
293 $     when {@cmd='POP'}
294                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = p.pop
295 $     end
296 $     when {@cmd='FETCHLIST'}
297                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = ${translate(@from,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
298                                         assert ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} isa Array[Object]
299 $     end
300 $     when {@cmd='FETCHNODE'}
301                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = ${translate(@from,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
302                                         assert ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} isa nullable @etype
303 $     end
304 $     when {@cmd='ADDNODE'}
305                                         if ${translate(@node,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} != null then
306                                                 ${translate(@tolist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}.add(${translate(@node,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")})
307                                         end
308 $     end
309 $     when {@cmd='ADDLIST'}
310                                         ${translate(@tolist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = concat(${translate(@tolist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}, ${translate(@fromlist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")})
311 $     end
312 $     when {@cmd='MAKELIST'}
313                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = new Array[Object]
314 $     end
315 $     when {@cmd='MAKENODE'}
316                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}: nullable @etype = new @etype.init_${translate(@etype,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}(
317 $       foreach {arg}
318 $           if @null
319                                                 null[-sep ','-]
320 $           else
321                                                 ${translate(.,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}[-sep ','-]
322 $           end
323 $       end foreach
324                                         )
325 $     end
326 $     when {@cmd='RETURNNODE'}
327 $       if @null
328                                         node_list = null
329 $       else
330                                         node_list = ${translate(@node,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
331 $       end
332 $     end
333 $     when {@cmd='RETURNLIST'}
334                                         node_list = ${translate(@list,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
335 $     end
336 $   end choose
337 $   end foreach
338                                         p.push(p.go_to(@leftside), node_list)
339         end
340 init do end
341 end
342 $ end foreach
343 $ end template
344
345 $ template make_parser_tables()
346 # Parser that build a full AST
347 abstract class ParserTable
348         var _action_table: Array[Array[Int]]
349         private fun build_action_table
350         do
351                 _action_table = once [
352 $ foreach {parser_data/action_table/row}
353                         action_table_row${position()}[-sep ','-]
354 $ end foreach
355                 ]
356         end
357
358 $ foreach {parser_data/action_table/row}
359         private fun action_table_row${position()}: Array[Int]
360         do
361                 return [
362 $   foreach {action}
363                                 @from, @action, @to[-sep ','-]
364 $   end foreach
365                         ]
366         end
367 $ end foreach
368
369         var _goto_table: Array[Array[Int]]
370         private fun build_goto_table
371         do
372                 _goto_table = once [
373 $ foreach {parser_data/goto_table/row}
374                         [
375 $   foreach {goto}
376                                 @from, @to[-sep ','-]
377 $   end foreach
378                         ][-sep ','-]
379 $ end foreach
380                 ]
381         end
382
383         init do end
384 end
385 $ end template