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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
|
//***************************************************************************
// Copyright © 2010 Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//***************************************************************************
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Shapes;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Dafny = Microsoft.Dafny;
namespace DafnyLanguage
{
#region Provider
[Export(typeof(ITaggerProvider))]
[ContentType("dafny")]
[TagType(typeof(IDafnyResolverTag))]
internal sealed class ResolverTaggerProvider : ITaggerProvider
{
[Import(typeof(Microsoft.VisualStudio.Shell.SVsServiceProvider))]
internal IServiceProvider _serviceProvider = null;
[Import]
ITextDocumentFactoryService _textDocumentFactory = null;
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag
{
// create a single tagger for each buffer.
Func<ITagger<T>> sc = delegate() { return new ResolverTagger(buffer, _serviceProvider, _textDocumentFactory) as ITagger<T>; };
return buffer.Properties.GetOrCreateSingletonProperty<ITagger<T>>(sc);
}
}
#endregion
#region Tagger
#region Tags
public interface IDafnyResolverTag : ITag
{
}
public class DafnyErrorResolverTag : ErrorTag, IDafnyResolverTag
{
public DafnyError Error { get; private set; }
public DafnyErrorResolverTag(DafnyError error)
: base(ConvertToErrorType(error), error.Message)
{
Error = error;
}
private static string ConvertToErrorType(DafnyError err)
{
string ty; // the COLORs below indicate what I see on my machine
switch (err.Category)
{
default: // unexpected category
case ErrorCategory.ParseError:
case ErrorCategory.ParseWarning:
ty = "syntax error"; break; // COLOR: red
case ErrorCategory.ResolveError:
ty = "compiler error"; break; // COLOR: blue
case ErrorCategory.VerificationError:
ty = "error"; break; // COLOR: red
case ErrorCategory.AuxInformation:
ty = "other error"; break; // COLOR: purple red
case ErrorCategory.InternalError:
ty = "error"; break; // COLOR: red
}
return ty;
}
}
public class DafnyErrorStateResolverTag : IDafnyResolverTag
{
public readonly DafnyError Error;
public readonly ITrackingSpan Span;
public readonly int Id;
public readonly string Description;
public DafnyErrorStateResolverTag(DafnyError error, ITrackingSpan span, int id, string description)
{
Error = error;
Span = span;
Id = id;
Description = description;
}
}
public class DafnySuccessResolverTag : IDafnyResolverTag
{
public readonly Dafny.Program Program;
public DafnySuccessResolverTag(Dafny.Program program)
{
Program = program;
}
}
#endregion
/// <summary>
/// Translate PkgDefTokenTags into ErrorTags and Error List items
/// </summary>
public sealed class ResolverTagger : ITagger<IDafnyResolverTag>, IDisposable
{
readonly ITextBuffer _buffer;
readonly ITextDocument _document;
ErrorListProvider _errorProvider;
private bool m_disposed;
// The 'Snapshot' and 'Program' fields should be updated and read together, so they are protected by "this"
public ITextSnapshot Snapshot; // may be null
public Dafny.Program Program; // non-null only if the snapshot contains a Dafny program that type checks
List<DafnyError> _resolutionErrors = new List<DafnyError>(); // if nonempty, then _snapshot is the snapshot from which the errors were produced
internal void AddError(DafnyError error, string unitId, string requestId)
{
ErrorContainer entry;
if (_verificationErrors.TryGetValue(unitId, out entry))
{
lock (entry)
{
if (entry.RequestId == null || new DateTime(long.Parse(entry.RequestId)) < new DateTime(long.Parse(requestId)))
{
entry.Errors.Clear();
entry.RequestId = requestId;
}
}
entry.Errors.Push(error);
UpdateErrorList(Snapshot);
}
}
string MostRecentRequestId;
internal void ReInitializeVerificationErrors(string mostRecentRequestId, List<Microsoft.Boogie.Declaration> units)
{
var implNames = units.OfType<Microsoft.Boogie.Implementation>().Select(impl => impl.Name);
lock (this)
{
MostRecentRequestId = mostRecentRequestId;
var outOfDatekeys = _verificationErrors.Keys.Except(implNames);
foreach (var key in outOfDatekeys)
{
ErrorContainer oldError;
_verificationErrors.TryRemove(key, out oldError);
}
var newKeys = implNames.Except(_verificationErrors.Keys).ToList();
newKeys.Add("$$program$$");
foreach (var key in newKeys)
{
_verificationErrors.TryAdd(key, new ErrorContainer());
}
}
}
public class ErrorContainer
{
internal string RequestId;
internal ConcurrentStack<DafnyError> Errors = new ConcurrentStack<DafnyError>();
}
public readonly ConcurrentDictionary<string, ErrorContainer> _verificationErrors = new ConcurrentDictionary<string, ErrorContainer>();
public IEnumerable<DafnyError> VerificationErrors
{
get
{
return _verificationErrors.Values.Where(ec => ec.RequestId == MostRecentRequestId).SelectMany(ec => ec.Errors.Reverse());
}
}
public IEnumerable<DafnyError> AllErrors
{
get
{
lock (this)
{
if (_resolutionErrors != null && _resolutionErrors.Any())
{
return _resolutionErrors;
}
else
{
return VerificationErrors;
}
}
}
}
public static readonly IDictionary<ITextBuffer, ResolverTagger> ResolverTaggers = new ConcurrentDictionary<ITextBuffer, ResolverTagger>();
internal ResolverTagger(ITextBuffer buffer, IServiceProvider serviceProvider, ITextDocumentFactoryService textDocumentFactory)
{
_buffer = buffer;
if (!textDocumentFactory.TryGetTextDocument(_buffer, out _document))
_document = null;
Snapshot = null; // this makes sure the next snapshot will look different
_errorProvider = new ErrorListProvider(serviceProvider);
BufferIdleEventUtil.AddBufferIdleEventListener(_buffer, ResolveBuffer);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
lock (this)
{
if (!m_disposed)
{
if (disposing)
{
if (_errorProvider != null)
{
try
{
_errorProvider.Tasks.Clear();
}
catch (InvalidOperationException)
{
// this may occur if the SVsServiceProvider somehow has been uninstalled before our Dispose method is called
}
_errorProvider.Dispose();
_errorProvider = null;
}
BufferIdleEventUtil.RemoveBufferIdleEventListener(_buffer, ResolveBuffer);
if (_document != null && _document.TextBuffer != null)
{
ResolverTaggers.Remove(_document.TextBuffer);
}
}
m_disposed = true;
}
}
}
/// <summary>
/// Find the Error tokens in the set of all tokens and create an ErrorTag for each
/// </summary>
public IEnumerable<ITagSpan<IDafnyResolverTag>> GetTags(NormalizedSnapshotSpanCollection spans)
{
if (spans.Count == 0) yield break;
var currentSnapshot = spans[0].Snapshot;
foreach (var err in AllErrors)
{
if (err.Category != ErrorCategory.ProcessError && err.Filename == System.IO.Path.GetFullPath(_document.FilePath))
{
yield return new TagSpan<IDafnyResolverTag>(err.Span.GetSpan(currentSnapshot), new DafnyErrorResolverTag(err));
if (err.StateSpans != null)
{
for (int i = 0; i < err.StateSpans.Length; i++)
{
var span = err.StateSpans[i];
var name = err.Model.States.ToArray()[i].Name;
var descStart = name.LastIndexOf(": ") + 2;
var description = 1 < descStart ? name.Substring(descStart) : "";
if (span != null)
{
yield return new TagSpan<IDafnyResolverTag>(span.GetSpan(currentSnapshot), new DafnyErrorStateResolverTag(err, span, i, description));
}
}
}
}
}
ITextSnapshot snap;
Dafny.Program prog;
lock (this)
{
snap = Snapshot;
prog = Program;
}
if (prog != null)
{
yield return new TagSpan<IDafnyResolverTag>(new SnapshotSpan(snap, 0, snap.Length), new DafnySuccessResolverTag(prog));
}
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
/// <summary>
/// Calls the Dafny parser/resolver/type checker on the contents of the buffer, updates the Error List accordingly.
/// </summary>
void ResolveBuffer(object sender, EventArgs args)
{
ITextSnapshot snapshot = _buffer.CurrentSnapshot;
if (snapshot == Snapshot)
return; // we've already done this snapshot
string filename = _document != null ? _document.FilePath : "<program>";
var driver = new DafnyDriver(snapshot, filename);
List<DafnyError> newErrors;
Dafny.Program program;
try
{
program = driver.ProcessResolution();
newErrors = driver.Errors;
}
catch (Exception e)
{
newErrors = new List<DafnyError> { new DafnyError(filename, 0, 0, ErrorCategory.InternalError, "internal Dafny error: " + e.Message, snapshot) };
program = null;
}
lock (this)
{
Snapshot = snapshot;
Program = program;
}
if (program != null && _document != null)
{
ResolverTaggers[_document.TextBuffer] = this;
}
else if (_document != null)
{
ResolverTaggers.Remove(_document.TextBuffer);
}
_resolutionErrors = newErrors;
UpdateErrorList(snapshot);
}
public void UpdateErrorList(ITextSnapshot snapshot)
{
lock (this)
{
if (_errorProvider != null && !m_disposed)
{
_errorProvider.SuspendRefresh(); // reduce flickering
_errorProvider.Tasks.Clear();
foreach (var err in AllErrors)
{
var lineNum = 0;
var columnNum = 0;
if (err.Span != null) {
var span = err.Span.GetSpan(snapshot);
lineNum = snapshot.GetLineNumberFromPosition(span.Start.Position);
var line = snapshot.GetLineFromPosition(span.Start.Position);
columnNum = span.Start - line.Start;
} else {
lineNum = err.Line;
columnNum = err.Column;
}
ErrorTask task = new ErrorTask()
{
Category = TaskCategory.BuildCompile,
ErrorCategory = CategoryConversion(err.Category),
Text = err.Message,
Line = lineNum,
Column = columnNum
};
if (err.Filename != null) {
task.Document = err.Filename;
}
else if (_document != null)
{
task.Document = _document.FilePath;
}
if (err.Category != ErrorCategory.ProcessError && err.Category != ErrorCategory.InternalError)
{
task.Navigate += new EventHandler(NavigateHandler);
}
_errorProvider.Tasks.Add(task);
}
_errorProvider.ResumeRefresh();
}
}
var chng = TagsChanged;
if (chng != null)
chng(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length)));
}
static TaskErrorCategory CategoryConversion(ErrorCategory cat)
{
switch (cat)
{
case ErrorCategory.ParseError:
case ErrorCategory.ResolveError:
case ErrorCategory.VerificationError:
case ErrorCategory.InternalError:
return TaskErrorCategory.Error;
case ErrorCategory.ParseWarning:
return TaskErrorCategory.Warning;
case ErrorCategory.AuxInformation:
return TaskErrorCategory.Message;
default:
Contract.Assert(false); // unexpected category
return TaskErrorCategory.Error; // please compiler
}
}
void NavigateHandler(object sender, EventArgs arguments)
{
var task = sender as ErrorTask;
if (task == null || task.Document == null)
return;
// This would have been the simple way of doing things:
// _errorProvider.Navigate(error, new Guid(EnvDTE.Constants.vsViewKindCode));
// Unfortunately, it doesn't work--it seems to ignore the column position. (Moreover, it wants 1-based
// line/column numbers, whereas the Error Task pane wants 0-based line/column numbers.)
// So, instead we do all the things that follow:
var openDoc = Package.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
if (openDoc == null)
return;
IVsWindowFrame frame;
Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp;
IVsUIHierarchy hier;
uint itemid;
Guid logicalView = VSConstants.LOGVIEWID_Code;
if (Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(task.Document, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null)
return;
object docData;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData));
// Get the VsTextBuffer
VsTextBuffer buffer = docData as VsTextBuffer;
if (buffer == null)
{
IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider;
if (bufferProvider != null)
{
IVsTextLines lines;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines));
buffer = lines as VsTextBuffer;
if (buffer == null)
return;
}
}
VsTextManager textManager = Package.GetGlobalService(typeof(VsTextManagerClass)) as VsTextManager;
if (textManager == null)
return;
// Finally, move the cursor
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(textManager.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, task.Line, task.Column));
}
}
#region Errors
public enum ErrorCategory
{
ProcessError, ParseWarning, ParseError, ResolveError, VerificationError, AuxInformation, InternalError
}
public class DafnyError
{
public readonly string Filename;
public readonly int Line; // 0 based
public readonly int Column; // 0 based
public readonly ErrorCategory Category;
public readonly string Message;
protected readonly ITextSnapshot Snapshot;
public readonly ITrackingSpan Span;
public readonly string ModelText;
public Microsoft.Boogie.Model _model;
public Microsoft.Boogie.Model Model
{
get
{
if (_model == null && !string.IsNullOrEmpty(ModelText))
{
using (var rd = new StringReader(ModelText))
{
var models = Microsoft.Boogie.Model.ParseModels(rd, null).ToArray();
Contract.Assert(models.Length == 1);
_model = models[0];
}
}
return _model;
}
}
private ITrackingSpan[] _stateSpans;
public ITrackingSpan[] StateSpans
{
get
{
if (_stateSpans == null && Model != null)
{
var model = Model;
var locRegex = new Regex(@"\((\d+),(\d+)\)");
_stateSpans = model.States.Select(
cs =>
{
var match = locRegex.Match(cs.Name);
if (!match.Success)
{
return null;
}
else
{
var line = Math.Max(0, int.Parse(match.Groups[1].Value) - 1);
var column = Math.Max(0, int.Parse(match.Groups[2].Value) - 1);
var sLine = Snapshot.GetLineFromLineNumber(line);
Contract.Assert(column <= sLine.Length);
var sLength = Math.Max(0, Math.Min(sLine.Length - column, 0));
return Snapshot.CreateTrackingSpan(sLine.Start + column, sLength, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward);
}
}).ToArray();
}
return _stateSpans;
}
}
public int SelectedStateId { get; set; }
public Shape SelectedStateAdornment { get; set; }
public bool IsSelected { get { return SelectedError == this; } }
private readonly ErrorSelection _errorSelection;
public DafnyError SelectedError { get { return _errorSelection.Error; } set { _errorSelection.Error = value; } }
public Shape Adornment;
public delegate void StateChangeEventHandler(object sender);
public event StateChangeEventHandler StateChangeEvent;
public void Notify()
{
if (StateChangeEvent != null)
{
StateChangeEvent(this);
}
}
public void UnsubscribeAll()
{
if (StateChangeEvent != null)
{
foreach (var d in StateChangeEvent.GetInvocationList())
{
StateChangeEvent -= (StateChangeEventHandler)d;
}
}
}
internal class ErrorSelection
{
internal DafnyError Error = null;
}
internal static readonly ErrorSelection _errorSelectionSingleton = new ErrorSelection();
/// <summary>
/// "line" and "col" are expected to be 0-based
/// </summary>
public DafnyError(string filename, int line, int col, ErrorCategory cat, string msg, ITextSnapshot snapshot, string model = null, bool inCurrentDocument=true)
{
Filename = filename;
Line = Math.Max(0, line);
Column = Math.Max(0, col);
Category = cat;
Message = msg;
Snapshot = snapshot;
if (inCurrentDocument) {
var sLine = snapshot.GetLineFromLineNumber(line);
Contract.Assert(Column <= sLine.Length);
var sLength = Math.Max(0, Math.Min(sLine.Length - Column, 5));
Span = snapshot.CreateTrackingSpan(sLine.Start + Column, sLength, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward);
} else {
Span = null;
}
ModelText = model;
_errorSelection = _errorSelectionSingleton;
SelectedStateId = -1;
}
}
#endregion
#endregion
}
|