function to read bril from text file

This commit is contained in:
Enrico Lumetti 2024-10-05 17:16:13 +02:00
parent 031b812c51
commit 5a90054972
3 changed files with 46 additions and 3 deletions

36
bril-sources/add.json Normal file
View File

@ -0,0 +1,36 @@
"functions": [
{
"instrs": [
{
"dest": "v0",
"op": "const",
"type": "int",
"value": 1
},
{
"dest": "v1",
"op": "const",
"type": "int",
"value": 2
},
{
"args": [
"v0",
"v1"
],
"dest": "v2",
"op": "add",
"type": "int"
},
{
"args": [
"v2"
],
"op": "print"
}
],
"name": "main"
}
]
}

View File

@ -23,7 +23,8 @@ library eoc-lib
base >=4.13 && <4.18,
text >= 2.0,
aeson >= 2.2,
sorted-list ^>= 0.2
sorted-list ^>= 0.2,
bytestring >= 0.11
default-language: Haskell2010
default-extensions: DeriveGeneric, OverloadedStrings

View File

@ -2,9 +2,10 @@ module Bril (
Function (..), Type (..), Value (..), InstrOperation (..), FunctionArg (..), Program (..),
Instruction (..),
parseValue,
parseBrilFromPath, parseBrilJSON,
)where
import Data.Aeson (FromJSON, parseJSON, withObject, withText, (.:), (.:?), decode)
import Data.Aeson (FromJSON, parseJSON, withObject, withText, (.:), (.:?), eitherDecode)
import Data.Aeson.Types (Parser, modifyFailure)
import qualified Data.Aeson (Value, Object, Key)
import Data.Aeson.KeyMap
@ -14,6 +15,7 @@ import Data.Text.Read (Reader, signed, decimal)
import Data.SortedList
import Data.Maybe (fromMaybe, isJust)
import qualified Data.ByteString.Lazy as LB
data Program = Program { programFns :: [Function] }
deriving (Show, Eq)
@ -215,4 +217,8 @@ parseValue Int =
else fail $ "invalid int literal: " ++ (T.unpack v)
parseBrilJSON text = (decode text :: Maybe Program)
parseBrilJSON text = (eitherDecode text :: Either String Program)
parseBrilFromPath path = do
contents <- LB.readFile path
return $ parseBrilJSON contents