Compare commits

...

13 Commits

Author SHA1 Message Date
655705d3f3 Remove enums that only existed for optional tags 2023-11-20 11:20:13 -06:00
6afacd7427 KCL optional parameters (#1087)
Part of https://github.com/KittyCAD/modeling-app/issues/1006#issuecomment-1816978586

This adds support for optional parameters to the AST. They are declared with a ? suffix, e.g. `(x, tag?) => {...}`.

This PR does not actually _use_ these optional parameters anywhere. In particular, it does not change the KCL stdlib or any existing function definitions. That will happen in a follow-up PR.
2023-11-20 11:19:08 -06:00
957001ee88 Bump uuid from 1.5.0 to 1.6.0 in /src/wasm-lib (#1089)
Bumps [uuid](https://github.com/uuid-rs/uuid) from 1.5.0 to 1.6.0.
- [Release notes](https://github.com/uuid-rs/uuid/releases)
- [Commits](https://github.com/uuid-rs/uuid/compare/1.5.0...1.6.0)

---
updated-dependencies:
- dependency-name: uuid
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 11:17:04 -06:00
8b4cc306af Bump openapitor from 5ed477b to 9caff1f in /src/wasm-lib (#1085)
Bumps [openapitor](https://github.com/KittyCAD/kittycad.rs) from `5ed477b` to `9caff1f`.
- [Release notes](https://github.com/KittyCAD/kittycad.rs/releases)
- [Commits](5ed477b5c9...9caff1f4f0)

---
updated-dependencies:
- dependency-name: openapitor
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 11:16:33 -06:00
52d88171ca Bump kittycad from 0.2.41 to 0.2.42 in /src/wasm-lib (#1086)
Bumps [kittycad](https://github.com/KittyCAD/kittycad.rs) from 0.2.41 to 0.2.42.
- [Release notes](https://github.com/KittyCAD/kittycad.rs/releases)
- [Commits](https://github.com/KittyCAD/kittycad.rs/compare/v0.2.41...v0.2.42)

---
updated-dependencies:
- dependency-name: kittycad
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 11:16:18 -06:00
9142cf3af7 Bump databake from 0.1.6 to 0.1.7 in /src/wasm-lib (#1082)
Bumps [databake](https://github.com/unicode-org/icu4x) from 0.1.6 to 0.1.7.
- [Release notes](https://github.com/unicode-org/icu4x/releases)
- [Changelog](https://github.com/unicode-org/icu4x/blob/main/CHANGELOG.md)
- [Commits](https://github.com/unicode-org/icu4x/commits)

---
updated-dependencies:
- dependency-name: databake
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 11:16:01 -06:00
361500058c Bump tauri-plugin-fs-extra from b13d97c to 642a195 in /src-tauri (#1084)
Bumps [tauri-plugin-fs-extra](https://github.com/tauri-apps/plugins-workspace) from `b13d97c` to `642a195`.
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](b13d97c7c7...642a195d34)

---
updated-dependencies:
- dependency-name: tauri-plugin-fs-extra
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-17 11:00:43 -08:00
198479a71a Bump openapitor from 3afe554 to 5ed477b in /src/wasm-lib (#1080)
Bumps [openapitor](https://github.com/KittyCAD/kittycad.rs) from `3afe554` to `5ed477b`.
- [Release notes](https://github.com/KittyCAD/kittycad.rs/releases)
- [Commits](3afe554cf9...5ed477b5c9)

---
updated-dependencies:
- dependency-name: openapitor
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-17 11:00:04 -08:00
905784c1e5 Bump @vitest/coverage-istanbul from 0.34.1 to 0.34.6 (#1071)
Bumps [@vitest/coverage-istanbul](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-istanbul) from 0.34.1 to 0.34.6.
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v0.34.6/packages/coverage-istanbul)

---
updated-dependencies:
- dependency-name: "@vitest/coverage-istanbul"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-16 05:48:35 -05:00
c33aaad800 Release KCL 0.1.36 (#1078) 2023-11-15 17:50:08 +00:00
d175c75780 Bump schemars, itertools, add comments to crates (#1077)
Bump itertools, schemars, add comments to crates
2023-11-15 11:41:12 -06:00
ba348d1222 Bump openapitor from 1b2562f to 3afe554 in /src/wasm-lib (#1073)
Bumps [openapitor](https://github.com/KittyCAD/kittycad.rs) from `1b2562f` to `3afe554`.
- [Release notes](https://github.com/KittyCAD/kittycad.rs/releases)
- [Commits](1b2562f4b3...3afe554cf9)

---
updated-dependencies:
- dependency-name: openapitor
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-14 13:31:34 -08:00
1f49ddfc29 Bump tauri-plugin-fs-extra from 61e8625 to b13d97c in /src-tauri (#1072)
Bumps [tauri-plugin-fs-extra](https://github.com/tauri-apps/plugins-workspace) from `61e8625` to `b13d97c`.
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](61e862597e...b13d97c7c7)

---
updated-dependencies:
- dependency-name: tauri-plugin-fs-extra
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-14 13:31:25 -08:00
21 changed files with 498 additions and 380 deletions

View File

@ -112,7 +112,7 @@
"@types/wicg-file-system-access": "^2020.9.6",
"@types/ws": "^8.5.5",
"@vitejs/plugin-react": "^4.1.1",
"@vitest/coverage-istanbul": "^0.34.1",
"@vitest/coverage-istanbul": "^0.34.6",
"autoprefixer": "^10.4.13",
"eslint": "^8.53.0",
"eslint-config-react-app": "^7.0.1",

31
src-tauri/Cargo.lock generated
View File

@ -1913,6 +1913,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "minisign-verify"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "933dca44d65cdd53b355d0b73d380a2ff5da71f87f036053188bf1eab6a19881"
[[package]]
name = "miniz_oxide"
version = "0.6.2"
@ -3106,9 +3112,9 @@ dependencies = [
[[package]]
name = "schemars"
version = "0.8.15"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f7b0ce13155372a76ee2e1c5ffba1fe61ede73fbea5630d61eee6fac4929c0c"
checksum = "45a28f4c49489add4ce10783f7911893516f15afe45d015608d41faca6bc4d29"
dependencies = [
"bigdecimal",
"bytes",
@ -3123,9 +3129,9 @@ dependencies = [
[[package]]
name = "schemars_derive"
version = "0.8.15"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e85e2a16b12bdb763244c69ab79363d71db2b4b918a2def53f80b02e0574b13c"
checksum = "c767fd6fa65d9ccf9cf026122c1b555f2ef9a4f0cea69da4d7dbc3e258d30967"
dependencies = [
"proc-macro2",
"quote",
@ -3739,6 +3745,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bfe673cf125ef364d6f56b15e8ce7537d9ca7e4dae1cf6fbbdeed2e024db3d9"
dependencies = [
"anyhow",
"base64 0.21.2",
"bytes",
"cocoa",
"dirs-next",
@ -3752,6 +3759,7 @@ dependencies = [
"heck 0.4.1",
"http",
"ignore",
"minisign-verify",
"objc",
"once_cell",
"open",
@ -3776,12 +3784,14 @@ dependencies = [
"tauri-utils",
"tempfile",
"thiserror",
"time",
"tokio",
"url",
"uuid",
"webkit2gtk",
"webview2-com",
"windows 0.39.0",
"zip",
]
[[package]]
@ -3846,7 +3856,7 @@ dependencies = [
[[package]]
name = "tauri-plugin-fs-extra"
version = "0.0.0"
source = "git+https://github.com/tauri-apps/plugins-workspace?branch=v1#61e862597e7234ddca9d9c4b07700855841888f3"
source = "git+https://github.com/tauri-apps/plugins-workspace?branch=v1#642a195d34ec5bf6bbc780dde9c02fca33e1bd00"
dependencies = [
"log",
"serde",
@ -5002,3 +5012,14 @@ checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
[[package]]
name = "zip"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"
dependencies = [
"byteorder",
"crc32fast",
"crossbeam-utils",
]

View File

@ -169,16 +169,24 @@ describe('testing function declaration', () => {
end: 39,
params: [
{
type: 'Identifier',
start: 12,
end: 13,
name: 'a',
type: 'Parameter',
identifier: {
type: 'Identifier',
start: 12,
end: 13,
name: 'a',
},
optional: false,
},
{
type: 'Identifier',
start: 15,
end: 16,
name: 'b',
type: 'Parameter',
identifier: {
type: 'Identifier',
start: 15,
end: 16,
name: 'b',
},
optional: false,
},
],
body: {
@ -244,16 +252,24 @@ const myVar = funcN(1, 2)`
end: 37,
params: [
{
type: 'Identifier',
start: 12,
end: 13,
name: 'a',
type: 'Parameter',
identifier: {
type: 'Identifier',
start: 12,
end: 13,
name: 'a',
},
optional: false,
},
{
type: 'Identifier',
start: 15,
end: 16,
name: 'b',
type: 'Parameter',
identifier: {
type: 'Identifier',
start: 15,
end: 16,
name: 'b',
},
optional: false,
},
],
body: {

View File

@ -1,5 +1,5 @@
import { getNodePathFromSourceRange, getNodeFromPath } from './queryAst'
import { Identifier, parse, initPromise } from './wasm'
import { Identifier, parse, initPromise, Parameter } from './wasm'
beforeAll(() => initPromise)
@ -46,7 +46,7 @@ const b1 = cube([0,0], 10)`
const ast = parse(code)
const nodePath = getNodePathFromSourceRange(ast, sourceRange)
const node = getNodeFromPath<Identifier>(ast, nodePath).node
const node = getNodeFromPath<Parameter>(ast, nodePath).node
expect(nodePath).toEqual([
['body', ''],
@ -57,8 +57,8 @@ const b1 = cube([0,0], 10)`
['params', 'FunctionExpression'],
[0, 'index'],
])
expect(node.type).toBe('Identifier')
expect(node.name).toBe('pos')
expect(node.type).toBe('Parameter')
expect(node.identifier.name).toBe('pos')
})
it('gets path right for deep within function definition body', () => {
const code = `fn cube = (pos, scale) => {

View File

@ -247,10 +247,10 @@ function moreNodePathFromSourceRange(
if (_node.type === 'FunctionExpression' && isInRange) {
for (let i = 0; i < _node.params.length; i++) {
const param = _node.params[i]
if (param.start <= start && param.end >= end) {
if (param.identifier.start <= start && param.identifier.end >= end) {
path.push(['params', 'FunctionExpression'])
path.push([i, 'index'])
return moreNodePathFromSourceRange(param, sourceRange, path)
return moreNodePathFromSourceRange(param.identifier, sourceRange, path)
}
}
if (_node.body.start <= start && _node.body.end >= end) {

View File

@ -20,6 +20,7 @@ export type { ObjectExpression } from '../wasm-lib/kcl/bindings/ObjectExpression
export type { MemberExpression } from '../wasm-lib/kcl/bindings/MemberExpression'
export type { PipeExpression } from '../wasm-lib/kcl/bindings/PipeExpression'
export type { VariableDeclaration } from '../wasm-lib/kcl/bindings/VariableDeclaration'
export type { Parameter } from '../wasm-lib/kcl/bindings/Parameter'
export type { PipeSubstitution } from '../wasm-lib/kcl/bindings/PipeSubstitution'
export type { Identifier } from '../wasm-lib/kcl/bindings/Identifier'
export type { UnaryExpression } from '../wasm-lib/kcl/bindings/UnaryExpression'

View File

@ -683,21 +683,20 @@ checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308"
[[package]]
name = "databake"
version = "0.1.6"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "959b676312ba1aaafb2219c475560082e6b20c3bc572ec1483f93cecd748cf3d"
checksum = "82175d72e69414ceafbe2b49686794d3a8bed846e0d50267355f83ea8fdd953a"
dependencies = [
"databake-derive",
"proc-macro2",
"quote",
"syn 2.0.39",
]
[[package]]
name = "databake-derive"
version = "0.1.6"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0694dfe255f1af0289d3d1b40787bb955e8603d96e96a6b14b225926e108fb"
checksum = "377af281d8f23663862a7c84623bc5dcf7f8c44b13c7496a590bdc157f941a43"
dependencies = [
"proc-macro2",
"quote",
@ -1383,9 +1382,9 @@ dependencies = [
[[package]]
name = "itertools"
version = "0.11.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
checksum = "25db6b064527c5d482d0423354fcd07a89a2dfe07b67892e62411946db7f07b0"
dependencies = [
"either",
]
@ -1427,7 +1426,7 @@ dependencies = [
[[package]]
name = "kcl-lib"
version = "0.1.35"
version = "0.1.36"
dependencies = [
"anyhow",
"async-recursion",
@ -1441,7 +1440,7 @@ dependencies = [
"expectorate",
"futures",
"insta",
"itertools 0.11.0",
"itertools 0.12.0",
"js-sys",
"kittycad",
"lazy_static",
@ -1477,9 +1476,9 @@ dependencies = [
[[package]]
name = "kittycad"
version = "0.2.41"
version = "0.2.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "874914cd40bfd43674406683bb3f0924d41780698a4ade96f2e180a73678bdd1"
checksum = "6aa554d86b6dbbd976a659c912ae25ce817b4378eb12a5684907e263410f0a7b"
dependencies = [
"anyhow",
"async-trait",
@ -1784,7 +1783,7 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]
name = "openapitor"
version = "0.0.9"
source = "git+https://github.com/KittyCAD/kittycad.rs?branch=main#1b2562f4b3ecd26a3683c3fc48a0d33707097a36"
source = "git+https://github.com/KittyCAD/kittycad.rs?branch=main#9caff1f4f00c64632ff5a226251e3dc68210b455"
dependencies = [
"Inflector",
"anyhow",
@ -1954,7 +1953,7 @@ dependencies = [
"bincode",
"either",
"fnv",
"itertools 0.11.0",
"itertools 0.10.5",
"lazy_static",
"nom",
"quick-xml",
@ -2521,9 +2520,9 @@ dependencies = [
[[package]]
name = "schemars"
version = "0.8.15"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f7b0ce13155372a76ee2e1c5ffba1fe61ede73fbea5630d61eee6fac4929c0c"
checksum = "45a28f4c49489add4ce10783f7911893516f15afe45d015608d41faca6bc4d29"
dependencies = [
"bigdecimal",
"bytes",
@ -2538,9 +2537,9 @@ dependencies = [
[[package]]
name = "schemars_derive"
version = "0.8.15"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e85e2a16b12bdb763244c69ab79363d71db2b4b918a2def53f80b02e0574b13c"
checksum = "c767fd6fa65d9ccf9cf026122c1b555f2ef9a4f0cea69da4d7dbc3e258d30967"
dependencies = [
"proc-macro2",
"quote",
@ -3548,9 +3547,9 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]]
name = "uuid"
version = "1.5.0"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ad59a7560b41a70d191093a945f0b87bc1deeda46fb237479708a1d6b6cdfc"
checksum = "c58fe91d841bc04822c9801002db4ea904b9e4b8e6bbad25127b46eff8dc516b"
dependencies = [
"atomic",
"getrandom",

View File

@ -15,7 +15,7 @@ gloo-utils = "0.2.0"
kcl-lib = { path = "kcl" }
kittycad = { workspace = true }
serde_json = "1.0.108"
uuid = { version = "1.5.0", features = ["v4", "js", "serde"] }
uuid = { version = "1.6.0", features = ["v4", "js", "serde"] }
wasm-bindgen = "0.2.88"
wasm-bindgen-futures = "0.4.38"
@ -27,7 +27,7 @@ pretty_assertions = "1.4.0"
reqwest = { version = "0.11.22", default-features = false }
tokio = { version = "1.34.0", features = ["rt-multi-thread", "macros", "time"] }
twenty-twenty = "0.6.1"
uuid = { version = "1.5.0", features = ["v4", "js", "serde"] }
uuid = { version = "1.6.0", features = ["v4", "js", "serde"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
futures = "0.3.29"
@ -57,7 +57,7 @@ members = [
]
[workspace.dependencies]
kittycad = { version = "0.2.41", default-features = false, features = ["js"] }
kittycad = { version = "0.2.42", default-features = false, features = ["js"] }
[[test]]
name = "executor"

View File

@ -12,7 +12,7 @@ repository = "https://github.com/KittyCAD/modeling-app"
proc-macro = true
[dependencies]
databake = "0.1.6"
databake = "0.1.7"
kcl-lib = { path = "../kcl" }
proc-macro2 = "1"
quote = "1"

View File

@ -1,3 +1,4 @@
//! This crate contains macros for parsing KCL at Rust compile-time.
use databake::*;
use proc_macro::TokenStream;
use quote::quote;

View File

@ -1,11 +1,13 @@
[package]
name = "kcl-lib"
description = "KittyCAD Language"
version = "0.1.35"
description = "KittyCAD Language implementation and tools"
version = "0.1.36"
edition = "2021"
license = "MIT"
repository = "https://github.com/KittyCAD/modeling-app"
rust-version = "1.73"
authors = ["Jess Frazelle", "Adam Chalmers", "KittyCAD, Inc"]
keywords = ["kcl", "KittyCAD", "CAD"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -15,18 +17,18 @@ async-recursion = "1.0.5"
async-trait = "0.1.73"
clap = { version = "4.4.8", features = ["cargo", "derive", "env", "unicode"], optional = true }
dashmap = "5.5.3"
databake = { version = "0.1.6", features = ["derive"] }
databake = { version = "0.1.7", features = ["derive"] }
derive-docs = { version = "0.1.4" }
#derive-docs = { path = "../derive-docs" }
kittycad = { workspace = true }
lazy_static = "1.4.0"
parse-display = "0.8.2"
schemars = { version = "0.8", features = ["impl_json_schema", "url", "uuid1"] }
schemars = { version = "0.8.16", features = ["impl_json_schema", "url", "uuid1"] }
serde = { version = "1.0.192", features = ["derive"] }
serde_json = "1.0.108"
thiserror = "1.0.50"
ts-rs = { version = "7", package = "ts-rs-json-value", features = ["serde-json-impl", "schemars-impl", "uuid-impl"] }
uuid = { version = "1.5.0", features = ["v4", "js", "serde"] }
uuid = { version = "1.6.0", features = ["v4", "js", "serde"] }
winnow = "0.5.18"
[target.'cfg(target_arch = "wasm32")'.dependencies]
@ -60,7 +62,7 @@ debug = true # Flamegraphs of benchmarks require accurate debug symbols
criterion = "0.5.1"
expectorate = "1.1.0"
insta = { version = "1.34.0", features = ["json"] }
itertools = "0.11.0"
itertools = "0.12.0"
pretty_assertions = "1.4.0"
tokio = { version = "1.34.0", features = ["rt-multi-thread", "macros", "time"] }

View File

@ -221,11 +221,11 @@ impl Program {
if let Some(Value::FunctionExpression(ref mut function_expression)) = &mut value {
// Check if the params to the function expression contain the position.
for param in &mut function_expression.params {
let param_source_range: SourceRange = param.clone().into();
let param_source_range: SourceRange = (&param.identifier).into();
if param_source_range.contains(pos) {
let old_name = param.name.clone();
let old_name = param.identifier.name.clone();
// Rename the param.
param.rename(&old_name, new_name);
param.identifier.rename(&old_name, new_name);
// Now rename all the identifiers in the rest of the program.
function_expression.body.rename_identifiers(&old_name, new_name);
return;
@ -1014,7 +1014,11 @@ impl CallExpression {
// Add the arguments to the memory.
let mut fn_memory = memory.clone();
for (index, param) in function_expression.params.iter().enumerate() {
fn_memory.add(&param.name, fn_args.get(index).unwrap().clone(), param.into())?;
fn_memory.add(
&param.identifier.name,
fn_args.get(index).unwrap().clone(),
param.identifier.clone().into(),
)?;
}
// Call the stdlib function
@ -1249,10 +1253,10 @@ impl VariableDeclaration {
symbol_kind = SymbolKind::FUNCTION;
let mut children = vec![];
for param in &function_expression.params {
let param_source_range: SourceRange = param.into();
let param_source_range: SourceRange = (&param.identifier).into();
#[allow(deprecated)]
children.push(DocumentSymbol {
name: param.name.clone(),
name: param.identifier.name.clone(),
detail: None,
kind: SymbolKind::VARIABLE,
range: param_source_range.to_lsp_range(code),
@ -1442,7 +1446,7 @@ impl From<&Box<Literal>> for MemoryItem {
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Bake)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Bake, Eq)]
#[databake(path = kcl_lib::ast::types)]
#[ts(export)]
#[serde(tag = "type")]
@ -2621,6 +2625,18 @@ async fn execute_pipe_body(
}
}
/// Parameter of a KCL function.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Bake)]
#[databake(path = kcl_lib::ast::types)]
#[ts(export)]
#[serde(tag = "type")]
pub struct Parameter {
/// The parameter's label or name.
pub identifier: Identifier,
/// Is the parameter optional?
pub optional: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Bake)]
#[databake(path = kcl_lib::ast::types)]
#[ts(export)]
@ -2628,7 +2644,7 @@ async fn execute_pipe_body(
pub struct FunctionExpression {
pub start: usize,
pub end: usize,
pub params: Vec<Identifier>,
pub params: Vec<Parameter>,
pub body: Program,
}
@ -2654,7 +2670,7 @@ impl FunctionExpression {
"({}) => {{\n{}{}\n}}",
self.params
.iter()
.map(|param| param.name.clone())
.map(|param| param.identifier.name.clone())
.collect::<Vec<String>>()
.join(", "),
options.get_indentation(indentation_level + 1),

View File

@ -908,9 +908,9 @@ pub async fn execute(
// Add the arguments to the memory.
for (index, param) in function_expression.params.iter().enumerate() {
fn_memory.add(
&param.name,
&param.identifier.name,
args.get(index).unwrap().clone(),
param.into(),
(&param.identifier).into(),
)?;
}

View File

@ -1,3 +1,7 @@
//! Rust support for KCL (aka the KittyCAD Language).
//!
//! KCL is written in Rust. This crate contains the compiler tooling (e.g. parser, lexer, code generation),
//! the standard library implementation, a LSP implementation, generator for the docs, and more.
#![recursion_limit = "1024"]
pub mod ast;

View File

@ -12,7 +12,7 @@ use crate::{
ArrayExpression, BinaryExpression, BinaryOperator, BinaryPart, BodyItem, CallExpression, CommentStyle,
ExpressionStatement, FunctionExpression, Identifier, Literal, LiteralIdentifier, LiteralValue,
MemberExpression, MemberObject, NonCodeMeta, NonCodeNode, NonCodeValue, ObjectExpression, ObjectProperty,
PipeExpression, PipeSubstitution, Program, ReturnStatement, UnaryExpression, UnaryOperator, Value,
Parameter, PipeExpression, PipeSubstitution, Program, ReturnStatement, UnaryExpression, UnaryOperator, Value,
VariableDeclaration, VariableDeclarator, VariableKind,
},
errors::{KclError, KclErrorDetails},
@ -1208,26 +1208,62 @@ fn arguments(i: TokenSlice) -> PResult<Vec<Value>> {
.parse_next(i)
}
fn not_close_paren(i: TokenSlice) -> PResult<Token> {
fn required_param(i: TokenSlice) -> PResult<Token> {
any.verify(|token: &Token| !matches!(token.token_type, TokenType::Brace) || token.value != ")")
.parse_next(i)
}
fn optional_param(i: TokenSlice) -> PResult<Token> {
let token = required_param.parse_next(i)?;
let _question_mark = one_of(TokenType::QuestionMark).parse_next(i)?;
Ok(token)
}
/// Parameters are declared in a function signature, and used within a function.
fn parameters(i: TokenSlice) -> PResult<Vec<Identifier>> {
fn parameters(i: TokenSlice) -> PResult<Vec<Parameter>> {
// Get all tokens until the next ), because that ends the parameter list.
let candidates: Vec<Token> = separated(0.., not_close_paren, comma_sep)
.context(expected("function parameters"))
.parse_next(i)?;
let candidates: Vec<_> = separated(
0..,
alt((optional_param.map(|t| (t, true)), required_param.map(|t| (t, false)))),
comma_sep,
)
.context(expected("function parameters"))
.parse_next(i)?;
// Make sure all those tokens are valid parameters.
let params = candidates
let params: Vec<Parameter> = candidates
.into_iter()
.map(|token| Identifier::try_from(token).and_then(Identifier::into_valid_binding_name))
.map(|(token, optional)| {
let identifier = Identifier::try_from(token).and_then(Identifier::into_valid_binding_name)?;
Ok(Parameter { identifier, optional })
})
.collect::<Result<_, _>>()
.map_err(|e| ErrMode::Backtrack(ContextError::from(e)))?;
.map_err(|e: KclError| ErrMode::Backtrack(ContextError::from(e)))?;
// Make sure optional parameters are last.
if let Err(e) = optional_after_required(&params) {
return Err(ErrMode::Cut(ContextError::from(e)));
}
Ok(params)
}
fn optional_after_required(params: &[Parameter]) -> Result<(), KclError> {
let mut found_optional = false;
for p in params {
if p.optional {
found_optional = true;
}
if !p.optional && found_optional {
let e = KclError::Syntax(KclErrorDetails {
source_ranges: vec![(&p.identifier).into()],
message: "mandatory parameters must be declared before optional parameters".to_owned(),
});
return Err(e);
}
}
Ok(())
}
impl Identifier {
fn into_valid_binding_name(self) -> Result<Identifier, KclError> {
// Make sure they are not assigning a variable to a stdlib function.
@ -1895,7 +1931,7 @@ const mySk1 = startSketchAt([0, 0])"#;
let tokens = crate::token::lexer(input);
let actual = parameters.parse(&tokens);
assert!(actual.is_ok(), "could not parse test {i}");
let actual_ids: Vec<_> = actual.unwrap().into_iter().map(|id| id.name).collect();
let actual_ids: Vec<_> = actual.unwrap().into_iter().map(|p| p.identifier.name).collect();
assert_eq!(actual_ids, expected);
}
}
@ -2322,6 +2358,82 @@ e
assert!(result.err().unwrap().to_string().contains("Unexpected token"));
}
#[test]
fn test_optional_param_order() {
for (i, (params, expect_ok)) in [
(
vec![Parameter {
identifier: Identifier {
start: 0,
end: 0,
name: "a".to_owned(),
},
optional: true,
}],
true,
),
(
vec![Parameter {
identifier: Identifier {
start: 0,
end: 0,
name: "a".to_owned(),
},
optional: false,
}],
true,
),
(
vec![
Parameter {
identifier: Identifier {
start: 0,
end: 0,
name: "a".to_owned(),
},
optional: false,
},
Parameter {
identifier: Identifier {
start: 0,
end: 0,
name: "b".to_owned(),
},
optional: true,
},
],
true,
),
(
vec![
Parameter {
identifier: Identifier {
start: 0,
end: 0,
name: "a".to_owned(),
},
optional: true,
},
Parameter {
identifier: Identifier {
start: 0,
end: 0,
name: "b".to_owned(),
},
optional: false,
},
],
false,
),
]
.into_iter()
.enumerate()
{
let actual = optional_after_required(&params);
assert_eq!(actual.is_ok(), expect_ok, "failed test {i}");
}
}
#[test]
fn test_parse_expand_array() {
let code = "const myArray = [0..10]";
@ -2801,4 +2913,5 @@ mod snapshot_tests {
snapshot_test!(ar, r#"5 + "a""#);
snapshot_test!(at, "line([0, l], %)");
snapshot_test!(au, include_str!("../../../tests/executor/inputs/cylinder.kcl"));
snapshot_test!(av, "fn f = (angle?) => { return default(angle, 360) }");
}

View File

@ -29,10 +29,13 @@ expression: actual
"end": 49,
"params": [
{
"type": "Identifier",
"start": 12,
"end": 17,
"name": "param"
"identifier": {
"type": "Identifier",
"start": 12,
"end": 17,
"name": "param"
},
"optional": false
}
],
"body": {

View File

@ -0,0 +1,97 @@
---
source: kcl/src/parser/parser_impl.rs
expression: actual
---
{
"start": 0,
"end": 49,
"body": [
{
"type": "VariableDeclaration",
"type": "VariableDeclaration",
"start": 0,
"end": 49,
"declarations": [
{
"type": "VariableDeclarator",
"start": 3,
"end": 49,
"id": {
"type": "Identifier",
"start": 3,
"end": 4,
"name": "f"
},
"init": {
"type": "FunctionExpression",
"type": "FunctionExpression",
"start": 7,
"end": 49,
"params": [
{
"identifier": {
"type": "Identifier",
"start": 8,
"end": 13,
"name": "angle"
},
"optional": true
}
],
"body": {
"start": 19,
"end": 49,
"body": [
{
"type": "ReturnStatement",
"type": "ReturnStatement",
"start": 21,
"end": 47,
"argument": {
"type": "CallExpression",
"type": "CallExpression",
"start": 28,
"end": 47,
"callee": {
"type": "Identifier",
"start": 28,
"end": 35,
"name": "default"
},
"arguments": [
{
"type": "Identifier",
"type": "Identifier",
"start": 36,
"end": 41,
"name": "angle"
},
{
"type": "Literal",
"type": "Literal",
"start": 43,
"end": 46,
"value": 360,
"raw": "360"
}
],
"optional": false
}
}
],
"nonCodeMeta": {
"nonCodeNodes": {},
"start": []
}
}
}
}
],
"kind": "fn"
}
],
"nonCodeMeta": {
"nonCodeNodes": {},
"start": []
}
}

View File

@ -20,17 +20,12 @@ use crate::{
/// Data to draw a line to a point.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum LineToData {
/// A point with a tag.
PointWithTag {
/// The to point.
to: [f64; 2],
/// The tag.
tag: String,
},
/// A point.
Point([f64; 2]),
#[serde(rename_all = "camelCase")]
pub struct LineToData {
/// The to point.
to: [f64; 2],
/// The tag.
tag: Option<String>,
}
/// Draw a line to a point.
@ -51,10 +46,8 @@ async fn inner_line_to(
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let to = match data {
LineToData::PointWithTag { to, .. } => to,
LineToData::Point(to) => to,
};
let to = data.to;
let name = data.tag.unwrap_or_default();
let id = uuid::Uuid::new_v4();
@ -63,11 +56,7 @@ async fn inner_line_to(
ModelingCmd::ExtendPath {
path: sketch_group.id,
segment: kittycad::types::PathSegment::Line {
end: Point3D {
x: to[0],
y: to[1],
z: 0.0,
},
end: point3d(to),
relative: false,
},
},
@ -78,11 +67,7 @@ async fn inner_line_to(
base: BasePath {
from: from.into(),
to,
name: if let LineToData::PointWithTag { tag, .. } = data {
tag.to_string()
} else {
"".to_string()
},
name,
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
@ -99,17 +84,12 @@ async fn inner_line_to(
/// Data to draw a line to a point on an axis.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum AxisLineToData {
/// A point with a tag.
PointWithTag {
/// The to point.
to: f64,
/// The tag.
tag: String,
},
/// A point.
Point(f64),
#[serde(rename_all = "camelCase")]
pub struct AxisLineToData {
/// The to point.
to: f64,
/// The tag.
tag: Option<String>,
}
/// Draw a line to a point on the x-axis.
@ -131,9 +111,9 @@ async fn inner_x_line_to(
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let line_to_data = match data {
AxisLineToData::PointWithTag { to, tag } => LineToData::PointWithTag { to: [to, from.y], tag },
AxisLineToData::Point(data) => LineToData::Point([data, from.y]),
let line_to_data = LineToData {
to: [data.to, from.y],
tag: data.tag,
};
let new_sketch_group = inner_line_to(line_to_data, sketch_group, args).await?;
@ -160,9 +140,9 @@ async fn inner_y_line_to(
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let line_to_data = match data {
AxisLineToData::PointWithTag { to, tag } => LineToData::PointWithTag { to: [from.x, to], tag },
AxisLineToData::Point(data) => LineToData::Point([from.x, data]),
let line_to_data = LineToData {
to: [from.x, data.to],
tag: data.tag,
};
let new_sketch_group = inner_line_to(line_to_data, sketch_group, args).await?;
@ -172,17 +152,12 @@ async fn inner_y_line_to(
/// Data to draw a line.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum LineData {
/// A point with a tag.
PointWithTag {
/// The to point.
to: [f64; 2],
/// The tag.
tag: String,
},
/// A point.
Point([f64; 2]),
#[serde(rename_all = "camelCase")]
pub struct LineData {
/// The to point.
to: [f64; 2],
/// The tag.
tag: Option<String>,
}
/// Draw a line.
@ -199,10 +174,7 @@ pub async fn line(args: Args) -> Result<MemoryItem, KclError> {
}]
async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let inner_args = match &data {
LineData::PointWithTag { to, .. } => *to,
LineData::Point(to) => *to,
};
let inner_args = data.to;
let delta = inner_args;
let to = [from.x + inner_args[0], from.y + inner_args[1]];
@ -214,11 +186,7 @@ async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args)
ModelingCmd::ExtendPath {
path: sketch_group.id,
segment: kittycad::types::PathSegment::Line {
end: Point3D {
x: delta[0],
y: delta[1],
z: 0.0,
},
end: point3d(delta),
relative: true,
},
},
@ -229,11 +197,7 @@ async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args)
base: BasePath {
from: from.into(),
to,
name: if let LineData::PointWithTag { tag, .. } = data {
tag.to_string()
} else {
"".to_string()
},
name: data.tag.unwrap_or_default(),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
@ -250,17 +214,12 @@ async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args)
/// Data to draw a line on an axis.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum AxisLineData {
/// The length with a tag.
LengthWithTag {
/// The length of the line.
length: f64,
/// The tag.
tag: String,
},
/// The length.
Length(f64),
#[serde(rename_all = "camelCase")]
pub struct AxisLineData {
/// The length of the line.
length: f64,
/// The tag.
tag: Option<String>,
}
/// Draw a line on the x-axis.
@ -280,9 +239,9 @@ async fn inner_x_line(
sketch_group: Box<SketchGroup>,
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let line_data = match data {
AxisLineData::LengthWithTag { length, tag } => LineData::PointWithTag { to: [length, 0.0], tag },
AxisLineData::Length(length) => LineData::Point([length, 0.0]),
let line_data = LineData {
to: [data.length, 0.0],
tag: data.tag,
};
let new_sketch_group = inner_line(line_data, sketch_group, args).await?;
@ -306,9 +265,9 @@ async fn inner_y_line(
sketch_group: Box<SketchGroup>,
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let line_data = match data {
AxisLineData::LengthWithTag { length, tag } => LineData::PointWithTag { to: [0.0, length], tag },
AxisLineData::Length(length) => LineData::Point([0.0, length]),
let line_data = LineData {
to: [0.0, data.length],
tag: data.tag,
};
let new_sketch_group = inner_line(line_data, sketch_group, args).await?;
@ -318,28 +277,19 @@ async fn inner_y_line(
/// Data to draw an angled line.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum AngledLineData {
/// An angle and length with a tag.
AngleWithTag {
/// The angle of the line.
angle: f64,
/// The length of the line.
length: f64,
/// The tag.
tag: String,
},
/// An angle and length.
AngleAndLength([f64; 2]),
#[serde(rename_all = "camelCase")]
pub struct AngledLineData {
/// The angle of the line.
angle: f64,
/// The length of the line.
length: f64,
/// The tag.
tag: Option<String>,
}
impl AngledLineData {
pub fn into_inner_line(self, to: [f64; 2]) -> LineData {
if let AngledLineData::AngleWithTag { tag, .. } = self {
LineData::PointWithTag { to, tag }
} else {
LineData::Point(to)
}
LineData { to, tag: self.tag }
}
}
@ -361,10 +311,7 @@ async fn inner_angled_line(
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let (angle, length) = match &data {
AngledLineData::AngleWithTag { angle, length, .. } => (*angle, *length),
AngledLineData::AngleAndLength(angle_and_length) => (angle_and_length[0], angle_and_length[1]),
};
let AngledLineData { angle, length, tag } = data;
//double check me on this one - mike
let delta: [f64; 2] = [
@ -381,11 +328,7 @@ async fn inner_angled_line(
base: BasePath {
from: from.into(),
to,
name: if let AngledLineData::AngleWithTag { tag, .. } = data {
tag.to_string()
} else {
"".to_string()
},
name: tag.unwrap_or_default(),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
@ -398,11 +341,7 @@ async fn inner_angled_line(
ModelingCmd::ExtendPath {
path: sketch_group.id,
segment: kittycad::types::PathSegment::Line {
end: Point3D {
x: delta[0],
y: delta[1],
z: 0.0,
},
end: point3d(delta),
relative,
},
},
@ -431,12 +370,7 @@ async fn inner_angled_line_of_x_length(
sketch_group: Box<SketchGroup>,
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let (angle, length) = match &data {
AngledLineData::AngleWithTag { angle, length, .. } => (*angle, *length),
AngledLineData::AngleAndLength(angle_and_length) => (angle_and_length[0], angle_and_length[1]),
};
let to = get_y_component(Angle::from_degrees(angle), length);
let to = get_y_component(Angle::from_degrees(data.angle), data.length);
let new_sketch_group = inner_line(data.into_inner_line(to.into()), sketch_group, args).await?;
@ -446,28 +380,20 @@ async fn inner_angled_line_of_x_length(
/// Data to draw an angled line to a point.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum AngledLineToData {
/// An angle and point with a tag.
AngleWithTag {
/// The angle of the line.
angle: f64,
/// The point to draw to.
to: f64,
/// The tag.
tag: String,
},
/// An angle and point to draw to.
AngleAndPoint([f64; 2]),
#[serde(rename_all = "camelCase")]
pub struct AngledLineToData {
/// The angle of the line.
angle: f64,
/// The point to draw to.
to: f64,
/// The tag.
tag: Option<String>,
}
impl AngledLineToData {
pub fn into_inner_line(self, x_to: f64, y_to: f64) -> LineToData {
if let AngledLineToData::AngleWithTag { tag, .. } = self {
LineToData::PointWithTag { to: [x_to, y_to], tag }
} else {
LineToData::Point([x_to, y_to])
}
let tag = self.tag;
LineToData { to: [x_to, y_to], tag }
}
}
@ -489,10 +415,7 @@ async fn inner_angled_line_to_x(
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let (angle, x_to) = match &data {
AngledLineToData::AngleWithTag { angle, to, .. } => (*angle, *to),
AngledLineToData::AngleAndPoint(angle_and_to) => (angle_and_to[0], angle_and_to[1]),
};
let (angle, x_to) = (data.angle, data.to);
let x_component = x_to - from.x;
let y_component = x_component * f64::tan(angle.to_radians());
@ -520,10 +443,7 @@ async fn inner_angled_line_of_y_length(
sketch_group: Box<SketchGroup>,
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let (angle, length) = match &data {
AngledLineData::AngleWithTag { angle, length, .. } => (*angle, *length),
AngledLineData::AngleAndLength(angle_and_length) => (angle_and_length[0], angle_and_length[1]),
};
let (angle, length) = (data.angle, data.length);
let to = get_x_component(Angle::from_degrees(angle), length);
@ -550,10 +470,7 @@ async fn inner_angled_line_to_y(
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let (angle, y_to) = match &data {
AngledLineToData::AngleWithTag { angle, to, .. } => (*angle, *to),
AngledLineToData::AngleAndPoint(angle_and_to) => (angle_and_to[0], angle_and_to[1]),
};
let (angle, y_to) = (data.angle, data.to);
let y_component = y_to - from.y;
let x_component = y_component / f64::tan(angle.to_radians());
@ -616,10 +533,9 @@ async fn inner_angled_line_that_intersects(
from,
);
let line_to_data = if let Some(tag) = data.tag {
LineToData::PointWithTag { to: to.into(), tag }
} else {
LineToData::Point(to.into())
let line_to_data = LineToData {
to: to.into(),
tag: data.tag,
};
let new_sketch_group = inner_line_to(line_to_data, sketch_group, args).await?;
@ -830,10 +746,7 @@ pub async fn start_profile_at(args: Args) -> Result<MemoryItem, KclError> {
name = "startProfileAt",
}]
async fn inner_start_profile_at(data: LineData, plane: Box<Plane>, args: Args) -> Result<Box<SketchGroup>, KclError> {
let to = match &data {
LineData::PointWithTag { to, .. } => *to,
LineData::Point(to) => *to,
};
let to = data.to;
let id = uuid::Uuid::new_v4();
let path_id = uuid::Uuid::new_v4();
@ -843,11 +756,7 @@ async fn inner_start_profile_at(data: LineData, plane: Box<Plane>, args: Args) -
id,
ModelingCmd::MovePathPen {
path: path_id,
to: Point3D {
x: to[0],
y: to[1],
z: 0.0,
},
to: point3d(to),
},
)
.await?;
@ -855,11 +764,7 @@ async fn inner_start_profile_at(data: LineData, plane: Box<Plane>, args: Args) -
let current_path = BasePath {
from: to,
to,
name: if let LineData::PointWithTag { tag, .. } = data {
tag.to_string()
} else {
"".to_string()
},
name: data.tag.unwrap_or_default(),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
@ -943,16 +848,7 @@ pub enum ArcData {
/// The radius.
radius: f64,
/// The tag.
tag: String,
},
/// Angles and radius.
AnglesAndRadius {
/// The start angle.
angle_start: f64,
/// The end angle.
angle_end: f64,
/// The radius.
radius: f64,
tag: Option<String>,
},
/// Center, to and radius with a tag.
CenterToRadiusWithTag {
@ -963,16 +859,7 @@ pub enum ArcData {
/// The radius.
radius: f64,
/// The tag.
tag: String,
},
/// Center, to and radius.
CenterToRadius {
/// The center.
center: [f64; 2],
/// The to point.
to: [f64; 2],
/// The radius.
radius: f64,
tag: Option<String>,
},
}
@ -1003,24 +890,10 @@ async fn inner_arc(data: ArcData, sketch_group: Box<SketchGroup>, args: Args) ->
let (center, end) = arc_center_and_end(from, a_start, a_end, *radius);
(center, a_start, a_end, *radius, end)
}
ArcData::AnglesAndRadius {
angle_start,
angle_end,
radius,
} => {
let a_start = Angle::from_degrees(*angle_start);
let a_end = Angle::from_degrees(*angle_end);
let (center, end) = arc_center_and_end(from, a_start, a_end, *radius);
(center, a_start, a_end, *radius, end)
}
ArcData::CenterToRadiusWithTag { center, to, radius, .. } => {
let (angle_start, angle_end) = arc_angles(from, center.into(), to.into(), *radius, args.source_range)?;
(center.into(), angle_start, angle_end, *radius, to.into())
}
ArcData::CenterToRadius { center, to, radius } => {
let (angle_start, angle_end) = arc_angles(from, center.into(), to.into(), *radius, args.source_range)?;
(center.into(), angle_start, angle_end, *radius, to.into())
}
};
let id = uuid::Uuid::new_v4();
@ -1047,10 +920,8 @@ async fn inner_arc(data: ArcData, sketch_group: Box<SketchGroup>, args: Args) ->
from: from.into(),
to: end.into(),
name: match data {
ArcData::AnglesAndRadiusWithTag { tag, .. } => tag.to_string(),
ArcData::AnglesAndRadius { .. } => "".to_string(),
ArcData::CenterToRadiusWithTag { tag, .. } => tag.to_string(),
ArcData::CenterToRadius { .. } => "".to_string(),
ArcData::AnglesAndRadiusWithTag { tag, .. } => tag.unwrap_or_default(),
ArcData::CenterToRadiusWithTag { tag, .. } => tag.unwrap_or_default(),
},
geo_meta: GeoMeta {
id,
@ -1082,10 +953,8 @@ pub enum TangentialArcData {
/// Where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
to: [f64; 2],
/// The tag.
tag: String,
tag: Option<String>,
},
/// A point where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
Point([f64; 2]),
}
/// Draw a tangential arc.
@ -1135,11 +1004,6 @@ async fn inner_tangential_arc(
TangentialArcData::PointWithTag { to, .. } => {
args.send_modeling_cmd(id, tan_arc_to(&sketch_group, to)).await?;
*to
}
TangentialArcData::Point(to) => {
args.send_modeling_cmd(id, tan_arc_to(&sketch_group, to)).await?;
*to
}
};
@ -1169,11 +1033,7 @@ fn tan_arc_to(sketch_group: &SketchGroup, to: &[f64; 2]) -> ModelingCmd {
path: sketch_group.id,
segment: kittycad::types::PathSegment::TangentialArcTo {
angle_snap_increment: None,
to: Point3D {
x: to[0],
y: to[1],
z: 0.0,
},
to: point3d(*to),
},
}
}
@ -1181,17 +1041,12 @@ fn tan_arc_to(sketch_group: &SketchGroup, to: &[f64; 2]) -> ModelingCmd {
/// Data to draw a tangential arc to a specific point.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum TangentialArcToData {
/// A point with a tag.
PointWithTag {
/// Where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
to: [f64; 2],
/// The tag.
tag: String,
},
/// A point where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
Point([f64; 2]),
#[serde(rename_all = "camelCase")]
pub struct TangentialArcToData {
/// Where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
to: [f64; 2],
/// The tag.
tag: Option<String>,
}
/// Draw a tangential arc to a specific point.
@ -1212,10 +1067,8 @@ async fn inner_tangential_arc_to(
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let from: Point2d = sketch_group.get_coords_from_paths()?;
let to = match &data {
TangentialArcToData::PointWithTag { to, .. } => to,
TangentialArcToData::Point(to) => to,
};
let to = data.to;
let name = data.tag.unwrap_or_default().to_owned();
let delta = [to[0] - from.x, to[1] - from.y];
let id = uuid::Uuid::new_v4();
@ -1224,12 +1077,8 @@ async fn inner_tangential_arc_to(
let current_path = Path::ToPoint {
base: BasePath {
from: from.into(),
to: *to,
name: if let TangentialArcToData::PointWithTag { tag, .. } = data {
tag.to_string()
} else {
"".to_string()
},
to,
name,
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
@ -1246,28 +1095,16 @@ async fn inner_tangential_arc_to(
/// Data to draw a bezier curve.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum BezierData {
/// Points with a tag.
PointsWithTag {
/// The to point.
to: [f64; 2],
/// The first control point.
control1: [f64; 2],
/// The second control point.
control2: [f64; 2],
/// The tag.
tag: String,
},
/// Points.
Points {
/// The to point.
to: [f64; 2],
/// The first control point.
control1: [f64; 2],
/// The second control point.
control2: [f64; 2],
},
#[serde(rename_all = "camelCase")]
pub struct BezierData {
/// The to point.
to: [f64; 2],
/// The first control point.
control1: [f64; 2],
/// The second control point.
control2: [f64; 2],
/// The tag.
tag: Option<String>,
}
/// Draw a bezier curve.
@ -1289,12 +1126,13 @@ async fn inner_bezier_curve(
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?;
let (to, control1, control2) = match &data {
BezierData::PointsWithTag {
to, control1, control2, ..
} => (to, control1, control2),
BezierData::Points { to, control1, control2 } => (to, control1, control2),
};
let BezierData {
to,
control1,
control2,
tag,
} = data;
let name = tag.unwrap_or_default();
let relative = true;
let delta = to;
@ -1307,21 +1145,9 @@ async fn inner_bezier_curve(
ModelingCmd::ExtendPath {
path: sketch_group.id,
segment: kittycad::types::PathSegment::Bezier {
control1: Point3D {
x: control1[0],
y: control1[1],
z: 0.0,
},
control2: Point3D {
x: control2[0],
y: control2[1],
z: 0.0,
},
end: Point3D {
x: delta[0],
y: delta[1],
z: 0.0,
},
control1: point3d(control1),
control2: point3d(control2),
end: point3d(delta),
relative,
},
},
@ -1332,11 +1158,7 @@ async fn inner_bezier_curve(
base: BasePath {
from: from.into(),
to,
name: if let BezierData::PointsWithTag { tag, .. } = data {
tag.to_string()
} else {
"".to_string()
},
name,
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
@ -1394,6 +1216,10 @@ async fn inner_hole(
Ok(sketch_group)
}
fn point3d([x, y]: [f64; 2]) -> Point3D {
Point3D { x, y, z: 0.0 }
}
#[cfg(test)]
mod tests {
@ -1403,21 +1229,30 @@ mod tests {
#[test]
fn test_deserialize_line_data() {
let data = LineData::Point([0.0, 1.0]);
let data = LineData {
to: [0.0, 1.0],
tag: None,
};
let mut str_json = serde_json::to_string(&data).unwrap();
assert_eq!(str_json, "[0.0,1.0]");
str_json = "[0, 1]".to_string();
let data: LineData = serde_json::from_str(&str_json).unwrap();
assert_eq!(data, LineData::Point([0.0, 1.0]));
assert_eq!(
data,
LineData {
to: [0.0, 1.0],
tag: None
}
);
str_json = "{ \"to\": [0.0, 1.0], \"tag\": \"thing\" }".to_string();
let data: LineData = serde_json::from_str(&str_json).unwrap();
assert_eq!(
data,
LineData::PointWithTag {
LineData {
to: [0.0, 1.0],
tag: "thing".to_string()
tag: Some("thing".to_string()),
}
);
}

View File

@ -47,6 +47,8 @@ pub enum TokenType {
Function,
/// Unknown lexemes.
Unknown,
/// The ? symbol, used for optional values.
QuestionMark,
}
/// Most KCL tokens correspond to LSP semantic tokens (but not all).
@ -58,6 +60,7 @@ impl TryFrom<TokenType> for SemanticTokenType {
TokenType::Word => Self::VARIABLE,
TokenType::Keyword => Self::KEYWORD,
TokenType::Operator => Self::OPERATOR,
TokenType::QuestionMark => Self::OPERATOR,
TokenType::String => Self::STRING,
TokenType::LineComment => Self::COMMENT,
TokenType::BlockComment => Self::COMMENT,

View File

@ -21,6 +21,7 @@ pub fn token(i: &mut Located<&str>) -> PResult<Token> {
'{' | '(' | '[' => brace_start,
'}' | ')' | ']' => brace_end,
',' => comma,
'?' => question_mark,
'0'..='9' => number,
':' => colon,
'.' => alt((number, double_period, period)),
@ -108,6 +109,11 @@ fn comma(i: &mut Located<&str>) -> PResult<Token> {
Ok(Token::from_range(range, TokenType::Comma, value.to_string()))
}
fn question_mark(i: &mut Located<&str>) -> PResult<Token> {
let (value, range) = '?'.with_span().parse_next(i)?;
Ok(Token::from_range(range, TokenType::QuestionMark, value.to_string()))
}
fn colon(i: &mut Located<&str>) -> PResult<Token> {
let (value, range) = ':'.with_span().parse_next(i)?;
Ok(Token::from_range(range, TokenType::Colon, value.to_string()))

View File

@ -2525,16 +2525,17 @@
"@types/babel__core" "^7.20.3"
react-refresh "^0.14.0"
"@vitest/coverage-istanbul@^0.34.1":
version "0.34.1"
resolved "https://registry.yarnpkg.com/@vitest/coverage-istanbul/-/coverage-istanbul-0.34.1.tgz#a3cf36630c95b090457138b0706133b69ab59189"
integrity sha512-5GprlyY2t1g6+RrssWcN/w5RnZV3qIOM0eoaSDJw3jXbHpBpMvAfTg791zXo7PIqNYs5ORUqBWXIIU0gyAfZxA==
"@vitest/coverage-istanbul@^0.34.6":
version "0.34.6"
resolved "https://registry.yarnpkg.com/@vitest/coverage-istanbul/-/coverage-istanbul-0.34.6.tgz#4fc91eac4d7cfc5b91850e9f82bcb986990b79a4"
integrity sha512-5KaBNZPDSk2ybavC3rZ1pWGniw7sJ5usuwVGRUYzJwiBfWvnLpuUer7bjw7qUCRGdKJXrBgb/Dsgif9rkwMX/A==
dependencies:
istanbul-lib-coverage "^3.2.0"
istanbul-lib-instrument "^6.0.0"
istanbul-lib-report "^3.0.1"
istanbul-lib-source-maps "^4.0.1"
istanbul-reports "^3.1.5"
picocolors "^1.0.0"
test-exclude "^6.0.0"
"@vitest/expect@0.34.6":