roan_ast/ast/expr.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
use crate::{statements::Stmt, GetSpan, Token, TokenKind};
use indexmap::IndexMap;
use roan_error::TextSpan;
use std::fmt::{Display, Formatter};
/// Represents a collection of expressions as a vector.
/// Used to handle lists of expressions, such as arrays or argument lists.
#[derive(Clone, Debug, PartialEq)]
pub struct VecExpr {
/// The vector containing the expressions.
pub exprs: Vec<Expr>,
}
/// Enum that defines the possible literal types in the language.
/// Literals are constant values such as numbers, strings, and booleans.
#[derive(Clone, Debug, PartialEq)]
pub enum LiteralType {
/// An integer literal (e.g., `42`).
Int(i64),
/// A floating-point literal (e.g., `3.14`).
Float(f64),
/// A string literal (e.g., `"hello"`).
String(String),
/// A boolean literal (`true` or `false`).
Bool(bool),
/// A character literal (e.g., `'a'`).
Char(char),
/// A `null` literal representing the absence of a value.
Null,
}
/// Represents a literal expression in the AST.
/// It consists of a token and a specific literal value (e.g., integer, string).
#[derive(Clone, Debug, PartialEq)]
pub struct Literal {
/// The token representing the literal in the source code.
pub token: Token,
/// The value of the literal.
pub value: LiteralType,
}
impl Literal {
pub fn new(token: Token, value: LiteralType) -> Self {
Literal { token, value }
}
}
/// Enum representing the various binary operators in the language.
/// Binary operators are used in binary expressions (e.g., `a + b`).
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum BinOpKind {
// Arithmetic operators
/// Addition operator (`+`).
Plus,
/// Subtraction operator (`-`).
Minus,
/// Multiplication operator (`*`).
Multiply,
/// Division operator (`/`).
Divide,
/// Exponentiation operator (`**`).
Power,
/// Modulo operator (`%`).
Modulo,
// Bitwise operators
/// Bitwise AND operator (`&`).
BitwiseAnd,
/// Bitwise OR operator (`|`).
BitwiseOr,
/// Bitwise XOR operator (`^`).
BitwiseXor,
/// Bitwise shift left operator (`<<`).
ShiftLeft,
/// Bitwise shift right operator (`>>`).
ShiftRight,
// Relational operators
/// Equality operator (`==`).
Equals,
/// Less-than operator (`<`).
LessThan,
/// Less-than-or-equal operator (`<=`).
LessThanOrEqual,
/// Greater-than operator (`>`).
GreaterThan,
/// Greater-than-or-equal operator (`>=`).
GreaterThanOrEqual,
// Logical operators
/// Logical AND operator (`&&`).
And,
/// Logical OR operator (`||`).
Or,
// Equality operators (duplicated? Consider removing duplicates)
/// Equality operator (`==`).
EqualsEquals,
/// Inequality operator (`!=`).
BangEquals,
// Increment/Decrement operators
/// Increment operator (`++`).
Increment,
/// Decrement operator (`--`).
Decrement,
// Assignment operators
/// Subtraction assignment operator (`-=`).
MinusEquals,
/// Addition assignment operator (`+=`).
PlusEquals,
}
/// Represents a binary expression in the AST.
/// A binary expression consists of two operands and an operator (e.g., `a + b`).
#[derive(Debug, Clone, PartialEq)]
pub struct Binary {
/// The left operand of the binary expression.
pub left: Box<Expr>,
/// The operator used in the binary expression.
pub operator: BinOpKind,
/// The right operand of the binary expression.
pub right: Box<Expr>,
}
impl GetSpan for Binary {
/// Returns the combined source span of the left and right operands.
fn span(&self) -> TextSpan {
let left = self.left.span();
let right = self.right.span();
TextSpan::combine(vec![left, right]).unwrap()
}
}
/// Represents a unary expression in the AST.
/// Unary expressions operate on a single operand (e.g., `-a`).
#[derive(Debug, Clone, PartialEq)]
pub struct Unary {
/// The operator used in the unary expression.
pub operator: UnOperator,
/// The operand of the unary expression.
pub expr: Box<Expr>,
/// The token representing the unary operation in the source code.
pub token: Token,
}
impl GetSpan for Unary {
/// Returns the source span of the unary expression.
fn span(&self) -> TextSpan {
TextSpan::combine(vec![self.operator.token.span.clone(), self.expr.span()]).unwrap()
}
}
/// Represents a variable in the AST.
/// A variable refers to a named entity in the program.
#[derive(Debug, Clone, PartialEq)]
pub struct Variable {
/// The name of the variable.
pub ident: String,
/// The token representing the variable in the source code.
pub token: Token,
}
/// Represents a parenthesized expression in the AST.
/// Parenthesized expressions are used to override operator precedence.
#[derive(Debug, Clone, PartialEq)]
pub struct Parenthesized {
/// The expression contained within the parentheses.
pub expr: Box<Expr>,
}
/// Represents a function call in the AST.
/// It consists of a function name (callee) and a list of arguments.
#[derive(Debug, Clone, PartialEq)]
pub struct CallExpr {
/// The name of the function being called.
pub callee: String,
/// The list of arguments passed to the function.
pub args: Vec<Expr>,
/// The token representing the function call in the source code.
pub token: Token,
}
impl GetSpan for CallExpr {
/// Returns the source span of the function call expression.
fn span(&self) -> TextSpan {
// TODO: get the span of the closing parenthesis
let callee_span = self.token.span.clone();
let args_span: Vec<TextSpan> = self.args.iter().map(|arg| arg.span()).collect();
let args_span = TextSpan::combine(args_span);
let mut spans = vec![callee_span];
if args_span.is_some() {
spans.push(args_span.unwrap());
}
TextSpan::combine(spans).unwrap()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum AssignOperator {
/// Assignment operator (`=`).
Assign,
/// Addition assignment operator (`+=`).
PlusEquals,
/// Subtraction assignment operator (`-=`).
MinusEquals,
/// Multiplication assignment operator (`*=`).
MultiplyEquals,
/// Division assignment operator (`/=`).
DivideEquals,
}
impl AssignOperator {
pub fn from_token_kind(kind: TokenKind) -> Self {
match kind {
TokenKind::Equals => AssignOperator::Assign,
TokenKind::PlusEquals => AssignOperator::PlusEquals,
TokenKind::MinusEquals => AssignOperator::MinusEquals,
TokenKind::MultiplyEquals => AssignOperator::MultiplyEquals,
TokenKind::DivideEquals => AssignOperator::DivideEquals,
_ => todo!("Proper error"),
}
}
}
/// Represents an assignment expression in the AST.
/// An assignment binds a value to a variable.
#[derive(Debug, Clone, PartialEq)]
pub struct Assign {
/// The variable being assigned to.
pub left: Box<Expr>,
/// The assignment operator.
pub op: AssignOperator,
/// The value being assigned.
pub right: Box<Expr>,
}
/// Enum representing unary operator kinds (e.g., `-`, `~`).
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum UnOpKind {
/// Minus operator (`-`).
Minus,
/// Bitwise NOT operator (`~`).
BitwiseNot,
/// Logical NOT operator (`!`).
LogicalNot,
}
impl Display for UnOpKind {
/// Formats the unary operator as a string.
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
UnOpKind::Minus => write!(f, "-"),
UnOpKind::BitwiseNot => write!(f, "~"),
UnOpKind::LogicalNot => write!(f, "!"),
}
}
}
/// Represents a unary operator in the AST.
#[derive(Debug, Clone, PartialEq)]
pub struct UnOperator {
/// The specific kind of unary operator.
pub kind: UnOpKind,
/// The token representing the unary operator in the source code.
pub token: Token,
}
impl UnOperator {
/// Creates a new unary operator.
///
/// # Arguments
///
/// * `kind` - The kind of unary operator.
/// * `token` - The token representing the operator in the source code.
///
/// # Returns
///
/// A new `UnOperator` instance.
pub fn new(kind: UnOpKind, token: Token) -> Self {
UnOperator { kind, token }
}
}
/// Represents a binary operator in the AST.
#[derive(Debug, Clone)]
pub struct BinOperator {
/// The specific kind of binary operator.
pub kind: BinOpKind,
/// The token representing the binary operator in the source code.
pub token: Token,
}
impl BinOperator {
/// Creates a new binary operator.
///
/// # Arguments
///
/// * `kind` - The kind of binary operator.
/// * `token` - The token representing the operator in the source code.
///
/// # Returns
///
/// A new `BinOperator` instance.
pub fn new(kind: BinOpKind, token: Token) -> Self {
BinOperator { kind, token }
}
/// Returns the precedence of the operator.
///
/// Higher numbers indicate higher precedence.
///
/// # Returns
///
/// An unsigned 8-bit integer representing the operator's precedence.
pub fn precedence(&self) -> u8 {
match self.kind {
// Highest precedence
BinOpKind::Power => 20,
BinOpKind::Multiply | BinOpKind::Divide | BinOpKind::Modulo => 19,
BinOpKind::Plus | BinOpKind::Minus => 18,
BinOpKind::ShiftLeft | BinOpKind::ShiftRight => 17,
BinOpKind::BitwiseAnd => 16,
BinOpKind::BitwiseXor => 15,
BinOpKind::BitwiseOr => 14,
// Relational operators
BinOpKind::LessThan
| BinOpKind::LessThanOrEqual
| BinOpKind::GreaterThan
| BinOpKind::GreaterThanOrEqual => 13,
// Equality operators
BinOpKind::Equals | BinOpKind::EqualsEquals | BinOpKind::BangEquals => 12,
// Logical operators
BinOpKind::And => 11,
BinOpKind::Or => 10,
// Increment/Decrement operators
BinOpKind::Increment | BinOpKind::Decrement => 9,
// Assignment operators
BinOpKind::MinusEquals | BinOpKind::PlusEquals => 8,
}
}
/// Returns the associativity of the operator.
///
/// Operators can be either left-associative or right-associative.
///
/// # Returns
///
/// A `BinOpAssociativity` enum indicating the associativity.
pub fn associativity(&self) -> BinOpAssociativity {
match self.kind {
BinOpKind::Power => BinOpAssociativity::Right,
_ => BinOpAssociativity::Left,
}
}
}
/// Enum representing the associativity of a binary operator.
#[derive(Debug, Clone, PartialEq)]
pub enum BinOpAssociativity {
/// Left-associative operators group from the left.
Left,
/// Right-associative operators group from the right.
Right,
}
/// Spread operator for variadic arguments.
///
/// The spread operator is used to pass an array as separate arguments to a function.
#[derive(Debug, Clone, PartialEq)]
pub struct Spread {
pub token: Token,
pub expr: Box<Expr>,
}
/// Enum representing an expression in the AST.
/// Expressions include literals, binary operations, unary operations, and more.
#[derive(Clone, Debug, PartialEq)]
pub enum Expr {
/// A literal value (e.g., number, string).
Literal(Literal),
/// A binary operation (e.g., `a + b`).
Binary(Binary),
/// A unary operation (e.g., `-a`).
Unary(Unary),
/// A variable reference.
Variable(Variable),
/// A parenthesized expression to override precedence.
Parenthesized(Parenthesized),
/// A function call expression.
Call(CallExpr),
/// An assignment expression (e.g., `a = b`).
Assign(Assign),
/// A vector (list) of expressions.
Vec(VecExpr),
/// An access expression (e.g., `struct.name`, `arr[0]`, `Person::new`).
Access(AccessExpr),
/// A spread operator for variadic arguments. (e.g., `...args`)
Spread(Spread),
/// Null literal.
Null(Token),
/// Struct constructor. (e.g., `MyStruct { field: value }`)
StructConstructor(StructConstructor),
/// Then-else expression. (e.g., `if condition then value else other`)
ThenElse(ThenElse),
/// Object expression.
Object(ObjectExpr),
}
/// Represents an object expression in the AST.
///
/// An object expression is a collection of key-value pairs.
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectExpr {
/// The key-value pairs in the object.
pub fields: IndexMap<String, Expr>,
/// The token representing opening and closing braces.
pub braces: (Token, Token),
}
/// Represents a then-else expression in the AST.
///
/// A then-else expression is used to conditionally evaluate one of two expressions.
///
/// # Examples
/// ```roan
/// let value = if condition then 42 else 0
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ThenElse {
/// The condition expression.
pub condition: Box<Expr>,
/// The expression to evaluate if the condition is true.
pub then_expr: Box<Expr>,
/// The expression to evaluate if the condition is false.
pub else_expr: Box<Expr>,
/// The token representing the `then` keyword.
pub then_token: Token,
/// The token representing the `else` keyword.
pub else_token: Token,
}
impl GetSpan for ThenElse {
/// Returns the combined source span of the condition, then expression, and else expression.
fn span(&self) -> TextSpan {
let condition_span = self.condition.span();
let then_span = self.then_expr.span();
let else_span = self.else_expr.span();
TextSpan::combine(vec![condition_span, then_span, else_span]).unwrap()
}
}
/// Represents a struct constructor expression in the AST.
///
/// A struct constructor creates a new instance of a struct with the specified field values.
#[derive(Debug, Clone, PartialEq)]
pub struct StructConstructor {
/// The name of the struct being constructed.
pub name: String,
/// The field values for the struct.
pub fields: Vec<(String, Expr)>,
/// The token representing the struct constructor in the source code.
pub token: Token,
}
/// Enum representing the kind of access in an access expression.
#[derive(Debug, Clone, PartialEq)]
pub enum AccessKind {
/// Field access (e.g., `.name`).
Field(Box<Expr>),
/// Index access (e.g., `[0]`).
Index(Box<Expr>),
/// Static method access (e.g., `Person::new`).
StaticMethod(Box<Expr>),
}
/// Represents an access expression in the AST.
/// It includes accessing a field or indexing into a collection.
#[derive(Debug, Clone, PartialEq)]
pub struct AccessExpr {
/// The base expression being accessed.
pub base: Box<Expr>,
/// The kind of access (field or index).
pub access: AccessKind,
/// The token representing the access operation (e.g., `.`, `[`, `]`).
pub token: Token,
}
impl GetSpan for AccessExpr {
/// Returns the combined source span of the base expression and the access operation.
fn span(&self) -> TextSpan {
let base_span = self.base.span();
let access_span = match &self.access {
AccessKind::Field(_) => self.token.span.clone(), // Span includes the '.' and the field name
AccessKind::Index(index_expr) => {
TextSpan::combine(vec![self.token.span.clone(), index_expr.span()]).unwrap()
} // Span includes '[' , index, and ']'
AccessKind::StaticMethod(method) => {
TextSpan::combine(vec![self.token.span.clone(), method.span()]).unwrap()
}
};
TextSpan::combine(vec![base_span, access_span]).unwrap()
}
}
impl GetSpan for Expr {
/// Returns the `TextSpan` associated with the expression in the source code.
fn span(&self) -> TextSpan {
match &self {
Expr::Literal(l) => l.clone().token.span,
Expr::Binary(b) => {
let left = b.left.span();
let right = b.right.span();
TextSpan::combine(vec![left, right]).unwrap()
}
Expr::Unary(u) => u.clone().token.span,
Expr::Variable(v) => v.clone().token.span,
Expr::Parenthesized(p) => p.expr.span(),
Expr::Call(c) => c.clone().token.span,
Expr::Assign(a) => {
let left = a.left.span();
let right = a.right.span();
TextSpan::combine(vec![left, right]).unwrap()
}
Expr::Vec(v) => {
let spans: Vec<TextSpan> = v.exprs.iter().map(|e| e.span()).collect();
TextSpan::combine(spans).unwrap()
}
Expr::Access(a) => a.span(),
Expr::Spread(s) => {
TextSpan::combine(vec![s.token.span.clone(), s.expr.span()]).unwrap()
}
Expr::Null(t) => t.span.clone(),
Expr::StructConstructor(s) => s.token.span.clone(),
Expr::ThenElse(t) => t.span(),
Expr::Object(o) => {
TextSpan::combine(vec![o.braces.0.span.clone(), o.braces.1.span.clone()]).unwrap()
}
}
}
}
impl Expr {
/// Converts the expression into a statement.
///
/// # Returns
///
/// A `Stmt::Expr` variant containing the expression.
pub fn into_stmt(self) -> Stmt {
Stmt::Expr(Box::new(self))
}
/// Converts the expression into a variable.
///
/// # Panics
///
/// Panics if the expression is not a `Variable` variant.
///
/// # Returns
///
/// The `Variable` struct contained within the expression.
pub fn into_variable(self) -> Variable {
match self {
Expr::Variable(v) => v,
_ => panic!("Expected variable"),
}
}
/// Creates a new null literal expression.
pub fn new_null(token: Token) -> Self {
Expr::Null(token)
}
/// Creates a new field access expression.
///
/// # Arguments
///
/// * `base` - The base expression being accessed.
/// * `field` - The name of the field to access.
/// * `token` - The token representing the '.' operator.
///
/// # Returns
///
/// A new `Expr::Access` variant with `AccessKind::Field`.
pub fn new_field_access(base: Expr, field: Expr, token: Token) -> Self {
Expr::Access(AccessExpr {
base: Box::new(base),
access: AccessKind::Field(Box::new(field)),
token,
})
}
/// Create a new spread expression.
///
/// # Arguments
/// * `token` - The token representing the spread operator.
/// * `expr` - The expression to spread.
///
/// # Returns
/// A new `Expr::Spread` variant.
pub fn new_spread(token: Token, expr: Expr) -> Self {
Expr::Spread(Spread {
token,
expr: Box::new(expr),
})
}
/// Creates a new index access expression.
///
/// # Arguments
///
/// * `base` - The base expression being accessed.
/// * `index` - The index expression.
/// * `token` - The token representing the '[' and ']' operators.
///
/// # Returns
///
/// A new `Expr::Access` variant with `AccessKind::Index`.
pub fn new_index_access(base: Expr, index: Expr, token: Token) -> Self {
// **Added**
Expr::Access(AccessExpr {
base: Box::new(base),
access: AccessKind::Index(Box::new(index)),
token,
})
}
/// Creates a new then-else expression.
///
/// # Arguments
/// * `condition` - The condition expression.
/// * `then_expr` - The expression to evaluate if the condition is true.
/// * `else_expr` - The expression to evaluate if the condition is false.
/// * `then_token` - The token representing the `then` keyword.
/// * `else_token` - The token representing the `else` keyword.
///
/// # Returns
///
/// A new `Expr::ThenElse` variant.
pub fn new_then_else(
condition: Expr,
then_expr: Expr,
else_expr: Expr,
then_token: Token,
else_token: Token,
) -> Self {
Expr::ThenElse(ThenElse {
condition: Box::new(condition),
then_expr: Box::new(then_expr),
else_expr: Box::new(else_expr),
then_token,
else_token,
})
}
/// Creates a new unary expression.
///
/// # Arguments
///
/// * `operator` - The unary operator.
/// * `expr` - The operand expression.
/// * `token` - The token representing the unary operation.
///
/// # Returns
///
/// A new `Expr::Unary` variant.
pub fn new_unary(operator: UnOperator, expr: Expr, token: Token) -> Self {
Expr::Unary(Unary {
operator,
expr: Box::new(expr),
token,
})
}
/// Creates a new assignment expression.
///
/// # Arguments
///
/// * `ident` - The token representing the variable identifier.
/// * `token` - The token representing the assignment operation.
/// * `value` - The expression to assign.
///
/// # Returns
///
/// A new `Expr::Assign` variant.
pub fn new_assign(left: Expr, op: AssignOperator, right: Expr) -> Self {
Expr::Assign(Assign {
left: Box::new(left),
op,
right: Box::new(right),
})
}
/// Creates a new binary expression.
///
/// # Arguments
///
/// * `left` - The left operand expression.
/// * `operator` - The binary operator.
/// * `right` - The right operand expression.
///
/// # Returns
///
/// A new `Expr::Binary` variant.
pub fn new_binary(left: Expr, operator: BinOperator, right: Expr) -> Self {
Expr::Binary(Binary {
left: Box::new(left),
operator: operator.kind,
right: Box::new(right),
})
}
/// Creates a new integer literal expression.
///
/// # Arguments
///
/// * `token` - The token representing the integer literal.
/// * `value` - The integer value.
///
/// # Returns
///
/// A new `Expr::Literal` variant with `LiteralType::Int`.
pub fn new_integer(token: Token, value: i64) -> Self {
Expr::Literal(Literal {
token,
value: LiteralType::Int(value),
})
}
/// Creates a new floating-point literal expression.
///
/// # Arguments
///
/// * `token` - The token representing the float literal.
/// * `value` - The floating-point value.
///
/// # Returns
///
/// A new `Expr::Literal` variant with `LiteralType::Float`.
pub fn new_float(token: Token, value: f64) -> Self {
Expr::Literal(Literal {
token,
value: LiteralType::Float(value),
})
}
/// Creates a new boolean literal expression.
///
/// # Arguments
///
/// * `token` - The token representing the boolean literal.
/// * `value` - The boolean value.
///
/// # Returns
///
/// A new `Expr::Literal` variant with `LiteralType::Bool`.
pub fn new_bool(token: Token, value: bool) -> Self {
Expr::Literal(Literal {
token,
value: LiteralType::Bool(value),
})
}
/// Creates a new variable expression.
///
/// # Arguments
///
/// * `ident` - The token representing the variable identifier.
/// * `name` - The name of the variable.
///
/// # Returns
///
/// A new `Expr::Variable` variant.
pub fn new_variable(ident: Token, name: String) -> Self {
Expr::Variable(Variable {
ident: name,
token: ident,
})
}
/// Creates a new function call expression.
///
/// # Arguments
///
/// * `callee` - The name of the function being called.
/// * `args` - The list of argument expressions.
/// * `token` - The token representing the function call.
///
/// # Returns
///
/// A new `Expr::Call` variant.
pub fn new_call(callee: String, args: Vec<Expr>, token: Token) -> Self {
Expr::Call(CallExpr {
callee,
args,
token,
})
}
/// Creates a new string literal expression.
///
/// # Arguments
///
/// * `token` - The token representing the string literal.
/// * `value` - The string value.
///
/// # Returns
///
/// A new `Expr::Literal` variant with `LiteralType::String`.
pub fn new_string(token: Token, value: String) -> Self {
Expr::Literal(Literal {
token,
value: LiteralType::String(value),
})
}
/// Creates a new character literal expression.
///
/// # Arguments
/// * `token` - The token representing the character literal.
/// * `value` - The character value.
///
/// # Returns
///
/// A new `Expr::Literal` variant with `LiteralType::Char`.
pub fn new_char(token: Token, value: char) -> Self {
Expr::Literal(Literal {
token,
value: LiteralType::Char(value),
})
}
/// Creates a new parenthesized expression.
///
/// # Arguments
///
/// * `expr` - The expression to be parenthesized.
///
/// # Returns
///
/// A new `Expr::Parenthesized` variant.
pub fn new_parenthesized(expr: Expr) -> Self {
Expr::Parenthesized(Parenthesized {
expr: Box::new(expr),
})
}
/// Creates a new vector expression.
///
/// # Arguments
///
/// * `exprs` - The list of expressions in the vector.
///
/// # Returns
///
/// A new `Expr::Vec` variant.
pub fn new_vec(exprs: Vec<Expr>) -> Self {
Expr::Vec(VecExpr { exprs })
}
/// Creates a new struct constructor expression.
///
/// # Arguments
/// * `name` - The name of the struct being constructed.
/// * `fields` - The field values for the struct.
/// * `token` - The token representing the struct constructor.
///
/// # Returns
///
/// A new `Expr::StructConstructor` variant.
pub fn new_struct_constructor(name: String, fields: Vec<(String, Expr)>, token: Token) -> Self {
Expr::StructConstructor(StructConstructor {
name,
fields,
token,
})
}
/// Creates a new static method access expression.
///
/// # Arguments
/// * `base` - The base expression being accessed.
/// * `method` - The method expression.
/// * `token` - The token representing the '::' operator.
///
/// # Returns
///
/// A new `Expr::Access` variant with `AccessKind::StaticMethod`.
pub fn new_static_method_access(base: Expr, method: Expr, token: Token) -> Self {
Expr::Access(AccessExpr {
base: Box::new(base),
access: AccessKind::StaticMethod(Box::new(method)),
token,
})
}
/// Creates a new object expression.
///
/// # Arguments
/// * `fields` - The key-value pairs in the object.
/// * `braces` - The tokens representing the opening and closing braces.
///
/// # Returns
///
/// A new `Expr::Object` variant.
pub fn new_object(fields: IndexMap<String, Expr>, braces: (Token, Token)) -> Self {
Expr::Object(ObjectExpr { fields, braces })
}
}