2 // driver.cs: The compiler command line driver.
5 // Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
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
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Collections.Generic;
21 using System.Globalization;
22 using System.Diagnostics;
23 using System.Threading;
28 /// The compiler driver.
32 readonly CompilerContext ctx;
34 public Driver (CompilerContext ctx)
45 void tokenize_file (SourceFile sourceFile, ModuleContainer module, ParserSession session)
50 input = File.OpenRead (sourceFile.Name);
52 Report.Error (2001, "Source file `" + sourceFile.Name + "' could not be found");
57 SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
58 var file = new CompilationSourceFile (module, sourceFile);
60 Tokenizer lexer = new Tokenizer (reader, file, session, ctx.Report);
61 int token, tokens = 0, errors = 0;
63 while ((token = lexer.token ()) != Token.EOF){
65 if (token == Token.ERROR)
68 Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
74 void Parse (ModuleContainer module)
76 bool tokenize_only = module.Compiler.Settings.TokenizeOnly;
77 var sources = module.Compiler.SourceFiles;
79 Location.Initialize (sources);
81 var session = new ParserSession {
82 UseJayGlobalArrays = true,
83 LocatedTokens = new LocatedToken[15000]
86 for (int i = 0; i < sources.Count; ++i) {
88 tokenize_file (sources[i], module, session);
90 Parse (sources[i], module, session, Report);
96 void ParseParallel (ModuleContainer module)
98 var sources = module.Compiler.SourceFiles;
100 Location.Initialize (sources);
102 var pcount = Environment.ProcessorCount;
103 var threads = new Thread[System.Math.Max (2, pcount - 1)];
105 for (int i = 0; i < threads.Length; ++i) {
106 var t = new Thread (l => {
107 var session = new ParserSession () {
108 //UseJayGlobalArrays = true,
111 var report = new Report (ctx, Report.Printer); // TODO: Implement flush at once printer
113 for (int ii = (int) l; ii < sources.Count; ii += threads.Length) {
114 Parse (sources[ii], module, session, report);
117 // TODO: Merge warning regions
124 for (int t = 0; t < threads.Length; ++t) {
130 public void Parse (SourceFile file, ModuleContainer module, ParserSession session, Report report)
135 input = File.OpenRead (file.Name);
137 report.Error (2001, "Source file `{0}' could not be found", file.Name);
142 if (input.ReadByte () == 77 && input.ReadByte () == 90) {
144 report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
150 SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding, session.StreamReaderBuffer);
152 Parse (reader, file, module, session, report);
154 if (ctx.Settings.GenerateDebugInfo && report.Errors == 0 && !file.HasChecksum) {
156 var checksum = session.GetChecksumAlgorithm ();
157 file.SetChecksum (checksum.ComputeHash (input));
164 public static void Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report)
166 var file = new CompilationSourceFile (module, sourceFile);
167 module.AddTypeContainer (file);
169 CSharpParser parser = new CSharpParser (reader, file, report, session);
173 public static int Main (string[] args)
175 Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
177 CommandLineParser cmd = new CommandLineParser (Console.Out);
178 var settings = cmd.ParseArguments (args);
179 if (settings == null)
182 if (cmd.HasBeenStopped)
185 Driver d = new Driver (new CompilerContext (settings, new ConsoleReportPrinter ()));
187 if (d.Compile () && d.Report.Errors == 0) {
188 if (d.Report.Warnings > 0) {
189 Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
191 Environment.Exit (0);
196 Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
197 d.Report.Errors, d.Report.Warnings);
198 Environment.Exit (1);
202 public static string GetPackageFlags (string packages, Report report)
204 ProcessStartInfo pi = new ProcessStartInfo ();
205 pi.FileName = "pkg-config";
206 pi.RedirectStandardOutput = true;
207 pi.UseShellExecute = false;
208 pi.Arguments = "--libs " + packages;
211 p = Process.Start (pi);
212 } catch (Exception e) {
216 report.Error (-27, "Couldn't run pkg-config: " + e.Message);
220 if (p.StandardOutput == null) {
222 throw new ApplicationException ("Specified package did not return any information");
224 report.Warning (-27, 1, "Specified package did not return any information");
229 string pkgout = p.StandardOutput.ReadToEnd ();
231 if (p.ExitCode != 0) {
233 throw new ApplicationException (pkgout);
235 report.Error (-27, "Error running pkg-config. Check the above output.");
245 // Main compilation method
247 public bool Compile ()
249 var settings = ctx.Settings;
252 // If we are an exe, require a source file for the entry point or
253 // if there is nothing to put in the assembly, and we are not a library
255 if (settings.FirstSourceFile == null &&
256 ((settings.Target == Target.Exe || settings.Target == Target.WinExe || settings.Target == Target.Module) ||
257 settings.Resources == null)) {
258 Report.Error (2008, "No files to compile were specified");
262 if (settings.Platform == Platform.AnyCPU32Preferred && (settings.Target == Target.Library || settings.Target == Target.Module)) {
263 Report.Error (4023, "Platform option `anycpu32bitpreferred' is valid only for executables");
267 TimeReporter tr = new TimeReporter (settings.Timestamps);
268 ctx.TimeReporter = tr;
271 var module = new ModuleContainer (ctx);
272 RootContext.ToplevelTypes = module;
274 tr.Start (TimeReporter.TimerType.ParseTotal);
276 tr.Stop (TimeReporter.TimerType.ParseTotal);
278 if (Report.Errors > 0)
281 if (settings.TokenizeOnly || settings.ParseOnly) {
287 var output_file = settings.OutputFile;
288 string output_file_name;
289 if (output_file == null) {
290 var source_file = settings.FirstSourceFile;
292 if (source_file == null) {
293 Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
297 output_file_name = source_file.Name;
298 int pos = output_file_name.LastIndexOf ('.');
301 output_file_name = output_file_name.Substring (0, pos);
303 output_file_name += settings.TargetExt;
304 output_file = output_file_name;
306 output_file_name = Path.GetFileName (output_file);
308 if (string.IsNullOrEmpty (Path.GetFileNameWithoutExtension (output_file_name)) ||
309 output_file_name.IndexOfAny (Path.GetInvalidFileNameChars ()) >= 0) {
310 Report.Error (2021, "Output file name is not valid");
316 var importer = new StaticImporter (module);
317 var references_loader = new StaticLoader (importer, ctx);
319 tr.Start (TimeReporter.TimerType.AssemblyBuilderSetup);
320 var assembly = new AssemblyDefinitionStatic (module, references_loader, output_file_name, output_file);
321 assembly.Create (references_loader.Domain);
322 tr.Stop (TimeReporter.TimerType.AssemblyBuilderSetup);
324 // Create compiler types first even before any referenced
325 // assembly is loaded to allow forward referenced types from
326 // loaded assembly into compiled builder to be resolved
328 tr.Start (TimeReporter.TimerType.CreateTypeTotal);
329 module.CreateContainer ();
330 importer.AddCompiledAssembly (assembly);
331 references_loader.CompiledAssembly = assembly;
332 tr.Stop (TimeReporter.TimerType.CreateTypeTotal);
334 references_loader.LoadReferences (module);
336 tr.Start (TimeReporter.TimerType.PredefinedTypesInit);
337 if (!ctx.BuiltinTypes.CheckDefinitions (module))
340 tr.Stop (TimeReporter.TimerType.PredefinedTypesInit);
342 references_loader.LoadModules (assembly, module.GlobalRootNamespace);
344 var assembly = new AssemblyDefinitionDynamic (module, output_file_name, output_file);
345 module.SetDeclaringAssembly (assembly);
347 var importer = new ReflectionImporter (module, ctx.BuiltinTypes);
348 assembly.Importer = importer;
350 var loader = new DynamicLoader (importer, ctx);
351 loader.LoadReferences (module);
353 if (!ctx.BuiltinTypes.CheckDefinitions (module))
356 if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
359 module.CreateContainer ();
361 loader.LoadModules (assembly, module.GlobalRootNamespace);
363 module.InitializePredefinedTypes ();
365 tr.Start (TimeReporter.TimerType.ModuleDefinitionTotal);
367 tr.Stop (TimeReporter.TimerType.ModuleDefinitionTotal);
369 if (Report.Errors > 0)
372 if (settings.DocumentationFile != null) {
373 var doc = new DocumentationBuilder (module);
374 doc.OutputDocComment (output_file, settings.DocumentationFile);
379 if (Report.Errors > 0)
383 tr.Start (TimeReporter.TimerType.EmitTotal);
385 tr.Stop (TimeReporter.TimerType.EmitTotal);
387 if (Report.Errors > 0){
391 tr.Start (TimeReporter.TimerType.CloseTypes);
392 module.CloseContainer ();
393 tr.Stop (TimeReporter.TimerType.CloseTypes);
395 tr.Start (TimeReporter.TimerType.Resouces);
396 if (!settings.WriteMetadataOnly)
397 assembly.EmbedResources ();
398 tr.Stop (TimeReporter.TimerType.Resouces);
400 if (Report.Errors > 0)
406 references_loader.Dispose ();
411 return Report.Errors == 0;
416 // This is the only public entry point
418 public class CompilerCallableEntryPoint : MarshalByRefObject {
419 public static bool InvokeCompiler (string [] args, TextWriter error)
422 CommandLineParser cmd = new CommandLineParser (error);
423 var setting = cmd.ParseArguments (args);
427 var d = new Driver (new CompilerContext (setting, new StreamReportPrinter (error)));
434 public static int[] AllWarningNumbers {
436 return Report.AllWarnings;
440 public static void Reset ()
445 public static void PartialReset ()
450 public static void Reset (bool full_flag)
457 Linq.QueryBlock.TransparentParameter.Reset ();