From 85a39109f863dc90de6a180ea9c8f9364b1d397f Mon Sep 17 00:00:00 2001 From: Frank Noirot Date: Fri, 11 Oct 2024 12:53:33 -0400 Subject: [PATCH] Don't mutate the user's `codeBasedSelections` when they apply a multi-selection constraint (#4141) * Don't mutate the user's `codeBasedSelections` when they apply a multi-selection constraint * Fix to not mutate the input parameter * Format --------- Co-authored-by: Jonathan Tran --- src/lang/std/sketchcombos.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/lang/std/sketchcombos.ts b/src/lang/std/sketchcombos.ts index 67de4939f..87491ff5c 100644 --- a/src/lang/std/sketchcombos.ts +++ b/src/lang/std/sketchcombos.ts @@ -1559,9 +1559,15 @@ export function transformSecondarySketchLinesTagFirst({ } | Error { // let node = structuredClone(ast) - const primarySelection = selectionRanges.codeBasedSelections.sort( - (a, b) => a.range[0] - b.range[0] - )[0].range + + // We need to sort the selections by their start position + // so that we can process them in dependency order and not write invalid KCL. + const sortedCodeBasedSelections = + selectionRanges.codeBasedSelections.toSorted( + (a, b) => a.range[0] - b.range[0] + ) + const primarySelection = sortedCodeBasedSelections[0].range + const secondarySelections = sortedCodeBasedSelections.slice(1) const _tag = giveSketchFnCallTag(ast, primarySelection, forceSegName) if (err(_tag)) return _tag @@ -1571,7 +1577,7 @@ export function transformSecondarySketchLinesTagFirst({ ast: modifiedAst, selectionRanges: { ...selectionRanges, - codeBasedSelections: selectionRanges.codeBasedSelections.slice(1), + codeBasedSelections: secondarySelections, }, referencedSegmentRange: primarySelection, transformInfos,