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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
|
using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.RepresentationModel;
using System.Linq;
using MonoDevelop.Ide.Editor.Highlighting.RegexEngine;
using System.Collections.Immutable;
using MonoDevelop.Core;
using System.IO.Compression;
using System.Threading.Tasks;
using System.Threading;
using MonoDevelop.Core.Text;
using Microsoft.CodeAnalysis.Execution;
namespace MonoDevelop.Ide.Editor.Highlighting
{
[Obsolete ("Use the Microsoft.VisualStudio.Text APIs")]
public class SyntaxHighlighting : ISyntaxHighlighting
{
readonly SyntaxHighlightingDefinition definition;
public IReadonlyTextDocument Document {
get;
set;
}
internal SyntaxHighlightingDefinition Definition {
get {
return definition;
}
}
public SyntaxHighlighting (SyntaxHighlightingDefinition definition, IReadonlyTextDocument document)
{
this.definition = definition ?? throw new ArgumentNullException (nameof (definition));
Document = document;
if (document is ITextDocument)
((ITextDocument)document).TextChanged += Handle_TextChanged;
}
public void Dispose()
{
if (Document is ITextDocument)
((ITextDocument)Document).TextChanged -= Handle_TextChanged;
}
async void Handle_TextChanged (object sender, Core.Text.TextChangeEventArgs e)
{
for (int i = 0; i < e.TextChanges.Count; ++i) {
var change = e.TextChanges[i];
var ln = Document.OffsetToLineNumber (change.NewOffset);
if (ln >= stateCache.Count)
continue;
var line = Document.GetLineByOffset (change.NewOffset);
var lastState = GetState (line);
var high = new Highlighter (this, lastState);
await high.GetColoredSegments (Document, line.Offset, line.LengthIncludingDelimiter);
OnHighlightingStateChanged (new LineEventArgs (line));
stateCache.RemoveRange (ln - 1, stateCache.Count - ln + 1);
}
}
public Task<HighlightedLine> GetHighlightedLineAsync (IDocumentLine line, CancellationToken cancellationToken)
{
if (Document == null) {
return DefaultSyntaxHighlighting.Instance.GetHighlightedLineAsync (line, cancellationToken);
}
var snapshot = Document.CreateSnapshot ();
var high = new Highlighter (this, GetState (line));
int offset = line.Offset;
int length = line.Length;
//return Task.Run (async delegate {
return high.GetColoredSegments (snapshot, offset, length);
//});
}
public async Task<ScopeStack> GetScopeStackAsync (int offset, CancellationToken cancellationToken)
{
var line = Document.GetLineByOffset (offset);
var state = GetState (line);
var lineOffset = line.Offset;
if (lineOffset == offset) {
return state.ScopeStack;
}
var high = new Highlighter (this, state);
foreach (var seg in (await high.GetColoredSegments (Document, lineOffset, line.Length)).Segments) {
if (seg.Contains (offset - lineOffset))
return seg.ScopeStack;
}
return high.State.ScopeStack;
}
List<HighlightState> stateCache = new List<HighlightState> ();
HighlightState GetState (IDocumentLine line)
{
var pl = line?.PreviousLine;
if (pl == null)
return HighlightState.CreateNewState (this);
if (stateCache.Count == 0)
stateCache.Add (HighlightState.CreateNewState (this));
var ln = line.LineNumber;
if (ln <= stateCache.Count) {
return stateCache [ln - 1].Clone ();
}
var lastState = stateCache [stateCache.Count - 1];
var cur = Document.GetLine (stateCache.Count);
if (cur != null && cur.Offset < line.Offset) {
do {
var high = new Highlighter (this, lastState.Clone ());
high.GetColoredSegments (Document, cur.Offset, cur.LengthIncludingDelimiter).Wait ();
stateCache.Add (lastState = high.State);
cur = cur.NextLine;
} while (cur != null && cur.Offset < line.Offset);
}
return lastState.Clone ();
}
class HighlightState : IEquatable<HighlightState>
{
public ImmutableStack<SyntaxContext> ContextStack;
public ImmutableStack<SyntaxMatch> MatchStack;
public ScopeStack ScopeStack;
public static HighlightState CreateNewState (SyntaxHighlighting highlighting)
{
if (highlighting == null)
throw new ArgumentNullException (nameof (highlighting));
var definition = highlighting.definition;
if (definition == null)
throw new NullReferenceException ("HighlightState.CreateNewState null reference exception highlighting.definition == null.");
return new HighlightState {
ContextStack = ImmutableStack<SyntaxContext>.Empty.Push (definition.MainContext),
ScopeStack = new ScopeStack (definition.Scope),
MatchStack = ImmutableStack<SyntaxMatch>.Empty
};
}
internal HighlightState Clone ()
{
return new HighlightState {
ContextStack = this.ContextStack,
ScopeStack = this.ScopeStack,
MatchStack = this.MatchStack
};
}
public bool Equals (HighlightState other)
{
return ContextStack.SequenceEqual (other.ContextStack) && ScopeStack.SequenceEqual (other.ScopeStack) && MatchStack.SequenceEqual (other.MatchStack);
}
}
class Highlighter
{
HighlightState state;
SyntaxHighlighting highlighting;
ImmutableStack<SyntaxContext> ContextStack { get { return state.ContextStack; } set { state.ContextStack = value; } }
ImmutableStack<SyntaxMatch> MatchStack { get { return state.MatchStack; } set { state.MatchStack = value; } }
ScopeStack ScopeStack { get { return state.ScopeStack; } set { state.ScopeStack = value; } }
public HighlightState State {
get {
return state;
}
}
public Highlighter (SyntaxHighlighting highlighting, HighlightState state)
{
this.highlighting = highlighting;
this.state = state;
}
static readonly TimeSpan matchTimeout = TimeSpan.FromMilliseconds (500);
const int maxLineLength = 1 << 16;
public Task<HighlightedLine> GetColoredSegments (ITextSource text, int startOffset, int length)
{
if (ContextStack.IsEmpty || length > maxLineLength)
return Task.FromResult (new HighlightedLine (new TextSegment (startOffset, length), new [] { new ColoredSegment (0, length, ScopeStack.Empty) }));
SyntaxContext currentContext = null;
Match match = null;
SyntaxMatch curMatch = null;
var segments = new List<ColoredSegment> ();
int offset = 0;
int curSegmentOffset = 0;
int endOffset = offset + length;
int lastMatch = -1;
var highlightedSegment = new TextSegment (startOffset, length);
string lineText = text.GetTextAt (startOffset, length);
var initialState = state.Clone ();
int timeoutOccursAt;
unchecked {
timeoutOccursAt = Environment.TickCount + (int)matchTimeout.TotalMilliseconds;
}
restart:
if (offset >= lineText.Length)
goto end;
lastMatch = offset;
currentContext = ContextStack.Peek ();
match = null;
curMatch = null;
foreach (var m in currentContext.Matches) {
if (m.GotTimeout)
continue;
var r = m.GetRegex ();
if (r == null)
continue;
try {
Match possibleMatch;
if (r.pattern == "(?<=\\})" && offset > 0) { // HACK to fix typescript highlighting.
possibleMatch = r.Match (lineText, offset - 1, length, matchTimeout);
} else {
possibleMatch = r.Match (lineText, offset, length, matchTimeout);
}
if (possibleMatch.Success) {
if (match == null || possibleMatch.Index < match.Index) {
match = possibleMatch;
curMatch = m;
// Console.WriteLine (match.Index + " possible match : " + m + "/" + possibleMatch.Index + "-" + possibleMatch.Length);
} else {
// Console.WriteLine (match.Index + " skip match : " + m + "/" + possibleMatch.Index + "-" + possibleMatch.Length);
}
} else {
// Console.WriteLine ("fail match : " + m);
}
} catch (RegexMatchTimeoutException) {
LoggingService.LogWarning ("Warning: Regex " + m.Match + " timed out on line:" + text.GetTextAt (offset, length));
m.GotTimeout = true;
continue;
}
}
if (length <= 0 && curMatch == null)
goto end;
if (Environment.TickCount >= timeoutOccursAt) {
if (curMatch != null)
curMatch.GotTimeout = true;
goto end;
}
if (match != null) {
// Console.WriteLine (match.Index + " taken match : " + curMatch + "/" + match.Index + "-" + match.Length);
var matchEndOffset = match.Index + match.Length;
if (curSegmentOffset < match.Index && match.Length > 0) {
segments.Add (new ColoredSegment (curSegmentOffset, match.Index - curSegmentOffset, ScopeStack));
curSegmentOffset = match.Index;
}
if (curMatch.Pop) {
PopMetaContentScopeStack (currentContext, curMatch);
}
PushScopeStack (curMatch.Scope);
if (curMatch.Captures.Groups.Count > 0) {
for (int i = 0; i < curMatch.Captures.Groups.Count; ++i) {
var capture = curMatch.Captures.Groups[i];
var grp = match.Groups [capture.Item1];
if (grp == null || grp.Length == 0)
continue;
if (curSegmentOffset < grp.Index) {
ReplaceSegment (segments, new ColoredSegment (curSegmentOffset, grp.Index - curSegmentOffset, ScopeStack));
}
ReplaceSegment (segments, new ColoredSegment (grp.Index, grp.Length, ScopeStack.Push (capture.Item2)));
curSegmentOffset = Math.Max (curSegmentOffset, grp.Index + grp.Length);
}
}
if (curMatch.Captures.NamedGroups.Count > 0) {
for (int i = 0; i < curMatch.Captures.NamedGroups.Count; ++i) {
var capture = curMatch.Captures.NamedGroups[i];
var grp = match.Groups [capture.Item1];
if (grp == null || grp.Length == 0)
continue;
if (curSegmentOffset < grp.Index) {
ReplaceSegment (segments, new ColoredSegment (curSegmentOffset, grp.Index - curSegmentOffset, ScopeStack));
}
ReplaceSegment (segments, new ColoredSegment (grp.Index, grp.Length, ScopeStack.Push (capture.Item2)));
curSegmentOffset = grp.Index + grp.Length;
}
}
if (curMatch.Scope.Count > 0 && curSegmentOffset < matchEndOffset && match.Length > 0) {
segments.Add (new ColoredSegment (curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
curSegmentOffset = matchEndOffset;
}
if (curMatch.Pop) {
if (matchEndOffset - curSegmentOffset > 0)
segments.Add (new ColoredSegment (curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
//if (curMatch.Scope != null)
// scopeStack = scopeStack.Pop ();
PopStack (currentContext, curMatch);
curSegmentOffset = matchEndOffset;
} else if (curMatch.Set != null) {
// if (matchEndOffset - curSegmentOffset > 0)
// segments.Add (new ColoredSegment (curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
//if (curMatch.Scope != null)
// scopeStack = scopeStack.Pop ();
PopMetaContentScopeStack (currentContext, curMatch);
PopStack (currentContext, curMatch);
//curSegmentOffset = matchEndOffset;
var nextContexts = curMatch.Set.GetContexts (currentContext);
PushStack (curMatch, nextContexts);
goto skip;
} else if (curMatch.Push != null) {
var nextContexts = curMatch.Push.GetContexts (currentContext);
PushStack (curMatch, nextContexts);
} else {
if (curMatch.Scope.Count > 0) {
for (int i = 0; i < curMatch.Scope.Count; i++)
ScopeStack = ScopeStack.Pop ();
}
}
if (curSegmentOffset < matchEndOffset && match.Length > 0) {
segments.Add (new ColoredSegment (curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
curSegmentOffset = matchEndOffset;
}
skip:
length -= curSegmentOffset - offset;
offset = curSegmentOffset;
goto restart;
}
end:
if (endOffset - curSegmentOffset > 0) {
segments.Add (new ColoredSegment (curSegmentOffset, endOffset - curSegmentOffset, ScopeStack));
}
return Task.FromResult (new HighlightedLine (highlightedSegment, segments) {
IsContinuedBeyondLineEnd = !initialState.Equals (state)
});
}
void PushStack (SyntaxMatch curMatch, IEnumerable<SyntaxContext> nextContexts)
{
if (nextContexts != null) {
bool first = true;
foreach (var nextContext in nextContexts) {
var ctx = nextContext;
if (curMatch.WithPrototype != null)
ctx = new SyntaxContextWithPrototype (nextContext, curMatch.WithPrototype);
if (first) {
MatchStack = MatchStack.Push (curMatch);
first = false;
} else {
MatchStack = MatchStack.Push (null);
}
ContextStack = ContextStack.Push (ctx);
PushScopeStack (ctx.MetaScope);
PushScopeStack (ctx.MetaContentScope);
}
}
}
void PushScopeStack (IReadOnlyList<string> scopeList)
{
if (scopeList == null)
return;
for (int i = 0; i < scopeList.Count; ++i) {
var scope = scopeList[i];
ScopeStack = ScopeStack.Push (scope);
}
}
void PopScopeStack (IReadOnlyList<string> scopeList)
{
if (scopeList == null)
return;
for (int i = 0; !ScopeStack.IsEmpty && i < scopeList.Count; i++)
ScopeStack = ScopeStack.Pop ();
}
void PopMetaContentScopeStack (SyntaxContext currentContext, SyntaxMatch curMatch)
{
if (ContextStack.Count () == 1) {
return;
}
PopScopeStack (currentContext.MetaContentScope);
}
void PopStack (SyntaxContext currentContext, SyntaxMatch curMatch)
{
if (ContextStack.Count () == 1) {
MatchStack = MatchStack.Clear ();
ScopeStack = new ScopeStack (highlighting.definition.Scope);
return;
}
ContextStack = ContextStack.Pop ();
if (!MatchStack.IsEmpty) {
PopScopeStack (MatchStack.Peek ()?.Scope);
MatchStack = MatchStack.Pop ();
}
PopScopeStack (currentContext.MetaScope);
if (curMatch.Scope.Count > 0 && !ScopeStack.IsEmpty) {
for (int i = 0; i < curMatch.Scope.Count; i++)
ScopeStack = ScopeStack.Pop ();
}
}
}
internal static void ReplaceSegment (List<ColoredSegment> list, ColoredSegment newSegment)
{
if (list.Count == 0) {
list.Add (newSegment);
return;
}
int i = list.Count;
while (i > 0 && list [i - 1].EndOffset > newSegment.Offset) {
i--;
}
if (i >= list.Count) {
list.Add (newSegment);
return;
}
int j = i;
while (j + 1 < list.Count && newSegment.EndOffset > list [j + 1].Offset) {
j++;
}
var startItem = list [i];
var endItem = list [j];
list.RemoveRange (i, j - i + 1);
var lengthAfter = endItem.EndOffset - newSegment.EndOffset;
if (lengthAfter > 0)
list.Insert (i, new ColoredSegment (newSegment.EndOffset, lengthAfter, endItem.ScopeStack));
list.Insert (i, newSegment);
var lengthBefore = newSegment.Offset - startItem.Offset;
if (lengthBefore > 0)
list.Insert (i, new ColoredSegment (startItem.Offset, lengthBefore, startItem.ScopeStack));
}
void OnHighlightingStateChanged (LineEventArgs e)
{
HighlightingStateChanged?.Invoke (this, e);
}
public event EventHandler<LineEventArgs> HighlightingStateChanged;
}
}
|