Example #1
0
        public static DynamicContext Create()
        {
            if (dc != null)
            {
                return(dc);
            }

            lock (compiler_initializer) {
                if (dc != null)
                {
                    return(dc);
                }

                var settings = new Compiler.CompilerSettings()
                {
                    WarningLevel = 0
                };

                var cc = new Compiler.CompilerContext(settings, ErrorPrinter.Instance)
                {
                    IsRuntimeBinder = true
                };

                //
                // Any later loaded assemblies are handled internally by GetAssemblyDefinition
                // domain.AssemblyLoad cannot be used as that would be too destructive as we
                // would hold all loaded assemblies even if they can be never visited
                //
                // TODO: Remove this code and rely on GetAssemblyDefinition only
                //
                var module = new Compiler.ModuleContainer(cc);
                module.HasTypesFullyDefined = true;

                // Setup fake assembly, it's used mostly to simplify checks like friend-access
                var temp = new Compiler.AssemblyDefinitionDynamic(module, "dynamic");
                module.SetDeclaringAssembly(temp);

                var importer = new Compiler.ReflectionImporter(module, cc.BuiltinTypes)
                {
                    IgnorePrivateMembers         = false,
                    IgnoreCompilerGeneratedField = false
                };

                // Import all currently loaded assemblies
                // TODO: Rewrite this to populate type cache on-demand, that should greatly
                // reduce our start-up cost
                var domain = AppDomain.CurrentDomain;
                foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    importer.ImportAssembly(a, module.GlobalRootNamespace);
                }

                cc.BuiltinTypes.CheckDefinitions(module);
                module.InitializePredefinedTypes();

                dc = new DynamicContext(module, importer);
            }

            return(dc);
        }
Example #2
0
        public int Run()
        {
            // Enable unsafe code by default
            var settings = new CompilerSettings () {
                Unsafe = true
            };

            var startup_files = new string [0];
            settings.SourceFiles.Clear ();
            ReportPrinter printer= new ConsoleReportPrinter ();
            var eval = new Evaluator (new CompilerContext (settings, printer));
            eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
            eval.DescribeTypeExpressions = true;
            eval.WaitOnTask = true;

            CSharpShell shell;
            #if !ON_DOTNET
            if (attach.HasValue) {
                shell = new ClientCSharpShell (eval, attach.Value);
            } else if (agent != null) {
                new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
                return 0;
            } else
                #endif
            {
                shell = new CSharpShell (eval, console);
            }
            return shell.Run (startup_files);
        }
Example #3
0
 public CompilerContext(CompilerSettings settings, ReportPrinter reportPrinter)
 {
     this.settings      = settings;
     this.report        = new Report(this, reportPrinter);
     this.builtin_types = new BuiltinTypes();
     this.TimeReporter  = DisabledTimeReporter;
 }
Example #4
0
        private static void InitializeEvaluator()
        {
            _Interop.VarStorage["ReplVersion"] = typeof(Program).Assembly.GetName().Version;

            var settings = new CompilerSettings() {
                StdLib = true
            };

            var reportPrinter = new ConsoleReportPrinter();

            var ctx = new CompilerContext(settings, reportPrinter);

            evaluator = new Evaluator(ctx);

            evaluator.ReferenceAssembly(typeof(_Interop).Assembly);

            evaluator.Run(
            @"
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            ");

            evaluator.Run("var _v = _Interop.VarStorage;");
            evaluator.Run("var _h = _Interop.History;");
            evaluator.Run("_Interop.VoidMethod exit = _Interop.Exit;");
            evaluator.Run("_Interop.ReturnStringListMethod globals = _Interop.GetGlobals");
        }
Example #5
0
 public CompilerContext(CompilerSettings settings, Report report)
 {
     this.settings      = settings;
     this.report        = report;
     this.builtin_types = new BuiltinTypes();
     this.TimeReporter  = DisabledTimeReporter;
 }
        public CSharpCompiler()
        {
            CompilerSettings settings = new CompilerSettings ();
            Report report = new Report (new NullReportPrinter ());

            evaluator = new Evaluator (settings, report);
        }
Example #7
0
		public static DynamicContext Create ()
		{
			if (dc != null)
				return dc;

			lock (compiler_initializer) {
				if (dc != null)
					return dc;

				var reporter = new Compiler.Report (ErrorPrinter.Instance) {
					WarningLevel = 0
				};

				var settings = new Compiler.CompilerSettings ();

				var cc = new Compiler.CompilerContext (settings, reporter) {
					IsRuntimeBinder = true
				};

				//IList<Compiler.PredefinedTypeSpec> core_types = null;
				//// HACK: To avoid re-initializing static TypeManager types, like string_type
				//if (!Compiler.RootContext.EvalMode) {
				//    core_types = Compiler.TypeManager.InitCoreTypes ();
				//}

				//
				// Any later loaded assemblies are handled internally by GetAssemblyDefinition
				// domain.AssemblyLoad cannot be used as that would be too destructive as we
				// would hold all loaded assemblies even if they can be never visited
				//
				// TODO: Remove this code and rely on GetAssemblyDefinition only
				//
				var module = new Compiler.ModuleContainer (cc);
				module.HasTypesFullyDefined = true;
				var temp = new Compiler.AssemblyDefinitionDynamic (module, "dynamic");
				module.SetDeclaringAssembly (temp);

				// Import all currently loaded assemblies
				var domain = AppDomain.CurrentDomain;

				temp.Create (domain, System.Reflection.Emit.AssemblyBuilderAccess.Run);
				var importer = new Compiler.ReflectionImporter (module, cc.BuiltinTypes) {
					IgnorePrivateMembers = false
				};

				foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
					importer.ImportAssembly (a, module.GlobalRootNamespace);
				}

				cc.BuiltinTypes.CheckDefinitions (module);
				module.InitializePredefinedTypes ();

				dc = new DynamicContext (module, importer);
			}

			return dc;
		}
Example #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Dynamic.Compiler"/> class.
 /// </summary>
 /// <param name="project">Project.</param>
 public Compiler(Project project)
 {
     Project = project;
     Settings = new CompilerSettings()
     {
         OutputFile = "DynamicCodeTests-Scene.dll"
     };
     //			Settings.AssemblyReferences.Remove("system.dll");
     Trace.Log(TraceEventType.Information, "Project=\"{0}\"\nSettings:\n{1}", project.Name, Settings.ToString());
 }
Example #9
0
		public Report (CompilerContext context, ReportPrinter printer)
		{
			if (context == null)
				throw new ArgumentNullException ("settings");
			if (printer == null)
				throw new ArgumentNullException ("printer");

			this.settings = context.Settings;
			this.printer = printer;
		}
        /// <summary>
        /// Initializes the evaluator and includes a few basic System libraries
        /// </summary>
        public Runner()
        {
            _report   = new Report(new Printer(this));
            _settings = new CommandLineParser(_report).ParseArguments(new string[] {});
            _eval     = new Evaluator(_settings, _report);

            _eval.Run("using System;");
            _eval.Run("using System.Linq;");
            _eval.Run("using System.Collections.Generic;");
        }
Example #11
0
        public void Setup()
        {
            var builder = new StringBuilder();
            var writer = new StringWriter(builder);
            var printer = new StreamReportPrinter(writer);
            var settings = new CompilerSettings();
            settings.AssemblyReferences.Add("DbTool.Testing");

            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context);
        }
