2 // driver.cs: The compiler command line driver.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Collections;
20 using System.Globalization;
21 using System.Diagnostics;
24 Library, Exe, Module, WinExe
28 /// The compiler driver.
34 // Assemblies references to be linked. Initialized with
36 static ArrayList references;
39 // If any of these fail, we ignore the problem. This is so
40 // that we can list all the assemblies in Windows and not fail
41 // if they are missing on Linux.
43 static ArrayList soft_references;
46 // Modules to be linked
48 static ArrayList modules;
51 static ArrayList link_paths;
53 // Whether we want to only run the tokenizer
54 static bool tokenize = false;
56 static string first_source;
58 static bool want_debugging_support = false;
60 static bool parse_only = false;
61 static bool timestamps = false;
62 static bool pause = false;
63 static bool show_counters = false;
66 // Whether to load the initial config file (what CSC.RSP has by default)
68 static bool load_default_config = true;
70 static Hashtable response_file_list;
73 // A list of resource files
75 static ArrayList resources;
76 static ArrayList embedded_resources;
77 static string win32ResourceFile;
78 static string win32IconFile;
81 // An array of the defines from the command line
83 static ArrayList defines;
88 static string output_file = null;
91 // Last time we took the time
93 static DateTime last_time, first_time;
96 // Encoding: ISO-Latin1 is 28591
98 static Encoding encoding;
101 // Whether the user has specified a different encoder manually
103 static bool using_default_encoder = true;
105 public static void ShowTime (string msg)
110 DateTime now = DateTime.Now;
111 TimeSpan span = now - last_time;
115 "[{0:00}:{1:000}] {2}",
116 (int) span.TotalSeconds, span.Milliseconds, msg);
119 public static void ShowTotalTime (string msg)
124 DateTime now = DateTime.Now;
125 TimeSpan span = now - first_time;
129 "[{0:00}:{1:000}] {2}",
130 (int) span.TotalSeconds, span.Milliseconds, msg);
133 static void tokenize_file (SourceFile file)
138 input = File.OpenRead (file.Name);
140 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
145 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
146 Tokenizer lexer = new Tokenizer (reader, file, defines);
147 int token, tokens = 0, errors = 0;
149 while ((token = lexer.token ()) != Token.EOF){
151 if (token == Token.ERROR)
154 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
160 // MonoTODO("Change error code for aborted compilation to something reasonable")]
161 static void parse (SourceFile file)
167 input = File.OpenRead (file.Name);
169 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
173 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
175 parser = new CSharpParser (reader, file, defines);
178 } catch (Exception ex) {
179 Report.Error(666, "Compilation aborted: " + ex);
185 static void OtherFlags ()
188 "Other flags in the compiler\n" +
189 " --fatal Makes errors fatal\n" +
190 " --parse Only parses the source file\n" +
191 " --stacktrace Shows stack trace at error location\n" +
192 " --timestamp Displays time stamps of various compiler events\n" +
193 " -2 Enables experimental C# features\n" +
194 " -v Verbose parsing (for debugging the parser)\n" +
195 " --mcs-debug X Sets MCS debugging level to X\n");
201 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
202 "mcs [options] source-files\n" +
203 " --about About the Mono C# compiler\n" +
204 " -addmodule:MODULE Adds the module to the generated assembly\n" +
205 " -checked[+|-] Set default context to checked\n" +
206 " -codepage:ID Sets code page to the one in ID\n" +
207 " (number, `utf8' or `reset')\n" +
208 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
209 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
210 " -debug[+|-] Generate debugging information\n" +
211 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
212 " -doc:FILE XML Documentation file to generate\n" +
213 " -g Generate debugging information\n" +
214 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
215 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
216 " -langversion:TEXT Specifies language version modes: ISO-1 or Default" + Environment.NewLine +
217 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
218 " -main:class Specified the class that contains the entry point\n" +
219 " -noconfig[+|-] Disables implicit references to assemblies\n" +
220 " -nostdlib[+|-] Does not load core libraries\n" +
221 " -nowarn:W1[,W2] Disables one or more warnings\n" +
222 " -optimize[+|-] Enables code optimalizations" + Environment.NewLine +
223 " -out:FNAME Specifies output file\n" +
224 " -pkg:P1[,Pn] References packages P1..Pn\n" +
225 " --expect-error X Expect that error X will be encountered\n" +
226 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
227 " -reference:ASS References the specified assembly (-r:ASS)\n" +
228 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
229 " library, module), (short: /t:)\n" +
230 " -unsafe[+|-] Allows unsafe code\n" +
231 " -warnaserror[+|-] Treat warnings as errors\n" +
232 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
233 " -help2 Show other help flags\n" +
236 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
237 " -resource:FILE[,ID] Embed FILE as a resource\n" +
238 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
239 " -win32icon:FILE Use this icon for the output\n" +
240 " @file Read response file for more options\n\n" +
241 "Options can be of the form -option or /option");
244 static void TargetUsage ()
246 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
252 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
253 "The compiler source code is released under the terms of the GNU GPL\n\n" +
255 "For more information on Mono, visit the project Web site\n" +
256 " http://www.go-mono.com\n\n" +
258 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
259 Environment.Exit (0);
262 public static int counter1, counter2;
264 public static int Main (string[] args)
266 bool ok = MainDriver (args);
268 if (ok && Report.Errors == 0) {
269 if (Report.Warnings > 0) {
270 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
273 Console.WriteLine ("Counter1: " + counter1);
274 Console.WriteLine ("Counter2: " + counter2);
280 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
281 Report.Errors, Report.Warnings);
286 static public void LoadAssembly (string assembly, bool soft)
289 string total_log = "";
292 char[] path_chars = { '/', '\\' };
294 if (assembly.IndexOfAny (path_chars) != -1) {
295 a = Assembly.LoadFrom (assembly);
297 string ass = assembly;
298 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
299 ass = assembly.Substring (0, assembly.Length - 4);
300 a = Assembly.Load (ass);
302 TypeManager.AddAssembly (a);
304 } catch (FileNotFoundException){
305 foreach (string dir in link_paths){
306 string full_path = Path.Combine (dir, assembly);
307 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
311 a = Assembly.LoadFrom (full_path);
312 TypeManager.AddAssembly (a);
314 } catch (FileNotFoundException ff) {
315 total_log += ff.FusionLog;
320 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
321 Console.WriteLine ("Log: \n" + total_log);
323 } catch (BadImageFormatException f) {
324 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
325 } catch (FileLoadException f){
326 Report.Error(6, "Cannot load assembly " + f.FusionLog);
327 } catch (ArgumentNullException){
328 Report.Error(6, "Cannot load assembly (null argument)");
332 static public void LoadModule (MethodInfo adder_method, string module)
335 string total_log = "";
339 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
341 catch (TargetInvocationException ex) {
342 throw ex.InnerException;
344 TypeManager.AddModule (m);
347 catch (FileNotFoundException){
348 foreach (string dir in link_paths){
349 string full_path = Path.Combine (dir, module);
350 if (!module.EndsWith (".netmodule"))
351 full_path += ".netmodule";
355 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
357 catch (TargetInvocationException ex) {
358 throw ex.InnerException;
360 TypeManager.AddModule (m);
362 } catch (FileNotFoundException ff) {
363 total_log += ff.FusionLog;
367 Report.Error (6, "Cannot find module `" + module + "'" );
368 Console.WriteLine ("Log: \n" + total_log);
369 } catch (BadImageFormatException f) {
370 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
371 } catch (FileLoadException f){
372 Report.Error(6, "Cannot load module " + f.FusionLog);
373 } catch (ArgumentNullException){
374 Report.Error(6, "Cannot load module (null argument)");
379 /// Loads all assemblies referenced on the command line
381 static public void LoadReferences ()
383 foreach (string r in references)
384 LoadAssembly (r, false);
386 foreach (string r in soft_references)
387 LoadAssembly (r, true);
392 static void SetupDefaultDefines ()
394 defines = new ArrayList ();
395 defines.Add ("__MonoCS__");
398 static string [] LoadArgs (string file)
401 ArrayList args = new ArrayList ();
404 f = new StreamReader (file);
409 StringBuilder sb = new StringBuilder ();
411 while ((line = f.ReadLine ()) != null){
414 for (int i = 0; i < t; i++){
417 if (c == '"' || c == '\''){
420 for (i++; i < t; i++){
427 } else if (c == ' '){
429 args.Add (sb.ToString ());
436 args.Add (sb.ToString ());
441 string [] ret_value = new string [args.Count];
442 args.CopyTo (ret_value, 0);
448 // Returns the directory where the system assemblies are installed
450 static string GetSystemDir ()
452 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
454 foreach (Assembly a in assemblies){
455 string codebase = a.Location;
456 string fn = System.IO.Path.GetFileName (codebase);
457 if (fn == "corlib.dll" || fn == "mscorlib.dll"){
458 return codebase.Substring (0, codebase.LastIndexOf (System.IO.Path.DirectorySeparatorChar));
462 Report.Error (-15, "Can not compute my system path");
467 // Given a path specification, splits the path from the file/pattern
469 static void SplitPathAndPattern (string spec, out string path, out string pattern)
471 int p = spec.LastIndexOf ('/');
474 // Windows does not like /file.cs, switch that to:
479 pattern = spec.Substring (1);
481 path = spec.Substring (0, p);
482 pattern = spec.Substring (p + 1);
487 p = spec.LastIndexOf ('\\');
489 path = spec.Substring (0, p);
490 pattern = spec.Substring (p + 1);
498 static void ProcessFile (string f)
500 if (first_source == null)
503 Location.AddFile (f);
506 static void ProcessFiles ()
508 Location.Initialize ();
510 foreach (SourceFile file in Location.SourceFiles) {
512 tokenize_file (file);
519 static void CompileFiles (string spec, bool recurse)
521 string path, pattern;
523 SplitPathAndPattern (spec, out path, out pattern);
524 if (pattern.IndexOf ('*') == -1){
529 string [] files = null;
531 files = Directory.GetFiles (path, pattern);
532 } catch (System.IO.DirectoryNotFoundException) {
533 Report.Error (2001, "Source file `" + spec + "' could not be found");
535 } catch (System.IO.IOException){
536 Report.Error (2001, "Source file `" + spec + "' could not be found");
539 foreach (string f in files) {
546 string [] dirs = null;
549 dirs = Directory.GetDirectories (path);
553 foreach (string d in dirs) {
555 // Don't include path in this string, as each
556 // directory entry already does
557 CompileFiles (d + "/" + pattern, true);
561 static void DefineDefaultConfig ()
564 // For now the "default config" is harcoded into the compiler
565 // we can move this outside later
567 string [] default_config = {
572 // Is it worth pre-loading all this stuff?
575 "System.Configuration.Install",
578 "System.DirectoryServices",
579 "System.Drawing.Design",
581 "System.EnterpriseServices",
584 "System.Runtime.Remoting",
585 "System.Runtime.Serialization.Formatters.Soap",
587 "System.ServiceProcess",
589 "System.Web.RegularExpressions",
590 "System.Web.Services",
591 "System.Windows.Forms"
596 foreach (string def in default_config)
597 soft_references.Insert (p++, def);
600 static void SetOutputFile (string name)
605 static void SetWarningLevel (string s)
610 level = Int32.Parse (s);
614 "--wlevel requires a value from 0 to 4");
615 Environment.Exit (1);
617 if (level < 0 || level > 4){
618 Report.Error (1900, "Warning level must be 0 to 4");
619 Environment.Exit (1);
621 RootContext.WarningLevel = level;
624 static void SetupV2 ()
626 RootContext.Version = LanguageVersion.Default;
627 defines.Add ("__V2__");
630 static void Version ()
632 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
633 Console.WriteLine ("Mono C# compiler version {0}", version);
634 Environment.Exit (0);
638 // Currently handles the Unix-like command line options, but will be
639 // deprecated in favor of the CSCParseOption, which will also handle the
640 // options that start with a dash in the future.
642 static bool UnixParseOption (string arg, ref string [] args, ref int i)
646 CSharpParser.yacc_verbose_flag++;
657 case "--main": case "-m":
658 if ((i + 1) >= args.Length){
660 Environment.Exit (1);
662 RootContext.MainClass = args [++i];
666 RootContext.Unsafe = true;
669 case "/?": case "/h": case "/help":
672 Environment.Exit (0);
676 if ((i + 1) >= args.Length){
678 Environment.Exit (1);
680 defines.Add (args [++i]);
683 case "--show-counters":
684 show_counters = true;
687 case "--expect-error": {
692 args [++i], NumberStyles.AllowLeadingSign);
693 Report.ExpectedError = code;
695 Report.Error (-14, "Invalid number specified");
706 if ((i + 1) >= args.Length){
708 Environment.Exit (1);
710 SetOutputFile (args [++i]);
714 RootContext.Checked = true;
718 Report.Stacktrace = true;
721 case "--linkresource":
723 if ((i + 1) >= args.Length){
725 Report.Error (5, "Missing argument to --linkres");
726 Environment.Exit (1);
728 if (resources == null)
729 resources = new ArrayList ();
731 resources.Add (args [++i]);
736 if ((i + 1) >= args.Length){
738 Report.Error (5, "Missing argument to --resource");
739 Environment.Exit (1);
741 if (embedded_resources == null)
742 embedded_resources = new ArrayList ();
744 embedded_resources.Add (args [++i]);
748 if ((i + 1) >= args.Length){
749 Environment.Exit (1);
753 string type = args [++i];
756 RootContext.Target = Target.Library;
757 RootContext.TargetExt = ".dll";
761 RootContext.Target = Target.Exe;
765 RootContext.Target = Target.WinExe;
769 RootContext.Target = Target.Module;
770 RootContext.TargetExt = ".dll";
774 Environment.Exit (1);
780 if ((i + 1) >= args.Length){
782 Environment.Exit (1);
785 references.Add (args [++i]);
789 if ((i + 1) >= args.Length){
791 Environment.Exit (1);
793 link_paths.Add (args [++i]);
797 RootContext.StdLib = false;
805 Report.WarningsAreErrors = true;
809 if ((i + 1) >= args.Length){
811 Environment.Exit (1);
816 warn = Int32.Parse (args [++i]);
819 Environment.Exit (1);
821 Report.SetIgnoreWarning (warn);
825 if ((i + 1) >= args.Length){
828 "--wlevel requires a value from 0 to 4");
829 Environment.Exit (1);
832 SetWarningLevel (args [++i]);
836 if ((i + 1) >= args.Length){
837 Report.Error (5, "--mcs-debug requires an argument");
838 Environment.Exit (1);
842 Report.DebugFlags = Int32.Parse (args [++i]);
844 Report.Error (5, "Invalid argument to --mcs-debug");
845 Environment.Exit (1);
854 if ((i + 1) >= args.Length){
855 Report.Error (5, "--recurse requires an argument");
856 Environment.Exit (1);
858 CompileFiles (args [++i], true);
863 last_time = first_time = DateTime.Now;
870 case "--debug": case "-g":
871 want_debugging_support = true;
875 load_default_config = false;
883 // Currently it is very basic option parsing, but eventually, this will
884 // be the complete option parser
886 static bool CSCParseOption (string option, ref string [] args, ref int i)
888 int idx = option.IndexOf (':');
895 arg = option.Substring (0, idx);
897 value = option.Substring (idx + 1);
908 RootContext.Target = Target.Exe;
912 RootContext.Target = Target.WinExe;
916 RootContext.Target = Target.Library;
917 RootContext.TargetExt = ".dll";
921 RootContext.Target = Target.Module;
922 RootContext.TargetExt = ".netmodule";
927 Environment.Exit (1);
935 Environment.Exit (1);
937 SetOutputFile (value);
942 RootContext.Optimize = true;
946 RootContext.Optimize = false;
950 case "/incremental+":
951 case "/incremental-":
961 Environment.Exit (1);
964 defs = value.Split (new Char [] {';', ','});
965 foreach (string d in defs){
972 case "/linkresource":
974 Report.Error (5, arg + " requires an argument");
975 Environment.Exit (1);
977 if (resources == null)
978 resources = new ArrayList ();
980 resources.Add (value);
988 Environment.Exit (1);
990 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
992 ProcessStartInfo pi = new ProcessStartInfo ();
993 pi.FileName = "pkg-config";
994 pi.RedirectStandardOutput = true;
995 pi.UseShellExecute = false;
996 pi.Arguments = "--libs " + packages;
999 p = Process.Start (pi);
1000 } catch (Exception e) {
1001 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1002 Environment.Exit (1);
1005 if (p.StandardOutput == null){
1006 Report.Warning (-27, "Specified package did not return any information");
1009 string pkgout = p.StandardOutput.ReadToEnd ();
1011 if (p.ExitCode != 0) {
1012 Report.Error (-27, "Error running pkg-config. Check the above output.");
1013 Environment.Exit (1);
1016 if (pkgout != null){
1017 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1018 Split (new Char [] { ' ', '\t'});
1019 args = AddArgs (args, xargs);
1029 Report.Error (5, "-resource requires an argument");
1030 Environment.Exit (1);
1032 if (embedded_resources == null)
1033 embedded_resources = new ArrayList ();
1035 if (embedded_resources.Contains (value)) {
1036 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1038 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1039 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1042 embedded_resources.Add (value);
1048 Report.Error (5, "-recurse requires an argument");
1049 Environment.Exit (1);
1051 CompileFiles (value, true);
1055 case "/reference": {
1057 Report.Error (5, "-reference requires an argument");
1058 Environment.Exit (1);
1061 string [] refs = value.Split (new char [] { ';', ',' });
1062 foreach (string r in refs){
1067 case "/addmodule": {
1069 Report.Error (5, arg + " requires an argument");
1070 Environment.Exit (1);
1073 string [] refs = value.Split (new char [] { ';', ',' });
1074 foreach (string r in refs){
1081 Report.Error (5, arg + " requires an argument");
1082 Environment.Exit (1);
1085 win32ResourceFile = value;
1088 case "/win32icon": {
1090 Report.Error (5, arg + " requires an argument");
1091 Environment.Exit (1);
1094 win32IconFile = value;
1099 Report.Error (2006, arg + " requires an argument");
1100 Environment.Exit (1);
1102 RootContext.Documentation = new Documentation (value);
1109 Report.Error (5, "/lib requires an argument");
1110 Environment.Exit (1);
1113 libdirs = value.Split (new Char [] { ',' });
1114 foreach (string dir in libdirs)
1115 link_paths.Add (dir);
1120 want_debugging_support = false;
1125 want_debugging_support = true;
1130 RootContext.Checked = true;
1134 RootContext.Checked = false;
1142 RootContext.VerifyClsCompliance = false;
1147 RootContext.Unsafe = true;
1151 RootContext.Unsafe = false;
1154 case "/warnaserror":
1155 case "/warnaserror+":
1156 Report.WarningsAreErrors = true;
1159 case "/warnaserror-":
1160 Report.WarningsAreErrors = false;
1164 SetWarningLevel (value);
1171 Report.Error (5, "/nowarn requires an argument");
1172 Environment.Exit (1);
1175 warns = value.Split (new Char [] {','});
1176 foreach (string wc in warns){
1178 int warn = Int32.Parse (wc);
1180 throw new ArgumentOutOfRangeException("warn");
1182 Report.SetIgnoreWarning (warn);
1184 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1185 Environment.Exit (1);
1192 load_default_config = true;
1197 load_default_config = false;
1202 Environment.Exit(0);
1208 Environment.Exit (0);
1214 Report.Error (5, arg + " requires an argument");
1215 Environment.Exit (1);
1217 RootContext.MainClass = value;
1222 RootContext.StdLib = false;
1226 RootContext.StdLib = true;
1233 if (value == String.Empty) {
1234 Report.Error (5, arg + " requires an argument");
1235 Environment.Exit (1);
1237 RootContext.StrongNameKeyFile = value;
1239 case "/keycontainer":
1240 if (value == String.Empty) {
1241 Report.Error (5, arg + " requires an argument");
1242 Environment.Exit (1);
1244 RootContext.StrongNameKeyContainer = value;
1247 RootContext.StrongNameDelaySign = true;
1250 RootContext.StrongNameDelaySign = false;
1255 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1259 case "/langversion":
1260 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1262 RootContext.Version = LanguageVersion.ISO_1;
1269 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1270 Environment.Exit (1);
1276 if (value == "utf8"){
1277 encoding = new UTF8Encoding();
1278 using_default_encoder = false;
1281 if (value == "reset"){
1283 // 28591 is the code page for ISO-8859-1 encoding.
1286 using_default_encoder = true;
1290 cp = Int32.Parse (value);
1291 encoding = Encoding.GetEncoding (cp);
1292 using_default_encoder = false;
1294 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1295 Environment.Exit (1);
1300 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1301 //Environment.Exit (1);
1305 static string [] AddArgs (string [] args, string [] extra_args)
1308 new_args = new string [extra_args.Length + args.Length];
1310 // if args contains '--' we have to take that into account
1311 // split args into first half and second half based on '--'
1312 // and add the extra_args before --
1313 int split_position = Array.IndexOf (args, "--");
1314 if (split_position != -1)
1316 Array.Copy (args, new_args, split_position);
1317 extra_args.CopyTo (new_args, split_position);
1318 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1322 args.CopyTo (new_args, 0);
1323 extra_args.CopyTo (new_args, args.Length);
1330 /// Parses the arguments, and drives the compilation
1335 /// TODO: Mostly structured to debug the compiler
1336 /// now, needs to be turned into a real driver soon.
1338 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1339 internal static bool MainDriver (string [] args)
1342 bool parsing_options = true;
1345 encoding = Encoding.GetEncoding (28591);
1347 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1348 encoding = Encoding.GetEncoding (1252);
1351 references = new ArrayList ();
1352 soft_references = new ArrayList ();
1353 modules = new ArrayList ();
1354 link_paths = new ArrayList ();
1356 SetupDefaultDefines ();
1361 // This is not required because Assembly.Load knows about this
1365 for (i = 0; i < args.Length; i++){
1366 string arg = args [i];
1370 if (arg.StartsWith ("@")){
1371 string [] extra_args;
1372 string response_file = arg.Substring (1);
1374 if (response_file_list == null)
1375 response_file_list = new Hashtable ();
1377 if (response_file_list.Contains (response_file)){
1379 1515, "Response file `" + response_file +
1380 "' specified multiple times");
1381 Environment.Exit (1);
1384 response_file_list.Add (response_file, response_file);
1386 extra_args = LoadArgs (response_file);
1387 if (extra_args == null){
1388 Report.Error (2011, "Unable to open response file: " +
1393 args = AddArgs (args, extra_args);
1397 if (parsing_options){
1399 parsing_options = false;
1403 if (arg.StartsWith ("-")){
1404 if (UnixParseOption (arg, ref args, ref i))
1408 string csc_opt = "/" + arg.Substring (1);
1409 if (CSCParseOption (csc_opt, ref args, ref i))
1412 if (arg.StartsWith ("/")){
1413 if (CSCParseOption (arg, ref args, ref i))
1419 CompileFiles (arg, false);
1428 // This will point to the NamespaceEntry of the last file that was parsed, and may
1429 // not be meaningful when resolving classes from other files. So, reset it to prevent
1432 RootContext.Tree.Types.NamespaceEntry = null;
1435 // If we are an exe, require a source file for the entry point
1437 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1438 if (first_source == null){
1439 Report.Error (2008, "No files to compile were specified");
1446 // If there is nothing to put in the assembly, and we are not a library
1448 if (first_source == null && embedded_resources == null && resources == null){
1449 Report.Error (2008, "No files to compile were specified");
1453 if (Report.Errors > 0)
1459 Tokenizer.Cleanup ();
1462 // Load Core Library for default compilation
1464 if (RootContext.StdLib)
1465 references.Insert (0, "mscorlib");
1467 if (load_default_config)
1468 DefineDefaultConfig ();
1470 if (Report.Errors > 0){
1475 // Load assemblies required
1478 ShowTime ("Loading references");
1479 link_paths.Add (GetSystemDir ());
1480 link_paths.Add (Directory.GetCurrentDirectory ());
1484 ShowTime (" References loaded");
1486 if (Report.Errors > 0){
1493 if (output_file == null){
1494 int pos = first_source.LastIndexOf ('.');
1497 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1499 output_file = first_source + RootContext.TargetExt;
1502 CodeGen.Init (output_file, output_file, want_debugging_support);
1504 if (RootContext.Target == Target.Module) {
1505 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1506 if (module_only == null) {
1507 Report.Error (0, new Location (-1), "Cannot use /target:module on this runtime: try the Mono runtime instead.");
1508 Environment.Exit (1);
1511 MethodInfo set_method = module_only.GetSetMethod (true);
1512 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1515 TypeManager.AddModule (CodeGen.Module.Builder);
1517 if (modules.Count > 0) {
1518 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1519 if (adder_method == null) {
1520 Report.Error (0, new Location (-1), "Cannot use /addmodule on this runtime: Try the Mono runtime instead.");
1521 Environment.Exit (1);
1524 foreach (string module in modules)
1525 LoadModule (adder_method, module);
1528 TypeManager.ComputeNamespaces ();
1531 // Before emitting, we need to get the core
1532 // types emitted from the user defined types
1533 // or from the system ones.
1536 ShowTime ("Initializing Core Types");
1537 if (!RootContext.StdLib){
1538 RootContext.ResolveCore ();
1539 if (Report.Errors > 0)
1543 TypeManager.InitCoreTypes ();
1545 ShowTime (" Core Types done");
1548 // The second pass of the compiler
1551 ShowTime ("Resolving tree");
1552 RootContext.ResolveTree ();
1554 if (Report.Errors > 0)
1557 ShowTime ("Populate tree");
1558 if (!RootContext.StdLib)
1559 RootContext.BootCorlib_PopulateCoreTypes ();
1561 RootContext.PopulateTypes ();
1562 RootContext.DefineTypes ();
1564 if (RootContext.Documentation != null &&
1565 !RootContext.Documentation.OutputDocComment (
1569 TypeManager.InitCodeHelpers ();
1572 // Verify using aliases now
1574 Namespace.VerifyUsing ();
1576 if (Report.Errors > 0){
1580 if (RootContext.VerifyClsCompliance) {
1581 CodeGen.Assembly.ResolveClsCompliance ();
1582 if (CodeGen.Assembly.IsClsCompliant) {
1583 AttributeTester.VerifyModulesClsCompliance ();
1584 TypeManager.LoadAllImportedTypes ();
1585 AttributeTester.VerifyTopLevelNameClsCompliance ();
1590 // The code generator
1593 ShowTime ("Emitting code");
1594 ShowTotalTime ("Total so far");
1595 RootContext.EmitCode ();
1599 if (Report.Errors > 0){
1604 ShowTime ("Closing types");
1606 RootContext.CloseTypes ();
1608 PEFileKinds k = PEFileKinds.ConsoleApplication;
1610 switch (RootContext.Target) {
1611 case Target.Library:
1613 k = PEFileKinds.Dll; break;
1615 k = PEFileKinds.ConsoleApplication; break;
1617 k = PEFileKinds.WindowApplication; break;
1620 if (RootContext.NeedsEntryPoint) {
1621 MethodInfo ep = RootContext.EntryPoint;
1624 if (RootContext.MainClass != null) {
1625 DeclSpace main_cont = RootContext.Tree.Decls [RootContext.MainClass] as DeclSpace;
1626 if (main_cont == null) {
1627 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1631 if (!(main_cont is ClassOrStruct)) {
1632 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1636 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1640 if (Report.Errors == 0)
1641 Report.Error (5001, "Program " + output_file +
1642 " does not have an entry point defined");
1646 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1647 } else if (RootContext.MainClass != null) {
1648 Report.Error (2017, "Can not specify -main: when building module or library");
1652 // Add the resources
1654 if (resources != null){
1655 foreach (string spec in resources){
1659 cp = spec.IndexOf (',');
1661 file = spec.Substring (0, cp);
1662 res = spec.Substring (cp + 1);
1666 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1670 if (embedded_resources != null){
1671 object[] margs = new object [2];
1672 Type[] argst = new Type [2];
1673 argst [0] = argst [1] = typeof (string);
1675 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1676 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1677 null, CallingConventions.Any, argst, null);
1679 if (embed_res == null) {
1680 Report.Warning (0, new Location (-1),
1681 "Cannot embed resources on this runtime: try the Mono runtime instead.");
1683 foreach (string spec in embedded_resources) {
1686 cp = spec.IndexOf (',');
1688 margs [0] = spec.Substring (cp + 1);
1689 margs [1] = spec.Substring (0, cp);
1692 margs [0] = Path.GetFileName (spec);
1695 if (File.Exists ((string) margs [1]))
1696 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1698 Report.Error (1566, "Can not find the resource " + margs [1]);
1705 // Add Win32 resources
1708 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1710 if (win32ResourceFile != null) {
1712 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1714 catch (ArgumentException) {
1715 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1719 if (win32IconFile != null) {
1720 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1721 if (define_icon == null) {
1722 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1724 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1727 if (Report.Errors > 0)
1730 CodeGen.Save (output_file);
1732 ShowTime ("Saved output");
1733 ShowTotalTime ("Total");
1736 Timer.ShowTimers ();
1738 if (Report.ExpectedError != 0) {
1739 if (Report.Errors == 0) {
1740 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1741 "No other errors reported.");
1743 Environment.Exit (2);
1745 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1746 "However, other errors were reported.");
1748 Environment.Exit (1);
1756 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1757 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1759 return (Report.Errors == 0);
1764 // This is the only public entry point
1766 public class CompilerCallableEntryPoint : MarshalByRefObject {
1767 static bool used = false;
1769 public bool InvokeCompiler (string [] args)
1773 bool ok = Driver.MainDriver (args);
1774 return ok && Report.Errors == 0;
1777 public void Reset ()