forked from Azure/bicep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBicepCompletionProvider.cs
1936 lines (1658 loc) · 101 KB
/
BicepCompletionProvider.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Azure.Deployments.Core.Comparers;
using Bicep.Core;
using Bicep.Core.Diagnostics;
using Bicep.Core.Emit;
using Bicep.Core.Extensions;
using Bicep.Core.FileSystem;
using Bicep.Core.Parsing;
using Bicep.Core.Resources;
using Bicep.Core.Semantics;
using Bicep.Core.Semantics.Namespaces;
using Bicep.Core.Syntax;
using Bicep.Core.Text;
using Bicep.Core.TypeSystem;
using Bicep.Core.Workspaces;
using Bicep.LanguageServer.Extensions;
using Bicep.LanguageServer.Snippets;
using Bicep.LanguageServer.Telemetry;
using Bicep.LanguageServer.Utils;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
using SymbolKind = Bicep.Core.Semantics.SymbolKind;
namespace Bicep.LanguageServer.Completions
{
public class BicepCompletionProvider : ICompletionProvider
{
private const string MarkdownNewLine = " \n";
private static readonly Container<string> ResourceSymbolCommitChars = new(":");
private static readonly Container<string> PropertyAccessCommitChars = new(".");
private static readonly Regex ModuleRegistryWithoutAliasPattern = new Regex(@"'br:(.*?):?'?$", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
private static readonly Regex ModuleRegistryWithAliasPattern = new Regex(@"'br/(.*?):(.*?):?'?$", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
private readonly IFileResolver FileResolver;
private readonly ISnippetsProvider SnippetsProvider;
public readonly IModuleReferenceCompletionProvider moduleReferenceCompletionProvider;
public BicepCompletionProvider(IFileResolver fileResolver, ISnippetsProvider snippetsProvider, IModuleReferenceCompletionProvider moduleReferenceCompletionProvider)
{
this.FileResolver = fileResolver;
this.SnippetsProvider = snippetsProvider;
this.moduleReferenceCompletionProvider = moduleReferenceCompletionProvider;
}
public async Task<IEnumerable<CompletionItem>> GetFilteredCompletions(Compilation compilation, BicepCompletionContext context, CancellationToken cancellationToken)
{
var model = compilation.GetEntrypointSemanticModel();
return GetDeclarationCompletions(model, context)
.Concat(GetSymbolCompletions(model, context))
.Concat(GetDeclarationTypeCompletions(model, context))
.Concat(GetObjectPropertyNameCompletions(model, context))
.Concat(GetMemberAccessCompletions(compilation, context))
.Concat(GetResourceAccessCompletions(compilation, context))
.Concat(GetArrayIndexCompletions(compilation, context))
.Concat(GetPropertyValueCompletions(model, context))
.Concat(GetArrayItemCompletions(model, context))
.Concat(GetResourceTypeCompletions(model, context))
.Concat(GetResourceTypeFollowerCompletions(context))
.Concat(GetLocalModulePathCompletions(model, context))
.Concat(GetModuleBodyCompletions(model, context))
.Concat(GetResourceBodyCompletions(model, context))
.Concat(GetParameterDefaultValueCompletions(model, context))
.Concat(GetVariableValueCompletions(context))
.Concat(GetOutputValueCompletions(model, context))
.Concat(GetOutputTypeFollowerCompletions(context))
.Concat(GetTargetScopeCompletions(model, context))
.Concat(GetImportCompletions(model, context))
.Concat(GetFunctionParamCompletions(model, context))
.Concat(GetExpressionCompletions(model, context))
.Concat(GetDisableNextLineDiagnosticsDirectiveCompletion(context))
.Concat(GetDisableNextLineDiagnosticsDirectiveCodesCompletion(model, context))
.Concat(GetParamIdentifierCompletions(model, context))
.Concat(GetParamValueCompletions(model, context))
.Concat(GetUsingDeclarationPathCompletions(model, context))
.Concat(await moduleReferenceCompletionProvider.GetFilteredCompletions(model.SourceFile.FileUri, context, cancellationToken));
}
private IEnumerable<CompletionItem> GetParamIdentifierCompletions(SemanticModel paramsSemanticModel, BicepCompletionContext paramsCompletionContext)
{
if (paramsCompletionContext.Kind.HasFlag(BicepCompletionContextKind.ParamIdentifier) &&
paramsSemanticModel.Root.TryGetBicepFileSemanticModelViaUsing(out var bicepSemanticModel, out _))
{
var bicepFileParamDeclarations = bicepSemanticModel.Root.ParameterDeclarations;
foreach (var declaration in bicepFileParamDeclarations)
{
if (!IsParamAssigned(declaration))
{
yield return CreateSymbolCompletion(declaration, paramsCompletionContext.ReplacementRange, bicepSemanticModel);
}
}
}
bool IsParamAssigned(ParameterSymbol declaration) => paramsSemanticModel.Binder.FileSymbol.ParameterAssignments.Any(paramDeclaration => paramDeclaration.Name == declaration.Name);
}
private IEnumerable<CompletionItem> GetParamValueCompletions(SemanticModel paramsSemanticModel, BicepCompletionContext paramsCompletionContext)
{
if (!paramsCompletionContext.Kind.HasFlag(BicepCompletionContextKind.ParamValue) ||
paramsCompletionContext.EnclosingDeclaration is not ParameterAssignmentSyntax paramAssignment)
{
return Enumerable.Empty<CompletionItem>();
}
var declaredType = paramsSemanticModel.GetDeclaredType(paramAssignment);
// loops are not allowed in param files... yet!
return GetValueCompletionsForType(paramsSemanticModel, paramsCompletionContext, declaredType, loopsAllowed: false);
}
private IEnumerable<CompletionItem> GetUsingDeclarationPathCompletions(SemanticModel paramsSemanticModel, BicepCompletionContext paramsCompletionContext)
{
if (!paramsCompletionContext.Kind.HasFlag(BicepCompletionContextKind.UsingFilePath))
{
return Enumerable.Empty<CompletionItem>();
}
if(paramsCompletionContext.EnclosingDeclaration is not UsingDeclarationSyntax usingDeclarationSyntax ||
usingDeclarationSyntax.Path is not StringSyntax stringSyntax ||
stringSyntax.TryGetLiteralValue() is not string entered)
{
entered = "";
}
// These should only fail if we're not able to resolve cwd path or the entered string
if (TryGetFilesForPathCompletions(paramsSemanticModel.SourceFile.FileUri, entered) is not {} fileCompletionInfo)
{
return Enumerable.Empty<CompletionItem>();
}
// Prioritize .bicep files higher than other files.
var bicepFileItems = CreateFileCompletionItems(paramsSemanticModel.SourceFile.FileUri, paramsCompletionContext.ReplacementRange, fileCompletionInfo, IsBicepFile, CompletionPriority.High);
var dirItems = CreateDirectoryCompletionItems(paramsCompletionContext.ReplacementRange, fileCompletionInfo);
return bicepFileItems.Concat(dirItems);
bool IsBicepFile(Uri fileUri) => PathHelper.HasBicepExtension(fileUri);
}
private IEnumerable<CompletionItem> GetDeclarationCompletions(SemanticModel model, BicepCompletionContext context)
{
if (context.Kind.HasFlag(BicepCompletionContextKind.TopLevelDeclarationStart))
{
switch (model.SourceFileKind)
{
case BicepSourceFileKind.BicepFile:
yield return CreateKeywordCompletion(LanguageConstants.MetadataKeyword, "Metadata keyword", context.ReplacementRange);
yield return CreateKeywordCompletion(LanguageConstants.ParameterKeyword, "Parameter keyword", context.ReplacementRange);
yield return CreateKeywordCompletion(LanguageConstants.VariableKeyword, "Variable keyword", context.ReplacementRange);
yield return CreateKeywordCompletion(LanguageConstants.ResourceKeyword, "Resource keyword", context.ReplacementRange, priority: CompletionPriority.High);
yield return CreateKeywordCompletion(LanguageConstants.OutputKeyword, "Output keyword", context.ReplacementRange);
yield return CreateKeywordCompletion(LanguageConstants.ModuleKeyword, "Module keyword", context.ReplacementRange);
yield return CreateKeywordCompletion(LanguageConstants.TargetScopeKeyword, "Target Scope keyword", context.ReplacementRange);
if (model.Features.ExtensibilityEnabled)
{
yield return CreateKeywordCompletion(LanguageConstants.ImportKeyword, "Import keyword", context.ReplacementRange);
}
if (model.Features.UserDefinedFunctionsEnabled)
{
yield return CreateContextualSnippetCompletion(
LanguageConstants.FunctionKeyword,
"Function declaration",
"func ${1:name}() ${2:outputType} => $0",
context.ReplacementRange);
}
foreach (Snippet resourceSnippet in SnippetsProvider.GetTopLevelNamedDeclarationSnippets())
{
string prefix = resourceSnippet.Prefix;
BicepTelemetryEvent telemetryEvent = BicepTelemetryEvent.CreateTopLevelDeclarationSnippetInsertion(prefix);
var command = TelemetryHelper.CreateCommand
(
title: "top level snippet completion",
name: TelemetryConstants.CommandName,
args: JArray.FromObject(new List<object> { telemetryEvent })
);
yield return CreateContextualSnippetCompletion(prefix,
resourceSnippet.Detail,
resourceSnippet.Text,
context.ReplacementRange,
command,
resourceSnippet.CompletionPriority);
}
break;
case BicepSourceFileKind.ParamsFile:
// the using declaration is a singleton
// we should not offer completions for it more than once
if (model.Root.UsingDeclarationSyntax is null)
{
yield return CreateKeywordCompletion(LanguageConstants.UsingKeyword, "Using keyword", context.ReplacementRange);
}
yield return CreateKeywordCompletion(LanguageConstants.ParameterKeyword, "Parameter assignment keyword", context.ReplacementRange);
break;
default:
throw new NotImplementedException($"Unexpected source file kind '{model.SourceFileKind}'.");
}
}
if (context.Kind.HasFlag(BicepCompletionContextKind.NestedResourceDeclarationStart) && context.EnclosingDeclaration is ResourceDeclarationSyntax resourceDeclarationSyntax)
{
yield return CreateKeywordCompletion(LanguageConstants.ResourceKeyword, "Resource keyword", context.ReplacementRange);
if (model.GetSymbolInfo(resourceDeclarationSyntax) is ResourceSymbol parentSymbol &&
parentSymbol.TryGetResourceTypeReference() is ResourceTypeReference parentTypeReference)
{
foreach (Snippet snippet in SnippetsProvider.GetNestedResourceDeclarationSnippets(parentTypeReference))
{
string prefix = snippet.Prefix;
BicepTelemetryEvent telemetryEvent = BicepTelemetryEvent.CreateNestedResourceDeclarationSnippetInsertion(prefix);
var command = TelemetryHelper.CreateCommand
(
title: "nested resource declaration completion snippet",
name: TelemetryConstants.CommandName,
args: JArray.FromObject(new List<object> { telemetryEvent })
);
yield return CreateContextualSnippetCompletion(prefix,
snippet.Detail,
snippet.Text,
context.ReplacementRange,
command,
snippet.CompletionPriority,
preselect: true);
}
}
}
}
private IEnumerable<CompletionItem> GetTargetScopeCompletions(SemanticModel model, BicepCompletionContext context)
{
return context.Kind.HasFlag(BicepCompletionContextKind.TargetScope) && context.TargetScope is { } targetScope
? GetValueCompletionsForType(model, context, model.GetDeclaredType(targetScope), loopsAllowed: false)
: Enumerable.Empty<CompletionItem>();
}
private IEnumerable<CompletionItem> GetSymbolCompletions(SemanticModel model, BicepCompletionContext context)
{
if (!context.Kind.HasFlag(BicepCompletionContextKind.Expression) &&
!context.Kind.HasFlag(BicepCompletionContextKind.DecoratorName))
{
return Enumerable.Empty<CompletionItem>();
}
if (context.Kind.HasFlag(BicepCompletionContextKind.DecoratorName | BicepCompletionContextKind.MemberAccess))
{
// This is already handled by GetMemberAccessCompletions.
return Enumerable.Empty<CompletionItem>();
}
if (context.Property != null && model.GetDeclaredTypeAssignment(context.Property)?.Flags == DeclaredTypeFlags.Constant)
{
// the enclosing property's declared type is supposed to be a constant value
// the constant flag comes from TypeProperty constant flag, so nothing else can really alter it except for another property
// (in other words constant flag inherits down into the expression tree of the property value)
return Enumerable.Empty<CompletionItem>();
}
// when we're inside an expression that is inside a property that expects a compile-time constant value,
// we should not be emitting accessible symbol completions
return GetAccessibleSymbolCompletions(model, context);
}
private IEnumerable<CompletionItem> GetDeclarationTypeCompletions(SemanticModel model, BicepCompletionContext context)
{
if (context.Kind.HasFlag(BicepCompletionContextKind.ParameterType))
{
var completions = GetAmbientTypeCompletions(model, context).Concat(GetParameterTypeSnippets(model.Compilation, context));
// Only show the aggregate type completions if the feature is enabled
if (model.Features.UserDefinedTypesEnabled)
{
completions = completions.Concat(GetUserDefinedTypeCompletions(model, context));
}
// Only show the resource type as a completion if the resource-typed parameter feature is enabled.
if (model.Features.ResourceTypedParamsAndOutputsEnabled)
{
completions = completions.Concat(CreateResourceTypeKeywordCompletion(context.ReplacementRange));
}
return completions;
}
if (context.Kind.HasFlag(BicepCompletionContextKind.TypeDeclarationValue))
{
return GetAmbientTypeCompletions(model, context).Concat(GetUserDefinedTypeCompletions(model, context, declaredType => !ReferenceEquals(declaredType.DeclaringType, context.EnclosingDeclaration)));
}
if (context.Kind.HasFlag(BicepCompletionContextKind.ObjectTypePropertyValue))
{
return GetAmbientTypeCompletions(model, context).Concat(GetUserDefinedTypeCompletions(model, context));
}
if (context.Kind.HasFlag(BicepCompletionContextKind.UnionTypeMember))
{
// union types must be composed of literals, so don't include primitive types or non-literal user defined types
var cyclableType = CyclableTypeEnclosingDeclaration(model.Binder, context.ReplacementTarget);
return GetUserDefinedTypeCompletions(model, context, declared => !ReferenceEquals(declared.DeclaringType, cyclableType) && IsTypeLiteralSyntax(declared.DeclaringType.Value));
}
if (context.Kind.HasFlag(BicepCompletionContextKind.TypedLocalVariableType) ||
context.Kind.HasFlag(BicepCompletionContextKind.TypedLambdaOutputType))
{
// user-defined functions don't yet support user-defined types
return GetAmbientTypeCompletions(model, context);
}
if (context.Kind.HasFlag(BicepCompletionContextKind.OutputType))
{
var completions = GetAmbientTypeCompletions(model, context);
// Only show the aggregate type completions if the feature is enabled
if (model.Features.UserDefinedTypesEnabled)
{
completions = completions.Concat(GetUserDefinedTypeCompletions(model, context));
}
// Only show the resource type as a completion if the resource-typed parameter feature is enabled.
if (model.Features.ResourceTypedParamsAndOutputsEnabled)
{
completions = completions.Concat(CreateResourceTypeKeywordCompletion(context.ReplacementRange));
}
return completions;
}
return Enumerable.Empty<CompletionItem>();
}
private static IEnumerable<CompletionItem> GetAmbientTypeCompletions(SemanticModel model, BicepCompletionContext context) => model.Binder.NamespaceResolver.GetKnownTypes()
.ToLookup(ambientType => ambientType.Name)
.SelectMany(grouping => grouping.Count() > 1 || model.Binder.FileSymbol.Declarations.Any(decl => LanguageConstants.IdentifierComparer.Equals(grouping.Key, decl.Name))
? grouping.Select(ambientType => ($"{ambientType.DeclaringNamespace.Name}.{ambientType.Name}", ambientType))
: grouping.Select(ambientType => (ambientType.Name, ambientType)))
.Select(tuple => CreateTypeCompletion(tuple.Item1, tuple.ambientType, context.ReplacementRange));
private static IEnumerable<CompletionItem> GetUserDefinedTypeCompletions(SemanticModel model, BicepCompletionContext context, Func<TypeAliasSymbol, bool>? filter = null)
{
IEnumerable<TypeAliasSymbol> declarationsForCompletions = model.Binder.FileSymbol.TypeDeclarations;
if (filter is not null)
{
declarationsForCompletions = declarationsForCompletions.Where(filter);
}
return declarationsForCompletions.Select(declaredType => CreateDeclaredTypeCompletion(declaredType, context.ReplacementRange, CompletionPriority.High));
}
private static bool IsTypeLiteralSyntax(SyntaxBase syntax) => syntax is BooleanLiteralSyntax
|| syntax is IntegerLiteralSyntax
|| (syntax is StringSyntax @string && @string.TryGetLiteralValue() is string literal)
|| syntax is UnionTypeSyntax
|| (syntax is ObjectTypeSyntax objectType && objectType.Properties.All(p => IsTypeLiteralSyntax(p.Value)))
|| (syntax is TupleTypeSyntax tupleType && tupleType.Items.All(i => IsTypeLiteralSyntax(i.Value)));
private static StatementSyntax? CyclableTypeEnclosingDeclaration(IBinder binder, SyntaxBase? syntax) => syntax switch
{
StatementSyntax statement => statement,
// Aggregate types have special rules around cycles and nullability. Stop looking for cycles if you hit one while climbing the syntax hierarchy for a given type declaration
ArrayTypeMemberSyntax or ObjectTypePropertySyntax or TupleTypeItemSyntax => null,
SyntaxBase otherwise => CyclableTypeEnclosingDeclaration(binder, binder.GetParent(otherwise)),
null => null,
};
private static string? TryGetSkippedTokenText(SkippedTriviaSyntax skippedTrivia)
{
// This method attempts to obtain text from a skipped token - in cases where the user has partially-typed syntax
// but may be looking for completions.
if (skippedTrivia.Elements.Length != 1 ||
skippedTrivia.Elements[0] is not Token token)
{
return null;
}
switch (token.Type)
{
case TokenType.Identifier:
return token.Text;
case TokenType.StringComplete:
if (!token.Text.EndsWith("'", StringComparison.Ordinal))
{
// An unterminated string will result in skipped trivia containing an unterminated token.
// Compensate here by building the expected token before lexing it.
token = SyntaxFactory.CreateFreeformToken(token.Type, $"{token.Text}'");
}
return Lexer.TryGetStringValue(token);
default:
return null;
}
}
private static string? TryGetEnteredTextFromStringOrSkipped(SyntaxBase syntax)
=> syntax switch {
StringSyntax s => s.TryGetLiteralValue(),
SkippedTriviaSyntax s => TryGetSkippedTokenText(s),
_ => null,
};
private IEnumerable<CompletionItem> GetResourceTypeCompletions(SemanticModel model, BicepCompletionContext context)
{
if (!context.Kind.HasFlag(BicepCompletionContextKind.ResourceType))
{
return Enumerable.Empty<CompletionItem>();
}
// For a nested resource, we want to filter the set of types.
//
// The strategy when *can't* filter - due to errors - to fallback to the main path and offer full completions
// then once the user corrects whatever's cause the error, they will be told to simplify the type.
if (context.EnclosingDeclaration is SyntaxBase &&
model.Binder.GetNearestAncestor<ResourceDeclarationSyntax>(context.EnclosingDeclaration) is ResourceDeclarationSyntax parentSyntax &&
model.GetSymbolInfo(parentSyntax) is ResourceSymbol parentSymbol &&
parentSymbol.TryGetResourceType() is { } parentResourceType)
{
// This is more complex because we allow the API version to be omitted, so we want to make a list of unique values
// for the FQT, and then create a "no version" completion + a completion for each version.
var filtered = parentResourceType.DeclaringNamespace.ResourceTypeProvider.GetAvailableTypes()
.Where(rt => parentResourceType.TypeReference.IsParentOf(rt))
.ToLookup(rt => rt.FormatType());
var index = 0;
var items = new List<CompletionItem>();
foreach (var group in filtered.OrderBy(group => group.Key, StringComparer.OrdinalIgnoreCase))
{
// Doesn't matter which one of the group we take, we're leaving out the version.
items.Add(CreateResourceTypeSegmentCompletion(group.First(), index++, context.ReplacementRange, includeApiVersion: false, displayApiVersion: parentResourceType.TypeReference.ApiVersion));
foreach (var resourceType in group.Where(rt => rt.ApiVersion is not null).OrderByDescending(rt => rt.ApiVersion, ApiVersionComparer.Instance))
{
items.Add(CreateResourceTypeSegmentCompletion(resourceType, index++, context.ReplacementRange, includeApiVersion: true, displayApiVersion: resourceType.ApiVersion));
}
}
return items;
}
static string? TryGetFullyQualifiedType(SyntaxBase? syntax)
{
if (syntax is not null &&
TryGetEnteredTextFromStringOrSkipped(syntax) is {} entered &&
ResourceTypeReference.HasResourceTypePrefix(entered))
{
return entered;
}
return null;
}
static string? TryGetFullyQualfiedResourceType(SyntaxBase? enclosingDeclaration)
{
return enclosingDeclaration switch
{
ResourceDeclarationSyntax resourceSyntax => TryGetFullyQualifiedType(resourceSyntax.Type),
ParameterDeclarationSyntax parameterSyntax when parameterSyntax.Type is ResourceTypeSyntax resourceType => TryGetFullyQualifiedType(resourceType.Type),
OutputDeclarationSyntax outputSyntax when outputSyntax.Type is ResourceTypeSyntax resourceType => TryGetFullyQualifiedType(resourceType.Type),
_ => null,
};
}
// ResourceType completions are divided into 2 parts.
// If the current value passes the namespace and type notation ("<Namespace>/<type>") format, we return the fully qualified resource types
if (TryGetFullyQualfiedResourceType(context.EnclosingDeclaration) is string qualified)
{
// newest api versions should be shown first
// strict filtering on type so that we show api versions for only the selected type
return model.Binder.NamespaceResolver.GetAvailableResourceTypes()
.Where(rt => StringComparer.OrdinalIgnoreCase.Equals(qualified.Split('@')[0], rt.FormatType()))
.OrderBy(rt => rt.FormatType(), StringComparer.OrdinalIgnoreCase)
.ThenByDescending(rt => rt.ApiVersion, ApiVersionComparer.Instance)
.Select((reference, index) => CreateResourceTypeCompletion(reference, index, context.ReplacementRange, showApiVersion: true))
.ToList();
}
// if we do not have the namespace and type notation, we only return unique resource types without their api-versions
// we need to ensure that Microsoft.Compute/virtualMachines comes before Microsoft.Compute/virtualMachines/extensions
// we still order by apiVersion first to have consistent indexes
return model.Binder.NamespaceResolver.GetAvailableResourceTypes()
.OrderByDescending(rt => rt.ApiVersion, ApiVersionComparer.Instance)
.GroupBy(rt => rt.FormatType())
.Select(rt => rt.First())
.OrderBy(rt => rt.FormatType(), StringComparer.OrdinalIgnoreCase)
.Select((reference, index) => CreateResourceTypeCompletion(reference, index, context.ReplacementRange, showApiVersion: false))
.ToList();
}
private IEnumerable<CompletionItem> GetResourceTypeFollowerCompletions(BicepCompletionContext context)
{
if (context.Kind.HasFlag(BicepCompletionContextKind.ResourceTypeFollower))
{
// Only when there is no existing assignment sign
if (context.EnclosingDeclaration is ResourceDeclarationSyntax { Assignment: SkippedTriviaSyntax { Elements: { IsDefaultOrEmpty: true } } })
{
const string equals = "=";
yield return CreateOperatorCompletion(equals, context.ReplacementRange, preselect: true);
}
if (context.EnclosingDeclaration is ResourceDeclarationSyntax { ExistingKeyword: null })
{
const string existing = "existing";
yield return CreateKeywordCompletion(existing, existing, context.ReplacementRange);
}
}
}
private record FileCompletionInfo(
Uri BicepFileParentUri,
Uri EnteredParentUri,
bool ShowCwdPrefix,
ImmutableArray<Uri> Files,
ImmutableArray<Uri> Directories);
private FileCompletionInfo? TryGetFilesForPathCompletions(Uri baseUri, string entered)
{
var files = new List<Uri>();
var dirs = new List<Uri>();
if (FileResolver.TryResolveFilePath(baseUri, ".") is not { } cwdUri
|| FileResolver.TryResolveFilePath(cwdUri, entered) is not { } query)
{
return null;
}
// technically bicep files do not have to follow the bicep extension, so
// we are not enforcing *.bicep get files command
var queryParent = (FileResolver.DirExists(query) ? query : FileResolver.TryResolveFilePath(query, "."));
if (queryParent is not null)
{
files = FileResolver.GetFiles(queryParent, string.Empty).ToList();
dirs = FileResolver.GetDirectories(queryParent, string.Empty).ToList();
// include the parent folder as a completion if we're not at the file system root
if (FileResolver.TryResolveFilePath(queryParent, "..") is {} parentDir &&
parentDir != queryParent)
{
dirs.Add(parentDir);
}
}
return new(
BicepFileParentUri: cwdUri,
EnteredParentUri: query,
ShowCwdPrefix: entered.StartsWith("./"),
Files: files.ToImmutableArray(),
Directories: dirs.ToImmutableArray());
}
private IEnumerable<CompletionItem> CreateFileCompletionItems(Uri mainFileUri, Range replacementRange, FileCompletionInfo info, Predicate<Uri> predicate, CompletionPriority priority)
{
foreach (var fileUri in info.Files)
{
if (fileUri == mainFileUri || !predicate(fileUri))
{
continue;
}
var completionName = info.EnteredParentUri.MakeRelativeUri(fileUri).ToString();
var completionValue = info.BicepFileParentUri.MakeRelativeUri(fileUri).ToString();
if (info.ShowCwdPrefix && !completionValue.StartsWith("../", StringComparison.Ordinal))
{
// "./" will not be preserved when making relative Uris. We have to go and manually add it.
completionValue = "./" + completionValue;
}
yield return CreateFilePathCompletionBuilder(
completionName,
completionValue,
replacementRange,
CompletionItemKind.File,
priority)
.Build();
}
}
private IEnumerable<CompletionItem> CreateDirectoryCompletionItems(Range replacementRange, FileCompletionInfo info, CompletionPriority priority = CompletionPriority.Low)
{
foreach (var dirUri in info.Directories)
{
var completionName = info.EnteredParentUri.MakeRelativeUri(dirUri).ToString();
var completionValue = info.BicepFileParentUri.MakeRelativeUri(dirUri).ToString();
if (info.ShowCwdPrefix && !completionValue.StartsWith("../", StringComparison.Ordinal))
{
// "./" will not be preserved when making relative Uris. We have to go and manually add it.
completionValue = "./" + completionValue;
}
yield return CreateFilePathCompletionBuilder(
completionName,
completionValue,
replacementRange,
CompletionItemKind.Folder,
priority)
.WithCommand(new Command { Name = EditorCommands.RequestCompletions, Title = "file path completion" })
.Build();
}
}
private IEnumerable<CompletionItem> GetLocalModulePathCompletions(SemanticModel model, BicepCompletionContext context)
{
if (!context.Kind.HasFlag(BicepCompletionContextKind.ModulePath))
{
return Enumerable.Empty<CompletionItem>();
}
if (IsOciModuleRegistryReference(context))
{
return Enumerable.Empty<CompletionItem>();
}
// To provide intellisense before the quotes are typed
if (context.EnclosingDeclaration is not ModuleDeclarationSyntax declarationSyntax
|| declarationSyntax.Path is not StringSyntax stringSyntax
|| stringSyntax.TryGetLiteralValue() is not string entered)
{
entered = "";
}
try
{
// These should only fail if we're not able to resolve cwd path or the entered string
if (TryGetFilesForPathCompletions(model.SourceFile.FileUri, entered) is not { } fileCompletionInfo)
{
return Enumerable.Empty<CompletionItem>();
}
var replacementRange = context.EnclosingDeclaration is ModuleDeclarationSyntax module ? module.Path.ToRange(model.SourceFile.LineStarts) : context.ReplacementRange;
// Prioritize .bicep files higher than other files.
var bicepFileItems = CreateFileCompletionItems(model.SourceFile.FileUri, replacementRange, fileCompletionInfo, IsBicepFile, CompletionPriority.High);
var armTemplateFileItems = CreateFileCompletionItems(model.SourceFile.FileUri, replacementRange, fileCompletionInfo, IsArmTemplateFileLike, CompletionPriority.Medium);
var dirItems = CreateDirectoryCompletionItems(replacementRange, fileCompletionInfo);
return bicepFileItems.Concat(armTemplateFileItems).Concat(dirItems);
}
catch (DirectoryNotFoundException)
{
return Enumerable.Empty<CompletionItem>();
}
// Local functions.
bool IsBicepFile(Uri fileUri) => PathHelper.HasBicepExtension(fileUri);
bool IsArmTemplateFileLike(Uri fileUri)
{
if (PathHelper.HasExtension(fileUri, LanguageConstants.ArmTemplateFileExtension))
{
return true;
}
if (model.Compilation.SourceFileGrouping.SourceFiles.Any(sourceFile =>
sourceFile is ArmTemplateFile &&
sourceFile.FileUri.LocalPath.Equals(fileUri.LocalPath, PathHelper.PathComparison)))
{
return true;
}
if (!PathHelper.HasExtension(fileUri, LanguageConstants.JsonFileExtension) &&
!PathHelper.HasExtension(fileUri, LanguageConstants.JsoncFileExtension))
{
return false;
}
if (FileResolver.TryReadAtMostNCharacters(fileUri, Encoding.UTF8, 2000, out var fileContents) &&
LanguageConstants.ArmTemplateSchemaRegex.IsMatch(fileContents))
{
return true;
}
return false;
}
}
private bool IsOciModuleRegistryReference(BicepCompletionContext context)
{
return context.ReplacementTarget is Token token &&
token.Text is string text &&
(ModuleRegistryWithoutAliasPattern.IsMatch(text) || ModuleRegistryWithAliasPattern.IsMatch(text));
}
private static IEnumerable<CompletionItem> GetParameterTypeSnippets(Compilation compitation, BicepCompletionContext context)
{
if (context.EnclosingDeclaration is ParameterDeclarationSyntax parameterDeclarationSyntax)
{
var bicepFile = compitation.SourceFileGrouping.EntryPoint;
Range enclosingDeclarationRange = parameterDeclarationSyntax.Keyword.ToRange(bicepFile.LineStarts);
TextEdit textEdit = new TextEdit()
{
Range = new Range()
{
Start = enclosingDeclarationRange.Start,
End = enclosingDeclarationRange.Start
},
NewText = "@secure()\n"
};
yield return CreateContextualSnippetCompletion("secureObject",
"Secure object",
"object",
context.ReplacementRange,
new TextEdit[] { textEdit });
yield return CreateContextualSnippetCompletion("securestring",
"Secure string",
"string",
context.ReplacementRange,
new TextEdit[] { textEdit });
}
}
private IEnumerable<CompletionItem> GetParameterDefaultValueCompletions(SemanticModel model, BicepCompletionContext context)
{
if (!context.Kind.HasFlag(BicepCompletionContextKind.ParameterDefaultValue) || context.EnclosingDeclaration is not ParameterDeclarationSyntax parameter)
{
return Enumerable.Empty<CompletionItem>();
}
var declaredType = model.GetDeclaredType(parameter);
return GetValueCompletionsForType(model, context, declaredType, loopsAllowed: false);
}
private IEnumerable<CompletionItem> GetVariableValueCompletions(BicepCompletionContext context)
{
if (!context.Kind.HasFlag(BicepCompletionContextKind.VariableValue))
{
return Enumerable.Empty<CompletionItem>();
}
// we don't know what the variable type is, so assume "any"
return CreateLoopCompletions(context.ReplacementRange, LanguageConstants.Any, filtersAllowed: false);
}
private IEnumerable<CompletionItem> GetOutputValueCompletions(SemanticModel model, BicepCompletionContext context)
{
if (!context.Kind.HasFlag(BicepCompletionContextKind.OutputValue) || context.EnclosingDeclaration is not OutputDeclarationSyntax output)
{
return Enumerable.Empty<CompletionItem>();
}
var declaredType = model.GetDeclaredType(output);
return GetValueCompletionsForType(model, context, declaredType, loopsAllowed: true);
}
private IEnumerable<CompletionItem> GetOutputTypeFollowerCompletions(BicepCompletionContext context)
{
if (context.Kind.HasFlag(BicepCompletionContextKind.OutputTypeFollower))
{
const string equals = "=";
yield return CreateOperatorCompletion(equals, context.ReplacementRange, preselect: true);
}
}
private IEnumerable<CompletionItem> GetResourceBodyCompletions(SemanticModel model, BicepCompletionContext context)
{
if (context.Kind.HasFlag(BicepCompletionContextKind.ResourceBody) && context.EnclosingDeclaration is ResourceDeclarationSyntax resourceDeclarationSyntax)
{
foreach (CompletionItem completionItem in CreateResourceBodyCompletions(model, context, resourceDeclarationSyntax))
{
yield return completionItem;
}
yield return CreateResourceOrModuleConditionCompletion(context.ReplacementRange);
// loops are always allowed as long as we're not already in a loop
if (resourceDeclarationSyntax.Value is not ForSyntax)
{
foreach (var completion in CreateLoopCompletions(context.ReplacementRange, LanguageConstants.Object, filtersAllowed: true))
{
yield return completion;
}
}
}
}
private IEnumerable<CompletionItem> CreateResourceBodyCompletions(SemanticModel model, BicepCompletionContext context, ResourceDeclarationSyntax resourceDeclarationSyntax)
{
if (model.GetDeclaredType(resourceDeclarationSyntax)?.UnwrapArrayType() is ResourceType resourceType)
{
var isResourceNested = model.Binder.GetNearestAncestor<ResourceDeclarationSyntax>(resourceDeclarationSyntax) is { };
var snippets = SnippetsProvider.GetResourceBodyCompletionSnippets(resourceType, resourceDeclarationSyntax.IsExistingResource(), isResourceNested);
foreach (Snippet snippet in snippets)
{
string prefix = snippet.Prefix;
BicepTelemetryEvent telemetryEvent = BicepTelemetryEvent.CreateResourceBodySnippetInsertion(prefix, resourceType.Type.Name);
Command command = TelemetryHelper.CreateCommand
(
title: "resource body completion snippet",
name: TelemetryConstants.CommandName,
args: JArray.FromObject(new List<object> { telemetryEvent })
);
yield return CreateContextualSnippetCompletion(prefix,
snippet.Detail,
snippet.Text,
context.ReplacementRange,
command,
snippet.CompletionPriority,
preselect: true);
}
}
}
private IEnumerable<CompletionItem> CreateModuleBodyCompletions(SemanticModel model, BicepCompletionContext context, ModuleDeclarationSyntax moduleDeclarationSyntax)
{
TypeSymbol typeSymbol = model.GetTypeInfo(moduleDeclarationSyntax);
IEnumerable<Snippet> snippets = SnippetsProvider.GetModuleBodyCompletionSnippets(typeSymbol.UnwrapArrayType());
foreach (Snippet snippet in snippets)
{
string prefix = snippet.Prefix;
BicepTelemetryEvent telemetryEvent = BicepTelemetryEvent.CreateModuleBodySnippetInsertion(prefix);
var command = TelemetryHelper.CreateCommand
(
title: "module body completion snippet",
name: TelemetryConstants.CommandName,
args: JArray.FromObject(new List<object> { telemetryEvent })
);
yield return CreateContextualSnippetCompletion(prefix,
snippet.Detail,
snippet.Text,
context.ReplacementRange,
command,
snippet.CompletionPriority,
preselect: true);
}
}
private IEnumerable<CompletionItem> GetModuleBodyCompletions(SemanticModel model, BicepCompletionContext context)
{
if (context.Kind.HasFlag(BicepCompletionContextKind.ModuleBody) && context.EnclosingDeclaration is ModuleDeclarationSyntax moduleDeclarationSyntax)
{
foreach (CompletionItem completionItem in CreateModuleBodyCompletions(model, context, moduleDeclarationSyntax))
{
yield return completionItem;
}
yield return CreateResourceOrModuleConditionCompletion(context.ReplacementRange);
// loops are always allowed in a resource/module if we're not inside another loop
if (moduleDeclarationSyntax.Value is not ForSyntax)
{
foreach (var completion in CreateLoopCompletions(context.ReplacementRange, LanguageConstants.Object, filtersAllowed: true))
{
yield return completion;
}
}
}
}
private static ImmutableDictionary<Symbol, NamespaceType> GetNamespaceTypeBySymbol(SemanticModel model)
{
return model.Root.Namespaces
.Select(ns => (symbol: ns, type: (ns as INamespaceSymbol)?.TryGetNamespaceType()))
.Where(x => x.type is not null)
.ToImmutableDictionary(x => x.symbol, x => x.type!);
}
private static CompletionPriority GetContextualCompletionPriority(Symbol symbol, SemanticModel model, BicepCompletionContext context, Symbol? enclosingDeclarationSymbol)
{
// The value type of resource/module.dependsOn items can only be a resource or module symbol so prioritize them higher than anything else.
// Expressions can also be accepted in this context so other completion items will still be available, just lower in the list.
if (context.Kind.HasFlag(BicepCompletionContextKind.ExpectsResourceSymbolicReference)
&& symbol is ResourceSymbol or ModuleSymbol)
{
// parent resource symbols of the current resource should not be prioritized but are still provided for use in expressions
var enclosingResourceMetadata = model.DeclaredResources.FirstOrDefault((drm) => drm.Symbol == enclosingDeclarationSymbol);
if (enclosingResourceMetadata != null
&& model.ResourceAncestors.GetAncestors(enclosingResourceMetadata).Any(ra => ra.Resource.Symbol == symbol))
{
return CompletionPriority.Medium;
}
return CompletionPriority.VeryHigh;
}
return GetCompletionPriority(symbol);
}
private static bool ShouldSymbolBeIncludedInCompletion(Symbol symbol, SemanticModel model, BicepCompletionContext context, Symbol? enclosingDeclarationSymbol)
{
// filter out self references
if (enclosingDeclarationSymbol != null && ReferenceEquals(symbol, enclosingDeclarationSymbol))
{
return false;
}
// For nested resource/module symbol completions, don't suggest child symbols for resource.dependsOn symbol completions.
if (context.Kind.HasFlag(BicepCompletionContextKind.ExpectsResourceSymbolicReference) && symbol is ResourceSymbol or ModuleSymbol)
{
// filter out child resource symbols of the enclosing declaration symbol
var symbolResourceMetadata = model.DeclaredResources.FirstOrDefault((drm) => drm.Symbol == symbol);
if (symbolResourceMetadata != null
&& model.ResourceAncestors.GetAncestors(symbolResourceMetadata).Any(ra => ra.Resource.Symbol == enclosingDeclarationSymbol))
{
return false;
}
}
return true;
}
private static IEnumerable<CompletionItem> GetAccessibleSymbolCompletions(SemanticModel model, BicepCompletionContext context)
{
// maps insert text to the completion item
var completions = new Dictionary<string, CompletionItem>();
var declaredNames = new HashSet<string>();
var accessibleDecoratorFunctionsCache = new Dictionary<NamespaceType, IEnumerable<FunctionSymbol>>();
var enclosingDeclarationSymbol = context.EnclosingDeclaration == null
? null
: model.GetSymbolInfo(context.EnclosingDeclaration);
// local function
void AddSymbolCompletions(IDictionary<string, CompletionItem> result, IEnumerable<Symbol> symbols)
{
foreach (var symbol in symbols)
{
if (!result.ContainsKey(symbol.Name) && ShouldSymbolBeIncludedInCompletion(symbol, model, context, enclosingDeclarationSymbol))
{
// the symbol satisfies the following conditions:
// - we have not added a symbol with the same name (avoids duplicate completions)
// - the symbol is different than the enclosing declaration (avoids suggesting cycles)
// - the symbol name is different than the name of the enclosing declaration (avoids suggesting a duplicate identifier)
var priority = GetContextualCompletionPriority(symbol, model, context, enclosingDeclarationSymbol);
result.Add(symbol.Name, CreateSymbolCompletion(symbol, context.ReplacementRange, priority: priority, model: model));
}
}
}
// local function
IEnumerable<FunctionSymbol> GetAccessibleDecoratorFunctionsWithCache(NamespaceType namespaceType)
{
if (accessibleDecoratorFunctionsCache.TryGetValue(namespaceType, out var result))
{
return result;
}
result = GetAccessibleDecoratorFunctions(namespaceType, enclosingDeclarationSymbol);
accessibleDecoratorFunctionsCache.Add(namespaceType, result);
return result;
}
var nsTypeDict = GetNamespaceTypeBySymbol(model);
if (!context.Kind.HasFlag(BicepCompletionContextKind.DecoratorName))
{
// add namespaces first
AddSymbolCompletions(completions, nsTypeDict.Keys);
// add accessible symbols from innermost scope and then move to outer scopes
// reverse loop iteration
foreach (var scope in context.ActiveScopes.Reverse())
{
// add referencable declarations with valid identifiers at current scope
AddSymbolCompletions(completions, scope.Declarations.Where(decl => decl.NameSource.IsValid && decl.CanBeReferenced()));
if (scope.ScopeResolution == ScopeResolution.GlobalsOnly)
{
// don't inherit outer scope variables
break;
}
}
}
else
{
// Only add the namespaces that contain accessible decorator function symbols.
AddSymbolCompletions(completions, nsTypeDict.Keys.Where(