Comments nu mogelijk
[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)
45 # lexout = lexer cs
46 # parsout = parser lexout
47 # stdin = stdin <<< (either (const "") toString parsout)
48 # (_, w) = fclose stdin w
49 = (lexout, parser lexout, w)
50
51 parseArgs :: *World -> (Opts, *World)
52 parseArgs w
53 # ([p:args], w) = getCommandLine w
54 = (pa args {program=p, lex=False, parse=False, fp=Nothing, help=False}, w)
55 where
56 pa :: [String] -> (Opts -> Opts)
57 pa [] = id
58 pa ["--help":r] = \o.pa r {o & help=True}
59 pa ["--lex":r] = \o.pa r {o & lex=True, parse=False}
60 pa ["--parse":r] = \o.pa r {o & lex=False, parse=True}
61 pa [x:r] = \o.pa r {o & fp=Just x}
62
63 readFileOrStdin :: *File (Maybe String) *World -> *(Either String [Char], *File, *World)
64 readFileOrStdin stdin Nothing w
65 # (cs, stdin) = readEntireFile stdin
66 = (Right cs, stdin, w)
67 readFileOrStdin stdin (Just fp) w
68 # (b, fin, w) = fopen fp FReadText w
69 | not b = (Left "Unable to open file", stdin, w)
70 # (cs, fin) = readEntireFile fin
71 # (b, w) = fclose fin w
72 | not b = (Left "Unable to close file", stdin, w)
73 = (Right cs, stdin, w)
74
75 readEntireFile :: *File -> *([Char], *File)
76 readEntireFile f
77 # (b, c, f) = freadc f
78 | not b = ([], f)
79 # (cs, f) = readEntireFile f
80 = ([c:cs], f)