Home My Page Projects Code Snippets Project Openings SML/NJ
Summary Activity Forums Tracker Lists Tasks Docs Surveys News SCM Files

SCM Repository

[smlnj] Annotation of /sml/trunk/src/ml-yacc/lib/parser2.sml
ViewVC logotype

Annotation of /sml/trunk/src/ml-yacc/lib/parser2.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 656 - (view) (download)

1 : blume 656 (* ML-Yacc Parser Generator (c) 1989 Andrew W. Appel, David R. Tarditi *)
2 : monnier 249
3 :     (* parser.sml: This is a parser driver for LR tables with an error-recovery
4 :     routine added to it. The routine used is described in detail in this
5 :     article:
6 :    
7 :     'A Practical Method for LR and LL Syntactic Error Diagnosis and
8 :     Recovery', by M. Burke and G. Fisher, ACM Transactions on
9 :     Programming Langauges and Systems, Vol. 9, No. 2, April 1987,
10 :     pp. 164-197.
11 :    
12 :     This program is an implementation is the partial, deferred method discussed
13 :     in the article. The algorithm and data structures used in the program
14 :     are described below.
15 :    
16 :     This program assumes that all semantic actions are delayed. A semantic
17 :     action should produce a function from unit -> value instead of producing the
18 :     normal value. The parser returns the semantic value on the top of the
19 :     stack when accept is encountered. The user can deconstruct this value
20 :     and apply the unit -> value function in it to get the answer.
21 :    
22 :     It also assumes that the lexer is a lazy stream.
23 :    
24 :     Data Structures:
25 :     ----------------
26 :    
27 :     * The parser:
28 :    
29 :     The state stack has the type
30 :    
31 :     (state * (semantic value * line # * line #)) list
32 :    
33 :     The parser keeps a queue of (state stack * lexer pair). A lexer pair
34 :     consists of a terminal * value pair and a lexer. This allows the
35 :     parser to reconstruct the states for terminals to the left of a
36 :     syntax error, and attempt to make error corrections there.
37 :    
38 :     The queue consists of a pair of lists (x,y). New additions to
39 :     the queue are cons'ed onto y. The first element of x is the top
40 :     of the queue. If x is nil, then y is reversed and used
41 :     in place of x.
42 :    
43 :     Algorithm:
44 :     ----------
45 :    
46 :     * The steady-state parser:
47 :    
48 :     This parser keeps the length of the queue of state stacks at
49 :     a steady state by always removing an element from the front when
50 :     another element is placed on the end.
51 :    
52 :     It has these arguments:
53 :    
54 :     stack: current stack
55 :     queue: value of the queue
56 :     lexPair ((terminal,value),lex stream)
57 :    
58 :     When SHIFT is encountered, the state to shift to and the value are
59 :     are pushed onto the state stack. The state stack and lexPair are
60 :     placed on the queue. The front element of the queue is removed.
61 :    
62 :     When REDUCTION is encountered, the rule is applied to the current
63 :     stack to yield a triple (nonterm,value,new stack). A new
64 :     stack is formed by adding (goto(top state of stack,nonterm),value)
65 :     to the stack.
66 :    
67 :     When ACCEPT is encountered, the top value from the stack and the
68 :     lexer are returned.
69 :    
70 :     When an ERROR is encountered, fixError is called. FixError
71 :     takes the arguments to the parser, fixes the error if possible and
72 :     returns a new set of arguments.
73 :    
74 :     * The distance-parser:
75 :    
76 :     This parser includes an additional argument distance. It pushes
77 :     elements on the queue until it has parsed distance tokens, or an
78 :     ACCEPT or ERROR occurs. It returns a stack, lexer, the number of
79 :     tokens left unparsed, a queue, and an action option.
80 :     *)
81 :    
82 :     signature FIFO =
83 :     sig type 'a queue
84 :     val empty : 'a queue
85 :     exception Empty
86 :     val get : 'a queue -> 'a * 'a queue
87 :     val put : 'a * 'a queue -> 'a queue
88 :     end
89 :    
90 :     (* drt (12/15/89) -- the functor should be used in development work, but
91 :     it wastes space in the release version.
92 :    
93 :     functor ParserGen(structure LrTable : LR_TABLE
94 :     structure Stream : STREAM) : LR_PARSER =
95 :     *)
96 :    
97 :     structure LrParser :> LR_PARSER =
98 :     struct
99 :     structure LrTable = LrTable
100 :     structure Stream = Stream
101 :    
102 :     structure Token : TOKEN =
103 :     struct
104 :     structure LrTable = LrTable
105 :     datatype ('a,'b) token = TOKEN of LrTable.term * ('a * 'b * 'b)
106 :     val sameToken = fn (TOKEN(t,_),TOKEN(t',_)) => t=t'
107 :     end
108 :    
109 :     open LrTable
110 :     open Token
111 :    
112 :     val DEBUG1 = false
113 :     val DEBUG2 = false
114 :     exception ParseError
115 :     exception ParseImpossible of int
116 :    
117 :     structure Fifo :> FIFO =
118 :     struct
119 :     type 'a queue = ('a list * 'a list)
120 :     val empty = (nil,nil)
121 :     exception Empty
122 :     fun get(a::x, y) = (a, (x,y))
123 :     | get(nil, nil) = raise Empty
124 :     | get(nil, y) = get(rev y, nil)
125 :     fun put(a,(x,y)) = (x,a::y)
126 :     end
127 :    
128 :     type ('a,'b) elem = (state * ('a * 'b * 'b))
129 :     type ('a,'b) stack = ('a,'b) elem list
130 :     type ('a,'b) lexv = ('a,'b) token
131 :     type ('a,'b) lexpair = ('a,'b) lexv * (('a,'b) lexv Stream.stream)
132 :     type ('a,'b) distanceParse =
133 :     ('a,'b) lexpair *
134 :     ('a,'b) stack *
135 :     (('a,'b) stack * ('a,'b) lexpair) Fifo.queue *
136 :     int ->
137 :     ('a,'b) lexpair *
138 :     ('a,'b) stack *
139 :     (('a,'b) stack * ('a,'b) lexpair) Fifo.queue *
140 :     int *
141 :     action option
142 :    
143 :     type ('a,'b) ecRecord =
144 :     {is_keyword : term -> bool,
145 :     preferred_change : (term list * term list) list,
146 :     error : string * 'b * 'b -> unit,
147 :     errtermvalue : term -> 'a,
148 :     terms : term list,
149 :     showTerminal : term -> string,
150 :     noShift : term -> bool}
151 :    
152 :     local
153 :     val print = fn s => TextIO.output(TextIO.stdOut,s)
154 :     val println = fn s => (print s; print "\n")
155 :     val showState = fn (STATE s) => "STATE " ^ (Int.toString s)
156 :     in
157 :     fun printStack(stack: ('a,'b) stack, n: int) =
158 :     case stack
159 :     of (state,_) :: rest =>
160 :     (print("\t" ^ Int.toString n ^ ": ");
161 :     println(showState state);
162 :     printStack(rest, n+1))
163 :     | nil => ()
164 :    
165 :     fun prAction showTerminal
166 :     (stack as (state,_) :: _, next as (TOKEN (term,_),_), action) =
167 :     (println "Parse: state stack:";
168 :     printStack(stack, 0);
169 :     print(" state="
170 :     ^ showState state
171 :     ^ " next="
172 :     ^ showTerminal term
173 :     ^ " action="
174 :     );
175 :     case action
176 :     of SHIFT state => println ("SHIFT " ^ (showState state))
177 :     | REDUCE i => println ("REDUCE " ^ (Int.toString i))
178 :     | ERROR => println "ERROR"
179 :     | ACCEPT => println "ACCEPT")
180 :     | prAction _ (_,_,action) = ()
181 :     end
182 :    
183 :     (* ssParse: parser which maintains the queue of (state * lexvalues) in a
184 :     steady-state. It takes a table, showTerminal function, saction
185 :     function, and fixError function. It parses until an ACCEPT is
186 :     encountered, or an exception is raised. When an error is encountered,
187 :     fixError is called with the arguments of parseStep (lexv,stack,and
188 :     queue). It returns the lexv, and a new stack and queue adjusted so
189 :     that the lexv can be parsed *)
190 :    
191 :     val ssParse =
192 :     fn (table,showTerminal,saction,fixError,arg) =>
193 :     let val prAction = prAction showTerminal
194 :     val action = LrTable.action table
195 :     val goto = LrTable.goto table
196 :     fun parseStep(args as
197 :     (lexPair as (TOKEN (terminal, value as (_,leftPos,_)),
198 :     lexer
199 :     ),
200 :     stack as (state,_) :: _,
201 :     queue)) =
202 :     let val nextAction = action (state,terminal)
203 :     val _ = if DEBUG1 then prAction(stack,lexPair,nextAction)
204 :     else ()
205 :     in case nextAction
206 :     of SHIFT s =>
207 :     let val newStack = (s,value) :: stack
208 :     val newLexPair = Stream.get lexer
209 :     val (_,newQueue) =Fifo.get(Fifo.put((newStack,newLexPair),
210 :     queue))
211 :     in parseStep(newLexPair,(s,value)::stack,newQueue)
212 :     end
213 :     | REDUCE i =>
214 :     (case saction(i,leftPos,stack,arg)
215 :     of (nonterm,value,stack as (state,_) :: _) =>
216 :     parseStep(lexPair,(goto(state,nonterm),value)::stack,
217 :     queue)
218 :     | _ => raise (ParseImpossible 197))
219 :     | ERROR => parseStep(fixError args)
220 :     | ACCEPT =>
221 :     (case stack
222 :     of (_,(topvalue,_,_)) :: _ =>
223 :     let val (token,restLexer) = lexPair
224 :     in (topvalue,Stream.cons(token,restLexer))
225 :     end
226 :     | _ => raise (ParseImpossible 202))
227 :     end
228 :     | parseStep _ = raise (ParseImpossible 204)
229 :     in parseStep
230 :     end
231 :    
232 :     (* distanceParse: parse until n tokens are shifted, or accept or
233 :     error are encountered. Takes a table, showTerminal function, and
234 :     semantic action function. Returns a parser which takes a lexPair
235 :     (lex result * lexer), a state stack, a queue, and a distance
236 :     (must be > 0) to parse. The parser returns a new lex-value, a stack
237 :     with the nth token shifted on top, a queue, a distance, and action
238 :     option. *)
239 :    
240 :     val distanceParse =
241 :     fn (table,showTerminal,saction,arg) =>
242 :     let val prAction = prAction showTerminal
243 :     val action = LrTable.action table
244 :     val goto = LrTable.goto table
245 :     fun parseStep(lexPair,stack,queue,0) = (lexPair,stack,queue,0,NONE)
246 :     | parseStep(lexPair as (TOKEN (terminal, value as (_,leftPos,_)),
247 :     lexer
248 :     ),
249 :     stack as (state,_) :: _,
250 :     queue,distance) =
251 :     let val nextAction = action(state,terminal)
252 :     val _ = if DEBUG1 then prAction(stack,lexPair,nextAction)
253 :     else ()
254 :     in case nextAction
255 :     of SHIFT s =>
256 :     let val newStack = (s,value) :: stack
257 :     val newLexPair = Stream.get lexer
258 :     in parseStep(newLexPair,(s,value)::stack,
259 :     Fifo.put((newStack,newLexPair),queue),distance-1)
260 :     end
261 :     | REDUCE i =>
262 :     (case saction(i,leftPos,stack,arg)
263 :     of (nonterm,value,stack as (state,_) :: _) =>
264 :     parseStep(lexPair,(goto(state,nonterm),value)::stack,
265 :     queue,distance)
266 :     | _ => raise (ParseImpossible 240))
267 :     | ERROR => (lexPair,stack,queue,distance,SOME nextAction)
268 :     | ACCEPT => (lexPair,stack,queue,distance,SOME nextAction)
269 :     end
270 :     | parseStep _ = raise (ParseImpossible 242)
271 :     in parseStep : ('_a,'_b) distanceParse
272 :     end
273 :    
274 :     (* mkFixError: function to create fixError function which adjusts parser state
275 :     so that parse may continue in the presence of an error *)
276 :    
277 :     fun mkFixError({is_keyword,terms,errtermvalue,
278 :     preferred_change,noShift,
279 :     showTerminal,error,...} : ('_a,'_b) ecRecord,
280 :     distanceParse : ('_a,'_b) distanceParse,
281 :     minAdvance,maxAdvance)
282 :    
283 :     (lexv as (TOKEN (term,value as (_,leftPos,_)),_),stack,queue) =
284 :     let val _ = if DEBUG2 then
285 :     error("syntax error found at " ^ (showTerminal term),
286 :     leftPos,leftPos)
287 :     else ()
288 :    
289 :     fun tokAt(t,p) = TOKEN(t,(errtermvalue t,p,p))
290 :    
291 :     val minDelta = 3
292 :    
293 :     (* pull all the state * lexv elements from the queue *)
294 :    
295 :     val stateList =
296 :     let fun f q = let val (elem,newQueue) = Fifo.get q
297 :     in elem :: (f newQueue)
298 :     end handle Fifo.Empty => nil
299 :     in f queue
300 :     end
301 :    
302 :     (* now number elements of stateList, giving distance from
303 :     error token *)
304 :    
305 :     val (_, numStateList) =
306 :     List.foldr (fn (a,(num,r)) => (num+1,(a,num)::r)) (0, []) stateList
307 :    
308 :     (* Represent the set of potential changes as a linked list.
309 :    
310 :     Values of datatype Change hold information about a potential change.
311 :    
312 :     oper = oper to be applied
313 :     pos = the # of the element in stateList that would be altered.
314 :     distance = the number of tokens beyond the error token which the
315 :     change allows us to parse.
316 :     new = new terminal * value pair at that point
317 :     orig = original terminal * value pair at the point being changed.
318 :     *)
319 :    
320 :     datatype ('a,'b) change = CHANGE of
321 :     {pos : int, distance : int, leftPos: 'b, rightPos: 'b,
322 :     new : ('a,'b) lexv list, orig : ('a,'b) lexv list}
323 :    
324 :    
325 :     val showTerms = concat o map (fn TOKEN(t,_) => " " ^ showTerminal t)
326 :    
327 :     val printChange = fn c =>
328 :     let val CHANGE {distance,new,orig,pos,...} = c
329 :     in (print ("{distance= " ^ (Int.toString distance));
330 :     print (",orig ="); print(showTerms orig);
331 :     print (",new ="); print(showTerms new);
332 :     print (",pos= " ^ (Int.toString pos));
333 :     print "}\n")
334 :     end
335 :    
336 :     val printChangeList = app printChange
337 :    
338 :     (* parse: given a lexPair, a stack, and the distance from the error
339 :     token, return the distance past the error token that we are able to parse.*)
340 :    
341 :     fun parse (lexPair,stack,queuePos : int) =
342 :     case distanceParse(lexPair,stack,Fifo.empty,queuePos+maxAdvance+1)
343 :     of (_,_,_,distance,SOME ACCEPT) =>
344 :     if maxAdvance-distance-1 >= 0
345 :     then maxAdvance
346 :     else maxAdvance-distance-1
347 :     | (_,_,_,distance,_) => maxAdvance - distance - 1
348 :    
349 :     (* catList: concatenate results of scanning list *)
350 :    
351 :     fun catList l f = List.foldr (fn(a,r)=> f a @ r) [] l
352 :    
353 :     fun keywordsDelta new = if List.exists (fn(TOKEN(t,_))=>is_keyword t) new
354 :     then minDelta else 0
355 :    
356 :     fun tryChange{lex,stack,pos,leftPos,rightPos,orig,new} =
357 :     let val lex' = List.foldr (fn (t',p)=>(t',Stream.cons p)) lex new
358 :     val distance = parse(lex',stack,pos+length new-length orig)
359 :     in if distance >= minAdvance + keywordsDelta new
360 :     then [CHANGE{pos=pos,leftPos=leftPos,rightPos=rightPos,
361 :     distance=distance,orig=orig,new=new}]
362 :     else []
363 :     end
364 :    
365 :    
366 :     (* tryDelete: Try to delete n terminals.
367 :     Return single-element [success] or nil.
368 :     Do not delete unshiftable terminals. *)
369 :    
370 :    
371 :     fun tryDelete n ((stack,lexPair as (TOKEN(term,(_,l,r)),_)),qPos) =
372 :     let fun del(0,accum,left,right,lexPair) =
373 :     tryChange{lex=lexPair,stack=stack,
374 :     pos=qPos,leftPos=left,rightPos=right,
375 :     orig=rev accum, new=[]}
376 :     | del(n,accum,left,right,(tok as TOKEN(term,(_,_,r)),lexer)) =
377 :     if noShift term then []
378 :     else del(n-1,tok::accum,left,r,Stream.get lexer)
379 :     in del(n,[],l,r,lexPair)
380 :     end
381 :    
382 :     (* tryInsert: try to insert tokens before the current terminal;
383 :     return a list of the successes *)
384 :    
385 :     fun tryInsert((stack,lexPair as (TOKEN(_,(_,l,_)),_)),queuePos) =
386 :     catList terms (fn t =>
387 :     tryChange{lex=lexPair,stack=stack,
388 :     pos=queuePos,orig=[],new=[tokAt(t,l)],
389 :     leftPos=l,rightPos=l})
390 :    
391 :     (* trySubst: try to substitute tokens for the current terminal;
392 :     return a list of the successes *)
393 :    
394 :     fun trySubst ((stack,lexPair as (orig as TOKEN (term,(_,l,r)),lexer)),
395 :     queuePos) =
396 :     if noShift term then []
397 :     else
398 :     catList terms (fn t =>
399 :     tryChange{lex=Stream.get lexer,stack=stack,
400 :     pos=queuePos,
401 :     leftPos=l,rightPos=r,orig=[orig],
402 :     new=[tokAt(t,r)]})
403 :    
404 :     (* do_delete(toks,lexPair) tries to delete tokens "toks" from "lexPair".
405 :     If it succeeds, returns SOME(toks',l,r,lp), where
406 :     toks' is the actual tokens (with positions and values) deleted,
407 :     (l,r) are the (leftmost,rightmost) position of toks',
408 :     lp is what remains of the stream after deletion
409 :     *)
410 :     fun do_delete(nil,lp as (TOKEN(_,(_,l,_)),_)) = SOME(nil,l,l,lp)
411 :     | do_delete([t],(tok as TOKEN(t',(_,l,r)),lp')) =
412 :     if t=t'
413 :     then SOME([tok],l,r,Stream.get lp')
414 :     else NONE
415 :     | do_delete(t::rest,(tok as TOKEN(t',(_,l,r)),lp')) =
416 :     if t=t'
417 :     then case do_delete(rest,Stream.get lp')
418 :     of SOME(deleted,l',r',lp'') =>
419 :     SOME(tok::deleted,l,r',lp'')
420 :     | NONE => NONE
421 :     else NONE
422 :    
423 :     fun tryPreferred((stack,lexPair),queuePos) =
424 :     catList preferred_change (fn (delete,insert) =>
425 :     if List.exists noShift delete then [] (* should give warning at
426 :     parser-generation time *)
427 :     else case do_delete(delete,lexPair)
428 :     of SOME(deleted,l,r,lp) =>
429 :     tryChange{lex=lp,stack=stack,pos=queuePos,
430 :     leftPos=l,rightPos=r,orig=deleted,
431 :     new=map (fn t=>(tokAt(t,r))) insert}
432 :     | NONE => [])
433 :    
434 :     val changes = catList numStateList tryPreferred @
435 :     catList numStateList tryInsert @
436 :     catList numStateList trySubst @
437 :     catList numStateList (tryDelete 1) @
438 :     catList numStateList (tryDelete 2) @
439 :     catList numStateList (tryDelete 3)
440 :    
441 :     val findMaxDist = fn l =>
442 :     foldr (fn (CHANGE {distance,...},high) => Int.max(distance,high)) 0 l
443 :    
444 :     (* maxDist: max distance past error taken that we could parse *)
445 :    
446 :     val maxDist = findMaxDist changes
447 :    
448 :     (* remove changes which did not parse maxDist tokens past the error token *)
449 :    
450 :     val changes = catList changes
451 :     (fn(c as CHANGE{distance,...}) =>
452 :     if distance=maxDist then [c] else [])
453 :    
454 :     in case changes
455 :     of (l as change :: _) =>
456 :     let fun print_msg (CHANGE {new,orig,leftPos,rightPos,...}) =
457 :     let val s =
458 :     case (orig,new)
459 :     of (_::_,[]) => "deleting " ^ (showTerms orig)
460 :     | ([],_::_) => "inserting " ^ (showTerms new)
461 :     | _ => "replacing " ^ (showTerms orig) ^
462 :     " with " ^ (showTerms new)
463 :     in error ("syntax error: " ^ s,leftPos,rightPos)
464 :     end
465 :    
466 :     val _ =
467 :     (if length l > 1 andalso DEBUG2 then
468 :     (print "multiple fixes possible; could fix it by:\n";
469 :     app print_msg l;
470 :     print "chosen correction:\n")
471 :     else ();
472 :     print_msg change)
473 :    
474 :     (* findNth: find nth queue entry from the error
475 :     entry. Returns the Nth queue entry and the portion of
476 :     the queue from the beginning to the nth-1 entry. The
477 :     error entry is at the end of the queue.
478 :    
479 :     Examples:
480 :    
481 :     queue = a b c d e
482 :     findNth 0 = (e,a b c d)
483 :     findNth 1 = (d,a b c)
484 :     *)
485 :    
486 :     val findNth = fn n =>
487 :     let fun f (h::t,0) = (h,rev t)
488 :     | f (h::t,n) = f(t,n-1)
489 :     | f (nil,_) = let exception FindNth
490 :     in raise FindNth
491 :     end
492 :     in f (rev stateList,n)
493 :     end
494 :    
495 :     val CHANGE {pos,orig,new,...} = change
496 :     val (last,queueFront) = findNth pos
497 :     val (stack,lexPair) = last
498 :    
499 :     val lp1 = foldl(fn (_,(_,r)) => Stream.get r) lexPair orig
500 :     val lp2 = foldr(fn(t,r)=>(t,Stream.cons r)) lp1 new
501 :    
502 :     val restQueue =
503 :     Fifo.put((stack,lp2),
504 :     foldl Fifo.put Fifo.empty queueFront)
505 :    
506 :     val (lexPair,stack,queue,_,_) =
507 :     distanceParse(lp2,stack,restQueue,pos)
508 :    
509 :     in (lexPair,stack,queue)
510 :     end
511 :     | nil => (error("syntax error found at " ^ (showTerminal term),
512 :     leftPos,leftPos); raise ParseError)
513 :     end
514 :    
515 :     val parse = fn {arg,table,lexer,saction,void,lookahead,
516 :     ec=ec as {showTerminal,...} : ('_a,'_b) ecRecord} =>
517 :     let val distance = 15 (* defer distance tokens *)
518 :     val minAdvance = 1 (* must parse at least 1 token past error *)
519 :     val maxAdvance = Int.max(lookahead,0)(* max distance for parse check *)
520 :     val lexPair = Stream.get lexer
521 :     val (TOKEN (_,(_,leftPos,_)),_) = lexPair
522 :     val startStack = [(initialState table,(void,leftPos,leftPos))]
523 :     val startQueue = Fifo.put((startStack,lexPair),Fifo.empty)
524 :     val distanceParse = distanceParse(table,showTerminal,saction,arg)
525 :     val fixError = mkFixError(ec,distanceParse,minAdvance,maxAdvance)
526 :     val ssParse = ssParse(table,showTerminal,saction,fixError,arg)
527 :     fun loop (lexPair,stack,queue,_,SOME ACCEPT) =
528 :     ssParse(lexPair,stack,queue)
529 :     | loop (lexPair,stack,queue,0,_) = ssParse(lexPair,stack,queue)
530 :     | loop (lexPair,stack,queue,distance,SOME ERROR) =
531 :     let val (lexPair,stack,queue) = fixError(lexPair,stack,queue)
532 :     in loop (distanceParse(lexPair,stack,queue,distance))
533 :     end
534 :     | loop _ = let exception ParseInternal
535 :     in raise ParseInternal
536 :     end
537 :     in loop (distanceParse(lexPair,startStack,startQueue,distance))
538 :     end
539 :     end;
540 :    

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0