Exemple #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);
        }
Exemple #2
0
        public DynamicLoader(ReflectionImporter importer, CompilerContext compiler)
            : base(compiler)
        {
            paths.Add(GetSystemDir());

            this.importer = importer;
        }
Exemple #3
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> > ();
        }
Exemple #4
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>> ();
		}
        /// <summary>
        ///   Optional initialization for the Evaluator.
        /// </summary>
        /// <remarks>
        ///  Initializes the Evaluator with the command line
        ///  options that would be processed by the command
        ///  line compiler.  Only the first call to
        ///  InitAndGetStartupFiles or Init will work, any future
        ///  invocations are ignored.
        ///
        ///  You can safely avoid calling this method if your application
        ///  does not need any of the features exposed by the command line
        ///  interface.
        ///
        ///  This method return an array of strings that contains any
        ///  files that were specified in `args'.
        ///
        ///  If the unknownOptionParser is not null, this function is invoked
        ///  with the current args array and the index of the option that is not
        ///  known.  A value of true means that the value was processed, otherwise
        ///  it will be reported as an error
        /// </remarks>
        public static string [] InitAndGetStartupFiles(string [] args, Func <string [], int, int> unknownOptionParser)
        {
            lock (evaluator_lock)
            {
                if (inited)
                {
                    return(new string [0]);
                }

                CompilerCallableEntryPoint.Reset();
                var crp = new ConsoleReportPrinter();
                driver = Driver.Create(args, false, unknownOptionParser, crp);
                if (driver == null)
                {
                    throw new Exception("Failed to create compiler driver with the given arguments");
                }

                crp.Fatal = driver.fatal_errors;
                ctx       = driver.ctx;

                RootContext.ToplevelTypes = new ModuleContainer(ctx);

                var startup_files = new List <string> ();
                foreach (CompilationUnit file in Location.SourceFiles)
                {
                    startup_files.Add(file.Path);
                }

                CompilerCallableEntryPoint.PartialReset();

                var importer = new ReflectionImporter(ctx.BuildinTypes);
                loader = new DynamicLoader(importer, ctx);

                RootContext.ToplevelTypes.SetDeclaringAssembly(new AssemblyDefinitionDynamic(RootContext.ToplevelTypes, "temp"));

                loader.LoadReferences(RootContext.ToplevelTypes);
                ctx.BuildinTypes.CheckDefinitions(RootContext.ToplevelTypes);
                RootContext.ToplevelTypes.InitializePredefinedTypes();

                RootContext.EvalMode = true;
                inited = true;

                return(startup_files.ToArray());
            }
        }
Exemple #6
0
        public Evaluator(CompilerContext ctx)
        {
            this.ctx = ctx;

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

            source_file = new CompilationSourceFile(module, null);
            module.AddTypeContainer(source_file);

            startup_files = ctx.SourceFiles.Count;

            // 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> > ();
        }
Exemple #7
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>> ();
		}
Exemple #8
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> > ();
        }
Exemple #9
0
        //
        // 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);
            }

            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 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.CreateType();
            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.CreateType();

            loader.LoadModules(assembly, module.GlobalRootNamespace);
#endif
            module.InitializePredefinedTypes();

            tr.Start(TimeReporter.TimerType.UsingResolve);
            foreach (var source_file in ctx.SourceFiles)
            {
                source_file.NamespaceContainer.Resolve();
            }
            tr.Stop(TimeReporter.TimerType.UsingResolve);

            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.CloseType();
            tr.Stop(TimeReporter.TimerType.CloseTypes);

            tr.Start(TimeReporter.TimerType.Resouces);
            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);
        }
