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

better track the root source code #5558

Merged
merged 4 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
34 changes: 12 additions & 22 deletions src/wasm-lib/kcl/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ impl KclErrorWithOutputs {
source_files: Default::default(),
}
}
pub fn into_miette_report_with_outputs(self, code: &str) -> anyhow::Result<ReportWithOutputs> {
pub fn into_miette_report_with_outputs(self) -> anyhow::Result<ReportWithOutputs> {
let mut source_ranges = self.error.source_ranges();

// Pop off the first source range to get the filename.
Expand All @@ -162,33 +162,23 @@ impl KclErrorWithOutputs {
.source_files
.get(&first_source_range.module_id())
.cloned()
.unwrap_or(ModuleSource {
source: code.to_string(),
path: self
.filenames
.get(&first_source_range.module_id())
.ok_or_else(|| {
anyhow::anyhow!(
"Could not find filename for module id: {:?}",
first_source_range.module_id()
)
})?
.clone(),
});
.ok_or_else(|| {
anyhow::anyhow!(
"Could not find source file for module id: {:?}",
first_source_range.module_id()
)
})?;
let filename = source.path.to_string();
let kcl_source = source.source.to_string();

let mut related = Vec::new();
for source_range in source_ranges {
let module_id = source_range.module_id();
let source = self.source_files.get(&module_id).cloned().unwrap_or(ModuleSource {
source: code.to_string(),
path: self
.filenames
.get(&module_id)
.ok_or_else(|| anyhow::anyhow!("Could not find filename for module id: {:?}", module_id))?
.clone(),
});
let source = self
.source_files
.get(&module_id)
.cloned()
.ok_or_else(|| anyhow::anyhow!("Could not find source file for module id: {:?}", module_id))?;
let error = self.error.override_source_ranges(vec![source_range]);
let report = Report {
error,
Expand Down
21 changes: 15 additions & 6 deletions src/wasm-lib/kcl/src/execution/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,7 @@ impl ExecutorContext {
}
}

exec_state.add_root_module_contents(&program);
let result = self.inner_run(&program.ast, &mut exec_state, true).await?;

// Restore any temporary variables, then save any newly created variables back to
Expand Down Expand Up @@ -585,9 +586,15 @@ impl ExecutorContext {
.await
.is_err()
{
(true, program.ast)
(true, program)
} else {
(clear_scene, changed_program)
(
clear_scene,
crate::Program {
ast: changed_program,
original_file_contents: program.original_file_contents,
},
)
}
}
CacheResult::NoAction(true) => {
Expand All @@ -608,7 +615,7 @@ impl ExecutorContext {

return Ok(old_state.to_wasm_outcome(result_env));
}
(true, program.ast)
(true, program)
}
CacheResult::NoAction(false) => return Ok(old_state.to_wasm_outcome(result_env)),
};
Expand Down Expand Up @@ -636,10 +643,11 @@ impl ExecutorContext {
self.send_clear_scene(&mut exec_state, Default::default())
.await
.map_err(KclErrorWithOutputs::no_outputs)?;
(program.ast, exec_state, false)
(program, exec_state, false)
};

let result = self.inner_run(&program, &mut exec_state, preserve_mem).await;
exec_state.add_root_module_contents(&program);
let result = self.inner_run(&program.ast, &mut exec_state, preserve_mem).await;

if result.is_err() {
cache::bust_cache().await;
Expand All @@ -650,7 +658,7 @@ impl ExecutorContext {

// Save this as the last successful execution to the cache.
cache::write_old_ast(OldAstState {
ast: program,
ast: program.ast,
exec_state: exec_state.clone(),
settings: self.settings.clone(),
result_env: result.0,
Expand Down Expand Up @@ -691,6 +699,7 @@ impl ExecutorContext {
self.send_clear_scene(exec_state, Default::default())
.await
.map_err(KclErrorWithOutputs::no_outputs)?;
exec_state.add_root_module_contents(program);
self.inner_run(&program.ast, exec_state, false).await
}

Expand Down
22 changes: 20 additions & 2 deletions src/wasm-lib/kcl/src/execution/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,26 @@ impl ExecState {
self.global.path_to_source_id.insert(path.clone(), id);
}

pub(crate) fn add_root_module_contents(&mut self, program: &crate::Program) {
let root_id = ModuleId::default();
// Get the path for the root module.
let path = self
.global
.path_to_source_id
.iter()
.find(|(_, v)| **v == root_id)
.unwrap()
.0
.clone();
self.add_id_to_source(
root_id,
ModuleSource {
path,
source: program.original_file_contents.to_string(),
},
);
}

pub(super) fn add_id_to_source(&mut self, id: ModuleId, source: ModuleSource) {
debug_assert!(!self.global.id_to_source.contains_key(&id));
self.global.id_to_source.insert(id, source.clone());
Expand Down Expand Up @@ -251,8 +271,6 @@ impl GlobalState {
global
.path_to_source_id
.insert(ModulePath::Local { value: root_path }, root_id);
// Ideally we'd have a way to set the root module's source here, but
// we don't have a way to get the source from the executor settings.
global
}
}
Expand Down
24 changes: 21 additions & 3 deletions src/wasm-lib/kcl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ use crate::log::{log, logln};
pub struct Program {
#[serde(flatten)]
pub ast: parsing::ast::types::Node<parsing::ast::types::Program>,
// The ui doesn't need to know about this.
// It's purely used for saving the contents of the original file, so we can use it for errors.
// Because in the case of the root file, we don't want to read the file from disk again.
#[serde(skip)]
pub original_file_contents: String,
}

#[cfg(any(test, feature = "lsp-test-util"))]
Expand All @@ -147,15 +152,24 @@ impl Program {
let tokens = parsing::token::lex(input, module_id)?;
let (ast, errs) = parsing::parse_tokens(tokens).0?;

Ok((ast.map(|ast| Program { ast }), errs))
Ok((
ast.map(|ast| Program {
ast,
original_file_contents: input.to_string(),
}),
errs,
))
}

pub fn parse_no_errs(input: &str) -> Result<Program, KclError> {
let module_id = ModuleId::default();
let tokens = parsing::token::lex(input, module_id)?;
let ast = parsing::parse_tokens(tokens).parse_errs_as_err()?;

Ok(Program { ast })
Ok(Program {
ast,
original_file_contents: input.to_string(),
})
}

pub fn compute_digest(&mut self) -> parsing::ast::digest::Digest {
Expand All @@ -171,6 +185,7 @@ impl Program {
pub fn change_meta_settings(&mut self, settings: crate::MetaSettings) -> Result<Self, KclError> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a weird method because it looks like it mutates the self passed in and returns a clone of itself? I'm a bit averse to cloning the program text (and the AST?) here, so could it take self by value or just mutate self rather than cloning?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah okay wasnt part of this pr but i can fix

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done!

Ok(Self {
ast: self.ast.change_meta_settings(settings)?,
original_file_contents: self.original_file_contents.clone(),
})
}

Expand All @@ -194,7 +209,10 @@ impl Program {

impl From<parsing::ast::types::Node<parsing::ast::types::Program>> for Program {
fn from(ast: parsing::ast::types::Node<parsing::ast::types::Program>) -> Program {
Self { ast }
Self {
ast,
original_file_contents: String::new(),
}
}
}

Expand Down
5 changes: 1 addition & 4 deletions src/wasm-lib/kcl/src/simulation_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,7 @@ async fn execute(test_name: &str, render_to_png: bool) {
Box::new(miette::MietteHandlerOpts::new().show_related_errors_as_nested().build())
}))
.unwrap();
let report = error
.clone()
.into_miette_report_with_outputs(&read("input.kcl", test_name))
.unwrap();
let report = error.clone().into_miette_report_with_outputs().unwrap();
let report = miette::Report::new(report);
if previously_passed {
eprintln!("This test case failed, but it previously passed. If this is intended, and the test should actually be failing now, please delete kcl/{ok_path_str} and other associated passing artifacts");
Expand Down
Loading