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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
|
//
// CSharpCompletionTextEditorExtension.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2011 Xamarin <http://xamarin.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using MonoDevelop.Core;
using MonoDevelop.Debugger;
using MonoDevelop.Ide.Gui;
using MonoDevelop.CodeGeneration;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Components.Commands;
using MonoDevelop.CSharp.Formatting;
using ICSharpCode.NRefactory6.CSharp.Completion;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using MonoDevelop.Ide.Editor.Extension;
using MonoDevelop.Ide.Editor;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using System.Xml;
using ICSharpCode.NRefactory6.CSharp;
using MonoDevelop.Refactoring;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using MonoDevelop.Ide;
using Mono.Addins;
using System.Reflection;
using System.Runtime.ExceptionServices;
using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CSharp.Completion
{
sealed class CSharpCompletionTextEditorExtension : CompletionTextEditorExtension, IDebuggerExpressionResolver
{
/* internal protected virtual Mono.TextEditor.TextEditorData TextEditorData {
get {
var doc = Document;
if (doc == null)
return null;
return doc.Editor;
}
}
protected virtual IProjectContent ProjectContent {
get { return Document.GetProjectContext (); }
}
*/
SyntaxTree unit;
static readonly SyntaxTree emptyUnit = CSharpSyntaxTree.ParseText ("");
List<CompletionContextHandler> additionalContextHandlers = new List<CompletionContextHandler> ();
SyntaxTree Unit {
get {
return unit ?? emptyUnit;
}
set {
unit = value;
}
}
public MonoDevelop.Ide.TypeSystem.ParsedDocument ParsedDocument {
get {
return DocumentContext.ParsedDocument;
}
}
public MonoDevelop.Projects.Project Project {
get {
return DocumentContext.Project;
}
}
CSharpFormattingPolicy policy;
public CSharpFormattingPolicy FormattingPolicy {
get {
if (policy == null) {
IEnumerable<string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (MonoDevelop.CSharp.Formatting.CSharpFormatter.MimeType);
if (DocumentContext.Project != null && DocumentContext.Project.Policies != null) {
policy = base.DocumentContext.Project.Policies.Get<CSharpFormattingPolicy> (types);
} else {
policy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);
}
}
return policy;
}
}
public override string CompletionLanguage {
get {
return "C#";
}
}
static Func<Microsoft.CodeAnalysis.Document, CancellationToken, Task<Microsoft.CodeAnalysis.Document>> WithFrozenPartialSemanticsAsync;
static List<CompletionData> snippets;
static CSharpCompletionTextEditorExtension ()
{
var methodInfo = typeof(Microsoft.CodeAnalysis.Document).GetMethod ("WithFrozenPartialSemanticsAsync", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod);
if (methodInfo == null)
LoggingService.LogError ("Error in completion set up: Document.WithFrozenPartialSemanticsAsync not found!");
WithFrozenPartialSemanticsAsync = delegate (Microsoft.CodeAnalysis.Document doc, CancellationToken token) {
try {
return (Task<Microsoft.CodeAnalysis.Document>)methodInfo.Invoke (doc, new object [] { token });
} catch (TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return null;
}
};
CompletionEngine.SnippetCallback = delegate(CancellationToken arg) {
if (snippets != null)
return Task.FromResult((IEnumerable<CompletionData>)snippets);
var newSnippets = new List<CompletionData>();
foreach (var ct in MonoDevelop.Ide.CodeTemplates.CodeTemplateService.GetCodeTemplates ("text/x-csharp")) {
if (string.IsNullOrEmpty (ct.Shortcut) || ct.CodeTemplateContext != MonoDevelop.Ide.CodeTemplates.CodeTemplateContext.Standard)
continue;
newSnippets.Add (new RoslynCompletionData (null) {
CompletionText = ct.Shortcut,
DisplayText = ct.Shortcut,
Description = ct.Shortcut + Environment.NewLine + GettextCatalog.GetString (ct.Description),
Icon = ct.Icon
});
}
snippets = newSnippets;
return Task.FromResult((IEnumerable<CompletionData>)newSnippets);
};
}
public CSharpCompletionTextEditorExtension ()
{
foreach (var node in AddinManager.GetExtensionNodes<InstanceExtensionNode> ("/MonoDevelop/CSharp/Completion/ContextHandler")) {
var handler = (CompletionContextHandler)node.CreateInstance ();
additionalContextHandlers.Add (handler);
}
}
bool addEventHandlersInInitialization = true;
/// <summary>
/// Used in testing environment.
/// </summary>
[System.ComponentModel.Browsable(false)]
public CSharpCompletionTextEditorExtension (MonoDevelop.Ide.Gui.Document doc, bool addEventHandlersInInitialization = true) : this ()
{
this.addEventHandlersInInitialization = addEventHandlersInInitialization;
Initialize (doc.Editor, doc);
}
protected override void Initialize ()
{
base.Initialize ();
var parsedDocument = DocumentContext.ParsedDocument;
if (parsedDocument != null) {
// this.Unit = parsedDocument.GetAst<SyntaxTree> ();
// this.UnresolvedFileCompilation = DocumentContext.Compilation;
// this.CSharpUnresolvedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile;
// Editor.CaretPositionChanged += HandlePositionChanged;
}
if (addEventHandlersInInitialization)
DocumentContext.DocumentParsed += HandleDocumentParsed;
}
CancellationTokenSource src = new CancellationTokenSource ();
void StopPositionChangedTask ()
{
src.Cancel ();
src = new CancellationTokenSource ();
}
[CommandUpdateHandler (CodeGenerationCommands.ShowCodeGenerationWindow)]
public void CheckShowCodeGenerationWindow (CommandInfo info)
{
info.Enabled = Editor != null && DocumentContext.GetContent<ICompletionWidget> () != null;
}
[CommandHandler (CodeGenerationCommands.ShowCodeGenerationWindow)]
public void ShowCodeGenerationWindow ()
{
var completionWidget = DocumentContext.GetContent<ICompletionWidget> ();
if (completionWidget == null)
return;
CodeCompletionContext completionContext = completionWidget.CreateCodeCompletionContext (Editor.CaretOffset);
GenerateCodeWindow.ShowIfValid (Editor, DocumentContext, completionContext);
}
public override void Dispose ()
{
CancelParsedDocumentUpdate ();
DocumentContext.DocumentParsed -= HandleDocumentParsed;
if (validTypeSystemSegmentTree != null) {
validTypeSystemSegmentTree.RemoveListener ();
validTypeSystemSegmentTree = null;
}
base.Dispose ();
}
CancellationTokenSource documentParsedTokenSrc = new CancellationTokenSource ();
void HandleDocumentParsed (object sender, EventArgs e)
{
var parsedDocument = DocumentContext.ParsedDocument;
if (parsedDocument == null)
return;
var semanticModel = parsedDocument.GetAst<SemanticModel> ();
if (semanticModel == null)
return;
CancelParsedDocumentUpdate ();
var token = documentParsedTokenSrc.Token;
Task.Run(delegate {
try {
var newTree = TypeSystemSegmentTree.Create (semanticModel, token);
if (validTypeSystemSegmentTree != null)
validTypeSystemSegmentTree.RemoveListener ();
validTypeSystemSegmentTree = newTree;
newTree.InstallListener (Editor);
if (TypeSegmentTreeUpdated != null)
TypeSegmentTreeUpdated (this, EventArgs.Empty);
} catch (OperationCanceledException) {
}
});
}
void CancelParsedDocumentUpdate ()
{
documentParsedTokenSrc.Cancel ();
documentParsedTokenSrc = new CancellationTokenSource ();
}
public event EventHandler TypeSegmentTreeUpdated;
public void UpdateParsedDocument ()
{
HandleDocumentParsed (null, null);
}
public override bool KeyPress (KeyDescriptor descriptor)
{
bool result = base.KeyPress (descriptor);
if (/*EnableParameterInsight &&*/ (descriptor.KeyChar == ',' || descriptor.KeyChar == ')') && CanRunParameterCompletionCommand ())
base.RunParameterCompletionCommand ();
// if (IsInsideComment ())
// ParameterInformationWindowManager.HideWindow (CompletionWidget);
return result;
}
public override Task<ICompletionDataList> HandleCodeCompletionAsync (CodeCompletionContext completionContext, char completionChar, CancellationToken token = default(CancellationToken))
{
// if (!EnableCodeCompletion)
// return null;
if (!IdeApp.Preferences.EnableAutoCodeCompletion && char.IsLetter (completionChar))
return null;
// var timer = Counters.ResolveTime.BeginTiming ();
try {
int triggerWordLength = 0;
if (char.IsLetterOrDigit (completionChar) || completionChar == '_') {
if (completionContext.TriggerOffset > 1 && char.IsLetterOrDigit (Editor.GetCharAt (completionContext.TriggerOffset - 2)))
return null;
triggerWordLength = 1;
}
return InternalHandleCodeCompletion (completionContext, completionChar, false, triggerWordLength, token);
} catch (Exception e) {
LoggingService.LogError ("Unexpected code completion exception." + Environment.NewLine +
"FileName: " + DocumentContext.Name + Environment.NewLine +
"Position: line=" + completionContext.TriggerLine + " col=" + completionContext.TriggerLineOffset + Environment.NewLine +
"Line text: " + Editor.GetLineText (completionContext.TriggerLine),
e);
return null;
} finally {
// if (timer != null)
// timer.Dispose ();
}
}
class CSharpCompletionDataList : CompletionDataList
{
}
interface IListData
{
CSharpCompletionDataList List { get; set; }
}
void AddImportCompletionData (CSharpCompletionDataList result, SemanticModel semanticModel, int position, CancellationToken cancellationToken = default(CancellationToken))
{
if (result.Count == 0)
return;
var root = semanticModel.SyntaxTree.GetRoot ();
var node = root.FindNode (TextSpan.FromBounds (position, position));
var syntaxTree = root.SyntaxTree;
if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken) ||
syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken) is EnumDeclarationSyntax ||
syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken))
return;
var tokenLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition (position, cancellationToken);
if (syntaxTree.IsGlobalStatementContext (position, cancellationToken) ||
syntaxTree.IsExpressionContext (position, tokenLeftOfPosition, true, cancellationToken) ||
syntaxTree.IsStatementContext (position, tokenLeftOfPosition, cancellationToken) ||
syntaxTree.IsTypeContext (position, cancellationToken) ||
syntaxTree.IsTypeDeclarationContext (position, tokenLeftOfPosition, cancellationToken) ||
syntaxTree.IsNamespaceContext (position, cancellationToken) ||
syntaxTree.IsMemberDeclarationContext (position, tokenLeftOfPosition, cancellationToken) ||
syntaxTree.IsLabelContext (position, cancellationToken)) {
var usedNamespaces = new HashSet<string> ();
foreach (var un in semanticModel.GetUsingNamespacesInScope (node)) {
usedNamespaces.Add (un.GetFullName ());
}
var enclosingNamespaceName = semanticModel.GetEnclosingNamespace (position, cancellationToken).GetFullName ();
var stack = new Stack<INamespaceOrTypeSymbol>();
foreach (var member in semanticModel.Compilation.GlobalNamespace.GetNamespaceMembers ())
stack.Push (member);
while (stack.Count > 0) {
if (cancellationToken.IsCancellationRequested)
break;
var current = stack.Pop();
var currentNs = current as INamespaceSymbol;
if (currentNs != null) {
var currentNsName = currentNs.GetFullName ();
if (usedNamespaces.Contains (currentNsName) ||
enclosingNamespaceName == currentNsName ||
(enclosingNamespaceName.StartsWith (currentNsName) &&
enclosingNamespaceName [currentNsName.Length] == '.')) {
foreach (var member in currentNs.GetNamespaceMembers ())
stack.Push (member);
} else {
foreach (var member in currentNs.GetMembers())
stack.Push (member);
}
} else {
var type = (INamedTypeSymbol)current;
if (type.IsImplicitClass || type.IsScriptClass)
continue;
if (type.DeclaredAccessibility != Accessibility.Public) {
if (type.DeclaredAccessibility != Accessibility.Internal)
continue;
if (!type.IsAccessibleWithin (semanticModel.Compilation.Assembly))
continue;
}
result.Add (new ImportSymbolCompletionData (this, type, false));
}
}
}
}
Task<ICompletionDataList> InternalHandleCodeCompletion (CodeCompletionContext completionContext, char completionChar, bool ctrlSpace, int triggerWordLength, CancellationToken token)
{
if (Editor.EditMode != MonoDevelop.Ide.Editor.EditMode.Edit)
return null;
// var data = Editor;
// if (data.CurrentMode is TextLinkEditMode) {
// if (((TextLinkEditMode)data.CurrentMode).TextLinkMode == TextLinkMode.EditIdentifier)
// return null;
// }
var offset = Editor.CaretOffset;
var list = new CSharpCompletionDataList ();
list.TriggerWordLength = triggerWordLength;
var analysisDocument = DocumentContext.AnalysisDocument;
if (analysisDocument == null)
return null;
return Task.Run (async delegate {
try {
var partialDoc = await WithFrozenPartialSemanticsAsync (analysisDocument, token).ConfigureAwait (false);
var semanticModel = await partialDoc.GetSemanticModelAsync (token).ConfigureAwait (false);
var roslynCodeCompletionFactory = new RoslynCodeCompletionFactory (this, semanticModel);
foreach (var extHandler in additionalContextHandlers.OfType<IExtensionContextHandler> ())
extHandler.Init (roslynCodeCompletionFactory);
var engine = new CompletionEngine(MonoDevelop.Ide.TypeSystem.TypeSystemService.Workspace, roslynCodeCompletionFactory);
var ctx = new ICSharpCode.NRefactory6.CSharp.CompletionContext (partialDoc, offset, semanticModel);
ctx.AdditionalContextHandlers = additionalContextHandlers;
var triggerInfo = new CompletionTriggerInfo (ctrlSpace ? CompletionTriggerReason.CompletionCommand : CompletionTriggerReason.CharTyped, completionChar);
var completionResult = await engine.GetCompletionDataAsync (ctx, triggerInfo, token).ConfigureAwait (false);
if (completionResult == CompletionResult.Empty)
return null;
foreach (var symbol in completionResult) {
list.Add ((Ide.CodeCompletion.CompletionData)symbol);
}
if (IdeApp.Preferences.AddImportedItemsToCompletionList.Value && list.OfType<RoslynSymbolCompletionData> ().Any (cd => cd.Symbol is ITypeSymbol)) {
AddImportCompletionData (list, semanticModel, offset, token);
}
list.AutoCompleteEmptyMatch = completionResult.AutoCompleteEmptyMatch;
// list.AutoCompleteEmptyMatchOnCurlyBrace = completionResult.AutoCompleteEmptyMatchOnCurlyBracket;
list.AutoSelect = completionResult.AutoSelect;
list.DefaultCompletionString = completionResult.DefaultCompletionString;
// list.CloseOnSquareBrackets = completionResult.CloseOnSquareBrackets;
if (ctrlSpace)
list.AutoCompleteUniqueMatch = true;
} catch (OperationCanceledException) {
return null;
} catch (AggregateException e) {
foreach (var inner in e.Flatten ().InnerExceptions)
LoggingService.LogError ("Error while getting C# recommendations", inner);
} catch (Exception e) {
LoggingService.LogError ("Error while getting C# recommendations", e);
}
return (ICompletionDataList)list;
});
}
public override Task<ICompletionDataList> CodeCompletionCommand (CodeCompletionContext completionContext)
{
int triggerWordLength = 0;
char ch = completionContext.TriggerOffset > 0 ? Editor.GetCharAt (completionContext.TriggerOffset - 1) : '\0';
return InternalHandleCodeCompletion (completionContext, ch, true, triggerWordLength, default(CancellationToken));
}
static bool HasAllUsedParameters (MonoDevelop.Ide.CodeCompletion.ParameterHintingData provider, string[] list)
{
if (provider == null || list == null)
return true;
int pc = provider.ParameterCount;
foreach (var usedParam in list) {
bool found = false;
for (int m = 0; m < pc; m++) {
if (usedParam == provider.GetParameterName (m)){
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
public override int GuessBestMethodOverload (MonoDevelop.Ide.CodeCompletion.ParameterHintingResult provider, int currentOverload)
{
var analysisDocument = DocumentContext.AnalysisDocument;
if (analysisDocument == null)
return -1;
var result = ICSharpCode.NRefactory6.CSharp.ParameterUtil.GetCurrentParameterIndex (analysisDocument, provider.StartOffset, Editor.CaretOffset).Result;
var cparam = result.ParameterIndex;
var list = result.UsedNamespaceParameters;
if (cparam > provider[currentOverload].ParameterCount && !provider[currentOverload].IsParameterListAllowed || !HasAllUsedParameters (provider[currentOverload], list)) {
// Look for an overload which has more parameters
int bestOverload = -1;
int bestParamCount = int.MaxValue;
for (int n = 0; n < provider.Count; n++) {
int pc = provider[n].ParameterCount;
if (pc < bestParamCount && pc >= cparam) {
if (HasAllUsedParameters (provider[n], list)) {
bestOverload = n;
bestParamCount = pc;
}
}
}
if (bestOverload == -1) {
for (int n=0; n<provider.Count; n++) {
if (provider[n].IsParameterListAllowed && HasAllUsedParameters (provider[n], list)) {
bestOverload = n;
break;
}
}
}
return bestOverload;
}
return -1;
}
// static bool ContainsPublicConstructors (ITypeDefinition t)
// {
// if (t.Methods.Count (m => m.IsConstructor) == 0)
// return true;
// return t.Methods.Any (m => m.IsConstructor && m.IsPublic);
// }
// CompletionDataList result = new ProjectDomCompletionDataList ();
// // "var o = new " needs special treatment.
// if (returnType == null && returnTypeUnresolved != null && returnTypeUnresolved.FullName == "var")
// returnType = returnTypeUnresolved = DomReturnType.Object;
//
// // ExpressionContext.TypeExpressionContext tce = context as ExpressionContext.TypeExpressionContext;
//
// CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, callingType, location);
// IType type = null;
// if (returnType != null)
// type = dom.GetType (returnType);
// if (type == null)
// type = dom.SearchType (Document.CompilationUnit, callingType, location, returnTypeUnresolved);
//
// // special handling for nullable types: Bug 674516 - new completion for nullables should not include "Nullable"
// if (type is InstantiatedType && ((InstantiatedType)type).UninstantiatedType.FullName == "System.Nullable" && ((InstantiatedType)type).GenericParameters.Count == 1) {
// var genericParameter = ((InstantiatedType)type).GenericParameters [0];
// returnType = returnTypeUnresolved = Document.CompilationUnit.ShortenTypeName (genericParameter, location);
// type = dom.SearchType (Document.CompilationUnit, callingType, location, genericParameter);
// }
//
// if (type == null || !(type.IsAbstract || type.ClassType == ClassType.Interface)) {
// if (type == null || type.ConstructorCount == 0 || type.Methods.Any (c => c.IsConstructor && c.IsAccessibleFrom (dom, callingType, type, callingType != null && dom.GetInheritanceTree (callingType).Any (x => x.FullName == type.FullName)))) {
// if (returnTypeUnresolved != null) {
// col.FullyQualify = true;
// CompletionData unresovedCompletionData = col.Add (returnTypeUnresolved);
// col.FullyQualify = false;
// // don't set default completion string for arrays, since it interferes with:
// // string[] arr = new string[] vs new { "a"}
// if (returnTypeUnresolved.ArrayDimensions == 0)
// result.DefaultCompletionString = StripGenerics (unresovedCompletionData.CompletionText);
// } else {
// CompletionData unresovedCompletionData = col.Add (returnType);
// if (returnType.ArrayDimensions == 0)
// result.DefaultCompletionString = StripGenerics (unresovedCompletionData.CompletionText);
// }
// }
// }
//
// // if (tce != null && tce.Type != null) {
// // result.DefaultCompletionString = StripGenerics (col.AddCompletionData (result, tce.Type).CompletionString);
// // }
// // else {
// // }
// if (type == null)
// return result;
// HashSet<string > usedNamespaces = new HashSet<string> (GetUsedNamespaces ());
// if (type.FullName == DomReturnType.Object.FullName)
// AddPrimitiveTypes (col);
//
// foreach (IType curType in dom.GetSubclasses (type)) {
// if (context != null && context.FilterEntry (curType))
// continue;
// if ((curType.TypeModifier & TypeModifier.HasOnlyHiddenConstructors) == TypeModifier.HasOnlyHiddenConstructors)
// continue;
// if (usedNamespaces.Contains (curType.Namespace)) {
// if (curType.ConstructorCount > 0) {
// if (!(curType.Methods.Any (c => c.IsConstructor && c.IsAccessibleFrom (dom, curType, callingType, callingType != null && dom.GetInheritanceTree (callingType).Any (x => x.FullName == curType.FullName)))))
// continue;
// }
// col.Add (curType);
// } else {
// string nsName = curType.Namespace;
// int idx = nsName.IndexOf ('.');
// if (idx >= 0)
// nsName = nsName.Substring (0, idx);
// col.Add (new Namespace (nsName));
// }
// }
//
// // add aliases
// if (returnType != null) {
// foreach (IUsing u in Document.CompilationUnit.Usings) {
// foreach (KeyValuePair<string, IReturnType> alias in u.Aliases) {
// if (alias.Value.ToInvariantString () == returnType.ToInvariantString ())
// result.Add (alias.Key, "md-class");
// }
// }
// }
//
// return result;
// }
// IEnumerable<ICompletionData> GetDefineCompletionData ()
// {
// if (Document.Project == null)
// yield break;
//
// var symbols = new Dictionary<string, string> ();
// var cp = new ProjectDomCompletionDataList ();
// foreach (DotNetProjectConfiguration conf in Document.Project.Configurations) {
// var cparams = conf.CompilationParameters as CSharpCompilerParameters;
// if (cparams != null) {
// string[] syms = cparams.DefineSymbols.Split (';');
// foreach (string s in syms) {
// string ss = s.Trim ();
// if (ss.Length > 0 && !symbols.ContainsKey (ss)) {
// symbols [ss] = ss;
// yield return factory.CreateLiteralCompletionData (ss);
// }
// }
// }
// }
// }
public override Task<Ide.CodeCompletion.ParameterHintingResult> ParameterCompletionCommand (CodeCompletionContext completionContext)
{
char ch = completionContext.TriggerOffset > 0 ? Editor.GetCharAt (completionContext.TriggerOffset - 1) : '\0';
return InternalHandleParameterCompletionCommand (completionContext, ch, true, default(CancellationToken));
}
public override Task<MonoDevelop.Ide.CodeCompletion.ParameterHintingResult> HandleParameterCompletionAsync (CodeCompletionContext completionContext, char completionChar, CancellationToken token = default (CancellationToken))
{
return InternalHandleParameterCompletionCommand (completionContext, completionChar, false, token);
}
public async Task<MonoDevelop.Ide.CodeCompletion.ParameterHintingResult> InternalHandleParameterCompletionCommand (CodeCompletionContext completionContext, char completionChar, bool force, CancellationToken token = default(CancellationToken))
{
var data = Editor;
if (!force && completionChar != '(' && completionChar != ',')
return null;
if (Editor.EditMode != EditMode.Edit)
return null;
var offset = Editor.CaretOffset;
try {
var analysisDocument = DocumentContext.AnalysisDocument;
if (analysisDocument == null)
return null;
var partialDoc = await WithFrozenPartialSemanticsAsync (analysisDocument, token);
var semanticModel = await partialDoc.GetSemanticModelAsync ();
var engine = new ParameterHintingEngine (MonoDevelop.Ide.TypeSystem.TypeSystemService.Workspace, new RoslynParameterHintingFactory ());
var result = await engine.GetParameterDataProviderAsync (analysisDocument, semanticModel, offset, token);
return new MonoDevelop.Ide.CodeCompletion.ParameterHintingResult (result.OfType<MonoDevelop.Ide.CodeCompletion.ParameterHintingData>().ToList (), result.StartOffset);
} catch (Exception e) {
LoggingService.LogError ("Unexpected parameter completion exception." + Environment.NewLine +
"FileName: " + DocumentContext.Name + Environment.NewLine +
"Position: line=" + completionContext.TriggerLine + " col=" + completionContext.TriggerLineOffset + Environment.NewLine +
"Line text: " + Editor.GetLineText (completionContext.TriggerLine),
e);
}
return null;
}
// List<string> GetUsedNamespaces ()
// {
// var scope = CSharpUnresolvedFile.GetUsingScope (document.Editor.Caret.Location);
// var result = new List<string> ();
// while (scope != null) {
// result.Add (scope.NamespaceName);
// var ctx = CSharpUnresolvedFile.GetResolver (Document.Compilation, scope.Region.Begin);
// foreach (var u in scope.Usings) {
// var ns = u.ResolveNamespace (ctx);
// if (ns == null)
// continue;
// result.Add (ns.FullName);
// }
// scope = scope.Parent;
// }
// return result;
// }
public override int GetCurrentParameterIndex (int startOffset)
{
var analysisDocument = DocumentContext.AnalysisDocument;
if (analysisDocument == null)
return -1;
var result = ICSharpCode.NRefactory6.CSharp.ParameterUtil.GetCurrentParameterIndex (analysisDocument, startOffset, Editor.CaretOffset).Result;
return result.ParameterIndex;
}
/*
#region ICompletionDataFactory implementation
internal class CompletionDataFactory : ICompletionDataFactory
{
internal readonly CSharpCompletionTextEditorExtension ext;
// readonly CSharpResolver state;
readonly TypeSystemAstBuilder builder;
public CSharpCompletionEngine Engine {
get;
set;
}
public CompletionDataFactory (CSharpCompletionTextEditorExtension ext, CSharpResolver state)
{
// this.state = state;
if (state != null)
builder = new TypeSystemAstBuilder(state);
this.ext = ext;
}
ICompletionData ICompletionDataFactory.CreateEntityCompletionData (IEntity entity)
{
return new MemberCompletionData (this, entity, OutputFlags.IncludeGenerics | OutputFlags.HideArrayBrackets | OutputFlags.IncludeParameterName) {
HideExtensionParameter = true
};
}
class GenericTooltipCompletionData : CompletionData, IListData
{
readonly Func<CSharpCompletionDataList, bool, TooltipInformation> tooltipFunc;
#region IListData implementation
CSharpCompletionDataList list;
public CSharpCompletionDataList List {
get {
return list;
}
set {
list = value;
if (overloads != null) {
foreach (var overload in overloads.Skip (1)) {
var ld = overload as IListData;
if (ld != null)
ld.List = list;
}
}
}
}
#endregion
public GenericTooltipCompletionData (Func<CSharpCompletionDataList, bool, TooltipInformation> tooltipFunc, string text, string icon) : base (text, icon)
{
this.tooltipFunc = tooltipFunc;
}
public GenericTooltipCompletionData (Func<CSharpCompletionDataList, bool, TooltipInformation> tooltipFunc, string text, string icon, string description, string completionText) : base (text, icon, description, completionText)
{
this.tooltipFunc = tooltipFunc;
}
public override TooltipInformation CreateTooltipInformation (bool smartWrap)
{
return tooltipFunc != null ? tooltipFunc (List, smartWrap) : new TooltipInformation ();
}
protected List<ICompletionData> overloads;
public override bool HasOverloads {
get { return overloads != null && overloads.Count > 0; }
}
public override IEnumerable<ICompletionData> OverloadedData {
get {
return overloads;
}
}
public override void AddOverload (ICSharpCode.NRefactory.Completion.ICompletionData data)
{
if (overloads == null) {
overloads = new List<ICompletionData> ();
overloads.Add (this);
}
overloads.Add (data);
}
public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, KeyDescriptor descriptor)
{
var currentWord = GetCurrentWord (window);
if (CompletionText == "new()" && descriptor.KeyChar == '(') {
window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, currentWord, "new");
} else {
window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, currentWord, CompletionText);
}
}
}
class LazyGenericTooltipCompletionData : GenericTooltipCompletionData
{
Lazy<string> displayText;
public override string DisplayText {
get {
return displayText.Value;
}
}
public override string CompletionText {
get {
return displayText.Value;
}
}
public LazyGenericTooltipCompletionData (Func<CSharpCompletionDataList, bool, TooltipInformation> tooltipFunc, Lazy<string> displayText, string icon) : base (tooltipFunc, null, icon)
{
this.displayText = displayText;
}
}
class TypeCompletionData : LazyGenericTooltipCompletionData, IListData
{
IType type;
CSharpCompletionTextEditorExtension ext;
CSharpUnresolvedFile file;
ICompilation compilation;
// CSharpResolver resolver;
string IdString {
get {
return DisplayText + type.TypeParameterCount;
}
}
public override string CompletionText {
get {
if (type.TypeParameterCount > 0 && !type.IsParameterized)
return type.Name;
return base.CompletionText;
}
}
public override TooltipInformation CreateTooltipInformation (bool smartWrap)
{
var def = type.GetDefinition ();
var result = def != null ? MemberCompletionData.CreateTooltipInformation (compilation, file, List.Resolver, ext.Editor, ext.FormattingPolicy, def, smartWrap) : new TooltipInformation ();
if (ConflictingTypes != null) {
var conflicts = new StringBuilder ();
var sig = new SignatureMarkupCreator (List.Resolver, ext.FormattingPolicy.CreateOptions ());
for (int i = 0; i < ConflictingTypes.Count; i++) {
var ct = ConflictingTypes[i];
if (i > 0)
conflicts.AppendLine (",");
// if ((i + 1) % 5 == 0)
// conflicts.Append (Environment.NewLine + "\t");
conflicts.Append (sig.GetTypeReferenceString (((TypeCompletionData)ct).type));
}
result.AddCategory ("Type Conflicts", conflicts.ToString ());
}
return result;
}
public TypeCompletionData (IType type, CSharpCompletionTextEditorExtension ext, Lazy<string> displayText, string icon, bool addConstructors) : base (null, displayText, icon)
{
this.type = type;
this.ext = ext;
this.file = ext.CSharpUnresolvedFile;
this.compilation = ext.UnresolvedFileCompilation;
}
Dictionary<string, ICSharpCode.NRefactory.Completion.ICompletionData> addedDatas = new Dictionary<string, ICSharpCode.NRefactory.Completion.ICompletionData> ();
List<ICompletionData> ConflictingTypes = null;
public override void AddOverload (ICSharpCode.NRefactory.Completion.ICompletionData data)
{
if (overloads == null)
addedDatas [IdString] = this;
if (data is TypeCompletionData) {
string id = ((TypeCompletionData)data).IdString;
ICompletionData oldData;
if (addedDatas.TryGetValue (id, out oldData)) {
var old = (TypeCompletionData)oldData;
if (old.ConflictingTypes == null)
old.ConflictingTypes = new List<ICompletionData> ();
old.ConflictingTypes.Add (data);
return;
}
addedDatas [id] = data;
}
base.AddOverload (data);
}
}
ICompletionData ICompletionDataFactory.CreateEntityCompletionData (IEntity entity, string text)
{
return new GenericTooltipCompletionData ((list, sw) => MemberCompletionData.CreateTooltipInformation (ext, list.Resolver, entity, sw), text, entity.GetStockIcon ());
}
ICompletionData ICompletionDataFactory.CreateTypeCompletionData (IType type, bool showFullName, bool isInAttributeContext, bool addConstructors)
{
if (addConstructors) {
ICompletionData constructorResult = null;
foreach (var ctor in type.GetConstructors ()) {
if (constructorResult != null) {
constructorResult.AddOverload (((ICompletionDataFactory)this).CreateEntityCompletionData (ctor));
} else {
constructorResult = ((ICompletionDataFactory)this).CreateEntityCompletionData (ctor);
}
}
return constructorResult;
}
Lazy<string> displayText = new Lazy<string> (delegate {
string name = showFullName ? builder.ConvertType(type).ToString() : type.Name;
if (isInAttributeContext && name.EndsWith("Attribute") && name.Length > "Attribute".Length) {
name = name.Substring(0, name.Length - "Attribute".Length);
}
return name;
});
var result = new TypeCompletionData (type, ext,
displayText,
type.GetStockIcon (),
addConstructors);
return result;
}
ICompletionData ICompletionDataFactory.CreateMemberCompletionData(IType type, IEntity member)
{
Lazy<string> displayText = new Lazy<string> (delegate {
string name = builder.ConvertType(type).ToString();
return name + "."+ member.Name;
});
var result = new LazyGenericTooltipCompletionData (
(List, sw) => new TooltipInformation (),
displayText,
member.GetStockIcon ());
return result;
}
ICompletionData ICompletionDataFactory.CreateLiteralCompletionData (string title, string description, string insertText)
{
return new GenericTooltipCompletionData ((list, smartWrap) => {
var sig = new SignatureMarkupCreator (list.Resolver, ext.FormattingPolicy.CreateOptions ());
sig.BreakLineAfterReturnType = smartWrap;
return sig.GetKeywordTooltip (title, null);
}, title, "md-keyword", description, insertText ?? title);
}
class XmlDocCompletionData : CompletionData, IListData
{
readonly CSharpCompletionTextEditorExtension ext;
readonly string title;
#region IListData implementation
CSharpCompletionDataList list;
public CSharpCompletionDataList List {
get {
return list;
}
set {
list = value;
}
}
#endregion
public XmlDocCompletionData (CSharpCompletionTextEditorExtension ext, string title, string description, string insertText) : base (title, "md-keyword", description, insertText ?? title)
{
this.ext = ext;
this.title = title;
}
public override TooltipInformation CreateTooltipInformation (bool smartWrap)
{
var sig = new SignatureMarkupCreator (List.Resolver, ext.FormattingPolicy.CreateOptions ());
sig.BreakLineAfterReturnType = smartWrap;
return sig.GetKeywordTooltip (title, null);
}
public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, KeyDescriptor descriptor)
{
var currentWord = GetCurrentWord (window);
var text = CompletionText;
if (descriptor.KeyChar != '>')
text += ">";
window.CompletionWidget.SetCompletionText (window.CodeCompletionContext, currentWord, text);
}
}
ICompletionData ICompletionDataFactory.CreateXmlDocCompletionData (string title, string description, string insertText)
{
return new XmlDocCompletionData (ext, title, description, insertText);
}
ICompletionData ICompletionDataFactory.CreateNamespaceCompletionData (INamespace name)
{
return new CompletionData (name.Name, AstStockIcons.Namespace, "", CSharpAmbience.FilterName (name.Name));
}
ICompletionData ICompletionDataFactory.CreateVariableCompletionData (IVariable variable)
{
return new VariableCompletionData (ext, variable);
}
ICompletionData ICompletionDataFactory.CreateVariableCompletionData (ITypeParameter parameter)
{
return new CompletionData (parameter.Name, parameter.GetStockIcon ());
}
ICompletionData ICompletionDataFactory.CreateEventCreationCompletionData (string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType)
{
return new EventCreationCompletionData (ext, varName, delegateType, evt, parameterDefinition, currentMember, currentType);
}
ICompletionData ICompletionDataFactory.CreateNewOverrideCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IMember m)
{
return new NewOverrideCompletionData (ext, declarationBegin, type, m);
}
ICompletionData ICompletionDataFactory.CreateNewPartialCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m)
{
var ctx = ext.CSharpUnresolvedFile.GetTypeResolveContext (ext.UnresolvedFileCompilation, ext.Editor.CaretLocation);
return new NewOverrideCompletionData (ext, declarationBegin, type, m.CreateResolved (ctx));
}
IEnumerable<ICompletionData> ICompletionDataFactory.CreateCodeTemplateCompletionData ()
{
var result = new CompletionDataList ();
if (EnableAutoCodeCompletion || IncludeCodeSnippetsInCompletionList.Value) {
CodeTemplateService.AddCompletionDataForMime ("text/x-csharp", result);
}
return result;
}
IEnumerable<ICompletionData> ICompletionDataFactory.CreatePreProcessorDefinesCompletionData ()
{
var project = ext.DocumentContext.Project;
if (project == null)
yield break;
var configuration = project.GetConfiguration (MonoDevelop.Ide.IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration;
if (configuration == null)
yield break;
foreach (var define in configuration.GetDefineSymbols ())
yield return new CompletionData (define, "md-keyword");
}
class FormatItemCompletionData : CompletionData
{
string format;
string description;
object example;
public FormatItemCompletionData (string format, string description, object example)
{
this.format = format;
this.description = description;
this.example = example;
}
public override string DisplayText {
get {
return format;
}
}
public override string GetDisplayDescription (bool isSelected)
{
return "- <span foreground=\"darkgray\" size='small'>" + description + "</span>";
}
string rightSideDescription = null;
public override string GetRightSideDescription (bool isSelected)
{
if (rightSideDescription == null) {
try {
rightSideDescription = "<span size='small'>" + string.Format ("{0:" +format +"}", example) +"</span>";
} catch (Exception e) {
rightSideDescription = "";
LoggingService.LogError ("Format error.", e);
}
}
return rightSideDescription;
}
public override string CompletionText {
get {
return format;
}
}
public override int CompareTo (object obj)
{
return 0;
}
}
ICompletionData ICompletionDataFactory.CreateFormatItemCompletionData(string format, string description, object example)
{
return new FormatItemCompletionData (format, description, example);
}
#endregion
*/
#region IDebuggerExpressionResolver implementation
async Task<DebugDataTipInfo> IDebuggerExpressionResolver.ResolveExpressionAsync (IReadonlyTextDocument editor, DocumentContext doc, int offset, CancellationToken cancellationToken)
{
return await Resolver.DebuggerExpressionResolver.ResolveAsync (editor, doc, offset, cancellationToken);
}
#endregion
#region TypeSystemSegmentTree
TypeSystemSegmentTree validTypeSystemSegmentTree;
internal class TypeSystemTreeSegment : TreeSegment
{
public SyntaxNode Entity {
get;
private set;
}
public TypeSystemTreeSegment (int offset, int length, SyntaxNode entity) : base (offset, length)
{
this.Entity = entity;
}
}
internal TypeSystemTreeSegment GetMemberSegmentAt (int offset)
{
TypeSystemTreeSegment result = null;
if (result == null && validTypeSystemSegmentTree != null)
result = validTypeSystemSegmentTree.GetMemberSegmentAt (offset);
return result;
}
internal class TypeSystemSegmentTree : SegmentTree<TypeSystemTreeSegment>
{
public SyntaxNode GetMemberAt (int offset)
{
// Members don't overlap
var seg = GetSegmentsAt (offset).FirstOrDefault ();
if (seg == null)
return null;
return seg.Entity;
}
public TypeSystemTreeSegment GetMemberSegmentAt (int offset)
{
return GetSegmentsAt (offset).LastOrDefault ();
}
internal static TypeSystemSegmentTree Create (SemanticModel semanticModel, CancellationToken token)
{
var visitor = new TreeVisitor (token);
visitor.Visit (semanticModel.SyntaxTree.GetRoot ());
return visitor.Result;
}
class TreeVisitor : CSharpSyntaxWalker
{
readonly CancellationToken token;
public TypeSystemSegmentTree Result = new TypeSystemSegmentTree ();
public TreeVisitor (System.Threading.CancellationToken token)
{
this.token = token;
}
public override void VisitClassDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
base.VisitClassDeclaration (node);
}
public override void VisitStructDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
base.VisitStructDeclaration (node);
}
public override void VisitInterfaceDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
base.VisitInterfaceDeclaration (node);
}
public override void VisitEnumDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitPropertyDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitMethodDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitConstructorDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.ConstructorDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitDestructorDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.DestructorDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitIndexerDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.IndexerDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitDelegateDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.DelegateDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitOperatorDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.OperatorDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitEventDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.EventDeclarationSyntax node)
{
Result.Add (new TypeSystemTreeSegment (node.SpanStart, node.Span.Length, node));
}
public override void VisitBlock (Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax node)
{
token.ThrowIfCancellationRequested ();
}
}
}
public SyntaxNode GetMemberAt (int offset)
{
SyntaxNode member = null;
if (member == null && validTypeSystemSegmentTree != null)
member = validTypeSystemSegmentTree.GetMemberAt (offset);
return member;
}
#endregion
[CommandHandler(RefactoryCommands.ImportSymbol)]
async void ImportSymbolCommand ()
{
if (Editor.SelectionMode == SelectionMode.Block)
return;
var analysisDocument = DocumentContext.AnalysisDocument;
if (analysisDocument == null)
return;
var offset = Editor.CaretOffset;
ICompletionDataList completionList = null;
int cpos, wlen;
if (!GetCompletionCommandOffset (out cpos, out wlen)) {
cpos = Editor.CaretOffset;
wlen = 0;
}
CurrentCompletionContext = CompletionWidget.CreateCodeCompletionContext (cpos);
CurrentCompletionContext.TriggerWordLength = wlen;
var list = new CSharpCompletionDataList ();
list.TriggerWordLength = wlen;
var partialDoc = await WithFrozenPartialSemanticsAsync (analysisDocument, default (CancellationToken));
var semanticModel = await partialDoc.GetSemanticModelAsync ();
AddImportCompletionData (list, semanticModel, offset);
completionList = await CodeCompletionCommand (CurrentCompletionContext);
if (completionList != null)
CompletionWindowManager.ShowWindow (this, (char)0, completionList, CompletionWidget, CurrentCompletionContext);
else
CurrentCompletionContext = null;
}
}
}
|