Exemple #10
0
		/// <summary>
		///   Optional initialization for the Evaluator.
		/// </summary>
		/// <remarks>
		///  Initializes the Evaluator with the command line
		///  options that would be processed by the command
		///  line compiler.  Only the first call to
		///  InitAndGetStartupFiles or Init will work, any future
		///  invocations are ignored.
		///
		///  You can safely avoid calling this method if your application
		///  does not need any of the features exposed by the command line
		///  interface.
		///
		///  This method return an array of strings that contains any
		///  files that were specified in `args'.
		///
		///  If the unknownOptionParser is not null, this function is invoked
		///  with the current args array and the index of the option that is not
		///  known.  A value of true means that the value was processed, otherwise
		///  it will be reported as an error
		/// </remarks>
		public static string [] InitAndGetStartupFiles (string [] args, Func<string [], int, int> unknownOptionParser)
		{
			lock (evaluator_lock){
				if (inited)
					return new string [0];

				CompilerCallableEntryPoint.Reset ();
				var crp = new ConsoleReportPrinter ();
				driver = Driver.Create (args, false, unknownOptionParser, crp);
				if (driver == null)
					throw new Exception ("Failed to create compiler driver with the given arguments");

				crp.Fatal = driver.fatal_errors;
				ctx = driver.ctx;

				RootContext.ToplevelTypes = new ModuleContainer (ctx);
				
				var startup_files = new List<string> ();
				foreach (CompilationUnit file in Location.SourceFiles)
					startup_files.Add (file.Path);
				
				CompilerCallableEntryPoint.PartialReset ();

				var importer = new ReflectionImporter (ctx.BuildinTypes);
				loader = new DynamicLoader (importer, ctx);

				RootContext.ToplevelTypes.SetDeclaringAssembly (new AssemblyDefinitionDynamic (RootContext.ToplevelTypes, "temp"));

				loader.LoadReferences (RootContext.ToplevelTypes);
				ctx.BuildinTypes.CheckDefinitions (RootContext.ToplevelTypes);
				RootContext.ToplevelTypes.InitializePredefinedTypes ();

				RootContext.EvalMode = true;
				inited = true;

				return startup_files.ToArray ();
			}
		}
Exemple #11
0
		//
		// 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;
		}
 private DynamicContext(Compiler.ModuleContainer module, Compiler.ReflectionImporter importer)
 {
     this.module   = module;
     this.importer = importer;
 }
        //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 (Location.FirstFile == 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;
            }

            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)
                return true;

            if (RootContext.ToplevelTypes.NamespaceEntry != null)
                throw new InternalErrorException ("who set it?");

            var output_file = settings.OutputFile;
            string output_file_name;
            if (output_file == null) {
                output_file_name = Location.FirstFile;

                if (output_file_name == null) {
                    Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
                    return false;
                }

                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 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.CreateType ();
            importer.AddCompiledAssembly (assembly);
            tr.Stop (TimeReporter.TimerType.CreateTypeTotal);

            references_loader.LoadReferences (module);

            tr.Start (TimeReporter.TimerType.PredefinedTypesInit);
            if (!ctx.BuildinTypes.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.BuildinTypes);
            assembly.Importer = importer;

            var loader = new DynamicLoader (importer, ctx);
            loader.LoadReferences (module);

            if (!ctx.BuildinTypes.CheckDefinitions (module))
                return false;

            if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Run))
                return false;

            module.CreateType ();

            loader.LoadModules (assembly, module.GlobalRootNamespace);
            #endif
            tr.Start (TimeReporter.TimerType.ModuleDefinitionTotal);
            module.Define ();
            tr.Stop (TimeReporter.TimerType.ModuleDefinitionTotal);

            if (Report.Errors > 0)
                return false;

            //if (settings.Documentation != null &&
            //    !settings.Documentation.OutputDocComment (
            //        output_file, Report))
            //    return false;

            //
            // Verify using aliases now
            //
            tr.Start (TimeReporter.TimerType.UsingVerification);
            NamespaceEntry.VerifyAllUsing ();
            tr.Stop (TimeReporter.TimerType.UsingVerification);

            if (Report.Errors > 0){
                return false;
            }

            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.CloseType ();
            tr.Stop (TimeReporter.TimerType.CloseTypes);

            tr.Start (TimeReporter.TimerType.Resouces);
            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;
        }
Exemple #14
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
				};

				// 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;
		}
Exemple #15
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 cc = new Compiler.CompilerContext (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);
				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 (cc.BuildinTypes) {
					IgnorePrivateMembers = false
				};

				Compiler.RootContext.ToplevelTypes = module;

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

				if (!Compiler.RootContext.EvalMode) {
					cc.BuildinTypes.CheckDefinitions (module);
					module.InitializePredefinedTypes ();
				}

				dc = new DynamicContext (module, importer);
			}

			return dc;
		}
