Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重构部分代码 #236

Merged
merged 1 commit into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 127 additions & 28 deletions samples/ReferenceSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
using static System.Diagnostics.DebuggableAttribute;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using HarmonyLib;
using System.Diagnostics.CodeAnalysis;
using System.Reflection.PortableExecutable;
using static System.Reflection.Metadata.BlobBuilder;

namespace ReferenceSample
{
Expand All @@ -16,59 +20,154 @@ internal class Program

static void Main(string[] args)
{
//NatashaManagement.Preheating(true, true);
//var domain = NatashaManagement.CreateRandomDomain();
//var asm = domain.LoadPluginUseDefaultDependency("I:\\OpenSource\\Natasha\\samples\\ReferenceSample\\bin\\Debug\\net8.0\\DynamicLibraryFolders\\Nc0e9a864079d427680ea239b5a9e525e\\a69937be3d244336a20c46843d51d19b.dll");

TestMini();
//var a = Math.Min(1, args.Length);
//NatashaManagement.Preheating(false, false);
//Console.WriteLine("=============================");
//AssemblyCSharpBuilder builder = new();
//var asm = builder
// .UseRandomDomain()
// .ConfigCompilerOption(item=>item.AddSupperess("CS8019"))
// .WithCombineReferences(item => item.UseDefaultReferences())
// .WithCombineUsingCode(UsingLoadBehavior.WithAll)
// .Add("public class A{}",UsingLoadBehavior.WithAll)
// .GetAssembly();
//Console.WriteLine(asm.FullName);
//Console.ReadKey();
//NatashaInitializer.Preheating((asmName, name) => {
// if (name != null)
// {
// if (name.Contains("System"))
// {
// if (name.Contains("IO"))
// {
// //排除
// return true;
// }
// }
// }
// return false;
//});
//var type = typeof(HarmonyPatch);
//var type2 = typeof(HarmonyPrefix);
//Run();
//TestMini();
//TestMini();
//NatashaManagement.Preheating(true, true);
//GC.Collect();
//Thread.Sleep(15000);
var method = typeof(Program).GetMethod("TestMini");
for (int i = 0; i < 5; i++)
{
method.Invoke(null,null);
Thread.Sleep(3000);
}
Console.ReadKey();
////GC.Collect();
////Thread.Sleep(15000);
//var method = typeof(Program).GetMethod("TestMini");
//for (int i = 0; i < 5; i++)
//{
// method.Invoke(null,null);
// Thread.Sleep(3000);
//}
//Console.ReadKey();

}

public static void TestMini()
{

AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder();
builder
AssemblyCSharpBuilder builder = new();
builder.WithAnalysisAccessibility()
//.ConfigCompilerOption(item=>item.WithSuppressReportor())
.UseRandomDomain()
.ConfigCompilerOption(opt=>opt
.AppendCompilerFlag(
Natasha.CSharp.Compiler.CompilerBinderFlags.SuppressConstraintChecks |
Natasha.CSharp.Compiler.CompilerBinderFlags.SuppressObsoleteChecks |
Natasha.CSharp.Compiler.CompilerBinderFlags.SuppressTypeArgumentBinding |
Natasha.CSharp.Compiler.CompilerBinderFlags.SuppressUnsafeDiagnostics)
)
.DisableSemanticCheck()
.WithDebugCompile(item=>item.WriteToFile())
.OutputAsFullAssembly()
//.WithOutput()
.WithoutCombineReferences()
.WithoutSemanticCheck()
.WithDebugCompile(item=>item.WriteToAssembly())
//.WithReleaseCompile(false)
//.OutputAsRefAssembly()
.WithoutPrivateMembers()
.WithCombineUsingCode(UsingLoadBehavior.WithCurrent)
.AddReference(typeof(HarmonyPatch))
.AddReference(typeof(DebuggableAttribute))
.AddReference(typeof(object).Assembly)
.AddReference(typeof(Math).Assembly)
.AddReference(typeof(MathF).Assembly)
.WithoutCombineReferences();
.AddReference(typeof(SuppressMessageAttribute));

builder.Add(@"
public static class A{
[assembly: TargetFramework("".NETCoreApp,Version=v8.0"", FrameworkDisplayName = "".NET 8.0"")]
public class A{
public static int N1 = 10;
public static float N2 = 1.2F;
public static double N3 = 3.44;
private static short N4 = 0;
public static object Invoke2(){
return new object();
}
public static object Invoke3<T>() where T : new()
{
return new T();
}
public static object Invoke(){

var type = typeof(HarmonyPatch);
var type2 = typeof(HarmonyPrefix);
int[] a = [1,2,3];
return N1 + MathF.Log10((float)Math.Sqrt(MathF.Sqrt(N2) + Math.Tan(N3)));
}
}", UsingLoadBehavior.WithCurrent);

[SuppressMessage(""Microsoft.Performance"", ""CA1801:ReviewUnusedParameters"", MessageId = ""isChecked"")]
public object Test(){
return N1;
}

}
");
builder.Add(@"public class B{

public object Invoke2(){
return new object();
}
public object Invoke3<T>() where T : new()
{
return new T();
}
}");
builder.Add(@"
namespace Microsoft.CodeAnalysis.Runtime
{
public static class Instrumentation
{
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength)
{
if (payload == null)
{
payload = new bool[payloadLength];
}
return payload;
}

public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength)
{
if (payload == null)
{
payload = new bool[payloadLength];
}
return payload;
}

public static void FlushPayload()
{

}
}
}");
DebugDirectoryBuilder debug = new DebugDirectoryBuilder();
debug.AddReproducibleEntry();
debug.AddReproducibleEntry();
var asm = builder.GetAssembly();
var type = asm.GetType("A");
var type1 = asm.GetType("<PrivateImplementationDetails>");
var method = type.GetMethod("Invoke");
var result = method.Invoke(null, null);
var result = method.Invoke(null, null);
var method2 = type.GetMethod("Invoke2");
var result2 = method2.Invoke(Activator.CreateInstance(type), null);

Console.WriteLine(result);
}

Expand Down
16 changes: 14 additions & 2 deletions samples/ReferenceSample/ReferenceSample.csproj
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<SatelliteResourceLanguages>zh-Hans</SatelliteResourceLanguages>
</PropertyGroup>

<ItemGroup>
<Compile Remove="FakesAssemblies\**" />
<EmbeddedResource Remove="FakesAssemblies\**" />
<None Remove="FakesAssemblies\**" />
</ItemGroup>

<!--<ItemGroup>
<ProjectReference Include="..\..\test\workflow\Solution.NET.Sdk\Solution.NET.Sdk.csproj" />
</ItemGroup>-->

<ItemGroup>
<!--<PackageReference Include="Dapper" Version="2.1.15" />-->
<PackageReference Include="DotNetCore.Compile.Environment" Version="3.2.0" />
<PackageReference Include="HarmonyX" Version="2.10.2" />
<PackageReference Include="Microsoft.QualityTools.Testing.Fakes" Version="16.11.230815" />
<!--<PackageReference Include="FreeSql" Version="3.2.801" />
<PackageReference Include="log4net" Version="2.0.15" />-->
<!--<PackageReference Include="DotNetCore.Natasha.CSharp" Version="5.2.2.1" />-->
Expand All @@ -28,6 +36,10 @@
<ProjectReference Include="..\..\src\Natasha.CSharp\Natasha.CSharp.Compiler\Natasha.CSharp.Compiler.csproj" />
</ItemGroup>

<ItemGroup>
<AdditionalDesignTimeBuildInput Remove="FakesAssemblies\**" />
</ItemGroup>

<!--<ItemGroup>
<ProjectReference Include="..\..\src\Natasha.CSharp\Natasha.CSharp\Natasha.CSharp.csproj" />
</ItemGroup>-->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ public sealed partial class AssemblyCSharpBuilder
{

private Func<IEnumerable<MetadataReference>, IEnumerable<MetadataReference>>? _referencesFilter;
private CombineReferenceBehavior _combineReferenceBehavior;
private CombineReferenceBehavior _combineReferenceBehavior = CombineReferenceBehavior.UseCurrent;
private ReferenceConfiguration _referenceConfiguration = new();


/// <summary>
/// 编译时,使用主域引用覆盖引用集,并配置同名引用版本行为
/// 编译时,使用主域引用覆盖引用集,并配置同名引用版本行为(默认优先使用主域引用)
/// </summary>
/// <param name="action">配置委托</param>
/// <returns></returns>
Expand All @@ -47,7 +47,7 @@ public AssemblyCSharpBuilder WithoutCombineReferences()
/// </summary>
/// <param name="referencesFilter"></param>
/// <returns></returns>
public AssemblyCSharpBuilder ConfigReferencesFilter(Func<IEnumerable<MetadataReference>, IEnumerable<MetadataReference>>? referencesFilter)
public AssemblyCSharpBuilder SetReferencesFilter(Func<IEnumerable<MetadataReference>, IEnumerable<MetadataReference>>? referencesFilter)
{
_referencesFilter = referencesFilter;
return this;
Expand Down Expand Up @@ -79,7 +79,7 @@ public CSharpCompilation GetAvailableCompilation(Func<CSharpCompilationOptions,
// _compilerOptions.WithLowerVersionsAssembly();
//}

var options = _compilerOptions.GetCompilationOptions(_codeOptimizationLevel);
var options = _compilerOptions.GetCompilationOptions(_codeOptimizationLevel,_withDebugInfo);
if (initOptionsFunc != null)
{
options = initOptionsFunc(options);
Expand All @@ -101,7 +101,7 @@ public CSharpCompilation GetAvailableCompilation(Func<CSharpCompilationOptions,

_compilation = CSharpCompilation.Create(AssemblyName, SyntaxTrees, references, options);
#if DEBUG
stopwatch.RestartAndShowCategoreInfo("[Compiler]", "获取编译单元", 2);
stopwatch.StopAndShowCategoreInfo("[Compiler]", "获取编译单元", 2);
#endif

if (EnableSemanticHandler)
Expand All @@ -111,10 +111,6 @@ public CSharpCompilation GetAvailableCompilation(Func<CSharpCompilationOptions,
_compilation = item(this, _compilation, _semanticCheckIgnoreAccessibility);
}
}

#if DEBUG
stopwatch.StopAndShowCategoreInfo("[Semantic]", "语义处理", 2);
#endif
return _compilation;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,18 @@ public NatashaReferenceDomain Domain
if (AssemblyLoadContext.CurrentContextualReflectionContext != default)
{
_domain = (NatashaReferenceDomain)(AssemblyLoadContext.CurrentContextualReflectionContext);
if (_domain.AssemblyLoadBehavior != _dependencyLoadBehavior)
{
_domain.SetAssemblyLoadBehavior(_dependencyLoadBehavior);
}
}
else
{
_domain = NatashaReferenceDomain.DefaultDomain;
}

}

return _domain;
}
set
Expand All @@ -65,7 +70,7 @@ public NatashaReferenceDomain Domain
/// </summary>
/// <param name="loadBehavior"></param>
/// <returns></returns>
public AssemblyCSharpBuilder ConfigAssemblyLoadBehavior(AssemblyCompareInfomation loadBehavior)
public AssemblyCSharpBuilder SetAssemblyLoadBehavior(AssemblyCompareInfomation loadBehavior)
{
_dependencyLoadBehavior = loadBehavior;
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
/// </summary>
public sealed partial class AssemblyCSharpBuilder
{
public AssemblyCSharpBuilder ConfigOutput(string? folder = null)
/// <summary>
/// 将编译结果 (dll / pdb / xml) 文件写入此文件夹。
/// 默认不输出到文件,只输出到内存。
/// </summary>
/// <param name="folder">文件夹路径</param>
/// <returns></returns>
public AssemblyCSharpBuilder WithOutput(string? folder = null)
{
if (folder == null)
{
Expand All @@ -28,7 +34,6 @@ public AssemblyCSharpBuilder ConfigOutput(string? folder = null)
XmlFilePath = Path.Combine(OutputFolder, $"{AssemblyName}.xml");
return this;
}

}
#endif

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,39 @@
/// </summary>
public sealed partial class AssemblyCSharpBuilder
{

/// <summary>
/// 注入代码并拼接using
/// </summary>
/// <param name="script">脚本代码</param>
/// <param name="script">C#代码</param>
/// <param name="usingLoadBehavior">using 拼接行为</param>
/// <returns></returns>
public AssemblyCSharpBuilder Add(string script, UsingLoadBehavior usingLoadBehavior = UsingLoadBehavior.WithCurrent)
public AssemblyCSharpBuilder Add(string script, UsingLoadBehavior usingLoadBehavior)
{
switch (usingLoadBehavior)
{
case UsingLoadBehavior.WithDefault:
return AddScript(DefaultUsing.UsingScript + script);
return AddScript(NatashaReferenceDomain.DefaultDomain.UsingRecorder + script);
case UsingLoadBehavior.WithCurrent:
if (Domain == NatashaReferenceDomain.DefaultDomain)
{
return AddScript(DefaultUsing.UsingScript + script);
return AddScript(NatashaReferenceDomain.DefaultDomain.UsingRecorder + script);
}
return AddScript(Domain.UsingRecorder + script);
case UsingLoadBehavior.WithAll:
if (Domain == NatashaReferenceDomain.DefaultDomain)
{
return AddScript(DefaultUsing.UsingScript + script);
return AddScript(NatashaReferenceDomain.DefaultDomain.UsingRecorder + script);
}
StringBuilder usingBuilder = new();
foreach (var item in Domain.UsingRecorder._usings)
{
if (!DefaultUsing.HasElement(item))
if (!NatashaReferenceDomain.DefaultDomain.UsingRecorder.HasUsing(item))
{
usingBuilder.AppendLine($"using {item};");
}
}
return AddScript(DefaultUsing.UsingScript + usingBuilder + script);
return AddScript(NatashaReferenceDomain.DefaultDomain.UsingRecorder.ToString() + usingBuilder + script);
default:
return AddScript(script);
}
Expand Down
Loading
Loading