the parser relies on some “monadic” programming idioms
basically, parser combinator (But 非常麻烦 in Coq)
Lex
代码语言:javascript复制Inductive chartype := white | alpha | digit | other.
Definition classifyChar (c : ascii) : chartype :=
if isWhite c then white
else if isAlpha c then alpha
else if isDigit c then digit
else other.
Definition token := string.
Syntax
带 error msg 的 option
:
Inductive optionE (X:Type) : Type :=
| SomeE (x : X)
| NoneE (s : string). (** w/ error msg **)
Arguments SomeE {X}.
Arguments NoneE {X}.
Monadic:
代码语言:javascript复制Notation "' p <- e1 ;; e2"
:= (match e1 with
| SomeE p ⇒ e2
| NoneE err ⇒ NoneE err
end)
(right associativity, p pattern, at level 60, e1 at next level).
Notation "'TRY' ' p <- e1 ;; e2 'OR' e3"
:= (match e1 with
| SomeE p ⇒ e2
| NoneE _ ⇒ e3
end)
(right associativity, p pattern,
at level 60, e1 at next level, e2 at next level).
代码语言:javascript复制Definition parser (T : Type) :=
list token → optionE (T * list token).
代码语言:javascript复制newtype Parser a = Parser (String -> [(a,String)])
instance Monad Parser where
-- (>>=) :: Parser a -> (a -> Parser b) -> Parser b
p >>= f = P (inp -> case parse p inp of
[] -> []
[(v,out)] -> parse (f v) out)
combinator many
Coq vs. Haskell
- explicit recursion depth, .e. step-indexed
- explicit exception
optionE
(in Haskell, it’s hidden behind theParser
Monad as[]
) - explicit string state
xs
(in Haskell, it’s hidden behind theParser
Monad asString -> String
) - explicit
acc
epted token (in Haskell, it’s hidden behind theParser
Monad asa
, argument)
Fixpoint many_helper {T} (p : parser T) acc steps xs :=
match steps, p xs with
| 0, _ ⇒
NoneE "Too many recursive calls"
| _, NoneE _ ⇒
SomeE ((rev acc), xs)
| S steps', SomeE (t, xs') ⇒
many_helper p (t :: acc) steps' xs'
end.
Fixpoint many {T} (p : parser T) (steps : nat) : parser (list T) :=
many_helper p [] steps.
代码语言:javascript复制manyL :: Parser a -> Parser [a]
manyL p = many1L p < return [] -- left biased OR
many1L :: Parser a -> Parser [a]
many1L p = (:) <$> p <*> manyL p
-- or
many1L p = do x <- p
xs <- manyL p
return (x : xs)
ident
代码语言:javascript复制Definition parseIdentifier (xs : list token) : optionE (string * list token) :=
match xs with
| [] ⇒ NoneE "Expected identifier"
| x::xs' ⇒ if forallb isLowerAlpha (list_of_string x)
then SomeE (x, xs')
else NoneE ("Illegal identifier:'" x "'")
end.
代码语言:javascript复制ident :: Parser String
ident = do x <- lower
xs <- many alphanum
return (x:xs)