-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocumentAnalyzer.cs
More file actions
295 lines (264 loc) · 11.9 KB
/
Copy pathDocumentAnalyzer.cs
File metadata and controls
295 lines (264 loc) · 11.9 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Heddle.Data;
using Heddle.Helpers;
using Heddle.Language;
using Heddle.Runtime;
using Heddle.Strings.Core;
namespace Heddle.LanguageServices
{
/// <summary>
/// Drives the engine pipeline (parse → <c>HeddleCompiler.Compile</c> → optional Roslyn) directly (D9) and
/// projects the side channels into an immutable <see cref="DocumentAnalysis"/> (D10). Never uses
/// <c>HeddleTemplate</c> — the facade wants tokens/errors/warnings/scope map, not the render tree.
/// </summary>
internal sealed class DocumentAnalyzer
{
private static readonly Regex ImportRegex =
new Regex(@"@<<\s*\{\{(?<path>[^}]*)\}\}", RegexOptions.Compiled);
private static readonly Regex PartialRegex =
new Regex(@"@partial\s*\(\s*\)\s*\{\{(?<path>[^}]*)\}\}", RegexOptions.Compiled);
private readonly HeddleLanguageServiceOptions _options;
internal DocumentAnalyzer(HeddleLanguageServiceOptions options)
{
_options = options;
}
internal DocumentAnalysis Analyze(string path, string text, int version,
Heddle.Runtime.Expressions.FunctionRegistry functions, CancellationToken cancellationToken)
{
var templateOptions = BuildTemplateOptions(functions);
var compileContext = new CompileContext(templateOptions, (ExType)typeof(object));
var parseContext = DocumentParser.Parse(text, compileContext, out _);
cancellationToken.ThrowIfCancellationRequested();
var compileScope = new CompileScope(compileContext);
try
{
var runtimeDocument = HeddleCompiler.Compile(text, compileScope, parseContext, null);
runtimeDocument?.Dispose();
}
catch (Exception e)
{
compileContext.CompileErrors.Add(new HeddleCompileError
{
Error = "Internal analysis error: " + e.Message,
Position = default
});
}
cancellationToken.ThrowIfCancellationRequested();
bool csharpUsed = false;
if (templateOptions.ExpressionMode == ExpressionMode.FullCSharp &&
compileScope.CSharpContext.Methods.Count > 0)
{
try
{
ContextCompilation.Compile(compileScope);
}
catch (Exception e)
{
compileContext.CompileErrors.Add(new HeddleCompileError
{
Error = "C# tier compile error: " + e.Message,
Position = default
});
}
csharpUsed = true;
}
var namespaces = compileScope.CSharpContext.Namespaces;
var lineMap = new LineMap(text);
var diagnostics = ProjectDiagnostics(compileContext, parseContext);
var definitions = ProjectDefinitions(parseContext, path, namespaces);
var imports = ScanImports(text);
var scopes = new ScopeMapView(compileContext.ScopeMap, compileContext.RootScopeType);
return new DocumentAnalysis(path, version, text, lineMap,
parseContext.Tokens.ToList(), parseContext.SkippedTokens.ToList(),
diagnostics, definitions, imports, scopes, csharpUsed);
}
private TemplateOptions BuildTemplateOptions(Heddle.Runtime.Expressions.FunctionRegistry functions)
{
return new TemplateOptions
{
ProvideLanguageFeatures = true,
RootPath = string.IsNullOrEmpty(_options?.RootPath)
? AppContext.BaseDirectory
: _options.RootPath,
OutputProfile = _options?.OutputProfile ?? OutputProfile.Text,
ExpressionMode = _options?.ExpressionMode ?? ExpressionMode.Native,
FileNamePostfix = _options?.FileNamePostfix ?? string.Empty,
Functions = functions
};
}
private IReadOnlyList<HeddleDiagnostic> ProjectDiagnostics(CompileContext compileContext,
ParseContext parseContext)
{
var seen = new HashSet<HeddleCompileError>();
var result = new List<HeddleDiagnostic>();
void Add(HeddleCompileError entry)
{
if (entry == null || !seen.Add(entry))
return;
var severity = entry is HeddleCompileWarning
? HeddleDiagnosticSeverity.Warning
: HeddleDiagnosticSeverity.Error;
var fix = (entry as HeddleCompileWarning)?.Fix;
int offset = entry.Position.StartIndex;
int length = entry.Position.Length;
string message = entry.Error;
string importedFrom = null;
var origin = entry.ImportOrigin;
if (origin != null)
{
importedFrom = RenderPath(origin.Path);
offset = origin.Site.StartIndex;
length = 0;
message = $"imported '{importedFrom}': {entry.Error}";
}
result.Add(new HeddleDiagnostic(entry.DiagnosticId, message, fix, severity, offset, length,
importedFrom));
}
foreach (var error in compileContext.CompileErrors)
Add(error);
foreach (var warning in compileContext.CompileWarnings)
Add(warning);
foreach (var error in parseContext.Errors)
Add(error);
foreach (var warning in parseContext.Warnings)
Add(warning);
return result;
}
private IReadOnlyList<DefinitionInfo> ProjectDefinitions(ParseContext parseContext, string analyzedPath,
ICollection<string> namespaces)
{
var result = new List<DefinitionInfo>();
foreach (var pair in parseContext.DefinitionsBlock.Definitions)
{
var definition = pair.Value;
var sourcePath = definition.Context?.ImportOrigin?.Path ?? analyzedPath;
var modelTypeName = definition.ModelType;
ExType modelType = ResolveType(modelTypeName, namespaces);
bool isPinned = modelType != null && !modelType.IsDynamic && modelType.Type != typeof(object);
var props = FlattenProps(definition, namespaces);
var slotTypeName = FirstSlotType(definition);
var regions = ProjectRegions(definition, namespaces);
result.Add(new DefinitionInfo(definition.Name, sourcePath,
definition.Position.StartIndex, definition.Position.Length,
modelTypeName, isPinned ? modelType : null, isPinned, props, slotTypeName,
definition.BaseDefinition?.Name, regions));
}
return result;
}
private IReadOnlyList<PropInfo> FlattenProps(DefinitionItem definition, ICollection<string> namespaces)
{
// Inheritance flattening (phase 5 D6): the most-derived declaration of each prop name wins.
var byName = new Dictionary<string, PropInfo>(StringComparer.Ordinal);
for (var d = definition; d != null; d = d.BaseDefinition)
{
foreach (var declaration in d.PropDeclarations)
{
if (byName.ContainsKey(declaration.Name))
continue;
var type = ResolveType(declaration.TypeName, namespaces);
byName[declaration.Name] = new PropInfo(declaration.Name, declaration.TypeName, type,
!declaration.HasDefault, declaration.DefaultValue,
declaration.Position.StartIndex, declaration.Position.Length);
}
}
return byName.Values.ToList();
}
/// <summary>Phase 7 (WI5): projects the parse-model region declarations — the LSP reads the parse model,
/// it does not reimplement the region table.</summary>
private IReadOnlyList<RegionInfo> ProjectRegions(DefinitionItem definition, ICollection<string> namespaces)
{
if (definition.Regions == null || definition.Regions.Count == 0)
return Array.Empty<RegionInfo>();
var result = new List<RegionInfo>(definition.Regions.Count);
foreach (var region in definition.Regions)
{
result.Add(new RegionInfo(region.Name, region.IsPublic, region.TypeName,
ResolveType(region.TypeName, namespaces),
region.Position.StartIndex, region.Position.Length));
}
return result;
}
private static string FirstSlotType(DefinitionItem definition)
{
for (var d = definition; d != null; d = d.BaseDefinition)
{
if (!string.IsNullOrEmpty(d.SlotTypeName))
return d.SlotTypeName;
}
return null;
}
private static ExType ResolveType(string name, ICollection<string> namespaces)
{
if (string.IsNullOrWhiteSpace(name) || name == "object")
return null;
if (name == "dynamic")
return ExType.Dynamic;
try
{
var resolved = ReflectionHelper.ResolveType(name, namespaces ?? Array.Empty<string>());
return resolved != null ? new ExType(resolved) : null;
}
catch
{
return null;
}
}
private IReadOnlyList<ImportLink> ScanImports(string text)
{
var links = new List<ImportLink>();
foreach (Match match in ImportRegex.Matches(text))
links.Add(BuildLink(ImportLinkKind.Import, match));
foreach (Match match in PartialRegex.Matches(text))
links.Add(BuildLink(ImportLinkKind.Partial, match));
return links;
}
private ImportLink BuildLink(ImportLinkKind kind, Match match)
{
var raw = match.Groups["path"].Value.Trim();
string resolved = null;
try
{
var root = string.IsNullOrEmpty(_options?.RootPath) ? AppContext.BaseDirectory : _options.RootPath;
var candidate = kind == ImportLinkKind.Partial
? Path.Combine(root, raw + (_options?.FileNamePostfix ?? string.Empty))
: Path.Combine(root, raw);
if (File.Exists(candidate))
resolved = candidate;
}
catch
{
// ignore malformed paths — ResolvedPath stays null
}
return new ImportLink(kind, match.Index, match.Length, raw, resolved);
}
private string RenderPath(string path)
{
if (string.IsNullOrEmpty(path))
return path;
var root = _options?.RootPath;
if (!string.IsNullOrEmpty(root))
{
try
{
var full = Path.GetFullPath(path);
var rootFull = Path.GetFullPath(root);
if (full.StartsWith(rootFull, StringComparison.OrdinalIgnoreCase))
{
var rel = full.Substring(rootFull.Length).TrimStart('/', '\\');
return rel.Replace('\\', '/');
}
}
catch
{
// fall through to absolute
}
}
return path.Replace('\\', '/');
}
}
}