Skip to content

Commit

Permalink
Remove reflection usage for creating parts and root elements (#1240)
Browse files Browse the repository at this point in the history
  • Loading branch information
twsouthwick authored Nov 23, 2022
1 parent 1cf27c1 commit e224ff5
Show file tree
Hide file tree
Showing 11 changed files with 219 additions and 144 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ public class SchemaType

public bool IsPart => !string.IsNullOrEmpty(Part);

public bool IsRootElement => IsPart || BaseClass == "OpenXmlPartRootElement" || BaseClass == "OpenXmlPartRootElement";

public string Part { get; set; } = null!;

public ParticleOrderType CompositeType { get; set; }
Expand Down
135 changes: 135 additions & 0 deletions gen/DocumentFormat.OpenXml.Generator/FactoryGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using DocumentFormat.OpenXml.Generator.Editor;
using DocumentFormat.OpenXml.Generator.Generators.Parts;
using Microsoft.CodeAnalysis;
using System.CodeDom.Compiler;
using System.Text;

namespace DocumentFormat.OpenXml.Generator;

[Generator]
public class FactoryGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var openXml = context.GetOpenXmlGeneratorContext()
.GetOpenXmlServices();

context.RegisterSourceOutput(openXml, (context, openXml) =>
{
GeneratePartFactory(context, openXml);
GenerateRootActivator(context, openXml);
});
}

private static void GeneratePartFactory(SourceProductionContext context, OpenXmlGeneratorServices openXml)
{
using var sw = new StringWriter();
using var writer = new IndentedTextWriter(sw);

writer.WriteFileHeader();

writer.WriteLine("using DocumentFormat.OpenXml;");
writer.WriteLine("using DocumentFormat.OpenXml.Packaging;");
writer.WriteLine();
writer.WriteLine("namespace DocumentFormat.OpenXml.Features;");

writer.WriteLine("internal partial class TypedPartFactory : IPartFactory");

using (writer.AddBlock())
{
writer.WriteLine("public T? Create<T>() where T : OpenXmlPart");

using (writer.AddBlock())
{
foreach (var part in openXml.Context.Parts)
{
writer.Write("if (typeof(T) == typeof(");
writer.Write(part.Name);
writer.WriteLine("))");

using (writer.AddBlock())
{
writer.Write("return (T)(object)new ");
writer.Write(part.Name);
writer.WriteLine("();");
}

writer.WriteLine();
}

writer.WriteLine("return default;");
}
}

context.AddSource("TypedPartFactory", sw.ToString());
}

private static void GenerateRootActivator(SourceProductionContext context, OpenXmlGeneratorServices openXml)
{
using var sw = new StringWriter();
using var writer = new IndentedTextWriter(sw);

writer.WriteFileHeader();

writer.WriteLine("using System;");
writer.WriteLine("using System.Collections.Generic;");
writer.WriteLine("using DocumentFormat.OpenXml;");
writer.WriteLine("using DocumentFormat.OpenXml.Packaging;");
writer.WriteLine("using DocumentFormat.OpenXml.Framework.Metadata;");
writer.WriteLine();
writer.WriteLine("namespace DocumentFormat.OpenXml.Features;");

writer.WriteLine("internal partial class TypedRootElementFactory : IRootElementFactory");

using (writer.AddBlock())
{
writer.WriteLine("public static IEnumerable<ElementFactory> GetAllRootElements()");

using (writer.AddBlock())
{
foreach (var model in openXml.Context.Namespaces)
{
foreach (var type in model.Types)
{
if (type.IsRootElement)
{
var className = openXml.FindClassName(type.Name, fullyQualified: true);

writer.Write("yield return new ElementFactory(typeof(");
writer.Write(className);
writer.Write("), new(");
writer.WriteString(openXml.GetNamespaceInfo(type.Name.QName.Prefix).Uri);
writer.Write(", ");
writer.WriteString(type.Name.QName.Name);
writer.Write("), () => new ");
writer.Write(className);
writer.WriteLine("());");
}
}
}
}
}

context.AddSource("TypedRootFactory", sw.ToString());
}

private static void WritePartFiles(SourceProductionContext context, OpenXmlGeneratorServices openXml)
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var writer = new IndentedTextWriter(sw);