Exemple #16
0
		//
		// Main compilation method
		//
		public bool Compile ()
		{
			var module = new ModuleContainer (ctx);
			RootContext.ToplevelTypes = module;

			if (timestamps) {
				stopwatch = Stopwatch.StartNew ();
				first_time = DateTime.Now;
			}

			Parse (module);
			ShowTime ("Parsing source files");

			if (Report.Errors > 0)
				return false;

			if (tokenize || parse_only)
				return true;

			if (RootContext.ToplevelTypes.NamespaceEntry != null)
				throw new InternalErrorException ("who set it?");

			//
			// Quick hack
			//
			if (output_file == null){
				if (first_source == null){
					Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
					return false;
				}
					
				int pos = first_source.LastIndexOf ('.');

				if (pos > 0)
					output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
				else
					output_file = first_source + RootContext.TargetExt;
			}

			//
			// Load assemblies required
			//
			if (timestamps)
				stopwatch = Stopwatch.StartNew ();

			var assembly = module.MakeExecutable (output_file, output_file);

			var importer = new ReflectionImporter (ctx.BuildinTypes);
			assembly.Importer = importer;

			var loader = new DynamicLoader (importer, ctx);
			loader.LoadReferences (module);

			ShowTime ("Imporing referenced assemblies");

			if (!ctx.BuildinTypes.CheckDefinitions (module))
				return false;

			ShowTime ("Initializing predefined types");

			if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
				return false;

			loader.LoadModules (assembly);

			module.Define ();

			ShowTime ("Types definition");

			if (Report.Errors > 0)
				return false;

			if (Report.Errors == 0 &&
				RootContext.Documentation != null &&
				!RootContext.Documentation.OutputDocComment (
					output_file, Report))
				return false;

			//
			// Verify using aliases now
			//
			NamespaceEntry.VerifyAllUsing ();
			
			if (Report.Errors > 0){
				return false;
			}

			assembly.Resolve ();
			
			if (Report.Errors > 0)
				return false;
			
			//
			// The code generator
			//
			if (timestamps)
				stopwatch = Stopwatch.StartNew ();

			assembly.Emit ();

			ShowTime ("Resolving and emitting members blocks");

			if (Report.Errors > 0){
				return false;
			}

			module.CloseType ();

			ShowTime ("Closing types");

			if (timestamps)
				stopwatch = Stopwatch.StartNew ();

			assembly.EmbedResources ();
			ShowTime ("Embedding resources");

			if (Report.Errors > 0)
				return false;

			if (timestamps)
				stopwatch = Stopwatch.StartNew ();
			
			assembly.Save ();

			ShowTime ("Saving output assembly");

			if (RootContext.GenerateDebugInfo) {
				SymbolWriter.WriteSymbolFile ();
				ShowTime ("Saving debug symbols");
			}

			ShowTotalTime ("Total");

			Timer.ShowTimers ();

			return (Report.Errors == 0);
		}
Exemple #17
0
        private bool PrepareCompiler([NotNull] ModuleContainer container, out ExplicitDynamicAsseblyDefinition assemblyDefinitionDynamic)
        {
            assemblyDefinitionDynamic = new ExplicitDynamicAsseblyDefinition(container, ModuleName, _builder, _path);
            container.SetDeclaringAssembly(assemblyDefinitionDynamic);

            var importer = new ReflectionImporter(container, container.Compiler.BuiltinTypes);
            assemblyDefinitionDynamic.Importer = importer;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) importer.ImportAssembly(assembly, container.GlobalRootNamespace);

            return container.Compiler.BuiltinTypes.CheckDefinitions(container);
        }
