2016-01-18 88 views
4

我正在为实验性语言进行语义分析。我使用Alex和Happy来生成词法分析器和解析器(实际上我使用BNFC工具来生成Alex和Happy文件)。每当出现语义错误时(例如类型错误),我都希望得到带有行号和列号的错误消息。在语义分析阶段获取行号信息(使用Alex,Happy)

看来,我将不得不存储行号信息,同时建立我的符号表或AST。如果我可以以某种方式访问​​Happy文件的规则部分中的位置信息,我的问题将被解决。

在这方面的任何建议将不胜感激。

我试着实现下面建议的答案,但不幸的是没有任何成功与此。让我们考虑一个非常简单的语法: -

Expr -> Expr + Term 
     | Term 
Term -> Int 

我的词法分析器如下图所示。

%wrapper "posn" 

$digit = 0-9   -- digits 
$alpha = [a-zA-Z]  -- alphabetic characters 

tokens :- 

    $white+    ; 
    "--".*    ; 
    $digit+    { \p s -> L {getPos = p , unPos = Tok_Int (read s) }} 
    \+     { \p s -> L {getPos = p , unPos = Tok_Plus} } 


{ 
data L a = L{ getPos :: AlexPosn, unPos :: a } deriving (Eq,Show) 

data Token = 
     Tok_Plus 
    | Tok_Int Int 
    deriving (Eq,Show) 


getToken :: IO [L Token] 
getToken = do 
    args <- getArgs 
    case length args == 0 of 
     True -> do 
       error $ "\n****************Error: Expecting file name as an argument.\n" 
     False -> do 
      let fname = args !! 0 
      conts <- readFile fname 
      let tokens = alexScanTokens conts 
      return tokens 

} 

我的Yacc文件是一样的,这是我挣扎的地方。如何在我的语法树中嵌入位置信息。

{ 
{-# OPTIONS_GHC -fno-warn-incomplete-patterns -fno-warn-overlapping-patterns #-} 
module Parser where 
import Lexer 

} 

%name pExpr Exp 
%name pTerm Term 

%tokentype {L Token} 
%error { parseError } 

%token 
     int    { L { getPos = _,unPos = Tok_Int $$ } } 
     '+'    { L { getPos = _,unPos = Tok_Plus } } 

%% 
Exp :: {L Expr} 
Exp : Exp '+' Term   { L { getPos = getPos $1 , unPos = EAdd (unPos $1) (unPos $3) } } 
    | Term     { $1 } 

Term :: {L Expr} 
Term : int     { L {getPos = getPos $1, unPos = EInt (unPos $1) } } 

{ 

data Expr = EAdd Expr Expr 
      | EInt Int 
      deriving (Eq,Show) 


returnM :: a -> Err a 
returnM = return 

thenM :: Err a -> (a -> Err b) -> Err b 
thenM = (>>=) 


parseError :: [L Token] -> a 
parseError _ = error "Parse error" 

} 

当试图编译生成的Haskell文件时,出现以下类型的错误。

Parser.hs:109:39: 
    Couldn't match expected type `L a0' with actual type `Int' 
    In the first argument of `getPos', namely `happy_var_1' 
    In the `getPos' field of a record 
    In the first argument of `HappyAbsSyn5', namely 
     `(L {getPos = getPos happy_var_1, 
      unPos = EInt (unPos happy_var_1)})' 

Parser.hs:109:73: 
    Couldn't match expected type `L Int' with actual type `Int' 
    In the first argument of `unPos', namely `happy_var_1' 
    In the first argument of `EInt', namely `(unPos happy_var_1)' 
    In the `unPos' field of a record 

你们可以告诉我如何让这个东西有效吗?

回答

5

如果在词法分析器输出中可以使用快乐规则,您可以访问位置信息。这正是如何GHC自己将SrcLoc放入自己的Haskell代码的内部表示中。

基本上,你可以使用the posn Alex wrapper注入的位置信息到您的令牌类型:

data L a = L{ getPos :: AlexPosn, unPos :: a } 

(所以你的亚历克斯标记生成器将返回L Token值);然后你将你的快乐规则中的个人标记位置合并到非终结符的位置(例如,你可以有一个规则,从Expr + ExprL (combinedPosn [getPos $1, getPos $2, getPos $3] $ PlusExpr (unPos $1) (unPos $3)