开发者

Happy parser rule order

开发者 https://www.devze.com 2023-02-15 01:28 出处:网络
I ran into a case using Happy (a Haskell parsing package) where the order of seemingly independent rules affects its behavior in a strange way.

I ran into a case using Happy (a Haskell parsing package) where the order of seemingly independent rules affects its behavior in a strange way.

{
module Parser where
}
%name constFoo
%name constBar
%tokentype开发者_C百科 { Token }
%error { parseError }
%token
    foo          { Foo }
    bar          { Bar }
%%
constFoo : foo { Foo }
constBar : bar { Bar }
{
parseError :: [Token] -> a
parseError _ = error "Parse error"
data Token = Bar | Foo deriving Show
}

As I understand how Happy works, both of the parses constFoo [Foo] and constBar [Bar] should succeed. However, with the above code, constFoo [Foo] succeeds but constBar [Bar] fails. If I swap the order of the rules for constFoo and constBar, the latter succeeds and the former fails.

Is there some aspect to Happy's semantics that I'm not understanding?


Edited - Happy's syntax allows you to specify the start production with the name directive:

%name parser constFoo

This creates a function called parser and it uses constFoo as the start production.

If you want parsers for both constFoo and constBar, this seems to be the syntax:

%name parser1 constFoo
%name parser2 constBar

I think in your original, both named parser functions (constFoo and constBar) defaulted to the first production in the grammar (constFoo).

0

精彩评论

暂无评论...
验证码 换一张
取 消