Fork of daniellemaywood.uk/gleam — Wasm codegen work
2

Configure Feed

Select the types of activity you want to include in your feed.

gleam / compiler-core / src / ast.rs
151 kB 4638 lines
1mod constant; 2mod typed; 3mod untyped; 4 5#[cfg(test)] 6mod tests; 7pub mod visit; 8 9pub use self::typed::{InvalidExpression, RecordUpdateAssignment, TypedExpr}; 10pub use self::untyped::{FunctionLiteralKind, UntypedExpr}; 11 12pub use self::constant::{Constant, TypedConstant, UntypedConstant}; 13 14use crate::analyse::Inferred; 15use crate::ast::typed::pairwise_all; 16use crate::bit_array; 17use crate::build::{ExpressionPosition, Located, Target, module_erlang_name}; 18use crate::exhaustiveness::CompiledCase; 19use crate::parse::{LiteralFloatValue, SpannedString}; 20use crate::type_::error::VariableOrigin; 21use crate::type_::expression::{Implementations, Purity}; 22use crate::type_::printer::Names; 23use crate::type_::{ 24 self, Deprecation, HasType, ModuleValueConstructor, PatternConstructor, Type, TypedCallArg, 25 ValueConstructor, ValueConstructorVariant, nil, 26}; 27use itertools::Itertools; 28use num_traits::Zero; 29use std::collections::HashSet; 30use std::sync::Arc; 31 32use ecow::EcoString; 33use num_bigint::{BigInt, Sign}; 34use num_traits::{One, ToPrimitive}; 35#[cfg(test)] 36use pretty_assertions::assert_eq; 37use vec1::Vec1; 38 39pub const PIPE_VARIABLE: &str = "_pipe"; 40pub const USE_ASSIGNMENT_VARIABLE: &str = "_use"; 41pub const RECORD_UPDATE_VARIABLE: &str = "_record"; 42pub const ASSERT_FAIL_VARIABLE: &str = "_assert_fail"; 43pub const ASSERT_SUBJECT_VARIABLE: &str = "_assert_subject"; 44pub const CAPTURE_VARIABLE: &str = "_capture"; 45pub const BLOCK_VARIABLE: &str = "_block"; 46 47pub trait HasLocation { 48 fn location(&self) -> SrcSpan; 49} 50 51pub type UntypedModule = Module<(), Vec<TargetedDefinition>>; 52pub type TypedModule = Module<type_::ModuleInterface, TypedDefinitions>; 53 54#[derive(Debug, Clone, PartialEq, Eq)] 55pub struct Module<Info, Definitions> { 56 pub name: EcoString, 57 pub documentation: Vec<EcoString>, 58 pub type_info: Info, 59 pub definitions: Definitions, 60 pub names: Names, 61 /// The source byte locations of definition that are unused. 62 /// This is used in code generation to know when definitions can be safely omitted. 63 pub unused_definition_positions: HashSet<u32>, 64} 65 66impl<Info, Definitions> Module<Info, Definitions> { 67 pub fn erlang_name(&self) -> EcoString { 68 module_erlang_name(&self.name) 69 } 70} 71 72impl TypedModule { 73 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 74 let TypedDefinitions { 75 imports, 76 constants, 77 custom_types, 78 type_aliases, 79 functions, 80 } = &self.definitions; 81 82 imports 83 .iter() 84 .find_map(|import| import.find_node(byte_index)) 85 .or_else(|| (constants.iter()).find_map(|constant| constant.find_node(byte_index))) 86 .or_else(|| (custom_types.iter()).find_map(|type_| type_.find_node(byte_index))) 87 .or_else(|| (type_aliases.iter()).find_map(|alias| alias.find_node(byte_index))) 88 .or_else(|| (functions.iter()).find_map(|function| function.find_node(byte_index))) 89 } 90 91 pub fn find_statement(&self, byte_index: u32) -> Option<&TypedStatement> { 92 // Statements can only be found inside a module function, there's no 93 // need to go over all the other module definitions. 94 self.definitions 95 .functions 96 .iter() 97 .find_map(|function| function.find_statement(byte_index)) 98 } 99 100 pub fn definitions_len(&self) -> usize { 101 let TypedDefinitions { 102 imports, 103 constants, 104 custom_types, 105 type_aliases, 106 functions, 107 } = &self.definitions; 108 109 imports.len() + constants.len() + custom_types.len() + type_aliases.len() + functions.len() 110 } 111} 112 113#[derive(Debug)] 114pub struct TypedDefinitions { 115 pub imports: Vec<TypedImport>, 116 pub constants: Vec<TypedModuleConstant>, 117 pub custom_types: Vec<TypedCustomType>, 118 pub type_aliases: Vec<TypedTypeAlias>, 119 pub functions: Vec<TypedFunction>, 120} 121 122/// The `@target(erlang)` and `@target(javascript)` attributes can be used to 123/// mark a definition as only being for a specific target. 124/// 125/// ```gleam 126/// const x: Int = 1 127/// 128/// @target(erlang) 129/// pub fn main(a) { ...} 130/// ``` 131/// 132#[derive(Debug, Clone, PartialEq, Eq)] 133pub struct TargetedDefinition { 134 pub definition: UntypedDefinition, 135 pub target: Option<Target>, 136} 137 138impl TargetedDefinition { 139 pub fn is_for(&self, target: Target) -> bool { 140 self.target.map(|t| t == target).unwrap_or(true) 141 } 142} 143 144impl UntypedModule { 145 pub fn dependencies(&self, target: Target) -> Vec<(EcoString, SrcSpan)> { 146 self.iter_definitions(target) 147 .flat_map(|definition| match definition { 148 Definition::Import(Import { 149 module, location, .. 150 }) => Some((module.clone(), *location)), 151 Definition::Function(_) 152 | Definition::TypeAlias(_) 153 | Definition::CustomType(_) 154 | Definition::ModuleConstant(_) => None, 155 }) 156 .collect() 157 } 158 159 pub fn iter_definitions(&self, target: Target) -> impl Iterator<Item = &UntypedDefinition> { 160 self.definitions 161 .iter() 162 .filter(move |definition| definition.is_for(target)) 163 .map(|definition| &definition.definition) 164 } 165 166 pub fn into_iter_definitions(self, target: Target) -> impl Iterator<Item = UntypedDefinition> { 167 self.definitions 168 .into_iter() 169 .filter(move |definition| definition.is_for(target)) 170 .map(|definition| definition.definition) 171 } 172} 173 174#[test] 175fn module_dependencies_test() { 176 let parsed = crate::parse::parse_module( 177 camino::Utf8PathBuf::from("test/path"), 178 "import one 179 @target(erlang) 180 import two 181 182 @target(javascript) 183 import three 184 185 import four", 186 &crate::warning::WarningEmitter::null(), 187 ) 188 .expect("syntax error"); 189 let module = parsed.module; 190 191 assert_eq!( 192 vec![ 193 ("one".into(), SrcSpan::new(0, 10)), 194 ("two".into(), SrcSpan::new(45, 55)), 195 ("four".into(), SrcSpan::new(118, 129)), 196 ], 197 module.dependencies(Target::Erlang) 198 ); 199} 200 201pub type TypedArg = Arg<Arc<Type>>; 202pub type UntypedArg = Arg<()>; 203 204#[derive(Debug, Clone, PartialEq, Eq)] 205pub struct Arg<T> { 206 pub names: ArgNames, 207 pub location: SrcSpan, 208 pub annotation: Option<TypeAst>, 209 pub type_: T, 210} 211 212impl<A> Arg<A> { 213 pub fn set_type<B>(self, t: B) -> Arg<B> { 214 Arg { 215 type_: t, 216 names: self.names, 217 location: self.location, 218 annotation: self.annotation, 219 } 220 } 221 222 pub fn get_variable_name(&self) -> Option<&EcoString> { 223 self.names.get_variable_name() 224 } 225 226 pub fn is_capture_hole(&self) -> bool { 227 match &self.names { 228 ArgNames::Named { name, .. } if name == CAPTURE_VARIABLE => true, 229 ArgNames::Discard { .. } 230 | ArgNames::LabelledDiscard { .. } 231 | ArgNames::Named { .. } 232 | ArgNames::NamedLabelled { .. } => false, 233 } 234 } 235} 236 237impl TypedArg { 238 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 239 if self.location.contains(byte_index) { 240 if let Some(annotation) = &self.annotation { 241 return annotation 242 .find_node(byte_index, self.type_.clone()) 243 .or(Some(Located::Arg(self))); 244 } 245 Some(Located::Arg(self)) 246 } else { 247 None 248 } 249 } 250} 251 252#[derive(Debug, Clone, PartialEq, Eq)] 253pub enum ArgNames { 254 Discard { 255 name: EcoString, 256 location: SrcSpan, 257 }, 258 LabelledDiscard { 259 label: EcoString, 260 label_location: SrcSpan, 261 name: EcoString, 262 name_location: SrcSpan, 263 }, 264 Named { 265 name: EcoString, 266 location: SrcSpan, 267 }, 268 NamedLabelled { 269 label: EcoString, 270 label_location: SrcSpan, 271 name: EcoString, 272 name_location: SrcSpan, 273 }, 274} 275 276impl ArgNames { 277 pub fn get_label(&self) -> Option<&EcoString> { 278 match self { 279 ArgNames::Discard { .. } | ArgNames::Named { .. } => None, 280 ArgNames::LabelledDiscard { label, .. } | ArgNames::NamedLabelled { label, .. } => { 281 Some(label) 282 } 283 } 284 } 285 pub fn get_variable_name(&self) -> Option<&EcoString> { 286 match self { 287 ArgNames::Discard { .. } | ArgNames::LabelledDiscard { .. } => None, 288 ArgNames::NamedLabelled { name, .. } | ArgNames::Named { name, .. } => Some(name), 289 } 290 } 291} 292 293pub type TypedRecordConstructor = RecordConstructor<Arc<Type>>; 294 295#[derive(Debug, Clone, PartialEq, Eq)] 296pub struct RecordConstructor<T> { 297 pub location: SrcSpan, 298 pub name_location: SrcSpan, 299 pub name: EcoString, 300 pub arguments: Vec<RecordConstructorArg<T>>, 301 pub documentation: Option<(u32, EcoString)>, 302 pub deprecation: Deprecation, 303} 304 305impl<A> RecordConstructor<A> { 306 pub fn put_doc(&mut self, new_doc: (u32, EcoString)) { 307 self.documentation = Some(new_doc); 308 } 309} 310 311pub type TypedRecordConstructorArg = RecordConstructorArg<Arc<Type>>; 312 313#[derive(Debug, Clone, PartialEq, Eq)] 314pub struct RecordConstructorArg<T> { 315 pub label: Option<SpannedString>, 316 pub ast: TypeAst, 317 pub location: SrcSpan, 318 pub type_: T, 319 pub doc: Option<(u32, EcoString)>, 320} 321 322impl<T: PartialEq> RecordConstructorArg<T> { 323 pub fn put_doc(&mut self, new_doc: (u32, EcoString)) { 324 self.doc = Some(new_doc); 325 } 326} 327 328#[derive(Debug, Clone, PartialEq, Eq)] 329pub struct TypeAstConstructor { 330 pub location: SrcSpan, 331 pub name: TypeAstConstructorName, 332 pub arguments: Vec<TypeAst>, 333 pub start_parentheses: Option<u32>, 334} 335 336/// This represents a type constructor name, that can either be qualified, or 337/// unqualified. 338#[derive(Debug, Clone, PartialEq, Eq)] 339pub enum TypeAstConstructorName { 340 /// ```gleam 341 /// pub fn wibble() -> wibble.Wibble 342 /// // ^^^^^^ module 343 /// // ^^^^^^ name 344 /// ``` 345 Qualified { 346 module: EcoString, 347 module_location: SrcSpan, 348 dot_location: u32, 349 /// Notice how the name could be missing, this is an error! However, instead 350 /// of treating it like a syntax error we allow parsing it and report it 351 /// later. This way the language server can provide better help! 352 name: Option<(EcoString, SrcSpan)>, 353 }, 354 355 /// ```gleam 356 /// pub fn wibble() -> Wibble 357 /// // ^^^^^^ name 358 /// ``` 359 Unqualified { name: EcoString, location: SrcSpan }, 360} 361 362impl TypeAstConstructorName { 363 pub fn is_qualified(&self) -> bool { 364 match self { 365 TypeAstConstructorName::Qualified { .. } => true, 366 TypeAstConstructorName::Unqualified { .. } => false, 367 } 368 } 369 370 pub fn module_name(&self) -> Option<&EcoString> { 371 match self { 372 TypeAstConstructorName::Qualified { module, .. } => Some(module), 373 TypeAstConstructorName::Unqualified { .. } => None, 374 } 375 } 376 377 pub fn name(&self) -> Option<&EcoString> { 378 match self { 379 TypeAstConstructorName::Unqualified { name, .. } 380 | TypeAstConstructorName::Qualified { 381 name: Some((name, _)), 382 .. 383 } => Some(name), 384 385 TypeAstConstructorName::Qualified { name: None, .. } => None, 386 } 387 } 388 389 pub fn name_location(&self) -> Option<SrcSpan> { 390 match self { 391 TypeAstConstructorName::Unqualified { location, .. } 392 | TypeAstConstructorName::Qualified { 393 name: Some((_, location)), 394 .. 395 } => Some(*location), 396 397 TypeAstConstructorName::Qualified { name: None, .. } => None, 398 } 399 } 400 401 fn is_logically_equal(&self, other: &TypeAstConstructorName) -> bool { 402 match (self, other) { 403 ( 404 TypeAstConstructorName::Qualified { module, name, .. }, 405 TypeAstConstructorName::Qualified { 406 module: other_module, 407 name: other_name, 408 .. 409 }, 410 ) => { 411 module == other_module 412 && match (name, other_name) { 413 (Some((name, _)), Some((other_name, _))) => name == other_name, 414 (None, Some(_)) | (Some(_), None) => false, 415 (None, None) => true, 416 } 417 } 418 419 ( 420 TypeAstConstructorName::Unqualified { name, location: _ }, 421 TypeAstConstructorName::Unqualified { 422 name: other_name, 423 location: _, 424 }, 425 ) => name == other_name, 426 427 ( 428 TypeAstConstructorName::Qualified { .. }, 429 TypeAstConstructorName::Unqualified { .. }, 430 ) 431 | ( 432 TypeAstConstructorName::Unqualified { .. }, 433 TypeAstConstructorName::Qualified { .. }, 434 ) => false, 435 } 436 } 437} 438 439#[derive(Debug, Clone, PartialEq, Eq)] 440pub struct TypeAstFn { 441 pub location: SrcSpan, 442 pub arguments: Vec<TypeAst>, 443 pub return_: Box<TypeAst>, 444} 445 446#[derive(Debug, Clone, PartialEq, Eq)] 447pub struct TypeAstVar { 448 pub location: SrcSpan, 449 pub name: EcoString, 450} 451 452#[derive(Debug, Clone, PartialEq, Eq)] 453pub struct TypeAstTuple { 454 pub location: SrcSpan, 455 pub elements: Vec<TypeAst>, 456} 457 458#[derive(Debug, Clone, PartialEq, Eq)] 459pub struct TypeAstHole { 460 pub location: SrcSpan, 461 pub name: EcoString, 462} 463 464#[derive(Debug, Clone, PartialEq, Eq)] 465pub enum TypeAst { 466 Constructor(TypeAstConstructor), 467 Fn(TypeAstFn), 468 Var(TypeAstVar), 469 Tuple(TypeAstTuple), 470 Hole(TypeAstHole), 471} 472 473impl TypeAst { 474 pub fn location(&self) -> SrcSpan { 475 match self { 476 TypeAst::Fn(TypeAstFn { location, .. }) 477 | TypeAst::Var(TypeAstVar { location, .. }) 478 | TypeAst::Hole(TypeAstHole { location, .. }) 479 | TypeAst::Tuple(TypeAstTuple { location, .. }) 480 | TypeAst::Constructor(TypeAstConstructor { location, .. }) => *location, 481 } 482 } 483 484 pub fn is_logically_equal(&self, other: &TypeAst) -> bool { 485 match self { 486 TypeAst::Constructor(TypeAstConstructor { 487 name, 488 arguments, 489 location: _, 490 start_parentheses: _, 491 }) => match other { 492 TypeAst::Constructor(TypeAstConstructor { 493 name: other_name, 494 arguments: other_arguments, 495 location: _, 496 start_parentheses: _, 497 }) => { 498 name.is_logically_equal(other_name) 499 && arguments.len() == other_arguments.len() 500 && arguments 501 .iter() 502 .zip(other_arguments) 503 .all(|argument| argument.0.is_logically_equal(argument.1)) 504 } 505 TypeAst::Fn(_) | TypeAst::Var(_) | TypeAst::Tuple(_) | TypeAst::Hole(_) => false, 506 }, 507 TypeAst::Fn(TypeAstFn { 508 arguments, 509 return_, 510 location: _, 511 }) => match other { 512 TypeAst::Fn(TypeAstFn { 513 arguments: o_arguments, 514 return_: o_return_, 515 location: _, 516 }) => { 517 arguments.len() == o_arguments.len() 518 && arguments 519 .iter() 520 .zip(o_arguments) 521 .all(|a| a.0.is_logically_equal(a.1)) 522 && return_.is_logically_equal(o_return_) 523 } 524 TypeAst::Constructor(_) 525 | TypeAst::Var(_) 526 | TypeAst::Tuple(_) 527 | TypeAst::Hole(_) => false, 528 }, 529 TypeAst::Var(TypeAstVar { name, location: _ }) => match other { 530 TypeAst::Var(TypeAstVar { 531 name: o_name, 532 location: _, 533 }) => name == o_name, 534 TypeAst::Constructor(_) | TypeAst::Fn(_) | TypeAst::Tuple(_) | TypeAst::Hole(_) => { 535 false 536 } 537 }, 538 TypeAst::Tuple(TypeAstTuple { 539 elements, 540 location: _, 541 }) => match other { 542 TypeAst::Tuple(TypeAstTuple { 543 elements: other_elements, 544 location: _, 545 }) => { 546 elements.len() == other_elements.len() 547 && elements 548 .iter() 549 .zip(other_elements) 550 .all(|a| a.0.is_logically_equal(a.1)) 551 } 552 TypeAst::Constructor(_) | TypeAst::Fn(_) | TypeAst::Var(_) | TypeAst::Hole(_) => { 553 false 554 } 555 }, 556 TypeAst::Hole(TypeAstHole { name, location: _ }) => match other { 557 TypeAst::Hole(TypeAstHole { 558 name: o_name, 559 location: _, 560 }) => name == o_name, 561 TypeAst::Constructor(_) | TypeAst::Fn(_) | TypeAst::Var(_) | TypeAst::Tuple(_) => { 562 false 563 } 564 }, 565 } 566 } 567 568 pub fn find_node(&self, byte_index: u32, type_: Arc<Type>) -> Option<Located<'_>> { 569 if !self.location().contains(byte_index) { 570 return None; 571 } 572 573 match self { 574 TypeAst::Fn(TypeAstFn { 575 arguments, return_, .. 576 }) => type_ 577 .fn_types() 578 .and_then(|(arg_types, ret_type)| { 579 if let Some(arg) = arguments 580 .iter() 581 .zip(arg_types) 582 .find_map(|(arg, arg_type)| arg.find_node(byte_index, arg_type.clone())) 583 { 584 return Some(arg); 585 } 586 if let Some(ret) = return_.find_node(byte_index, ret_type) { 587 return Some(ret); 588 } 589 590 None 591 }) 592 .or(Some(Located::Annotation { ast: self, type_ })), 593 TypeAst::Constructor(TypeAstConstructor { 594 arguments, name, .. 595 }) => { 596 // 597 type_ 598 .named_type_information() 599 .and_then(|(module_name, _, arg_types)| { 600 if let Some(arg) = arguments 601 .iter() 602 .zip(arg_types) 603 .find_map(|(arg, arg_type)| arg.find_node(byte_index, arg_type.clone())) 604 { 605 return Some(arg); 606 } 607 608 if let TypeAstConstructorName::Qualified { 609 module_location, 610 module: module_alias, 611 .. 612 } = name 613 && module_location.contains(byte_index) 614 { 615 return Some(Located::ModuleName { 616 location: *module_location, 617 module_name, 618 module_alias: module_alias.clone(), 619 layer: Layer::Type, 620 }); 621 } 622 623 None 624 }) 625 .or(Some(Located::Annotation { ast: self, type_ })) 626 } 627 TypeAst::Tuple(TypeAstTuple { elements, .. }) => type_ 628 .tuple_types() 629 .and_then(|elem_types| { 630 if let Some(e) = elements 631 .iter() 632 .zip(elem_types) 633 .find_map(|(e, e_type)| e.find_node(byte_index, e_type.clone())) 634 { 635 return Some(e); 636 } 637 638 None 639 }) 640 .or(Some(Located::Annotation { ast: self, type_ })), 641 TypeAst::Var(_) | TypeAst::Hole(_) => Some(Located::Annotation { ast: self, type_ }), 642 } 643 } 644 645 /// Generates an annotation corresponding to the type. 646 pub fn print(&self, buffer: &mut EcoString) { 647 match &self { 648 TypeAst::Var(var) => buffer.push_str(&var.name), 649 TypeAst::Hole(hole) => buffer.push_str(&hole.name), 650 TypeAst::Tuple(tuple) => { 651 buffer.push_str("#("); 652 for (i, element) in tuple.elements.iter().enumerate() { 653 element.print(buffer); 654 if i < tuple.elements.len() - 1 { 655 buffer.push_str(", "); 656 } 657 } 658 buffer.push(')') 659 } 660 TypeAst::Fn(func) => { 661 buffer.push_str("fn("); 662 for (i, argument) in func.arguments.iter().enumerate() { 663 argument.print(buffer); 664 if i < func.arguments.len() - 1 { 665 buffer.push_str(", "); 666 } 667 } 668 buffer.push(')'); 669 buffer.push_str(" -> "); 670 func.return_.print(buffer); 671 } 672 TypeAst::Constructor(constructor) => { 673 match &constructor.name { 674 TypeAstConstructorName::Unqualified { name, .. } => buffer.push_str(name), 675 TypeAstConstructorName::Qualified { module, name, .. } => { 676 buffer.push_str(module); 677 buffer.push('.'); 678 if let Some((name, _name_location)) = name { 679 buffer.push_str(name); 680 } 681 } 682 }; 683 684 if !constructor.arguments.is_empty() { 685 buffer.push('('); 686 for (i, argument) in constructor.arguments.iter().enumerate() { 687 argument.print(buffer); 688 if i < constructor.arguments.len() - 1 { 689 buffer.push_str(", "); 690 } 691 } 692 buffer.push(')'); 693 } 694 } 695 } 696 } 697} 698 699#[test] 700fn type_ast_print_fn() { 701 let mut buffer = EcoString::new(); 702 let ast = TypeAst::Fn(TypeAstFn { 703 location: SrcSpan { start: 1, end: 1 }, 704 arguments: vec![ 705 TypeAst::Var(TypeAstVar { 706 location: SrcSpan { start: 1, end: 1 }, 707 name: "String".into(), 708 }), 709 TypeAst::Var(TypeAstVar { 710 location: SrcSpan { start: 1, end: 1 }, 711 name: "Bool".into(), 712 }), 713 ], 714 return_: Box::new(TypeAst::Var(TypeAstVar { 715 location: SrcSpan { start: 1, end: 1 }, 716 name: "Int".into(), 717 })), 718 }); 719 ast.print(&mut buffer); 720 assert_eq!(&buffer, "fn(String, Bool) -> Int") 721} 722 723#[test] 724fn type_ast_print_constructor() { 725 let mut buffer = EcoString::new(); 726 let ast = TypeAst::Constructor(TypeAstConstructor { 727 name: TypeAstConstructorName::Qualified { 728 module: "some_module".into(), 729 dot_location: 1, 730 module_location: SrcSpan { start: 1, end: 1 }, 731 name: Some(("SomeType".into(), SrcSpan { start: 1, end: 1 })), 732 }, 733 location: SrcSpan { start: 1, end: 1 }, 734 arguments: vec![ 735 TypeAst::Var(TypeAstVar { 736 location: SrcSpan { start: 1, end: 1 }, 737 name: "String".into(), 738 }), 739 TypeAst::Var(TypeAstVar { 740 location: SrcSpan { start: 1, end: 1 }, 741 name: "Bool".into(), 742 }), 743 ], 744 start_parentheses: Some(1), 745 }); 746 ast.print(&mut buffer); 747 assert_eq!(&buffer, "some_module.SomeType(String, Bool)") 748} 749 750#[test] 751fn type_ast_print_tuple() { 752 let mut buffer = EcoString::new(); 753 let ast = TypeAst::Tuple(TypeAstTuple { 754 location: SrcSpan { start: 1, end: 1 }, 755 elements: vec![ 756 TypeAst::Constructor(TypeAstConstructor { 757 name: TypeAstConstructorName::Qualified { 758 module: "some_module".into(), 759 module_location: SrcSpan { start: 1, end: 1 }, 760 dot_location: 1, 761 name: Some(("SomeType".into(), SrcSpan { start: 1, end: 1 })), 762 }, 763 location: SrcSpan { start: 1, end: 1 }, 764 arguments: vec![ 765 TypeAst::Var(TypeAstVar { 766 location: SrcSpan { start: 1, end: 1 }, 767 name: "String".into(), 768 }), 769 TypeAst::Var(TypeAstVar { 770 location: SrcSpan { start: 1, end: 1 }, 771 name: "Bool".into(), 772 }), 773 ], 774 start_parentheses: Some(1), 775 }), 776 TypeAst::Fn(TypeAstFn { 777 location: SrcSpan { start: 1, end: 1 }, 778 arguments: vec![ 779 TypeAst::Var(TypeAstVar { 780 location: SrcSpan { start: 1, end: 1 }, 781 name: "String".into(), 782 }), 783 TypeAst::Var(TypeAstVar { 784 location: SrcSpan { start: 1, end: 1 }, 785 name: "Bool".into(), 786 }), 787 ], 788 return_: Box::new(TypeAst::Var(TypeAstVar { 789 location: SrcSpan { start: 1, end: 1 }, 790 name: "Int".into(), 791 })), 792 }), 793 ], 794 }); 795 ast.print(&mut buffer); 796 assert_eq!( 797 &buffer, 798 "#(some_module.SomeType(String, Bool), fn(String, Bool) -> Int)" 799 ) 800} 801 802#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 803pub enum Publicity { 804 Public, 805 Private, 806 Internal { attribute_location: Option<SrcSpan> }, 807} 808 809impl Publicity { 810 pub fn is_private(&self) -> bool { 811 match self { 812 Self::Private => true, 813 Self::Public | Self::Internal { .. } => false, 814 } 815 } 816 817 pub fn is_internal(&self) -> bool { 818 match self { 819 Self::Internal { .. } => true, 820 Self::Public | Self::Private => false, 821 } 822 } 823 824 pub fn is_public(&self) -> bool { 825 match self { 826 Self::Public => true, 827 Self::Internal { .. } | Self::Private => false, 828 } 829 } 830 831 pub fn is_importable(&self) -> bool { 832 match self { 833 Self::Internal { .. } | Self::Public => true, 834 Self::Private => false, 835 } 836 } 837} 838 839#[derive(Debug, Clone, PartialEq, Eq)] 840/// A function definition 841/// 842/// Note that an anonymous function will have `None` as the name field, while a 843/// named function will have `Some`. 844/// 845/// # Example(s) 846/// 847/// ```gleam 848/// // Public function 849/// pub fn wobble() -> String { ... } 850/// // Private function 851/// fn wibble(x: Int) -> Int { ... } 852/// // Anonymous function 853/// fn(x: Int) { ... } 854/// ``` 855pub struct Function<T, Expr> { 856 pub location: SrcSpan, 857 pub body_start: Option<u32>, 858 pub end_position: u32, 859 pub name: Option<SpannedString>, 860 pub arguments: Vec<Arg<T>>, 861 pub body: Vec<Statement<T, Expr>>, 862 pub publicity: Publicity, 863 pub deprecation: Deprecation, 864 pub return_annotation: Option<TypeAst>, 865 pub return_type: T, 866 pub documentation: Option<(u32, EcoString)>, 867 pub external_erlang: Option<(EcoString, EcoString, SrcSpan)>, 868 pub external_javascript: Option<(EcoString, EcoString, SrcSpan)>, 869 pub implementations: Implementations, 870 pub purity: Purity, 871} 872 873pub type TypedFunction = Function<Arc<Type>, TypedExpr>; 874pub type UntypedFunction = Function<(), UntypedExpr>; 875 876impl<T, E> Function<T, E> { 877 pub fn full_location(&self) -> SrcSpan { 878 SrcSpan::new(self.location.start, self.end_position) 879 } 880} 881 882impl TypedFunction { 883 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 884 // Search for the corresponding node inside the function 885 // only if the index falls within the function's full location. 886 if !self.full_location().contains(byte_index) { 887 return None; 888 } 889 890 if let Some(found) = self 891 .body 892 .iter() 893 .find_map(|statement| statement.find_node(byte_index)) 894 { 895 return Some(found); 896 } 897 898 if let Some(found_arg) = self 899 .arguments 900 .iter() 901 .find_map(|arg| arg.find_node(byte_index)) 902 { 903 return Some(found_arg); 904 }; 905 906 if let Some(found_statement) = self 907 .body 908 .iter() 909 .find(|statement| statement.location().contains(byte_index)) 910 { 911 return Some(Located::Statement(found_statement)); 912 }; 913 914 // Check if location is within the return annotation. 915 if let Some(located) = self 916 .return_annotation 917 .iter() 918 .find_map(|annotation| annotation.find_node(byte_index, self.return_type.clone())) 919 { 920 return Some(located); 921 }; 922 923 // Note that the fn `.location` covers the function head, not 924 // the entire statement. 925 if self.location.contains(byte_index) { 926 Some(Located::ModuleFunction(self)) 927 } else if self.full_location().contains(byte_index) { 928 Some(Located::FunctionBody(self)) 929 } else { 930 None 931 } 932 } 933 934 pub fn find_statement(&self, byte_index: u32) -> Option<&TypedStatement> { 935 if !self.full_location().contains(byte_index) { 936 return None; 937 } 938 939 self.body 940 .iter() 941 .find_map(|statement| statement.find_statement(byte_index)) 942 } 943 944 pub fn main_function(&self) -> Option<&TypedFunction> { 945 if let Some((_, name)) = &self.name 946 && name == "main" 947 { 948 Some(self) 949 } else { 950 None 951 } 952 } 953} 954 955pub type UntypedImport = Import<()>; 956pub type TypedImport = Import<EcoString>; 957 958#[derive(Debug, Clone, PartialEq, Eq)] 959/// Import another Gleam module so the current module can use the types and 960/// values it defines. 961/// 962/// # Example(s) 963/// 964/// ```gleam 965/// import unix/cat 966/// // Import with alias 967/// import animal/cat as kitty 968/// ``` 969pub struct Import<PackageName> { 970 pub documentation: Option<EcoString>, 971 pub location: SrcSpan, 972 pub module_location: SrcSpan, 973 pub module: EcoString, 974 pub as_name: Option<(AssignName, SrcSpan)>, 975 pub unqualified_values: Vec<UnqualifiedImport>, 976 pub unqualified_types: Vec<UnqualifiedImport>, 977 pub package: PackageName, 978} 979 980impl<T> Import<T> { 981 pub fn used_name(&self) -> Option<EcoString> { 982 match self.as_name.as_ref() { 983 Some((AssignName::Variable(name), _)) => Some(name.clone()), 984 Some((AssignName::Discard(_), _)) => None, 985 None => self.module.split('/').next_back().map(EcoString::from), 986 } 987 } 988 989 pub(crate) fn alias_location(&self) -> Option<SrcSpan> { 990 self.as_name.as_ref().map(|(_, location)| *location) 991 } 992} 993 994impl TypedImport { 995 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 996 if !self.location.contains(byte_index) { 997 return None; 998 } 999 1000 if let Some(unqualified) = self 1001 .unqualified_values 1002 .iter() 1003 .find(|unqualified_value| unqualified_value.location.contains(byte_index)) 1004 { 1005 return Some(Located::UnqualifiedImport( 1006 crate::build::UnqualifiedImport { 1007 name: &unqualified.name, 1008 module: &self.module, 1009 is_type: false, 1010 location: &unqualified.location, 1011 }, 1012 )); 1013 } 1014 1015 if let Some(unqualified) = self 1016 .unqualified_types 1017 .iter() 1018 .find(|unqualified_value| unqualified_value.location.contains(byte_index)) 1019 { 1020 return Some(Located::UnqualifiedImport( 1021 crate::build::UnqualifiedImport { 1022 name: &unqualified.name, 1023 module: &self.module, 1024 is_type: true, 1025 location: &unqualified.location, 1026 }, 1027 )); 1028 } 1029 1030 Some(Located::ModuleImport(self)) 1031 } 1032} 1033 1034pub type UntypedModuleConstant = ModuleConstant<(), ()>; 1035pub type TypedModuleConstant = ModuleConstant<Arc<Type>, EcoString>; 1036 1037#[derive(Debug, Clone, PartialEq, Eq)] 1038/// A certain fixed value that can be used in multiple places 1039/// 1040/// # Example(s) 1041/// 1042/// ```gleam 1043/// pub const start_year = 2101 1044/// pub const end_year = 2111 1045/// ``` 1046pub struct ModuleConstant<T, ConstantRecordTag> { 1047 pub documentation: Option<(u32, EcoString)>, 1048 /// The location of the constant, starting at the "(pub) const" keywords and 1049 /// ending after the ": Type" annotation, or (without an annotation) after its name. 1050 pub location: SrcSpan, 1051 pub publicity: Publicity, 1052 pub name: EcoString, 1053 pub name_location: SrcSpan, 1054 pub annotation: Option<TypeAst>, 1055 pub value: Box<Constant<T, ConstantRecordTag>>, 1056 pub type_: T, 1057 pub deprecation: Deprecation, 1058 pub implementations: Implementations, 1059} 1060 1061impl TypedModuleConstant { 1062 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 1063 // Check if location is within the annotation. 1064 if let Some(annotation) = &self.annotation 1065 && let Some(located) = annotation.find_node(byte_index, self.type_.clone()) 1066 { 1067 return Some(located); 1068 } 1069 1070 if let Some(located) = self.value.find_node(byte_index) { 1071 return Some(located); 1072 } 1073 1074 if self.location.contains(byte_index) { 1075 Some(Located::ModuleConstant(self)) 1076 } else { 1077 None 1078 } 1079 } 1080} 1081 1082pub type UntypedCustomType = CustomType<()>; 1083pub type TypedCustomType = CustomType<Arc<Type>>; 1084 1085#[derive(Debug, Clone, PartialEq, Eq)] 1086/// A newly defined type with one or more constructors. 1087/// Each variant of the custom type can contain different types, so the type is 1088/// the product of the types contained by each variant. 1089/// 1090/// This might be called an algebraic data type (ADT) or tagged union in other 1091/// languages and type systems. 1092/// 1093/// 1094/// # Example(s) 1095/// 1096/// ```gleam 1097/// pub type Cat { 1098/// Cat(name: String, cuteness: Int) 1099/// } 1100/// ``` 1101pub struct CustomType<T> { 1102 pub location: SrcSpan, 1103 pub end_position: u32, 1104 pub name: EcoString, 1105 pub name_location: SrcSpan, 1106 pub publicity: Publicity, 1107 pub constructors: Vec<RecordConstructor<T>>, 1108 pub documentation: Option<(u32, EcoString)>, 1109 pub deprecation: Deprecation, 1110 pub opaque: bool, 1111 /// The names of the type parameters. 1112 pub parameters: Vec<SpannedString>, 1113 /// Once type checked this field will contain the type information for the 1114 /// type parameters. 1115 pub typed_parameters: Vec<T>, 1116 pub external_erlang: Option<(EcoString, EcoString, SrcSpan)>, 1117 pub external_javascript: Option<(EcoString, EcoString, SrcSpan)>, 1118} 1119 1120impl<T> CustomType<T> { 1121 /// The `location` field of a `CustomType` is only the location of `pub type 1122 /// TheName`. This method returns a `SrcSpan` that includes the entire type 1123 /// definition. 1124 pub fn full_location(&self) -> SrcSpan { 1125 SrcSpan::new(self.location.start, self.end_position) 1126 } 1127} 1128 1129impl TypedCustomType { 1130 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 1131 // Check if location is within the type of one of the arguments of a constructor. 1132 if let Some(constructor) = self 1133 .constructors 1134 .iter() 1135 .find(|constructor| constructor.location.contains(byte_index)) 1136 { 1137 if let Some(annotation) = constructor 1138 .arguments 1139 .iter() 1140 .find(|arg| arg.location.contains(byte_index)) 1141 .and_then(|arg| arg.ast.find_node(byte_index, arg.type_.clone())) 1142 { 1143 return Some(annotation); 1144 } 1145 1146 return Some(Located::VariantConstructorDefinition(constructor)); 1147 } 1148 1149 // Note that the custom type `.location` covers the function 1150 // head, not the entire statement. 1151 if self.full_location().contains(byte_index) { 1152 Some(Located::ModuleCustomType(self)) 1153 } else { 1154 None 1155 } 1156 } 1157} 1158 1159pub type UntypedTypeAlias = TypeAlias<()>; 1160pub type TypedTypeAlias = TypeAlias<Arc<Type>>; 1161 1162#[derive(Debug, Clone, PartialEq, Eq)] 1163/// A new name for an existing type 1164/// 1165/// # Example(s) 1166/// 1167/// ```gleam 1168/// pub type Headers = 1169/// List(#(String, String)) 1170/// ``` 1171pub struct TypeAlias<T> { 1172 pub location: SrcSpan, 1173 pub alias: EcoString, 1174 pub name_location: SrcSpan, 1175 pub parameters: Vec<SpannedString>, 1176 pub type_ast: TypeAst, 1177 pub type_: T, 1178 pub publicity: Publicity, 1179 pub documentation: Option<(u32, EcoString)>, 1180 pub deprecation: Deprecation, 1181} 1182 1183impl TypedTypeAlias { 1184 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 1185 // Check if location is within the type being aliased. 1186 if let Some(located) = self.type_ast.find_node(byte_index, self.type_.clone()) { 1187 return Some(located); 1188 } 1189 1190 if self.location.contains(byte_index) { 1191 Some(Located::ModuleTypeAlias(self)) 1192 } else { 1193 None 1194 } 1195 } 1196} 1197 1198pub type UntypedDefinition = Definition<(), UntypedExpr, (), ()>; 1199 1200#[derive(Debug, Clone, PartialEq, Eq)] 1201pub enum Definition<T, Expr, ConstantRecordTag, PackageName> { 1202 Function(Function<T, Expr>), 1203 TypeAlias(TypeAlias<T>), 1204 CustomType(CustomType<T>), 1205 Import(Import<PackageName>), 1206 ModuleConstant(ModuleConstant<T, ConstantRecordTag>), 1207} 1208 1209impl<A, B, C, E> Definition<A, B, C, E> { 1210 pub fn location(&self) -> SrcSpan { 1211 match self { 1212 Definition::Function(Function { location, .. }) 1213 | Definition::Import(Import { location, .. }) 1214 | Definition::TypeAlias(TypeAlias { location, .. }) 1215 | Definition::CustomType(CustomType { location, .. }) 1216 | Definition::ModuleConstant(ModuleConstant { location, .. }) => *location, 1217 } 1218 } 1219 1220 /// Returns `true` if the definition is [`Import`]. 1221 /// 1222 /// [`Import`]: Definition::Import 1223 #[must_use] 1224 pub fn is_import(&self) -> bool { 1225 matches!(self, Self::Import(..)) 1226 } 1227 1228 /// Returns `true` if the module statement is [`Function`]. 1229 /// 1230 /// [`Function`]: ModuleStatement::Function 1231 #[must_use] 1232 pub fn is_function(&self) -> bool { 1233 matches!(self, Self::Function(..)) 1234 } 1235 1236 /// Returns `true` if the module statement is [`CustomType`]. 1237 /// 1238 /// [`CustomType`]: ModuleStatement::CustomType 1239 #[must_use] 1240 pub fn is_custom_type(&self) -> bool { 1241 matches!(self, Self::CustomType(..)) 1242 } 1243 1244 pub fn get_doc(&self) -> Option<EcoString> { 1245 match self { 1246 Definition::Import(Import { .. }) => None, 1247 1248 Definition::Function(Function { 1249 documentation: doc, .. 1250 }) 1251 | Definition::TypeAlias(TypeAlias { 1252 documentation: doc, .. 1253 }) 1254 | Definition::CustomType(CustomType { 1255 documentation: doc, .. 1256 }) 1257 | Definition::ModuleConstant(ModuleConstant { 1258 documentation: doc, .. 1259 }) => doc.as_ref().map(|(_, doc)| doc.clone()), 1260 } 1261 } 1262 1263 pub fn is_internal(&self) -> bool { 1264 match self { 1265 Definition::Function(Function { publicity, .. }) 1266 | Definition::CustomType(CustomType { publicity, .. }) 1267 | Definition::ModuleConstant(ModuleConstant { publicity, .. }) 1268 | Definition::TypeAlias(TypeAlias { publicity, .. }) => publicity.is_internal(), 1269 1270 Definition::Import(_) => false, 1271 } 1272 } 1273} 1274 1275#[derive(Debug, Clone, PartialEq, Eq)] 1276pub struct UnqualifiedImport { 1277 pub location: SrcSpan, 1278 /// The location excluding the potential `as ...` clause, or the `type` keyword 1279 pub imported_name_location: SrcSpan, 1280 pub name: EcoString, 1281 pub as_name: Option<EcoString>, 1282} 1283 1284impl UnqualifiedImport { 1285 pub fn used_name(&self) -> &EcoString { 1286 self.as_name.as_ref().unwrap_or(&self.name) 1287 } 1288} 1289 1290#[derive(Debug, Clone, PartialEq, Eq, Copy, Default, serde::Serialize, serde::Deserialize)] 1291pub enum Layer { 1292 #[default] 1293 Value, 1294 Type, 1295} 1296 1297impl Layer { 1298 /// Returns `true` if the layer is [`Value`]. 1299 pub fn is_value(&self) -> bool { 1300 matches!(self, Self::Value) 1301 } 1302} 1303 1304#[derive(Debug, Clone, Copy, PartialEq, Eq)] 1305pub enum BinOp { 1306 // Boolean logic 1307 And, 1308 Or, 1309 1310 // Equality 1311 Eq, 1312 NotEq, 1313 1314 // Order comparison 1315 LtInt, 1316 LtEqInt, 1317 LtFloat, 1318 LtEqFloat, 1319 GtEqInt, 1320 GtInt, 1321 GtEqFloat, 1322 GtFloat, 1323 1324 // Maths 1325 AddInt, 1326 AddFloat, 1327 SubInt, 1328 SubFloat, 1329 MultInt, 1330 MultFloat, 1331 DivInt, 1332 DivFloat, 1333 RemainderInt, 1334 1335 // Strings 1336 Concatenate, 1337} 1338 1339#[derive(Clone, Copy, Debug, PartialEq)] 1340pub enum OperatorKind { 1341 BooleanLogic, 1342 Equality, 1343 IntComparison, 1344 FLoatComparison, 1345 IntMath, 1346 FloatMath, 1347 StringConcatenation, 1348} 1349 1350pub const PIPE_PRECEDENCE: u8 = 6; 1351 1352impl BinOp { 1353 pub fn precedence(&self) -> u8 { 1354 // Ensure that this matches the other precedence function for guards 1355 match self { 1356 Self::Or => 1, 1357 1358 Self::And => 2, 1359 1360 Self::Eq | Self::NotEq => 3, 1361 1362 Self::LtInt 1363 | Self::LtEqInt 1364 | Self::LtFloat 1365 | Self::LtEqFloat 1366 | Self::GtEqInt 1367 | Self::GtInt 1368 | Self::GtEqFloat 1369 | Self::GtFloat => 4, 1370 1371 Self::Concatenate => 5, 1372 1373 // Pipe is 6 1374 Self::AddInt | Self::AddFloat | Self::SubInt | Self::SubFloat => 7, 1375 1376 Self::MultInt 1377 | Self::MultFloat 1378 | Self::DivInt 1379 | Self::DivFloat 1380 | Self::RemainderInt => 8, 1381 } 1382 } 1383 1384 pub fn name(&self) -> &'static str { 1385 match self { 1386 Self::And => "&&", 1387 Self::Or => "||", 1388 Self::LtInt => "<", 1389 Self::LtEqInt => "<=", 1390 Self::LtFloat => "<.", 1391 Self::LtEqFloat => "<=.", 1392 Self::Eq => "==", 1393 Self::NotEq => "!=", 1394 Self::GtEqInt => ">=", 1395 Self::GtInt => ">", 1396 Self::GtEqFloat => ">=.", 1397 Self::GtFloat => ">.", 1398 Self::AddInt => "+", 1399 Self::AddFloat => "+.", 1400 Self::SubInt => "-", 1401 Self::SubFloat => "-.", 1402 Self::MultInt => "*", 1403 Self::MultFloat => "*.", 1404 Self::DivInt => "/", 1405 Self::DivFloat => "/.", 1406 Self::RemainderInt => "%", 1407 Self::Concatenate => "<>", 1408 } 1409 } 1410 1411 pub fn operator_kind(&self) -> OperatorKind { 1412 match self { 1413 Self::Concatenate => OperatorKind::StringConcatenation, 1414 Self::Eq | Self::NotEq => OperatorKind::Equality, 1415 Self::And | Self::Or => OperatorKind::BooleanLogic, 1416 Self::LtInt | Self::LtEqInt | Self::GtEqInt | Self::GtInt => { 1417 OperatorKind::IntComparison 1418 } 1419 Self::LtFloat | Self::LtEqFloat | Self::GtEqFloat | Self::GtFloat => { 1420 OperatorKind::FLoatComparison 1421 } 1422 Self::AddInt | Self::SubInt | Self::MultInt | Self::RemainderInt | Self::DivInt => { 1423 OperatorKind::IntMath 1424 } 1425 Self::AddFloat | Self::SubFloat | Self::MultFloat | Self::DivFloat => { 1426 OperatorKind::FloatMath 1427 } 1428 } 1429 } 1430 1431 pub fn can_be_grouped_with(&self, other: &BinOp) -> bool { 1432 self.operator_kind() == other.operator_kind() 1433 } 1434 1435 pub fn is_float_operator(&self) -> bool { 1436 match self { 1437 BinOp::LtFloat 1438 | BinOp::LtEqFloat 1439 | BinOp::GtEqFloat 1440 | BinOp::GtFloat 1441 | BinOp::AddFloat 1442 | BinOp::SubFloat 1443 | BinOp::MultFloat 1444 | BinOp::DivFloat => true, 1445 1446 BinOp::And 1447 | BinOp::Or 1448 | BinOp::Eq 1449 | BinOp::NotEq 1450 | BinOp::LtInt 1451 | BinOp::LtEqInt 1452 | BinOp::GtEqInt 1453 | BinOp::GtInt 1454 | BinOp::AddInt 1455 | BinOp::SubInt 1456 | BinOp::MultInt 1457 | BinOp::DivInt 1458 | BinOp::RemainderInt 1459 | BinOp::Concatenate => false, 1460 } 1461 } 1462 1463 fn is_bool_operator(&self) -> bool { 1464 match self { 1465 BinOp::And | BinOp::Or => true, 1466 BinOp::Eq 1467 | BinOp::NotEq 1468 | BinOp::LtInt 1469 | BinOp::LtEqInt 1470 | BinOp::LtFloat 1471 | BinOp::LtEqFloat 1472 | BinOp::GtEqInt 1473 | BinOp::GtInt 1474 | BinOp::GtEqFloat 1475 | BinOp::GtFloat 1476 | BinOp::AddInt 1477 | BinOp::AddFloat 1478 | BinOp::SubInt 1479 | BinOp::SubFloat 1480 | BinOp::MultInt 1481 | BinOp::MultFloat 1482 | BinOp::DivInt 1483 | BinOp::DivFloat 1484 | BinOp::RemainderInt 1485 | BinOp::Concatenate => false, 1486 } 1487 } 1488 1489 pub fn is_int_operator(&self) -> bool { 1490 match self { 1491 BinOp::LtInt 1492 | BinOp::LtEqInt 1493 | BinOp::GtEqInt 1494 | BinOp::GtInt 1495 | BinOp::AddInt 1496 | BinOp::SubInt 1497 | BinOp::MultInt 1498 | BinOp::DivInt 1499 | BinOp::RemainderInt => true, 1500 1501 BinOp::And 1502 | BinOp::Or 1503 | BinOp::Eq 1504 | BinOp::NotEq 1505 | BinOp::LtFloat 1506 | BinOp::LtEqFloat 1507 | BinOp::GtEqFloat 1508 | BinOp::GtFloat 1509 | BinOp::AddFloat 1510 | BinOp::SubFloat 1511 | BinOp::MultFloat 1512 | BinOp::DivFloat 1513 | BinOp::Concatenate => false, 1514 } 1515 } 1516 1517 pub fn float_equivalent(&self) -> Option<BinOp> { 1518 match self { 1519 BinOp::LtInt => Some(BinOp::LtFloat), 1520 BinOp::LtEqInt => Some(BinOp::LtEqFloat), 1521 BinOp::GtEqInt => Some(BinOp::GtEqFloat), 1522 BinOp::GtInt => Some(BinOp::GtFloat), 1523 BinOp::AddInt => Some(BinOp::AddFloat), 1524 BinOp::SubInt => Some(BinOp::SubFloat), 1525 BinOp::MultInt => Some(BinOp::MultFloat), 1526 BinOp::DivInt => Some(BinOp::DivFloat), 1527 BinOp::And 1528 | BinOp::Or 1529 | BinOp::Eq 1530 | BinOp::NotEq 1531 | BinOp::LtFloat 1532 | BinOp::LtEqFloat 1533 | BinOp::GtEqFloat 1534 | BinOp::GtFloat 1535 | BinOp::AddFloat 1536 | BinOp::SubFloat 1537 | BinOp::MultFloat 1538 | BinOp::DivFloat 1539 | BinOp::RemainderInt 1540 | BinOp::Concatenate => None, 1541 } 1542 } 1543 1544 pub fn int_equivalent(&self) -> Option<BinOp> { 1545 match self { 1546 BinOp::LtFloat => Some(BinOp::LtInt), 1547 BinOp::LtEqFloat => Some(BinOp::LtEqInt), 1548 BinOp::GtEqFloat => Some(BinOp::GtEqInt), 1549 BinOp::GtFloat => Some(BinOp::GtInt), 1550 BinOp::AddFloat => Some(BinOp::AddInt), 1551 BinOp::SubFloat => Some(BinOp::SubInt), 1552 BinOp::MultFloat => Some(BinOp::MultInt), 1553 BinOp::DivFloat => Some(BinOp::DivInt), 1554 BinOp::And 1555 | BinOp::Or 1556 | BinOp::Eq 1557 | BinOp::NotEq 1558 | BinOp::LtInt 1559 | BinOp::LtEqInt 1560 | BinOp::GtEqInt 1561 | BinOp::GtInt 1562 | BinOp::AddInt 1563 | BinOp::SubInt 1564 | BinOp::MultInt 1565 | BinOp::DivInt 1566 | BinOp::RemainderInt 1567 | BinOp::Concatenate => None, 1568 } 1569 } 1570} 1571 1572#[derive(Debug, PartialEq, Eq, Clone, serde::Serialize, serde::Deserialize)] 1573pub struct CallArg<A> { 1574 pub label: Option<EcoString>, 1575 pub location: SrcSpan, 1576 pub value: A, 1577 pub implicit: Option<ImplicitCallArgOrigin>, 1578} 1579 1580#[derive(Debug, PartialEq, Eq, Clone, Copy, serde::Serialize, serde::Deserialize)] 1581pub enum ImplicitCallArgOrigin { 1582 /// The implicit callback argument passed as the last argument to the 1583 /// function on the right hand side of `use`. 1584 /// 1585 Use, 1586 /// An argument added by the compiler when rewriting a pipe `left |> right`. 1587 /// 1588 Pipe, 1589 /// An argument added by the compiler to fill in all the missing fields of a 1590 /// record that are being ignored with the `..` syntax. 1591 /// 1592 PatternFieldSpread, 1593 /// An argument used to fill in the missing args when a function on the 1594 /// right hand side of `use` is being called with the wrong arity. 1595 /// 1596 IncorrectArityUse, 1597 /// An argument added by the compiler to fill in the missing args when using 1598 /// the record update synax. 1599 /// 1600 RecordUpdate, 1601} 1602 1603impl<A> CallArg<A> { 1604 #[must_use] 1605 pub fn is_implicit(&self) -> bool { 1606 self.implicit.is_some() 1607 } 1608 1609 #[must_use] 1610 pub fn is_use_implicit_callback(&self) -> bool { 1611 match self.implicit { 1612 Some(ImplicitCallArgOrigin::Use | ImplicitCallArgOrigin::IncorrectArityUse) => true, 1613 Some(_) | None => false, 1614 } 1615 } 1616} 1617 1618impl CallArg<TypedExpr> { 1619 pub fn find_node<'a>( 1620 &'a self, 1621 byte_index: u32, 1622 called_function: &'a TypedExpr, 1623 function_arguments: &'a [TypedCallArg], 1624 ) -> Option<Located<'a>> { 1625 match (self.implicit, &self.value) { 1626 // If a call argument is the implicit use callback then we don't 1627 // want to look at its arguments and body but we don't want to 1628 // return the whole anonymous function if anything else doesn't 1629 // match. 1630 // 1631 // In addition, if the callback is invalid because it couldn't be 1632 // typed, we don't want to return it as it would make it hard for 1633 // the LSP to give any suggestions on the use function being typed. 1634 // 1635 (Some(ImplicitCallArgOrigin::Use), TypedExpr::Invalid { .. }) => None, 1636 // So the code below is exactly the same as 1637 // `TypedExpr::Fn{}.find_node()` except we do not return self as a 1638 // fallback. 1639 // 1640 ( 1641 Some(ImplicitCallArgOrigin::Use), 1642 TypedExpr::Fn { 1643 arguments, body, .. 1644 }, 1645 ) => arguments 1646 .iter() 1647 .find_map(|argument| argument.find_node(byte_index)) 1648 .or_else(|| body.iter().find_map(|s| s.find_node(byte_index))), 1649 // In all other cases we're happy with the default behaviour. 1650 // 1651 _ => match self.value.find_node(byte_index) { 1652 Some(Located::Expression { expression, .. }) 1653 // This is only possibly a label if we are at the end of the expression 1654 // (so not in the middle like `[abc|]`) and if this argument doesn't 1655 // already have a label. 1656 if byte_index == self.value.location().end && self.label.is_none() => 1657 { 1658 Some(Located::Expression { 1659 expression, 1660 position: ExpressionPosition::ArgumentOrLabel { 1661 called_function, 1662 function_arguments, 1663 }, 1664 }) 1665 } 1666 Some(located) => Some(located), 1667 None => { 1668 if self.location.contains(byte_index) && self.label.is_some() { 1669 Some(Located::Label(self.location, self.value.type_())) 1670 } else { 1671 None 1672 } 1673 } 1674 }, 1675 } 1676 } 1677 1678 pub fn find_statement(&self, byte_index: u32) -> Option<&TypedStatement> { 1679 match (self.implicit, &self.value) { 1680 (Some(ImplicitCallArgOrigin::Use), TypedExpr::Invalid { .. }) => None, 1681 (Some(ImplicitCallArgOrigin::Use), TypedExpr::Fn { body, .. }) => { 1682 body.iter().find_map(|s| s.find_statement(byte_index)) 1683 } 1684 1685 _ => self.value.find_statement(byte_index), 1686 } 1687 } 1688 1689 pub fn is_capture_hole(&self) -> bool { 1690 match &self.value { 1691 TypedExpr::Var { name, .. } => name == CAPTURE_VARIABLE, 1692 TypedExpr::Int { .. } 1693 | TypedExpr::Float { .. } 1694 | TypedExpr::String { .. } 1695 | TypedExpr::Block { .. } 1696 | TypedExpr::Pipeline { .. } 1697 | TypedExpr::Fn { .. } 1698 | TypedExpr::List { .. } 1699 | TypedExpr::Call { .. } 1700 | TypedExpr::BinOp { .. } 1701 | TypedExpr::Case { .. } 1702 | TypedExpr::RecordAccess { .. } 1703 | TypedExpr::PositionalAccess { .. } 1704 | TypedExpr::ModuleSelect { .. } 1705 | TypedExpr::Tuple { .. } 1706 | TypedExpr::TupleIndex { .. } 1707 | TypedExpr::Todo { .. } 1708 | TypedExpr::Panic { .. } 1709 | TypedExpr::Echo { .. } 1710 | TypedExpr::BitArray { .. } 1711 | TypedExpr::RecordUpdate { .. } 1712 | TypedExpr::NegateBool { .. } 1713 | TypedExpr::NegateInt { .. } 1714 | TypedExpr::Invalid { .. } => false, 1715 } 1716 } 1717} 1718 1719impl CallArg<TypedPattern> { 1720 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 1721 match self.value.find_node(byte_index) { 1722 Some(located) => Some(located), 1723 _ => { 1724 if self.location.contains(byte_index) && self.label.is_some() { 1725 Some(Located::Label(self.location, self.value.type_())) 1726 } else { 1727 None 1728 } 1729 } 1730 } 1731 } 1732} 1733 1734impl CallArg<TypedConstant> { 1735 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 1736 match self.value.find_node(byte_index) { 1737 Some(located) => Some(located), 1738 _ => { 1739 if self.location.contains(byte_index) && self.label.is_some() { 1740 Some(Located::Label(self.location, self.value.type_())) 1741 } else { 1742 None 1743 } 1744 } 1745 } 1746 } 1747} 1748 1749impl CallArg<UntypedExpr> { 1750 pub fn is_capture_hole(&self) -> bool { 1751 match &self.value { 1752 UntypedExpr::Var { name, .. } => name == CAPTURE_VARIABLE, 1753 UntypedExpr::Int { .. } 1754 | UntypedExpr::Float { .. } 1755 | UntypedExpr::String { .. } 1756 | UntypedExpr::Block { .. } 1757 | UntypedExpr::Fn { .. } 1758 | UntypedExpr::List { .. } 1759 | UntypedExpr::Call { .. } 1760 | UntypedExpr::BinOp { .. } 1761 | UntypedExpr::PipeLine { .. } 1762 | UntypedExpr::Case { .. } 1763 | UntypedExpr::FieldAccess { .. } 1764 | UntypedExpr::Tuple { .. } 1765 | UntypedExpr::TupleIndex { .. } 1766 | UntypedExpr::Todo { .. } 1767 | UntypedExpr::Panic { .. } 1768 | UntypedExpr::Echo { .. } 1769 | UntypedExpr::BitArray { .. } 1770 | UntypedExpr::RecordUpdate { .. } 1771 | UntypedExpr::NegateBool { .. } 1772 | UntypedExpr::NegateInt { .. } => false, 1773 } 1774 } 1775} 1776 1777impl<T> CallArg<T> 1778where 1779 T: HasLocation, 1780{ 1781 #[must_use] 1782 pub fn uses_label_shorthand(&self) -> bool { 1783 self.label_shorthand_name().is_some() 1784 } 1785 1786 /// If the call arg is defined using a label shorthand, this will return the 1787 /// label name. 1788 /// 1789 pub fn label_shorthand_name(&self) -> Option<&EcoString> { 1790 if !self.is_implicit() && self.location == self.value.location() { 1791 self.label.as_ref() 1792 } else { 1793 None 1794 } 1795 } 1796} 1797 1798impl<T> HasLocation for CallArg<T> { 1799 fn location(&self) -> SrcSpan { 1800 self.location 1801 } 1802} 1803 1804#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 1805pub struct RecordBeingUpdated<A> { 1806 pub base: Box<A>, 1807 pub location: SrcSpan, 1808} 1809 1810#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 1811pub struct RecordUpdateArg<A> { 1812 pub label: EcoString, 1813 pub location: SrcSpan, 1814 pub value: A, 1815} 1816 1817pub type UntypedRecordUpdateArg = RecordUpdateArg<UntypedExpr>; 1818 1819impl<A> HasLocation for RecordUpdateArg<A> { 1820 fn location(&self) -> SrcSpan { 1821 self.location 1822 } 1823} 1824 1825impl<A: HasLocation> RecordUpdateArg<A> { 1826 #[must_use] 1827 pub fn uses_label_shorthand(&self) -> bool { 1828 self.value.location() == self.location 1829 } 1830} 1831 1832pub type MultiPattern<Type> = Vec<Pattern<Type>>; 1833 1834pub type UntypedMultiPattern = MultiPattern<()>; 1835pub type TypedMultiPattern = MultiPattern<Arc<Type>>; 1836 1837pub type TypedClause = Clause<TypedExpr, Arc<Type>, EcoString>; 1838 1839pub type UntypedClause = Clause<UntypedExpr, (), ()>; 1840 1841#[derive(Debug, Clone, PartialEq, Eq)] 1842pub struct Clause<Expr, Type, RecordTag> { 1843 pub location: SrcSpan, 1844 pub pattern: MultiPattern<Type>, 1845 pub alternative_patterns: Vec<MultiPattern<Type>>, 1846 pub guard: Option<ClauseGuard<Type, RecordTag>>, 1847 pub then: Expr, 1848} 1849 1850impl<A, B, C> Clause<A, B, C> { 1851 pub fn pattern_count(&self) -> usize { 1852 1 + self.alternative_patterns.len() 1853 } 1854} 1855 1856impl TypedClause { 1857 pub fn location(&self) -> SrcSpan { 1858 SrcSpan { 1859 start: self 1860 .pattern 1861 .first() 1862 .map(|p| p.location().start) 1863 .unwrap_or_default(), 1864 end: self.then.location().end, 1865 } 1866 } 1867 1868 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 1869 self.pattern 1870 .iter() 1871 .find_map(|p| p.find_node(byte_index)) 1872 .or_else(|| { 1873 self.alternative_patterns 1874 .iter() 1875 .flat_map(|p| p.iter()) 1876 .find_map(|p| p.find_node(byte_index)) 1877 }) 1878 .or_else(|| { 1879 self.guard 1880 .as_ref() 1881 .and_then(|guard| guard.find_node(byte_index)) 1882 }) 1883 .or_else(|| self.then.find_node(byte_index)) 1884 } 1885 1886 pub fn pattern_location(&self) -> SrcSpan { 1887 let start = self.pattern.first().map(|pattern| pattern.location().start); 1888 1889 let end = if let Some(last_pattern) = self 1890 .alternative_patterns 1891 .last() 1892 .and_then(|patterns| patterns.last()) 1893 { 1894 Some(last_pattern.location().end) 1895 } else { 1896 self.pattern.last().map(|pattern| pattern.location().end) 1897 }; 1898 1899 SrcSpan::new(start.unwrap_or_default(), end.unwrap_or_default()) 1900 } 1901 1902 /// If the branch is rebuilding exactly one of the matched subjects and 1903 /// returning it, this will return the index of that subject. 1904 /// 1905 /// For example: 1906 /// - `n -> n`, `1 -> 1`, `Ok(1) -> Ok(1)` all return `Some(0)` 1907 /// - `"a", n -> n`, `n, m if n == m -> a` all return `Some(1)` 1908 /// - `_ -> 1`, `Ok(1), _ -> Ok(2)` all return `None` 1909 /// ``` 1910 /// 1911 pub fn returned_subject(&self) -> Option<usize> { 1912 // The pattern must not have any alternative patterns. 1913 if !self.alternative_patterns.is_empty() { 1914 return None; 1915 } 1916 1917 self.pattern 1918 .iter() 1919 .find_position(|pattern| pattern_and_expression_are_the_same(pattern, &self.then)) 1920 .map(|(position, _)| position) 1921 } 1922 1923 /// This returns the names of all the variables bound in this case clause. 1924 /// For example if we had `#(a, b) | c` this will return "a", "b", and "c". 1925 pub fn bound_variables(&self) -> impl Iterator<Item = BoundVariable> { 1926 std::iter::once(&self.pattern) 1927 .chain(&self.alternative_patterns) 1928 .flatten() 1929 .flat_map(|pattern| pattern.bound_variables()) 1930 } 1931 1932 fn syntactically_eq(&self, other: &Self) -> bool { 1933 let patterns_are_equal = pairwise_all(&self.pattern, &other.pattern, |(one, other)| { 1934 one.syntactically_eq(other) 1935 }); 1936 1937 let alternatives_are_equal = pairwise_all( 1938 &self.alternative_patterns, 1939 &other.alternative_patterns, 1940 |(patterns_one, patterns_other)| { 1941 pairwise_all(patterns_one, patterns_other, |(one, other)| -> bool { 1942 one.syntactically_eq(other) 1943 }) 1944 }, 1945 ); 1946 1947 let guards_are_equal = match (&self.guard, &other.guard) { 1948 (None, None) => true, 1949 (None, Some(_)) | (Some(_), None) => false, 1950 (Some(one), Some(other)) => one.syntactically_eq(other), 1951 }; 1952 1953 patterns_are_equal 1954 && alternatives_are_equal 1955 && guards_are_equal 1956 && self.then.syntactically_eq(&other.then) 1957 } 1958} 1959 1960/// Returns true if a pattern and an expression are the same: that is the expression 1961/// would be building the exact matched value back. 1962/// For example, if I had a branch like this: 1963/// 1964/// ```gleam 1965/// [a, b, c] -> [a, b, c] 1966/// ``` 1967/// 1968/// The pattern and the expression would indeed be the same. However, if I had 1969/// something like this: 1970/// 1971/// ```gleam 1972/// [first, ..rest] -> [first] 1973/// ``` 1974/// 1975/// They wouldn't be the same! I'm not building back exactly the value the 1976/// pattern can match on. 1977/// 1978fn pattern_and_expression_are_the_same(pattern: &TypedPattern, expression: &TypedExpr) -> bool { 1979 match (pattern, expression) { 1980 // A pattern could be the same as a block if the block is wrapping just 1981 // a single expression that is the same as the pattern itself! 1982 (pattern, TypedExpr::Block { statements, .. }) if statements.len() == 1 => { 1983 match statements.first() { 1984 Statement::Assignment(_) | Statement::Use(_) | Statement::Assert(_) => false, 1985 Statement::Expression(expression) => { 1986 pattern_and_expression_are_the_same(pattern, expression) 1987 } 1988 } 1989 } 1990 // If the block has many statements then it can never be the same as a 1991 // pattern. 1992 (_, TypedExpr::Block { .. }) => false, 1993 1994 // A pattern and an expression are the same if they're a simple variable 1995 // with exactly the same name: `x -> x`, `a -> a` 1996 ( 1997 TypedPattern::Variable { 1998 name: pattern_var, .. 1999 }, 2000 TypedExpr::Var { name: body_var, .. }, 2001 ) => pattern_var == body_var, 2002 (TypedPattern::Variable { .. }, _) => false, 2003 2004 // Floats, Ints, and Strings are the same if they are exactly the same 2005 // literal. 2006 // `1 -> 1` 2007 // `1.1 -> 1.1` 2008 // `"wibble" -> "wibble"` 2009 ( 2010 TypedPattern::Float { 2011 float_value: pattern_value, 2012 .. 2013 }, 2014 TypedExpr::Float { float_value, .. }, 2015 ) => pattern_value == float_value, 2016 (TypedPattern::Float { .. }, _) => false, 2017 2018 ( 2019 TypedPattern::Int { 2020 int_value: pattern_value, 2021 .. 2022 }, 2023 TypedExpr::Int { int_value, .. }, 2024 ) => pattern_value == int_value, 2025 (TypedPattern::Int { .. }, _) => false, 2026 2027 ( 2028 TypedPattern::String { 2029 value: pattern_value, 2030 .. 2031 }, 2032 TypedExpr::String { value, .. }, 2033 ) => pattern_value == value, 2034 (TypedPattern::String { .. }, _) => false, 2035 2036 // A string prefix is equivalent to building the string back: 2037 // `"wibble" <> wobble -> "wibble" <> wobble` 2038 // `"wibble" as a <> wobble -> a <> wobble` 2039 ( 2040 TypedPattern::StringPrefix { 2041 left_side_assignment, 2042 left_side_string, 2043 right_side_assignment, 2044 .. 2045 }, 2046 TypedExpr::BinOp { 2047 name: BinOp::Concatenate, 2048 left, 2049 right, 2050 .. 2051 }, 2052 ) => { 2053 let left_side_matches = match (left_side_assignment, left_side_string, left.as_ref()) { 2054 (_, left_side_string, TypedExpr::String { value, .. }) => value == left_side_string, 2055 (Some((left_side_name, _)), _, TypedExpr::Var { name, .. }) => { 2056 left_side_name == name 2057 } 2058 (_, _, _) => false, 2059 }; 2060 let right_side_matches = match (right_side_assignment, right.as_ref()) { 2061 (AssignName::Variable(right_side_name), TypedExpr::Var { name, .. }) => { 2062 name == right_side_name 2063 } 2064 (AssignName::Variable(_) | AssignName::Discard(_), _) => false, 2065 }; 2066 left_side_matches && right_side_matches 2067 } 2068 (TypedPattern::StringPrefix { .. }, _) => false, 2069 2070 // Two tuples where each element is equivalent to the other: 2071 // `#(a, 1, "wibble") -> #(a, 1, "wibble")` 2072 // `#(a, b) -> #(a, b)` 2073 ( 2074 TypedPattern::Tuple { 2075 elements: pattern_elements, 2076 .. 2077 }, 2078 TypedExpr::Tuple { elements, .. }, 2079 ) => { 2080 pattern_elements.len() == elements.len() 2081 && pattern_elements 2082 .iter() 2083 .zip(elements) 2084 .all(|(pattern, expression)| { 2085 pattern_and_expression_are_the_same(pattern, expression) 2086 }) 2087 } 2088 (TypedPattern::Tuple { .. }, _) => false, 2089 2090 // Two lists are the same if each element is equivalent to the other: 2091 // `[] -> []` 2092 // `[a, b] -> [a, b]` 2093 // `[1, ..rest] -> [1, ..rest]` 2094 ( 2095 TypedPattern::List { 2096 elements: pattern_elements, 2097 tail: pattern_tail, 2098 .. 2099 }, 2100 TypedExpr::List { elements, tail, .. }, 2101 ) => { 2102 let tails_are_the_same = match (pattern_tail, tail) { 2103 (None, None) => true, 2104 (None, Some(_)) | (Some(_), None) => false, 2105 (Some(tail_pattern), Some(tail_expression)) => { 2106 pattern_and_expression_are_the_same(&tail_pattern.pattern, tail_expression) 2107 } 2108 }; 2109 2110 tails_are_the_same 2111 && pattern_elements.len() == elements.len() 2112 && pattern_elements 2113 .iter() 2114 .zip(elements) 2115 .all(|(pattern, expression)| { 2116 pattern_and_expression_are_the_same(pattern, expression) 2117 }) 2118 } 2119 (TypedPattern::List { .. }, _) => false, 2120 2121 // Two constructors are the same if the expression is building exactly 2122 // the same value being matched on (regardless of qualification). 2123 // `Ok(a) -> Ok(a)` 2124 // `Ok(1) -> Ok(1)` 2125 // `Wibble(a, b, c) -> Wibble(a, b, c)` 2126 // `Ok(a) -> gleam.Ok(a)` 2127 // `gleam.Ok(1) -> Ok(1)` 2128 ( 2129 TypedPattern::Constructor { 2130 constructor: 2131 Inferred::Known(PatternConstructor { 2132 module: pattern_module, 2133 name: pattern_name, 2134 .. 2135 }), 2136 arguments: pattern_arguments, 2137 spread: None, 2138 .. 2139 }, 2140 TypedExpr::Call { fun, arguments, .. }, 2141 ) => match fun.as_ref() { 2142 TypedExpr::Var { 2143 constructor: 2144 ValueConstructor { 2145 variant: ValueConstructorVariant::Record { name, module, .. }, 2146 .. 2147 }, 2148 .. 2149 } 2150 | TypedExpr::ModuleSelect { 2151 constructor: ModuleValueConstructor::Record { name, .. }, 2152 module_name: module, 2153 .. 2154 } => { 2155 pattern_module == module 2156 && pattern_name == name 2157 && pattern_arguments.len() == arguments.len() 2158 && pattern_arguments 2159 .iter() 2160 .zip(arguments) 2161 .all(|(pattern, expression)| { 2162 pattern_and_expression_are_the_same(&pattern.value, &expression.value) 2163 }) 2164 } 2165 2166 TypedExpr::Int { .. } 2167 | TypedExpr::Float { .. } 2168 | TypedExpr::String { .. } 2169 | TypedExpr::Block { .. } 2170 | TypedExpr::Pipeline { .. } 2171 | TypedExpr::Var { .. } 2172 | TypedExpr::Fn { .. } 2173 | TypedExpr::List { .. } 2174 | TypedExpr::Call { .. } 2175 | TypedExpr::BinOp { .. } 2176 | TypedExpr::Case { .. } 2177 | TypedExpr::RecordAccess { .. } 2178 | TypedExpr::PositionalAccess { .. } 2179 | TypedExpr::ModuleSelect { .. } 2180 | TypedExpr::Tuple { .. } 2181 | TypedExpr::TupleIndex { .. } 2182 | TypedExpr::Todo { .. } 2183 | TypedExpr::Panic { .. } 2184 | TypedExpr::Echo { .. } 2185 | TypedExpr::BitArray { .. } 2186 | TypedExpr::RecordUpdate { .. } 2187 | TypedExpr::NegateBool { .. } 2188 | TypedExpr::NegateInt { .. } 2189 | TypedExpr::Invalid { .. } => false, 2190 }, 2191 2192 // A pattern for a constructor with no arguments: 2193 // `Nil -> Nil` 2194 // `gleam.Nil -> Nil` 2195 // `Nil -> gleam.Nil` 2196 // `Wibble -> Wibble` 2197 ( 2198 TypedPattern::Constructor { 2199 constructor: 2200 Inferred::Known(PatternConstructor { 2201 module: pattern_module, 2202 name: pattern_name, 2203 .. 2204 }), 2205 arguments: pattern_arguments, 2206 spread: None, 2207 .. 2208 }, 2209 TypedExpr::Var { 2210 constructor: 2211 ValueConstructor { 2212 variant: ValueConstructorVariant::Record { name, module, .. }, 2213 .. 2214 }, 2215 .. 2216 } 2217 | TypedExpr::ModuleSelect { 2218 constructor: ModuleValueConstructor::Record { name, .. }, 2219 module_name: module, 2220 .. 2221 }, 2222 ) => pattern_module == module && pattern_name == name && pattern_arguments.is_empty(), 2223 (TypedPattern::Constructor { .. }, _) => false, 2224 2225 // An assignment is the same if the corresponding expression is a 2226 // variable with the same name, or if the inner pattern is the same: 2227 // `Ok(1) as a -> a` 2228 // `Ok(1) as a -> Ok(1)` 2229 ( 2230 TypedPattern::Assign { 2231 name: pattern_name, .. 2232 }, 2233 TypedExpr::Var { name, .. }, 2234 ) => pattern_name == name, 2235 (TypedPattern::Assign { pattern, .. }, expression) => { 2236 pattern_and_expression_are_the_same(pattern, expression) 2237 } 2238 2239 // Bit arrays are trickier as they can use existing variables in their 2240 // pattern and shadow existing variables so for now we just ignore 2241 // those. 2242 (TypedPattern::BitArray { .. } | TypedPattern::BitArraySize { .. }, _) => false, 2243 2244 // A discard is never the same as an expression, same goes for an 2245 // invalid pattern: there's no way to check if it matches an expression! 2246 (TypedPattern::Discard { .. } | TypedPattern::Invalid { .. }, _) => false, 2247 } 2248} 2249 2250pub type UntypedClauseGuard = ClauseGuard<(), ()>; 2251pub type TypedClauseGuard = ClauseGuard<Arc<Type>, EcoString>; 2252 2253#[derive(Debug, Clone, PartialEq, Eq)] 2254pub enum ClauseGuard<Type, RecordTag> { 2255 Block { 2256 location: SrcSpan, 2257 value: Box<ClauseGuard<Type, RecordTag>>, 2258 }, 2259 2260 BinaryOperator { 2261 location: SrcSpan, 2262 operator: BinOp, 2263 left: Box<Self>, 2264 right: Box<Self>, 2265 }, 2266 2267 Not { 2268 location: SrcSpan, 2269 expression: Box<Self>, 2270 }, 2271 2272 Var { 2273 location: SrcSpan, 2274 type_: Type, 2275 name: EcoString, 2276 definition_location: SrcSpan, 2277 origin: VariableOrigin, 2278 }, 2279 2280 TupleIndex { 2281 location: SrcSpan, 2282 index: u64, 2283 type_: Type, 2284 tuple: Box<Self>, 2285 }, 2286 2287 FieldAccess { 2288 label_location: SrcSpan, 2289 index: Option<u64>, 2290 label: EcoString, 2291 type_: Type, 2292 container: Box<Self>, 2293 }, 2294 2295 ModuleSelect { 2296 location: SrcSpan, 2297 field_start: u32, 2298 definition_location: SrcSpan, 2299 type_: Type, 2300 label: EcoString, 2301 module_name: EcoString, 2302 module_alias: EcoString, 2303 literal: Constant<Type, RecordTag>, 2304 }, 2305 2306 Constant(Constant<Type, RecordTag>), 2307} 2308 2309impl<A, B> ClauseGuard<A, B> { 2310 pub fn location(&self) -> SrcSpan { 2311 match self { 2312 ClauseGuard::Constant(constant) => constant.location(), 2313 ClauseGuard::BinaryOperator { location, .. } 2314 | ClauseGuard::Not { location, .. } 2315 | ClauseGuard::Var { location, .. } 2316 | ClauseGuard::TupleIndex { location, .. } 2317 | ClauseGuard::ModuleSelect { location, .. } 2318 | ClauseGuard::Block { location, .. } => *location, 2319 ClauseGuard::FieldAccess { 2320 label_location, 2321 container, 2322 .. 2323 } => container.location().merge(label_location), 2324 } 2325 } 2326 2327 pub fn precedence(&self) -> u8 { 2328 // Ensure that this matches the other precedence function for guards 2329 match self.bin_op_name() { 2330 Some(name) => name.precedence(), 2331 None => u8::MAX, 2332 } 2333 } 2334 2335 pub fn bin_op_name(&self) -> Option<BinOp> { 2336 match self { 2337 ClauseGuard::BinaryOperator { operator, .. } => Some(*operator), 2338 2339 ClauseGuard::Constant(_) 2340 | ClauseGuard::Var { .. } 2341 | ClauseGuard::Not { .. } 2342 | ClauseGuard::TupleIndex { .. } 2343 | ClauseGuard::FieldAccess { .. } 2344 | ClauseGuard::ModuleSelect { .. } 2345 | ClauseGuard::Block { .. } => None, 2346 } 2347 } 2348} 2349 2350impl TypedClauseGuard { 2351 pub fn type_(&self) -> Arc<Type> { 2352 match self { 2353 ClauseGuard::Var { type_, .. } => type_.clone(), 2354 ClauseGuard::TupleIndex { type_, .. } => type_.clone(), 2355 ClauseGuard::FieldAccess { type_, .. } => type_.clone(), 2356 ClauseGuard::ModuleSelect { type_, .. } => type_.clone(), 2357 ClauseGuard::Constant(constant) => constant.type_(), 2358 ClauseGuard::Block { value, .. } => value.type_(), 2359 2360 ClauseGuard::Not { .. } => type_::bool(), 2361 2362 ClauseGuard::BinaryOperator { operator, .. } => match operator { 2363 BinOp::AddInt 2364 | BinOp::SubInt 2365 | BinOp::MultInt 2366 | BinOp::DivInt 2367 | BinOp::RemainderInt => type_::int(), 2368 BinOp::AddFloat | BinOp::SubFloat | BinOp::MultFloat | BinOp::DivFloat => { 2369 type_::float() 2370 } 2371 BinOp::Concatenate => type_::string(), 2372 BinOp::Or 2373 | BinOp::And 2374 | BinOp::Eq 2375 | BinOp::NotEq 2376 | BinOp::GtInt 2377 | BinOp::GtEqInt 2378 | BinOp::LtInt 2379 | BinOp::LtEqInt 2380 | BinOp::GtFloat 2381 | BinOp::GtEqFloat 2382 | BinOp::LtFloat 2383 | BinOp::LtEqFloat => type_::bool(), 2384 }, 2385 } 2386 } 2387 2388 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 2389 if !self.location().contains(byte_index) { 2390 return None; 2391 } 2392 2393 match self { 2394 ClauseGuard::ModuleSelect { 2395 location, 2396 module_name, 2397 module_alias, 2398 .. 2399 } => { 2400 let module_span = 2401 SrcSpan::new(location.start, location.start + (module_alias.len() as u32)); 2402 2403 if module_span.contains(byte_index) { 2404 Some(Located::ModuleName { 2405 location: module_span, 2406 module_name: module_name.clone(), 2407 module_alias: module_alias.clone(), 2408 layer: Layer::Value, 2409 }) 2410 } else { 2411 Some(Located::ClauseGuard(self)) 2412 } 2413 } 2414 2415 ClauseGuard::BinaryOperator { left, right, .. } => left 2416 .find_node(byte_index) 2417 .or_else(|| right.find_node(byte_index)), 2418 2419 ClauseGuard::Not { 2420 expression: value, .. 2421 } 2422 | ClauseGuard::TupleIndex { tuple: value, .. } 2423 | ClauseGuard::FieldAccess { 2424 container: value, .. 2425 } 2426 | ClauseGuard::Block { value, .. } => value.find_node(byte_index), 2427 ClauseGuard::Constant(constant) => constant.find_node(byte_index), 2428 ClauseGuard::Var { .. } => Some(Located::ClauseGuard(self)), 2429 } 2430 } 2431 2432 pub(crate) fn referenced_variables(&self) -> im::HashSet<&EcoString> { 2433 match self { 2434 ClauseGuard::Var { name, .. } => im::hashset![name], 2435 2436 ClauseGuard::Block { value, .. } => value.referenced_variables(), 2437 ClauseGuard::Not { expression, .. } => expression.referenced_variables(), 2438 ClauseGuard::TupleIndex { tuple, .. } => tuple.referenced_variables(), 2439 ClauseGuard::FieldAccess { container, .. } => container.referenced_variables(), 2440 ClauseGuard::Constant(constant) => constant.referenced_variables(), 2441 ClauseGuard::ModuleSelect { .. } => im::HashSet::new(), 2442 2443 ClauseGuard::BinaryOperator { left, right, .. } => left 2444 .referenced_variables() 2445 .union(right.referenced_variables()), 2446 } 2447 } 2448 2449 fn syntactically_eq(&self, other: &Self) -> bool { 2450 match (self, other) { 2451 ( 2452 ClauseGuard::Block { value, .. }, 2453 ClauseGuard::Block { 2454 value: other_value, .. 2455 }, 2456 ) => value.syntactically_eq(other_value), 2457 (ClauseGuard::Block { .. }, _) => false, 2458 2459 ( 2460 ClauseGuard::BinaryOperator { left, right, .. }, 2461 ClauseGuard::BinaryOperator { 2462 left: other_left, 2463 right: other_right, 2464 .. 2465 }, 2466 ) => left.syntactically_eq(other_left) && right.syntactically_eq(other_right), 2467 (ClauseGuard::BinaryOperator { .. }, _) => false, 2468 2469 ( 2470 ClauseGuard::Not { expression, .. }, 2471 ClauseGuard::Not { 2472 expression: other_expression, 2473 .. 2474 }, 2475 ) => expression.syntactically_eq(other_expression), 2476 (ClauseGuard::Not { .. }, _) => false, 2477 2478 ( 2479 ClauseGuard::Var { name, .. }, 2480 ClauseGuard::Var { 2481 name: other_name, .. 2482 }, 2483 ) => name == other_name, 2484 (ClauseGuard::Var { .. }, _) => false, 2485 2486 ( 2487 ClauseGuard::TupleIndex { index, tuple, .. }, 2488 ClauseGuard::TupleIndex { 2489 index: other_index, 2490 tuple: other_tuple, 2491 .. 2492 }, 2493 ) => index == other_index && tuple.syntactically_eq(other_tuple), 2494 (ClauseGuard::TupleIndex { .. }, _) => false, 2495 2496 ( 2497 ClauseGuard::FieldAccess { 2498 label, container, .. 2499 }, 2500 ClauseGuard::FieldAccess { 2501 label: other_label, 2502 container: other_container, 2503 .. 2504 }, 2505 ) => label == other_label && container.syntactically_eq(other_container), 2506 (ClauseGuard::FieldAccess { .. }, _) => false, 2507 2508 ( 2509 ClauseGuard::ModuleSelect { 2510 label, 2511 module_alias, 2512 .. 2513 }, 2514 ClauseGuard::ModuleSelect { 2515 label: other_label, 2516 module_alias: other_module_alias, 2517 .. 2518 }, 2519 ) => label == other_label && module_alias == other_module_alias, 2520 (ClauseGuard::ModuleSelect { .. }, _) => false, 2521 2522 (ClauseGuard::Constant(one), ClauseGuard::Constant(other)) => { 2523 one.syntactically_eq(other) 2524 } 2525 (ClauseGuard::Constant(_), _) => false, 2526 } 2527 } 2528 2529 pub fn definition_location(&self) -> Option<DefinitionLocation> { 2530 match self { 2531 ClauseGuard::Block { .. } 2532 | ClauseGuard::BinaryOperator { .. } 2533 | ClauseGuard::Not { .. } 2534 | ClauseGuard::TupleIndex { .. } 2535 | ClauseGuard::FieldAccess { .. } => None, 2536 ClauseGuard::Constant(constant) => constant.definition_location(), 2537 ClauseGuard::Var { 2538 definition_location, 2539 .. 2540 } => Some(DefinitionLocation { 2541 module: None, 2542 span: *definition_location, 2543 }), 2544 ClauseGuard::ModuleSelect { 2545 module_name, 2546 definition_location, 2547 .. 2548 } => Some(DefinitionLocation { 2549 module: Some(module_name.clone()), 2550 span: *definition_location, 2551 }), 2552 } 2553 } 2554} 2555 2556#[derive( 2557 Debug, 2558 PartialEq, 2559 Eq, 2560 PartialOrd, 2561 Ord, 2562 Default, 2563 Clone, 2564 Copy, 2565 serde::Serialize, 2566 serde::Deserialize, 2567 Hash, 2568)] 2569pub struct SrcSpan { 2570 pub start: u32, 2571 pub end: u32, 2572} 2573 2574impl SrcSpan { 2575 pub fn new(start: u32, end: u32) -> Self { 2576 Self { start, end } 2577 } 2578 2579 pub fn contains(&self, byte_index: u32) -> bool { 2580 byte_index >= self.start && byte_index <= self.end 2581 } 2582 2583 pub fn contains_span(&self, span: SrcSpan) -> bool { 2584 self.contains(span.start) && self.contains(span.end) 2585 } 2586 2587 /// Merges two spans into a new one that starts at the start of the smaller 2588 /// one and ends at the end of the bigger one. For example: 2589 /// 2590 /// ```txt 2591 /// wibble wobble 2592 /// ─┬──── ─┬──── 2593 /// │ ╰─ one span 2594 /// ╰─ the other span 2595 /// ─┬────────────── 2596 /// ╰─ the span you get by merging the two 2597 /// ``` 2598 pub fn merge(&self, with: &SrcSpan) -> SrcSpan { 2599 Self { 2600 start: self.start.min(with.start), 2601 end: self.end.max(with.end), 2602 } 2603 } 2604 2605 pub fn is_empty(&self) -> bool { 2606 self.len() == 0 2607 } 2608 2609 pub fn len(&self) -> usize { 2610 (self.end - self.start) as usize 2611 } 2612} 2613 2614#[derive(Debug, PartialEq, Eq, Clone)] 2615pub struct DefinitionLocation { 2616 pub module: Option<EcoString>, 2617 pub span: SrcSpan, 2618} 2619 2620pub type UntypedPattern = Pattern<()>; 2621pub type TypedPattern = Pattern<Arc<Type>>; 2622 2623#[derive(Debug, Clone, PartialEq, Eq)] 2624pub enum Pattern<Type> { 2625 Int { 2626 location: SrcSpan, 2627 value: EcoString, 2628 int_value: BigInt, 2629 }, 2630 2631 Float { 2632 location: SrcSpan, 2633 value: EcoString, 2634 float_value: LiteralFloatValue, 2635 }, 2636 2637 String { 2638 location: SrcSpan, 2639 value: EcoString, 2640 }, 2641 2642 /// The creation of a variable. 2643 /// e.g. `assert [this_is_a_var, .._] = x` 2644 Variable { 2645 location: SrcSpan, 2646 name: EcoString, 2647 type_: Type, 2648 origin: VariableOrigin, 2649 }, 2650 2651 /// The specified size of a bit array. This can either be a literal integer, 2652 /// a reference to a variable, or a maths expression. 2653 /// e.g. `let assert <<y:size(somevar)>> = x` 2654 BitArraySize(BitArraySize<Type>), 2655 2656 /// A name given to a sub-pattern using the `as` keyword. 2657 /// e.g. `assert #(1, [_, _] as the_list) = x` 2658 Assign { 2659 name: EcoString, 2660 location: SrcSpan, 2661 pattern: Box<Self>, 2662 }, 2663 2664 /// A pattern that binds to any value but does not assign a variable. 2665 /// Always starts with an underscore. 2666 Discard { 2667 name: EcoString, 2668 location: SrcSpan, 2669 type_: Type, 2670 }, 2671 2672 List { 2673 location: SrcSpan, 2674 elements: Vec<Self>, 2675 tail: Option<Box<TailPattern<Type>>>, 2676 /// The type of the list, so this is going to be `List(something)`. 2677 /// 2678 type_: Type, 2679 }, 2680 2681 /// The constructor for a custom type. Starts with an uppercase letter. 2682 Constructor { 2683 location: SrcSpan, 2684 name_location: SrcSpan, 2685 name: EcoString, 2686 arguments: Vec<CallArg<Self>>, 2687 module: Option<(EcoString, SrcSpan)>, 2688 constructor: Inferred<PatternConstructor>, 2689 spread: Option<SrcSpan>, 2690 type_: Type, 2691 }, 2692 2693 Tuple { 2694 location: SrcSpan, 2695 elements: Vec<Self>, 2696 }, 2697 2698 BitArray { 2699 location: SrcSpan, 2700 segments: Vec<BitArraySegment<Self, Type>>, 2701 }, 2702 2703 // "prefix" <> variable 2704 StringPrefix { 2705 location: SrcSpan, 2706 left_location: SrcSpan, 2707 left_side_assignment: Option<(EcoString, SrcSpan)>, 2708 right_location: SrcSpan, 2709 left_side_string: EcoString, 2710 /// The variable on the right hand side of the `<>`. 2711 right_side_assignment: AssignName, 2712 }, 2713 2714 /// A placeholder pattern used to allow module analysis to continue 2715 /// even when there are type errors. Should never end up in generated code. 2716 Invalid { 2717 location: SrcSpan, 2718 type_: Type, 2719 }, 2720} 2721 2722pub type TypedBitArraySize = BitArraySize<Arc<Type>>; 2723 2724#[derive(Debug, Clone, PartialEq, Eq)] 2725pub enum BitArraySize<Type> { 2726 Int { 2727 location: SrcSpan, 2728 value: EcoString, 2729 int_value: BigInt, 2730 }, 2731 2732 Variable { 2733 location: SrcSpan, 2734 name: EcoString, 2735 constructor: Option<Box<ValueConstructor>>, 2736 type_: Type, 2737 }, 2738 2739 BinaryOperator { 2740 location: SrcSpan, 2741 operator: IntOperator, 2742 left: Box<Self>, 2743 right: Box<Self>, 2744 }, 2745 2746 Block { 2747 location: SrcSpan, 2748 inner: Box<Self>, 2749 }, 2750} 2751 2752#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] 2753pub enum IntOperator { 2754 Add, 2755 Subtract, 2756 Multiply, 2757 Divide, 2758 Remainder, 2759} 2760 2761impl IntOperator { 2762 pub fn precedence(&self) -> u8 { 2763 match self { 2764 Self::Add | Self::Subtract => 7, 2765 2766 Self::Multiply | Self::Divide | Self::Remainder => 8, 2767 } 2768 } 2769 2770 pub fn to_bin_op(&self) -> BinOp { 2771 match self { 2772 IntOperator::Add => BinOp::AddInt, 2773 IntOperator::Subtract => BinOp::SubInt, 2774 IntOperator::Multiply => BinOp::MultInt, 2775 IntOperator::Divide => BinOp::DivInt, 2776 IntOperator::Remainder => BinOp::RemainderInt, 2777 } 2778 } 2779} 2780 2781impl<T> BitArraySize<T> { 2782 pub fn location(&self) -> SrcSpan { 2783 match self { 2784 BitArraySize::Int { location, .. } 2785 | BitArraySize::Variable { location, .. } 2786 | BitArraySize::BinaryOperator { location, .. } 2787 | BitArraySize::Block { location, .. } => *location, 2788 } 2789 } 2790 2791 pub fn non_zero_compile_time_number(&self) -> bool { 2792 self.compile_time_number() 2793 .is_some_and(|number| number != BigInt::ZERO) 2794 } 2795 2796 pub fn compile_time_number(&self) -> Option<BigInt> { 2797 match self { 2798 BitArraySize::Int { int_value, .. } => Some(int_value.clone()), 2799 BitArraySize::Block { inner, .. } => inner.compile_time_number(), 2800 BitArraySize::Variable { .. } | BitArraySize::BinaryOperator { .. } => None, 2801 } 2802 } 2803 2804 fn syntactically_eq(&self, other: &Self) -> bool { 2805 match (self, other) { 2806 (BitArraySize::Int { int_value: n, .. }, BitArraySize::Int { int_value: m, .. }) => { 2807 n == m 2808 } 2809 (BitArraySize::Int { .. }, _) => false, 2810 2811 ( 2812 BitArraySize::Variable { name, .. }, 2813 BitArraySize::Variable { 2814 name: other_name, .. 2815 }, 2816 ) => name == other_name, 2817 (BitArraySize::Variable { .. }, _) => false, 2818 2819 ( 2820 BitArraySize::BinaryOperator { 2821 operator, 2822 left, 2823 right, 2824 .. 2825 }, 2826 BitArraySize::BinaryOperator { 2827 operator: other_operator, 2828 left: other_left, 2829 right: other_right, 2830 .. 2831 }, 2832 ) => { 2833 operator == other_operator 2834 && left.syntactically_eq(other_left) 2835 && right.syntactically_eq(other_right) 2836 } 2837 (BitArraySize::BinaryOperator { .. }, _) => false, 2838 2839 ( 2840 BitArraySize::Block { inner, .. }, 2841 BitArraySize::Block { 2842 inner: other_inner, .. 2843 }, 2844 ) => inner.syntactically_eq(other_inner), 2845 (BitArraySize::Block { .. }, _) => false, 2846 } 2847 } 2848} 2849 2850pub type TypedTailPattern = TailPattern<Arc<Type>>; 2851 2852pub type UntypedTailPattern = TailPattern<()>; 2853 2854/// The pattern one can use to match on the rest of a list: 2855/// 2856#[derive(Debug, Clone, PartialEq, Eq)] 2857pub struct TailPattern<Type> { 2858 /// The entire location of the pattern, covering the `..` as well. 2859 /// 2860 pub location: SrcSpan, 2861 2862 /// The name assigned to the rest of the list being matched: 2863 /// 2864 /// ```gleam 2865 /// [wibble, ..] 2866 /// // ^^ no name 2867 /// 2868 /// [wibble, ..rest] 2869 /// // ^^^^^^ a variable name 2870 /// 2871 /// [wibble, .._rest] 2872 /// // ^^^^^^^ a discarded name 2873 /// ``` 2874 /// 2875 pub pattern: Pattern<Type>, 2876} 2877 2878#[derive(Debug, Clone, PartialEq, Eq, Hash)] 2879pub enum AssignName { 2880 Variable(EcoString), 2881 Discard(EcoString), 2882} 2883 2884impl AssignName { 2885 pub fn name(&self) -> &EcoString { 2886 match self { 2887 AssignName::Variable(name) | AssignName::Discard(name) => name, 2888 } 2889 } 2890 2891 pub fn to_arg_names(self, location: SrcSpan) -> ArgNames { 2892 match self { 2893 AssignName::Variable(name) => ArgNames::Named { name, location }, 2894 AssignName::Discard(name) => ArgNames::Discard { name, location }, 2895 } 2896 } 2897 2898 pub fn assigned_name(&self) -> Option<&str> { 2899 match self { 2900 AssignName::Variable(name) => Some(name), 2901 AssignName::Discard(_) => None, 2902 } 2903 } 2904} 2905 2906impl<A> Pattern<A> { 2907 pub fn location(&self) -> SrcSpan { 2908 match self { 2909 Pattern::Assign { 2910 pattern, location, .. 2911 } => SrcSpan::new(pattern.location().start, location.end), 2912 Pattern::Int { location, .. } 2913 | Pattern::Variable { location, .. } 2914 | Pattern::List { location, .. } 2915 | Pattern::Float { location, .. } 2916 | Pattern::Discard { location, .. } 2917 | Pattern::String { location, .. } 2918 | Pattern::Tuple { location, .. } 2919 | Pattern::Constructor { location, .. } 2920 | Pattern::StringPrefix { location, .. } 2921 | Pattern::BitArray { location, .. } 2922 | Pattern::Invalid { location, .. } => *location, 2923 Pattern::BitArraySize(size) => size.location(), 2924 } 2925 } 2926 2927 /// Returns `true` if the pattern is [`Discard`]. 2928 /// 2929 /// [`Discard`]: Pattern::Discard 2930 #[must_use] 2931 pub fn is_discard(&self) -> bool { 2932 matches!(self, Self::Discard { .. }) 2933 } 2934 2935 #[must_use] 2936 pub fn is_variable(&self) -> bool { 2937 matches!(self, Pattern::Variable { .. }) 2938 } 2939 2940 #[must_use] 2941 pub fn is_string(&self) -> bool { 2942 matches!(self, Self::String { .. }) 2943 } 2944} 2945 2946impl TypedPattern { 2947 fn syntactically_eq(&self, other: &Self) -> bool { 2948 match (self, other) { 2949 (Pattern::Int { int_value: n, .. }, Pattern::Int { int_value: m, .. }) => n == m, 2950 (Pattern::Int { .. }, _) => false, 2951 2952 (Pattern::Float { float_value: n, .. }, Pattern::Float { float_value: m, .. }) => { 2953 n == m 2954 } 2955 (Pattern::Float { .. }, _) => false, 2956 2957 ( 2958 Pattern::String { value, .. }, 2959 Pattern::String { 2960 value: other_value, .. 2961 }, 2962 ) => value == other_value, 2963 (Pattern::String { .. }, _) => false, 2964 2965 ( 2966 Pattern::Variable { name, .. }, 2967 Pattern::Variable { 2968 name: other_name, .. 2969 }, 2970 ) => name == other_name, 2971 (Pattern::Variable { .. }, _) => false, 2972 2973 (Pattern::BitArraySize(one), Pattern::BitArraySize(other)) => { 2974 one.syntactically_eq(other) 2975 } 2976 (Pattern::BitArraySize(..), _) => false, 2977 2978 ( 2979 Pattern::Assign { name, pattern, .. }, 2980 Pattern::Assign { 2981 name: other_name, 2982 pattern: other_pattern, 2983 .. 2984 }, 2985 ) => name == other_name && pattern.syntactically_eq(other_pattern), 2986 (Pattern::Assign { .. }, _) => false, 2987 2988 ( 2989 Pattern::Discard { name, .. }, 2990 Pattern::Discard { 2991 name: other_name, .. 2992 }, 2993 ) => name == other_name, 2994 (Pattern::Discard { .. }, _) => false, 2995 2996 ( 2997 Pattern::List { elements, tail, .. }, 2998 Pattern::List { 2999 elements: other_elements, 3000 tail: other_tail, 3001 .. 3002 }, 3003 ) => { 3004 let tails_are_equal = match (tail, other_tail) { 3005 (None, None) => true, 3006 (None, Some(_)) | (Some(_), None) => false, 3007 (Some(one), Some(other)) => one.pattern.syntactically_eq(&other.pattern), 3008 }; 3009 tails_are_equal 3010 && pairwise_all(elements, other_elements, |(one, other)| { 3011 one.syntactically_eq(other) 3012 }) 3013 } 3014 (Pattern::List { .. }, _) => false, 3015 3016 ( 3017 Pattern::Constructor { 3018 name, 3019 arguments, 3020 module, 3021 .. 3022 }, 3023 Pattern::Constructor { 3024 name: other_name, 3025 arguments: other_arguments, 3026 module: other_module, 3027 .. 3028 }, 3029 ) => { 3030 let modules_are_equal = match (module, other_module) { 3031 (None, None) => true, 3032 (None, Some(_)) | (Some(_), None) => false, 3033 (Some((one, _)), Some((other, _))) => one == other, 3034 }; 3035 modules_are_equal 3036 && name == other_name 3037 && pairwise_all(arguments, other_arguments, |(one, other)| { 3038 one.label == other.label && one.value.syntactically_eq(&other.value) 3039 }) 3040 } 3041 (Pattern::Constructor { .. }, _) => false, 3042 3043 ( 3044 Pattern::Tuple { elements, .. }, 3045 Pattern::Tuple { 3046 elements: other_elements, 3047 .. 3048 }, 3049 ) => pairwise_all(elements, other_elements, |(one, other)| { 3050 one.syntactically_eq(other) 3051 }), 3052 (Pattern::Tuple { .. }, _) => false, 3053 3054 ( 3055 Pattern::BitArray { segments, .. }, 3056 Pattern::BitArray { 3057 segments: other_segments, 3058 .. 3059 }, 3060 ) => pairwise_all(segments, other_segments, |(one, other)| { 3061 one.syntactically_eq(other) 3062 }), 3063 (Pattern::BitArray { .. }, _) => false, 3064 3065 ( 3066 Pattern::StringPrefix { 3067 left_side_assignment, 3068 left_side_string, 3069 right_side_assignment, 3070 .. 3071 }, 3072 Pattern::StringPrefix { 3073 left_side_assignment: other_left_side_assignment, 3074 left_side_string: other_left_side_string, 3075 right_side_assignment: other_right_side_assignment, 3076 .. 3077 }, 3078 ) => { 3079 let left_side_assignments_are_equal = 3080 match (left_side_assignment, other_left_side_assignment) { 3081 (None, None) => true, 3082 (None, Some(_)) | (Some(_), None) => false, 3083 (Some((one, _)), Some((other, _))) => one == other, 3084 }; 3085 let right_side_assignments_are_equal = 3086 match (right_side_assignment, other_right_side_assignment) { 3087 (AssignName::Variable(one), AssignName::Variable(other)) => one == other, 3088 (AssignName::Variable(_), AssignName::Discard(_)) => false, 3089 (AssignName::Discard(one), AssignName::Discard(other)) => one == other, 3090 (AssignName::Discard(_), AssignName::Variable(_)) => false, 3091 }; 3092 left_side_string == other_left_side_string 3093 && left_side_assignments_are_equal 3094 && right_side_assignments_are_equal 3095 } 3096 (Pattern::StringPrefix { .. }, _) => false, 3097 3098 (Pattern::Invalid { .. }, _) => false, 3099 } 3100 } 3101} 3102 3103/// A variable bound inside a pattern. 3104#[derive(Debug, Clone)] 3105pub struct BoundVariable { 3106 pub name: BoundVariableName, 3107 pub location: SrcSpan, 3108 pub type_: Arc<Type>, 3109} 3110 3111#[derive(Debug, Clone)] 3112pub enum BoundVariableName { 3113 /// A record's labelled field introduced with the shorthand syntax. 3114 ShorthandLabel { name: EcoString }, 3115 ListTail { 3116 name: EcoString, 3117 /// The location of the whole tail, from the `..` prefix until the end of the variable. 3118 tail_location: SrcSpan, 3119 }, 3120 /// Any other variable name. 3121 Regular { name: EcoString }, 3122} 3123 3124impl BoundVariable { 3125 pub fn name(&self) -> EcoString { 3126 match &self.name { 3127 BoundVariableName::ShorthandLabel { name } 3128 | BoundVariableName::ListTail { name, .. } 3129 | BoundVariableName::Regular { name } => name.clone(), 3130 } 3131 } 3132} 3133 3134impl TypedPattern { 3135 pub fn definition_location(&self) -> Option<DefinitionLocation> { 3136 match self { 3137 Pattern::Int { .. } 3138 | Pattern::Float { .. } 3139 | Pattern::String { .. } 3140 | Pattern::Variable { .. } 3141 | Pattern::BitArraySize { .. } 3142 | Pattern::Assign { .. } 3143 | Pattern::Discard { .. } 3144 | Pattern::List { .. } 3145 | Pattern::Tuple { .. } 3146 | Pattern::BitArray { .. } 3147 | Pattern::StringPrefix { .. } 3148 | Pattern::Invalid { .. } => None, 3149 3150 Pattern::Constructor { constructor, .. } => constructor.definition_location(), 3151 } 3152 } 3153 3154 pub fn get_documentation(&self) -> Option<&str> { 3155 match self { 3156 Pattern::Int { .. } 3157 | Pattern::Float { .. } 3158 | Pattern::String { .. } 3159 | Pattern::Variable { .. } 3160 | Pattern::BitArraySize { .. } 3161 | Pattern::Assign { .. } 3162 | Pattern::Discard { .. } 3163 | Pattern::List { .. } 3164 | Pattern::Tuple { .. } 3165 | Pattern::BitArray { .. } 3166 | Pattern::StringPrefix { .. } 3167 | Pattern::Invalid { .. } => None, 3168 3169 Pattern::Constructor { constructor, .. } => constructor.get_documentation(), 3170 } 3171 } 3172 3173 pub fn type_(&self) -> Arc<Type> { 3174 match self { 3175 Pattern::Int { .. } => type_::int(), 3176 Pattern::Float { .. } => type_::float(), 3177 Pattern::String { .. } => type_::string(), 3178 Pattern::BitArray { .. } => type_::bit_array(), 3179 Pattern::StringPrefix { .. } => type_::string(), 3180 3181 Pattern::Variable { type_, .. } 3182 | Pattern::List { type_, .. } 3183 | Pattern::Constructor { type_, .. } 3184 | Pattern::Invalid { type_, .. } => type_.clone(), 3185 3186 Pattern::Assign { pattern, .. } => pattern.type_(), 3187 3188 // Bit array sizes should always be integers 3189 Pattern::BitArraySize(_) => type_::int(), 3190 3191 Pattern::Discard { type_, .. } => type_.clone(), 3192 3193 Pattern::Tuple { elements, .. } => { 3194 type_::tuple(elements.iter().map(|p| p.type_()).collect()) 3195 } 3196 } 3197 } 3198 3199 fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 3200 if !self.location().contains(byte_index) { 3201 return None; 3202 } 3203 3204 if let Pattern::Variable { name, .. } = self { 3205 // For pipes the pattern can't be pointed to 3206 if name.as_str().eq(PIPE_VARIABLE) { 3207 return None; 3208 } 3209 } 3210 3211 match self { 3212 Pattern::Int { .. } 3213 | Pattern::Float { .. } 3214 | Pattern::String { .. } 3215 | Pattern::Variable { .. } 3216 | Pattern::BitArraySize { .. } 3217 | Pattern::Discard { .. } 3218 | Pattern::Invalid { .. } => Some(Located::Pattern(self)), 3219 Pattern::StringPrefix { 3220 left_side_assignment, 3221 right_side_assignment, 3222 right_location, 3223 .. 3224 } => { 3225 // Handle the prefix alias: "prefix" as name 3226 if let Some((name, left_side_assignment_location)) = left_side_assignment 3227 && left_side_assignment_location.contains(byte_index) 3228 { 3229 return Some(Located::StringPrefixPatternVariable { 3230 location: *left_side_assignment_location, 3231 name, 3232 }); 3233 } 3234 3235 // Handle the suffix: <> name 3236 if let AssignName::Variable(name) = right_side_assignment 3237 && right_location.contains(byte_index) 3238 { 3239 return Some(Located::StringPrefixPatternVariable { 3240 location: *right_location, 3241 name, 3242 }); 3243 } 3244 3245 Some(Located::Pattern(self)) 3246 } 3247 Pattern::Assign { pattern, .. } => pattern 3248 .find_node(byte_index) 3249 .or_else(|| Some(Located::Pattern(self))), 3250 3251 Pattern::Constructor { 3252 module, 3253 spread, 3254 arguments, 3255 constructor, 3256 .. 3257 } => { 3258 if let Some((module_alias, module_location)) = module 3259 && let Inferred::Known(constructor) = constructor 3260 && module_location.contains(byte_index) 3261 { 3262 Some(Located::ModuleName { 3263 location: *module_location, 3264 module_name: constructor.module.clone(), 3265 module_alias: module_alias.clone(), 3266 layer: Layer::Value, 3267 }) 3268 } else if let Some(spread_location) = spread 3269 && spread_location.contains(byte_index) 3270 { 3271 Some(Located::PatternSpread { 3272 spread_location: *spread_location, 3273 pattern: self, 3274 }) 3275 } else { 3276 arguments 3277 .iter() 3278 .find_map(|argument| argument.find_node(byte_index)) 3279 } 3280 } 3281 3282 Pattern::List { elements, tail, .. } => elements 3283 .iter() 3284 .find_map(|element| element.find_node(byte_index)) 3285 .or_else(|| { 3286 tail.as_ref() 3287 .and_then(|tail| tail.pattern.find_node(byte_index)) 3288 }), 3289 3290 Pattern::Tuple { elements, .. } => elements 3291 .iter() 3292 .find_map(|element| element.find_node(byte_index)), 3293 3294 Pattern::BitArray { segments, .. } => segments 3295 .iter() 3296 .find_map(|segment| segment.find_node(byte_index)) 3297 .or(Some(Located::Pattern(self))), 3298 } 3299 .or(Some(Located::Pattern(self))) 3300 } 3301 3302 /// If the pattern is a `Constructor` with a spread, it returns a tuple with 3303 /// all the ignored fields. Split in unlabelled and labelled ones. 3304 /// 3305 pub fn unused_arguments(&self) -> Option<PatternUnusedArguments> { 3306 let TypedPattern::Constructor { 3307 arguments, 3308 spread: Some(_), 3309 .. 3310 } = self 3311 else { 3312 return None; 3313 }; 3314 3315 let mut positional = vec![]; 3316 let mut labelled = vec![]; 3317 for argument in arguments { 3318 // We only want to display the arguments that were ignored using `..`. 3319 // Any argument ignored that way is marked as implicit, so if it is 3320 // not implicit we just ignore it. 3321 if !argument.is_implicit() { 3322 continue; 3323 } 3324 let type_ = argument.value.type_(); 3325 match &argument.label { 3326 Some(label) => labelled.push((label.clone(), type_)), 3327 None => positional.push(type_), 3328 } 3329 } 3330 3331 Some(PatternUnusedArguments { 3332 positional, 3333 labelled, 3334 }) 3335 } 3336 3337 /// Whether the pattern always matches. For example, a tuple or simple 3338 /// variable assignment always match and can never fail. 3339 #[must_use] 3340 pub fn always_matches(&self) -> bool { 3341 match self { 3342 Pattern::Variable { .. } | Pattern::Discard { .. } => true, 3343 Pattern::Assign { pattern, .. } => pattern.always_matches(), 3344 Pattern::Tuple { elements, .. } => { 3345 elements.iter().all(|element| element.always_matches()) 3346 } 3347 Pattern::Int { .. } 3348 | Pattern::Float { .. } 3349 | Pattern::String { .. } 3350 | Pattern::BitArraySize { .. } 3351 | Pattern::List { .. } 3352 | Pattern::Constructor { .. } 3353 | Pattern::BitArray { .. } 3354 | Pattern::StringPrefix { .. } 3355 | Pattern::Invalid { .. } => false, 3356 } 3357 } 3358 3359 pub fn bound_variables(&self) -> Vec<BoundVariable> { 3360 let mut variables = Vec::new(); 3361 self.collect_bound_variables(&mut variables); 3362 variables 3363 } 3364 3365 fn collect_bound_variables(&self, variables: &mut Vec<BoundVariable>) { 3366 match self { 3367 Pattern::Int { .. } 3368 | Pattern::Float { .. } 3369 | Pattern::String { .. } 3370 | Pattern::Discard { .. } 3371 | Pattern::Invalid { .. } => {} 3372 3373 Pattern::Variable { 3374 name, 3375 location, 3376 type_, 3377 .. 3378 } => variables.push(BoundVariable { 3379 name: BoundVariableName::Regular { name: name.clone() }, 3380 location: *location, 3381 type_: type_.clone(), 3382 }), 3383 Pattern::BitArraySize { .. } => {} 3384 Pattern::Assign { 3385 name, 3386 pattern, 3387 location, 3388 } => { 3389 variables.push(BoundVariable { 3390 name: BoundVariableName::Regular { name: name.clone() }, 3391 location: *location, 3392 type_: pattern.type_(), 3393 }); 3394 pattern.collect_bound_variables(variables); 3395 } 3396 Pattern::List { 3397 elements, 3398 tail, 3399 type_, 3400 .. 3401 } => { 3402 for element in elements { 3403 element.collect_bound_variables(variables); 3404 } 3405 if let Some(tail) = tail 3406 && let Pattern::Variable { name, location, .. } = tail.pattern.to_owned() 3407 { 3408 variables.push(BoundVariable { 3409 name: BoundVariableName::ListTail { 3410 name, 3411 tail_location: tail.location, 3412 }, 3413 location, 3414 type_: type_.clone(), 3415 }) 3416 }; 3417 } 3418 Pattern::Constructor { arguments, .. } => { 3419 for argument in arguments { 3420 if let Some(name) = argument.label_shorthand_name() { 3421 variables.push(BoundVariable { 3422 name: BoundVariableName::ShorthandLabel { name: name.clone() }, 3423 location: argument.location, 3424 type_: argument.value.type_(), 3425 }) 3426 } else { 3427 argument.value.collect_bound_variables(variables); 3428 } 3429 } 3430 } 3431 Pattern::Tuple { elements, .. } => { 3432 for element in elements { 3433 element.collect_bound_variables(variables); 3434 } 3435 } 3436 Pattern::BitArray { segments, .. } => { 3437 for segment in segments { 3438 segment.value.collect_bound_variables(variables); 3439 } 3440 } 3441 Pattern::StringPrefix { 3442 left_side_assignment, 3443 right_side_assignment, 3444 right_location, 3445 .. 3446 } => { 3447 if let Some((name, location)) = left_side_assignment { 3448 variables.push(BoundVariable { 3449 name: BoundVariableName::Regular { name: name.clone() }, 3450 location: *location, 3451 type_: type_::string(), 3452 }); 3453 } 3454 match right_side_assignment { 3455 AssignName::Variable(name) => variables.push(BoundVariable { 3456 name: BoundVariableName::Regular { name: name.clone() }, 3457 location: *right_location, 3458 type_: type_::string(), 3459 }), 3460 AssignName::Discard(_) => {} 3461 } 3462 } 3463 } 3464 } 3465} 3466 3467#[derive(Debug, Default)] 3468pub struct PatternUnusedArguments { 3469 pub positional: Vec<Arc<Type>>, 3470 pub labelled: Vec<(EcoString, Arc<Type>)>, 3471} 3472 3473impl<A> HasLocation for Pattern<A> { 3474 fn location(&self) -> SrcSpan { 3475 self.location() 3476 } 3477} 3478 3479#[derive(Debug, Clone, PartialEq, Eq)] 3480pub enum AssignmentKind<Expression> { 3481 /// let x = ... 3482 Let, 3483 /// This is a let assignment generated by the compiler for intermediate 3484 /// variables needed by record updates and `use`. 3485 /// Like a regular `Let` assignment this can never fail. 3486 /// 3487 Generated, 3488 /// let assert x = ... 3489 Assert { 3490 /// The src byte span of the `let assert` 3491 /// 3492 /// ```gleam 3493 /// let assert Wibble = todo 3494 /// ^^^^^^^^^^ 3495 /// ``` 3496 location: SrcSpan, 3497 3498 /// The byte index of the start of `assert` 3499 /// 3500 /// ```gleam 3501 /// let assert Wibble = todo 3502 /// ^ 3503 /// ``` 3504 assert_keyword_start: u32, 3505 3506 /// The message given to the assertion: 3507 /// 3508 /// ```gleam 3509 /// let asset Ok(a) = something() as "This will never fail" 3510 /// ^^^^^^^^^^^^^^^^^^^^^^ 3511 /// ``` 3512 message: Option<Expression>, 3513 }, 3514} 3515 3516impl<Expression> AssignmentKind<Expression> { 3517 /// Returns `true` if the assignment kind is [`Assert`]. 3518 /// 3519 /// [`Assert`]: AssignmentKind::Assert 3520 #[must_use] 3521 pub fn is_assert(&self) -> bool { 3522 match self { 3523 Self::Assert { .. } => true, 3524 Self::Let | Self::Generated => false, 3525 } 3526 } 3527} 3528 3529// BitArrays 3530 3531pub type UntypedExprBitArraySegment = BitArraySegment<UntypedExpr, ()>; 3532pub type TypedExprBitArraySegment = BitArraySegment<TypedExpr, Arc<Type>>; 3533 3534pub type UntypedConstantBitArraySegment = BitArraySegment<UntypedConstant, ()>; 3535pub type TypedConstantBitArraySegment = BitArraySegment<TypedConstant, Arc<Type>>; 3536 3537pub type UntypedPatternBitArraySegment = BitArraySegment<UntypedPattern, ()>; 3538pub type TypedPatternBitArraySegment = BitArraySegment<TypedPattern, Arc<Type>>; 3539 3540#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 3541pub struct BitArraySegment<Value, Type> { 3542 pub location: SrcSpan, 3543 pub value: Box<Value>, 3544 pub options: Vec<BitArrayOption<Value>>, 3545 pub type_: Type, 3546} 3547 3548#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, serde::Serialize, serde::Deserialize)] 3549pub enum Endianness { 3550 Big, 3551 Little, 3552} 3553 3554impl Endianness { 3555 pub fn is_big(&self) -> bool { 3556 *self == Endianness::Big 3557 } 3558} 3559 3560impl<Value, Type> HasLocation for BitArraySegment<Value, Type> { 3561 fn location(&self) -> SrcSpan { 3562 self.location 3563 } 3564} 3565 3566impl<Type> BitArraySegment<Pattern<Type>, Type> { 3567 /// Returns the value of the pattern unwrapping any assign pattern. 3568 /// 3569 pub fn value_unwrapping_assign(&self) -> &Pattern<Type> { 3570 match self.value.as_ref() { 3571 Pattern::Assign { pattern, .. } => pattern, 3572 Pattern::Int { .. } 3573 | Pattern::Float { .. } 3574 | Pattern::String { .. } 3575 | Pattern::Variable { .. } 3576 | Pattern::BitArraySize { .. } 3577 | Pattern::Discard { .. } 3578 | Pattern::List { .. } 3579 | Pattern::Constructor { .. } 3580 | Pattern::Tuple { .. } 3581 | Pattern::BitArray { .. } 3582 | Pattern::StringPrefix { .. } 3583 | Pattern::Invalid { .. } => self.value.as_ref(), 3584 } 3585 } 3586} 3587 3588impl<Value, Type> BitArraySegment<Value, Type> { 3589 #[must_use] 3590 pub fn has_native_option(&self) -> bool { 3591 self.options 3592 .iter() 3593 .any(|x| matches!(x, BitArrayOption::Native { .. })) 3594 } 3595 3596 #[must_use] 3597 pub fn has_utf16_codepoint_option(&self) -> bool { 3598 self.options 3599 .iter() 3600 .any(|x| matches!(x, BitArrayOption::Utf16Codepoint { .. })) 3601 } 3602 3603 #[must_use] 3604 pub fn has_utf32_codepoint_option(&self) -> bool { 3605 self.options 3606 .iter() 3607 .any(|x| matches!(x, BitArrayOption::Utf32Codepoint { .. })) 3608 } 3609 3610 #[must_use] 3611 pub fn has_utf16_option(&self) -> bool { 3612 self.options 3613 .iter() 3614 .any(|x| matches!(x, BitArrayOption::Utf16 { .. })) 3615 } 3616 3617 #[must_use] 3618 pub fn has_utf32_option(&self) -> bool { 3619 self.options 3620 .iter() 3621 .any(|x| matches!(x, BitArrayOption::Utf32 { .. })) 3622 } 3623 3624 pub fn endianness(&self) -> Endianness { 3625 if self 3626 .options 3627 .iter() 3628 .any(|x| matches!(x, BitArrayOption::Little { .. })) 3629 { 3630 Endianness::Little 3631 } else { 3632 Endianness::Big 3633 } 3634 } 3635 3636 pub(crate) fn signed(&self) -> bool { 3637 self.options 3638 .iter() 3639 .any(|x| matches!(x, BitArrayOption::Signed { .. })) 3640 } 3641 3642 pub fn size(&self) -> Option<&Value> { 3643 self.options.iter().find_map(|x| match x { 3644 BitArrayOption::Size { value, .. } => Some(value.as_ref()), 3645 BitArrayOption::Bytes { .. } 3646 | BitArrayOption::Int { .. } 3647 | BitArrayOption::Float { .. } 3648 | BitArrayOption::Bits { .. } 3649 | BitArrayOption::Utf8 { .. } 3650 | BitArrayOption::Utf16 { .. } 3651 | BitArrayOption::Utf32 { .. } 3652 | BitArrayOption::Utf8Codepoint { .. } 3653 | BitArrayOption::Utf16Codepoint { .. } 3654 | BitArrayOption::Utf32Codepoint { .. } 3655 | BitArrayOption::Signed { .. } 3656 | BitArrayOption::Unsigned { .. } 3657 | BitArrayOption::Big { .. } 3658 | BitArrayOption::Little { .. } 3659 | BitArrayOption::Native { .. } 3660 | BitArrayOption::Unit { .. } => None, 3661 }) 3662 } 3663 3664 /// Returns the unit of `size` in the bit array segment. The `unit` option 3665 /// overrides the `bytes` option, so if a segment has both, the unit is what 3666 /// is specified in `unit`, not 8. 3667 pub fn unit(&self) -> u8 { 3668 let mut has_bytes_option = false; 3669 3670 for option in self.options.iter() { 3671 match option { 3672 BitArrayOption::Unit { value, .. } => return *value, 3673 BitArrayOption::Bytes { .. } => has_bytes_option = true, 3674 BitArrayOption::Int { .. } 3675 | BitArrayOption::Float { .. } 3676 | BitArrayOption::Bits { .. } 3677 | BitArrayOption::Utf8 { .. } 3678 | BitArrayOption::Utf16 { .. } 3679 | BitArrayOption::Utf32 { .. } 3680 | BitArrayOption::Utf8Codepoint { .. } 3681 | BitArrayOption::Utf16Codepoint { .. } 3682 | BitArrayOption::Utf32Codepoint { .. } 3683 | BitArrayOption::Signed { .. } 3684 | BitArrayOption::Unsigned { .. } 3685 | BitArrayOption::Big { .. } 3686 | BitArrayOption::Little { .. } 3687 | BitArrayOption::Native { .. } 3688 | BitArrayOption::Size { .. } => {} 3689 } 3690 } 3691 3692 if has_bytes_option { 8 } else { 1 } 3693 } 3694 3695 pub(crate) fn has_bits_option(&self) -> bool { 3696 self.options 3697 .iter() 3698 .any(|option| matches!(option, BitArrayOption::Bits { .. })) 3699 } 3700 3701 pub(crate) fn has_bytes_option(&self) -> bool { 3702 self.options 3703 .iter() 3704 .any(|option| matches!(option, BitArrayOption::Bytes { .. })) 3705 } 3706} 3707 3708impl<Value, Type> BitArraySegment<Value, Type> { 3709 #[must_use] 3710 pub(crate) fn has_type_option(&self) -> bool { 3711 self.options.iter().any(|option| option.is_type_option()) 3712 } 3713} 3714 3715impl TypedExprBitArraySegment { 3716 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 3717 self.value.find_node(byte_index) 3718 } 3719 3720 fn syntactically_eq(&self, other: &Self) -> bool { 3721 self.value.syntactically_eq(&other.value) 3722 && pairwise_all(&self.options, &other.options, |(option, other_option)| { 3723 option.syntactically_eq(other_option, |size, other_size| { 3724 size.syntactically_eq(other_size) 3725 }) 3726 }) 3727 } 3728} 3729 3730impl<TypedValue> BitArraySegment<TypedValue, Arc<Type>> 3731where 3732 TypedValue: HasType + HasLocation + Clone + bit_array::GetLiteralValue, 3733{ 3734 pub fn check_for_truncated_value(&self) -> Option<BitArraySegmentTruncation> { 3735 // Both the size and the value must be two compile-time known constants. 3736 let segment_bits = self.bits_size()?.to_i64()?; 3737 let literal_value = self.value.as_int_literal()?; 3738 if segment_bits <= 0 { 3739 return None; 3740 } 3741 3742 let safe_range = match literal_value.sign() { 3743 Sign::NoSign => return None, 3744 Sign::Minus => { 3745 (-(BigInt::one() << (segment_bits - 1))) 3746 ..((BigInt::one() << (segment_bits - 1)) - 1) 3747 } 3748 Sign::Plus => BigInt::ZERO..(BigInt::one() << segment_bits), 3749 }; 3750 3751 if !safe_range.contains(&literal_value) { 3752 Some(BitArraySegmentTruncation { 3753 truncated_value: literal_value.clone(), 3754 truncated_into: truncate(&literal_value, segment_bits), 3755 value_location: self.value.location(), 3756 segment_bits, 3757 }) 3758 } else { 3759 None 3760 } 3761 } 3762 3763 /// If the segment size is a compile-time known constant this returns the 3764 /// segment size in bits, taking the segment's unit into consideration! 3765 /// 3766 fn bits_size(&self) -> Option<BigInt> { 3767 let size = match self.size() { 3768 None if self.type_.is_int() => 8.into(), 3769 None => 64.into(), 3770 Some(value) => value.as_int_literal()?, 3771 }; 3772 3773 let unit = self.unit(); 3774 Some(size * unit) 3775 } 3776} 3777 3778/// As Björn said, when a value is smaller than the segment's size it will be 3779/// truncated, only taking the first `n` bits: 3780/// 3781/// > It will be silently truncated. In general, when storing value an integer 3782/// > `I` into a segment of size `N`, the actual value stored will be 3783/// > `I band ((1 bsl N) - 1)`. 3784/// 3785/// <https://erlangforums.com/t/what-happens-when-a-bit-array-segment-size-is-smaller-than-its-value/4650/2?u=giacomocavalieri> 3786/// 3787/// Thank you Björn! 3788/// 3789fn truncate(literal_value: &BigInt, segment_bits: i64) -> BigInt { 3790 literal_value & ((BigInt::one() << segment_bits) - BigInt::one()) 3791} 3792 3793#[derive(serde::Deserialize, serde::Serialize, Eq, PartialEq, Clone, Debug)] 3794pub struct BitArraySegmentTruncation { 3795 /// The value that would end up being truncated. 3796 pub truncated_value: BigInt, 3797 /// What the value would be truncated into. 3798 pub truncated_into: BigInt, 3799 /// The span of the segment's value being truncated. 3800 pub value_location: SrcSpan, 3801 /// The size of the segment. 3802 pub segment_bits: i64, 3803} 3804 3805impl TypedPatternBitArraySegment { 3806 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 3807 self.value.find_node(byte_index).or_else(|| { 3808 self.options 3809 .iter() 3810 .find_map(|option| option.find_node(byte_index)) 3811 }) 3812 } 3813 3814 fn syntactically_eq(&self, other: &Self) -> bool { 3815 self.value.syntactically_eq(&other.value) 3816 && pairwise_all(&self.options, &other.options, |(option, other_option)| { 3817 option.syntactically_eq(other_option, |size, other_size| { 3818 size.syntactically_eq(other_size) 3819 }) 3820 }) 3821 } 3822} 3823 3824impl TypedConstantBitArraySegment { 3825 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 3826 self.value.find_node(byte_index).or_else(|| { 3827 self.options 3828 .iter() 3829 .find_map(|option| option.find_node(byte_index)) 3830 }) 3831 } 3832 3833 fn syntactically_eq(&self, other: &Self) -> bool { 3834 self.value.syntactically_eq(&other.value) 3835 && pairwise_all(&self.options, &other.options, |(option, other_option)| { 3836 option.syntactically_eq(other_option, |size, other_size| { 3837 size.syntactically_eq(other_size) 3838 }) 3839 }) 3840 } 3841} 3842 3843pub type TypedConstantBitArraySegmentOption = BitArrayOption<TypedConstant>; 3844 3845#[derive(Debug, PartialEq, Eq, Clone, serde::Serialize, serde::Deserialize)] 3846pub enum BitArrayOption<Value> { 3847 Bytes { 3848 location: SrcSpan, 3849 }, 3850 3851 Int { 3852 location: SrcSpan, 3853 }, 3854 3855 Float { 3856 location: SrcSpan, 3857 }, 3858 3859 Bits { 3860 location: SrcSpan, 3861 }, 3862 3863 Utf8 { 3864 location: SrcSpan, 3865 }, 3866 3867 Utf16 { 3868 location: SrcSpan, 3869 }, 3870 3871 Utf32 { 3872 location: SrcSpan, 3873 }, 3874 3875 Utf8Codepoint { 3876 location: SrcSpan, 3877 }, 3878 3879 Utf16Codepoint { 3880 location: SrcSpan, 3881 }, 3882 3883 Utf32Codepoint { 3884 location: SrcSpan, 3885 }, 3886 3887 Signed { 3888 location: SrcSpan, 3889 }, 3890 3891 Unsigned { 3892 location: SrcSpan, 3893 }, 3894 3895 Big { 3896 location: SrcSpan, 3897 }, 3898 3899 Little { 3900 location: SrcSpan, 3901 }, 3902 3903 Native { 3904 location: SrcSpan, 3905 }, 3906 3907 Size { 3908 location: SrcSpan, 3909 value: Box<Value>, 3910 short_form: bool, 3911 }, 3912 3913 Unit { 3914 location: SrcSpan, 3915 value: u8, 3916 }, 3917} 3918 3919impl<A> BitArrayOption<A> { 3920 pub fn value(&self) -> Option<&A> { 3921 match self { 3922 BitArrayOption::Size { value, .. } => Some(value), 3923 BitArrayOption::Bytes { .. } 3924 | BitArrayOption::Int { .. } 3925 | BitArrayOption::Float { .. } 3926 | BitArrayOption::Bits { .. } 3927 | BitArrayOption::Utf8 { .. } 3928 | BitArrayOption::Utf16 { .. } 3929 | BitArrayOption::Utf32 { .. } 3930 | BitArrayOption::Utf8Codepoint { .. } 3931 | BitArrayOption::Utf16Codepoint { .. } 3932 | BitArrayOption::Utf32Codepoint { .. } 3933 | BitArrayOption::Signed { .. } 3934 | BitArrayOption::Unsigned { .. } 3935 | BitArrayOption::Big { .. } 3936 | BitArrayOption::Little { .. } 3937 | BitArrayOption::Native { .. } 3938 | BitArrayOption::Unit { .. } => None, 3939 } 3940 } 3941 3942 pub fn location(&self) -> SrcSpan { 3943 match self { 3944 BitArrayOption::Bytes { location } 3945 | BitArrayOption::Int { location } 3946 | BitArrayOption::Float { location } 3947 | BitArrayOption::Bits { location } 3948 | BitArrayOption::Utf8 { location } 3949 | BitArrayOption::Utf16 { location } 3950 | BitArrayOption::Utf32 { location } 3951 | BitArrayOption::Utf8Codepoint { location } 3952 | BitArrayOption::Utf16Codepoint { location } 3953 | BitArrayOption::Utf32Codepoint { location } 3954 | BitArrayOption::Signed { location } 3955 | BitArrayOption::Unsigned { location } 3956 | BitArrayOption::Big { location } 3957 | BitArrayOption::Little { location } 3958 | BitArrayOption::Native { location } 3959 | BitArrayOption::Size { location, .. } 3960 | BitArrayOption::Unit { location, .. } => *location, 3961 } 3962 } 3963 3964 pub fn label(&self) -> EcoString { 3965 match self { 3966 BitArrayOption::Bytes { .. } => "bytes".into(), 3967 BitArrayOption::Int { .. } => "int".into(), 3968 BitArrayOption::Float { .. } => "float".into(), 3969 BitArrayOption::Bits { .. } => "bits".into(), 3970 BitArrayOption::Utf8 { .. } => "utf8".into(), 3971 BitArrayOption::Utf16 { .. } => "utf16".into(), 3972 BitArrayOption::Utf32 { .. } => "utf32".into(), 3973 BitArrayOption::Utf8Codepoint { .. } => "utf8_codepoint".into(), 3974 BitArrayOption::Utf16Codepoint { .. } => "utf16_codepoint".into(), 3975 BitArrayOption::Utf32Codepoint { .. } => "utf32_codepoint".into(), 3976 BitArrayOption::Signed { .. } => "signed".into(), 3977 BitArrayOption::Unsigned { .. } => "unsigned".into(), 3978 BitArrayOption::Big { .. } => "big".into(), 3979 BitArrayOption::Little { .. } => "little".into(), 3980 BitArrayOption::Native { .. } => "native".into(), 3981 BitArrayOption::Size { .. } => "size".into(), 3982 BitArrayOption::Unit { .. } => "unit".into(), 3983 } 3984 } 3985 3986 fn is_type_option(&self) -> bool { 3987 match self { 3988 BitArrayOption::Bytes { .. } 3989 | BitArrayOption::Int { .. } 3990 | BitArrayOption::Float { .. } 3991 | BitArrayOption::Bits { .. } 3992 | BitArrayOption::Utf8 { .. } 3993 | BitArrayOption::Utf16 { .. } 3994 | BitArrayOption::Utf32 { .. } 3995 | BitArrayOption::Utf8Codepoint { .. } 3996 | BitArrayOption::Utf16Codepoint { .. } 3997 | BitArrayOption::Utf32Codepoint { .. } => true, 3998 3999 BitArrayOption::Signed { .. } 4000 | BitArrayOption::Unsigned { .. } 4001 | BitArrayOption::Big { .. } 4002 | BitArrayOption::Little { .. } 4003 | BitArrayOption::Native { .. } 4004 | BitArrayOption::Size { .. } 4005 | BitArrayOption::Unit { .. } => false, 4006 } 4007 } 4008 4009 fn syntactically_eq(&self, other: &Self, compare_sizes: impl Fn(&A, &A) -> bool) -> bool { 4010 match (self, other) { 4011 (BitArrayOption::Bytes { .. }, BitArrayOption::Bytes { .. }) => true, 4012 (BitArrayOption::Bytes { .. }, _) => false, 4013 4014 (BitArrayOption::Int { .. }, BitArrayOption::Int { .. }) => true, 4015 (BitArrayOption::Int { .. }, _) => false, 4016 4017 (BitArrayOption::Float { .. }, BitArrayOption::Float { .. }) => true, 4018 (BitArrayOption::Float { .. }, _) => false, 4019 4020 (BitArrayOption::Bits { .. }, BitArrayOption::Bits { .. }) => true, 4021 (BitArrayOption::Bits { .. }, _) => false, 4022 4023 (BitArrayOption::Utf8 { .. }, BitArrayOption::Utf8 { .. }) => true, 4024 (BitArrayOption::Utf8 { .. }, _) => false, 4025 4026 (BitArrayOption::Utf16 { .. }, BitArrayOption::Utf16 { .. }) => true, 4027 (BitArrayOption::Utf16 { .. }, _) => false, 4028 4029 (BitArrayOption::Utf32 { .. }, BitArrayOption::Utf32 { .. }) => true, 4030 (BitArrayOption::Utf32 { .. }, _) => false, 4031 4032 (BitArrayOption::Utf8Codepoint { .. }, BitArrayOption::Utf8Codepoint { .. }) => true, 4033 (BitArrayOption::Utf8Codepoint { .. }, _) => false, 4034 4035 (BitArrayOption::Utf16Codepoint { .. }, BitArrayOption::Utf16Codepoint { .. }) => true, 4036 (BitArrayOption::Utf16Codepoint { .. }, _) => false, 4037 4038 (BitArrayOption::Utf32Codepoint { .. }, BitArrayOption::Utf32Codepoint { .. }) => true, 4039 (BitArrayOption::Utf32Codepoint { .. }, _) => false, 4040 4041 (BitArrayOption::Signed { .. }, BitArrayOption::Signed { .. }) => true, 4042 (BitArrayOption::Signed { .. }, _) => false, 4043 4044 (BitArrayOption::Unsigned { .. }, BitArrayOption::Unsigned { .. }) => true, 4045 (BitArrayOption::Unsigned { .. }, _) => false, 4046 4047 (BitArrayOption::Big { .. }, BitArrayOption::Big { .. }) => true, 4048 (BitArrayOption::Big { .. }, _) => false, 4049 4050 (BitArrayOption::Little { .. }, BitArrayOption::Little { .. }) => true, 4051 (BitArrayOption::Little { .. }, _) => false, 4052 4053 (BitArrayOption::Native { .. }, BitArrayOption::Native { .. }) => true, 4054 (BitArrayOption::Native { .. }, _) => false, 4055 4056 ( 4057 BitArrayOption::Unit { value, .. }, 4058 BitArrayOption::Unit { 4059 value: other_value, .. 4060 }, 4061 ) => value == other_value, 4062 (BitArrayOption::Unit { .. }, _) => false, 4063 4064 ( 4065 BitArrayOption::Size { 4066 value, short_form, .. 4067 }, 4068 BitArrayOption::Size { 4069 value: other_value, 4070 short_form: other_short_form, 4071 .. 4072 }, 4073 ) => short_form == other_short_form && compare_sizes(value, other_value), 4074 (BitArrayOption::Size { .. }, _) => false, 4075 } 4076 } 4077} 4078 4079impl BitArrayOption<TypedConstant> { 4080 fn referenced_variables(&self) -> im::HashSet<&EcoString> { 4081 match self { 4082 BitArrayOption::Bytes { .. } 4083 | BitArrayOption::Int { .. } 4084 | BitArrayOption::Float { .. } 4085 | BitArrayOption::Bits { .. } 4086 | BitArrayOption::Utf8 { .. } 4087 | BitArrayOption::Utf16 { .. } 4088 | BitArrayOption::Utf32 { .. } 4089 | BitArrayOption::Utf8Codepoint { .. } 4090 | BitArrayOption::Utf16Codepoint { .. } 4091 | BitArrayOption::Utf32Codepoint { .. } 4092 | BitArrayOption::Signed { .. } 4093 | BitArrayOption::Unsigned { .. } 4094 | BitArrayOption::Big { .. } 4095 | BitArrayOption::Little { .. } 4096 | BitArrayOption::Unit { .. } 4097 | BitArrayOption::Native { .. } => im::hashset![], 4098 4099 BitArrayOption::Size { value, .. } => value.referenced_variables(), 4100 } 4101 } 4102} 4103 4104impl BitArrayOption<TypedPattern> { 4105 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4106 match self { 4107 BitArrayOption::Bytes { .. } 4108 | BitArrayOption::Int { .. } 4109 | BitArrayOption::Float { .. } 4110 | BitArrayOption::Bits { .. } 4111 | BitArrayOption::Utf8 { .. } 4112 | BitArrayOption::Utf16 { .. } 4113 | BitArrayOption::Utf32 { .. } 4114 | BitArrayOption::Utf8Codepoint { .. } 4115 | BitArrayOption::Utf16Codepoint { .. } 4116 | BitArrayOption::Utf32Codepoint { .. } 4117 | BitArrayOption::Signed { .. } 4118 | BitArrayOption::Unsigned { .. } 4119 | BitArrayOption::Big { .. } 4120 | BitArrayOption::Little { .. } 4121 | BitArrayOption::Native { .. } 4122 | BitArrayOption::Unit { .. } => None, 4123 BitArrayOption::Size { value, .. } => value.find_node(byte_index), 4124 } 4125 } 4126} 4127 4128impl BitArrayOption<TypedConstant> { 4129 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4130 match self { 4131 BitArrayOption::Bytes { .. } 4132 | BitArrayOption::Int { .. } 4133 | BitArrayOption::Float { .. } 4134 | BitArrayOption::Bits { .. } 4135 | BitArrayOption::Utf8 { .. } 4136 | BitArrayOption::Utf16 { .. } 4137 | BitArrayOption::Utf32 { .. } 4138 | BitArrayOption::Utf8Codepoint { .. } 4139 | BitArrayOption::Utf16Codepoint { .. } 4140 | BitArrayOption::Utf32Codepoint { .. } 4141 | BitArrayOption::Signed { .. } 4142 | BitArrayOption::Unsigned { .. } 4143 | BitArrayOption::Big { .. } 4144 | BitArrayOption::Little { .. } 4145 | BitArrayOption::Native { .. } 4146 | BitArrayOption::Unit { .. } => None, 4147 BitArrayOption::Size { value, .. } => value.find_node(byte_index), 4148 } 4149 } 4150} 4151 4152#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] 4153pub enum TodoKind { 4154 Keyword, 4155 EmptyFunction { function_location: SrcSpan }, 4156 IncompleteUse, 4157 EmptyBlock, 4158} 4159 4160#[derive(Debug, Default)] 4161pub struct GroupedDefinitions { 4162 pub functions: Vec<UntypedFunction>, 4163 pub constants: Vec<UntypedModuleConstant>, 4164 pub custom_types: Vec<UntypedCustomType>, 4165 pub imports: Vec<UntypedImport>, 4166 pub type_aliases: Vec<UntypedTypeAlias>, 4167} 4168 4169impl GroupedDefinitions { 4170 pub fn new(definitions: impl IntoIterator<Item = UntypedDefinition>) -> Self { 4171 let mut this = Self::default(); 4172 4173 for definition in definitions { 4174 this.add(definition) 4175 } 4176 4177 this 4178 } 4179 4180 pub fn len(&self) -> usize { 4181 let Self { 4182 custom_types, 4183 functions, 4184 constants, 4185 imports, 4186 type_aliases, 4187 } = self; 4188 functions.len() + constants.len() + imports.len() + custom_types.len() + type_aliases.len() 4189 } 4190 4191 fn add(&mut self, statement: UntypedDefinition) { 4192 match statement { 4193 Definition::Import(import) => self.imports.push(import), 4194 Definition::Function(function) => self.functions.push(function), 4195 Definition::TypeAlias(type_alias) => self.type_aliases.push(type_alias), 4196 Definition::CustomType(custom_type) => self.custom_types.push(custom_type), 4197 Definition::ModuleConstant(constant) => self.constants.push(constant), 4198 } 4199 } 4200} 4201 4202/// A statement with in a function body. 4203#[derive(Debug, Clone, PartialEq, Eq)] 4204pub enum Statement<TypeT, ExpressionT> { 4205 /// A bare expression that is not assigned to any variable. 4206 Expression(ExpressionT), 4207 /// Assigning an expression to variables using a pattern. 4208 Assignment(Box<Assignment<TypeT, ExpressionT>>), 4209 /// A `use` expression. 4210 Use(Use<TypeT, ExpressionT>), 4211 /// A bool assertion. 4212 Assert(Assert<ExpressionT>), 4213} 4214 4215pub type UntypedUse = Use<(), UntypedExpr>; 4216pub type TypedUse = Use<Arc<Type>, TypedExpr>; 4217 4218#[derive(Debug, Clone, PartialEq, Eq)] 4219pub struct Use<TypeT, ExpressionT> { 4220 /// In an untyped use this is the expression with the untyped code of the 4221 /// callback function. 4222 /// 4223 /// In a typed use this is the typed function call the use expression 4224 /// desugars to. 4225 /// 4226 pub call: Box<ExpressionT>, 4227 4228 /// This is the location of the whole use line, starting from the `use` 4229 /// keyword and ending with the function call on the right hand side of 4230 /// `<-`. 4231 /// 4232 /// ```gleam 4233 /// use a <- result.try(result) 4234 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4235 /// ``` 4236 /// 4237 pub location: SrcSpan, 4238 4239 /// This is the location of the expression on the right hand side of the use 4240 /// arrow. 4241 /// 4242 /// ```gleam 4243 /// use a <- result.try(result) 4244 /// ^^^^^^^^^^^^^^^^^^ 4245 /// ``` 4246 /// 4247 pub right_hand_side_location: SrcSpan, 4248 4249 /// This is the SrcSpan of the patterns you find on the left hand side of 4250 /// `<-` in a use expression. 4251 /// 4252 /// ```gleam 4253 /// use pattern1, pattern2 <- todo 4254 /// ^^^^^^^^^^^^^^^^^^ 4255 /// ``` 4256 /// 4257 /// In case there's no patterns it will be corresponding to the SrcSpan of 4258 /// the `use` keyword itself. 4259 /// 4260 pub assignments_location: SrcSpan, 4261 4262 /// The patterns on the left hand side of `<-` in a use expression. 4263 /// 4264 pub assignments: Vec<UseAssignment<TypeT>>, 4265} 4266 4267pub type UntypedUseAssignment = UseAssignment<()>; 4268pub type TypedUseAssignment = UseAssignment<Arc<Type>>; 4269 4270#[derive(Debug, Clone, PartialEq, Eq)] 4271pub struct UseAssignment<TypeT> { 4272 pub location: SrcSpan, 4273 pub pattern: Pattern<TypeT>, 4274 pub annotation: Option<TypeAst>, 4275} 4276 4277impl TypedUse { 4278 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4279 for assignment in self.assignments.iter() { 4280 if let Some(found) = assignment.pattern.find_node(byte_index) { 4281 return Some(found); 4282 } 4283 if let Some(found) = assignment 4284 .annotation 4285 .as_ref() 4286 .and_then(|annotation| annotation.find_node(byte_index, assignment.pattern.type_())) 4287 { 4288 return Some(found); 4289 } 4290 } 4291 self.call.find_node(byte_index) 4292 } 4293 4294 pub fn callback_arguments(&self) -> Option<&Vec<TypedArg>> { 4295 let TypedExpr::Call { arguments, .. } = self.call.as_ref() else { 4296 return None; 4297 }; 4298 let callback = arguments.iter().last()?; 4299 let TypedExpr::Fn { arguments, .. } = &callback.value else { 4300 // The expression might be invalid so we have to return a None here 4301 return None; 4302 }; 4303 Some(arguments) 4304 } 4305} 4306 4307pub type TypedStatement = Statement<Arc<Type>, TypedExpr>; 4308pub type UntypedStatement = Statement<(), UntypedExpr>; 4309 4310impl<T, E> Statement<T, E> { 4311 /// Returns `true` if the statement is [`Expression`]. 4312 /// 4313 /// [`Expression`]: Statement::Expression 4314 #[must_use] 4315 pub fn is_expression(&self) -> bool { 4316 matches!(self, Self::Expression(..)) 4317 } 4318 4319 #[must_use] 4320 pub fn is_use(&self) -> bool { 4321 matches!(self, Self::Use(_)) 4322 } 4323} 4324 4325impl UntypedStatement { 4326 pub fn location(&self) -> SrcSpan { 4327 match self { 4328 Statement::Expression(expression) => expression.location(), 4329 Statement::Assignment(assignment) => assignment.location, 4330 Statement::Use(use_) => use_.location.merge(&use_.call.location()), 4331 Statement::Assert(assert) => assert.location, 4332 } 4333 } 4334 4335 pub fn start_byte_index(&self) -> u32 { 4336 match self { 4337 Statement::Expression(expression) => expression.start_byte_index(), 4338 Statement::Assignment(assignment) => assignment.location.start, 4339 Statement::Use(use_) => use_.location.start, 4340 Statement::Assert(assert) => assert.location.start, 4341 } 4342 } 4343} 4344 4345impl TypedStatement { 4346 pub fn is_println(&self) -> bool { 4347 match self { 4348 Statement::Expression(e) => e.is_println(), 4349 Statement::Assignment(_) => false, 4350 Statement::Use(_) => false, 4351 Statement::Assert(_) => false, 4352 } 4353 } 4354 4355 pub fn location(&self) -> SrcSpan { 4356 match self { 4357 Statement::Expression(expression) => expression.location(), 4358 Statement::Assignment(assignment) => assignment.location, 4359 // A use statement covers the entire block: `use_.location` covers 4360 // just the use's first line and not what comes after it. 4361 Statement::Use(use_) => use_.location.merge(&use_.call.location()), 4362 Statement::Assert(assert) => assert.location, 4363 } 4364 } 4365 4366 /// Returns the location of the last element of a statement. This means that 4367 /// if the statement is a use you'll get the location of the last item at 4368 /// the end of its block. 4369 pub fn last_location(&self) -> SrcSpan { 4370 match self { 4371 Statement::Expression(expression) => expression.last_location(), 4372 Statement::Assignment(assignment) => assignment.value.last_location(), 4373 Statement::Use(use_) => use_.call.last_location(), 4374 Statement::Assert(assert) => assert.value.last_location(), 4375 } 4376 } 4377 4378 pub fn type_(&self) -> Arc<Type> { 4379 match self { 4380 Statement::Expression(expression) => expression.type_(), 4381 Statement::Assignment(assignment) => assignment.type_(), 4382 Statement::Use(use_) => use_.call.type_(), 4383 Statement::Assert(_) => nil(), 4384 } 4385 } 4386 4387 pub fn definition_location(&self) -> Option<DefinitionLocation> { 4388 match self { 4389 Statement::Expression(expression) => expression.definition_location(), 4390 Statement::Assignment(_) => None, 4391 Statement::Use(use_) => use_.call.definition_location(), 4392 Statement::Assert(_) => None, 4393 } 4394 } 4395 4396 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4397 match self { 4398 Statement::Use(use_) => use_.find_node(byte_index), 4399 Statement::Expression(expression) => expression.find_node(byte_index), 4400 Statement::Assignment(assignment) => assignment.find_node(byte_index).or_else(|| { 4401 if assignment.location.contains(byte_index) { 4402 Some(Located::Statement(self)) 4403 } else { 4404 None 4405 } 4406 }), 4407 Statement::Assert(assert) => assert.find_node(byte_index).or_else(|| { 4408 if assert.location.contains(byte_index) { 4409 Some(Located::Statement(self)) 4410 } else { 4411 None 4412 } 4413 }), 4414 } 4415 } 4416 4417 pub fn find_statement(&self, byte_index: u32) -> Option<&TypedStatement> { 4418 match self { 4419 Statement::Use(use_) => use_.call.find_statement(byte_index), 4420 Statement::Expression(expression) => expression.find_statement(byte_index), 4421 Statement::Assignment(assignment) => { 4422 assignment.value.find_statement(byte_index).or_else(|| { 4423 if assignment.location.contains(byte_index) { 4424 Some(self) 4425 } else { 4426 None 4427 } 4428 }) 4429 } 4430 Statement::Assert(assert) => assert.value.find_statement(byte_index).or_else(|| { 4431 if assert.location.contains(byte_index) { 4432 Some(self) 4433 } else { 4434 None 4435 } 4436 }), 4437 } 4438 } 4439 4440 pub fn type_defining_location(&self) -> SrcSpan { 4441 match self { 4442 Statement::Expression(expression) => expression.type_defining_location(), 4443 Statement::Assignment(assignment) => assignment.location, 4444 Statement::Use(use_) => use_.location, 4445 Statement::Assert(assert) => assert.location, 4446 } 4447 } 4448 4449 fn is_pure_value_constructor(&self) -> bool { 4450 match self { 4451 Statement::Expression(expression) => expression.is_pure_value_constructor(), 4452 Statement::Assignment(assignment) => { 4453 // A let assert is not considered a pure value constructor 4454 // as it could crash the program! 4455 !assignment.kind.is_assert() && assignment.value.is_pure_value_constructor() 4456 } 4457 Statement::Use(Use { call, .. }) => call.is_pure_value_constructor(), 4458 // Assert statements by definition are not pure 4459 Statement::Assert(_) => false, 4460 } 4461 } 4462 4463 fn syntactically_eq(&self, other: &Self) -> bool { 4464 match (self, other) { 4465 (Statement::Expression(one), Statement::Expression(other)) => { 4466 one.syntactically_eq(other) 4467 } 4468 (Statement::Expression(_), _) => false, 4469 4470 (Statement::Assignment(one), Statement::Assignment(other)) => { 4471 one.pattern.syntactically_eq(&other.pattern) 4472 && one.value.syntactically_eq(&other.value) 4473 } 4474 (Statement::Assignment(_), _) => false, 4475 4476 (Statement::Use(one), Statement::Use(other)) => one.call.syntactically_eq(&other.call), 4477 (Statement::Use(_), _) => false, 4478 4479 (Statement::Assert(one), Statement::Assert(other)) => { 4480 let messages_are_equal = match (&one.message, &other.message) { 4481 (None, None) => true, 4482 (None, Some(_)) | (Some(_), None) => false, 4483 (Some(one), Some(other)) => one.syntactically_eq(other), 4484 }; 4485 messages_are_equal && one.value.syntactically_eq(&other.value) 4486 } 4487 (Statement::Assert(_), _) => false, 4488 } 4489 } 4490} 4491 4492#[derive(Debug, Clone, PartialEq, Eq)] 4493pub struct Assignment<TypeT, ExpressionT> { 4494 pub location: SrcSpan, 4495 pub value: ExpressionT, 4496 pub pattern: Pattern<TypeT>, 4497 pub kind: AssignmentKind<ExpressionT>, 4498 pub compiled_case: CompiledCase, 4499 /// This will be true for assignments that are automatically generated by 4500 /// the compiler. 4501 pub annotation: Option<TypeAst>, 4502} 4503 4504pub type TypedAssignment = Assignment<Arc<Type>, TypedExpr>; 4505pub type UntypedAssignment = Assignment<(), UntypedExpr>; 4506 4507impl TypedAssignment { 4508 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4509 if let Some(annotation) = &self.annotation 4510 && let Some(l) = annotation.find_node(byte_index, self.pattern.type_()) 4511 { 4512 return Some(l); 4513 } 4514 self.pattern 4515 .find_node(byte_index) 4516 .or_else(|| self.value.find_node(byte_index)) 4517 } 4518 4519 pub fn type_(&self) -> Arc<Type> { 4520 self.value.type_() 4521 } 4522} 4523 4524pub type TypedAssert = Assert<TypedExpr>; 4525pub type UntypedAssert = Assert<UntypedExpr>; 4526 4527#[derive(Debug, Clone, PartialEq, Eq)] 4528pub struct Assert<Expression> { 4529 pub location: SrcSpan, 4530 pub value: Expression, 4531 pub message: Option<Expression>, 4532} 4533 4534impl TypedAssert { 4535 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4536 if let Some(found) = self.value.find_node(byte_index) { 4537 return Some(found); 4538 } 4539 if let Some(message) = &self.message 4540 && let Some(found) = message.find_node(byte_index) 4541 { 4542 return Some(found); 4543 } 4544 None 4545 } 4546} 4547 4548/// A pipeline is desugared to a series of assignments: 4549/// 4550/// ```gleam 4551/// wibble |> wobble |> woo 4552/// ``` 4553/// 4554/// Becomes: 4555/// 4556/// ```erl 4557/// Pipe1 = wibble 4558/// Pipe2 = wobble(Pipe1) 4559/// woo(Pipe2) 4560/// ``` 4561/// 4562/// This represents one of such assignments once the pipeline has been desugared 4563/// and each step has been typed. 4564/// 4565/// > We're not using a more general `TypedAssignment` node since that has much 4566/// > more informations to carry around. This one is limited since we know it 4567/// > will always be in the form `VarName = <Expr>`, with no patterns on the 4568/// > left hand side of the assignment. 4569/// > Being more constrained simplifies code generation for pipelines! 4570/// 4571#[derive(Debug, Clone, PartialEq, Eq)] 4572pub struct TypedPipelineAssignment { 4573 /// This is the location of the corresponding pipeline step. 4574 /// 4575 /// Take this pipeline: 4576 /// 4577 /// ```gleam 4578 /// wibble |> wobble |> woo 4579 /// ``` 4580 /// 4581 /// It's made of two steps and a final expression: 4582 /// 4583 /// ```gleam 4584 /// let step_0 = wibble 4585 /// let step_1 = wobble(step_0) 4586 /// woo(step_1) 4587 /// ``` 4588 /// 4589 /// The locations of each step would be the following: 4590 /// 4591 /// ```gleam 4592 /// wibble |> wobble |> woo 4593 /// ^^^^^^ location of first step 4594 /// ^^^^^^ location of second step 4595 /// ``` 4596 /// 4597 pub location: SrcSpan, 4598 pub name: EcoString, 4599 pub value: Box<TypedExpr>, 4600} 4601 4602impl TypedPipelineAssignment { 4603 pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> { 4604 self.value.find_node(byte_index) 4605 } 4606 4607 pub fn find_statement(&self, byte_index: u32) -> Option<&TypedStatement> { 4608 self.value.find_statement(byte_index) 4609 } 4610 4611 pub fn type_(&self) -> Arc<Type> { 4612 self.value.type_() 4613 } 4614} 4615 4616/// The kind of desugaring that might take place when rewriting a pipeline to 4617/// regular assignments. 4618/// 4619#[derive(Debug, Clone, Copy, PartialEq, Eq)] 4620pub enum PipelineAssignmentKind { 4621 /// In case `a |> b(c)` is desugared to `b(a, c)`. 4622 FirstArgument { 4623 /// The location of the second argument of the call, in case there's any: 4624 /// - `a |> b(c, d)`: here it's `Some` wrapping the location of `c`. 4625 /// - `a |> b()`: here it's `None`. 4626 second_argument: Option<SrcSpan>, 4627 }, 4628 4629 /// In case there's an explicit hole and `a |> b(_, c)` is desugared to 4630 /// `b(a, c)`. 4631 Hole { hole: SrcSpan }, 4632 4633 /// In case `a |> b(c)` is desugared to `b(c)(a)` 4634 FunctionCall, 4635 4636 /// In case there's an echo in the middle of a pipeline `a |> echo` 4637 Echo, 4638}