public Task <CodeAnalysis.Compilation> EmitCellCompilationAsync( CodeCellId cellId, EvaluationEnvironment evaluationEnvironment, CancellationToken cancellationToken = default) => EmitSubmissionCompilationAsync( cellId.ToDocumentId(), evaluationEnvironment, cancellationToken);
public async Task <IActionResult> Evaluate([FromBody] string code) { var globals = new EvaluationEnvironment(this.HttpContext, this.Url, this.Database, this.Redis, this.Filesystem, this.Tokens); var sopts = ScriptOptions.Default .WithImports("System", "System.Collections.Generic", "System.Diagnostics", "System.Linq", "System.Net.Http", "System.Net.Http.Headers", "System.Reflection", "System.Text", "System.Threading.Tasks", "SlimGet", "SlimGet.Data", "SlimGet.Data.Configuration", "SlimGet.Data.Database", "SlimGet.Services", "SlimGet.Models", "SlimGet.Filters") .WithReferences(AppDomain.CurrentDomain.GetAssemblies().Where(xa => !xa.IsDynamic && !string.IsNullOrWhiteSpace(xa.Location))); var sw1 = Stopwatch.StartNew(); var cs = CSharpScript.Create(code, sopts, typeof(EvaluationEnvironment)); var csc = cs.Compile(); sw1.Stop(); this.Response.Headers.Add("X-Compilation-Time", sw1.ElapsedMilliseconds.ToString("#,##0")); if (csc.Any(xd => xd.Severity == DiagnosticSeverity.Error)) { var sb = new StringBuilder(); foreach (var xd in csc) { var ls = xd.Location.GetLineSpan(); sb.AppendLine($"Error at {ls.StartLinePosition.Line:#,##0}, {ls.StartLinePosition.Character:#,##0}: {xd.GetMessage()}"); } return(this.Content(sb.ToString(), "text/plain", AbstractionUtilities.UTF8)); } Exception rex = null; ScriptState <object> css = null; var sw2 = Stopwatch.StartNew(); try { css = await cs.RunAsync(globals).ConfigureAwait(false); rex = css.Exception; } catch (Exception ex) { rex = ex; } sw2.Stop(); this.Response.Headers.Add("X-Execution-Time", sw2.ElapsedMilliseconds.ToString("#,##0")); if (rex != null) { return(this.Content($"Execution failed with exception\n{rex.GetType()}: {rex.Message}\n{rex.StackTrace}", "text/plain", AbstractionUtilities.UTF8)); } if (css.ReturnValue != null) { this.Response.Headers.Add("X-Result-Type", css.ReturnValue.GetType().ToString()); return(this.Content(css.ReturnValue.ToString(), "text/plain", AbstractionUtilities.UTF8)); } return(this.NoContent()); }
public InteractiveSessionDescription( LanguageDescription languageDescription, string targetPlatformIdentifier, EvaluationEnvironment evaluationEnvironment = default) { LanguageDescription = languageDescription; TargetPlatformIdentifier = targetPlatformIdentifier; EvaluationEnvironment = evaluationEnvironment; }
public void Calculate(TaxReturn @return) { if (!Definition.Calculateable) { return; } var env = new EvaluationEnvironment(@return, null); foreach (var inst in Forms) { inst.Calculate(env); } }
public Compilation(CodeCellId codeCellId, int submissionNumber, EvaluationEnvironment evaluationEnvironment, bool isResultAnExpression, AssemblyDefinition executableAssembly, IReadOnlyList <AssemblyDefinition> references);
EmitSubmissionCompilationAsync( DocumentId submissionDocumentId, EvaluationEnvironment evaluationEnvironment, CancellationToken cancellationToken = default) { if (submissionDocumentId == null) { throw new ArgumentNullException(nameof(submissionDocumentId)); } var submissionDocument = workspace.CurrentSolution.GetDocument(submissionDocumentId); var semanticModel = await submissionDocument .GetSemanticModelAsync(cancellationToken) .ConfigureAwait(false); var syntaxRewriter = new InteractiveSyntaxRewriter(semanticModel); var compilationUnit = (CompilationUnitSyntax)syntaxRewriter.VisitCompilationUnit( semanticModel.SyntaxTree.GetCompilationUnitRoot(cancellationToken)); workspace.SetLoadDirectiveFiles( submissionDocumentId, sourceReferenceResolver, syntaxRewriter.LoadDirectives); var fixedUpCompilationUnit = await FixupSubmissionForEmissionAsync( compilationUnit, cancellationToken) .ConfigureAwait(false); if (fixedUpCompilationUnit != compilationUnit) { workspace.SetCurrentSolution( workspace.CurrentSolution.WithDocumentSyntaxRoot( submissionDocument.Id, fixedUpCompilationUnit)); } var compilation = await GetCompilationAsync(submissionDocument.Id, cancellationToken) .ConfigureAwait(false); using (var stream = new MemoryStream()) { byte[] peImage = null; var emitResult = compilation.Emit(stream, cancellationToken: cancellationToken); if (emitResult.Success) { stream.Position = 0; peImage = stream.ToArray(); } lastEmitDiagnostics = emitResult.Diagnostics; AssemblyDefinition executableAssembly = null; if (peImage != null) { var entryPoint = compilation.GetEntryPoint(cancellationToken); var ns = entryPoint.ContainingNamespace; var type = entryPoint.ContainingType; executableAssembly = new AssemblyDefinition( new AssemblyName(compilation.AssemblyName), null, string.IsNullOrEmpty(ns?.MetadataName) ? type.MetadataName : ns.MetadataName + "." + type.MetadataName, entryPoint.MetadataName, peImage); } return(new CodeAnalysis.Compilation( submissionDocumentId.ToCodeCellId(), submissionCount, evaluationEnvironment, DetermineIfResultIsAnExpression( compilation, compilation.SyntaxTrees.Last(), cancellationToken), monoScriptCompilationPatcher.Patch( submissionDocumentId, executableAssembly), await DependencyResolver.ResolveReferencesAsync( compilation.References, includePeImagesInResolution, cancellationToken).ConfigureAwait(false))); } }
public EvaluationService(IWorkspaceService workspace, EvaluationEnvironment evaluationEnvironment, IEvaluationContextManager evaluationContextManager = null);
public async Task EvaluateAsync(CommandContext ctx, [RemainingText, Description("Code to evaluate.")] string code) { if (string.IsNullOrWhiteSpace(code)) { throw new InvalidCommandUsageException("Code missing."); } int cs1 = code.IndexOf("```") + 3; int cs2 = code.LastIndexOf("```"); if (cs1 == -1 || cs2 == -1) { throw new InvalidCommandUsageException("You need to wrap the code into a code block."); } code = code.Substring(cs1, cs2 - cs1); var emb = new DiscordEmbedBuilder { Title = "Evaluating...", Color = this.ModuleColor }; DiscordMessage msg = await ctx.RespondAsync(embed : emb.Build()); var globals = new EvaluationEnvironment(ctx); var sopts = ScriptOptions.Default .WithImports("System", "System.Collections.Generic", "System.Linq", "System.Net.Http", "System.Net.Http.Headers", "System.Reflection", "System.Text", "System.Text.RegularExpressions", "System.Threading.Tasks", "DSharpPlus", "DSharpPlus.CommandsNext", "DSharpPlus.Entities", "DSharpPlus.Interactivity") .WithReferences(AppDomain.CurrentDomain.GetAssemblies().Where(xa => !xa.IsDynamic && !string.IsNullOrWhiteSpace(xa.Location))); var sw1 = Stopwatch.StartNew(); var snippet = CSharpScript.Create(code, sopts, typeof(EvaluationEnvironment)); var diag = snippet.Compile(); sw1.Stop(); if (diag.Any(d => d.Severity == DiagnosticSeverity.Error)) { emb = new DiscordEmbedBuilder { Title = "Compilation failed", Description = $"Compilation failed after {sw1.ElapsedMilliseconds.ToString("#,##0")}ms with {diag.Length} errors.", Color = DiscordColor.Red }; foreach (Diagnostic d in diag.Take(3)) { FileLinePositionSpan ls = d.Location.GetLineSpan(); emb.AddField($"Error at line: {ls.StartLinePosition.Line}, {ls.StartLinePosition.Character}", Formatter.InlineCode(d.GetMessage())); } if (diag.Length > 3) { emb.AddField("Some errors were omitted", $"{diag.Length - 3} errors not displayed"); } if (msg != null) { msg = await msg.ModifyAsync(embed : emb.Build()); } return; } Exception exc = null; ScriptState <object> css = null; var sw2 = Stopwatch.StartNew(); try { css = await snippet.RunAsync(globals); exc = css.Exception; } catch (Exception e) { exc = e; } sw2.Stop(); if (exc != null) { emb = new DiscordEmbedBuilder { Title = "Execution failed", Description = $"Execution failed after {sw2.ElapsedMilliseconds.ToString("#,##0")}ms with {Formatter.InlineCode($"{exc.GetType()} : {exc.Message}")}.", Color = this.ModuleColor }; if (msg != null) { msg = await msg.ModifyAsync(embed : emb.Build()); } return; } emb = new DiscordEmbedBuilder { Title = "Evaluation successful", Color = DiscordColor.Aquamarine }; emb.AddField("Result", css.ReturnValue != null ? css.ReturnValue.ToString() : "No value returned", false); emb.AddField("Compilation time", string.Concat(sw1.ElapsedMilliseconds.ToString("#,##0"), "ms"), true); emb.AddField("Execution time", string.Concat(sw2.ElapsedMilliseconds.ToString("#,##0"), "ms"), true); if (css.ReturnValue != null) { emb.AddField("Return type", css.ReturnValue.GetType().ToString(), true); } if (msg != null) { await msg.ModifyAsync(embed : emb.Build()); } else { await ctx.RespondAsync(embed : emb.Build()); } }
public EvaluationService(IWorkspaceService workspace, EvaluationEnvironment evaluationEnvironment);
public InteractiveSessionDescription(LanguageDescription languageDescription, string targetPlatformIdentifier, EvaluationEnvironment evaluationEnvironment = default(EvaluationEnvironment));
public EvaluationResult EvaluateField(EvaluationEnvironment env, string fieldName) { return(new ArrayResult(new List <EvaluationResult>())); }
public EvaluationResult EvaluateField(EvaluationEnvironment env, string fieldName) { return(EvaluationResult.Zero); }