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

实现程序集全面测试 #265

Merged
merged 2 commits into from
Jan 7, 2024
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
93 changes: 48 additions & 45 deletions samples/ReferenceSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using HotReloadPlugin;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyModel;
using Microsoft.CodeAnalysis;
using Natasha.CSharp.Codecov.Utils;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
Expand Down Expand Up @@ -31,37 +29,41 @@ static void Main(string[] args)
//var a = typeof(CodecovMonitor);
//var b = typeof(A);
//NatashaManagement.Preheating(true, true);
//NatashaManagement.RegistDomainCreator<NatashaDomainCreator>();
//Console.WriteLine(typeof(Attribute).Assembly.FullName);
//Console.WriteLine(typeof(Console).Assembly.FullName);
//Console.WriteLine(typeof(Math).Assembly.FullName);
NatashaManagement.RegistDomainCreator<NatashaDomainCreator>();
NatashaManagement.Preheating(true, true);
//TestMini();
//TestMini();
//var a = Math.Min(1, args.Length);
NatashaManagement.Preheating<NatashaDomainCreator>(true, true);

//Console.WriteLine("=============================");
AssemblyCSharpBuilder builder = new();
var asm = builder
.UseRandomDomain()
.UseSmartMode()
//.WithoutCombineUsingCode()
.WithFileOutput()
.WithReleaseCompile()
.WithoutInjectToDomain()
.OutputAsRefAssembly()
.Add(@"
/// <summary>
/// 测试类
/// </summary>
public class A{
/// <summary>
/// 输出信息
/// </summary>
public void Show(){
Console.WriteLine(1);
}
}")
.GetAssembly();
Console.WriteLine(asm.FullName);
Console.ReadKey();
// NatashaManagement.Preheating<NatashaDomainCreator>(true, true);

// //Console.WriteLine("=============================");
// AssemblyCSharpBuilder builder = new();
// var asm = builder
// .UseRandomDomain()
// .UseSmartMode()
// //.WithoutCombineUsingCode()
// .WithFileOutput()
// .WithReleaseCompile()
// .WithoutInjectToDomain()
// .OutputAsRefAssembly()
// .Add(@"
///// <summary>
///// 测试类
///// </summary>
//public class A{
// /// <summary>
// /// 输出信息
// /// </summary>
// public void Show(){
// Console.WriteLine(1);
// }
//}")
// .GetAssembly();
// //Console.WriteLine(asm.FullName);
// Console.ReadKey();
//NatashaInitializer.Preheating((asmName, name) => {
// if (name != null)
// {
Expand Down Expand Up @@ -99,15 +101,15 @@ public static void TestMini1()
AssemblyCSharpBuilder builder = new();
builder
.UseNewDomain("adasd")
.UseSmartMode()
.ConfigCompilerOption(item => item.WithLowerVersionsAssembly().WithDiagnosticLevel(ReportDiagnostic.Warn))
.ConfigCompilerOption(item => item.WithLowerVersionsAssembly())
//.WithFileOutput()
.WithDebugCompile(item => item.WriteToAssembly())
.UseSimpleMode()
.ConfigLoadContext(ldc=> ldc
.AddReferenceAndUsingCode(typeof(Math).Assembly)
.AddReferenceAndUsingCode(typeof(MathF).Assembly)
.AddReferenceAndUsingCode(typeof(A))
.AddReferenceAndUsingCode(typeof(object))
.AddReferenceAndUsingCode(typeof(System.Runtime.AmbiguousImplementationException))
.AddReferenceAndUsingCode(typeof(CodecovMonitor))
.AddReferenceAndUsingCode(typeof(SuppressMessageAttribute)))
;
Expand Down Expand Up @@ -139,21 +141,22 @@ public static object Invoke(){
public static void TestMini()
{


AssemblyCSharpBuilder builder = new();
builder
.UseRandomDomain()
//.UseSmartMode()
.ConfigCompilerOption(item => item.WithLowerVersionsAssembly().WithDiagnosticLevel(ReportDiagnostic.Warn))
.ConfigCompilerOption(item => item.WithLowerVersionsAssembly())
//.WithFileOutput()
.WithDebugCompile(item => item.WriteToAssembly())
.UseSimpleMode()
.ConfigLoadContext(ldc=>ldc
.AddReferenceAndUsingCode(typeof(Math).Assembly)
.AddReferenceAndUsingCode(typeof(MathF).Assembly)
.AddReferenceAndUsingCode(typeof(A))
.AddReferenceAndUsingCode(typeof(CodecovMonitor))
.AddReferenceAndUsingCode(typeof(SuppressMessageAttribute)))
.UseSmartMode()
//.ConfigLoadContext(ldc => ldc
// .AddReferenceAndUsingCode(typeof(Math).Assembly)
// .AddReferenceAndUsingCode(typeof(MathF).Assembly)
// .AddReferenceAndUsingCode(typeof(object))
// .AddReferenceAndUsingCode(typeof(Console))
// .AddReferenceAndUsingCode(typeof(Attribute))
// .AddReferenceAndUsingCode(typeof(CodecovMonitor))
// .AddReferenceAndUsingCode(typeof(SuppressMessageAttribute)))
;


Expand All @@ -175,8 +178,8 @@ public static object Invoke2(){
/// </summary>
public static object Invoke(){
if(N1 == 10){
HotReloadPlugin.A asdasd = new();
asdasd.Show();
//HotReloadPlugin.A asdasd = new();
// asdasd.Show();
int[] a = [1,2,3];
Console.WriteLine(a);
return N1 + MathF.Log10((float)Math.Sqrt(MathF.Sqrt(N2) + Math.Tan(N3)));
Expand Down
7 changes: 3 additions & 4 deletions samples/ReferenceSample/ReferenceSample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
Expand All @@ -22,8 +22,8 @@
<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="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 @@ -40,7 +40,6 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Natasha.CSharp\Component\Core\Natasha.CSharp.Compiler.Domain\Natasha.CSharp.Compiler.Domain.csproj" />
<ProjectReference Include="..\..\src\Natasha.CSharp\Extension\Natasha.CSharp.Codecov\Natasha.CSharp.Codecov.csproj" />
<ProjectReference Include="..\HotReloadPlugin\HotReloadPlugin.csproj" />
</ItemGroup>

<!--<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,27 @@ static UsingAnalysistor()
{

var trees = compilation.SyntaxTrees;
#if DEBUG
int index = 0;
#endif
foreach (var tree in trees)
{
#if DEBUG
index += 1;
string treeName = $"脚本{index}";
Stopwatch stopwatch = new();
stopwatch.Start();
#endif
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();

SemanticModel semantiModel = compilation.GetSemanticModel(tree, ignoreAccessibility);
#if DEBUG
stopwatch.RestartAndShowCategoreInfo("[Semantic]", "语义节点获取", 3);
stopwatch.RestartAndShowCategoreInfo("[Semantic]", $"{treeName}_语义节点获取", 3);
#endif

var errors = semantiModel.GetDiagnostics();
#if DEBUG
stopwatch.StopAndShowCategoreInfo("[Semantic]", "语义诊断获取", 3);
stopwatch.StopAndShowCategoreInfo("[Semantic]", $"{treeName}_语义诊断获取", 3);
//stopwatch.Restart();
#endif

Expand Down Expand Up @@ -76,7 +81,7 @@ static UsingAnalysistor()
}

#if DEBUG
stopwatch.StopAndShowCategoreInfo("[Semantic]", "语义节点筛查", 3);
stopwatch.StopAndShowCategoreInfo("[Semantic]", $"{treeName}_语义节点筛查", 3);
#endif
if (errorNodes.Count > 0)
{
Expand All @@ -85,12 +90,14 @@ static UsingAnalysistor()
#endif
compilation = compilation.ReplaceSyntaxTree(tree, root.RemoveNodes(errorNodes, SyntaxRemoveOptions.KeepNoTrivia)!.SyntaxTree);
#if DEBUG
stopwatch.StopAndShowCategoreInfo("[Semantic]", "语义节点替换", 3);
stopwatch.StopAndShowCategoreInfo("[Semantic]", $"{treeName}_语义节点替换", 3);
#endif
}

}

#if DEBUG
Console.WriteLine();
#endif
}
return compilation;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,15 @@ public void AddReference(AssemblyName assemblyName, MetadataReference reference,
}

}
if (_referenceNameCache.TryGetValue(name,out var asmName))
{
if (asmName.FullName == assemblyName.FullName)
{
return;
}
}
_referenceNameCache[name] = assemblyName;
_referenceCache[assemblyName] = reference;

}
public bool HasReference(AssemblyName assemblyName)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
public enum UsingLoadBehavior
{
/// <summary>
/// 不合并 UsingCode, 只用手写的 Using.
/// </summary>
None = 0,
/// <summary>
/// 仅使用 [共享域] 加载或者编译产生的 UsingCode
/// </summary>
WithDefault = 1,
/// <summary>
/// 仅使用 [当前域] 加载或者编译产生的 UsingCode
/// </summary>
WithCurrent = 2,
/// <summary>
/// 合并 [共享域] 以及 [当前域] 的 UsingCode
/// </summary>
WithAll = 3
}

Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ internal static NatashaException GetCompileException(CSharpCompilation compilati
{
exception.Formatter = first.Location.SourceTree.ToString();
}
else if(compilation.SyntaxTrees.Length > 0)
{
exception.Formatter = compilation.SyntaxTrees[0].ToString();
}
exception.CompileMessage = $"编译程序集为:{compilation.AssemblyName};CSharp版本:{compilation.LanguageVersion};";
exception.ErrorKind = NatashaExceptionKind.Compile;
return exception;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
Expand All @@ -18,28 +19,33 @@ public static class MetadataHelper
#region metadata & namespace in memroy
public static unsafe (AssemblyName asmName, MetadataReference metadata, HashSet<string> namespaces)? GetMetadataAndNamespaceFromMemory(Assembly assembly, Func<AssemblyName?, string?, bool>? filter = null)
{
#if DEBUG
Debug.WriteLine($"~~提取元数据:{assembly.FullName}");
#endif
var asmName = assembly.GetName();
if (NatashaLoadContext.Creator.TryGetRawMetadata(assembly, out var blob, out var length))
{
if (filter == null || !filter(asmName, asmName.Name))
{

return (asmName
, AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob, length)).GetReference()
, GetNamespaceFromMemroy(assembly, filter)
return (
asmName,
AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob, length)).GetReference(),
GetNamespaceFromMemroy(assembly, filter)
);
}
}
return null;
}
public static unsafe (AssemblyName asmName, MetadataReference metadata)? GetMetadataFromMemory(Assembly assembly, Func<AssemblyName?, string?, bool>? filter = null)
{
#if DEBUG
Debug.WriteLine($"~~提取元数据:{assembly.FullName}");
#endif
var asmName = assembly.GetName();
if (NatashaLoadContext.Creator.TryGetRawMetadata(assembly, out var blob, out var length))
{
if (filter == null || !filter(asmName, asmName.Name))
{

return (asmName, AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob, length)).GetReference());
}
}
Expand Down Expand Up @@ -228,7 +234,7 @@ public static HashSet<string> GetNamespaceFromMemroy(Assembly assembly, Func<Ass
}
return tempSets;
}
#endregion
#endregion

