ligo/tools/lsp/squirrel/src/Parser.hs

445 lines
11 KiB
Haskell
Raw Normal View History

2020-04-30 14:39:51 +04:00
2020-05-08 01:18:26 +04:00
{-
The thing that can untangle the mess that tree-sitter produced.
If there be errors, it /will/ be a mess.
The AST you are building must:
1) Have first field with type `ASTInfo` in each non-error constructor at each
type.
2) Have `Error`-only constructor to represent failure and implement `Stubbed`.
I recommend parametrising your `AST` with some `info` typevar to be
`ASTInfo` in the moment of parsing.
I also recomment, in your tree-sitter grammar, to add `field("foo", ...)`
to each sub-rule, that has `$.` in front of it - in a rule, that doesn't
start with `_` in its name.
As a general rule of thumb, make each significant part a separate rule,
even if it is a keyword. Then, apply previous advice.
Only make rule start with `_` if it is a pure choice.
('block'
...
a: <a>
...
b: <b>
...)
->
block = do
subtree "block" do
ctor Block
<*> inside "a" a
<*> inside "b" b
-}
2020-05-08 22:14:09 +04:00
module Parser
( Parser
, runParser
, debugParser
, subtree
, anything
, token
, ASTInfo
, ctor
, inside
, many
, some
, (<|>)
, optional
, select
, dump
, stubbed
, Stubbed (stub)
, Error
, HasComments (getComments)
) where
2020-04-30 14:39:51 +04:00
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Reader
import Control.Monad.Except
import Control.Monad.Identity
import Data.Foldable
2020-05-08 20:38:41 +04:00
import Data.Functor
2020-04-30 14:39:51 +04:00
import Data.Text (Text, pack, unpack)
import qualified Data.Text as Text
2020-04-30 14:39:51 +04:00
import qualified Data.ByteString as ByteString
import Data.ByteString (ByteString)
import ParseTree
import Range
import Pretty
2020-04-30 14:39:51 +04:00
2020-04-30 17:46:39 +04:00
import Debug.Trace
2020-04-30 14:39:51 +04:00
2020-05-08 00:52:33 +04:00
-- | Parse error.
2020-04-30 14:39:51 +04:00
data Error
2020-04-30 21:06:01 +04:00
= Expected
2020-05-08 00:52:33 +04:00
{ eMsg :: Text -- ^ Description of what was expected.
, eWhole :: Text -- ^ Offending text.
, eRange :: Range -- ^ Location of the error.
2020-04-30 21:06:01 +04:00
}
2020-05-08 00:52:33 +04:00
deriving (Show) via PP Error
2020-04-30 14:39:51 +04:00
instance Pretty Error where
pp (Expected msg found r) = "" <> pp msg <> pp r <> "" <> pp found <> ""
2020-05-08 00:52:33 +04:00
-- | Parser of tree-sitter-made tree.
2020-05-08 22:07:53 +04:00
--
-- TODO: separate state. Polysemy?
--
2020-04-30 14:39:51 +04:00
newtype Parser a = Parser
{ unParser
2020-05-08 21:30:19 +04:00
:: WriterT [Error] -- Early I though to report errors that way.
( StateT (ParseForest, [Text]) -- Current forest to recognise + comments.
( ExceptT Error -- Backtracking. Change `Error` to `()`?
( Identity ))) -- I forgot why. `#include`? Debug via `print`?
2020-04-30 14:39:51 +04:00
a
}
deriving newtype
( Functor
, Applicative
, Monad
2020-05-08 21:30:19 +04:00
, MonadState (ParseForest, [Text])
2020-04-30 14:39:51 +04:00
, MonadWriter [Error]
, MonadError Error
)
2020-05-08 00:52:33 +04:00
-- | Generate error originating at current location.
2020-04-30 21:06:01 +04:00
makeError :: Text -> Parser Error
makeError msg = do
rng <- getRange
makeError' msg rng
2020-05-08 00:52:33 +04:00
-- | Generate error originating at given location.
2020-04-30 21:06:01 +04:00
makeError' :: Text -> Range -> Parser Error
makeError' msg rng = do
rng <- getRange
2020-05-08 21:30:19 +04:00
src <- gets (pfGrove . fst) <&> \case
2020-05-08 20:38:41 +04:00
[] -> ""
(,) _ ParseTree { ptSource } : _ -> ptSource
2020-04-30 21:06:01 +04:00
return Expected
{ eMsg = msg
, eWhole = src
, eRange = rng
}
2020-05-08 00:52:33 +04:00
-- | Pick next tree in a forest or die with msg.
2020-04-30 14:39:51 +04:00
takeNext :: Text -> Parser ParseTree
takeNext msg = do
2020-05-08 21:30:19 +04:00
(st@Forest {pfGrove, pfRange}, comms) <- get
2020-04-30 14:39:51 +04:00
case pfGrove of
[] -> die msg
(_, t) : f -> do
2020-05-08 21:30:19 +04:00
if "comment" `Text.isSuffixOf` ptName t
then do
(st, comms) <- get
put (st, ptSource t : comms)
takeNext msg
else do
put
( st
{ pfRange = diffRange pfRange (ptRange t)
, pfGrove = f
}
, comms
)
return t
2020-04-30 14:39:51 +04:00
2020-05-08 00:52:33 +04:00
-- | Pick a tree with that /field name/ or die with name as msg.
--
-- Will erase all subtrees with different names on the path!
--
2020-04-30 17:46:39 +04:00
field :: Text -> Parser a -> Parser a
2020-04-30 14:39:51 +04:00
field name parser = do
2020-05-08 21:30:19 +04:00
grove <- gets (pfGrove . fst)
2020-04-30 14:39:51 +04:00
case grove of
(name', t) : _
| name == name' -> do
sandbox True t
_ -> do
case lookup name grove of
Just tree -> sandbox False tree
Nothing -> die name
where
sandbox firstOne tree@ParseTree {ptID, ptRange} = do
2020-05-08 21:30:19 +04:00
(st@Forest {pfGrove = grove, pfRange = rng}, comments) <- get
let (errs, new_comments, grove') = delete name grove
put
( Forest
{ pfID = ptID
, pfGrove = [(name, tree)]
, pfRange = ptRange
}
, comments ++ new_comments
)
2020-04-30 14:39:51 +04:00
2020-05-08 20:38:41 +04:00
res <- parser
2020-05-08 21:30:19 +04:00
put
( st
{ pfGrove = grove'
, pfRange = if firstOne then diffRange rng ptRange else rng
}
, []
)
2020-04-30 14:39:51 +04:00
for_ errs (tell . pure . unexpected)
2020-05-08 20:38:41 +04:00
return res
2020-05-08 00:52:33 +04:00
-- | Variuos error reports.
2020-04-30 21:06:01 +04:00
fallback :: Stubbed a => Text -> Parser a
fallback' :: Stubbed a => Text -> Range -> Parser a
die :: Text -> Parser a
die' :: Text -> Range -> Parser a
complain :: Text -> Range -> Parser ()
fallback msg = pure . stub =<< makeError msg
fallback' msg rng = pure . stub =<< makeError' msg rng
die msg = throwError =<< makeError msg
die' msg rng = throwError =<< makeError' msg rng
complain msg rng = tell . pure =<< makeError' msg rng
2020-04-30 14:39:51 +04:00
unexpected :: ParseTree -> Error
unexpected ParseTree { ptSource, ptRange } =
Expected "unexpected" ptSource ptRange
2020-05-08 00:52:33 +04:00
-- | If a parser fails, return stub with error originating here.
2020-04-30 14:39:51 +04:00
stubbed :: Stubbed a => Text -> Parser a -> Parser a
stubbed msg parser = do
parser <|> fallback msg
2020-05-08 00:52:33 +04:00
-- | The forest must start with tree of that name. Its subtrees become new
-- forest. Otherwise, it dies with name as msg.
2020-04-30 14:39:51 +04:00
subtree :: Text -> Parser a -> Parser a
subtree msg parser = do
ParseTree {ptChildren, ptName} <- takeNext msg
if ptName == msg
then do
2020-05-08 21:30:19 +04:00
(save, comms) <- get
put (ptChildren, comms)
rest <- gets (pfGrove . fst)
collectErrors rest
2020-05-08 21:30:19 +04:00
(_, comms') <- get
parser <* put (save, comms')
2020-04-30 14:39:51 +04:00
else do
die msg
2020-05-08 00:52:33 +04:00
-- | Because `ExceptT` requires error to be `Monoid` for `Alternative`.
2020-04-30 14:39:51 +04:00
(<|>) :: Parser a -> Parser a -> Parser a
Parser l <|> Parser r = Parser (l `catchError` const r)
select :: [Parser a] -> Parser a
select = foldl1 (<|>)
optional :: Parser a -> Parser (Maybe a)
optional p = fmap Just p <|> return Nothing
2020-05-08 00:52:33 +04:00
-- | Custom `Alternative.many`.
--
2020-05-09 12:17:37 +04:00
-- TODO: remove, replace with `fields` combinator.
--
many :: Parser a -> Parser [a]
many p = many'
2020-04-30 14:39:51 +04:00
where
many' = some' <|> pure []
2020-04-30 17:46:39 +04:00
some' = do
x <- p
xs <- many'
return (x : xs)
2020-04-30 14:39:51 +04:00
2020-05-08 00:52:33 +04:00
-- | Custom `Alternative.some`.
--
some :: Parser a -> Parser [a]
some p = some'
2020-04-30 14:39:51 +04:00
where
many' = some' <|> pure []
2020-04-30 17:46:39 +04:00
some' = do
x <- p
xs <- many'
return (x : xs)
2020-05-08 00:52:33 +04:00
-- | Run parser on given file.
--
2020-04-30 14:39:51 +04:00
runParser :: Parser a -> FilePath -> IO (a, [Error])
runParser (Parser parser) fin = do
pforest <- toParseTree fin
let
res =
runIdentity
$ runExceptT
2020-05-08 21:30:19 +04:00
$ flip runStateT (pforest, [])
2020-04-30 14:39:51 +04:00
$ runWriterT
$ parser
either (error . show) (return . fst) res
2020-05-08 00:52:33 +04:00
-- | Run parser on given file and pretty-print stuff.
2020-05-08 21:30:19 +04:00
--
debugParser :: Show a => Parser a -> FilePath -> IO ()
debugParser parser fin = do
(res, errs) <- runParser parser fin
putStrLn "Result:"
print res
unless (null errs) do
putStrLn ""
putStrLn "Errors:"
for_ errs (print . nest 2 . pp)
2020-05-08 00:52:33 +04:00
-- | Consume next tree if it has give name. Or die.
2020-04-30 14:39:51 +04:00
token :: Text -> Parser Text
token node = do
2020-05-08 20:38:41 +04:00
tree@ParseTree {ptName, ptRange, ptSource} <- takeNext node
2020-04-30 14:39:51 +04:00
if ptName == node
2020-05-08 20:38:41 +04:00
then return ptSource
else die' node ptRange
2020-04-30 14:39:51 +04:00
2020-05-08 00:52:33 +04:00
-- | Consume next tree, return its textual representation.
2020-04-30 14:39:51 +04:00
anything :: Parser Text
anything = do
tree <- takeNext "anything"
2020-05-08 20:38:41 +04:00
return $ ptSource tree
2020-04-30 14:39:51 +04:00
2020-05-08 00:52:33 +04:00
-- | Get range of current tree or forest before the parser was run.
2020-04-30 14:39:51 +04:00
range :: Parser a -> Parser (a, Range)
range parser =
get >>= \case
2020-05-08 21:30:19 +04:00
(,) Forest {pfGrove = (,) _ ParseTree {ptRange} : _} _ -> do
2020-04-30 14:39:51 +04:00
a <- parser
return (a, ptRange)
2020-05-08 21:30:19 +04:00
(,) Forest {pfRange} _ -> do
2020-04-30 14:39:51 +04:00
a <- parser
return (a, pfRange)
2020-05-08 00:52:33 +04:00
-- | Get current range.
2020-04-30 14:39:51 +04:00
getRange :: Parser Range
getRange = snd <$> range (return ())
2020-05-08 00:52:33 +04:00
-- | Remove all keys until given key is found; remove the latter as well.
--
2020-05-08 21:30:19 +04:00
-- Also returns all ERROR-nodes.
--
-- TODO: rename.
--
2020-05-08 00:52:33 +04:00
-- Notice: this works differently from `Prelude.remove`!
--
2020-05-08 21:30:19 +04:00
delete :: Text -> [(Text, ParseTree)] -> ([ParseTree], [Text], [(Text, ParseTree)])
delete _ [] = ([], [], [])
2020-04-30 14:39:51 +04:00
delete k ((k', v) : rest) =
if k == k'
2020-05-08 21:30:19 +04:00
then (addIfError v [], addIfComment v [], rest)
else (addIfError v vs, addIfComment v cs, remains)
where
2020-05-08 21:30:19 +04:00
(vs, cs, remains) = delete k rest
addIfError v =
if ptName v == "ERROR"
then (:) v
else id
addIfComment v =
if "comment" `Text.isSuffixOf` ptName v
then (ptSource v :)
else id
-- | Report all ERRORs from the list.
collectErrors :: [(Text, ParseTree)] -> Parser ()
collectErrors vs =
for_ vs \(_, v) -> do
when (ptName v == "ERROR") do
tell [unexpected v]
2020-04-30 14:39:51 +04:00
2020-05-08 00:52:33 +04:00
-- | Parser negation.
2020-04-30 17:46:39 +04:00
notFollowedBy :: Parser a -> Parser ()
notFollowedBy parser = do
good <- do
parser
return False
<|> do
return True
unless good do
die "notFollowedBy"
2020-05-08 00:52:33 +04:00
-- | For types that have a default replacer with an `Error`.
2020-04-30 14:39:51 +04:00
class Stubbed a where
stub :: Error -> a
instance Stubbed Text where
stub = pack . show
2020-05-08 00:52:33 +04:00
-- | This is bad, but I had to.
--
2020-05-08 21:30:19 +04:00
-- TODO: Find a way to remove this instance.
-- I probably need a wrapper around '[]'.
2020-05-08 00:52:33 +04:00
--
instance Stubbed [a] where
stub _ = []
2020-05-08 00:52:33 +04:00
-- | `Nothing` would be bad default replacer.
instance Stubbed a => Stubbed (Maybe a) where
stub = Just . stub
2020-05-08 00:52:33 +04:00
-- | Universal accessor.
--
-- Usage:
--
-- > inside "$field:$treename"
-- > inside "$field"
-- > inside ":$treename" -- don't, use "subtree"
--
inside :: Stubbed a => Text -> Parser a -> Parser a
inside sig parser = do
let (f, st') = Text.breakOn ":" sig
let st = Text.drop 1 st'
if Text.null f
then do
2020-05-08 00:52:33 +04:00
-- The order is important.
subtree st do
stubbed f do
parser
else do
field f do
stubbed f do
if Text.null st
then do
parser
else do
subtree st do
parser
2020-05-08 00:52:33 +04:00
-- Auto-accumulated information to be fed into AST being build.
data ASTInfo = ASTInfo
{ aiRange :: Range
, aiComments :: [Text]
}
2020-05-08 21:30:19 +04:00
class HasComments c where
getComments :: c -> [Text]
instance HasComments ASTInfo where
getComments = aiComments
2020-05-08 00:52:33 +04:00
-- | Equip given constructor with info.
ctor :: (ASTInfo -> a) -> Parser a
2020-05-08 21:30:19 +04:00
ctor = (<$> (ASTInfo <$> getRange <*> grabComments))
grabComments :: Parser [Text]
grabComments = do
(st, comms) <- get
put (st, [])
return comms
2020-05-08 00:52:33 +04:00
-- | /Actual/ debug pring.
dump :: Parser ()
2020-05-08 21:30:19 +04:00
dump = gets (pfGrove . fst) >>= traceShowM