foreach (var part in openXml.Context.Parts)
{
sb.Clear();

writer.WriteFileHeader();
writer.WritePart(openXml, part);

context.AddSource(part.Name, sb.ToString());
}
}
}
31 changes: 19 additions & 12 deletions gen/DocumentFormat.OpenXml.Generator/PartGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,35 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
{
var openXml = context.GetOpenXmlGeneratorContext().GetOpenXmlServices();
var options = context.GetOpenXmlOptions().Select(static (o, _) => o.GenerateParts);
var parts = openXml.Combine(options);

context.RegisterSourceOutput(openXml.Combine(options), (context, data) =>
context.RegisterSourceOutput(parts, (context, data) =>
{
if (!data.Right)
{
return;
}
var openXml = data.Left;
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var writer = new IndentedTextWriter(sw);
foreach (var part in openXml.Context.Parts)
{
sb.Clear();
WritePartFiles(context, openXml);
});
}

writer.WriteFileHeader();
writer.WritePart(openXml, part);
private static void WritePartFiles(SourceProductionContext context, OpenXmlGeneratorServices openXml)
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var writer = new IndentedTextWriter(sw);

context.AddSource(part.Name, sb.ToString());
}
});
foreach (var part in openXml.Context.Parts)
{
sb.Clear();

writer.WriteFileHeader();
writer.WritePart(openXml, part);

context.AddSource(part.Name, sb.ToString());
}
}
}
37 changes: 0 additions & 37 deletions src/DocumentFormat.OpenXml/Features/ClassActivator{T}.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/DocumentFormat.OpenXml/Features/IPartFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ namespace DocumentFormat.OpenXml.Features;

internal interface IPartFactory
{
T Create<T>() where T : OpenXmlPart;
T? Create<T>() where T : OpenXmlPart;
}

This file was deleted.

17 changes: 0 additions & 17 deletions src/DocumentFormat.OpenXml/Features/ReflectionPartFactory.cs

This file was deleted.

4 changes: 2 additions & 2 deletions src/DocumentFormat.OpenXml/Features/TypedFeatures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ public static IFeatureCollection Shared

public int Revision => 0;

[KnownFeature(typeof(IRootElementFactory), typeof(ReflectionBasedRootElementFactory))]
[KnownFeature(typeof(IRootElementFactory), typeof(TypedRootElementFactory))]
[KnownFeature(typeof(IPartMetadataFeature), typeof(CachedPartMetadataProvider))]
[KnownFeature(typeof(IOpenXmlNamespaceResolver), typeof(OpenXmlNamespaceResolver))]
[KnownFeature(typeof(IPartFactory), typeof(ReflectionPartFactory))]
[KnownFeature(typeof(IPartFactory), typeof(TypedPartFactory))]
[DelegatedFeature(nameof(FeatureCollection.Default), typeof(FeatureCollection))]
[ThreadSafe]
public partial T? Get<T>();
Expand Down
27 changes: 27 additions & 0 deletions src/DocumentFormat.OpenXml/Features/TypedRootElementFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using DocumentFormat.OpenXml.Framework;
using DocumentFormat.OpenXml.Framework.Metadata;
using System;
using System.Diagnostics.CodeAnalysis;

namespace DocumentFormat.OpenXml.Features;

internal partial class TypedRootElementFactory : IRootElementFactory
{
private readonly Lazy<ElementFactoryCollection> _collection;

public TypedRootElementFactory()
{
_collection = new Lazy<ElementFactoryCollection>(() => new ElementFactoryCollection(GetAllRootElements()));
}

public ElementFactoryCollection Collection => _collection.Value;

public bool TryCreate(in OpenXmlQualifiedName qname, [NotNullWhen(true)] out OpenXmlElement? element)
{
element = _collection.Value.Create(in qname);
return element is not null;
}
}
11 changes: 10 additions & 1 deletion src/DocumentFormat.OpenXml/Packaging/OpenXmlPartContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1077,9 +1077,13 @@ internal T AddNewPartInternal<T>()
{
ThrowIfObjectDisposed();

// use reflection to create the instance. As the default constructor of part is not "public"
var part = Features.GetRequired<IPartFactory>().Create<T>();

if (part is null)
{
throw new OpenXmlPackageException(ExceptionMessages.AddedPartIsNotAllowed);
}

try
{
InitPart(part, part.ContentType);
Expand Down Expand Up @@ -1145,6 +1149,11 @@ internal T AddNewPartInternal<T>(string? contentType, string? id)
throw new ArgumentOutOfRangeException(nameof(T), ExceptionMessages.ExtendedPartNotAllowed);
}

if (part is null)
{
throw new OpenXmlPackageException(ExceptionMessages.AddedPartIsNotAllowed);
}

if (contentType is not null && part.IsContentTypeFixed && !string.Equals(contentType, part.ContentType, StringComparison.Ordinal))
{
throw new ArgumentOutOfRangeException(nameof(contentType), ExceptionMessages.ErrorContentType);
Expand Down
Loading

0 comments on commit e224ff5

Please sign in to comment.