Parsing grammars using OCaml

前端 未结 3 1318
余生分开走
余生分开走 2020-12-28 10:33

I have a task to write a (toy) parser for a (toy) grammar using OCaml and not sure how to start (and proceed with) this problem.

Here\'s a sample Awk grammar:

<
3条回答
  •  误落风尘
    2020-12-28 11:06

    Here is a rough sketch - straightforwardly descend into the grammar and try each branch in order. Possible optimization : tail recursion for single non-terminal in a branch.

    exception Backtrack
    
    let parse l =
      let rules = snd awksub_grammar in
      let rec descend gram l =
        let rec loop = function 
          | [] -> raise Backtrack
          | x::xs -> try attempt x l with Backtrack -> loop xs
        in
        loop (rules gram)
      and attempt branch (path,tokens) =
        match branch, tokens with
        | T x :: branch' , h::tokens' when h = x -> 
            attempt branch' ((T x :: path),tokens')
        | N n :: branch' , _ -> 
            let (path',tokens) = descend n ((N n :: path),tokens) in 
            attempt branch' (path', tokens)
        | [], _ -> path,tokens
        | _, _ -> raise Backtrack
      in
      let (path,tail) = descend (fst awksub_grammar) ([],l) in
      tail, List.rev path
    

提交回复
热议问题