Example #12
0
        /// <summary>
        /// Initializes the evaluator and includes a few basic System libraries
        /// </summary>
        public Runner()
        {
            _report = new Report(new Printer(this));
            _settings = new CommandLineParser(_report).ParseArguments (new string[] {});
            _eval = new Evaluator(_settings, _report);

            _eval.ReferenceAssembly(typeof(System.Linq.Enumerable).Assembly);

            _eval.Run("using System;");
            _eval.Run("using System.Collections.Generic;");
            _eval.Run("using System.Linq;");
        }
Example #13
0
		public static DynamicContext Create ()
		{
			if (dc != null)
				return dc;

			lock (compiler_initializer) {
				if (dc != null)
					return dc;

				var settings = new Compiler.CompilerSettings () {
					WarningLevel = 0
				};

				var cc = new Compiler.CompilerContext (settings, ErrorPrinter.Instance) {
					IsRuntimeBinder = true
				};

				//
				// Any later loaded assemblies are handled internally by GetAssemblyDefinition
				// domain.AssemblyLoad cannot be used as that would be too destructive as we
				// would hold all loaded assemblies even if they can be never visited
				//
				// TODO: Remove this code and rely on GetAssemblyDefinition only
				//
				var module = new Compiler.ModuleContainer (cc);
				module.HasTypesFullyDefined = true;
				
				// Setup fake assembly, it's used mostly to simplify checks like friend-access
				var temp = new Compiler.AssemblyDefinitionDynamic (module, "dynamic");
				module.SetDeclaringAssembly (temp);

				var importer = new Compiler.ReflectionImporter (module, cc.BuiltinTypes) {
					IgnorePrivateMembers = false,
					IgnoreCompilerGeneratedField = false
				};

				// Import all currently loaded assemblies
				// TODO: Rewrite this to populate type cache on-demand, that should greatly
				// reduce our start-up cost
				var domain = AppDomain.CurrentDomain;
				foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
					importer.ImportAssembly (a, module.GlobalRootNamespace);
				}

				cc.BuiltinTypes.CheckDefinitions (module);
				module.InitializePredefinedTypes ();

				dc = new DynamicContext (module, importer);
			}

			return dc;
		}
Example #14
0
		public Evaluator (CompilerSettings settings, Report report)
		{
			ctx = new CompilerContext (settings, report);

			module = new ModuleContainer (ctx);
			module.Evaluator = this;

			// FIXME: Importer needs this assembly for internalsvisibleto
			module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
			importer = new ReflectionImporter (module, ctx.BuildinTypes);

			InteractiveBaseClass = typeof (InteractiveBase);
			fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
		}
Example #15
0
		void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
		{
			if (assembly.Length == 0) {
				report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
				return;
			}

			if (!IsExternAliasValid (alias)) {
				report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
				return;
			}

			settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
		}
Example #16
0
        public Evaluator(CompilerSettings settings, Report report)
        {
            ctx = new CompilerContext(settings, report);

            module           = new ModuleContainer(ctx);
            module.Evaluator = this;

            // FIXME: Importer needs this assembly for internalsvisibleto
            module.SetDeclaringAssembly(new AssemblyDefinitionDynamic(module, "evaluator"));
            importer = new ReflectionImporter(module, ctx.BuildinTypes);

            InteractiveBaseClass = typeof(InteractiveBase);
            fields = new Dictionary <string, Tuple <FieldSpec, FieldInfo> > ();
        }
Example #17
0
        public Report(CompilerContext context, ReportPrinter printer)
        {
            if (context == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (printer == null)
            {
                throw new ArgumentNullException("printer");
            }

            this.settings = context.Settings;
            this.printer  = printer;
        }
Example #18
0
		void AddResource (AssemblyResource res, CompilerSettings settings)
		{
			if (settings.Resources == null) {
				settings.Resources = new List<AssemblyResource> ();
				settings.Resources.Add (res);
				return;
			}

			if (settings.Resources.Contains (res)) {
				report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
				return;
			}

			settings.Resources.Add (res);
		}
Example #19
0
File: repl.cs Project: GirlD/mono
		static int Main (string [] args)
		{
			var cmd = new CommandLineParser (Console.Out);
			cmd.UnknownOptionHandler += HandleExtraArguments;

			// Enable unsafe code by default
			var settings = new CompilerSettings () {
				Unsafe = true
			};

			if (!cmd.ParseArguments (settings, args))
				return 1;

			var startup_files = new string [settings.SourceFiles.Count];
			int i = 0;
			foreach (var source in settings.SourceFiles)
				startup_files [i++] = source.FullPathName;
			settings.SourceFiles.Clear ();

			TextWriter agent_stderr = null;
			ReportPrinter printer;
			if (agent != null) {
				agent_stderr = new StringWriter ();
				printer = new StreamReportPrinter (agent_stderr);
			} else {
				printer = new ConsoleReportPrinter ();
			}

			var eval = new Evaluator (new CompilerContext (settings, printer));

			eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
			eval.DescribeTypeExpressions = true;
			eval.WaitOnTask = true;

			CSharpShell shell;
#if !ON_DOTNET
			if (attach.HasValue) {
				shell = new ClientCSharpShell (eval, attach.Value);
			} else if (agent != null) {
				new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
				return 0;
			} else
#endif
			{
				shell = new CSharpShell (eval);
			}
			return shell.Run (startup_files);
		}
        public void Init()
        {
            var printer = new StreamReportPrinter(_stringWriter);
            var settings = new CompilerSettings();
            settings.AssemblyReferences.AddRange(InitialAssemblies);
            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context)
                {
                    InteractiveBaseClass = typeof (DbToolInteractive),
                    DescribeTypeExpressions = true,
                };
            ReferenceAssemblies(typeof(Database).Assembly, typeof(DynamicSqlQuery).Assembly);

            Using(InitialUsings);
            DbToolInteractive.Evaluator = _evaluator;
            DbToolInteractive.Output = _stringWriter;
        }
        private CompilerContext CreateContext([NotNull] string source)
        {
            var settings = new CompilerSettings
            {
                Target = Target.Library,
                TargetExt = ".dll",
                LoadDefaultReferences = true,
                ShowFullPaths = false,
                StdLib = true,
            };

            var context = new CompilerContext(settings, new ConsoleReportPrinter(_logger));
            context.SourceFiles.Add(new SourceFile("Source", source, 0));

            _report = new Report(context, new ConsoleReportPrinter(_logger));

            return context;
        }
        // This method evaluates the given code and returns a CompilerOutput object
        public static CompilerOutput evaluateCode(string code)
        {
            CompilerOutput compilerOutput = new CompilerOutput ();
            /*
            var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());

            var evaluator = new Evaluator(compilerContext);
            */
            var reportWriter = new StringWriter();
            var settings = new CompilerSettings();
            var printer = new ConsoleReportPrinter(reportWriter);

            var compilerContext = new CompilerContext (settings, printer);
            var reports = new Report(compilerContext, printer);
            var evaluator = new Evaluator(compilerContext);

            var myString = "";
            originalConsoleOut_global = Console.Out; // preserve the original stream
            using(var writer = new StringWriter())
            {
                Console.SetOut(writer);

                evaluator.Run (code);
                evaluator.Run ("MainClass m1 = new MainClass(); m1.Main();");

                //bConsole.WriteLine ("after executing code");

                if (reports.Errors > 0) {
                    Console.WriteLine ("reportWriter.ToString: \n" + reportWriter.ToString ());
                    compilerOutput.errors = reportWriter.ToString ();
                }

                writer.Flush(); // make sure everything is written out of consule

                myString = writer.GetStringBuilder().ToString();

                compilerOutput.consoleOut = myString;

            }

            Console.SetOut(originalConsoleOut_global); // restore Console.Out

            return compilerOutput;
        }
