Skip to content

Instantly share code, notes, and snippets.

@jozefizso
Created February 9, 2022 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jozefizso/0a0d32ed598552b37e5f149fac081e6e to your computer and use it in GitHub Desktop.
Save jozefizso/0a0d32ed598552b37e5f149fac081e6e to your computer and use it in GitHub Desktop.
NetOffice code gen
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Xml;
using System.Xml.Linq;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
var srcDir = @"d:\dev\github\NetOfficeFw\Data2\src\";
var destDir = @"d:\dev\github\NetOfficeFw\docgen\out\";
var lib = XDocument.Load(Path.Combine(srcDir, @"Word\DispatchInterfaces.xml"));
using var sw = new StreamWriter(Path.Combine(destDir, "Word.cs"));
var ns = NamespaceDeclaration(ParseName("NetOffice.Word"));
var interfaces = lib.Root.Elements("Interface");
foreach (var iface in interfaces)
{
ProcessInterface(iface, ref ns);
}
ns.NormalizeWhitespace().WriteTo(sw);
void ProcessInterface(XElement i, ref NamespaceDeclarationSyntax ns)
{
var name = i.Attribute("Name").Value;
int.TryParse(i.Attribute("TypeLibType").Value, out var typeLibType);
Console.WriteLine($"Interface {name}");
var cls = InterfaceDeclaration(Identifier(name));
cls = cls.AddAttributeLists(AttributeList(
SingletonSeparatedList(
Attribute(
IdentifierName("TypeLibType"),
AttributeArgumentList(SeparatedList(new[] { AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(typeLibType))) }))
)
)
));
//var field = FieldDeclaration(VariableDeclaration(ParseTypeName("int"), SeparatedList(VariableDeclarator(Identifier("_typeLibType")))));
var methods = i.Element("Methods").Elements("Method");
foreach (var method in methods)
{
ProcessMethod(method, ref cls);
}
ns = ns.AddMembers(cls);
}
void ProcessMethod(XElement m, ref InterfaceDeclarationSyntax cls)
{
var name = m.Attribute("Name").Value;
int.TryParse(m.Element("DispIds")?.Element("DispId")?.Attribute("Id")?.Value, out var dispId);
Console.WriteLine($" method {name}");
var returnType = ParseTypeName("void");
var elmReturnValue = m.Element("Parameters")?.Element("ReturnValue");
if (elmReturnValue != null)
{
returnType = ParseTypeName(elmReturnValue.Attribute("Type").Value);
}
var method = MethodDeclaration(
List<AttributeListSyntax>(new[] {
AttributeList(
SingletonSeparatedList(
Attribute(
IdentifierName("DispId"),
AttributeArgumentList(SeparatedList(new[] { AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(dispId))) }))
)
)
)
}),
TokenList(),
returnType,
null,
Identifier(name),
null,
ParameterList(),
List<TypeParameterConstraintClauseSyntax>(),
null,
Token(SyntaxKind.SemicolonToken)
);
cls = cls.AddMembers(method);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment