Compare commits

...

27 Commits

Author SHA1 Message Date
b5c8ca05a5 Fix whitespace in updater toast (#7331)
pierremtb/adhoc/whitespace-fix-updater-toast
2025-06-03 10:15:42 -04:00
33f7badf41 point and click-ify mounting plate (#7287)
* point and click-ify mounting plate

* Update kcl-samples simulation test output

* Update public/kcl-samples/mounting-plate/main.kcl

* Update public/kcl-samples/mounting-plate/main.kcl

* fix

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-06-03 08:10:37 -04:00
569935c21f Move segment functions to KCL (#7333)
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2025-06-03 15:15:51 +12:00
7680605085 KCL: Fix 'cryptic' error when referencing a variable in its own declaration (#7325)
Previously, `x = cos(x)` would just say "`x` is undefined". Now it says that `x` cannot be referenced in its own definition, try using a different variable instead.

To do this, I've added a new `Option<String>` field to the mod-local executor context, tracking the current variable declaration. This means cloning some strings, implying a small performance hit. I think it's fine, for the better diagnostics.

In the future we could refactor this to use a &str or store variable labels in stack-allocated strings like docs.rs/compact_str or something.

Closes https://github.com/KittyCAD/modeling-app/issues/6072
2025-06-02 18:25:55 -04:00
2bb6c74f42 Update error message after engine change (#7330) 2025-06-02 18:05:46 -04:00
faf4d42b6a Update getSketchExprsFromSelection to use codeRef.pathToNode (#6737) 2025-06-02 16:49:41 -04:00
8dd2a86191 Make sweep tests more point-and-click like and clean up pathToNode retrieval (#6963)
WIP: udpate sweep point-and-click tests and mess with pathToNode
Fixes #6952
2025-06-02 16:49:20 -04:00
13c4de77c3 Fix broken WASM test (#7324)
Previous PR (#7321) was set to automerge, but apparently the npm-unit-test
CI target doesn't block merges if it fails. Fixed now.
2025-06-02 15:56:49 -04:00
e29ee9d1ca KCL: Use named fields for KclError (#7321)
We've changed the unnamed field of `KclError` variants to a named called `details`.

To clarify: previously KCL errors looked like this:

```rust
pub enum KclError {
    Lexical(KclErrorDetails),
    Syntax(KclErrorDetails),
```

Now they look like this:

```rust
pub enum KclError {
    Lexical { details: KclErrorDetails },
    Syntax { details: KclErrorDetails },
}
```

This lets us more easily add fields to the errors. For example, in the UndefinedValue case, adding a field for what the undefined name was. This PR refactors the code to make my PR in https://github.com/KittyCAD/modeling-app/pull/7309 much easier.

Pure refactor, should not change any behaviour.
2025-06-02 14:30:57 -04:00
b7437e949a Update generated output to try to fix flakiness (#7323) 2025-06-02 13:36:41 -04:00
08781ff010 Add transform operations to the Feature Tree (#7307)
* Add transform operations

* Update output

* Add scale icon
2025-06-02 10:32:36 -04:00
eb79b1f746 #7227 Fix project not saving when dragging a segment (#7276)
* fix bug of not saving project when dragging a segment, add a test

* Update e2e/playwright/projects.spec.ts

Co-authored-by: Jace Browning <jacebrowning@gmail.com>

---------

Co-authored-by: Jace Browning <jacebrowning@gmail.com>
2025-06-02 09:28:23 +02:00
8df81b2753 Update URL in Discord Bot (#7306) 2025-05-30 14:36:45 -07:00
e75a604c64 Fix the link for plan upgrades (#7305) 2025-05-30 16:54:07 -04:00
0624e42822 Add more detail to close() docs (#7300)
* Add more detail to close() docs

* Run gen
2025-05-30 16:05:32 -04:00
1c07e8af5b Add hysteresis and EMA to ping to avoid flickering network badge (#7197)
* Don't use WEAK and yellow

* fmt && lint && tsc

* Fix up the rebase & dark mode colors

* Update src/hooks/useNetworkStatus.tsx

Co-authored-by: graphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>

* Change Weak to Ok

* Change Connected to Strong

* fmt

* Sync selectors for start sketch

* Remove unused test-util brought back in a rebase

* Align the other OKs

* Add an else statement to overallState

---------

Co-authored-by: graphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
2025-05-30 15:50:05 -04:00
5fccaad0e7 KCL: Fix cryptic error on unexpected tokens in fn call (#7295)
This program:
```kcl
1
|> extrude(
  length=depth,
})
```

was giving this bad error:

```
unexpected token |>
```

Now it gives

```kcl
There was an unexpected }. Try removing it.
```

and it correctly puts the diagnostic on the extra }.

Fixes https://github.com/KittyCAD/modeling-app/issues/6126
2025-05-30 14:57:05 -04:00
a506f7f698 KCL: Fix cryptic error when missing commas between arguments (#7297)
Previously, this KCL

```
arc(
    endAbsolute = [0, 50]
    interiorAbsolute = [-50, 0]
)
```

gave the error `This argument has a label, but no value. Put some value after the equals sign`.

Now it gives this much better error `Missing comma between arguments, try adding a comma in`, and its source range (red underline) is on the whitespace which was missing a comma:

<img width="666" src="https://github.com/user-attachments/assets/aa5035f5-f748-4dab-b918-b81b05733323" />

Thanks for reporting this @benjamaan476
2025-05-30 13:20:06 -05:00
1bb96cd878 Release KCL 78 (#7298) 2025-05-30 13:48:17 -04:00
b63b0e538a Fix to not have infinite console errors editing tangentialArc (#7296) 2025-05-30 12:58:47 -04:00
5118198cec Add variable name to operations display in Feature Tree (#7274)
* Add variable name to operations in Feature Tree

* small design tweak

---------

Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
2025-05-30 11:09:01 -04:00
1611244b94 Revert "Fix the black screen of death" (#7292)
Revert "Fix the black screen of death (#7238)"

This reverts commit 46b6707e3a.
2025-05-30 10:36:33 -04:00
227ad31fc2 #4376 UI should generate relative tangentialArc (#7189)
* first step of UI using trelative angentialArc

* use tangentialArcTo when snapping to one of the axes

* remove duplications via tangentialArcHelpers

* update test: snapToProfile start only works for current profile

* add test: Can add multiple profiles to a sketch (all tool types)

* update test: Straight line snapping to previous tangent

* fixes for removing individual constraints (should keep endAbsolute for lines, tangentialArcs)

* fix fnNameToToolTipFromSegment arcTo

* update snapshot test to use relative tangentialArc

* stabilize some snapshot tests

* stabilize and update Inch snapshot test on ubuntu

* fix tsc

* stabilize and update Millimeter scale snapshot test on ubuntu

* update snapshot for Inch scale test

* Update snapshots

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-05-30 14:44:31 +02:00
80e3dc9095 Move more functions to KCL decls (#7266)
* Move some sketch functions to KCL

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* Move asserts to KCL

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* sweep, loft -> KCL

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* Move pattern transforms to KCL

Signed-off-by: Nick Cameron <nrc@ncameron.org>

---------

Signed-off-by: Nick Cameron <nrc@ncameron.org>
2025-05-29 19:00:16 -04:00
46b6707e3a Fix the black screen of death (#7238)
* Fix the black screen of death

* fmt

* make check

* Clean up

* Fix up zoom to fit

* Change how emulateNetworkConditions work

* Do NOT use browser's offline/online mechanisms

* Fix test
2025-05-29 15:02:12 -04:00
0eebb76bfd Update Bone Plate (#7260)
* Add clock

* update bone plate

* header check

* adding nick b's comments

* Update kcl-samples simulation test output

* Update kcl-samples simulation test output

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-05-29 09:59:27 -07:00
464372e7ed Use the same OS images for web and desktop e2e (#7275) 2025-05-29 12:51:11 -04:00
242 changed files with 17161 additions and 94623 deletions

View File

@ -217,7 +217,10 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
include:
- os: "runs-on=${{ github.run_id }}/family=i7ie.2xlarge/image=ubuntu22-full-x64"
- os: namespace-profile-macos-8-cores
- os: windows-latest-8-cores
runs-on: ${{ matrix.os }}
name: e2e:web (${{ contains(matrix.os, 'ubuntu') && 'ubuntu' || (contains(matrix.os, 'windows') && 'windows' || 'macos') }})
env:

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -14,7 +14,7 @@ close(
): Sketch
```
If you want to perform some 3-dimensional operation on a sketch, like extrude or sweep, you must `close` it first. `close` must be called even if the end point of the last segment is coincident with the sketch starting point.
### Arguments

View File

@ -0,0 +1,50 @@
---
title: "assert"
subtitle: "Function in std"
excerpt: ""
layout: manual
---
```kcl
assert(
@actual: number,
isGreaterThan?: number,
isLessThan?: number,
isGreaterThanOrEqual?: number,
isLessThanOrEqual?: number,
isEqualTo?: number,
tolerance?: number,
error?: string,
)
```
Check a value meets some expected conditions at runtime. Program terminates with an error if conditions aren't met.
If you provide multiple conditions, they will all be checked and all must be met.
### Arguments
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `actual` | [`number`](/docs/kcl-std/types/std-types-number) | Value to check. If this is the boolean value true, assert passes. Otherwise it fails.. | Yes |
| `isGreaterThan` | [`number`](/docs/kcl-std/types/std-types-number) | Comparison argument. If given, checks the `actual` value is greater than this. | No |
| `isLessThan` | [`number`](/docs/kcl-std/types/std-types-number) | Comparison argument. If given, checks the `actual` value is less than this. | No |
| `isGreaterThanOrEqual` | [`number`](/docs/kcl-std/types/std-types-number) | Comparison argument. If given, checks the `actual` value is greater than or equal to this. | No |
| `isLessThanOrEqual` | [`number`](/docs/kcl-std/types/std-types-number) | Comparison argument. If given, checks the `actual` value is less than or equal to this. | No |
| `isEqualTo` | [`number`](/docs/kcl-std/types/std-types-number) | Comparison argument. If given, checks the `actual` value is less than or equal to this. | No |
| `tolerance` | [`number`](/docs/kcl-std/types/std-types-number) | If `isEqualTo` is used, this is the tolerance to allow for the comparison. This tolerance is used because KCL's number system has some floating-point imprecision when used with very large decimal places. | No |
| `error` | [`string`](/docs/kcl-std/types/std-types-string) | If the value was false, the program will terminate with this error message | No |
### Examples
```kcl
n = 10
assert(n, isEqualTo = 10)
assert(n, isGreaterThanOrEqual = 0, isLessThan = 100, error = "number should be between 0 and 100")
assert(1.0000000000012, isEqualTo = 1, tolerance = 0.0001, error = "number should be almost exactly 1")
```

View File

@ -0,0 +1,35 @@
---
title: "assertIs"
subtitle: "Function in std"
excerpt: "Asserts that a value is the boolean value true."
layout: manual
---
Asserts that a value is the boolean value true.
```kcl
assertIs(
@actual: bool,
error?: string,
)
```
### Arguments
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `actual` | [`bool`](/docs/kcl-std/types/std-types-bool) | Value to check. If this is the boolean value true, assert passes. Otherwise it fails.. | Yes |
| `error` | [`string`](/docs/kcl-std/types/std-types-string) | If the value was false, the program will terminate with this error message | No |
### Examples
```kcl
kclIsFun = true
assertIs(kclIsFun)
```

View File

@ -9,7 +9,7 @@ layout: manual
```kcl
circle(
@sketch_or_surface: Sketch | Plane | Face,
@sketchOrSurface: Sketch | Plane | Face,
center: Point2d,
radius?: number(Length),
diameter?: number(Length),
@ -24,7 +24,7 @@ the provided (x, y) origin point.
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketch_or_surface` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) or [`Plane`](/docs/kcl-std/types/std-types-Plane) or [`Face`](/docs/kcl-std/types/std-types-Face) | Sketch to extend, or plane or surface to sketch on. | Yes |
| `sketchOrSurface` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) or [`Plane`](/docs/kcl-std/types/std-types-Plane) or [`Face`](/docs/kcl-std/types/std-types-Face) | Sketch to extend, or plane or surface to sketch on. | Yes |
| `center` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | The center of the circle. | Yes |
| `radius` | [`number(Length)`](/docs/kcl-std/types/std-types-number) | The radius of the circle. Incompatible with `diameter`. | No |
| `diameter` | [`number(Length)`](/docs/kcl-std/types/std-types-number) | The diameter of the circle. Incompatible with `radius`. | No |

View File

@ -9,11 +9,11 @@ Construct a circle derived from 3 points.
```kcl
circleThreePoint(
@sketchSurfaceOrGroup: Sketch | Plane | Face,
@sketchOrSurface: Sketch | Plane | Face,
p1: Point2d,
p2: Point2d,
p3: Point2d,
tag?: TagDeclarator,
tag?: tag,
): Sketch
```
@ -23,11 +23,11 @@ circleThreePoint(
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketchSurfaceOrGroup` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) or [`Plane`](/docs/kcl-std/types/std-types-Plane) or [`Face`](/docs/kcl-std/types/std-types-Face) | Plane or surface to sketch on. | Yes |
| `sketchOrSurface` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) or [`Plane`](/docs/kcl-std/types/std-types-Plane) or [`Face`](/docs/kcl-std/types/std-types-Face) | Plane or surface to sketch on. | Yes |
| `p1` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | 1st point to derive the circle. | Yes |
| `p2` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | 2nd point to derive the circle. | Yes |
| `p3` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | 3rd point to derive the circle. | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagDeclarator`](/docs/kcl-lang/types#TagDeclarator) | Identifier for the circle to reference elsewhere. | No |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | Identifier for the circle to reference elsewhere. | No |
### Returns
@ -38,7 +38,7 @@ circleThreePoint(
```kcl
exampleSketch = startSketchOn(XY)
|> circleThreePoint(p1 = [10, 10], p2 = [20, 8], p3 = [15, 5])
|> circleThreePoint(p1 = [10,10], p2 = [20,8], p3 = [15,5])
|> extrude(length = 5)
```

View File

@ -1,39 +1,43 @@
---
title: "extrude"
subtitle: "Function in std::sketch"
excerpt: "Extend a 2-dimensional sketch through a third dimension in order to create new 3-dimensional volume, or if extruded into an existing volume, cut into an existing solid."
excerpt: ""
layout: manual
---
Extend a 2-dimensional sketch through a third dimension in order to create new 3-dimensional volume, or if extruded into an existing volume, cut into an existing solid.
```kcl
extrude(
@sketches: [Sketch],
length: number,
@sketches: [Sketch; 1+],
length: number(Length),
symmetric?: bool,
bidirectionalLength?: number,
tagStart?: TagDeclarator,
tagEnd?: TagDeclarator,
): [Solid]
bidirectionalLength?: number(Length),
tagStart?: tag,
tagEnd?: tag,
): [Solid; 1+]
```
You can provide more than one sketch to extrude, and they will all be extruded in the same direction.
Extend a 2-dimensional sketch through a third dimension in order to
create new 3-dimensional volume, or if extruded into an existing volume,cut into an existing solid.
You can provide more than one sketch to extrude, and they will all be
extruded in the same direction.
### Arguments
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketches` | [`[Sketch]`](/docs/kcl-std/types/std-types-Sketch) | Which sketch or sketches should be extruded | Yes |
| `length` | [`number`](/docs/kcl-std/types/std-types-number) | How far to extrude the given sketches | Yes |
| `sketches` | [`[Sketch; 1+]`](/docs/kcl-std/types/std-types-Sketch) | Which sketch or sketches should be extruded. | Yes |
| `length` | [`number(Length)`](/docs/kcl-std/types/std-types-number) | How far to extrude the given sketches. | Yes |
| `symmetric` | [`bool`](/docs/kcl-std/types/std-types-bool) | If true, the extrusion will happen symmetrically around the sketch. Otherwise, the extrusion will happen on only one side of the sketch. | No |
| `bidirectionalLength` | [`number`](/docs/kcl-std/types/std-types-number) | If specified, will also extrude in the opposite direction to 'distance' to the specified distance. If 'symmetric' is true, this value is ignored. | No |
| `tagStart` | [`TagDeclarator`](/docs/kcl-lang/types#TagDeclarator) | A named tag for the face at the start of the extrusion, i.e. the original sketch | No |
| `tagEnd` | [`TagDeclarator`](/docs/kcl-lang/types#TagDeclarator) | A named tag for the face at the end of the extrusion, i.e. the new face created by extruding the original sketch | No |
| `bidirectionalLength` | [`number(Length)`](/docs/kcl-std/types/std-types-number) | If specified, will also extrude in the opposite direction to 'distance' to the specified distance. If 'symmetric' is true, this value is ignored. | No |
| `tagStart` | [`tag`](/docs/kcl-std/types/std-types-tag) | A named tag for the face at the start of the extrusion, i.e. the original sketch. | No |
| `tagEnd` | [`tag`](/docs/kcl-std/types/std-types-tag) | A named tag for the face at the end of the extrusion, i.e. the new face created by extruding the original sketch. | No |
### Returns
[`[Solid]`](/docs/kcl-std/types/std-types-Solid)
[`[Solid; 1+]`](/docs/kcl-std/types/std-types-Solid)
### Examples
@ -42,10 +46,18 @@ You can provide more than one sketch to extrude, and they will all be extruded i
example = startSketchOn(XZ)
|> startProfile(at = [0, 0])
|> line(end = [10, 0])
|> arc(angleStart = 120, angleEnd = 0, radius = 5)
|> arc(
angleStart = 120,
angleEnd = 0,
radius = 5,
)
|> line(end = [5, 0])
|> line(end = [0, 10])
|> bezierCurve(control1 = [-10, 0], control2 = [2, 10], end = [-5, 10])
|> bezierCurve(
control1 = [-10, 0],
control2 = [2, 10],
end = [-5, 10],
)
|> line(end = [-5, -2])
|> close()
|> extrude(length = 10)
@ -56,10 +68,18 @@ example = startSketchOn(XZ)
```kcl
exampleSketch = startSketchOn(XZ)
|> startProfile(at = [-10, 0])
|> arc(angleStart = 120, angleEnd = -60, radius = 5)
|> arc(
angleStart = 120,
angleEnd = -60,
radius = 5,
)
|> line(end = [10, 0])
|> line(end = [5, 0])
|> bezierCurve(control1 = [-3, 0], control2 = [2, 10], end = [-5, 10])
|> bezierCurve(
control1 = [-3, 0],
control2 = [2, 10],
end = [-5, 10],
)
|> line(end = [-4, 10])
|> line(end = [-5, -2])
|> close()
@ -72,10 +92,18 @@ example = extrude(exampleSketch, length = 10)
```kcl
exampleSketch = startSketchOn(XZ)
|> startProfile(at = [-10, 0])
|> arc(angleStart = 120, angleEnd = -60, radius = 5)
|> arc(
angleStart = 120,
angleEnd = -60,
radius = 5,
)
|> line(end = [10, 0])
|> line(end = [5, 0])
|> bezierCurve(control1 = [-3, 0], control2 = [2, 10], end = [-5, 10])
|> bezierCurve(
control1 = [-3, 0],
control2 = [2, 10],
end = [-5, 10],
)
|> line(end = [-4, 10])
|> line(end = [-5, -2])
|> close()
@ -88,10 +116,18 @@ example = extrude(exampleSketch, length = 20, symmetric = true)
```kcl
exampleSketch = startSketchOn(XZ)
|> startProfile(at = [-10, 0])
|> arc(angleStart = 120, angleEnd = -60, radius = 5)
|> arc(
angleStart = 120,
angleEnd = -60,
radius = 5,
)
|> line(end = [10, 0])
|> line(end = [5, 0])
|> bezierCurve(control1 = [-3, 0], control2 = [2, 10], end = [-5, 10])
|> bezierCurve(
control1 = [-3, 0],
control2 = [2, 10],
end = [-5, 10],
)
|> line(end = [-4, 10])
|> line(end = [-5, -2])
|> close()

View File

@ -8,7 +8,7 @@ layout: manual
Extract the 'x' axis value of the last line segment in the provided 2-d sketch.
```kcl
lastSegX(@sketch: Sketch): number
lastSegX(@sketch: Sketch): number(Length)
```
@ -17,11 +17,11 @@ lastSegX(@sketch: Sketch): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketch` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) | The sketch whose line segment is being queried | Yes |
| `sketch` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) | The sketch whose line segment is being queried. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples

View File

@ -8,7 +8,7 @@ layout: manual
Extract the 'y' axis value of the last line segment in the provided 2-d sketch.
```kcl
lastSegY(@sketch: Sketch): number
lastSegY(@sketch: Sketch): number(Length)
```
@ -17,11 +17,11 @@ lastSegY(@sketch: Sketch): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketch` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) | The sketch whose line segment is being queried | Yes |
| `sketch` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) | The sketch whose line segment is being queried. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples

File diff suppressed because one or more lines are too long

View File

@ -1,39 +1,41 @@
---
title: "patternCircular2d"
subtitle: "Function in std::sketch"
excerpt: "Repeat a 2-dimensional sketch some number of times along a partial or complete circle some specified number of times. Each object may additionally be rotated along the circle, ensuring orientation of the solid with respect to the center of the circle is maintained."
excerpt: ""
layout: manual
---
Repeat a 2-dimensional sketch some number of times along a partial or complete circle some specified number of times. Each object may additionally be rotated along the circle, ensuring orientation of the solid with respect to the center of the circle is maintained.
```kcl
patternCircular2d(
@sketchSet: [Sketch],
instances: number,
@sketches: [Sketch; 1+],
instances: number(_),
center: Point2d,
arcDegrees?: number,
arcDegrees?: number(Angle),
rotateDuplicates?: bool,
useOriginal?: bool,
): [Sketch]
): [Sketch; 1+]
```
Repeat a 2-dimensional sketch some number of times along a partial or
complete circle some specified number of times. Each object mayadditionally be rotated along the circle, ensuring orientation of the
solid with respect to the center of the circle is maintained.
### Arguments
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketchSet` | [`[Sketch]`](/docs/kcl-std/types/std-types-Sketch) | Which sketch(es) to pattern | Yes |
| `instances` | [`number`](/docs/kcl-std/types/std-types-number) | The number of total instances. Must be greater than or equal to 1. This includes the original entity. For example, if instances is 2, there will be two copies -- the original, and one new copy. If instances is 1, this has no effect. | Yes |
| `sketches` | [`[Sketch; 1+]`](/docs/kcl-std/types/std-types-Sketch) | The sketch(es) to duplicate. | Yes |
| `instances` | [`number(_)`](/docs/kcl-std/types/std-types-number) | The number of total instances. Must be greater than or equal to 1. This includes the original entity. For example, if instances is 2, there will be two copies -- the original, and one new copy. If instances is 1, this has no effect. | Yes |
| `center` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | The center about which to make the pattern. This is a 2D vector. | Yes |
| `arcDegrees` | [`number`](/docs/kcl-std/types/std-types-number) | The arc angle (in degrees) to place the repetitions. Must be greater than 0. Defaults to 360. | No |
| `rotateDuplicates` | [`bool`](/docs/kcl-std/types/std-types-bool) | Whether or not to rotate the duplicates as they are copied. Defaults to true. | No |
| `useOriginal` | [`bool`](/docs/kcl-std/types/std-types-bool) | If the target was sketched on an extrusion, setting this will use the original sketch as the target, not the entire joined solid. Defaults to false. | No |
| `arcDegrees` | [`number(Angle)`](/docs/kcl-std/types/std-types-number) | The arc angle (in degrees) to place the repetitions. Must be greater than 0. | No |
| `rotateDuplicates` | [`bool`](/docs/kcl-std/types/std-types-bool) | Whether or not to rotate the duplicates as they are copied. | No |
| `useOriginal` | [`bool`](/docs/kcl-std/types/std-types-bool) | If the target was sketched on an extrusion, setting this will use the original sketch as the target, not the entire joined solid. | No |
### Returns
[`[Sketch]`](/docs/kcl-std/types/std-types-Sketch)
[`[Sketch; 1+]`](/docs/kcl-std/types/std-types-Sketch)
### Examples
@ -49,7 +51,7 @@ exampleSketch = startSketchOn(XZ)
center = [0, 0],
instances = 13,
arcDegrees = 360,
rotateDuplicates = true,
rotateDuplicates = true
)
example = extrude(exampleSketch, length = 1)

File diff suppressed because one or more lines are too long

View File

@ -9,9 +9,9 @@ Create a regular polygon with the specified number of sides that is either inscr
```kcl
polygon(
@sketchSurfaceOrGroup: Sketch | Plane | Face,
radius: number,
numSides: u64,
@sketchOrSurface: Sketch | Plane | Face,
radius: number(Length),
numSides: number(_),
center: Point2d,
inscribed?: bool,
): Sketch
@ -23,11 +23,11 @@ polygon(
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| `sketchSurfaceOrGroup` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) or [`Plane`](/docs/kcl-std/types/std-types-Plane) or [`Face`](/docs/kcl-std/types/std-types-Face) | Plane or surface to sketch on | Yes |
| `radius` | [`number`](/docs/kcl-std/types/std-types-number) | The radius of the polygon | Yes |
| `numSides` | `u64` | The number of sides in the polygon | Yes |
| `center` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | The center point of the polygon | Yes |
| `inscribed` | [`bool`](/docs/kcl-std/types/std-types-bool) | Whether the polygon is inscribed (true, the default) or circumscribed (false) about a circle with the specified radius | No |
| `sketchOrSurface` | [`Sketch`](/docs/kcl-std/types/std-types-Sketch) or [`Plane`](/docs/kcl-std/types/std-types-Plane) or [`Face`](/docs/kcl-std/types/std-types-Face) | Plane or surface to sketch on. | Yes |
| `radius` | [`number(Length)`](/docs/kcl-std/types/std-types-number) | The radius of the polygon. | Yes |
| `numSides` | [`number(_)`](/docs/kcl-std/types/std-types-number) | The number of sides in the polygon. | Yes |
| `center` | [`Point2d`](/docs/kcl-std/types/std-types-Point2d) | The center point of the polygon. | Yes |
| `inscribed` | [`bool`](/docs/kcl-std/types/std-types-bool) | Whether the polygon is inscribed (true, the default) or circumscribed (false) about a circle with the specified radius. | No |
### Returns
@ -40,11 +40,11 @@ polygon(
// Create a regular hexagon inscribed in a circle of radius 10
hex = startSketchOn(XY)
|> polygon(
radius = 10,
numSides = 6,
center = [0, 0],
inscribed = true,
)
radius = 10,
numSides = 6,
center = [0, 0],
inscribed = true,
)
example = extrude(hex, length = 5)
```
@ -55,11 +55,11 @@ example = extrude(hex, length = 5)
// Create a square circumscribed around a circle of radius 5
square = startSketchOn(XY)
|> polygon(
radius = 5.0,
numSides = 4,
center = [10, 10],
inscribed = false,
)
radius = 5.0,
numSides = 4,
center = [10, 10],
inscribed = false,
)
example = extrude(square, length = 5)
```

View File

@ -8,7 +8,7 @@ layout: manual
Compute the angle (in degrees) of the provided line segment.
```kcl
segAng(@tag: TagIdentifier): number
segAng(@tag: tag): number(Angle)
```
@ -17,11 +17,11 @@ segAng(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Angle)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples

View File

@ -8,7 +8,7 @@ layout: manual
Compute the ending point of the provided line segment.
```kcl
segEnd(@tag: TagIdentifier): Point2d
segEnd(@tag: tag): Point2d
```
@ -17,7 +17,7 @@ segEnd(@tag: TagIdentifier): Point2d
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
@ -39,9 +39,9 @@ cube = startSketchOn(XY)
fn cylinder(radius, tag) {
return startSketchOn(XY)
|> startProfile(at = [0, 0])
|> circle(radius = radius, center = segEnd(tag))
|> extrude(length = radius)
|> startProfile(at = [0, 0])
|> circle(radius = radius, center = segEnd(tag) )
|> extrude(length = radius)
}
cylinder(radius = 1, tag = line1)

View File

@ -8,7 +8,7 @@ layout: manual
Compute the ending point of the provided line segment along the 'x' axis.
```kcl
segEndX(@tag: TagIdentifier): number
segEndX(@tag: tag): number(Length)
```
@ -17,11 +17,11 @@ segEndX(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples

View File

@ -8,7 +8,7 @@ layout: manual
Compute the ending point of the provided line segment along the 'y' axis.
```kcl
segEndY(@tag: TagIdentifier): number
segEndY(@tag: tag): number(Length)
```
@ -17,11 +17,11 @@ segEndY(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples

View File

@ -8,7 +8,7 @@ layout: manual
Compute the length of the provided line segment.
```kcl
segLen(@tag: TagIdentifier): number
segLen(@tag: tag): number(Length)
```
@ -17,11 +17,11 @@ segLen(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples
@ -29,9 +29,16 @@ segLen(@tag: TagIdentifier): number
```kcl
exampleSketch = startSketchOn(XZ)
|> startProfile(at = [0, 0])
|> angledLine(angle = 60, length = 10, tag = $thing)
|> angledLine(
angle = 60,
length = 10,
tag = $thing,
)
|> tangentialArc(angle = -120, radius = 5)
|> angledLine(angle = -60, length = segLen(thing))
|> angledLine(
angle = -60,
length = segLen(thing),
)
|> close()
example = extrude(exampleSketch, length = 5)

View File

@ -8,7 +8,7 @@ layout: manual
Compute the starting point of the provided line segment.
```kcl
segStart(@tag: TagIdentifier): Point2d
segStart(@tag: tag): Point2d
```
@ -17,7 +17,7 @@ segStart(@tag: TagIdentifier): Point2d
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
@ -39,9 +39,9 @@ cube = startSketchOn(XY)
fn cylinder(radius, tag) {
return startSketchOn(XY)
|> startProfile(at = [0, 0])
|> circle(radius = radius, center = segStart(tag))
|> extrude(length = radius)
|> startProfile(at = [0, 0])
|> circle( radius = radius, center = segStart(tag) )
|> extrude(length = radius)
}
cylinder(radius = 1, tag = line1)

View File

@ -8,7 +8,7 @@ layout: manual
Compute the starting point of the provided line segment along the 'x' axis.
```kcl
segStartX(@tag: TagIdentifier): number
segStartX(@tag: tag): number(Length)
```
@ -17,11 +17,11 @@ segStartX(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples

View File

@ -8,7 +8,7 @@ layout: manual
Compute the starting point of the provided line segment along the 'y' axis.
```kcl
segStartY(@tag: TagIdentifier): number
segStartY(@tag: tag): number(Length)
```
@ -17,11 +17,11 @@ segStartY(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Length)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples
@ -32,7 +32,7 @@ exampleSketch = startSketchOn(XZ)
|> line(end = [20, 0])
|> line(end = [0, 3], tag = $thing)
|> line(end = [-10, 0])
|> line(end = [0, 20 - segStartY(thing)])
|> line(end = [0, 20-segStartY(thing)])
|> line(end = [-10, 0])
|> close()

File diff suppressed because one or more lines are too long

View File

@ -8,7 +8,7 @@ layout: manual
Returns the angle coming out of the end of the segment in degrees.
```kcl
tangentToEnd(@tag: TagIdentifier): number
tangentToEnd(@tag: tag): number(Angle)
```
@ -17,11 +17,11 @@ tangentToEnd(@tag: TagIdentifier): number
| Name | Type | Description | Required |
|----------|------|-------------|----------|
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`TagIdentifier`](/docs/kcl-lang/types#TagIdentifier) | The line segment being queried by its tag | Yes |
| [`tag`](/docs/kcl-std/types/std-types-tag) | [`tag`](/docs/kcl-std/types/std-types-tag) | The line segment being queried by its tag. | Yes |
### Returns
[`number`](/docs/kcl-std/types/std-types-number) - A number.
[`number(Angle)`](/docs/kcl-std/types/std-types-number) - A number.
### Examples
@ -32,7 +32,10 @@ pillSketch = startSketchOn(XZ)
|> startProfile(at = [0, 0])
|> line(end = [20, 0])
|> tangentialArc(end = [0, 10], tag = $arc1)
|> angledLine(angle = tangentToEnd(arc1), length = 20)
|> angledLine(
angle = tangentToEnd(arc1),
length = 20,
)
|> tangentialArc(end = [0, -10])
|> close()
@ -47,7 +50,10 @@ pillSketch = startSketchOn(XZ)
|> startProfile(at = [0, 0])
|> line(end = [0, 20])
|> tangentialArc(endAbsolute = [10, 20], tag = $arc1)
|> angledLine(angle = tangentToEnd(arc1), length = 20)
|> angledLine(
angle = tangentToEnd(arc1),
length = 20,
)
|> tangentialArc(end = [-10, 0])
|> close()
@ -60,7 +66,10 @@ pillExtrude = extrude(pillSketch, length = 10)
rectangleSketch = startSketchOn(XZ)
|> startProfile(at = [0, 0])
|> line(end = [10, 0], tag = $seg1)
|> angledLine(angle = tangentToEnd(seg1), length = 10)
|> angledLine(
angle = tangentToEnd(seg1),
length = 10,
)
|> line(end = [0, 10])
|> line(end = [-20, 0])
|> close()
@ -73,7 +82,11 @@ rectangleExtrude = extrude(rectangleSketch, length = 10)
```kcl
bottom = startSketchOn(XY)
|> startProfile(at = [0, 0])
|> arc(endAbsolute = [10, 10], interiorAbsolute = [5, 1], tag = $arc1)
|> arc(
endAbsolute = [10, 10],
interiorAbsolute = [5, 1],
tag = $arc1,
)
|> angledLine(angle = tangentToEnd(arc1), length = 20)
|> close()
```
@ -82,7 +95,7 @@ bottom = startSketchOn(XY)
```kcl
circSketch = startSketchOn(XY)
|> circle(center = [0, 0], radius = 3, tag = $circ)
|> circle(center = [0, 0], radius= 3, tag = $circ)
triangleSketch = startSketchOn(XY)
|> startProfile(at = [-5, 0])

View File

@ -9,12 +9,11 @@ layout: manual
### Functions
* [**std**](/docs/kcl-std/modules/std)
* [`assert`](/docs/kcl-std/assert)
* [`assertIs`](/docs/kcl-std/assertIs)
* [`assert`](/docs/kcl-std/functions/std-assert)
* [`assertIs`](/docs/kcl-std/functions/std-assertIs)
* [`clone`](/docs/kcl-std/functions/std-clone)
* [`helix`](/docs/kcl-std/functions/std-helix)
* [`offsetPlane`](/docs/kcl-std/functions/std-offsetPlane)
* [`patternLinear2d`](/docs/kcl-std/patternLinear2d)
* [**std::appearance**](/docs/kcl-std/modules/std-appearance)
* [`appearance::hexString`](/docs/kcl-std/functions/std-appearance-hexString)
* [**std::array**](/docs/kcl-std/modules/std-array)
@ -53,38 +52,39 @@ layout: manual
* [`arc`](/docs/kcl-std/arc)
* [`bezierCurve`](/docs/kcl-std/bezierCurve)
* [`circle`](/docs/kcl-std/functions/std-sketch-circle)
* [`circleThreePoint`](/docs/kcl-std/circleThreePoint)
* [`circleThreePoint`](/docs/kcl-std/functions/std-sketch-circleThreePoint)
* [`close`](/docs/kcl-std/close)
* [`extrude`](/docs/kcl-std/extrude)
* [`extrude`](/docs/kcl-std/functions/std-sketch-extrude)
* [`getCommonEdge`](/docs/kcl-std/functions/std-sketch-getCommonEdge)
* [`getNextAdjacentEdge`](/docs/kcl-std/functions/std-sketch-getNextAdjacentEdge)
* [`getOppositeEdge`](/docs/kcl-std/functions/std-sketch-getOppositeEdge)
* [`getPreviousAdjacentEdge`](/docs/kcl-std/functions/std-sketch-getPreviousAdjacentEdge)
* [`involuteCircular`](/docs/kcl-std/involuteCircular)
* [`lastSegX`](/docs/kcl-std/lastSegX)
* [`lastSegY`](/docs/kcl-std/lastSegY)
* [`lastSegX`](/docs/kcl-std/functions/std-sketch-lastSegX)
* [`lastSegY`](/docs/kcl-std/functions/std-sketch-lastSegY)
* [`line`](/docs/kcl-std/line)
* [`loft`](/docs/kcl-std/loft)
* [`patternCircular2d`](/docs/kcl-std/patternCircular2d)
* [`loft`](/docs/kcl-std/functions/std-sketch-loft)
* [`patternCircular2d`](/docs/kcl-std/functions/std-sketch-patternCircular2d)
* [`patternLinear2d`](/docs/kcl-std/functions/std-sketch-patternLinear2d)
* [`patternTransform2d`](/docs/kcl-std/functions/std-sketch-patternTransform2d)
* [`polygon`](/docs/kcl-std/polygon)
* [`polygon`](/docs/kcl-std/functions/std-sketch-polygon)
* [`profileStart`](/docs/kcl-std/profileStart)
* [`profileStartX`](/docs/kcl-std/profileStartX)
* [`profileStartY`](/docs/kcl-std/profileStartY)
* [`revolve`](/docs/kcl-std/functions/std-sketch-revolve)
* [`segAng`](/docs/kcl-std/segAng)
* [`segEnd`](/docs/kcl-std/segEnd)
* [`segEndX`](/docs/kcl-std/segEndX)
* [`segEndY`](/docs/kcl-std/segEndY)
* [`segLen`](/docs/kcl-std/segLen)
* [`segStart`](/docs/kcl-std/segStart)
* [`segStartX`](/docs/kcl-std/segStartX)
* [`segStartY`](/docs/kcl-std/segStartY)
* [`segAng`](/docs/kcl-std/functions/std-sketch-segAng)
* [`segEnd`](/docs/kcl-std/functions/std-sketch-segEnd)
* [`segEndX`](/docs/kcl-std/functions/std-sketch-segEndX)
* [`segEndY`](/docs/kcl-std/functions/std-sketch-segEndY)
* [`segLen`](/docs/kcl-std/functions/std-sketch-segLen)
* [`segStart`](/docs/kcl-std/functions/std-sketch-segStart)
* [`segStartX`](/docs/kcl-std/functions/std-sketch-segStartX)
* [`segStartY`](/docs/kcl-std/functions/std-sketch-segStartY)
* [`startProfile`](/docs/kcl-std/startProfile)
* [`startSketchOn`](/docs/kcl-std/startSketchOn)
* [`subtract2d`](/docs/kcl-std/subtract2d)
* [`sweep`](/docs/kcl-std/sweep)
* [`tangentToEnd`](/docs/kcl-std/tangentToEnd)
* [`sweep`](/docs/kcl-std/functions/std-sketch-sweep)
* [`tangentToEnd`](/docs/kcl-std/functions/std-sketch-tangentToEnd)
* [`tangentialArc`](/docs/kcl-std/tangentialArc)
* [`xLine`](/docs/kcl-std/xLine)
* [`yLine`](/docs/kcl-std/yLine)

View File

@ -17,38 +17,39 @@ This module contains functions for creating and manipulating sketches, and makin
* [`arc`](/docs/kcl-std/arc)
* [`bezierCurve`](/docs/kcl-std/bezierCurve)
* [`circle`](/docs/kcl-std/functions/std-sketch-circle)
* [`circleThreePoint`](/docs/kcl-std/circleThreePoint)
* [`circleThreePoint`](/docs/kcl-std/functions/std-sketch-circleThreePoint)
* [`close`](/docs/kcl-std/close)
* [`extrude`](/docs/kcl-std/extrude)
* [`extrude`](/docs/kcl-std/functions/std-sketch-extrude)
* [`getCommonEdge`](/docs/kcl-std/functions/std-sketch-getCommonEdge)
* [`getNextAdjacentEdge`](/docs/kcl-std/functions/std-sketch-getNextAdjacentEdge)
* [`getOppositeEdge`](/docs/kcl-std/functions/std-sketch-getOppositeEdge)
* [`getPreviousAdjacentEdge`](/docs/kcl-std/functions/std-sketch-getPreviousAdjacentEdge)
* [`involuteCircular`](/docs/kcl-std/involuteCircular)
* [`lastSegX`](/docs/kcl-std/lastSegX)
* [`lastSegY`](/docs/kcl-std/lastSegY)
* [`lastSegX`](/docs/kcl-std/functions/std-sketch-lastSegX)
* [`lastSegY`](/docs/kcl-std/functions/std-sketch-lastSegY)
* [`line`](/docs/kcl-std/line)
* [`loft`](/docs/kcl-std/loft)
* [`patternCircular2d`](/docs/kcl-std/patternCircular2d)
* [`loft`](/docs/kcl-std/functions/std-sketch-loft)
* [`patternCircular2d`](/docs/kcl-std/functions/std-sketch-patternCircular2d)
* [`patternLinear2d`](/docs/kcl-std/functions/std-sketch-patternLinear2d)
* [`patternTransform2d`](/docs/kcl-std/functions/std-sketch-patternTransform2d)
* [`polygon`](/docs/kcl-std/polygon)
* [`polygon`](/docs/kcl-std/functions/std-sketch-polygon)
* [`profileStart`](/docs/kcl-std/profileStart)
* [`profileStartX`](/docs/kcl-std/profileStartX)
* [`profileStartY`](/docs/kcl-std/profileStartY)
* [`revolve`](/docs/kcl-std/functions/std-sketch-revolve)
* [`segAng`](/docs/kcl-std/segAng)
* [`segEnd`](/docs/kcl-std/segEnd)
* [`segEndX`](/docs/kcl-std/segEndX)
* [`segEndY`](/docs/kcl-std/segEndY)
* [`segLen`](/docs/kcl-std/segLen)
* [`segStart`](/docs/kcl-std/segStart)
* [`segStartX`](/docs/kcl-std/segStartX)
* [`segStartY`](/docs/kcl-std/segStartY)
* [`segAng`](/docs/kcl-std/functions/std-sketch-segAng)
* [`segEnd`](/docs/kcl-std/functions/std-sketch-segEnd)
* [`segEndX`](/docs/kcl-std/functions/std-sketch-segEndX)
* [`segEndY`](/docs/kcl-std/functions/std-sketch-segEndY)
* [`segLen`](/docs/kcl-std/functions/std-sketch-segLen)
* [`segStart`](/docs/kcl-std/functions/std-sketch-segStart)
* [`segStartX`](/docs/kcl-std/functions/std-sketch-segStartX)
* [`segStartY`](/docs/kcl-std/functions/std-sketch-segStartY)
* [`startProfile`](/docs/kcl-std/startProfile)
* [`startSketchOn`](/docs/kcl-std/startSketchOn)
* [`subtract2d`](/docs/kcl-std/subtract2d)
* [`sweep`](/docs/kcl-std/sweep)
* [`tangentToEnd`](/docs/kcl-std/tangentToEnd)
* [`sweep`](/docs/kcl-std/functions/std-sketch-sweep)
* [`tangentToEnd`](/docs/kcl-std/functions/std-sketch-tangentToEnd)
* [`tangentialArc`](/docs/kcl-std/tangentialArc)
* [`xLine`](/docs/kcl-std/xLine)
* [`yLine`](/docs/kcl-std/yLine)

View File

@ -36,10 +36,9 @@ You might also want the [KCL language reference](/docs/kcl-lang) or the [KCL gui
* [`Y`](/docs/kcl-std/consts/std-Y)
* [`YZ`](/docs/kcl-std/consts/std-YZ)
* [`Z`](/docs/kcl-std/consts/std-Z)
* [`assert`](/docs/kcl-std/assert)
* [`assertIs`](/docs/kcl-std/assertIs)
* [`assert`](/docs/kcl-std/functions/std-assert)
* [`assertIs`](/docs/kcl-std/functions/std-assertIs)
* [`clone`](/docs/kcl-std/functions/std-clone)
* [`helix`](/docs/kcl-std/functions/std-helix)
* [`offsetPlane`](/docs/kcl-std/functions/std-offsetPlane)
* [`patternLinear2d`](/docs/kcl-std/patternLinear2d)

File diff suppressed because it is too large Load Diff

View File

@ -265,6 +265,7 @@ middle(0)
})
await expect(
page.getByText(`assert failed: Expected 0 to be greater than 0 but it wasn't
assert()
check()
middle()`)
).toBeVisible()

View File

@ -1766,7 +1766,7 @@ loft001 = loft([sketch001, sketch002])
sketch001 = startSketchOn(YZ)
profile001 = circle(sketch001, center = [0, 0], radius = 500)
sketch002 = startSketchOn(XZ)
|> startProfile(at = [0, 0])
profile002 = startProfile(sketch002, at = [0, 0])
|> xLine(length = -500)
|> tangentialArc(endAbsolute = [-2000, 500])`,
},
@ -1782,7 +1782,7 @@ profile001 = startProfile(sketch001, at = [-400, -400])
|> line(endAbsolute = [profileStartX(%), profileStartY(%)])
|> close()
sketch002 = startSketchOn(XZ)
|> startProfile(at = [0, 0])
profile002 = startProfile(sketch002, at = [0, 0])
|> xLine(length = -500)
|> tangentialArc(endAbsolute = [-2000, 500])`,
},
@ -1810,9 +1810,9 @@ sketch002 = startSketchOn(XZ)
testPoint.x - 50,
testPoint.y
)
const sweepDeclaration = 'sweep001 = sweep(profile001, path = sketch002)'
const sweepDeclaration = 'sweep001 = sweep(profile001, path = profile002)'
const editedSweepDeclaration =
'sweep001 = sweep(profile001, path = sketch002, sectional = true)'
'sweep001 = sweep(profile001, path = profile002, sectional = true)'
await test.step(`Look for sketch001`, async () => {
await toolbar.closePane('code')

View File

@ -2116,3 +2116,74 @@ test(
})
}
)
test(
'segment position changes persist after dragging and reopening project',
{ tag: '@desktop' },
async ({ scene, cmdBar, context, page, editor, toolbar }, testInfo) => {
const projectName = 'segment-drag-test'
await context.folderSetupFn(async (dir) => {
const projectDir = path.join(dir, projectName)
await fsp.mkdir(projectDir, { recursive: true })
await fsp.writeFile(
path.join(projectDir, 'main.kcl'),
`sketch001 = startSketchOn(XZ)
profile001 = startProfile(sketch001, at = [0, 0])
|> line(end = [0, 6])
|> line(end = [10, 0])
|> line(end = [-8, -5])
`
)
})
await page.setBodyDimensions({ width: 1200, height: 600 })
const u = await getUtils(page)
await test.step('Opening the project and entering sketch mode', async () => {
await expect(page.getByText(projectName)).toBeVisible()
await page.getByText(projectName).click()
await scene.settled(cmdBar)
// go to sketch mode
await (await toolbar.getFeatureTreeOperation('Sketch', 0)).dblclick()
// Without this, "add axis n grid" action runs after editing the sketch and invokes codeManager.writeToFile()
// so we wait for that action to run first before we start editing the sketch and making sure it's saving
// because of those edits.
await page.waitForTimeout(2000)
})
const changedLine = 'line(end = [-6.54, -4.99])'
await test.step('Dragging the line endpoint to modify it', async () => {
// Get the last line's endpoint position
const lineEnd = await u.getBoundingBox('[data-overlay-index="3"]')
await page.mouse.move(lineEnd.x, lineEnd.y - 5)
await page.mouse.down()
await page.mouse.move(lineEnd.x + 80, lineEnd.y)
await page.mouse.up()
await editor.expectEditor.toContain(changedLine)
// Exit sketch mode
await page.keyboard.press('Escape')
await page.waitForTimeout(100)
})
await test.step('Going back to dashboard', async () => {
await page.getByTestId('app-logo').click()
await page.waitForTimeout(1000)
})
await test.step('Reopening the project and verifying changes are saved', async () => {
await page.getByText(projectName).click()
await scene.settled(cmdBar)
// Check if new line coordinates were saved
await editor.expectEditor.toContain(changedLine)
})
}
)

View File

@ -1733,7 +1733,7 @@ profile003 = startProfile(sketch001, at = [206.63, -56.73])
await page.waitForTimeout(600)
})
const codeFromTangentialArc = ` |> tangentialArc(endAbsolute = [39.49, 88.22])`
const codeFromTangentialArc = ` |> tangentialArc(end = [-10.82, 144.95])`
await test.step('check that tangential tool does not snap to other profile starts', async () => {
await toolbar.selectTangentialArc()
await page.waitForTimeout(1000)
@ -1755,7 +1755,7 @@ profile003 = startProfile(sketch001, at = [206.63, -56.73])
// check pixel is now gray at tanArcLocation to verify code has executed
await scene.expectPixelColor([26, 26, 26], tanArcLocation, 15)
await editor.expectEditor.not.toContain(
`tangentialArc(endAbsolute = [39.49, 88.22])`
`tangentialArc(end = [-10.82, 144.95])`
)
})
@ -1955,7 +1955,7 @@ profile003 = startProfile(sketch001, at = [206.63, -56.73])
await endArcStartLine()
await editor.expectEditor.toContain(
`|> tangentialArc(endAbsolute = [16.61, 4.14])`
`|> tangentialArc(end = [2.98, -7.52])`
)
// Add a three-point arc segment
@ -3181,7 +3181,7 @@ test.describe('Redirecting to home page and back to the original file should cle
sketch001 = startSketchOn(XZ)
profile001 = startProfile(sketch001, at = [0, 0])
|> line(end = [191.39, 191.39])
|> tangentialArc(endAbsolute = [287.08, 95.69], tag = $seg01)
|> tangentialArc(end = [95.69, -95.7], tag = $seg01)
|> angledLine(angle = tangentToEnd(seg01), length = 135.34)
|> arc(interiorAbsolute = [191.39, -95.69], endAbsolute = [287.08, -95.69], tag = $seg02)
|> angledLine(angle = tangentToEnd(seg02) + turns::HALF_TURN, length = 270.67)

View File

@ -375,22 +375,22 @@ test.describe(
await expect(u.codeLocator).toHaveText(code)
await toolbar.selectTangentialArc()
await page.waitForTimeout(100)
await page.waitForTimeout(200)
// click to continue profile
await page.mouse.click(813, 392)
await page.waitForTimeout(100)
await page.waitForTimeout(300)
await page.mouse.click(startXPx + PUR * 30, 500 - PUR * 20)
code += `
|> tangentialArc(endAbsolute = [551.2, -62.01])`
|> tangentialArc(end = [184.31, 184.31])`
await expect(u.codeLocator).toHaveText(code)
// click tangential arc tool again to unequip it
// it will be available directly in the toolbar since it was last equipped
await toolbar.tangentialArcBtn.click()
await page.waitForTimeout(100)
await page.waitForTimeout(1000)
// screen shot should show the sketch
await expect(page).toHaveScreenshot({
@ -472,20 +472,20 @@ test.describe(
await expect(u.codeLocator).toHaveText(code)
await toolbar.selectTangentialArc()
await page.waitForTimeout(100)
await page.waitForTimeout(200)
// click to continue profile
await page.mouse.click(813, 392)
await page.waitForTimeout(100)
await page.waitForTimeout(300)
await page.mouse.click(startXPx + PUR * 30, 500 - PUR * 20)
code += `
|> tangentialArc(endAbsolute = [551.2, -62.01])`
|> tangentialArc(end = [184.31, 184.31])`
await expect(u.codeLocator).toHaveText(code)
await toolbar.tangentialArcBtn.click()
await page.waitForTimeout(100)
await page.waitForTimeout(1000)
// screen shot should show the sketch
await expect(page).toHaveScreenshot({
@ -823,7 +823,7 @@ test('theme persists', async ({ page, context, homePage }) => {
uploadThroughput: -1,
})
await expect(networkToggle).toContainText('Connected')
await expect(networkToggle).toContainText('Network health (Strong)')
await expect(page.getByText('building scene')).not.toBeVisible()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

View File

@ -14,8 +14,10 @@ test.describe('Test network related behaviors', () => {
'simulate network down and network little widget',
{ tag: '@skipLocalEngine' },
async ({ page, homePage }) => {
const networkToggleConnectedText = page.getByText('Connected')
const networkToggleWeakText = page.getByText('Network health (Weak)')
const networkToggleConnectedText = page.getByText(
'Network health (Strong)'
)
const networkToggleWeakText = page.getByText('Network health (Ok)')
const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 })
@ -98,8 +100,10 @@ test.describe('Test network related behaviors', () => {
{ tag: '@skipLocalEngine' },
async ({ page, homePage, toolbar, scene, cmdBar }) => {
const networkToggle = page.getByTestId('network-toggle')
const networkToggleConnectedText = page.getByText('Connected')
const networkToggleWeakText = page.getByText('Network health (Weak)')
const networkToggleConnectedText = page.getByText(
'Network health (Strong)'
)
const networkToggleWeakText = page.getByText('Network health (Ok)')
const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 })
@ -282,8 +286,10 @@ profile001 = startProfile(sketch001, at = [12.34, -12.34])
{ tag: ['@desktop', '@skipLocalEngine'] },
async ({ page, homePage, scene, cmdBar, toolbar, tronApp }) => {
const networkToggle = page.getByTestId('network-toggle')
const networkToggleConnectedText = page.getByText('Connected')
const networkToggleWeakText = page.getByText('Network health (Weak)')
const networkToggleConnectedText = page.getByText(
'Network health (Strong)'
)
const networkToggleWeakText = page.getByText('Network health (Ok)')
if (!tronApp) {
fail()

View File

@ -27,7 +27,7 @@ if len(modified_release_body) > max_length:
# Message to send to Discord
data = {
"content": textwrap.dedent(f'''
**{release_version}** is now available! Check out the latest features and improvements here: <https://zoo.dev/design-studio>
**{release_version}** is now available! Check out the latest features and improvements here: <https://zoo.dev/design-studio/download#added>
{modified_release_body}
'''),

View File

@ -29,27 +29,27 @@ plateRevolve = startSketchOn(YZ)
|> close()
|> revolve(axis = Y, angle = 65, symmetric = true)
// Create a hole sketch with the size and location of each bolt hole
holeSketch = startSketchOn(XZ)
hole01 = circle(holeSketch, center = [0, 12.25], radius = boltSize / 2)
|> extrude(length = -100)
hole02 = circle(holeSketch, center = [0, 29.5], radius = boltSize / 2)
|> extrude(length = -100)
hole03 = circle(holeSketch, center = [0, 46.25], radius = boltSize / 2)
|> extrude(length = -100)
hole04 = circle(holeSketch, center = [0, 77], radius = boltSize / 2)
|> extrude(length = -100)
hole05 = circle(holeSketch, center = [0, 100], radius = boltSize / 2)
|> extrude(length = -100)
hole06 = circle(holeSketch, center = [0, 130], radius = boltSize / 2)
|> extrude(length = -100)
hole07 = circle(holeSketch, center = [-20, 130], radius = boltSize / 2)
|> extrude(length = -100)
hole08 = circle(holeSketch, center = [20, 130], radius = boltSize / 2)
|> extrude(length = -100)
// Define a function to create and extrude holes
fn holeFn(@center) {
return startSketchOn(XZ)
|> circle(center = center, diameter = boltSize)
|> extrude(length = -100)
}
// Cut each guiding clearance hole from the bone plate
solid001 = subtract([plateRevolve], tools = union([hole01, hole02]))
solid002 = subtract([solid001], tools = union([hole03, hole04]))
solid003 = subtract([solid002], tools = union([hole05, hole06]))
solid004 = subtract([solid003], tools = union([hole07, hole08]))
// Create a hole sketch with the size and location of each bolt hole
holeCenters = [
[0, 12.25],
[0, 29.5],
[0, 46.25],
[0, 77],
[0, 100],
[0, 130],
[-20, 130],
[20, 130]
]
// Use map to apply the hole creation function to the list of center coordinates
holes = map(holeCenters, f = holeFn)
// Cut each guiding clearance hole from the bone plate using a single subtract operation
solid = subtract([plateRevolve], tools = holes)

View File

@ -11,24 +11,20 @@ filletRadius = 0.5
plateThickness = .5
centerHoleDiameter = 2
// Create a function that defines the body width and length of the mounting plate. Tag the corners so they can be passed through the fillet function.
fn rectShape(pos, w, l) {
rr = startSketchOn(XY)
|> startProfile(at = [pos[0] - (w / 2), pos[1] - (l / 2)])
|> line(endAbsolute = [pos[0] + w / 2, pos[1] - (l / 2)], tag = $edge1)
|> line(endAbsolute = [pos[0] + w / 2, pos[1] + l / 2], tag = $edge2)
|> line(endAbsolute = [pos[0] - (w / 2), pos[1] + l / 2], tag = $edge3)
|> close(tag = $edge4)
return rr
}
// Define the hole radius and x, y location constants
holeRadius = .25
holeIndex = .75
sketch001 = startSketchOn(XY)
rectShape = startProfile(sketch001, at = [-plateWidth / 2, plateLength / 2])
|> angledLine(angle = 0, length = plateWidth, tag = $basePlateEdge1)
|> angledLine(angle = segAng(basePlateEdge1) - 90, length = plateLength, tag = $basePlateEdge2)
|> angledLine(angle = segAng(basePlateEdge1), length = -segLen(basePlateEdge1), tag = $basePlateEdge3)
|> line(endAbsolute = [profileStartX(%), profileStartY(%)], tag = $basePlateEdge4)
|> close()
// Create the mounting plate extrusion, holes, and fillets
rs = rectShape(pos = [0, 0], w = plateWidth, l = plateLength)
part = rs
part = rectShape
|> subtract2d(tool = circle(
center = [
-plateWidth / 2 + holeIndex,
@ -62,9 +58,9 @@ part = rs
|> fillet(
radius = filletRadius,
tags = [
getPreviousAdjacentEdge(rs.tags.edge1),
getPreviousAdjacentEdge(rs.tags.edge2),
getPreviousAdjacentEdge(rs.tags.edge3),
getPreviousAdjacentEdge(rs.tags.edge4)
getCommonEdge(faces = [basePlateEdge3, basePlateEdge2]),
getCommonEdge(faces = [basePlateEdge4, basePlateEdge3]),
getCommonEdge(faces = [basePlateEdge4, basePlateEdge1]),
getCommonEdge(faces = [basePlateEdge2, basePlateEdge1])
],
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

20
rust/Cargo.lock generated
View File

@ -1815,7 +1815,7 @@ dependencies = [
[[package]]
name = "kcl-bumper"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"anyhow",
"clap",
@ -1826,7 +1826,7 @@ dependencies = [
[[package]]
name = "kcl-derive-docs"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"Inflector",
"anyhow",
@ -1845,7 +1845,7 @@ dependencies = [
[[package]]
name = "kcl-directory-test-macro"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"convert_case",
"proc-macro2",
@ -1855,7 +1855,7 @@ dependencies = [
[[package]]
name = "kcl-language-server"
version = "0.2.77"
version = "0.2.78"
dependencies = [
"anyhow",
"clap",
@ -1876,7 +1876,7 @@ dependencies = [
[[package]]
name = "kcl-language-server-release"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"anyhow",
"clap",
@ -1896,7 +1896,7 @@ dependencies = [
[[package]]
name = "kcl-lib"
version = "0.2.77"
version = "0.2.78"
dependencies = [
"anyhow",
"approx 0.5.1",
@ -1973,7 +1973,7 @@ dependencies = [
[[package]]
name = "kcl-python-bindings"
version = "0.3.77"
version = "0.3.78"
dependencies = [
"anyhow",
"kcl-lib",
@ -1988,7 +1988,7 @@ dependencies = [
[[package]]
name = "kcl-test-server"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"anyhow",
"hyper 0.14.32",
@ -2001,7 +2001,7 @@ dependencies = [
[[package]]
name = "kcl-to-core"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"anyhow",
"async-trait",
@ -2015,7 +2015,7 @@ dependencies = [
[[package]]
name = "kcl-wasm-lib"
version = "0.1.77"
version = "0.1.78"
dependencies = [
"anyhow",
"bson",

View File

@ -1,7 +1,7 @@
[package]
name = "kcl-bumper"
version = "0.1.77"
version = "0.1.78"
edition = "2021"
repository = "https://github.com/KittyCAD/modeling-api"
rust-version = "1.76"

View File

@ -1,7 +1,7 @@
[package]
name = "kcl-derive-docs"
description = "A tool for generating documentation from Rust derive macros"
version = "0.1.77"
version = "0.1.78"
edition = "2021"
license = "MIT"
repository = "https://github.com/KittyCAD/modeling-app"

View File

@ -117,6 +117,38 @@ pub const TEST_NAMES: &[&str] = &[
"std-sketch-getOppositeEdge-0",
"std-sketch-getPreviousAdjacentEdge-0",
"std-sketch-getNextAdjacentEdge-0",
"std-sketch-extrude-0",
"std-sketch-extrude-1",
"std-sketch-extrude-2",
"std-sketch-extrude-3",
"std-sketch-polygon-0",
"std-sketch-polygon-1",
"std-sketch-sweep-0",
"std-sketch-sweep-1",
"std-sketch-sweep-2",
"std-sketch-sweep-3",
"std-sketch-loft-0",
"std-sketch-loft-1",
"std-sketch-loft-2",
"std-sketch-patternLinear2d-0",
"std-sketch-patternLinear2d-1",
"std-sketch-patternCircular2d-0",
"std-sketch-circleThreePoint-0",
"std-sketch-segStart-0",
"std-sketch-segStartX-0",
"std-sketch-segStartY-0",
"std-sketch-segEnd-0",
"std-sketch-segEndX-0",
"std-sketch-segEndY-0",
"std-sketch-lastSegX-0",
"std-sketch-lastSegY-0",
"std-sketch-segAng-0",
"std-sketch-segLen-0",
"std-sketch-tangentToEnd-0",
"std-sketch-tangentToEnd-1",
"std-sketch-tangentToEnd-2",
"std-sketch-tangentToEnd-3",
"std-sketch-tangentToEnd-4",
"std-solid-appearance-0",
"std-solid-appearance-1",
"std-solid-appearance-2",

View File

@ -1,7 +1,7 @@
[package]
name = "kcl-directory-test-macro"
description = "A tool for generating tests from a directory of kcl files"
version = "0.1.77"
version = "0.1.78"
edition = "2021"
license = "MIT"
repository = "https://github.com/KittyCAD/modeling-app"

View File

@ -1,6 +1,6 @@
[package]
name = "kcl-language-server-release"
version = "0.1.77"
version = "0.1.78"
edition = "2021"
authors = ["KittyCAD Inc <kcl@kittycad.io>"]
publish = false

View File

@ -2,7 +2,7 @@
name = "kcl-language-server"
description = "A language server for KCL."
authors = ["KittyCAD Inc <kcl@kittycad.io>"]
version = "0.2.77"
version = "0.2.78"
edition = "2021"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,7 +1,7 @@
[package]
name = "kcl-lib"
description = "KittyCAD Language implementation and tools"
version = "0.2.77"
version = "0.2.78"
edition = "2021"
license = "MIT"
repository = "https://github.com/KittyCAD/modeling-app"

View File

@ -644,13 +644,13 @@ impl FnData {
format!("{}({})", self.preferred_name, args.join(", "))
}
fn to_signature_help(&self) -> SignatureHelp {
pub(crate) fn to_signature_help(&self) -> SignatureHelp {
// TODO Fill this in based on the current position of the cursor.
let active_parameter = None;
SignatureHelp {
signatures: vec![SignatureInformation {
label: self.preferred_name.clone(),
label: self.preferred_name.clone() + &self.fn_signature(),
documentation: self.short_docs().map(|s| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
@ -824,6 +824,7 @@ impl ArgData {
),
)),
Some("Axis2d | Edge") | Some("Axis3d | Edge") => Some((index, format!(r#"{label}${{{index}:X}}"#))),
Some("Sketch") | Some("Sketch | Helix") => Some((index, format!(r#"{label}${{{index}:sketch000}}"#))),
Some("Edge") => Some((index, format!(r#"{label}${{{index}:tag_or_edge_fn}}"#))),
Some("[Edge; 1+]") => Some((index, format!(r#"{label}[${{{index}:tag_or_edge_fn}}]"#))),
Some("Plane") => Some((index, format!(r#"{label}${{{}:XY}}"#, index))),
@ -1280,7 +1281,10 @@ mod test {
continue;
};
for i in 0..f.examples.len() {
for (i, (_, props)) in f.examples.iter().enumerate() {
if props.norun {
continue;
}
let name = format!("{}-{i}", f.qual_name.replace("::", "-"));
assert!(TEST_NAMES.contains(&&*name), "Missing test for example \"{name}\", maybe need to update kcl-derive-docs/src/example_tests.rs?")
}

View File

@ -976,9 +976,12 @@ mod tests {
#[test]
fn get_autocomplete_snippet_extrude() {
let extrude_fn: Box<dyn StdLibFn> = Box::new(crate::std::extrude::Extrude);
let snippet = extrude_fn.to_autocomplete_snippet().unwrap();
assert_eq!(snippet, r#"extrude(${0:%}, length = ${1:3.14})"#);
let data = kcl_doc::walk_prelude();
let DocData::Fn(data) = data.find_by_name("extrude").unwrap() else {
panic!();
};
let snippet = data.to_autocomplete_snippet();
assert_eq!(snippet, r#"extrude(length = ${0:10})"#);
}
#[test]
@ -1064,11 +1067,14 @@ mod tests {
#[test]
fn get_autocomplete_snippet_pattern_linear_2d() {
let pattern_fn: Box<dyn StdLibFn> = Box::new(crate::std::patterns::PatternLinear2D);
let snippet = pattern_fn.to_autocomplete_snippet().unwrap();
let data = kcl_doc::walk_prelude();
let DocData::Fn(data) = data.find_by_name("patternLinear2d").unwrap() else {
panic!();
};
let snippet = data.to_autocomplete_snippet();
assert_eq!(
snippet,
r#"patternLinear2d(${0:%}, instances = ${1:10}, distance = ${2:3.14}, axis = [${3:1}, ${4:0}])"#
r#"patternLinear2d(instances = ${0:10}, distance = ${1:10}, axis = [${2:1}, ${3:0}])"#
);
}
@ -1084,16 +1090,22 @@ mod tests {
#[test]
fn get_autocomplete_snippet_loft() {
let loft_fn: Box<dyn StdLibFn> = Box::new(crate::std::loft::Loft);
let snippet = loft_fn.to_autocomplete_snippet().unwrap();
let data = kcl_doc::walk_prelude();
let DocData::Fn(data) = data.find_by_name("loft").unwrap() else {
panic!();
};
let snippet = data.to_autocomplete_snippet();
assert_eq!(snippet, r#"loft([${0:sketch000}, ${1:sketch001}])"#);
}
#[test]
fn get_autocomplete_snippet_sweep() {
let sweep_fn: Box<dyn StdLibFn> = Box::new(crate::std::sweep::Sweep);
let snippet = sweep_fn.to_autocomplete_snippet().unwrap();
assert_eq!(snippet, r#"sweep(${0:%}, path = ${1:sketch000})"#);
let data = kcl_doc::walk_prelude();
let DocData::Fn(data) = data.find_by_name("sweep").unwrap() else {
panic!();
};
let snippet = data.to_autocomplete_snippet();
assert_eq!(snippet, r#"sweep(path = ${0:sketch000})"#);
}
#[test]
@ -1225,18 +1237,21 @@ mod tests {
#[test]
fn get_extrude_signature_help() {
let extrude_fn: Box<dyn StdLibFn> = Box::new(crate::std::extrude::Extrude);
let sh = extrude_fn.to_signature_help();
let data = kcl_doc::walk_prelude();
let DocData::Fn(data) = data.find_by_name("extrude").unwrap() else {
panic!();
};
let sh = data.to_signature_help();
assert_eq!(
sh.signatures[0].label,
r#"extrude(
@sketches: [Sketch],
length: number,
@sketches: [Sketch; 1+],
length: number(Length),
symmetric?: bool,
bidirectionalLength?: number,
tagStart?: TagNode,
tagEnd?: TagNode,
): [Solid]"#
bidirectionalLength?: number(Length),
tagStart?: tag,
tagEnd?: tag,
): [Solid; 1+]"#
);
}
}

View File

@ -439,7 +439,7 @@ impl EngineManager for EngineConnection {
request_sent: tx,
})
.await
.map_err(|e| KclError::Engine(KclErrorDetails::new(format!("Failed to send debug: {}", e), vec![])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(format!("Failed to send debug: {}", e), vec![])))?;
let _ = rx.await;
Ok(())
@ -474,7 +474,7 @@ impl EngineManager for EngineConnection {
})
.await
.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to send modeling command: {}", e),
vec![source_range],
))
@ -483,13 +483,13 @@ impl EngineManager for EngineConnection {
// Wait for the request to be sent.
rx.await
.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("could not send request to the engine actor: {e}"),
vec![source_range],
))
})?
.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("could not send request to the engine: {e}"),
vec![source_range],
))
@ -516,12 +516,12 @@ impl EngineManager for EngineConnection {
// Check if we have any pending errors.
let pe = self.pending_errors.read().await;
if !pe.is_empty() {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
pe.join(", ").to_string(),
vec![source_range],
)));
} else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
"Modeling command failed: websocket closed early".to_string(),
vec![source_range],
)));
@ -543,7 +543,7 @@ impl EngineManager for EngineConnection {
}
}
Err(KclError::Engine(KclErrorDetails::new(
Err(KclError::new_engine(KclErrorDetails::new(
format!("Modeling command timed out `{}`", id),
vec![source_range],
)))

View File

@ -147,19 +147,19 @@ impl EngineConnection {
id_to_source_range: HashMap<uuid::Uuid, SourceRange>,
) -> Result<(), KclError> {
let source_range_str = serde_json::to_string(&source_range).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to serialize source range: {:?}", e),
vec![source_range],
))
})?;
let cmd_str = serde_json::to_string(&cmd).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to serialize modeling command: {:?}", e),
vec![source_range],
))
})?;
let id_to_source_range_str = serde_json::to_string(&id_to_source_range).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to serialize id to source range: {:?}", e),
vec![source_range],
))
@ -167,7 +167,7 @@ impl EngineConnection {
self.manager
.fire_modeling_cmd_from_wasm(id.to_string(), source_range_str, cmd_str, id_to_source_range_str)
.map_err(|e| KclError::Engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
Ok(())
}
@ -180,19 +180,19 @@ impl EngineConnection {
id_to_source_range: HashMap<uuid::Uuid, SourceRange>,
) -> Result<WebSocketResponse, KclError> {
let source_range_str = serde_json::to_string(&source_range).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to serialize source range: {:?}", e),
vec![source_range],
))
})?;
let cmd_str = serde_json::to_string(&cmd).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to serialize modeling command: {:?}", e),
vec![source_range],
))
})?;
let id_to_source_range_str = serde_json::to_string(&id_to_source_range).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to serialize id to source range: {:?}", e),
vec![source_range],
))
@ -201,7 +201,7 @@ impl EngineConnection {
let promise = self
.manager
.send_modeling_cmd_from_wasm(id.to_string(), source_range_str, cmd_str, id_to_source_range_str)
.map_err(|e| KclError::Engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
let value = crate::wasm::JsFuture::from(promise).await.map_err(|e| {
// Try to parse the error as an engine error.
@ -209,7 +209,7 @@ impl EngineConnection {
if let Ok(kittycad_modeling_cmds::websocket::FailureWebSocketResponse { errors, .. }) =
serde_json::from_str(&err_str)
{
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
errors.iter().map(|e| e.message.clone()).collect::<Vec<_>>().join("\n"),
vec![source_range],
))
@ -218,7 +218,7 @@ impl EngineConnection {
{
if let Some(data) = data.first() {
// It could also be an array of responses.
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
data.errors
.iter()
.map(|e| e.message.clone())
@ -227,13 +227,13 @@ impl EngineConnection {
vec![source_range],
))
} else {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
"Received empty response from engine".into(),
vec![source_range],
))
}
} else {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to wait for promise from send modeling command: {:?}", e),
vec![source_range],
))
@ -241,7 +241,7 @@ impl EngineConnection {
})?;
if value.is_null() || value.is_undefined() {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
"Received null or undefined response from engine".into(),
vec![source_range],
)));
@ -251,7 +251,7 @@ impl EngineConnection {
let data = js_sys::Uint8Array::from(value);
let ws_result: WebSocketResponse = bson::from_slice(&data.to_vec()).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to deserialize bson response from engine: {:?}", e),
vec![source_range],
))
@ -308,10 +308,10 @@ impl crate::engine::EngineManager for EngineConnection {
let promise = self
.manager
.start_new_session()
.map_err(|e| KclError::Engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
crate::wasm::JsFuture::from(promise).await.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to wait for promise from start new session: {:?}", e),
vec![source_range],
))

View File

@ -276,7 +276,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
{
let duration = instant::Duration::from_millis(1);
wasm_timer::Delay::new(duration).await.map_err(|err| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("Failed to sleep: {:?}", err),
vec![source_range],
))
@ -293,7 +293,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
return Ok(response);
}
Err(KclError::Engine(KclErrorDetails::new(
Err(KclError::new_engine(KclErrorDetails::new(
"async command timed out".to_string(),
vec![source_range],
)))
@ -547,7 +547,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
id_to_source_range.insert(Uuid::from(*cmd_id), *range);
}
_ => {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!("The request is not a modeling command: {:?}", req),
vec![*range],
)));
@ -595,7 +595,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
self.parse_batch_responses(last_id.into(), id_to_source_range, responses)
} else {
// We should never get here.
Err(KclError::Engine(KclErrorDetails::new(
Err(KclError::new_engine(KclErrorDetails::new(
format!("Failed to get batch response: {:?}", response),
vec![source_range],
)))
@ -610,7 +610,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
// request so we need the original request source range in case the engine returns
// an error.
let source_range = id_to_source_range.get(cmd_id.as_ref()).cloned().ok_or_else(|| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to get source range for command ID: {:?}", cmd_id),
vec![],
))
@ -620,7 +620,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
.await?;
self.parse_websocket_response(ws_resp, source_range)
}
_ => Err(KclError::Engine(KclErrorDetails::new(
_ => Err(KclError::new_engine(KclErrorDetails::new(
format!("The final request is not a modeling command: {:?}", final_req),
vec![source_range],
))),
@ -729,7 +729,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
for (name, plane_id, color) in plane_settings {
let info = DEFAULT_PLANE_INFO.get(&name).ok_or_else(|| {
// We should never get here.
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to get default plane info for: {:?}", name),
vec![source_range],
))
@ -763,7 +763,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
WebSocketResponse::Success(success) => Ok(success.resp),
WebSocketResponse::Failure(fail) => {
let _request_id = fail.request_id;
Err(KclError::Engine(KclErrorDetails::new(
Err(KclError::new_engine(KclErrorDetails::new(
fail.errors
.iter()
.map(|e| e.message.clone())
@ -805,12 +805,12 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
BatchResponse::Failure { errors } => {
// Get the source range for the command.
let source_range = id_to_source_range.get(cmd_id).cloned().ok_or_else(|| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to get source range for command ID: {:?}", cmd_id),
vec![],
))
})?;
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
errors.iter().map(|e| e.message.clone()).collect::<Vec<_>>().join("\n"),
vec![source_range],
)));
@ -820,7 +820,7 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
// Return an error that we did not get an error or the response we wanted.
// This should never happen but who knows.
Err(KclError::Engine(KclErrorDetails::new(
Err(KclError::new_engine(KclErrorDetails::new(
format!("Failed to find response for command ID: {:?}", id),
vec![],
)))

View File

@ -91,30 +91,33 @@ pub enum ConnectionError {
#[ts(export)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum KclError {
#[error("lexical: {0:?}")]
Lexical(KclErrorDetails),
#[error("syntax: {0:?}")]
Syntax(KclErrorDetails),
#[error("semantic: {0:?}")]
Semantic(KclErrorDetails),
#[error("import cycle: {0:?}")]
ImportCycle(KclErrorDetails),
#[error("type: {0:?}")]
Type(KclErrorDetails),
#[error("i/o: {0:?}")]
Io(KclErrorDetails),
#[error("unexpected: {0:?}")]
Unexpected(KclErrorDetails),
#[error("value already defined: {0:?}")]
ValueAlreadyDefined(KclErrorDetails),
#[error("undefined value: {0:?}")]
UndefinedValue(KclErrorDetails),
#[error("invalid expression: {0:?}")]
InvalidExpression(KclErrorDetails),
#[error("engine: {0:?}")]
Engine(KclErrorDetails),
#[error("internal error, please report to KittyCAD team: {0:?}")]
Internal(KclErrorDetails),
#[error("lexical: {details:?}")]
Lexical { details: KclErrorDetails },
#[error("syntax: {details:?}")]
Syntax { details: KclErrorDetails },
#[error("semantic: {details:?}")]
Semantic { details: KclErrorDetails },
#[error("import cycle: {details:?}")]
ImportCycle { details: KclErrorDetails },
#[error("type: {details:?}")]
Type { details: KclErrorDetails },
#[error("i/o: {details:?}")]
Io { details: KclErrorDetails },
#[error("unexpected: {details:?}")]
Unexpected { details: KclErrorDetails },
#[error("value already defined: {details:?}")]
ValueAlreadyDefined { details: KclErrorDetails },
#[error("undefined value: {details:?}")]
UndefinedValue {
details: KclErrorDetails,
name: Option<String>,
},
#[error("invalid expression: {details:?}")]
InvalidExpression { details: KclErrorDetails },
#[error("engine: {details:?}")]
Engine { details: KclErrorDetails },
#[error("internal error, please report to KittyCAD team: {details:?}")]
Internal { details: KclErrorDetails },
}
impl From<KclErrorWithOutputs> for KclError {
@ -296,18 +299,18 @@ pub struct ReportWithOutputs {
impl miette::Diagnostic for ReportWithOutputs {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
let family = match self.error.error {
KclError::Lexical(_) => "Lexical",
KclError::Syntax(_) => "Syntax",
KclError::Semantic(_) => "Semantic",
KclError::ImportCycle(_) => "ImportCycle",
KclError::Type(_) => "Type",
KclError::Io(_) => "I/O",
KclError::Unexpected(_) => "Unexpected",
KclError::ValueAlreadyDefined(_) => "ValueAlreadyDefined",
KclError::UndefinedValue(_) => "UndefinedValue",
KclError::InvalidExpression(_) => "InvalidExpression",
KclError::Engine(_) => "Engine",
KclError::Internal(_) => "Internal",
KclError::Lexical { .. } => "Lexical",
KclError::Syntax { .. } => "Syntax",
KclError::Semantic { .. } => "Semantic",
KclError::ImportCycle { .. } => "ImportCycle",
KclError::Type { .. } => "Type",
KclError::Io { .. } => "I/O",
KclError::Unexpected { .. } => "Unexpected",
KclError::ValueAlreadyDefined { .. } => "ValueAlreadyDefined",
KclError::UndefinedValue { .. } => "UndefinedValue",
KclError::InvalidExpression { .. } => "InvalidExpression",
KclError::Engine { .. } => "Engine",
KclError::Internal { .. } => "Internal",
};
let error_string = format!("KCL {family} error");
Some(Box::new(error_string))
@ -346,18 +349,18 @@ pub struct Report {
impl miette::Diagnostic for Report {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
let family = match self.error {
KclError::Lexical(_) => "Lexical",
KclError::Syntax(_) => "Syntax",
KclError::Semantic(_) => "Semantic",
KclError::ImportCycle(_) => "ImportCycle",
KclError::Type(_) => "Type",
KclError::Io(_) => "I/O",
KclError::Unexpected(_) => "Unexpected",
KclError::ValueAlreadyDefined(_) => "ValueAlreadyDefined",
KclError::UndefinedValue(_) => "UndefinedValue",
KclError::InvalidExpression(_) => "InvalidExpression",
KclError::Engine(_) => "Engine",
KclError::Internal(_) => "Internal",
KclError::Lexical { .. } => "Lexical",
KclError::Syntax { .. } => "Syntax",
KclError::Semantic { .. } => "Semantic",
KclError::ImportCycle { .. } => "ImportCycle",
KclError::Type { .. } => "Type",
KclError::Io { .. } => "I/O",
KclError::Unexpected { .. } => "Unexpected",
KclError::ValueAlreadyDefined { .. } => "ValueAlreadyDefined",
KclError::UndefinedValue { .. } => "UndefinedValue",
KclError::InvalidExpression { .. } => "InvalidExpression",
KclError::Engine { .. } => "Engine",
KclError::Internal { .. } => "Internal",
};
let error_string = format!("KCL {family} error");
Some(Box::new(error_string))
@ -410,11 +413,53 @@ impl KclErrorDetails {
impl KclError {
pub fn internal(message: String) -> KclError {
KclError::Internal(KclErrorDetails {
source_ranges: Default::default(),
backtrace: Default::default(),
message,
})
KclError::Internal {
details: KclErrorDetails {
source_ranges: Default::default(),
backtrace: Default::default(),
message,
},
}
}
pub fn new_internal(details: KclErrorDetails) -> KclError {
KclError::Internal { details }
}
pub fn new_import_cycle(details: KclErrorDetails) -> KclError {
KclError::ImportCycle { details }
}
pub fn new_semantic(details: KclErrorDetails) -> KclError {
KclError::Semantic { details }
}
pub fn new_value_already_defined(details: KclErrorDetails) -> KclError {
KclError::ValueAlreadyDefined { details }
}
pub fn new_syntax(details: KclErrorDetails) -> KclError {
KclError::Syntax { details }
}
pub fn new_io(details: KclErrorDetails) -> KclError {
KclError::Io { details }
}
pub fn new_engine(details: KclErrorDetails) -> KclError {
KclError::Engine { details }
}
pub fn new_lexical(details: KclErrorDetails) -> KclError {
KclError::Lexical { details }
}
pub fn new_undefined_value(details: KclErrorDetails, name: Option<String>) -> KclError {
KclError::UndefinedValue { details, name }
}
pub fn new_type(details: KclErrorDetails) -> KclError {
KclError::Type { details }
}
/// Get the error message.
@ -424,88 +469,88 @@ impl KclError {
pub fn error_type(&self) -> &'static str {
match self {
KclError::Lexical(_) => "lexical",
KclError::Syntax(_) => "syntax",
KclError::Semantic(_) => "semantic",
KclError::ImportCycle(_) => "import cycle",
KclError::Type(_) => "type",
KclError::Io(_) => "i/o",
KclError::Unexpected(_) => "unexpected",
KclError::ValueAlreadyDefined(_) => "value already defined",
KclError::UndefinedValue(_) => "undefined value",
KclError::InvalidExpression(_) => "invalid expression",
KclError::Engine(_) => "engine",
KclError::Internal(_) => "internal",
KclError::Lexical { .. } => "lexical",
KclError::Syntax { .. } => "syntax",
KclError::Semantic { .. } => "semantic",
KclError::ImportCycle { .. } => "import cycle",
KclError::Type { .. } => "type",
KclError::Io { .. } => "i/o",
KclError::Unexpected { .. } => "unexpected",
KclError::ValueAlreadyDefined { .. } => "value already defined",
KclError::UndefinedValue { .. } => "undefined value",
KclError::InvalidExpression { .. } => "invalid expression",
KclError::Engine { .. } => "engine",
KclError::Internal { .. } => "internal",
}
}
pub fn source_ranges(&self) -> Vec<SourceRange> {
match &self {
KclError::Lexical(e) => e.source_ranges.clone(),
KclError::Syntax(e) => e.source_ranges.clone(),
KclError::Semantic(e) => e.source_ranges.clone(),
KclError::ImportCycle(e) => e.source_ranges.clone(),
KclError::Type(e) => e.source_ranges.clone(),
KclError::Io(e) => e.source_ranges.clone(),
KclError::Unexpected(e) => e.source_ranges.clone(),
KclError::ValueAlreadyDefined(e) => e.source_ranges.clone(),
KclError::UndefinedValue(e) => e.source_ranges.clone(),
KclError::InvalidExpression(e) => e.source_ranges.clone(),
KclError::Engine(e) => e.source_ranges.clone(),
KclError::Internal(e) => e.source_ranges.clone(),
KclError::Lexical { details: e } => e.source_ranges.clone(),
KclError::Syntax { details: e } => e.source_ranges.clone(),
KclError::Semantic { details: e } => e.source_ranges.clone(),
KclError::ImportCycle { details: e } => e.source_ranges.clone(),
KclError::Type { details: e } => e.source_ranges.clone(),
KclError::Io { details: e } => e.source_ranges.clone(),
KclError::Unexpected { details: e } => e.source_ranges.clone(),
KclError::ValueAlreadyDefined { details: e } => e.source_ranges.clone(),
KclError::UndefinedValue { details: e, .. } => e.source_ranges.clone(),
KclError::InvalidExpression { details: e } => e.source_ranges.clone(),
KclError::Engine { details: e } => e.source_ranges.clone(),
KclError::Internal { details: e } => e.source_ranges.clone(),
}
}
/// Get the inner error message.
pub fn message(&self) -> &str {
match &self {
KclError::Lexical(e) => &e.message,
KclError::Syntax(e) => &e.message,
KclError::Semantic(e) => &e.message,
KclError::ImportCycle(e) => &e.message,
KclError::Type(e) => &e.message,
KclError::Io(e) => &e.message,
KclError::Unexpected(e) => &e.message,
KclError::ValueAlreadyDefined(e) => &e.message,
KclError::UndefinedValue(e) => &e.message,
KclError::InvalidExpression(e) => &e.message,
KclError::Engine(e) => &e.message,
KclError::Internal(e) => &e.message,
KclError::Lexical { details: e } => &e.message,
KclError::Syntax { details: e } => &e.message,
KclError::Semantic { details: e } => &e.message,
KclError::ImportCycle { details: e } => &e.message,
KclError::Type { details: e } => &e.message,
KclError::Io { details: e } => &e.message,
KclError::Unexpected { details: e } => &e.message,
KclError::ValueAlreadyDefined { details: e } => &e.message,
KclError::UndefinedValue { details: e, .. } => &e.message,
KclError::InvalidExpression { details: e } => &e.message,
KclError::Engine { details: e } => &e.message,
KclError::Internal { details: e } => &e.message,
}
}
pub fn backtrace(&self) -> Vec<BacktraceItem> {
match self {
KclError::Lexical(e)
| KclError::Syntax(e)
| KclError::Semantic(e)
| KclError::ImportCycle(e)
| KclError::Type(e)
| KclError::Io(e)
| KclError::Unexpected(e)
| KclError::ValueAlreadyDefined(e)
| KclError::UndefinedValue(e)
| KclError::InvalidExpression(e)
| KclError::Engine(e)
| KclError::Internal(e) => e.backtrace.clone(),
KclError::Lexical { details: e }
| KclError::Syntax { details: e }
| KclError::Semantic { details: e }
| KclError::ImportCycle { details: e }
| KclError::Type { details: e }
| KclError::Io { details: e }
| KclError::Unexpected { details: e }
| KclError::ValueAlreadyDefined { details: e }
| KclError::UndefinedValue { details: e, .. }
| KclError::InvalidExpression { details: e }
| KclError::Engine { details: e }
| KclError::Internal { details: e } => e.backtrace.clone(),
}
}
pub(crate) fn override_source_ranges(&self, source_ranges: Vec<SourceRange>) -> Self {
let mut new = self.clone();
match &mut new {
KclError::Lexical(e)
| KclError::Syntax(e)
| KclError::Semantic(e)
| KclError::ImportCycle(e)
| KclError::Type(e)
| KclError::Io(e)
| KclError::Unexpected(e)
| KclError::ValueAlreadyDefined(e)
| KclError::UndefinedValue(e)
| KclError::InvalidExpression(e)
| KclError::Engine(e)
| KclError::Internal(e) => {
KclError::Lexical { details: e }
| KclError::Syntax { details: e }
| KclError::Semantic { details: e }
| KclError::ImportCycle { details: e }
| KclError::Type { details: e }
| KclError::Io { details: e }
| KclError::Unexpected { details: e }
| KclError::ValueAlreadyDefined { details: e }
| KclError::UndefinedValue { details: e, .. }
| KclError::InvalidExpression { details: e }
| KclError::Engine { details: e }
| KclError::Internal { details: e } => {
e.backtrace = source_ranges
.iter()
.map(|s| BacktraceItem {
@ -523,18 +568,18 @@ impl KclError {
pub(crate) fn set_last_backtrace_fn_name(&self, last_fn_name: Option<String>) -> Self {
let mut new = self.clone();
match &mut new {
KclError::Lexical(e)
| KclError::Syntax(e)
| KclError::Semantic(e)
| KclError::ImportCycle(e)
| KclError::Type(e)
| KclError::Io(e)
| KclError::Unexpected(e)
| KclError::ValueAlreadyDefined(e)
| KclError::UndefinedValue(e)
| KclError::InvalidExpression(e)
| KclError::Engine(e)
| KclError::Internal(e) => {
KclError::Lexical { details: e }
| KclError::Syntax { details: e }
| KclError::Semantic { details: e }
| KclError::ImportCycle { details: e }
| KclError::Type { details: e }
| KclError::Io { details: e }
| KclError::Unexpected { details: e }
| KclError::ValueAlreadyDefined { details: e }
| KclError::UndefinedValue { details: e, .. }
| KclError::InvalidExpression { details: e }
| KclError::Engine { details: e }
| KclError::Internal { details: e } => {
if let Some(item) = e.backtrace.last_mut() {
item.fn_name = last_fn_name;
}
@ -547,18 +592,18 @@ impl KclError {
pub(crate) fn add_unwind_location(&self, last_fn_name: Option<String>, source_range: SourceRange) -> Self {
let mut new = self.clone();
match &mut new {
KclError::Lexical(e)
| KclError::Syntax(e)
| KclError::Semantic(e)
| KclError::ImportCycle(e)
| KclError::Type(e)
| KclError::Io(e)
| KclError::Unexpected(e)
| KclError::ValueAlreadyDefined(e)
| KclError::UndefinedValue(e)
| KclError::InvalidExpression(e)
| KclError::Engine(e)
| KclError::Internal(e) => {
KclError::Lexical { details: e }
| KclError::Syntax { details: e }
| KclError::Semantic { details: e }
| KclError::ImportCycle { details: e }
| KclError::Type { details: e }
| KclError::Io { details: e }
| KclError::Unexpected { details: e }
| KclError::ValueAlreadyDefined { details: e }
| KclError::UndefinedValue { details: e, .. }
| KclError::InvalidExpression { details: e }
| KclError::Engine { details: e }
| KclError::Internal { details: e } => {
if let Some(item) = e.backtrace.last_mut() {
item.fn_name = last_fn_name;
}
@ -645,7 +690,7 @@ impl From<String> for KclError {
#[cfg(feature = "pyo3")]
impl From<pyo3::PyErr> for KclError {
fn from(error: pyo3::PyErr) -> Self {
KclError::Internal(KclErrorDetails {
KclError::new_internal(KclErrorDetails {
source_ranges: vec![],
backtrace: Default::default(),
message: error.to_string(),

View File

@ -70,7 +70,7 @@ pub(super) fn expect_properties<'a>(
) -> Result<&'a [Node<ObjectProperty>], KclError> {
assert_eq!(annotation.name().unwrap(), for_key);
Ok(&**annotation.properties.as_ref().ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Empty `{for_key}` annotation"),
vec![annotation.as_source_range()],
))
@ -84,7 +84,7 @@ pub(super) fn expect_ident(expr: &Expr) -> Result<&str, KclError> {
}
}
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
"Unexpected settings value, expected a simple name, e.g., `mm`".to_owned(),
vec![expr.into()],
)))
@ -98,7 +98,7 @@ pub(super) fn expect_number(expr: &Expr) -> Result<String, KclError> {
}
}
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
"Unexpected settings value, expected a number, e.g., `1.0`".to_owned(),
vec![expr.into()],
)))
@ -113,7 +113,7 @@ pub(super) fn get_impl(annotations: &[Node<Annotation>], source_range: SourceRan
if &*p.key.name == IMPL {
if let Some(s) = p.value.ident_name() {
return Impl::from_str(s).map(Some).map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"Invalid value for {} attribute, expected one of: {}",
IMPL,
@ -139,7 +139,7 @@ impl UnitLen {
"inch" | "in" => Ok(UnitLen::Inches),
"ft" => Ok(UnitLen::Feet),
"yd" => Ok(UnitLen::Yards),
value => Err(KclError::Semantic(KclErrorDetails::new(
value => Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Unexpected value for length units: `{value}`; expected one of `mm`, `cm`, `m`, `in`, `ft`, `yd`"
),
@ -154,7 +154,7 @@ impl UnitAngle {
match s {
"deg" => Ok(UnitAngle::Degrees),
"rad" => Ok(UnitAngle::Radians),
value => Err(KclError::Semantic(KclErrorDetails::new(
value => Err(KclError::new_semantic(KclErrorDetails::new(
format!("Unexpected value for angle units: `{value}`; expected one of `deg`, `rad`"),
vec![source_range],
))),

View File

@ -24,7 +24,7 @@ macro_rules! internal_error {
($range:expr, $($rest:tt)*) => {{
let message = format!($($rest)*);
debug_assert!(false, "{}", &message);
return Err(KclError::Internal(KclErrorDetails::new(message, vec![$range])));
return Err(KclError::new_internal(KclErrorDetails::new(message, vec![$range])));
}};
}
@ -949,7 +949,7 @@ fn artifacts_to_update(
ModelingCmd::StartPath(_) => {
let mut return_arr = Vec::new();
let current_plane_id = path_to_plane_id_map.get(&artifact_command.cmd_id).ok_or_else(|| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("Expected a current plane ID when processing StartPath command, but we have none: {id:?}"),
vec![range],
))
@ -1137,7 +1137,7 @@ fn artifacts_to_update(
// TODO: Using the first one. Make sure to revisit this
// choice, don't think it matters for now.
path_id: ArtifactId::new(*loft_cmd.section_ids.first().ok_or_else(|| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("Expected at least one section ID in Loft command: {id:?}; cmd={cmd:?}"),
vec![range],
))
@ -1180,7 +1180,7 @@ fn artifacts_to_update(
};
last_path = Some(path);
let path_sweep_id = path.sweep_id.ok_or_else(|| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!(
"Expected a sweep ID on the path when processing Solid3dGetExtrusionFaceInfo command, but we have none: {id:?}, {path:?}"
),
@ -1234,7 +1234,7 @@ fn artifacts_to_update(
continue;
};
let path_sweep_id = path.sweep_id.ok_or_else(|| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!(
"Expected a sweep ID on the path when processing last path's Solid3dGetExtrusionFaceInfo command, but we have none: {id:?}, {path:?}"
),

View File

@ -131,7 +131,7 @@ impl ExecutorContext {
match statement {
BodyItem::ImportStatement(import_stmt) => {
if !matches!(body_type, BodyType::Root) {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Imports are only supported at the top-level of a file.".to_owned(),
vec![import_stmt.into()],
)));
@ -164,15 +164,18 @@ impl ExecutorContext {
let mut mod_value = mem.get_from(&mod_name, env_ref, import_item.into(), 0).cloned();
if value.is_err() && ty.is_err() && mod_value.is_err() {
return Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("{} is not defined in module", import_item.name.name),
vec![SourceRange::from(&import_item.name)],
)));
return Err(KclError::new_undefined_value(
KclErrorDetails::new(
format!("{} is not defined in module", import_item.name.name),
vec![SourceRange::from(&import_item.name)],
),
None,
));
}
// Check that the item is allowed to be imported (in at least one namespace).
if value.is_ok() && !module_exports.contains(&import_item.name.name) {
value = Err(KclError::Semantic(KclErrorDetails::new(
value = Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
@ -182,7 +185,7 @@ impl ExecutorContext {
}
if ty.is_ok() && !module_exports.contains(&ty_name) {
ty = Err(KclError::Semantic(KclErrorDetails::new(format!(
ty = Err(KclError::new_semantic(KclErrorDetails::new(format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
),
@ -190,7 +193,7 @@ impl ExecutorContext {
}
if mod_value.is_ok() && !module_exports.contains(&mod_name) {
mod_value = Err(KclError::Semantic(KclErrorDetails::new(format!(
mod_value = Err(KclError::new_semantic(KclErrorDetails::new(format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
),
@ -253,7 +256,7 @@ impl ExecutorContext {
.memory
.get_from(name, env_ref, source_range, 0)
.map_err(|_err| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("{} is not defined in module (but was exported?)", name),
vec![source_range],
))
@ -301,7 +304,10 @@ impl ExecutorContext {
let annotations = &variable_declaration.outer_attrs;
let value = self
// During the evaluation of the variable's LHS, set context that this is all happening inside a variable
// declaration, for the given name. This helps improve user-facing error messages.
exec_state.mod_local.being_declared = Some(variable_declaration.inner.name().to_owned());
let rhs_result = self
.execute_expr(
&variable_declaration.declaration.init,
exec_state,
@ -309,10 +315,14 @@ impl ExecutorContext {
annotations,
StatementKind::Declaration { name: &var_name },
)
.await?;
.await;
// Declaration over, so unset this context.
exec_state.mod_local.being_declared = None;
let rhs = rhs_result?;
exec_state
.mut_stack()
.add(var_name.clone(), value.clone(), source_range)?;
.add(var_name.clone(), rhs.clone(), source_range)?;
// Track exports.
if let ItemVisibility::Export = variable_declaration.visibility {
@ -326,7 +336,7 @@ impl ExecutorContext {
}
}
// Variable declaration can be the return value of a module.
last_expr = matches!(body_type, BodyType::Root).then_some(value);
last_expr = matches!(body_type, BodyType::Root).then_some(rhs);
}
BodyItem::TypeDeclaration(ty) => {
let metadata = Metadata::from(&**ty);
@ -336,7 +346,7 @@ impl ExecutorContext {
let std_path = match &exec_state.mod_local.path {
ModulePath::Std { value } => value,
ModulePath::Local { .. } | ModulePath::Main => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"User-defined types are not yet supported.".to_owned(),
vec![metadata.source_range],
)));
@ -352,7 +362,7 @@ impl ExecutorContext {
.mut_stack()
.add(name_in_mem.clone(), value, metadata.source_range)
.map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Redefinition of type {}.", ty.name.name),
vec![metadata.source_range],
))
@ -373,7 +383,7 @@ impl ExecutorContext {
exec_state,
metadata.source_range,
)
.map_err(|e| KclError::Semantic(e.into()))?,
.map_err(|e| KclError::new_semantic(e.into()))?,
),
meta: vec![metadata],
};
@ -382,7 +392,7 @@ impl ExecutorContext {
.mut_stack()
.add(name_in_mem.clone(), value, metadata.source_range)
.map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Redefinition of type {}.", ty.name.name),
vec![metadata.source_range],
))
@ -393,7 +403,7 @@ impl ExecutorContext {
}
}
None => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"User-defined types are not yet supported.".to_owned(),
vec![metadata.source_range],
)))
@ -407,7 +417,7 @@ impl ExecutorContext {
let metadata = Metadata::from(return_statement);
if matches!(body_type, BodyType::Root) {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Cannot return from outside a function.".to_owned(),
vec![metadata.source_range],
)));
@ -426,7 +436,7 @@ impl ExecutorContext {
.mut_stack()
.add(memory::RETURN_NAME.to_owned(), value, metadata.source_range)
.map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
"Multiple returns from a single function.".to_owned(),
vec![metadata.source_range],
))
@ -531,7 +541,7 @@ impl ExecutorContext {
*cache = Some((val, er, items.clone()));
(er, items)
}),
ModuleRepr::Foreign(geom, _) => Err(KclError::Semantic(KclErrorDetails::new(
ModuleRepr::Foreign(geom, _) => Err(KclError::new_semantic(KclErrorDetails::new(
"Cannot import items from foreign modules".to_owned(),
vec![geom.source_range],
))),
@ -605,12 +615,12 @@ impl ExecutorContext {
exec_state.global.mod_loader.leave_module(path);
result.map_err(|err| {
if let KclError::ImportCycle(_) = err {
if let KclError::ImportCycle { .. } = err {
// It was an import cycle. Keep the original message.
err.override_source_ranges(vec![source_range])
} else {
// TODO would be great to have line/column for the underlying error here
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"Error loading imported file ({path}). Open it to view more details.\n {}",
err.message()
@ -677,7 +687,7 @@ impl ExecutorContext {
meta: vec![metadata.to_owned()],
}
} else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Rust implementation of functions is restricted to the standard library".to_owned(),
vec![metadata.source_range],
)));
@ -704,7 +714,7 @@ impl ExecutorContext {
"you cannot declare variable {name} as %, because % can only be used in function calls"
);
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
message,
vec![pipe_substitution.into()],
)));
@ -712,7 +722,7 @@ impl ExecutorContext {
StatementKind::Expression => match exec_state.mod_local.pipe_value.clone() {
Some(x) => x,
None => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"cannot use % outside a pipe expression".to_owned(),
vec![pipe_substitution.into()],
)));
@ -761,7 +771,7 @@ fn apply_ascription(
source_range: SourceRange,
) -> Result<KclValue, KclError> {
let ty = RuntimeType::from_parsed(ty.inner.clone(), exec_state, value.into())
.map_err(|e| KclError::Semantic(e.into()))?;
.map_err(|e| KclError::new_semantic(e.into()))?;
value.coerce(&ty, false, exec_state).map_err(|_| {
let suggestion = if ty == RuntimeType::length() {
@ -771,7 +781,7 @@ fn apply_ascription(
} else {
""
};
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"could not coerce value of type {} to type {ty}{suggestion}",
value.human_friendly_type()
@ -804,7 +814,7 @@ impl Node<Name> {
ctx: &ExecutorContext,
) -> Result<&'a KclValue, KclError> {
if self.abs_path {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Absolute paths (names beginning with `::` are not yet supported)".to_owned(),
self.as_source_ranges(),
)));
@ -825,7 +835,7 @@ impl Node<Name> {
let value = match mem_spec {
Some((env, exports)) => {
if !exports.contains(&p.name) {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Item {} not found in module's exported items", p.name),
p.as_source_ranges(),
)));
@ -842,7 +852,7 @@ impl Node<Name> {
};
let KclValue::Module { value: module_id, .. } = value else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Identifier in path must refer to a module, found {}",
value.human_friendly_type()
@ -888,7 +898,7 @@ impl Node<Name> {
// Either item or module is defined, but not exported.
debug_assert!((item_value.is_ok() && !item_exported) || (mod_value.is_ok() && !mod_exported));
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
format!("Item {} not found in module's exported items", self.name.name),
self.name.as_source_ranges(),
)))
@ -913,14 +923,17 @@ impl Node<MemberExpression> {
if let Some(value) = map.get(&property) {
Ok(value.to_owned())
} else {
Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("Property '{property}' not found in object"),
vec![self.clone().into()],
)))
Err(KclError::new_undefined_value(
KclErrorDetails::new(
format!("Property '{property}' not found in object"),
vec![self.clone().into()],
),
None,
))
}
}
(KclValue::Object { .. }, Property::String(property), true) => {
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
format!("Cannot index object with string; use dot notation instead, e.g. `obj.{property}`"),
vec![self.clone().into()],
)))
@ -928,7 +941,7 @@ impl Node<MemberExpression> {
(KclValue::Object { .. }, p, _) => {
let t = p.type_name();
let article = article_for(t);
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
format!("Only strings can be used as the property of an object, but you're using {article} {t}",),
vec![self.clone().into()],
)))
@ -938,10 +951,13 @@ impl Node<MemberExpression> {
if let Some(value) = value_of_arr {
Ok(value.to_owned())
} else {
Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("The array doesn't have any item at index {index}"),
vec![self.clone().into()],
)))
Err(KclError::new_undefined_value(
KclErrorDetails::new(
format!("The array doesn't have any item at index {index}"),
vec![self.clone().into()],
),
None,
))
}
}
// Singletons and single-element arrays should be interchangeable, but only indexing by 0 should work.
@ -950,7 +966,7 @@ impl Node<MemberExpression> {
(KclValue::HomArray { .. }, p, _) => {
let t = p.type_name();
let article = article_for(t);
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
format!("Only integers >= 0 can be used as the index of an array, but you're using {article} {t}",),
vec![self.clone().into()],
)))
@ -971,7 +987,7 @@ impl Node<MemberExpression> {
(being_indexed, _, _) => {
let t = being_indexed.human_friendly_type();
let article = article_for(&t);
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
format!("Only arrays can be indexed, but you're trying to index {article} {t}"),
vec![self.clone().into()],
)))
@ -1049,7 +1065,7 @@ impl Node<BinaryExpression> {
meta: _,
} = left_value
else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Cannot apply logical operator to non-boolean value: {}",
left_value.human_friendly_type()
@ -1062,7 +1078,7 @@ impl Node<BinaryExpression> {
meta: _,
} = right_value
else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Cannot apply logical operator to non-boolean value: {}",
right_value.human_friendly_type()
@ -1168,7 +1184,7 @@ impl Node<UnaryExpression> {
meta: _,
} = value
else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Cannot apply unary operator ! to non-boolean value: {}",
value.human_friendly_type()
@ -1189,7 +1205,7 @@ impl Node<UnaryExpression> {
let value = &self.argument.get_result(exec_state, ctx).await?;
let err = || {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"You can only negate numbers, planes, or lines, but this is a {}",
value.human_friendly_type()
@ -1292,7 +1308,7 @@ pub(crate) async fn execute_pipe_body(
ctx: &ExecutorContext,
) -> Result<KclValue, KclError> {
let Some((first, body)) = body.split_first() else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Pipe expressions cannot be empty".to_owned(),
vec![source_range],
)));
@ -1330,7 +1346,7 @@ async fn inner_execute_pipe_body(
) -> Result<KclValue, KclError> {
for expression in body {
if let Expr::TagDeclarator(_) = expression {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("This cannot be in a PipeExpression: {:?}", expression),
vec![expression.into()],
)));
@ -1404,7 +1420,7 @@ impl Node<ArrayRangeExpression> {
.await?;
let (start, start_ty) = start_val
.as_int_with_ty()
.ok_or(KclError::Semantic(KclErrorDetails::new(
.ok_or(KclError::new_semantic(KclErrorDetails::new(
format!("Expected int but found {}", start_val.human_friendly_type()),
vec![self.into()],
)))?;
@ -1412,24 +1428,26 @@ impl Node<ArrayRangeExpression> {
let end_val = ctx
.execute_expr(&self.end_element, exec_state, &metadata, &[], StatementKind::Expression)
.await?;
let (end, end_ty) = end_val.as_int_with_ty().ok_or(KclError::Semantic(KclErrorDetails::new(
format!("Expected int but found {}", end_val.human_friendly_type()),
vec![self.into()],
)))?;
let (end, end_ty) = end_val
.as_int_with_ty()
.ok_or(KclError::new_semantic(KclErrorDetails::new(
format!("Expected int but found {}", end_val.human_friendly_type()),
vec![self.into()],
)))?;
if start_ty != end_ty {
let start = start_val.as_ty_f64().unwrap_or(TyF64 { n: 0.0, ty: start_ty });
let start = fmt::human_display_number(start.n, start.ty);
let end = end_val.as_ty_f64().unwrap_or(TyF64 { n: 0.0, ty: end_ty });
let end = fmt::human_display_number(end.n, end.ty);
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Range start and end must be of the same type, but found {start} and {end}"),
vec![self.into()],
)));
}
if end < start {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Range start is greater than range end: {start} .. {end}"),
vec![self.into()],
)));
@ -1493,7 +1511,7 @@ fn article_for<S: AsRef<str>>(s: S) -> &'static str {
fn number_as_f64(v: &KclValue, source_range: SourceRange) -> Result<TyF64, KclError> {
v.as_ty_f64().ok_or_else(|| {
let actual_type = v.human_friendly_type();
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Expected a number, but found {actual_type}",),
vec![source_range],
))
@ -1585,13 +1603,13 @@ impl Property {
if let Some(x) = crate::try_f64_to_usize(value) {
Ok(Property::UInt(x))
} else {
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
format!("{value} is not a valid index, indices must be whole numbers >= 0"),
property_sr,
)))
}
}
_ => Err(KclError::Semantic(KclErrorDetails::new(
_ => Err(KclError::new_semantic(KclErrorDetails::new(
"Only numbers (>= 0) can be indexes".to_owned(),
vec![sr],
))),
@ -1602,7 +1620,8 @@ impl Property {
}
fn jvalue_to_prop(value: &KclValue, property_sr: Vec<SourceRange>, name: &str) -> Result<Property, KclError> {
let make_err = |message: String| Err::<Property, _>(KclError::Semantic(KclErrorDetails::new(message, property_sr)));
let make_err =
|message: String| Err::<Property, _>(KclError::new_semantic(KclErrorDetails::new(message, property_sr)));
match value {
KclValue::Number{value: num, .. } => {
let num = *num;
@ -1846,7 +1865,7 @@ d = b + c
crate::engine::conn_mock::EngineConnection::new()
.await
.map_err(|err| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("Failed to create mock engine connection: {}", err),
vec![SourceRange::default()],
))

View File

@ -295,7 +295,7 @@ impl Node<CallExpressionKw> {
let func = fn_name.get_result(exec_state, ctx).await?.clone();
let Some(fn_src) = func.as_function() else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"cannot call this because it isn't a function".to_string(),
vec![callsite],
)));
@ -318,10 +318,13 @@ impl Node<CallExpressionKw> {
if let KclValue::Function { meta, .. } = func {
source_ranges = meta.iter().map(|m| m.source_range).collect();
};
KclError::UndefinedValue(KclErrorDetails::new(
format!("Result of user-defined function {} is undefined", fn_name),
source_ranges,
))
KclError::new_undefined_value(
KclErrorDetails::new(
format!("Result of user-defined function {} is undefined", fn_name),
source_ranges,
),
None,
)
})?;
Ok(result)
@ -500,7 +503,7 @@ fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut Ex
let tag_id = if let Some(t) = value.sketch.tags.get(&tag.name) {
let mut t = t.clone();
let Some(info) = t.get_cur_info() else {
return Err(KclError::Internal(KclErrorDetails::new(
return Err(KclError::new_internal(KclErrorDetails::new(
format!("Tag {} does not have path info", tag.name),
vec![tag.into()],
)));
@ -605,7 +608,7 @@ fn type_check_params_kw(
arg.value = arg
.value
.coerce(
&RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range).map_err(|e| KclError::Semantic(e.into()))?,
&RuntimeType::from_parsed(ty.clone(), exec_state, arg.source_range).map_err(|e| KclError::new_semantic(e.into()))?,
true,
exec_state,
)
@ -619,7 +622,7 @@ fn type_check_params_kw(
// TODO if we have access to the AST for the argument we could choose which example to suggest.
message = format!("{message}\n\nYou may need to add information about the type of the argument, for example:\n using a numeric suffix: `42{ty}`\n or using type ascription: `foo(): number({ty})`");
}
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
message,
vec![arg.source_range],
))
@ -670,7 +673,7 @@ fn type_check_params_kw(
let first = errors.next().unwrap();
errors.for_each(|e| exec_state.err(e));
return Err(KclError::Semantic(first.into()));
return Err(KclError::new_semantic(first.into()));
}
if let Some(arg) = &mut args.unlabeled {
@ -680,12 +683,12 @@ fn type_check_params_kw(
.value
.coerce(
&RuntimeType::from_parsed(ty.clone(), exec_state, arg.1.source_range)
.map_err(|e| KclError::Semantic(e.into()))?,
.map_err(|e| KclError::new_semantic(e.into()))?,
true,
exec_state,
)
.map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"The input argument of {} requires a value with type `{}`, but found {}",
fn_name
@ -742,7 +745,7 @@ fn assign_args_to_params_kw(
.add(name.clone(), value, default_val.source_range())?;
}
None => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"This function requires a parameter {}, but you haven't passed it one.",
name
@ -759,12 +762,12 @@ fn assign_args_to_params_kw(
let Some(unlabeled) = unlabelled else {
return Err(if args.kw_args.labeled.contains_key(param_name) {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("The function does declare a parameter named '{param_name}', but this parameter doesn't use a label. Try removing the `{param_name}:`"),
source_ranges,
))
} else {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
"This function expects an unlabeled first parameter, but you haven't passed it one.".to_owned(),
source_ranges,
))
@ -788,9 +791,9 @@ fn coerce_result_type(
if let Ok(Some(val)) = result {
if let Some(ret_ty) = &fn_def.return_type {
let ty = RuntimeType::from_parsed(ret_ty.inner.clone(), exec_state, ret_ty.as_source_range())
.map_err(|e| KclError::Semantic(e.into()))?;
.map_err(|e| KclError::new_semantic(e.into()))?;
let val = val.coerce(&ty, true, exec_state).map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"This function requires its result to be of type `{}`, but found {}",
ty.human_friendly_type(),
@ -874,7 +877,7 @@ mod test {
"all params required, none given, should error",
vec![req_param("x")],
vec![],
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
"This function requires a parameter x, but you haven't passed it one.".to_owned(),
vec![SourceRange::default()],
))),
@ -889,7 +892,7 @@ mod test {
"mixed params, too few given",
vec![req_param("x"), opt_param("y")],
vec![],
Err(KclError::Semantic(KclErrorDetails::new(
Err(KclError::new_semantic(KclErrorDetails::new(
"This function requires a parameter x, but you haven't passed it one.".to_owned(),
vec![SourceRange::default()],
))),

View File

@ -469,7 +469,7 @@ impl TryFrom<PlaneData> for PlaneInfo {
PlaneData::NegYZ => PlaneName::NegYz,
PlaneData::Plane(_) => {
// We will never get here since we already checked for PlaneData::Plane.
return Err(KclError::Internal(KclErrorDetails::new(
return Err(KclError::new_internal(KclErrorDetails::new(
format!("PlaneData {:?} not found", value),
Default::default(),
)));
@ -477,7 +477,7 @@ impl TryFrom<PlaneData> for PlaneInfo {
};
let info = DEFAULT_PLANE_INFO.get(&name).ok_or_else(|| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("Plane {} not found", name),
Default::default(),
))

View File

@ -37,25 +37,25 @@ pub async fn import_foreign(
) -> Result<PreImportedGeometry, KclError> {
// Make sure the file exists.
if !ctxt.fs.exists(file_path, source_range).await? {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("File `{}` does not exist.", file_path.display()),
vec![source_range],
)));
}
let ext_format = get_import_format_from_extension(file_path.extension().ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("No file extension found for `{}`", file_path.display()),
vec![source_range],
))
})?)
.map_err(|e| KclError::Semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
.map_err(|e| KclError::new_semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
// Get the format type from the extension of the file.
let format = if let Some(format) = format {
// Validate the given format with the extension format.
validate_extension_format(ext_format, format.clone())
.map_err(|e| KclError::Semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
.map_err(|e| KclError::new_semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
format
} else {
ext_format
@ -66,11 +66,11 @@ pub async fn import_foreign(
.fs
.read(file_path, source_range)
.await
.map_err(|e| KclError::Semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
.map_err(|e| KclError::new_semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
// We want the file_path to be without the parent.
let file_name = file_path.file_name().map(|p| p.to_string()).ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Could not get the file name from the path `{}`", file_path.display()),
vec![source_range],
))
@ -87,7 +87,7 @@ pub async fn import_foreign(
// file.
if !file_contents.starts_with(b"glTF") {
let json = gltf_json::Root::from_slice(&file_contents)
.map_err(|e| KclError::Semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
.map_err(|e| KclError::new_semantic(KclErrorDetails::new(e.to_string(), vec![source_range])))?;
// Read the gltf file and check if there is a bin file.
for buffer in json.buffers.iter() {
@ -95,16 +95,15 @@ pub async fn import_foreign(
if !uri.starts_with("data:") {
// We want this path relative to the file_path given.
let bin_path = file_path.parent().map(|p| p.join(uri)).ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Could not get the parent path of the file `{}`", file_path.display()),
vec![source_range],
))
})?;
let bin_contents =
ctxt.fs.read(&bin_path, source_range).await.map_err(|e| {
KclError::Semantic(KclErrorDetails::new(e.to_string(), vec![source_range]))
})?;
let bin_contents = ctxt.fs.read(&bin_path, source_range).await.map_err(|e| {
KclError::new_semantic(KclErrorDetails::new(e.to_string(), vec![source_range]))
})?;
import_files.push(ImportFile {
path: uri.to_string(),
@ -141,7 +140,7 @@ pub(super) fn format_from_annotations(
if p.key.name == annotations::IMPORT_FORMAT {
result = Some(
get_import_format_from_extension(annotations::expect_ident(&p.value)?).map_err(|_| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"Unknown format for import, expected one of: {}",
crate::IMPORT_FILE_EXTENSIONS.join(", ")
@ -159,7 +158,7 @@ pub(super) fn format_from_annotations(
path.extension()
.and_then(|ext| get_import_format_from_extension(ext).ok())
})
.ok_or(KclError::Semantic(KclErrorDetails::new(
.ok_or(KclError::new_semantic(KclErrorDetails::new(
"Unknown or missing extension, and no specified format for imported file".to_owned(),
vec![import_source_range],
)))?;
@ -174,7 +173,7 @@ pub(super) fn format_from_annotations(
}
annotations::IMPORT_FORMAT => {}
_ => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Unexpected annotation for import, expected one of: {}, {}, {}",
annotations::IMPORT_FORMAT,
@ -199,7 +198,7 @@ fn set_coords(fmt: &mut InputFormat3d, coords_str: &str, source_range: SourceRan
}
let Some(coords) = coords else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Unknown coordinate system: {coords_str}, expected one of: {}",
annotations::IMPORT_COORDS_VALUES
@ -217,7 +216,7 @@ fn set_coords(fmt: &mut InputFormat3d, coords_str: &str, source_range: SourceRan
InputFormat3d::Ply(opts) => opts.coords = coords,
InputFormat3d::Stl(opts) => opts.coords = coords,
_ => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"`{}` option cannot be applied to the specified format",
annotations::IMPORT_COORDS
@ -238,7 +237,7 @@ fn set_length_unit(fmt: &mut InputFormat3d, units_str: &str, source_range: Sourc
InputFormat3d::Ply(opts) => opts.units = units.into(),
InputFormat3d::Stl(opts) => opts.units = units.into(),
_ => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"`{}` option cannot be applied to the specified format",
annotations::IMPORT_LENGTH_UNIT

View File

@ -574,7 +574,7 @@ impl KclValue {
pub fn get_tag_identifier(&self) -> Result<TagIdentifier, KclError> {
match self {
KclValue::TagIdentifier(t) => Ok(*t.clone()),
_ => Err(KclError::Semantic(KclErrorDetails::new(
_ => Err(KclError::new_semantic(KclErrorDetails::new(
format!("Not a tag identifier: {:?}", self),
self.clone().into(),
))),
@ -585,7 +585,7 @@ impl KclValue {
pub fn get_tag_declarator(&self) -> Result<TagNode, KclError> {
match self {
KclValue::TagDeclarator(t) => Ok((**t).clone()),
_ => Err(KclError::Semantic(KclErrorDetails::new(
_ => Err(KclError::new_semantic(KclErrorDetails::new(
format!("Not a tag declarator: {:?}", self),
self.clone().into(),
))),
@ -595,7 +595,7 @@ impl KclValue {
/// If this KCL value is a bool, retrieve it.
pub fn get_bool(&self) -> Result<bool, KclError> {
self.as_bool().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected bool, found {}", self.human_friendly_type()),
self.into(),
))

View File

@ -367,10 +367,10 @@ impl ProgramMemory {
let name = var.trim_start_matches(TYPE_PREFIX).trim_start_matches(MODULE_PREFIX);
Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("`{name}` is not defined"),
vec![source_range],
)))
Err(KclError::new_undefined_value(
KclErrorDetails::new(format!("`{name}` is not defined"), vec![source_range]),
Some(name.to_owned()),
))
}
/// Iterate over all key/value pairs in the specified environment which satisfy the provided
@ -488,10 +488,10 @@ impl ProgramMemory {
};
}
Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("`{}` is not defined", var),
vec![],
)))
Err(KclError::new_undefined_value(
KclErrorDetails::new(format!("`{}` is not defined", var), vec![]),
Some(var.to_owned()),
))
}
}
@ -646,7 +646,7 @@ impl Stack {
pub fn add(&mut self, key: String, value: KclValue, source_range: SourceRange) -> Result<(), KclError> {
let env = self.memory.get_env(self.current_env.index());
if env.contains_key(&key) {
return Err(KclError::ValueAlreadyDefined(KclErrorDetails::new(
return Err(KclError::new_value_already_defined(KclErrorDetails::new(
format!("Cannot redefine `{}`", key),
vec![source_range],
)));

View File

@ -858,7 +858,7 @@ impl ExecutorContext {
for module in modules {
let Some((import_stmt, module_id, module_path, repr)) = universe.get(&module) else {
return Err(KclErrorWithOutputs::no_outputs(KclError::Internal(
return Err(KclErrorWithOutputs::no_outputs(KclError::new_internal(
KclErrorDetails::new(format!("Module {module} not found in universe"), Default::default()),
)));
};
@ -920,7 +920,7 @@ impl ExecutorContext {
result.map(|val| ModuleRepr::Foreign(geom.clone(), val))
}
ModuleRepr::Dummy | ModuleRepr::Root => Err(KclError::Internal(KclErrorDetails::new(
ModuleRepr::Dummy | ModuleRepr::Root => Err(KclError::new_internal(KclErrorDetails::new(
format!("Module {module_path} not found in universe"),
vec![source_range],
))),
@ -1283,7 +1283,7 @@ impl ExecutorContext {
.await?;
let kittycad_modeling_cmds::websocket::OkWebSocketResponseData::Export { files } = resp else {
return Err(KclError::Internal(crate::errors::KclErrorDetails::new(
return Err(KclError::new_internal(crate::errors::KclErrorDetails::new(
format!("Expected Export response, got {resp:?}",),
vec![SourceRange::default()],
)));
@ -1303,7 +1303,7 @@ impl ExecutorContext {
coords: *kittycad_modeling_cmds::coord::KITTYCAD,
created: if deterministic_time {
Some("2021-01-01T00:00:00Z".parse().map_err(|e| {
KclError::Internal(crate::errors::KclErrorDetails::new(
KclError::new_internal(crate::errors::KclErrorDetails::new(
format!("Failed to parse date: {}", e),
vec![SourceRange::default()],
))
@ -1383,7 +1383,7 @@ pub(crate) async fn parse_execute_with_project_dir(
let exec_ctxt = ExecutorContext {
engine: Arc::new(Box::new(
crate::engine::conn_mock::EngineConnection::new().await.map_err(|err| {
KclError::Internal(crate::errors::KclErrorDetails::new(
KclError::new_internal(crate::errors::KclErrorDetails::new(
format!("Failed to create mock engine connection: {}", err),
vec![SourceRange::default()],
))
@ -1799,7 +1799,7 @@ foo
let err = result.unwrap_err();
assert_eq!(
err,
KclError::Syntax(KclErrorDetails::new(
KclError::new_syntax(KclErrorDetails::new(
"Unexpected token: #".to_owned(),
vec![SourceRange::new(14, 15, ModuleId::default())],
)),
@ -2058,7 +2058,7 @@ notTagIdentifier = !myTag";
// TODO: We don't currently parse this, but we should. It should be
// a runtime error instead.
parse_execute(code10).await.unwrap_err(),
KclError::Syntax(KclErrorDetails::new(
KclError::new_syntax(KclErrorDetails::new(
"Unexpected token: !".to_owned(),
vec![SourceRange::new(10, 11, ModuleId::default())],
))
@ -2071,9 +2071,9 @@ notPipeSub = 1 |> identity(!%))";
// TODO: We don't currently parse this, but we should. It should be
// a runtime error instead.
parse_execute(code11).await.unwrap_err(),
KclError::Syntax(KclErrorDetails::new(
"Unexpected token: |>".to_owned(),
vec![SourceRange::new(44, 46, ModuleId::default())],
KclError::new_syntax(KclErrorDetails::new(
"There was an unexpected !. Try removing it.".to_owned(),
vec![SourceRange::new(56, 57, ModuleId::default())],
))
);

View File

@ -80,6 +80,11 @@ pub(super) struct ModuleState {
/// The current value of the pipe operator returned from the previous
/// expression. If we're not currently in a pipeline, this will be None.
pub pipe_value: Option<KclValue>,
/// The closest variable declaration being executed in any parent node in the AST.
/// This is used to provide better error messages, e.g. noticing when the user is trying
/// to use the variable `length` inside the RHS of its own definition, like `length = tan(length)`.
/// TODO: Make this a reference.
pub being_declared: Option<String>,
/// Identifiers that have been exported from the current module.
pub module_exports: Vec<String>,
/// Settings specified from annotations.
@ -276,7 +281,7 @@ impl ExecState {
}
pub(super) fn circular_import_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
KclError::ImportCycle(KclErrorDetails::new(
KclError::new_import_cycle(KclErrorDetails::new(
format!(
"circular import of modules is not allowed: {} -> {}",
self.global
@ -342,6 +347,7 @@ impl ModuleState {
id_generator: IdGenerator::new(module_id),
stack: memory.new_stack(),
pipe_value: Default::default(),
being_declared: Default::default(),
module_exports: Default::default(),
explicit_length_units: false,
path,
@ -389,7 +395,7 @@ impl MetaSettings {
self.kcl_version = value;
}
name => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Unexpected settings key: `{name}`; expected one of `{}`, `{}`",
annotations::SETTINGS_UNIT_LENGTH,

View File

@ -28,7 +28,7 @@ impl Default for FileManager {
impl FileSystem for FileManager {
async fn read(&self, path: &TypedPath, source_range: SourceRange) -> Result<Vec<u8>, KclError> {
tokio::fs::read(&path.0).await.map_err(|e| {
KclError::Io(KclErrorDetails::new(
KclError::new_io(KclErrorDetails::new(
format!("Failed to read file `{}`: {}", path.display(), e),
vec![source_range],
))
@ -37,7 +37,7 @@ impl FileSystem for FileManager {
async fn read_to_string(&self, path: &TypedPath, source_range: SourceRange) -> Result<String, KclError> {
tokio::fs::read_to_string(&path.0).await.map_err(|e| {
KclError::Io(KclErrorDetails::new(
KclError::new_io(KclErrorDetails::new(
format!("Failed to read file `{}`: {}", path.display(), e),
vec![source_range],
))
@ -49,7 +49,7 @@ impl FileSystem for FileManager {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(false)
} else {
Err(KclError::Io(KclErrorDetails::new(
Err(KclError::new_io(KclErrorDetails::new(
format!("Failed to check if file `{}` exists: {}", path.display(), e),
vec![source_range],
)))
@ -71,7 +71,7 @@ impl FileSystem for FileManager {
}
let mut read_dir = tokio::fs::read_dir(&path).await.map_err(|e| {
KclError::Io(KclErrorDetails::new(
KclError::new_io(KclErrorDetails::new(
format!("Failed to read directory `{}`: {}", path.display(), e),
vec![source_range],
))

View File

@ -49,10 +49,10 @@ impl FileSystem for FileManager {
let promise = self
.manager
.read_file(path.to_string_lossy())
.map_err(|e| KclError::Engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
let value = JsFuture::from(promise).await.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to wait for promise from engine: {:?}", e),
vec![source_range],
))
@ -67,7 +67,7 @@ impl FileSystem for FileManager {
async fn read_to_string(&self, path: &TypedPath, source_range: SourceRange) -> Result<String, KclError> {
let bytes = self.read(path, source_range).await?;
let string = String::from_utf8(bytes).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to convert bytes to string: {:?}", e),
vec![source_range],
))
@ -80,17 +80,17 @@ impl FileSystem for FileManager {
let promise = self
.manager
.exists(path.to_string_lossy())
.map_err(|e| KclError::Engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
let value = JsFuture::from(promise).await.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to wait for promise from engine: {:?}", e),
vec![source_range],
))
})?;
let it_exists = value.as_bool().ok_or_else(|| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
"Failed to convert value to bool".to_string(),
vec![source_range],
))
@ -107,24 +107,24 @@ impl FileSystem for FileManager {
let promise = self
.manager
.get_all_files(path.to_string_lossy())
.map_err(|e| KclError::Engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
.map_err(|e| KclError::new_engine(KclErrorDetails::new(e.to_string().into(), vec![source_range])))?;
let value = JsFuture::from(promise).await.map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to wait for promise from javascript: {:?}", e),
vec![source_range],
))
})?;
let s = value.as_string().ok_or_else(|| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to get string from response from javascript: `{:?}`", value),
vec![source_range],
))
})?;
let files: Vec<String> = serde_json::from_str(&s).map_err(|e| {
KclError::Engine(KclErrorDetails::new(
KclError::new_engine(KclErrorDetails::new(
format!("Failed to parse json from javascript: `{}` `{:?}`", s, e),
vec![source_range],
))

View File

@ -1202,17 +1202,7 @@ a1 = startSketchOn(offsetPlane(XY, offset = 10))
"Expected one signature, got {:?}",
signature_help.signatures
);
assert_eq!(
signature_help.signatures[0].label,
r#"extrude(
@sketches: [Sketch],
length: number,
symmetric?: bool,
bidirectionalLength?: number,
tagStart?: TagNode,
tagEnd?: TagNode,
): [Solid]"#
);
assert!(signature_help.signatures[0].label.starts_with("extrude"));
} else {
panic!("Expected signature help");
}
@ -1300,17 +1290,7 @@ a1 = startSketchOn(offsetPlane(XY, offset = 10))
"Expected one signature, got {:?}",
signature_help.signatures
);
assert_eq!(
signature_help.signatures[0].label,
r#"extrude(
@sketches: [Sketch],
length: number,
symmetric?: bool,
bidirectionalLength?: number,
tagStart?: TagNode,
tagEnd?: TagNode,
): [Solid]"#
);
assert!(signature_help.signatures[0].label.starts_with("extrude"));
} else {
panic!("Expected signature help");
}
@ -1393,17 +1373,7 @@ a1 = startSketchOn(offsetPlane(XY, offset = 10))
"Expected one signature, got {:?}",
signature_help.signatures
);
assert_eq!(
signature_help.signatures[0].label,
r#"extrude(
@sketches: [Sketch],
length: number,
symmetric?: bool,
bidirectionalLength?: number,
tagStart?: TagNode,
tagEnd?: TagNode,
): [Solid]"#
);
assert!(signature_help.signatures[0].label.starts_with("extrude"));
} else {
panic!("Expected signature help");
}
@ -1491,17 +1461,7 @@ a1 = startSketchOn(offsetPlane(XY, offset = 10))
"Expected one signature, got {:?}",
signature_help.signatures
);
assert_eq!(
signature_help.signatures[0].label,
r#"extrude(
@sketches: [Sketch],
length: number,
symmetric?: bool,
bidirectionalLength?: number,
tagStart?: TagNode,
tagEnd?: TagNode,
): [Solid]"#
);
assert!(signature_help.signatures[0].label.starts_with("extrude"));
} else {
panic!("Expected signature help");
}

View File

@ -58,7 +58,7 @@ impl ModuleLoader {
}
pub(crate) fn import_cycle_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
KclError::ImportCycle(KclErrorDetails::new(
KclError::new_import_cycle(KclErrorDetails::new(
format!(
"circular import of modules is not allowed: {} -> {}",
self.import_stack
@ -163,7 +163,7 @@ impl ModulePath {
ModulePath::Std { value: name } => Ok(ModuleSource {
source: read_std(name)
.ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Cannot find standard library module to import: std::{name}."),
vec![source_range],
))
@ -202,7 +202,7 @@ impl ModulePath {
ModulePath::Std { .. } => {
let message = format!("Cannot import a non-std KCL file from std: {path}.");
debug_assert!(false, "{}", &message);
return Err(KclError::Internal(KclErrorDetails::new(message, vec![])));
return Err(KclError::new_internal(KclErrorDetails::new(message, vec![])));
}
};
@ -217,7 +217,7 @@ impl ModulePath {
if path.len() != 2 || path[0] != "std" {
let message = format!("Invalid std import path: {path:?}.");
debug_assert!(false, "{}", &message);
return Err(KclError::Internal(KclErrorDetails::new(message, vec![])));
return Err(KclError::new_internal(KclErrorDetails::new(message, vec![])));
}
Ok(ModulePath::Std { value: path[1].clone() })

View File

@ -51,7 +51,7 @@ pub fn parse_tokens(mut tokens: TokenStream) -> ParseResult {
} else {
format!("found unknown tokens [{}]", token_list.join(", "))
};
return KclError::Lexical(KclErrorDetails::new(message, source_ranges)).into();
return KclError::new_lexical(KclErrorDetails::new(message, source_ranges)).into();
}
// Important, to not call this before the unknown tokens check.
@ -110,7 +110,7 @@ impl ParseResult {
let (p, errs) = self.0?;
if let Some(err) = errs.iter().find(|e| e.severity.is_err()) {
return Err(KclError::Syntax(err.clone().into()));
return Err(KclError::new_syntax(err.clone().into()));
}
match p {
Some(p) => Ok(p),

View File

@ -979,12 +979,18 @@ fn property_separator(i: &mut TokenSlice) -> ModalResult<()> {
}
/// Match something that separates the labeled arguments of a fn call.
fn labeled_arg_separator(i: &mut TokenSlice) -> ModalResult<()> {
/// Returns the source range of the erroneous separator, if any was found.
fn labeled_arg_separator(i: &mut TokenSlice) -> ModalResult<Option<SourceRange>> {
alt((
// Normally you need a comma.
comma_sep,
comma_sep.map(|_| None),
// But, if the argument list is ending, no need for a comma.
peek(preceded(opt(whitespace), close_paren)).void(),
peek(preceded(opt(whitespace), close_paren)).void().map(|_| None),
whitespace.map(|mut tokens| {
// Safe to unwrap here because `whitespace` is guaranteed to return at least 1 whitespace.
let first_token = tokens.pop().unwrap();
Some(SourceRange::from(&first_token))
}),
))
.parse_next(i)
}
@ -3135,7 +3141,7 @@ fn binding_name(i: &mut TokenSlice) -> ModalResult<Node<Identifier>> {
/// Either a positional or keyword function call.
fn fn_call_pos_or_kw(i: &mut TokenSlice) -> ModalResult<Expr> {
alt((fn_call_kw.map(Box::new).map(Expr::CallExpressionKw),)).parse_next(i)
fn_call_kw.map(Box::new).map(Expr::CallExpressionKw).parse_next(i)
}
fn labelled_fn_call(i: &mut TokenSlice) -> ModalResult<Expr> {
@ -3198,7 +3204,7 @@ fn fn_call_kw(i: &mut TokenSlice) -> ModalResult<Node<CallExpressionKw>> {
#[allow(clippy::large_enum_variant)]
enum ArgPlace {
NonCode(Node<NonCodeNode>),
LabeledArg(LabeledArg),
LabeledArg((LabeledArg, Option<SourceRange>)),
UnlabeledArg(Expr),
Keyword(Token),
}
@ -3208,7 +3214,7 @@ fn fn_call_kw(i: &mut TokenSlice) -> ModalResult<Node<CallExpressionKw>> {
alt((
terminated(non_code_node.map(ArgPlace::NonCode), whitespace),
terminated(any_keyword.map(ArgPlace::Keyword), whitespace),
terminated(labeled_argument, labeled_arg_separator).map(ArgPlace::LabeledArg),
(labeled_argument, labeled_arg_separator).map(ArgPlace::LabeledArg),
expression.map(ArgPlace::UnlabeledArg),
)),
)
@ -3220,7 +3226,16 @@ fn fn_call_kw(i: &mut TokenSlice) -> ModalResult<Node<CallExpressionKw>> {
ArgPlace::NonCode(x) => {
non_code_nodes.insert(index, vec![x]);
}
ArgPlace::LabeledArg(x) => {
ArgPlace::LabeledArg((x, bad_token_source_range)) => {
if let Some(bad_token_source_range) = bad_token_source_range {
return Err(ErrMode::Cut(
CompilationError::fatal(
bad_token_source_range,
"Missing comma between arguments, try adding a comma in",
)
.into(),
));
}
args.push(x);
}
ArgPlace::Keyword(kw) => {
@ -3255,7 +3270,22 @@ fn fn_call_kw(i: &mut TokenSlice) -> ModalResult<Node<CallExpressionKw>> {
)?;
ignore_whitespace(i);
opt(comma_sep).parse_next(i)?;
let end = close_paren.parse_next(i)?.end;
let end = match close_paren.parse_next(i) {
Ok(tok) => tok.end,
Err(e) => {
if let Some(tok) = i.next_token() {
return Err(ErrMode::Cut(
CompilationError::fatal(
SourceRange::from(&tok),
format!("There was an unexpected {}. Try removing it.", tok.value),
)
.into(),
));
} else {
return Err(e);
}
}
};
// Validate there aren't any duplicate labels.
let mut counted_labels = IndexMap::with_capacity(args.len());
@ -3376,8 +3406,7 @@ mod tests {
fn kw_call_as_operand() {
let tokens = crate::parsing::token::lex("f(x = 1)", ModuleId::default()).unwrap();
let tokens = tokens.as_slice();
let op = operand.parse(tokens).unwrap();
println!("{op:#?}");
operand.parse(tokens).unwrap();
}
#[test]
@ -4383,7 +4412,7 @@ secondExtrude = startSketchOn(XY)
#[test]
fn test_parse_parens_unicode() {
let result = crate::parsing::top_level_parse("");
let KclError::Lexical(details) = result.0.unwrap_err() else {
let KclError::Lexical { details } = result.0.unwrap_err() else {
panic!();
};
// TODO: Better errors when program cannot tokenize.
@ -4417,8 +4446,8 @@ z(-[["#,
assert_err(
r#"z
(--#"#,
"Unexpected token: (",
[2, 3],
"There was an unexpected -. Try removing it.",
[3, 4],
);
}
@ -5133,6 +5162,27 @@ bar = 1
assert_eq!(actual.operator, UnaryOperator::Not);
crate::parsing::top_level_parse(some_program_string).unwrap(); // Updated import path
}
#[test]
fn test_sensible_error_when_missing_comma_between_fn_args() {
let program_source = "startSketchOn(XY)
|> arc(
endAbsolute = [0, 50]
interiorAbsolute = [-50, 0]
)";
let expected_src_start = program_source.find("]").unwrap();
let tokens = crate::parsing::token::lex(program_source, ModuleId::default()).unwrap();
ParseContext::init();
let err = program
.parse(tokens.as_slice())
.expect_err("Program succeeded, but it should have failed");
let cause = err
.inner()
.cause
.as_ref()
.expect("Found an error, but there was no cause. Add a cause.");
assert_eq!(cause.message, "Missing comma between arguments, try adding a comma in",);
assert_eq!(cause.source_range.start() - 1, expected_src_start);
}
#[test]
fn test_sensible_error_when_missing_rhs_of_kw_arg() {
@ -5152,14 +5202,32 @@ bar = 1
}
}
#[test]
fn test_sensible_error_when_unexpected_token_in_fn_call() {
let program_source = "1
|> extrude(
length=depth,
})";
let expected_src_start = program_source.find("}").expect("Program should have an extraneous }");
let tokens = crate::parsing::token::lex(program_source, ModuleId::default()).unwrap();
ParseContext::init();
let err = program.parse(tokens.as_slice()).unwrap_err();
let cause = err
.inner()
.cause
.as_ref()
.expect("Found an error, but there was no cause. Add a cause.");
assert_eq!(cause.message, "There was an unexpected }. Try removing it.",);
assert_eq!(cause.source_range.start(), expected_src_start);
}
#[test]
fn test_sensible_error_when_using_keyword_as_arg_label() {
for (i, program) in ["pow(2, fn = 8)"].into_iter().enumerate() {
let tokens = crate::parsing::token::lex(program, ModuleId::default()).unwrap();
let err = match fn_call_kw.parse(tokens.as_slice()) {
Err(e) => e,
Ok(ast) => {
eprintln!("{ast:#?}");
Ok(_ast) => {
panic!("Expected this to error but it didn't");
}
};

View File

@ -597,7 +597,7 @@ impl From<ParseError<Input<'_>, winnow::error::ContextError>> for KclError {
// This is an offset, not an index, and may point to
// the end of input (input.len()) on eof errors.
return KclError::Lexical(crate::errors::KclErrorDetails::new(
return KclError::new_lexical(crate::errors::KclErrorDetails::new(
"unexpected EOF while parsing".to_owned(),
vec![SourceRange::new(offset, offset, module_id)],
));
@ -608,7 +608,7 @@ impl From<ParseError<Input<'_>, winnow::error::ContextError>> for KclError {
let bad_token = &input[offset];
// TODO: Add the Winnow parser context to the error.
// See https://github.com/KittyCAD/modeling-app/issues/784
KclError::Lexical(crate::errors::KclErrorDetails::new(
KclError::new_lexical(crate::errors::KclErrorDetails::new(
format!("found unknown token '{}'", bad_token),
vec![SourceRange::new(offset, offset + 1, module_id)],
))

View File

@ -3483,3 +3483,24 @@ mod spheres {
super::execute(TEST_NAME, true).await
}
}
mod var_ref_in_own_def {
const TEST_NAME: &str = "var_ref_in_own_def";
/// Test parsing KCL.
#[test]
fn parse() {
super::parse(TEST_NAME)
}
/// Test that parsing and unparsing KCL produces the original KCL input.
#[tokio::test(flavor = "multi_thread")]
async fn unparse() {
super::unparse(TEST_NAME).await
}
/// Test that KCL is executed correctly.
#[tokio::test(flavor = "multi_thread")]
async fn kcl_test_execute() {
super::execute(TEST_NAME, true).await
}
}

View File

@ -30,7 +30,7 @@ pub async fn hex_string(exec_state: &mut ExecState, args: Args) -> Result<KclVal
// Make sure the color if set is valid.
if let Some(component) = rgb.iter().find(|component| component.n < 0.0 || component.n > 255.0) {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Colors are given between 0 and 255, so {} is invalid", component.n),
vec![args.source_range],
)));
@ -62,7 +62,7 @@ pub async fn appearance(exec_state: &mut ExecState, args: Args) -> Result<KclVal
// Make sure the color if set is valid.
if !HEX_REGEX.is_match(&color) {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Invalid hex color (`{}`), try something like `#fff000`", color),
vec![args.source_range],
)));
@ -93,7 +93,7 @@ async fn inner_appearance(
for solid_id in solids.ids(&args.ctx).await? {
// Set the material properties.
let rgb = rgba_simple::RGB::<f32>::from_hex(&color).map_err(|err| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Invalid hex color (`{color}`): {err}"),
vec![args.source_range],
))

View File

@ -123,7 +123,7 @@ impl Args {
}
T::from_kcl_val(&arg.value).map(Some).ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!(
"The arg {label} was given, but it was the wrong type. It should be type {} but it was {}",
tynm::type_name::<T>(),
@ -156,7 +156,7 @@ impl Args {
T: FromKclValue<'a>,
{
self.get_kw_arg_opt(label)?.ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("This function requires a keyword argument '{label}'"),
vec![self.source_range],
))
@ -173,7 +173,7 @@ impl Args {
T: for<'a> FromKclValue<'a>,
{
let Some(arg) = self.kw_args.labeled.get(label) else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("This function requires a keyword argument '{label}'"),
vec![self.source_range],
)));
@ -207,7 +207,7 @@ impl Args {
if message.contains("one or more Solids or imported geometry but it's actually of type Sketch") {
message = format!("{message}. {ERROR_STRING_SKETCH_TO_SOLID_HELPER}");
}
KclError::Semantic(KclErrorDetails::new(message, arg.source_ranges()))
KclError::new_semantic(KclErrorDetails::new(message, arg.source_ranges()))
})?;
// TODO unnecessary cloning
@ -221,7 +221,7 @@ impl Args {
label: &str,
) -> Result<Vec<(EdgeReference, SourceRange)>, KclError> {
let Some(arg) = self.kw_args.labeled.get(label) else {
let err = KclError::Semantic(KclErrorDetails::new(
let err = KclError::new_semantic(KclErrorDetails::new(
format!("This function requires a keyword argument '{label}'"),
vec![self.source_range],
));
@ -234,7 +234,7 @@ impl Args {
.map(|item| {
let source = SourceRange::from(item);
let val = FromKclValue::from_kcl_val(item).ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!("Expected an Edge but found {}", arg.value.human_friendly_type()),
arg.source_ranges(),
))
@ -270,7 +270,7 @@ impl Args {
{
let arg = self
.unlabeled_kw_arg_unconverted()
.ok_or(KclError::Semantic(KclErrorDetails::new(
.ok_or(KclError::new_semantic(KclErrorDetails::new(
format!("This function requires a value for the special unlabeled first parameter, '{label}'"),
vec![self.source_range],
)))?;
@ -304,11 +304,11 @@ impl Args {
if message.contains("one or more Solids or imported geometry but it's actually of type Sketch") {
message = format!("{message}. {ERROR_STRING_SKETCH_TO_SOLID_HELPER}");
}
KclError::Semantic(KclErrorDetails::new(message, arg.source_ranges()))
KclError::new_semantic(KclErrorDetails::new(message, arg.source_ranges()))
})?;
T::from_kcl_val(&arg).ok_or_else(|| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("Mismatch between type coercion and value extraction (this isn't your fault).\nTo assist in bug-reporting, expected type: {ty:?}; actual value: {arg:?}"),
vec![self.source_range],
))
@ -354,14 +354,14 @@ impl Args {
exec_state.stack().get_from_call_stack(&tag.value, self.source_range)?
{
let info = t.get_info(epoch).ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Tag `{}` does not have engine info", tag.value),
vec![self.source_range],
))
})?;
Ok(info)
} else {
Err(KclError::Type(KclErrorDetails::new(
Err(KclError::new_type(KclErrorDetails::new(
format!("Tag `{}` does not exist", tag.value),
vec![self.source_range],
)))
@ -493,7 +493,7 @@ impl Args {
must_be_planar: bool,
) -> Result<uuid::Uuid, KclError> {
if tag.value.is_empty() {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Expected a non-empty tag for the face".to_string(),
vec![self.source_range],
)));
@ -502,7 +502,7 @@ impl Args {
let engine_info = self.get_tag_engine_info_check_surface(exec_state, tag)?;
let surface = engine_info.surface.as_ref().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Tag `{}` does not have a surface", tag.value),
vec![self.source_range],
))
@ -521,7 +521,7 @@ impl Args {
}
}
// The must be planar check must be called before the arc check.
ExtrudeSurface::ExtrudeArc(_) if must_be_planar => Some(Err(KclError::Type(KclErrorDetails::new(
ExtrudeSurface::ExtrudeArc(_) if must_be_planar => Some(Err(KclError::new_type(KclErrorDetails::new(
format!("Tag `{}` is a non-planar surface", tag.value),
vec![self.source_range],
)))),
@ -548,7 +548,7 @@ impl Args {
}
}
// The must be planar check must be called before the fillet check.
ExtrudeSurface::Fillet(_) if must_be_planar => Some(Err(KclError::Type(KclErrorDetails::new(
ExtrudeSurface::Fillet(_) if must_be_planar => Some(Err(KclError::new_type(KclErrorDetails::new(
format!("Tag `{}` is a non-planar surface", tag.value),
vec![self.source_range],
)))),
@ -568,7 +568,7 @@ impl Args {
}
// If we still haven't found the face, return an error.
Err(KclError::Type(KclErrorDetails::new(
Err(KclError::new_type(KclErrorDetails::new(
format!("Expected a face with the tag `{}`", tag.value),
vec![self.source_range],
)))
@ -593,13 +593,13 @@ where
{
fn from_args(args: &'a Args, i: usize) -> Result<Self, KclError> {
let Some(arg) = args.args.get(i) else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Expected an argument at index {i}"),
vec![args.source_range],
)));
};
let Some(val) = T::from_kcl_val(&arg.value) else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Argument at index {i} was supposed to be type {} but found {}",
tynm::type_name::<T>(),
@ -622,7 +622,7 @@ where
return Ok(None);
}
let Some(val) = T::from_kcl_val(&arg.value) else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Argument at index {i} was supposed to be type Option<{}> but found {}",
tynm::type_name::<T>(),

View File

@ -58,7 +58,7 @@ async fn call_map_closure(
let output = map_fn.call_kw(None, exec_state, ctxt, args, source_range).await?;
let source_ranges = vec![source_range];
let output = output.ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
"Map function must return a value".to_owned(),
source_ranges,
))
@ -118,7 +118,7 @@ async fn call_reduce_closure(
// Unpack the returned transform object.
let source_ranges = vec![source_range];
let out = transform_fn_return.ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
"Reducer function must return a value".to_string(),
source_ranges.clone(),
))
@ -138,7 +138,7 @@ pub async fn push(exec_state: &mut ExecState, args: Args) -> Result<KclValue, Kc
pub async fn pop(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let (mut array, ty) = args.get_unlabeled_kw_arg_array_and_type("array", exec_state)?;
if array.is_empty() {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Cannot pop from an empty array".to_string(),
vec![args.source_range],
)));

View File

@ -1,7 +1,6 @@
//! Standard library assert functions.
use anyhow::Result;
use kcl_derive_docs::stdlib;
use super::args::TyF64;
use crate::{
@ -12,7 +11,7 @@ use crate::{
async fn _assert(value: bool, message: &str, args: &Args) -> Result<(), KclError> {
if !value {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
format!("assert failed: {}", message),
vec![args.source_range],
)));
@ -42,19 +41,6 @@ pub async fn assert(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
Ok(KclValue::none())
}
/// Asserts that a value is the boolean value true.
/// ```no_run
/// kclIsFun = true
/// assertIs(kclIsFun)
/// ```
#[stdlib{
name = "assertIs",
unlabeled_first = true,
args = {
actual = { docs = "Value to check. If this is the boolean value true, assert passes. Otherwise it fails." },
error = { docs = "If the value was false, the program will terminate with this error message" },
}
}]
async fn inner_assert_is(actual: bool, error: Option<String>, args: &Args) -> Result<(), KclError> {
let error_msg = match &error {
Some(x) => x,
@ -63,29 +49,6 @@ async fn inner_assert_is(actual: bool, error: Option<String>, args: &Args) -> Re
_assert(actual, error_msg, args).await
}
/// Check a value meets some expected conditions at runtime. Program terminates with an error if conditions aren't met.
/// If you provide multiple conditions, they will all be checked and all must be met.
///
/// ```no_run
/// n = 10
/// assert(n, isEqualTo = 10)
/// assert(n, isGreaterThanOrEqual = 0, isLessThan = 100, error = "number should be between 0 and 100")
/// assert(1.0000000000012, isEqualTo = 1, tolerance = 0.0001, error = "number should be almost exactly 1")
/// ```
#[stdlib {
name = "assert",
unlabeled_first = true,
args = {
actual = { docs = "Value to check. It will be compared with one of the comparison arguments." },
is_greater_than = { docs = "Comparison argument. If given, checks the `actual` value is greater than this." },
is_less_than = { docs = "Comparison argument. If given, checks the `actual` value is less than this." },
is_greater_than_or_equal = { docs = "Comparison argument. If given, checks the `actual` value is greater than or equal to this." },
is_less_than_or_equal = { docs = "Comparison argument. If given, checks the `actual` value is less than or equal to this." },
is_equal_to = { docs = "Comparison argument. If given, checks the `actual` value is less than or equal to this.", include_in_snippet = true },
tolerance = { docs = "If `isEqualTo` is used, this is the tolerance to allow for the comparison. This tolerance is used because KCL's number system has some floating-point imprecision when used with very large decimal places." },
error = { docs = "If the value was false, the program will terminate with this error message" },
}
}]
#[allow(clippy::too_many_arguments)]
async fn inner_assert(
actual: TyF64,
@ -109,14 +72,14 @@ async fn inner_assert(
.iter()
.all(|cond| cond.is_none());
if no_condition_given {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"You must provide at least one condition in this assert (for example, isEqualTo)".to_owned(),
vec![args.source_range],
)));
}
if tolerance.is_some() && is_equal_to.is_none() {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"The `tolerance` arg is only used with `isEqualTo`. Either remove `tolerance` or add an `isEqualTo` arg."
.to_owned(),
vec![args.source_range],

View File

@ -41,7 +41,7 @@ async fn inner_chamfer(
// If you try and tag multiple edges with a tagged chamfer, we want to return an
// error to the user that they can only tag one edge at a time.
if tag.is_some() && tags.len() > 1 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"You can only tag one edge at a time with a tagged chamfer. Either delete the tag for the chamfer fn if you don't need it OR separate into individual chamfer functions for each tag.".to_string(),
vec![args.source_range],
)));

View File

@ -84,7 +84,7 @@ async fn inner_clone(
fix_tags_and_references(&mut new_geometry, old_id, exec_state, &args)
.await
.map_err(|e| {
KclError::Internal(KclErrorDetails::new(
KclError::new_internal(KclErrorDetails::new(
format!("failed to fix tags and references: {:?}", e),
vec![args.source_range],
))

View File

@ -23,7 +23,7 @@ pub async fn union(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
let tolerance: Option<TyF64> = args.get_kw_arg_opt_typed("tolerance", &RuntimeType::length(), exec_state)?;
if solids.len() < 2 {
return Err(KclError::UndefinedValue(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"At least two solids are required for a union operation.".to_string(),
vec![args.source_range],
)));
@ -66,7 +66,7 @@ pub(crate) async fn inner_union(
modeling_response: OkModelingCmdResponse::BooleanUnion(BooleanUnion { extra_solid_ids }),
} = result
else {
return Err(KclError::Internal(KclErrorDetails::new(
return Err(KclError::new_internal(KclErrorDetails::new(
"Failed to get the result of the union operation.".to_string(),
vec![args.source_range],
)));
@ -88,7 +88,7 @@ pub async fn intersect(exec_state: &mut ExecState, args: Args) -> Result<KclValu
let tolerance: Option<TyF64> = args.get_kw_arg_opt_typed("tolerance", &RuntimeType::length(), exec_state)?;
if solids.len() < 2 {
return Err(KclError::UndefinedValue(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"At least two solids are required for an intersect operation.".to_string(),
vec![args.source_range],
)));
@ -131,7 +131,7 @@ pub(crate) async fn inner_intersect(
modeling_response: OkModelingCmdResponse::BooleanIntersection(BooleanIntersection { extra_solid_ids }),
} = result
else {
return Err(KclError::Internal(KclErrorDetails::new(
return Err(KclError::new_internal(KclErrorDetails::new(
"Failed to get the result of the intersection operation.".to_string(),
vec![args.source_range],
)));
@ -193,7 +193,7 @@ pub(crate) async fn inner_subtract(
modeling_response: OkModelingCmdResponse::BooleanSubtract(BooleanSubtract { extra_solid_ids }),
} = result
else {
return Err(KclError::Internal(KclErrorDetails::new(
return Err(KclError::new_internal(KclErrorDetails::new(
"Failed to get the result of the subtract operation.".to_string(),
vec![args.source_range],
)));

View File

@ -52,7 +52,7 @@ async fn inner_get_opposite_edge(
modeling_response: OkModelingCmdResponse::Solid3dGetOppositeEdge(opposite_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!("mcmd::Solid3dGetOppositeEdge response was not as expected: {:?}", resp),
vec![args.source_range],
)));
@ -100,7 +100,7 @@ async fn inner_get_next_adjacent_edge(
modeling_response: OkModelingCmdResponse::Solid3dGetNextAdjacentEdge(adjacent_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!(
"mcmd::Solid3dGetNextAdjacentEdge response was not as expected: {:?}",
resp
@ -110,7 +110,7 @@ async fn inner_get_next_adjacent_edge(
};
adjacent_edge.edge.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("No edge found next adjacent to tag: `{}`", edge.value),
vec![args.source_range],
))
@ -155,7 +155,7 @@ async fn inner_get_previous_adjacent_edge(
modeling_response: OkModelingCmdResponse::Solid3dGetPrevAdjacentEdge(adjacent_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!(
"mcmd::Solid3dGetPrevAdjacentEdge response was not as expected: {:?}",
resp
@ -165,7 +165,7 @@ async fn inner_get_previous_adjacent_edge(
};
adjacent_edge.edge.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("No edge found previous adjacent to tag: `{}`", edge.value),
vec![args.source_range],
))
@ -198,7 +198,7 @@ async fn inner_get_common_edge(
}
if faces.len() != 2 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"getCommonEdge requires exactly two tags for faces".to_string(),
vec![args.source_range],
)));
@ -210,7 +210,7 @@ async fn inner_get_common_edge(
let second_tagged_path = args.get_tag_engine_info(exec_state, &faces[1])?;
if first_tagged_path.sketch != second_tagged_path.sketch {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"getCommonEdge requires the faces to be in the same original sketch".to_string(),
vec![args.source_range],
)));
@ -239,14 +239,14 @@ async fn inner_get_common_edge(
modeling_response: OkModelingCmdResponse::Solid3dGetCommonEdge(common_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!("mcmd::Solid3dGetCommonEdge response was not as expected: {:?}", resp),
vec![args.source_range],
)));
};
common_edge.edge.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!(
"No common edge was found between `{}` and `{}`",
faces[0].value, faces[1].value

View File

@ -3,7 +3,6 @@
use std::collections::HashMap;
use anyhow::Result;
use kcl_derive_docs::stdlib;
use kcmc::{
each_cmd as mcmd,
length_unit::LengthUnit,
@ -52,113 +51,6 @@ pub async fn extrude(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
Ok(result.into())
}
/// Extend a 2-dimensional sketch through a third dimension in order to
/// create new 3-dimensional volume, or if extruded into an existing volume,
/// cut into an existing solid.
///
/// You can provide more than one sketch to extrude, and they will all be
/// extruded in the same direction.
///
/// ```no_run
/// example = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [10, 0])
/// |> arc(
/// angleStart = 120,
/// angleEnd = 0,
/// radius = 5,
/// )
/// |> line(end = [5, 0])
/// |> line(end = [0, 10])
/// |> bezierCurve(
/// control1 = [-10, 0],
/// control2 = [2, 10],
/// end = [-5, 10],
/// )
/// |> line(end = [-5, -2])
/// |> close()
/// |> extrude(length = 10)
/// ```
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [-10, 0])
/// |> arc(
/// angleStart = 120,
/// angleEnd = -60,
/// radius = 5,
/// )
/// |> line(end = [10, 0])
/// |> line(end = [5, 0])
/// |> bezierCurve(
/// control1 = [-3, 0],
/// control2 = [2, 10],
/// end = [-5, 10],
/// )
/// |> line(end = [-4, 10])
/// |> line(end = [-5, -2])
/// |> close()
///
/// example = extrude(exampleSketch, length = 10)
/// ```
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [-10, 0])
/// |> arc(
/// angleStart = 120,
/// angleEnd = -60,
/// radius = 5,
/// )
/// |> line(end = [10, 0])
/// |> line(end = [5, 0])
/// |> bezierCurve(
/// control1 = [-3, 0],
/// control2 = [2, 10],
/// end = [-5, 10],
/// )
/// |> line(end = [-4, 10])
/// |> line(end = [-5, -2])
/// |> close()
///
/// example = extrude(exampleSketch, length = 20, symmetric = true)
/// ```
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [-10, 0])
/// |> arc(
/// angleStart = 120,
/// angleEnd = -60,
/// radius = 5,
/// )
/// |> line(end = [10, 0])
/// |> line(end = [5, 0])
/// |> bezierCurve(
/// control1 = [-3, 0],
/// control2 = [2, 10],
/// end = [-5, 10],
/// )
/// |> line(end = [-4, 10])
/// |> line(end = [-5, -2])
/// |> close()
///
/// example = extrude(exampleSketch, length = 10, bidirectionalLength = 50)
/// ```
#[stdlib {
name = "extrude",
feature_tree_operation = true,
unlabeled_first = true,
args = {
sketches = { docs = "Which sketch or sketches should be extruded"},
length = { docs = "How far to extrude the given sketches"},
symmetric = { docs = "If true, the extrusion will happen symmetrically around the sketch. Otherwise, the extrusion will happen on only one side of the sketch." },
bidirectional_length = { docs = "If specified, will also extrude in the opposite direction to 'distance' to the specified distance. If 'symmetric' is true, this value is ignored."},
tag_start = { docs = "A named tag for the face at the start of the extrusion, i.e. the original sketch" },
tag_end = { docs = "A named tag for the face at the end of the extrusion, i.e. the new face created by extruding the original sketch" },
},
tags = ["sketch"]
}]
#[allow(clippy::too_many_arguments)]
async fn inner_extrude(
sketches: Vec<Sketch>,
@ -174,7 +66,7 @@ async fn inner_extrude(
let mut solids = Vec::new();
if symmetric.unwrap_or(false) && bidirectional_length.is_some() {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
.to_owned(),
vec![args.source_range],
@ -261,7 +153,7 @@ pub(crate) async fn do_post_extrude<'a>(
// The "get extrusion face info" API call requires *any* edge on the sketch being extruded.
// So, let's just use the first one.
let Some(any_edge_id) = sketch.paths.first().map(|edge| edge.get_base().geo_meta.id) else {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Expected a non-empty sketch".to_owned(),
vec![args.source_range],
)));
@ -386,7 +278,7 @@ pub(crate) async fn do_post_extrude<'a>(
// Add the tags for the start or end caps.
if let Some(tag_start) = named_cap_tags.start {
let Some(start_cap_id) = start_cap_id else {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
format!(
"Expected a start cap ID for tag `{}` for extrusion of sketch {:?}",
tag_start.name, sketch.id
@ -406,7 +298,7 @@ pub(crate) async fn do_post_extrude<'a>(
}
if let Some(tag_end) = named_cap_tags.end {
let Some(end_cap_id) = end_cap_id else {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
format!(
"Expected an end cap ID for tag `{}` for extrusion of sketch {:?}",
tag_end.name, sketch.id

View File

@ -49,7 +49,7 @@ pub(super) fn validate_unique<T: Eq + std::hash::Hash>(tags: &[(T, SourceRange)]
}
}
if !duplicate_tags_source.is_empty() {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"The same edge ID is being referenced multiple times, which is not allowed. Please select a different edge"
.to_string(),
duplicate_tags_source,
@ -85,14 +85,14 @@ async fn inner_fillet(
// If you try and tag multiple edges with a tagged fillet, we want to return an
// error to the user that they can only tag one edge at a time.
if tag.is_some() && tags.len() > 1 {
return Err(KclError::Type(KclErrorDetails {
return Err(KclError::new_type(KclErrorDetails {
message: "You can only tag one edge at a time with a tagged fillet. Either delete the tag for the fillet fn if you don't need it OR separate into individual fillet functions for each tag.".to_string(),
source_ranges: vec![args.source_range],
backtrace: Default::default(),
}));
}
if tags.is_empty() {
return Err(KclError::Semantic(KclErrorDetails {
return Err(KclError::new_semantic(KclErrorDetails {
source_ranges: vec![args.source_range],
message: "You must fillet at least one tag".to_owned(),
backtrace: Default::default(),

View File

@ -33,7 +33,7 @@ pub async fn helix(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
// Make sure we have a radius if we don't have a cylinder.
if radius.is_none() && cylinder.is_none() {
return Err(KclError::Semantic(crate::errors::KclErrorDetails::new(
return Err(KclError::new_semantic(crate::errors::KclErrorDetails::new(
"Radius is required when creating a helix without a cylinder.".to_string(),
vec![args.source_range],
)));
@ -41,7 +41,7 @@ pub async fn helix(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
// Make sure we don't have a radius if we have a cylinder.
if radius.is_some() && cylinder.is_some() {
return Err(KclError::Semantic(crate::errors::KclErrorDetails::new(
return Err(KclError::new_semantic(crate::errors::KclErrorDetails::new(
"Radius is not allowed when creating a helix with a cylinder.".to_string(),
vec![args.source_range],
)));
@ -49,7 +49,7 @@ pub async fn helix(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
// Make sure we have an axis if we don't have a cylinder.
if axis.is_none() && cylinder.is_none() {
return Err(KclError::Semantic(crate::errors::KclErrorDetails::new(
return Err(KclError::new_semantic(crate::errors::KclErrorDetails::new(
"Axis is required when creating a helix without a cylinder.".to_string(),
vec![args.source_range],
)));
@ -57,7 +57,7 @@ pub async fn helix(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
// Make sure we don't have an axis if we have a cylinder.
if axis.is_some() && cylinder.is_some() {
return Err(KclError::Semantic(crate::errors::KclErrorDetails::new(
return Err(KclError::new_semantic(crate::errors::KclErrorDetails::new(
"Axis is not allowed when creating a helix with a cylinder.".to_string(),
vec![args.source_range],
)));
@ -65,7 +65,7 @@ pub async fn helix(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
// Make sure we have a radius if we have an axis.
if radius.is_none() && axis.is_some() {
return Err(KclError::Semantic(crate::errors::KclErrorDetails::new(
return Err(KclError::new_semantic(crate::errors::KclErrorDetails::new(
"Radius is required when creating a helix around an axis.".to_string(),
vec![args.source_range],
)));
@ -73,7 +73,7 @@ pub async fn helix(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
// Make sure we have an axis if we have a radius.
if axis.is_none() && radius.is_some() {
return Err(KclError::Semantic(crate::errors::KclErrorDetails::new(
return Err(KclError::new_semantic(crate::errors::KclErrorDetails::new(
"Axis is required when creating a helix around an axis.".to_string(),
vec![args.source_range],
)));
@ -140,7 +140,7 @@ async fn inner_helix(
Axis3dOrEdgeReference::Axis { direction, origin } => {
// Make sure they gave us a length.
let Some(length) = length else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Length is required when creating a helix around an axis.".to_owned(),
vec![args.source_range],
)));

View File

@ -3,7 +3,6 @@
use std::num::NonZeroU32;
use anyhow::Result;
use kcl_derive_docs::stdlib;
use kcmc::{each_cmd as mcmd, length_unit::LengthUnit, ModelingCmd};
use kittycad_modeling_cmds as kcmc;
@ -55,87 +54,6 @@ pub async fn loft(exec_state: &mut ExecState, args: Args) -> Result<KclValue, Kc
Ok(KclValue::Solid { value })
}
/// Create a 3D surface or solid by interpolating between two or more sketches.
///
/// The sketches need to closed and on the same plane.
///
/// ```no_run
/// // Loft a square and a triangle.
/// squareSketch = startSketchOn(XY)
/// |> startProfile(at = [-100, 200])
/// |> line(end = [200, 0])
/// |> line(end = [0, -200])
/// |> line(end = [-200, 0])
/// |> line(endAbsolute = [profileStartX(%), profileStartY(%)])
/// |> close()
///
/// triangleSketch = startSketchOn(offsetPlane(XY, offset = 75))
/// |> startProfile(at = [0, 125])
/// |> line(end = [-15, -30])
/// |> line(end = [30, 0])
/// |> line(endAbsolute = [profileStartX(%), profileStartY(%)])
/// |> close()
///
/// loft([triangleSketch, squareSketch])
/// ```
///
/// ```no_run
/// // Loft a square, a circle, and another circle.
/// squareSketch = startSketchOn(XY)
/// |> startProfile(at = [-100, 200])
/// |> line(end = [200, 0])
/// |> line(end = [0, -200])
/// |> line(end = [-200, 0])
/// |> line(endAbsolute = [profileStartX(%), profileStartY(%)])
/// |> close()
///
/// circleSketch0 = startSketchOn(offsetPlane(XY, offset = 75))
/// |> circle( center = [0, 100], radius = 50 )
///
/// circleSketch1 = startSketchOn(offsetPlane(XY, offset = 150))
/// |> circle( center = [0, 100], radius = 20 )
///
/// loft([squareSketch, circleSketch0, circleSketch1])
/// ```
///
/// ```no_run
/// // Loft a square, a circle, and another circle with options.
/// squareSketch = startSketchOn(XY)
/// |> startProfile(at = [-100, 200])
/// |> line(end = [200, 0])
/// |> line(end = [0, -200])
/// |> line(end = [-200, 0])
/// |> line(endAbsolute = [profileStartX(%), profileStartY(%)])
/// |> close()
///
/// circleSketch0 = startSketchOn(offsetPlane(XY, offset = 75))
/// |> circle( center = [0, 100], radius = 50 )
///
/// circleSketch1 = startSketchOn(offsetPlane(XY, offset = 150))
/// |> circle( center = [0, 100], radius = 20 )
///
/// loft([squareSketch, circleSketch0, circleSketch1],
/// baseCurveIndex = 0,
/// bezApproximateRational = false,
/// tolerance = 0.000001,
/// vDegree = 2,
/// )
/// ```
#[stdlib {
name = "loft",
feature_tree_operation = true,
unlabeled_first = true,
args = {
sketches = {docs = "Which sketches to loft. Must include at least 2 sketches."},
v_degree = {docs = "Degree of the interpolation. Must be greater than zero. For example, use 2 for quadratic, or 3 for cubic interpolation in the V direction. This defaults to 2, if not specified."},
bez_approximate_rational = {docs = "Attempt to approximate rational curves (such as arcs) using a bezier. This will remove banding around interpolations between arcs and non-arcs. It may produce errors in other scenarios Over time, this field won't be necessary."},
base_curve_index = {docs = "This can be set to override the automatically determined topological base curve, which is usually the first section encountered."},
tolerance = {docs = "Tolerance for the loft operation."},
tag_start = { docs = "A named tag for the face at the start of the loft, i.e. the original sketch" },
tag_end = { docs = "A named tag for the face at the end of the loft, i.e. the last sketch" },
},
tags = ["sketch"]
}]
#[allow(clippy::too_many_arguments)]
async fn inner_loft(
sketches: Vec<Sketch>,
@ -150,7 +68,7 @@ async fn inner_loft(
) -> Result<Box<Solid>, KclError> {
// Make sure we have at least two sketches.
if sketches.len() < 2 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Loft requires at least two sketches, but only {} were provided.",
sketches.len()

View File

@ -56,7 +56,7 @@ pub async fn sqrt(exec_state: &mut ExecState, args: Args) -> Result<KclValue, Kc
let input: TyF64 = args.get_unlabeled_kw_arg_typed("input", &RuntimeType::num_any(), exec_state)?;
if input.n < 0.0 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Attempt to take square root (`sqrt`) of a number less than zero ({})",
input.n

View File

@ -101,7 +101,7 @@ async fn inner_mirror_2d(
OkModelingCmdResponse::EntityGetAllChildUuids(EntityGetAllChildUuids { entity_ids: child_ids }),
} = response
else {
return Err(KclError::Internal(KclErrorDetails::new(
return Err(KclError::new_internal(KclErrorDetails::new(
"Expected a successful response from EntityGetAllChildUuids".to_string(),
vec![args.source_range],
)));
@ -112,7 +112,7 @@ async fn inner_mirror_2d(
let child_id = child_ids[1];
sketch.mirror = Some(child_id);
} else {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Expected child uuids to be >= 2".to_string(),
vec![args.source_range],
)));

View File

@ -45,20 +45,6 @@ pub type StdFn = fn(
lazy_static! {
static ref CORE_FNS: Vec<Box<dyn StdLibFn>> = vec![
Box::new(crate::std::extrude::Extrude),
Box::new(crate::std::segment::SegEnd),
Box::new(crate::std::segment::SegEndX),
Box::new(crate::std::segment::SegEndY),
Box::new(crate::std::segment::SegStart),
Box::new(crate::std::segment::SegStartX),
Box::new(crate::std::segment::SegStartY),
Box::new(crate::std::segment::LastSegX),
Box::new(crate::std::segment::LastSegY),
Box::new(crate::std::segment::SegLen),
Box::new(crate::std::segment::SegAng),
Box::new(crate::std::segment::TangentToEnd),
Box::new(crate::std::shapes::CircleThreePoint),
Box::new(crate::std::shapes::Polygon),
Box::new(crate::std::sketch::InvoluteCircular),
Box::new(crate::std::sketch::Line),
Box::new(crate::std::sketch::XLine),
@ -75,12 +61,6 @@ lazy_static! {
Box::new(crate::std::sketch::TangentialArc),
Box::new(crate::std::sketch::BezierCurve),
Box::new(crate::std::sketch::Subtract2D),
Box::new(crate::std::patterns::PatternLinear2D),
Box::new(crate::std::patterns::PatternCircular2D),
Box::new(crate::std::sweep::Sweep),
Box::new(crate::std::loft::Loft),
Box::new(crate::std::assert::Assert),
Box::new(crate::std::assert::AssertIs)
];
}
@ -219,20 +199,28 @@ pub(crate) fn std_fn(path: &str, fn_name: &str) -> (crate::std::StdFn, StdFnProp
),
("transform", "translate") => (
|e, a| Box::pin(crate::std::transform::translate(e, a)),
StdFnProps::default("std::transform::translate"),
StdFnProps::default("std::transform::translate").include_in_feature_tree(),
),
("transform", "rotate") => (
|e, a| Box::pin(crate::std::transform::rotate(e, a)),
StdFnProps::default("std::transform::rotate"),
StdFnProps::default("std::transform::rotate").include_in_feature_tree(),
),
("transform", "scale") => (
|e, a| Box::pin(crate::std::transform::scale(e, a)),
StdFnProps::default("std::transform::scale"),
StdFnProps::default("std::transform::scale").include_in_feature_tree(),
),
("prelude", "offsetPlane") => (
|e, a| Box::pin(crate::std::planes::offset_plane(e, a)),
StdFnProps::default("std::offsetPlane").include_in_feature_tree(),
),
("prelude", "assert") => (
|e, a| Box::pin(crate::std::assert::assert(e, a)),
StdFnProps::default("std::assert"),
),
("prelude", "assertIs") => (
|e, a| Box::pin(crate::std::assert::assert_is(e, a)),
StdFnProps::default("std::assertIs"),
),
("solid", "fillet") => (
|e, a| Box::pin(crate::std::fillet::fillet(e, a)),
StdFnProps::default("std::solid::fillet").include_in_feature_tree(),
@ -301,6 +289,10 @@ pub(crate) fn std_fn(path: &str, fn_name: &str) -> (crate::std::StdFn, StdFnProp
|e, a| Box::pin(crate::std::shapes::circle(e, a)),
StdFnProps::default("std::sketch::circle"),
),
("sketch", "extrude") => (
|e, a| Box::pin(crate::std::extrude::extrude(e, a)),
StdFnProps::default("std::sketch::extrude").include_in_feature_tree(),
),
("sketch", "patternTransform2d") => (
|e, a| Box::pin(crate::std::patterns::pattern_transform_2d(e, a)),
StdFnProps::default("std::sketch::patternTransform2d"),
@ -309,6 +301,22 @@ pub(crate) fn std_fn(path: &str, fn_name: &str) -> (crate::std::StdFn, StdFnProp
|e, a| Box::pin(crate::std::revolve::revolve(e, a)),
StdFnProps::default("std::sketch::revolve").include_in_feature_tree(),
),
("sketch", "sweep") => (
|e, a| Box::pin(crate::std::sweep::sweep(e, a)),
StdFnProps::default("std::sketch::sweep").include_in_feature_tree(),
),
("sketch", "loft") => (
|e, a| Box::pin(crate::std::loft::loft(e, a)),
StdFnProps::default("std::sketch::loft").include_in_feature_tree(),
),
("sketch", "polygon") => (
|e, a| Box::pin(crate::std::shapes::polygon(e, a)),
StdFnProps::default("std::sketch::polygon"),
),
("sketch", "circleThreePoint") => (
|e, a| Box::pin(crate::std::shapes::circle_three_point(e, a)),
StdFnProps::default("std::sketch::circleThreePoint"),
),
("sketch", "getCommonEdge") => (
|e, a| Box::pin(crate::std::edge::get_common_edge(e, a)),
StdFnProps::default("std::sketch::getCommonEdge"),
@ -325,6 +333,58 @@ pub(crate) fn std_fn(path: &str, fn_name: &str) -> (crate::std::StdFn, StdFnProp
|e, a| Box::pin(crate::std::edge::get_previous_adjacent_edge(e, a)),
StdFnProps::default("std::sketch::getPreviousAdjacentEdge"),
),
("sketch", "patternLinear2d") => (
|e, a| Box::pin(crate::std::patterns::pattern_linear_2d(e, a)),
StdFnProps::default("std::sketch::patternLinear2d"),
),
("sketch", "patternCircular2d") => (
|e, a| Box::pin(crate::std::patterns::pattern_circular_2d(e, a)),
StdFnProps::default("std::sketch::patternCircular2d"),
),
("sketch", "segEnd") => (
|e, a| Box::pin(crate::std::segment::segment_end(e, a)),
StdFnProps::default("std::sketch::segEnd"),
),
("sketch", "segEndX") => (
|e, a| Box::pin(crate::std::segment::segment_end_x(e, a)),
StdFnProps::default("std::sketch::segEndX"),
),
("sketch", "segEndY") => (
|e, a| Box::pin(crate::std::segment::segment_end_y(e, a)),
StdFnProps::default("std::sketch::segEndY"),
),
("sketch", "segStart") => (
|e, a| Box::pin(crate::std::segment::segment_start(e, a)),
StdFnProps::default("std::sketch::segStart"),
),
("sketch", "segStartX") => (
|e, a| Box::pin(crate::std::segment::segment_start_x(e, a)),
StdFnProps::default("std::sketch::segStartX"),
),
("sketch", "segStartY") => (
|e, a| Box::pin(crate::std::segment::segment_start_y(e, a)),
StdFnProps::default("std::sketch::segStartY"),
),
("sketch", "lastSegX") => (
|e, a| Box::pin(crate::std::segment::last_segment_x(e, a)),
StdFnProps::default("std::sketch::lastSegX"),
),
("sketch", "lastSegY") => (
|e, a| Box::pin(crate::std::segment::last_segment_y(e, a)),
StdFnProps::default("std::sketch::lastSegY"),
),
("sketch", "segLen") => (
|e, a| Box::pin(crate::std::segment::segment_length(e, a)),
StdFnProps::default("std::sketch::segLen"),
),
("sketch", "segAng") => (
|e, a| Box::pin(crate::std::segment::segment_angle(e, a)),
StdFnProps::default("std::sketch::segAng"),
),
("sketch", "tangentToEnd") => (
|e, a| Box::pin(crate::std::segment::tangent_to_end(e, a)),
StdFnProps::default("std::sketch::tangentToEnd"),
),
("appearance", "hexString") => (
|e, a| Box::pin(crate::std::appearance::hex_string(e, a)),
StdFnProps::default("std::appearance::hexString"),

View File

@ -3,7 +3,6 @@
use std::cmp::Ordering;
use anyhow::Result;
use kcl_derive_docs::stdlib;
use kcmc::{
each_cmd as mcmd, length_unit::LengthUnit, ok_response::OkModelingCmdResponse, shared::Transform,
websocket::OkWebSocketResponseData, ModelingCmd,
@ -67,7 +66,7 @@ async fn inner_pattern_transform<'a>(
// Build the vec of transforms, one for each repetition.
let mut transform_vec = Vec::with_capacity(usize::try_from(instances).unwrap());
if instances < 1 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
MUST_HAVE_ONE_INSTANCE.to_owned(),
vec![args.source_range],
)));
@ -97,7 +96,7 @@ async fn inner_pattern_transform_2d<'a>(
// Build the vec of transforms, one for each repetition.
let mut transform_vec = Vec::with_capacity(usize::try_from(instances).unwrap());
if instances < 1 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
MUST_HAVE_ONE_INSTANCE.to_owned(),
vec![args.source_range],
)));
@ -177,7 +176,7 @@ async fn send_pattern_transform<T: GeometryTrait>(
}
&mock_ids
} else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!("EntityLinearPattern response was not as expected: {:?}", resp),
vec![args.source_range],
)));
@ -223,7 +222,7 @@ async fn make_transform<T: GeometryTrait>(
// Unpack the returned transform object.
let source_ranges = vec![source_range];
let transform_fn_return = transform_fn_return.ok_or_else(|| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
"Transform function must return a value".to_string(),
source_ranges.clone(),
))
@ -234,7 +233,7 @@ async fn make_transform<T: GeometryTrait>(
let transforms: Vec<_> = value
.into_iter()
.map(|val| {
val.into_object().ok_or(KclError::Semantic(KclErrorDetails::new(
val.into_object().ok_or(KclError::new_semantic(KclErrorDetails::new(
"Transform function must return a transform object".to_string(),
source_ranges.clone(),
)))
@ -243,7 +242,7 @@ async fn make_transform<T: GeometryTrait>(
transforms
}
_ => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Transform function must return a transform object".to_string(),
source_ranges.clone(),
)))
@ -266,7 +265,7 @@ fn transform_from_obj_fields<T: GeometryTrait>(
Some(KclValue::Bool { value: true, .. }) => true,
Some(KclValue::Bool { value: false, .. }) => false,
Some(_) => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"The 'replicate' key must be a bool".to_string(),
source_ranges.clone(),
)));
@ -298,7 +297,7 @@ fn transform_from_obj_fields<T: GeometryTrait>(
let mut rotation = Rotation::default();
if let Some(rot) = transform.get("rotation") {
let KclValue::Object { value: rot, meta: _ } = rot else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"The 'rotation' key must be an object (with optional fields 'angle', 'axis' and 'origin')".to_owned(),
source_ranges.clone(),
)));
@ -312,7 +311,7 @@ fn transform_from_obj_fields<T: GeometryTrait>(
rotation.angle = Angle::from_degrees(*number);
}
_ => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"The 'rotation.angle' key must be a number (of degrees)".to_owned(),
source_ranges.clone(),
)));
@ -346,7 +345,7 @@ fn array_to_point3d(
) -> Result<[TyF64; 3], KclError> {
val.coerce(&RuntimeType::point3d(), true, exec_state)
.map_err(|e| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"Expected an array of 3 numbers (i.e., a 3D point), found {}",
e.found
@ -366,7 +365,7 @@ fn array_to_point2d(
) -> Result<[TyF64; 2], KclError> {
val.coerce(&RuntimeType::point2d(), true, exec_state)
.map_err(|e| {
KclError::Semantic(KclErrorDetails::new(
KclError::new_semantic(KclErrorDetails::new(
format!(
"Expected an array of 2 numbers (i.e., a 2D point), found {}",
e.found
@ -535,7 +534,7 @@ pub async fn pattern_linear_2d(exec_state: &mut ExecState, args: Args) -> Result
let axis = axis.to_point2d();
if axis[0].n == 0.0 && axis[1].n == 0.0 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"The axis of the linear pattern cannot be the zero vector. Otherwise they will just duplicate in place."
.to_owned(),
vec![args.source_range],
@ -546,47 +545,6 @@ pub async fn pattern_linear_2d(exec_state: &mut ExecState, args: Args) -> Result
Ok(sketches.into())
}
/// Repeat a 2-dimensional sketch along some dimension, with a dynamic amount
/// of distance between each repetition, some specified number of times.
///
/// ```no_run
/// /// Pattern using a named axis.
///
/// exampleSketch = startSketchOn(XZ)
/// |> circle(center = [0, 0], radius = 1)
/// |> patternLinear2d(
/// axis = X,
/// instances = 7,
/// distance = 4
/// )
///
/// example = extrude(exampleSketch, length = 1)
/// ```
///
/// ```no_run
/// /// Pattern using a raw axis.
///
/// exampleSketch = startSketchOn(XZ)
/// |> circle(center = [0, 0], radius = 1)
/// |> patternLinear2d(
/// axis = [1, 0],
/// instances = 7,
/// distance = 4
/// )
///
/// example = extrude(exampleSketch, length = 1)
/// ```
#[stdlib {
name = "patternLinear2d",
unlabeled_first = true,
args = {
sketches = { docs = "The sketch(es) to duplicate" },
instances = { docs = "The number of total instances. Must be greater than or equal to 1. This includes the original entity. For example, if instances is 2, there will be two copies -- the original, and one new copy. If instances is 1, this has no effect." },
distance = { docs = "Distance between each repetition. Also known as 'spacing'."},
axis = { docs = "The axis of the pattern. A 2D vector.", snippet_value_array = ["1", "0"] },
use_original = { docs = "If the target was sketched on an extrusion, setting this will use the original sketch as the target, not the entire joined solid. Defaults to false." },
}
}]
async fn inner_pattern_linear_2d(
sketches: Vec<Sketch>,
instances: u32,
@ -636,7 +594,7 @@ pub async fn pattern_linear_3d(exec_state: &mut ExecState, args: Args) -> Result
let axis = axis.to_point3d();
if axis[0].n == 0.0 && axis[1].n == 0.0 && axis[2].n == 0.0 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"The axis of the linear pattern cannot be the zero vector. Otherwise they will just duplicate in place."
.to_owned(),
vec![args.source_range],
@ -810,40 +768,6 @@ pub async fn pattern_circular_2d(exec_state: &mut ExecState, args: Args) -> Resu
Ok(sketches.into())
}
/// Repeat a 2-dimensional sketch some number of times along a partial or
/// complete circle some specified number of times. Each object may
/// additionally be rotated along the circle, ensuring orientation of the
/// solid with respect to the center of the circle is maintained.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [.5, 25])
/// |> line(end = [0, 5])
/// |> line(end = [-1, 0])
/// |> line(end = [0, -5])
/// |> close()
/// |> patternCircular2d(
/// center = [0, 0],
/// instances = 13,
/// arcDegrees = 360,
/// rotateDuplicates = true
/// )
///
/// example = extrude(exampleSketch, length = 1)
/// ```
#[stdlib {
name = "patternCircular2d",
unlabeled_first = true,
args = {
sketch_set = { docs = "Which sketch(es) to pattern" },
instances = { docs = "The number of total instances. Must be greater than or equal to 1. This includes the original entity. For example, if instances is 2, there will be two copies -- the original, and one new copy. If instances is 1, this has no effect."},
center = { docs = "The center about which to make the pattern. This is a 2D vector.", snippet_value_array = ["0", "0"]},
arc_degrees = { docs = "The arc angle (in degrees) to place the repetitions. Must be greater than 0. Defaults to 360."},
rotate_duplicates= { docs = "Whether or not to rotate the duplicates as they are copied. Defaults to true."},
use_original= { docs = "If the target was sketched on an extrusion, setting this will use the original sketch as the target, not the entire joined solid. Defaults to false."},
},
tags = ["sketch"]
}]
#[allow(clippy::too_many_arguments)]
async fn inner_pattern_circular_2d(
sketch_set: Vec<Sketch>,
@ -879,7 +803,7 @@ async fn inner_pattern_circular_2d(
.await?;
let Geometries::Sketches(new_sketches) = geometries else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Expected a vec of sketches".to_string(),
vec![args.source_range],
)));
@ -977,7 +901,7 @@ async fn inner_pattern_circular_3d(
.await?;
let Geometries::Solids(new_solids) = geometries else {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Expected a vec of solids".to_string(),
vec![args.source_range],
)));
@ -1002,7 +926,7 @@ async fn pattern_circular(
return Ok(Geometries::from(geometry));
}
RepetitionsNeeded::Invalid => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
MUST_HAVE_ONE_INSTANCE.to_owned(),
vec![args.source_range],
)));
@ -1047,7 +971,7 @@ async fn pattern_circular(
}
&mock_ids
} else {
return Err(KclError::Engine(KclErrorDetails::new(
return Err(KclError::new_engine(KclErrorDetails::new(
format!("EntityCircularPattern response was not as expected: {:?}", resp),
vec![args.source_range],
)));

View File

@ -75,7 +75,7 @@ async fn inner_revolve(
// We don't use validate() here because we want to return a specific error message that is
// nice and we use the other data in the docs, so we still need use the derive above for the json schema.
if !(-360.0..=360.0).contains(&angle) || angle == 0.0 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("Expected angle to be between -360 and 360 and not 0, found `{}`", angle),
vec![args.source_range],
)));
@ -87,7 +87,7 @@ async fn inner_revolve(
// We don't use validate() here because we want to return a specific error message that is
// nice and we use the other data in the docs, so we still need use the derive above for the json schema.
if !(-360.0..=360.0).contains(&bidirectional_angle) || bidirectional_angle == 0.0 {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Expected bidirectional angle to be between -360 and 360 and not 0, found `{}`",
bidirectional_angle
@ -99,7 +99,7 @@ async fn inner_revolve(
if let Some(angle) = angle {
let ang = angle.signum() * bidirectional_angle + angle;
if !(-360.0..=360.0).contains(&ang) {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Combined angle and bidirectional must be between -360 and 360, found '{}'",
ang
@ -111,7 +111,7 @@ async fn inner_revolve(
}
if symmetric.unwrap_or(false) && bidirectional_angle.is_some() {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
.to_owned(),
vec![args.source_range],

View File

@ -1,7 +1,6 @@
//! Functions related to line segments.
use anyhow::Result;
use kcl_derive_docs::stdlib;
use kittycad_modeling_cmds::shared::Angle;
use super::utils::untype_point;
@ -22,43 +21,10 @@ pub async fn segment_end(exec_state: &mut ExecState, args: Args) -> Result<KclVa
args.make_kcl_val_from_point([pt[0].n, pt[1].n], pt[0].ty.clone())
}
/// Compute the ending point of the provided line segment.
///
/// ```no_run
/// w = 15
/// cube = startSketchOn(XY)
/// |> startProfile(at = [0, 0])
/// |> line(end = [w, 0], tag = $line1)
/// |> line(end = [0, w], tag = $line2)
/// |> line(end = [-w, 0], tag = $line3)
/// |> line(end = [0, -w], tag = $line4)
/// |> close()
/// |> extrude(length = 5)
///
/// fn cylinder(radius, tag) {
/// return startSketchOn(XY)
/// |> startProfile(at = [0, 0])
/// |> circle(radius = radius, center = segEnd(tag) )
/// |> extrude(length = radius)
/// }
///
/// cylinder(radius = 1, tag = line1)
/// cylinder(radius = 2, tag = line2)
/// cylinder(radius = 3, tag = line3)
/// cylinder(radius = 4, tag = line4)
/// ```
#[stdlib {
name = "segEnd",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_end(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<[TyF64; 2], KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -78,31 +44,10 @@ pub async fn segment_end_x(exec_state: &mut ExecState, args: Args) -> Result<Kcl
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Compute the ending point of the provided line segment along the 'x' axis.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [20, 0], tag = $thing)
/// |> line(end = [0, 5])
/// |> line(end = [segEndX(thing), 0])
/// |> line(end = [-20, 10])
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "segEndX",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_end_x(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<TyF64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -119,32 +64,10 @@ pub async fn segment_end_y(exec_state: &mut ExecState, args: Args) -> Result<Kcl
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Compute the ending point of the provided line segment along the 'y' axis.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [20, 0])
/// |> line(end = [0, 3], tag = $thing)
/// |> line(end = [-10, 0])
/// |> line(end = [0, segEndY(thing)])
/// |> line(end = [-10, 0])
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "segEndY",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_end_y(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<TyF64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -161,43 +84,10 @@ pub async fn segment_start(exec_state: &mut ExecState, args: Args) -> Result<Kcl
args.make_kcl_val_from_point([pt[0].n, pt[1].n], pt[0].ty.clone())
}
/// Compute the starting point of the provided line segment.
///
/// ```no_run
/// w = 15
/// cube = startSketchOn(XY)
/// |> startProfile(at = [0, 0])
/// |> line(end = [w, 0], tag = $line1)
/// |> line(end = [0, w], tag = $line2)
/// |> line(end = [-w, 0], tag = $line3)
/// |> line(end = [0, -w], tag = $line4)
/// |> close()
/// |> extrude(length = 5)
///
/// fn cylinder(radius, tag) {
/// return startSketchOn(XY)
/// |> startProfile(at = [0, 0])
/// |> circle( radius = radius, center = segStart(tag) )
/// |> extrude(length = radius)
/// }
///
/// cylinder(radius = 1, tag = line1)
/// cylinder(radius = 2, tag = line2)
/// cylinder(radius = 3, tag = line3)
/// cylinder(radius = 4, tag = line4)
/// ```
#[stdlib {
name = "segStart",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_start(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<[TyF64; 2], KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -217,31 +107,10 @@ pub async fn segment_start_x(exec_state: &mut ExecState, args: Args) -> Result<K
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Compute the starting point of the provided line segment along the 'x' axis.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [20, 0], tag = $thing)
/// |> line(end = [0, 5])
/// |> line(end = [20 - segStartX(thing), 0])
/// |> line(end = [-20, 10])
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "segStartX",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_start_x(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<TyF64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -258,32 +127,10 @@ pub async fn segment_start_y(exec_state: &mut ExecState, args: Args) -> Result<K
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Compute the starting point of the provided line segment along the 'y' axis.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [20, 0])
/// |> line(end = [0, 3], tag = $thing)
/// |> line(end = [-10, 0])
/// |> line(end = [0, 20-segStartY(thing)])
/// |> line(end = [-10, 0])
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "segStartY",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_start_y(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<TyF64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -300,34 +147,12 @@ pub async fn last_segment_x(exec_state: &mut ExecState, args: Args) -> Result<Kc
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Extract the 'x' axis value of the last line segment in the provided 2-d
/// sketch.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [5, 0])
/// |> line(end = [20, 5])
/// |> line(end = [lastSegX(%), 0])
/// |> line(end = [-15, 0])
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "lastSegX",
unlabeled_first = true,
args = {
sketch = { docs = "The sketch whose line segment is being queried"},
},
tags = ["sketch"]
}]
fn inner_last_segment_x(sketch: Sketch, args: Args) -> Result<TyF64, KclError> {
let last_line = sketch
.paths
.last()
.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a Sketch with at least one segment, found `{:?}`", sketch),
vec![args.source_range],
))
@ -346,34 +171,12 @@ pub async fn last_segment_y(exec_state: &mut ExecState, args: Args) -> Result<Kc
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Extract the 'y' axis value of the last line segment in the provided 2-d
/// sketch.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [5, 0])
/// |> line(end = [20, 5])
/// |> line(end = [0, lastSegY(%)])
/// |> line(end = [-15, 0])
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "lastSegY",
unlabeled_first = true,
args = {
sketch = { docs = "The sketch whose line segment is being queried"},
},
tags = ["sketch"]
}]
fn inner_last_segment_y(sketch: Sketch, args: Args) -> Result<TyF64, KclError> {
let last_line = sketch
.paths
.last()
.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a Sketch with at least one segment, found `{:?}`", sketch),
vec![args.source_range],
))
@ -390,37 +193,10 @@ pub async fn segment_length(exec_state: &mut ExecState, args: Args) -> Result<Kc
Ok(args.make_user_val_from_f64_with_type(result))
}
/// Compute the length of the provided line segment.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> angledLine(
/// angle = 60,
/// length = 10,
/// tag = $thing,
/// )
/// |> tangentialArc(angle = -120, radius = 5)
/// |> angledLine(
/// angle = -60,
/// length = segLen(thing),
/// )
/// |> close()
///
/// example = extrude(exampleSketch, length = 5)
/// ```
#[stdlib {
name = "segLen",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_length(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<TyF64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -437,33 +213,10 @@ pub async fn segment_angle(exec_state: &mut ExecState, args: Args) -> Result<Kcl
Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, NumericType::degrees())))
}
/// Compute the angle (in degrees) of the provided line segment.
///
/// ```no_run
/// exampleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [10, 0])
/// |> line(end = [5, 10], tag = $seg01)
/// |> line(end = [-10, 0])
/// |> angledLine(angle = segAng(seg01), length = 10)
/// |> line(end = [-10, 0])
/// |> angledLine(angle = segAng(seg01), length = -15)
/// |> close()
///
/// example = extrude(exampleSketch, length = 4)
/// ```
#[stdlib {
name = "segAng",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
fn inner_segment_angle(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<f64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))
@ -482,89 +235,10 @@ pub async fn tangent_to_end(exec_state: &mut ExecState, args: Args) -> Result<Kc
Ok(args.make_user_val_from_f64_with_type(TyF64::new(result, NumericType::degrees())))
}
/// Returns the angle coming out of the end of the segment in degrees.
///
/// ```no_run
/// // Horizontal pill.
/// pillSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [20, 0])
/// |> tangentialArc(end = [0, 10], tag = $arc1)
/// |> angledLine(
/// angle = tangentToEnd(arc1),
/// length = 20,
/// )
/// |> tangentialArc(end = [0, -10])
/// |> close()
///
/// pillExtrude = extrude(pillSketch, length = 10)
/// ```
///
/// ```no_run
/// // Vertical pill. Use absolute coordinate for arc.
/// pillSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [0, 20])
/// |> tangentialArc(endAbsolute = [10, 20], tag = $arc1)
/// |> angledLine(
/// angle = tangentToEnd(arc1),
/// length = 20,
/// )
/// |> tangentialArc(end = [-10, 0])
/// |> close()
///
/// pillExtrude = extrude(pillSketch, length = 10)
/// ```
///
/// ```no_run
/// rectangleSketch = startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
/// |> line(end = [10, 0], tag = $seg1)
/// |> angledLine(
/// angle = tangentToEnd(seg1),
/// length = 10,
/// )
/// |> line(end = [0, 10])
/// |> line(end = [-20, 0])
/// |> close()
///
/// rectangleExtrude = extrude(rectangleSketch, length = 10)
/// ```
///
/// ```no_run
/// bottom = startSketchOn(XY)
/// |> startProfile(at = [0, 0])
/// |> arc(
/// endAbsolute = [10, 10],
/// interiorAbsolute = [5, 1],
/// tag = $arc1,
/// )
/// |> angledLine(angle = tangentToEnd(arc1), length = 20)
/// |> close()
/// ```
///
/// ```no_run
/// circSketch = startSketchOn(XY)
/// |> circle( center= [0, 0], radius= 3 , tag= $circ)
///
/// triangleSketch = startSketchOn(XY)
/// |> startProfile(at = [-5, 0])
/// |> angledLine(angle = tangentToEnd(circ), length = 10)
/// |> line(end = [-15, 0])
/// |> close()
/// ```
#[stdlib {
name = "tangentToEnd",
unlabeled_first = true,
args = {
tag = { docs = "The line segment being queried by its tag"},
},
tags = ["sketch"]
}]
async fn inner_tangent_to_end(tag: &TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<f64, KclError> {
let line = args.get_tag_engine_info(exec_state, tag)?;
let path = line.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected a line segment with a path, found `{:?}`", line),
vec![args.source_range],
))

View File

@ -1,7 +1,6 @@
//! Standard library shapes.
use anyhow::Result;
use kcl_derive_docs::stdlib;
use kcmc::{
each_cmd as mcmd,
length_unit::LengthUnit,
@ -143,26 +142,6 @@ pub async fn circle_three_point(exec_state: &mut ExecState, args: Args) -> Resul
})
}
/// Construct a circle derived from 3 points.
///
/// ```no_run
/// exampleSketch = startSketchOn(XY)
/// |> circleThreePoint(p1 = [10,10], p2 = [20,8], p3 = [15,5])
/// |> extrude(length = 5)
/// ```
#[stdlib {
name = "circleThreePoint",
unlabeled_first = true,
args = {
sketch_surface_or_group = {docs = "Plane or surface to sketch on."},
p1 = {docs = "1st point to derive the circle."},
p2 = {docs = "2nd point to derive the circle."},
p3 = {docs = "3rd point to derive the circle."},
tag = {docs = "Identifier for the circle to reference elsewhere."},
},
tags = ["sketch"]
}]
// Similar to inner_circle, but needs to retain 3-point information in the
// path so it can be used for other features, otherwise it's lost.
async fn inner_circle_three_point(
@ -281,44 +260,6 @@ pub async fn polygon(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
})
}
/// Create a regular polygon with the specified number of sides that is either inscribed or circumscribed around a circle of the specified radius.
///
/// ```no_run
/// // Create a regular hexagon inscribed in a circle of radius 10
/// hex = startSketchOn(XY)
/// |> polygon(
/// radius = 10,
/// numSides = 6,
/// center = [0, 0],
/// inscribed = true,
/// )
///
/// example = extrude(hex, length = 5)
/// ```
///
/// ```no_run
/// // Create a square circumscribed around a circle of radius 5
/// square = startSketchOn(XY)
/// |> polygon(
/// radius = 5.0,
/// numSides = 4,
/// center = [10, 10],
/// inscribed = false,
/// )
/// example = extrude(square, length = 5)
/// ```
#[stdlib {
name = "polygon",
unlabeled_first = true,
args = {
sketch_surface_or_group = { docs = "Plane or surface to sketch on" },
radius = { docs = "The radius of the polygon", include_in_snippet = true },
num_sides = { docs = "The number of sides in the polygon", include_in_snippet = true },
center = { docs = "The center point of the polygon", snippet_value_array = ["0", "0"] },
inscribed = { docs = "Whether the polygon is inscribed (true, the default) or circumscribed (false) about a circle with the specified radius" },
},
tags = ["sketch"]
}]
#[allow(clippy::too_many_arguments)]
async fn inner_polygon(
sketch_surface_or_group: SketchOrSurface,
@ -330,14 +271,14 @@ async fn inner_polygon(
args: Args,
) -> Result<Sketch, KclError> {
if num_sides < 3 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Polygon must have at least 3 sides".to_string(),
vec![args.source_range],
)));
}
if radius.n <= 0.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Radius must be greater than 0".to_string(),
vec![args.source_range],
)));
@ -466,11 +407,11 @@ pub(crate) fn get_radius(
match (radius, diameter) {
(Some(radius), None) => Ok(radius),
(None, Some(diameter)) => Ok(TyF64::new(diameter.n / 2.0, diameter.ty)),
(None, None) => Err(KclError::Type(KclErrorDetails::new(
(None, None) => Err(KclError::new_type(KclErrorDetails::new(
"This function needs either `diameter` or `radius`".to_string(),
vec![source_range],
))),
(Some(_), Some(_)) => Err(KclError::Type(KclErrorDetails::new(
(Some(_), Some(_)) => Err(KclError::new_type(KclErrorDetails::new(
"You cannot specify both `diameter` and `radius`, please remove one".to_string(),
vec![source_range],
))),

View File

@ -36,14 +36,14 @@ async fn inner_shell(
args: Args,
) -> Result<Vec<Solid>, KclError> {
if faces.is_empty() {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"You must shell at least one face".to_owned(),
vec![args.source_range],
)));
}
if solids.is_empty() {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"You must shell at least one solid".to_owned(),
vec![args.source_range],
)));
@ -63,7 +63,7 @@ async fn inner_shell(
}
if face_ids.is_empty() {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Expected at least one valid face".to_owned(),
vec![args.source_range],
)));
@ -72,7 +72,7 @@ async fn inner_shell(
// Make sure all the solids have the same id, as we are going to shell them all at
// once.
if !solids.iter().all(|eg| eg.id == solids[0].id) {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"All solids stem from the same root object, like multiple sketch on face extrusions, etc.".to_owned(),
vec![args.source_range],
)));

View File

@ -12,6 +12,7 @@ use parse_display::{Display, FromStr};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::shapes::get_radius;
#[cfg(feature = "artifact-graph")]
use crate::execution::{Artifact, ArtifactId, CodeRef, StartSketchOnFace, StartSketchOnPlane};
use crate::{
@ -32,8 +33,6 @@ use crate::{
},
};
use super::shapes::get_radius;
/// A tag for a face.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
@ -66,13 +65,13 @@ impl FaceTag {
match self {
FaceTag::Tag(ref t) => args.get_adjacent_face_to_tag(exec_state, t, must_be_planar).await,
FaceTag::StartOrEnd(StartOrEnd::Start) => solid.start_cap_id.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
"Expected a start face".to_string(),
vec![args.source_range],
))
}),
FaceTag::StartOrEnd(StartOrEnd::End) => solid.end_cap_id.ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
"Expected an end face".to_string(),
vec![args.source_range],
))
@ -329,7 +328,7 @@ async fn straight_line(
let from = sketch.current_pen_position()?;
let (point, is_absolute) = match (end_absolute, end) {
(Some(_), Some(_)) => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"You cannot give both `end` and `endAbsolute` params, you have to choose one or the other".to_owned(),
vec![args.source_range],
)));
@ -337,7 +336,7 @@ async fn straight_line(
(Some(end_absolute), None) => (end_absolute, true),
(None, Some(end)) => (end, false),
(None, None) => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("You must supply either `{relative_name}` or `endAbsolute` arguments"),
vec![args.source_range],
)));
@ -604,7 +603,7 @@ async fn inner_angled_line(
.filter(|x| x.is_some())
.count();
if options_given > 1 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
" one of `length`, `lengthX`, `lengthY`, `endAbsoluteX`, `endAbsoluteY` can be given".to_string(),
vec![args.source_range],
)));
@ -632,11 +631,11 @@ async fn inner_angled_line(
(None, None, None, None, Some(end_absolute_y)) => {
inner_angled_line_to_y(angle_degrees, end_absolute_y, sketch, tag, exec_state, args).await
}
(None, None, None, None, None) => Err(KclError::Type(KclErrorDetails::new(
(None, None, None, None, None) => Err(KclError::new_type(KclErrorDetails::new(
"One of `length`, `lengthX`, `lengthY`, `endAbsoluteX`, `endAbsoluteY` must be given".to_string(),
vec![args.source_range],
))),
_ => Err(KclError::Type(KclErrorDetails::new(
_ => Err(KclError::new_type(KclErrorDetails::new(
"Only One of `length`, `lengthX`, `lengthY`, `endAbsoluteX`, `endAbsoluteY` can be given".to_owned(),
vec![args.source_range],
))),
@ -710,14 +709,14 @@ async fn inner_angled_line_of_x_length(
args: Args,
) -> Result<Sketch, KclError> {
if angle_degrees.abs() == 270.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have an x constrained angle of 270 degrees".to_string(),
vec![args.source_range],
)));
}
if angle_degrees.abs() == 90.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have an x constrained angle of 90 degrees".to_string(),
vec![args.source_range],
)));
@ -742,14 +741,14 @@ async fn inner_angled_line_to_x(
let from = sketch.current_pen_position()?;
if angle_degrees.abs() == 270.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have an x constrained angle of 270 degrees".to_string(),
vec![args.source_range],
)));
}
if angle_degrees.abs() == 90.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have an x constrained angle of 90 degrees".to_string(),
vec![args.source_range],
)));
@ -777,14 +776,14 @@ async fn inner_angled_line_of_y_length(
args: Args,
) -> Result<Sketch, KclError> {
if angle_degrees.abs() == 0.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have a y constrained angle of 0 degrees".to_string(),
vec![args.source_range],
)));
}
if angle_degrees.abs() == 180.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have a y constrained angle of 180 degrees".to_string(),
vec![args.source_range],
)));
@ -809,14 +808,14 @@ async fn inner_angled_line_to_y(
let from = sketch.current_pen_position()?;
if angle_degrees.abs() == 0.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have a y constrained angle of 0 degrees".to_string(),
vec![args.source_range],
)));
}
if angle_degrees.abs() == 180.0 {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Cannot have a y constrained angle of 180 degrees".to_string(),
vec![args.source_range],
)));
@ -893,7 +892,7 @@ pub async fn inner_angled_line_that_intersects(
) -> Result<Sketch, KclError> {
let intersect_path = args.get_tag_engine_info(exec_state, &intersect_tag)?;
let path = intersect_path.path.clone().ok_or_else(|| {
KclError::Type(KclErrorDetails::new(
KclError::new_type(KclErrorDetails::new(
format!("Expected an intersect path with a path, found `{:?}`", intersect_path),
vec![args.source_range],
))
@ -1170,7 +1169,7 @@ async fn inner_start_sketch_on(
SketchData::Plane(plane) => {
if plane.value == crate::exec::PlaneType::Uninit {
if plane.info.origin.units == UnitLen::Unknown {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"Origin of plane has unknown units".to_string(),
vec![args.source_range],
)));
@ -1194,7 +1193,7 @@ async fn inner_start_sketch_on(
}
SketchData::Solid(solid) => {
let Some(tag) = face else {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Expected a tag for the face to sketch on".to_string(),
vec![args.source_range],
)));
@ -1544,6 +1543,11 @@ pub async fn close(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
/// Construct a line segment from the current origin back to the profile's
/// origin, ensuring the resulting 2-dimensional sketch is not open-ended.
///
/// If you want to perform some 3-dimensional operation on a sketch, like
/// extrude or sweep, you must `close` it first. `close` must be called even
/// if the end point of the last segment is coincident with the sketch
/// starting point.
///
/// ```no_run
/// startSketchOn(XZ)
/// |> startProfile(at = [0, 0])
@ -1713,7 +1717,7 @@ pub(crate) async fn inner_arc(
absolute_arc(&args, id, exec_state, sketch, from, interior_absolute, end_absolute, tag).await
}
_ => {
Err(KclError::Type(KclErrorDetails::new(
Err(KclError::new_type(KclErrorDetails::new(
"Invalid combination of arguments. Either provide (angleStart, angleEnd, radius) or (endAbsolute, interiorAbsolute)".to_owned(),
vec![args.source_range],
)))
@ -1800,7 +1804,7 @@ pub async fn relative_arc(
let radius = radius.to_length_units(from.units);
let (center, end) = arc_center_and_end(from.ignore_units(), a_start, a_end, radius);
if a_start == a_end {
return Err(KclError::Type(KclErrorDetails::new(
return Err(KclError::new_type(KclErrorDetails::new(
"Arc start and end angles must be different".to_string(),
vec![args.source_range],
)));
@ -1968,11 +1972,11 @@ async fn inner_tangential_arc(
let data = TangentialArcData::RadiusAndOffset { radius, offset: angle };
inner_tangential_arc_radius_angle(data, sketch, tag, exec_state, args).await
}
(Some(_), Some(_), None, None, None) => Err(KclError::Semantic(KclErrorDetails::new(
(Some(_), Some(_), None, None, None) => Err(KclError::new_semantic(KclErrorDetails::new(
"You cannot give both `end` and `endAbsolute` params, you have to choose one or the other".to_owned(),
vec![args.source_range],
))),
(_, _, _, _, _) => Err(KclError::Semantic(KclErrorDetails::new(
(_, _, _, _, _) => Err(KclError::new_semantic(KclErrorDetails::new(
"You must supply `end`, `endAbsolute`, or both `angle` and `radius`/`diameter` arguments".to_owned(),
vec![args.source_range],
))),
@ -2126,13 +2130,13 @@ async fn inner_tangential_arc_to_point(
});
if result.center[0].is_infinite() {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"could not sketch tangential arc, because its center would be infinitely far away in the X direction"
.to_owned(),
vec![args.source_range],
)));
} else if result.center[1].is_infinite() {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"could not sketch tangential arc, because its center would be infinitely far away in the Y direction"
.to_owned(),
vec![args.source_range],
@ -2310,7 +2314,7 @@ async fn inner_bezier_curve(
to
}
_ => {
return Err(KclError::Semantic(KclErrorDetails::new(
return Err(KclError::new_semantic(KclErrorDetails::new(
"You must either give `control1`, `control2` and `end`, or `control1Absolute`, `control2Absolute` and `endAbsolute`.".to_owned(),
vec![args.source_range],
)));

View File

@ -1,7 +1,6 @@
//! Standard library sweep.
use anyhow::Result;
use kcl_derive_docs::stdlib;
use kcmc::{each_cmd as mcmd, length_unit::LengthUnit, ModelingCmd};
use kittycad_modeling_cmds::{self as kcmc, shared::RelativeTo};
use schemars::JsonSchema;
@ -56,122 +55,6 @@ pub async fn sweep(exec_state: &mut ExecState, args: Args) -> Result<KclValue, K
Ok(value.into())
}
/// Extrude a sketch along a path.
///
/// This, like extrude, is able to create a 3-dimensional solid from a
/// 2-dimensional sketch. However, unlike extrude, this creates a solid
/// by using the extent of the sketch as its path. This is useful for
/// creating more complex shapes that can't be created with a simple
/// extrusion.
///
/// You can provide more than one sketch to sweep, and they will all be
/// swept along the same path.
///
/// ```no_run
/// // Create a pipe using a sweep.
///
/// // Create a path for the sweep.
/// sweepPath = startSketchOn(XZ)
/// |> startProfile(at = [0.05, 0.05])
/// |> line(end = [0, 7])
/// |> tangentialArc(angle = 90, radius = 5)
/// |> line(end = [-3, 0])
/// |> tangentialArc(angle = -90, radius = 5)
/// |> line(end = [0, 7])
///
/// // Create a hole for the pipe.
/// pipeHole = startSketchOn(XY)
/// |> circle(
/// center = [0, 0],
/// radius = 1.5,
/// )
///
/// sweepSketch = startSketchOn(XY)
/// |> circle(
/// center = [0, 0],
/// radius = 2,
/// )
/// |> subtract2d(tool = pipeHole)
/// |> sweep(path = sweepPath)
/// ```
///
/// ```no_run
/// // Create a spring by sweeping around a helix path.
///
/// // Create a helix around the Z axis.
/// helixPath = helix(
/// angleStart = 0,
/// ccw = true,
/// revolutions = 4,
/// length = 10,
/// radius = 5,
/// axis = Z,
/// )
///
///
/// // Create a spring by sweeping around the helix path.
/// springSketch = startSketchOn(XZ)
/// |> circle( center = [5, 0], radius = 1)
/// |> sweep(path = helixPath)
/// ```
///
/// ```no_run
/// // Sweep two sketches along the same path.
///
/// sketch001 = startSketchOn(XY)
/// rectangleSketch = startProfile(sketch001, at = [-200, 23.86])
/// |> angledLine(angle = 0, length = 73.47, tag = $rectangleSegmentA001)
/// |> angledLine(
/// angle = segAng(rectangleSegmentA001) - 90,
/// length = 50.61,
/// )
/// |> angledLine(
/// angle = segAng(rectangleSegmentA001),
/// length = -segLen(rectangleSegmentA001),
/// )
/// |> line(endAbsolute = [profileStartX(%), profileStartY(%)])
/// |> close()
///
/// circleSketch = circle(sketch001, center = [200, -30.29], radius = 32.63)
///
/// sketch002 = startSketchOn(YZ)
/// sweepPath = startProfile(sketch002, at = [0, 0])
/// |> yLine(length = 231.81)
/// |> tangentialArc(radius = 80, angle = -90)
/// |> xLine(length = 384.93)
///
/// sweep([rectangleSketch, circleSketch], path = sweepPath)
/// ```
/// ```
/// // Sectionally sweep one sketch along the path
///
/// sketch001 = startSketchOn(XY)
/// circleSketch = circle(sketch001, center = [200, -30.29], radius = 32.63)
///
/// sketch002 = startSketchOn(YZ)
/// sweepPath = startProfile(sketch002, at = [0, 0])
/// |> yLine(length = 231.81)
/// |> tangentialArc(radius = 80, angle = -90)
/// |> xLine(length = 384.93)
///
/// sweep(circleSketch, path = sweepPath, sectional = true)
/// ```
#[stdlib {
name = "sweep",
feature_tree_operation = true,
unlabeled_first = true,
args = {
sketches = { docs = "The sketch or set of sketches that should be swept in space" },
path = { docs = "The path to sweep the sketch along" },
sectional = { docs = "If true, the sweep will be broken up into sub-sweeps (extrusions, revolves, sweeps) based on the trajectory path components." },
tolerance = { docs = "Tolerance for this operation" },
relative_to = { docs = "What is the sweep relative to? Can be either 'sketchPlane' or 'trajectoryCurve'. Defaults to trajectoryCurve."},
tag_start = { docs = "A named tag for the face at the start of the sweep, i.e. the original sketch" },
tag_end = { docs = "A named tag for the face at the end of the sweep" },
},
tags = ["sketch"]
}]
#[allow(clippy::too_many_arguments)]
async fn inner_sweep(
sketches: Vec<Sketch>,
@ -192,7 +75,7 @@ async fn inner_sweep(
Some("sketchPlane") => RelativeTo::SketchPlane,
Some("trajectoryCurve") | None => RelativeTo::TrajectoryCurve,
Some(_) => {
return Err(KclError::Syntax(crate::errors::KclErrorDetails::new(
return Err(KclError::new_syntax(crate::errors::KclErrorDetails::new(
"If you provide relativeTo, it must either be 'sketchPlane' or 'trajectoryCurve'".to_owned(),
vec![args.source_range],
)))

Some files were not shown because too many files have changed in this diff Show More