rhai/ast/ast.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 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
//! Module defining the AST (abstract syntax tree).
use super::{ASTFlags, Expr, FnAccess, Stmt};
use crate::{expose_under_internals, Dynamic, FnNamespace, ImmutableString, Position, ThinVec};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
borrow::Borrow,
fmt,
hash::Hash,
ops::{Add, AddAssign},
ptr,
};
/// Compiled AST (abstract syntax tree) of a Rhai script.
///
/// # Thread Safety
///
/// Currently, [`AST`] is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`.
#[derive(Clone)]
pub struct AST {
/// Source of the [`AST`].
source: Option<ImmutableString>,
/// Global statements.
body: ThinVec<Stmt>,
/// Script-defined functions.
#[cfg(not(feature = "no_function"))]
lib: crate::SharedModule,
/// Embedded module resolver, if any.
#[cfg(not(feature = "no_module"))]
pub(crate) resolver: Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
/// [`AST`] documentation.
#[cfg(feature = "metadata")]
pub(crate) doc: crate::SmartString,
}
impl Default for AST {
#[inline(always)]
#[must_use]
fn default() -> Self {
Self::empty()
}
}
impl fmt::Debug for AST {
#[cold]
#[inline(never)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut fp = f.debug_struct("AST");
fp.field("source", &self.source);
#[cfg(feature = "metadata")]
fp.field("doc", &self.doc);
#[cfg(not(feature = "no_module"))]
fp.field("resolver", &self.resolver);
fp.field("body", &self.body);
#[cfg(not(feature = "no_function"))]
for (.., fn_def) in self.lib.iter_script_fn() {
let sig = fn_def.to_string();
fp.field(&sig, &fn_def.body.statements());
}
fp.finish()
}
}
impl AST {
/// _(internals)_ Create a new [`AST`].
/// Exported under the `internals` feature only.
#[expose_under_internals]
#[inline]
#[must_use]
fn new(
statements: impl IntoIterator<Item = Stmt>,
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::SharedModule>,
) -> Self {
Self {
source: None,
#[cfg(feature = "metadata")]
doc: crate::SmartString::new_const(),
body: statements.into_iter().collect(),
#[cfg(not(feature = "no_function"))]
lib: functions.into(),
#[cfg(not(feature = "no_module"))]
resolver: None,
}
}
/// _(internals)_ Create a new [`AST`] with a source name.
/// Exported under the `internals` feature only.
#[expose_under_internals]
#[inline]
#[must_use]
fn new_with_source(
statements: impl IntoIterator<Item = Stmt>,
#[cfg(not(feature = "no_function"))] functions: impl Into<crate::SharedModule>,
source: impl Into<ImmutableString>,
) -> Self {
let mut ast = Self::new(
statements,
#[cfg(not(feature = "no_function"))]
functions,
);
ast.set_source(source);
ast
}
/// Create an empty [`AST`].
#[inline]
#[must_use]
pub fn empty() -> Self {
Self {
source: None,
#[cfg(feature = "metadata")]
doc: crate::SmartString::new_const(),
body: <_>::default(),
#[cfg(not(feature = "no_function"))]
lib: crate::Module::new().into(),
#[cfg(not(feature = "no_module"))]
resolver: None,
}
}
/// Get the source, if any.
#[inline(always)]
#[must_use]
pub fn source(&self) -> Option<&str> {
self.source.as_deref()
}
/// Get a reference to the source.
#[inline(always)]
#[must_use]
pub(crate) const fn source_raw(&self) -> Option<&ImmutableString> {
self.source.as_ref()
}
/// Set the source.
#[inline]
pub fn set_source(&mut self, source: impl Into<ImmutableString>) -> &mut Self {
let source = source.into();
#[cfg(not(feature = "no_function"))]
crate::Shared::get_mut(&mut self.lib)
.as_mut()
.map(|m| m.set_id(source.clone()));
self.source = (!source.is_empty()).then_some(source);
self
}
/// Clear the source.
#[inline(always)]
pub fn clear_source(&mut self) -> &mut Self {
self.source = None;
self
}
/// Get the documentation (if any).
/// Exported under the `metadata` feature only.
///
/// Documentation is a collection of all comment lines beginning with `//!`.
///
/// Leading white-spaces are stripped, and each line always starts with `//!`.
#[cfg(feature = "metadata")]
#[inline(always)]
#[must_use]
pub fn doc(&self) -> &str {
&self.doc
}
/// _(internals)_ Get the statements.
/// Exported under the `internals` feature only.
#[expose_under_internals]
#[inline(always)]
#[must_use]
fn statements(&self) -> &[Stmt] {
&self.body
}
/// Get the statements.
#[inline(always)]
#[must_use]
#[allow(dead_code)]
pub(crate) fn statements_mut(&mut self) -> &mut ThinVec<Stmt> {
&mut self.body
}
/// Does this [`AST`] contain script-defined functions?
///
/// Not available under `no_function`.
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[must_use]
pub fn has_functions(&self) -> bool {
!self.lib.is_empty()
}
/// _(internals)_ Get the internal shared [`Module`][crate::Module] containing all script-defined functions.
/// Exported under the `internals` feature only.
///
/// Not available under `no_function`.
#[expose_under_internals]
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[must_use]
const fn shared_lib(&self) -> &crate::SharedModule {
&self.lib
}
/// _(internals)_ Get the embedded [module resolver][crate::ModuleResolver].
/// Exported under the `internals` feature only.
///
/// Not available under `no_module`.
#[cfg(feature = "internals")]
#[cfg(not(feature = "no_module"))]
#[inline(always)]
#[must_use]
pub const fn resolver(
&self,
) -> Option<&crate::Shared<crate::module::resolvers::StaticModuleResolver>> {
self.resolver.as_ref()
}
/// Clone the [`AST`]'s functions into a new [`AST`].
/// No statements are cloned.
///
/// Not available under `no_function`.
///
/// This operation is cheap because functions are shared.
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[must_use]
pub fn clone_functions_only(&self) -> Self {
self.clone_functions_only_filtered(|_, _, _, _, _| true)
}
/// Clone the [`AST`]'s functions into a new [`AST`] based on a filter predicate.
/// No statements are cloned.
///
/// Not available under `no_function`.
///
/// This operation is cheap because functions are shared.
#[cfg(not(feature = "no_function"))]
#[inline]
#[must_use]
pub fn clone_functions_only_filtered(
&self,
filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> Self {
let mut lib = crate::Module::new();
lib.merge_filtered(&self.lib, &filter);
Self {
source: self.source.clone(),
#[cfg(feature = "metadata")]
doc: self.doc.clone(),
body: <_>::default(),
lib: lib.into(),
#[cfg(not(feature = "no_module"))]
resolver: self.resolver.clone(),
}
}
/// Clone the [`AST`]'s script statements into a new [`AST`].
/// No functions are cloned.
#[inline(always)]
#[must_use]
pub fn clone_statements_only(&self) -> Self {
Self {
source: self.source.clone(),
#[cfg(feature = "metadata")]
doc: self.doc.clone(),
body: self.body.clone(),
#[cfg(not(feature = "no_function"))]
lib: crate::Module::new().into(),
#[cfg(not(feature = "no_module"))]
resolver: self.resolver.clone(),
}
}
/// Merge two [`AST`] into one. Both [`AST`]'s are untouched and a new, merged,
/// version is returned.
///
/// Statements in the second [`AST`] are simply appended to the end of the first _without any processing_.
/// Thus, the return value of the first [`AST`] (if using expression-statement syntax) is buried.
/// Of course, if the first [`AST`] uses a `return` statement at the end, then
/// the second [`AST`] will essentially be dead code.
///
/// All script-defined functions in the second [`AST`] overwrite similarly-named functions
/// in the first [`AST`] with the same number of parameters.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_function"))]
/// # {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let ast1 = engine.compile("
/// fn foo(x) { 42 + x }
/// foo(1)
/// ")?;
///
/// let ast2 = engine.compile(r#"
/// fn foo(n) { `hello${n}` }
/// foo("!")
/// "#)?;
///
/// let ast = ast1.merge(&ast2); // Merge 'ast2' into 'ast1'
///
/// // Notice that using the '+' operator also works:
/// // let ast = &ast1 + &ast2;
///
/// // 'ast' is essentially:
/// //
/// // fn foo(n) { `hello${n}` } // <- definition of first 'foo' is overwritten
/// // foo(1) // <- notice this will be "hello1" instead of 43,
/// // // but it is no longer the return value
/// // foo("!") // returns "hello!"
///
/// // Evaluate it
/// assert_eq!(engine.eval_ast::<String>(&ast)?, "hello!");
/// # }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
#[must_use]
pub fn merge(&self, other: &Self) -> Self {
self.merge_filtered_impl(other, |_, _, _, _, _| true)
}
/// Combine one [`AST`] with another. The second [`AST`] is consumed.
///
/// Statements in the second [`AST`] are simply appended to the end of the first _without any processing_.
/// Thus, the return value of the first [`AST`] (if using expression-statement syntax) is buried.
/// Of course, if the first [`AST`] uses a `return` statement at the end, then
/// the second [`AST`] will essentially be dead code.
///
/// All script-defined functions in the second [`AST`] overwrite similarly-named functions
/// in the first [`AST`] with the same number of parameters.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_function"))]
/// # {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let mut ast1 = engine.compile("
/// fn foo(x) { 42 + x }
/// foo(1)
/// ")?;
///
/// let ast2 = engine.compile(r#"
/// fn foo(n) { `hello${n}` }
/// foo("!")
/// "#)?;
///
/// ast1.combine(ast2); // Combine 'ast2' into 'ast1'
///
/// // Notice that using the '+=' operator also works:
/// // ast1 += ast2;
///
/// // 'ast1' is essentially:
/// //
/// // fn foo(n) { `hello${n}` } // <- definition of first 'foo' is overwritten
/// // foo(1) // <- notice this will be "hello1" instead of 43,
/// // // but it is no longer the return value
/// // foo("!") // returns "hello!"
///
/// // Evaluate it
/// assert_eq!(engine.eval_ast::<String>(&ast1)?, "hello!");
/// # }
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub fn combine(&mut self, other: Self) -> &mut Self {
self.combine_filtered_impl(other, |_, _, _, _, _| true)
}
/// Merge two [`AST`] into one. Both [`AST`]'s are untouched and a new, merged, version
/// is returned.
///
/// Not available under `no_function`.
///
/// Statements in the second [`AST`] are simply appended to the end of the first _without any processing_.
/// Thus, the return value of the first [`AST`] (if using expression-statement syntax) is buried.
/// Of course, if the first [`AST`] uses a `return` statement at the end, then
/// the second [`AST`] will essentially be dead code.
///
/// All script-defined functions in the second [`AST`] are first selected based on a filter
/// predicate, then overwrite similarly-named functions in the first [`AST`] with the
/// same number of parameters.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let ast1 = engine.compile("
/// fn foo(x) { 42 + x }
/// foo(1)
/// ")?;
///
/// let ast2 = engine.compile(r#"
/// fn foo(n) { `hello${n}` }
/// fn error() { 0 }
/// foo("!")
/// "#)?;
///
/// // Merge 'ast2', picking only 'error()' but not 'foo(..)', into 'ast1'
/// let ast = ast1.merge_filtered(&ast2, |_, _, script, name, params|
/// script && name == "error" && params == 0);
///
/// // 'ast' is essentially:
/// //
/// // fn foo(n) { 42 + n } // <- definition of 'ast1::foo' is not overwritten
/// // // because 'ast2::foo' is filtered away
/// // foo(1) // <- notice this will be 43 instead of "hello1",
/// // // but it is no longer the return value
/// // fn error() { 0 } // <- this function passes the filter and is merged
/// // foo("!") // <- returns "42!"
///
/// // Evaluate it
/// assert_eq!(engine.eval_ast::<String>(&ast)?, "42!");
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[must_use]
pub fn merge_filtered(
&self,
other: &Self,
filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> Self {
self.merge_filtered_impl(other, filter)
}
/// Merge two [`AST`] into one. Both [`AST`]'s are untouched and a new, merged, version
/// is returned.
#[inline]
#[must_use]
fn merge_filtered_impl(
&self,
other: &Self,
_filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> Self {
let merged = match (self.body.as_ref(), other.body.as_ref()) {
([], []) => <_>::default(),
(_, []) => self.body.to_vec(),
([], _) => other.body.to_vec(),
(body, other) => {
let mut body = body.to_vec();
body.extend(other.iter().cloned());
body
}
};
#[cfg(not(feature = "no_function"))]
let lib = {
let mut lib = self.lib.as_ref().clone();
lib.merge_filtered(&other.lib, &_filter);
lib
};
let mut _ast = match other.source {
Some(ref source) => Self::new_with_source(
merged,
#[cfg(not(feature = "no_function"))]
lib,
source.clone(),
),
None => Self::new(
merged,
#[cfg(not(feature = "no_function"))]
lib,
),
};
#[cfg(not(feature = "no_module"))]
match (
self.resolver.as_deref().map_or(true, |r| r.is_empty()),
other.resolver.as_deref().map_or(true, |r| r.is_empty()),
) {
(true, true) => (),
(false, true) => _ast.resolver.clone_from(&self.resolver),
(true, false) => _ast.resolver.clone_from(&other.resolver),
(false, false) => {
let mut resolver = self.resolver.as_deref().unwrap().clone();
for (k, v) in other.resolver.as_deref().unwrap() {
resolver.insert(k.clone(), v.as_ref().clone());
}
_ast.resolver = Some(resolver.into());
}
}
#[cfg(feature = "metadata")]
match (other.doc.as_str(), _ast.doc.as_str()) {
("", _) => (),
(_, "") => _ast.doc = other.doc.clone(),
(_, _) => {
_ast.doc.push_str("\n");
_ast.doc.push_str(&other.doc);
}
}
_ast
}
/// Combine one [`AST`] with another. The second [`AST`] is consumed.
///
/// Not available under `no_function`.
///
/// Statements in the second [`AST`] are simply appended to the end of the first _without any processing_.
/// Thus, the return value of the first [`AST`] (if using expression-statement syntax) is buried.
/// Of course, if the first [`AST`] uses a `return` statement at the end, then
/// the second [`AST`] will essentially be dead code.
///
/// All script-defined functions in the second [`AST`] are first selected based on a filter
/// predicate, then overwrite similarly-named functions in the first [`AST`] with the
/// same number of parameters.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let mut ast1 = engine.compile("
/// fn foo(x) { 42 + x }
/// foo(1)
/// ")?;
///
/// let ast2 = engine.compile(r#"
/// fn foo(n) { `hello${n}` }
/// fn error() { 0 }
/// foo("!")
/// "#)?;
///
/// // Combine 'ast2', picking only 'error()' but not 'foo(..)', into 'ast1'
/// ast1.combine_filtered(ast2, |_, _, script, name, params|
/// script && name == "error" && params == 0);
///
/// // 'ast1' is essentially:
/// //
/// // fn foo(n) { 42 + n } // <- definition of 'ast1::foo' is not overwritten
/// // // because 'ast2::foo' is filtered away
/// // foo(1) // <- notice this will be 43 instead of "hello1",
/// // // but it is no longer the return value
/// // fn error() { 0 } // <- this function passes the filter and is merged
/// // foo("!") // <- returns "42!"
///
/// // Evaluate it
/// assert_eq!(engine.eval_ast::<String>(&ast1)?, "42!");
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn combine_filtered(
&mut self,
other: Self,
filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> &mut Self {
self.combine_filtered_impl(other, filter)
}
/// Combine one [`AST`] with another. The second [`AST`] is consumed.
fn combine_filtered_impl(
&mut self,
other: Self,
_filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool,
) -> &mut Self {
#[cfg(not(feature = "no_module"))]
match (
self.resolver.as_deref().map_or(true, |r| r.is_empty()),
other.resolver.as_deref().map_or(true, |r| r.is_empty()),
) {
(_, true) => (),
(true, false) => self.resolver.clone_from(&other.resolver),
(false, false) => {
let resolver = crate::func::shared_make_mut(self.resolver.as_mut().unwrap());
let other_resolver = crate::func::shared_take_or_clone(other.resolver.unwrap());
for (k, v) in other_resolver {
resolver.insert(k, crate::func::shared_take_or_clone(v));
}
}
}
match (self.body.as_ref(), other.body.as_ref()) {
(_, []) => (),
([], _) => self.body = other.body,
(_, _) => self.body.extend(other.body),
}
#[cfg(not(feature = "no_function"))]
if !other.lib.is_empty() {
crate::func::shared_make_mut(&mut self.lib).merge_filtered(&other.lib, &_filter);
}
#[cfg(feature = "metadata")]
match (other.doc.as_str(), self.doc.as_str()) {
("", _) => (),
(_, "") => self.doc = other.doc,
(_, _) => {
self.doc.push_str("\n");
self.doc.push_str(&other.doc);
}
}
self
}
/// Filter out the functions, retaining only some based on a filter predicate.
///
/// Not available under `no_function`.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # #[cfg(not(feature = "no_function"))]
/// # {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let mut ast = engine.compile(r#"
/// fn foo(n) { n + 1 }
/// fn bar() { print("hello"); }
/// "#)?;
///
/// // Remove all functions except 'foo(..)'
/// ast.retain_functions(|_, _, name, params| name == "foo" && params == 1);
/// # }
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
#[inline]
pub fn retain_functions(
&mut self,
filter: impl Fn(FnNamespace, FnAccess, &str, usize) -> bool,
) -> &mut Self {
if self.has_functions() {
crate::func::shared_make_mut(&mut self.lib).retain_script_functions(filter);
}
self
}
/// _(internals)_ Iterate through all function definitions.
/// Exported under the `internals` feature only.
///
/// Not available under `no_function`.
#[expose_under_internals]
#[cfg(not(feature = "no_function"))]
#[inline]
fn iter_fn_def(&self) -> impl Iterator<Item = &crate::Shared<super::ScriptFuncDef>> {
self.lib.iter_script_fn().map(|(.., fn_def)| fn_def)
}
/// Iterate through all function definitions.
///
/// Not available under `no_function`.
#[cfg(not(feature = "no_function"))]
#[inline]
pub fn iter_functions(&self) -> impl Iterator<Item = super::ScriptFnMetadata> {
self.lib
.iter_script_fn()
.map(|(.., fn_def)| fn_def.as_ref().into())
}
/// Clear all function definitions in the [`AST`].
///
/// Not available under `no_function`.
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn clear_functions(&mut self) -> &mut Self {
self.lib = crate::Module::new().into();
self
}
/// Clear all statements in the [`AST`], leaving only function definitions.
#[inline(always)]
pub fn clear_statements(&mut self) -> &mut Self {
self.body = <_>::default();
self
}
/// Extract all top-level literal constant and/or variable definitions.
/// This is useful for extracting all global constants from a script without actually running it.
///
/// A literal constant/variable definition takes the form of:
/// `const VAR = `_value_`;` and `let VAR = `_value_`;`
/// where _value_ is a literal expression or will be optimized into a literal.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
///
/// let ast = engine.compile(
/// "
/// const A = 40 + 2; // constant that optimizes into a literal
/// let b = 123; // literal variable
/// const B = b * A; // non-literal constant
/// const C = 999; // literal constant
/// b = A + C; // expression
///
/// { // <- new block scope
/// const Z = 0; // <- literal constant not at top-level
///
/// print(Z); // make sure the block is not optimized away
/// }
/// ")?;
///
/// let mut iter = ast.iter_literal_variables(true, false)
/// .map(|(name, is_const, value)| (name, is_const, value.as_int().unwrap()));
///
/// # #[cfg(not(feature = "no_optimize"))]
/// assert_eq!(iter.next(), Some(("A", true, 42)));
/// assert_eq!(iter.next(), Some(("C", true, 999)));
/// assert_eq!(iter.next(), None);
///
/// let mut iter = ast.iter_literal_variables(false, true)
/// .map(|(name, is_const, value)| (name, is_const, value.as_int().unwrap()));
///
/// assert_eq!(iter.next(), Some(("b", false, 123)));
/// assert_eq!(iter.next(), None);
///
/// let mut iter = ast.iter_literal_variables(true, true)
/// .map(|(name, is_const, value)| (name, is_const, value.as_int().unwrap()));
///
/// # #[cfg(not(feature = "no_optimize"))]
/// assert_eq!(iter.next(), Some(("A", true, 42)));
/// assert_eq!(iter.next(), Some(("b", false, 123)));
/// assert_eq!(iter.next(), Some(("C", true, 999)));
/// assert_eq!(iter.next(), None);
///
/// let scope: Scope = ast.iter_literal_variables(true, false).collect();
///
/// # #[cfg(not(feature = "no_optimize"))]
/// assert_eq!(scope.len(), 2);
///
/// Ok(())
/// # }
/// ```
pub fn iter_literal_variables(
&self,
include_constants: bool,
include_variables: bool,
) -> impl Iterator<Item = (&str, bool, Dynamic)> {
self.statements().iter().filter_map(move |stmt| match stmt {
Stmt::Var(x, options, ..)
if options.intersects(ASTFlags::CONSTANT) && include_constants
|| !options.intersects(ASTFlags::CONSTANT) && include_variables =>
{
let (name, expr, ..) = &**x;
expr.get_literal_value()
.map(|value| (name.as_str(), options.intersects(ASTFlags::CONSTANT), value))
}
_ => None,
})
}
/// _(internals)_ Recursively walk the [`AST`], including function bodies (if any).
/// Return `false` from the callback to terminate the walk.
/// Exported under the `internals` feature only.
#[cfg(feature = "internals")]
#[inline(always)]
pub fn walk(&self, on_node: &mut (impl FnMut(&[ASTNode]) -> bool + ?Sized)) -> bool {
self._walk(on_node)
}
/// Recursively walk the [`AST`], including function bodies (if any).
/// Return `false` from the callback to terminate the walk.
pub(crate) fn _walk(&self, on_node: &mut (impl FnMut(&[ASTNode]) -> bool + ?Sized)) -> bool {
let path = &mut Vec::new();
for stmt in self.statements() {
if !stmt.walk(path, on_node) {
return false;
}
}
#[cfg(not(feature = "no_function"))]
for stmt in self.iter_fn_def().flat_map(|f| f.body.iter()) {
if !stmt.walk(path, on_node) {
return false;
}
}
true
}
}
impl<A: AsRef<AST>> Add<A> for &AST {
type Output = AST;
#[inline(always)]
fn add(self, rhs: A) -> Self::Output {
self.merge(rhs.as_ref())
}
}
impl<A: Into<Self>> AddAssign<A> for AST {
#[inline(always)]
fn add_assign(&mut self, rhs: A) {
self.combine(rhs.into());
}
}
impl Borrow<[Stmt]> for AST {
#[inline(always)]
#[must_use]
fn borrow(&self) -> &[Stmt] {
self.statements()
}
}
impl AsRef<[Stmt]> for AST {
#[inline(always)]
#[must_use]
fn as_ref(&self) -> &[Stmt] {
self.statements()
}
}
#[cfg(not(feature = "no_function"))]
impl Borrow<crate::Module> for AST {
#[inline(always)]
#[must_use]
fn borrow(&self) -> &crate::Module {
self.shared_lib()
}
}
#[cfg(not(feature = "no_function"))]
impl AsRef<crate::Module> for AST {
#[inline(always)]
#[must_use]
fn as_ref(&self) -> &crate::Module {
self.shared_lib().as_ref()
}
}
#[cfg(not(feature = "no_function"))]
impl Borrow<crate::SharedModule> for AST {
#[inline(always)]
#[must_use]
fn borrow(&self) -> &crate::SharedModule {
self.shared_lib()
}
}
#[cfg(not(feature = "no_function"))]
impl AsRef<crate::SharedModule> for AST {
#[inline(always)]
#[must_use]
fn as_ref(&self) -> &crate::SharedModule {
self.shared_lib()
}
}
/// _(internals)_ An [`AST`] node, consisting of either an [`Expr`] or a [`Stmt`].
/// Exported under the `internals` feature only.
#[derive(Debug, Clone, Copy, Hash)]
#[non_exhaustive]
pub enum ASTNode<'a> {
/// A statement ([`Stmt`]).
Stmt(&'a Stmt),
/// An expression ([`Expr`]).
Expr(&'a Expr),
}
impl<'a> From<&'a Stmt> for ASTNode<'a> {
#[inline(always)]
fn from(stmt: &'a Stmt) -> Self {
Self::Stmt(stmt)
}
}
impl<'a> From<&'a Expr> for ASTNode<'a> {
#[inline(always)]
fn from(expr: &'a Expr) -> Self {
Self::Expr(expr)
}
}
impl PartialEq for ASTNode<'_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Stmt(x), Self::Stmt(y)) => ptr::eq(*x, *y),
(Self::Expr(x), Self::Expr(y)) => ptr::eq(*x, *y),
_ => false,
}
}
}
impl Eq for ASTNode<'_> {}
impl ASTNode<'_> {
/// Is this [`ASTNode`] a [`Stmt`]?
#[inline(always)]
#[must_use]
pub const fn is_stmt(&self) -> bool {
matches!(self, Self::Stmt(..))
}
/// Is this [`ASTNode`] an [`Expr`]?
#[inline(always)]
#[must_use]
pub const fn is_expr(&self) -> bool {
matches!(self, Self::Expr(..))
}
/// Get the [`Position`] of this [`ASTNode`].
#[inline]
#[must_use]
pub fn position(&self) -> Position {
match self {
Self::Stmt(stmt) => stmt.position(),
Self::Expr(expr) => expr.position(),
}
}
}
/// _(internals)_ Encapsulated AST environment.
/// Exported under the `internals` feature only.
///
/// 1) functions defined within the same AST
/// 2) the stack of imported [modules][crate::Module]
/// 3) global constants
#[derive(Debug, Clone)]
pub struct EncapsulatedEnviron {
/// Functions defined within the same [`AST`][crate::AST].
#[cfg(not(feature = "no_function"))]
pub lib: crate::SharedModule,
/// Imported [modules][crate::Module].
#[cfg(not(feature = "no_module"))]
pub imports: crate::ThinVec<(ImmutableString, crate::SharedModule)>,
/// Globally-defined constants.
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))]
pub constants: Option<crate::eval::SharedGlobalConstants>,
}