[Haskell-beginners] Happy generated parser fails to compile.

Rohit Garg rpg.314 at gmail.com
Sun Sep 26 10:58:05 EDT 2010


Hi,

Following is a simple parser definition I am trying to write for
simple numerical expressions. A sequence of numerical expressions
actually. Happy reports that there are 3 un-used terminals. AFAIK,
they should be let, in and '='. Is that correct?

Although, happy generates a .hs file without any other message. GHC
gives a type mismatch error. I don't suppose it could be a lexer
error, could it?

a) Could this be a bug in Happy (very unlikely, IMO) it is generating
code that has type mismatches.

b) If there is a bug in my parser definition, shouldn't Happy beep on it?

Any suggestions to fix it will be highly appreciated.

Thanks,
===================
{
module Main where
import Tokens_posn
}

%name calc
%tokentype { Token }

%token  let		{ Let _     }
	in		{ In  _     }
	';'		{ Newstatement _ }
	int		{ Int _ $$  }
	var		{ Var _ $$  }
	'='		{ Sym _ '=' }
	'+'		{ Sym _ '+' }
	'-'		{ Sym _ '-' }
	'*'		{ Sym _ '*' }
	'/'		{ Sym _ '/' }
	'('		{ Sym _ '(' }
	')'		{ Sym _ ')' }

%%

Exprs   :: { [ Expr ] }
Exprs   : Exprs Expr ';'                { $2 : $1 }
	| Expr ';'                      { [$1] }

Expr : Expr '+' Term		{ PlusE  $1 $3  }
     | Expr '-' Term		{ MinusE $1 $3  }
     | Term			{ $1            }

Term : Term '*' Factor		{ TimesE $1 $3  }
     | Term '/' Factor		{ DivE $1 $3    }
     | Factor			{ $1            }

Factor : '-' Atom		{ NegE $2	}
       | Atom			{ $1		}

Atom : int			{ IntE $1   }
       | var			{ VarE $1       }
       | '(' Expr ')'		{ $2            }

{
data Expr =
	LetE   String Expr Expr |
	PlusE  Expr Expr        |
	MinusE Expr Expr        |
	TimesE Expr Expr        |
	DivE   Expr Expr        |
	NegE   Expr	      |
	IntE   Int            |
	VarE   String
	deriving Show

flist :: [Int] -> Int -> [Int]
flist x a = a : x

main:: IO ()
main =  interact (show.runCalc)

runCalc :: String -> Expr
runCalc = calc . alexScanTokens

happyError :: [Token] -> a
happyError tks = error ("Parse error at " ++ lcn ++ "\n")
	where
	lcn = 	case tks of
		  [] -> "end of file"
		  tk:_ -> "line " ++ show l ++ ", column " ++ show c
			where
			AlexPn _ l c = token_posn tk
}

-- 
Rohit Garg

http://rpg-314.blogspot.com/


More information about the Beginners mailing list