我刚拿起haskell和alex / happy因为我想写一个解析器。但是,我遇到了这个问题:
source:lexer.x
{
module ValkenLexer where
strip :: String -> String
strip s = take ((length s) - 2) (drop 1 s)
}
%wrapper "basic"
$digit = 0-9
$alpha = [a-zA-Z]
tokens :-
$white+ ;
$alpha+ { \s -> TokIdent s }
\"[^\"]*\" { \s -> TokStr strip(s) }
= { \s -> TokSlash}
\| { \s -> TokPipe }
\/ { \s -> TokSlash }
\n { \s -> TokEol}
\%$alpha+ { \s -> TokVar (drop 1 s)}
{
data Token = TokIdent String
| TokStr String
| TokEq
| TokPipe
| TokSlash
| TokEol
| TokVar String
deriving (Eq,Show)
}
得到了:
\->>> alex lexer.x && ghc lexer.hs
[1 of 1] Compiling ValkenLexer ( lexer.hs, lexer.o )
lexer.hs:15:1: parse error on input `import'
我做错了什么?
答案 0 :(得分:2)
正如Daniel Wagner预测的那样,功能定义需要在页脚上进行。您只能在标头上放置模块声明和导入语句。此外,您需要将TokStr strip(s)
更改为TokStr (strip s)
{
module ValkenLexer where
}
%wrapper "basic"
$digit = 0-9
$alpha = [a-zA-Z]
tokens :-
$white+ ;
$alpha+ { \s -> TokIdent s }
\"[^\"]*\" { \s -> TokStr (strip s) }
= { \s -> TokSlash}
\| { \s -> TokPipe }
\/ { \s -> TokSlash }
\n { \s -> TokEol}
\%$alpha+ { \s -> TokVar (drop 1 s)}
{
strip :: String -> String
strip s = take ((length s) - 2) (drop 1 s)
data Token = TokIdent String
| TokStr String
| TokEq
| TokPipe
| TokSlash
| TokEol
| TokVar String
deriving (Eq,Show)
}