This repository was archived by the owner on Jul 10, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathStructVisitor.cs
95 lines (75 loc) · 3.12 KB
/
StructVisitor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
namespace ClangSharpPInvokeGenerator
{
using System;
using System.Collections.Generic;
using System.IO;
using ClangSharp;
internal sealed class StructVisitor : ICXCursorVisitor
{
private readonly ISet<string> visitedStructs = new HashSet<string>();
private readonly TextWriter tw;
private int indentLevel = 1;
private int fieldPosition;
private const int indentMultiplier = 4;
public StructVisitor(TextWriter tw)
{
this.tw = tw;
}
public CXChildVisitResult Visit(CXCursor cursor, CXCursor parent, IntPtr data)
{
if (cursor.IsInSystemHeader())
{
return CXChildVisitResult.CXChildVisit_Continue;
}
CXCursorKind curKind = clang.getCursorKind(cursor);
if (curKind == CXCursorKind.CXCursor_StructDecl)
{
this.fieldPosition = 0;
var structName = clang.getCursorSpelling(cursor).ToString();
// struct names can be empty, and so we visit its sibling to find the name
if (string.IsNullOrEmpty(structName))
{
var forwardDeclaringVisitor = new ForwardDeclarationVisitor(cursor);
clang.visitChildren(clang.getCursorSemanticParent(cursor), forwardDeclaringVisitor.Visit, new CXClientData(IntPtr.Zero));
structName = clang.getCursorSpelling(forwardDeclaringVisitor.ForwardDeclarationCursor).ToString();
if (string.IsNullOrEmpty(structName))
{
structName = "_";
}
}
if (!this.visitedStructs.Contains(structName))
{
this.IndentedWriteLine("public partial struct " + structName);
this.IndentedWriteLine("{");
this.indentLevel++;
clang.visitChildren(cursor, this.Visit, new CXClientData(IntPtr.Zero));
this.indentLevel--;
this.IndentedWriteLine("}");
this.tw.WriteLine();
this.visitedStructs.Add(structName);
}
return CXChildVisitResult.CXChildVisit_Continue;
}
if (curKind == CXCursorKind.CXCursor_FieldDecl)
{
var fieldName = clang.getCursorSpelling(cursor).ToString();
if (string.IsNullOrEmpty(fieldName))
{
fieldName = "field" + this.fieldPosition; // what if they have fields called field*? :)
}
this.fieldPosition++;
this.IndentedWriteLine(cursor.ToMarshalString(fieldName));
return CXChildVisitResult.CXChildVisit_Continue;
}
return CXChildVisitResult.CXChildVisit_Recurse;
}
private void IndentedWriteLine(string s)
{
for (int i = 0; i < indentMultiplier * indentLevel; ++i)
{
this.tw.Write(" ");
}
this.tw.WriteLine(s);
}
}
}