6

我试图总体上理解 Alex 和词法分析器,但我无法运行我的词法分析器。

我在“basic”和“posn”包装器中编写了词法分析器,但我不能在“monad”包装器中。我想我必须使用monad包装器,因为我需要在输入中收集字符串和令牌位置。我还需要多个状态。现在我正在尝试运行这个简单的例子:

{
module Main (main) where
}

%wrapper "monad"

$whitespace = [\ \b\t\n\f\v\r]
$digit      = 0-9
$alpha      = [a-zA-Z_]
$upper      = [A-Z]
$lower      = [a-z]

@tidentifier = $upper($alpha|_|$digit)*
@identifier  = $lower($alpha|_|$digit)*


tokens :-

$whitespace+ ;
$upper $alpha+ { typeId }
$lower $alpha+ { id_ }
$digit+ { int }

{

data Lexeme = L AlexPosn LexemeClass String

data LexemeClass
        = TypeId String
        | Id String
        | Int Int
        | EOF
    deriving (Show, Eq)

typeId :: AlexInput -> Int -> Alex Lexeme
typeId = undefined

id_ :: AlexInput -> Int -> Alex Lexeme
id_ = undefined

int :: AlexInput -> Int -> Alex Lexeme
int = undefined

alexEOF = return (L undefined EOF "")

main :: IO ()
main = do
    s <- getContents
    let r = runAlex s $ do
                return alexMonadScan
    print r
}

我的行动是undefined暂时的。当我尝试编译它时,我收到了这个错误:

➜  haskell  ghc --make Tokens.hs
[1 of 1] Compiling Main             ( Tokens.hs, Tokens.o )

templates/wrappers.hs:208:17:
    Couldn't match expected type `(AlexPosn, Char, [Byte], String)'
                with actual type `(t0, t1, t2)'
    Expected type: AlexInput
      Actual type: (t0, t1, t2)
    In the return type of a call of `ignorePendingBytes'
    In the first argument of `action', namely
      `(ignorePendingBytes inp)'

当我尝试在 Alex 的 github 存储库中编译示例时,我也遇到了各种错误,这可能与版本不匹配有关吗?我已经使用 ghc 7.0.4 从 cabal 安装了 alex。有任何想法吗?

4

1 回答 1

7

这看起来像是 Alex 3.0.1 中的一个错误。在处理了代码1中的一些其他不相关问题后,它在 2.3.3 版本中运行良好。问题是生成的代码中的这一行:

ignorePendingBytes (p,c,ps,s) = (p,c,s)

通过遵循生成代码中的类型,该函数似乎应该具有 type AlexInput -> AlexInput,但AlexInput显然不能同时是 3 元组和 4 元组。

这可能是因为AlexInput两个版本之间的定义发生了变化。

type AlexInput = (AlexPosn, Char, String)         -- v2.3.3
type AlexInput = (AlexPosn, Char, [Byte], String) -- v3.0.1

据我所知,正确的代码应该是

ignorePendingBytes (p,c,ps,s) = (p,c,[],s)

并在生成的代码中手动进行此更改使其在处理其他问题后编译。

但是,除非您需要 3.0.1 中的某些内容,否则我建议您降级直到修复此问题,因为必须针对生成的代码维护补丁通常比它的价值更麻烦。

1您的代码缺少一个Show实例 forLexeme并且您还在调用returnon alexMonadScan,它已经在Alexmonad 中。

于 2012-05-09T15:54:05.413 回答