public void GivenModulesWithCyclicReferences_WhenIncludeReferencesAndSortModules_ThenExceptionThrown() { var module1 = new Module("~/module1"); var module2 = new Module("~/module2"); module1.AddReferences(new[] { "~/module2" }); module2.AddReferences(new[] { "~/module1" }); var container = new ModuleContainer<Module>(new[] { module1, module2 }); Assert.Throws<InvalidOperationException>(delegate { container.IncludeReferencesAndSortModules(new[] { module2, module1 }); }); }
public Manager() { configuration = LoadConfigurationFromWebConfig(); // Module files will be cached in isolated storage. storage = IsolatedStorageFile.GetUserStoreForDomain(); coffeeScriptCompiler = new CoffeeScriptCompiler(File.ReadAllText); scriptModuleContainer = BuildScriptModuleContainer(storage, configuration); stylesheetModuleContainer = BuildStylesheetModuleContainer(storage, configuration); scriptModuleContainer.UpdateStorage("scripts.xml"); stylesheetModuleContainer.UpdateStorage("stylesheets.xml"); }
public ModuleContainer_facts() { storage = IsolatedStorageFile.GetUserStoreForDomain(); moduleContainer = new ModuleContainer(new[] { new Module( @"scripts/module-a", new Resource[] { new Resource(@"scripts/module-a/test.js", new byte[0], new string[0]) }, new string[0], null ), new Module(@"scripts/module-b", new Resource[0], new string[0], null) }, storage, tw => null); }
static void Main(string[] args) { NLogLogger.Use(); var container = new ModuleContainer(); container.AddModule(new TestModule()); var bootstrapper = new Bootstrapper(); var engine = bootstrapper.BootWith(container); string uri = "http://localhost:3202/"; var host = new SelfHost(engine, new Uri(uri)); host.Start(); Console.WriteLine("Server is listening on [{0}].", uri); //AutoNavigateTo(uri); Console.ReadKey(); Console.WriteLine("Stopped. Goodbye!"); }
public ModuleContainerBuilder_AddModuleForEachSubdirectoryOf() { storage = IsolatedStorageFile.GetUserStoreForAssembly(); rootDirectory = Path.GetFullPath(Guid.NewGuid().ToString()); // Create a fake set of scripts in modules. Directory.CreateDirectory(Path.Combine(rootDirectory, "lib")); File.WriteAllText(Path.Combine(rootDirectory, "lib", "jquery.js"), "function jQuery(){}"); File.WriteAllText(Path.Combine(rootDirectory, "lib", "knockout.js"), "function knockout(){}"); Directory.CreateDirectory(Path.Combine(rootDirectory, "app")); File.WriteAllText(Path.Combine(rootDirectory, "app", "widgets.js"), "/// <reference path=\"../lib/jquery.js\"/>\r\n/// <reference path=\"../lib/knockout.js\"/>\r\nfunction widgets(){}"); File.WriteAllText(Path.Combine(rootDirectory, "app", "main.js"), "/// <reference path=\"widgets.js\"/>\r\nfunction main() {}"); var builder = new ScriptModuleContainerBuilder(storage, rootDirectory, new CoffeeScriptCompiler(File.ReadAllText)); builder.AddModuleForEachSubdirectoryOf("", ""); container = builder.Build(); }
public void GivenDiamondReferencing_ThenConcatDependenciesReturnsEachReferencedModuleOnlyOnceInDependencyOrder() { var module1 = new Module("~/module-1"); var asset1 = new Mock<IAsset>(); SetupAsset("~/module-1/a.js", asset1); asset1.SetupGet(a => a.References) .Returns(new[] { new AssetReference("~/module-2/b.js", asset1.Object, 1, AssetReferenceType.DifferentModule), new AssetReference("~/module-3/c.js", asset1.Object, 1, AssetReferenceType.DifferentModule) }); module1.Assets.Add(asset1.Object); var module2 = new Module("~/module-2"); var asset2 = new Mock<IAsset>(); SetupAsset("~/module-2/b.js", asset2); asset2.SetupGet(a => a.References) .Returns(new[] { new AssetReference("~/module-4/d.js", asset2.Object, 1, AssetReferenceType.DifferentModule) }); module2.Assets.Add(asset2.Object); var module3 = new Module("~/module-3"); var asset3 = new Mock<IAsset>(); SetupAsset("~/module-3/c.js", asset3); asset3.SetupGet(a => a.References) .Returns(new[] { new AssetReference("~/module-4/d.js", asset3.Object, 1, AssetReferenceType.DifferentModule) }); module3.Assets.Add(asset3.Object); var module4 = new Module("~/module-4"); var asset4 = new Mock<IAsset>(); SetupAsset("~/module-4/d.js", asset4); module4.Assets.Add(asset4.Object); var container = new ModuleContainer<Module>(new[] { module1, module2, module3, module4 }); container.IncludeReferencesAndSortModules(new[] { module1, module2, module3, module4 }) .SequenceEqual(new[] { module4, module2, module3, module1 }).ShouldBeTrue(); }
public bool Compile(out AssemblyBuilder assembly, AppDomain domain, bool generateInMemory) { // Get the current settings CompilerSettings settings = context.Settings; // Set the result for quick exit assembly = null; // Check if any source files were supplied if (settings.FirstSourceFile == null && (((MCSTarget)settings.Target == MCSTarget.Exe || (MCSTarget)settings.Target == MCSTarget.WinExe || (MCSTarget)settings.Target == MCSTarget.Module) || settings.Resources == null)) { Report.Error(2008, "No source files specified"); return(false); } // Check for any invalid settings if (settings.Platform == Platform.AnyCPU32Preferred && ((MCSTarget)settings.Target == MCSTarget.Library || (MCSTarget)settings.Target == MCSTarget.Module)) { Report.Error(4023, "The preferred platform '{0}' is only valid on executable outputs", Platform.AnyCPU32Preferred.ToString()); return(false); } // Create the time reporter TimeReporter time = new TimeReporter(settings.Timestamps); context.TimeReporter = time; time.StartTotal(); // Create the module ModuleContainer module = new ModuleContainer(context); RootContext.ToplevelTypes = module; // Start timing the parse stage time.Start(TimeReporter.TimerType.ParseTotal); { // Begin parse Parse(module); } time.Stop(TimeReporter.TimerType.ParseTotal); // Check for any errors if (Report.Errors > 0) { return(false); } // Check for partial compilation if (settings.TokenizeOnly == true || settings.ParseOnly == true) { time.StopTotal(); time.ShowStats(); return(true); } // Get the output file string output = settings.OutputFile; string outputName = Path.GetFileName(output); // Create an assembly defenition AssemblyDefinitionDynamic defenition = new AssemblyDefinitionDynamic(module, outputName, output); module.SetDeclaringAssembly(defenition); ReflectionImporter importer = new ReflectionImporter(module, context.BuiltinTypes); defenition.Importer = importer; DynamicLoader loader = new DynamicLoader(importer, context); loader.LoadReferences(module); // Validate built in types if (context.BuiltinTypes.CheckDefinitions(module) == false) { return(false); } // Create the assmbly in domain if (defenition.Create(domain, AssemblyBuilderAccess.RunAndSave) == false) { return(false); } module.CreateContainer(); loader.LoadModules(defenition, module.GlobalRootNamespace); module.InitializePredefinedTypes(); // Check for any resource strings if (settings.GetResourceStrings != null) { module.LoadGetResourceStrings(settings.GetResourceStrings); } // Time the module defenition time.Start(TimeReporter.TimerType.ModuleDefinitionTotal); { try { // Begin defining module.Define(); } catch { // Failed to define module return(false); } } time.Stop(TimeReporter.TimerType.ModuleDefinitionTotal); // Check for any errors if (Report.Errors > 0) { return(false); } // Check for documentation if (settings.DocumentationFile != null) { // Build the xml docs file DocumentationBuilder docs = new DocumentationBuilder(module); docs.OutputDocComment(output, settings.DocumentationFile); } defenition.Resolve(); // Check for documentation errors if (Report.Errors > 0) { return(false); } // Finally emit the defenition into something useful time.Start(TimeReporter.TimerType.EmitTotal); { // Emit assembly defenition.Emit(); } time.Stop(TimeReporter.TimerType.EmitTotal); // Check for any emit errors if (Report.Errors > 0) { return(false); } // Module cleanup time.Start(TimeReporter.TimerType.CloseTypes); { module.CloseContainer(); } time.Stop(TimeReporter.TimerType.CloseTypes); // Check for embedded resources time.Start(TimeReporter.TimerType.Resouces); { if (settings.WriteMetadataOnly == false) { defenition.EmbedResources(); } } time.Stop(TimeReporter.TimerType.Resouces); // Embedd errors if (Report.Errors > 0) { return(false); } // Check for generate in memory if (generateInMemory == false) { defenition.Save(); } // Store the result assembly = defenition.Builder; time.StopTotal(); time.ShowStats(); // Check for errors return(Report.Errors == 0); }
public ReferenceBuilder(ModuleContainer moduleContainer) { this.moduleContainer = moduleContainer; }
public Assembly DoStaticCompile(IEnumerable <object> sources, string prefix = "compiled_") { reporter.Reset(); Location.Reset(); var ctx = BuildContext(reporter); ctx.Settings.SourceFiles.Clear(); int i = 0; var allBytes = new MemoryStream(); List <Assembly> imports = new List <Assembly>(); foreach (var fo in sources) { Assembly impass = fo as Assembly; if (impass != null) { imports.Add(impass); continue; } var f = fo as string; byte[] fbuf = fo as byte[]; if (f != null) { if (!f.EndsWith(".cs")) { continue; } var bname = (f + "\n").ToBytes(); allBytes.Write(bname, 0, bname.Length); fbuf = File.ReadAllBytes(f); allBytes.Write(fbuf, 0, fbuf.Length); } else { allBytes.Write(fbuf, 0, fbuf.Length); f = null; } i++; ctx.Settings.SourceFiles.Add(new SourceFile(f == null ? "<eval>" : Path.GetFileName(f), f ?? "<eval>", i, (o) => { return(new SeekableStreamReader(new MemoryStream(fbuf), Encoding.UTF8)); })); } string dllname = prefix + (counter++) + ".dll"; if (tempdir != null) { if (hashkey != null) { var hb = hashkey.ToBytes(); allBytes.Write(hb, 0, hb.Length); } var hash = prefix + Ext.HashToString(allBytes.ToArray()).Substring(0, 12).ToLower() + ".dll"; if (hashkey == null) { hashkey = hash; } dllname = Path.Combine(tempdir, hash); if (File.Exists(dllname)) { var nam = AssemblyName.GetAssemblyName(dllname); unloaded.Remove(nam.Name.ToLower()); return(Assembly.Load(nam)); } } var mod = new ModuleContainer(ctx); RootContext.ToplevelTypes = mod; Location.Initialize(ctx.Settings.SourceFiles); var session = new ParserSession() { UseJayGlobalArrays = true, LocatedTokens = new LocatedToken[15000] }; mod.EnableRedefinition(); foreach (var finfo in ctx.Settings.SourceFiles) { var fs = finfo.GetInputStream(finfo); var csrc = new CompilationSourceFile(mod, finfo); csrc.EnableRedefinition(); mod.AddTypeContainer(csrc); var parser = new CSharpParser(fs, csrc, session); parser.parse(); } Debug.Log("Defining new assembly " + dllname); var ass = new AssemblyDefinitionDynamic(mod, Path.GetFileNameWithoutExtension(dllname), dllname); mod.SetDeclaringAssembly(ass); var importer = new ReflectionImporter(mod, ctx.BuiltinTypes); ass.Importer = importer; var loader = new DynamicLoader(importer, ctx); ImportAssemblies((a) => importer.ImportAssembly(a, mod.GlobalRootNamespace), prefix); foreach (var impa in imports) { importer.ImportAssembly(impa, mod.GlobalRootNamespace); } loader.LoadReferences(mod); ass.Create(AppDomain.CurrentDomain, AssemblyBuilderAccess.RunAndSave); mod.CreateContainer(); loader.LoadModules(ass, mod.GlobalRootNamespace); mod.InitializePredefinedTypes(); mod.Define(); if (ctx.Report.Errors > 0) { tw.WriteLine($"{ctx.Report.Errors} errors, aborting."); return(null); } try { ass.Resolve(); ass.Emit(); mod.CloseContainer(); ass.EmbedResources(); } catch (Exception ex) { tw.WriteLine($"Link error: " + ex.ToString()); return(null); } if (tempdir != null) { ass.Save(); } return(ass.Builder); }
void ProcessModuleRequest(HttpContextBase context, ModuleContainer container, string contentType) { var module = FindModule(context.Request, container); if (module == null) { NotFound(context); return; } var serverETag = module.Hash.ToHexString(); if (ClientHasCurrentVersion(context.Request, serverETag)) { NotModified(context); } else { context.Response.StatusCode = 200; context.Response.ContentType = contentType; SetLongLivedCacheHeaders(context.Response.Cache, serverETag); // NOTE: If people want compression then tell IIS to do it using config! WriteModuleContentToResponse(module, container, context.Response); } }
Module FindModule(HttpRequestBase request, ModuleContainer container) { var modulePath = GetModulePath(request); var module = container.FindModule(modulePath); return module; }
public static TypeSpec MakeType (ModuleContainer module, TypeSpec underlyingType) { return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module, new[] { underlyingType }); }
public static void GenerateDynamicPartialClasses(ModuleContainer module, ParserSession session, Report report) { List <Class> classes = new List <Class>(); FindDynamicClasses(module, classes); if (classes.Count == 0) { return; } var os = new StringWriter(); os.Write(@" // Generated dynamic class partial classes "); foreach (var cl in classes) { os.Write(@" namespace {1} {{ partial class {2} : PlayScript.IDynamicClass {{ private PlayScript.IDynamicClass __dynamicProps; dynamic PlayScript.IDynamicClass.__GetDynamicValue(string name) {{ object value = null; if (__dynamicProps != null) {{ value = __dynamicProps.__GetDynamicValue(name); }} return value; }} bool PlayScript.IDynamicClass.__TryGetDynamicValue(string name, out object value) {{ if (__dynamicProps != null) {{ return __dynamicProps.__TryGetDynamicValue(name, out value); }} else {{ value = PlayScript.Undefined._undefined; return false; }} }} void PlayScript.IDynamicClass.__SetDynamicValue(string name, object value) {{ if (__dynamicProps == null) {{ __dynamicProps = new PlayScript.DynamicProperties(this); }} __dynamicProps.__SetDynamicValue(name, value); }} bool PlayScript.IDynamicClass.__DeleteDynamicValue(object name) {{ if (__dynamicProps != null) {{ return __dynamicProps.__DeleteDynamicValue(name); }} return false; }} bool PlayScript.IDynamicClass.__HasDynamicValue(string name) {{ if (__dynamicProps != null) {{ return __dynamicProps.__HasDynamicValue(name); }} return false; }} System.Collections.IEnumerable PlayScript.IDynamicClass.__GetDynamicNames() {{ if (__dynamicProps != null) {{ return __dynamicProps.__GetDynamicNames(); }} return null; }} }} }} ", PsConsts.PsRootNamespace, ((ITypeDefinition)cl).Namespace, cl.MemberName.Basename); } string fileStr = os.ToString(); var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(module.Compiler.Settings.OutputFile)), "dynamic.g.cs"); System.IO.File.WriteAllText(path, fileStr); byte[] byteArray = Encoding.ASCII.GetBytes(fileStr); var input = new MemoryStream(byteArray, false); var reader = new SeekableStreamReader(input, System.Text.Encoding.UTF8); SourceFile file = new SourceFile(path, path, 0); file.FileType = SourceFileType.CSharp; Driver.Parse(reader, file, module, session, report); }
public void SortModulesToleratesExternalModulesWhichAreNotInTheContainer() { var externalModule1 = new ExternalScriptModule("http://test.com/test1.js"); var externalModule2 = new ExternalScriptModule("http://test.com/test2.js"); var container = new ModuleContainer<ScriptModule>(Enumerable.Empty<ScriptModule>()); var results = container.IncludeReferencesAndSortModules(new[] { externalModule1, externalModule2 }); results.SequenceEqual(new[] { externalModule1, externalModule2 }).ShouldBeTrue(); }
public void FindModuleContainingPathOfAssetReturnsTheModule() { var expectedModule = new Module("~/test"); var asset = new Mock<IAsset>(); asset.Setup(a => a.Accept(It.IsAny<IAssetVisitor>())) .Callback<IAssetVisitor>(v => v.Visit(asset.Object)); asset.SetupGet(a => a.SourceFilename).Returns("~/test/test.js"); expectedModule.Assets.Add(asset.Object); var container = new ModuleContainer<Module>(new[] { expectedModule }); var actualModule = container.FindModuleContainingPath("~/test/test.js"); actualModule.ShouldBeSameAs(expectedModule); }
public void GivenModuleWithReferenceToAnotherModule_ModulesAreSortedInDependencyOrder() { var module1 = new Module("~/module1"); var module2 = new Module("~/module2"); module1.AddReferences(new[] { "~/module2" }); var container = new ModuleContainer<Module>(new[] { module1, module2 }); var sorted = container.IncludeReferencesAndSortModules(new[] { module1, module2 }); sorted.SequenceEqual(new[] { module2, module1 }).ShouldBeTrue(); }
public void ImplicitReferenceOrderingMustNotIntroduceCycles() { var ms = Enumerable.Range(0, 5).Select(i => new Module("~/" + i)).ToArray(); ms[1].AddReferences(new[] { "~/4" }); ms[4].AddReferences(new[] { "~/3" }); var container = new ModuleContainer<Module>(ms); var sorted = container.IncludeReferencesAndSortModules(ms).ToArray(); sorted[0].ShouldBeSameAs(ms[0]); sorted[1].ShouldBeSameAs(ms[2]); sorted[2].ShouldBeSameAs(ms[3]); sorted[3].ShouldBeSameAs(ms[4]); sorted[4].ShouldBeSameAs(ms[1]); }
private static void Main(string[] args) { //Window set up. Window = new RenderWindow(new VideoMode(550, 104), "Smus", Styles.None); Window.SetFramerateLimit(61); Window.GainedFocus += (o, e) => { WindowFocused = true; }; Window.LostFocus += (o, e) => { WindowFocused = false; }; Window.MouseButtonPressed += (o, e) => { //Hack to fix window focus. if (!WindowFocused) { Window.Position += new Vector2i(0, 0); } }; //Make sure the window can close properly. Window.Closed += (o, e) => Window.Close(); Window.Closed += (o, e) => { if (Audio.Engine != null) { Audio.Engine.Dispose(); } }; Window.Closed += (o, e) => IsRunning = false; //Get bin directory. var ass = Assembly.GetExecutingAssembly(); AssPath = Path.GetDirectoryName(ass.Location); //Initialize Audio Audio.StartEngine(); //Config Config.PopulateConfig(AssPath + "/Resources/Config/config.xml"); //SpriteBatch/Atlas AtlasData = new AtlasData(AssPath + "/Resources/Textures/Atlas"); SpriteBatch = new SpriteBatch(AtlasData.AtlasTexture); //Container var moduleContainer = new ModuleContainer(); //Modules LoadModules(moduleContainer); //Update SpriteBatch SpriteBatch.SortZ(); SpriteBatch.CalculateVertices(); //Main loop while (IsRunning) { Window.DispatchEvents(); if (!WindowFocused) { Thread.Sleep(200); //Doesn't need to run as smooth. } Window.Clear(Config.Colors["background"]); if ((Keyboard.IsKeyPressed(Keyboard.Key.LAlt) || Keyboard.IsKeyPressed(Keyboard.Key.RAlt)) && Keyboard.IsKeyPressed(Keyboard.Key.F4)) { IsRunning = false; } moduleContainer.Update(); Window.Display(); } Audio.Engine.Dispose(); Window.Close(); }
public async Task RemoveModule(ModuleContainer container) { await CurrentPage.RemoveModule(container); Mediator.Send(new RemoveModuleMessage(container.Module)); }
public void Setup() { this.moduleContainer = new ModuleContainer(containerCapacity); }
public JsEmitContext(ModuleContainer module) { Module = module; Buf = new JsEmitBuffer(); Buf.EmitContext = this; }
public void FindModuleContainingPathOfModuleReturnsTheModule() { var expectedModule = new Module("~/test"); var container = new ModuleContainer<Module>(new[] { expectedModule }); var actualModule = container.FindModuleContainingPath("~/test"); actualModule.ShouldBeSameAs(expectedModule); }
public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum) { return MakeType (module, EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum))); }
public void FindModuleContainingPathWithWrongPathReturnsNull() { var container = new ModuleContainer<Module>(new[] { new Module("~/test") }); var actualModule = container.FindModuleContainingPath("~/WRONG"); actualModule.ShouldBeNull(); }
private static void FindEmbedFields(ModuleContainer module, ClassOrStruct cl, List <EmbedData> embeds) { foreach (var m in cl.Members) { var f = m as Field; if (f == null || f.OptAttributes == null || f.OptAttributes.Attrs.Count == 0) { continue; } if (!(f.TypeExpression is TypeExpression) || f.TypeExpression.Type != module.Compiler.BuiltinTypes.Type) { continue; } Mono.CSharp.Attribute embedAttr = null; foreach (var attr in f.OptAttributes.Attrs) { if (attr.Name == "Embed") { embedAttr = attr; break; } } if (embedAttr == null) { continue; } var e = new EmbedData(); e._index = _embedCount; _embedCount++; e._className = "__EmbedLoader" + e._index; e._field = f; e.source = e.mimeType = e.embedAsCFF = e.fontFamily = e.symbol = "null"; foreach (NamedArgument arg in embedAttr.NamedArguments) { if (!(arg.Expr is StringLiteral)) { continue; } var s = ((StringLiteral)(arg.Expr)).GetValueAsLiteral(); switch (arg.Name) { case "source": e.source = s; break; case "mimeType": e.mimeType = s; break; case "embedAsCFF": e.embedAsCFF = s; break; case "fontFamily": e.fontFamily = s; break; case "symbol": e.symbol = s; break; } } embeds.Add(e); } }
public AbstractModuleLayer() { mContainer = new ModuleContainer(new DefaultModuleCache(), mFactory); }
public VSProject(ModuleContainer module) { this.module = module; }
public ModuleContainerBuilder_Build_when_already_cached_in_storage() { storage = IsolatedStorageFile.GetUserStoreForAssembly(); rootDirectory = Path.GetFullPath(Guid.NewGuid().ToString()); // Create a fake set of scripts in modules. Directory.CreateDirectory(Path.Combine(rootDirectory, "junk")); File.WriteAllText(Path.Combine(rootDirectory, "junk", "test.js"), "function junk(){}"); Directory.CreateDirectory(Path.Combine(rootDirectory, "lib")); File.WriteAllText(Path.Combine(rootDirectory, "lib", "jquery.js"), "function jQuery(){}"); Directory.CreateDirectory(Path.Combine(rootDirectory, "app")); File.WriteAllText(Path.Combine(rootDirectory, "app", "widgets.js"), "/// <reference path=\"../lib/jquery.js\"/>\r\nfunction widgets(){}"); File.WriteAllText(Path.Combine(rootDirectory, "app", "main.js"), "/// <reference path=\"widgets.js\"/>\r\nfunction main() {}"); // Create the "old" continer. var builder = new ScriptModuleContainerBuilder(storage, rootDirectory, new CoffeeScriptCompiler(File.ReadAllText)); builder.AddModule("lib", null); builder.AddModule("app", null); builder.AddModule("junk", null); var oldContainer = builder.Build(); oldContainer.UpdateStorage("scripts.xml"); // Now simulate changes to the modules. File.WriteAllText(Path.Combine(rootDirectory, "lib", "knockout.js"), "function knockout(){}"); File.WriteAllText(Path.Combine(rootDirectory, "app", "widgets.js"), "/// <reference path=\"../lib/jquery.js\"/>\r\n/// <reference path=\"../lib/knockout.js\"/>\r\nfunction widgets(){}"); // Build the updated container to excerise container manifest loading and differencing. builder = new ScriptModuleContainerBuilder(storage, rootDirectory, new CoffeeScriptCompiler(File.ReadAllText)); builder.AddModule("lib", null); builder.AddModule("app", null); container = builder.Build(); container.UpdateStorage("scripts.xml"); }
void WriteModuleContentToResponse(Module module, ModuleContainer moduleContainer, HttpResponseBase response) { using (var stream = moduleContainer.OpenModuleFile(module)) { stream.CopyTo(response.OutputStream); } }
public void GivenModulesWithNoDependenciesAreReferencedInNonAlphaOrder_WhenIncludeReferencesAndSortModules_ThenReferenceOrderIsMaintained() { var module1 = new Module("~/module1"); var module2 = new Module("~/module2"); var container = new ModuleContainer<Module>(new[] { module1, module2 }); var sorted = container.IncludeReferencesAndSortModules(new[] { module2, module1 }); sorted.SequenceEqual(new[] { module2, module1 }).ShouldBeTrue(); }
public JsEmitContext(ModuleContainer module) { Module = module; Buf = new JsEmitBuffer(); Buf.EmitContext = this; }
public AssemblyDefinitionDynamicMonoScript(ModuleContainer module, string name, string fileName) : base(module, name, fileName) { }
// // Main compilation method // public bool Compile(out AssemblyBuilder outAssembly, AppDomain domain, bool generateInMemory) { var settings = ctx.Settings; outAssembly = null; // // 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; * } * }*/ 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(domain, AssemblyBuilderAccess.RunAndSave)) { return(false); } module.CreateContainer(); loader.LoadModules(assembly, module.GlobalRootNamespace); module.InitializePredefinedTypes(); if (settings.GetResourceStrings != null) { module.LoadGetResourceStrings(settings.GetResourceStrings); } 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); } if (!generateInMemory) { assembly.Save(); } outAssembly = assembly.Builder; tr.StopTotal(); tr.ShowStats(); return(Report.Errors == 0); }
static void Main(string[] args) { var pipelines = new Pipelines(); Metric.Config //.WithAllCounters() // optional -- enable both System and App counters //.WithSystemCounters() // optional -- enable System counters //.WithAppCounters() // optional -- enable App counters //.WithReporting(r => r.WithConsoleReport(TimeSpan.FromSeconds(30))) // optional -- display to console //.WithReporting(r => r.WithCSVReports(@"C:\metrics\csv", TimeSpan.FromSeconds(30))) //.WithReporting(r => r.WithTextFileReport(@"C:\metrics\text\metrics.txt", TimeSpan.FromSeconds(30))) //.WithHttpEndpoint("http://localhost:3201/metrics/") // optional -- listen http port .WithHapper(pipelines); var container = new ModuleContainer(); // http://localhost:3202/ // http://localhost:3202/ping // http://localhost:3202/hello // http://localhost:3202/text // http://localhost:3202/time container.AddModule(new SimpleModule()); // http://localhost:3202/thread // http://localhost:3202/sleep container.AddModule(new ThreadModule()); // http://localhost:3202/plaintext container.AddModule(new PlainModule()); // http://localhost:3202/metrics // http://localhost:3202/metrics/ping // http://localhost:3202/metrics/text // http://localhost:3202/metrics/health // http://localhost:3202/metrics/json // http://localhost:3202/metrics/v1/health // http://localhost:3202/metrics/v1/json // http://localhost:3202/metrics/v2/json container.AddModule(new MetricsModule()); var bootstrapper = new Bootstrapper(); var engine = bootstrapper.BootWith(container, pipelines); // enable "Transfer-Encoding" = "chunked" instead of "Content-Length". //engine.ConfigureChunkedTransferEncoding(false); // enable "Content-Encoding" = "gzip" if "Accept-Encoding" requested. //engine.ConfigureResponseCompressionEnabled(); var uri = "http://localhost:3202/"; var host = new SelfHost(engine, new Uri(uri)); host.Start(); _log.WarnFormat("Server is listening on [{0}].", uri); while (true) { string input = Console.ReadLine().ToLowerInvariant(); if (input == "exit" || input == "quit" || input == "stop") { break; } else if (input == "restart") { _log.WarnFormat("Server is restarting."); host.Stop(); _log.WarnFormat("Server is stopped."); host.Start(); _log.WarnFormat("Server is listening on [{0}].", uri); } } host.Stop(); _log.WarnFormat("Server is stopped."); Console.ReadKey(); }
public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum) { return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module, new[] { EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum)) }); }
public void SetUp() { this.moduleContainer = new ModuleContainer(Capacity); }