/
ProjectInfo.cs
1179 lines (927 loc) · 35.1 KB
/
ProjectInfo.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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Shell.Interop;
using Nemerle.Compiler;
using Nemerle.Completion2;
using Nemerle.VisualStudio.LanguageService;
using MSBuild = Microsoft.Build.BuildEngine;
using SourceMap = System.Collections.Generic.Dictionary<int, Nemerle.Completion2.IIdeSource>;
using Nemerle.VisualStudio.GUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Package;
using Nemerle.VisualStudio.Package;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using Microsoft.VisualStudio.TextManager.Interop;
using BndFlgs = System.Reflection.BindingFlags;
using MethodBuilderEx = Nemerle.Completion2.Factories.IntelliSenseModeMethodBuilder;
using Tuple = Nemerle.Builtins.Tuple<Nemerle.Compiler.Location, int>;
namespace Nemerle.VisualStudio.Project
{
public class ProjectInfo : IIdeProject
{
private static Collection<ProjectInfo> _projects = new Collection<ProjectInfo>();
public bool IsLoaded { get; private set; }
public string ProjectFullPath { get; private set; }
HierarchyListener _listener;
public NemerleLanguageService LanguageService { get; private set; }
readonly ErrorListProvider _errorList;
public int ErrorCount { get { return _errorList.Tasks.Count; } }
readonly SourceMap _sourceMap = new SourceMap();
readonly List<IIdeSource> _sources = new List<IIdeSource>();
private string _projectLocation;
private bool _fileRenamingInProgress;
public ProjectInfo(
NemerleProjectNode projectNode,
IVsHierarchy hierarchy,
NemerleLanguageService languageService,
string fileName,
string location
)
{
ErrorHelper.ThrowIsNull(languageService, "languageService");
ErrorHelper.ThrowIsNull(projectNode, "projectNode");
ErrorHelper.ThrowIsNull(hierarchy, "hierarchy");
Debug.Assert(projectNode.Site != null);
LanguageService = languageService;
_errorList = new ErrorListProvider(languageService.Site);
ProjectFullPath = Path.GetFullPath(fileName);
_projectNode = projectNode;
_hierarchy = hierarchy;
_engine = EngineFactory.Create(this, new TraceWriter(), false); // it enables parser working.
Engine.TypedtreeCreated += delegate
{
_buildTypedtreeCount++;
AstToolWindow tool = AstToolWindow.AstTool;
if (tool != null)
tool.BuildTypedtreeCount = _buildTypedtreeCount;
};
if (!string.IsNullOrEmpty(location))
_projectLocation = location;
else
_projectLocation = Path.GetDirectoryName(fileName);
if (!_projectLocation.EndsWith("\\"))
_projectLocation += "\\";
}
public void OpenAllFiles()
{
var nodes = new List<NemerleFileNode>();
ProjectNode.FindNodesOfType<NemerleFileNode>(nodes);
foreach (NemerleFileNode node in nodes)
{
var manager = (FileDocumentManager)node.GetDocumentManager();
Debug.Assert(manager != null, "Could not get the FileDocumentManager");
IVsWindowFrame frame;
manager.Open(false, false, VSConstants.LOGVIEWID_Code, out frame, WindowFrameShowAction.Show);
}
}
public bool IsCosed { get; private set; }
public void Close()
{
if (IsCosed)
return;
ResetAssembleReferences();
Engine.Close();
IsCosed = true;
_projects.Remove(this);
_errorList.Tasks.Clear();
_sources.Clear();
_sourceMap.Clear();
//TODO: VladD2: Удалить из очередей AsyncWorker все запросы и ответы связанные с данным проектом!
}
public string ProjectName { get { return _projectNode.VSProject.Project.Name; } }
public string ProjectFullName { get { return _projectNode.VSProject.Project.FullName; } }
public string RootNamespace { get { return (_projectNode.VSProject.Project.Properties.Item("DefaultNamespace").Value ?? "").ToString(); } }
int _buildTypedtreeCount;
readonly List<MethodBuilderEx> _methodsCheckQueue = new List<MethodBuilderEx>(100);
private IIdeEngine _engine;
public IIdeEngine Engine
{
[DebuggerNonUserCode]
get { ManagerClass.Instance = (ManagerClass)_engine; return _engine; }
}
private NemerleProjectNode _projectNode;
public NemerleProjectNode ProjectNode { get { return _projectNode; } }
bool GetBoolProp(string name) { return Utils.IsTrue(ProjectNode.BuildProject, name); }
public bool RunDebugger { get { return GetBoolProp("RunDebugger"); } }
public bool NoStdLib { get { return GetBoolProp("NoStdLib"); } }
public bool NoStdMacros { get { return GetBoolProp("NoStdMacros"); } }
IVsHierarchy _hierarchy;
public void InitListener()
{
_listener = new HierarchyListener(_hierarchy);
_listener.ItemAdded += FileAdded;
_listener.ItemDeleted += FileDeleted;
_listener.StartListening(true);
}
public static Collection<ProjectInfo> Projects
{
get { return _projects; }
}
#region Assemble Reference Managment
#region Assembly References helpers
public void AddAssembly(List<string> assemblies, ReferenceNode node, string type)
{
//TODO: Проследить что где-то добавляется вочер для сборки!
var path = GetAssemblyReferencesString(node);
if (!string.IsNullOrEmpty(path))
{
assemblies.Add(path);
AddAssembleReferenceWatcher(path);
}
else
Debug.Assert(false, "Can't add " + type + "assembly reference '" + node.Caption + "' (" + node.Url + ")");
if (IsLoaded)
Engine.RequestOnReloadProject();
}
public void RemoveAssembly(List<string> assemblies, ReferenceNode node, string type)
{
//TODO: Проследить что где-то удаляется вочер для сборки!
var path = GetAssemblyReferencesString(node);
if (!string.IsNullOrEmpty(path))
{
RemoveAssembleReferenceWatcher(path);
bool res = assemblies.Remove(path);
Debug.Assert(res, "Can't remove " + type + "assembly reference '" + node.Caption + "' (" + node.Url + ")");
}
else
Debug.Assert(false, "Can't remove " + type + "assembly reference '" + node.Caption + "' (" + node.Url + ")");
Engine.RequestOnReloadProject();
}
#endregion
#region Assembly References
List<string> _assemblyReferences = new List<string>();
IEnumerable<string> IIdeProject.GetAssemblyReferences()
{
if (!IsLoaded)
UpdateAssembleReferences();
return _assemblyReferences.ToArray();
}
public void AddAssembly(ReferenceNode node)
{
AddAssembly(_assemblyReferences, node, "");
}
public void RemoveAssembly(ReferenceNode node)
{
RemoveAssembly(_assemblyReferences, node, "");
}
#endregion
#region MacroAssembly References
List<string> _macroAssemblyReferences = new List<string>();
IEnumerable<string> IIdeProject.GetMacroAssemblyReferences()
{
if (!IsLoaded)
UpdateAssembleReferences();
return _macroAssemblyReferences.ToArray();
}
public void AddMacroAssembly(ReferenceNode node)
{
AddAssembly(_macroAssemblyReferences, node, "macro ");
}
public void RemoveMacroAssembly(ReferenceNode node)
{
RemoveAssembly(_macroAssemblyReferences, node, "macro ");
}
#endregion
#region Assemble Reference Watchers
// Assemble Watcher-ы используются для слежением за изменением файлов сборок.
// При изменении файла автоматически производится запрос на перезагрузку проекта.
/// <summary>Watchers for project assemble reference.</summary>
List<FileSystemWatcher> _assembleReferenceWatchers = new List<FileSystemWatcher>();
private void AddAssembleReferenceWatcher(string filePath)
{
if (!File.Exists(filePath))
Debug.WriteLine("Assemble " + filePath + " does not exists!");
try
{
string path = Path.GetDirectoryName(filePath);
if (!Directory.Exists(path))
return;
string name = Path.GetFileName(filePath);
FileSystemWatcher watcher = new FileSystemWatcher(path, name);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += watcher_Changed;
_assembleReferenceWatchers.Add(watcher);
watcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
SetCompilerMessages(new[] {new CompilerMessage(Location.Default, ex.Message,
MessageKind.Error, Engine, false)}, null);
throw;
}
}
void RemoveAssembleReferenceWatcher(string filePath)
{
if (!File.Exists(filePath))
{
Debug.WriteLine("Assemble " + filePath + " does not exists!");
}
string path = Path.GetDirectoryName(filePath);
string name = Path.GetFileName(filePath);
var index = _assembleReferenceWatchers.FindIndex(w => w.Path == path && w.Filter == name);
if (index >= 0)
{
FileSystemWatcher watcher = _assembleReferenceWatchers[index];
watcher.Dispose();
_assembleReferenceWatchers.RemoveAt(index);
}
}
void ResetAssembleReferences()
{
IsLoaded = false;
ResetAssembleReferenceWatchers();
_macroAssemblyReferences.Clear();
_assemblyReferences.Clear();
}
void ResetAssembleReferenceWatchers()
{
foreach (FileSystemWatcher watcher in _assembleReferenceWatchers)
watcher.Dispose();
_assembleReferenceWatchers.Clear();
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
Engine.RequestOnReloadProject();
}
#endregion
#endregion
internal void AddEditableSource(NemerleSource source)
{
ReplaseOrAddSource(source);
}
internal void ReplaseOrAddSource(IIdeSource source)
{
var fileIndex = source.FileIndex;
IIdeSource old;
if (_sourceMap.TryGetValue(fileIndex, out old))
_sources.Remove(old);
_sourceMap[fileIndex] = source;
_sources.Add(source);
//Engine.RequestOnBuildTypesTree();
}
internal void RemoveEditableSource(NemerleSource source)
{
var fileIndex = source.FileIndex;
var taksForSource = GetTaksForSource(source.FileIndex);
foreach (var task in taksForSource)
task.DisposeTextLineMarker();
ReplaseOrAddSource(new FileNemerleSource(fileIndex));
}
internal void RemoveSource(IIdeSource source)
{
_sourceMap.Remove(source.FileIndex);
_sources.Remove(source);
Engine.RequestOnBuildTypesTree();
}
public void RemoveSource(string path)
{
if (_fileRenamingInProgress)
return;
var fileIndex = Location.GetFileIndex(path);
if (IsFileInProject(fileIndex))
{
var source = GetSource(fileIndex);
Trace.Assert(source != null);
RemoveSource(source);
}
}
public NemerleSource GetEditableSource(int fileIndex, WindowFrameShowAction action)
{
IIdeSource source;
if (!_sourceMap.TryGetValue(fileIndex, out source))
throw new ApplicationException("File not in project");
var nemerleSource = source as NemerleSource;
if (nemerleSource != null)
return nemerleSource;
return OpenEditableSource(fileIndex, action);
}
NemerleSource OpenEditableSource(int fileIndex, WindowFrameShowAction action)
{
IVsWindowFrame frame = OpenWindowFrame(fileIndex, action);
if (frame == null)
throw new ApplicationException("frame (IVsWindowFrame) is null");
object docData;
frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData);
// Get the VsTextBuffer
var buffer = docData as VsTextBuffer;
if (buffer == null)
{
var bufferProvider = docData as IVsTextBufferProvider;
if (bufferProvider != null)
{
IVsTextLines lines;
ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines));
var source = LanguageService.CreateSource(lines);
return (NemerleSource)source;
}
}
else
{
var lines = (IVsTextLines)buffer;
var source = LanguageService.CreateSource(lines);
return (NemerleSource)source;
}
throw new ApplicationException("can't retrive IVsTextLines from IVsWindowFrame");
}
IVsWindowFrame OpenWindowFrame(int fileIndex, WindowFrameShowAction action)
{
var path = Location.GetFileName(fileIndex);
var node = (FileNode)_projectNode.FindChild(path);
var manager = (FileDocumentManager)node.GetDocumentManager();
IVsWindowFrame frame;
// Open the document in rdt.
ErrorHandler.ThrowOnFailure(manager.Open(false, false, VSConstants.LOGVIEWID_Code,
out frame, action));
return frame;
}
public IIdeSource GetSource(int fileIndex)
{
IIdeSource source;
return _sourceMap.TryGetValue(fileIndex, out source) ? source : null;
}
public IIdeSource GetSource(string filePath)
{
return GetSource(Location.GetFileIndex(filePath));
}
public bool IsFileInProject(string filePath)
{
return IsFileInProject(Location.GetFileIndex(filePath));
}
public bool IsFileInProject(int fileIndex)
{
return _sourceMap.ContainsKey(fileIndex);
}
private static NemerleFileNodeProperties GetNodeProperties(IVsHierarchy hierarchy, uint itemID)
{
ErrorHelper.ThrowIsNull(hierarchy, "hierarchy");
object propertyValue;
int hr = hierarchy.GetProperty(itemID, (int)__VSHPROPID.VSHPROPID_BrowseObject, out propertyValue);
if (hr != VSConstants.S_OK)
throw new ArgumentException("Can't obtain VSHPROPID_BrowseObject for item with ID "
+ itemID, "itemID", new Win32Exception(hr));
NemerleFileNodeProperties properties = propertyValue as NemerleFileNodeProperties;
if (properties == null)
return new NemerleFileNodeProperties(((NodeProperties)propertyValue).Node);
else
return properties;
}
#region IIdeProject
CompilationOptions IIdeProject.GetOptions()
{
var options = new CompilationOptions();
string defineConstants = _projectNode.GetProjectProperty("DefineConstants", false);
if (!string.IsNullOrEmpty(defineConstants))
{
var defines = defineConstants
.Split(new char[]{';', ' ', '\r', '\n', '\t'}, StringSplitOptions.RemoveEmptyEntries);
foreach (var define in defines)
options.DefineConstant(define.Trim());
}
var projectFullName = ProjectFullName;
var outputFileName = this.ProjectNode.OutputFileName;
var outputPath = GetStringProp("OutputPath");
outputFileName = Path.IsPathRooted(outputFileName)
? outputFileName
: Path.Combine(Path.Combine(Path.GetDirectoryName(projectFullName), outputPath), outputFileName);
options.OutputFileName = Path.GetFullPath(outputFileName);
options.ColorMessages = false;
options.IgnoreConfusion = true;
var prop = GetStringProp("OutputType");
if (string.Equals(prop, "WinExe", StringComparison.InvariantCultureIgnoreCase))
options.TargetIsWinexe = true;
else if (string.Equals(prop, "Library", StringComparison.InvariantCultureIgnoreCase))
options.TargetIsLibrary = true;
options.GreedyReferences = GetBoolProp("GreedyReferences");
options.DoNotLoadStdlib = NoStdLib;
options.DoNotLoadMacros = NoStdMacros;
options.OutputPath = GetStringProp("OutputPath");
options.ProjectPath = projectFullName;
options.RootNamespace = RootNamespace;
return options;
}
private string GetStringProp(string propertyName)
{
return ProjectNode.BuildProject.GetPropertyValue(propertyName);
}
IEnumerable<IIdeSource> IIdeProject.GetSources()
{
return _sources;
}
public GotoInfo[] LookupLocationsFromDebugInformation(GotoInfo info)
{
var vsSmartOpenScope = (IVsSmartOpenScope)ProjectNode.Site.GetService(typeof(SVsSmartOpenScope));
return NemerleGoto.LookupLocationsFromPdb(info, vsSmartOpenScope);
}
#endregion
internal void FileBuildActionPropertyChanged(HierarchyNode node, NemerleBuildAction oldAction, NemerleBuildAction newAction)
{
if (oldAction == NemerleBuildAction.Compile && newAction != NemerleBuildAction.Compile)
RemoveSource(node.Url);
else if (newAction == NemerleBuildAction.Compile && oldAction != NemerleBuildAction.Compile)
AddSource(node.Url);
}
private void FileAdded(object sender, HierarchyEventArgs ergs)
{
Debug.Assert(ergs.TextBuffer == null);
IVsHierarchy hierarchy = (IVsHierarchy)sender;
NemerleFileNodeProperties nodeProps = GetNodeProperties(hierarchy, ergs.ItemID);
if (nodeProps.BuildAction != BuildAction.Compile)
return;
string path = ergs.FileName;
AddSource(path);
}
public void AddSource(string path)
{
if (_fileRenamingInProgress)
return;
IIdeSource source = (NemerleSource)LanguageService.GetSource(path); // TODO: VladD2: тут надо искать Source по иерархии, а не по пути!
//source = new NemerleSource(LanguageService, );
try
{
if (source == null)
source = new FileNemerleSource(Location.GetFileIndex(path));
else
((NemerleSource)source).UpdateProjectInfo(this);
_sourceMap.Add(source.FileIndex, source);
_sources.Add(source);
Engine.RequestOnBuildTypesTree();
}
catch (Exception ex)
{
SetCompilerMessages(new[] {new CompilerMessage(Location.Default, ex.Message,
MessageKind.Error, Engine, false)}, null);
}
}
private void FileDeleted(object sender, HierarchyEventArgs ergs)
{
Debug.Assert(ergs.TextBuffer == null);
string path = ergs.FileName;
RemoveSource(path);
}
public static ProjectInfo FindProject(IVsHierarchy hierarchy)
{
foreach (ProjectInfo proj in _projects)
if (Utilities.IsSameComObject(proj._hierarchy, hierarchy))
return proj;
return null;
}
public static ProjectInfo FindProjectByOutput(string fileName)
{
var fullPath = Path.GetFullPath(fileName).ToLower();
ErrorHelper.ThrowIfPathNullOrEmpty(fileName, "fileName");
foreach (ProjectInfo proj in _projects)
{
var outFile = (string)proj._projectNode.VSProject.Project.Properties.Item("OutputFileName").Value ?? "";
var outPath = (string)proj._projectNode.VSProject.Project.Properties.Item("OutputPath").Value ?? "";
var dir = (string)proj._projectNode.VSProject.Project.Properties.Item("FullPath").Value ?? "";
var fullOutPath = Path.GetFullPath(Path.Combine(dir, Path.Combine(outPath, outFile))).ToLower();
if (fullOutPath == fullPath)
return proj;
}
return null;
}
public static ProjectInfo FindProject(string fileName)
{
ErrorHelper.ThrowIfPathNullOrEmpty(fileName, "fileName");
foreach (ProjectInfo proj in _projects)
if (proj.IsFileInProject(fileName))
return proj;
return null;
}
public bool IsProjectAvailable
{
get { return Engine.IsProjectAvailable; }
}
public bool IsDocumentOpening { get; internal set; }
public IEnumerable<NemerleErrorTask> FindTaks(Func<NemerleErrorTask, bool> predicate)
{
var tasks = _errorList.Tasks.OfType<NemerleErrorTask>();
var taksForSource = tasks.Where(predicate);
return taksForSource;
}
IEnumerable<NemerleErrorTask> GetTaksForSource(int fileIndex)
{
var tasks = _errorList.Tasks.OfType<NemerleErrorTask>();
var taksForSource = tasks.Where(t => t.CompilerMessage.Location.FileIndex == fileIndex);
return taksForSource;
}
internal void MakeCompilerMessagesTextMarkers(IVsTextLines buffer, int fileIndex)
{
var taksForSource = GetTaksForSource(fileIndex);
foreach (var task in taksForSource)
task.MakeTextMarker(buffer);
}
#region IIdeProject Members
public void ShowMessage(string message, MessageType messageType)
{
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
switch (messageType)
{
case MessageType.Error: icon = OLEMSGICON.OLEMSGICON_CRITICAL; break;
case MessageType.Hint: icon = OLEMSGICON.OLEMSGICON_INFO; break;
case MessageType.Info: icon = OLEMSGICON.OLEMSGICON_INFO; break;
case MessageType.Warning: icon = OLEMSGICON.OLEMSGICON_WARNING; break;
}
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(ProjectNode.ProjectMgr.Site,
message, NemerleConstants.ProductName, icon, buttons, defaultButton);
}
void IIdeProject.ClearAllCompilerMessages()
{
lock (_errorList.Tasks)
{
_errorList.SuspendRefresh();
try
{
ClearCompilerMessgesTasks(x => true);
}
finally { _errorList.ResumeRefresh(); }
}
}
void IIdeProject.SetTopLevelCompilerMessages(IEnumerable<CompilerMessage> messages)
{
SetCompilerMessages(messages, null);
}
void IIdeProject.SetCompilerMessageForCompileUnit(CompileUnit compileUnit)
{
var fileIndex = compileUnit.FileIndex;
SetCompilerMessages(compileUnit.ParseCompilerMessages, task =>
{
var msg = task.CompilerMessage as CompilerMessageForCompileUnit;
if (msg != null)
return msg.CompileUnit.FileIndex == fileIndex;
return false;
});
}
void IIdeProject.ClearMethodCompilerMessages(MemberBuilder member)
{
lock (_errorList.Tasks)
{
_errorList.SuspendRefresh();
try
{
ClearCompilerMessgesTasks(task =>
{
var memberMsg = task.CompilerMessage as CompilerMessageForMethod;
var result = memberMsg != null && (memberMsg.Member == member || memberMsg.Member.ToString() == member.ToString());
return result;
});
}
finally { _errorList.ResumeRefresh(); }
}
}
Queue<IEnumerable<CompilerMessage>> _delayedMethodCompilerMessages = new Queue<IEnumerable<CompilerMessage>>();
TimeSpan _lastTimeOfProcessDelayedMethodCompilerMessages;
Stopwatch _processDelayedMethodCompilerMessagesTimer = Stopwatch.StartNew();
/// <summary>
/// Разбирвает очередь _delayedMethodCompilerMessages. В эту очередь помещаются сообщения компилятора
/// возникающие при типизации тел методов при условии, что уже имеется много сообщений от компилятора.
/// Этот трюк нужен так как в противном случае GUI VS начинает дико тормозить в случае наличия множества
/// ошибок.
/// </summary>
internal void ProcessDelayedMethodCompilerMessages()
{
var current = _processDelayedMethodCompilerMessagesTimer.Elapsed;
var delta = current - _lastTimeOfProcessDelayedMethodCompilerMessages;
if (delta < TimeSpan.FromSeconds(1))
return;
var queue = _delayedMethodCompilerMessages;
if (queue.Count <= 0)
return;
_lastTimeOfProcessDelayedMethodCompilerMessages = current;
_errorList.SuspendRefresh();
try
{
while (queue.Count > 0)
{
var messages = queue.Dequeue();
AddNewCompilerMessages(messages.Select(m => TranslateSecondarySourceMessage(m)).Where(m => m != null));
}
}
finally { _errorList.ResumeRefresh(); }
}
void IIdeProject.SetMethodCompilerMessages(MemberBuilder member, IEnumerable<CompilerMessage> messages)
{
if (!IsMemberVersionCorrect(member))
return;
var count = _errorList.Tasks.Count;
if (count > 100)
_delayedMethodCompilerMessages.Enqueue(messages);
else
SetCompilerMessages(messages, null /* messges related to member was deleted be ClearMethodCompilerMessages() */);
// Following for debugging purpose:
//var res = _errorList.Tasks.OfType<NemerleErrorTask>().GroupBy(x => x.ToString()).Where(g => g.Count() > 1).ToArray();
//if (res.Length > 0)
// Test(res, Engine.TypesTreeVersion);
}
void IIdeProject.TypesTreeCreated()
{
foreach (IIdeSource source in _sources)
{
var nemerleSource = source as NemerleSource;
if (nemerleSource != null)
{
var lineCount = nemerleSource.GetLineCount();
if (lineCount > 0)
nemerleSource.Recolorize(0, lineCount - 1);
}
}
}
// Транслирует привязку сообщения к позиции в secondary файле в привязку к позиции в primary файле.
// Primary файл - исходный aspx, secondary - автосгенерированный по нему исходный код на Немерле
private CompilerMessage TranslateSecondarySourceMessage(CompilerMessage message)
{
var source = GetSource(message.Location.FileIndex) as NemerleSource;
if (source != null && source.IsSecondarySource)
{
var primaryLocation = source.MapSecondaryToPrimaryLocation(message.Location);
if (primaryLocation.Line == 1 && primaryLocation.Column == 1) // && message.Kind == MessageKind.Error)
{
// Исключим из списка сообщения, относящиеся исключительно к автосгенерированному (по исходному aspx) файлу.
// Как правило такие сообщения вызваны не совсем корректной работой кодогенератора,
// использующего в design time упрощенный режим генерации
return null;
}
CompilerMessage translatedMessage = null;
if (message is CompilerMessageForMethod)
{
var methodMessage = (CompilerMessageForMethod)message;
translatedMessage = new CompilerMessageForMethod(primaryLocation, methodMessage.Msg, methodMessage.Kind, methodMessage.Engin, methodMessage.IsRelated, methodMessage.Member);
}
else if (message is CompilerMessageForCompileUnit)
{
var unitMessage = (CompilerMessageForCompileUnit)message;
translatedMessage = new CompilerMessageForCompileUnit(primaryLocation, unitMessage.Msg, unitMessage.Kind, unitMessage.Engin, unitMessage.IsRelated);
((CompilerMessageForCompileUnit)translatedMessage).CompileUnit = unitMessage.CompileUnit;
}
else
translatedMessage = new CompilerMessage(primaryLocation, message.Msg, message.Kind, message.Engin, message.IsRelated);
// трансляции позиций для вложенных сообщений
translatedMessage.RelatedMessages.AddRange(message.RelatedMessages.Select(m => TranslateSecondarySourceMessage(m)).Where(m => m != null));
return translatedMessage;
}
else
return message;
}
public static string GetAssemblyReferencesString(ReferenceNode node)
{
string assemblyId = null;
var prjRef = node as NemerleProjectReferenceNode;
if (prjRef != null) // Is project reference...
{
assemblyId = prjRef.ReferencedProjectOutputPath; // calc real assembly name.
}
else if (node.Url != null) //IT: if dll does not exist, the Url will be null.
assemblyId = node.Url;
else
{
//TODO: Notify user about reference does not exist.
}
return assemblyId;
}
public void SetStatusText(string text) // implemetn IIdeProject
{
LanguageService.SetStatusBarText(text);
Debug.WriteLine(text);
}
public void AddUnimplementedMembers(IIdeSource source, TypeBuilder ty,
IEnumerable<IGrouping<FixedType.Class, IMember>> unimplementedMembers)
{
using (var form = new ImplementMembersForm((NemerleSource)source, ty, unimplementedMembers))
{
form.ShowDialog();
}
}
public void AddOverrideMembers(IIdeSource source, TypeBuilder ty, IEnumerable<IMember> notOverriden)
{
var ty2 = ty.GetMemType();
var notOverriden2 = notOverriden.Select(m => new { ty2, m }).GroupBy(x => x.ty2, x => x.m);
using (var form = new ImplementMembersForm((NemerleSource)source, ty, notOverriden2))
{
form.ShowDialog();
}
}
public void SetUsageHighlighting(IIdeSource source, IEnumerable<GotoInfo> usages)
{
((NemerleSource)source).SetUsageHighlighting(usages);
}
#region Implementation
/// This method need only for debugging purpose.
bool IsMemberVersionCorrect(MemberBuilder member)
{
var method = member as MethodBuilderEx;
if (method == null)
{
Debug.Assert(false);
return false;
}
var treeVer = Engine.TypesTreeVersion;
var methodVer = method.TypesTreeVersion;
if (methodVer != treeVer)
{
//Trace.Assert(false, "This should not happen. We have problem with multithreading!");
return false;
}
return true;
}
class CompilerMessageEqComparer : IEqualityComparer<CompilerMessage>
{
#region IEqualityComparer<CompilerMessage> Members
public bool Equals(CompilerMessage x, CompilerMessage y)
{
return x.Location.Equals(y.Location) && x.Kind == y.Kind && x.Msg == y.Msg;
}
public int GetHashCode(CompilerMessage obj)
{
return obj.Location.GetHashCode() ^ (obj.Msg == null ? 0 : obj.Msg.GetHashCode());
}
#endregion
public static readonly CompilerMessageEqComparer Instance = new CompilerMessageEqComparer();
}
/// try add text markers (markers visualise errors in editor).
void TryAddTextMarkers(IEnumerable<NemerleErrorTask> tasks)
{
var taskGroups = tasks.GroupBy(t => t.CompilerMessage.Location.FileIndex);
foreach (var taskGroup in taskGroups)
{
IVsTextLines buffer = null;
// Маркеры для сообщений, сгенерированных при компиляции secondary
// файлов, должны устанавливаться в primary буфере
if (NemerleSource.HasSecondarySource(taskGroup.Key))
{
var secondarySource = GetSource(NemerleSource.GetSecondaryFileIndex(taskGroup.Key)) as NemerleSource;
if (secondarySource != null)
buffer = secondarySource.GetPrimaryTextLines();
}
else
{
var source = GetSource(taskGroup.Key) as NemerleSource;
if (source != null)
buffer = source.GetTextLines();
}
if (buffer != null)
{
foreach (var task in taskGroup)
task.MakeTextMarker(buffer);
}
}
}
private void NavigateTo(object sender, EventArgs arguments)
{
var task = sender as NemerleErrorTask;
if (task == null)
throw new ArgumentException("sender");
// Get the doc data for the task's document
if (String.IsNullOrEmpty(task.Document))
return;
var serviceProvider = ProjectNode.GetServiceProvider();