Bump cargo to 1.88; 2024 edition for kcl-lib (#7618)

This is a big one because the edition changes a fair number of things.
This commit is contained in:
Adam Chalmers
2025-06-26 17:02:54 -05:00
committed by GitHub
parent 6a2027cd51
commit 4356885aa2
100 changed files with 769 additions and 802 deletions

View File

@ -2,13 +2,13 @@
use std::str::FromStr;
use kittycad_modeling_cmds::coord::{System, KITTYCAD, OPENGL, VULKAN};
use kittycad_modeling_cmds::coord::{KITTYCAD, OPENGL, System, VULKAN};
use crate::{
KclError, SourceRange,
errors::KclErrorDetails,
execution::types::{UnitAngle, UnitLen},
parsing::ast::types::{Annotation, Expr, LiteralValue, Node, ObjectProperty},
KclError, SourceRange,
};
/// Annotations which should cause re-execution if they change.

View File

@ -1,20 +1,19 @@
use fnv::FnvHashMap;
use indexmap::IndexMap;
use kittycad_modeling_cmds::{
self as kcmc,
self as kcmc, EnableSketchMode, ModelingCmd,
ok_response::OkModelingCmdResponse,
shared::ExtrusionFaceCapType,
websocket::{BatchResponse, OkWebSocketResponseData, WebSocketResponse},
EnableSketchMode, ModelingCmd,
};
use serde::{ser::SerializeSeq, Serialize};
use serde::{Serialize, ser::SerializeSeq};
use uuid::Uuid;
use crate::{
KclError, NodePath, SourceRange,
errors::KclErrorDetails,
execution::ArtifactId,
parsing::ast::types::{Node, Program},
KclError, NodePath, SourceRange,
};
#[cfg(test)]
@ -893,7 +892,10 @@ fn artifacts_to_update(
),
};
if original_path_ids.len() != face_edge_infos.len() {
internal_error!(range, "EntityMirror or EntityMirrorAcrossEdge response has different number face edge info than original mirrored paths: id={id:?}, cmd={cmd:?}, response={response:?}");
internal_error!(
range,
"EntityMirror or EntityMirrorAcrossEdge response has different number face edge info than original mirrored paths: id={id:?}, cmd={cmd:?}, response={response:?}"
);
}
let mut return_arr = Vec::new();
for (face_edge_info, original_path_id) in face_edge_infos.iter().zip(original_path_ids) {
@ -909,7 +911,10 @@ fn artifacts_to_update(
// of its info.
let Some(Artifact::Path(original_path)) = artifacts.get(&original_path_id) else {
// We couldn't find the original path. This is a bug.
internal_error!(range, "Couldn't find original path for mirror2d: original_path_id={original_path_id:?}, cmd={cmd:?}");
internal_error!(
range,
"Couldn't find original path for mirror2d: original_path_id={original_path_id:?}, cmd={cmd:?}"
);
};
Path {
id: path_id,

View File

@ -268,7 +268,7 @@ impl ArtifactGraph {
for (group_id, artifact_ids) in groups {
let group_id = *stable_id_map.get(&group_id).unwrap();
writeln!(output, "{prefix}subgraph path{group_id} [Path]")?;
let indented = format!("{} ", prefix);
let indented = format!("{prefix} ");
for artifact_id in artifact_ids {
let artifact = self.map.get(&artifact_id).unwrap();
let id = *stable_id_map.get(&artifact_id).unwrap();
@ -353,7 +353,7 @@ impl ArtifactGraph {
node_path_display(output, prefix, None, &segment.code_ref)?;
}
Artifact::Solid2d(_solid2d) => {
writeln!(output, "{prefix}{}[Solid2d]", id)?;
writeln!(output, "{prefix}{id}[Solid2d]")?;
}
Artifact::StartSketchOnFace(StartSketchOnFace { code_ref, .. }) => {
writeln!(
@ -494,24 +494,24 @@ impl ArtifactGraph {
match edge.flow {
EdgeFlow::SourceToTarget => match edge.direction {
EdgeDirection::Forward => {
writeln!(output, "{prefix}{source_id} x{}--> {}", extra, target_id)?;
writeln!(output, "{prefix}{source_id} x{extra}--> {target_id}")?;
}
EdgeDirection::Backward => {
writeln!(output, "{prefix}{source_id} <{}--x {}", extra, target_id)?;
writeln!(output, "{prefix}{source_id} <{extra}--x {target_id}")?;
}
EdgeDirection::Bidirectional => {
writeln!(output, "{prefix}{source_id} {}--- {}", extra, target_id)?;
writeln!(output, "{prefix}{source_id} {extra}--- {target_id}")?;
}
},
EdgeFlow::TargetToSource => match edge.direction {
EdgeDirection::Forward => {
writeln!(output, "{prefix}{target_id} x{}--> {}", extra, source_id)?;
writeln!(output, "{prefix}{target_id} x{extra}--> {source_id}")?;
}
EdgeDirection::Backward => {
writeln!(output, "{prefix}{target_id} <{}--x {}", extra, source_id)?;
writeln!(output, "{prefix}{target_id} <{extra}--x {source_id}")?;
}
EdgeDirection::Bidirectional => {
writeln!(output, "{prefix}{target_id} {}--- {}", extra, source_id)?;
writeln!(output, "{prefix}{target_id} {extra}--- {source_id}")?;
}
},
}

View File

@ -6,15 +6,14 @@ use itertools::{EitherOrBoth, Itertools};
use tokio::sync::RwLock;
use crate::{
ExecOutcome, ExecutorContext,
execution::{
annotations,
EnvironmentRef, ExecutorSettings, annotations,
memory::Stack,
state::{self as exec_state, ModuleInfoMap},
EnvironmentRef, ExecutorSettings,
},
parsing::ast::types::{Annotation, Node, Program},
walk::Node as WalkNode,
ExecOutcome, ExecutorContext,
};
lazy_static::lazy_static! {
@ -337,7 +336,7 @@ mod tests {
use pretty_assertions::assert_eq;
use super::*;
use crate::execution::{parse_execute, parse_execute_with_project_dir, ExecTestResults};
use crate::execution::{ExecTestResults, parse_execute, parse_execute_with_project_dir};
#[tokio::test(flavor = "multi_thread")]
async fn test_get_changed_program_same_code() {
@ -755,7 +754,7 @@ extrude(profile001, length = 100)"#
.await;
let CacheResult::CheckImportsOnly { reapply_settings, .. } = result else {
panic!("Expected CheckImportsOnly, got {:?}", result);
panic!("Expected CheckImportsOnly, got {result:?}");
};
assert_eq!(reapply_settings, false);
@ -839,7 +838,7 @@ extrude(profile001, length = 100)
.await;
let CacheResult::CheckImportsOnly { reapply_settings, .. } = result else {
panic!("Expected CheckImportsOnly, got {:?}", result);
panic!("Expected CheckImportsOnly, got {result:?}");
};
assert_eq!(reapply_settings, false);

View File

@ -1,10 +1,10 @@
use indexmap::IndexMap;
use serde::Serialize;
use super::{types::NumericType, ArtifactId, KclValue};
use super::{ArtifactId, KclValue, types::NumericType};
#[cfg(feature = "artifact-graph")]
use crate::parsing::ast::types::{Node, Program};
use crate::{parsing::ast::types::ItemVisibility, ModuleId, NodePath, SourceRange};
use crate::{ModuleId, NodePath, SourceRange, parsing::ast::types::ItemVisibility};
/// A CAD modeling operation for display in the feature tree, AKA operations
/// timeline.
@ -57,7 +57,7 @@ impl Operation {
/// If the variant is `StdLibCall`, set the `is_error` field.
pub(crate) fn set_std_lib_call_is_error(&mut self, is_err: bool) {
match self {
Self::StdLibCall { ref mut is_error, .. } => *is_error = is_err,
Self::StdLibCall { is_error, .. } => *is_error = is_err,
Self::VariableDeclaration { .. } | Self::GroupBegin { .. } | Self::GroupEnd => {}
}
}

View File

@ -3,17 +3,17 @@ use std::collections::HashMap;
use async_recursion::async_recursion;
use crate::{
CompilationError, NodePath,
errors::{KclError, KclErrorDetails},
execution::{
annotations,
BodyType, EnvironmentRef, ExecState, ExecutorContext, KclValue, Metadata, ModelingCmdMeta, ModuleArtifactState,
Operation, PlaneType, StatementKind, TagIdentifier, annotations,
cad_op::OpKclValue,
fn_call::Args,
kcl_value::{FunctionSource, TypeDef},
memory,
state::ModuleState,
types::{NumericType, PrimitiveType, RuntimeType},
BodyType, EnvironmentRef, ExecState, ExecutorContext, KclValue, Metadata, ModelingCmdMeta, ModuleArtifactState,
Operation, PlaneType, StatementKind, TagIdentifier,
},
fmt,
modules::{ModuleId, ModulePath, ModuleRepr},
@ -28,7 +28,6 @@ use crate::{
},
source_range::SourceRange,
std::args::TyF64,
CompilationError, NodePath,
};
impl<'a> StatementKind<'a> {
@ -198,19 +197,23 @@ impl ExecutorContext {
}
if ty.is_ok() && !module_exports.contains(&ty_name) {
ty = Err(KclError::new_semantic(KclErrorDetails::new(format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
),
vec![SourceRange::from(&import_item.name)],)));
ty = Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
),
vec![SourceRange::from(&import_item.name)],
)));
}
if mod_value.is_ok() && !module_exports.contains(&mod_name) {
mod_value = Err(KclError::new_semantic(KclErrorDetails::new(format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
),
vec![SourceRange::from(&import_item.name)],)));
mod_value = Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"Cannot import \"{}\" from module because it is not exported. Add \"export\" before the definition to export it.",
import_item.name.name
),
vec![SourceRange::from(&import_item.name)],
)));
}
if value.is_err() && ty.is_err() && mod_value.is_err() {
@ -270,7 +273,7 @@ impl ExecutorContext {
.get_from(name, env_ref, source_range, 0)
.map_err(|_err| {
KclError::new_internal(KclErrorDetails::new(
format!("{} is not defined in module (but was exported?)", name),
format!("{name} is not defined in module (but was exported?)"),
vec![source_range],
))
})?
@ -431,7 +434,7 @@ impl ExecutorContext {
return Err(KclError::new_semantic(KclErrorDetails::new(
"User-defined types are not yet supported.".to_owned(),
vec![metadata.source_range],
)))
)));
}
},
}
@ -792,11 +795,12 @@ fn var_in_own_ref_err(e: KclError, being_declared: &Option<String>) -> KclError
// TODO after June 26th: replace this with a let-chain,
// which will be available in Rust 1.88
// https://rust-lang.github.io/rfcs/2497-if-let-chains.html
match (&being_declared, &name) {
(Some(name0), Some(name1)) if name0 == name1 => {
details.message = format!("You can't use `{name0}` because you're currently trying to define it. Use a different variable here instead.");
}
_ => {}
if let (Some(name0), Some(name1)) = (&being_declared, &name)
&& name0 == name1
{
details.message = format!(
"You can't use `{name0}` because you're currently trying to define it. Use a different variable here instead."
);
}
KclError::UndefinedValue { details, name }
}
@ -1077,7 +1081,7 @@ impl Node<BinaryExpression> {
(&left_value, &right_value)
{
return Ok(KclValue::String {
value: format!("{}{}", left, right),
value: format!("{left}{right}"),
meta,
});
}
@ -1237,7 +1241,9 @@ impl Node<BinaryExpression> {
exec_state.clear_units_warnings(&sr);
let mut err = CompilationError::err(
sr,
format!("{} numbers which have unknown or incompatible units.\nYou can probably fix this error by specifying the units using type ascription, e.g., `len: number(mm)` or `(a * b): number(deg)`.", verb),
format!(
"{verb} numbers which have unknown or incompatible units.\nYou can probably fix this error by specifying the units using type ascription, e.g., `len: number(mm)` or `(a * b): number(deg)`."
),
);
err.tag = crate::errors::Tag::UnknownNumericUnits;
exec_state.warn(err);
@ -1417,7 +1423,7 @@ async fn inner_execute_pipe_body(
for expression in body {
if let Expr::TagDeclarator(_) = expression {
return Err(KclError::new_semantic(KclErrorDetails::new(
format!("This cannot be in a PipeExpression: {:?}", expression),
format!("This cannot be in a PipeExpression: {expression:?}"),
vec![expression.into()],
)));
}
@ -1699,9 +1705,15 @@ fn jvalue_to_prop(value: &KclValue, property_sr: Vec<SourceRange>, name: &str) -
let make_err =
|message: String| Err::<Property, _>(KclError::new_semantic(KclErrorDetails::new(message, property_sr)));
match value {
n @ KclValue::Number{value: num, ty, .. } => {
if !matches!(ty, NumericType::Known(crate::exec::UnitType::Count) | NumericType::Default { .. } | NumericType::Any ) {
return make_err(format!("arrays can only be indexed by non-dimensioned numbers, found {}", n.human_friendly_type()));
n @ KclValue::Number { value: num, ty, .. } => {
if !matches!(
ty,
NumericType::Known(crate::exec::UnitType::Count) | NumericType::Default { .. } | NumericType::Any
) {
return make_err(format!(
"arrays can only be indexed by non-dimensioned numbers, found {}",
n.human_friendly_type()
));
}
let num = *num;
if num < 0.0 {
@ -1711,13 +1723,15 @@ fn jvalue_to_prop(value: &KclValue, property_sr: Vec<SourceRange>, name: &str) -
if let Some(nearest_int) = nearest_int {
Ok(Property::UInt(nearest_int))
} else {
make_err(format!("'{num}' is not an integer, so you can't index an array with it"))
make_err(format!(
"'{num}' is not an integer, so you can't index an array with it"
))
}
}
KclValue::String{value: x, meta:_} => Ok(Property::String(x.to_owned())),
_ => {
make_err(format!("{name} is not a valid property/index, you can only use a string to get the property of an object, or an int (>= 0) to get an item in an array"))
}
KclValue::String { value: x, meta: _ } => Ok(Property::String(x.to_owned())),
_ => make_err(format!(
"{name} is not a valid property/index, you can only use a string to get the property of an object, or an int (>= 0) to get an item in an array"
)),
}
}
@ -1745,9 +1759,9 @@ mod test {
use super::*;
use crate::{
exec::UnitType,
execution::{parse_execute, ContextType},
ExecutorSettings, UnitLen,
exec::UnitType,
execution::{ContextType, parse_execute},
};
#[tokio::test(flavor = "multi_thread")]
@ -1777,7 +1791,7 @@ arr1 = [42]: [number(cm)]
.get_from("arr1", result.mem_env, SourceRange::default(), 0)
.unwrap();
if let KclValue::HomArray { value, ty } = arr1 {
assert_eq!(value.len(), 1, "Expected Vec with specific length: found {:?}", value);
assert_eq!(value.len(), 1, "Expected Vec with specific length: found {value:?}");
assert_eq!(*ty, RuntimeType::known_length(UnitLen::Cm));
// Compare, ignoring meta.
if let KclValue::Number { value, ty, .. } = &value[0] {
@ -1946,7 +1960,7 @@ d = b + c
.await
.map_err(|err| {
KclError::new_internal(KclErrorDetails::new(
format!("Failed to create mock engine connection: {}", err),
format!("Failed to create mock engine connection: {err}"),
vec![SourceRange::default()],
))
})

View File

@ -2,19 +2,19 @@ use async_recursion::async_recursion;
use indexmap::IndexMap;
use crate::{
CompilationError, NodePath,
errors::{KclError, KclErrorDetails},
execution::{
BodyType, EnvironmentRef, ExecState, ExecutorContext, KclValue, Metadata, StatementKind, TagEngineInfo,
TagIdentifier,
cad_op::{Group, OpArg, OpKclValue, Operation},
kcl_value::FunctionSource,
memory,
types::RuntimeType,
BodyType, EnvironmentRef, ExecState, ExecutorContext, KclValue, Metadata, StatementKind, TagEngineInfo,
TagIdentifier,
},
parsing::ast::types::{CallExpressionKw, DefaultParamVal, FunctionExpression, Node, Program, Type},
source_range::SourceRange,
std::StdFn,
CompilationError, NodePath,
};
#[derive(Debug, Clone)]
@ -269,7 +269,7 @@ impl Node<CallExpressionKw> {
};
KclError::new_undefined_value(
KclErrorDetails::new(
format!("Result of user-defined function {} is undefined", fn_name),
format!("Result of user-defined function {fn_name} is undefined"),
source_ranges,
),
None,
@ -445,7 +445,7 @@ fn update_memory_for_tags_of_geometry(result: &mut KclValue, exec_state: &mut Ex
}
}
}
KclValue::Solid { ref mut value } => {
KclValue::Solid { value } => {
for v in &value.value {
if let Some(tag) = v.get_tag() {
// Get the past tag and update it.
@ -555,9 +555,9 @@ fn type_err_str(expected: &Type, found: &KclValue, source_range: &SourceRange, e
let found_human = found.human_friendly_type();
let found_ty = found.principal_type_string();
let found_str = if found_human == found_ty || found_human == format!("a {}", strip_backticks(&found_ty)) {
format!("a value with type {}", found_ty)
format!("a value with type {found_ty}")
} else {
format!("{found_human} (with type {})", found_ty)
format!("{found_human} (with type {found_ty})")
};
let mut result = format!("{expected_str}, but found {found_str}.");
@ -626,7 +626,7 @@ fn type_check_params_kw(
format!(
"`{label}` is not an argument of {}",
fn_name
.map(|n| format!("`{}`", n))
.map(|n| format!("`{n}`"))
.unwrap_or_else(|| "this function".to_owned()),
),
));
@ -676,7 +676,7 @@ fn type_check_params_kw(
format!(
"The input argument of {} requires {}",
fn_name
.map(|n| format!("`{}`", n))
.map(|n| format!("`{n}`"))
.unwrap_or_else(|| "this function".to_owned()),
type_err_str(ty, &arg.1.value, &arg.1.source_range, exec_state),
),
@ -691,7 +691,7 @@ fn type_check_params_kw(
format!(
"{} expects an unlabeled first argument (`@{name}`), but it is labelled in the call",
fn_name
.map(|n| format!("The function `{}`", n))
.map(|n| format!("The function `{n}`"))
.unwrap_or_else(|| "This function".to_owned()),
),
));
@ -721,7 +721,7 @@ fn assign_args_to_params_kw(
)?;
}
None => match default {
Some(ref default_val) => {
Some(default_val) => {
let value = KclValue::from_default_param(default_val.clone(), exec_state);
exec_state
.mut_stack()
@ -729,10 +729,7 @@ fn assign_args_to_params_kw(
}
None => {
return Err(KclError::new_semantic(KclErrorDetails::new(
format!(
"This function requires a parameter {}, but you haven't passed it one.",
name
),
format!("This function requires a parameter {name}, but you haven't passed it one."),
source_ranges,
)));
}
@ -746,7 +743,9 @@ fn assign_args_to_params_kw(
let Some(unlabeled) = unlabelled else {
return Err(if args.kw_args.labeled.contains_key(param_name) {
KclError::new_semantic(KclErrorDetails::new(
format!("The function does declare a parameter named '{param_name}', but this parameter doesn't use a label. Try removing the `{param_name}:`"),
format!(
"The function does declare a parameter named '{param_name}', but this parameter doesn't use a label. Try removing the `{param_name}:`"
),
source_ranges,
))
} else {
@ -799,7 +798,7 @@ mod test {
use super::*;
use crate::{
execution::{memory::Stack, parse_execute, types::NumericType, ContextType},
execution::{ContextType, memory::Stack, parse_execute, types::NumericType},
parsing::ast::types::{DefaultParamVal, Identifier, Parameter},
};

View File

@ -3,16 +3,16 @@ use std::ops::{Add, AddAssign, Mul};
use anyhow::Result;
use indexmap::IndexMap;
use kittycad_modeling_cmds as kcmc;
use kittycad_modeling_cmds::{each_cmd as mcmd, length_unit::LengthUnit, websocket::ModelingCmdReq, ModelingCmd};
use kittycad_modeling_cmds::{ModelingCmd, each_cmd as mcmd, length_unit::LengthUnit, websocket::ModelingCmdReq};
use parse_display::{Display, FromStr};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::{
engine::{PlaneName, DEFAULT_PLANE_INFO},
engine::{DEFAULT_PLANE_INFO, PlaneName},
errors::{KclError, KclErrorDetails},
execution::{
types::NumericType, ArtifactId, ExecState, ExecutorContext, Metadata, TagEngineInfo, TagIdentifier, UnitLen,
ArtifactId, ExecState, ExecutorContext, Metadata, TagEngineInfo, TagIdentifier, UnitLen, types::NumericType,
},
parsing::ast::types::{Node, NodeRef, TagDeclarator, TagNode},
std::{args::TyF64, sketch::PlaneData},
@ -472,7 +472,7 @@ impl TryFrom<PlaneData> for PlaneInfo {
PlaneData::Plane(_) => {
// We will never get here since we already checked for PlaneData::Plane.
return Err(KclError::new_internal(KclErrorDetails::new(
format!("PlaneData {:?} not found", value),
format!("PlaneData {value:?} not found"),
Default::default(),
)));
}
@ -480,7 +480,7 @@ impl TryFrom<PlaneData> for PlaneInfo {
let info = DEFAULT_PLANE_INFO.get(&name).ok_or_else(|| {
KclError::new_internal(KclErrorDetails::new(
format!("Plane {} not found", name),
format!("Plane {name} not found"),
Default::default(),
))
})?;
@ -815,8 +815,8 @@ impl EdgeCut {
pub fn set_id(&mut self, id: uuid::Uuid) {
match self {
EdgeCut::Fillet { id: ref mut i, .. } => *i = id,
EdgeCut::Chamfer { id: ref mut i, .. } => *i = id,
EdgeCut::Fillet { id: i, .. } => *i = id,
EdgeCut::Chamfer { id: i, .. } => *i = id,
}
}
@ -829,8 +829,8 @@ impl EdgeCut {
pub fn set_edge_id(&mut self, id: uuid::Uuid) {
match self {
EdgeCut::Fillet { edge_id: ref mut i, .. } => *i = id,
EdgeCut::Chamfer { edge_id: ref mut i, .. } => *i = id,
EdgeCut::Fillet { edge_id: i, .. } => *i = id,
EdgeCut::Chamfer { edge_id: i, .. } => *i = id,
}
}

View File

@ -2,12 +2,12 @@ use std::str::FromStr;
use anyhow::Result;
use kcmc::{
coord::{System, KITTYCAD},
ImportFile, ModelingCmd,
coord::{KITTYCAD, System},
each_cmd as mcmd,
format::InputFormat3d,
shared::FileImportFormat,
units::UnitLength,
ImportFile, ModelingCmd,
};
use kittycad_modeling_cmds as kcmc;
use serde::{Deserialize, Serialize};
@ -16,8 +16,8 @@ use uuid::Uuid;
use crate::{
errors::{KclError, KclErrorDetails},
execution::{
annotations, typed_path::TypedPath, types::UnitLen, ExecState, ExecutorContext, ImportedGeometry,
ModelingCmdMeta,
ExecState, ExecutorContext, ImportedGeometry, ModelingCmdMeta, annotations, typed_path::TypedPath,
types::UnitLen,
},
fs::FileSystem,
parsing::ast::types::{Annotation, Node},
@ -184,7 +184,7 @@ pub(super) fn format_from_annotations(
annotations::IMPORT_LENGTH_UNIT
),
vec![p.as_source_range()],
)))
)));
}
}
}
@ -225,7 +225,7 @@ fn set_coords(fmt: &mut InputFormat3d, coords_str: &str, source_range: SourceRan
annotations::IMPORT_COORDS
),
vec![source_range],
)))
)));
}
}
@ -246,7 +246,7 @@ fn set_length_unit(fmt: &mut InputFormat3d, units_str: &str, source_range: Sourc
annotations::IMPORT_LENGTH_UNIT
),
vec![source_range],
)))
)));
}
}
@ -291,7 +291,9 @@ fn get_import_format_from_extension(ext: &str) -> Result<InputFormat3d> {
} else if ext == "glb" {
FileImportFormat::Gltf
} else {
anyhow::bail!("unknown source format for file extension: {ext}. Try setting the `--src-format` flag explicitly or use a valid format.")
anyhow::bail!(
"unknown source format for file extension: {ext}. Try setting the `--src-format` flag explicitly or use a valid format."
)
}
}
};

