KCL: Use keyword arguments for line, lineTo, extrude and close (#5249)

Part of #4600.

PR: https://github.com/KittyCAD/modeling-app/pull/4826

# Changes to KCL stdlib

- `line(point, sketch, tag)` and `lineTo(point, sketch, tag)` are combined into `line(@sketch, end?, endAbsolute?, tag?)`
- `close(sketch, tag?)` is now `close(@sketch, tag?)`
- `extrude(length, sketch)` is now `extrude(@sketch, length)`

Note that if a parameter starts with `@` like `@sketch`, it doesn't have any label when called, so you call it like this:

```
sketch = startSketchAt([0, 0])
line(sketch, end = [3, 3], tag = $hi)
```

Note also that if you're using a `|>` pipeline, you can omit the `@` argument and it will be assumed to be the LHS of the `|>`. So the above could be written as

```
sketch = startSketchAt([0, 0])
|> line(end = [3, 3], tag = $hi)
```

Also changes frontend tests to use KittyCAD/kcl-samples#139 instead of its main

The regex find-and-replace I use for migrating code (note these don't work with multi-line expressions) are:

```
 line\(([^=]*), %\)
 line(end = $1)

 line\((.*), %, (.*)\)
 line(end = $1, tag = $2)

 lineTo\((.*), %\)
 line(endAbsolute = $1)

 lineTo\((.*), %, (.*)\)
 line(endAbsolute = $1, tag = $2)

 extrude\((.*), %\)
 extrude(length = $1)

extrude\(([^=]*), ([a-zA-Z0-9]+)\)
extrude($2, length = $1)

 close\(%, (.*)\)
 close(tag = $1)
```

# Selected notes from commits before I squash them all

* Fix test 'yRelative to horizontal distance'

Fixes:
 - Make a lineTo helper
 - Fix pathToNode to go through the labeled arg .arg property

* Fix test by changing lookups into transformMap

Parts of the code assumed that `line` is always a relative call. But
actually now it might be absolute, if it's got an `endAbsolute` parameter.

So, change whether to look up `line` or `lineTo` and the relevant absolute
or relative line types based on that parameter.

* Stop asserting on exact source ranges

When I changed line to kwargs, all the source ranges we assert on became
slightly different. I find these assertions to be very very low value.
So I'm removing them.

* Fix more tests: getConstraintType calls weren't checking if the
'line' fn was absolute or relative.

* Fixed another queryAst test

There were 2 problems:
 - Test was looking for the old style of `line` call to choose an offset
   for pathToNode
 - Test assumed that the `tag` param was always the third one, but in
   a kwarg call, you have to look it up by label

* Fix test: traverse was not handling CallExpressionKw

* Fix another test, addTagKw

addTag helper was not aware of kw args.

* Convert close from positional to kwargs

If the close() call has 0 args, or a single unlabeled arg, the parser
interprets it as a CallExpression (positional) not a CallExpressionKw.

But then if a codemod wants to add a tag to it, it tries adding a kwarg
called 'tag', which fails because the CallExpression doesn't need
kwargs inserted into it.

The fix is: change the node from CallExpression to CallExpressionKw, and
update getNodeFromPath to take a 'replacement' arg, so we can replace
the old node with the new node in the AST.

* Fix the last test

Test was looking for `lineTo` as a substring of the input KCL program.
But there's no more lineTo function, so I changed it to look for
line() with an endAbsolute arg, which is the new equivalent.

Also changed the getConstraintInfo code to look up the lineTo if using
line with endAbsolute.

* Fix many bad regex find-replaces

I wrote a regex find-and-replace which converted `line` calls from
positional to keyword calls. But it was accidentally applied to more
places than it should be, for example, angledLine, xLine and yLine calls.

Fixes this.

* Fixes test 'Basic sketch › code pane closed at start'

Problem was, the getNodeFromPath call might not actually find a callExpressionKw,
it might find a callExpression. So the `giveSketchFnCallTag` thought
it was modifying a kwargs call, but it was actually modifying a positional
call.

This meant it tried to push a labeled argument in, rather than a normal
arg, and a lot of other problems. Fixed by doing runtime typechecking.

* Fix: Optional args given with wrong type were silently ignored

Optional args don't have to be given. But if the user gives them, they
should be the right type.

Bug: if the KCL interpreter found an optional arg, which was given, but
was the wrong type, it would ignore it and pretend the arg was never
given at all. This was confusing for users.

Fix: Now if you give an optional arg, but it's the wrong type, KCL will
emit a type error just like it would for a mandatory argument.

---------

Signed-off-by: Nick Cameron <nrc@ncameron.org>
Co-authored-by: Nick Cameron <nrc@ncameron.org>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Frank Noirot <frank@kittycad.io>
Co-authored-by: Kevin Nadro <kevin@zoo.dev>
Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
This commit is contained in:
Adam Chalmers
2025-02-04 08:31:43 -06:00
committed by GitHub
parent f5b8298735
commit 8397405998
553 changed files with 140134 additions and 136409 deletions

View File

@ -3,6 +3,8 @@ import { Selection } from 'lib/selections'
import {
Program,
CallExpression,
LabeledArg,
CallExpressionKw,
PipeExpression,
VariableDeclaration,
VariableDeclarator,
@ -29,9 +31,16 @@ import {
getNodeFromPath,
isNodeSafeToReplace,
traverse,
ARG_INDEX_FIELD,
LABELED_ARG_FIELD,
} from './queryAst'
import {
addTagForSketchOnFace,
ARG_TAG,
getConstraintInfo,
getConstraintInfoKw,
} from './std/sketch'
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
import { addTagForSketchOnFace, getConstraintInfo } from './std/sketch'
import {
PathToNodeMap,
isLiteralArrayOrStatic,
@ -47,6 +56,7 @@ import { Models } from '@kittycad/lib'
import { ExtrudeFacePlane } from 'machines/modelingMachine'
import { Node } from 'wasm-lib/kcl/bindings/Node'
import { KclExpressionWithVariable } from 'lib/commandTypes'
import { findKwArg } from './util'
import { deleteEdgeTreatment } from './modifyAst/addEdgeTreatment'
export function startSketchOnDefault(
@ -134,10 +144,11 @@ export function addSketchTo(
createLiteral('default'),
createPipeSubstitution(),
])
const initialLineTo = createCallExpressionStdLib('line', [
createLiteral('default'),
createPipeSubstitution(),
])
const initialLineTo = createCallExpressionStdLibKw(
'line',
null, // Assumes this is being called in a pipeline, so the first arg is optional and if not given, will become pipeline substitution.
[createLabeledArg('end', createLiteral('default'))]
)
const pipeBody = [startSketchOn, startProfileAt, initialLineTo]
@ -200,6 +211,27 @@ export function findUniqueName(
return findUniqueName(searchStr, name, pad, index + 1)
}
/**
Set the keyword argument to the given value.
Returns true if it overwrote an existing argument.
Returns false if no argument with the label existed before.
*/
export function mutateKwArg(
label: string,
node: CallExpressionKw,
val: Expr
): boolean {
for (let i = 0; i < node.arguments.length; i++) {
const arg = node.arguments[i]
if (arg.label.name === label) {
node.arguments[i].arg = val
return true
}
}
node.arguments.push(createLabeledArg(label, val))
return false
}
export function mutateArrExp(node: Expr, updateWith: ArrayExpression): boolean {
if (node.type === 'ArrayExpression') {
node.elements.forEach((element, i) => {
@ -288,12 +320,15 @@ export function extrudeSketch(
if (err(_node3)) return _node3
const { node: variableDeclarator, shallowPath: pathToDecleration } = _node3
const extrudeCall = createCallExpressionStdLib('extrude', [
distance,
shouldPipe
? createPipeSubstitution()
: createIdentifier(variableDeclarator.id.name),
const sketchToExtrude = shouldPipe
? createPipeSubstitution()
: createIdentifier(variableDeclarator.id.name)
const extrudeCall = createCallExpressionStdLibKw('extrude', sketchToExtrude, [
createLabeledArg('length', distance),
])
// index of the 'length' arg above. If you reorder the labeled args above,
// make sure to update this too.
const argIndex = 0
if (shouldPipe) {
const pipeChain = createPipeExpression(
@ -308,8 +343,9 @@ export function extrudeSketch(
['init', 'VariableDeclarator'],
['body', ''],
[pipeChain.body.length - 1, 'index'],
['arguments', 'CallExpression'],
[0, 'index'],
['arguments', 'CallExpressionKw'],
[argIndex, ARG_INDEX_FIELD],
['arg', LABELED_ARG_FIELD],
]
return {
@ -336,8 +372,9 @@ export function extrudeSketch(
[sketchIndexInBody + 1, 'index'],
['declaration', 'VariableDeclaration'],
['init', 'VariableDeclarator'],
['arguments', 'CallExpression'],
[0, 'index'],
['arguments', 'CallExpressionKw'],
[argIndex, ARG_INDEX_FIELD],
['arg', LABELED_ARG_FIELD],
]
return {
modifiedAst: _node,
@ -523,10 +560,10 @@ export function sketchOnExtrudedFace(
const { node: oldSketchNode } = _node1
const oldSketchName = oldSketchNode.id.name
const _node2 = getNodeFromPath<CallExpression>(
const _node2 = getNodeFromPath<CallExpression | CallExpressionKw>(
_node,
sketchPathToNode,
'CallExpression'
['CallExpression', 'CallExpressionKw']
)
if (err(_node2)) return _node2
const { node: expression } = _node2
@ -827,6 +864,29 @@ export function createCallExpressionStdLib(
}
}
export function createCallExpressionStdLibKw(
name: string,
unlabeled: CallExpressionKw['unlabeled'],
args: CallExpressionKw['arguments']
): Node<CallExpressionKw> {
return {
type: 'CallExpressionKw',
start: 0,
end: 0,
moduleId: 0,
callee: {
type: 'Identifier',
start: 0,
end: 0,
moduleId: 0,
name,
},
unlabeled,
arguments: args,
}
}
export function createCallExpression(
name: string,
args: CallExpression['arguments']
@ -978,20 +1038,46 @@ export function giveSketchFnCallTag(
}
| Error {
const path = getNodePathFromSourceRange(ast, range)
const _node1 = getNodeFromPath<CallExpression>(ast, path, 'CallExpression')
if (err(_node1)) return _node1
const { node: primaryCallExp } = _node1
const maybeTag = (() => {
const callNode = getNodeFromPath<CallExpression | CallExpressionKw>(
ast,
path,
['CallExpression', 'CallExpressionKw']
)
if (!err(callNode) && callNode.node.type === 'CallExpressionKw') {
const { node: primaryCallExp } = callNode
const existingTag = findKwArg(ARG_TAG, primaryCallExp)
const tagDeclarator =
existingTag || createTagDeclarator(tag || findUniqueName(ast, 'seg', 2))
const isTagExisting = !!existingTag
if (!isTagExisting) {
callNode.node.arguments.push(createLabeledArg(ARG_TAG, tagDeclarator))
}
return { tagDeclarator, isTagExisting }
}
// Tag is always 3rd expression now, using arg index feels brittle
// but we can come up with a better way to identify tag later.
const thirdArg = primaryCallExp.arguments?.[2]
const tagDeclarator =
thirdArg ||
(createTagDeclarator(tag || findUniqueName(ast, 'seg', 2)) as TagDeclarator)
const isTagExisting = !!thirdArg
if (!isTagExisting) {
primaryCallExp.arguments[2] = tagDeclarator
}
// We've handled CallExpressionKw above, so this has to be positional.
const _node1 = getNodeFromPath<CallExpression>(ast, path, 'CallExpression')
if (err(_node1)) return _node1
const { node: primaryCallExp } = _node1
// Tag is always 3rd expression now, using arg index feels brittle
// but we can come up with a better way to identify tag later.
const thirdArg = primaryCallExp.arguments?.[2]
const tagDeclarator =
thirdArg ||
(createTagDeclarator(
tag || findUniqueName(ast, 'seg', 2)
) as TagDeclarator)
const isTagExisting = !!thirdArg
if (!isTagExisting) {
primaryCallExp.arguments[2] = tagDeclarator
}
return { tagDeclarator, isTagExisting }
})()
if (err(maybeTag)) return maybeTag
const { tagDeclarator, isTagExisting } = maybeTag
if ('value' in tagDeclarator) {
// Now TypeScript knows tagDeclarator has a value property
return {
@ -1112,17 +1198,22 @@ export function deleteSegmentFromPipeExpression(
dependentRanges.forEach((range) => {
const path = getNodePathFromSourceRange(_modifiedAst, range)
const callExp = getNodeFromPath<Node<CallExpression>>(
const callExp = getNodeFromPath<Node<CallExpression | CallExpressionKw>>(
_modifiedAst,
path,
'CallExpression',
['CallExpression', 'CallExpressionKw'],
true
)
if (err(callExp)) return callExp
const constraintInfo = getConstraintInfo(callExp.node, code, path).find(
({ sourceRange }) => isOverlap(sourceRange, range)
)
const constraintInfo =
callExp.node.type === 'CallExpression'
? getConstraintInfo(callExp.node, code, path).find(({ sourceRange }) =>
isOverlap(sourceRange, range)
)
: getConstraintInfoKw(callExp.node, code, path).find(
({ sourceRange }) => isOverlap(sourceRange, range)
)
if (!constraintInfo) return
if (!constraintInfo.argPosition) return
@ -1218,11 +1309,16 @@ export async function deleteFromSelection(
if (node.type === 'VariableDeclaration') {
const dec = node.declaration
if (
dec.init.type === 'CallExpression' &&
(dec.init.callee.name === 'extrude' ||
dec.init.callee.name === 'revolve') &&
dec.init.arguments?.[1].type === 'Identifier' &&
dec.init.arguments?.[1].name === varDecName
(dec.init.type === 'CallExpression' &&
(dec.init.callee.name === 'extrude' ||
dec.init.callee.name === 'revolve') &&
dec.init.arguments?.[1].type === 'Identifier' &&
dec.init.arguments?.[1].name === varDecName) ||
(dec.init.type === 'CallExpressionKw' &&
(dec.init.callee.name === 'extrude' ||
dec.init.callee.name === 'revolve') &&
dec.init.unlabeled?.type === 'Identifier' &&
dec.init.unlabeled?.name === varDecName)
) {
pathToNode = path
extrudeNameToDelete = dec.id.name
@ -1393,3 +1489,7 @@ export async function deleteFromSelection(
const nonCodeMetaEmpty = () => {
return { nonCodeNodes: {}, startNodes: [], start: 0, end: 0 }
}
export const createLabeledArg = (name: string, arg: Expr): LabeledArg => {
return { label: createIdentifier(name), arg, type: 'LabeledArg' }
}