Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 44042b9

Browse files
committedAug 16, 2023
add code action for wrapping option patterns in Some when not already wrapped
1 parent 35bc283 commit 44042b9

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
 

‎server/src/codeActions.ts

+72
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ export let findCodeActionsInDiagnosticsMessage = ({
156156
simpleConversion,
157157
applyUncurried,
158158
simpleAddMissingCases,
159+
wrapInSome,
159160
];
160161

161162
for (let extractCodeAction of codeActionEtractors) {
@@ -240,6 +241,77 @@ let didYouMeanAction: codeActionExtractor = ({
240241
return false;
241242
};
242243

244+
// This action offers to wrap patterns that aren't option in Some.
245+
let wrapInSome: codeActionExtractor = ({
246+
codeActions,
247+
diagnostic,
248+
file,
249+
line,
250+
range,
251+
array,
252+
index,
253+
}) => {
254+
if (line.startsWith("This pattern matches values of type")) {
255+
let regex = /This pattern matches values of type (.*)$/;
256+
257+
let match = line.match(regex);
258+
259+
if (match === null) {
260+
return false;
261+
}
262+
263+
let [_, type] = match;
264+
265+
if (!type.startsWith("option<")) {
266+
// Look for the expected type
267+
let restOfMessage = array.slice(index + 1);
268+
let lineIndexWithType = restOfMessage.findIndex((l) =>
269+
l
270+
.trim()
271+
.startsWith("but a pattern was expected which matches values of type")
272+
);
273+
274+
if (lineIndexWithType === -1) return false;
275+
// The type is either on this line or the next
276+
let [_, typ = ""] = restOfMessage[lineIndexWithType].split(
277+
"but a pattern was expected which matches values of type"
278+
);
279+
280+
console.log({ typ });
281+
282+
if (typ.trim() === "") {
283+
// Type is on the next line
284+
typ = (restOfMessage[lineIndexWithType + 1] ?? "").trim();
285+
}
286+
287+
if (typ.trim().startsWith("option<")) {
288+
codeActions[file] = codeActions[file] || [];
289+
290+
let codeAction: p.CodeAction = {
291+
title: `Wrap in option Some`,
292+
edit: {
293+
changes: {
294+
[file]: wrapRangeInText(range, `Some(`, `)`),
295+
},
296+
},
297+
diagnostics: [diagnostic],
298+
kind: p.CodeActionKind.QuickFix,
299+
isPreferred: true,
300+
};
301+
302+
codeActions[file].push({
303+
range,
304+
codeAction,
305+
});
306+
307+
return true;
308+
}
309+
}
310+
}
311+
312+
return false;
313+
};
314+
243315
// This action handles when the compiler errors on certain fields of a record
244316
// being undefined. We then offers an action that inserts all of the record
245317
// fields, with an `assert false` dummy value. `assert false` is so applying the

0 commit comments

Comments
 (0)
Please sign in to comment.