crafting-interpreters-hs/app/Main.hs

40 lines
1.1 KiB
Haskell
Raw Permalink Normal View History

2025-12-09 17:23:54 +03:00
import Lox.Scanner
2025-12-25 18:41:04 +03:00
import Lox.Parser
import Lox.Interpreter
2025-12-25 19:00:01 +03:00
import System.IO
2025-12-30 04:01:20 +03:00
import System.Environment
2025-12-09 17:23:54 +03:00
run :: String -> IO ()
2025-12-29 23:57:15 +03:00
run source = do
let tokensMaybe = scanTokensFromSource source
case tokensMaybe of
2025-12-30 06:58:23 +03:00
Left (LexicalError s) -> putStrLn s
2025-12-29 23:57:15 +03:00
Right tokens -> do
2025-12-30 01:27:01 +03:00
let stmtMaybe = parse tokens
case stmtMaybe of
2025-12-30 05:43:01 +03:00
Left (SyntaxError s) -> putStrLn s
2025-12-30 01:27:01 +03:00
Right statements -> runStatements statements
2025-12-09 17:23:54 +03:00
2025-12-30 06:53:05 +03:00
runEval :: String -> IO ()
runEval source = do
let tokensMaybe = scanTokensFromSource source
object <- case tokensMaybe of
2025-12-30 06:58:23 +03:00
Left (LexicalError s) -> putStrLn s >> return NullObject
2025-12-30 06:53:05 +03:00
Right tokens -> do
let exprMaybe = parseExpression tokens
case exprMaybe of
Left (SyntaxError s) -> putStrLn s >> return NullObject
Right statements -> eval statements
print object
2025-12-30 04:01:20 +03:00
repl :: IO ()
2025-12-30 06:53:05 +03:00
repl = putStr ">> " >> hFlush stdout >> getLine >>= runEval
2025-12-30 04:01:20 +03:00
2025-12-02 23:26:17 +03:00
main :: IO ()
2025-12-30 04:01:20 +03:00
main = getArgs >>= fs
fs :: [String] -> IO ()
fs [] = repl
fs [s] = readFile s >>= run
fs _ = putStrLn "Usage: lox [file]"