X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=src%2Fadvent18%2FAdvent18Parser.hs;fp=src%2Fadvent18%2FAdvent18Parser.hs;h=4489fdd27b97e2b95b1703ce4612efe268594e9e;hb=eefbb6bc370b6ae9c2ad16f7daaeac78642025d3;hp=0000000000000000000000000000000000000000;hpb=9ce2b21f9734aa6e51186d2cc0075083a5864155;p=advent-of-code-17.git diff --git a/src/advent18/Advent18Parser.hs b/src/advent18/Advent18Parser.hs new file mode 100644 index 0000000..4489fdd --- /dev/null +++ b/src/advent18/Advent18Parser.hs @@ -0,0 +1,49 @@ +module Advent18Parser (successfulParse, Location(..), Instruction(..)) where + +import Data.Text (Text) +import Text.Megaparsec hiding (State) +import qualified Text.Megaparsec.Lexer as L +import Text.Megaparsec.Text (Parser) +import qualified Control.Applicative as CA + +data Location = Literal Integer | Register Char deriving (Show, Eq) +data Instruction = Snd Location + | Set Location Location + | Add Location Location + | Mul Location Location + | Mod Location Location + | Rcv Location + | Jgz Location Location + deriving (Show, Eq) + + +sc :: Parser () +sc = L.space (skipSome spaceChar) CA.empty CA.empty + +lexeme = L.lexeme sc + +integer = lexeme L.integer +signedInteger = L.signed sc integer + +symb = L.symbol sc +reg = lexeme (some letterChar) + +location = (Literal <$> signedInteger) <|> register +register = (Register . head) <$> reg + +instructionsP = instructionP `sepBy` space +instructionP = choice [sndP, setP, addP, mulP, modP, rcvP, jgzP] + +sndP = Snd <$> (try (symb "snd") *> location) +setP = Set <$> (try (symb "set") *> register) <*> location +addP = Add <$> (try (symb "add") *> register) <*> location +mulP = Mul <$> (try (symb "mul") *> register) <*> location +modP = Mod <$> (try (symb "mod") *> register) <*> location +rcvP = Rcv <$> (try (symb "rcv") *> location) +jgzP = Jgz <$> (try (symb "jgz") *> location) <*> location + +successfulParse :: Text -> [Instruction] +successfulParse input = + case parse instructionsP "input" input of + Left _error -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err + Right instructions -> instructions \ No newline at end of file