View File

@ -6,12 +6,12 @@ use std::{
use anyhow::Result;
use crate::{
ExecState, ExecutorContext, KclError, ModuleId, SourceRange,
errors::KclErrorDetails,
execution::typed_path::TypedPath,
modules::{ModulePath, ModuleRepr},
parsing::ast::types::{ImportPath, ImportStatement, Node as AstNode},
walk::{Node, Visitable},
ExecState, ExecutorContext, KclError, ModuleId, SourceRange,
};
/// Specific dependency between two modules. The 0th element of this info
@ -147,7 +147,7 @@ fn import_dependencies(
ret.lock()
.map_err(|err| {
KclError::new_internal(KclErrorDetails::new(
format!("Failed to lock mutex: {}", err),
format!("Failed to lock mutex: {err}"),
Default::default(),
))
})?
@ -157,7 +157,7 @@ fn import_dependencies(
ret.lock()
.map_err(|err| {
KclError::new_internal(KclErrorDetails::new(
format!("Failed to lock mutex: {}", err),
format!("Failed to lock mutex: {err}"),
Default::default(),
))
})?
@ -179,7 +179,7 @@ fn import_dependencies(
let ret = ret.lock().map_err(|err| {
KclError::new_internal(KclErrorDetails::new(
format!("Failed to lock mutex: {}", err),
format!("Failed to lock mutex: {err}"),
Default::default(),
))
})?;
@ -224,7 +224,7 @@ pub(crate) async fn import_universe(
let repr = {
let Some(module_info) = exec_state.get_module(module_id) else {
return Err(KclError::new_internal(KclErrorDetails::new(
format!("Module {} not found", module_id),
format!("Module {module_id} not found"),
vec![import_stmt.into()],
)));
};
@ -244,9 +244,7 @@ mod tests {
use crate::parsing::ast::types::{ImportSelector, Program};
macro_rules! kcl {
( $kcl:expr ) => {{
$crate::parsing::top_level_parse($kcl).unwrap()
}};
( $kcl:expr_2021 ) => {{ $crate::parsing::top_level_parse($kcl).unwrap() }};
}
fn into_module_info(program: AstNode<Program>) -> DependencyInfo {

View File

@ -5,18 +5,18 @@ use schemars::JsonSchema;
use serde::Serialize;
use crate::{
CompilationError, KclError, ModuleId, SourceRange,
errors::KclErrorDetails,
execution::{
annotations::{SETTINGS, SETTINGS_UNIT_LENGTH},
types::{NumericType, PrimitiveType, RuntimeType, UnitLen},
EnvironmentRef, ExecState, Face, Geometry, GeometryWithImportedGeometry, Helix, ImportedGeometry, MetaSettings,
Metadata, Plane, Sketch, Solid, TagIdentifier,
annotations::{SETTINGS, SETTINGS_UNIT_LENGTH},
types::{NumericType, PrimitiveType, RuntimeType, UnitLen},
},
parsing::ast::types::{
DefaultParamVal, FunctionExpression, KclNone, Literal, LiteralValue, Node, TagDeclarator, TagNode,
},
std::{args::TyF64, StdFnProps},
CompilationError, KclError, ModuleId, SourceRange,
std::{StdFnProps, args::TyF64},
};
pub type KclObjectFields = HashMap<String, KclValue>;
@ -136,9 +136,9 @@ impl JsonSchema for FunctionSource {
"FunctionSource".to_owned()
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
// TODO: Actually generate a reasonable schema.
gen.subschema_for::<()>()
r#gen.subschema_for::<()>()
}
}
@ -587,7 +587,7 @@ impl KclValue {
match self {
KclValue::TagIdentifier(t) => Ok(*t.clone()),
_ => Err(KclError::new_semantic(KclErrorDetails::new(
format!("Not a tag identifier: {:?}", self),
format!("Not a tag identifier: {self:?}"),
self.clone().into(),
))),
}
@ -598,7 +598,7 @@ impl KclValue {
match self {
KclValue::TagDeclarator(t) => Ok((**t).clone()),
_ => Err(KclError::new_semantic(KclErrorDetails::new(
format!("Not a tag declarator: {:?}", self),
format!("Not a tag declarator: {self:?}"),
self.clone().into(),
))),
}

View File

@ -207,8 +207,8 @@ use std::{
fmt,
pin::Pin,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
@ -489,7 +489,7 @@ impl ProgramMemory {
}
Err(KclError::new_undefined_value(
KclErrorDetails::new(format!("`{}` is not defined", var), vec![]),
KclErrorDetails::new(format!("`{var}` is not defined"), vec![]),
Some(var.to_owned()),
))
}
@ -647,7 +647,7 @@ impl Stack {
let env = self.memory.get_env(self.current_env.index());
if env.contains_key(&key) {
return Err(KclError::new_value_already_defined(KclErrorDetails::new(
format!("Cannot redefine `{}`", key),
format!("Cannot redefine `{key}`"),
vec![source_range],
)));
}
@ -1047,7 +1047,7 @@ mod env {
}
/// Take all bindings from the environment.
pub(super) fn take_bindings(self: Pin<&mut Self>) -> impl Iterator<Item = (String, (usize, KclValue))> {
pub(super) fn take_bindings(self: Pin<&mut Self>) -> impl Iterator<Item = (String, (usize, KclValue))> + use<> {
// SAFETY: caller must have unique access since self is mut. We're not moving or invalidating `self`.
let bindings = std::mem::take(unsafe { self.bindings.get().as_mut().unwrap() });
bindings.into_iter()

View File

@ -16,10 +16,9 @@ pub(crate) use import::PreImportedGeometry;
use indexmap::IndexMap;
pub use kcl_value::{KclObjectFields, KclValue};
use kcmc::{
each_cmd as mcmd,
ok_response::{output::TakeSnapshot, OkModelingCmdResponse},
ImageFormat, ModelingCmd, each_cmd as mcmd,
ok_response::{OkModelingCmdResponse, output::TakeSnapshot},
websocket::{ModelingSessionData, OkWebSocketResponseData},
ImageFormat, ModelingCmd,
};
use kittycad_modeling_cmds::{self as kcmc, id::ModelingCmdId};
pub use memory::EnvironmentRef;
@ -31,6 +30,7 @@ pub use state::{ExecState, MetaSettings};
use uuid::Uuid;
use crate::{
CompilationError, ExecError, KclErrorWithOutputs,
engine::{EngineManager, GridScaleBehavior},
errors::{KclError, KclErrorDetails},
execution::{
@ -43,7 +43,6 @@ use crate::{
modules::{ModuleId, ModulePath, ModuleRepr},
parsing::ast::types::{Expr, ImportPath, NodeRef},
source_range::SourceRange,
CompilationError, ExecError, KclErrorWithOutputs,
};
pub(crate) mod annotations;
@ -1329,7 +1328,7 @@ impl ExecutorContext {
created: if deterministic_time {
Some("2021-01-01T00:00:00Z".parse().map_err(|e| {
KclError::new_internal(crate::errors::KclErrorDetails::new(
format!("Failed to parse date: {}", e),
format!("Failed to parse date: {e}"),
vec![SourceRange::default()],
))
})?)
@ -1409,7 +1408,7 @@ pub(crate) async fn parse_execute_with_project_dir(
engine: Arc::new(Box::new(
crate::engine::conn_mock::EngineConnection::new().await.map_err(|err| {
KclError::new_internal(crate::errors::KclErrorDetails::new(
format!("Failed to create mock engine connection: {}", err),
format!("Failed to create mock engine connection: {err}"),
vec![SourceRange::default()],
))
})?,
@ -1446,7 +1445,7 @@ mod tests {
use pretty_assertions::assert_eq;
use super::*;
use crate::{errors::KclErrorDetails, execution::memory::Stack, ModuleId};
use crate::{ModuleId, errors::KclErrorDetails, execution::memory::Stack};
/// Convenience function to get a JSON value from memory and unwrap.
#[track_caller]
@ -2045,8 +2044,7 @@ notFunction = !x";
fn_err
.message()
.starts_with("Cannot apply unary operator ! to non-boolean value: "),
"Actual error: {:?}",
fn_err
"Actual error: {fn_err:?}"
);
let code8 = "
@ -2059,8 +2057,7 @@ notTagDeclarator = !myTagDeclarator";
tag_declarator_err
.message()
.starts_with("Cannot apply unary operator ! to non-boolean value: a tag declarator"),
"Actual error: {:?}",
tag_declarator_err
"Actual error: {tag_declarator_err:?}"
);
let code9 = "
@ -2073,8 +2070,7 @@ notTagIdentifier = !myTag";
tag_identifier_err
.message()
.starts_with("Cannot apply unary operator ! to non-boolean value: a tag identifier"),
"Actual error: {:?}",
tag_identifier_err
"Actual error: {tag_identifier_err:?}"
);
let code10 = "notPipe = !(1 |> 2)";
@ -2226,7 +2222,7 @@ w = f() + f()
if let Err(err) = ctx.run_with_caching(old_program).await {
let report = err.into_miette_report_with_outputs(code).unwrap();
let report = miette::Report::new(report);
panic!("Error executing program: {:?}", report);
panic!("Error executing program: {report:?}");
}
// Get the id_generator from the first execution.

View File

@ -8,10 +8,10 @@ use uuid::Uuid;
#[cfg(feature = "artifact-graph")]
use crate::exec::ArtifactCommand;
use crate::{
ExecState, ExecutorContext, KclError, SourceRange,
exec::{IdGenerator, KclValue},
execution::Solid,
std::Args,
ExecState, ExecutorContext, KclError, SourceRange,
};
/// Context and metadata needed to send a single modeling command.

View File

@ -9,20 +9,19 @@ use uuid::Uuid;
#[cfg(feature = "artifact-graph")]
use crate::execution::{Artifact, ArtifactCommand, ArtifactGraph, ArtifactId};
use crate::{
CompilationError, EngineManager, ExecutorContext, KclErrorWithOutputs,
errors::{KclError, KclErrorDetails, Severity},
exec::DefaultPlanes,
execution::{
annotations,
EnvironmentRef, ExecOutcome, ExecutorSettings, KclValue, UnitAngle, UnitLen, annotations,
cad_op::Operation,
id_generator::IdGenerator,
memory::{ProgramMemory, Stack},
types::{self, NumericType},
EnvironmentRef, ExecOutcome, ExecutorSettings, KclValue, UnitAngle, UnitLen,
},
modules::{ModuleId, ModuleInfo, ModuleLoader, ModulePath, ModuleRepr, ModuleSource},
parsing::ast::types::{Annotation, NodeRef},
source_range::SourceRange,
CompilationError, EngineManager, ExecutorContext, KclErrorWithOutputs,
};
/// State for executing a program.
@ -555,7 +554,7 @@ impl MetaSettings {
annotations::SETTINGS_UNIT_ANGLE
),
vec![annotation.as_source_range()],
)))
)));
}
}
}

View File

@ -220,9 +220,9 @@ impl schemars::JsonSchema for TypedPath {
"TypedPath".to_owned()
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
// TODO: Actually generate a reasonable schema.
gen.subschema_for::<std::path::PathBuf>()
r#gen.subschema_for::<std::path::PathBuf>()
}
}

View File

@ -5,17 +5,17 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::{
CompilationError, SourceRange,
execution::{
ExecState, Plane, PlaneInfo, Point3d,
kcl_value::{KclValue, TypeDef},
memory::{self},
ExecState, Plane, PlaneInfo, Point3d,
},
parsing::{
ast::types::{PrimitiveType as AstPrimitiveType, Type},
token::NumericSuffix,
},
std::args::{FromKclValue, TyF64},
CompilationError, SourceRange,
};
#[derive(Debug, Clone, PartialEq)]
@ -210,7 +210,7 @@ impl RuntimeType {
let ty_val = exec_state
.stack()
.get(&format!("{}{}", memory::TYPE_PREFIX, alias), source_range)
.map_err(|_| CompilationError::err(source_range, format!("Unknown type: {}", alias)))?;
.map_err(|_| CompilationError::err(source_range, format!("Unknown type: {alias}")))?;
Ok(match ty_val {
KclValue::Type { value, .. } => match value {
@ -241,7 +241,7 @@ impl RuntimeType {
"a tuple with values of types ({})",
tys.iter().map(Self::human_friendly_type).collect::<Vec<_>>().join(", ")
),
RuntimeType::Object(_) => format!("an object with fields {}", self),
RuntimeType::Object(_) => format!("an object with fields {self}"),
}
}
@ -1529,7 +1529,7 @@ impl KclValue {
#[cfg(test)]
mod test {
use super::*;
use crate::execution::{parse_execute, ExecTestResults};
use crate::execution::{ExecTestResults, parse_execute};
fn values(exec_state: &mut ExecState) -> Vec<KclValue> {
vec![
@ -1975,14 +1975,16 @@ mod test {
])
)
);
assert!(RuntimeType::Union(vec![
RuntimeType::Primitive(PrimitiveType::Number(NumericType::Any)),
RuntimeType::Primitive(PrimitiveType::Boolean)
])
.subtype(&RuntimeType::Union(vec![
RuntimeType::Primitive(PrimitiveType::Number(NumericType::Any)),
RuntimeType::Primitive(PrimitiveType::Boolean)
])));
assert!(
RuntimeType::Union(vec![
RuntimeType::Primitive(PrimitiveType::Number(NumericType::Any)),
RuntimeType::Primitive(PrimitiveType::Boolean)
])
.subtype(&RuntimeType::Union(vec![
RuntimeType::Primitive(PrimitiveType::Number(NumericType::Any)),
RuntimeType::Primitive(PrimitiveType::Boolean)
]))
);
// Covariance
let count = KclValue::Number {