1use std::str::FromStr;
4
5use kittycad_modeling_cmds::coord::KITTYCAD;
6use kittycad_modeling_cmds::coord::OPENGL;
7use kittycad_modeling_cmds::coord::System;
8use kittycad_modeling_cmds::coord::VULKAN;
9use serde::Deserialize;
10use serde::Serialize;
11
12use crate::KclError;
13use crate::SourceRange;
14use crate::errors::KclErrorDetails;
15use crate::errors::Severity;
16use crate::parsing::ast::types::Annotation;
17use crate::parsing::ast::types::Expr;
18use crate::parsing::ast::types::LiteralValue;
19use crate::parsing::ast::types::Node;
20use crate::parsing::ast::types::ObjectProperty;
21
22pub(super) const SIGNIFICANT_ATTRS: [&str; 3] = [SETTINGS, NO_PRELUDE, WARNINGS];
24
25pub(crate) const SETTINGS: &str = "settings";
26pub(crate) const SETTINGS_UNIT_LENGTH: &str = "defaultLengthUnit";
27pub(crate) const SETTINGS_UNIT_ANGLE: &str = "defaultAngleUnit";
28pub(crate) const SETTINGS_VERSION: &str = "kclVersion";
29pub(crate) const SETTINGS_EXPERIMENTAL_FEATURES: &str = "experimentalFeatures";
30
31pub(super) const NO_PRELUDE: &str = "no_std";
32pub(crate) const DEPRECATED: &str = "deprecated";
33pub(crate) const EXPERIMENTAL: &str = "experimental";
34pub(crate) const INCLUDE_IN_FEATURE_TREE: &str = "feature_tree";
35
36pub(super) const IMPORT_FORMAT: &str = "format";
37pub(super) const IMPORT_COORDS: &str = "coords";
38pub(super) const IMPORT_COORDS_VALUES: [(&str, &System); 3] =
39 [("zoo", KITTYCAD), ("opengl", OPENGL), ("vulkan", VULKAN)];
40pub(super) const IMPORT_LENGTH_UNIT: &str = "lengthUnit";
41
42pub(crate) const IMPL: &str = "impl";
43pub(crate) const IMPL_RUST: &str = "std_rust";
44pub(crate) const IMPL_CONSTRAINT: &str = "std_rust_constraint";
45pub(crate) const IMPL_CONSTRAINABLE: &str = "std_constrainable";
46pub(crate) const IMPL_RUST_CONSTRAINABLE: &str = "std_rust_constrainable";
47pub(crate) const IMPL_KCL: &str = "kcl";
48pub(crate) const IMPL_PRIMITIVE: &str = "primitive";
49pub(super) const IMPL_VALUES: [&str; 6] = [
50 IMPL_RUST,
51 IMPL_KCL,
52 IMPL_PRIMITIVE,
53 IMPL_CONSTRAINT,
54 IMPL_CONSTRAINABLE,
55 IMPL_RUST_CONSTRAINABLE,
56];
57
58pub(crate) const WARNINGS: &str = "warnings";
59pub(crate) const WARN_ALLOW: &str = "allow";
60pub(crate) const WARN_DENY: &str = "deny";
61pub(crate) const WARN_WARN: &str = "warn";
62pub(super) const WARN_LEVELS: [&str; 3] = [WARN_ALLOW, WARN_DENY, WARN_WARN];
63pub(crate) const WARN_UNKNOWN_UNITS: &str = "unknownUnits";
64pub(crate) const WARN_ANGLE_UNITS: &str = "angleUnits";
65pub(crate) const WARN_UNKNOWN_ATTR: &str = "unknownAttribute";
66pub(crate) const WARN_MOD_RETURN_VALUE: &str = "moduleReturnValue";
67pub(crate) const WARN_DEPRECATED: &str = "deprecated";
68pub(crate) const WARN_IGNORED_Z_AXIS: &str = "ignoredZAxis";
69pub(crate) const WARN_SOLVER: &str = "solver";
70pub(crate) const WARN_SHOULD_BE_PERCENTAGE: &str = "shouldBePercentage";
71pub(crate) const WARN_INVALID_MATH: &str = "invalidMath";
72pub(crate) const WARN_UNNECESSARY_CLOSE: &str = "unnecessaryClose";
73pub(crate) const WARN_UNUSED_TAGS: &str = "unusedTags";
74pub(crate) const WARN_NOT_YET_SUPPORTED: &str = "notYetSupported";
75pub(super) const WARN_VALUES: [&str; 11] = [
76 WARN_UNKNOWN_UNITS,
77 WARN_ANGLE_UNITS,
78 WARN_UNKNOWN_ATTR,
79 WARN_MOD_RETURN_VALUE,
80 WARN_DEPRECATED,
81 WARN_IGNORED_Z_AXIS,
82 WARN_SOLVER,
83 WARN_SHOULD_BE_PERCENTAGE,
84 WARN_INVALID_MATH,
85 WARN_UNNECESSARY_CLOSE,
86 WARN_NOT_YET_SUPPORTED,
87];
88
89#[derive(Clone, Copy, Eq, PartialEq, Debug, Deserialize, Serialize, ts_rs::TS)]
90#[ts(export)]
91#[serde(tag = "type")]
92pub enum WarningLevel {
93 Allow,
94 Warn,
95 Deny,
96}
97
98impl WarningLevel {
99 pub(crate) fn is_allow(self) -> bool {
100 match self {
101 WarningLevel::Allow => true,
102 WarningLevel::Warn => false,
103 WarningLevel::Deny => false,
104 }
105 }
106
107 pub(crate) fn severity(self) -> Option<Severity> {
108 match self {
109 WarningLevel::Allow => None,
110 WarningLevel::Warn => Some(Severity::Warning),
111 WarningLevel::Deny => Some(Severity::Error),
112 }
113 }
114
115 pub(crate) fn as_str(self) -> &'static str {
116 match self {
117 WarningLevel::Allow => WARN_ALLOW,
118 WarningLevel::Warn => WARN_WARN,
119 WarningLevel::Deny => WARN_DENY,
120 }
121 }
122}
123
124impl FromStr for WarningLevel {
125 type Err = ();
126
127 fn from_str(s: &str) -> Result<Self, Self::Err> {
128 match s {
129 WARN_ALLOW => Ok(Self::Allow),
130 WARN_WARN => Ok(Self::Warn),
131 WARN_DENY => Ok(Self::Deny),
132 _ => Err(()),
133 }
134 }
135}
136
137#[derive(Clone, Copy, Eq, PartialEq, Debug, Default)]
138pub enum Impl {
139 #[default]
140 Kcl,
141 KclConstrainable,
142 Rust,
143 RustConstrainable,
144 RustConstraint,
145 Primitive,
146}
147
148impl FromStr for Impl {
149 type Err = ();
150
151 fn from_str(s: &str) -> Result<Self, Self::Err> {
152 match s {
153 IMPL_RUST => Ok(Self::Rust),
154 IMPL_CONSTRAINT => Ok(Self::RustConstraint),
155 IMPL_CONSTRAINABLE => Ok(Self::KclConstrainable),
156 IMPL_RUST_CONSTRAINABLE => Ok(Self::RustConstrainable),
157 IMPL_KCL => Ok(Self::Kcl),
158 IMPL_PRIMITIVE => Ok(Self::Primitive),
159 _ => Err(()),
160 }
161 }
162}
163
164pub(crate) fn settings_completion_text() -> String {
165 format!("@{SETTINGS}({SETTINGS_UNIT_LENGTH} = mm, {SETTINGS_VERSION} = 1.0)")
166}
167
168pub(super) fn is_significant(attr: &&Node<Annotation>) -> bool {
169 match attr.name() {
170 Some(name) => SIGNIFICANT_ATTRS.contains(&name),
171 None => true,
172 }
173}
174
175pub(super) fn expect_properties<'a>(
176 for_key: &'static str,
177 annotation: &'a Node<Annotation>,
178) -> Result<&'a [Node<ObjectProperty>], KclError> {
179 assert_eq!(annotation.name().unwrap(), for_key);
180 Ok(&**annotation.properties.as_ref().ok_or_else(|| {
181 KclError::new_semantic(KclErrorDetails::new(
182 format!("Empty `{for_key}` annotation"),
183 vec![annotation.as_source_range()],
184 ))
185 })?)
186}
187
188pub(super) fn expect_ident(expr: &Expr) -> Result<&str, KclError> {
189 if let Expr::Name(name) = expr
190 && let Some(name) = name.local_ident()
191 {
192 return Ok(*name);
193 }
194
195 Err(KclError::new_semantic(KclErrorDetails::new(
196 "Unexpected settings value, expected a simple name, e.g., `mm`".to_owned(),
197 vec![expr.into()],
198 )))
199}
200
201pub(super) fn many_of(
202 expr: &Expr,
203 of: &[&'static str],
204 source_range: SourceRange,
205) -> Result<Vec<&'static str>, KclError> {
206 const UNEXPECTED_MSG: &str = "Unexpected warnings value, expected a name or array of names, e.g., `unknownUnits` or `[unknownUnits, deprecated]`";
207
208 let values = match expr {
209 Expr::Name(name) => {
210 if let Some(name) = name.local_ident() {
211 vec![*name]
212 } else {
213 return Err(KclError::new_semantic(KclErrorDetails::new(
214 UNEXPECTED_MSG.to_owned(),
215 vec![expr.into()],
216 )));
217 }
218 }
219 Expr::ArrayExpression(e) => {
220 let mut result = Vec::new();
221 for e in &e.elements {
222 if let Expr::Name(name) = e
223 && let Some(name) = name.local_ident()
224 {
225 result.push(*name);
226 continue;
227 }
228 return Err(KclError::new_semantic(KclErrorDetails::new(
229 UNEXPECTED_MSG.to_owned(),
230 vec![e.into()],
231 )));
232 }
233 result
234 }
235 _ => {
236 return Err(KclError::new_semantic(KclErrorDetails::new(
237 UNEXPECTED_MSG.to_owned(),
238 vec![expr.into()],
239 )));
240 }
241 };
242
243 values
244 .into_iter()
245 .map(|v| {
246 of.iter()
247 .find(|vv| **vv == v)
248 .ok_or_else(|| {
249 KclError::new_semantic(KclErrorDetails::new(
250 format!("Unexpected warning value: `{v}`; accepted values: {}", of.join(", "),),
251 vec![source_range],
252 ))
253 })
254 .copied()
255 })
256 .collect::<Result<Vec<&str>, KclError>>()
257}
258
259pub(super) fn expect_number(expr: &Expr) -> Result<String, KclError> {
261 if let Expr::Literal(lit) = expr
262 && let LiteralValue::Number { .. } = &lit.value
263 {
264 return Ok(lit.raw.clone());
265 }
266
267 Err(KclError::new_semantic(KclErrorDetails::new(
268 "Unexpected settings value, expected a number, e.g., `1.0`".to_owned(),
269 vec![expr.into()],
270 )))
271}
272
273#[derive(Debug, Clone, Copy, Eq, PartialEq)]
274pub struct FnAttrs {
275 pub impl_: Impl,
276 pub deprecated: bool,
277 pub experimental: bool,
278 pub include_in_feature_tree: bool,
279}
280
281impl Default for FnAttrs {
282 fn default() -> Self {
283 Self {
284 impl_: Impl::default(),
285 deprecated: false,
286 experimental: false,
287 include_in_feature_tree: true,
288 }
289 }
290}
291
292pub(super) fn get_fn_attrs(
293 annotations: &[Node<Annotation>],
294 source_range: SourceRange,
295) -> Result<Option<FnAttrs>, KclError> {
296 let mut result = None;
297 for attr in annotations {
298 if attr.name.is_some() || attr.properties.is_none() {
299 continue;
300 }
301 for p in attr.properties.as_ref().unwrap() {
302 if &*p.key.name == IMPL
303 && let Some(s) = p.value.ident_name()
304 {
305 if result.is_none() {
306 result = Some(FnAttrs::default());
307 }
308
309 result.as_mut().unwrap().impl_ = Impl::from_str(s).map_err(|_| {
310 KclError::new_semantic(KclErrorDetails::new(
311 format!(
312 "Invalid value for {} attribute, expected one of: {}",
313 IMPL,
314 IMPL_VALUES.join(", ")
315 ),
316 vec![source_range],
317 ))
318 })?;
319 continue;
320 }
321
322 if &*p.key.name == DEPRECATED
323 && let Some(b) = p.value.literal_bool()
324 {
325 if result.is_none() {
326 result = Some(FnAttrs::default());
327 }
328 result.as_mut().unwrap().deprecated = b;
329 continue;
330 }
331
332 if &*p.key.name == EXPERIMENTAL
333 && let Some(b) = p.value.literal_bool()
334 {
335 if result.is_none() {
336 result = Some(FnAttrs::default());
337 }
338 result.as_mut().unwrap().experimental = b;
339 continue;
340 }
341
342 if &*p.key.name == INCLUDE_IN_FEATURE_TREE
343 && let Some(b) = p.value.literal_bool()
344 {
345 if result.is_none() {
346 result = Some(FnAttrs::default());
347 }
348 result.as_mut().unwrap().include_in_feature_tree = b;
349 continue;
350 }
351
352 return Err(KclError::new_semantic(KclErrorDetails::new(
353 format!(
354 "Invalid attribute, expected one of: {IMPL}, {DEPRECATED}, {EXPERIMENTAL}, {INCLUDE_IN_FEATURE_TREE}, found `{}`",
355 &*p.key.name,
356 ),
357 vec![source_range],
358 )));
359 }
360 }
361
362 Ok(result)
363}