
(* Convert from linear to tree form,
   but handle broken linear forms. (For
   generating testcases.) - Tom 7 *)

(* DO NOT USE THIS IN THE FINAL PRODUCT;
   IT DOES NOT MAKE SENSE *)
structure ToTreeLoose :> TOTREE =
struct

  (* never used here *)
  exception BadLinear of string

    open Il

    infixr :-: 
    fun a :-: (b,c) = (a::b, c)

    (* given a token list,
       return (list of Il.exp, token list).
       Stops when it gets to a closing tag or EOL.
     *)
    fun loe (Token.Text s :: rest) = Text s :-: loe rest
      | loe (l as (Token.Closetag _ :: _)) = (nil, l)
      | loe nil = (nil, nil)
      | loe (Token.Tag t :: rest) =
        let val (exp, rest) = tot nil t rest
        in exp :-: loe rest
        end

    (* returns an expression and the rest of the list,
       as if we just entered a tag t *)
    and tot l t (more as (Token.Closetag tt :: rest)) =
        let in 
          if Token.eqtag (t, tt) then
            (mktag ([t],mkseq l), rest)
          else (* silently insert it *)
            (mktag ([t],mkseq l), more)
        end
      | tot l t nil = (* pretend tag is here *)
        (mktag ([t], mkseq l), nil)
      | tot l t more = 
        let
            val (exp,rest) = loe more
        in
            tot (l @ exp) t rest
        end

    fun totree m =
        case loe m of
            (l, _) => mkseq l (* ignore extra closing tags *)
end
