kcl_lib/std/
mod.rs

1//! Functions implemented for language execution.
2
3pub 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 indexmap::IndexMap;
34use kcl_derive_docs::stdlib;
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::XLine),
77        Box::new(crate::std::sketch::YLine),
78        Box::new(crate::std::sketch::AngledLineToX),
79        Box::new(crate::std::sketch::AngledLineToY),
80        Box::new(crate::std::sketch::AngledLine),
81        Box::new(crate::std::sketch::AngledLineOfXLength),
82        Box::new(crate::std::sketch::AngledLineOfYLength),
83        Box::new(crate::std::sketch::AngledLineThatIntersects),
84        Box::new(crate::std::sketch::StartSketchOn),
85        Box::new(crate::std::sketch::StartProfileAt),
86        Box::new(crate::std::sketch::ProfileStartX),
87        Box::new(crate::std::sketch::ProfileStartY),
88        Box::new(crate::std::sketch::ProfileStart),
89        Box::new(crate::std::sketch::Close),
90        Box::new(crate::std::sketch::Arc),
91        Box::new(crate::std::sketch::ArcTo),
92        Box::new(crate::std::sketch::TangentialArc),
93        Box::new(crate::std::sketch::TangentialArcTo),
94        Box::new(crate::std::sketch::TangentialArcToRelative),
95        Box::new(crate::std::sketch::BezierCurve),
96        Box::new(crate::std::sketch::Hole),
97        Box::new(crate::std::mirror::Mirror2D),
98        Box::new(crate::std::patterns::PatternLinear2D),
99        Box::new(crate::std::patterns::PatternLinear3D),
100        Box::new(crate::std::patterns::PatternCircular2D),
101        Box::new(crate::std::patterns::PatternCircular3D),
102        Box::new(crate::std::patterns::PatternTransform),
103        Box::new(crate::std::patterns::PatternTransform2D),
104        Box::new(crate::std::array::Reduce),
105        Box::new(crate::std::array::Map),
106        Box::new(crate::std::array::Push),
107        Box::new(crate::std::array::Pop),
108        Box::new(crate::std::chamfer::Chamfer),
109        Box::new(crate::std::fillet::Fillet),
110        Box::new(crate::std::fillet::GetOppositeEdge),
111        Box::new(crate::std::fillet::GetNextAdjacentEdge),
112        Box::new(crate::std::fillet::GetPreviousAdjacentEdge),
113        Box::new(crate::std::helix::Helix),
114        Box::new(crate::std::helix::HelixRevolutions),
115        Box::new(crate::std::shell::Shell),
116        Box::new(crate::std::shell::Hollow),
117        Box::new(crate::std::revolve::Revolve),
118        Box::new(crate::std::sweep::Sweep),
119        Box::new(crate::std::loft::Loft),
120        Box::new(crate::std::planes::OffsetPlane),
121        Box::new(crate::std::import::Import),
122        Box::new(crate::std::math::Acos),
123        Box::new(crate::std::math::Asin),
124        Box::new(crate::std::math::Atan),
125        Box::new(crate::std::math::Atan2),
126        Box::new(crate::std::math::Pi),
127        Box::new(crate::std::math::E),
128        Box::new(crate::std::math::Tau),
129        Box::new(crate::std::math::Sqrt),
130        Box::new(crate::std::math::Abs),
131        Box::new(crate::std::math::Rem),
132        Box::new(crate::std::math::Round),
133        Box::new(crate::std::math::Floor),
134        Box::new(crate::std::math::Ceil),
135        Box::new(crate::std::math::Min),
136        Box::new(crate::std::math::Max),
137        Box::new(crate::std::math::Pow),
138        Box::new(crate::std::math::Log),
139        Box::new(crate::std::math::Log2),
140        Box::new(crate::std::math::Log10),
141        Box::new(crate::std::math::Ln),
142        Box::new(crate::std::math::ToDegrees),
143        Box::new(crate::std::math::ToRadians),
144        Box::new(crate::std::units::Mm),
145        Box::new(crate::std::units::Inch),
146        Box::new(crate::std::units::Ft),
147        Box::new(crate::std::units::M),
148        Box::new(crate::std::units::Cm),
149        Box::new(crate::std::units::Yd),
150        Box::new(crate::std::polar::Polar),
151        Box::new(crate::std::assert::Assert),
152        Box::new(crate::std::assert::AssertEqual),
153        Box::new(crate::std::assert::AssertLessThan),
154        Box::new(crate::std::assert::AssertGreaterThan),
155        Box::new(crate::std::assert::AssertLessThanOrEq),
156        Box::new(crate::std::assert::AssertGreaterThanOrEq),
157        Box::new(crate::std::transform::Scale),
158        Box::new(crate::std::transform::Translate),
159        Box::new(crate::std::transform::Rotate),
160    ];
161}
162
163pub fn name_in_stdlib(name: &str) -> bool {
164    CORE_FNS.iter().any(|f| f.name() == name)
165}
166
167pub fn get_stdlib_fn(name: &str) -> Option<Box<dyn StdLibFn>> {
168    CORE_FNS.iter().find(|f| f.name() == name).cloned()
169}
170
171#[derive(Clone, Debug, PartialEq, Eq)]
172pub struct StdFnProps {
173    pub name: String,
174    pub deprecated: bool,
175}
176
177impl StdFnProps {
178    fn default(name: &str) -> Self {
179        Self {
180            name: name.to_owned(),
181            deprecated: false,
182        }
183    }
184}
185
186pub(crate) fn std_fn(path: &str, fn_name: &str) -> (crate::std::StdFn, StdFnProps) {
187    match (path, fn_name) {
188        ("math", "cos") => (
189            |e, a| Box::pin(crate::std::math::cos(e, a)),
190            StdFnProps::default("std::math::cos"),
191        ),
192        ("math", "sin") => (
193            |e, a| Box::pin(crate::std::math::sin(e, a)),
194            StdFnProps::default("std::math::sin"),
195        ),
196        ("math", "tan") => (
197            |e, a| Box::pin(crate::std::math::tan(e, a)),
198            StdFnProps::default("std::math::tan"),
199        ),
200        _ => unreachable!(),
201    }
202}
203
204pub(crate) fn std_ty(path: &str, fn_name: &str) -> (crate::execution::PrimitiveType, StdFnProps) {
205    match (path, fn_name) {
206        ("prelude", "Sketch") => (
207            crate::execution::PrimitiveType::Sketch,
208            StdFnProps::default("std::Sketch"),
209        ),
210        ("prelude", "Solid") => (
211            crate::execution::PrimitiveType::Solid,
212            StdFnProps::default("std::Solid"),
213        ),
214        ("prelude", "Plane") => (
215            crate::execution::PrimitiveType::Plane,
216            StdFnProps::default("std::Plane"),
217        ),
218        _ => unreachable!(),
219    }
220}
221
222pub struct StdLib {
223    pub fns: IndexMap<String, Box<dyn StdLibFn>>,
224}
225
226impl std::fmt::Debug for StdLib {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        f.debug_struct("StdLib").field("fns.len()", &self.fns.len()).finish()
229    }
230}
231
232impl StdLib {
233    pub fn new() -> Self {
234        let fns = CORE_FNS
235            .clone()
236            .into_iter()
237            .map(|internal_fn| (internal_fn.name(), internal_fn))
238            .collect();
239
240        Self { fns }
241    }
242
243    // Get the combined hashmaps.
244    pub fn combined(&self) -> IndexMap<String, Box<dyn StdLibFn>> {
245        self.fns.clone()
246    }
247
248    pub fn get(&self, name: &str) -> Option<Box<dyn StdLibFn>> {
249        self.fns.get(name).cloned()
250    }
251
252    pub fn get_either(&self, name: &str) -> FunctionKind {
253        if let Some(f) = self.get(name) {
254            FunctionKind::Core(f)
255        } else {
256            FunctionKind::UserDefined
257        }
258    }
259
260    pub fn contains_key(&self, key: &str) -> bool {
261        self.fns.contains_key(key)
262    }
263}
264
265impl Default for StdLib {
266    fn default() -> Self {
267        Self::new()
268    }
269}
270
271#[derive(Debug)]
272pub enum FunctionKind {
273    Core(Box<dyn StdLibFn>),
274    UserDefined,
275}
276
277/// Compute the length of the given leg.
278pub async fn leg_length(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
279    let (hypotenuse, leg, ty) = args.get_hypotenuse_leg()?;
280    let result = inner_leg_length(hypotenuse, leg);
281    Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
282}
283
284/// Compute the length of the given leg.
285///
286/// ```no_run
287/// legLen(5, 3)
288/// ```
289#[stdlib {
290    name = "legLen",
291    tags = ["utilities"],
292}]
293fn inner_leg_length(hypotenuse: f64, leg: f64) -> f64 {
294    (hypotenuse.powi(2) - f64::min(hypotenuse.abs(), leg.abs()).powi(2)).sqrt()
295}
296
297/// Compute the angle of the given leg for x.
298pub async fn leg_angle_x(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
299    let (hypotenuse, leg, ty) = args.get_hypotenuse_leg()?;
300    let result = inner_leg_angle_x(hypotenuse, leg);
301    Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
302}
303
304/// Compute the angle of the given leg for x.
305///
306/// ```no_run
307/// legAngX(5, 3)
308/// ```
309#[stdlib {
310    name = "legAngX",
311    tags = ["utilities"],
312}]
313fn inner_leg_angle_x(hypotenuse: f64, leg: f64) -> f64 {
314    (leg.min(hypotenuse) / hypotenuse).acos().to_degrees()
315}
316
317/// Compute the angle of the given leg for y.
318pub async fn leg_angle_y(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
319    let (hypotenuse, leg, ty) = args.get_hypotenuse_leg()?;
320    let result = inner_leg_angle_y(hypotenuse, leg);
321    Ok(KclValue::from_number_with_type(result, ty, vec![args.into()]))
322}
323
324/// Compute the angle of the given leg for y.
325///
326/// ```no_run
327/// legAngY(5, 3)
328/// ```
329#[stdlib {
330    name = "legAngY",
331    tags = ["utilities"],
332}]
333fn inner_leg_angle_y(hypotenuse: f64, leg: f64) -> f64 {
334    (leg.min(hypotenuse) / hypotenuse).asin().to_degrees()
335}
336
337/// The primitive types that can be used in a KCL file.
338#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Display, FromStr)]
339#[serde(rename_all = "lowercase")]
340#[display(style = "lowercase")]
341pub enum Primitive {
342    /// A boolean value.
343    Bool,
344    /// A number value.
345    Number,
346    /// A string value.
347    String,
348    /// A uuid value.
349    Uuid,
350}