63180cf6fc0939662acba472303a0e7e58dddf8c
[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 TablesCapable
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_reduce_table
53         end
54
55         # Do a transition in the automata
56         private fun go_to(index: Int): Int
57         do
58                 var state = state
59                 var low = 1
60                 var high = parser_goto(index, 0) - 1
61
62                 while low <= high do
63                         var middle = (low + high) / 2
64                         var subindex = middle * 2 + 1 # +1 because parser_goto(index, 0) is the length
65
66                         var goal = parser_goto(index, subindex)
67                         if state < goal then
68                                 high = middle - 1
69                         else if state > goal then
70                                 low = middle + 1
71                         else
72                                 return parser_goto(index, subindex+1)
73                         end
74                 end
75
76                 return parser_goto(index, 2) # Default value
77         end
78
79         # Push someting in the state stack
80         private fun push(numstate: Int, list_node: nullable Object)
81         do
82                 var pos = _stack_pos + 1
83                 _stack_pos = pos
84                 if pos < _stack.length then
85                         var state = _stack[pos]
86                         state.state = numstate
87                         state.nodes = list_node
88                 else
89                         _stack.push(new State(numstate, list_node))
90                 end
91         end
92
93         # The current state
94         private fun state: Int
95         do
96                 return _stack[_stack_pos].state
97         end
98
99         # Pop something from the stack state
100         private fun pop: nullable Object
101         do
102                 var res = _stack[_stack_pos].nodes
103                 _stack_pos = _stack_pos -1
104                 return res
105         end
106
107         # Build and return a full AST.
108         fun parse: Start
109         do
110                 push(0, null)
111
112                 var lexer = _lexer
113                 loop
114                         var token = lexer.peek
115                         if token isa PError then
116                                 return new Start(null, token)
117                         end
118
119                         var index = token.parser_index
120                         var action_type = parser_action(state, 2)
121                         var action_value = parser_action(state, 3)
122
123                         var low = 1
124                         var high = parser_action(state, 0) - 1
125
126                         while low <= high do
127                                 var middle = (low + high) / 2
128                                 var subindex = middle * 3 + 1 # +1 because parser_action(state, 0) is the length
129
130                                 var goal = parser_action(state, subindex)
131                                 if index < goal then
132                                         high = middle - 1
133                                 else if index > goal then
134                                         low = middle + 1
135                                 else
136                                         action_type = parser_action(state, subindex+1)
137                                         action_value = parser_action(state, subindex+2)
138                                         high = low -1 # break
139                                 end
140                         end
141
142                         if action_type == 0 then # SHIFT
143                                 push(action_value, lexer.next)
144                         else if action_type == 1 then # REDUCE
145                                 _reduce_table[action_value].action(self)
146                         else if action_type == 2 then # ACCEPT
147                                 var node2 = lexer.next
148                                 assert node2 isa EOF
149                                 var node1 = pop
150                                 assert node1 isa ${/parser/prods/prod/@ename}
151                                 var node = new Start(node1, node2)
152                                 (new ComputeProdLocationVisitor).enter_visit(node)
153                                 return node
154                         else if action_type == 3 then # ERROR
155                                 var node2 = new PError.init_error("Syntax error: unexpected token.", token.location)
156                                 var node = new Start(null, node2)
157                                 return node
158                         end
159                         if false then break # FIXME remove once unreach loop exits are in c_src
160                 end
161                 abort # FIXME remove once unreach loop exits are in c_src
162         end
163
164         var _reduce_table: Array[ReduceAction]
165         private fun build_reduce_table
166         do
167                 _reduce_table = new Array[ReduceAction].with_items(
168 $ foreach {rules/rule}
169                         new ReduceAction@index(@leftside)[-sep ','-]
170 $ end foreach
171                 )
172         end
173 end
174
175 redef class Prod
176         # Location on the first token after the start of a production
177         # So outside the production for epilon production
178         var _first_location: nullable Location
179
180         # Location of the last token before the end of a production
181         # So outside the production for epilon production
182         var _last_location: nullable Location
183 end
184
185 # Find location of production nodes
186 # Uses existing token locations to infer location of productions.
187 private class ComputeProdLocationVisitor
188 special Visitor
189         # Currenlty visited productions that need a first token
190         var _need_first_prods: Array[Prod] = new Array[Prod]
191
192         # Already visited epsilon productions that waits something after them
193         var _need_after_epsilons: Array[Prod] = new Array[Prod]
194
195         # Already visited epsilon production that waits something before them
196         var _need_before_epsilons: Array[Prod] = new Array[Prod]
197
198         # Location of the last visited token in the current production
199         var _last_location: nullable Location = null
200
201         redef fun visit(n: nullable PNode)
202         do
203                 if n == null then
204                         return
205                 else if n isa Token then
206                         var loc = n.location
207                         _last_location = loc
208
209                         # Add a first token to productions that need one
210                         for no in _need_first_prods do
211                                 no._first_location = loc
212                         end
213                         _need_first_prods.clear
214
215                         # Find location for already visited epsilon production that need one
216                         for no in _need_after_epsilons do
217                                 # Epsilon production that is in the middle of a non-epsilon production
218                                 # The epsilon production has both a token before and after it
219                                 var endl = loc
220                                 var startl = no._last_location
221                                 no.location = new Location(endl.file, startl.line_end, endl.line_start, startl.column_end, endl.column_start)
222                         end
223                         _need_after_epsilons.clear
224                 else
225                         assert n isa Prod
226                         _need_first_prods.add(n)
227
228                         var old_last = _last_location
229                         _last_location = null
230                         n.visit_all(self)
231                         var endl = _last_location
232                         if endl == null then _last_location = old_last
233
234                         n._last_location = endl
235                         var startl = n._first_location
236                         if startl != null then
237                                 # Non-epsilon production
238                                 assert endl != null
239
240                                 n.location = new Location(startl.file, startl.line_start, endl.line_end, startl.column_start, endl.column_end)
241
242                                 for no in _need_before_epsilons do
243                                         # Epsilon production that starts the current non-epsilon production
244                                         #var startl = n.location
245                                         no.location = new Location(startl.file, startl.line_start, startl.line_start, startl.column_start, startl.column_start)
246                                 end
247                                 _need_before_epsilons.clear
248
249                                 for no in _need_after_epsilons do
250                                         # Epsilon production that finishes the current non-epsilon production
251                                         #var endl = n.location
252                                         no.location = new Location(endl.file, endl.line_end, endl.line_end, endl.column_end, endl.column_end)
253                                 end
254                                 _need_after_epsilons.clear
255                         else
256                                 # No first token means epsilon production (or "throw all my tokens" production)
257                                 # So, it must be located it later
258                                 if endl == null then
259                                         # Epsilon production that starts a parent non-epsilon production
260                                         _need_before_epsilons.add(n)
261                                 else
262                                         # Epsilon production in the middle or that finishes a parent non-epsilon production
263                                         _need_after_epsilons.add(n)
264                                 end
265                         end
266                 end
267         end
268
269         init do end
270 end
271
272 # Each reduca action has its own class, this one is the root of the hierarchy.
273 private abstract class ReduceAction
274         fun action(p: Parser) is abstract
275         fun concat(l1, l2 : Array[Object]): Array[Object]
276         do
277                 if l1.is_empty then return l2
278                 l1.append(l2)
279                 return l1
280         end
281 end
282
283 $ foreach {rules/rule}
284 private class ReduceAction@index
285 special ReduceAction
286         redef fun action(p: Parser)
287         do
288                                         var node_list: nullable Object = null
289 $   foreach {action}
290 $   choose
291 $     when {@cmd='POP'}
292                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = p.pop
293 $     end
294 $     when {@cmd='FETCHLIST'}
295                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = ${translate(@from,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
296                                         assert ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} isa Array[Object]
297 $     end
298 $     when {@cmd='FETCHNODE'}
299                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = ${translate(@from,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
300                                         assert ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} isa nullable @etype
301 $     end
302 $     when {@cmd='ADDNODE'}
303                                         if ${translate(@node,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} != null then
304                                                 ${translate(@tolist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}.add(${translate(@node,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")})
305                                         end
306 $     end
307 $     when {@cmd='ADDLIST'}
308                                         ${translate(@tolist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = concat(${translate(@tolist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}, ${translate(@fromlist,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")})
309 $     end
310 $     when {@cmd='MAKELIST'}
311                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")} = new Array[Object]
312 $     end
313 $     when {@cmd='MAKENODE'}
314                                         var ${translate(@result,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}: nullable @etype = new @etype.init_${translate(@etype,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}(
315 $       foreach {arg}
316 $           if @null
317                                                 null[-sep ','-]
318 $           else
319                                                 ${translate(.,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}[-sep ','-]
320 $           end
321 $       end foreach
322                                         )
323 $     end
324 $     when {@cmd='RETURNNODE'}
325 $       if @null
326                                         node_list = null
327 $       else
328                                         node_list = ${translate(@node,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
329 $       end
330 $     end
331 $     when {@cmd='RETURNLIST'}
332                                         node_list = ${translate(@list,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")}
333 $     end
334 $   end choose
335 $   end foreach
336                                         p.push(p.go_to(_goto), node_list)
337         end
338         var _goto: Int
339         init(g: Int) do _goto = g
340 end
341 $ end foreach
342 $ end template
343
344 $ template make_parser_table()
345 $ foreach {parser_data/action_table/row}
346 static int parser_action_row${position()}[] = {
347         ${count(action)},
348 $   foreach {action}
349         @from, @action, @to[-sep ','-]
350 $   end foreach
351 };
352 $ end foreach
353
354 const int* const parser_action_table[] = {
355 $ foreach {parser_data/action_table/row}
356         parser_action_row${position()}[-sep ','-]
357 $ end foreach
358 };
359
360 $ foreach {parser_data/goto_table/row}
361 static int parser_goto_row${position()}[] = {
362         ${count(goto)},
363 $   foreach {goto}
364         @from, @to[-sep ','-]
365 $   end foreach
366 };
367 $ end foreach
368
369 const int* const parser_goto_table[] = {
370 $ foreach {parser_data/goto_table/row}
371         parser_goto_row${position()}[-sep ','-]
372 $ end foreach
373 };
374 $ end template