2002-02-27 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mcs / mcs / driver.cs
1 //
2 // driver.cs: The compiler command line driver.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //
6 // Licensed under the terms of the GNU GPL
7 //
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
9 //
10
11 namespace Mono.CSharp
12 {
13         using System;
14         using System.Reflection;
15         using System.Reflection.Emit;
16         using System.Collections;
17         using System.IO;
18         using System.Globalization;
19         using Mono.Languages;
20
21         enum Target {
22                 Library, Exe, Module, WinExe
23         };
24         
25         /// <summary>
26         ///    The compiler driver.
27         /// </summary>
28         public class Driver
29         {
30                 
31                 //
32                 // Assemblies references to be linked.   Initialized with
33                 // mscorlib.dll here.
34                 static ArrayList references;
35
36                 // Lookup paths
37                 static ArrayList link_paths;
38
39                 // Whether we want Yacc to output its progress
40                 static bool yacc_verbose = false;
41
42                 // Whether we want to only run the tokenizer
43                 static bool tokenize = false;
44                 
45                 static int error_count = 0;
46
47                 static string first_source;
48
49                 static Target target = Target.Exe;
50                 static string target_ext = ".exe";
51
52                 static bool parse_only = false;
53                 static bool timestamps = false;
54
55                 static Hashtable response_file_list;
56                 static Hashtable source_files = new Hashtable ();
57                 
58                 //
59                 // An array of the defines from the command line
60                 //
61                 static ArrayList defines;
62
63                 //
64                 // Last time we took the time
65                 //
66                 static DateTime last_time;
67                 static void ShowTime (string msg)
68                 {
69                         DateTime now = DateTime.Now;
70                         TimeSpan span = now - last_time;
71                         last_time = now;
72                         
73                         Console.WriteLine (
74                                 "[{0:00}:{1:000}] {2}",
75                                 span.Seconds, span.Milliseconds, msg);
76                 }
77                 
78                 static int tokenize_file (string input_file)
79                 {
80                         Stream input;
81
82                         try {
83                                 input = File.OpenRead (input_file);
84
85                         } catch {
86                                 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
87                                 return 1;
88                         }
89
90                         using (input){
91                                 Tokenizer lexer = new Tokenizer (input, input_file, defines);
92                                 int token, tokens = 0, errors = 0;
93
94                                 while ((token = lexer.token ()) != Token.EOF){
95                                         Location l = lexer.Location;
96                                         tokens++;
97                                         if (token == Token.ERROR)
98                                                 errors++;
99                                 }
100                                 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
101                         }
102                         
103                         return 0;
104                 }
105                 
106                 static int parse (string input_file)
107                 {
108                         CSharpParser parser;
109                         Stream input;
110                         int errors;
111
112                         try {
113                                 input = File.OpenRead (input_file);
114                         } catch {
115                                 Report.Error (2001, "Source file '" + input_file + "' could not be opened");
116                                 return 1;
117                         }
118
119                         parser = new CSharpParser (input_file, input, defines);
120                         parser.yacc_verbose = yacc_verbose;
121                         try {
122                                 errors = parser.parse ();
123                         } catch (Exception ex) {
124                                 Console.WriteLine (ex);
125                                 Console.WriteLine ("Compilation aborted");
126                                 return 1;
127                         } finally {
128                                 input.Close ();
129                         }
130                         
131                         return errors;
132                 }
133                 
134                 static void Usage (bool is_error)
135                 {
136                         Console.WriteLine (
137                                 "Mono C# compiler, (C) 2001 Ximian, Inc.\n" +
138                                 "mcs [options] source-files\n" +
139                                 "   --about         About the Mono C# compiler\n" +
140                                 "   --checked       Set default context to checked\n" +
141                                 "   --define SYM    Defines the symbol SYM\n" + 
142                                 "   --fatal         Makes errors fatal\n" +
143                                 "   --stacktrace    Shows stack trace at error location\n" +
144                                 "   -L PATH         Adds PATH to the assembly link path\n" +
145                                 "   --nostdlib      Does not load core libraries\n" +
146                                 "   --nowarn XXX    Ignores warning number XXX\n" +
147                                 "   -o FNAME        Specifies output file\n" +
148                                 "   --optimize      Optimizes\n" +
149                                 "   --parse         Only parses the source file\n" +
150                                 "   --probe X       Probes for the source to generate code X on line L\n" +
151                                 "   --target KIND   Specifies the target (KIND is one of: exe, winexe, " +
152                                                     "library, module)\n" +
153                                 "   --timestamp     Displays time stamps of various compiler events\n" +
154                                 "   --unsafe        Allows unsafe code\n" +
155                                 "   --werror        Treat warnings as errors\n" +
156                                 "   --wlevel LEVEL  Sets warning level (the highest is 4, the default)\n" +
157                                 "   -r              References an assembly\n" +
158                                 "   -v              Verbose parsing (for debugging the parser)\n" +
159                                 "   @file           Read response file for more options");
160                         if (is_error)
161                                 error_count++;
162                 }
163
164                 static void About ()
165                 {
166                         Console.WriteLine (
167                                 "The Mono C# compiler is (C) 2001 Ximian, Inc.\n\n" +
168                                 "The compiler source code is released under the terms of the GNU GPL\n\n" +
169
170                                 "For more information on Mono, visit the project Web site\n" +
171                                 "   http://www.go-mono.com\n\n" +
172
173                                 "The compiler was written by Miguel de Icaza and Ravi Pratap");
174                 }
175                 
176                 static void error (string msg)
177                 {
178                         Console.WriteLine ("Error: " + msg);
179                 }
180
181                 static void notice (string msg)
182                 {
183                         Console.WriteLine (msg);
184                 }
185                 
186                 public static int Main (string[] args)
187                 {
188                         MainDriver (args);
189                         
190                         return (error_count + Report.Errors) != 0 ? 1 : 0;
191                 }
192
193                 static public int LoadAssembly (string assembly)
194                 {
195                         Assembly a;
196                         string total_log = "";
197
198                         try {
199                                 a = Assembly.Load (assembly);
200                                 RootContext.TypeManager.AddAssembly (a);
201                                 return 0;
202                         } catch (FileNotFoundException){
203                                 foreach (string dir in link_paths){
204                                         string full_path = dir + "/" + assembly + ".dll";
205
206                                         try {
207                                                 a = Assembly.LoadFrom (full_path);
208                                                 RootContext.TypeManager.AddAssembly (a);
209                                                 return 0;
210                                         } catch (FileNotFoundException ff) {
211                                                 total_log += ff.FusionLog;
212                                                 continue;
213                                         }
214                                 }
215                         } catch (BadImageFormatException f) {
216                                 error ("// Bad file format while loading assembly");
217                                 error ("Log: " + f.FusionLog);
218                                 return 1;
219                         } catch (FileLoadException f){
220                                 error ("// File Load Exception: ");
221                                 error ("Log: " + f.FusionLog);
222                                 return 1;
223                         } catch (ArgumentNullException){
224                                 error ("// Argument Null exception ");
225                                 return 1;
226                         }
227                         
228                         Report.Error (6, "Can not find assembly `" + assembly + "'" );
229                         Console.WriteLine ("Log: \n" + total_log);
230
231                         return 0;
232                 }
233
234                 /// <summary>
235                 ///   Loads all assemblies referenced on the command line
236                 /// </summary>
237                 static public int LoadReferences ()
238                 {
239                         int errors = 0;
240
241                         foreach (string r in references)
242                                 errors += LoadAssembly (r);
243
244                         return errors;
245                 }
246
247                 static void SetupDefaultDefines ()
248                 {
249                         defines = new ArrayList ();
250                         defines.Add ("__MonoCS__");
251                 }
252
253                 static string [] LoadArgs (string file)
254                 {
255                         StreamReader f;
256                         ArrayList args = new ArrayList ();
257                         string line;
258                         try {
259                                 f = new StreamReader (file);
260                         } catch {
261                                 return null;
262                         }
263
264                         while ((line = f.ReadLine ()) != null){
265                                 string [] line_args = line.Split (new char [] { ' ' });
266
267                                 foreach (string arg in line_args)
268                                         args.Add (arg);
269                         }
270
271                         string [] ret_value = new string [args.Count];
272                         args.CopyTo (ret_value, 0);
273
274                         return ret_value;
275                 }
276
277                 //
278                 // Returns the directory where the system assemblies are installed
279                 //
280                 static string GetSystemDir ()
281                 {
282                         Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
283
284                         foreach (Assembly a in assemblies){
285                                 string codebase = a.CodeBase;
286                                 if (codebase.EndsWith ("corlib.dll")){
287                                         return codebase.Substring (0, codebase.LastIndexOf ("/"));
288                                 }
289                         }
290
291                         Report.Error (-15, "Can not compute my system path");
292                         return "";
293                 }
294
295                 //
296                 // Given a path specification, splits the path from the file/pattern
297                 //
298                 static void SplitPathAndPattern (string spec, out string path, out string pattern)
299                 {
300                         int p = spec.LastIndexOf ("/");
301                         if (p != -1){
302                                 //
303                                 // Windows does not like /file.cs, switch that to:
304                                 // "\", "file.cs"
305                                 //
306                                 if (p == 0){
307                                         path = "\\";
308                                         pattern = spec.Substring (1);
309                                 } else {
310                                         path = spec.Substring (0, p);
311                                         pattern = spec.Substring (p + 1);
312                                 }
313                                 return;
314                         }
315
316                         p = spec.LastIndexOf ("\\");
317                         if (p != -1){
318                                 path = spec.Substring (0, p - 1);
319                                 pattern = spec.Substring (p);
320                                 return;
321                         }
322
323                         path = ".";
324                         pattern = spec;
325                 }
326
327                 static int ProcessFile (string f)
328                 {
329                         if (source_files.Contains (f)){
330                                 Report.Error (
331                                         1516,
332                                         "Source file `" + f + "' specified multiple times");
333                                 Environment.Exit (1);
334                         } else
335                                 source_files.Add (f, f);
336                                         
337                         if (tokenize)
338                                 tokenize_file (f);
339                         else
340                                 return parse (f);
341                         return 0;
342                 }
343
344                 static void RecurseOn (string pattern)
345                 {
346                         // FIXME: implement.
347                 }
348                 
349                 /// <summary>
350                 ///    Parses the arguments, and drives the compilation
351                 ///    process.
352                 /// </summary>
353                 ///
354                 /// <remarks>
355                 ///    TODO: Mostly structured to debug the compiler
356                 ///    now, needs to be turned into a real driver soon.
357                 /// </remarks>
358                 static void MainDriver (string [] args)
359                 {
360                         int errors = 0, i;
361                         string output_file = null;
362                         bool parsing_options = true;
363                         
364                         references = new ArrayList ();
365                         link_paths = new ArrayList ();
366
367                         SetupDefaultDefines ();
368                         
369                         //
370                         // Setup defaults
371                         //
372                         // This is not required because Assembly.Load knows about this
373                         // path.
374                         //
375                         link_paths.Add (GetSystemDir ());
376
377                         int argc = args.Length;
378                         for (i = 0; i < argc; i++){
379                                 string arg = args [i];
380
381                                 if (arg.StartsWith ("@")){
382                                         string [] new_args, extra_args;
383                                         string response_file = arg.Substring (1);
384
385                                         if (response_file_list == null)
386                                                 response_file_list = new Hashtable ();
387                                         
388                                         if (response_file_list.Contains (response_file)){
389                                                 Report.Error (
390                                                         1515, "Response file `" + response_file +
391                                                         "' specified multiple times");
392                                                 Environment.Exit (1);
393                                         }
394                                         
395                                         response_file_list.Add (response_file, response_file);
396                                                     
397                                         extra_args = LoadArgs (response_file);
398                                         if (extra_args == null){
399                                                 Report.Error (2011, "Unable to open response file: " +
400                                                               response_file);
401                                                 return;
402                                         }
403
404                                         new_args = new string [extra_args.Length + argc];
405                                         args.CopyTo (new_args, 0);
406                                         extra_args.CopyTo (new_args, argc);
407                                         args = new_args;
408                                         argc = new_args.Length;
409                                         continue;
410                                 }
411
412                                 //
413                                 // Prepare to recurse
414                                 //
415                                 
416                                 if (parsing_options && (arg.StartsWith ("-") || arg.StartsWith ("/"))){
417                                         switch (arg){
418                                         case "-v":
419                                                 yacc_verbose = true;
420                                                 continue;
421
422                                         case "--":
423                                                 parsing_options = false;
424                                                 continue;
425
426                                         case "--parse":
427                                                 parse_only = true;
428                                                 continue;
429
430                                         case "--main": case "-m":
431                                                 if ((i + 1) >= argc){
432                                                         Usage (true);
433                                                         return;
434                                                 }
435                                                 RootContext.MainClass = args [++i];
436                                                 continue;
437
438                                         case "--unsafe":
439                                                 RootContext.Unsafe = true;
440                                                 continue;
441                                                 
442                                         case "--optimize":
443                                                 RootContext.Optimize = true;
444                                                 continue;
445
446                                         case "/?": case "/h": case "/help":
447                                         case "--help":
448                                                 Usage (false);
449                                                 return;
450
451                                         case "--define":
452                                                 if ((i + 1) >= argc){
453                                                         Usage (true);
454                                                         return;
455                                                 }
456                                                 defines.Add (args [++i]);
457                                                 continue;
458                                                 
459                                         case "--probe": {
460                                                 int code = 0;
461
462                                                 try {
463                                                         code = Int32.Parse (
464                                                                 args [++i], NumberStyles.AllowLeadingSign);
465                                                         Report.SetProbe (code);
466                                                 } catch {
467                                                         Report.Error (-14, "Invalid number specified");
468                                                 } 
469                                                 continue;
470                                         }
471
472                                         case "--tokenize": {
473                                                 tokenize = true;
474                                                 continue;
475                                         }
476                                         
477                                         case "-o": 
478                                         case "--output":
479                                                 if ((i + 1) >= argc){
480                                                         Usage (true);
481                                                         return;
482                                                 }
483                                                 output_file = args [++i];
484                                                 string bname = CodeGen.Basename (output_file);
485                                                 if (bname.IndexOf (".") == -1)
486                                                         output_file += ".exe";
487                                                 continue;
488
489                                         case "--checked":
490                                                 RootContext.Checked = true;
491                                                 continue;
492
493                                         case "--stacktrace":
494                                                 Report.Stacktrace = true;
495                                                 continue;
496                                                 
497                                         case "--target":
498                                                 if ((i + 1) >= argc){
499                                                         Usage (true);
500                                                         return;
501                                                 }
502
503                                                 string type = args [++i];
504                                                 switch (type){
505                                                 case "library":
506                                                         target = Target.Library;
507                                                         target_ext = ".dll";
508                                                         break;
509                                                         
510                                                 case "exe":
511                                                         target = Target.Exe;
512                                                         break;
513                                                         
514                                                 case "winexe":
515                                                         target = Target.WinExe;
516                                                         break;
517                                                         
518                                                 case "module":
519                                                         target = Target.Module;
520                                                         target_ext = ".dll";
521                                                         break;
522                                                 }
523                                                 continue;
524
525                                         case "-r":
526                                                 if ((i + 1) >= argc){
527                                                         Usage (true);
528                                                         return;
529                                                 }
530                                                 
531                                                 references.Add (args [++i]);
532                                                 continue;
533                                                 
534                                         case "-L":
535                                                 if ((i + 1) >= argc){
536                                                         Usage (true);
537                                                         return;
538                                                 }
539                                                 link_paths.Add (args [++i]);
540                                                 continue;
541                                                 
542                                         case "--nostdlib":
543                                                 RootContext.StdLib = false;
544                                                 continue;
545                                                 
546                                         case "--fatal":
547                                                 Report.Fatal = true;
548                                                 continue;
549
550                                         case "--werror":
551                                                 Report.WarningsAreErrors = true;
552                                                 continue;
553
554                                         case "--nowarn":
555                                                 if ((i + 1) >= argc){
556                                                         Usage (true);
557                                                         return;
558                                                 }
559                                                 int warn;
560                                                 
561                                                 try {
562                                                         warn = Int32.Parse (args [++i]);
563                                                 } catch {
564                                                         Usage (true);
565                                                         return;
566                                                 }
567                                                 Report.SetIgnoreWarning (warn);
568                                                 continue;
569
570                                         case "--wlevel":
571                                                 if ((i + 1) >= argc){
572                                                         Usage (true);
573                                                         error_count++;
574                                                         return;
575                                                 }
576                                                 int level;
577                                                 
578                                                 try {
579                                                         level = Int32.Parse (args [++i]);
580                                                 } catch {
581                                                         Usage (true);
582                                                         return;
583                                                 }
584                                                 if (level < 0 || level > 4){
585                                                         Report.Error (1900, "Warning level must be 0 to 4");
586                                                         return;
587                                                 } else
588                                                         RootContext.WarningLevel = level;
589                                                 continue;
590                                                 
591                                         case "--about":
592                                                 About ();
593                                                 return;
594
595                                         case "--recurse":
596                                                 if ((i + 1) >= argc){
597                                                         Usage (true);
598                                                         error_count++;
599                                                         return;
600                                                 }
601                                                 RecurseOn (args [++i]);
602                                                 continue;
603                                                 
604                                         case "--timestamp":
605                                                 timestamps = true;
606                                                 last_time = DateTime.Now;
607                                                 continue;
608                                         }
609                                 }
610
611                                 if (first_source == null)
612                                         first_source = arg;
613
614                                 string path, pattern;
615                                 SplitPathAndPattern (arg, out path, out pattern);
616                                 string [] files = null;
617                                 try {
618                                         files = Directory.GetFiles (path, pattern);
619                                 } catch (System.IO.DirectoryNotFoundException) {
620                                         Report.Error (2001, "Source file `" + arg + "' could not be found");
621                                         continue;
622                                 }
623                                 
624                                 foreach (string f in files)
625                                         errors += ProcessFile (f);
626                         }
627
628                         if (tokenize)
629                                 return;
630                         
631                         if (first_source == null){
632                                 Report.Error (2008, "No files to compile were specified");
633                                 return;
634                         }
635
636                         if (Report.Errors > 0)
637                                 return;
638                         
639                         if (parse_only)
640                                 return;
641                         
642                         //
643                         // Load Core Library for default compilation
644                         //
645                         if (RootContext.StdLib){
646                                 references.Insert (0, "mscorlib");
647                                 references.Insert (1, "System");
648                         }
649
650                         if (errors > 0){
651                                 error ("Parsing failed");
652                                 return;
653                         }
654
655                         //
656                         // Load assemblies required
657                         //
658                         if (timestamps)
659                                 ShowTime ("Loading references");
660                         errors += LoadReferences ();
661                         if (timestamps)
662                                 ShowTime ("   References loaded");
663                         
664                         if (errors > 0){
665                                 error ("Could not load one or more assemblies");
666                                 return;
667                         }
668
669                         error_count = errors;
670
671                         //
672                         // Quick hack
673                         //
674                         if (output_file == null){
675                                 int pos = first_source.LastIndexOf (".");
676
677                                 if (pos > 0)
678                                         output_file = first_source.Substring (0, pos) + target_ext;
679                                 else
680                                         output_file = first_source + target_ext;
681                         }
682
683                         RootContext.CodeGen = new CodeGen (output_file, output_file);
684
685                         //
686                         // Before emitting, we need to get the core
687                         // types emitted from the user defined types
688                         // or from the system ones.
689                         //
690                         if (timestamps)
691                                 ShowTime ("Initializing Core Types");
692                         RootContext.TypeManager.InitCoreTypes ();
693                         if (timestamps)
694                                 ShowTime ("   Core Types done");
695
696                         RootContext.TypeManager.AddModule (RootContext.CodeGen.ModuleBuilder);
697                         
698                         //
699                         // The second pass of the compiler
700                         //
701                         if (timestamps)
702                                 ShowTime ("Resolving tree");
703                         RootContext.ResolveTree ();
704                         if (timestamps)
705                                 ShowTime ("Populate tree");
706                         RootContext.PopulateTypes ();
707                         
708                         if (Report.Errors > 0){
709                                 error ("Compilation failed");
710                                 return;
711                         }
712                         
713                         //
714                         // The code generator
715                         //
716                         if (timestamps)
717                                 ShowTime ("Emitting code");
718                         RootContext.EmitCode ();
719                         if (timestamps)
720                                 ShowTime ("   done");
721
722                         if (Report.Errors > 0){
723                                 error ("Compilation failed");
724                                 return;
725                         }
726
727                         if (timestamps)
728                                 ShowTime ("Closing types");
729                         
730                         RootContext.CloseTypes ();
731
732                         PEFileKinds k = PEFileKinds.ConsoleApplication;
733                                 
734                         if (target == Target.Library || target == Target.Module)
735                                 k = PEFileKinds.Dll;
736                         else if (target == Target.Exe)
737                                 k = PEFileKinds.ConsoleApplication;
738                         else if (target == Target.WinExe)
739                                 k = PEFileKinds.WindowApplication;
740
741                         if (target == Target.Exe || target == Target.WinExe){
742                                 MethodInfo ep = RootContext.EntryPoint;
743
744                                 if (ep == null){
745                                         Report.Error (5001, "Program " + output_file +
746                                                               " does not have an entry point defined");
747                                         return;
748                                 }
749                                 
750                                 RootContext.CodeGen.AssemblyBuilder.SetEntryPoint (ep, k);
751                         }
752                         
753                         RootContext.CodeGen.Save (output_file);
754                         if (timestamps)
755                                 ShowTime ("Saved output");
756
757                         if (Report.Errors > 0){
758                                 error ("Compilation failed");
759                                 return;
760                         } else if (Report.ProbeCode != 0){
761                                 error ("Failed to report code " + Report.ProbeCode);
762                                 Environment.Exit (124);
763                         }
764                 }
765
766         }
767 }