Skip to content

Commit f9196a8

Browse files
committed
A bunch of random improvements
1 parent 6fe7aec commit f9196a8

18 files changed

+257
-499
lines changed

CSharpRepl.Tests/EvalTests.cs

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public EvalTests(ITestOutputHelper outputHelper)
6565
[Theory]
6666
[InlineData("1+1", 2L, "int")]
6767
[InlineData("return 1+1;", 2L, "int")]
68-
[InlineData("return Random.Next(1,2);", 1L, "int")]
68+
[InlineData("return Random.Shared.Next(1,2);", 1L, "int")]
6969
[InlineData(@"var a = ""thing""; return a;", "thing", "string")]
7070
[InlineData("Math.Pow(1,2)", 1D, "double")]
7171
[InlineData(@"Enumerable.Range(0,1).Select(a=>""@"");", null, null)]
@@ -79,7 +79,7 @@ public async Task Eval_WellFormattedCodeExecutes(string expr, object expected, s
7979
var (result, statusCode) = await Execute(expr);
8080
var res = result.ReturnValue as JsonElement?;
8181
object convertedValue;
82-
if (res.Value.ValueKind == JsonValueKind.Array)
82+
if (res?.ValueKind == JsonValueKind.Array)
8383
{
8484
convertedValue = res.Value.GetRawText();
8585
}
@@ -150,9 +150,9 @@ public async Task Eval_JsonNetSerializationFailureHandled(string expr, string me
150150
}
151151

152152
[Theory]
153-
[InlineData(@"Enumerable.Range(0,1).Select(a=>""@"")", "@", 1, "SelectRangeIterator<string>")]
154-
[InlineData(@"return Enumerable.Range(0,1).Select(a=>""@"");", "@", 1, "SelectRangeIterator<string>")]
155-
public async Task Eval_EnumerablesReturnArraysOf(string expr, object expected, int count, string type)
153+
[InlineData(@"Enumerable.Range(0,1).Select(a=>""@"")", "@", 1)]
154+
[InlineData(@"return Enumerable.Range(0,1).Select(a=>""@"");", "@", 1)]
155+
public async Task Eval_EnumerablesReturnArraysOf(string expr, object expected, int count)
156156
{
157157
var (result, statusCode) = await Execute(expr);
158158

@@ -162,13 +162,11 @@ public async Task Eval_EnumerablesReturnArraysOf(string expr, object expected, i
162162
Assert.Equal(expr, result.Code);
163163
Assert.Equal(expected, res.Value[0].GetString());
164164
Assert.Equal(count, res.Value.GetArrayLength());
165-
Assert.Equal(type, result.ReturnTypeName);
166165
}
167166

168167
[Theory]
169168
[InlineData("return 1+1", "CompilationErrorException", "; expected")]
170169
[InlineData(@"throw new Exception(""test"");", "Exception", "test")]
171-
[InlineData("return System.Environment.MachineName;", "CompilationErrorException", "Usage of this API is prohibited\nUsage of this API is prohibited")]
172170
[InlineData("return DoesNotCompile()", "CompilationErrorException", "; expected\nThe name 'DoesNotCompile' does not exist in the current context")]
173171
public async Task Eval_FaultyCodeThrowsExpectedException(string expr, string exception, string message)
174172
{
@@ -193,15 +191,6 @@ public async Task Eval_ConsoleOutputIsCaptured(string expr, string consoleOut, o
193191
Assert.Equal(returnValue, result.ReturnValue);
194192
}
195193

196-
[Fact]
197-
public async Task Eval_LoadDLLThatExposesTypeOfADependency()
198-
{
199-
var expr = "#nuget CK.ActivityMonitor\nvar m = new CK.Core.ActivityMonitor();";
200-
var (result, statusCode) = await Execute(expr);
201-
202-
Assert.Equal(HttpStatusCode.OK, statusCode);
203-
}
204-
205194
[Fact]
206195
public async Task Eval_FaultyDirectiveFailsGracefully()
207196
{
@@ -233,15 +222,17 @@ public async void Eval_ValidateGenericMathSupport()
233222
Assert.Equal(HttpStatusCode.OK, statusCode);
234223
}
235224

236-
[Fact(Skip = "Test is failing presumably because of a bug in ByteSize")]
225+
[Fact]
237226
public async Task Eval_SupportsNugetDirectiveWithActualUsage()
238227
{
239-
var expr = @"#nuget ByteSize
240-
var input = ""80527998976 B"";
241-
if (ByteSize.TryParse(input, NumberStyles.Any, new CultureInfo(""en-us""), out var output))
228+
var expr = """
229+
#nuget ByteSize
230+
var input = "80527998976 B";
231+
if (ByteSize.TryParse(input, NumberStyles.Any, new CultureInfo("en-us"), out var output))
242232
{
243233
Console.WriteLine(output);
244-
}";
234+
}
235+
""";
245236

246237
var (result, statusCode) = await Execute(expr);
247238

CSharpRepl/CSharpRepl.csproj

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<EnablePreviewFeatures>true</EnablePreviewFeatures>
4+
<EnablePreviewFeatures>true</EnablePreviewFeatures>
55
<LangVersion>preview</LangVersion>
66
<TargetFramework>net9.0</TargetFramework>
77
<OutputType>Exe</OutputType>
@@ -15,8 +15,11 @@
1515
<ItemGroup>
1616
<PackageReference Include="AngouriMath" Version="1.3.0" />
1717
<PackageReference Include="ICSharpCode.Decompiler" Version="8.2.0.7535" />
18-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.11.0" />
19-
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
18+
<PackageReference Include="Basic.Reference.Assemblies.Net90" Version="1.7.9" />
19+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.12.0-3.final" />
20+
<PackageReference Include="Newtonsoft.Json" Version="13.0.3">
21+
<ExcludeAssets>compile</ExcludeAssets>
22+
</PackageReference>
2023
<PackageReference Include="NuGet.Resolver" Version="6.11.1" />
2124
<PackageReference Include="Seq.Extensions.Logging" Version="6.1.0" />
2225
</ItemGroup>

CSharpRepl/Eval/BlacklistedTypesAnalyzer.cs

Lines changed: 0 additions & 56 deletions
This file was deleted.

CSharpRepl/Eval/CSharpEval.cs

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using CSDiscordService.Eval.ResultModels;
22
using Microsoft.CodeAnalysis;
33
using Microsoft.CodeAnalysis.CSharp.Scripting;
4-
using Microsoft.CodeAnalysis.Diagnostics;
54
using Microsoft.CodeAnalysis.Scripting;
65
using System;
76
using System.Collections.Immutable;
@@ -17,10 +16,6 @@ namespace CSDiscordService.Eval
1716
{
1817
public class CSharpEval
1918
{
20-
private static readonly ImmutableArray<DiagnosticAnalyzer> Analyzers =
21-
ImmutableArray.Create<DiagnosticAnalyzer>(new BlacklistedTypesAnalyzer());
22-
23-
private static readonly Random random = new Random();
2419
private readonly JsonSerializerOptions _serializerOptions;
2520
private readonly IPreProcessorService _preProcessor;
2621
private readonly ILogger<CSharpEval> _logger;
@@ -31,12 +26,10 @@ public CSharpEval(JsonSerializerOptions serializerOptons, IPreProcessorService p
3126
_preProcessor = preProcessor;
3227
_logger = logger;
3328
}
34-
3529
public async Task<EvalResult> RunEvalAsync(string code)
3630
{
3731
var sb = new StringBuilder();
3832
using var textWr = new ConsoleLikeStringWriter(sb);
39-
var env = new BasicEnvironment();
4033

4134
var sw = Stopwatch.StartNew();
4235

@@ -47,16 +40,16 @@ public async Task<EvalResult> RunEvalAsync(string code)
4740
}
4841
catch(Exception ex)
4942
{
50-
var diagnostics = Diagnostic.Create(new DiagnosticDescriptor("REPL01", ex.Message, ex.Message, "Code", DiagnosticSeverity.Error, true),
43+
var diagnostic = Diagnostic.Create(new DiagnosticDescriptor("REPL01", ex.Message, ex.Message, "Code", DiagnosticSeverity.Error, true),
5144
Location.Create("", TextSpan.FromBounds(0,0), new LinePositionSpan(LinePosition.Zero, LinePosition.Zero)));
5245
_logger.LogCritical(ex, "{message}", ex.Message);
53-
return EvalResult.CreateErrorResult(code, sb.ToString(), sw.Elapsed, new[] { diagnostics }.ToImmutableArray());
46+
return EvalResult.CreateErrorResult(code, sb.ToString(), sw.Elapsed, [diagnostic]);
5447
}
5548
var eval = CSharpScript.Create(context.Code, context.Options, typeof(Globals));
5649

57-
var compilation = eval.GetCompilation().WithAnalyzers(Analyzers);
50+
var compilation = eval.GetCompilation();
5851

59-
var compileResult = await compilation.GetAllDiagnosticsAsync();
52+
var compileResult = compilation.GetDiagnostics();
6053
var compileErrors = compileResult.Where(a => a.Severity == DiagnosticSeverity.Error).ToImmutableArray();
6154
sw.Stop();
6255

@@ -67,16 +60,14 @@ public async Task<EvalResult> RunEvalAsync(string code)
6760
}
6861

6962
var globals = new Globals();
70-
Globals.Random = random;
7163
Globals.Console = textWr;
72-
Globals.Environment = env;
7364

7465
sw.Restart();
7566
ScriptState<object> result;
7667

7768
try
7869
{
79-
result = await eval.RunAsync(globals, ex => true);
70+
result = await eval.RunAsync(globals, _ => true);
8071
}
8172
catch (CompilationErrorException ex)
8273
{

CSharpRepl/Eval/DisassemblyService.cs

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,39 +2,20 @@
22
using ICSharpCode.Decompiler.Disassembler;
33
using Microsoft.CodeAnalysis;
44
using Microsoft.CodeAnalysis.CSharp;
5-
using Newtonsoft.Json;
65
using System;
7-
using System.Collections.Generic;
86
using System.Collections.Immutable;
97
using System.IO;
108
using System.Linq;
11-
using System.Linq.Expressions;
12-
using System.Net.Http;
13-
using System.Reflection;
149
using System.Text;
15-
using System.Text.RegularExpressions;
1610
using System.Threading;
1711
using ICSharpCode.Decompiler.Metadata;
1812

1913
namespace CSDiscordService.Eval
2014
{
2115
public class DisassemblyService
2216
{
23-
private static readonly IReadOnlyCollection<MetadataReference> References = ImmutableArray.Create(
24-
MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location),
25-
MetadataReference.CreateFromFile(typeof(ValueTuple<>).GetTypeInfo().Assembly.Location),
26-
MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location),
27-
MetadataReference.CreateFromFile(typeof(List<>).GetTypeInfo().Assembly.Location),
28-
MetadataReference.CreateFromFile(typeof(JsonConvert).GetTypeInfo().Assembly.Location),
29-
MetadataReference.CreateFromFile(typeof(string).GetTypeInfo().Assembly.Location),
30-
MetadataReference.CreateFromFile(typeof(HttpClient).GetTypeInfo().Assembly.Location),
31-
MetadataReference.CreateFromFile(typeof(Regex).GetTypeInfo().Assembly.Location),
32-
MetadataReference.CreateFromFile(typeof(BinaryExpression).GetTypeInfo().Assembly.Location),
33-
MetadataReference.CreateFromFile(typeof(Console).GetTypeInfo().Assembly.Location),
34-
MetadataReference.CreateFromFile(Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location)
35-
);
36-
37-
private static readonly ImmutableArray<string> Imports = ImmutableArray.Create(
17+
private static readonly ImmutableArray<string> Imports =
18+
[
3819
"System",
3920
"System.IO",
4021
"System.Linq",
@@ -46,11 +27,9 @@ public class DisassemblyService
4627
"System.Threading",
4728
"System.Threading.Tasks",
4829
"System.Net.Http",
49-
"Newtonsoft.Json",
50-
"Newtonsoft.Json.Linq",
5130
"System.Reflection",
5231
"System.Reflection.Emit"
53-
);
32+
];
5433

5534
public string GetIl(string code)
5635
{
@@ -85,7 +64,7 @@ public object Main()
8564
.WithAllowUnsafe(true)
8665
.WithPlatform(Platform.AnyCpu);
8766

88-
var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString(), options: compOpts, references: References)
67+
var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString(), options: compOpts, references: Basic.Reference.Assemblies.Net90.References.All)
8968
.AddSyntaxTrees(scriptSyntaxTree);
9069

9170
var sb = new StringBuilder();

CSharpRepl/Eval/Globals.cs

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,8 @@ namespace CSDiscordService.Eval
66
{
77
public class Globals
88
{
9-
public static Random Random { get; set; }
109
public static ConsoleLikeStringWriter Console { get; internal set; }
11-
public static BasicEnvironment Environment { get; internal set; }
1210

13-
public void ResetButton()
14-
{
15-
System.Environment.Exit(0);
16-
}
17-
18-
public void PowerButton()
19-
{
20-
System.Environment.Exit(1);
21-
}
2211
public void Cmd(string name, string args = "")
2312
{
2413
var psi = new ProcessStartInfo(name)
@@ -33,22 +22,5 @@ public void Cmd(string name, string args = "")
3322
Console.WriteLine(p.StandardOutput.ReadToEnd());
3423
Console.WriteLine(p.StandardError.ReadToEnd());
3524
}
36-
3725
}
38-
39-
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
40-
public class ʘ‿ʘAttribute : Attribute { }
41-
42-
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
43-
public class ʘ_ʘAttribute : Attribute { }
44-
45-
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
46-
public class ಠ_ಠAttribute : Attribute { }
47-
48-
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
49-
public class ಠ‿ಠAttribute : Attribute { }
50-
51-
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
52-
public class 눈ᆺ눈Attribute : Attribute { }
53-
5426
}

0 commit comments

Comments
 (0)