Example #23
0
        public Evaluator(CompilerSettings settings, Report report)
        {
            ctx = new CompilerContext(settings, report);

            module           = new ModuleContainer(ctx);
            module.Evaluator = this;

            source_file = new CompilationSourceFile("{interactive}", "", 1);
            source_file.NamespaceContainer = new NamespaceEntry(module, null, source_file, null);

            ctx.SourceFiles.Add(source_file);

            // FIXME: Importer needs this assembly for internalsvisibleto
            module.SetDeclaringAssembly(new AssemblyDefinitionDynamic(module, "evaluator"));
            importer = new ReflectionImporter(module, ctx.BuiltinTypes);

            InteractiveBaseClass = typeof(InteractiveBase);
            fields = new Dictionary <string, Tuple <FieldSpec, FieldInfo> > ();
        }
Example #24
0
		public Evaluator (CompilerSettings settings, Report report)
		{
			ctx = new CompilerContext (settings, report);

			module = new ModuleContainer (ctx);
			module.Evaluator = this;

			source_file = new CompilationSourceFile ("{interactive}", "", 1);
 			source_file.NamespaceContainer = new NamespaceContainer (null, module, null, source_file);

			ctx.SourceFiles.Add (source_file);

			// FIXME: Importer needs this assembly for internalsvisibleto
			module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
			importer = new ReflectionImporter (module, ctx.BuiltinTypes);

			InteractiveBaseClass = typeof (InteractiveBase);
			fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
		}
Example #25
0
        ///////////////////////////////////////////////////////////////////////
        private void Initialize()
        {
            CompilerSettings sett = new CompilerSettings();
            ReportPrinter prnt = new ConsoleReportPrinter();

            // TODO programatically add references for all flynn assemblies

            sett.AssemblyReferences.Add("Flynn.Core.dll");
            sett.AssemblyReferences.Add("Flynn.X10.dll");
            sett.AssemblyReferences.Add("Flynn.Cron.dll");
            sett.AssemblyReferences.Add("Flynn.Utilities.dll");

            CompilerContext ctx = new CompilerContext(sett, prnt);

            _eval = new Evaluator(ctx);

            _eval.Run(Resources.CSharpEngine_InitUsings);
            _eval.Run(Resources.CSharpEngine_InitScript);
        }
        public MonoCSharpExecutor()
        {
            _reportBuilder = new StringBuilder();
            var writer = new StringWriter(_reportBuilder);
            var printer = new StreamReportPrinter(writer);
            var settings = new CompilerSettings();

            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context);
            _evaluator.InteractiveBaseClass = typeof (InteractiveStuff);
            _evaluator.ReferenceAssembly(typeof(HttpContext).Assembly);
            _evaluator.ReferenceAssembly(typeof(VisualFarmRepo).Assembly);
            _evaluator.ReferenceAssembly(typeof(BondegardFacade).Assembly);
            _evaluator.ReferenceAssembly(typeof(IVFSConfig).Assembly);
            Execute("using System;");
            Execute("using System.Linq;");
            Execute("using System.Web;");
            Execute("using VisualFarmStudio.Core.Domain;");
            Execute("using VisualFarmStudio.Core.Repository;");
            Execute("using VisualFarmStudio.Lib.Model;");
            Execute("using VisualFarmStudio.Lib.Containers;");
        }
Example #27
0
        public DebuggerWindow(PluginContext context, String hackPath)
        {
            this.InitializeComponent();

            Trace.Listeners.Add(this.listener);

            var compilerSettings = new CompilerSettings
            {
                Unsafe = true,
            };
            compilerSettings.AssemblyReferences.Add("System.dll");
            compilerSettings.AssemblyReferences.Add("System.Core.dll");
            compilerSettings.AssemblyReferences.Add(typeof(MessageBox).Assembly.CodeBase); // PresentationFramework.dll
            compilerSettings.AssemblyReferences.Add(Path.Combine(hackPath, "SharpCraft.dll"));

            var compilerContext = new CompilerContext(compilerSettings, new DebuggerReportPrinter());

            evaluator = new Evaluator(compilerContext);
            evaluator.Compile("using System;");
            evaluator.Compile("using TinkerWorX.SharpCraft;");
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            CompilerSettings settings = new CompilerSettings();
            Report report = new Report(new ConsoleReportPrinter());
            Evaluator eval = new Evaluator(settings, report);

            object instance = null;
            bool instanceCreated = false;
            eval.ReferenceAssembly(typeof(Controller).Assembly);

            foreach (Assembly assembly in assemblies)
            {
                eval.ReferenceAssembly(assembly);
            }

            string controllerName = GetControllerName(requestContext, controllerType);
            string path = pathProvider.GetPath(requestContext, controllerName);
            CSharpControllerFile controllerFile = CSharpControllerFile.Parse(File.ReadAllText(path));

            eval.Run(controllerFile.ClassSource);
            eval.Evaluate("new " + controllerName + "();", out instance, out instanceCreated);

            return (IController)instance;
        }
Example #29
0
		void InitIfNeeded()
		{
			if (eval == null) {

				Log ("INIT EVAL");

				var settings = new CompilerSettings ();
				settings.AddConditionalSymbol ("__Continuous__");
				settings.AddConditionalSymbol ("DEBUG");
				PlatformSettings (settings);
				var context = new CompilerContext (settings, printer);
				eval = new Evaluator (context);

				//
				// Add References to get UIKit, etc. Also add a hook to catch dynamically loaded assemblies.
				//
				AppDomain.CurrentDomain.AssemblyLoad += (_, e) => {
					Log ("DYNAMIC REF {0}", e.LoadedAssembly);
					AddReference (e.LoadedAssembly);
				};
				foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
					Log ("STATIC REF {0}", a);
					AddReference (a);
				}

				//
				// Add default namespaces
				//
				object res;
				bool hasRes;
				eval.Evaluate ("using System;", out res, out hasRes);
				eval.Evaluate ("using System.Collections.Generic;", out res, out hasRes);
				eval.Evaluate ("using System.Linq;", out res, out hasRes);
				PlatformInit ();
			}
		}
Example #30
0
		public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
		{
			var rp = new StreamReportPrinter (errorOutput);

			parser_settings = new CompilerSettings ();
			report = new Report (new CompilerContext (parser_settings, rp), rp);
			this.output = messagesOutput;
		}
Example #31
0
		void SetWarningLevel (string s, CompilerSettings settings)
		{
			int level = -1;

			try {
				level = int.Parse (s);
			} catch {
			}
			if (level < 0 || level > 4) {
				report.Error (1900, "Warning level must be in the range 0-4");
				return;
			}
			settings.WarningLevel = level;
		}
