rhai/src/ast/stmt.rs

1029 lines
32 KiB
Rust
Raw Normal View History

2021-12-17 09:07:13 +01:00
//! Module defining script statements.
2022-02-25 04:42:59 +01:00
use super::{ASTFlags, ASTNode, BinaryExpr, Expr, FnCallExpr, Ident};
2021-12-30 05:14:54 +01:00
use crate::engine::KEYWORD_EVAL;
2022-02-08 16:01:47 +01:00
use crate::tokenizer::{Span, Token};
2021-12-17 09:07:13 +01:00
use crate::{calc_fn_hash, Position, StaticVec, INT};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
collections::BTreeMap,
fmt,
hash::Hash,
mem,
2022-02-18 08:04:46 +01:00
num::NonZeroUsize,
2022-07-04 11:42:24 +02:00
ops::{Deref, DerefMut, Range, RangeInclusive},
2021-12-17 09:07:13 +01:00
};
/// _(internals)_ An op-assignment operator.
/// Exported under the `internals` feature only.
2022-04-18 17:12:47 +02:00
///
/// This type may hold a straight assignment (i.e. not an op-assignment).
2022-04-19 10:20:43 +02:00
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
2022-05-26 12:17:08 +02:00
pub struct OpAssignment {
2021-12-17 09:07:13 +01:00
/// Hash of the op-assignment call.
pub hash_op_assign: u64,
/// Hash of the underlying operator call (for fallback).
pub hash_op: u64,
/// Op-assignment operator.
2022-05-26 12:17:08 +02:00
pub op_assign: &'static str,
2022-01-28 01:28:31 +01:00
/// Underlying operator.
2022-05-26 12:17:08 +02:00
pub op: &'static str,
2022-04-18 17:12:47 +02:00
/// [Position] of the op-assignment operator.
pub pos: Position,
2021-12-17 09:07:13 +01:00
}
2022-05-26 12:17:08 +02:00
impl OpAssignment {
2022-04-18 17:12:47 +02:00
/// Create a new [`OpAssignment`] that is only a straight assignment.
#[must_use]
#[inline(always)]
pub const fn new_assignment(pos: Position) -> Self {
Self {
hash_op_assign: 0,
hash_op: 0,
op_assign: "=",
op: "=",
pos,
}
}
/// Is this an op-assignment?
#[must_use]
#[inline(always)]
pub const fn is_op_assignment(&self) -> bool {
self.hash_op_assign != 0 || self.hash_op != 0
}
2021-12-17 09:07:13 +01:00
/// Create a new [`OpAssignment`].
///
/// # Panics
///
2021-12-17 09:55:24 +01:00
/// Panics if the name is not an op-assignment operator.
2021-12-17 09:07:13 +01:00
#[must_use]
2021-12-17 09:55:24 +01:00
#[inline(always)]
2022-04-18 17:12:47 +02:00
pub fn new_op_assignment(name: &str, pos: Position) -> Self {
2022-08-27 10:26:41 +02:00
Self::new_op_assignment_from_token(&Token::lookup_from_syntax(name).expect("operator"), pos)
2021-12-17 09:55:24 +01:00
}
/// Create a new [`OpAssignment`] from a [`Token`].
///
/// # Panics
///
/// Panics if the token is not an op-assignment operator.
#[must_use]
2022-08-27 10:26:41 +02:00
pub fn new_op_assignment_from_token(op: &Token, pos: Position) -> Self {
2021-12-17 09:07:13 +01:00
let op_raw = op
.get_base_op_from_assignment()
2021-12-17 09:55:24 +01:00
.expect("op-assignment operator")
2021-12-17 09:07:13 +01:00
.literal_syntax();
Self {
2021-12-17 09:55:24 +01:00
hash_op_assign: calc_fn_hash(op.literal_syntax(), 2),
2021-12-17 09:07:13 +01:00
hash_op: calc_fn_hash(op_raw, 2),
2022-01-28 01:28:31 +01:00
op_assign: op.literal_syntax(),
op: op_raw,
2022-04-18 17:12:47 +02:00
pos,
2021-12-17 09:07:13 +01:00
}
}
/// Create a new [`OpAssignment`] from a base operator.
///
/// # Panics
///
/// Panics if the name is not an operator that can be converted into an op-operator.
#[must_use]
#[inline(always)]
2022-04-18 17:12:47 +02:00
pub fn new_op_assignment_from_base(name: &str, pos: Position) -> Self {
Self::new_op_assignment_from_base_token(
2022-08-27 10:26:41 +02:00
&Token::lookup_from_syntax(name).expect("operator"),
2022-04-18 17:12:47 +02:00
pos,
)
}
/// Convert a [`Token`] into a new [`OpAssignment`].
///
/// # Panics
///
/// Panics if the token is cannot be converted into an op-assignment operator.
#[inline(always)]
#[must_use]
2022-08-27 10:26:41 +02:00
pub fn new_op_assignment_from_base_token(op: &Token, pos: Position) -> Self {
Self::new_op_assignment_from_token(&op.convert_to_op_assignment().expect("operator"), pos)
}
2021-12-17 09:07:13 +01:00
}
2022-05-26 12:17:08 +02:00
impl fmt::Debug for OpAssignment {
2022-04-19 10:20:43 +02:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_op_assignment() {
f.debug_struct("OpAssignment")
.field("hash_op_assign", &self.hash_op_assign)
.field("hash_op", &self.hash_op)
.field("op_assign", &self.op_assign)
.field("op", &self.op)
.field("pos", &self.pos)
.finish()
} else {
fmt::Debug::fmt(&self.pos, f)
}
}
}
2022-07-19 07:33:53 +02:00
/// An expression with a condition.
///
/// The condition may simply be [`Expr::BoolConstant`] with `true` if there is actually no condition.
2022-07-04 11:42:24 +02:00
#[derive(Debug, Clone, Default, Hash)]
2022-07-19 07:33:53 +02:00
pub struct ConditionalExpr {
2022-04-19 10:20:43 +02:00
/// Condition.
pub condition: Expr,
2022-07-19 07:33:53 +02:00
/// Expression.
pub expr: Expr,
}
2022-07-19 07:33:53 +02:00
impl<E: Into<Expr>> From<E> for ConditionalExpr {
2022-03-20 14:58:43 +01:00
#[inline(always)]
2022-07-19 07:33:53 +02:00
fn from(value: E) -> Self {
2022-03-20 14:58:43 +01:00
Self {
2022-04-19 10:20:43 +02:00
condition: Expr::BoolConstant(true, Position::NONE),
2022-07-19 07:33:53 +02:00
expr: value.into(),
2022-03-20 14:58:43 +01:00
}
}
}
2022-07-19 07:33:53 +02:00
impl<E: Into<Expr>> From<(Expr, E)> for ConditionalExpr {
2022-03-20 14:58:43 +01:00
#[inline(always)]
2022-07-19 07:33:53 +02:00
fn from(value: (Expr, E)) -> Self {
Self {
condition: value.0,
2022-07-19 07:33:53 +02:00
expr: value.1.into(),
}
}
}
2022-07-19 07:33:53 +02:00
impl ConditionalExpr {
/// Is the condition always `true`?
#[inline(always)]
#[must_use]
2022-08-27 10:26:41 +02:00
pub const fn is_always_true(&self) -> bool {
2022-07-27 10:04:24 +02:00
matches!(self.condition, Expr::BoolConstant(true, ..))
}
2022-07-19 07:33:53 +02:00
/// Is the condition always `false`?
#[inline(always)]
#[must_use]
2022-08-27 10:26:41 +02:00
pub const fn is_always_false(&self) -> bool {
2022-07-27 10:04:24 +02:00
matches!(self.condition, Expr::BoolConstant(false, ..))
}
}
2022-07-04 11:42:24 +02:00
/// _(internals)_ A type containing a range case for a `switch` statement.
/// Exported under the `internals` feature only.
#[derive(Clone, Hash)]
pub enum RangeCase {
/// Exclusive range.
ExclusiveInt(Range<INT>, usize),
/// Inclusive range.
InclusiveInt(RangeInclusive<INT>, usize),
}
impl fmt::Debug for RangeCase {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ExclusiveInt(r, n) => write!(f, "{}..{} => {}", r.start, r.end, n),
Self::InclusiveInt(r, n) => write!(f, "{}..={} => {}", *r.start(), *r.end(), n),
}
}
}
impl From<Range<INT>> for RangeCase {
#[inline(always)]
fn from(value: Range<INT>) -> Self {
2022-07-18 07:40:41 +02:00
Self::ExclusiveInt(value, usize::MAX)
2022-07-04 11:42:24 +02:00
}
}
impl From<RangeInclusive<INT>> for RangeCase {
#[inline(always)]
fn from(value: RangeInclusive<INT>) -> Self {
2022-07-18 07:40:41 +02:00
Self::InclusiveInt(value, usize::MAX)
2022-07-04 11:42:24 +02:00
}
}
2022-07-18 02:54:10 +02:00
impl IntoIterator for RangeCase {
type Item = INT;
type IntoIter = Box<dyn Iterator<Item = Self::Item>>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
match self {
2022-07-20 14:28:17 +02:00
Self::ExclusiveInt(r, ..) => Box::new(r),
Self::InclusiveInt(r, ..) => Box::new(r),
2022-07-18 02:54:10 +02:00
}
}
}
2022-07-04 11:42:24 +02:00
impl RangeCase {
2022-08-14 08:39:30 +02:00
/// Returns `true` if the range contains no items.
2022-07-04 11:42:24 +02:00
#[inline(always)]
#[must_use]
pub fn is_empty(&self) -> bool {
match self {
Self::ExclusiveInt(r, ..) => r.is_empty(),
Self::InclusiveInt(r, ..) => r.is_empty(),
}
}
2022-07-18 02:54:10 +02:00
/// Size of the range.
2022-07-04 11:42:24 +02:00
#[inline(always)]
#[must_use]
2022-08-27 10:26:41 +02:00
pub fn len(&self) -> INT {
2022-07-04 11:42:24 +02:00
match self {
2022-07-18 02:54:10 +02:00
Self::ExclusiveInt(r, ..) if r.is_empty() => 0,
2022-08-27 10:26:41 +02:00
Self::ExclusiveInt(r, ..) => r.end - r.start,
2022-07-18 02:54:10 +02:00
Self::InclusiveInt(r, ..) if r.is_empty() => 0,
2022-08-27 10:26:41 +02:00
Self::InclusiveInt(r, ..) => *r.end() - *r.start() + 1,
2022-07-04 11:42:24 +02:00
}
}
2022-07-18 02:54:10 +02:00
/// Is the specified number within this range?
2022-07-04 11:42:24 +02:00
#[inline(always)]
#[must_use]
2022-07-18 02:54:10 +02:00
pub fn contains(&self, n: INT) -> bool {
2022-07-04 11:42:24 +02:00
match self {
2022-07-18 02:54:10 +02:00
Self::ExclusiveInt(r, ..) => r.contains(&n),
Self::InclusiveInt(r, ..) => r.contains(&n),
2022-07-04 11:42:24 +02:00
}
}
/// Is the specified range inclusive?
#[inline(always)]
#[must_use]
2022-08-27 10:26:41 +02:00
pub const fn is_inclusive(&self) -> bool {
2022-07-04 11:42:24 +02:00
match self {
Self::ExclusiveInt(..) => false,
Self::InclusiveInt(..) => true,
}
}
/// Get the index to the [`ConditionalExpr`].
2022-07-04 11:42:24 +02:00
#[inline(always)]
#[must_use]
2022-08-27 10:26:41 +02:00
pub const fn index(&self) -> usize {
2022-07-04 11:42:24 +02:00
match self {
Self::ExclusiveInt(.., n) | Self::InclusiveInt(.., n) => *n,
}
}
/// Set the index to the [`ConditionalExpr`].
2022-07-04 11:42:24 +02:00
#[inline(always)]
pub fn set_index(&mut self, index: usize) {
match self {
Self::ExclusiveInt(.., n) | Self::InclusiveInt(.., n) => *n = index,
}
}
}
2022-07-18 07:40:41 +02:00
pub type CaseBlocksList = smallvec::SmallVec<[usize; 1]>;
/// _(internals)_ A type containing all cases for a `switch` statement.
/// Exported under the `internals` feature only.
#[derive(Debug, Clone, Hash)]
2022-07-18 07:40:41 +02:00
pub struct SwitchCasesCollection {
2022-07-19 07:33:53 +02:00
/// List of [`ConditionalExpr`]'s.
pub expressions: StaticVec<ConditionalExpr>,
/// Dictionary mapping value hashes to [`ConditionalExpr`]'s.
2022-07-18 07:40:41 +02:00
pub cases: BTreeMap<u64, CaseBlocksList>,
/// List of range cases.
2022-07-04 11:42:24 +02:00
pub ranges: StaticVec<RangeCase>,
2022-07-18 16:30:09 +02:00
/// Statements block for the default case (there can be no condition for the default case).
pub def_case: Option<usize>,
}
/// _(internals)_ A `try-catch` block.
/// Exported under the `internals` feature only.
#[derive(Debug, Clone, Hash)]
pub struct TryCatchBlock {
/// `try` block.
pub try_block: StmtBlock,
/// `catch` variable, if any.
2022-03-05 10:57:23 +01:00
pub catch_var: Ident,
/// `catch` block.
pub catch_block: StmtBlock,
}
2022-02-16 10:51:14 +01:00
/// _(internals)_ The underlying container type for [`StmtBlock`].
/// Exported under the `internals` feature only.
///
/// A [`SmallVec`](https://crates.io/crates/smallvec) containing up to 8 items inline is used to
/// hold a statements block, with the assumption that most program blocks would container fewer than
/// 8 statements, and those that do have a lot more statements.
#[cfg(not(feature = "no_std"))]
2022-02-16 05:57:26 +01:00
pub type StmtBlockContainer = smallvec::SmallVec<[Stmt; 8]>;
2022-02-16 10:51:14 +01:00
/// _(internals)_ The underlying container type for [`StmtBlock`].
/// Exported under the `internals` feature only.
#[cfg(feature = "no_std")]
pub type StmtBlockContainer = StaticVec<Stmt>;
2021-12-17 09:07:13 +01:00
/// _(internals)_ A scoped block of statements.
/// Exported under the `internals` feature only.
#[derive(Clone, Hash, Default)]
2022-05-26 12:17:08 +02:00
pub struct StmtBlock {
2022-07-04 11:42:24 +02:00
/// List of [statements][Stmt].
2022-05-26 12:17:08 +02:00
block: StmtBlockContainer,
2022-07-04 11:42:24 +02:00
/// [Position] of the statements block.
2022-05-26 12:17:08 +02:00
span: Span,
}
2021-12-17 09:07:13 +01:00
impl StmtBlock {
/// A [`StmtBlock`] that does not exist.
pub const NONE: Self = Self::empty(Position::NONE);
/// Create a new [`StmtBlock`].
2022-02-16 10:51:14 +01:00
#[inline(always)]
2021-12-17 09:07:13 +01:00
#[must_use]
2022-02-04 05:04:33 +01:00
pub fn new(
statements: impl IntoIterator<Item = Stmt>,
start_pos: Position,
end_pos: Position,
) -> Self {
2022-02-16 10:51:14 +01:00
Self::new_with_span(statements, Span::new(start_pos, end_pos))
}
/// Create a new [`StmtBlock`].
#[must_use]
pub fn new_with_span(statements: impl IntoIterator<Item = Stmt>, span: Span) -> Self {
2022-02-16 05:57:26 +01:00
let mut statements: smallvec::SmallVec<_> = statements.into_iter().collect();
2021-12-17 09:07:13 +01:00
statements.shrink_to_fit();
2022-05-26 12:17:08 +02:00
Self {
block: statements,
span,
}
2021-12-17 09:07:13 +01:00
}
/// Create an empty [`StmtBlock`].
#[inline(always)]
#[must_use]
pub const fn empty(pos: Position) -> Self {
2022-05-26 12:17:08 +02:00
Self {
block: StmtBlockContainer::new_const(),
span: Span::new(pos, pos),
}
2021-12-17 09:07:13 +01:00
}
2022-08-14 08:39:30 +02:00
/// Returns `true` if this statements block contains no statements.
2021-12-17 09:07:13 +01:00
#[inline(always)]
#[must_use]
pub fn is_empty(&self) -> bool {
2022-05-26 12:17:08 +02:00
self.block.is_empty()
2021-12-17 09:07:13 +01:00
}
/// Number of statements in this statements block.
#[inline(always)]
#[must_use]
pub fn len(&self) -> usize {
2022-05-26 12:17:08 +02:00
self.block.len()
2021-12-17 09:07:13 +01:00
}
/// Get the statements of this statements block.
#[inline(always)]
#[must_use]
pub fn statements(&self) -> &[Stmt] {
2022-05-26 12:17:08 +02:00
&self.block
2021-12-17 09:07:13 +01:00
}
/// Extract the statements.
#[inline(always)]
#[must_use]
2022-02-16 05:57:26 +01:00
pub(crate) fn take_statements(&mut self) -> StmtBlockContainer {
2022-05-26 12:17:08 +02:00
mem::take(&mut self.block)
2021-12-17 09:07:13 +01:00
}
/// Get an iterator over the statements of this statements block.
#[inline(always)]
pub fn iter(&self) -> impl Iterator<Item = &Stmt> {
2022-05-26 12:17:08 +02:00
self.block.iter()
2021-12-17 09:07:13 +01:00
}
2022-02-04 05:04:33 +01:00
/// Get the start position (location of the beginning `{`) of this statements block.
2021-12-17 09:07:13 +01:00
#[inline(always)]
#[must_use]
pub const fn position(&self) -> Position {
2022-05-26 12:17:08 +02:00
(self.span).start()
2022-02-04 05:04:33 +01:00
}
/// Get the end position (location of the ending `}`) of this statements block.
#[inline(always)]
#[must_use]
pub const fn end_position(&self) -> Position {
2022-05-26 12:17:08 +02:00
(self.span).end()
2022-02-04 05:04:33 +01:00
}
/// Get the positions (locations of the beginning `{` and ending `}`) of this statements block.
#[inline(always)]
#[must_use]
2022-02-08 16:01:47 +01:00
pub const fn span(&self) -> Span {
2022-05-26 12:17:08 +02:00
self.span
2021-12-17 09:07:13 +01:00
}
2022-02-04 05:04:33 +01:00
/// Get the positions (locations of the beginning `{` and ending `}`) of this statements block
/// or a default.
2021-12-17 09:07:13 +01:00
#[inline(always)]
2022-02-04 05:04:33 +01:00
#[must_use]
2022-02-08 16:01:47 +01:00
pub const fn span_or_else(&self, def_start_pos: Position, def_end_pos: Position) -> Span {
Span::new(
2022-05-26 12:17:08 +02:00
(self.span).start().or_else(def_start_pos),
(self.span).end().or_else(def_end_pos),
2022-02-04 05:04:33 +01:00
)
}
/// Set the positions of this statements block.
#[inline(always)]
pub fn set_position(&mut self, start_pos: Position, end_pos: Position) {
2022-05-26 12:17:08 +02:00
self.span = Span::new(start_pos, end_pos);
2021-12-17 09:07:13 +01:00
}
}
impl Deref for StmtBlock {
2022-02-16 05:57:26 +01:00
type Target = StmtBlockContainer;
2021-12-17 09:07:13 +01:00
#[inline(always)]
fn deref(&self) -> &Self::Target {
2022-05-26 12:17:08 +02:00
&self.block
2021-12-17 09:07:13 +01:00
}
}
impl DerefMut for StmtBlock {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
2022-05-26 12:17:08 +02:00
&mut self.block
2021-12-17 09:07:13 +01:00
}
}
impl AsRef<[Stmt]> for StmtBlock {
#[inline(always)]
fn as_ref(&self) -> &[Stmt] {
2022-05-26 12:17:08 +02:00
&self.block
}
}
impl AsMut<[Stmt]> for StmtBlock {
#[inline(always)]
fn as_mut(&mut self) -> &mut [Stmt] {
2022-05-26 12:17:08 +02:00
&mut self.block
}
}
2021-12-17 09:07:13 +01:00
impl fmt::Debug for StmtBlock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Block")?;
2022-05-26 12:17:08 +02:00
fmt::Debug::fmt(&self.block, f)?;
if !self.span.is_none() {
write!(f, " @ {:?}", self.span())?;
2022-02-04 05:04:33 +01:00
}
Ok(())
2021-12-17 09:07:13 +01:00
}
}
impl From<Stmt> for StmtBlock {
#[inline]
fn from(stmt: Stmt) -> Self {
match stmt {
2022-02-16 10:51:14 +01:00
Stmt::Block(block) => *block,
2022-05-26 12:17:08 +02:00
Stmt::Noop(pos) => Self {
block: StmtBlockContainer::new_const(),
span: Span::new(pos, pos),
},
_ => {
let pos = stmt.position();
2022-05-26 12:17:08 +02:00
Self {
block: vec![stmt].into(),
span: Span::new(pos, Position::NONE),
}
}
}
2021-12-17 09:07:13 +01:00
}
}
impl IntoIterator for StmtBlock {
type Item = Stmt;
2022-02-16 11:05:09 +01:00
#[cfg(not(feature = "no_std"))]
2022-02-16 05:57:26 +01:00
type IntoIter = smallvec::IntoIter<[Stmt; 8]>;
2022-02-16 11:05:09 +01:00
#[cfg(feature = "no_std")]
type IntoIter = smallvec::IntoIter<[Stmt; 3]>;
2021-12-17 09:07:13 +01:00
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
2022-05-26 12:17:08 +02:00
self.block.into_iter()
2021-12-17 09:07:13 +01:00
}
}
2022-07-05 10:26:38 +02:00
impl<'a> IntoIterator for &'a StmtBlock {
type Item = &'a Stmt;
type IntoIter = std::slice::Iter<'a, Stmt>;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
2022-07-20 14:38:50 +02:00
self.block.iter()
2022-07-05 10:26:38 +02:00
}
}
2021-12-17 09:07:13 +01:00
impl Extend<Stmt> for StmtBlock {
#[inline(always)]
fn extend<T: IntoIterator<Item = Stmt>>(&mut self, iter: T) {
2022-07-27 12:04:59 +02:00
self.block.extend(iter);
2021-12-17 09:07:13 +01:00
}
}
/// _(internals)_ A statement.
/// Exported under the `internals` feature only.
#[derive(Debug, Clone, Hash)]
2022-04-26 10:36:24 +02:00
#[non_exhaustive]
2021-12-17 09:07:13 +01:00
pub enum Stmt {
/// No-op.
Noop(Position),
/// `if` expr `{` stmt `}` `else` `{` stmt `}`
2022-02-16 10:51:14 +01:00
If(Box<(Expr, StmtBlock, StmtBlock)>, Position),
/// `switch` expr `{` literal or range or _ `if` condition `=>` stmt `,` ... `}`
///
/// ### Data Structure
///
/// 0) Hash table for (condition, block)
/// 1) Default block
/// 2) List of ranges: (start, end, inclusive, condition, statement)
2022-07-18 07:40:41 +02:00
Switch(Box<(Expr, SwitchCasesCollection)>, Position),
2021-12-17 09:07:13 +01:00
/// `while` expr `{` stmt `}` | `loop` `{` stmt `}`
///
/// If the guard expression is [`UNIT`][Expr::Unit], then it is a `loop` statement.
2022-02-16 10:51:14 +01:00
While(Box<(Expr, StmtBlock)>, Position),
2021-12-17 09:07:13 +01:00
/// `do` `{` stmt `}` `while`|`until` expr
///
2022-02-25 04:42:59 +01:00
/// ### Flags
2021-12-17 09:07:13 +01:00
///
2022-02-25 04:42:59 +01:00
/// * [`NONE`][ASTFlags::NONE] = `while`
/// * [`NEGATED`][ASTFlags::NEGATED] = `until`
Do(Box<(Expr, StmtBlock)>, ASTFlags, Position),
2021-12-17 09:07:13 +01:00
/// `for` `(` id `,` counter `)` `in` expr `{` stmt `}`
2022-03-05 10:57:23 +01:00
For(Box<(Ident, Ident, Expr, StmtBlock)>, Position),
2021-12-17 09:07:13 +01:00
/// \[`export`\] `let`|`const` id `=` expr
///
2022-02-25 04:42:59 +01:00
/// ### Flags
2021-12-17 09:07:13 +01:00
///
2022-02-25 04:42:59 +01:00
/// * [`EXPORTED`][ASTFlags::EXPORTED] = `export`
/// * [`CONSTANT`][ASTFlags::CONSTANT] = `const`
Var(Box<(Ident, Expr, Option<NonZeroUsize>)>, ASTFlags, Position),
2021-12-17 09:07:13 +01:00
/// expr op`=` expr
2022-05-26 12:17:08 +02:00
Assignment(Box<(OpAssignment, BinaryExpr)>),
2021-12-17 09:07:13 +01:00
/// func `(` expr `,` ... `)`
///
/// Note - this is a duplicate of [`Expr::FnCall`] to cover the very common pattern of a single
/// function call forming one statement.
FnCall(Box<FnCallExpr>, Position),
/// `{` stmt`;` ... `}`
2022-02-16 10:51:14 +01:00
Block(Box<StmtBlock>),
2021-12-17 09:07:13 +01:00
/// `try` `{` stmt; ... `}` `catch` `(` var `)` `{` stmt; ... `}`
TryCatch(Box<TryCatchBlock>, Position),
2021-12-17 09:07:13 +01:00
/// [expression][Expr]
2022-02-16 10:51:14 +01:00
Expr(Box<Expr>),
2021-12-17 09:07:13 +01:00
/// `continue`/`break`
///
2022-02-25 04:42:59 +01:00
/// ### Flags
2021-12-17 09:07:13 +01:00
///
2022-02-25 04:42:59 +01:00
/// * [`NONE`][ASTFlags::NONE] = `continue`
/// * [`BREAK`][ASTFlags::BREAK] = `break`
BreakLoop(ASTFlags, Position),
2021-12-17 09:07:13 +01:00
/// `return`/`throw`
///
2022-02-25 04:42:59 +01:00
/// ### Flags
2021-12-17 09:07:13 +01:00
///
2022-02-25 04:42:59 +01:00
/// * [`NONE`][ASTFlags::NONE] = `return`
/// * [`BREAK`][ASTFlags::BREAK] = `throw`
Return(Option<Box<Expr>>, ASTFlags, Position),
2022-02-18 08:04:46 +01:00
/// `import` expr `as` alias
2021-12-17 09:07:13 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
2022-03-05 10:57:23 +01:00
Import(Box<(Expr, Ident)>, Position),
2022-02-18 08:04:46 +01:00
/// `export` var `as` alias
2021-12-17 09:07:13 +01:00
///
/// Not available under `no_module`.
#[cfg(not(feature = "no_module"))]
Export(Box<(Ident, Ident)>, Position),
2021-12-17 09:07:13 +01:00
/// Convert a variable to shared.
///
/// Not available under `no_closure`.
///
/// # Notes
///
/// This variant does not map to any language structure. It is currently only used only to
/// convert a normal variable into a shared variable when the variable is _captured_ by a closure.
#[cfg(not(feature = "no_closure"))]
2022-08-13 12:07:42 +02:00
Share(crate::ImmutableString, Position),
2021-12-17 09:07:13 +01:00
}
impl Default for Stmt {
#[inline(always)]
fn default() -> Self {
Self::Noop(Position::NONE)
}
}
impl From<StmtBlock> for Stmt {
#[inline(always)]
fn from(block: StmtBlock) -> Self {
2022-02-16 10:51:14 +01:00
Self::Block(block.into())
}
}
2022-08-27 10:26:41 +02:00
impl<T: IntoIterator<Item = Self>> From<(T, Position, Position)> for Stmt {
2022-02-16 10:51:14 +01:00
#[inline(always)]
fn from(value: (T, Position, Position)) -> Self {
StmtBlock::new(value.0, value.1, value.2).into()
}
}
2022-08-27 10:26:41 +02:00
impl<T: IntoIterator<Item = Self>> From<(T, Span)> for Stmt {
2022-02-16 10:51:14 +01:00
#[inline(always)]
fn from(value: (T, Span)) -> Self {
StmtBlock::new_with_span(value.0, value.1).into()
2021-12-17 09:07:13 +01:00
}
}
impl Stmt {
/// Is this statement [`Noop`][Stmt::Noop]?
#[inline(always)]
#[must_use]
pub const fn is_noop(&self) -> bool {
2022-02-08 02:46:14 +01:00
matches!(self, Self::Noop(..))
2021-12-17 09:07:13 +01:00
}
/// Get the [position][Position] of this statement.
#[must_use]
2022-02-10 10:55:32 +01:00
pub fn position(&self) -> Position {
2021-12-17 09:07:13 +01:00
match self {
Self::Noop(pos)
2022-02-08 02:02:15 +01:00
| Self::BreakLoop(.., pos)
| Self::FnCall(.., pos)
| Self::If(.., pos)
| Self::Switch(.., pos)
| Self::While(.., pos)
| Self::Do(.., pos)
| Self::For(.., pos)
| Self::Return(.., pos)
| Self::Var(.., pos)
| Self::TryCatch(.., pos) => *pos,
2021-12-17 09:07:13 +01:00
2022-04-18 17:12:47 +02:00
Self::Assignment(x) => x.0.pos,
2022-02-16 10:51:14 +01:00
Self::Block(x) => x.position(),
2022-02-08 16:01:47 +01:00
2022-02-04 05:04:33 +01:00
Self::Expr(x) => x.start_position(),
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Import(.., pos) => *pos,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Export(.., pos) => *pos,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_closure"))]
2022-02-09 06:40:51 +01:00
Self::Share(.., pos) => *pos,
2021-12-17 09:07:13 +01:00
}
}
/// Override the [position][Position] of this statement.
pub fn set_position(&mut self, new_pos: Position) -> &mut Self {
match self {
Self::Noop(pos)
2022-02-08 02:02:15 +01:00
| Self::BreakLoop(.., pos)
| Self::FnCall(.., pos)
| Self::If(.., pos)
| Self::Switch(.., pos)
| Self::While(.., pos)
| Self::Do(.., pos)
| Self::For(.., pos)
| Self::Return(.., pos)
| Self::Var(.., pos)
| Self::TryCatch(.., pos) => *pos = new_pos,
2021-12-17 09:07:13 +01:00
2022-04-18 17:12:47 +02:00
Self::Assignment(x) => x.0.pos = new_pos,
2022-02-16 10:51:14 +01:00
Self::Block(x) => x.set_position(new_pos, x.end_position()),
2022-02-08 16:01:47 +01:00
2021-12-17 09:07:13 +01:00
Self::Expr(x) => {
x.set_position(new_pos);
}
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Import(.., pos) => *pos = new_pos,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Export(.., pos) => *pos = new_pos,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_closure"))]
2022-02-09 06:40:51 +01:00
Self::Share(.., pos) => *pos = new_pos,
2021-12-17 09:07:13 +01:00
}
self
}
/// Does this statement return a value?
#[must_use]
pub const fn returns_value(&self) -> bool {
match self {
2022-02-08 02:02:15 +01:00
Self::If(..)
| Self::Switch(..)
| Self::Block(..)
2022-02-08 02:46:14 +01:00
| Self::Expr(..)
2022-02-08 02:02:15 +01:00
| Self::FnCall(..) => true,
2021-12-17 09:07:13 +01:00
2022-02-08 14:28:15 +01:00
Self::Noop(..)
| Self::While(..)
| Self::Do(..)
| Self::For(..)
| Self::TryCatch(..) => false,
2021-12-17 09:07:13 +01:00
2022-02-08 02:02:15 +01:00
Self::Var(..) | Self::Assignment(..) | Self::BreakLoop(..) | Self::Return(..) => false,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Import(..) | Self::Export(..) => false,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_closure"))]
2022-02-08 02:46:14 +01:00
Self::Share(..) => false,
2021-12-17 09:07:13 +01:00
}
}
/// Is this statement self-terminated (i.e. no need for a semicolon terminator)?
#[must_use]
pub const fn is_self_terminated(&self) -> bool {
match self {
2022-02-08 02:02:15 +01:00
Self::If(..)
| Self::Switch(..)
| Self::While(..)
| Self::For(..)
| Self::Block(..)
| Self::TryCatch(..) => true,
2021-12-17 09:07:13 +01:00
// A No-op requires a semicolon in order to know it is an empty statement!
2022-02-08 02:46:14 +01:00
Self::Noop(..) => false,
2021-12-17 09:07:13 +01:00
2022-02-16 10:51:14 +01:00
Self::Expr(e) => match &**e {
2022-07-05 16:59:03 +02:00
#[cfg(not(feature = "no_custom_syntax"))]
2022-02-16 10:51:14 +01:00
Expr::Custom(x, ..) if x.is_self_terminated() => true,
_ => false,
},
2021-12-17 09:07:13 +01:00
2022-02-08 02:02:15 +01:00
Self::Var(..)
| Self::Assignment(..)
| Self::FnCall(..)
| Self::Do(..)
| Self::BreakLoop(..)
| Self::Return(..) => false,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Import(..) | Self::Export(..) => false,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_closure"))]
2022-02-08 02:46:14 +01:00
Self::Share(..) => false,
2021-12-17 09:07:13 +01:00
}
}
/// Is this statement _pure_?
///
/// A pure statement has no side effects.
#[must_use]
pub fn is_pure(&self) -> bool {
match self {
2022-02-08 02:46:14 +01:00
Self::Noop(..) => true,
2021-12-17 09:07:13 +01:00
Self::Expr(expr) => expr.is_pure(),
2022-02-16 10:51:14 +01:00
Self::If(x, ..) => {
2022-08-27 10:26:41 +02:00
x.0.is_pure() && x.1.iter().all(Self::is_pure) && x.2.iter().all(Self::is_pure)
2021-12-17 09:07:13 +01:00
}
2022-02-16 10:51:14 +01:00
Self::Switch(x, ..) => {
2022-07-05 10:26:38 +02:00
let (expr, sw) = &**x;
2022-07-04 11:42:24 +02:00
expr.is_pure()
2022-07-18 07:40:41 +02:00
&& sw.cases.values().flat_map(|cases| cases.iter()).all(|&c| {
2022-07-19 07:33:53 +02:00
let block = &sw.expressions[c];
block.condition.is_pure() && block.expr.is_pure()
2021-12-17 09:07:13 +01:00
})
2022-07-04 11:42:24 +02:00
&& sw.ranges.iter().all(|r| {
2022-07-19 07:33:53 +02:00
let block = &sw.expressions[r.index()];
block.condition.is_pure() && block.expr.is_pure()
2021-12-17 09:07:13 +01:00
})
2022-07-18 16:30:09 +02:00
&& sw.def_case.is_some()
2022-07-19 07:33:53 +02:00
&& sw.expressions[sw.def_case.unwrap()].expr.is_pure()
2021-12-17 09:07:13 +01:00
}
// Loops that exit can be pure because it can never be infinite.
2022-02-16 10:51:14 +01:00
Self::While(x, ..) if matches!(x.0, Expr::BoolConstant(false, ..)) => true,
Self::Do(x, options, ..) if matches!(x.0, Expr::BoolConstant(..)) => match x.0 {
2022-02-25 04:42:59 +01:00
Expr::BoolConstant(cond, ..) if cond == options.contains(ASTFlags::NEGATED) => {
2022-08-27 10:26:41 +02:00
x.1.iter().all(Self::is_pure)
2022-02-16 10:51:14 +01:00
}
_ => false,
},
2021-12-17 09:07:13 +01:00
// Loops are never pure since they can be infinite - and that's a side effect.
2022-02-08 02:02:15 +01:00
Self::While(..) | Self::Do(..) => false,
2021-12-17 09:07:13 +01:00
// For loops can be pure because if the iterable is pure, it is finite,
// so infinite loops can never occur.
2022-08-27 10:26:41 +02:00
Self::For(x, ..) => x.2.is_pure() && x.3.iter().all(Self::is_pure),
2021-12-17 09:07:13 +01:00
2022-02-08 02:02:15 +01:00
Self::Var(..) | Self::Assignment(..) | Self::FnCall(..) => false,
2022-08-27 10:26:41 +02:00
Self::Block(block, ..) => block.iter().all(Self::is_pure),
2022-02-08 02:02:15 +01:00
Self::BreakLoop(..) | Self::Return(..) => false,
Self::TryCatch(x, ..) => {
2022-08-27 10:26:41 +02:00
x.try_block.iter().all(Self::is_pure) && x.catch_block.iter().all(Self::is_pure)
2021-12-17 09:07:13 +01:00
}
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Import(..) => false,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Export(..) => false,
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_closure"))]
2022-02-08 02:46:14 +01:00
Self::Share(..) => false,
2021-12-17 09:07:13 +01:00
}
}
2021-12-30 05:14:54 +01:00
/// Does this statement's behavior depend on its containing block?
///
2022-02-24 03:36:20 +01:00
/// A statement that depends on its containing block behaves differently when promoted to an
/// upper block.
2021-12-30 05:14:54 +01:00
///
/// Currently only variable definitions (i.e. `let` and `const`), `import`/`export` statements,
2022-03-09 02:25:55 +01:00
/// and `eval` calls (which may in turn define variables) fall under this category.
2021-12-30 05:14:54 +01:00
#[inline]
#[must_use]
pub fn is_block_dependent(&self) -> bool {
match self {
2022-02-08 02:02:15 +01:00
Self::Var(..) => true,
2021-12-30 05:14:54 +01:00
2022-02-16 10:51:14 +01:00
Self::Expr(e) => match &**e {
2022-08-27 10:26:41 +02:00
Expr::Stmt(s) => s.iter().all(Self::is_block_dependent),
2022-02-16 10:51:14 +01:00
Expr::FnCall(x, ..) => !x.is_qualified() && x.name == KEYWORD_EVAL,
_ => false,
},
2021-12-30 05:19:41 +01:00
2022-02-16 10:51:14 +01:00
Self::FnCall(x, ..) => !x.is_qualified() && x.name == KEYWORD_EVAL,
2021-12-30 05:14:54 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Import(..) | Self::Export(..) => true,
2021-12-30 05:14:54 +01:00
_ => false,
}
}
2021-12-17 09:07:13 +01:00
/// Is this statement _pure_ within the containing block?
///
/// An internally pure statement only has side effects that disappear outside the block.
///
/// Currently only variable definitions (i.e. `let` and `const`) and `import`/`export`
2021-12-30 05:14:54 +01:00
/// statements are internally pure, other than pure expressions.
2021-12-17 09:07:13 +01:00
#[inline]
#[must_use]
pub fn is_internally_pure(&self) -> bool {
match self {
2022-02-16 10:51:14 +01:00
Self::Var(x, ..) => x.1.is_pure(),
2021-12-17 09:07:13 +01:00
2022-07-05 10:26:38 +02:00
Self::Expr(e) => match &**e {
2022-08-27 10:26:41 +02:00
Expr::Stmt(s) => s.iter().all(Self::is_internally_pure),
2022-02-16 10:51:14 +01:00
_ => self.is_pure(),
},
2021-12-30 05:19:41 +01:00
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-16 10:51:14 +01:00
Self::Import(x, ..) => x.0.is_pure(),
2021-12-17 09:07:13 +01:00
#[cfg(not(feature = "no_module"))]
2022-02-08 02:02:15 +01:00
Self::Export(..) => true,
2021-12-17 09:07:13 +01:00
_ => self.is_pure(),
}
}
/// Does this statement break the current control flow through the containing block?
///
/// Currently this is only true for `return`, `throw`, `break` and `continue`.
///
/// All statements following this statement will essentially be dead code.
#[inline]
#[must_use]
pub const fn is_control_flow_break(&self) -> bool {
match self {
2022-02-08 02:02:15 +01:00
Self::Return(..) | Self::BreakLoop(..) => true,
2021-12-17 09:07:13 +01:00
_ => false,
}
}
/// Recursively walk this statement.
/// Return `false` from the callback to terminate the walk.
pub fn walk<'a>(
&'a self,
path: &mut Vec<ASTNode<'a>>,
on_node: &mut impl FnMut(&[ASTNode]) -> bool,
) -> bool {
// Push the current node onto the path
path.push(self.into());
if !on_node(path) {
return false;
}
match self {
2022-02-16 10:51:14 +01:00
Self::Var(x, ..) => {
if !x.1.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
}
2022-02-16 10:51:14 +01:00
Self::If(x, ..) => {
if !x.0.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
2022-07-05 10:26:38 +02:00
for s in &x.1 {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
2022-07-05 10:26:38 +02:00
for s in &x.2 {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
}
2022-02-16 10:51:14 +01:00
Self::Switch(x, ..) => {
2022-07-05 10:26:38 +02:00
let (expr, sw) = &**x;
2022-07-04 11:42:24 +02:00
if !expr.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
2022-07-18 07:40:41 +02:00
for (.., blocks) in &sw.cases {
for &b in blocks {
2022-07-19 07:33:53 +02:00
let block = &sw.expressions[b];
2022-07-04 11:42:24 +02:00
2022-07-18 07:40:41 +02:00
if !block.condition.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
2022-07-19 07:33:53 +02:00
if !block.expr.walk(path, on_node) {
return false;
2022-07-18 07:40:41 +02:00
}
2021-12-17 09:07:13 +01:00
}
}
2022-07-05 10:26:38 +02:00
for r in &sw.ranges {
2022-07-19 07:33:53 +02:00
let block = &sw.expressions[r.index()];
2022-07-04 11:42:24 +02:00
if !block.condition.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
2022-07-19 07:33:53 +02:00
if !block.expr.walk(path, on_node) {
return false;
2021-12-17 09:07:13 +01:00
}
}
2022-07-18 16:30:09 +02:00
if let Some(index) = sw.def_case {
2022-07-19 07:33:53 +02:00
if !sw.expressions[index].expr.walk(path, on_node) {
return false;
2021-12-17 09:07:13 +01:00
}
}
}
2022-02-16 10:51:14 +01:00
Self::While(x, ..) | Self::Do(x, ..) => {
if !x.0.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
2022-02-16 10:51:14 +01:00
for s in x.1.statements() {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
}
2022-02-16 10:51:14 +01:00
Self::For(x, ..) => {
2022-02-18 08:04:46 +01:00
if !x.2.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
2022-07-05 10:26:38 +02:00
for s in &x.3 {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
}
2022-02-08 02:02:15 +01:00
Self::Assignment(x, ..) => {
if !x.1.lhs.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
if !x.1.rhs.walk(path, on_node) {
2021-12-17 09:07:13 +01:00
return false;
}
}
2022-02-08 02:02:15 +01:00
Self::FnCall(x, ..) => {
2021-12-17 09:07:13 +01:00
for s in &x.args {
if !s.walk(path, on_node) {
return false;
}
}
}
2022-02-08 02:02:15 +01:00
Self::Block(x, ..) => {
2022-02-16 10:51:14 +01:00
for s in x.statements() {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
}
2022-02-08 02:02:15 +01:00
Self::TryCatch(x, ..) => {
2022-07-05 10:26:38 +02:00
for s in &x.try_block {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
2022-07-05 10:26:38 +02:00
for s in &x.catch_block {
2021-12-17 09:07:13 +01:00
if !s.walk(path, on_node) {
return false;
}
}
}
2022-02-16 10:51:14 +01:00
Self::Expr(e) => {
2021-12-17 09:07:13 +01:00
if !e.walk(path, on_node) {
return false;
}
}
2022-02-16 10:51:14 +01:00
Self::Return(Some(e), ..) => {
2021-12-17 09:07:13 +01:00
if !e.walk(path, on_node) {
return false;
}
}
2022-02-16 10:51:14 +01:00
#[cfg(not(feature = "no_module"))]
Self::Import(x, ..) => {
if !x.0.walk(path, on_node) {
return false;
}
}
2021-12-17 09:07:13 +01:00
_ => (),
}
2022-01-06 04:07:52 +01:00
path.pop().unwrap();
2021-12-17 09:07:13 +01:00
true
}
}