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