Example #32
0
		//
		// Currently handles the Unix-like command line options, but will be
		// deprecated in favor of the CSCParseOption, which will also handle the
		// options that start with a dash in the future.
		//
		ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
		{
			switch (arg){
			case "-v":
				settings.VerboseParserFlag++;
				return ParseResult.Success;

			case "--version":
				Version ();
				return ParseResult.Stop;
				
			case "--parse":
				settings.ParseOnly = true;
				return ParseResult.Success;
				
			case "--main": case "-m":
				report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				settings.MainClass = args[++i];
				return ParseResult.Success;
				
			case "--unsafe":
				report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
				settings.Unsafe = true;
				return ParseResult.Success;
				
			case "/?": case "/h": case "/help":
			case "--help":
				Usage ();
				return ParseResult.Stop;

			case "--define":
				report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				settings.AddConditionalSymbol (args [++i]);
				return ParseResult.Success;

			case "--tokenize":
				settings.TokenizeOnly = true;
				return ParseResult.Success;
				
			case "-o": 
			case "--output":
				report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				settings.OutputFile = args[++i];
				return ParseResult.Success;

			case "--checked":
				report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
				settings.Checked = true;
				return ParseResult.Success;
				
			case "--stacktrace":
				settings.Stacktrace = true;
				return ParseResult.Success;
				
			case "--linkresource":
			case "--linkres":
				report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				AddResource (new AssemblyResource (args[++i], args[i]), settings);
				return ParseResult.Success;
				
			case "--resource":
			case "--res":
				report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				AddResource (new AssemblyResource (args[++i], args[i], true), settings);
				return ParseResult.Success;
				
			case "--target":
				report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				
				string type = args [++i];
				switch (type){
				case "library":
					settings.Target = Target.Library;
					settings.TargetExt = ".dll";
					break;
					
				case "exe":
					settings.Target = Target.Exe;
					break;
					
				case "winexe":
					settings.Target = Target.WinExe;
					break;
					
				case "module":
					settings.Target = Target.Module;
					settings.TargetExt = ".dll";
					break;
				default:
					report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
					break;
				}
				return ParseResult.Success;
				
			case "-r":
				report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				
				string val = args [++i];
				int idx = val.IndexOf ('=');
				if (idx > -1) {
					string alias = val.Substring (0, idx);
					string assembly = val.Substring (idx + 1);
					AddAssemblyReference (alias, assembly, settings);
					return ParseResult.Success;
				}

				settings.AssemblyReferences.Add (val);
				return ParseResult.Success;
				
			case "-L":
				report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				settings.ReferencesLookupPaths.Add (args [++i]);
				return ParseResult.Success;

			case "--lint":
				settings.EnhancedWarnings = true;
				return ParseResult.Success;
				
			case "--nostdlib":
				report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
				settings.StdLib = false;
				return ParseResult.Success;
				
			case "--nowarn":
				report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				int warn = 0;
				
				try {
					warn = int.Parse (args [++i]);
				} catch {
					Usage ();
					Environment.Exit (1);
				}
				settings.SetIgnoreWarning (warn);
				return ParseResult.Success;

			case "--wlevel":
				report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				SetWarningLevel (args [++i], settings);
				return ParseResult.Success;

			case "--mcs-debug":
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				try {
					settings.DebugFlags = int.Parse (args [++i]);
				} catch {
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				return ParseResult.Success;
				
			case "--about":
				About ();
				return ParseResult.Stop;
				
			case "--recurse":
				report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				ProcessSourceFiles (args [++i], true, settings.SourceFiles);
				return ParseResult.Success;
				
			case "--timestamp":
				settings.Timestamps = true;
				return ParseResult.Success;

			case "--debug": case "-g":
				report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
				settings.GenerateDebugInfo = true;
				return ParseResult.Success;
				
			case "--noconfig":
				report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
				settings.LoadDefaultReferences = false;
				return ParseResult.Success;

			case "--metadata-only":
				settings.WriteMetadataOnly = true;
				return ParseResult.Success;

			default:
				if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
					int fatal = 1;
					if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
						int.TryParse (arg.Substring (8), out fatal);

					settings.FatalCounter = fatal;
					return ParseResult.Success;
				}
				if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
					string version = arg.Substring (10);

					switch (version) {
					case "v1":
					case "V1":
						settings.StdLibRuntimeVersion = RuntimeVersion.v1;
						break;
					case "v2":
					case "V2":
						settings.StdLibRuntimeVersion = RuntimeVersion.v2;
						break;
					case "v4":
					case "V4":
						settings.StdLibRuntimeVersion = RuntimeVersion.v4;
						break;
					}
					return ParseResult.Success;
				}

				return ParseResult.UnknownOption;
			}
		}
Example #33
0
		public CompilerContext (CompilerSettings settings, ReportPrinter reportPrinter)
		{
			this.settings = settings;
			this.report = new Report (this, reportPrinter);
			this.builtin_types = new BuiltinTypes ();
			this.TimeReporter = DisabledTimeReporter;
		}
Example #34
0
 		public void Setup ()
 		{
			settings = new CompilerSettings ();
			var ctx = new CompilerContext (settings, new AssertReportPrinter ());
			evaluator = new Evaluator (ctx);
		}
Example #35
0
		//
		// Currently handles the Unix-like command line options, but will be
		// deprecated in favor of the CSCParseOption, which will also handle the
		// options that start with a dash in the future.
		//
		ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
		{
			switch (arg){
			case "-v":
				CSharpParser.yacc_verbose_flag++;
				return ParseResult.Success;

			case "--version":
				Version ();
				return ParseResult.Stop;
				
			case "--parse":
				settings.ParseOnly = true;
				return ParseResult.Success;
				
			case "--main": case "-m":
				report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				settings.MainClass = args[++i];
				return ParseResult.Success;
				
			case "--unsafe":
				report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
				settings.Unsafe = true;
				return ParseResult.Success;
				
			case "/?": case "/h": case "/help":
			case "--help":
				Usage ();
				return ParseResult.Stop;

			case "--define":
				report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				RootContext.AddConditional (args [++i]);
				return ParseResult.Success;

			case "--tokenize":
				settings.TokenizeOnly = true;
				return ParseResult.Success;
				
			case "-o": 
			case "--output":
				report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				settings.OutputFile = args[++i];
				return ParseResult.Success;

			case "--checked":
				report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
				settings.Checked = true;
				return ParseResult.Success;
				
			case "--stacktrace":
				report.Printer.Stacktrace = true;
				return ParseResult.Success;
				
			case "--linkresource":
			case "--linkres":
				report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				AddResource (new AssemblyResource (args[++i], args[i]), settings);
				return ParseResult.Success;
				
			case "--resource":
			case "--res":
				report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				AddResource (new AssemblyResource (args[++i], args[i], true), settings);
				return ParseResult.Success;
				
			case "--target":
				report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				
				string type = args [++i];
				switch (type){
				case "library":
					settings.Target = Target.Library;
					settings.TargetExt = ".dll";
					break;
					
				case "exe":
					settings.Target = Target.Exe;
					break;
					
				case "winexe":
					settings.Target = Target.WinExe;
					break;
					
				case "module":
					settings.Target = Target.Module;
					settings.TargetExt = ".dll";
					break;
				default:
					report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
					break;
				}
				return ParseResult.Success;
				
			case "-r":
				report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				
				string val = args [++i];
				int idx = val.IndexOf ('=');
				if (idx > -1) {
					string alias = val.Substring (0, idx);
					string assembly = val.Substring (idx + 1);
					AddAssemblyReference (alias, assembly, settings);
					return ParseResult.Success;
				}

				settings.AssemblyReferences.Add (val);
				return ParseResult.Success;
				
			case "-L":
				report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				settings.ReferencesLookupPaths.Add (args [++i]);
				return ParseResult.Success;

			case "--lint":
				settings.EnhancedWarnings = true;
				return ParseResult.Success;
				
			case "--nostdlib":
				report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
				settings.StdLib = false;
				return ParseResult.Success;
				
			case "--nowarn":
				report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				int warn = 0;
				
				try {
					warn = int.Parse (args [++i]);
				} catch {
					Usage ();
					//Environment.Exit (1);
				}
				report.SetIgnoreWarning (warn);
				return ParseResult.Success;

			case "--wlevel":
				report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				SetWarningLevel (args [++i]);
				return ParseResult.Success;

			case "--mcs-debug":
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				try {
					Report.DebugFlags = int.Parse (args [++i]);
				} catch {
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}

				return ParseResult.Success;
				
			case "--about":
				About ();
				return ParseResult.Stop;
				
			case "--recurse":
				report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
				if ((i + 1) >= args.Length){
					Error_RequiresArgument (arg);
					return ParseResult.Error;
				}
				ProcessSourceFiles (args [++i], true); 
				return ParseResult.Success;
				
			case "--timestamp":
				settings.Timestamps = true;
				return ParseResult.Success;

			case "--debug": case "-g":
				report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
				settings.GenerateDebugInfo = true;
				return ParseResult.Success;
				
			case "--noconfig":
				report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
				settings.LoadDefaultReferences = false;
				return ParseResult.Success;

			default:
				if (arg.StartsWith ("--fatal")){
					int fatal = 1;
					if (arg.StartsWith ("--fatal="))
						int.TryParse (arg.Substring (8), out fatal);

					report.Printer.FatalCounter = fatal;
					return ParseResult.Success;
				}
				if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
					string version = arg.Substring (10);

					switch (version) {
					case "v1":
					case "V1":
						settings.StdLibRuntimeVersion = RuntimeVersion.v1;
						break;
					case "v2":
					case "V2":
						settings.StdLibRuntimeVersion = RuntimeVersion.v2;
						break;
					case "v4":
					case "V4":
						settings.StdLibRuntimeVersion = RuntimeVersion.v4;
						break;
					}
					return ParseResult.Success;
				}

				return ParseResult.UnknownOption;
			}
		}
