Haskell:为什么我的解析器不能正确回溯?

时间:2012-03-30 17:39:13

标签: html parsing haskell backtracking parsec

我决定自学如何使用Parsec,而且我自己分配了一个玩具项目的路障。

我正在尝试解析HTML,特别是:

<html>
  <head>
    <title>Insert Clever Title</title>
  </head>
  <body>
    What don't you like?
    <select id="some stuff">
      <option name="first" font="green">boilerplate</option>
      <option selected name="second" font="blue">parsing HTML with regexes</option>
      <option name="third" font="red">closing tags for option elements
    </select>
    That was short.
  </body>
</html>

我的代码是:

{-# LANGUAGE FlexibleContexts, RankNTypes #-}
module Main where

import System.Environment (getArgs)
import Data.Map hiding (null)
import Text.Parsec hiding ((<|>), label, many, optional)
import Text.Parsec.Token
import Control.Applicative

data HTML = Element { tag :: String, attributes :: Map String (Maybe String), children :: [HTML] }
          | Text { contents :: String }
  deriving (Show, Eq)

type HTMLParser a = forall s u m. Stream s m Char => ParsecT s u m a

htmlDoc :: HTMLParser HTML
htmlDoc = do
  spaces
  doc <- html
  spaces >> eof
  return doc

html :: HTMLParser HTML
html = text <|> element

text  :: HTMLParser HTML
text = Text <$> (many1 $ noneOf "<")

label :: HTMLParser String
label = many1 . oneOf $ ['a' .. 'z']  ++ ['A' .. 'Z']

value :: HTMLParser String
value = between (char '"') (char '"') (many anyChar) <|> label

attribute :: HTMLParser (String, Maybe String)
attribute = (,) <$> label <*> (optionMaybe $ spaces >> char '=' >> spaces >> value)

element :: HTMLParser HTML
element = do
  char '<' >> spaces
  tag <- label
  -- at least one space between each attribute and what was before
  attributes <- fromList <$> many (space >> spaces >> attribute)
  spaces >> char '>' 
  -- nested html
  children <- many html
  optional $ string "</" >> spaces >> string tag >> spaces >> char '>'
  return $ Element tag attributes children

main = do
  source : _ <- getArgs
  result <- parse htmlDoc source <$> readFile source
  print result

问题似乎是我的解析器不喜欢结束标记 - 似乎贪婪地假设<总是意味着一个开始标记(据我所知):

% HTMLParser temp.html
Left "temp.html" (line 3, column 32):
unexpected "/"
expecting white space

我已经玩了一段时间,但我不确定为什么它不会超越char '<'匹配。

1 个答案:

答案 0 :(得分:2)

像ehird说的那样,我需要尝试使用:

attribute = (,) <$> label <*> (optionMaybe . try $ spaces >> char '=' >> spaces >> value) 
--...
attributes <- fromList <$> many (try $ space >> spaces >> attribute)
--...
children <- many $ try html
optional . try $ string "</" >> spaces >> string tag >> spaces >> char '>'