1pub mod argument_value;
2pub mod array_lang;
3pub mod function_lang;
4pub mod module_lang;
5pub mod operators;
6pub mod var;
7pub mod var_function;
8
9use crate::components::context::config::Config;
10use crate::components::context::config::Environment;
11use crate::components::context::Context;
12use crate::components::error_message::help_data::HelpData;
13use crate::components::error_message::locatable::Locatable;
14use crate::components::error_message::syntax_error::SyntaxError;
15use crate::components::language::argument_value::ArgumentValue;
16use crate::components::language::operators::Op;
17use crate::components::language::var::Var;
18use crate::components::r#type::argument_type::ArgumentType;
19use crate::components::r#type::function_type::FunctionType;
20use crate::components::r#type::Type;
21use crate::processes::parsing::elements::elements;
22use crate::processes::parsing::lang_token::LangToken;
23use crate::processes::parsing::operation_priority::TokenKind;
24use crate::processes::transpiling::translatable::RTranslatable;
25use crate::processes::type_checking::type_context::TypeContext;
26use crate::processes::type_checking::typing;
27use crate::utils::builder;
28use serde::{Deserialize, Serialize};
29use std::str::FromStr;
30
31#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
32pub enum ModulePosition {
33 Internal,
34 External,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub enum Lang {
39 Number(f32, HelpData),
40 Integer(i32, HelpData),
41 Bool(bool, HelpData),
42 Char(String, HelpData),
43 Union(Box<Lang>, Box<Lang>, HelpData),
44 Scope(Vec<Lang>, HelpData),
45 Function(Vec<ArgumentType>, Type, Box<Lang>, HelpData),
46 Module(String, Vec<Lang>, ModulePosition, Config, HelpData),
47 ModuleDecl(String, HelpData),
48 Variable(String, bool, Type, HelpData),
49 FunctionApp(Box<Lang>, Vec<Lang>, HelpData),
50 VecFunctionApp(Box<Lang>, Vec<Lang>, HelpData),
51 MethodCall(Box<Lang>, Vec<Lang>, Type, HelpData),
52 ArrayIndexing(Box<Lang>, Box<Lang>, HelpData),
53 Let(Box<Lang>, Type, Box<Lang>, HelpData),
54 Alias(Box<Lang>, Vec<Type>, Type, HelpData),
55 Array(Vec<Lang>, HelpData),
56 Record(Vec<ArgumentValue>, HelpData),
57 Tag(String, Box<Lang>, HelpData),
58 If(Box<Lang>, Box<Lang>, Box<Lang>, HelpData),
59 Match(Box<Lang>, Var, Vec<(Type, Box<Lang>)>, HelpData),
60 Tuple(Vec<Lang>, HelpData),
61 Lines(Vec<Lang>, HelpData),
62 Assign(Box<Lang>, Box<Lang>, HelpData),
63 Comment(String, HelpData),
64 ModuleImport(String, HelpData),
65 Import(Type, HelpData),
66 GenFunc(String, String, HelpData),
67 Test(Vec<Lang>, HelpData),
68 Return(Box<Lang>, HelpData),
69 VecBlock(String, HelpData),
70 Lambda(Box<Lang>, HelpData),
71 Library(String, HelpData),
72 Exp(String, HelpData),
73 Signature(Var, Type, HelpData),
74 ForLoop(Var, Box<Lang>, Box<Lang>, HelpData),
75 RFunction(Vec<Lang>, String, HelpData),
76 KeyValue(String, Box<Lang>, HelpData),
77 Vector(Vec<Lang>, HelpData),
78 Sequence(Vec<Lang>, HelpData),
79 Not(Box<Lang>, HelpData),
80 TestBlock(Box<Lang>, HelpData),
81 JSBlock(Box<Lang>, u32, HelpData),
82 Use(Box<Lang>, Box<Lang>, HelpData),
83 Empty(HelpData),
84 WhileLoop(Box<Lang>, Box<Lang>, HelpData),
85 Break(HelpData),
86 Operator(Op, Box<Lang>, Box<Lang>, HelpData),
87 SyntaxErr(Box<Lang>, SyntaxError),
88}
89
90impl PartialEq for Lang {
91 fn eq(&self, other: &Self) -> bool {
92 match (self, other) {
93 (Lang::Number(a, _), Lang::Number(b, _)) => a == b,
94 (Lang::Integer(a, _), Lang::Integer(b, _)) => a == b,
95 (Lang::Bool(a, _), Lang::Bool(b, _)) => a == b,
96 (Lang::Char(a, _), Lang::Char(b, _)) => a == b,
97 (Lang::Union(a1, a2, _), Lang::Union(b1, b2, _)) => a1 == b1 && a2 == b2,
98 (Lang::Scope(a, _), Lang::Scope(b, _)) => a == b,
99 (Lang::Function(a1, a2, a3, _), Lang::Function(b1, b2, b3, _)) => {
100 a1 == b1 && a2 == b2 && a3 == b3
101 }
102 (Lang::Module(a1, a2, a3, a4, _), Lang::Module(b1, b2, b3, b4, _)) => {
103 a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4
104 }
105 (Lang::ModuleDecl(a, _), Lang::ModuleDecl(b, _)) => a == b,
106 (Lang::Variable(a1, a2, a3, _), Lang::Variable(b1, b2, b3, _)) => {
107 a1 == b1 && a2 == b2 && a3 == b3
108 }
109 (Lang::FunctionApp(a1, a2, _), Lang::FunctionApp(b1, b2, _)) => a1 == b1 && a2 == b2,
110 (Lang::VecFunctionApp(a1, a2, _), Lang::VecFunctionApp(b1, b2, _)) => {
111 a1 == b1 && a2 == b2
112 }
113 (Lang::MethodCall(a1, a2, a3, _), Lang::MethodCall(b1, b2, b3, _)) => {
114 a1 == b1 && a2 == b2 && a3 == b3
115 }
116 (Lang::ArrayIndexing(a1, a2, _), Lang::ArrayIndexing(b1, b2, _)) => {
117 a1 == b1 && a2 == b2
118 }
119 (Lang::Let(a1, a2, a3, _), Lang::Let(b1, b2, b3, _)) => {
120 a1 == b1 && a2 == b2 && a3 == b3
121 }
122 (Lang::Alias(a1, a2, a3, _), Lang::Alias(b1, b2, b3, _)) => {
123 a1 == b1 && a2 == b2 && a3 == b3
124 }
125 (Lang::Array(a, _), Lang::Array(b, _)) => a == b,
126 (Lang::Record(a, _), Lang::Record(b, _)) => a == b,
127 (Lang::Tag(a1, a2, _), Lang::Tag(b1, b2, _)) => a1 == b1 && a2 == b2,
128 (Lang::If(a1, a2, a3, _), Lang::If(b1, b2, b3, _)) => a1 == b1 && a2 == b2 && a3 == b3,
129 (Lang::Match(a1, a2, a3, _), Lang::Match(b1, b2, b3, _)) => {
130 a1 == b1 && a2 == b2 && a3 == b3
131 }
132 (Lang::Tuple(a, _), Lang::Tuple(b, _)) => a == b,
133 (Lang::Lines(a, _), Lang::Lines(b, _)) => a == b,
134 (Lang::Assign(a1, a2, _), Lang::Assign(b1, b2, _)) => a1 == b1 && a2 == b2,
135 (Lang::Comment(a, _), Lang::Comment(b, _)) => a == b,
136 (Lang::ModuleImport(a, _), Lang::ModuleImport(b, _)) => a == b,
137 (Lang::Import(a, _), Lang::Import(b, _)) => a == b,
138 (Lang::GenFunc(a1, a2, _), Lang::GenFunc(b1, b2, _)) => a1 == b1 && a2 == b2,
139 (Lang::Test(a, _), Lang::Test(b, _)) => a == b,
140 (Lang::Return(a, _), Lang::Return(b, _)) => a == b,
141 (Lang::VecBlock(a, _), Lang::VecBlock(b, _)) => a == b,
142 (Lang::Lambda(a, _), Lang::Lambda(b, _)) => a == b,
143 (Lang::Library(a, _), Lang::Library(b, _)) => a == b,
144 (Lang::Exp(a, _), Lang::Exp(b, _)) => a == b,
145 (Lang::Signature(a1, a2, _), Lang::Signature(b1, b2, _)) => a1 == b1 && a2 == b2,
146 (Lang::ForLoop(a1, a2, a3, _), Lang::ForLoop(b1, b2, b3, _)) => {
147 a1 == b1 && a2 == b2 && a3 == b3
148 }
149 (Lang::RFunction(a1, a2, _), Lang::RFunction(b1, b2, _)) => a1 == b1 && a2 == b2,
150 (Lang::KeyValue(a1, a2, _), Lang::KeyValue(b1, b2, _)) => a1 == b1 && a2 == b2,
151 (Lang::Vector(a, _), Lang::Vector(b, _)) => a == b,
152 (Lang::Sequence(a, _), Lang::Sequence(b, _)) => a == b,
153 (Lang::Not(a, _), Lang::Not(b, _)) => a == b,
154 (Lang::TestBlock(a, _), Lang::TestBlock(b, _)) => a == b,
155 (Lang::JSBlock(a1, a2, _), Lang::JSBlock(b1, b2, _)) => a1 == b1 && a2 == b2,
156 (Lang::Use(a1, a2, _), Lang::Use(b1, b2, _)) => a1 == b1 && a2 == b2,
157 (Lang::Empty(_), Lang::Empty(_)) => true,
158 (Lang::WhileLoop(a1, a2, _), Lang::WhileLoop(b1, b2, _)) => a1 == b1 && a2 == b2,
159 (Lang::Break(_), Lang::Break(_)) => true,
160 (Lang::Operator(a1, a2, a3, _), Lang::Operator(b1, b2, b3, _)) => {
161 a1 == b1 && a2 == b2 && a3 == b3
162 }
163 (Lang::SyntaxErr(a, _), Lang::SyntaxErr(b, _)) => a == b,
164 _ => false,
165 }
166 }
167}
168
169impl Eq for Lang {}
170
171impl Default for Lang {
172 fn default() -> Lang {
173 builder::empty_lang()
174 }
175}
176
177impl Locatable for Lang {
178 fn get_help_data(&self) -> HelpData {
179 Lang::get_help_data(self)
180 }
181}
182
183impl From<Var> for Lang {
184 fn from(val: Var) -> Self {
185 Lang::Variable(val.name, val.is_opaque, val.related_type, val.help_data)
186 }
187}
188
189impl From<LangToken> for Lang {
190 fn from(val: LangToken) -> Self {
191 match val {
192 LangToken::Expression(exp) => exp,
193 LangToken::Operator(op) => panic!("Shouldn't convert the token to lang {}", op),
194 LangToken::EmptyOperator => panic!("Shouldn't be empty "),
195 }
196 }
197}
198
199pub fn set_related_type_if_variable((val, arg): (&Lang, &Type)) -> Lang {
200 let oargs = FunctionType::try_from(arg.clone()).map(|fn_t| fn_t.get_param_types());
201
202 match oargs {
203 Ok(args) => (args.len() > 0)
204 .then_some(val.set_type_if_variable(&args[0]))
205 .unwrap_or(val.clone()),
206 Err(_) => val.clone(),
207 }
208}
209
210impl Lang {
212 pub fn save_in_memory(&self) -> bool {
213 match self {
214 Lang::Let(_, _, _, _) => true,
215 Lang::Assign(_, _, _) => true,
216 _ => false,
217 }
218 }
219
220 pub fn to_module(self, name: &str, environment: Environment) -> Self {
221 match self {
222 Lang::Lines(v, h) => Lang::Module(
223 name.to_string(),
224 v,
225 ModulePosition::External,
226 Config::default().set_environment(environment),
227 h,
228 ),
229 s => s,
230 }
231 }
232
233 fn set_type_if_variable(&self, typ: &Type) -> Lang {
234 match self {
235 Lang::Variable(name, spec, _, h) => {
236 Lang::Variable(name.clone(), spec.clone(), typ.clone(), h.clone())
237 }
238 _ => self.clone(),
239 }
240 }
241
242 pub fn to_arg_type(&self) -> Option<ArgumentType> {
243 match self {
244 Lang::Let(var, ty, _, _) => Some(ArgumentType::new(
245 &Var::from_language((**var).clone()).unwrap().get_name(),
246 &ty,
247 )),
248 Lang::Alias(var, _types, ty, _) => Some(ArgumentType::new(
249 &Var::from_language((**var).clone()).unwrap().get_name(),
250 &ty,
251 )),
252 _ => None,
253 }
254 }
255
256 pub fn extract_types_from_expression(&self, context: &Context) -> Vec<Type> {
257 if self.is_value() {
258 vec![typing(context, self).value.clone()]
259 } else {
260 match self {
261 Lang::FunctionApp(exp, arg_typs, _) => {
262 let typs = exp.extract_types_from_expression(context);
263 let typs2 = arg_typs
264 .iter()
265 .flat_map(|x| x.extract_types_from_expression(context))
266 .collect::<Vec<_>>();
267 typs.iter().chain(typs2.iter()).cloned().collect()
268 }
269 _ => vec![],
270 }
271 }
272 }
273
274 pub fn is_value(&self) -> bool {
275 match self {
276 Lang::Number(_, _) | Lang::Integer(_, _) | Lang::Bool(_, _) | Lang::Char(_, _) => true,
277 Lang::Array(_, _) => true,
278 _ => false,
279 }
280 }
281
282 pub fn is_undefined(&self) -> bool {
283 if let Lang::Function(_, _, body, _h) = self.clone() {
284 if let Lang::Scope(v, _) = *body.clone() {
285 let ele = v.first().unwrap();
286 if let Lang::Empty(_) = ele {
287 true
288 } else {
289 false
290 }
291 } else {
292 false
293 }
294 } else {
295 false
296 }
297 }
298
299 pub fn is_function(&self) -> bool {
300 match self {
301 Lang::Function(_, _, _, _) => true,
302 Lang::RFunction(_, _, _) => true,
303 _ => false,
304 }
305 }
306
307 pub fn infer_var_name(&self, args: &Vec<Lang>, context: &Context) -> Var {
308 if args.len() > 0 {
309 let first = typing(context, &args.iter().nth(0).unwrap().clone()).value;
310 Var::from_language(self.clone())
311 .unwrap()
312 .set_type(first.clone())
313 } else {
314 Var::from_language(self.clone()).unwrap()
315 }
316 }
317
318 pub fn get_related_function(self, args: &Vec<Lang>, context: &Context) -> Option<FunctionType> {
319 let var_name = self.infer_var_name(args, context);
320 let fn_ty = typing(context, &var_name.to_language()).value;
321 fn_ty.clone().to_function_type()
322 }
323
324 pub fn lang_substitution(&self, sub_var: &Lang, var: &Lang, context: &Context) -> String {
325 if let Lang::Variable(name, _, _, _) = var {
326 let res = match self {
327 Lang::Variable(_, _, _, h) if self == sub_var => {
328 Lang::Exp(format!("{}[[2]]", name.to_string()), h.clone())
329 }
330 lang => lang.clone(),
331 };
332 res.to_r(context).0
333 } else {
334 panic!("var is not a variable")
335 }
336 }
337
338 pub fn get_help_data(&self) -> HelpData {
339 match self {
340 Lang::Number(_, h) => h,
341 Lang::Integer(_, h) => h,
342 Lang::Char(_, h) => h,
343 Lang::Bool(_, h) => h,
344 Lang::Union(_, _, h) => h,
345 Lang::Scope(_, h) => h,
346 Lang::Function(_, _, _, h) => h,
347 Lang::Module(_, _, _, _, h) => h,
348 Lang::ModuleDecl(_, h) => h,
349 Lang::Variable(_, _, _, h) => h,
350 Lang::FunctionApp(_, _, h) => h,
351 Lang::VecFunctionApp(_, _, h) => h,
352 Lang::MethodCall(_, _, _, h) => h,
353 Lang::ArrayIndexing(_, _, h) => h,
354 Lang::Let(_, _, _, h) => h,
355 Lang::Array(_, h) => h,
356 Lang::Record(_, h) => h,
357 Lang::Alias(_, _, _, h) => h,
358 Lang::Tag(_, _, h) => h,
359 Lang::If(_, _, _, h) => h,
360 Lang::Match(_, _, _, h) => h,
361 Lang::Tuple(_, h) => h,
362 Lang::Lines(_, h) => h,
363 Lang::Assign(_, _, h) => h,
364 Lang::Comment(_, h) => h,
365 Lang::ModuleImport(_, h) => h,
366 Lang::Import(_, h) => h,
367 Lang::GenFunc(_, _, h) => h,
368 Lang::Test(_, h) => h,
369 Lang::Return(_, h) => h,
370 Lang::VecBlock(_, h) => h,
371 Lang::Lambda(_, h) => h,
372 Lang::Library(_, h) => h,
373 Lang::Exp(_, h) => h,
374 Lang::Empty(h) => h,
375 Lang::Signature(_, _, h) => h,
376 Lang::ForLoop(_, _, _, h) => h,
377 Lang::RFunction(_, _, h) => h,
378 Lang::KeyValue(_, _, h) => h,
379 Lang::Vector(_, h) => h,
380 Lang::Not(_, h) => h,
381 Lang::Sequence(_, h) => h,
382 Lang::TestBlock(_, h) => h,
383 Lang::JSBlock(_, _, h) => h,
384 Lang::Use(_, _, h) => h,
385 Lang::WhileLoop(_, _, h) => h,
386 Lang::Break(h) => h,
387 Lang::Operator(_, _, _, h) => h,
388 Lang::SyntaxErr(inner, _) => return inner.get_help_data(),
389 }
390 .clone()
391 }
392
393 pub fn linearize_array(&self) -> Vec<Lang> {
394 match self {
395 Lang::Array(v, _) => v.iter().fold(vec![], |acc, x| {
396 acc.iter()
397 .chain(x.linearize_array().iter())
398 .cloned()
399 .collect()
400 }),
401 _ => vec![self.to_owned()],
402 }
403 }
404
405 pub fn is_r_function(&self) -> bool {
406 match self {
407 Lang::RFunction(_, _, _) => true,
408 _ => false,
409 }
410 }
411
412 pub fn nb_params(&self) -> usize {
413 self.simple_print();
414 match self {
415 Lang::Function(params, _, _, _) => params.len(),
416 _ => 0 as usize,
417 }
418 }
419
420 pub fn simple_print(&self) -> String {
421 match self {
422 Lang::Number(_, _) => "Number".to_string(),
423 Lang::Integer(_, _) => "Integer".to_string(),
424 Lang::Char(_, _) => "Char".to_string(),
425 Lang::Bool(_, _) => "Bool".to_string(),
426 Lang::Union(_, _, _) => "Union".to_string(),
427 Lang::Scope(_, _) => "Scope".to_string(),
428 Lang::Function(_, _, _, _) => "Function".to_string(),
429 Lang::Module(_, _, _, _, _) => "Module".to_string(),
430 Lang::ModuleDecl(_, _) => "ModuleDecl".to_string(),
431 Lang::Variable(name, _, _, _) => format!("Variable({})", name),
432 Lang::FunctionApp(var, _, _) => format!(
433 "FunctionApp({})",
434 Var::from_language(*(var.clone())).unwrap().get_name()
435 ),
436 Lang::VecFunctionApp(var, _, _) => format!(
437 "VecFunctionApp({})",
438 Var::from_language(*(var.clone())).unwrap().get_name()
439 ),
440 Lang::MethodCall(var, _, _, _) => format!(
441 "MethodCall({})",
442 Var::from_language(*(var.clone())).unwrap().get_name()
443 ),
444 Lang::ArrayIndexing(_, _, _) => "ArrayIndexing".to_string(),
445 Lang::Let(var, _, _, _) => format!(
446 "let {}",
447 Var::from_language((**var).clone()).unwrap().get_name()
448 ),
449 Lang::Array(_, _) => "Array".to_string(),
450 Lang::Record(_, _) => "Record".to_string(),
451 Lang::Alias(_, _, _, _) => "Alias".to_string(),
452 Lang::Tag(_, _, _) => "Tag".to_string(),
453 Lang::If(_, _, _, _) => "If".to_string(),
454 Lang::Match(_, _, _, _) => "Match".to_string(),
455 Lang::Tuple(_, _) => "Tuple".to_string(),
456 Lang::Lines(_, _) => "Sequence".to_string(),
457 Lang::Assign(_, _, _) => "Assign".to_string(),
458 Lang::Comment(_, _) => "Comment".to_string(),
459 Lang::ModuleImport(_, _) => "ModImp".to_string(),
460 Lang::Import(_, _) => "Import".to_string(),
461 Lang::GenFunc(_, _, _) => "GenFunc".to_string(),
462 Lang::Test(_, _) => "Test".to_string(),
463 Lang::Return(_, _) => "Return".to_string(),
464 Lang::VecBlock(_, _) => "VecBloc".to_string(),
465 Lang::Lambda(_, _) => "Lambda".to_string(),
466 Lang::Library(_, _) => "Library".to_string(),
467 Lang::Exp(_, _) => "Exp".to_string(),
468 Lang::Empty(_) => "Empty".to_string(),
469 Lang::Signature(_, _, _) => "Signature".to_string(),
470 Lang::ForLoop(_, _, _, _) => "ForLoop".to_string(),
471 Lang::RFunction(_, _, _) => "RFunction".to_string(),
472 Lang::KeyValue(_, _, _) => "KeyValue".to_string(),
473 Lang::Vector(_, _) => "Vector".to_string(),
474 Lang::Not(_, _) => "Not".to_string(),
475 Lang::Sequence(_, _) => "Sequence".to_string(),
476 Lang::TestBlock(_, _) => "TestBlock".to_string(),
477 Lang::JSBlock(_, _, _) => "JSBlock".to_string(),
478 Lang::Use(_, _, _) => "Use".to_string(),
479 Lang::WhileLoop(_, _, _) => "WhileLoop".to_string(),
480 Lang::Break(_) => "Break".to_string(),
481 Lang::Operator(_, _, _, _) => "Operator".to_string(),
482 Lang::SyntaxErr(_, _) => "SyntaxErr".to_string(),
483 }
484 }
485
486 pub fn typing(&self, context: &Context) -> TypeContext {
487 typing(context, self)
488 }
489
490 pub fn to_js(&self, context: &Context) -> (String, Context) {
491 match self {
492 Lang::Char(val, _) => (format!("\\'{}\\'", val), context.clone()),
493 Lang::Bool(b, _) => (format!("{}", b.to_string().to_uppercase()), context.clone()),
494 Lang::Number(n, _) => (format!("{}", n), context.clone()),
495 Lang::Integer(i, _) => (format!("{}", i), context.clone()),
496 Lang::Let(var, _, body, _) => (
497 format!(
498 "let {} = {};",
499 Var::from_language(*(var.clone())).unwrap().get_name(),
500 body.to_js(context).0
501 ),
502 context.clone(),
503 ),
504 Lang::Assign(var, body, _) => (
505 format!("{} = {};", var.to_js(context).0, body.to_js(context).0),
506 context.clone(),
507 ),
508 Lang::Scope(langs, _) => {
509 let res = langs
510 .iter()
511 .map(|x| x.to_js(context).0)
512 .collect::<Vec<_>>()
513 .join("\n");
514 (res, context.clone())
515 }
516 Lang::Return(exp, _) => (format!("return {};", exp.to_js(context).0), context.clone()),
517 Lang::FunctionApp(exp, params, _) => {
518 let var = Var::try_from(exp.clone()).unwrap();
519 let res = format!(
520 "{}({})",
521 var.get_name().replace("__", "."),
522 params
523 .iter()
524 .map(|x| x.to_js(context).0)
525 .collect::<Vec<_>>()
526 .join(", ")
527 );
528 (res, context.clone())
529 }
530 Lang::Function(params, _, body, _) => {
531 let parameters = ¶ms
532 .iter()
533 .map(|x| x.get_argument_str())
534 .collect::<Vec<_>>()
535 .join(", ");
536 (
537 format!("({}) => {{\n{}\n}}", parameters, body.to_js(context).0),
538 context.clone(),
539 )
540 }
541 Lang::Use(lib, members, _) => {
542 let body = match (**members).clone() {
543 Lang::Vector(v, _) => v
544 .iter()
545 .map(|val| val.to_js(context).0.replace("\\'", ""))
546 .collect::<Vec<_>>()
547 .join(", "),
548 Lang::Char(val, _) => val.clone(),
549 lang => lang.simple_print(),
550 };
551 (
552 format!("import {{ {} }} from {};", body, lib.to_js(context).0),
553 context.clone(),
554 )
555 }
556 Lang::Sequence(v, _) => {
557 let res = "[".to_string()
558 + &v.iter()
559 .map(|lang| lang.to_js(context).0)
560 .collect::<Vec<_>>()
561 .join(", ")
562 + "]";
563 (res, context.clone())
564 }
565 Lang::Array(v, _) => {
566 let res = "[".to_string()
567 + &v.iter()
568 .map(|lang| lang.to_js(context).0)
569 .collect::<Vec<_>>()
570 .join(", ")
571 + "]";
572 (res, context.clone())
573 }
574 Lang::Vector(v, _) => {
575 let res = "[".to_string()
576 + &v.iter()
577 .map(|lang| lang.to_js(context).0)
578 .collect::<Vec<_>>()
579 .join(", ")
580 + "]";
581 (res, context.clone())
582 }
583 Lang::Record(arg_vals, _) => {
584 let res = "{".to_string()
585 + &arg_vals
586 .iter()
587 .map(|arg_val| {
588 arg_val.get_argument().replace("'", "")
589 + ": "
590 + &arg_val.get_value().to_js(context).0
591 })
592 .collect::<Vec<_>>()
593 .join(", ")
594 + "}";
595 (res, context.clone())
596 }
597 Lang::Lambda(body, _) => (format!("x => {}", body.to_js(context).0), context.clone()),
598 Lang::Operator(op, e1, e2, _) => (
599 format!(
600 "{} {} {}",
601 e1.to_js(context).0,
602 op.to_string(),
603 e2.to_js(context).0
604 ),
605 context.clone(),
606 ),
607 _ => self.to_r(context),
608 }
609 }
610
611 pub fn to_simple_r(&self, context: &Context) -> (String, Context) {
612 match self {
613 Lang::Number(n, _) => (n.to_string(), context.clone()),
614 Lang::Array(v, _) => {
615 if v.len() == 1 {
616 v[0].to_simple_r(context)
617 } else {
618 panic!("Not yet implemented for indexing of multiple elements")
619 }
620 }
621 _ => self.to_r(context),
622 }
623 }
624
625 pub fn to_module_member(self) -> Lang {
626 match self {
627 Lang::Module(name, body, _, _, h) => {
628 Lang::Lines(body.clone(), h).to_module_helper(&name)
629 }
630 res => res,
631 }
632 }
633
634 pub fn to_module_helper(self, name: &str) -> Lang {
635 match self.clone() {
636 Lang::Variable(_, _, _, h) => Lang::Operator(
637 Op::Dollar(h.clone()),
638 Box::new(Var::from_name(name).to_language()),
639 Box::new(self),
640 h,
641 ),
642 Lang::Let(var, typ, lang, h) => {
643 let expr = Lang::Operator(
644 Op::Dollar(h.clone()),
645 var,
646 Box::new(Var::from_name(name).to_language()),
647 h.clone(),
648 );
649 Lang::Let(Box::new(expr), typ, lang, h)
650 }
651 Lang::Alias(var, types, typ, h) => {
652 let expr = Lang::Operator(
653 Op::Dollar(h.clone()),
654 Box::new(Var::from_name(name).to_language()),
655 var,
656 h.clone(),
657 );
658 Lang::Alias(Box::new(expr), types, typ, h)
659 }
660 Lang::Function(args, typ, body, h) => {
661 Lang::Function(args, typ, Box::new(body.to_module_helper(name)), h)
662 }
663 Lang::Lines(exprs, h) => Lang::Lines(
664 exprs
665 .iter()
666 .cloned()
667 .map(|expr| expr.to_module_helper(name))
668 .collect::<Vec<_>>(),
669 h,
670 ),
671 rest => rest,
672 }
673 }
674
675 pub fn to_arg_value(self, type_module: &Type, context: &Context) -> Option<Vec<ArgumentValue>> {
676 match self {
677 Lang::Let(lang, _, body, h) if Var::from_language(*lang.clone()).is_some() => {
678 let var = Var::from_language(*lang).unwrap();
679 type_module
680 .get_first_function_parameter_type(&var.get_name())
681 .map(|typ_par| {
682 var.clone().set_name(&format!(
683 "{}.{}",
684 var.get_name(),
685 context.get_type_anotation_no_parentheses(&typ_par)
686 ))
687 })
688 .map(|var2| {
689 Some(vec![
690 ArgumentValue(
691 var.get_name(),
692 Lang::GenFunc(var.get_name(), var.get_name(), h),
693 ),
694 ArgumentValue(var2.get_name(), *body.clone()),
695 ])
696 })
697 .unwrap_or(Some(vec![ArgumentValue(var.get_name(), *body)]))
698 }
699 _ => None,
700 }
701 }
702
703 pub fn get_token_type(&self) -> TokenKind {
704 TokenKind::Expression
705 }
706
707 pub fn get_binding_power(&self) -> i32 {
708 1
709 }
710
711 pub fn get_members_if_array(&self) -> Option<Vec<Lang>> {
712 match self {
713 Lang::Array(members, _) => Some(members.clone()),
714 _ => None,
715 }
716 }
717
718 pub fn len(&self) -> i32 {
719 match self {
720 Lang::Integer(i, _) => *i,
721 n => panic!("not implemented for language {}", n.simple_print()),
722 }
723 }
724
725 pub fn to_vec(self) -> Vec<Lang> {
726 match self {
727 Lang::Lines(v, _) => v,
728 l => vec![l],
729 }
730 }
731}
732
733impl From<Lang> for HelpData {
734 fn from(val: Lang) -> Self {
735 match val {
736 Lang::Number(_, h) => h,
737 Lang::Integer(_, h) => h,
738 Lang::Bool(_, h) => h,
739 Lang::Char(_, h) => h,
740 Lang::Variable(_, _, _, h) => h,
741 Lang::Match(_, _, _, h) => h,
742 Lang::FunctionApp(_, _, h) => h,
743 Lang::VecFunctionApp(_, _, h) => h,
744 Lang::MethodCall(_, _, _, h) => h,
745 Lang::Empty(h) => h,
746 Lang::Array(_, h) => h,
747 Lang::Record(_, h) => h,
748 Lang::Scope(_, h) => h,
749 Lang::Let(_, _, _, h) => h,
750 Lang::Alias(_, _, _, h) => h,
751 Lang::Lambda(_, h) => h,
752 Lang::Function(_, _, _, h) => h,
753 Lang::VecBlock(_, h) => h,
754 Lang::If(_, _, _, h) => h,
755 Lang::Assign(_, _, h) => h,
756 Lang::Union(_, _, h) => h,
757 Lang::Module(_, _, _, _, h) => h,
758 Lang::ModuleDecl(_, h) => h,
759 Lang::ModuleImport(_, h) => h,
760 Lang::Import(_, h) => h,
761 Lang::ArrayIndexing(_, _, h) => h,
762 Lang::Tag(_, _, h) => h,
763 Lang::Tuple(_, h) => h,
764 Lang::Lines(_, h) => h,
765 Lang::Comment(_, h) => h,
766 Lang::GenFunc(_, _, h) => h,
767 Lang::Test(_, h) => h,
768 Lang::Return(_, h) => h,
769 Lang::Library(_, h) => h,
770 Lang::Exp(_, h) => h,
771 Lang::Signature(_, _, h) => h,
772 Lang::ForLoop(_, _, _, h) => h,
773 Lang::RFunction(_, _, h) => h,
774 Lang::KeyValue(_, _, h) => h,
775 Lang::Vector(_, h) => h,
776 Lang::Not(_, h) => h,
777 Lang::Sequence(_, h) => h,
778 Lang::TestBlock(_, h) => h,
779 Lang::JSBlock(_, _, h) => h,
780 Lang::Use(_, _, h) => h,
781 Lang::WhileLoop(_, _, h) => h,
782 Lang::Break(h) => h,
783 Lang::Operator(_, _, _, h) => h,
784 Lang::SyntaxErr(inner, _) => return (*inner).clone().into(),
785 }
786 .clone()
787 }
788}
789
790use std::fmt;
791impl fmt::Display for Lang {
792 fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793 let res = match self {
794 Lang::Variable(name, _bo, typ, _h) => format!("{} -> {}", name, typ),
795 _ => format!("{:?}", self),
796 };
797 write!(f, "{}", res)
798 }
799}
800
801pub fn format_backtick(s: String) -> String {
802 "`".to_string() + &s.replace("`", "") + "`"
803}
804
805#[derive(Debug)]
806pub struct ErrorStruct;
807
808impl FromStr for Lang {
809 type Err = ErrorStruct;
810
811 fn from_str(s: &str) -> Result<Self, Self::Err> {
812 let val = elements(s.into())
813 .map(|x| x.1)
814 .unwrap_or(builder::empty_lang());
815 Ok(val)
816 }
817}