Skip to content

Commit

Permalink
Added MaybeNullAttribute and fixed tests with the correct check. Chan…
Browse files Browse the repository at this point in the history
…ges to Compiler.cs are not necessary anymore.
  • Loading branch information
andreas.hoffmann committed Mar 15, 2022
1 parent aa97eaf commit 032f1e4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 59 deletions.
59 changes: 18 additions & 41 deletions XmlSchemaClassGenerator.Tests/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static CompilationResult GenerateAssembly(Compilation compilation)
};
}

private static readonly ConcurrentDictionary<string, Tuple<List<SyntaxTree>, Assembly>> Assemblies = new();
private static readonly ConcurrentDictionary<string, Assembly> Assemblies = new();

private static readonly string[] DependencyAssemblies = new[]
{
Expand All @@ -55,33 +55,21 @@ public static CompilationResult GenerateAssembly(Compilation compilation)
public static Assembly GetAssembly(string name)
{
Assemblies.TryGetValue(name, out var assembly);
return assembly.Item2;
}

public static Assembly Generate(string name, string pattern, Generator generatorPrototype = null)
{
(_, var assembly) = GenerateVerbose(name, pattern, generatorPrototype);
return assembly;
return assembly;
}

public static (List<SyntaxTree>, Assembly) GenerateVerbose(string name, string pattern, Generator generatorPrototype = null)
{
if (Assemblies.TryGetValue(name, out var assembly)) { return (assembly.Item1, assembly.Item2); }
public static Assembly Generate(string name, string pattern, Generator generatorPrototype = null)
{
if (Assemblies.ContainsKey(name)) { return Assemblies[name]; }

var files = Glob.ExpandNames(pattern).OrderByDescending(f => f);

return GenerateFilesVerbose(name, files, generatorPrototype);
return GenerateFiles(name, files, generatorPrototype);
}

public static Assembly GenerateFiles(string name, IEnumerable<string> files, Generator generatorPrototype = null)
{
(_, var assembly) = GenerateFilesVerbose(name, files, generatorPrototype);
return assembly;
}

public static (List<SyntaxTree>, Assembly) GenerateFilesVerbose(string name, IEnumerable<string> files, Generator generatorPrototype = null)
{
if (Assemblies.TryGetValue(name, out var assembly)) { return (assembly.Item1, assembly.Item2); }
public static Assembly GenerateFiles(string name, IEnumerable<string> files, Generator generatorPrototype = null)
{
if (Assemblies.ContainsKey(name)) { return Assemblies[name]; }

generatorPrototype ??= new Generator
{
Expand Down Expand Up @@ -125,6 +113,7 @@ public static (List<SyntaxTree>, Assembly) GenerateFilesVerbose(string name, IEn
UniqueTypeNamesAcrossNamespaces = generatorPrototype.UniqueTypeNamesAcrossNamespaces,
CreateGeneratedCodeAttributeVersion = generatorPrototype.CreateGeneratedCodeAttributeVersion,
NetCoreSpecificCode = generatorPrototype.NetCoreSpecificCode,
EnableNullableReferenceAttributes = generatorPrototype.EnableNullableReferenceAttributes,
NamingScheme = generatorPrototype.NamingScheme
};

Expand All @@ -135,40 +124,28 @@ public static (List<SyntaxTree>, Assembly) GenerateFilesVerbose(string name, IEn

gen.Generate(files);

return CompileFilesVerbose(name, output.Files);
return CompileFiles(name, output.Files);
}

public static Assembly CompileFiles(string name, IEnumerable<string> files)
{
(_, var assembly) = CompileFilesVerbose(name, files);
return assembly;
}

public static (List<SyntaxTree>, Assembly) CompileFilesVerbose(string name, IEnumerable<string> files)
{
return CompileVerbose(name, files.Select(f => File.ReadAllText(f)).ToArray());
public static Assembly CompileFiles(string name, IEnumerable<string> files)
{
return Compile(name, files.Select(f => File.ReadAllText(f)).ToArray());
}

private static readonly LanguageVersion MaxLanguageVersion = Enum
.GetValues(typeof(LanguageVersion))
.Cast<LanguageVersion>()
.Max();

public static Assembly Compile(string name, params string[] contents)
public static Assembly Compile(string name, params string[] contents)
{
(_, var assembly) = CompileVerbose(name, contents);
return assembly;
}

public static (List<SyntaxTree>, Assembly) CompileVerbose(string name, params string[] contents)
{
var trustedAssembliesPaths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator);
var references = trustedAssembliesPaths
.Where(p => DependencyAssemblies.Contains(Path.GetFileNameWithoutExtension(p)))
.Select(p => MetadataReference.CreateFromFile(p))
.ToList();
var options = new CSharpParseOptions(kind: SourceCodeKind.Regular, languageVersion: MaxLanguageVersion);
var syntaxTrees = contents.Select(c => CSharpSyntaxTree.ParseText(c, options)).ToList();
var syntaxTrees = contents.Select(c => CSharpSyntaxTree.ParseText(c, options));
var compilation = CSharpCompilation.Create(name, syntaxTrees)
.AddReferences(references)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
Expand All @@ -179,9 +156,9 @@ public static (List<SyntaxTree>, Assembly) CompileVerbose(string name, params st
Assert.True(result.Result.Success);
Assert.NotNull(result.Assembly);

Assemblies[name] = Tuple.Create(syntaxTrees, result.Assembly);
Assemblies[name] = result.Assembly;

return (syntaxTrees, result.Assembly);
return result.Assembly;
}
}
}
34 changes: 17 additions & 17 deletions XmlSchemaClassGenerator.Tests/XmlTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -2382,27 +2383,26 @@ public void TestNullableReferenceAttributes()
GenerateNamespace = key => "Test"
}
};
//Unfortunately, I did not find access to the Attribute "AllowNull" in the generated Assembly.
//It is just not accessible via "CustomAttributes".
//So I have to parse the Syntax-Tree to find it.
(var syntaxTrees, _) = Compiler.GenerateVerbose(nameof(TestNullableReferenceAttributes), NullableReferenceAttributesPattern, generator);
var assembly = Compiler.Generate(nameof(TestNullableReferenceAttributes), NullableReferenceAttributesPattern, generator);
void assertNullable(string typename, bool nullable)
{
var root = (CompilationUnitSyntax)syntaxTrees.Single().GetRoot();
var ns = (NamespaceDeclarationSyntax)root.Members.Single();
var c1 = (ClassDeclarationSyntax)ns.Members.Single(
m => m is ClassDeclarationSyntax c && c.Identifier.ToString() == typename
);
var p = (PropertyDeclarationSyntax)c1.Members.Single(m => m is PropertyDeclarationSyntax n && n.Identifier.ToString() == "Text");
var hasAllowNullAttribute = p.AttributeLists.Any(d => d.Attributes.Any(a => a.GetText().ToString() == "System.Diagnostics.CodeAnalysis.AllowNullAttribute()"));
Type c = assembly.GetType(typename);
var property = c.GetProperty("Text");
var setParameter = property.SetMethod.GetParameters();
var getReturnParameter = property.GetMethod.ReturnParameter;
var allowNullableAttribute = setParameter.Single().CustomAttributes.SingleOrDefault(a => a.AttributeType == typeof(AllowNullAttribute));
var maybeNullAttribute = getReturnParameter.CustomAttributes.SingleOrDefault(a => a.AttributeType == typeof(MaybeNullAttribute));
var hasAllowNullAttribute = allowNullableAttribute != null;
var hasMaybeNullAttribute = maybeNullAttribute != null;
Assert.Equal(nullable, hasAllowNullAttribute);
Assert.Equal(nullable, hasMaybeNullAttribute);
}
assertNullable("ElementReferenceNullable", true);
assertNullable("ElementReferenceList", true);
assertNullable("ElementReferenceNonNullable", false);
assertNullable("AttributeReferenceNullable", true);
assertNullable("AttributeReferenceNonNullable", false);
assertNullable("AttributeValueNullableInt", false);
assertNullable("Test.ElementReferenceNullable", true);
assertNullable("Test.ElementReferenceList", true);
assertNullable("Test.ElementReferenceNonNullable", false);
assertNullable("Test.AttributeReferenceNullable", true);
assertNullable("Test.AttributeReferenceNonNullable", false);
assertNullable("Test.AttributeValueNullableInt", false);
}

[Fact, TestPriority(1)]
Expand Down
3 changes: 2 additions & 1 deletion XmlSchemaClassGenerator/TypeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1127,7 +1127,8 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
if (isNullableReferenceType && Configuration.EnableNullableReferenceAttributes)
{
member.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.CodeAnalysis.AllowNullAttribute"));
}
member.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.CodeAnalysis.MaybeNullAttribute"));
}

var attributes = GetAttributes(isArray).ToArray();
member.CustomAttributes.AddRange(attributes);
Expand Down

0 comments on commit 032f1e4

Please sign in to comment.