edd07f19c76a04cc8d181624333a9c083385209e
[cc1516.git] / src / main.icl
1 module main
2
3 import StdFile
4 import StdBool
5 import StdMisc
6 import StdFunc
7 import StdList
8 import StdString
9 import Data.Either
10 import Data.Maybe
11 import System.CommandLine
12
13 import parse
14 import lex
15
16 :: Opts = {
17 program :: String,
18 lex :: Bool,
19 parse :: Bool,
20 fp :: Maybe String,
21 help :: Bool}
22
23 :: *StartType :== (LexerOutput, ParserOutput, *World)
24
25 Start :: *World -> *StartType
26 Start w
27 # (args, w) = parseArgs w
28 | args.help
29 # (out, w) = stdio w
30 # out = out <<< "\nUsage: " <<< args.program <<< " [opts] [FILENAME]\n"
31 <<< "\t--help Show this help\n"
32 <<< "\t--lex Lex only, is mutually exclusive with --parse\n"
33 <<< "\t--parse Lex & Parse only\n\n"
34 <<< "\tFILENAME File to parse, when unspecified stdin is parsed\n"
35 # (_, w) = fclose out w
36 = (Left "", Left "", w)
37 # (stdin, w) = stdio w
38 # (contents, stdin, w) = readFileOrStdin stdin args.fp w
39 | args.lex = case contents of
40 (Right cs) = (lexer cs, Left "Parsing Disabled", w)
41 (Left e) = (Left e, Left "Parsing disabled", w)
42 = case contents of
43 (Left e) = (Left e, Left "", w)
44 (Right cs) = let lexOut = lexer cs in (lexOut, parser lexOut, w)
45
46 parseArgs :: *World -> (Opts, *World)
47 parseArgs w
48 # ([p:args], w) = getCommandLine w
49 = (pa args {program=p, lex=False, parse=False, fp=Nothing, help=False}, w)
50 where
51 pa :: [String] -> (Opts -> Opts)
52 pa [] = id
53 pa ["--help":r] = \o.pa r {o & help=True}
54 pa ["--lex":r] = \o.pa r {o & lex=True, parse=False}
55 pa ["--parse":r] = \o.pa r {o & lex=False, parse=True}
56 pa [x:r] = \o.pa r {o & fp=Just x}
57
58 readFileOrStdin :: *File (Maybe String) *World -> *(Either String [Char], *File, *World)
59 readFileOrStdin stdin Nothing w
60 # (cs, stdin) = readEntireFile stdin
61 = (Right cs, stdin, w)
62 readFileOrStdin stdin (Just fp) w
63 # (b, fin, w) = fopen fp FReadText w
64 | not b = (Left "Unable to open file", stdin, w)
65 # (cs, fin) = readEntireFile fin
66 # (b, w) = fclose fin w
67 | not b = (Left "Unable to close file", stdin, w)
68 = (Right cs, stdin, w)
69
70 readEntireFile :: *File -> *([Char], *File)
71 readEntireFile f
72 # (b, c, f) = freadc f
73 | not b = ([], f)
74 # (cs, f) = readEntireFile f
75 = ([c:cs], f)