Search code examples
parsinghaskellparser-combinators

Haskell -- parser combinators keywords


I am working on building a parser in Haskell using parser combinators. I have an issue with parsing keywords such as "while", "true", "if" etc

So the issue I am facing is that after a keyword there is a requirement that there is a separator or whitespace, for example in the statement if cond then stat1 else stat2 fi;x = 1 with this statement all keywords have either a space in front of them or a semi colon. However in different situations there can be different separators.

Currently I have implemented it as follows:

keyword :: String -> Parser String
keyword k = do
  kword <- leadingWS (string k)
  check (== ';') <|> check isSpace <|> check (== ',') <|> check (== ']')
  junk
  return word

however the problem with this keyword parser is that it will allow programs which have statements like if; cond then stat1 else stat2 fi

We tried passing in a (Char -> Bool) to keyword, which would then be passed to check. But this wouldn’t work because where we parse the keyword we don’t know what kind of separator is allowed.

I was wondering if I could have some help with this issue?


Solution

  • Don't try to handle the separators in keyword but you need to ensure that keyword "if" will not be confused with an identifier "iffy" (see comment by sepp2k).

    keyword :: String -> Parser String
    keyword k = leadingWS $ try (do string k
                                    notFollowedBy alphanum)
    

    Handling separators for statements would go like this:

    statements = statement `sepBy` semi
    statement  = ifStatement <|> assignmentStatement <|> ...