public Task SetPileAsSource(IPile pile, CompilerConfiguration compilerManager) { if (pile == null) { throw new ArgumentNullException("pile"); } if (compilerManager == null) { throw new ArgumentNullException("compilerManager"); } if(_pile != null) { throw new InvalidOperationException("Cannot change the pile once set - use another Source Manager!"); } _compilerManager = compilerManager; _pile = pile; // Make sure compilation global directory exists foreach (var innerPile in _pile.FindAllPiles()) { var dirPath = Path.Combine(_compilationDirectory.FullName, innerPile); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } } if (_pile.IsWatchingFiles) { _pile.FileCreated += PileOnFileUpdated; _pile.FileDeleted += PileOnFileUpdated; _pile.FileUpdated += PileOnFileUpdated; } return CompileAndSetupWatchers(); }
public string Render <TModel>(CompilerConfiguration configuration, FilePath templatePath, TModel model) where TModel : TemplateViewModel { lock (_lock) { var templateName = templatePath.FullPath; if (!_engine.IsTemplateCached(templateName, typeof(TModel))) { templatePath = configuration.Root.CombineWithFilePath(templatePath); // Make sure the template exist. if (!_fileSystem.Exist(templatePath)) { const string format = "The template '{0}' do not exist."; var message = string.Format(format, templatePath.FullPath); throw new InvalidOperationException(message); } using (var stream = _fileSystem.GetFile(templatePath).OpenRead()) using (var reader = new StreamReader(stream)) { // Read the template and compile it. var template = reader.ReadToEnd(); _engine.AddTemplate(templateName, template); _engine.Compile(templateName, typeof(TModel)); } } return(_engine.Run(templateName, typeof(TModel), model)); } }
public void Generate(CompilerConfiguration configuration, Content parent) { // Install packages. var files = _nugetInstaller.Install(configuration, false /* Skip addins for now */); // Get document model. var modelBuilder = new DocumentModelBuilder(); var model = modelBuilder.BuildModel(files.Select(x => x.Path.FullPath)); // Build context. var renderer = new CommentRenderer(); var pageIndex = new ApiUrlResolver(model); var context = new ApiContext(model, renderer, pageIndex); // Create the API and DSL reference overview. var apiRoot = _apiOverviewBuilder.Create(configuration, context, parent, model); var dslRoot = _dslOverviewBuilder.Create(configuration, context, parent, model); // Add the generated content to it's parent. parent.AddChild(dslRoot); parent.AddChild(apiRoot); // Generate the content. Generate(configuration, context, apiRoot); }
private Content GenerateType(CompilerConfiguration configuration, ApiContext context, Content parent, DocumentedType type) { var typeContent = _typeBuilder.Create(configuration, context, parent, type); // Generate constructors. foreach (var constructorContent in type.Constructors.OrderBy(x => x.Parameters.Count) .Select(c => _methodBuilder.Create(configuration, context, typeContent, c))) { typeContent.AddChild(constructorContent); } // Generate properties. foreach (var propertyContent in type.Properties.OrderBy(x => x.Definition.Name) .Select(p => _propertyBuilder.Create(configuration, context, typeContent, p))) { typeContent.AddChild(propertyContent); } // Generate methods. foreach (var methodContent in type.Methods.OrderBy(x => x.Definition.Name) .Select(method => _methodBuilder.Create(configuration, context, typeContent, method))) { typeContent.AddChild(methodContent); } return(typeContent); }
public void CodeDomPipeline() { TestBehavior.count = 0; ICompilerConfiguration configuration = new CompilerConfiguration(); configuration.References().AddDirectory(Environment.CurrentDirectory); TestPipeline(behaviorProvider => new CodeDomPipeline <ProductQueryHandler>(new CodeDomPipelineConfiguration(behaviorProvider, configuration))); }
private void Generate(CompilerConfiguration configuration, ApiContext context, Content parent) { foreach (var assembly in context.DocumentModel.Assemblies) { foreach (var @namespace in assembly.Namespaces.OrderBy(x => x.Identity)) { // Build the namespace content. var namespaceContent = GenerateNamespace(configuration, context, parent, @namespace); // Add the namespace content to the parent. parent.AddChild(namespaceContent); } } }
internal static Instance <JitEntryPoint> CompileWasm(UInt160 contract, byte[] buffer, ImportDictionary imports, bool ignoreEndingCode) { if (ByteCodeCache.TryGetValue(contract, out var instance)) { return(instance()); } var config = new CompilerConfiguration() { IgnoreEndingCode = ignoreEndingCode }; using var stream = new MemoryStream(buffer, 0, buffer.Length, false); return(Compile.FromBinary <JitEntryPoint>(stream, config)(imports)); }
public Content Create(CompilerConfiguration configuration, ApiContext context, Content parent, TModel model) { var viewModel = CreateViewModel(context, parent, model); var template = GetTemplate(context, parent, model, viewModel); var body = _engine.Render(configuration, template, viewModel); return(new Content( GetContentId(context, parent, model, viewModel), GetLink(context, parent, model, viewModel), GetTitle(context, parent, model, viewModel), GetSubTitle(context, parent, model, viewModel), GetMenuTitle(context, parent, model, viewModel), body)); }
private Content GenerateNamespace(CompilerConfiguration configuration, ApiContext context, Content parent, DocumentedNamespace @namespace) { var namespaceContent = _namespaceBuilder.Create(configuration, context, parent, @namespace); foreach (var type in @namespace.Types.OrderBy(x => x.Definition.Name)) { // Generate type content. var typeContent = GenerateType(configuration, context, namespaceContent, type); // Add the type to the namespace content. namespaceContent.AddChild(typeContent); } return(namespaceContent); }
public static bool VerifyContract(byte[] contractCode, bool ignoreEndingCode) { try { var config = new CompilerConfiguration() { IgnoreEndingCode = ignoreEndingCode }; using var stream = new MemoryStream(contractCode); Compile.FromBinary <dynamic>(stream, config)(BlockchainInterface.GetFunctionImports()); return(true); } catch (Exception ex) { Logger.LogInformation($"Failed to verify: {ex}"); return(false); } }
protected void exec() { if (File.If(out var sourceFile)) { if (sourceFile.TryTo.Text.If(out var source, out var exception)) { var stopwatch = new Stopwatch(); if (Stopwatch) { stopwatch.Start(); } var configuration = new CompilerConfiguration { ShowOperations = ShowOps, Tracing = Trace }; var compiler = new Compiler(source, configuration, this); var result = from machine in compiler.Generate().OnSuccess(m => { if (configuration.ShowOperations) { WriteLine(m.Operations); } }) from executed in machine.Execute() select executed; if (result.IfNot(out var failureException)) { WriteLine($"Exception: {failureException}"); } if (Stopwatch) { stopwatch.Stop(); WriteLine(stopwatch.Elapsed.ToLongString(true)); } } else { WriteLine($"Exception: {exception}"); } } }
public IEnumerable <IFile> Install(CompilerConfiguration options, bool installAddins) { var result = new List <FilePath>(); foreach (var package in options.Packages) { if (!package.IsCore && !installAddins) { continue; } var paths = new FilePathCollection(PathComparer.Default); // Install the package. var packagePath = Install(package); var packageDirectory = _fileSystem.GetDirectory(packagePath); if (package.Filters != null && package.Filters.Count > 0) { // Get all files matching the filters. foreach (var filter in package.Filters) { var pattern = string.Concat(packagePath.FullPath, "/", filter.TrimStart('/', '\\')); paths.Add(_globber.GetFiles(pattern)); } } else { // Do a recursive search in the package directory. paths.Add(packageDirectory. GetFiles("*", SearchScope.Recursive) .Select(file => file.Path)); } if (paths.Count > 0) { result.AddRange(paths); } } return(result.Select(path => _fileSystem.GetFile(path))); }
public int BuildPage(CompilerConfiguration configuration, Content root, Content parent, Content current) { var count = 1; // Create the view model. var model = new LayoutViewModel(parent, current.Title); model.CurrentId = current.Id; model.Current = current; model.Root = root; // Render the master page with the model. var html = _engine.Render(configuration, "templates/layout.cshtml", model); // Save the result to disc. var outputFilePath = current.Id == "index" && current.Parent == root ? new FilePath("index.html") : new FilePath(string.Concat(current.GetLink(), "/index.html").TrimStart('/')); outputFilePath = outputFilePath.MakeAbsolute(configuration.OutputPath); var outputPath = outputFilePath.GetDirectory(); if (!_fileSystem.Exist(outputPath)) { _fileSystem.GetDirectory(outputPath).Create(); } using (var stream = _fileSystem.GetFile(outputFilePath).OpenWrite()) using (var writer = new StreamWriter(stream)) { writer.Write(html); } // Process child pages recursivly. foreach (var child in current.Children) { count += BuildPage(configuration, root, current, child); } return(count); }
private static void TestServices() { Console.WriteLine("Current ThreadID: {0}", Thread.CurrentThread.ManagedThreadId); IBehaviorProvider behaviors = new BehaviorProviderCollection() .Add( new AttributeBehaviorCollection() .Add(typeof(ReprocessAttribute), typeof(ReprocessBehavior)) ); ICompilerConfiguration configuration = new CompilerConfiguration() //.BaseType(typeof(WorkerPipelineHandler<>)) .AddTempDirectory(@"C:\Temp\Pipelines"); configuration.References() .AddDirectory(Environment.CurrentDirectory); configuration.GetBehaviorGenerator( new CodeDomBehaviorGeneratorCollection() .Add(typeof(ReprocessAttribute), new CodeDomReprocessBehaviorInstanceGenerator()) ); ServiceHandlerCollection collection = new ServiceHandlerCollection(); //collection.Add(new TempCheckServiceHandler()); collection.Add( new BackgroundServiceCollection() .AddIntervalHandler(TimeSpan.FromSeconds(5), new TempCheckWorkerHandler()) ); //collection.Add(new Temp2CheckServiceHandler()); Console.WriteLine("Starting services..."); collection.Start(); Console.WriteLine("Press any key to stop services..."); Console.ReadKey(true); collection.Stop(); Console.WriteLine("All services stopped..."); }
public void Generate(CompilerConfiguration configuration, Content parent) { var pagesPath = configuration.Root.Combine("pages").MakeAbsolute(_environment); var pagesDirectory = _fileSystem.GetDirectory(pagesPath); if (!pagesDirectory.Exists) { _log.Warning("No pages directory found."); return; } // Get all files. var pages = new List <StaticPage>(); var files = pagesDirectory.GetFiles("*.md", SearchScope.Current) .Concat(pagesDirectory.GetFiles("*.html", SearchScope.Current)); foreach (var file in files) { var page = StaticPageParser.Parse(file); pages.Add(page); } // Create content from all files. foreach (var page in pages.OrderBy(x => x.SortOrder)) { var pageContent = page.Content; if (page.ContentType == "markdown") { // Process markdown. var md = new MarkdownDeep.Markdown(); pageContent = md.Transform(pageContent); } var content = new Content(page.Id, page.Id, page.Title, null, pageContent); parent.AddChild(content); } }
// Constructors public TranslatorContext(Session session, CompilerConfiguration rseCompilerConfiguration, Expression query, CompiledQueryProcessingScope compiledQueryScope) { ArgumentValidator.EnsureArgumentNotNull(session, nameof(session)); ArgumentValidator.EnsureArgumentNotNull(rseCompilerConfiguration, nameof(rseCompilerConfiguration)); ArgumentValidator.EnsureArgumentNotNull(query, nameof(query)); Domain = session.Domain; RseCompilerConfiguration = rseCompilerConfiguration; // Applying query preprocessors query = Domain.Handler.QueryPreprocessors .Aggregate(query, (current, preprocessor) => ApplyPreprocessor(preprocessor, session, current)); // Built-in preprocessors query = AggregateOptimizer.Rewrite(query); query = ClosureAccessRewriter.Rewrite(query, compiledQueryScope); query = EqualityRewriter.Rewrite(query); query = EntitySetAccessRewriter.Rewrite(query); query = SubqueryDefaultResultRewriter.Rewrite(query); Evaluator = new ExpressionEvaluator(query); query = PersistentIndexerRewriter.Rewrite(query, this); Query = query; resultAliasGenerator = AliasGenerator.Create("#{0}{1}"); columnAliasGenerator = AliasGenerator.Create(new[] { "c01umn" }); CustomCompilerProvider = Domain.Handler.GetMemberCompilerProvider <Expression>(); Model = Domain.Model; TypeIdRegistry = session.StorageNode.TypeIdRegistry; ProviderInfo = Domain.Handlers.ProviderInfo; Translator = new Translator(this, compiledQueryScope); ParameterExtractor = new ParameterExtractor(Evaluator); Bindings = new LinqBindingCollection(); applyParameters = new Dictionary <CompilableProvider, ApplyParameter>(); tupleParameters = new Dictionary <ParameterExpression, Parameter <Tuple> >(); boundItemProjectors = new Dictionary <ParameterExpression, ItemProjectorExpression>(); }
protected void update(bool execute, bool fromMenu) { if (!locked && textEditor.TextLength != 0) { locked = true; if (manual) { labelStatus.Text = "running..."; Application.DoEvents(); } else if (fromMenu) { document.Save(); } try { textConsole.Clear(); context.ClearPeeks(); stopwatch.Reset(); stopwatch.Start(); _exceptionIndex = none <int>(); _exceptionData = none <ExceptionData>(); var kagamiConfiguration = new CompilerConfiguration { ShowOperations = dumpOperations, Tracing = tracing }; var compiler = new Compiler(textEditor.Text, kagamiConfiguration, context); if (compiler.Generate().If(out var machine, out var exception)) { machine.PackageFolder = packageFolder.FullPath; if (execute) { if (machine.Execute().IfNot(out exception)) { textWriter.WriteLine(KAGAMI_EXCEPTION_PROMPT + exception.Message); _exceptionIndex = compiler.ExceptionIndex; if (_exceptionIndex.IsNone) { _exceptionIndex = textEditor.SelectionStart.Some(); } } else { cancelled = context.Cancelled(); context.Reset(); } } stopwatch.Stop(); var state = textEditor.StopAutoScrollingAlways(); try { colorizer.Colorize(compiler.Tokens); } finally { textEditor.ResumeAutoScrollingAlways(state); } if (_exceptionIndex.If(out var index)) { var remainingLineLength = getRemainingLineIndex(index); if (remainingLineLength > -1) { showException(index, remainingLineLength); } } if (dumpOperations && compiler.Operations.If(out var operations)) { textWriter.WriteLine(operations); } document.Clean(); labelStatus.Text = stopwatch.Elapsed.ToLongString(true) + (cancelled ? " (cancelled)" : ""); } else { textWriter.WriteLine(KAGAMI_EXCEPTION_PROMPT + exception.Message); _exceptionIndex = compiler.ExceptionIndex; if (_exceptionIndex.IsNone) { _exceptionIndex = textEditor.SelectionStart.Some(); } if (_exceptionIndex.If(out var index)) { var remainingLineLength = getRemainingLineIndex(index); if (remainingLineLength > -1) { showException(index, remainingLineLength); } } } } catch (Exception exception) { textWriter.WriteLine(KAGAMI_EXCEPTION_PROMPT + exception.Message); } finally { locked = false; } } }
protected override ICompiler CreateCompiler(CompilerConfiguration configuration) => new SqlCompiler(Handlers, configuration);
public CompilationContext(CompilerConfiguration configuration) { Assert(configuration != null); this.Configuration = configuration; }
public void Build() { Configuration = new CompilerConfiguration <S>("ArmatSoftware.Code.Engine.Tests.Executors"); Compiler = new CSharpCompiler <S>(); }
internal TranslatedQuery <TResult> Translate <TResult>(Expression expression, CompilerConfiguration compilerConfiguration) { try { var context = new TranslatorContext(session, compilerConfiguration, expression); return(context.Translator.Translate <TResult>()); } catch (Exception ex) { throw new QueryTranslationException(String.Format( Strings.ExUnableToTranslateXExpressionSeeInnerExceptionForDetails, expression.ToString(true)), ex); } }
public SqlCompiler(HandlerAccessor handlers, CompilerConfiguration configuration) : base(handlers, configuration) { }
public CompilationContext(CompilerConfiguration configuration) { this.Configuration = configuration; }
protected override ICompiler CreateCompiler(CompilerConfiguration configuration) { return(new SqlCompiler(Handlers, configuration)); }
internal ExecutableProvider Compile(CompilableProvider provider, CompilerConfiguration configuration) { return(CompilationService.Compile(provider, configuration)); }
public async Task<CompileResult> CompileFile(FileInfo file, CompilerConfiguration compilerConfig) { if (file == null) { throw new ArgumentNullException("file"); } if (compilerConfig == null) { throw new ArgumentNullException("compilerConfig"); } var compiler = compilerConfig.GetCompiler(file.Name); if (compiler == null) { throw new InvalidOperationException("Compiler could not be found for '" + file.Extension + "' type file"); } ICompiler minCompiler = null; string minFileName = null; if (_minimise) { minFileName = Path.GetFileNameWithoutExtension(file.Name) + _compileExtension + ".min"; minCompiler = compilerConfig.GetCompiler(minFileName); if (minCompiler == null) { throw new InvalidOperationException("Minimising compiler could not be found for '" + _compileExtension + "' type file"); } } // First step is grab the file contents, then continue // Do the initial compile var fileData = file.Exists ? AttemptRead(file.FullName) : string.Empty; var output = string.Empty; var deps = new List<string>(); bool hasErrored = false; if (!string.IsNullOrEmpty(fileData)) { var stopwatch = new Stopwatch(); stopwatch.Start(); try { var compileResult = await compiler.Compile(fileData, file).ConfigureAwait(false); output = compileResult.Output; deps = compileResult.AdditionalDependencies ?? deps; } catch (Exception e) { output = "An error occurred during initial compilation: \r\n" + e.GetBaseException().Message; hasErrored = true; compilerConfig.HasException(e); } stopwatch.Stop(); compilerConfig.HasMeasurement(new CompileMeasurement { Compiler = compiler.GetType().Name, File = file.FullName, CompileTimeMilliseconds = stopwatch.ElapsedMilliseconds }); } // Do the minimisation if it has been selected if (!hasErrored && _minimise && !string.IsNullOrEmpty(output)) { var stopwatch = new Stopwatch(); stopwatch.Start(); try { var minResult = await minCompiler.Compile(output, null).ConfigureAwait(false); output = minResult.Output; if (minResult.AdditionalDependencies != null && minResult.AdditionalDependencies.Any()) { foreach(var dep in minResult.AdditionalDependencies) { if (!deps.Contains(dep)) { deps.Add(dep); } } } } catch (Exception e) { output = "An error occurred during minification: \r\n" + e.GetBaseException().Message; compilerConfig.HasException(e); } stopwatch.Stop(); compilerConfig.HasMeasurement(new CompileMeasurement { Compiler = minCompiler.GetType().Name, File = minFileName, CompileTimeMilliseconds = stopwatch.ElapsedMilliseconds }); } return new CompileResult { Output = output, AdditionalDependencies = deps }; }