#region metadata & namespace in file
internal static (AssemblyName asmName, MetadataReference metadata, HashSet<string> namespaces)? GetMetadataAndNamespaceFromFile(string path, Func<AssemblyName?, string?, bool>? filter = null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Natasha.DynamicLoad.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public static class NatashaLoadContext<TCreator> where TCreator : INatashaDynamicLoadContextCreator, new()
Expand Down Expand Up @@ -92,7 +93,7 @@ public NatashaLoadContext AddReferenceAndUsingCode(Assembly assembly, Func<Assem
{
AddReferenceAndUsing(result.Value.asmName, result.Value.metadata, result.Value.namespaces, loadReferenceBehavior);
var assmblies = Creator.GetDependencyAssemblies(assembly);
if (assmblies != null)
if (assmblies != null && assmblies.Any())
{
if (excludeAssembliesFunc != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,17 @@

public static class NatashaLoadContextExtension
{

/// <summary>
/// 根据类型所在的 Assmely及其引用的程序集 增加元数据 和 using
/// </summary>
/// <typeparam name="T">要添加引用的类型</typeparam>
/// <param name="context">Natasha 加载上下文</param>
/// <param name="loadReferenceBehavior">加载行为</param>
/// <returns></returns>
public static NatashaLoadContext AddReferenceAndUsingCode<T>(this NatashaLoadContext context, AssemblyCompareInfomation loadReferenceBehavior = AssemblyCompareInfomation.None)
{
return context.AddReferenceAndUsingCode(typeof(T).Assembly, null, loadReferenceBehavior);
}
/// <summary>
/// 根据类型所在的 Assmely及其引用的程序集 增加元数据 和 using
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@ internal static Assembly[] GetRuntimeAssemblies()
var defaultContext = DependencyContext.Default;
if (defaultContext != null)
{
return new HashSet<Assembly>(defaultContext
var tempAssemblies = new HashSet<Assembly>(defaultContext
.RuntimeLibraries
.SelectMany(lib => lib
.GetDefaultAssemblyNames(defaultContext)
.Select(Assembly.Load)))
.ToArray();
{
typeof(object).Assembly
};
return [.. tempAssemblies];
}
else
{
var noUseAsm = typeof(object).Assembly;
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
Expand Down
Loading
Loading