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;
71 // A list of resource files
73 static ArrayList resources;
74 static ArrayList embedded_resources;
75 static string win32ResourceFile;
76 static string win32IconFile;
79 // An array of the defines from the command line
81 static ArrayList defines;
86 static string output_file = null;
89 // Last time we took the time
91 static DateTime last_time, first_time;
94 // Encoding: ISO-Latin1 is 28591
96 static Encoding encoding;
99 // Whether the user has specified a different encoder manually
101 static bool using_default_encoder = true;
104 static public void Reset ()
106 want_debugging_support = false;
110 show_counters = false;
111 load_default_config = true;
112 resources = embedded_resources = null;
113 win32ResourceFile = win32IconFile = null;
117 using_default_encoder = true;
121 public static void ShowTime (string msg)
126 DateTime now = DateTime.Now;
127 TimeSpan span = now - last_time;
131 "[{0:00}:{1:000}] {2}",
132 (int) span.TotalSeconds, span.Milliseconds, msg);
135 public static void ShowTotalTime (string msg)
140 DateTime now = DateTime.Now;
141 TimeSpan span = now - first_time;
145 "[{0:00}:{1:000}] {2}",
146 (int) span.TotalSeconds, span.Milliseconds, msg);
149 static void tokenize_file (SourceFile file)
154 input = File.OpenRead (file.Name);
156 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
161 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
162 Tokenizer lexer = new Tokenizer (reader, file, defines);
163 int token, tokens = 0, errors = 0;
165 while ((token = lexer.token ()) != Token.EOF){
167 if (token == Token.ERROR)
170 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
176 // MonoTODO("Change error code for aborted compilation to something reasonable")]
177 static void parse (SourceFile file)
183 input = File.OpenRead (file.Name);
185 Report.Error (2001, "Source file '" + file.Name + "' could not be opened");
189 SeekableStreamReader reader = new SeekableStreamReader (input, encoding, using_default_encoder);
191 parser = new CSharpParser (reader, file, defines);
192 parser.ErrorOutput = Report.Stderr;
195 } catch (Exception ex) {
196 Report.Error(666, "Compilation aborted: " + ex);
202 static void OtherFlags ()
205 "Other flags in the compiler\n" +
206 " --fatal Makes errors fatal\n" +
207 " --parse Only parses the source file\n" +
208 " --stacktrace Shows stack trace at error location\n" +
209 " --timestamp Displays time stamps of various compiler events\n" +
210 " --expect-error X Expect that error X will be encountered\n" +
211 " -2 Enables experimental C# features\n" +
212 " -v Verbose parsing (for debugging the parser)\n" +
213 " --mcs-debug X Sets MCS debugging level to X\n");
219 "Mono C# compiler, (C) 2001 - 2003 Ximian, Inc.\n" +
220 "mcs [options] source-files\n" +
221 " --about About the Mono C# compiler\n" +
222 " -addmodule:MODULE Adds the module to the generated assembly\n" +
223 " -checked[+|-] Set default context to checked\n" +
224 " -codepage:ID Sets code page to the one in ID (number, utf8, reset)\n" +
225 " -clscheck[+|-] Disables CLS Compliance verifications" + Environment.NewLine +
226 " -define:S1[;S2] Defines one or more symbols (short: /d:)\n" +
227 " -debug[+|-], -g Generate debugging information\n" +
228 " -delaysign[+|-] Only insert the public key into the assembly (no signing)\n" +
229 " -doc:FILE XML Documentation file to generate\n" +
230 " -keycontainer:NAME The key pair container used to strongname the assembly\n" +
231 " -keyfile:FILE The strongname key file used to strongname the assembly\n" +
232 " -langversion:TEXT Specifies language version modes: ISO-1 or Default\n" +
233 " -lib:PATH1,PATH2 Adds the paths to the assembly link path\n" +
234 " -main:class Specified the class that contains the entry point\n" +
235 " -noconfig[+|-] Disables implicit references to assemblies\n" +
236 " -nostdlib[+|-] Does not load core libraries\n" +
237 " -nowarn:W1[,W2] Disables one or more warnings\n" +
238 " -optimize[+|-] Enables code optimalizations\n" +
239 " -out:FNAME Specifies output file\n" +
240 " -pkg:P1[,Pn] References packages P1..Pn\n" +
241 " -recurse:SPEC Recursively compiles the files in SPEC ([dir]/file)\n" +
242 " -reference:ASS References the specified assembly (-r:ASS)\n" +
243 " -target:KIND Specifies the target (KIND is one of: exe, winexe,\n" +
244 " library, module), (short: /t:)\n" +
245 " -unsafe[+|-] Allows unsafe code\n" +
246 " -warnaserror[+|-] Treat warnings as errors\n" +
247 " -warn:LEVEL Sets warning level (the highest is 4, the default is 2)\n" +
248 " -help2 Show other help flags\n" +
251 " -linkresource:FILE[,ID] Links FILE as a resource\n" +
252 " -resource:FILE[,ID] Embed FILE as a resource\n" +
253 " -win32res:FILE Specifies Win32 resource file (.res)\n" +
254 " -win32icon:FILE Use this icon for the output\n" +
255 " @file Read response file for more options\n\n" +
256 "Options can be of the form -option or /option");
259 static void TargetUsage ()
261 Report.Error (2019, "Valid options for -target: are exe, winexe, library or module");
267 "The Mono C# compiler is (C) 2001, 2002, 2003 Ximian, Inc.\n\n" +
268 "The compiler source code is released under the terms of the GNU GPL\n\n" +
270 "For more information on Mono, visit the project Web site\n" +
271 " http://www.go-mono.com\n\n" +
273 "The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath");
274 Environment.Exit (0);
277 public static int counter1, counter2;
279 public static int Main (string[] args)
281 bool ok = MainDriver (args);
283 if (ok && Report.Errors == 0) {
284 if (Report.Warnings > 0) {
285 Console.WriteLine ("Compilation succeeded - {0} warning(s)", Report.Warnings);
288 Console.WriteLine ("Counter1: " + counter1);
289 Console.WriteLine ("Counter2: " + counter2);
295 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
296 Report.Errors, Report.Warnings);
301 static public void LoadAssembly (string assembly, bool soft)
304 string total_log = "";
307 char[] path_chars = { '/', '\\' };
309 if (assembly.IndexOfAny (path_chars) != -1) {
310 a = Assembly.LoadFrom (assembly);
312 string ass = assembly;
313 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
314 ass = assembly.Substring (0, assembly.Length - 4);
315 a = Assembly.Load (ass);
317 TypeManager.AddAssembly (a);
319 } catch (FileNotFoundException){
320 foreach (string dir in link_paths){
321 string full_path = Path.Combine (dir, assembly);
322 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
326 a = Assembly.LoadFrom (full_path);
327 TypeManager.AddAssembly (a);
329 } catch (FileNotFoundException ff) {
330 total_log += ff.FusionLog;
335 Report.Error (6, "Cannot find assembly `" + assembly + "'" );
336 Console.WriteLine ("Log: \n" + total_log);
338 } catch (BadImageFormatException f) {
339 Report.Error(6, "Cannot load assembly (bad file format)" + f.FusionLog);
340 } catch (FileLoadException f){
341 Report.Error(6, "Cannot load assembly " + f.FusionLog);
342 } catch (ArgumentNullException){
343 Report.Error(6, "Cannot load assembly (null argument)");
347 static public void LoadModule (MethodInfo adder_method, string module)
350 string total_log = "";
354 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { module });
356 catch (TargetInvocationException ex) {
357 throw ex.InnerException;
359 TypeManager.AddModule (m);
362 catch (FileNotFoundException){
363 foreach (string dir in link_paths){
364 string full_path = Path.Combine (dir, module);
365 if (!module.EndsWith (".netmodule"))
366 full_path += ".netmodule";
370 m = (Module)adder_method.Invoke (CodeGen.Assembly.Builder, new object [] { full_path });
372 catch (TargetInvocationException ex) {
373 throw ex.InnerException;
375 TypeManager.AddModule (m);
377 } catch (FileNotFoundException ff) {
378 total_log += ff.FusionLog;
382 Report.Error (6, "Cannot find module `" + module + "'" );
383 Console.WriteLine ("Log: \n" + total_log);
384 } catch (BadImageFormatException f) {
385 Report.Error(6, "Cannot load module (bad file format)" + f.FusionLog);
386 } catch (FileLoadException f){
387 Report.Error(6, "Cannot load module " + f.FusionLog);
388 } catch (ArgumentNullException){
389 Report.Error(6, "Cannot load module (null argument)");
394 /// Loads all assemblies referenced on the command line
396 static public void LoadReferences ()
398 foreach (string r in references)
399 LoadAssembly (r, false);
401 foreach (string r in soft_references)
402 LoadAssembly (r, true);
407 static void SetupDefaultDefines ()
409 defines = new ArrayList ();
410 defines.Add ("__MonoCS__");
413 static string [] LoadArgs (string file)
416 ArrayList args = new ArrayList ();
419 f = new StreamReader (file);
424 StringBuilder sb = new StringBuilder ();
426 while ((line = f.ReadLine ()) != null){
429 for (int i = 0; i < t; i++){
432 if (c == '"' || c == '\''){
435 for (i++; i < t; i++){
442 } else if (c == ' '){
444 args.Add (sb.ToString ());
451 args.Add (sb.ToString ());
456 string [] ret_value = new string [args.Count];
457 args.CopyTo (ret_value, 0);
463 // Returns the directory where the system assemblies are installed
465 static string GetSystemDir ()
467 return Path.GetDirectoryName (typeof (object).Assembly.Location);
471 // Given a path specification, splits the path from the file/pattern
473 static void SplitPathAndPattern (string spec, out string path, out string pattern)
475 int p = spec.LastIndexOf ('/');
478 // Windows does not like /file.cs, switch that to:
483 pattern = spec.Substring (1);
485 path = spec.Substring (0, p);
486 pattern = spec.Substring (p + 1);
491 p = spec.LastIndexOf ('\\');
493 path = spec.Substring (0, p);
494 pattern = spec.Substring (p + 1);
502 static void ProcessFile (string f)
504 if (first_source == null)
507 Location.AddFile (f);
510 static void ProcessFiles ()
512 Location.Initialize ();
514 foreach (SourceFile file in Location.SourceFiles) {
516 tokenize_file (file);
523 static void CompileFiles (string spec, bool recurse)
525 string path, pattern;
527 SplitPathAndPattern (spec, out path, out pattern);
528 if (pattern.IndexOf ('*') == -1){
533 string [] files = null;
535 files = Directory.GetFiles (path, pattern);
536 } catch (System.IO.DirectoryNotFoundException) {
537 Report.Error (2001, "Source file `" + spec + "' could not be found");
539 } catch (System.IO.IOException){
540 Report.Error (2001, "Source file `" + spec + "' could not be found");
543 foreach (string f in files) {
550 string [] dirs = null;
553 dirs = Directory.GetDirectories (path);
557 foreach (string d in dirs) {
559 // Don't include path in this string, as each
560 // directory entry already does
561 CompileFiles (d + "/" + pattern, true);
565 static void DefineDefaultConfig ()
568 // For now the "default config" is harcoded into the compiler
569 // we can move this outside later
571 string [] default_config = {
576 // Is it worth pre-loading all this stuff?
579 "System.Configuration.Install",
582 "System.DirectoryServices",
583 "System.Drawing.Design",
585 "System.EnterpriseServices",
588 "System.Runtime.Remoting",
589 "System.Runtime.Serialization.Formatters.Soap",
591 "System.ServiceProcess",
593 "System.Web.RegularExpressions",
594 "System.Web.Services",
595 "System.Windows.Forms"
600 foreach (string def in default_config)
601 soft_references.Insert (p++, def);
604 static void SetOutputFile (string name)
609 static void SetWarningLevel (string s)
614 level = Int32.Parse (s);
618 "--wlevel requires a value from 0 to 4");
621 if (level < 0 || level > 4){
622 Report.Error (1900, "Warning level must be 0 to 4");
625 RootContext.WarningLevel = level;
628 static void SetupV2 ()
630 RootContext.Version = LanguageVersion.Default;
631 defines.Add ("__V2__");
634 static void Version ()
636 string version = Assembly.GetExecutingAssembly ().GetName ().Version.ToString ();
637 Console.WriteLine ("Mono C# compiler version {0}", version);
638 Environment.Exit (0);
642 // Currently handles the Unix-like command line options, but will be
643 // deprecated in favor of the CSCParseOption, which will also handle the
644 // options that start with a dash in the future.
646 static bool UnixParseOption (string arg, ref string [] args, ref int i)
650 CSharpParser.yacc_verbose_flag++;
661 case "--main": case "-m":
662 Report.Warning (-29, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
663 if ((i + 1) >= args.Length){
665 Environment.Exit (1);
667 RootContext.MainClass = args [++i];
671 Report.Warning (-29, "Compatibility: Use -unsafe instead of --unsafe");
672 RootContext.Unsafe = true;
675 case "/?": case "/h": case "/help":
678 Environment.Exit (0);
682 Report.Warning (-29, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
683 if ((i + 1) >= args.Length){
685 Environment.Exit (1);
687 defines.Add (args [++i]);
690 case "--show-counters":
691 show_counters = true;
694 case "--expect-error": {
699 args [++i], NumberStyles.AllowLeadingSign);
700 Report.ExpectedError = code;
702 Report.Error (-14, "Invalid number specified");
713 Report.Warning (-29, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
714 if ((i + 1) >= args.Length){
716 Environment.Exit (1);
718 SetOutputFile (args [++i]);
722 Report.Warning (-29, "Compatibility: Use -checked instead of --checked");
723 RootContext.Checked = true;
727 Report.Stacktrace = true;
730 case "--linkresource":
732 Report.Warning (-29, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
733 if ((i + 1) >= args.Length){
735 Report.Error (5, "Missing argument to --linkres");
736 Environment.Exit (1);
738 if (resources == null)
739 resources = new ArrayList ();
741 resources.Add (args [++i]);
746 Report.Warning (-29, "Compatibility: Use -res:VALUE instead of --res VALUE");
747 if ((i + 1) >= args.Length){
749 Report.Error (5, "Missing argument to --resource");
750 Environment.Exit (1);
752 if (embedded_resources == null)
753 embedded_resources = new ArrayList ();
755 embedded_resources.Add (args [++i]);
759 Report.Warning (-29, "Compatibility: Use -target:KIND instead of --target KIND");
760 if ((i + 1) >= args.Length){
761 Environment.Exit (1);
765 string type = args [++i];
768 RootContext.Target = Target.Library;
769 RootContext.TargetExt = ".dll";
773 RootContext.Target = Target.Exe;
777 RootContext.Target = Target.WinExe;
781 RootContext.Target = Target.Module;
782 RootContext.TargetExt = ".dll";
791 Report.Warning (-29, "Compatibility: Use -r:LIBRARY instead of -r library");
792 if ((i + 1) >= args.Length){
794 Environment.Exit (1);
797 references.Add (args [++i]);
801 Report.Warning (-29, "Compatibility: Use -lib:ARG instead of --L arg");
802 if ((i + 1) >= args.Length){
804 Environment.Exit (1);
806 link_paths.Add (args [++i]);
810 Report.Warning (-29, "Compatibility: Use -nostdlib instead of --nostdlib");
811 RootContext.StdLib = false;
819 Report.Warning (-29, "Compatibility: Use -warnaserror: option instead of --werror");
820 Report.WarningsAreErrors = true;
824 Report.Warning (-29, "Compatibility: Use -nowarn instead of --nowarn");
825 if ((i + 1) >= args.Length){
827 Environment.Exit (1);
832 warn = Int32.Parse (args [++i]);
835 Environment.Exit (1);
837 Report.SetIgnoreWarning (warn);
841 Report.Warning (-29, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
842 if ((i + 1) >= args.Length){
845 "--wlevel requires a value from 0 to 4");
846 Environment.Exit (1);
849 SetWarningLevel (args [++i]);
853 if ((i + 1) >= args.Length){
854 Report.Error (5, "--mcs-debug requires an argument");
855 Environment.Exit (1);
859 Report.DebugFlags = Int32.Parse (args [++i]);
861 Report.Error (5, "Invalid argument to --mcs-debug");
862 Environment.Exit (1);
871 Report.Warning (-29, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
872 if ((i + 1) >= args.Length){
873 Report.Error (5, "--recurse requires an argument");
874 Environment.Exit (1);
876 CompileFiles (args [++i], true);
881 last_time = first_time = DateTime.Now;
888 case "--debug": case "-g":
889 Report.Warning (-29, "Compatibility: Use -debug option instead of -g or --debug");
890 want_debugging_support = true;
894 Report.Warning (-29, "Compatibility: Use -noconfig option instead of --noconfig");
895 load_default_config = false;
903 // This parses the -arg and /arg options to the compiler, even if the strings
904 // in the following text use "/arg" on the strings.
906 static bool CSCParseOption (string option, ref string [] args, ref int i)
908 int idx = option.IndexOf (':');
915 arg = option.Substring (0, idx);
917 value = option.Substring (idx + 1);
928 RootContext.Target = Target.Exe;
932 RootContext.Target = Target.WinExe;
936 RootContext.Target = Target.Library;
937 RootContext.TargetExt = ".dll";
941 RootContext.Target = Target.Module;
942 RootContext.TargetExt = ".netmodule";
954 Environment.Exit (1);
956 SetOutputFile (value);
961 RootContext.Optimize = true;
965 RootContext.Optimize = false;
969 case "/incremental+":
970 case "/incremental-":
980 Environment.Exit (1);
983 defs = value.Split (new Char [] {';', ','});
984 foreach (string d in defs){
992 // We should collect data, runtime, etc and store in the file specified
994 Console.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
998 case "/linkresource":
1000 Report.Error (5, arg + " requires an argument");
1001 Environment.Exit (1);
1003 if (resources == null)
1004 resources = new ArrayList ();
1006 resources.Add (value);
1014 Environment.Exit (1);
1016 packages = String.Join (" ", value.Split (new Char [] { ';', ',', '\n', '\r'}));
1018 ProcessStartInfo pi = new ProcessStartInfo ();
1019 pi.FileName = "pkg-config";
1020 pi.RedirectStandardOutput = true;
1021 pi.UseShellExecute = false;
1022 pi.Arguments = "--libs " + packages;
1025 p = Process.Start (pi);
1026 } catch (Exception e) {
1027 Report.Error (-27, "Couldn't run pkg-config: " + e.Message);
1028 Environment.Exit (1);
1031 if (p.StandardOutput == null){
1032 Report.Warning (-27, "Specified package did not return any information");
1035 string pkgout = p.StandardOutput.ReadToEnd ();
1037 if (p.ExitCode != 0) {
1038 Report.Error (-27, "Error running pkg-config. Check the above output.");
1039 Environment.Exit (1);
1042 if (pkgout != null){
1043 string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
1044 Split (new Char [] { ' ', '\t'});
1045 args = AddArgs (args, xargs);
1055 Report.Error (5, "-resource requires an argument");
1056 Environment.Exit (1);
1058 if (embedded_resources == null)
1059 embedded_resources = new ArrayList ();
1061 if (embedded_resources.Contains (value)) {
1062 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1064 else if (value.IndexOf (',') != -1 && embedded_resources.Contains (value.Split (',')[1])) {
1065 Report.Error (1508, String.Format ("The resource identifier '{0}' has already been used in this assembly.", value));
1068 embedded_resources.Add (value);
1074 Report.Error (5, "-recurse requires an argument");
1075 Environment.Exit (1);
1077 CompileFiles (value, true);
1081 case "/reference": {
1083 Report.Error (5, "-reference requires an argument");
1084 Environment.Exit (1);
1087 string [] refs = value.Split (new char [] { ';', ',' });
1088 foreach (string r in refs){
1093 case "/addmodule": {
1095 Report.Error (5, arg + " requires an argument");
1096 Environment.Exit (1);
1099 string [] refs = value.Split (new char [] { ';', ',' });
1100 foreach (string r in refs){
1107 Report.Error (5, arg + " requires an argument");
1108 Environment.Exit (1);
1111 win32ResourceFile = value;
1114 case "/win32icon": {
1116 Report.Error (5, arg + " requires an argument");
1117 Environment.Exit (1);
1120 win32IconFile = value;
1125 Report.Error (2006, arg + " requires an argument");
1126 Environment.Exit (1);
1128 RootContext.Documentation = new Documentation (value);
1135 Report.Error (5, "/lib requires an argument");
1136 Environment.Exit (1);
1139 libdirs = value.Split (new Char [] { ',' });
1140 foreach (string dir in libdirs)
1141 link_paths.Add (dir);
1146 want_debugging_support = false;
1151 want_debugging_support = true;
1156 RootContext.Checked = true;
1160 RootContext.Checked = false;
1168 RootContext.VerifyClsCompliance = false;
1173 RootContext.Unsafe = true;
1177 RootContext.Unsafe = false;
1180 case "/warnaserror":
1181 case "/warnaserror+":
1182 Report.WarningsAreErrors = true;
1185 case "/warnaserror-":
1186 Report.WarningsAreErrors = false;
1190 SetWarningLevel (value);
1197 Report.Error (5, "/nowarn requires an argument");
1198 Environment.Exit (1);
1201 warns = value.Split (new Char [] {','});
1202 foreach (string wc in warns){
1204 int warn = Int32.Parse (wc);
1206 throw new ArgumentOutOfRangeException("warn");
1208 Report.SetIgnoreWarning (warn);
1210 Report.Error (1904, String.Format("'{0}' is not a valid warning number", wc));
1217 load_default_config = true;
1222 load_default_config = false;
1227 Environment.Exit(0);
1233 Environment.Exit (0);
1239 Report.Error (5, arg + " requires an argument");
1240 Environment.Exit (1);
1242 RootContext.MainClass = value;
1247 RootContext.StdLib = false;
1251 RootContext.StdLib = true;
1258 if (value == String.Empty) {
1259 Report.Error (5, arg + " requires an argument");
1260 Environment.Exit (1);
1262 RootContext.StrongNameKeyFile = value;
1264 case "/keycontainer":
1265 if (value == String.Empty) {
1266 Report.Error (5, arg + " requires an argument");
1267 Environment.Exit (1);
1269 RootContext.StrongNameKeyContainer = value;
1272 RootContext.StrongNameDelaySign = true;
1275 RootContext.StrongNameDelaySign = false;
1280 Console.WriteLine ("The compiler option -2 is obsolete. Please use /langversion instead");
1284 case "/langversion":
1285 switch (value.ToLower (CultureInfo.InvariantCulture)) {
1287 RootContext.Version = LanguageVersion.ISO_1;
1294 Report.Error (1617, "Invalid option '{0}' for /langversion; must be ISO-1 or Default", value);
1300 if (value == "utf8"){
1301 encoding = new UTF8Encoding();
1302 using_default_encoder = false;
1305 if (value == "reset"){
1307 // 28591 is the code page for ISO-8859-1 encoding.
1310 using_default_encoder = true;
1314 cp = Int32.Parse (value);
1315 encoding = Encoding.GetEncoding (cp);
1316 using_default_encoder = false;
1318 Report.Error (2016, String.Format("Code page '{0}' is invalid or not installed", cp));
1323 //Report.Error (2007, String.Format ("Unrecognized command-line option: '{0}'", option));
1324 //Environment.Exit (1);
1328 static string [] AddArgs (string [] args, string [] extra_args)
1331 new_args = new string [extra_args.Length + args.Length];
1333 // if args contains '--' we have to take that into account
1334 // split args into first half and second half based on '--'
1335 // and add the extra_args before --
1336 int split_position = Array.IndexOf (args, "--");
1337 if (split_position != -1)
1339 Array.Copy (args, new_args, split_position);
1340 extra_args.CopyTo (new_args, split_position);
1341 Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
1345 args.CopyTo (new_args, 0);
1346 extra_args.CopyTo (new_args, args.Length);
1353 /// Parses the arguments, and drives the compilation
1358 /// TODO: Mostly structured to debug the compiler
1359 /// now, needs to be turned into a real driver soon.
1361 // [MonoTODO("Change error code for unknown argument to something reasonable")]
1362 internal static bool MainDriver (string [] args)
1365 bool parsing_options = true;
1368 encoding = Encoding.GetEncoding (28591);
1370 Console.WriteLine ("Error: could not load encoding 28591, trying 1252");
1371 encoding = Encoding.GetEncoding (1252);
1374 references = new ArrayList ();
1375 soft_references = new ArrayList ();
1376 modules = new ArrayList ();
1377 link_paths = new ArrayList ();
1379 SetupDefaultDefines ();
1384 // This is not required because Assembly.Load knows about this
1388 Hashtable response_file_list = null;
1390 for (i = 0; i < args.Length; i++){
1391 string arg = args [i];
1395 if (arg.StartsWith ("@")){
1396 string [] extra_args;
1397 string response_file = arg.Substring (1);
1399 if (response_file_list == null)
1400 response_file_list = new Hashtable ();
1402 if (response_file_list.Contains (response_file)){
1404 1515, "Response file `" + response_file +
1405 "' specified multiple times");
1406 Environment.Exit (1);
1409 response_file_list.Add (response_file, response_file);
1411 extra_args = LoadArgs (response_file);
1412 if (extra_args == null){
1413 Report.Error (2011, "Unable to open response file: " +
1418 args = AddArgs (args, extra_args);
1422 if (parsing_options){
1424 parsing_options = false;
1428 if (arg.StartsWith ("-")){
1429 if (UnixParseOption (arg, ref args, ref i))
1433 string csc_opt = "/" + arg.Substring (1);
1434 if (CSCParseOption (csc_opt, ref args, ref i))
1437 if (arg.StartsWith ("/")){
1438 if (CSCParseOption (arg, ref args, ref i))
1444 CompileFiles (arg, false);
1453 // This will point to the NamespaceEntry of the last file that was parsed, and may
1454 // not be meaningful when resolving classes from other files. So, reset it to prevent
1457 RootContext.Tree.Types.NamespaceEntry = null;
1460 // If we are an exe, require a source file for the entry point
1462 if (RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe){
1463 if (first_source == null){
1464 Report.Error (2008, "No files to compile were specified");
1471 // If there is nothing to put in the assembly, and we are not a library
1473 if (first_source == null && embedded_resources == null && resources == null){
1474 Report.Error (2008, "No files to compile were specified");
1478 if (Report.Errors > 0)
1485 // Load Core Library for default compilation
1487 if (RootContext.StdLib)
1488 references.Insert (0, "mscorlib");
1490 if (load_default_config)
1491 DefineDefaultConfig ();
1493 if (Report.Errors > 0){
1498 // Load assemblies required
1501 ShowTime ("Loading references");
1502 link_paths.Add (GetSystemDir ());
1503 link_paths.Add (Directory.GetCurrentDirectory ());
1507 ShowTime (" References loaded");
1509 if (Report.Errors > 0){
1516 if (output_file == null){
1517 int pos = first_source.LastIndexOf ('.');
1520 output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
1522 output_file = first_source + RootContext.TargetExt;
1525 if (!CodeGen.Init (output_file, output_file, want_debugging_support))
1528 if (RootContext.Target == Target.Module) {
1529 PropertyInfo module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1530 if (module_only == null) {
1531 Report.RuntimeMissingSupport (Location.Null, "/target:module");
1532 Environment.Exit (1);
1535 MethodInfo set_method = module_only.GetSetMethod (true);
1536 set_method.Invoke (CodeGen.Assembly.Builder, BindingFlags.Default, null, new object[]{true}, null);
1539 TypeManager.AddModule (CodeGen.Module.Builder);
1541 if (modules.Count > 0) {
1542 MethodInfo adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1543 if (adder_method == null) {
1544 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1545 Environment.Exit (1);
1548 foreach (string module in modules)
1549 LoadModule (adder_method, module);
1552 TypeManager.ComputeNamespaces ();
1555 // Before emitting, we need to get the core
1556 // types emitted from the user defined types
1557 // or from the system ones.
1560 ShowTime ("Initializing Core Types");
1561 if (!RootContext.StdLib){
1562 RootContext.ResolveCore ();
1563 if (Report.Errors > 0)
1567 TypeManager.InitCoreTypes ();
1569 ShowTime (" Core Types done");
1571 CodeGen.Module.ResolveAttributes ();
1574 // The second pass of the compiler
1577 ShowTime ("Resolving tree");
1578 RootContext.ResolveTree ();
1580 if (Report.Errors > 0)
1583 ShowTime ("Populate tree");
1584 if (!RootContext.StdLib)
1585 RootContext.BootCorlib_PopulateCoreTypes ();
1587 RootContext.PopulateTypes ();
1588 RootContext.DefineTypes ();
1590 if (RootContext.Documentation != null &&
1591 !RootContext.Documentation.OutputDocComment (
1595 TypeManager.InitCodeHelpers ();
1598 // Verify using aliases now
1600 Namespace.VerifyUsing ();
1602 if (Report.Errors > 0){
1606 if (RootContext.VerifyClsCompliance) {
1607 CodeGen.Assembly.ResolveClsCompliance ();
1608 if (CodeGen.Assembly.IsClsCompliant) {
1609 AttributeTester.VerifyModulesClsCompliance ();
1610 TypeManager.LoadAllImportedTypes ();
1611 AttributeTester.VerifyTopLevelNameClsCompliance ();
1614 if (Report.Errors > 0)
1618 // The code generator
1621 ShowTime ("Emitting code");
1622 ShowTotalTime ("Total so far");
1623 RootContext.EmitCode ();
1627 if (Report.Errors > 0){
1632 ShowTime ("Closing types");
1634 RootContext.CloseTypes ();
1636 PEFileKinds k = PEFileKinds.ConsoleApplication;
1638 switch (RootContext.Target) {
1639 case Target.Library:
1641 k = PEFileKinds.Dll; break;
1643 k = PEFileKinds.ConsoleApplication; break;
1645 k = PEFileKinds.WindowApplication; break;
1648 if (RootContext.NeedsEntryPoint) {
1649 MethodInfo ep = RootContext.EntryPoint;
1652 if (RootContext.MainClass != null) {
1653 DeclSpace main_cont = RootContext.Tree.GetDecl (MemberName.FromDotted (RootContext.MainClass));
1654 if (main_cont == null) {
1655 Report.Error (1555, output_file, "Could not find '{0}' specified for Main method", RootContext.MainClass);
1659 if (!(main_cont is ClassOrStruct)) {
1660 Report.Error (1556, output_file, "'{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
1664 Report.Error (1558, main_cont.Location, "'{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
1668 if (Report.Errors == 0)
1669 Report.Error (5001, "Program " + output_file +
1670 " does not have an entry point defined");
1674 CodeGen.Assembly.Builder.SetEntryPoint (ep, k);
1675 } else if (RootContext.MainClass != null) {
1676 Report.Error (2017, "Can not specify -main: when building module or library");
1680 // Add the resources
1682 if (resources != null){
1683 foreach (string spec in resources){
1687 cp = spec.IndexOf (',');
1689 file = spec.Substring (0, cp);
1690 res = spec.Substring (cp + 1);
1694 CodeGen.Assembly.Builder.AddResourceFile (res, file);
1698 if (embedded_resources != null){
1699 object[] margs = new object [2];
1700 Type[] argst = new Type [2];
1701 argst [0] = argst [1] = typeof (string);
1703 MethodInfo embed_res = typeof (AssemblyBuilder).GetMethod (
1704 "EmbedResourceFile", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
1705 null, CallingConventions.Any, argst, null);
1707 if (embed_res == null) {
1708 Report.RuntimeMissingSupport (Location.Null, "Resource embedding");
1710 foreach (string spec in embedded_resources) {
1713 cp = spec.IndexOf (',');
1715 margs [0] = spec.Substring (cp + 1);
1716 margs [1] = spec.Substring (0, cp);
1719 margs [0] = Path.GetFileName (spec);
1722 if (File.Exists ((string) margs [1]))
1723 embed_res.Invoke (CodeGen.Assembly.Builder, margs);
1725 Report.Error (1566, "Can not find the resource " + margs [1]);
1732 // Add Win32 resources
1735 CodeGen.Assembly.Builder.DefineVersionInfoResource ();
1737 if (win32ResourceFile != null) {
1739 CodeGen.Assembly.Builder.DefineUnmanagedResource (win32ResourceFile);
1741 catch (ArgumentException) {
1742 Report.Warning (0, new Location (-1), "Cannot embed win32 resources on this runtime: try the Mono runtime instead.");
1746 if (win32IconFile != null) {
1747 MethodInfo define_icon = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
1748 if (define_icon == null) {
1749 Report.Warning (0, new Location (-1), "Cannot embed icon resource on this runtime: try the Mono runtime instead.");
1751 define_icon.Invoke (CodeGen.Assembly.Builder, new object [] { win32IconFile });
1754 if (Report.Errors > 0)
1757 CodeGen.Save (output_file);
1759 ShowTime ("Saved output");
1760 ShowTotalTime ("Total");
1763 Timer.ShowTimers ();
1765 if (Report.ExpectedError != 0) {
1766 if (Report.Errors == 0) {
1767 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1768 "No other errors reported.");
1770 Environment.Exit (2);
1772 Console.WriteLine ("Failed to report expected error " + Report.ExpectedError + ".\n" +
1773 "However, other errors were reported.");
1775 Environment.Exit (1);
1783 Console.WriteLine ("Size of strings held: " + DeclSpace.length);
1784 Console.WriteLine ("Size of strings short: " + DeclSpace.small);
1786 return (Report.Errors == 0);
1791 // This is the only public entry point
1793 public class CompilerCallableEntryPoint : MarshalByRefObject {
1794 public static bool InvokeCompiler (string [] args, TextWriter error)
1796 Report.Stderr = error;
1798 return Driver.MainDriver (args) && Report.Errors == 0;
1801 Report.Stderr = Console.Error;
1806 static void Reset ()
1810 RootContext.Reset ();
1812 TypeManager.Reset ();
1813 TypeHandle.Reset ();