-
Notifications
You must be signed in to change notification settings - Fork 89
/
NemerleSource.cs
1628 lines (1293 loc) · 58 KB
/
NemerleSource.cs
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Package;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Nemerle.Compiler;
using Nemerle.Compiler.Parsetree;
using Nemerle.Compiler.Utils;
using Nemerle.Compiler.Utils.Async;
using Nemerle.Completion2;
using Nemerle.Completion2.CodeFormatting;
using Nemerle.VisualStudio.GUI;
using Nemerle.VisualStudio.LanguageService.Highlighting.TypeClassifier;
using Nemerle.VisualStudio.Package;
using Nemerle.VisualStudio.Project;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using TopDeclaration = Nemerle.Compiler.Parsetree.TopDeclaration;
using TupleIntInt = Nemerle.Builtins.Tuple<int, int>;
using TupleStringInt = Nemerle.Builtins.Tuple<string, int>;
using TupleStringIntInt = Nemerle.Builtins.Tuple<string, int, int>;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
// ReSharper disable LocalizableElement
namespace Nemerle.VisualStudio.LanguageService
{
public partial class NemerleSource : Source, IIdeSource
{
#region Init
public NemerleSource(NemerleLanguageService service, IVsTextLines textLines)
: base(service, textLines, null)
{
// ReSharper disable DoNotCallOverridableMethodsInConstructor
string path = GetFilePath();
// ReSharper restore DoNotCallOverridableMethodsInConstructor
IsNemerleSybtax = Utils.Eq(Path.GetExtension(path), ".n");
var vsTextBuffer = textLines as IVsTextBuffer;
var textBuffer = vsTextBuffer.ToITextBuffer();
if (!textBuffer.Properties.ContainsProperty(typeof(NemerleSource)))
textBuffer.Properties.AddProperty(typeof(NemerleSource), this);
Service = service;
ProjectInfo projectInfo = ProjectInfo.FindProject(path);
ProjectInfo = projectInfo;
if (projectInfo != null)
{
projectInfo.AddEditableSource(this);
try
{
projectInfo.MakeCompilerMessagesTextMarkers(textLines, FileIndex);
}
catch { }
}
LastDirtyTime = DateTime.Now;
SmartIndent = new NemerleSmartIndentation(this);
UpdateProjectInfo(projectInfo);
}
public void UpdateProjectInfo(ProjectInfo projectInfo)
{
if (projectInfo == null)
GetEngine().BeginUpdateCompileUnit(this);
else
{
ProjectInfo = projectInfo;
projectInfo.Engine.BeginUpdateCompileUnit(this);
}
}
#endregion
#region Properties
public int RefCount { get; private set; }
public DateTime LastDirtyTime { get; private set; }
//public new DateTime LastParseTime { get; private set; }
public NemerleLanguageService Service { get; private set; }
public ProjectInfo ProjectInfo { get; private set; }
public MethodData MethodData { get; private set; }
public int TimeStamp { get; private set; }
internal TopDeclaration[] Declarations { get; set; }
public bool RegionsLoaded { get; set; }
public CompileUnit CompileUnit { get; set; }
/// <summary>
/// A NemerleSource usen for .n files and for extentions like .cs-files inside Nemerle project.
/// IsNemerleSybtax is true if this file is Nemerle language file (niot extension).
/// </summary>
public bool IsNemerleSybtax { get; private set; }
internal NemerleSmartIndentation SmartIndent { get; private set; }
public int FileIndex
{
get
{
if (_fileIndex <= 0)
{
var path = base.GetFilePath();
if (path.IsNullOrEmpty())
path = GetStubFileForSecondaryBuffer(this.GetTextLines());
if (path.IsNullOrEmpty())
return -1;
_fileIndex = Location.GetFileIndex(path);
}
return _fileIndex;
}
}
public bool HasView
{
get
{
//var vsTextBuffer = (IVsTextBuffer)TextLines;
//var mgr = (IVsTextManager)LanguageService.GetService(typeof(VsTextManagerClass));
//IVsTextView vsTextView;
//var result = mgr.GetActiveView(0, vsTextBuffer, out vsTextView);
//return result >= 0;
return true;
}
}
public IVsTextLines TextLines
{
get { return GetTextLines(); }
}
#endregion
#region Fields
public IList<Location> TypeLocations;
public List<Tuple<Location, List<Location>>> MethodsTypeLocations = new List<Tuple<Location, List<Location>>>();
readonly List<RelocationRequest> _relocationRequestsQueue = new List<RelocationRequest>();
int _fileIndex = -1;
QuickTipInfoAsyncRequest _tipAsyncRequest;
#endregion
#region OnChangeLineText
public override void OnChangeLineText(TextLineChange[] lineChange, int last)
{
base.OnChangeLineText(lineChange, last);
if (!IsNemerleSybtax)
return;
TimeStamp++;
ProjectInfo projectInfo = ProjectInfo;
if (projectInfo == null)
{
GetEngine().BeginUpdateCompileUnit(this);
return;
}
if (projectInfo.IsDocumentOpening)
return;
if (projectInfo.IsProjectAvailable)
{
TextLineChange changes = lineChange[0];
var info = new RelocationInfo(FileIndex,
new TextPoint(changes.iStartLine + 1, changes.iStartIndex + 1),
new TextPoint(changes.iOldEndLine + 1, changes.iOldEndIndex + 1),
new TextPoint(changes.iNewEndLine + 1, changes.iNewEndIndex + 1)
);
RelocateTypeLocations(info);
// TODO: use info in AddRelocationRequest()
RelocationQueue.AddRelocationRequest(
RelocationRequestsQueue,
FileIndex, CurrentVersion,
changes.iNewEndLine + 1, changes.iNewEndIndex + 1,
changes.iOldEndLine + 1, changes.iOldEndIndex + 1,
changes.iStartLine + 1, changes.iStartIndex + 1);
}
projectInfo.Engine.BeginUpdateCompileUnit(this); // Add request for reparse & update info about CompileUnit
}
private void RelocateTypeLocations(RelocationInfo info)
{
RelocateList(info, TypeLocations);
for (int i = 0; i < MethodsTypeLocations.Count; i++)
{
var methodsTypeLocation = MethodsTypeLocations[i];
var loc = methodsTypeLocation.Item1;
var lst = methodsTypeLocation.Item2;
var newLoc = Nemerle.Compiler.Completion.Relocate(loc, info);
if (newLoc != loc)
{
RelocateList(info, lst);
MethodsTypeLocations[i] = Tuple.Create(loc, lst);
}
}
}
private static void RelocateList(RelocationInfo info, IList<Location> locations)
{
if (locations != null)
{
for (int i = 0; i < locations.Count; i++)
{
var typeLoc = locations[i];
var newLoc = Nemerle.Compiler.Completion.Relocate(typeLoc, info);
if (newLoc != typeLoc)
locations[i] = newLoc;
}
}
}
#endregion
#region Overrides
public override TextSpan UncommentLines(TextSpan span, string lineComment)
{
// Remove line comments
int clen = lineComment.Length;
var editMgr = new EditArray(this, null, true, "UncommentLines");
for (int line = span.iStartLine; line <= span.iEndLine; line++)
{
int i = this.ScanToNonWhitespaceChar(line);
string text = base.GetLine(line);
if ((i + clen) <= text.Length && text.Substring(i, clen) == lineComment)
{
var es = new EditSpan(new TextSpan()
{
iEndLine = line,
iStartLine = line,
iStartIndex = i,
iEndIndex = i + clen
}, "");
editMgr.Add(es); // remove line comment.
if (line == span.iStartLine && span.iStartIndex != 0)
span.iStartIndex = i;
}
}
editMgr.ApplyEdits();
span.iStartIndex = 0;
return span;
}
public override CompletionSet CreateCompletionSet()
{
return new NemerleCompletionSet(LanguageService.GetImageList(), this);
}
public void Completion(IVsTextView textView, int lintIndex, int columnIndex, bool byTokenTrigger)
{
var result = GetEngine().Completion(this, lintIndex + 1, columnIndex + 1, false);
var decls = new NemerleDeclarations(result, this, result.CompletionResult.IsMemeberComplation);
CompletionSet.Init(textView, decls, !byTokenTrigger);
}
public void ImportCompletion(IVsTextView textView, int lintIndex, int columnIndex)
{
var result = GetEngine().Completion(this, lintIndex + 1, columnIndex + 1, true);
var decls = new NemerleDeclarations(result, this, result.CompletionResult.IsMemeberComplation);
CompletionSet.Init(textView, decls, true);
}
public override string GetFilePath()
{
return Location.GetFileName(FileIndex);
}
public override bool IsDirty
{
get { return base.IsDirty; }
set
{
Debug.WriteLine("IsDirty = " + value);
base.IsDirty = value;
if (value)
LastDirtyTime = DateTime.Now;
//else
// LastParseTime = System.DateTime.Now;
}
}
public override void OnIdle(bool periodic)
{
}
public IVsTextView GetView()
{
if (Service == null)
throw new InvalidOperationException("The Service property of NemerleSource is null!");
return Service.GetPrimaryViewForSource(this);
}
public override void MethodTip(IVsTextView textView, int line, int index, TokenInfo info)
{
var result = GetEngine().BeginGetMethodTipInfo(this, line + 1, index + 1);
result.AsyncWaitHandle.WaitOne();
if (result.Stop)
return;
if (result.MethodTipInfo == null || !result.MethodTipInfo.HasTip)
{
MethodData.Dismiss();
return;
}
var methods = new NemerleMethods(result.MethodTipInfo);
var span = result.MethodTipInfo.StartName.Combine(result.MethodTipInfo.EndParameters).ToTextSpan();
MethodData.Refresh(textView, methods, result.MethodTipInfo.ParameterIndex, span);
Debug.WriteLine("MethodTip");
}
/// <summary>
/// Подготавливает результаты Find Usages/Find All References
/// </summary>
public GotoInfo[] GetGotoInfo(IVsTextView view, bool gotoDefinition, int lineIndex, int colIndex, out string caption)
{
caption = null;
var engine = GetEngine();
var line = lineIndex + 1;
var col = colIndex + 1;
GotoInfo[] infos = gotoDefinition
? engine.GetGotoInfo(this, line, col, GotoKind.Definition)
: engine.GetGotoInfo(this, line, col, GotoKind.Usages);
if(infos == null || infos.Length == 0)
return infos;
if(!infos[0].HasLocation && infos[0].Member != null)
{
Debug.Assert(infos.Length == 1, "Multiple unknown locations are unexpected");
var inf = infos[0];
GotoInfo[] infoFromPdb = TryFindGotoInfoByDebugInfo(engine, inf);
if(infoFromPdb.Length == 0)
{
if(inf.Member != null)
{
var res = ProjectInfo.FindProjectByOutput(inf.FilePath);
if(res != null)
infos = res.Engine.GetGotoInfoForMember(inf.Member.GetFullName(), false, GotoKind.Definition);
if(infos.Length <= 0 || res == null)
infos = NemerleGoto.GenerateSource(infos, engine, out caption);
} else
infos = NemerleGoto.GenerateSource(infos, engine, out caption);
} else
infos = infoFromPdb;
}
return infos;
}
/// <summary>
/// Этот метод заполняет и показывает окошко GotoUsageForm
/// </summary>
public void Goto(IVsTextView view, bool gotoDefinition, int lineIndex, int colIndex)
{
string caption;
var infos = GetGotoInfo(view, gotoDefinition, lineIndex, colIndex, out caption);
if((infos == null) || (infos.Length == 0))
return;
var langSrvc = (NemerleLanguageService)LanguageService;
if (infos.Length == 1)
langSrvc.GotoLocation(infos[0].Location, caption, caption != null);
else if (infos.Length > 0)
{
var textEditorWnd = NativeWindow.FromHandle(view.GetWindowHandle());
using (var popup = new GotoUsageForm(infos))
if ((textEditorWnd == null ? popup.ShowDialog() : popup.ShowDialog(textEditorWnd)) == DialogResult.OK)
langSrvc.GotoLocation(popup.Result.Location, caption, caption != null);
}
}
/// <summary>
/// Этот метод пытается найти позиции перехода на основании имеющехся типов считанных из других сборок,
/// анализа .pdb-файлов (файлов содежащих отладочную информацию) и парсинга исходников.
/// </summary>
/// <param name="engine"></param>
/// <param name="inf"></param>
/// <returns></returns>
/// <remarks>
/// Описание проблемы:
/// К сожалению .pdb-файлы не содержат полной информации о местоположениях тиопов. Местоположения содержатся
/// только для методов (так как именно они подвергаются отладке). Нам же нужно находить не так же типы
/// (причем типы могут располагаться более чем в одном файле). Поэтому поступаем следующим образом...
/// 1. Извлекаем тип для которого нужно получить информацию для перехода. Это может быть или непосредственно
/// член на котрый осуществляетя переход, или тип в котором объявлен этот член (если перход идет на член
/// отличный от типа.
/// 2. Получаем полный список членов в котором типа полученного на шаге 1.
/// 3. Получаем местоположения членов (вместе с путем к файлу). Местоположения могут быть не полными. Например,
/// может быть задан только путь к файлу, а позиция в файле может быть не верной (при этом, в колонке
/// содержится 0). Если мы нашли местопложение для искомого члена и оно корректно, то используем его
/// (на этом поиск нужно прекратить). В противном случае переходим к следующему шагу.
/// 4. Мы получили список файлов в которых может содежаться искомый член. Парсим каждый из файлов
/// и ищем в них тип в котором объявлен нужный нам член. Если член и есть тип, то завершаем обработку
/// и возвращаем местположения типа (тип может быть обявлен более чем в одном файле).
/// В противном случае переходим к следующему шагу.
/// 5. Ищем в типе наденом на шаге 5 член с именем совпадающим с искомым (взятым из IMember). Если найдено
/// более одного члена, то производит отсев наиболее подходящего. Для этого последовательно проверяем список
/// аргументов, возвращаемое значение и т.п.
/// </remarks>
private GotoInfo[] TryFindGotoInfoByDebugInfo(IIdeEngine engine, GotoInfo inf)
{
GotoInfo[] infoFromPdb = ProjectInfo.LookupLocationsFromDebugInformation(inf);
var result = new List<GotoInfo>();
foreach (GotoInfo item in infoFromPdb)
{
var cu = engine.ParseCompileUnit(new FileNemerleSource(item.Location.FileIndex));
var res = TryGetGotoInfoForMemberFromSource(inf.Member, item.Location, cu);
if (res.Length > 0)
result.AddRange(res);
}
return result.ToArray();
}
private static GotoInfo[] TryGetGotoInfoForMemberFromSource(IMember member, Location loc, CompileUnit cu)
{
Trace.Assert(member != null);
var ty = member as TypeInfo;
var soughtIsType = ty != null;
if (ty == null)
// ReSharper disable PossibleNullReferenceException
ty = member.DeclaringType;
// ReSharper restore PossibleNullReferenceException
var td = FindTopDeclaration(ty, cu);
if (td == null)
return new[] { new GotoInfo(loc, UsageType.GeneratedDefinition) };
if (soughtIsType)
return new[] { new GotoInfo(Location.GetFileName(cu.FileIndex), td.NameLocation) };
var name = member.Name;
var file = Location.GetFileName(cu.FileIndex);
var members = td.GetMembers().Where(m => string.Equals(m.Name, name, StringComparison.Ordinal)).ToArray();
if (members.Length == 1)
return new[] { new GotoInfo(file, members[0].NameLocation) };
var isProp = member is IProperty;
members = td.GetMembers().Where(m => string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)
// Макро [Accessor] может изменять имя свойства. Учитываем это...
|| (isProp && string.Equals(m.Name.Replace("_", ""), name, StringComparison.OrdinalIgnoreCase))).ToArray();
if (members.Length > 0)
{
if (loc.Column > 0)
{
var members2 = members.Where(m => m.Location.Contains(loc)).ToArray();
if (members2.Length > 0)
return members2.Select(m => new GotoInfo(file, m.NameLocation)).ToArray();
return new[] { new GotoInfo(file, td.NameLocation) };
}
if (members.Length == 1)
return new[] { new GotoInfo(file, members[0].NameLocation) };
return FindBastMember(members, member).Select(m => new GotoInfo(file, m.NameLocation)).ToArray();
}
// ничего не нашли
if (td != null) // но у нас есть тип в котором объявлен член...
return new[] { new GotoInfo(td.NameLocation) }; // возвращаем его имя!
if (loc.IsEmpty)
return new GotoInfo[0];
return new[] { new GotoInfo(loc, UsageType.GeneratedDefinition) }; // если все обломалось, вернем хотя бы что-то (правда, вряд ли это будте корректным результатом)
}
// ReSharper disable ParameterTypeCanBeEnumerable.Local
// ReSharper disable ReturnTypeCanBeEnumerable.Local
private static ClassMember[] FindBastMember(ClassMember[] members, IMember member)
{
var method = member as IMethod;
if (method != null)
return FindBastMethod(members, method);
return members;
}
private static ClassMember[] FindBastMethod(ClassMember[] members, IMethod method)
{
var parms = method.GetParameters();
var parmsCount = parms.Length;
var methods = members.Where(m => m is ClassMember.Function).Cast<ClassMember.Function>().ToArray();
var methods2 = methods.Where(m => m.header.ParsedParameters.Length == parmsCount).ToArray();
if (methods2.Length == 1)
return methods2;
return methods2;
}
// ReSharper restore ReturnTypeCanBeEnumerable.Local
// ReSharper restore ParameterTypeCanBeEnumerable.Local
private static TopDeclaration FindTopDeclaration(TypeInfo ty, CompileUnit cu)
{
var fullName = ty.FrameworkTypeName.Replace("+", ".");//ty.FullName;
foreach (var td in cu.TopDeclarations)
{
if (td.FullQualifiedName == fullName)
return td;
foreach (var td2 in td.GetAllInnerTypes())
{
if (td2.FullQualifiedName == fullName)
return td2;
}
}
return null;
}
public override ParseRequest BeginParse(int line, int idx, TokenInfo info, ParseReason reason, IVsTextView view, ParseResultHandler callback)
{
//return base.BeginParse(line, idx, info, reason, view, callback);
switch (reason)
{
case ParseReason.Autos: break;
case ParseReason.Check: break;
case ParseReason.CodeSpan: break;
case ParseReason.CompleteWord: break;
case ParseReason.DisplayMemberList: break;
case ParseReason.Goto: break;
case ParseReason.MemberSelect: break;
case ParseReason.MemberSelectAndHighlightBraces: break;
case ParseReason.MethodTip: break;
case ParseReason.None: break;
case ParseReason.QuickInfo: break;
case ParseReason.HighlightBraces:
case ParseReason.MatchBraces:
Trace.Assert(false);
break;
default: break;
}
Debug.WriteLine("Soutce.BeginParse: " + reason);
return null;
}
public override void Dispose()
{
if (ProjectInfo != null)
{
ProjectInfo.RemoveEditableSource(this);
if (IsSecondarySource)
{
var source = ProjectInfo.GetSource(FileIndex);
if (source != null)
ProjectInfo.RemoveSource(source);
RemoveStubFileForSecondaryBuffer(GetTextLines());
}
ProjectInfo = null;
}
SmartIndent = null;
MethodData = null;
_tipAsyncRequest = null;
CompileUnit = null;
Declarations = null;
Service = null;
if (_relocationRequestsQueue != null)
_relocationRequestsQueue.Clear();
if (TypeLocations != null)
TypeLocations.Clear();
if (MethodsTypeLocations != null)
MethodsTypeLocations.Clear();
base.Dispose();
}
public override string ToString()
{
var name = Location.GetFileName(FileIndex);
if (IsClosed)
return "NemerleSource: " + name + " (Closed!)";
return "NemerleSource: " + name;
}
public override CommentInfo GetCommentFormat()
{
return new CommentInfo { UseLineComments = true, LineStart = "//", BlockStart = "/*", BlockEnd = "*/" };
}
public override TextSpan CommentLines(TextSpan span, string lineComment)
{
// Calculate minimal position of non-space char
// at lines in selected span.
var minNonEmptyPosition = 0;
for (var i = span.iStartLine; i <= span.iEndLine; ++i)
{
var line = base.GetLine(i);
if (line.Trim().Length <= 0)
continue;
var spaceLen = line.Replace(line.TrimStart(), "").Length;
if (minNonEmptyPosition == 0 || spaceLen < minNonEmptyPosition)
minNonEmptyPosition = spaceLen;
}
// insert line comment at calculated position.
var editMgr = new EditArray(this, null, true, "CommentLines");
for (var i = span.iStartLine; i <= span.iEndLine; ++i)
{
var text = base.GetLine(i);
if (minNonEmptyPosition <= text.Length && text.Trim().Length > 0)
{
var commentSpan = new TextSpan();
commentSpan.iStartLine = commentSpan.iEndLine = i;
commentSpan.iStartIndex = commentSpan.iEndIndex = minNonEmptyPosition;
editMgr.Add(new EditSpan(commentSpan, lineComment));
}
}
editMgr.ApplyEdits();
// adjust original span to fit comment symbols
span.iEndIndex += lineComment.Length;
return span;
}
public override AuthoringSink CreateAuthoringSink(ParseReason reason, int line, int col)
{
Trace.Assert(false, "We don't using MS infrastructure of background parsing now. This code should not be called!");
throw new NotImplementedException("This should not be heppen!");
}
public override TokenInfo GetTokenInfo(int line, int col)
{
TokenInfo tokenInfo;
if (ParseUtil.TryGetTokenInfo(TextLines.ToITextBuffer(), line, col, out tokenInfo))
return tokenInfo;
else
return new TokenInfo();
}
public override void ProcessHiddenRegions(System.Collections.ArrayList hiddenRegions)
{
// TranslateMe:ss
//VladD2: Приходится переписывать реализацию от МС, так как она практически не расширяется как нужно нам.
throw new NotImplementedException();
}
class TextSpanEqCmp : IEqualityComparer<TextSpan>
{
public bool Equals(TextSpan x, TextSpan y)
{
return x.iStartLine == y.iStartLine && x.iEndLine == y.iEndLine
&& x.iEndIndex == y.iEndIndex && x.iStartIndex == y.iStartIndex;
}
public int GetHashCode(TextSpan x)
{
return x.iStartLine ^ x.iEndLine ^ x.iEndIndex ^ x.iStartIndex;
}
public static readonly TextSpanEqCmp Instance = new TextSpanEqCmp();
}
public void ProcessHiddenRegions(List<NewHiddenRegion> regions, int sourceVersion)
{
if (!OutliningEnabled)
return;
//var timer = Stopwatch.StartNew();
//var timerAll = Stopwatch.StartNew();
//Debug.WriteLine("SetRegions: begin " + timer.Elapsed); timer.Reset(); timer.Start();
#region Получаем список региотов которые уже есть в редакторе.
// Регионы в редакторе могут быть
// по двум причинам:
// 1. Она билы добавлены предыдущим запуском этого метода.
// 2. Они были загружены самим редакторм для востановления состояния состояния
// (открыты / закрыты) регионов после открытия файла (обычно случается только
// если файл открывается при открытом Solution).
// При этом студия не востанавливает баннеры, так что их приходится обновлять
// (см. коментарий к вызову region.SetBanner()).
IVsHiddenTextSession session = GetHiddenTextSession();
var aspan = new TextSpan[1];
aspan[0] = GetDocumentSpan();
var aregion = new IVsHiddenRegion[1];
var oldRegionsMap = new Dictionary<TextSpan, IVsHiddenRegion>(TextSpanEqCmp.Instance);
IVsEnumHiddenRegions ppenum = null;
ErrorHandler.ThrowOnFailure(session.EnumHiddenRegions((uint)FIND_HIDDEN_REGION_FLAGS.FHR_ALL_REGIONS, HiddenRegionCookie, aspan, out ppenum));
uint fetched;
while (ppenum.Next(1, aregion, out fetched) == NativeMethods.S_OK && fetched == 1)
{
var region = aregion[0];
int regTypeInt;
ErrorHandler.ThrowOnFailure(region.GetType(out regTypeInt));
uint dwData;
region.GetClientData(out dwData);
var regType = (HIDDEN_REGION_TYPE)regTypeInt;
if (regType != HIDDEN_REGION_TYPE.hrtCollapsible)// || dwData != 0 && dwData != HiddenRegionCookie)
continue;
ErrorHandler.ThrowOnFailure(region.GetSpan(aspan));
TextSpan s = aspan[0];
//var loc = Utils.LocationFromSpan(FileIndex, s);
oldRegionsMap[s] = region;
}
//Debug.WriteLine("SetRegions: old regions fetched " + timer.Elapsed); timer.Reset(); timer.Start();
#endregion
// Обновлять регионы нужно на заблокированном для записи редакторе, иначе, если текст
// изменится во время обновления, то мы получим рассинхронизацию, и как следствие,
// неопределенное поеведение. По возможности не следует добавлять долгие действия
// в блок расположенный ниже, так как обновление идет в GUI-потоке и медленная работа
// может привести к ощутимому неудобству для пользователя.
LockWrite();
try
{
if (CurrentVersion != sourceVersion)
return;
#region Вычисляем регионы которых небыло в редакторе и обновляем баннеры у старых
var newRegions = new List<NewHiddenRegion>();
foreach (var rg in regions)
{
IVsHiddenRegion region;
if (oldRegionsMap.TryGetValue(rg.tsHiddenText, out region))
{
// Регион с такими же координатами уже был в редактре...
// Похоже VS, при закрытии файла, запоминает только расположение регионов,
// но не их баннеры. Нам нужно обновить баннер если они не совпадают.
// Кроме того баннеры нужно обновлять когда они физически меняются (пользователем).
string banner;
region.GetBanner(out banner);
if (rg.pszBanner != banner && !(banner == "..." && rg.pszBanner.IsNullOrEmpty()))
region.SetBanner(rg.pszBanner);
}
else
newRegions.Add(rg); // Регион новый! Запоминаем его...
}
//Debug.WriteLine("SetRegions: calc new reg & up b " + timer.Elapsed); timer.Reset(); timer.Start();
#endregion
#region Вычисляем список устаревших регионов и удаляем их
var newRegiohsMap = new Dictionary<TextSpan, NewHiddenRegion>(regions.Count);
// Формируем "мап" новых регионов. .ToDictianary() не применим, так как он
// генерирует исключение при попытке добавить элемент с уже существующим ключем.
foreach (var rg in regions)
if (newRegiohsMap.ContainsKey(rg.tsHiddenText))
{ }
else newRegiohsMap[rg.tsHiddenText] = rg;
foreach (var rg in oldRegionsMap)
{
if (!newRegiohsMap.ContainsKey(rg.Key))
{ // Чтарый регион не совпадает по местоположению ни с одним из новых. Удаляем его!
ErrorHandler.ThrowOnFailure(rg.Value.Invalidate((int)CHANGE_HIDDEN_REGION_FLAGS.chrNonUndoable));
//removed++;
}
}
//Debug.WriteLine("SetRegions: bad regions removed " + timer.Elapsed); timer.Reset(); timer.Start();
#endregion
#region Добавляем регионы которых не было в редакторе
int start = Environment.TickCount;
if (newRegions.Count > 0)
{
int count = newRegions.Count;
// For very large documents this can take a while, so add them in chunks of
// 1000 and stop after 5 seconds.
int maxTime = LanguageService.Preferences.MaxRegionTime;
const int ChunkSize = 1000;
var chunk = new NewHiddenRegion[ChunkSize];
int i = 0;
while (i < count && Utils.TimeSince(start) < maxTime)
{
int j = 0;
while (i < count && j < ChunkSize)
{
NewHiddenRegion r = newRegions[i];
if (!TextSpanHelper.ValidSpan(this, r.tsHiddenText))
{
//Debug.Assert(false, "Invalid span " + r.tsHiddenText.iStartLine + "," + r.tsHiddenText.iStartIndex + ","
// + r.tsHiddenText.iEndLine + "," + r.tsHiddenText.iEndIndex);
//break;
//invalid++;
}
else
{
chunk[j] = r;
j++;
//added++;
}
i++;
}
if (j > 0)
{
int hr = session.AddHiddenRegions((int)CHANGE_HIDDEN_REGION_FLAGS.chrNonUndoable, j, chunk, null);
if (ErrorHandler.Failed(hr))
break; // stop adding if we start getting errors.
}
}
}
//Debug.WriteLine("SetRegions: new regions added " + timer.Elapsed); timer.Reset(); timer.Start();
//Debug.WriteLine("Removed: " + removed + " For add: " + newRegions.Count + " Really added: " + added + " invalid: " + invalid);
#endregion
}
catch (Exception ex) { Debug.WriteLine("Exception while region processing: " + ex.Message); }
finally
{
UnlockWrite();
//Debug.WriteLine("SetRegions: end (took all) " + timerAll.Elapsed);
}
RegionsLoaded = true;
}
public override void ReformatSpan(EditArray mgr, TextSpan span)
{
string filePath = GetFilePath();
ProjectInfo projectInfo = ProjectInfo.FindProject(filePath);
IIdeEngine engine = projectInfo != null ? projectInfo.Engine : NemerleLanguageService.DefaultEngine;
ReformatSpanInternal(mgr, span, engine, filePath, this, LanguageService.GetLanguagePreferences());
}
private static void ReformatSpanInternal(EditArray mgr, TextSpan span, IIdeEngine engine, string filePath, IIdeSource src, LanguagePreferences pref)
{
var result = Formatter.BeginFormat(span.iStartLine + 1,
span.iStartIndex + 1,
span.iEndLine + 1,
span.iEndIndex + 1,
engine,
src, new IndentInfo(pref.InsertTabs, pref.IndentSize, pref.TabSize));
result.AsyncWaitHandle.WaitOne();
var results = result.Result;
using (var editArray = new EditArray(mgr.Source, mgr.TextView, true, "formatting"))
{
foreach (FormatterResult res in results)
{
var loc = new TextSpan
{
iStartIndex = res.StartCol - 1,
iStartLine = res.StartLine - 1,
iEndIndex = res.EndCol - 1,
iEndLine = res.EndLine - 1
};
editArray.Add(new EditSpan(loc, res.ReplacementString));
}
editArray.ApplyEdits();
}
}
public override MethodData CreateMethodData()
{
return MethodData = base.CreateMethodData();
}
public override void OnCommand(IVsTextView textView, VsCommands2K command, char ch)
{
if (textView == null || Service == null || !Service.Preferences.EnableCodeSense)
return;
int line, idx;
textView.GetCaretPos(out line, out idx);
if (LanguageService.Preferences.IndentStyle == IndentingStyle.Smart && ch == '}')
SmartIndent.At(line);
TokenInfo tokenBeforeCaret = GetTokenInfo(line, idx);
//VladD2: We do not trigger MethodTip on type because it's very slow!
// This code open completion list if user enter '.'.
if ((tokenBeforeCaret.Trigger & TokenTriggers.MemberSelect) != 0 && (command == VsCommands2K.TYPECHAR))
{
var spaces = new[] { '\t', ' ', '\u000B', '\u000C' };
var tokenBeforeCaretLength = tokenBeforeCaret.EndIndex - tokenBeforeCaret.StartIndex;
var str = GetText(line, 0, line, idx - tokenBeforeCaretLength).Trim(spaces);
while (str.Length <= 0 && line > 0) // skip empy lines
{
line--;
str = GetLine(line + 1).Trim(spaces);
}
if (str.Length > 0)
{
var lastChar = str[str.Length - 1];
// Don't show completion list if previous char not one of following:
if (char.IsLetterOrDigit(lastChar) || lastChar == ')' || lastChar == ']')
Completion(textView, line, idx, true);
}
}
}
public override void GetPairExtents(IVsTextView view, int line, int col, out TextSpan span)
{
span = new TextSpan();
}
private CompileUnit TryGetCompileUnit()
{
var compileUnit = CompileUnit;
return compileUnit;
}