Example #36
0
		void AddResource (AssemblyResource res, CompilerSettings settings)
		{
			if (settings.Resources == null) {
				settings.Resources = new List<AssemblyResource> ();
				settings.Resources.Add (res);
				return;
			}

			if (settings.Resources.Contains (res)) {
				report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
				return;
			}

			settings.Resources.Add (res);
		}
Example #37
0
		public CompilerSettings ParseArguments (string[] args)
		{
			CompilerSettings settings = new CompilerSettings ();
			List<string> response_file_list = null;
			bool parsing_options = true;
			stop_argument = false;
			source_file_index = new Dictionary<string, int> ();

			for (int i = 0; i < args.Length; i++) {
				string arg = args[i];
				if (arg.Length == 0)
					continue;

				if (arg[0] == '@') {
					string[] extra_args;
					string response_file = arg.Substring (1);

					if (response_file_list == null)
						response_file_list = new List<string> ();

					if (response_file_list.Contains (response_file)) {
						report.Error (1515, "Response file `{0}' specified multiple times", response_file);
						return null;
					}

					response_file_list.Add (response_file);

					extra_args = LoadArgs (response_file);
					if (extra_args == null) {
						report.Error (2011, "Unable to open response file: " + response_file);
						return null;
					}

					args = AddArgs (args, extra_args);
					continue;
				}

				if (parsing_options) {
					if (arg == "--") {
						parsing_options = false;
						continue;
					}

					bool dash_opt = arg[0] == '-';
					bool slash_opt = arg[0] == '/';
					if (dash_opt) {
						switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
						case ParseResult.Error:
						case ParseResult.Success:
							continue;
						case ParseResult.Stop:
							stop_argument = true;
							return settings;
						case ParseResult.UnknownOption:
							if (UnknownOptionHandler != null) {
								var ret = UnknownOptionHandler (args, i);
								if (ret != -1) {
									i = ret;
									continue;
								}
							}
							break;
						}
					}

					if (dash_opt || slash_opt) {
						// Try a -CSCOPTION
						string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
						switch (ParseOption (csc_opt, ref args, settings)) {
						case ParseResult.Error:
						case ParseResult.Success:
							continue;
						case ParseResult.UnknownOption:
							// Need to skip `/home/test.cs' however /test.cs is considered as error
							if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
								break;

							if (UnknownOptionHandler != null) {
								var ret = UnknownOptionHandler (args, i);
								if (ret != -1) {
									i = ret;
									continue;
								}
							}

							Error_WrongOption (arg);
							return null;

						case ParseResult.Stop:
							stop_argument = true;
							return settings;
						}
					}
				}

				ProcessSourceFiles (arg, false, settings.SourceFiles);
			}

			if (report.Errors > 0)
				return null;

			return settings;
		}
Example #38
0
		public CompilerSettings ParseArguments (string[] args)
		{
			CompilerSettings settings = new CompilerSettings ();
			List<string> response_file_list = null;
			bool parsing_options = true;
			stop_argument = false;

			for (int i = 0; i < args.Length; i++) {
				string arg = args[i];
				if (arg.Length == 0)
					continue;

				if (arg[0] == '@') {
					string[] extra_args;
					string response_file = arg.Substring (1);

					if (response_file_list == null)
						response_file_list = new List<string> ();

					if (response_file_list.Contains (response_file)) {
						report.Error (1515, "Response file `{0}' specified multiple times", response_file);
						return null;
					}

					response_file_list.Add (response_file);

					extra_args = LoadArgs (response_file);
					if (extra_args == null) {
						report.Error (2011, "Unable to open response file: " + response_file);
						return null;
					}

					args = AddArgs (args, extra_args);
					continue;
				}

				if (parsing_options) {
					if (arg == "--") {
						parsing_options = false;
						continue;
					}

					bool dash_opt = arg[0] == '-';
					bool slash_opt = arg[0] == '/';
					if (dash_opt) {
						switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
						case ParseResult.Error:
						case ParseResult.Success:
							continue;
						case ParseResult.Stop:
							stop_argument = true;
							return settings;
						case ParseResult.UnknownOption:
							if (UnknownOptionHandler != null) {
								var ret = UnknownOptionHandler (args, i);
								if (ret != -1) {
									i = ret;
									continue;
								}
							}
							break;
						}
					}

					if (dash_opt || slash_opt) {
						// Try a -CSCOPTION
						string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
						switch (ParseOption (csc_opt, ref args, settings)) {
						case ParseResult.Error:
						case ParseResult.Success:
							continue;
						case ParseResult.UnknownOption:
							// Need to skip `/home/test.cs' however /test.cs is considered as error
							if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
								break;

							if (UnknownOptionHandler != null) {
								var ret = UnknownOptionHandler (args, i);
								if (ret != -1) {
									i = ret;
									continue;
								}
							}

							Error_WrongOption (arg);
							return null;

						case ParseResult.Stop:
							stop_argument = true;
							return settings;
						}
					}
				}

				ProcessSourceFiles (arg, false);
			}

			return settings;
		}
Example #39
0
		void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
		{
			if (assembly.Length == 0) {
				report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
				return;
			}

			if (!IsExternAliasValid (alias)) {
				report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
				return;
			}

			settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
		}
