f029e9a1934b0daa1c464eea6add7ed7dd2d8624
[mono.git] / mcs / mcs / driver.cs
1 //
2 // driver.cs: The compiler command line driver.
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@gnu.org)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
13 //
14
15 using System;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Collections.Generic;
19 using System.IO;
20 using System.Text;
21 using System.Globalization;
22 using System.Diagnostics;
23
24 namespace Mono.CSharp
25 {
26         /// <summary>
27         ///    The compiler driver.
28         /// </summary>
29         class Driver
30         {
31                 readonly CompilerContext ctx;
32
33                 public Driver (CompilerContext ctx)
34                 {
35                         this.ctx = ctx;
36                 }
37
38                 Report Report {
39                         get {
40                                 return ctx.Report;
41                         }
42                 }
43
44                 void tokenize_file (SourceFile sourceFile, ModuleContainer module)
45                 {
46                         Stream input;
47
48                         try {
49                                 input = File.OpenRead (sourceFile.Name);
50                         } catch {
51                                 Report.Error (2001, "Source file `" + sourceFile.Name + "' could not be found");
52                                 return;
53                         }
54
55                         using (input){
56                                 SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
57                                 var file = new CompilationSourceFile (module, sourceFile);
58
59                                 Tokenizer lexer = new Tokenizer (reader, file);
60                                 int token, tokens = 0, errors = 0;
61
62                                 while ((token = lexer.token ()) != Token.EOF){
63                                         tokens++;
64                                         if (token == Token.ERROR)
65                                                 errors++;
66                                 }
67                                 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
68                         }
69                         
70                         return;
71                 }
72
73                 void Parse (ModuleContainer module)
74                 {
75                         bool tokenize_only = module.Compiler.Settings.TokenizeOnly;
76                         var sources = module.Compiler.SourceFiles;
77
78                         Location.Initialize (sources);
79
80                         for (int i = 0; i < sources.Count; ++i) {
81                                 if (tokenize_only) {
82                                         tokenize_file (sources[i], module);
83                                 } else {
84                                         Parse (sources[i], module);
85                                 }
86                         }
87                 }
88
89                 public void Parse (SourceFile file, ModuleContainer module)
90                 {
91                         Stream input;
92
93                         try {
94                                 input = File.OpenRead (file.Name);
95                         } catch {
96                                 Report.Error (2001, "Source file `{0}' could not be found", file.Name);
97                                 return;
98                         }
99
100                         // Check 'MZ' header
101                         if (input.ReadByte () == 77 && input.ReadByte () == 90) {
102
103                                 Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
104                                 input.Close ();
105                                 return;
106                         }
107
108                         input.Position = 0;
109                         SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
110
111                         Parse (reader, file, module);
112                         reader.Dispose ();
113                         input.Close ();
114                 }
115
116                 public void Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module)
117                 {
118                         var file = new CompilationSourceFile (module, sourceFile);
119                         module.AddTypeContainer (file);
120
121                         CSharpParser parser = new CSharpParser (reader, file);
122                         parser.parse ();
123                 }
124                 
125                 public static int Main (string[] args)
126                 {
127                         Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
128
129                         CommandLineParser cmd = new CommandLineParser (Console.Out);
130                         var settings = cmd.ParseArguments (args);
131                         if (settings == null)
132                                 return 1;
133
134                         if (cmd.HasBeenStopped)
135                                 return 0;
136
137                         Driver d = new Driver (new CompilerContext (settings, new ConsoleReportPrinter ()));
138
139                         if (d.Compile () && d.Report.Errors == 0) {
140                                 if (d.Report.Warnings > 0) {
141                                         Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
142                                 }
143                                 Environment.Exit (0);
144                                 return 0;
145                         }
146                         
147                         
148                         Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
149                                 d.Report.Errors, d.Report.Warnings);
150                         Environment.Exit (1);
151                         return 1;
152                 }
153
154                 public static string GetPackageFlags (string packages, Report report)
155                 {
156                         ProcessStartInfo pi = new ProcessStartInfo ();
157                         pi.FileName = "pkg-config";
158                         pi.RedirectStandardOutput = true;
159                         pi.UseShellExecute = false;
160                         pi.Arguments = "--libs " + packages;
161                         Process p = null;
162                         try {
163                                 p = Process.Start (pi);
164                         } catch (Exception e) {
165                                 if (report == null)
166                                         throw;
167
168                                 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
169                                 return null;
170                         }
171                         
172                         if (p.StandardOutput == null) {
173                                 if (report == null)
174                                         throw new ApplicationException ("Specified package did not return any information");
175
176                                 report.Warning (-27, 1, "Specified package did not return any information");
177                                 p.Close ();
178                                 return null;
179                         }
180
181                         string pkgout = p.StandardOutput.ReadToEnd ();
182                         p.WaitForExit ();
183                         if (p.ExitCode != 0) {
184                                 if (report == null)
185                                         throw new ApplicationException (pkgout);
186
187                                 report.Error (-27, "Error running pkg-config. Check the above output.");
188                                 p.Close ();
189                                 return null;
190                         }
191
192                         p.Close ();
193                         return pkgout;
194                 }
195
196                 //
197                 // Main compilation method
198                 //
199                 public bool Compile ()
200                 {
201                         var settings = ctx.Settings;
202
203                         //
204                         // If we are an exe, require a source file for the entry point or
205                         // if there is nothing to put in the assembly, and we are not a library
206                         //
207                         if (settings.FirstSourceFile == null &&
208                                 ((settings.Target == Target.Exe || settings.Target == Target.WinExe || settings.Target == Target.Module) ||
209                                 settings.Resources == null)) {
210                                 Report.Error (2008, "No files to compile were specified");
211                                 return false;
212                         }
213
214                         TimeReporter tr = new TimeReporter (settings.Timestamps);
215                         ctx.TimeReporter = tr;
216                         tr.StartTotal ();
217
218                         var module = new ModuleContainer (ctx);
219                         RootContext.ToplevelTypes = module;
220
221                         tr.Start (TimeReporter.TimerType.ParseTotal);
222                         Parse (module);
223                         tr.Stop (TimeReporter.TimerType.ParseTotal);
224
225                         if (Report.Errors > 0)
226                                 return false;
227
228                         if (settings.TokenizeOnly || settings.ParseOnly) {
229                                 tr.StopTotal ();
230                                 tr.ShowStats ();
231                                 return true;
232                         }
233
234                         var output_file = settings.OutputFile;
235                         string output_file_name;
236                         if (output_file == null) {
237                                 var source_file = settings.FirstSourceFile;
238
239                                 if (source_file == null) {
240                                         Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
241                                         return false;
242                                 }
243
244                                 output_file_name = source_file.Name;
245                                 int pos = output_file_name.LastIndexOf ('.');
246
247                                 if (pos > 0)
248                                         output_file_name = output_file_name.Substring (0, pos);
249                                 
250                                 output_file_name += settings.TargetExt;
251                                 output_file = output_file_name;
252                         } else {
253                                 output_file_name = Path.GetFileName (output_file);
254                         }
255
256 #if STATIC
257                         var importer = new StaticImporter (module);
258                         var references_loader = new StaticLoader (importer, ctx);
259
260                         tr.Start (TimeReporter.TimerType.AssemblyBuilderSetup);
261                         var assembly = new AssemblyDefinitionStatic (module, references_loader, output_file_name, output_file);
262                         assembly.Create (references_loader.Domain);
263                         tr.Stop (TimeReporter.TimerType.AssemblyBuilderSetup);
264
265                         // Create compiler types first even before any referenced
266                         // assembly is loaded to allow forward referenced types from
267                         // loaded assembly into compiled builder to be resolved
268                         // correctly
269                         tr.Start (TimeReporter.TimerType.CreateTypeTotal);
270                         module.CreateContainer ();
271                         importer.AddCompiledAssembly (assembly);
272                         tr.Stop (TimeReporter.TimerType.CreateTypeTotal);
273
274                         references_loader.LoadReferences (module);
275
276                         tr.Start (TimeReporter.TimerType.PredefinedTypesInit);
277                         if (!ctx.BuiltinTypes.CheckDefinitions (module))
278                                 return false;
279
280                         tr.Stop (TimeReporter.TimerType.PredefinedTypesInit);
281
282                         references_loader.LoadModules (assembly, module.GlobalRootNamespace);
283 #else
284                         var assembly = new AssemblyDefinitionDynamic (module, output_file_name, output_file);
285                         module.SetDeclaringAssembly (assembly);
286
287                         var importer = new ReflectionImporter (module, ctx.BuiltinTypes);
288                         assembly.Importer = importer;
289
290                         var loader = new DynamicLoader (importer, ctx);
291                         loader.LoadReferences (module);
292
293                         if (!ctx.BuiltinTypes.CheckDefinitions (module))
294                                 return false;
295
296                         if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
297                                 return false;
298
299                         module.CreateContainer ();
300
301                         loader.LoadModules (assembly, module.GlobalRootNamespace);
302 #endif
303                         module.InitializePredefinedTypes ();
304
305                         tr.Start (TimeReporter.TimerType.ModuleDefinitionTotal);
306                         module.Define ();
307                         tr.Stop (TimeReporter.TimerType.ModuleDefinitionTotal);
308
309                         if (Report.Errors > 0)
310                                 return false;
311
312                         if (settings.DocumentationFile != null) {
313                                 var doc = new DocumentationBuilder (module);
314                                 doc.OutputDocComment (output_file, settings.DocumentationFile);
315                         }
316
317                         assembly.Resolve ();
318                         
319                         if (Report.Errors > 0)
320                                 return false;
321
322
323                         tr.Start (TimeReporter.TimerType.EmitTotal);
324                         assembly.Emit ();
325                         tr.Stop (TimeReporter.TimerType.EmitTotal);
326
327                         if (Report.Errors > 0){
328                                 return false;
329                         }
330
331                         tr.Start (TimeReporter.TimerType.CloseTypes);
332                         module.CloseContainer ();
333                         tr.Stop (TimeReporter.TimerType.CloseTypes);
334
335                         tr.Start (TimeReporter.TimerType.Resouces);
336                         assembly.EmbedResources ();
337                         tr.Stop (TimeReporter.TimerType.Resouces);
338
339                         if (Report.Errors > 0)
340                                 return false;
341
342                         assembly.Save ();
343
344 #if STATIC
345                         references_loader.Dispose ();
346 #endif
347                         tr.StopTotal ();
348                         tr.ShowStats ();
349
350                         return Report.Errors == 0;
351                 }
352         }
353
354         //
355         // This is the only public entry point
356         //
357         public class CompilerCallableEntryPoint : MarshalByRefObject {
358                 public static bool InvokeCompiler (string [] args, TextWriter error)
359                 {
360                         try {
361                                 CommandLineParser cmd = new CommandLineParser (error);
362                                 var setting = cmd.ParseArguments (args);
363                                 if (setting == null)
364                                         return false;
365
366                                 var d = new Driver (new CompilerContext (setting, new StreamReportPrinter (error)));
367                                 return d.Compile ();
368                         } finally {
369                                 Reset ();
370                         }
371                 }
372
373                 public static int[] AllWarningNumbers {
374                         get {
375                                 return Report.AllWarnings;
376                         }
377                 }
378
379                 public static void Reset ()
380                 {
381                         Reset (true);
382                 }
383
384                 public static void PartialReset ()
385                 {
386                         Reset (false);
387                 }
388                 
389                 public static void Reset (bool full_flag)
390                 {
391                         Location.Reset ();
392                         
393                         if (!full_flag)
394                                 return;
395
396                         SymbolWriter.Reset ();
397                         Linq.QueryBlock.TransparentParameter.Reset ();
398                         TypeInfo.Reset ();
399                 }
400         }
401 }