forked from Azure/bicep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBicepCodeActionHandler.cs
245 lines (217 loc) · 11.6 KB
/
BicepCodeActionHandler.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Immutable;
using Bicep.Core;
using Bicep.Core.Analyzers;
using Bicep.Core.CodeAction;
using Bicep.Core.CodeAction.Fixes;
using Bicep.Core.Diagnostics;
using Bicep.Core.Extensions;
using Bicep.Core.Parsing;
using Bicep.Core.Semantics;
using Bicep.Core.Text;
using Bicep.Core.Workspaces;
using Bicep.LanguageServer.CompilationManager;
using Bicep.LanguageServer.Completions;
using Bicep.LanguageServer.Extensions;
using Bicep.LanguageServer.Providers;
using Bicep.LanguageServer.Telemetry;
using Bicep.LanguageServer.Utils;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
namespace Bicep.LanguageServer.Handlers
{
// Provides code actions/fixes for a range in a Bicep document
public class BicepCodeActionHandler : CodeActionHandlerBase
{
private readonly IClientCapabilitiesProvider clientCapabilitiesProvider;
private readonly ICompilationManager compilationManager;
public BicepCodeActionHandler(ICompilationManager compilationManager, IClientCapabilitiesProvider clientCapabilitiesProvider)
{
this.clientCapabilitiesProvider = clientCapabilitiesProvider;
this.compilationManager = compilationManager;
}
public override async Task<CommandOrCodeActionContainer?> Handle(CodeActionParams request, CancellationToken cancellationToken)
{
await Task.CompletedTask;
cancellationToken.ThrowIfCancellationRequested();
var documentUri = request.TextDocument.Uri;
var compilationContext = this.compilationManager.GetCompilation(documentUri);
if (compilationContext == null)
{
return null;
}
var requestStartOffset = PositionHelper.GetOffset(compilationContext.LineStarts, request.Range.Start);
var requestEndOffset = request.Range.Start != request.Range.End
? PositionHelper.GetOffset(compilationContext.LineStarts, request.Range.End)
: requestStartOffset;
var compilation = compilationContext.Compilation;
var semanticModel = compilation.GetEntrypointSemanticModel();
var diagnostics = semanticModel.GetAllDiagnostics();
var quickFixes = diagnostics
.Where(fixable =>
fixable.Span.ContainsInclusive(requestStartOffset) ||
fixable.Span.ContainsInclusive(requestEndOffset) ||
(requestStartOffset <= fixable.Span.Position && fixable.GetEndPosition() <= requestEndOffset))
.OfType<IFixable>()
.SelectMany(fixable => fixable.Fixes.Select(fix => CreateCodeFix(request.TextDocument.Uri, compilationContext, fix)));
List<CommandOrCodeAction> commandOrCodeActions = new();
commandOrCodeActions.AddRange(quickFixes);
var coreCompilerErrors = diagnostics
.Where(diagnostic => !diagnostic.CanBeSuppressed());
var diagnosticsThatCanBeSuppressed = diagnostics
.Where(diagnostic =>
diagnostic.Span.ContainsInclusive(requestStartOffset) ||
diagnostic.Span.ContainsInclusive(requestEndOffset) ||
(requestStartOffset <= diagnostic.Span.Position && diagnostic.GetEndPosition() <= requestEndOffset))
.Except(coreCompilerErrors);
HashSet<string> diagnosticCodesToSuppressInline = new();
foreach (IDiagnostic diagnostic in diagnosticsThatCanBeSuppressed)
{
if (!diagnosticCodesToSuppressInline.Contains(diagnostic.Code))
{
diagnosticCodesToSuppressInline.Add(diagnostic.Code);
var commandOrCodeAction = DisableDiagnostic(documentUri, diagnostic.Code, semanticModel.SourceFile, diagnostic.Span, compilationContext.LineStarts);
if (commandOrCodeAction is not null)
{
commandOrCodeActions.Add(commandOrCodeAction);
}
}
}
if (clientCapabilitiesProvider.DoesClientSupportShowDocumentRequest())
{
// Add "Edit <rule> in bicepconfig.json" for all linter failures
var editLinterRuleActions = diagnostics
.Where(analyzerDiagnostic =>
analyzerDiagnostic.Span.ContainsInclusive(requestStartOffset) ||
analyzerDiagnostic.Span.ContainsInclusive(requestEndOffset) ||
(requestStartOffset <= analyzerDiagnostic.Span.Position && analyzerDiagnostic.GetEndPosition() <= requestEndOffset))
.OfType<AnalyzerDiagnostic>()
.Select(analyzerDiagnostic => CreateEditLinterRuleAction(documentUri, analyzerDiagnostic.Code, semanticModel.Configuration.ConfigFileUri?.LocalPath));
commandOrCodeActions.AddRange(editLinterRuleActions);
}
var matchingNodes = SyntaxMatcher.FindNodesInRange(compilationContext.ProgramSyntax, requestStartOffset, requestEndOffset);
var codeFixes = GetDecoratorCodeFixProviders(semanticModel)
.SelectMany(provider => provider.GetFixes(semanticModel, matchingNodes))
.Select(fix => CreateCodeFix(request.TextDocument.Uri, compilationContext, fix));
commandOrCodeActions.AddRange(codeFixes);
return new(commandOrCodeActions);
}
private IEnumerable<DecoratorCodeFixProvider> GetDecoratorCodeFixProviders(SemanticModel semanticModel)
{
var nsResolver = semanticModel.Binder.NamespaceResolver;
return nsResolver.GetNamespaceNames().Select(nsResolver.TryGetNamespace).WhereNotNull()
.SelectMany(ns => ns.DecoratorResolver.GetKnownDecoratorFunctions().Select(kvp => (ns, kvp.Key, kvp.Value)))
.ToLookup(t => t.Key)
.SelectMany(grouping => grouping.Count() > 1
? grouping.SelectMany(tuple => tuple.Value.Overloads.Select(tuple.ns.DecoratorResolver.TryGetDecorator).WhereNotNull().Select(decorator => ($"{tuple.ns.Name}.{tuple.Key}", decorator)))
: grouping.SelectMany(tuple => tuple.Value.Overloads.Select(tuple.ns.DecoratorResolver.TryGetDecorator).WhereNotNull().Select(decorator => (tuple.Key, decorator))))
.Select(t => new DecoratorCodeFixProvider(t.Item1, t.decorator));
}
private static CommandOrCodeAction? DisableDiagnostic(DocumentUri documentUri,
DiagnosticCode diagnosticCode,
BicepSourceFile bicepFile,
TextSpan span,
ImmutableArray<int> lineStarts)
{
if (diagnosticCode.String is null)
{
return null;
}
var disabledDiagnosticsCache = bicepFile.DisabledDiagnosticsCache;
(int diagnosticLine, _) = TextCoordinateConverter.GetPosition(bicepFile.LineStarts, span.Position);
TextEdit? textEdit;
int previousLine = diagnosticLine - 1;
if (disabledDiagnosticsCache.TryGetDisabledNextLineDirective(previousLine) is { } disableNextLineDirectiveEndPositionAndCodes)
{
textEdit = new TextEdit
{
Range = new Range(previousLine, disableNextLineDirectiveEndPositionAndCodes.endPosition, previousLine, disableNextLineDirectiveEndPositionAndCodes.endPosition),
NewText = ' ' + diagnosticCode.String
};
}
else
{
var range = span.ToRange(lineStarts);
textEdit = new TextEdit
{
Range = new Range(range.Start.Line, 0, range.Start.Line, 0),
NewText = "#" + LanguageConstants.DisableNextLineDiagnosticsKeyword + ' ' + diagnosticCode.String + '\n'
};
}
BicepTelemetryEvent telemetryEvent = BicepTelemetryEvent.CreateDisableNextLineDiagnostics(diagnosticCode.String);
var telemetryCommand = TelemetryHelper.CreateCommand(
title: "disable next line diagnostics code action",
name: TelemetryConstants.CommandName,
args: JArray.FromObject(new List<object> { telemetryEvent })
);
return new CodeAction
{
Title = string.Format(LangServerResources.DisableDiagnosticForThisLine, diagnosticCode.String),
Edit = new WorkspaceEdit
{
Changes = new Dictionary<DocumentUri, IEnumerable<TextEdit>>
{
[documentUri] = new List<TextEdit> { textEdit }
}
},
Command = telemetryCommand
};
}
private static CommandOrCodeAction CreateEditLinterRuleAction(DocumentUri documentUri, string ruleName, string? bicepConfigFilePath)
{
return new CodeAction
{
Title = String.Format(LangServerResources.EditLinterRuleActionTitle, ruleName),
Command = TelemetryHelper.CreateCommand
(
title: "edit linter rule code action",
name: LangServerConstants.EditLinterRuleCommandName,
args: JArray.FromObject(new List<object> { documentUri, ruleName, bicepConfigFilePath ?? string.Empty /* (passing null not allowed) */ })
)
};
}
public override Task<CodeAction> Handle(CodeAction request, CancellationToken cancellationToken)
{
// we are currently precomputing our quickfixes, so there's no need to resolve them after they are chosen
// this shouldn't be called because registration options disabled the resolve functionality
return Task.FromResult(request);
}
private static CommandOrCodeAction CreateCodeFix(DocumentUri uri, CompilationContext context, CodeFix fix)
{
var codeActionKind = fix.Kind switch
{
CodeFixKind.QuickFix => CodeActionKind.QuickFix,
CodeFixKind.Refactor => CodeActionKind.Refactor,
_ => CodeActionKind.Empty,
};
return new CodeAction
{
Kind = codeActionKind,
Title = fix.Title,
IsPreferred = fix.IsPreferred,
Edit = new WorkspaceEdit
{
Changes = new Dictionary<DocumentUri, IEnumerable<TextEdit>>
{
[uri] = fix.Replacements.Select(replacement => new TextEdit
{
Range = replacement.ToRange(context.LineStarts),
NewText = replacement.Text
})
}
}
};
}
protected override CodeActionRegistrationOptions CreateRegistrationOptions(CodeActionCapability capability, ClientCapabilities clientCapabilities) => new()
{
DocumentSelector = DocumentSelectorFactory.CreateForBicepAndParams(),
CodeActionKinds = new Container<CodeActionKind>(CodeActionKind.QuickFix),
ResolveProvider = false
};
}
}