Example #40
0
		//
		// This parses the -arg and /arg options to the compiler, even if the strings
		// in the following text use "/arg" on the strings.
		//
		ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
		{
			int idx = option.IndexOf (':');
			string arg, value;

			if (idx == -1) {
				arg = option;
				value = "";
			} else {
				arg = option.Substring (0, idx);

				value = option.Substring (idx + 1);
			}

			switch (arg.ToLowerInvariant ()) {
			case "/nologo":
				return ParseResult.Success;

			case "/t":
			case "/target":
				switch (value) {
				case "exe":
					settings.Target = Target.Exe;
					break;

				case "winexe":
					settings.Target = Target.WinExe;
					break;

				case "library":
					settings.Target = Target.Library;
					settings.TargetExt = ".dll";
					break;

				case "module":
					settings.Target = Target.Module;
					settings.TargetExt = ".netmodule";
					break;

				default:
					report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
					return ParseResult.Error;
				}
				return ParseResult.Success;

			case "/out":
				if (value.Length == 0) {
					Error_RequiresFileName (option);
					return ParseResult.Error;
				}
				settings.OutputFile = value;
				return ParseResult.Success;

			case "/o":
			case "/o+":
			case "/optimize":
			case "/optimize+":
				settings.Optimize = true;
				return ParseResult.Success;

			case "/o-":
			case "/optimize-":
				settings.Optimize = false;
				return ParseResult.Success;

			// TODO: Not supported by csc 3.5+
			case "/incremental":
			case "/incremental+":
			case "/incremental-":
				// nothing.
				return ParseResult.Success;

			case "/d":
			case "/define": {
					if (value.Length == 0) {
						Error_RequiresArgument (option);
						return ParseResult.Error;
					}

					foreach (string d in value.Split (argument_value_separator)) {
						string conditional = d.Trim ();
						if (!Tokenizer.IsValidIdentifier (conditional)) {
							report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
							continue;
						}
						RootContext.AddConditional (conditional);
					}
					return ParseResult.Success;
				}

			case "/bugreport":
				//
				// We should collect data, runtime, etc and store in the file specified
				//
				output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
				return ParseResult.Success;

			case "/pkg": {
					string packages;

					if (value.Length == 0) {
						Error_RequiresArgument (option);
						return ParseResult.Error;
					}
					packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
                    string pkgout = null;// Driver.GetPackageFlags(packages, report);

					if (pkgout == null)
						return ParseResult.Error;

					string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
					args = AddArgs (args, xargs);
					return ParseResult.Success;
				}

			case "/linkres":
			case "/linkresource":
			case "/res":
			case "/resource":
				AssemblyResource res = null;
				string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
				switch (s.Length) {
				case 1:
					if (s[0].Length == 0)
						goto default;
					res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
					break;
				case 2:
					res = new AssemblyResource (s[0], s[1]);
					break;
				case 3:
					if (s[2] != "public" && s[2] != "private") {
						report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
						return ParseResult.Error;
					}
					res = new AssemblyResource (s[0], s[1], s[2] == "private");
					break;
				default:
					report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
					return ParseResult.Error;
				}

				if (res != null) {
					res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
					AddResource (res, settings);
				}

				return ParseResult.Success;

			case "/recurse":
				if (value.Length == 0) {
					Error_RequiresFileName (option);
					return ParseResult.Error;
				}
				ProcessSourceFiles (value, true);
				return ParseResult.Success;

			case "/r":
			case "/reference": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					string[] refs = value.Split (argument_value_separator);
					foreach (string r in refs) {
						if (r.Length == 0)
							continue;

						string val = r;
						int index = val.IndexOf ('=');
						if (index > -1) {
							string alias = r.Substring (0, index);
							string assembly = r.Substring (index + 1);
							AddAssemblyReference (alias, assembly, settings);
							if (refs.Length != 1) {
								report.Error (2034, "Cannot specify multiple aliases using single /reference option");
								return ParseResult.Error;
							}
						} else {
							settings.AssemblyReferences.Add (val);
						}
					}
					return ParseResult.Success;
				}
			case "/addmodule": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					string[] refs = value.Split (argument_value_separator);
					foreach (string r in refs) {
						settings.Modules.Add (r);
					}
					return ParseResult.Success;
				}
			case "/win32res": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					if (settings.Win32IconFile != null)
						report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");

					settings.Win32ResourceFile = value;
					return ParseResult.Success;
				}
			case "/win32icon": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					if (settings.Win32ResourceFile != null)
						report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");

					settings.Win32IconFile = value;
					return ParseResult.Success;
				}
			case "/doc": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					//settings.Documentation = new Documentation (value);
					return ParseResult.Error;
				}
			case "/lib": {
					string[] libdirs;

					if (value.Length == 0) {
						return ParseResult.Error;
					}

					libdirs = value.Split (argument_value_separator);
					foreach (string dir in libdirs)
						settings.ReferencesLookupPaths.Add (dir);
					return ParseResult.Success;
				}

			case "/debug-":
				settings.GenerateDebugInfo = false;
				return ParseResult.Success;

			case "/debug":
				if (value == "full" || value == "")
					settings.GenerateDebugInfo = true;

				return ParseResult.Success;

			case "/debug+":
				settings.GenerateDebugInfo = true;
				return ParseResult.Success;

			case "/checked":
			case "/checked+":
				settings.Checked = true;
				return ParseResult.Success;

			case "/checked-":
				settings.Checked = false;
				return ParseResult.Success;

			case "/clscheck":
			case "/clscheck+":
				settings.VerifyClsCompliance = true;
				return ParseResult.Success;

			case "/clscheck-":
				settings.VerifyClsCompliance = false;
				return ParseResult.Success;

			case "/unsafe":
			case "/unsafe+":
				settings.Unsafe = true;
				return ParseResult.Success;

			case "/unsafe-":
				settings.Unsafe = false;
				return ParseResult.Success;

			case "/warnaserror":
			case "/warnaserror+":
				if (value.Length == 0) {
					report.WarningsAreErrors = true;
				} else {
					foreach (string wid in value.Split (numeric_value_separator))
						report.AddWarningAsError (wid);
				}
				return ParseResult.Success;

			case "/warnaserror-":
				if (value.Length == 0) {
					report.WarningsAreErrors = false;
				} else {
					foreach (string wid in value.Split (numeric_value_separator))
						report.RemoveWarningAsError (wid);
				}
				return ParseResult.Success;

			case "/warn":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				SetWarningLevel (value);
				return ParseResult.Success;

			case "/nowarn":
					if (value.Length == 0) {
						Error_RequiresArgument (option);
						return ParseResult.Error;
					}

					var warns = value.Split (numeric_value_separator);
					foreach (string wc in warns) {
						try {
							if (wc.Trim ().Length == 0)
								continue;

							int warn = Int32.Parse (wc);
							if (warn < 1) {
								throw new ArgumentOutOfRangeException ("warn");
							}
							report.SetIgnoreWarning (warn);
						} catch {
							report.Error (1904, "`{0}' is not a valid warning number", wc);
							return ParseResult.Error;
						}
					}
					return ParseResult.Success;

			case "/noconfig":
				settings.LoadDefaultReferences = false;
				return ParseResult.Success;

			case "/platform":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				switch (value.ToLower (CultureInfo.InvariantCulture)) {
				case "anycpu":
					settings.Platform = Platform.AnyCPU;
					break;
				case "x86":
					settings.Platform = Platform.X86;
					break;
				case "x64":
					settings.Platform = Platform.X64;
					break;
				case "itanium":
					settings.Platform = Platform.IA64;
					break;
				default:
					report.Error (1672, "Invalid platform type for -platform. Valid options are `anycpu', `x86', `x64' or `itanium'");
					return ParseResult.Error;
				}

				return ParseResult.Success;

			case "/sdk":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				settings.SdkVersion = value;
				return ParseResult.Success;

			// We just ignore this.
			case "/errorreport":
			case "/filealign":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				return ParseResult.Success;

			case "/helpinternal":
				OtherFlags ();
				return ParseResult.Stop;

			case "/help":
			case "/?":
				Usage ();
				return ParseResult.Stop;

			case "/main":
			case "/m":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}
				settings.MainClass = value;
				return ParseResult.Success;

			case "/nostdlib":
			case "/nostdlib+":
				settings.StdLib = false;
				return ParseResult.Success;

			case "/nostdlib-":
				settings.StdLib = true;
				return ParseResult.Success;

			case "/fullpaths":
				report.Printer.ShowFullPaths = true;
				return ParseResult.Success;

			case "/keyfile":
				if (value.Length == 0) {
					Error_RequiresFileName (option);
					return ParseResult.Error;
				}

				settings.StrongNameKeyFile = value;
				return ParseResult.Success;

			case "/keycontainer":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				settings.StrongNameKeyContainer = value;
				return ParseResult.Success;

			case "/delaysign+":
			case "/delaysign":
				settings.StrongNameDelaySign = true;
				return ParseResult.Success;

			case "/delaysign-":
				settings.StrongNameDelaySign = false;
				return ParseResult.Success;

			case "/langversion":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				switch (value.ToLowerInvariant ()) {
				case "iso-1":
					settings.Version = LanguageVersion.ISO_1;
					return ParseResult.Success;
				case "default":
					settings.Version = LanguageVersion.Default;
					RootContext.AddConditional ("__V2__");
					return ParseResult.Success;
				case "iso-2":
					settings.Version = LanguageVersion.ISO_2;
					return ParseResult.Success;
				case "3":
					settings.Version = LanguageVersion.V_3;
					return ParseResult.Success;
				case "future":
					settings.Version = LanguageVersion.Future;
					return ParseResult.Success;
				}

				report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3' or `Default'", value);
				return ParseResult.Error;

			case "/codepage":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				switch (value) {
				case "utf8":
					settings.Encoding = new UTF8Encoding ();
					break;
				case "reset":
					settings.Encoding =  new UTF8Encoding ();//Encoding.Default;
					break;
				default:
					try {
                        settings.Encoding = new UTF8Encoding(); //Encoding.GetEncoding(int.Parse(value));
					} catch {
						report.Error (2016, "Code page `{0}' is invalid or not installed", value);
					}
					return ParseResult.Error;
				}
				return ParseResult.Success;

			default:
				return ParseResult.UnknownOption;
			}
		}
