Copy system environment into initial env, and also add %stdlib.
[goals.git] / src / main.ml
1 (* Goalfile parser
2  * Copyright (C) 2019 Richard W.M. Jones
3  * Copyright (C) 2019 Red Hat Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  *)
19
20 open Printf
21
22 open Utils
23
24 (* See comment in parser.mly. *)
25 let () =
26   Parser.lexer_read := Some Lexer.read;
27   Parser.eval_substitute := Some Eval.substitute
28
29 let main () =
30   (* Change directory (-C option). *)
31   Sys.chdir Cmdline.directory;
32
33   (* Create the initial environment, containing the system environment
34    * and a few other standard strings.
35    *)
36   let env =
37     Array.fold_left (
38       fun env environ ->
39         let k, v = split "=" environ in
40         Ast.Env.add k (Ast.EConstant (Ast.noloc, Ast.CString v)) env
41     ) Ast.Env.empty (Unix.environment ()) in
42   let env =
43     Ast.Env.add "stdlib"
44       (Ast.EConstant (Ast.noloc, Ast.CString Cmdline.stdlibdir))
45       env in
46   (*let env =
47     if Cmdline.debug_flag then Ast.Env.add "debug" (Ast.EConstant (noloc, Ast.CBool true)) env else env in *)
48
49   (* Parse the prelude. *)
50   let env =
51     if Cmdline.use_prelude then
52       Parse.parse_goalfile env Cmdline.prelude_gl_file
53     else env in
54
55   (* Parse the input file. *)
56   let env = Parse.parse_goalfile env Cmdline.input_file in
57
58   (* Parse the command line assignments. *)
59   let env =
60     List.fold_left (
61       fun env (name, expr) ->
62         let expr = Parse.parse_expr "commandline" expr in
63         Ast.Env.add name expr env
64     ) env Cmdline.anon_vars in
65
66   (* Parse the target expressions. *)
67   let targets = List.map (Parse.parse_expr "commandline") Cmdline.targets in
68
69   (* If no target was set on the command line, use "all ()". *)
70   let targets =
71     if targets <> [] then targets
72     else [Ast.ECall (Ast.noloc, "all", [])] in
73
74   if Cmdline.debug_flag then
75     Ast.print_env stderr env;
76
77   (* Run the target expressions. *)
78   Run.run_targets env targets
79
80 let () =
81   try main ()
82   with
83     Failure msg | Sys_error msg ->
84       prerr_endline ("error: " ^ msg); exit 1