Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
Signed-off-by: Nick Cameron <nrc@ncameron.org>
  • Loading branch information
nrc committed Feb 10, 2025
1 parent 0558fb0 commit 6ec1715
Show file tree
Hide file tree
Showing 14 changed files with 301 additions and 164 deletions.
1 change: 1 addition & 0 deletions src/clientSideScene/ClientSideSceneComp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@ export async function deleteSegment({
ast: modifiedAst,
engineCommandManager: engineCommandManager,
isMock: true,
usePrevMemory: false,
})
if (testExecute.errors.length) {
toast.error('Segment tag used outside of current Sketch. Could not delete.')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ describe('processMemory', () => {
expect(output.myVar).toEqual(5)
expect(output.otherVar).toEqual(3)
expect(output).toEqual({
HALF_TURN: 180,
QUARTER_TURN: 90,
THREE_QUARTER_TURN: 270,
ZERO: 0,
myVar: 5,
myFn: '__function(a)__',
otherVar: 3,
Expand Down
2 changes: 1 addition & 1 deletion src/lang/executor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,6 @@ const theExtrude = startSketchOn('XY')
async function exe(code: string, variables: VariableMap = {}) {
const ast = assertParse(code)

const execState = await enginelessExecutor(ast, undefined, variables)
const execState = await enginelessExecutor(ast, true, undefined, variables)
return execState.variables
}
1 change: 1 addition & 0 deletions src/lang/kclSamples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ describe('Test KCL Samples from public Github repository', () => {
const ast = assertParse(code)
await enginelessExecutor(
ast,
false,
file.pathFromProjectDirectoryToFirstFile
)
},
Expand Down
10 changes: 6 additions & 4 deletions src/lang/langHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {
Program,
executor,
executeWithEngine,
executeMock,
kclLint,
emptyExecState,
ExecState,
VariableMap,
} from 'lang/wasm'
import { enginelessExecutor } from 'lib/testHelpers'
import { EngineCommandManager } from 'lang/std/engineConnection'
import { KCLError } from 'lang/errors'
import { Diagnostic } from '@codemirror/lint'
Expand Down Expand Up @@ -49,12 +49,14 @@ export async function executeAst({
path,
engineCommandManager,
isMock,
usePrevMemory,
variables,
}: {
ast: Node<Program>
path?: string
engineCommandManager: EngineCommandManager
isMock: boolean
usePrevMemory?: boolean
variables?: VariableMap
isInterrupted?: boolean
}): Promise<{
Expand All @@ -65,8 +67,8 @@ export async function executeAst({
}> {
try {
const execState = await (isMock
? enginelessExecutor(ast, path, variables)
: executor(ast, engineCommandManager, false, path))
? executeMock(ast, usePrevMemory, path, variables)
: executeWithEngine(ast, engineCommandManager, path))

await engineCommandManager.waitForAllCommands()

Expand Down
114 changes: 90 additions & 24 deletions src/lang/wasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
parse_wasm,
recast_wasm,
format_number,
execute_all,
execute_with_engine,
execute_mock,
kcl_lint,
modify_ast_for_sketch_wasm,
Expand Down Expand Up @@ -416,16 +416,6 @@ export const executor = async (
variables?: { [key in string]?: KclValue }
): Promise<ExecState> => {
try {
let jsAppSettings = default_app_settings()
if (!TEST) {
const lastSettingsSnapshot = await import(
'components/SettingsAuthProvider'
).then((module) => module.lastSettingsContextSnapshot)
if (lastSettingsSnapshot) {
jsAppSettings = getAllCurrentSettings(lastSettingsSnapshot)
}
}

if (isMock) {
if (!variables) {
variables = {}
Expand All @@ -434,36 +424,112 @@ export const executor = async (
const execOutcome: RustExecOutcome = await execute_mock(
JSON.stringify(node),
path,
JSON.stringify({ settings: jsAppSettings }),
JSON.stringify({ settings: jsAppSettings() }),
true,
JSON.stringify(variables),
fileSystemManager
)
return mockExecStateFromRust(execOutcome)
} else {
console.log('wasm full')
const execOutcome: RustExecOutcome = await execute_all(
const execOutcome: RustExecOutcome = await execute_with_engine(
JSON.stringify(node),
path,
JSON.stringify({ settings: jsAppSettings }),
JSON.stringify({ settings: jsAppSettings() }),
engineCommandManager,
fileSystemManager
)
return execStateFromRust(execOutcome, node)
}
} catch (e: any) {
console.log('execute error', e)
const parsed: KclErrorWithOutputs = JSON.parse(e.toString())
const kclError = new KCLError(
parsed.error.kind,
parsed.error.msg,
firstSourceRange(parsed.error),
parsed.operations,
parsed.artifactCommands,
rustArtifactGraphToMap(parsed.artifactGraph)
return Promise.reject(errFromErrWithOutputs(e))
}
}

/**
* Execute a KCL program.
* @param node The AST of the program to execute.
* @param path The full path of the file being executed. Use `null` for
* expressions that don't have a file, like expressions in the command bar.
*/
export const executeMock = async (
node: Node<Program>,
usePrevMemory?: boolean,
path?: string,
variables?: { [key in string]?: KclValue }
): Promise<ExecState> => {
try {
if (!variables) {
variables = {}
}
if (usePrevMemory === undefined) {
usePrevMemory = true
}
console.log('wasm mock', variables)
const execOutcome: RustExecOutcome = await execute_mock(
JSON.stringify(node),
path,
JSON.stringify({ settings: await jsAppSettings() }),
usePrevMemory,
JSON.stringify(variables),
fileSystemManager
)
return mockExecStateFromRust(execOutcome)
} catch (e: any) {
return Promise.reject(errFromErrWithOutputs(e))
}
}

/**
* Execute a KCL program.
* @param node The AST of the program to execute.
* @param path The full path of the file being executed. Use `null` for
* expressions that don't have a file, like expressions in the command bar.
*/
export const executeWithEngine = async (
node: Node<Program>,
engineCommandManager: EngineCommandManager,
path?: string
): Promise<ExecState> => {
try {
console.log('wasm full')
const execOutcome: RustExecOutcome = await execute_with_engine(
JSON.stringify(node),
path,
JSON.stringify({ settings: await jsAppSettings() }),
engineCommandManager,
fileSystemManager
)
return execStateFromRust(execOutcome, node)
} catch (e: any) {
return Promise.reject(errFromErrWithOutputs(e))
}
}

return Promise.reject(kclError)
const jsAppSettings = async () => {
let jsAppSettings = default_app_settings()
if (!TEST) {
const lastSettingsSnapshot = await import(
'components/SettingsAuthProvider'
).then((module) => module.lastSettingsContextSnapshot)
if (lastSettingsSnapshot) {
jsAppSettings = getAllCurrentSettings(lastSettingsSnapshot)
}
}
return jsAppSettings
}

const errFromErrWithOutputs = (e: any): KCLError => {
console.log('execute error', e)
const parsed: KclErrorWithOutputs = JSON.parse(e.toString())
return new KCLError(
parsed.error.kind,
parsed.error.msg,
firstSourceRange(parsed.error),
parsed.operations,
parsed.artifactCommands,
rustArtifactGraphToMap(parsed.artifactGraph)
)
}

export const kclLint = async (ast: Program): Promise<Array<Discovered>> => {
Expand Down
19 changes: 3 additions & 16 deletions src/lib/testHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
Program,
executor,
executeMock,
SourceRange,
ExecState,
VariableMap,
Expand Down Expand Up @@ -80,22 +80,9 @@ class MockEngineCommandManager {

export async function enginelessExecutor(
ast: Node<Program>,
usePrevMemory?: boolean,
path?: string,
variables?: VariableMap
): Promise<ExecState> {
const mockEngineCommandManager = new MockEngineCommandManager({
setIsStreamReady: () => {},
setMediaStream: () => {},
}) as any as EngineCommandManager
// eslint-disable-next-line @typescript-eslint/no-floating-promises
mockEngineCommandManager.startNewSession()
const execState = await executor(
ast,
mockEngineCommandManager,
true,
path,
variables
)
await mockEngineCommandManager.waitForAllCommands()
return execState
return await executeMock(ast, usePrevMemory, path, variables)
}
6 changes: 3 additions & 3 deletions src/lib/wasm_lib_wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
parse_wasm as ParseWasm,
recast_wasm as RecastWasm,
format_number as FormatNumber,
execute_all as ExecuteAll,
execute_with_engine as ExecuteWithEngine,
execute_mock as ExecuteMock,
kcl_lint as KclLint,
modify_ast_for_sketch_wasm as ModifyAstForSketch,
Expand Down Expand Up @@ -58,8 +58,8 @@ export const recast_wasm: typeof RecastWasm = (...args) => {
export const format_number: typeof FormatNumber = (...args) => {
return getModule().format_number(...args)
}
export const execute_all: typeof ExecuteAll = (...args) => {
return getModule().execute_all(...args)
export const execute_with_engine: typeof ExecuteWithEngine = (...args) => {
return getModule().execute_with_engine(...args)
}
export const execute_mock: typeof ExecuteMock = (...args) => {
return getModule().execute_mock(...args)
Expand Down
30 changes: 18 additions & 12 deletions src/wasm-lib/kcl/src/execution/exec_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl ExecutorContext {

// Add the item to the current module.
exec_state.mut_memory().add(
import_item.identifier(),
import_item.identifier().to_owned(),
item,
SourceRange::from(&import_item.name),
)?;
Expand Down Expand Up @@ -149,7 +149,7 @@ impl ExecutorContext {
})

Check warning on line 149 in src/wasm-lib/kcl/src/execution/exec_ast.rs

View check run for this annotation

Codecov / codecov/patch

src/wasm-lib/kcl/src/execution/exec_ast.rs#L146-L149

Added lines #L146 - L149 were not covered by tests
})?
.clone();
exec_state.mut_memory().add(name, item, source_range)?;
exec_state.mut_memory().add(name.to_owned(), item, source_range)?;

if let ItemVisibility::Export = import_stmt.visibility {
exec_state.mod_local.module_exports.push(name.clone());
Expand All @@ -162,7 +162,7 @@ impl ExecutorContext {
value: module_id,
meta: vec![source_range.into()],
};
exec_state.mut_memory().add(&name, item, source_range)?;
exec_state.mut_memory().add(name, item, source_range)?;
}
}
last_expr = None;
Expand Down Expand Up @@ -192,7 +192,9 @@ impl ExecutorContext {
StatementKind::Declaration { name: &var_name },
)
.await?;
exec_state.mut_memory().add(&var_name, memory_item, source_range)?;
exec_state
.mut_memory()
.add(var_name.clone(), memory_item, source_range)?;

// Track exports.
if let ItemVisibility::Export = variable_declaration.visibility {
Expand Down Expand Up @@ -220,7 +222,7 @@ impl ExecutorContext {
.await?;
exec_state
.mut_memory()
.add(memory::RETURN_NAME, value, metadata.source_range)
.add(memory::RETURN_NAME.to_owned(), value, metadata.source_range)
.map_err(|_| {
KclError::Semantic(KclErrorDetails {
message: "Multiple returns from a single function.".to_owned(),
Expand Down Expand Up @@ -499,7 +501,7 @@ impl ExecutorContext {
.await?;
exec_state
.mut_memory()
.add(&expr.label.name, result.clone(), init.into())?;
.add(expr.label.name.clone(), result.clone(), init.into())?;
// TODO this lets us use the label as a variable name, but not as a tag in most cases
result
}
Expand Down Expand Up @@ -1225,7 +1227,7 @@ impl Node<TagDeclarator> {

exec_state
.mut_memory()
.add(&self.name, memory_item.clone(), self.into())?;
.add(self.name.clone(), memory_item.clone(), self.into())?;

Ok(self.into())
}
Expand Down Expand Up @@ -1529,14 +1531,18 @@ fn assign_args_to_params(
for (index, param) in function_expression.params.iter().enumerate() {
if let Some(arg) = args.get(index) {
// Argument was provided.
fn_memory.add(&param.identifier.name, arg.value.clone(), (&param.identifier).into())?;
fn_memory.add(
param.identifier.name.clone(),
arg.value.clone(),
(&param.identifier).into(),
)?;
} else {
// Argument was not provided.
if let Some(ref default_val) = param.default_value {
// If the corresponding parameter is optional,
// then it's fine, the user doesn't need to supply it.
fn_memory.add(
&param.identifier.name,
param.identifier.name.clone(),
default_val.clone().into(),
(&param.identifier).into(),
)?;
Expand Down Expand Up @@ -1576,7 +1582,7 @@ fn assign_args_to_params_kw(
}
},
};
fn_memory.add(&param.identifier.name, arg_val, (&param.identifier).into())?;
fn_memory.add(param.identifier.name.clone(), arg_val, (&param.identifier).into())?;
} else {
let Some(unlabeled) = args.unlabeled.take() else {
let param_name = &param.identifier.name;
Expand All @@ -1594,7 +1600,7 @@ fn assign_args_to_params_kw(
});
};
fn_memory.add(
&param.identifier.name,
param.identifier.name.clone(),
unlabeled.value.clone(),
(&param.identifier).into(),
)?;
Expand Down Expand Up @@ -1754,7 +1760,7 @@ mod test {
let mut program_memory = ProgramMemory::new();
for (name, item) in items {
program_memory
.add(name.as_str(), item.clone(), SourceRange::default())
.add(name.clone(), item.clone(), SourceRange::default())
.unwrap();
}
program_memory
Expand Down
Loading

0 comments on commit 6ec1715

Please sign in to comment.