Example #41
0
		//
		// This parses the -arg and /arg options to the compiler, even if the strings
		// in the following text use "/arg" on the strings.
		//
		ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
		{
			int idx = option.IndexOf (':');
			string arg, value;

			if (idx == -1) {
				arg = option;
				value = "";
			} else {
				arg = option.Substring (0, idx);

				value = option.Substring (idx + 1);
			}

			switch (arg.ToLowerInvariant ()) {
			case "/nologo":
				return ParseResult.Success;

			case "/t":
			case "/target":
				bool is_dotnet = true;
				switch (value) {
				case "exe":
					settings.Target = Target.Exe;
					break;

				case "winexe":
					settings.Target = Target.WinExe;
					break;

				case "library":
					settings.Target = Target.Library;
					settings.TargetExt = ".dll";
					break;

				case "module":
					settings.Target = Target.Module;
					settings.TargetExt = ".netmodule";
					break;

				case "javascript":
					settings.Target = Target.JavaScript;
					settings.TargetExt = ".js";
					settings.AddConditionalSymbol ("TARGET_JS");
					is_dotnet = false;
					break;

				case "cpp":
					settings.Target = Target.Cpp;
					settings.TargetExt = ".cpp";
					settings.AddConditionalSymbol ("TARGET_CPP");
					is_dotnet = false;
					break;

				default:
					report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library', `module', `javascript' or `cpp'");
					return ParseResult.Error;
				}
				if (is_dotnet) {
					settings.AddConditionalSymbol ("TARGET_IL");
				}
				return ParseResult.Success;

			case "/out":
				if (value.Length == 0) {
					Error_RequiresFileName (option);
					return ParseResult.Error;
				}
				settings.OutputFile = value;
				return ParseResult.Success;

			case "/o":
			case "/o+":
			case "/optimize":
			case "/optimize+":
				settings.Optimize = true;
				return ParseResult.Success;

			case "/o-":
			case "/optimize-":
				settings.Optimize = false;
				return ParseResult.Success;

			// TODO: Not supported by csc 3.5+
			case "/incremental":
			case "/incremental+":
			case "/incremental-":
				// nothing.
				return ParseResult.Success;

			case "/d":
			case "/define": {
					if (value.Length == 0) {
						Error_RequiresArgument (option);
						return ParseResult.Error;
					}

					foreach (string d in value.Split (argument_value_separator)) {
						string conditional = d.Trim ();
						if (!Tokenizer.IsValidIdentifier (conditional)) {
							report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
							continue;
						}

						settings.AddConditionalSymbol (conditional);
					}
					return ParseResult.Success;
				}

			case "/bugreport":
				//
				// We should collect data, runtime, etc and store in the file specified
				//
				output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
				return ParseResult.Success;

			case "/pkg": {
					string packages;

					if (value.Length == 0) {
						Error_RequiresArgument (option);
						return ParseResult.Error;
					}
					packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
					string pkgout = Driver.GetPackageFlags (packages, report);

					if (pkgout == null)
						return ParseResult.Error;

					string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
					args = AddArgs (args, xargs);
					return ParseResult.Success;
				}

			case "/linkres":
			case "/linkresource":
			case "/res":
			case "/resource":
				AssemblyResource res = null;
				string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
				switch (s.Length) {
				case 1:
					if (s[0].Length == 0)
						goto default;
					res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
					break;
				case 2:
					res = new AssemblyResource (s[0], s[1]);
					break;
				case 3:
					if (s[2] != "public" && s[2] != "private") {
						report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
						return ParseResult.Error;
					}
					res = new AssemblyResource (s[0], s[1], s[2] == "private");
					break;
				default:
					report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
					return ParseResult.Error;
				}

				if (res != null) {
					res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
					AddResource (res, settings);
				}

				return ParseResult.Success;

			case "/recurse":
				if (value.Length == 0) {
					Error_RequiresFileName (option);
					return ParseResult.Error;
				}
				ProcessSourceFiles (value, true, settings.SourceFiles);
				return ParseResult.Success;

			case "/r":
			case "/reference": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					string[] refs = value.Split (argument_value_separator);
					foreach (string r in refs) {
						if (r.Length == 0)
							continue;

						string val = r;
						int index = val.IndexOf ('=');
						if (index > -1) {
							string alias = r.Substring (0, index);
							string assembly = r.Substring (index + 1);
							AddAssemblyReference (alias, assembly, settings);
							if (refs.Length != 1) {
								report.Error (2034, "Cannot specify multiple aliases using single /reference option");
								return ParseResult.Error;
							}
						} else {
							settings.AssemblyReferences.Add (val);
						}
					}
					return ParseResult.Success;
				}
			case "/addmodule": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					string[] refs = value.Split (argument_value_separator);
					foreach (string r in refs) {
						settings.Modules.Add (r);
					}
					return ParseResult.Success;
				}
			case "/win32res": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					if (settings.Win32IconFile != null)
						report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");

					settings.Win32ResourceFile = value;
					return ParseResult.Success;
				}
			case "/win32icon": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					if (settings.Win32ResourceFile != null)
						report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");

					settings.Win32IconFile = value;
					return ParseResult.Success;
				}
			case "/doc": {
					if (value.Length == 0) {
						Error_RequiresFileName (option);
						return ParseResult.Error;
					}

					settings.DocumentationFile = value;
					return ParseResult.Success;
				}
			case "/lib": {
					string[] libdirs;

					if (value.Length == 0) {
						return ParseResult.Error;
					}

					libdirs = value.Split (argument_value_separator);
					foreach (string dir in libdirs)
						settings.ReferencesLookupPaths.Add (dir);
					return ParseResult.Success;
				}

			case "/debug-":
				settings.GenerateDebugInfo = false;
				return ParseResult.Success;

			case "/debug":
				if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
					settings.GenerateDebugInfo = true;
					return ParseResult.Success;
				}

				if (value.Length > 0) {
					report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
				} else {
					Error_RequiresArgument (option);
				}

				return ParseResult.Error;

			case "/debug+":
				settings.GenerateDebugInfo = true;
				return ParseResult.Success;

			case "/checked":
			case "/checked+":
				settings.Checked = true;
				return ParseResult.Success;

			case "/checked-":
				settings.Checked = false;
				return ParseResult.Success;

			case "/clscheck":
			case "/clscheck+":
				settings.VerifyClsCompliance = true;
				return ParseResult.Success;

			case "/clscheck-":
				settings.VerifyClsCompliance = false;
				return ParseResult.Success;

			case "/unsafe":
			case "/unsafe+":
				settings.Unsafe = true;
				return ParseResult.Success;

			case "/unsafe-":
				settings.Unsafe = false;
				return ParseResult.Success;

			case "/warnaserror":
			case "/warnaserror+":
				if (value.Length == 0) {
					settings.WarningsAreErrors = true;
					parser_settings.WarningsAreErrors = true;
				} else {
					if (!ProcessWarningsList (value, v => settings.AddWarningAsError (v)))
						return ParseResult.Error;
				}
				return ParseResult.Success;

			case "/warnaserror-":
				if (value.Length == 0) {
					settings.WarningsAreErrors = false;
				} else {
					if (!ProcessWarningsList (value, v => settings.AddWarningOnly (v)))
						return ParseResult.Error;
				}
				return ParseResult.Success;

			case "/warn":
			case "/w":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				SetWarningLevel (value, settings);
				return ParseResult.Success;

			case "/nowarn":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				if (!ProcessWarningsList (value, v => settings.SetIgnoreWarning (v)))
					return ParseResult.Error;

				return ParseResult.Success;

			case "/noconfig":
				settings.LoadDefaultReferences = false;
				return ParseResult.Success;

			case "/platform":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				switch (value.ToLowerInvariant ()) {
				case "arm":
					settings.Platform = Platform.Arm;
					break;
				case "anycpu":
					settings.Platform = Platform.AnyCPU;
					break;
				case "x86":
					settings.Platform = Platform.X86;
					break;
				case "x64":
					settings.Platform = Platform.X64;
					break;
				case "itanium":
					settings.Platform = Platform.IA64;
					break;
				case "anycpu32bitpreferred":
					settings.Platform = Platform.AnyCPU32Preferred;
					break;
				default:
					report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
						value);
					return ParseResult.Error;
				}

				return ParseResult.Success;

			case "/sdk":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				settings.SdkVersion = value;
				return ParseResult.Success;

			// We just ignore this.
			case "/errorreport":
			case "/filealign":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				return ParseResult.Success;

            // We just ignore this.
            case "/errorendlocation":
            case "/highentropyva-":
            case "/highentropyva+":
            case "/highentropyva":
            case "/utf8output":
                return ParseResult.Success;

            // We just ignore this.
            case "/preferreduilang":
                switch (value.ToLowerInvariant())
                {
                    default:
                        return ParseResult.Success;
                }
                   
			case "/helpinternal":
				OtherFlags ();
				return ParseResult.Stop;

			case "/help":
			case "/?":
				Usage ();
				return ParseResult.Stop;

			case "/main":
			case "/m":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}
				settings.MainClass = value;
				return ParseResult.Success;

			case "/nostdlib":
			case "/nostdlib+":
				settings.StdLib = false;
				return ParseResult.Success;

			case "/nostdlib-":
				settings.StdLib = true;
				return ParseResult.Success;

			case "/fullpaths":
				settings.ShowFullPaths = true;
				return ParseResult.Success;

			case "/keyfile":
				if (value.Length == 0) {
					Error_RequiresFileName (option);
					return ParseResult.Error;
				}

				settings.StrongNameKeyFile = value;
				return ParseResult.Success;

			case "/keycontainer":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				settings.StrongNameKeyContainer = value;
				return ParseResult.Success;

			case "/delaysign+":
			case "/delaysign":
				settings.StrongNameDelaySign = true;
				return ParseResult.Success;

			case "/delaysign-":
				settings.StrongNameDelaySign = false;
				return ParseResult.Success;

			case "/langversion":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				switch (value.ToLowerInvariant ()) {
				case "iso-1":
					settings.Version = LanguageVersion.ISO_1;
					return ParseResult.Success;
				case "default":
					settings.Version = LanguageVersion.Default;
					return ParseResult.Success;
				case "iso-2":
					settings.Version = LanguageVersion.ISO_2;
					return ParseResult.Success;
				case "3":
					settings.Version = LanguageVersion.V_3;
					return ParseResult.Success;
				case "4":
					settings.Version = LanguageVersion.V_4;
					return ParseResult.Success;
				case "5":
					settings.Version = LanguageVersion.V_5;
					return ParseResult.Success;
				case "future":
					settings.Version = LanguageVersion.Future;
					return ParseResult.Success;
				}

				report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3', `4', `5', `Default' or `Future'", value);
				return ParseResult.Error;

			case "/codepage":
				if (value.Length == 0) {
					Error_RequiresArgument (option);
					return ParseResult.Error;
				}

				switch (value) {
				case "utf8":
					settings.Encoding = Encoding.UTF8;
					break;
				case "reset":
					settings.Encoding = Encoding.Default;
					break;
				default:
					try {
						settings.Encoding = Encoding.GetEncoding (int.Parse (value));
					} catch {
						report.Error (2016, "Code page `{0}' is invalid or not installed", value);
					}
					return ParseResult.Error;
				}
				return ParseResult.Success;

			default:
				return ParseResult.UnknownOption;
			}
		}
