1pub mod appearance;
4pub mod args;
5pub mod array;
6pub mod assert;
7pub mod axis_or_reference;
8pub mod chamfer;
9pub mod convert;
10pub mod extrude;
11pub mod fillet;
12pub mod helix;
13pub mod import;
14pub mod loft;
15pub mod math;
16pub mod mirror;
17pub mod patterns;
18pub mod planes;
19pub mod polar;
20pub mod revolve;
21pub mod segment;
22pub mod shapes;
23pub mod shell;
24pub mod sketch;
25pub mod sweep;
26pub mod transform;
27pub mod types;
28pub mod units;
29pub mod utils;
30
31use anyhow::Result;
32pub use args::Args;
33use derive_docs::stdlib;
34use indexmap::IndexMap;
35use lazy_static::lazy_static;
36use parse_display::{Display, FromStr};
37use schemars::JsonSchema;
38use serde::{Deserialize, Serialize};
39
40use crate::{
41 docs::StdLibFn,
42 errors::KclError,
43 execution::{ExecState, KclValue},
44};
45
46pub type StdFn = fn(
47 &mut ExecState,
48 Args,
49) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<KclValue, KclError>> + Send + '_>>;
50
51lazy_static! {
52 static ref CORE_FNS: Vec<Box<dyn StdLibFn>> = vec![
53 Box::new(LegLen),
54 Box::new(LegAngX),
55 Box::new(LegAngY),
56 Box::new(crate::std::appearance::Appearance),
57 Box::new(crate::std::convert::Int),
58 Box::new(crate::std::extrude::Extrude),
59 Box::new(crate::std::segment::SegEnd),
60 Box::new(crate::std::segment::SegEndX),
61 Box::new(crate::std::segment::SegEndY),
62 Box::new(crate::std::segment::SegStart),
63 Box::new(crate::std::segment::SegStartX),
64 Box::new(crate::std::segment::SegStartY),
65 Box::new(crate::std::segment::LastSegX),
66 Box::new(crate::std::segment::LastSegY),
67 Box::new(crate::std::segment::SegLen),
68 Box::new(crate::std::segment::SegAng),
69 Box::new(crate::std::segment::TangentToEnd),
70 Box::new(crate::std::segment::AngleToMatchLengthX),
71 Box::new(crate::std::segment::AngleToMatchLengthY),
72 Box::new(crate::std::shapes::Circle),
73 Box::new(crate::std::shapes::CircleThreePoint),
74 Box::new(crate::std::shapes::Polygon),
75 Box::new(crate::std::sketch::Line),
76 Box::new(crate::std::sketch::XLineTo),
77 Box::new(crate::std::sketch::XLine),
78 Box::new(crate::std::sketch::YLineTo),
79 Box::new(crate::std::sketch::YLine),
80 Box::new(crate::std::sketch::AngledLineToX),
81 Box::new(crate::std::sketch::AngledLineToY),
82 Box::new(crate::std::sketch::AngledLine),
83 Box::new(crate::std::sketch::AngledLineOfXLength),
84 Box::new(crate::std::sketch::AngledLineOfYLength),
85 Box::new(crate::std::sketch::AngledLineThatIntersects),
86 Box::new(crate::std::sketch::StartSketchAt),
87 Box::new(crate::std::sketch::StartSketchOn),
88 Box::new(crate::std::sketch::StartProfileAt),
89 Box::new(crate::std::sketch::ProfileStartX),
90 Box::new(crate::std::sketch::ProfileStartY),
91 Box::new(crate::std::sketch::ProfileStart),
92 Box::new(crate::std::sketch::Close),
93 Box::new(crate::std::sketch::Arc),
94 Box::new(crate::std::sketch::ArcTo),
95 Box::new(crate::std::sketch::TangentialArc),
96 Box::new(crate::std::sketch::TangentialArcTo),
97 Box::new(crate::std::sketch::TangentialArcToRelative),
98 Box::new(crate::std::sketch::BezierCurve),
99 Box::new(crate::std::sketch::Hole),
100 Box::new(crate::std::mirror::Mirror2D),
101 Box::new(crate::std::patterns::PatternLinear2D),
102 Box::new(crate::std::patterns::PatternLinear3D),
103 Box::new(crate::std::patterns::PatternCircular2D),
104 Box::new(crate::std::patterns::PatternCircular3D),
105 Box::new(crate::std::patterns::PatternTransform),
106 Box::new(crate::std::patterns::PatternTransform2D),
107 Box::new(crate::std::array::Reduce),
108 Box::new(crate::std::array::Map),
109 Box::new(crate::std::array::Push),
110 Box::new(crate::std::array::Pop),
111 Box::new(crate::std::chamfer::Chamfer),
112 Box::new(crate::std::fillet::Fillet),
113 Box::new(crate::std::fillet::GetOppositeEdge),
114 Box::new(crate::std::fillet::GetNextAdjacentEdge),
115 Box::new(crate::std::fillet::GetPreviousAdjacentEdge),
116 Box::new(crate::std::helix::Helix),
117 Box::new(crate::std::helix::HelixRevolutions),
118 Box::new(crate::std::shell::Shell),
119 Box::new(crate::std::shell::Hollow),
120 Box::new(crate::std::revolve::Revolve),
121 Box::new(crate::std::sweep::Sweep),
122 Box::new(crate::std::loft::Loft),
123 Box::new(crate::std::planes::OffsetPlane),
124 Box::new(crate::std::import::Import),
125 Box::new(crate::std::math::Acos),
126 Box::new(crate::std::math::Asin),
127 Box::new(crate::std::math::Atan),
128 Box::new(crate::std::math::Atan2),
129 Box::new(crate::std::math::Pi),
130 Box::new(crate::std::math::E),
131 Box::new(crate::std::math::Tau),
132 Box::new(crate::std::math::Sqrt),
133 Box::new(crate::std::math::Abs),
134 Box::new(crate::std::math::Rem),
135 Box::new(crate::std::math::Round),
136 Box::new(crate::std::math::Floor),
137 Box::new(crate::std::math::Ceil),
138 Box::new(crate::std::math::Min),
139 Box::new(crate::std::math::Max),
140 Box::new(crate::std::math::Pow),
141 Box::new(crate::std::math::Log),
142 Box::new(crate::std::math::Log2),
143 Box::new(crate::std::math::Log10),
144 Box::new(crate::std::math::Ln),
145 Box::new(crate::std::math::ToDegrees),
146 Box::new(crate::std::math::ToRadians),
147 Box::new(crate::std::units::Mm),
148 Box::new(crate::std::units::Inch),
149 Box::new(crate::std::units::Ft),
150 Box::new(crate::std::units::M),
151 Box::new(crate::std::units::Cm),
152 Box::new(crate::std::units::Yd),
153 Box::new(crate::std::polar::Polar),
154 Box::new(crate::std::assert::Assert),
155 Box::new(crate::std::assert::AssertEqual),
156 Box::new(crate::std::assert::AssertLessThan),
157 Box::new(crate::std::assert::AssertGreaterThan),
158 Box::new(crate::std::assert::AssertLessThanOrEq),
159 Box::new(crate::std::assert::AssertGreaterThanOrEq),
160 Box::new(crate::std::transform::Scale),
161 Box::new(crate::std::transform::Translate),
162 Box::new(crate::std::transform::Rotate),
163 ];
164}
165
166pub fn name_in_stdlib(name: &str) -> bool {
167 CORE_FNS.iter().any(|f| f.name() == name)
168}
169
170pub fn get_stdlib_fn(name: &str) -> Option<Box<dyn StdLibFn>> {
171 CORE_FNS.iter().find(|f| f.name() == name).cloned()
172}
173
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct StdFnProps {
176 pub name: String,
177 pub deprecated: bool,
178}
179
180impl StdFnProps {
181 fn default(name: &str) -> Self {
182 Self {
183 name: name.to_owned(),
184 deprecated: false,
185 }
186 }
187}
188
189pub(crate) fn std_fn(path: &str, fn_name: &str) -> (crate::std::StdFn, StdFnProps) {
190 match (path, fn_name) {
191 ("math", "cos") => (
192 |e, a| Box::pin(crate::std::math::cos(e, a)),
193 StdFnProps::default("std::math::cos"),
194 ),
195 ("math", "sin") => (
196 |e, a| Box::pin(crate::std::math::sin(e, a)),
197 StdFnProps::default("std::math::sin"),
198 ),
199 ("math", "tan") => (
200 |e, a| Box::pin(crate::std::math::tan(e, a)),
201 StdFnProps::default("std::math::tan"),
202 ),
203 _ => unreachable!(),
204 }
205}
206
207pub struct StdLib {
208 pub fns: IndexMap<String, Box<dyn StdLibFn>>,
209}
210
211impl std::fmt::Debug for StdLib {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 f.debug_struct("StdLib").field("fns.len()", &self.fns.len()).finish()
214 }
215}
216
217impl StdLib {
218 pub fn new() -> Self {
219 let fns = CORE_FNS
220 .clone()
221 .into_iter()
222 .map(|internal_fn| (internal_fn.name(), internal_fn))
223 .collect();
224
225 Self { fns }
226 }
227
228 pub fn combined(&self) -> IndexMap<String, Box<dyn StdLibFn>> {
230 self.fns.clone()
231 }
232
233 pub fn get(&self, name: &str) -> Option<Box<dyn StdLibFn>> {
234 self.fns.get(name).cloned()
235 }
236
237 pub fn get_either(&self, name: &str) -> FunctionKind {
238 if let Some(f) = self.get(name) {
239 FunctionKind::Core(f)
240 } else {
241 FunctionKind::UserDefined
242 }
243 }
244
245 pub fn contains_key(&self, key: &str) -> bool {
246 self.fns.contains_key(key)
247 }
248}
249
250impl Default for StdLib {
251 fn default() -> Self {
252 Self::new()
253 }
254}
255
256#[derive(Debug)]
257pub enum FunctionKind {
258 Core(Box<dyn StdLibFn>),
259 UserDefined,
260}
261
262pub async fn leg_length(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
264 let (hypotenuse, leg, ty) = args.get_hypotenuse_leg()?;
265 let result = inner_leg_length(hypotenuse, leg);
266 Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
267}
268
269#[stdlib {
275 name = "legLen",
276 tags = ["utilities"],
277}]
278fn inner_leg_length(hypotenuse: f64, leg: f64) -> f64 {
279 (hypotenuse.powi(2) - f64::min(hypotenuse.abs(), leg.abs()).powi(2)).sqrt()
280}
281
282pub async fn leg_angle_x(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
284 let (hypotenuse, leg, ty) = args.get_hypotenuse_leg()?;
285 let result = inner_leg_angle_x(hypotenuse, leg);
286 Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
287}
288
289#[stdlib {
295 name = "legAngX",
296 tags = ["utilities"],
297}]
298fn inner_leg_angle_x(hypotenuse: f64, leg: f64) -> f64 {
299 (leg.min(hypotenuse) / hypotenuse).acos().to_degrees()
300}
301
302pub async fn leg_angle_y(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
304 let (hypotenuse, leg, ty) = args.get_hypotenuse_leg()?;
305 let result = inner_leg_angle_y(hypotenuse, leg);
306 Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
307}
308
309#[stdlib {
315 name = "legAngY",
316 tags = ["utilities"],
317}]
318fn inner_leg_angle_y(hypotenuse: f64, leg: f64) -> f64 {
319 (leg.min(hypotenuse) / hypotenuse).asin().to_degrees()
320}
321
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Display, FromStr)]
324#[serde(rename_all = "lowercase")]
325#[display(style = "lowercase")]
326pub enum Primitive {
327 Bool,
329 Number,
331 String,
333 Uuid,
335}