-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
179 lines (150 loc) · 4.95 KB
/
Copy pathProgram.cs
File metadata and controls
179 lines (150 loc) · 4.95 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.SqlServer.TransactSql.ScriptDom;
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.Error.WriteLine("Usage: TsqlAstParser <sql-file> [output-json-file]");
return 1;
}
string sqlFile = args[0];
string outputFile = args.Length > 1 ? args[1] : "ast.json";
if (!File.Exists(sqlFile))
{
Console.Error.WriteLine($"Error: SQL file '{sqlFile}' not found.");
return 1;
}
string sql = File.ReadAllText(sqlFile);
var parser = new TSql160Parser(initialQuotedIdentifiers: true);
using var reader = new StringReader(sql);
var fragment = parser.Parse(reader, out var errors);
if (errors.Count > 0)
{
Console.Error.WriteLine("Parse errors:");
foreach (var error in errors)
{
Console.Error.WriteLine($" Line {error.Line}, Column {error.Column}: {error.Message}");
}
return 1;
}
var astConverter = new AstToJsonConverter();
var jsonObject = astConverter.Convert(fragment);
var options = new JsonSerializerOptions
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
string json = JsonSerializer.Serialize(jsonObject, options);
File.WriteAllText(outputFile, json);
Console.WriteLine($"AST written to {outputFile}");
return 0;
}
}
/// <summary>
/// Converts TSqlFragment AST nodes to JSON-serializable dictionaries
/// </summary>
class AstToJsonConverter
{
private readonly HashSet<object> _visited = new();
// Properties to skip during serialization (internal/infrastructure properties)
private static readonly HashSet<string> SkipProperties = new()
{
"ScriptTokenStream",
"FirstTokenIndex",
"LastTokenIndex",
"FragmentLength",
"StartOffset",
"StartLine",
"StartColumn"
};
public Dictionary<string, object?> Convert(TSqlFragment fragment)
{
_visited.Clear();
return ConvertNode(fragment);
}
private Dictionary<string, object?> ConvertNode(TSqlFragment node)
{
if (_visited.Contains(node))
{
return new Dictionary<string, object?> { ["$ref"] = node.GetType().Name };
}
_visited.Add(node);
var result = new Dictionary<string, object?>
{
["$type"] = node.GetType().Name
};
// Emit positional information for fragments that have real tokens.
// Synthesized fragments (no source tokens) have StartOffset == -1.
if (node.StartOffset >= 0)
{
result["StartOffset"] = node.StartOffset;
result["FragmentLength"] = node.FragmentLength;
result["StartLine"] = node.StartLine;
result["StartColumn"] = node.StartColumn;
}
var type = node.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in properties)
{
if (SkipProperties.Contains(prop.Name))
continue;
// Skip indexers
if (prop.GetIndexParameters().Length > 0)
continue;
try
{
var value = prop.GetValue(node);
var convertedValue = ConvertValue(value);
if (convertedValue != null)
{
result[prop.Name] = convertedValue;
}
}
catch
{
// Skip properties that throw exceptions
}
}
return result;
}
private object? ConvertValue(object? value)
{
if (value == null)
return null;
var type = value.GetType();
// Handle TSqlFragment nodes
if (value is TSqlFragment fragment)
{
return ConvertNode(fragment);
}
// Handle collections of TSqlFragment
if (value is System.Collections.IEnumerable enumerable && type != typeof(string))
{
var list = new List<object?>();
foreach (var item in enumerable)
{
var converted = ConvertValue(item);
if (converted != null)
{
list.Add(converted);
}
}
return list.Count > 0 ? list : null;
}
// Handle primitive types and enums
if (type.IsPrimitive || type.IsEnum || value is string || value is decimal)
{
if (type.IsEnum)
{
return value.ToString();
}
return value;
}
// For other complex types, just return the string representation
return value.ToString();
}
}