forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSharpNamespaceParser.cs
More file actions
359 lines (316 loc) · 13.5 KB
/
Copy pathCSharpNamespaceParser.cs
File metadata and controls
359 lines (316 loc) · 13.5 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
namespace UnityEditor.Scripting.ScriptCompilation
{
internal class IllegalNamespaceParsing : Exception
{
public IllegalNamespaceParsing(string className, Exception cause)
: base($"Searching for classname: '{className}' caused error in CSharpNameParser", cause)
{
}
}
internal class UnsupportedDefineExpression : Exception
{
public UnsupportedDefineExpression(string message) : base(message) {}
}
internal static class CSharpNamespaceParser
{
static readonly Regex k_ReDefineExpr = new Regex(@"r'\s+|([=!]=)\s*(true|false)|([_a-zA-Z][_a-zA-Z0-9]*)|([()!]|&&|\|\|)", RegexOptions.Compiled);
static readonly Regex k_BlockComments = new Regex(@"((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))", RegexOptions.Compiled);
static readonly Regex k_LineComments = new Regex(@"//.*?\n", RegexOptions.Compiled);
static readonly Regex k_Strings = new Regex(@"""((\\[^\n]|[^""\n])*)""", RegexOptions.Compiled);
static readonly Regex k_VerbatimStrings = new Regex(@"@(""[^""]*"")+", RegexOptions.Compiled);
static readonly Regex k_NewlineRegex = new Regex("\r\n?", RegexOptions.Compiled);
static readonly Regex k_SingleQuote = new Regex(@"((?<![\\])['])(?:.(?!(?<![\\])\1))*.?\1", RegexOptions.Compiled);
static readonly Regex k_ConditionalCompilation = new Regex(@"[\t ]*#[\t ]*(if|else|elif|endif|define|undef)([\t !(]+[^/\n]*)?", RegexOptions.Compiled);
static string s_ClassName;
public static string GetNamespace(string sourceCode, string className, params string[] defines)
{
s_ClassName = className;
sourceCode = k_NewlineRegex.Replace(sourceCode, "\n");
sourceCode = k_SingleQuote.Replace(sourceCode, "");
sourceCode = k_Strings.Replace(sourceCode, "");
sourceCode = k_BlockComments.Replace(sourceCode, "");
sourceCode = k_LineComments.Replace(sourceCode, "\n");
sourceCode = k_VerbatimStrings.Replace(sourceCode, "");
try
{
sourceCode = RemoveUnusedDefines(sourceCode, defines.ToList());
return FindNamespaceForMono(className, sourceCode);
}
catch (Exception e)
{
throw new IllegalNamespaceParsing(className, e);
}
}
static string FindNamespaceForMono(string className, string source)
{
source = FixBraces(source);
var split = source.Split(new[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
var parent = new Node { Name = "-1" };
var builder = new StringBuilder(source.Length);
var buildingNode = false;
var buildingClass = false;
var level = 0;
var resNamespace = "";
foreach (var token in split)
{
switch (token)
{
case "{":
if (buildingNode)
{
parent = AddCurrent(level, builder.ToString(), parent);
builder = new StringBuilder();
buildingNode = false;
}
level++;
break;
case "}":
if (parent.Level > --level)
{
parent = parent.Parent;
builder.Clear();
}
break;
case "class":
buildingClass = true;
buildingNode = true;
break;
case "namespace":
buildingNode = true;
break;
default:
if (buildingNode)
{
var strippedClassname = StripClassName(token);
if (buildingClass && strippedClassname.Equals(className))
{
buildingClass = false;
resNamespace = CollectNamespace(parent);
}
else
{
builder.Append(token);
}
}
break;
}
}
return resNamespace;
}
static string StripClassName(string classname)
{
var strippedClassname = classname.Contains(":") ? classname.Split(':')[0] : classname;
strippedClassname = strippedClassname.StartsWith("@") ? strippedClassname.Split('@')[1] : strippedClassname;
return strippedClassname;
}
static string FixBraces(string sourceCode)
{
var stringBuilder = new StringBuilder(sourceCode.Length * 2);
var lastChar = '-';
foreach (var c in sourceCode.ToCharArray())
{
if ((c == '{' || c == '}') && (lastChar != '\n' || lastChar != ' '))
stringBuilder.Append(' ');
if ((lastChar == '{' || lastChar == '}') && (c != '\n' || c != ' '))
stringBuilder.Append(' ');
stringBuilder.Append(c);
lastChar = c;
}
return stringBuilder.ToString();
}
static string CollectNamespace(Node parent)
{
var list = new List<string>();
for (var par = parent; par.Name != "-1"; par = par.Parent) { list.Add(par.Name); }
if (list.Count == 0) return "";
list.Reverse();
return list.Aggregate((a, b) => a + "." + b);
}
static Node AddCurrent(int level, string s, Node parent)
{
return new Node { Level = level + 1, Name = s, Parent = parent };
}
class Node
{
public int Level;
public string Name;
public Node Parent;
}
static string RemoveUnusedDefines(string source, List<string> defines)
{
var stack = new Stack<Tuple<bool, bool>>();
var split = source.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
var longest = split.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur);
var stringBuilder = new StringBuilder(split.Length * longest.Length);
foreach (var s in split)
{
if (s.IndexOf("#", StringComparison.Ordinal) < 0)
{
if (stack.Count == 0 || stack.Peek().Item1)
{
stringBuilder.Append(s).Append("\n");
}
continue;
}
var match = k_ConditionalCompilation.Match(s);
var directive = match.Groups[1].Value;
if (directive == "else")
{
var elseEmitting = stack.Peek().Item2;
stack.Pop();
stack.Push(new Tuple<bool, bool>(elseEmitting, false));
continue;
}
if (directive == "endif")
{
stack.Pop();
continue;
}
var arg = match.Groups[2].Value.Trim();
if (directive.Length > 0 && arg.Length == 0)
{
throw new UnsupportedDefineExpression(s);
}
if (directive == "define")
{
if (!defines.Contains(arg) && (stack.Count == 0 || stack.Peek().Item1))
{
defines.Add(arg);
}
}
else if (directive == "undefine")
{
if (stack.Count == 0 || stack.Peek().Item1)
{
defines.Remove(arg);
}
}
else if (directive == "if")
{
var evalResult = EvaluateDefine(arg.Trim(), defines);
var isEmitting = stack.Count == 0 || stack.Peek().Item1;
stack.Push(new Tuple<bool, bool>(isEmitting && evalResult, isEmitting && !evalResult));
}
else if (directive == "elif")
{
var evalResult = EvaluateDefine(arg, defines);
var elseEmitting = stack.Peek().Item2;
stack.Pop();
stack.Push(new Tuple<bool, bool>(elseEmitting && evalResult, elseEmitting && !evalResult));
}
}
return stringBuilder.ToString();
}
static bool IsNullOrWhiteSpace(string value)
{
return value == null || value.All(char.IsWhiteSpace);
}
public static bool EvaluateDefine(string expr, ICollection<string> defines)
{
var res = new List<string>();
var pos = 0;
while (pos < expr.Length)
{
var match = k_ReDefineExpr.Match(expr, pos); // eq_operator, bool_val, symbol, operator
// TODO: C# 4.0+ Replace with string.IsNullOrWhiteSpace when available
if (IsNullOrWhiteSpace(expr.Substring(pos)))
break;
if (!match.Success)
throw new InvalidOperationException($"Error while searching for {s_ClassName}: invalid #ifdef expression: {expr} (error while searching for {expr.Substring(pos)}");
pos = match.Index + match.Length;
if (match.Groups[1].Success)
res.Add(match.Groups[1].Value + (match.Groups[2].Value == "true").ToString().ToLower());
else if (match.Groups[3].Value == "true" || match.Groups[3].Value == "false")
res.Add((match.Groups[3].Value == "true").ToString().ToLower());
else if (match.Groups[3].Success)
res.Add(defines.Contains(match.Groups[3].Value).ToString().ToLower());
else if (match.Groups[4].Success)
res.Add(match.Groups[4].Value);
}
try
{
return EvaluateBooleanExpression(string.Join(" ", res.ToArray()));
}
catch (InvalidOperationException)
{
throw new UnsupportedDefineExpression($"{expr}: caused an error in CSharpNamespaceParser");
}
}
static bool EvaluateBooleanExpression(string expression)
{
expression = expression.Replace("&&", "&").Replace("||", "|").Replace("==", "=");
expression = expression.Replace("true", "1").Replace("false", "0");
expression = expression.Replace(" ", string.Empty);
return EvaluateBool(expression);
}
static bool EvaluateBool(string expression)
{
var tokens = expression.ToCharArray();
var values = new Stack<bool>();
var ops = new Stack<char>();
foreach (var token in tokens)
{
if (token == '0' || token == '1') values.Push(token == '1');
else if (token == '(') ops.Push(token);
else if (token == ')')
{
for (var nextOp = ops.Pop(); nextOp != '('; nextOp = ops.Pop())
values.Push(ApplyOp(nextOp, values));
}
else if (token == '&' || token == '|' || token == '!' || token == '=')
{
while (ops.Count != 0 && HasPrecedence(token, ops.Peek()))
{
values.Push(ApplyOp(ops.Pop(), values));
}
ops.Push(token);
}
}
while (ops.Count != 0)
{
values.Push(ApplyOp(ops.Pop(), values));
}
return values.Pop();
}
static bool ApplyOp(char op, Stack<bool> values)
{
var val1 = values.Pop();
switch (op)
{
case '&':
{
var val2 = values.Pop();
return val1 && val2;
}
case '|':
{
var val2 = values.Pop();
return val1 || val2;
}
case '!': return !val1;
case '=': return val1 == values.Pop();
default:
throw new NotImplementedException($"{op}: unrecognized operator");
}
}
/// <returns>Returns whether 'op2' has higher or same precedence as 'op1'.</returns>
static bool HasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')') return false;
if (op1 == '!' && op2 == '&') return false;
if (op1 == '!' && op2 == '|') return false;
if (op1 == '&' && op2 == '|') return false;
if (op1 == '=') return false;
return true;
}
}
}