Compare commits

...

7 Commits

Author SHA1 Message Date
cfde4e99f9 add more tests 2024-05-23 11:17:04 +10:00
1bcaaec807 Merge remote-tracking branch 'origin' into max-unused-variables 2024-05-23 10:51:11 +10:00
fe621240c3 use tauri command to run commands (#2475)
* use tauri command to run commands

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* add capabilities

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-22 17:44:13 -07:00
97faf5ae2b Simplify the pentagon test (#2474)
* plumbus fixes

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* Simplify the pentagon test

* Fix up triangle png

* Triangle plumbuses now face the camera

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: Jess Frazelle <github@jessfraz.com>
2024-05-22 16:50:54 -07:00
67e90f580d nicer query
added PipeExpression checker.

now query works with :

const xRel001 = -20
      const xRel002 = -50
      const part001 = startSketchOn('-XZ')
        |> startProfileAt([175.73, 109.38], %)
        |> line([xRel001, 178.25], %)
        |> line([-265.39, -87.86], %)
        |> tangentialArcTo([543.32, -355.04], %)
2024-05-22 22:45:22 +02:00
78046eceb6 simple test
const xRel001 = -20
const xRel002 = xRel001-50
2024-05-22 21:18:55 +02:00
502cb08a10 findUnusedVariables
first draft
2024-05-21 22:40:30 +02:00
12 changed files with 239 additions and 111 deletions

13
src-tauri/Cargo.lock generated
View File

@ -2567,7 +2567,7 @@ dependencies = [
[[package]]
name = "kcl-lib"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"anyhow",
"approx",
@ -6059,9 +6059,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "ts-rs"
version = "7.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2cae1fc5d05d47aa24b64f9a4f7cba24cdc9187a2084dd97ac57bef5eccae6"
version = "8.1.0"
source = "git+https://github.com/Aleph-Alpha/ts-rs#f898578d80d3e2a54080c1c046c45f9eaa2435c3"
dependencies = [
"chrono",
"thiserror",
@ -6072,11 +6071,9 @@ dependencies = [
[[package]]
name = "ts-rs-macros"
version = "7.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f7f9b821696963053a89a7bd8b292dc34420aea8294d7b225274d488f3ec92"
version = "8.1.0"
source = "git+https://github.com/Aleph-Alpha/ts-rs#f898578d80d3e2a54080c1c046c45f9eaa2435c3"
dependencies = [
"Inflector",
"proc-macro2",
"quote",
"syn 2.0.65",

View File

@ -56,6 +56,33 @@
]
},
"shell:allow-open",
{
"identifier": "shell:allow-execute",
"allow": [
{
"name": "open",
"cmd": "open",
"args": [
"-R",
{
"validator": "\\S+"
}
],
"sidecar": false
},
{
"name": "explorer",
"cmd": "explorer",
"args": [
"/select",
{
"validator": "\\S+"
}
],
"sidecar": false
}
]
},
"dialog:allow-open",
"dialog:allow-save",
"dialog:allow-message",

View File

@ -18,7 +18,6 @@ use oauth2::TokenResponse;
use tauri::{ipc::InvokeError, Manager};
use tauri_plugin_cli::CliExt;
use tauri_plugin_shell::ShellExt;
use tokio::process::Command;
const DEFAULT_HOST: &str = "https://api.zoo.dev";
const SETTINGS_FILE_NAME: &str = "settings.toml";
@ -332,10 +331,20 @@ async fn get_user(token: &str, hostname: &str) -> Result<kittycad::types::User,
/// From this GitHub comment: https://github.com/tauri-apps/tauri/issues/4062#issuecomment-1338048169
/// But with the Linux support removed since we don't need it for now.
#[tauri::command]
fn show_in_folder(path: &str) -> Result<(), InvokeError> {
fn show_in_folder(app: tauri::AppHandle, path: &str) -> Result<(), InvokeError> {
// Check if the file exists.
// If it doesn't, return an error.
if !Path::new(path).exists() {
return Err(InvokeError::from_anyhow(anyhow::anyhow!(
"The file `{}` does not exist",
path
)));
}
#[cfg(not(unix))]
{
Command::new("explorer")
app.shell()
.command("explorer")
.args(["/select,", path]) // The comma after select is not a typo
.spawn()
.map_err(|e| InvokeError::from_anyhow(e.into()))?;
@ -343,7 +352,8 @@ fn show_in_folder(path: &str) -> Result<(), InvokeError> {
#[cfg(unix)]
{
Command::new("open")
app.shell()
.command("open")
.args(["-R", path])
.spawn()
.map_err(|e| InvokeError::from_anyhow(e.into()))?;

View File

@ -1,6 +1,7 @@
import { parse, recast, initPromise } from './wasm'
import {
findAllPreviousVariables,
findUnusedVariables,
isNodeSafeToReplace,
isTypeInValue,
getNodePathFromSourceRange,
@ -60,6 +61,91 @@ const variableBelowShouldNotBeIncluded = 3
})
})
describe('Test findUnusedVariables', () => {
it('should find unused variable in common kcl code', () => {
// example code
const code = `
const xRel001 = -20
const xRel002 = -50
const part001 = startSketchOn('-XZ')
|> startProfileAt([175.73, 109.38], %)
|> line([xRel001, 178.25], %)
|> line([-265.39, -87.86], %)
|> tangentialArcTo([543.32, -355.04], %)
`
// parse into ast
const ast = parse(code)
// find unused variables
const unusedVariables = findUnusedVariables(ast)
// check wether unused variables match the expected result
expect(
unusedVariables
.map((node) => node.declarations.map((decl) => decl.id.name))
.flat()
).toEqual(['xRel002'])
})
it("should not find used variable, even if it's heavy nested", () => {
// example code
const code = `
const deepWithin = 1
const veryNested = [
{ key: [{ key2: max(5, deepWithin) }] }
]
`
// parse into ast
const ast = parse(code)
// find unused variables
const unusedVariables = findUnusedVariables(ast)
// check wether unused variables match the expected result
expect(
unusedVariables.find((node) =>
node.declarations.find((decl) => decl.id.name === 'deepWithin')
)
).toBeFalsy()
})
it('should not find used variable, even if used in a closure', () => {
// example code
const code = `const usedInClosure = 1
fn myFunction = () => {
return usedInClosure
}
`
// parse into ast
const ast = parse(code)
// find unused variables
const unusedVariables = findUnusedVariables(ast)
// check wether unused variables match the expected result
expect(
unusedVariables.find((node) =>
node.declarations.find((decl) => decl.id.name === 'usedInClosure')
)
).toBeFalsy()
})
// TODO: The commented code in the below does not even parse due to a KCL bug
// When it does parse correctly we'de expect 'a' to be defined but unused
// as it's shadowed by the 'a' in the inner scope
// it('should find unused variable when the same identifier is used in deeper scope', () => {
// const code = `const a = 1
// const b = 2
// fn (a) => {
// return a + 1
// }
// const myVar = b + 5`
// // parse into ast
// const ast = parse(code)
// console.log('ast', ast)
// // find unused variables
// const unusedVariables = findUnusedVariables(ast)
// console.log('unusedVariables', unusedVariables)
// // check wether unused variables match the expected result
// expect(
// unusedVariables
// .map((node) => node.declarations.map((decl) => decl.id.name))
// .flat()
// ).toEqual(['a'])
// })
})
describe('testing argIsNotIdentifier', () => {
const code = `const part001 = startSketchOn('XY')
|> startProfileAt([-1.2, 4.83], %)

View File

@ -392,6 +392,68 @@ export function findAllPreviousVariables(
}
}
export function findUnusedVariables(ast: Program): Array<VariableDeclaration> {
const declaredVariables = new Map<string, VariableDeclarator>() // Map to store declared variables
const usedVariables = new Set<string>() // Set to track used variables
// 1. Traverse and populate
ast.body.forEach((node) => {
traverse(node, {
enter(node) {
if (node.type === 'VariableDeclarator') {
// if node is a VariableDeclarator,
// add it to declaredVariables
declaredVariables.set(node.id.name, node)
} else if (node.type === 'Identifier') {
// if the node is Identifier, (use of a variable)
// check if it is a declared value,
// just in case...
// to be sure it's a part of the declared variables
if (declaredVariables.has(node.name)) {
// if yes - mark it as used
usedVariables.add(node.name)
}
} else if (node.type === 'VariableDeclaration') {
// check if the declaration is model-defining (contains PipeExpression)
const isModelDefining = node.declarations.some(
(decl) => decl.init?.type === 'PipeExpression'
)
if (isModelDefining) {
// If it is, mark all contained variables as used
node.declarations.forEach((decl) => {
usedVariables.add(decl.id.name)
})
}
}
},
})
})
// 2. Remove used variables from declaredVariables
usedVariables.forEach((name) => {
declaredVariables.delete(name)
})
// 3. collect unused VariableDeclarations
const unusedVariableDeclarations: Array<VariableDeclaration> = []
ast.body.forEach((node) => {
if (node.type === 'VariableDeclaration') {
const unusedDeclarators = node.declarations.filter((declarator) =>
declaredVariables.has(declarator.id.name)
)
if (unusedDeclarators.length > 0) {
unusedVariableDeclarations.push({
...node,
declarations: unusedDeclarators,
})
}
}
})
// 4. Return the unused variables
return unusedVariableDeclarations
}
type ReplacerFn = (_ast: Program, varName: string) => { modifiedAst: Program }
export function isNodeSafeToReplace(

View File

@ -1121,7 +1121,7 @@ impl ExecutorContext {
&self,
program: crate::ast::types::Program,
memory: &mut ProgramMemory,
_body_type: BodyType,
body_type: BodyType,
) -> Result<ProgramMemory, KclError> {
let pipe_info = PipeInfo::default();
@ -1328,8 +1328,10 @@ impl ExecutorContext {
}
}
// Flush the batch queue.
self.engine.flush_batch(SourceRange([program.end, program.end])).await?;
if BodyType::Root == body_type {
// Flush the batch queue.
self.engine.flush_batch(SourceRange([program.end, program.end])).await?;
}
Ok(memory.clone())
}

View File

@ -1,42 +0,0 @@
fn make_circle = (face, tag, pos, radius) => {
const sg0 = startSketchOn(face, tag)
const sg1 = startProfileAt([pos[0] + radius, pos[1]], sg0)
const sg2 = arc({
angle_end: 360,
angle_start: 0,
radius: radius
}, sg1, 'arc-' + tag)
return close(sg2)
}
fn pentagon = (len) => {
const sg3 = startSketchOn('XY')
const sg4 = startProfileAt([-len / 2, -len / 2], sg3)
const sg5 = angledLine({ angle: 0, length: len }, sg4, 'a')
const sg6 = angledLine({
angle: segAng('a', sg5) + 180 - 108,
length: len
},sg5, 'b')
const sg7 = angledLine({
angle: segAng('b', sg6) + 180 - 108,
length: len
}, sg6, 'c')
const sg8 = angledLine({
angle: segAng('c', sg7) + 180 - 108,
length: len
}, sg7, 'd')
return angledLine({
angle: segAng('d', sg8) + 180 - 108,
length: len
}, sg8)
}
const p = pentagon(48)
const pe = extrude(30, p)
const plumbus0 = make_circle(pe, 'a', [0, 0], 9)
const plumbus1 = extrude(18, plumbus0)
const plumbus2 = fillet({
radius: 0.5,
tags: ['arc-a', getOppositeEdge('arc-a', plumbus1)]
}, plumbus1)

View File

@ -1,46 +1,41 @@
fn make_circle = (face, tag, pos, radius) => {
const sg = startSketchOn(face, tag)
|> startProfileAt([pos[0] + radius, pos[1]], %)
|> arc({
angle_end: 360,
angle_start: 0,
radius: radius
}, %, 'arc-' + tag)
|> close(%)
return sg
fn triangle = (len) => {
return startSketchOn('XY')
|> startProfileAt([0, 0], %)
|> angledLine({angle: 60, length: len}, %, 'a')
|> angledLine({angle: 180, length: len}, %, 'b')
|> angledLine({angle: 300, length: len}, %, 'c')
}
fn pentagon = (len) => {
const sg = startSketchOn('XY')
|> startProfileAt([-len / 2, -len / 2], %)
|> angledLine({ angle: 0, length: len }, %, 'a')
|> angledLine({
angle: segAng('a', %) + 180 - 108,
length: len
}, %, 'b')
|> angledLine({
angle: segAng('b', %) + 180 - 108,
length: len
}, %, 'c')
|> angledLine({
angle: segAng('c', %) + 180 - 108,
length: len
}, %, 'd')
|> angledLine({
angle: segAng('d', %) + 180 - 108,
length: len
let triangleHeight = 200
let plumbusLen = 100
let radius = 80
let circ = {angle_start: 0, angle_end: 360, radius: radius}
let triangleLen = 500
const p = triangle(triangleLen)
|> extrude(triangleHeight, %)
fn circl = (x, tag) => {
return startSketchOn(p, tag)
|> startProfileAt([x + radius, triangleHeight/2], %)
|> arc(circ, %, 'arc-' + tag)
|> close(%)
}
const plumbus1 =
circl(-200, 'c')
|> extrude(plumbusLen, %)
|> fillet({
radius: 5,
tags: ['arc-c', getOppositeEdge('arc-c', %)]
}, %)
return sg
}
const p = pentagon(48)
|> extrude(30, %)
const plumbus0 = make_circle(p, 'a', [0, 0], 9)
|> extrude(18, %)
const plumbus0 =
circl(200, 'a')
|> extrude(plumbusLen, %)
|> fillet({
radius: 0.5,
radius: 5,
tags: ['arc-a', getOppositeEdge('arc-a', %)]
}, %)

View File

@ -128,15 +128,6 @@ async fn serial_test_lego() {
twenty_twenty::assert_image("tests/executor/outputs/lego.png", &result, 0.999);
}
#[tokio::test(flavor = "multi_thread")]
async fn serial_test_pentagon_fillet_desugar() {
let code = include_str!("inputs/pentagon_fillet_desugar.kcl");
let result = execute_and_snapshot(code, kcl_lib::settings::types::UnitLength::Cm)
.await
.unwrap();
twenty_twenty::assert_image("tests/executor/outputs/pentagon_fillet_desugar.png", &result, 0.999);
}
#[tokio::test(flavor = "multi_thread")]
async fn serial_test_pentagon_fillet_sugar() {
let code = include_str!("inputs/pentagon_fillet_sugar.kcl");
@ -1955,12 +1946,12 @@ const plumbus0 = make_circle(p, 'a', [0, 0], 2.5)
tags: ['arc-a', getOppositeEdge('arc-a', %)]
}, %)
// const plumbus1 = make_circle(p, 'b', [0, 0], 2.5)
// |> extrude(10, %)
// |> fillet({
// radius: 0.5,
// tags: ['arc-b', getOppositeEdge('arc-b', %)]
// }, %)
const plumbus1 = make_circle(p, 'b', [0, 0], 2.5)
|> extrude(10, %)
|> fillet({
radius: 0.5,
tags: ['arc-b', getOppositeEdge('arc-b', %)]
}, %)
"#;
let result = execute_and_snapshot(code, kcl_lib::settings::types::UnitLength::Mm)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 127 KiB

After

Width:  |  Height:  |  Size: 133 KiB