[Haskell-cafe] Parsec : Problems with operator precedence

Erik de Castro Lopo mle+cl at mega-nerd.com
Mon Dec 29 04:27:53 EST 2008

Hi all,

I'm using Text.ParserCombinators.Parsec.Expr to parse expressions for
a Javascript like language. This language has C-like logical operators
('&&' and '||') and bitwise operators ('&' and '|'). Furthermore, the
language definition states that bitwise operators have a higher precedence
than the logical ones.

I therefore have the following (trimmed):

    import qualified Text.ParserCombinators.Parsec.Expr as E

    opTable :: [[ E.Operator Char st Expression ]]
    opTable = [
        -- Operators listed from highest precedence to  lowest precedence.

        {- snip, snip -}

        [    binaryOp "&" BinOpBinAnd E.AssocLeft ],
        [    binaryOp "^"  BinOpBinXor E.AssocLeft ],
        [    binaryOp "|"  BinOpBinOr E.AssocLeft ],

        [    binaryOp "&&" BinOpLogAnd E.AssocLeft ],
        [    binaryOp "||" BinOpLogOr E.AssocLeft ]

    binaryOp :: String -> (SourcePos -> a -> a -> a) -> E.Assoc -> E.Operator Char st a
    binaryOp name con assoc =
        E.Infix (reservedOp name >>
            getPosition >>=
            return . con) assoc

but I still get the following parse error:

    unexpected "|"
    expecting end of "|" or term

on the line:

    if (name == null || value == null)

If I change the above from a logical to a bitwise OR, the parser
accepts it quite happily.

Any clues as to what I'm doing wrong here?

Erik de Castro Lopo
BSD:  A psychoactive drug, popular in the 80s, probably developed at UC
Berkeley or thereabouts.  Similar in many ways to the prescription-only
medication called "System V", but infinitely more useful. (Or, at least,
more fun.)  The full chemical name is "Berkeley Standard Distribution".

More information about the Haskell-Cafe mailing list