我正在尝试用haskell中的Parsec解析Abap语言的片段。 Abap中的语句由点分隔。函数定义的语法是:
FORM <name> <arguments>.
<statements>.
ENDFORM.
我将它用作一个最小的例子。
这是我尝试在haskell和解析器中编写相应的类型。 GenStatement
- 构造函数用于除上述函数定义之外的所有其他语句。
module Main where
import Control.Applicative
import Data.Functor.Identity
import qualified Text.Parsec as P
import qualified Text.Parsec.String as S
import Text.Parsec.Language
import qualified Text.Parsec.Token as T
type Args = String
type Name = String
data AbapExpr -- ABAP Program
= Form Name Args [AbapExpr]
| GenStatement String [AbapExpr]
deriving (Show, Read)
lexer :: T.TokenParser ()
lexer = T.makeTokenParser style
where
caseSensitive = False
keys = ["form", "endform"]
style = emptyDef
{ T.reservedNames = keys
, T.identStart = P.alphaNum <|> P.char '_'
, T.identLetter = P.alphaNum <|> P.char '_'
}
dot :: S.Parser String
dot = T.dot lexer
reserved :: String -> S.Parser ()
reserved = T.reserved lexer
identifier :: S.Parser String
identifier = T.identifier lexer
argsP :: S.Parser String
argsP = P.manyTill P.anyChar (P.try (P.lookAhead dot))
genericStatementP :: S.Parser String
genericStatementP = P.manyTill P.anyChar (P.try dot)
abapExprP = P.try (P.between (reserved "form")
(reserved "endform" >> dot)
abapFormP)
<|> abapStmtP
where
abapFormP = Form <$> identifier <*> argsP <* dot <*> many abapExprP
abapStmtP = GenStatement <$> genericStatementP <*> many abapExprP
使用以下输入测试解析器会导致奇怪的行为。
-- a wrapper for convenience
parse :: S.Parser a -> String -> Either P.ParseError a
parse = flip P.parse "Test"
testParse1 = parse abapExprP "form foo arg1 arg2 arg2. form bar arg1. endform. endform."
结果
Right (GenStatement "form foo arg1 arg2 arg2" [GenStatement "form bar arg1" [GenStatement "endform" [GenStatement "endform" []]]])
所以看起来第一个brach总是失败,只有第二个泛型分支成功。但是,如果第二个分支(解析通用语句)被注释,解析表单突然成功:
abapExprP = P.try (P.between (reserved "form")
(reserved "endform" >> dot)
abapFormP)
-- <|> abapStmtP
where
abapFormP = Form <$> identifier <*> argsP <* dot <*> many abapExprP
-- abapStmtP = GenStatement <$> genericStatementP <*> many abapExprP
现在我们得到
Right (Form "foo" "arg1 arg2 arg2" [Form "bar" "arg1" []])
这怎么可能?似乎第一个分支成功,所以为什么它不能在第一个例子中起作用 - 我缺少什么?
非常感谢提前!
答案 0 :(得分:2)
找我,你的解析器genericStatementP
解析任何字符,直到出现一个点(你正在使用P.anyChar
)。因此,它不会识别词法分析器的保留关键字。
我认为你必须定义:
type Args = [String]
和
argsP :: S.Parser [String]
argsP = P.manyTill identifier (P.try (P.lookAhead dot))
genericStatementP :: S.Parser String
genericStatementP = identifier
通过这些更改,我得到以下结果:
Right (Form "foo" ["arg1","arg2","arg2"] [Form "bar" ["arg1"] []])