Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UoM types in AST, unnamed annotations, and syntax for importing from std #5324

Merged
merged 1 commit into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/wasm-lib/kcl/src/execution/annotations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
pub(crate) const SETTINGS: &str = "settings";
pub(crate) const SETTINGS_UNIT_LENGTH: &str = "defaultLengthUnit";
pub(crate) const SETTINGS_UNIT_ANGLE: &str = "defaultAngleUnit";
pub(super) const NO_PRELUDE: &str = "no_prelude";

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(super) enum AnnotationScope {
Expand All @@ -23,7 +24,7 @@ pub(super) fn expect_properties<'a>(
) -> Result<&'a [Node<ObjectProperty>], KclError> {
match annotation {
NonCodeValue::Annotation { name, properties } => {
assert_eq!(name.name, for_key);
assert_eq!(name.as_ref().unwrap().name, for_key);
Ok(&**properties.as_ref().ok_or_else(|| {
KclError::Semantic(KclErrorDetails {
message: format!("Empty `{for_key}` annotation"),
Expand Down
2 changes: 1 addition & 1 deletion src/wasm-lib/kcl/src/execution/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ pub(super) async fn get_changed_program(old: CacheInformation<'_>, new: CacheInf
properties: new_properties,
},
) => {
name.digest == new_name.digest
name.as_ref().map(|n| n.digest) == new_name.as_ref().map(|n| n.digest)
&& properties
.as_ref()
.map(|props| props.iter().map(|p| p.digest).collect::<Vec<_>>())
Expand Down
153 changes: 81 additions & 72 deletions src/wasm-lib/kcl/src/execution/exec_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@
annotations,
cad_op::{OpArg, Operation},
state::ModuleState,
BodyType, ExecState, ExecutorContext, KclValue, MemoryFunction, Metadata, ModuleRepr, ProgramMemory,
TagEngineInfo, TagIdentifier,
BodyType, ExecState, ExecutorContext, KclValue, MemoryFunction, Metadata, ModulePath, ModuleRepr,
ProgramMemory, TagEngineInfo, TagIdentifier,
},
fs::FileSystem,
parsing::ast::types::{
ArrayExpression, ArrayRangeExpression, BinaryExpression, BinaryOperator, BinaryPart, BodyItem, CallExpression,
CallExpressionKw, Expr, FunctionExpression, IfExpression, ImportPath, ImportSelector, ItemVisibility,
Expand All @@ -38,7 +37,8 @@
annotations: impl Iterator<Item = (&NonCodeValue, SourceRange)>,
scope: annotations::AnnotationScope,
exec_state: &mut ExecState,
) -> Result<(), KclError> {
) -> Result<bool, KclError> {
let mut no_prelude = false;
for (annotation, source_range) in annotations {
if annotation.annotation_name() == Some(annotations::SETTINGS) {
if scope == annotations::AnnotationScope::Module {
Expand All @@ -48,7 +48,7 @@
.settings
.update_from_annotation(annotation, source_range)?;
let new_units = exec_state.length_unit();
if old_units != new_units {
if !self.engine.execution_kind().is_isolated() && old_units != new_units {
self.engine.set_units(new_units.into(), source_range).await?;
}
} else {
Expand All @@ -58,9 +58,19 @@
}));
}
}
if annotation.annotation_name() == Some(annotations::NO_PRELUDE) {
if scope == annotations::AnnotationScope::Module {
no_prelude = true;
} else {
return Err(KclError::Semantic(KclErrorDetails {
message: "Prelude can only be skipped at the top level scope of a file".to_owned(),
source_ranges: vec![source_range],
}));

Check warning on line 68 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#L62-L68

Added lines #L62 - L68 were not covered by tests
}
}
// TODO warn on unknown annotations
}
Ok(())
Ok(no_prelude)
}

/// Execute an AST's program.
Expand All @@ -71,22 +81,32 @@
exec_state: &mut ExecState,
body_type: BodyType,
) -> Result<Option<KclValue>, KclError> {
self.handle_annotations(
program
.non_code_meta
.start_nodes
.iter()
.filter_map(|n| n.annotation().map(|result| (result, n.as_source_range()))),
annotations::AnnotationScope::Module,
exec_state,
)
.await?;
if body_type == BodyType::Root {
let _no_prelude = self
.handle_annotations(
program
.non_code_meta
.start_nodes
.iter()
.filter_map(|n| n.annotation().map(|result| (result, n.as_source_range()))),
annotations::AnnotationScope::Module,
exec_state,
)
.await?;
}

let mut last_expr = None;
// Iterate over the body of the program.
for statement in &program.body {
for (i, statement) in program.body.iter().enumerate() {
match statement {
BodyItem::ImportStatement(import_stmt) => {
if body_type != BodyType::Root {
return Err(KclError::Semantic(KclErrorDetails {
message: "Imports are only supported at the top-level of a file.".to_owned(),
source_ranges: vec![import_stmt.into()],
}));

Check warning on line 107 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#L105-L107

Added lines #L105 - L107 were not covered by tests
}

let source_range = SourceRange::from(import_stmt);
let module_id = self.open_module(&import_stmt.path, exec_state, source_range).await?;

Expand Down Expand Up @@ -178,6 +198,14 @@
let source_range = SourceRange::from(&variable_declaration.declaration.init);
let metadata = Metadata { source_range };

let _meta_nodes = if i == 0 {
&program.non_code_meta.start_nodes
} else if let Some(meta) = program.non_code_meta.non_code_nodes.get(&(i - 1)) {
meta
} else {
&Vec::new()
};

let memory_item = self
.execute_expr(
&variable_declaration.declaration.init,
Expand Down Expand Up @@ -231,63 +259,45 @@
exec_state: &mut ExecState,
source_range: SourceRange,
) -> Result<ModuleId, KclError> {
let resolved_path = ModulePath::from_import_path(path, &self.settings.project_directory);
match path {
ImportPath::Kcl { filename } => {
let resolved_path = if let Some(project_dir) = &self.settings.project_directory {
project_dir.join(filename)
} else {
std::path::PathBuf::from(filename)
};
ImportPath::Kcl { .. } => {
exec_state.global.mod_loader.cycle_check(&resolved_path, source_range)?;

if exec_state.mod_local.import_stack.contains(&resolved_path) {
return Err(KclError::ImportCycle(KclErrorDetails {
message: format!(
"circular import of modules is not allowed: {} -> {}",
exec_state
.mod_local
.import_stack
.iter()
.map(|p| p.as_path().to_string_lossy())
.collect::<Vec<_>>()
.join(" -> "),
resolved_path.to_string_lossy()
),
source_ranges: vec![source_range],
}));
}

if let Some(id) = exec_state.global.path_to_source_id.get(&resolved_path) {
return Ok(*id);
if let Some(id) = exec_state.id_for_module(&resolved_path) {
return Ok(id);
}

let source = self.fs.read_to_string(&resolved_path, source_range).await?;
let id = ModuleId::from_usize(exec_state.global.path_to_source_id.len());
let id = exec_state.next_module_id();
let source = resolved_path.source(&self.fs, source_range).await?;
// TODO handle parsing errors properly
let parsed = crate::parsing::parse_str(&source, id).parse_errs_as_err()?;
let repr = ModuleRepr::Kcl(parsed);

Ok(exec_state.add_module(id, resolved_path, repr))
exec_state.add_module(id, resolved_path, ModuleRepr::Kcl(parsed));
Ok(id)
}
ImportPath::Foreign { path } => {
let resolved_path = if let Some(project_dir) = &self.settings.project_directory {
project_dir.join(path)
} else {
std::path::PathBuf::from(path)
};
ImportPath::Foreign { .. } => {
if let Some(id) = exec_state.id_for_module(&resolved_path) {
return Ok(id);

Check warning on line 280 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#L280

Added line #L280 was not covered by tests
}

if let Some(id) = exec_state.global.path_to_source_id.get(&resolved_path) {
return Ok(*id);
let id = exec_state.next_module_id();
let geom =
super::import::import_foreign(resolved_path.expect_path(), None, exec_state, self, source_range)
.await?;
exec_state.add_module(id, resolved_path, ModuleRepr::Foreign(geom));
Ok(id)
}
ImportPath::Std { .. } => {
if let Some(id) = exec_state.id_for_module(&resolved_path) {
return Ok(id);

Check warning on line 292 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#L291-L292

Added lines #L291 - L292 were not covered by tests
}

let geom = super::import::import_foreign(&resolved_path, None, exec_state, self, source_range).await?;
let repr = ModuleRepr::Foreign(geom);
let id = ModuleId::from_usize(exec_state.global.path_to_source_id.len());
Ok(exec_state.add_module(id, resolved_path, repr))
let id = exec_state.next_module_id();
let source = resolved_path.source(&self.fs, source_range).await?;
let parsed = crate::parsing::parse_str(&source, id).parse_errs_as_err().unwrap();
exec_state.add_module(id, resolved_path, ModuleRepr::Kcl(parsed));
Ok(id)

Check warning on line 299 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#L295-L299

Added lines #L295 - L299 were not covered by tests
}
i => Err(KclError::Semantic(KclErrorDetails {
message: format!("Unsupported import: `{i}`"),
source_ranges: vec![source_range],
})),
}
}

Expand All @@ -307,22 +317,20 @@
message: format!(
"circular import of modules is not allowed: {} -> {}",
exec_state
.mod_local
.global
.mod_loader
.import_stack
.iter()
.map(|p| p.as_path().to_string_lossy())
.collect::<Vec<_>>()
.join(" -> "),
info.path.display()
info.path
),
source_ranges: vec![source_range],
})),
ModuleRepr::Kcl(program) => {
let mut local_state = ModuleState {
import_stack: exec_state.mod_local.import_stack.clone(),
..ModuleState::new(&self.settings)
};
local_state.import_stack.push(info.path.clone());
let mut local_state = ModuleState::new(&self.settings);
exec_state.global.mod_loader.enter_module(&info.path);
std::mem::swap(&mut exec_state.mod_local, &mut local_state);
let original_execution = self.engine.replace_execution_kind(exec_kind);

Expand All @@ -332,7 +340,8 @@

let new_units = exec_state.length_unit();
std::mem::swap(&mut exec_state.mod_local, &mut local_state);
if new_units != old_units {
exec_state.global.mod_loader.leave_module(&info.path);
if !exec_kind.is_isolated() && new_units != old_units {
self.engine.set_units(old_units.into(), Default::default()).await?;
}
self.engine.replace_execution_kind(original_execution);
Expand All @@ -345,7 +354,7 @@
KclError::Semantic(KclErrorDetails {
message: format!(
"Error loading imported file. Open it to view more details. {}: {}",
info.path.display(),
info.path,

Check warning on line 357 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#L357

Added line #L357 was not covered by tests
err.message()
),
source_ranges: vec![source_range],
Expand Down
Loading
Loading