Example #42
0
        public static DynamicContext Create()
        {
            if (dc != null)
            {
                return(dc);
            }

            lock (compiler_initializer) {
                if (dc != null)
                {
                    return(dc);
                }

                var reporter = new Compiler.Report(ErrorPrinter.Instance)
                {
                    WarningLevel = 0
                };

                var settings = new Compiler.CompilerSettings();

                var cc = new Compiler.CompilerContext(settings, reporter)
                {
                    IsRuntimeBinder = true
                };

                //IList<Compiler.PredefinedTypeSpec> core_types = null;
                //// HACK: To avoid re-initializing static TypeManager types, like string_type
                //if (!Compiler.RootContext.EvalMode) {
                //    core_types = Compiler.TypeManager.InitCoreTypes ();
                //}

                //
                // Any later loaded assemblies are handled internally by GetAssemblyDefinition
                // domain.AssemblyLoad cannot be used as that would be too destructive as we
                // would hold all loaded assemblies even if they can be never visited
                //
                // TODO: Remove this code and rely on GetAssemblyDefinition only
                //
                var module = new Compiler.ModuleContainer(cc);
                module.HasTypesFullyDefined = true;
                var temp = new Compiler.AssemblyDefinitionDynamic(module, "dynamic");
                module.SetDeclaringAssembly(temp);

                // Import all currently loaded assemblies
                var domain = AppDomain.CurrentDomain;

                temp.Create(domain, System.Reflection.Emit.AssemblyBuilderAccess.Run);
                var importer = new Compiler.ReflectionImporter(module, cc.BuiltinTypes)
                {
                    IgnorePrivateMembers = false
                };

                foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    importer.ImportAssembly(a, module.GlobalRootNamespace);
                }

                cc.BuiltinTypes.CheckDefinitions(module);
                module.InitializePredefinedTypes();

                dc = new DynamicContext(module, importer);
            }

            return(dc);
        }