Exemple #18
0
		//
		// Main compilation method
		//
		public bool Compile ()
		{
			var module = new ModuleContainer (ctx);
			RootContext.ToplevelTypes = module;

			if (timestamps) {
				stopwatch = Stopwatch.StartNew ();
				first_time = DateTime.Now;
			}

			Parse (module);
			ShowTime ("Parsing source files");

			if (Report.Errors > 0)
				return false;

			if (RootContext.TokenizeOnly || RootContext.ParseOnly)
				return true;

			if (RootContext.ToplevelTypes.NamespaceEntry != null)
				throw new InternalErrorException ("who set it?");

			//
			// Quick hack
			//
			var output_file = RootContext.OutputFile;
			string output_file_name;
			if (output_file == null) {
				if (first_source == null) {
					Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
					return false;
				}

				int pos = first_source.LastIndexOf ('.');

				if (pos > 0)
					output_file = first_source.Substring (0, pos) + RootContext.TargetExt;
				else
					output_file = first_source + RootContext.TargetExt;

				output_file_name = output_file;
			} else {
				output_file_name = Path.GetFileName (output_file);
			}

			//
			// Load assemblies required
			//
			if (timestamps)
				stopwatch = Stopwatch.StartNew ();

#if STATIC
			var assembly = new AssemblyDefinitionStatic (module, output_file_name, output_file);
			module.SetDeclaringAssembly (assembly);

			var importer = new StaticImporter ();
			assembly.Importer = importer;

			var loader = new StaticLoader (importer, ctx);
			loader.LoadReferences (module);

			ShowTime ("Imporing referenced assemblies");

			if (!ctx.BuildinTypes.CheckDefinitions (module))
				return false;

			ShowTime ("Initializing predefined types");

			if (!assembly.Create (loader))
				return false;

			// System.Object was not loaded, use compiled assembly as corlib
			if (loader.Corlib == null)
				loader.Corlib = assembly.Builder;

			loader.LoadModules (assembly, module.GlobalRootNamespace);
#else
			var assembly = new AssemblyDefinitionDynamic (module, output_file_name, output_file);
			module.SetDeclaringAssembly (assembly);

			var importer = new ReflectionImporter (ctx.BuildinTypes);
			assembly.Importer = importer;

			var loader = new DynamicLoader (importer, ctx);
			loader.LoadReferences (module);

			ShowTime ("Imporing referenced assemblies");

			if (!ctx.BuildinTypes.CheckDefinitions (module))
				return false;

			ShowTime ("Initializing predefined types");

			if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
				return false;

			loader.LoadModules (assembly, module.GlobalRootNamespace);
#endif
			module.Define ();

			ShowTime ("Types definition");

			if (Report.Errors > 0)
				return false;

			if (Report.Errors == 0 &&
				RootContext.Documentation != null &&
				!RootContext.Documentation.OutputDocComment (
					output_file, Report))
				return false;

			//
			// Verify using aliases now
			//
			NamespaceEntry.VerifyAllUsing ();
			
			if (Report.Errors > 0){
				return false;
			}

			assembly.Resolve ();
			
			if (Report.Errors > 0)
				return false;
			
			//
			// The code generator
			//
			if (timestamps)
				stopwatch = Stopwatch.StartNew ();

			assembly.Emit ();

			ShowTime ("Resolving and emitting members blocks");

			if (Report.Errors > 0){
				return false;
			}

			module.CloseType ();

			ShowTime ("Closing types");

			if (timestamps)
				stopwatch = Stopwatch.StartNew ();

			assembly.EmbedResources ();
			ShowTime ("Embedding resources");

			if (Report.Errors > 0)
				return false;

			if (timestamps)
				stopwatch = Stopwatch.StartNew ();
			
			assembly.Save ();

#if STATIC
			loader.Dispose ();
#endif

			ShowTime ("Saving output assembly");

			ShowTotalTime ("Total");

			Timer.ShowTimers ();

			return (Report.Errors == 0);
		}
Exemple #19
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);
        }
Exemple #20
0
		public Evaluator (CompilerContext ctx)
		{
			this.ctx = ctx;

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

			source_file = new CompilationSourceFile (module);
			module.AddTypeContainer (source_file);

			startup_files = ctx.SourceFiles.Count;

			// 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>> ();
		}
Exemple #21
0
		private DynamicContext (Compiler.ModuleContainer module, Compiler.ReflectionImporter importer)
		{
			this.module = module;
			this.importer = importer;
		}
Exemple #22
0
		public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
		{
			this.importer = importer;
			this.reporter = compiler.Report;

			default_references = GetDefaultReferences ();

			paths = new List<string> ();
			paths.AddRange (RootContext.ReferencesLookupPaths);
			paths.Add (GetSystemDir ());
			paths.Add (Directory.GetCurrentDirectory ());
		}