use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::time::Duration;
use alloc::rc::Rc;
use core::cell::RefCell;
use crate::hotkeys::Condition;
use crate::ast::{
AccessBody, AccessDef, AssignOp, BinaryOp, Declarations, DeclareKind, DynamicPiece, LegacyForm,
LiteralValue, LoopKind, MemberName, MethodDef, Node, ObjectItem, Parameter, PropertyDef,
UnaryOp,
};
pub use crate::desktop::{Desktop, Files, WindowAnswer};
const THE_LOOP_VARIABLES: &[&str] = &[
"index",
"loopfield",
"loopreadline",
"loopfilename",
"loopfileext",
"loopfilepath",
"loopfilefullpath",
"loopfiledir",
"loopregname",
"loopregtype",
"loopregkey",
"loopregtimemodified",
];
const SPREAD_VARIABLE: &str = "\u{0}spread";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeName {
String,
Integer,
Float,
Object,
VarRef,
Number,
Class,
ComValue,
}
impl TypeName {
pub fn name(self) -> &'static str {
match self {
TypeName::String => "String",
TypeName::Integer => "Integer",
TypeName::Float => "Float",
TypeName::Object => "Object",
TypeName::VarRef => "VarRef",
TypeName::Number => "Number",
TypeName::Class => "Class",
TypeName::ComValue => "ComValue",
}
}
pub fn lowercase(self) -> &'static str {
match self {
TypeName::String => "string",
TypeName::Integer => "integer",
TypeName::Float => "float",
TypeName::Object => "object",
TypeName::VarRef => "varref",
TypeName::Number => "number",
TypeName::Class => "class",
TypeName::ComValue => "comvalue",
}
}
pub fn article(self) -> &'static str {
match self {
TypeName::Integer | TypeName::Object => "n",
_ => "",
}
}
pub fn phrase(self) -> String {
format!("a{} {}", self.article(), self.name())
}
}
pub fn expected_type(expected: TypeName, got: TypeName) -> String {
format!(
"Expected a{} {} but got a{} {}.",
expected.article(),
expected.name(),
got.article(),
got.name()
)
}
pub fn expected_the_kind(expected: TypeName, got: &str) -> String {
format!(
"Expected a{} {} but got a{} {}.",
expected.article(),
expected.name(),
the_article_of(got),
got
)
}
pub fn expected_the_class(expected: &str, got: &str) -> String {
format!(
"Expected a{} {} but got a{} {}.",
the_article_of(expected),
expected,
the_article_of(got),
got
)
}
fn the_article_of(name: &str) -> &'static str {
match name.chars().next() {
Some(first) if "AEIOU".contains(first.to_ascii_uppercase()) => "n",
_ => "",
}
}
fn the_hexadecimal_of_a_text(text: &str) -> Option<i64> {
let text = text.trim();
let (negative, digits) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text.strip_prefix('+').unwrap_or(text)),
};
let digits = digits
.strip_prefix("0x")
.or_else(|| digits.strip_prefix("0X"))?;
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
let magnitude = u64::from_str_radix(digits, 16).unwrap_or(u64::MAX);
let value = if magnitude > i64::MAX as u64 {
i64::MAX
} else {
magnitude as i64
};
Some(if negative { -value } else { value })
}
fn the_number_of_the_text(text: &str) -> f64 {
let text = text.trim();
let bytes = text.as_bytes();
let mut end = 0;
if end < bytes.len() && (bytes[end] == b'+' || bytes[end] == b'-') {
end += 1;
}
let mut digits = 0;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
digits += 1;
}
if end < bytes.len() && bytes[end] == b'.' {
end += 1;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
digits += 1;
}
}
if digits == 0 {
return 0.0;
}
if end < bytes.len() && (bytes[end] == b'e' || bytes[end] == b'E') {
let mut next = end + 1;
if next < bytes.len() && (bytes[next] == b'+' || bytes[next] == b'-') {
next += 1;
}
let mut exponent = 0;
while next < bytes.len() && bytes[next].is_ascii_digit() {
next += 1;
exponent += 1;
}
if exponent > 0 {
end = next;
}
}
text[..end].parse::<f64>().unwrap_or(0.0)
}
const STRING_MEMORY_BASE: i64 = 0x0000_5A00_0000_0000;
const STRING_MEMORY_STRIDE: i64 = 16;
fn the_capacity_of_a_text(text: &str) -> i64 {
let length = text.chars().count() as i64;
if length == 0 {
0
} else if length <= 3 {
3
} else if length <= 7 {
7
} else if length <= 63 {
63
} else {
length + 1
}
}
fn the_node_is_unset(node: &Node) -> bool {
match node {
Node::Unset { .. } => true,
Node::Var { name, .. } => name.eq_ignore_ascii_case("unset"),
_ => false,
}
}
pub fn expected_number(value: &Value) -> String {
format!("Expected a Number but got {}.", the_kind_of(value))
}
pub fn requires(index: usize, name: &str, wants: TypeName, value: &Value) -> String {
format!(
"Parameter #{index} of {name} requires a{} {}, but received {}.",
wants.article(),
wants.name(),
the_kind_of(value)
)
}
pub fn expects_a_kind(kind: TypeName, value: &Value) -> String {
format!(
"Expected a{} {} but got {}.",
kind.article(),
kind.name(),
the_kind_of(value)
)
}
pub fn accepts(kind: TypeName, value: &Value) -> bool {
match kind {
TypeName::String => matches!(value, Value::Text(_) | Value::Int(_) | Value::Float(_)),
TypeName::Number | TypeName::Integer => value.to_number_strict().is_ok(),
TypeName::Object => matches!(value, Value::Object(_)),
TypeName::VarRef => matches!(value, Value::Reference(_)),
TypeName::ComValue => false,
_ => true,
}
}
pub fn is_of_the_kind(kind: TypeName, value: &Value) -> bool {
match kind {
TypeName::String => matches!(value, Value::Text(_)),
TypeName::Object => matches!(value, Value::Object(_)),
_ => true,
}
}
pub fn the_kind_of(value: &Value) -> String {
match value {
Value::Text(text) if text.is_empty() => "an empty string".to_string(),
other => {
let kind = other.the_kind();
format!("a{} {}", the_article_of(&kind), kind)
}
}
}
pub fn unassigned_parameter() -> String {
"This parameter has not been assigned a value.".to_string()
}
pub(crate) fn the_mark_of_a_value_without_one() -> Value {
Value::List(vec![Value::Int(0)])
}
pub(crate) fn is_a_value_without_one(value: &Value) -> bool {
matches!(value, Value::List(items) if items.len() == 1 && items[0] == Value::Int(0))
}
pub fn invalid_parameter(index: usize, name: &str) -> String {
format!("Parameter #{index} of {name} is invalid.")
}
pub fn wants_a_reference(index: usize, name: &str, wants: &str, value: &Value) -> String {
format!(
"Parameter #{index} of {name} requires {wants}, but received {}.",
the_kind_of(value)
)
}
fn the_condition_of_a_hotif(argument: &str) -> Result<Option<Condition>, ()> {
let text = argument.trim();
if text.is_empty() {
return Ok(None);
}
let open = text.find('(').ok_or(())?;
let name = text[..open].trim().to_lowercase();
let inside = text[open + 1..].trim_end();
let inside = inside.strip_suffix(')').ok_or(())?.trim();
let title = inside
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.ok_or(())?;
if title.contains('"') {
return Err(());
}
let condition = match name.as_str() {
"winactive" => Condition::WindowActive(title.into()),
"winexist" => Condition::WindowExists(title.into()),
"winnotactive" => Condition::WindowNotActive(title.into()),
"winnotexist" => Condition::WindowNotExist(title.into()),
_ => return Err(()),
};
Ok(Some(condition))
}
fn the_boolean_of_a_directive(argument: &str) -> Option<bool> {
let argument = argument.trim();
if argument.is_empty() {
return Some(true);
}
match argument.to_ascii_lowercase().as_str() {
"true" | "on" | "1" => Some(true),
"false" | "off" | "0" => Some(false),
_ => None,
}
}
pub fn refusal_of_directive(name: &str) -> Option<&'static str> {
match name {
"commentflag" | "escapechar" => Some("the comment flags are not carried by this runtime."),
"maxmem" => Some("the memory limits are not carried by this runtime."),
"if"
| "iftimeout"
| "ifwinactive"
| "installkeybdhook"
| "installmousehook"
| "keyhistory"
| "maxhotkeysperinterval"
| "hotkeyinterval"
| "hotkeymodifiertimeout"
| "menumaskkey"
| "usehook"
| "maxthreads"
| "maxthreadsperhotkey"
| "maxthreadsbuffer" => Some("the hotkeys are not carried by this runtime."),
"clipboardtimeout" => Some("the clipboard is not carried by this runtime."),
"inputlevel" => Some("the input level is not carried by this runtime."),
"winactivateforce" => Some("the window activation is not carried by this runtime."),
"warn" => Some("the warnings are not carried by this runtime."),
"include" | "includeagain" => {
Some("the includes are resolved by the runner, not by the language.")
}
"dllload" => Some("a Windows library is a Windows thing and this box has none."),
_ => None,
}
}
fn the_name_of(path: &str) -> &str {
match path.rfind(['/', '\\']) {
Some(at) => &path[at + 1..],
None => path,
}
}
fn the_folder_of(path: &str) -> &str {
match path.rfind(['/', '\\']) {
Some(at) => &path[..at],
None => "",
}
}
fn the_path_that_is_relative_to(file: &str, folder: &str) -> String {
let rest = match file.strip_prefix(folder) {
Some(rest) => rest,
None => return file.to_string(),
};
rest.trim_start_matches(['/', '\\']).to_string()
}
fn the_extension_of(name: &str) -> &str {
match name.rfind('.') {
Some(at) if at > 0 => &name[at + 1..],
_ => "",
}
}
fn the_letter_that_the_mode_does_not_carry(mode: &str) -> Option<char> {
mode.chars().find(|letter| {
!matches!(
letter,
'R' | 'r' | 'D' | 'd' | 'F' | 'f' | 'V' | 'v' | 'K' | 'k' | ' ' | '\t'
)
})
}
fn without_the_extension(path: &str, extension: &str) -> String {
if extension.is_empty() {
return path.to_string();
}
path[..path.len() - extension.len() - 1].to_string()
}
pub(crate) const BASE: &str = "object base";
pub(crate) const DESCRIPTOR: &str = "property descriptor";
pub(crate) const METHOD_CLASS: &str = "method class";
pub(crate) const METHOD_NAME: &str = "method name";
pub(crate) const BOUND: &str = "bound object";
pub(crate) const BOUND_TARGET: &str = "bound target";
pub(crate) const CLOSURE: &str = "function closure";
pub(crate) const PARAMETERS: &str = "parameter flags";
fn the_flags_of_the_parameters(parameters: &[crate::ast::Parameter], this: bool) -> Value {
let mut flags: Vec<Value> = Vec::new();
if this {
flags.push(Value::Int(0));
}
flags.extend(parameters.iter().map(|parameter| {
Value::Int((parameter.by_ref as i64) | (((!parameter.is_required()) as i64) << 1))
}));
Value::List(flags)
}
pub(crate) const CLASS_NAME: &str = "class name";
type ScopeTable = Rc<RefCell<BTreeMap<String, Value>>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
Global,
Local(usize),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Reference {
pub name: String,
pub scope: Scope,
pub alias: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Int(i64),
Float(f64),
Text(String),
List(Vec<Value>),
Object(Rc<RefCell<Object>>),
Reference(Reference),
Skipped,
Unset,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Object {
pub class: String,
pub properties: BTreeMap<String, Property>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Property {
pub name: String,
pub value: Value,
}
pub(crate) fn put(properties: &mut BTreeMap<String, Property>, name: &str, value: Value) {
let key = name.to_lowercase();
let name = properties
.get(&key)
.map(|property| property.name.clone())
.unwrap_or_else(|| name.to_string());
properties.insert(key, Property { name, value });
}
impl Object {
pub fn value_of(&self, key: &str) -> Option<Value> {
self.properties
.get(key)
.map(|property| property.value.clone())
}
pub fn put(&mut self, name: &str, value: Value) {
put(&mut self.properties, name, value);
}
}
#[derive(Clone)]
pub struct Class {
pub name: String,
pub extends: Option<String>,
pub methods: BTreeMap<String, MethodDef>,
pub properties: Vec<PropertyDef>,
pub accessors: BTreeMap<String, AccessDef>,
pub nested: Vec<String>,
}
fn the_number_of_a_text(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
if let Some(hex) = text
.strip_prefix("0x")
.or_else(|| text.strip_prefix("0X"))
{
if hex.is_empty() || !hex.chars().all(|digit| digit.is_ascii_hexdigit()) {
return None;
}
return u128::from_str_radix(hex, 16).ok().map(|number| number as f64);
}
text.parse::<f64>().ok()
}
fn the_zero_of_a_text(text: &str) -> Option<bool> {
the_number_of_a_text(text).map(|number| number == 0.0)
}
impl Value {
pub fn truthy(&self) -> bool {
match self {
Value::Text(text) => match the_zero_of_a_text(text) {
Some(is_zero) => !is_zero,
None => !text.is_empty(),
},
Value::Int(number) => *number != 0,
Value::Float(number) => *number != 0.0,
Value::List(items) => !items.is_empty(),
Value::Unset | Value::Skipped => false,
Value::Object(_) => true,
Value::Reference(_) => true,
}
}
pub fn type_name(&self) -> TypeName {
match self {
Value::Int(_) => TypeName::Integer,
Value::Float(_) => TypeName::Float,
Value::Text(_) => TypeName::String,
Value::List(_) | Value::Object(_) => TypeName::Object,
Value::Unset | Value::Skipped => TypeName::String,
Value::Reference(_) => TypeName::VarRef,
}
}
pub fn to_text(&self) -> String {
match self {
Value::Int(number) => number.to_string(),
Value::Float(number) => crate::float_text::the_text_of(*number),
Value::Text(text) => text.clone(),
Value::Unset | Value::Skipped => String::new(),
Value::List(items) => items
.iter()
.map(|item| item.to_text())
.collect::<Vec<String>>()
.join(","),
Value::Object(object) => object.borrow().class.clone(),
Value::Reference(reference) => reference.name.clone(),
}
}
pub fn as_text(&self) -> Result<String, TypeName> {
match self {
Value::Reference(_) => Err(TypeName::VarRef),
other => Ok(other.to_text()),
}
}
pub fn the_kind(&self) -> String {
match self {
Value::Int(_) => "Integer".to_string(),
Value::Float(_) => "Float".to_string(),
Value::Text(_) => "String".to_string(),
Value::List(_) => "Array".to_string(),
Value::Reference(_) => "VarRef".to_string(),
Value::Unset | Value::Skipped => String::new(),
Value::Object(object) => {
let borrowed = object.borrow();
if borrowed.class == "prototype" {
return "Prototype".to_string();
}
if borrowed.properties.contains_key("prototype") {
return "Class".to_string();
}
let mut name = borrowed.class.clone();
if name.is_empty() {
name = "Object".to_string();
}
if let Some(first) = name.get_mut(0..1) {
first.make_ascii_uppercase();
}
name
}
}
}
pub fn to_number(&self) -> Option<f64> {
match self {
Value::Int(number) => Some(*number as f64),
Value::Float(number) => Some(*number),
Value::Text(text) => text.trim().parse::<f64>().ok(),
Value::List(_) | Value::Object(_) | Value::Reference(_) => None,
Value::Unset | Value::Skipped => None,
}
}
pub fn to_number_strict(&self) -> Result<f64, TypeName> {
match self {
Value::Int(number) => Ok(*number as f64),
Value::Float(number) => Ok(*number),
Value::Text(text) => {
let trimmed = text.trim();
if trimmed.is_empty() {
return Err(TypeName::String);
}
if let Some(number) = the_hexadecimal_of_a_text(trimmed) {
return Ok(number as f64);
}
trimmed.parse::<f64>().map_err(|_| TypeName::String)
}
Value::List(_) | Value::Object(_) => Err(TypeName::Object),
Value::Reference(_) => Err(TypeName::VarRef),
Value::Unset | Value::Skipped => Err(TypeName::String),
}
}
pub fn to_number_lenient(&self) -> f64 {
match self {
Value::Int(number) => *number as f64,
Value::Float(number) => *number,
Value::Text(text) => the_number_of_the_text(text),
_ => 0.0,
}
}
pub fn from_number(number: f64) -> Value {
if fract(number) == 0.0 && number.abs() < 9.0e15 {
Value::Int(number as i64)
} else {
Value::Float(number)
}
}
}
#[derive(Debug)]
pub struct RuntimeError {
pub message: String,
pub line: u32,
}
impl core::fmt::Display for RuntimeError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "{} (line {})", self.message, self.line)
}
}
#[cfg(feature = "std")]
impl std::error::Error for RuntimeError {}
#[derive(Debug)]
pub struct Timeout {
pub seconds: f64,
}
impl core::fmt::Display for Timeout {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "the script ran for more than {}s", self.seconds)
}
}
#[cfg(feature = "std")]
impl std::error::Error for Timeout {}
pub trait Clock {
fn now_ms(&self) -> u64;
fn sleep_ms(&mut self, millis: u64);
fn wall_clock(&self) -> Option<crate::date::WallClock> {
None
}
}
#[cfg(feature = "std")]
#[derive(Debug, Clone, Copy)]
pub struct SystemClock {
started: std::time::Instant,
}
#[cfg(feature = "std")]
impl SystemClock {
pub fn new() -> Self {
Self {
started: std::time::Instant::now(),
}
}
}
#[cfg(feature = "std")]
impl Default for SystemClock {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "std")]
impl Clock for SystemClock {
fn now_ms(&self) -> u64 {
self.started.elapsed().as_millis() as u64
}
fn sleep_ms(&mut self, millis: u64) {
std::thread::sleep(Duration::from_millis(millis));
}
fn wall_clock(&self) -> Option<crate::date::WallClock> {
crate::date::system_wall_clock()
}
}
enum ClockSource<'a> {
Borrowed(&'a mut dyn Clock),
#[cfg(feature = "std")]
System(SystemClock),
}
impl ClockSource<'_> {
fn now_ms(&self) -> u64 {
match self {
ClockSource::Borrowed(clock) => clock.now_ms(),
#[cfg(feature = "std")]
ClockSource::System(clock) => clock.now_ms(),
}
}
fn sleep_ms(&mut self, millis: u64) {
match self {
ClockSource::Borrowed(clock) => clock.sleep_ms(millis),
#[cfg(feature = "std")]
ClockSource::System(clock) => clock.sleep_ms(millis),
}
}
fn wall_clock(&self) -> Option<crate::date::WallClock> {
match self {
ClockSource::Borrowed(clock) => clock.wall_clock(),
#[cfg(feature = "std")]
ClockSource::System(clock) => clock.wall_clock(),
}
}
}
#[derive(Debug, Clone)]
pub struct Step {
pub line: u32,
pub op: String,
pub detail: String,
pub ok: bool,
pub elapsed_ms: u64,
}
#[derive(Debug, Clone, Default)]
pub struct Report {
pub ok: bool,
pub steps: Vec<Step>,
pub output: Vec<String>,
pub warnings: Vec<crate::warnings::Warning>,
pub notes: Vec<String>,
pub error: Option<String>,
pub error_line: Option<u32>,
pub exit_code: Option<i32>,
pub elapsed_ms: u64,
pub variables: BTreeMap<String, Value>,
}
pub(crate) enum Flow {
Break(u32),
Continue(u32),
Return(Option<Value>),
Exit(i32),
Goto {
name: String,
line: u32,
computed: bool,
},
}
pub(crate) enum TheFlowOfALoop {
Next,
Break,
Continue,
Out(RuntimeFailure),
}
fn the_flow_of_a_loop_body(outcome: Result<(), RuntimeFailure>) -> TheFlowOfALoop {
match outcome {
Ok(()) => TheFlowOfALoop::Next,
Err(RuntimeFailure::Flow(Flow::Break(level))) if level <= 1 => TheFlowOfALoop::Break,
Err(RuntimeFailure::Flow(Flow::Continue(level))) if level <= 1 => {
TheFlowOfALoop::Continue
}
Err(RuntimeFailure::Flow(Flow::Break(level))) => {
TheFlowOfALoop::Out(RuntimeFailure::Flow(Flow::Break(level - 1)))
}
Err(RuntimeFailure::Flow(Flow::Continue(level))) => {
TheFlowOfALoop::Out(RuntimeFailure::Flow(Flow::Continue(level - 1)))
}
Err(other) => TheFlowOfALoop::Out(other),
}
}
enum TheError {
Goes,
Hidden,
Continues,
}
#[derive(Clone)]
struct Function {
name: String,
pub(crate) parameters: Vec<Parameter>,
body: Vec<Node>,
declarations: Declarations,
closure: Vec<ScopeTable>,
}
struct Timer {
name: String,
period: u64,
last: u64,
}
#[derive(Clone)]
pub(crate) struct Callback {
pub name: String,
pub line: u32,
}
#[derive(Debug, Clone)]
struct Frame {
name: String,
line: u32,
}
pub struct Runtime<'a> {
desktop: &'a mut dyn Desktop,
clock: ClockSource<'a>,
dialect: &'static dyn crate::dialect::Dialect,
no_env: bool,
warnings: Vec<crate::warnings::Warning>,
modes: crate::warnings::TheModes,
auto_trim: bool,
integer_format: IntegerFormat,
float_format: FloatFormat,
case_sense: CaseSense,
batch_lines: alloc::string::String,
timeout: Duration,
variables: BTreeMap<String, Value>,
string_capacities: BTreeMap<(u8, String), i64>,
string_memory: RefCell<Vec<String>>,
initial_working_dir: Option<String>,
scopes: Vec<ScopeTable>,
label_scopes: Vec<Vec<String>>,
in_the_body_of_a_hotkey: bool,
declarations: Vec<Declarations>,
statics: BTreeMap<String, BTreeMap<String, Value>>,
statics_run: BTreeMap<String, BTreeSet<String>>,
current_classes: Vec<String>,
frames: Vec<Frame>,
loop_output_files: Vec<String>,
the_short_names_of_the_files_are_refused: bool,
source: Vec<String>,
auto_execute_line: u32,
functions: BTreeMap<String, Function>,
closures: usize,
classes: BTreeMap<String, Class>,
class_values: RefCell<BTreeMap<String, Value>>,
initialised: RefCell<BTreeSet<String>>,
steps: Vec<Step>,
output: Vec<String>,
notes: Vec<String>,
started_ms: u64,
random_seed: u64,
steps_taken: usize,
depth: usize,
stack_base: usize,
stack_budget: usize,
timers: Vec<Timer>,
hotkeys: Vec<crate::hotkeys::Hotkey>,
hotkeys_are_not_watched: bool,
hotif_condition: Option<crate::hotkeys::Condition>,
finally_labels: Vec<Vec<String>>,
suspended: bool,
paused: bool,
suspend_exempt: bool,
hotkey_is_exempt: Vec<bool>,
hotkey_was_enabled: Vec<bool>,
exit_requested: Option<i32>,
thrown_value: Option<Value>,
thread: Option<Value>,
exit_callbacks: Vec<Callback>,
error_callbacks: Vec<Callback>,
try_active: usize,
failure_hidden: bool,
caught_value: Option<Value>,
}
impl<'a> Runtime<'a> {
pub(crate) fn the_hotif(&mut self) -> Option<String> {
if let Some(condition) = crate::hotkeys::the_condition_of_the_script(self) {
return Some(crate::hotkeys::the_text_of_a_condition(&condition));
}
let mut answer = None;
for hotkey in self.hotkeys().iter() {
if let Some(condition) = &hotkey.condition {
answer = Some(crate::hotkeys::the_text_of_a_condition(condition));
}
}
answer
}
pub const MAX_STEPS: usize = 20_000;
pub const MAX_ITERATIONS: usize = 1000;
pub const MAX_DEPTH: usize = 1000;
pub const MAX_STACK: usize = 512 * 1024;
#[cfg(feature = "std")]
pub fn new(desktop: &'a mut dyn Desktop, timeout: Duration) -> Self {
let initial_working_dir = desktop.initial_working_directory().ok();
Self {
desktop,
clock: ClockSource::System(SystemClock::new()),
dialect: crate::dialect::v2(),
no_env: false,
warnings: Vec::new(),
modes: crate::warnings::TheModes::the_defaults_of_the_v2(),
auto_trim: true,
integer_format: IntegerFormat::Decimal,
float_format: FloatFormat::DEFAULT,
case_sense: CaseSense::Off,
batch_lines: "10ms".to_string(),
timeout,
variables: BTreeMap::new(),
statics: BTreeMap::new(),
statics_run: BTreeMap::new(),
initial_working_dir,
string_capacities: BTreeMap::new(),
string_memory: RefCell::new(Vec::new()),
scopes: Vec::new(),
label_scopes: Vec::new(),
in_the_body_of_a_hotkey: false,
declarations: Vec::new(),
current_classes: Vec::new(),
frames: Vec::new(),
loop_output_files: Vec::new(),
the_short_names_of_the_files_are_refused: false,
source: Vec::new(),
auto_execute_line: 0,
functions: BTreeMap::new(),
closures: 0,
classes: BTreeMap::new(),
class_values: RefCell::new(BTreeMap::new()),
initialised: RefCell::new(BTreeSet::new()),
steps: Vec::new(),
output: Vec::new(),
notes: Vec::new(),
started_ms: 0,
random_seed: 0,
steps_taken: 0,
depth: 0,
stack_base: Self::stack_here(),
stack_budget: Self::MAX_STACK,
timers: Vec::new(),
hotkeys: Vec::new(),
hotkeys_are_not_watched: false,
hotif_condition: None,
finally_labels: Vec::new(),
suspended: false,
paused: false,
suspend_exempt: false,
hotkey_is_exempt: Vec::new(),
hotkey_was_enabled: Vec::new(),
exit_requested: None,
thrown_value: None,
thread: None,
exit_callbacks: Vec::new(),
error_callbacks: Vec::new(),
try_active: 0,
failure_hidden: false,
caught_value: None,
}
}
pub fn with_clock(
desktop: &'a mut dyn Desktop,
clock: &'a mut dyn Clock,
timeout: Duration,
) -> Self {
let started_ms = clock.now_ms();
let initial_working_dir = desktop.initial_working_directory().ok();
Self {
desktop,
clock: ClockSource::Borrowed(clock),
random_seed: 0,
dialect: crate::dialect::v2(),
no_env: false,
warnings: Vec::new(),
modes: crate::warnings::TheModes::the_defaults_of_the_v2(),
auto_trim: true,
integer_format: IntegerFormat::Decimal,
float_format: FloatFormat::DEFAULT,
case_sense: CaseSense::Off,
batch_lines: "10ms".to_string(),
timeout,
variables: BTreeMap::new(),
statics: BTreeMap::new(),
statics_run: BTreeMap::new(),
initial_working_dir,
string_capacities: BTreeMap::new(),
string_memory: RefCell::new(Vec::new()),
scopes: Vec::new(),
label_scopes: Vec::new(),
in_the_body_of_a_hotkey: false,
declarations: Vec::new(),
current_classes: Vec::new(),
frames: Vec::new(),
loop_output_files: Vec::new(),
the_short_names_of_the_files_are_refused: false,
source: Vec::new(),
auto_execute_line: 0,
functions: BTreeMap::new(),
closures: 0,
classes: BTreeMap::new(),
class_values: RefCell::new(BTreeMap::new()),
initialised: RefCell::new(BTreeSet::new()),
steps: Vec::new(),
output: Vec::new(),
notes: Vec::new(),
started_ms,
steps_taken: 0,
depth: 0,
stack_base: Self::stack_here(),
stack_budget: Self::MAX_STACK,
timers: Vec::new(),
hotkeys: Vec::new(),
hotkeys_are_not_watched: false,
hotif_condition: None,
finally_labels: Vec::new(),
suspended: false,
paused: false,
suspend_exempt: false,
hotkey_is_exempt: Vec::new(),
hotkey_was_enabled: Vec::new(),
exit_requested: None,
thrown_value: None,
thread: None,
exit_callbacks: Vec::new(),
error_callbacks: Vec::new(),
try_active: 0,
failure_hidden: false,
caught_value: None,
}
}
pub fn with_stack_budget(mut self, bytes: usize) -> Self {
self.stack_budget = bytes;
self
}
pub fn with_source(mut self, source: &str) -> Self {
self.source = source.lines().map(|line| line.to_string()).collect();
self
}
pub fn with_dialect(mut self, dialect: &'static dyn crate::dialect::Dialect) -> Self {
self.dialect = dialect;
self.dialect.the_defaults_of_the_settings();
self
}
pub fn dialect(&self) -> &'static dyn crate::dialect::Dialect {
self.dialect
}
pub fn auto_trim(&self) -> bool {
self.auto_trim
}
pub fn set_auto_trim(&mut self, on: bool) {
self.auto_trim = on;
}
pub fn batch_lines(&self) -> &str {
&self.batch_lines
}
pub fn set_batch_lines(&mut self, text: &str) {
self.batch_lines = text.to_string();
}
pub fn integer_format(&self) -> IntegerFormat {
self.integer_format
}
pub fn float_format(&self) -> FloatFormat {
self.float_format
}
pub fn set_integer_format(&mut self, format: IntegerFormat) {
self.integer_format = format;
}
pub fn set_float_format(&mut self, format: FloatFormat) {
self.float_format = format;
}
pub fn case_sense(&self) -> CaseSense {
self.case_sense
}
pub(crate) fn set_the_error_level(&mut self, value: Value) {
self.variables.insert(the_key_of("ErrorLevel"), value);
}
pub fn set_case_sense(&mut self, sense: CaseSense) {
self.case_sense = sense;
}
pub(crate) fn an_object_has_no_text(&self) -> bool {
self.dialect.an_object_has_no_text()
}
pub fn the_text_of(&self, value: &Value) -> String {
if self.dialect.an_object_has_no_text() {
if let Value::Object(_) = value {
return String::new();
}
}
if !self.dialect.formats_the_numbers() {
return value.to_text();
}
match value {
Value::Int(number) => self.integer_format.the_text_of(*number),
Value::Float(number) => self.float_format.the_text_of(*number),
other => other.to_text(),
}
}
pub(crate) fn builtin(&self, name: &str) -> Option<&'static crate::builtins::Builtin> {
let wanted = name.to_lowercase();
crate::builtins::the_builtin_in_the_dialect(self.dialect, &wanted)
}
pub(crate) fn the_seed_of_the_random(&self) -> u64 {
self.random_seed
}
pub(crate) fn seed_the_random(&mut self, seed: i64) {
self.random_seed = seed as u64;
}
pub(crate) fn the_builtin_of_the_kind(
&self,
name: &str,
kind: crate::builtins::BuiltinKind,
) -> Option<&'static crate::builtins::Builtin> {
let wanted = name.to_lowercase();
let builtins = self.dialect.builtins();
builtins
.iter()
.find(|builtin| builtin.name.to_lowercase() == wanted && builtin.kind == kind)
.or_else(|| {
builtins
.iter()
.find(|builtin| builtin.name.to_lowercase() == wanted)
})
.or_else(|| self.dialect.the_builtin_of_the_extension(&wanted))
}
pub(crate) fn elapsed_ms(&self) -> u64 {
self.clock.now_ms().saturating_sub(self.started_ms)
}
pub(crate) fn remaining_ms(&self) -> u64 {
let limit = self.timeout.as_millis() as u64;
limit.saturating_sub(self.elapsed_ms())
}
fn register_the_hotkeys_of_the_v1(&mut self, statements: &[Node]) -> Result<(), RuntimeError> {
for statement in statements {
if let Node::HotkeyDefinition {
name, body, line, ..
} = statement
{
crate::hotkeys::register_the_hotkey_of_the_v1(self, name, body.clone(), *line)
.map_err(|failure| match failure {
RuntimeFailure::Error(error) => error,
RuntimeFailure::Detailed(error, _) => error,
RuntimeFailure::Fatal(error) => error,
_ => RuntimeError {
message: "the hotkey could not be registered.".to_string(),
line: *line,
},
})?;
self.hotkey_is_exempt.push(false);
self.hotkey_was_enabled.push(true);
self.register_the_hotkeys_of_the_v1(body)?;
}
}
Ok(())
}
fn register_the_hotkeys_of_the_v2(&mut self, statements: &[Node]) -> Result<(), RuntimeError> {
for statement in statements {
if let Node::HotkeyDefinition {
name, body, line, ..
} = statement
{
if name.starts_with("::") {
continue;
}
crate::hotkeys::register_the_hotkey_of_the_v2(
self,
name,
body.clone(),
*line,
self.hotif_condition.clone(),
)
.map_err(|failure| match failure {
RuntimeFailure::Error(error) => error,
RuntimeFailure::Detailed(error, _) => error,
RuntimeFailure::Fatal(error) => error,
_ => RuntimeError {
message: "the hotkey could not be registered.".to_string(),
line: *line,
},
})?;
self.hotkey_is_exempt.push(self.suspend_exempt);
self.hotkey_was_enabled.push(true);
self.register_the_hotkeys_of_the_v2(body)?;
continue;
}
if let Node::Directive {
name, argument, line, ..
} = statement
{
if name.eq_ignore_ascii_case("suspendexempt") {
if let Some(exempt) = the_boolean_of_a_directive(argument) {
self.suspend_exempt = exempt;
}
}
if name.eq_ignore_ascii_case("hotif") {
match the_condition_of_a_hotif(argument) {
Ok(condition) => self.hotif_condition = condition,
Err(()) => {
return Err(RuntimeError {
message: "The condition of #HotIf is not carried by this runtime: only the WinActive, WinExist, WinNotActive and WinNotExist forms with a literal title are.".to_string(),
line: *line,
})
}
}
}
}
}
Ok(())
}
pub fn run(mut self, statements: &[Node]) -> Report {
let mut error = None;
let mut error_line = None;
let mut exit_code = None;
self.collect_functions(statements);
self.warnings = self.the_warnings_of_the_script(statements);
let registered = if self.dialect.the_hotkeys_are_of_the_v2() {
self.register_the_hotkeys_of_the_v2(statements)
} else {
self.register_the_hotkeys_of_the_v1(statements)
};
self.set_global("A_LineFile", Value::Text("*".to_string()));
self.label_scopes.push(the_labels_of(statements));
match registered {
Ok(()) => match self.run_block(statements) {
Ok(()) => {}
Err(RuntimeFailure::Flow(Flow::Break(_)))
| Err(RuntimeFailure::Flow(Flow::Continue(_))) => {}
Err(RuntimeFailure::Flow(Flow::Return(_))) => {}
Err(RuntimeFailure::Flow(Flow::Exit(code))) => exit_code = Some(code),
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => {
let failure = if computed {
self.the_failure_of_a_computed_jump(&name, statements, line)
} else {
let error = self.the_label_is_not_there(&name, statements, line);
RuntimeFailure::Error(error)
};
let (message, line) = match failure {
RuntimeFailure::Error(error)
| RuntimeFailure::Detailed(error, _)
| RuntimeFailure::Fatal(error) => (error.message, error.line),
_ => (String::new(), line),
};
error = Some(message);
error_line = Some(line);
}
Err(RuntimeFailure::Fatal(failure)) => {
error = Some(failure.message);
error_line = Some(failure.line);
}
Err(RuntimeFailure::Error(failure)) => {
error = Some(failure.message);
error_line = Some(failure.line);
}
Err(RuntimeFailure::Detailed(failure, _)) => {
error = Some(failure.message);
error_line = Some(failure.line);
}
Err(RuntimeFailure::Timeout(timeout)) => {
error = Some(timeout.to_string());
}
Err(RuntimeFailure::Thrown(value)) => {
error = Some(thrown_message(&value));
}
},
Err(failure) => {
error = Some(failure.message);
error_line = Some(failure.line);
}
}
if self.failure_hidden {
error = None;
error_line = None;
}
let reason = if error.is_some() { "Error" } else { "Exit" };
let code = exit_code.unwrap_or(0);
self.exit_requested = None;
let mut prevented = false;
let callbacks: Vec<Callback> = core::mem::take(&mut self.exit_callbacks);
for callback in callbacks {
let values = [Value::Text(reason.to_string()), Value::Int(code as i64)];
match self.call_named(&callback.name, &values, callback.line, Route::Written) {
Ok(answer) => {
if answer.to_number().unwrap_or(0.0) != 0.0 {
prevented = true;
break;
}
}
Err(failure) => {
let (message, line) = match failure {
RuntimeFailure::Error(error) => (error.message, error.line),
RuntimeFailure::Detailed(error, _) => (error.message, error.line),
RuntimeFailure::Fatal(error) => (error.message, error.line),
RuntimeFailure::Thrown(value) => (thrown_message(&value), 0),
RuntimeFailure::Timeout(timeout) => (timeout.to_string(), 0),
RuntimeFailure::Flow(_) => (
"the function of the exit left the script in the middle of a block."
.to_string(),
0,
),
};
if error.is_none() {
error = Some(message);
error_line = Some(if line == 0 { callback.line } else { line });
} else {
self.note(format!("the function of the exit failed: {message}"));
}
}
}
}
if prevented {
exit_code = None;
self.note(
"a function of the exit asked to keep the script alive, and this runtime ends the script when its statements end.",
);
}
if let Some(code) = self.exit_requested {
exit_code = Some(code);
}
let elapsed_ms = self.elapsed_ms();
Report {
ok: error.is_none(),
steps: self.steps,
output: self.output,
warnings: self.warnings,
notes: self.notes,
error,
error_line,
exit_code,
elapsed_ms,
variables: self.variables.clone(),
}
}
fn the_warnings_of_the_script(&mut self, statements: &[Node]) -> Vec<crate::warnings::Warning> {
self.modes = crate::warnings::the_modes_of_the_script(statements, self.dialect);
for kind in crate::warnings::the_types_of_the_script(statements, self.dialect) {
if !crate::warnings::the_types_that_are_carried().contains(&kind) {
self.note(format!(
"the warnings of the type \"{}\" are not carried by this runtime.",
crate::warnings::the_name_of_the_type(kind)
));
}
}
let mut warnings = Vec::new();
if self.modes.local_same_as_global != crate::warnings::WarningMode::Off {
let mode = self.modes.local_same_as_global;
for warning in crate::warnings::the_warnings_of_the_locals_that_are_globals(
statements,
self.dialect,
) {
self.warn(warning.line, warning.message.clone(), mode);
warnings.push(warning);
}
}
if self.modes.var_unset != crate::warnings::WarningMode::Off {
let mode = self.modes.var_unset;
for warning in
crate::warnings::the_warnings_of_the_variables_that_are_never_written(statements)
{
self.warn(warning.line, warning.message.clone(), mode);
warnings.push(warning);
}
}
if self.modes.class_overwrite != crate::warnings::WarningMode::Off {
let mode = self.modes.class_overwrite;
for warning in
crate::warnings::the_warnings_of_the_classes_that_are_overwritten(statements)
{
self.warn(warning.line, warning.message.clone(), mode);
warnings.push(warning);
}
}
if self.modes.unreachable != crate::warnings::WarningMode::Off {
let mode = self.modes.unreachable;
for warning in crate::warnings::the_warnings_of_the_script(statements) {
self.warn(warning.line, warning.message.clone(), mode);
warnings.push(warning);
}
}
warnings
}
fn warn(&mut self, line: u32, message: String, mode: crate::warnings::WarningMode) {
self.warnings.push(crate::warnings::Warning {
line,
message: message.clone(),
});
if mode == crate::warnings::WarningMode::StdOut {
self.output
.push(format!("({line}) : ==> Warning: {message}"));
}
}
fn warn_about_the_variable_that_has_no_value(&mut self, name: &str, line: u32) {
if !self.dialect.unset_is_blank() {
return;
}
let local = !matches!(self.the_scope_of(name), Scope::Global);
let kind = if local {
if self.variables.contains_key(&the_key_of(name)) {
"a local variable with same name as a global"
} else {
"a local variable"
}
} else {
"a global variable"
};
let mode = if local {
self.modes.use_unset_local
} else {
self.modes.use_unset_global
};
if mode == crate::warnings::WarningMode::Off {
return;
}
self.warn(
line,
format!(
"This variable has not been assigned a value.\n Specifically: {name} ({kind})"
),
mode,
);
}
fn warn_about_the_environment_that_is_accessed(&mut self, name: &str, line: u32) {
let mode = self.modes.use_env;
if mode == crate::warnings::WarningMode::Off {
return;
}
let message = format!(
"An environment variable is being accessed; see #NoEnv.\n Specifically: {name}"
);
self.warn(line, message, mode);
}
pub fn note(&mut self, note: impl Into<String>) {
self.notes.push(note.into());
}
fn collect_functions(&mut self, statements: &[Node]) {
for statement in statements {
match statement {
Node::ClassDef {
name,
extends,
methods,
properties,
accessors,
nested,
..
} => {
let mut table: BTreeMap<String, MethodDef> = BTreeMap::new();
for method in methods {
table.insert(method.name.to_lowercase(), method.clone());
}
let mut properties_with_a_getter: BTreeMap<String, AccessDef> = BTreeMap::new();
for access in accessors {
properties_with_a_getter.insert(access.name.to_lowercase(), access.clone());
}
let mut held = Vec::new();
for node in nested {
if let Node::ClassDef { name, .. } = node {
held.push(name.to_lowercase());
}
}
self.classes.insert(
name.to_lowercase(),
Class {
name: name.clone(),
extends: extends.clone(),
methods: table,
properties: properties.clone(),
accessors: properties_with_a_getter,
nested: held,
},
);
self.collect_functions(nested);
}
Node::FunctionDef {
name,
parameters,
body,
declarations,
..
} => {
self.functions.insert(
name.to_lowercase(),
Function {
name: name.clone(),
parameters: parameters.clone(),
body: body.clone(),
declarations: declarations.clone(),
closure: Vec::new(),
},
);
}
Node::Block { body, .. } => self.collect_functions(body),
Node::LegacyIf {
body, otherwise, ..
} => {
self.collect_functions(body);
self.collect_functions(otherwise);
}
Node::If {
branches,
otherwise,
..
} => {
for branch in branches {
self.collect_functions(&branch.tail);
self.collect_functions(&branch.body);
}
self.collect_functions(otherwise);
}
Node::Switch { cases, .. } => {
for case in cases {
self.collect_functions(&case.body);
}
}
Node::While { body, .. } | Node::Loop { body, .. } => self.collect_functions(body),
Node::Try {
body,
catches,
otherwise,
finally,
..
} => {
self.collect_functions(body);
for catch in catches {
self.collect_functions(&catch.body);
}
self.collect_functions(otherwise);
self.collect_functions(finally);
}
_ => {}
}
}
}
fn collect_the_nested_functions(&mut self, statements: &[Node]) {
for statement in statements {
match statement {
Node::FunctionDef {
name,
parameters,
body,
declarations,
..
} => {
let function = Function {
name: name.clone(),
parameters: parameters.clone(),
body: body.clone(),
declarations: declarations.clone(),
closure: self.scopes.clone(),
};
let closure = self.make_a_closure(function.clone());
let value = closure_value(&closure, &function, false);
self.assign_in_the_scope(name, value);
}
Node::Block { body, .. } => self.collect_the_nested_functions(body),
Node::LegacyIf {
body, otherwise, ..
} => {
self.collect_the_nested_functions(body);
self.collect_the_nested_functions(otherwise);
}
Node::If {
branches,
otherwise,
..
} => {
for branch in branches {
self.collect_the_nested_functions(&branch.body);
}
self.collect_the_nested_functions(otherwise);
}
Node::Switch { cases, .. } => {
for case in cases {
self.collect_the_nested_functions(&case.body);
}
}
Node::While { body, .. } | Node::Loop { body, .. } => {
self.collect_the_nested_functions(body)
}
Node::Try {
body,
catches,
otherwise,
finally,
..
} => {
self.collect_the_nested_functions(body);
for catch in catches {
self.collect_the_nested_functions(&catch.body);
}
self.collect_the_nested_functions(otherwise);
self.collect_the_nested_functions(finally);
}
_ => {}
}
}
}
fn the_label_is_not_there(&self, name: &str, scope: &[Node], line: u32) -> RuntimeError {
if the_labels_of(scope)
.iter()
.any(|label| label.eq_ignore_ascii_case(name))
{
return RuntimeError {
message: self
.dialect
.the_refusal_of_a_jump_into_a_block()
.to_string(),
line,
};
}
RuntimeError {
message: format!("Label not found in current scope.\n Specifically: {name}"),
line,
}
}
fn the_jump_leaves_a_finally(&self, name: &str) -> bool {
let Some(labels) = self.finally_labels.last() else {
return false;
};
!labels.iter().any(|label| label.eq_ignore_ascii_case(name))
}
fn the_failure_of_a_computed_jump(
&self,
name: &str,
scope: &[Node],
line: u32,
) -> RuntimeFailure {
if the_labels_of(scope)
.iter()
.any(|label| label.eq_ignore_ascii_case(name))
{
return RuntimeFailure::Error(RuntimeError {
message: self
.dialect
.the_refusal_of_a_jump_into_a_block()
.to_string(),
line,
});
}
RuntimeFailure::Detailed(
RuntimeError {
message: "Label not found in current scope.".to_string(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
)
}
pub fn has_label(&self, name: &str) -> bool {
let Some(scope) = self.label_scopes.last() else {
return false;
};
scope.iter().any(|label| label.eq_ignore_ascii_case(name))
}
fn run_block(&mut self, statements: &[Node]) -> Result<(), RuntimeFailure> {
let caller_line = self.lookup("A_LineNumber");
let answer = self.run_the_statements_of_a_block(statements);
if let Some(line) = caller_line {
self.set_global("A_LineNumber", line);
}
answer
}
fn run_the_statements_of_a_block(
&mut self,
statements: &[Node],
) -> Result<(), RuntimeFailure> {
let mut index = 0;
while index < statements.len() {
let statement = &statements[index];
self.set_global("A_LineNumber", Value::Int(statement.line() as i64));
match self.execute(statement) {
Ok(()) => {}
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => {
match the_place_of_the_label(statements, &name) {
Some(place) => index = place,
None => {
return Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
}))
}
}
}
Err(failure @ RuntimeFailure::Fatal(_)) => return Err(failure),
Err(failure) => match self.ask_the_error_callbacks(&failure) {
TheError::Continues => {}
TheError::Hidden => {
self.failure_hidden = true;
self.note(format!(
"the functions of the error hid the failure: {}",
the_message_of(&failure)
));
return Err(failure);
}
TheError::Goes => return Err(failure),
},
}
if self.the_section_that_runs() {
self.run_timers()?;
if !self.hotkeys_are_not_watched {
match crate::hotkeys::run_fired(self) {
Ok(()) => {}
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => {
match the_place_of_the_label(statements, &name) {
Some(place) => index = place,
None => {
return Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
}))
}
}
}
Err(failure) => {
if self.dialect.the_hotkeys_are_of_the_v2() {
let message = match &failure {
RuntimeFailure::Error(error) => error.message.clone(),
RuntimeFailure::Detailed(error, _) => error.message.clone(),
RuntimeFailure::Fatal(error) => error.message.clone(),
_ => "the keyboard cannot be watched".to_string(),
};
self.hotkeys_are_not_watched = true;
self.note(format!(
"the hotkeys of this script are not watched on this desktop: {message}"
));
} else {
return Err(failure);
}
}
}
}
if self.dialect.the_section_that_runs_ends_at_the_hotkey()
&& self.the_statement_ends_the_section(statement)
{
return Ok(());
}
}
if let Some(code) = self.exit_requested {
return Err(RuntimeFailure::Flow(Flow::Exit(code)));
}
index += 1;
}
Ok(())
}
pub(crate) fn run_the_body_of_a_hotkey(&mut self, body: &[Node]) -> Result<(), RuntimeFailure> {
let was_in_the_body = self.in_the_body_of_a_hotkey;
self.in_the_body_of_a_hotkey = true;
let answer = self.run_block(body);
self.in_the_body_of_a_hotkey = was_in_the_body;
match answer {
Err(RuntimeFailure::Flow(Flow::Return(_))) => Ok(()),
other => other,
}
}
fn the_section_that_runs(&self) -> bool {
self.scopes.is_empty() && !self.in_the_body_of_a_hotkey
}
fn the_statement_ends_the_section(&self, statement: &Node) -> bool {
match statement {
Node::HotkeyDefinition { .. } => true,
Node::LegacyCall { name, .. } => name == "hotstring",
_ => false,
}
}
fn run_try(
&mut self,
body: &[Node],
catches: &[crate::ast::Catch],
otherwise: &[Node],
finally: &[Node],
) -> Result<(), RuntimeFailure> {
self.try_active += 1;
let mut failure = self.run_block(body).err();
self.try_active -= 1;
let mut taken = false;
let thrown = match failure.as_ref() {
Some(RuntimeFailure::Error(error)) => Some(self.error_value(error)),
Some(RuntimeFailure::Detailed(error, detail)) => {
Some(self.error_value_with(error, detail))
}
Some(RuntimeFailure::Thrown(value)) => Some(value.clone()),
_ => None,
};
if let Some(value) = thrown {
for catch in catches {
if !self.catch_takes(catch, &value)? {
continue;
}
taken = true;
if let Some(variable) = &catch.variable {
self.assign(variable, value.clone());
}
let before = self.caught_value.replace(value);
let result = self.run_block(&catch.body);
self.caught_value = before;
failure = result.err();
break;
}
}
if !taken && failure.is_none() {
failure = self.run_block(otherwise).err();
}
self.finally_labels.push(the_labels_of(finally));
let in_finally = self.run_block(finally);
self.finally_labels.pop();
if let Err(other) = in_finally {
failure = Some(other);
}
match failure {
Some(failure) => Err(failure),
None => Ok(()),
}
}
fn catch_takes(
&self,
catch: &crate::ast::Catch,
value: &Value,
) -> Result<bool, RuntimeFailure> {
let class = catch.class.to_lowercase();
if class == "any" {
return Ok(true);
}
if class == "error" {
let Value::Object(object) = value else {
return Ok(false);
};
return Ok(crate::classes::error::is_a_class(&object.borrow().class));
}
let known = self.classes.contains_key(&class)
|| crate::classes::is_type(&class)
|| class == "object";
if !known {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"the class of a catch is not a class of this runtime: {}",
catch.class
),
line: 0,
}));
}
Ok(self.value_has_class(value, &class))
}
fn value_has_class(&self, value: &Value, class: &str) -> bool {
let Value::Object(object) = value else {
return false;
};
let mut name = object.borrow().class.clone();
loop {
if name.eq_ignore_ascii_case(class) {
return true;
}
match self.classes.get(&name.to_lowercase()) {
Some(definition) => match &definition.extends {
Some(base) => name = base.clone(),
None => return false,
},
None => return false,
}
}
}
fn error_value(&self, error: &RuntimeError) -> Value {
crate::classes::error::error_value_of(
crate::classes::error::the_class_of(&error.message),
&error.message,
"",
"",
error.line,
&self.the_stack(),
)
}
fn error_value_with(&self, error: &RuntimeError, detail: &Detail) -> Value {
let class = if error.message == "Invalid parameter(s)."
&& detail.what.eq_ignore_ascii_case("Mod")
{
"TypeError"
} else {
crate::classes::error::the_class_of(&error.message)
};
crate::classes::error::error_value_of(
class,
&error.message,
&detail.what,
&detail.extra,
error.line,
&self.the_stack(),
)
}
pub(crate) fn the_stack(&self) -> String {
let mut lines: Vec<String> = Vec::new();
for frame in self.frames.iter().rev() {
lines.push(self.the_line_of_a_frame(&frame.name, frame.line));
}
lines.push(self.the_line_of_a_frame("", self.auto_execute_line));
lines.push("> Auto-execute".to_string());
lines.join("\n")
}
fn the_line_of_a_frame(&self, name: &str, line: u32) -> String {
format!(" ({line}) : [{name}] {}", self.the_source_of_the_line(line))
}
fn the_source_of_the_line(&self, line: u32) -> String {
self.source
.get(line.saturating_sub(1) as usize)
.map(|text| text.trim().to_string())
.unwrap_or_default()
}
fn name_the_thrower(&self, value: &Value) {
let Value::Object(object) = value else { return };
if object.borrow().class != "error" {
return;
}
let carries = object
.borrow()
.value_of("what")
.map(|what| !what.to_text().is_empty())
.unwrap_or(false);
if carries {
return;
}
let Some(frame) = self.frames.last() else {
return;
};
put(
&mut object.borrow_mut().properties,
"what",
Value::Text(frame.name.clone()),
);
}
pub(crate) fn the_timers(&self) -> Vec<(String, u64, u64)> {
self.timers
.iter()
.map(|timer| (timer.name.clone(), timer.period, timer.last))
.collect()
}
fn run_timers(&mut self) -> Result<(), RuntimeFailure> {
let now = self.now_ms();
let due: Vec<String> = self
.timers
.iter_mut()
.filter(|timer| now.saturating_sub(timer.last) >= timer.period)
.map(|timer| {
timer.last = now;
timer.name.clone()
})
.collect();
for name in due {
let Some(function) = self.functions.get(&name.to_lowercase()).cloned() else {
continue;
};
self.call_function(&function, &[], 0, Route::Written)?;
}
Ok(())
}
pub(crate) fn add_timer(&mut self, name: &str, period: u64) {
let last = self.now_ms();
self.timers.push(Timer {
name: name.to_string(),
period,
last,
});
}
pub(crate) fn exit_with(&mut self, code: i32) {
self.exit_requested = Some(code);
}
pub(crate) fn throw_the_value(&mut self, value: Value) {
self.thrown_value = Some(value);
}
pub(crate) fn take_the_thrown_value(&mut self) -> Option<Value> {
self.thrown_value.take()
}
pub(crate) fn the_current_thread(&mut self) -> Value {
if let Some(thread) = &self.thread {
return thread.clone();
}
let thread = crate::classes::object("thread");
self.thread = Some(thread.clone());
thread
}
pub(crate) fn the_properties_of_a_value(
&self,
target: &Value,
) -> Option<Vec<(Value, Value)>> {
let Value::Object(object) = target else {
return None;
};
let class = object.borrow().class.to_lowercase();
let definition = self.classes.get(&class)?;
let mut pairs: Vec<(Value, Value)> = Vec::new();
let mut named: Vec<String> = Vec::new();
for property in &definition.properties {
named.push(property.name.clone());
}
for access in definition.accessors.values() {
if !named
.iter()
.any(|name| name.eq_ignore_ascii_case(&access.name))
{
named.push(access.name.clone());
}
}
for name in named {
let value = object
.borrow()
.properties
.get(&name.to_lowercase())
.map(|property| property.value.clone())
.unwrap_or(Value::Unset);
pairs.push((Value::Text(name), value));
}
for (key, property) in object.borrow().properties.iter() {
if key.as_str() == BASE
|| key.as_str() == CLASS_NAME
|| key.as_str() == "prototype"
|| key.starts_with('\u{1}')
{
continue;
}
if pairs
.iter()
.any(|(name, _)| name.to_text().eq_ignore_ascii_case(&property.name))
{
continue;
}
pairs.push((Value::Text(property.name.clone()), property.value.clone()));
}
Some(pairs)
}
pub(crate) fn base_object(
&mut self,
target: &Value,
name: &str,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeError> {
match self.base_method(target, name, arguments, line) {
Some(Ok(value)) => Ok(value),
Some(Err(RuntimeFailure::Error(error))) => Err(error),
Some(Err(RuntimeFailure::Detailed(error, _))) => Err(error),
Some(Err(_)) => Err(RuntimeError {
message: "the runtime cannot answer that.".into(),
line,
}),
None => Err(RuntimeError {
message: format!(
"This value of type \"{}\" has no method named {name:?}.",
self.the_type_of(target)
),
line,
}),
}
}
fn execute(&mut self, statement: &Node) -> Result<(), RuntimeFailure> {
self.steps_taken += 1;
match self.frames.last_mut() {
Some(frame) => frame.line = statement.line(),
None => self.auto_execute_line = statement.line(),
}
if self.steps_taken > Self::MAX_STEPS {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!("the script ran more than {} statements", Self::MAX_STEPS),
line: statement.line(),
}));
}
if self.elapsed_ms() > self.timeout.as_millis() as u64 {
return Err(RuntimeFailure::Timeout(Timeout {
seconds: self.timeout.as_secs_f64(),
}));
}
let started = self.clock.now_ms();
let mut detail = String::new();
match statement {
Node::Assign {
name,
op,
value,
line,
} => {
if *op == AssignOp::Set && the_node_is_unset(value) {
self.unset_variable(name);
detail = format!("{name} = ");
} else {
let value = self.evaluate(value)?;
if *op == AssignOp::Set && matches!(value, Value::Unset | Value::Skipped) {
self.unset_variable(name);
detail = format!("{name} = ");
} else {
let stored = self.write_a_variable(name, *op, value, *line)?;
detail = format!("{name} = {}", stored.to_text());
}
}
}
Node::CallValue {
target,
arguments,
line,
} => {
let value = self.evaluate(target)?;
let answer = self.call_the_value_of(value, arguments, *line)?;
detail = answer.to_text();
}
Node::LegacyAssign { name, text, line } => { let value = self.the_value_of_a_legacy_assignment(text, *line)?;
let stored = self.write_a_variable(name, AssignOp::Set, value, *line)?;
detail = format!("{name} = {}", stored.to_text());
}
Node::LegacyCall {
name,
parameters,
line,
} => {
let value = self.the_legacy_command(name, parameters, *line)?;
detail = value.to_text();
}
Node::LegacyIf {
name,
parameters,
body,
otherwise,
line,
} => {
let holds = self.the_condition_of_a_legacy_if(name, parameters, *line)?;
if holds {
self.run_block(body)?;
} else {
self.run_block(otherwise)?;
}
}
Node::ClassDef { name, line, .. } => {
self.initialise_the_class(name, *line)?;
detail = format!("the class {name} is defined");
}
Node::ArrayLiteral { .. } => {
}
Node::ObjectLiteral { .. } => {
}
Node::Lambda { .. } => {
}
Node::For {
variables,
source,
body,
until,
otherwise,
line,
} => {
self.for_loop(variables, source, body, until, otherwise, *line)?;
}
Node::MethodCall {
target,
name,
arguments,
line,
} => {
let name = self.the_name_of_the_member(name, *line)?;
let value = if let Node::Super { .. } = &**target {
self.call_the_method_of_the_base(&name, arguments, *line)?
} else {
let target_value = self.evaluate(target)?;
self.call_method_on(&target_value, &name, arguments, *line)?
};
detail = value.to_text();
}
Node::Property { target, name, line } => {
let name = self.the_name_of_the_member(name, *line)?;
let value = if let Node::Super { .. } = &**target {
self.read_the_property_of_the_base(&name, *line)?
} else {
let target_value = self.evaluate(target)?;
self.read_property(&target_value, &name, *line)?
};
detail = value.to_text();
}
Node::AssignDynamic {
name,
op,
value,
line,
} => {
let name = self.the_name_of_the_pieces(name, *line)?;
let value = self.evaluate(value)?;
let stored = self.write_a_dynamic_name(&name, *op, value, *line)?;
detail = format!("{name} = {}", stored.to_text());
}
Node::AssignProperty {
target,
name,
op,
value,
line,
} => {
if matches!(&**target, Node::Maybe { .. })
&& self.dialect.the_chain_may_be_skipped()
&& matches!(self.evaluate(target)?, Value::Unset | Value::Skipped)
{
detail = String::new();
} else {
let value = self.evaluate(value)?;
let name = self.the_name_of_the_member(name, *line)?;
let stored = self.write_a_property(target, &name, *op, value, *line)?;
detail = format!("{name} = {}", stored.to_text());
}
}
Node::AssignIndex {
target,
index,
also,
op,
value,
line,
} => {
if let Node::Property { .. } = &**target {
let stored = self.write_the_property_of_a_parameterised_item(
target, index, also, *op, value, *line,
)?;
detail = stored.to_text();
} else {
let target_value = self.evaluate(target)?;
if self.dialect.the_chain_may_be_skipped()
&& matches!(target_value, Value::Unset)
{
detail = String::new();
} else {
let keys = self.the_keys_of_an_index(index, also)?;
let value = self.evaluate(value)?;
let stored = self.set_item(&target_value, &keys, *op, value, *line)?;
let key = keys.first().map(Value::to_text).unwrap_or_default();
detail = format!("{key} = {}", stored.to_text());
}
}
} Node::Call {
name,
arguments,
line,
} => {
let value = self.call(name, arguments, *line)?;
detail = value.to_text();
}
Node::New {
path,
arguments,
line,
} => {
let value = self.new_instance(path, arguments, *line)?;
detail = value.to_text();
}
Node::Block { body, .. } => {
self.run_block(body)?;
}
Node::If {
branches,
otherwise,
..
} => {
let mut taken = false;
for branch in branches {
let value = self.the_value_of_the_condition(&branch.condition)?;
for item in &branch.tail {
self.evaluate(item)?;
}
if self.the_value_is_true(&value) {
self.run_block(&branch.body)?;
taken = true;
break;
}
}
if !taken {
self.run_block(otherwise)?;
}
}
Node::Switch {
subject,
cases,
line,
} => {
let value = self.evaluate(subject)?;
let mut matched = false;
for case in cases {
if case.values.is_empty() {
self.run_block(&case.body)?;
matched = true;
break;
}
for expected in &case.values {
let expected = self.evaluate(expected)?;
if values_equal(&value, &expected, false) {
self.run_block(&case.body)?;
matched = true;
break;
}
}
if matched {
break;
}
}
let _ = (matched, line);
}
Node::While {
condition,
body,
until,
otherwise,
..
} => {
if body.is_empty() && self.dialect.a_loop_without_a_body_ends_the_script() {
return Err(RuntimeFailure::Flow(Flow::Return(None)));
}
let mut iterations = 0usize;
let mut turn = 1i64;
let saved = self.the_index_is_saved();
loop {
self.set_global("A_Index", Value::Int(turn));
let value = self.the_value_of_the_condition(condition)?;
if !self.the_value_is_true(&value) {
break;
}
iterations += 1;
if iterations > Self::MAX_ITERATIONS {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"the loop ran more than {} times",
Self::MAX_ITERATIONS
),
line: statement.line(),
}));
}
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next | TheFlowOfALoop::Continue => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Out(failure) => {
self.the_index_is_given_back(saved);
return Err(failure);
}
}
if self.the_until_ends_the_loop(until)? {
break;
}
turn += 1;
}
if iterations == 0 {
if let Some(otherwise) = otherwise {
self.run_block(otherwise)?;
}
}
self.the_index_is_given_back(saved);
}
Node::Try {
body,
catches,
otherwise,
finally,
..
} => {
self.run_try(body, catches, otherwise, finally)?;
}
Node::Super { line } => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Syntax error.\n Specifically: super".into(),
line: *line,
}));
}
Node::Declare { scope, names, line } => {
for declared in names {
if let Some(value) = &declared.value {
if *scope == DeclareKind::Static
&& self.the_static_already_ran(*line, &declared.name)
{
continue;
}
let value = self.evaluate(value)?;
let current = match self.lookup(&declared.name) {
Some(value) => Some(value),
None => self.the_value_of_a_variable_of_the_runtime(&declared.name),
};
let stored = self.apply_assign(
declared.op,
&declared.name,
current,
value,
*line,
)?;
self.assign(&declared.name, stored);
if *scope == DeclareKind::Static {
self.mark_the_static_as_ran(*line, &declared.name);
}
}
}
let _ = line;
}
Node::Throw { value, line } => {
let value = match value {
Some(value) => self.evaluate(value)?,
None => match self.caught_value.clone() {
Some(value) => value,
None => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "there is nothing to throw again: no catch took a value."
.into(),
line: *line,
}));
}
},
};
self.name_the_thrower(&value);
return Err(RuntimeFailure::Thrown(value));
}
Node::Loop {
mode,
arguments,
body,
until,
otherwise,
line,
} => {
let saved = self.the_index_is_saved();
let turns: usize;
match mode {
LoopKind::Count => {
match arguments.first() {
Some(node) => {
if self.dialect.legacy_commands() {
if let Some(pattern) = self.the_pattern_of_the_files_of_the_v1(
node, arguments, *line,
)? {
self.the_loop_of_the_files_of_the_v1(
&pattern, arguments, body, until, *line,
)?;
self.the_index_is_given_back(saved);
return Ok(());
}
}
let count = self.the_count_of_the_loop(node, *line)?;
turns = count.max(0) as usize;
let mut turn = 1i64;
while turn <= count.max(0) {
self.set_global("A_Index", Value::Int(turn));
let flow = the_flow_of_a_loop_body(self.run_block(body));
if matches!(flow, TheFlowOfALoop::Break) {
break;
}
if let TheFlowOfALoop::Out(failure) = flow {
self.the_index_is_given_back(saved);
return Err(failure);
}
if self.the_until_ends_the_loop(until)? {
break;
}
turn = self.the_index_of_the_turn() + 1;
}
}
None => {
if body.is_empty()
&& self.dialect.a_loop_without_a_body_ends_the_script()
{
return Err(RuntimeFailure::Flow(Flow::Return(None)));
}
let mut turn = 1i64;
turns = 1;
loop {
self.steps_taken += 1;
if self.steps_taken > Self::MAX_STEPS {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"the script ran more than {} statements",
Self::MAX_STEPS
),
line: *line,
}));
}
self.set_global("A_Index", Value::Int(turn));
turn += 1;
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => {
if self.the_until_ends_the_loop(until)? {
break;
}
continue;
}
TheFlowOfALoop::Out(failure) => {
self.the_index_is_given_back(saved);
return Err(failure);
}
}
if self.the_until_ends_the_loop(until)? {
break;
}
}
}
}
}
LoopKind::Parse => {
if self.dialect.legacy_commands() {
self.the_parse_loop_of_the_v1(arguments, body, until, *line)?;
self.the_index_is_given_back(saved);
return Ok(());
}
let text = self.loop_argument(arguments, 0, *line)?.to_text();
let delimiters = match arguments.get(1) {
Some(node) => self.evaluate(node)?.to_text(),
None => String::new(),
};
let omitted = match arguments.get(2) {
Some(node) => self.evaluate(node)?.to_text(),
None => String::new(),
};
let pieces: Vec<String> = if text.is_empty() {
Vec::new()
} else if delimiters.eq_ignore_ascii_case("csv") {
the_fields_of_a_csv(&text)
.into_iter()
.map(|piece| {
piece
.trim_matches(|character| omitted.contains(character))
.to_string()
})
.collect()
} else if delimiters.is_empty() {
text.chars()
.filter(|character| !omitted.contains(*character))
.map(|character| character.to_string())
.collect()
} else {
split_on_any(&text, &delimiters)
.into_iter()
.map(|piece| {
piece
.trim_matches(|character| omitted.contains(character))
.to_string()
})
.collect()
};
turns = pieces.len();
for (index, piece) in pieces.iter().enumerate() {
self.set_global("A_Index", Value::Int(index as i64 + 1));
self.set_global("A_LoopField", Value::Text(piece.clone()));
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => continue,
TheFlowOfALoop::Out(failure) => {
self.the_index_is_given_back(saved);
return Err(failure);
}
}
}
}
LoopKind::Files => {
if self.dialect.legacy_commands() {
self.the_loop_of_the_files_of_the_v1_with_the_kind(
arguments, body, until, *line,
)?;
self.the_index_is_given_back(saved);
return Ok(());
}
if arguments.len() > 2 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "\"Loop Files\" accepts at most 2 parameters.".into(),
line: *line,
}));
}
let pattern = self.loop_argument(arguments, 0, *line)?.to_text();
let mode = match arguments.get(1) {
Some(node) => self.evaluate(node)?.to_text(),
None => String::new(),
};
if let Some(letter) = the_letter_that_the_mode_does_not_carry(&mode) {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"the mode of a `Loop Files` is the \"R\", the \"D\", the \"F\", the \"V\" or the \"K\", and the letter \"{letter}\" is not one of them."
),
line: *line,
}));
}
let folder = self.desktop().working_directory().map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line: *line,
})
})?;
let files = self
.desktop()
.list_files(&folder, &pattern, &mode)
.map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line: *line,
})
})?;
turns = files.len();
for (index, file) in files.iter().enumerate() {
let name = the_name_of(file);
let extension = the_extension_of(name);
self.set_global("A_Index", Value::Int(index as i64 + 1));
self.set_global("A_LoopFileFullPath", Value::Text(file.clone()));
self.set_global("A_LoopFileName", Value::Text(name.to_string()));
self.set_global("A_LoopFileExt", Value::Text(extension.to_string()));
self.set_global(
"A_LoopFileDir",
Value::Text(the_folder_of(file).to_string()),
);
self.set_global(
"A_LoopFilePath",
Value::Text(without_the_extension(file, extension)),
);
self.the_short_names_of_the_files_are_refused = true;
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => continue,
TheFlowOfALoop::Out(failure) => {
self.the_index_is_given_back(saved);
return Err(failure);
}
}
}
}
LoopKind::Read => {
if self.dialect.legacy_commands() {
self.the_read_loop_of_the_v1(arguments, body, until, *line)?;
self.the_index_is_given_back(saved);
return Ok(());
}
let path = self.loop_argument(arguments, 0, *line)?.to_text();
let output = match arguments.get(1) {
Some(node) => self.evaluate(node)?.to_text(),
None => String::new(),
};
let lines = self.desktop().read_file(&path).map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line: *line,
})
})?;
self.loop_output_files.push(output);
turns = lines.len();
let mut failure = None;
for (index, line_text) in lines.iter().enumerate() {
self.set_global("A_Index", Value::Int(index as i64 + 1));
self.set_global("A_LoopReadLine", Value::Text(line_text.clone()));
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => continue,
TheFlowOfALoop::Out(other) => {
failure = Some(other);
break;
}
}
}
self.loop_output_files.pop();
if let Some(other) = failure {
self.the_index_is_given_back(saved);
return Err(other);
}
}
LoopKind::Reg => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "the registry is a Windows thing and this box has none."
.into(),
line: *line,
}));
}
}
if turns == 0 {
if let Some(otherwise) = otherwise {
self.run_block(otherwise)?;
}
}
self.the_index_is_given_back(saved);
}
Node::Directive {
name,
argument,
line,
} => {
detail = self.directive(name, argument, *line)?;
}
Node::Label { .. } => {}
Node::Expression { value, .. } => {
self.evaluate(value)?;
}
Node::LegacyExpression { value, .. } => {
self.evaluate(value)?;
}
Node::Goto { name, line } => {
if self.the_jump_leaves_a_finally(name) {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Jumps cannot exit a FINALLY block.".to_string(),
line: *line,
}));
}
return Err(RuntimeFailure::Flow(Flow::Goto {
name: name.clone(),
line: *line,
computed: false,
}));
}
Node::GotoComputed { value, line } => {
let name = self.evaluate(value)?.to_text();
if self.the_jump_leaves_a_finally(&name) {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Jumps cannot exit a FINALLY block.".to_string(),
line: *line,
}));
}
return Err(RuntimeFailure::Flow(Flow::Goto {
name,
line: *line,
computed: true,
}));
}
Node::HotkeyDefinition { body, .. } => {
if self.in_the_body_of_a_hotkey {
self.run_block(body)?;
}
}
Node::Break { level, .. } => return Err(RuntimeFailure::Flow(Flow::Break(*level))),
Node::Continue { level, .. } => {
return Err(RuntimeFailure::Flow(Flow::Continue(*level)))
}
Node::Spread { line, .. } => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Missing operand.".into(),
line: *line,
}))
}
Node::Return { value, .. } => {
let value = match value {
Some(node) => Some(self.evaluate(node)?),
None => None,
};
return Err(RuntimeFailure::Flow(Flow::Return(value)));
}
Node::ExitApp { code, .. } => {
let code = match code {
Some(node) => self.evaluate(node)?.to_number().unwrap_or(0.0) as i32,
None => 0,
};
return Err(RuntimeFailure::Flow(Flow::Exit(code)));
}
Node::FunctionDef { name, .. } => {
detail = format!("{name} is defined");
}
Node::Unary { op, operand, line } => {
if matches!(
op,
UnaryOp::PreIncrement
| UnaryOp::PreDecrement
| UnaryOp::PostIncrement
| UnaryOp::PostDecrement
) {
self.increment(*op, operand, *line)?;
detail = "the variable moved".into();
} else {
return Err(RuntimeFailure::Error(RuntimeError {
message: "this is an expression, not a statement".into(),
line: statement.line(),
}));
}
}
Node::Index { .. } => {
self.evaluate(statement)?;
detail = "the item was read".into();
}
Node::DynamicName { .. } => {
self.evaluate(statement)?;
detail = "the variable was read".into();
}
Node::Literal { .. }
| Node::Var { .. }
| Node::Binary { .. }
| Node::Unset { .. }
| Node::Ternary { .. }
| Node::Group { .. }
| Node::Maybe { .. }
| Node::LegacyComparison { .. }
| Node::LegacyMatch { .. }
| Node::LegacyControl { .. }
| Node::Empty { .. } => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "this is an expression, not a statement".into(),
line: statement.line(),
}));
}
Node::Legacy { items, .. } => {
for item in items {
self.evaluate(item)?;
}
detail = "the list of v1".into();
}
}
self.steps.push(Step {
line: statement.line(),
op: op_name_in(statement, self.dialect).to_string(),
detail,
ok: true,
elapsed_ms: self.clock.now_ms().saturating_sub(started),
});
Ok(())
}
fn for_loop(
&mut self,
variables: &[String],
source: &Node,
body: &[Node],
until: &Option<Box<Node>>,
otherwise: &Option<Vec<Node>>,
line: u32,
) -> Result<(), RuntimeFailure> {
if variables.len() > 2 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "a for loop takes at most two variables.".into(),
line,
}));
}
let saved: Vec<(String, Option<Value>)> = variables
.iter()
.filter(|name| !name.is_empty())
.map(|name| (name.clone(), self.lookup_variable(name)))
.collect();
let object = self.evaluate(source)?;
if self.dialect.the_for_is_the_one_of_the_v1() {
if self.the_class_of_the_value(&object) != "Array" {
return Ok(());
}
}
let wanted = if self.dialect.the_for_is_the_one_of_the_v1() {
2
} else {
variables.len()
};
let enumerator = self.the_enumerator(&object, wanted, line)?;
if let Err(failure) = self.check_the_enumerator(&enumerator, line) {
for (name, value) in saved {
self.restore_variable(&name, value);
}
return Err(failure);
}
let saved_index = self.the_index_is_saved();
let mut turns = 0usize;
let mut outcome = Ok(());
loop {
let item = match self.the_next_item(&enumerator, variables, wanted, line) {
Ok(Some(item)) => item,
Ok(None) => break,
Err(failure) => {
outcome = Err(failure);
break;
}
};
turns += 1;
if turns > Self::MAX_ITERATIONS {
outcome = Err(RuntimeFailure::Error(RuntimeError {
message: format!("the loop ran more than {} times", Self::MAX_ITERATIONS),
line,
}));
break;
}
if let Err(failure) = self.set_loop_variables(variables, &item, line) {
outcome = Err(failure);
break;
}
self.set_global("A_Index", Value::Int(turns as i64));
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next | TheFlowOfALoop::Continue => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Out(failure) => {
outcome = Err(failure);
break;
}
}
if self.the_until_ends_the_loop(until)? {
break;
}
}
for (name, value) in saved {
self.restore_variable(&name, value);
}
self.the_index_is_given_back(saved_index);
if outcome.is_ok() && turns == 0 {
if let Some(otherwise) = otherwise {
outcome = self.run_block(otherwise);
}
}
outcome
}
fn the_enumerator(
&mut self,
object: &Value,
wanted: usize,
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.can_enumerate(object) {
let count = Node::Literal {
value: LiteralValue::Integer(wanted as i64),
line,
};
return self.call_method_on(object, "__enum", &[count], line);
}
if crate::classes::enumerator::is_one(object) {
return Ok(object.clone());
}
if let Some(enumerator) = self.the_prototype_enum_of(object, wanted, line) {
return enumerator;
}
Err(RuntimeFailure::Error(RuntimeError {
message: "Value not enumerable.".into(),
line,
}))
}
fn the_prototype_enum_of(
&mut self,
value: &Value,
wanted: usize,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let mut class = Some(value.type_name().name().to_lowercase());
while let Some(name) = class {
let prototype = self.the_prototype_of(&name)?;
let stored = match &prototype {
Value::Object(object) => object
.borrow()
.properties
.get("__enum")
.map(|property| property.value.clone()),
_ => None,
};
if let Some(stored) = stored {
let members = self.the_members_of_a_descriptor(&stored)?;
let call = members.get("call")?.value.clone();
let values = vec![Value::Int(wanted as i64)];
return Some(self.call_the_function(&call, value, &values, line));
}
class = crate::classes::the_base_class_of_a_class(&name).map(|base| base.to_string());
}
None
}
fn check_the_enumerator(&self, enumerator: &Value, line: u32) -> Result<(), RuntimeFailure> {
match enumerator {
Value::Object(_) if crate::classes::enumerator::is_one(enumerator) => Ok(()),
Value::Object(_) if self.is_a_function(enumerator) => Ok(()),
Value::Object(_) if self.find_method_on(enumerator, "call").is_some() => Ok(()),
Value::Object(_) => Err(RuntimeFailure::Error(RuntimeError {
message: "Value not enumerable.".into(),
line,
})),
_ => Err(RuntimeFailure::Error(RuntimeError {
message: "Type mismatch.".into(),
line,
})),
}
}
fn the_next_item(
&mut self,
enumerator: &Value,
variables: &[String],
wanted: usize,
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
if crate::classes::enumerator::is_one(enumerator) {
return Ok(crate::classes::enumerator::the_turn(enumerator, wanted));
}
let references: Vec<Value> = variables
.iter()
.filter(|name| !name.is_empty())
.map(|name| {
Value::Reference(Reference {
name: name.clone(),
scope: self.the_scope_of(name),
alias: true,
})
})
.collect();
let answer = if self.is_a_function(enumerator) {
match crate::classes::func::call_the_value(enumerator, &references, self, line) {
Some(result) => result?,
None => return Err(self.no_method(enumerator, "Call", line)),
}
} else {
self.own_method(enumerator, "call", &references, line)?
};
if !answer.truthy() {
return Ok(None);
}
let mut values = Vec::new();
for reference in &references {
let Value::Reference(reference) = reference else {
continue;
};
values.push(
self.read_reference(reference)
.unwrap_or(Value::Text(String::new())),
);
}
let item = if values.len() >= 2 {
Value::List(vec![values[0].clone(), values[1].clone()])
} else {
values
.into_iter()
.next()
.unwrap_or(Value::Text(String::new()))
};
Ok(Some(item))
}
fn the_scope_of(&self, name: &str) -> Scope {
let name = the_key_of(name);
if self.lives_in_the_script(&name) {
return Scope::Global;
}
if self.the_scopes_around_are_shared() {
for (depth, scope) in self.scopes.iter().enumerate().rev().skip(1) {
if scope.borrow().contains_key(&name) {
return Scope::Local(depth);
}
}
}
match self.scopes.len() {
0 => Scope::Global,
depth => Scope::Local(depth - 1),
}
}
fn can_enumerate(&self, object: &Value) -> bool {
let Value::Object(value) = object else {
return false;
};
if self.find_method_on(object, "__enum").is_some() {
return true;
}
let class = value.borrow().class.clone();
crate::classes::carries(&class, "__enum")
}
fn set_loop_variables(
&mut self,
variables: &[String],
item: &Value,
line: u32,
) -> Result<(), RuntimeFailure> {
if self.dialect.the_for_is_the_one_of_the_v1() {
let pair = match item {
Value::List(pair) if pair.len() == 2 => pair,
_ => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "the enumeration did not give a key and a value.".into(),
line,
}));
}
};
let names: Vec<&String> = variables.iter().filter(|name| !name.is_empty()).collect();
if let Some(name) = names.first() {
self.assign(name, pair[0].clone());
}
if let Some(name) = names.get(1) {
self.assign(name, pair[1].clone());
}
return Ok(());
}
match variables.len() {
0 => Ok(()),
1 => {
if !variables[0].is_empty() {
if is_a_value_without_one(item) {
self.unset_variable(&variables[0]);
} else {
self.assign(&variables[0], item.clone());
}
}
Ok(())
}
_ => {
let pair = match item {
Value::List(pair) if pair.len() == 2 => pair,
_ => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "the enumeration did not give a key and a value.".into(),
line,
}));
}
};
for (name, value) in variables.iter().zip(pair.iter()) {
if name.is_empty() {
continue;
}
if is_a_value_without_one(value) {
self.unset_variable(name);
} else {
self.assign(name, value.clone());
}
}
Ok(())
}
}
}
fn restore_variable(&mut self, name: &str, value: Option<Value>) {
match value {
Some(value) => self.assign(name, value),
None => match self.scopes.last() {
Some(scope) => {
scope.borrow_mut().remove(the_key_of(name).as_str());
}
None => {
self.variables.remove(the_key_of(name).as_str());
}
},
}
}
fn unset_variable(&mut self, name: &str) {
if let Some(reference) = self.alias_of(name) {
self.unset_reference(&Value::Reference(reference));
return;
}
let name = the_key_of(name);
if self.is_declared_static(&name) {
self.the_statics_of_the_frame().remove(name.as_str());
return;
}
if self.lives_in_the_script(&name) {
self.variables.remove(name.as_str());
return;
}
for scope in self.scopes.iter().rev().skip(1) {
if scope.borrow().contains_key(&name) {
scope.borrow_mut().remove(name.as_str());
return;
}
}
match self.scopes.last() {
Some(scope) => {
scope.borrow_mut().remove(name.as_str());
}
None => {
self.variables.remove(name.as_str());
}
}
}
fn lookup(&self, name: &str) -> Option<Value> {
let key = name.to_lowercase();
if self.is_declared_static(&key) && self.the_static_of_the_frame(&key).is_none() {
return None;
}
if let Some(value) = self.lookup_variable(name) {
return Some(value);
}
let key = name.to_lowercase();
if let Some(function) = self.functions.get(&key) {
if !self.dialect.the_name_of_a_function_is_a_value() {
return Some(Value::Text(String::new()));
}
return Some(func_value(&function.name, function));
}
if let Some(builtin) = self.builtin(&key) {
if !self.dialect.the_name_of_a_function_is_a_value() {
return Some(Value::Text(String::new()));
}
return Some(builtin_value(builtin.name, builtin.min, builtin.max as u32));
}
if self.classes.contains_key(&key)
|| crate::classes::is_type(&key)
|| self.dialect.carries_the_class_of_the_extension(&key)
{
return self.class_value_of(&key);
}
None
}
pub(crate) fn class_value_of(&self, name: &str) -> Option<Value> {
let key = name.to_lowercase();
if let Some(value) = self.class_values.borrow().get(&key) {
return Some(value.clone());
}
let value = if let Some(class) = self.classes.get(&key) {
class_value(&key, class)
} else if crate::classes::is_type(&key) {
crate::classes::class_value(&key)
} else if self.dialect.carries_the_class_of_the_extension(&key) {
crate::classes::class_value(&key)
} else {
return None;
};
self.class_values.borrow_mut().insert(key, value.clone());
Some(value)
}
pub(crate) fn class_of(&self, target: &Value) -> Option<String> {
let Value::Object(object) = target else {
return None;
};
let class = object.borrow().class.clone();
if let Some(Value::Object(class)) = self.class_value_of(&class) {
if let Some(name) = class.borrow().value_of(CLASS_NAME) {
return Some(name.to_text());
}
}
Some(crate::classes::the_spelling_of(&class))
}
pub(crate) fn class_name_of(&self, value: &Value) -> Option<String> {
let Value::Object(object) = value else {
return None;
};
for class in self.class_values.borrow().values() {
let Value::Object(other) = class else {
continue;
};
if Rc::ptr_eq(object, other) {
return object
.borrow()
.value_of(CLASS_NAME)
.map(|name| name.to_text().to_lowercase());
}
}
None
}
pub(crate) fn base_of(&self, target: &Value) -> Option<Value> {
let Value::Object(object) = target else {
return None;
};
if let Some(base) = object.borrow().value_of(BASE) {
return Some(base.clone());
}
let class = object.borrow().class.clone();
let Value::Object(class) = self.class_value_of(&class)? else {
return None;
};
class.borrow().value_of("prototype")
}
pub(crate) fn stored_base_of(&self, target: &Value) -> Option<Value> {
let Value::Object(object) = target else {
return None;
};
object.borrow().value_of(BASE)
}
pub(crate) fn own_method(
&mut self,
target: &Value,
name: &str,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeError> {
let Value::Object(object) = target else {
return Err(RuntimeError {
message: expected_type(TypeName::Object, target.type_name()),
line,
});
};
if name == "ownprops" && self.class_name_of(target).is_some() {
return self.base_object(target, name, arguments, line);
}
let class = object.borrow().class.clone();
match crate::classes::call(&class, name, target, arguments, self, line) {
Some(Ok(value)) => Ok(value),
Some(Err(failure)) => Err(as_error(failure, line)),
None => self.base_object(target, name, arguments, line),
}
}
pub(crate) fn property_of(&mut self, target: &Value, name: &str, line: u32) -> Option<Value> {
self.read_property(target, name, line).ok()
}
pub(crate) fn write_property_of(
&mut self,
target: &Value,
name: &str,
value: Value,
line: u32,
) -> Result<(), RuntimeError> {
self.write_property(target, name, value, line)
.map_err(|failure| as_error(failure, line))
}
pub(crate) fn set_base_of(
&mut self,
target: &Value,
base: Value,
line: u32,
) -> Result<(), RuntimeError> {
let Value::Object(object) = target else {
return Err(RuntimeError {
message: expected_type(TypeName::Object, target.type_name()),
line,
});
};
let class = object.borrow().class.clone();
if self.class_name_of(target).is_none()
&& matches!(
class.as_str(),
"array" | "buffer" | "enumerator" | "file" | "func" | "gui" | "map" | "menu"
)
{
return Err(RuntimeError {
message: "Invalid base.".to_string(),
line,
});
}
object.borrow_mut().put(BASE, base);
Ok(())
}
fn lookup_variable(&self, name: &str) -> Option<Value> {
let name = the_key_of(name);
if let Some(scope) = self.scopes.last() {
match scope.borrow().get(&name) {
Some(Value::Reference(reference)) if reference.alias => {
return self.read_reference(reference);
}
Some(value) => return Some(value.clone()),
None => {}
}
}
if let Some(value) = self.the_static_of_the_frame(&name) {
return Some(value);
}
if self.the_scopes_around_are_shared() {
for scope in self.scopes.iter().rev().skip(1) {
match scope.borrow().get(&name) {
Some(Value::Reference(reference)) if reference.alias => {
return self.read_reference(reference);
}
Some(value) => return Some(value.clone()),
None => continue,
}
}
}
if self.is_declared_local(&name) {
return None;
}
let owned = crate::variables::spelled(&name)
.map(|rest| crate::variables::THE_RUNTIME_OWNS.contains(&rest.as_str()))
.unwrap_or(false);
if self.dialect.the_scope_of_a_function_is_its_own()
&& !self.scopes.is_empty()
&& !owned
&& !self.lives_in_the_script(&name)
{
return None;
}
self.variables.get(&name).cloned()
}
fn the_scopes_around_are_shared(&self) -> bool {
!self.dialect.the_scope_of_a_function_is_its_own()
}
fn is_declared_static(&self, name: &str) -> bool {
let Some(frame) = self.declarations.last() else {
return false;
};
frame.statics.contains(name)
}
fn the_built_in_variable(&mut self, name: &str) -> Option<Result<Value, RuntimeError>> {
let dialect = self.dialect;
dialect.lookup_variable(name, self)
}
fn the_write_of_the_built_in_variable(
&mut self,
name: &str,
op: AssignOp,
value: &Value,
line: u32,
) -> Option<Result<Value, RuntimeError>> {
let dialect = self.dialect;
dialect.write_variable(name, op, value, line, self)
}
pub(crate) fn has_a_value(&mut self, name: &str) -> bool {
if self.lookup_variable(name).is_some() {
return true;
}
self.dialect.carries_variable(name)
}
pub(crate) fn has_a_function(&self, name: &str) -> bool {
self.functions.contains_key(&name.to_lowercase())
}
pub(crate) fn has_a_builtin_function(&self, name: &str) -> bool {
self.dialect.builtins().iter().any(|builtin| {
builtin.kind == crate::builtins::BuiltinKind::Function
&& builtin.name.eq_ignore_ascii_case(name)
}) || self
.dialect
.the_builtin_of_the_extension(name)
.is_some_and(|builtin| {
builtin.kind == crate::builtins::BuiltinKind::Function
&& builtin.name.eq_ignore_ascii_case(name)
})
}
pub(crate) fn the_builtin_function(&self, name: &str) -> Option<Value> {
let builtin = self
.dialect
.builtins()
.iter()
.find(|builtin| {
builtin.kind == crate::builtins::BuiltinKind::Function
&& builtin.name.eq_ignore_ascii_case(name)
})
.or_else(|| {
self.dialect.the_builtin_of_the_extension(name).filter(|builtin| {
builtin.kind == crate::builtins::BuiltinKind::Function
&& builtin.name.eq_ignore_ascii_case(name)
})
})?;
let max = self.dialect.the_maximum_of_the_parameters(builtin.max);
Some(builtin_value(builtin.name, builtin.min, max))
}
pub(crate) fn is_a_reference(&self, name: &str) -> bool {
matches!(self.lookup_variable(name), Some(Value::Reference(_)))
}
pub(crate) fn the_function_of_the_script(&self, name: &str) -> Option<Value> {
let function = self.functions.get(&name.to_lowercase())?;
Some(func_value(&function.name, function))
}
fn the_statics_of_the_frame(&mut self) -> &mut BTreeMap<String, Value> {
let frame = self
.frames
.last()
.map(|frame| frame.name.clone())
.unwrap_or_default();
self.statics.entry(frame).or_default()
}
fn the_static_of_the_frame(&self, name: &str) -> Option<Value> {
let frame = self.frames.last()?;
self.statics.get(&frame.name)?.get(name).cloned()
}
fn the_static_already_ran(&self, line: u32, name: &str) -> bool {
let Some(frame) = self.frames.last() else {
return false;
};
let Some(ran) = self.statics_run.get(&frame.name) else {
return false;
};
ran.contains(&the_key_of_a_declaration(line, name))
}
fn mark_the_static_as_ran(&mut self, line: u32, name: &str) {
let frame = self
.frames
.last()
.map(|frame| frame.name.clone())
.unwrap_or_default();
self.statics_run
.entry(frame)
.or_default()
.insert(the_key_of_a_declaration(line, name));
}
fn is_declared_local(&self, name: &str) -> bool {
let Some(frame) = self.declarations.last() else {
return false;
};
frame.locals.contains(name)
}
fn the_class_is_not_written(
&self,
name: &str,
value: &Value,
line: u32,
) -> Result<(), RuntimeFailure> {
if self.declarations.is_empty() {
return Ok(());
}
let key = the_key_of(name);
if self.lives_in_the_script(&key) {
return Ok(());
}
let Some(class) = self.the_class_of_the_name(&key) else {
return Ok(());
};
if self.the_class_key_of_the_value(value).as_deref() != Some(class.as_str()) {
return Ok(());
}
let message = if self.is_declared_local(&key) {
"This local variable has not been assigned a value.".to_string()
} else {
"This local variable has not been assigned a value. A global declaration inside the function may be required.".to_string()
};
Err(RuntimeFailure::Error(RuntimeError { message, line }))
}
fn the_class_of_the_name(&self, name: &str) -> Option<String> {
if self.classes.contains_key(name) || crate::classes::is_type(name) {
return Some(name.to_string());
}
None
}
fn the_class_key_of_the_value(&self, value: &Value) -> Option<String> {
let Value::Object(object) = value else {
return None;
};
Some(object.borrow().class.clone())
}
fn alias_of(&self, name: &str) -> Option<Reference> {
let name = the_key_of(name);
for scope in self.scopes.iter().rev() {
let Some(found) = scope.borrow().get(&name).cloned() else {
continue;
};
if let Value::Reference(reference) = found {
if reference.alias {
return Some(reference);
}
}
return None;
}
None
}
pub(crate) fn read_reference(&self, reference: &Reference) -> Option<Value> {
if reference.name.is_empty() {
return None;
}
let name = the_key_of(&reference.name);
match reference.scope {
Scope::Global => self.variables.get(&name).cloned(),
Scope::Local(depth) => self.scopes.get(depth)?.borrow().get(&name).cloned(),
}
}
pub(crate) fn write_reference(&mut self, value: &Value, written: Value) {
let Value::Reference(reference) = value else {
return;
};
if reference.name.is_empty() {
return;
}
let name = the_key_of(&reference.name);
match reference.scope {
Scope::Global => {
self.variables.insert(name, written);
}
Scope::Local(depth) => {
if let Some(scope) = self.scopes.get(depth) {
scope.borrow_mut().insert(name, written);
}
}
}
}
pub(crate) fn unset_reference(&mut self, value: &Value) {
let Value::Reference(reference) = value else {
return;
};
if reference.name.is_empty() {
return;
}
let name = the_key_of(&reference.name);
match reference.scope {
Scope::Global => {
self.variables.remove(name.as_str());
}
Scope::Local(depth) => {
if let Some(scope) = self.scopes.get(depth) {
scope.borrow_mut().remove(name.as_str());
}
}
}
}
fn the_scope_number(scope: Scope) -> u8 {
match scope {
Scope::Global => 0,
Scope::Local(depth) => (depth.saturating_add(1)).min(255) as u8,
}
}
pub(crate) fn string_capacity(&self, reference: &Reference) -> i64 {
let key = (
Self::the_scope_number(reference.scope),
the_key_of(&reference.name),
);
if let Some(capacity) = self.string_capacities.get(&key) {
return *capacity;
}
match self.read_reference(reference) {
Some(Value::Text(text)) => the_capacity_of_a_text(&text),
Some(_) => 0,
None => 0,
}
}
pub(crate) fn set_string_capacity(&mut self, reference: &Reference, capacity: i64) {
let key = (
Self::the_scope_number(reference.scope),
the_key_of(&reference.name),
);
self.string_capacities.insert(key, capacity);
}
pub(crate) fn keeps_a_string_capacity(&self, reference: &Reference) -> bool {
let key = (
Self::the_scope_number(reference.scope),
the_key_of(&reference.name),
);
self.string_capacities.contains_key(&key)
}
pub(crate) fn forget_a_string_capacity(&mut self, reference: &Reference) {
let key = (
Self::the_scope_number(reference.scope),
the_key_of(&reference.name),
);
self.string_capacities.remove(&key);
}
fn forget_the_capacities_beyond_the_stack(&mut self) {
let deepest = if self.scopes.is_empty() {
0
} else {
Self::the_scope_number(Scope::Local(self.scopes.len() - 1))
};
self.string_capacities
.retain(|(scope, _), _| *scope <= deepest);
}
pub(crate) fn the_address_of_a_text(&mut self, text: &str) -> i64 {
let mut memory = self.string_memory.borrow_mut();
let place = match memory.iter().position(|candidate| candidate == text) {
Some(place) => place,
None => {
memory.push(text.to_string());
memory.len() - 1
}
};
STRING_MEMORY_BASE + place as i64 * STRING_MEMORY_STRIDE
}
pub(crate) fn the_text_at_an_address(&self, address: i64) -> Option<String> {
let place = address.checked_sub(STRING_MEMORY_BASE)?;
if place < 0 || place % STRING_MEMORY_STRIDE != 0 {
return None;
}
let place = (place / STRING_MEMORY_STRIDE) as usize;
self.string_memory.borrow().get(place).cloned()
}
fn assign(&mut self, name: &str, value: Value) {
if let Some(reference) = self.alias_of(name) {
self.write_reference(&Value::Reference(reference), value);
return;
}
let name = the_key_of(name);
if self.is_declared_static(&name) {
self.the_statics_of_the_frame().insert(name, value);
return;
}
if self.lives_in_the_script(&name) {
self.variables.insert(name, value);
return;
}
if self.the_scopes_around_are_shared() {
for scope in self.scopes.iter().rev().skip(1) {
if scope.borrow().contains_key(&name) {
scope.borrow_mut().insert(name, value);
return;
}
}
}
match self.scopes.last() {
Some(scope) => {
scope.borrow_mut().insert(name, value);
}
None => {
self.variables.insert(name, value);
}
}
}
fn lives_in_the_script(&self, name: &str) -> bool {
let Some(frame) = self.declarations.last() else {
return false;
};
if frame.globals.contains(name) {
return true;
}
if frame.locals.contains(name) {
return false;
}
frame.assume_global
}
fn cannot_be_referenced(&self, name: &str) -> Option<&'static str> {
let key = name.to_lowercase();
if crate::variables::is_built_in(name) || self.dialect.carries_variable(name) {
return Some("built-in variable");
}
if self.functions.contains_key(&key) || self.builtin(&key).is_some() {
return Some("Func");
}
if self.classes.contains_key(&key) || crate::classes::is_type(&key) {
return Some("Class");
}
None
}
fn the_chain_of_the_bases(&self, target: &Value) -> Vec<Rc<RefCell<Object>>> {
let mut chain: Vec<Rc<RefCell<Object>>> = Vec::new();
let Value::Object(object) = target else {
return chain;
};
let mut class = object.borrow().class.clone();
if self.class_name_of(target).is_some() {
let Some(base) = self.the_base_class_of(&class) else {
return chain;
};
class = base;
}
if let Some(Value::Object(base)) = object.borrow().value_of(BASE) {
chain.push(base.clone());
class = base.borrow().class.clone();
}
while let Some(prototype) = self.the_prototype_of_the_class(&class) {
if chain.iter().any(|seen| Rc::ptr_eq(seen, &prototype)) {
break;
}
chain.push(prototype);
let Some(base) = self.the_base_class_of(&class) else {
break;
};
class = base;
}
chain
}
fn the_prototype_of_the_class(&self, class: &str) -> Option<Rc<RefCell<Object>>> {
let Some(Value::Object(value)) = self.class_value_of(class) else {
return None;
};
let prototype = value.borrow().value_of("prototype");
let Some(Value::Object(prototype)) = prototype else {
return None;
};
Some(prototype)
}
fn the_base_class_of(&self, class: &str) -> Option<String> {
if let Some(definition) = self.classes.get(class) {
if let Some(base) = &definition.extends {
return Some(base.to_lowercase());
}
return Some("object".to_string());
}
if let Some(base) = crate::classes::the_base_of(class) {
return Some(base.to_string());
}
Some("object".to_string())
}
fn class_chain(&self, name: &str) -> Vec<String> {
let mut chain: Vec<String> = Vec::new();
let mut current = Some(name.to_lowercase());
while let Some(class) = current {
if chain.contains(&class) {
break;
}
chain.push(class.clone());
current = match self.classes.get(&class) {
Some(definition) => definition.extends.clone().map(|base| base.to_lowercase()),
None => crate::classes::the_base_of(&class).or_else(|| {
crate::classes::the_base_of_the_primitive_of_the_class(&class)
})
.map(|base| base.to_string()),
};
}
chain
}
fn find_method_in(&self, class: &str, name: &str) -> Option<(String, MethodDef)> {
let name = name.to_lowercase();
for class in self.class_chain(class) {
if let Some(definition) = self.classes.get(&class) {
if let Some(method) = definition.methods.get(&name) {
return Some((class.clone(), method.clone()));
}
}
}
None
}
fn find_method_on(&self, target: &Value, name: &str) -> Option<(String, MethodDef)> {
let Value::Object(object) = target else {
return None;
};
let class = object.borrow().class.clone();
if self.class_name_of(target).is_some() {
if self
.dialect
.a_method_of_the_class_object_is_a_method_of_the_class()
{
return self.find_the_instance_method_in(&class, name);
}
return self.find_the_static_method_in(&class, name);
}
let class = self.the_class_of_the_prototype(target).unwrap_or(class);
self.find_the_instance_method_in(&class, name)
}
fn construct(
&mut self,
class: &str,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if !self.classes.contains_key(&class.to_lowercase()) {
let values = self.evaluate_all(arguments)?;
return self.construct_with_values(class, &values, line);
}
let object = self.the_object_of_a_class(class);
self.call_the_init(class, &object, line)?;
if let Some((defining, method)) = self.find_the_instance_method_in(class, "__new") {
let result = self.call_method(&defining, &method, &object, arguments, line)?;
return Ok(match result {
Value::Object(_) => result,
_ => object,
});
}
Ok(object)
}
fn new_instance(
&mut self,
path: &[String],
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.the_class_is_a_variable() {
return self.new_instance_of_the_v1(path, arguments, line);
}
let Some(class) = path.first() else {
return Ok(Value::Text(String::new()));
};
if !self.classes.contains_key(&class.to_lowercase()) {
return Ok(Value::Text(String::new()));
}
self.construct(class, arguments, line)
}
fn new_instance_of_the_v1(
&mut self,
path: &[String],
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
let Some(first) = path.first() else {
return Ok(Value::Text(String::new()));
};
let mut value = if first == "this" {
self.the_this()
} else {
match self
.lookup_variable(first)
.or_else(|| self.class_value_of(first))
{
Some(value) => value,
None => return Ok(Value::Text(String::new())),
}
};
for name in &path[1..] {
let Some(class) = self.the_class_that_the_v1_holds(&value, name) else {
return Ok(Value::Text(String::new()));
};
value = class;
}
let Value::Object(object) = &value else {
return Ok(Value::Text(String::new()));
};
let class = match self.class_name_of(&value) {
Some(class) => class,
None => object.borrow().class.clone(),
};
self.construct(&class, arguments, line)
}
fn construct_with_values(
&mut self,
class: &str,
values: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
if !self.classes.contains_key(&class.to_lowercase()) {
if let Some(result) = crate::classes::construct(class, values, self, line) {
return result;
}
}
let object = self.the_object_of_a_class(class);
self.call_the_init(class, &object, line)?;
if let Some((defining, method)) = self.find_the_instance_method_in(class, "__new") {
let result = self.call_method_with(&defining, &method, &object, values, line)?;
return Ok(match result {
Value::Object(_) => result,
_ => object,
});
}
Ok(object)
}
fn the_object_of_a_class(&self, class: &str) -> Value {
Value::Object(Rc::new(RefCell::new(Object {
class: class.to_lowercase(),
properties: BTreeMap::new(),
})))
}
fn call_the_init(
&mut self,
class: &str,
object: &Value,
line: u32,
) -> Result<(), RuntimeFailure> {
let chain = self.class_chain(class);
self.call_the_init_of(&chain, object, line)
}
fn initialise_the_class(&mut self, class: &str, line: u32) -> Result<(), RuntimeFailure> {
let key = class.to_lowercase();
if !self.classes.contains_key(&key) {
return Ok(());
}
if !self.initialised.borrow_mut().insert(key.clone()) {
return Ok(());
}
self.assign_the_static_variables(&key)?;
if let Some((defining, method)) = self.find_the_static_method_in(&key, "__new") {
if let Some(value) = self.class_value_of(&key) {
self.call_method(&defining, &method, &value, &[], line)?;
}
}
Ok(())
}
fn assign_the_static_variables(&mut self, class: &str) -> Result<(), RuntimeFailure> {
let Some(definition) = self.classes.get(class).cloned() else {
return Ok(());
};
let Some(value) = self.class_value_of(class) else {
return Ok(());
};
let Value::Object(object) = value else {
return Ok(());
};
for property in &definition.properties {
if !property.is_static {
continue;
}
let value = match &property.value {
Some(node) => self.evaluate(node)?,
None => Value::Text(String::new()),
};
put(&mut object.borrow_mut().properties, &property.name, value);
}
Ok(())
}
fn find_the_static_method_in(&self, class: &str, name: &str) -> Option<(String, MethodDef)> {
let name = name.to_lowercase();
for class in self.class_chain(class) {
if let Some(definition) = self.classes.get(&class) {
if let Some(method) = definition.methods.get(&name) {
if method.is_static {
return Some((class.clone(), method.clone()));
}
}
}
}
None
}
fn find_the_instance_method_in(&self, class: &str, name: &str) -> Option<(String, MethodDef)> {
let name = name.to_lowercase();
for class in self.class_chain(class) {
if let Some(definition) = self.classes.get(&class) {
if let Some(method) = definition.methods.get(&name) {
if !method.is_static {
return Some((class.clone(), method.clone()));
}
}
}
}
None
}
fn call_the_init_of(
&mut self,
chain: &[String],
object: &Value,
line: u32,
) -> Result<(), RuntimeFailure> {
for (index, name) in chain.iter().enumerate() {
let Some(definition) = self.classes.get(name).cloned() else {
continue;
};
if let Some(method) = definition.methods.get("__init").cloned() {
self.call_method(name, &method, object, &[], line)?;
self.assign_the_variables(name, object)?;
return Ok(());
}
if !definition.properties.is_empty() {
if index + 1 < chain.len() {
self.call_the_init_of(&chain[index + 1..], object, line)?;
}
self.assign_the_variables(name, object)?;
return Ok(());
}
}
Ok(())
}
fn assign_the_variables(&mut self, class: &str, object: &Value) -> Result<(), RuntimeFailure> {
let Some(definition) = self.classes.get(class).cloned() else {
return Ok(());
};
let Value::Object(cell) = object else {
return Ok(());
};
self.scopes.push(Rc::new(RefCell::new({
let mut scope = BTreeMap::new();
scope.insert("this".to_string(), object.clone());
scope
})));
let outcome = self.assign_the_variables_of_the_instance(&definition, object, cell);
self.scopes.pop();
outcome
}
fn assign_the_variables_of_the_instance(
&mut self,
definition: &Class,
object: &Value,
cell: &Rc<RefCell<Object>>,
) -> Result<(), RuntimeFailure> {
for property in &definition.properties {
if property.is_static {
continue;
}
let value = match &property.value {
Some(node) => self.evaluate(node)?,
None => Value::Text(String::new()),
};
if self.the_accessor_of(object, &property.name).is_some() {
self.the_write_of_an_accessor(object, &property.name, &[], value, 0)?;
continue;
}
put(&mut cell.borrow_mut().properties, &property.name, value);
}
Ok(())
}
fn evaluate_all(&mut self, arguments: &[Node]) -> Result<Vec<Value>, RuntimeFailure> {
Ok(self.evaluate_the_arguments(arguments)?.0)
}
fn evaluate_the_arguments(
&mut self,
arguments: &[Node],
) -> Result<(Vec<Value>, Vec<bool>), RuntimeFailure> {
let mut values = Vec::with_capacity(arguments.len());
let mut missing = Vec::with_capacity(arguments.len());
for argument in arguments {
if let Node::Spread { value, line } = argument {
let spread = self.evaluate(value)?;
let items = self.the_items_of_a_spread(&spread, *line)?;
missing.extend(items.iter().map(|_| false));
values.extend(items);
continue;
}
values.push(self.evaluate(argument)?);
missing.push(matches!(argument, Node::Empty { .. }));
}
Ok((values, missing))
}
fn the_items_of_a_spread(
&mut self,
value: &Value,
line: u32,
) -> Result<Vec<Value>, RuntimeFailure> {
let enumerator = self.the_enumerator(value, 1, line)?;
self.check_the_enumerator(&enumerator, line)?;
let variables = [SPREAD_VARIABLE.to_string()];
let mut items = Vec::new();
while let Some(item) = self.the_next_item(&enumerator, &variables, 1, line)? {
items.push(item);
}
Ok(items)
}
fn the_base_of_the_running_method(&self) -> Option<String> {
let class = self.current_classes.last()?;
self.class_chain(class).get(1).cloned()
}
fn the_this(&self) -> Value {
for scope in self.scopes.iter().rev() {
if let Some(value) = scope.borrow().get("this") {
return value.clone();
}
}
Value::Text(String::new())
}
fn the_class_of_this(&self) -> String {
self.class_of(&self.the_this()).unwrap_or_default()
}
fn call_the_method_of_the_base(
&mut self,
name: &str,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if name.eq_ignore_ascii_case("__init") {
let this = self.the_this();
if let Some(base) = self.the_base_of_the_running_method() {
let chain = self.class_chain(&base);
self.call_the_init_of(&chain, &this, line)?;
}
return Ok(Value::Text(String::new()));
}
let found = self
.the_base_of_the_running_method()
.and_then(|base| self.find_method_in(&base, name));
let Some((defining, method)) = found else {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This value of type \"{}\" has no method named \"{name}\".",
self.the_class_of_this()
),
line,
}));
};
let this = self.the_this();
self.call_method(&defining, &method, &this, arguments, line)
}
fn read_the_property_of_the_base(
&mut self,
name: &str,
line: u32,
) -> Result<Value, RuntimeFailure> {
let base = self.the_base_of_the_running_method();
let this = self.the_this();
if let Some(base) = base {
if let Some((defining, method)) = self.find_method_in(&base, "__get") {
let params = self.the_params(&[], line)?;
return self.call_method_with(
&defining,
&method,
&this,
&[Value::Text(name.to_string()), params],
line,
);
}
}
Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This value of type \"{}\" has no property named \"{name}\".",
self.the_class_of_this()
),
line,
}))
}
fn read_the_item_of_the_base(
&mut self,
keys: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
let base = self.the_base_of_the_running_method();
let this = self.the_this();
if let Some(base) = base {
if let Some((defining, method)) = self.find_method_in(&base, "__item") {
let arguments: Vec<Node> = keys
.iter()
.map(|key| Self::the_node_of_a_value(key, line))
.collect();
return self.call_method(&defining, &method, &this, &arguments, line);
}
} Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This value of type \"{}\" has no property named \"__Item\".",
self.the_class_of_this()
),
line,
}))
}
fn call_method_on(
&mut self,
target: &Value,
name: &str,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match target {
Value::Skipped => return Ok(Value::Skipped),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
if let Some((defining, method)) = self.find_method_on(target, name) {
return self.call_method(&defining, &method, target, arguments, line);
}
if self.class_name_of(target).is_some() {
if name.eq_ignore_ascii_case("call") {
let class = self.class_name_of(target).unwrap_or_default();
if self.dialect.the_call_of_a_class_makes_nothing() {
return Ok(Value::Text(String::new()));
}
return self.construct(&class, arguments, line);
}
if name.eq_ignore_ascii_case("clone") {
return Ok(self.clone_of_a_class(target));
}
if name.eq_ignore_ascii_case("getmethod") {
let values = self.evaluate_all(arguments)?;
return self.the_static_method(target, &values, line);
}
if let Some(value) = self.the_class_that_a_class_holds(target, name) {
if self.dialect.the_call_of_a_class_makes_nothing() {
return Ok(Value::Text(String::new()));
}
let class = self.class_name_of(&value).unwrap_or_default();
return self.construct(&class, arguments, line);
}
}
if let Some(access) = self.the_accessor_of(target, name) {
if !access.parameters.is_empty() {
let Some(getter) = &access.getter else {
return Err(self.no_method(target, name, line));
};
return self.call_the_body_of_an_accessor(target, &access, getter, line, &[], None);
}
}
if name.eq_ignore_ascii_case("__init") {
if let Value::Object(object) = target {
let class = object.borrow().class.clone();
let chain = self.class_chain(&class);
self.call_the_init_of(&chain, target, line)?;
return Ok(Value::Text(String::new()));
}
}
let values = self.evaluate_all(arguments)?;
if let Some(call) = self.the_call_of_the_descriptor(target, name) {
return self.call_the_function(&call, target, &values, line);
}
if let Some(value) = self.the_value_of_the_descriptor_for_a_call(target, name, line)? {
if self.is_a_function(&value) {
return self.call_the_function(&value, target, &values, line);
}
}
let class = match target {
Value::Object(object) => object.borrow().class.clone(),
_ => String::new(),
};
if let Some((min, max)) = crate::classes::the_arity_of(&class, name) {
let count = values.len() as i64;
if count < min || (max >= 0 && count > max) {
let message = if count < min {
"Too few parameters passed to function."
} else {
"Too many parameters passed to function."
};
return Err(crate::classes::the_arity_failure(
&class, name, message, line,
));
}
}
if self.class_name_of(target).is_none()
|| self.dialect.carries_the_class_of_the_extension(&class)
{
if let Some(result) = crate::classes::call(&class, name, target, &values, self, line) {
return result;
}
}
if self.dialect.a_property_that_holds_a_function_is_a_method() {
if let Ok(held) = self.read_property(target, &name.to_lowercase(), line) {
if self.is_a_function(&held) {
return self.call_the_function(&held, target, &values, line);
}
}
}
if let Some(class) = self.the_class_of_the_prototype(target) {
if crate::classes::the_prototype_is_not_one(&class) {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: format!(
"This value of type \"{}\" has no method named \"{}\".",
self.the_type_of(target),
name
),
line,
},
Detail {
what: String::new(),
extra: String::new(),
},
));
}
}
if let Some(class) = self.the_class_of_the_prototype(target) {
if self.the_class_has_the_method(&class, name) {
if self.classes.contains_key(&class) {
if let Some((defining, method)) = self.find_the_instance_method_in(&class, name)
{
return self.call_method_with(&defining, &method, target, &values, line);
}
}
let spelled = self.the_spelling_of_the_method_of_a_class(&class, name);
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_the_class(
&self.the_spelling_of_the_class(&class),
"Prototype",
),
line,
},
Detail {
what: self.the_name_of_a_member(&class, &spelled),
extra: String::new(),
},
));
}
}
if let Some(result) = self.base_method(target, name, &values, line) {
return result;
}
if matches!(target, Value::Text(_))
&& self
.dialect
.carries_the_member_of_the_extension("string", name)
{
if let Some(result) =
crate::classes::call("string", name, target, &values, self, line)
{
return result;
}
}
if let Some((defining, method)) = self.find_method_in(&class, "__call") {
let params = self.the_params(&values, line)?;
return self.call_method_with(
&defining,
&method,
target,
&[Value::Text(name.to_string()), params],
line,
);
}
if self.dialect.a_member_that_is_not_there_is_answered() {
return Ok(Value::Text(String::new()));
}
Err(self.no_method(target, name, line))
}
fn call_method(
&mut self,
class: &str,
method: &MethodDef,
this: &Value,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if arguments
.iter()
.any(|argument| matches!(argument, Node::Spread { .. }))
{
let (values, missing) = self.evaluate_the_arguments(arguments)?;
self.the_arity_of_a_method_at(class, method, values.len(), &missing, line)?;
return self.call_method_with_missing(class, method, this, &values, line, &missing);
}
self.the_arity_of_a_method(class, method, arguments, line)?;
let mut values: Vec<Value> = Vec::with_capacity(arguments.len());
for argument in arguments {
values.push(self.evaluate(argument)?);
}
let missing: Vec<bool> = arguments
.iter()
.map(|argument| matches!(argument, Node::Empty { .. }))
.collect();
self.call_method_with_missing(class, method, this, &values, line, &missing)
}
fn the_arity_of_a_method(
&self,
class: &str,
method: &MethodDef,
arguments: &[Node],
line: u32,
) -> Result<(), RuntimeFailure> {
let missing: Vec<bool> = arguments
.iter()
.map(|argument| matches!(argument, Node::Empty { .. }))
.collect();
self.the_arity_of_a_method_at(class, method, arguments.len(), &missing, line)
}
fn the_arity_of_a_method_at(
&self,
class: &str,
method: &MethodDef,
count: usize,
missing: &[bool],
line: u32,
) -> Result<(), RuntimeFailure> {
if !self.dialect.the_call_of_a_method_checks_the_arity() {
return Ok(());
}
let variadic = method.parameters.iter().any(|parameter| parameter.variadic);
if !variadic && count > method.parameters.len() {
let extra = self.the_name_of_the_method(class, method);
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Too many parameters passed to function.".into(),
line,
},
Detail {
what: String::new(),
extra,
},
));
}
for (index, parameter) in method.parameters.iter().enumerate() {
let is_missing = missing.get(index).copied().unwrap_or(false);
if (is_missing || index >= count) && parameter.is_required() {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Missing a required parameter.".into(),
line,
},
Detail {
what: String::new(),
extra: parameter.name.clone(),
},
));
}
}
Ok(())
}
fn call_method_with(
&mut self,
class: &str,
method: &MethodDef,
this: &Value,
values: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
self.call_method_with_missing(class, method, this, values, line, &[])
}
fn call_method_with_missing(
&mut self,
class: &str,
method: &MethodDef,
this: &Value,
values: &[Value],
line: u32,
missing: &[bool],
) -> Result<Value, RuntimeFailure> {
let variadic = method.parameters.iter().any(|parameter| parameter.variadic);
if self.dialect.the_call_of_a_method_checks_the_arity() {
if !variadic && values.len() > method.parameters.len() {
let extra = self.the_name_of_the_method(class, method);
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Too many parameters passed to function.".into(),
line,
},
Detail {
what: String::new(),
extra,
},
));
}
for (index, parameter) in method.parameters.iter().enumerate() {
let is_missing = missing.get(index).copied().unwrap_or(false);
if (is_missing || values.get(index).is_none())
&& parameter.is_required()
{
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Missing a required parameter.".into(),
line,
},
Detail {
what: String::new(),
extra: parameter.name.clone(),
},
));
}
}
} else {
for (index, parameter) in method.parameters.iter().enumerate() {
let is_missing = missing.get(index).copied().unwrap_or(false);
if (is_missing || values.get(index).is_none())
&& parameter.is_required()
{
return Ok(Value::Text(String::new()));
}
}
}
let mut scope: BTreeMap<String, Value> = BTreeMap::new();
scope.insert("this".to_string(), this.clone());
for (index, parameter) in method.parameters.iter().enumerate() {
let given = values.get(index);
let is_missing = missing.get(index).copied().unwrap_or(false);
if parameter.optional && (is_missing || given.is_none()) {
continue;
}
let value = match given {
Some(value) if !is_missing => value.clone(),
_ => match ¶meter.default {
Some(default) => self.evaluate(default)?,
None => Value::Text(String::new()),
},
};
if parameter.by_ref && given.is_some() && !is_missing {
let Value::Reference(reference) = value else {
return Err(RuntimeFailure::Error(RuntimeError {
message: wants_a_reference(
index + 1,
&method.name,
"a variable reference",
&value,
),
line,
}));
};
let mut alias = reference;
alias.alias = true;
scope.insert(the_key_of(¶meter.name), Value::Reference(alias));
continue;
}
scope.insert(the_key_of(¶meter.name), value);
}
if let Some(index) = method
.parameters
.iter()
.position(|parameter| parameter.variadic)
{
let rest: Vec<Value> = values.iter().skip(index).cloned().collect();
let array = match crate::classes::construct("array", &rest, self, line) {
Some(result) => result?,
None => Value::List(rest),
};
scope.insert(the_key_of(&method.parameters[index].name), array);
}
let frame = self.the_name_of_the_method(class, method);
self.enter_call(line)?;
self.scopes.push(Rc::new(RefCell::new(scope)));
self.collect_the_nested_functions(&method.body);
self.declarations.push(method.declarations.clone());
self.current_classes.push(class.to_lowercase());
self.frames.push(Frame { name: frame, line });
self.label_scopes.push(the_labels_of(&method.body));
let outcome = self.run_block(&method.body);
self.label_scopes.pop();
self.frames.pop();
self.current_classes.pop();
self.declarations.pop();
self.scopes.pop();
self.forget_the_capacities_beyond_the_stack();
self.leave_call();
match outcome {
Ok(()) => Ok(Value::Text(String::new())),
Err(RuntimeFailure::Flow(Flow::Return(value))) => {
Ok(value.unwrap_or(Value::Text(String::new())))
}
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => {
if computed {
Err(self.the_failure_of_a_computed_jump(&name, &method.body, line))
} else {
Err(RuntimeFailure::Fatal(self.the_label_is_not_there(
&name,
&method.body,
line,
)))
}
}
Err(other) => Err(other),
}
}
fn the_base_of_the_value(&self, target: &Value) -> Option<Value> {
let Value::Object(object) = target else {
return None;
};
let class = object.borrow().class.clone();
if class == "prototype" {
let name = object
.borrow()
.value_of(CLASS_NAME)
.map(|value| value.to_text().to_lowercase())?;
let base = crate::classes::the_base_class_of_a_class(&name)?;
return self.the_prototype_of(base);
}
if let Some(name) = self.class_name_of(target) {
if let Some(base) = self.stored_base_of(target) {
return Some(base);
}
return self.the_base_of_the_class(&name);
}
self.base_of(target)
}
fn the_base_of_the_class(&self, name: &str) -> Option<Value> {
let base = self.the_base_of_the_class_name(name)?;
self.class_value_of(&base)
}
fn the_base_of_the_class_name(&self, name: &str) -> Option<String> {
let name = name.to_lowercase();
if let Some(definition) = self.classes.get(&name) {
let base = definition
.extends
.clone()
.unwrap_or_else(|| "object".to_string());
return Some(base.to_lowercase());
}
crate::classes::the_base_class_of_a_class(&name).map(|base| base.to_string())
}
fn the_chain_of_the_class_bases(&self, target: &Value) -> Vec<Value> {
let mut chain: Vec<Value> = Vec::new();
let Some(name) = self.class_name_of(target) else {
return chain;
};
if self.stored_base_of(target).is_some() {
return chain;
}
let mut current = self.the_base_of_the_class_name(&name);
while let Some(class) = current {
let Some(value) = self.class_value_of(&class) else {
break;
};
let Value::Object(object) = &value else { break };
if chain.iter().any(|seen| match seen {
Value::Object(other) => Rc::ptr_eq(other, object),
_ => false,
}) {
break;
}
chain.push(value);
current = self.the_base_of_the_class_name(&class);
}
chain
}
fn the_prototype_of(&self, class: &str) -> Option<Value> {
let Value::Object(value) = self.class_value_of(class)? else {
return None;
};
value.borrow().value_of("prototype")
}
fn the_static_method(
&self,
target: &Value,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Err(RuntimeFailure::Error(RuntimeError {
message: "GetMethod needs a name.".to_string(),
line,
}));
};
let lower = name.to_lowercase();
if lower == "prototype" {
return Err(crate::classes::named(
RuntimeFailure::Error(RuntimeError {
message: "This value of type \"Prototype\" has no method named \"Call\"."
.to_string(),
line,
}),
"GetMethod",
));
}
if let Some(class) = self.class_name_of(target) {
if let Some((defining, method)) = self.find_the_static_method_in(&class, &lower) {
return Ok(self.static_method_reference(&defining, &method));
}
}
if !crate::classes::the_static_methods_of_a_class().contains(&lower.as_str()) {
return Err(crate::classes::named(
self.no_method(target, &name, line),
"GetMethod",
));
}
let spelled = if lower == "call" {
let class = self.class_name_of(target).unwrap_or_default();
format!("{}.Call", crate::classes::the_spelling_of(&class))
} else {
crate::classes::the_name_of_a_method_of_the_base_object(&lower)
};
let (min, max) = crate::classes::the_arity_of("object", &lower).unwrap_or((0, 0));
Ok(self.method_reference_of_the_base_object(&spelled, &lower, min + 1, max + 1))
}
fn the_static_methods_of_a_class_value(&self, target: &Value) -> Vec<String> {
let mut names: Vec<String> = crate::classes::the_static_methods_of_a_class()
.iter()
.map(|name| name.to_string())
.collect();
for name in self.the_static_methods_declared_by_a_class(target) {
if !names.contains(&name) {
names.push(name);
}
}
names
}
fn the_static_methods_declared_by_a_class(&self, target: &Value) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let Some(class) = self.class_name_of(target) else {
return names;
};
for class in self.class_chain(&class) {
let Some(definition) = self.classes.get(&class) else {
continue;
};
for (name, method) in &definition.methods {
if method.is_static && !names.contains(name) {
names.push(name.clone());
}
}
}
names
}
fn the_static_method_of_a_class_value(
&mut self,
target: &Value,
name: &str,
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
let lower = name.to_lowercase();
if !self
.the_static_methods_of_a_class_value(target)
.contains(&lower)
{
return Ok(None);
}
if let Some(class) = self.class_name_of(target) {
if let Some((defining, method)) = self.find_the_static_method_in(&class, &lower) {
return Ok(Some(self.static_method_reference(&defining, &method)));
}
}
let values = [Value::Text(name.to_string())];
Ok(Some(self.the_static_method(target, &values, line)?))
}
fn the_class_of_the_prototype(&self, target: &Value) -> Option<String> {
let Value::Object(object) = target else {
return None;
};
if object.borrow().class != "prototype" {
return None;
}
object
.borrow()
.value_of(CLASS_NAME)
.map(|name| name.to_text().to_lowercase())
}
fn the_spelling_of_the_class(&self, class: &str) -> String {
self.classes
.get(class)
.map(|definition| definition.name.clone())
.unwrap_or_else(|| crate::classes::the_spelling_of(class))
}
fn the_name_of_a_member(&self, class: &str, member: &str) -> String {
format!(
"{}.Prototype.{}",
self.the_spelling_of_the_class(class),
member
)
}
fn the_spelling_of_the_method_of_a_class(&self, class: &str, name: &str) -> String {
let lower = name.to_lowercase();
if let Some(definition) = self.classes.get(class) {
if let Some(method) = definition.methods.get(&lower) {
return method.name.clone();
}
}
crate::classes::the_method_of(class, &lower)
.map(|(spelled, _, _)| spelled.to_string())
.unwrap_or_else(|| name.to_string())
}
fn the_class_has_the_method(&self, class: &str, name: &str) -> bool {
let lower = name.to_lowercase();
if crate::classes::the_base_object_has_the_method(&lower) {
return false;
}
if self.classes.contains_key(class) {
return self.find_the_instance_method_in(class, &lower).is_some();
}
crate::classes::the_methods_of_the_prototype(class)
.iter()
.any(|method| method.to_lowercase() == lower)
}
fn the_prototype_has_the_member(&self, class: &str, name: &str) -> bool {
let lower = name.to_lowercase();
if let Some(definition) = self.classes.get(class) {
return definition
.methods
.values()
.any(|method| !method.is_static && method.name.to_lowercase() == lower)
|| definition
.accessors
.values()
.any(|access| !access.is_static && access.name.to_lowercase() == lower);
}
crate::classes::the_members_of_the_prototype(class)
.iter()
.any(|member| member.to_lowercase() == lower)
}
fn the_own_properties_of_a_prototype(&self, target: &Value) -> Vec<String> {
let mut names = vec!["__Class".to_string()];
let Some(class) = self.the_class_of_the_prototype(target) else {
return names;
};
match self.classes.get(&class) {
Some(definition) => {
for method in definition.methods.values() {
if !method.is_static {
names.push(method.name.clone());
}
}
for access in definition.accessors.values() {
if !access.is_static {
names.push(access.name.clone());
}
}
if !definition.methods.contains_key("__init")
&& definition
.properties
.iter()
.any(|property| !property.is_static)
{
names.push("__Init".to_string());
}
}
None => {
for name in crate::classes::the_members_of_the_prototype(&class) {
names.push((*name).to_string());
}
}
}
names.sort_by_key(|name| name.to_lowercase());
names.dedup();
names
}
fn the_value_of_an_own_property_of_a_prototype(&self, target: &Value, name: &str) -> Value {
let lower = name.to_lowercase();
if lower == "__class" {
return Value::Text(self.the_class_of_the_value(target));
}
let Some(class) = self.the_class_of_the_prototype(target) else {
return Value::Text(String::new());
};
if let Some((defining, method)) = self.find_method_in(&class, &lower) {
return self.method_reference(&defining, &method);
}
if let Some((spelled, min, max)) = crate::classes::the_method_of(&class, &lower)
.or_else(|| self.the_extension_method(&class, &lower))
{
return self.method_reference_of_a_class_type(&class, spelled, min, max);
}
if crate::classes::the_base_object_has_the_method(&lower) {
let spelled = crate::classes::the_name_of_a_method_of_the_base_object(&lower);
let (min, max) = crate::classes::the_arity_of("object", &lower).unwrap_or((0, 0));
return self.method_reference_of_the_base_object(&spelled, &lower, min + 1, max + 1);
}
Value::Text(String::new())
}
fn the_own_properties_of_a_class_value(&self, target: &Value) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let Some(class) = self.class_name_of(target) else {
return names;
};
match self.classes.get(&class) {
Some(definition) => {
names.push("__Init".to_string());
for method in definition.methods.values() {
if method.is_static {
names.push(method.name.clone());
}
}
for access in definition.accessors.values() {
if access.is_static {
names.push(access.name.clone());
}
}
for nested in &definition.nested {
names.push(self.the_name_of_a_class(nested));
}
}
None => {
if crate::classes::the_class_owns_the_call(&class) {
names.push("Call".to_string());
}
}
}
names.push("Prototype".to_string());
names
}
fn the_value_of_an_own_property_of_a_class_value(
&self,
target: &Value,
name: &str,
line: u32,
) -> Value {
let lower = name.to_lowercase();
match lower.as_str() {
"call" => self
.the_static_method(target, &[Value::Text(name.to_string())], line)
.unwrap_or_else(|_| Value::Text(String::new())),
"__init" => self.the_init_of_a_class_value(target),
"prototype" => match target {
Value::Object(object) => object
.borrow()
.value_of("prototype")
.unwrap_or_else(|| Value::Text(String::new())),
_ => Value::Text(String::new()),
},
_ => {
let Some(class) = self.class_name_of(target) else {
return Value::Text(String::new());
};
if let Some(value) = self.the_class_that_a_class_holds(target, name) {
return value;
}
match self.find_the_static_method_in(&class, &lower) {
Some((defining, method)) => self.static_method_reference(&defining, &method),
None => Value::Text(String::new()),
}
}
}
}
fn the_init_of_a_class_value(&self, target: &Value) -> Value {
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
let mut name = String::new();
let mut built_in = 1;
if let Some(class) = self.class_name_of(target) {
if let Some(definition) = self.classes.get(&class) {
name = format!("{}.__Init", definition.name);
built_in = 0;
}
}
put(&mut properties, "name", Value::Text(name));
put(&mut properties, "minparams", Value::Int(1));
put(&mut properties, "maxparams", Value::Int(1));
put(&mut properties, "isbuiltin", Value::Int(built_in));
put(&mut properties, "isvariadic", Value::Int(0));
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
fn static_method_reference(&self, class: &str, method: &MethodDef) -> Value {
let owner = self
.classes
.get(class)
.map(|definition| definition.name.clone())
.unwrap_or_else(|| class.to_string());
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(
&mut properties,
"name",
Value::Text(format!("{owner}.{}", method.name)),
);
let required = method
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count();
put(
&mut properties,
"minparams",
Value::Int(required as i64 + 1),
);
put(
&mut properties,
"maxparams",
Value::Int(method.parameters.len() as i64 + 1),
);
put(&mut properties, "isbuiltin", Value::Int(0));
put(&mut properties, "isvariadic", Value::Int(0));
put(
&mut properties,
PARAMETERS,
the_flags_of_the_parameters(&method.parameters, true),
);
put(
&mut properties,
METHOD_CLASS,
Value::Text(class.to_string()),
);
put(
&mut properties,
METHOD_NAME,
Value::Text(method.name.clone()),
);
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
fn method_reference_of_the_base_object(
&self,
spelled: &str,
method: &str,
min: i64,
max: i64,
) -> Value {
let mut properties = BTreeMap::new();
put(&mut properties, "name", Value::Text(spelled.to_string()));
put(&mut properties, "minparams", Value::Int(min));
put(&mut properties, "maxparams", Value::Int(max));
put(&mut properties, "isbuiltin", Value::Int(1));
put(&mut properties, "isvariadic", Value::Int(0));
put(
&mut properties,
METHOD_CLASS,
Value::Text("object".to_string()),
);
put(
&mut properties,
METHOD_NAME,
Value::Text(method.to_string()),
);
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
fn clone_of_an_object(&self, target: &Value) -> Value {
let Value::Object(object) = target else {
return target.clone();
};
let class = object.borrow().class.clone();
let mut properties = BTreeMap::new();
for (key, property) in object.borrow().properties.iter() {
properties.insert(key.clone(), property.clone());
}
Value::Object(Rc::new(RefCell::new(Object { class, properties })))
}
fn clone_of_a_class(&self, target: &Value) -> Value {
let Value::Object(object) = target else {
return target.clone();
};
let class = object.borrow().class.clone();
let mut properties = BTreeMap::new();
for (key, property) in object.borrow().properties.iter() {
properties.insert(key.clone(), property.clone());
}
let key = format!("{} copy {}", class, self.class_values.borrow().len());
let copy = Value::Object(Rc::new(RefCell::new(Object { class, properties })));
self.class_values.borrow_mut().insert(key, copy.clone());
copy
}
pub(crate) fn base_method(
&mut self,
target: &Value,
name: &str,
arguments: &[Value],
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let answer = self.the_base_method(target, name, arguments, line);
answer.map(|result| {
result.map_err(|failure| {
crate::classes::named(
failure,
&crate::classes::the_name_of_a_method_of_the_base_object(name),
)
})
})
}
fn the_method_of_the_v1(
&mut self,
target: &Value,
name: &str,
_arguments: &[Value],
_line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
match name.to_lowercase().as_str() {
"count" => Some(Ok(Value::Int(self.the_members_of_the_v1(target) as i64))),
"length" => Some(Ok(Value::Int(self.the_items_of_the_v1(target) as i64))),
_ => None,
}
}
fn the_members_of_the_v1(&self, target: &Value) -> usize {
let Value::Object(object) = target else {
return 0;
};
let mut count = 0;
for name in object.borrow().properties.keys() {
if name.as_str() == BASE
|| name.as_str() == CLASS_NAME
|| name.as_str() == "prototype"
|| name.as_str() == "array state"
{
continue;
}
count += 1;
}
count + crate::classes::array::the_number_of_the_items(target)
}
fn the_items_of_the_v1(&self, target: &Value) -> usize {
crate::classes::array::the_number_of_the_places(target)
}
fn the_base_method(
&mut self,
target: &Value,
name: &str,
arguments: &[Value],
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let Value::Object(object) = target else {
return None;
};
if !self.dialect.the_object_has_the_methods_of_the_base_object() {
return self.the_method_of_the_v1(target, name, arguments, line);
}
let class = object.borrow().class.clone();
let method = name.to_string();
let missing = || {
RuntimeFailure::Error(RuntimeError {
message: format!("{method} needs a name."),
line,
})
};
match name.to_lowercase().as_str() {
"clone" => {
if class == "prototype" {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: "Type mismatch.".to_string(),
line,
})));
}
if crate::classes::the_method_of(&class, "clone").is_some() {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: "Type mismatch.".to_string(),
line,
})));
}
Some(Ok(self.clone_of_an_object(target)))
}
"call" => {
let class = self.class_name_of(target)?;
Some(self.construct_with_values(&class, arguments, line))
}
"hasprop" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Err(missing()));
};
let found = object.borrow().properties.contains_key(&name.to_lowercase())
|| self.declares_an_instance_property(&class, &name)
|| name.eq_ignore_ascii_case("__class")
|| name.eq_ignore_ascii_case("base")
|| self.find_the_instance_method_in(&class, &name).is_some()
|| crate::classes::the_method_of(&class, &name).or_else(|| self.the_extension_method(&class, &name)).is_some()
|| self.the_accessor_of(target, &name).is_some()
|| name.eq_ignore_ascii_case("__init")
|| crate::classes::the_base_object_has_the_method(&name);
let found = if let Some(class) = self.the_class_of_the_prototype(target) {
crate::classes::the_members_of_the_prototype(&class)
.iter()
.any(|member| member.to_lowercase() == name.to_lowercase())
|| self.find_the_instance_method_in(&class, &name).is_some()
|| self.the_accessor_of(target, &name).is_some()
|| name.eq_ignore_ascii_case("__init")
|| name.eq_ignore_ascii_case("__class")
} else if self.class_name_of(target).is_some() {
self.the_own_properties_of_a_class_value(target)
.iter()
.any(|own| own.to_lowercase() == name.to_lowercase())
|| object
.borrow()
.properties
.contains_key(&name.to_lowercase())
|| name.eq_ignore_ascii_case("base")
|| self
.the_static_methods_of_a_class_value(target)
.iter()
.any(|method| *method == name.to_lowercase())
|| name.eq_ignore_ascii_case("__class")
} else {
found
};
Some(Ok(Value::Int(found as i64)))
}
"hasmethod" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Ok(Value::Int(self.class_name_of(target).is_some() as i64)));
};
let class = if class == "prototype" {
object
.borrow()
.value_of(CLASS_NAME)
.map(|name| name.to_text().to_lowercase())
.unwrap_or(class)
} else {
class
};
let found = if self.class_name_of(target).is_some() {
self.the_static_methods_of_a_class_value(target)
.contains(&name.to_lowercase())
} else if let Some(class) = self.the_class_of_the_prototype(target) {
self.find_the_instance_method_in(&class, &name).is_some()
|| crate::classes::the_methods_of_the_prototype(&class)
.iter()
.any(|method| method.to_lowercase() == name.to_lowercase())
|| crate::classes::the_base_object_has_the_method(&name)
} else {
self.find_the_instance_method_in(&class, &name).is_some()
|| crate::classes::the_method_of(&class, &name).or_else(|| self.the_extension_method(&class, &name)).is_some()
|| crate::classes::the_base_object_has_the_method(&name)
};
let found = found || name.eq_ignore_ascii_case("__init");
Some(Ok(Value::Int(found as i64)))
}
"getmethod" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Err(missing()));
};
if let Some(class) = self.the_class_of_the_prototype(target) {
if let Some((defining, method)) =
self.find_the_instance_method_in(&class, &name)
{
return Some(Ok(self.method_reference(&defining, &method)));
}
if let Some((spelled, min, max)) = crate::classes::the_method_of(&class, &name).or_else(|| self.the_extension_method(&class, &name))
{
let reference =
self.method_reference_of_a_class_type(&class, spelled, min, max);
return Some(Ok(reference));
}
if crate::classes::the_base_object_has_the_method(&name) {
let spelled =
crate::classes::the_name_of_a_method_of_the_base_object(&name);
let (min, max) =
crate::classes::the_arity_of("object", &name).unwrap_or((0, 0));
let reference = self.method_reference_of_the_base_object(
&spelled,
&name,
min + 1,
max + 1,
);
return Some(Ok(reference));
}
return Some(Err(self.no_method(target, &name, line)));
}
if let Some((defining, method)) = self.find_the_instance_method_in(&class, &name) {
return Some(Ok(self.method_reference(&defining, &method)));
}
if let Some((spelled, min, max)) = crate::classes::the_method_of(&class, &name).or_else(|| self.the_extension_method(&class, &name)) {
let reference =
self.method_reference_of_a_class_type(&class, spelled, min, max);
return Some(Ok(reference));
}
if crate::classes::the_base_object_has_the_method(&name) {
let spelled = crate::classes::the_name_of_a_method_of_the_base_object(&name);
let (min, max) =
crate::classes::the_arity_of("object", &name).unwrap_or((0, 0));
let reference =
self.method_reference_of_the_base_object(&spelled, &name, min + 1, max + 1);
return Some(Ok(reference));
}
Some(Err(self.no_method(target, &name, line)))
}
"hasbase" => {
let Some(base) = arguments.first() else {
return Some(Err(missing()));
};
let Value::Object(base) = base else {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: format!("Expected an object but got {}.", the_kind_of(base)),
line,
})));
};
if self.class_name_of(target).is_some() {
let chain = self.the_chain_of_the_class_bases(target);
return Some(Ok(Value::Int(chain.iter().any(|object| match object {
Value::Object(one) => Rc::ptr_eq(one, base),
_ => false,
}) as i64)));
}
let chain = self.the_chain_of_the_bases(target);
Some(Ok(Value::Int(
chain.iter().any(|object| Rc::ptr_eq(object, base)) as i64,
)))
}
"hasownprop" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Err(missing()));
};
let lower = name.to_lowercase();
if let Some(class) = self.the_class_of_the_prototype(target) {
if crate::classes::the_prototype_is_not_one(&class) {
return Some(Err(RuntimeFailure::Detailed(
RuntimeError {
message: format!(
"This value of type \"{}\" has no method named \"HasOwnProp\".",
self.the_type_of(target)
),
line,
},
Detail {
what: String::new(),
extra: String::new(),
},
)));
}
let own = self
.the_own_properties_of_a_prototype(target)
.iter()
.any(|name| name.to_lowercase() == lower);
return Some(Ok(Value::Int(own as i64)));
}
let own = if matches!(object.borrow().class.as_str(), "func" | "closure") {
false
} else if self.class_name_of(target).is_some() {
object.borrow().properties.contains_key(&lower)
&& lower != CLASS_NAME
&& lower != BASE
&& lower != "prototype"
} else {
object.borrow().properties.contains_key(&lower)
};
let own = own
|| (self.class_name_of(target).is_some()
&& self
.the_own_properties_of_a_class_value(target)
.iter()
.any(|name| name.to_lowercase() == lower));
Some(Ok(Value::Int(own as i64)))
}
"ownprops" => {
if let Some(class) = self.the_class_of_the_prototype(target) {
if crate::classes::the_prototype_is_not_one(&class) {
return Some(Err(RuntimeFailure::Detailed(
RuntimeError {
message: format!(
"This value of type \"{}\" has no method named \"OwnProps\".",
self.the_type_of(target)
),
line,
},
Detail {
what: String::new(),
extra: String::new(),
},
)));
}
let mut pairs: Vec<(Value, Value)> = Vec::new();
for name in self.the_own_properties_of_a_prototype(target) {
let value = self.the_value_of_an_own_property_of_a_prototype(target, &name);
pairs.push((Value::Text(name), value));
}
return Some(Ok(crate::classes::enumerator::make(
pairs,
crate::classes::enumerator::Alone::TheKey,
)));
}
if self.class_name_of(target).is_some() {
let mut pairs: Vec<(Value, Value)> = Vec::new();
for name in self.the_own_properties_of_a_class_value(target) {
let value =
self.the_value_of_an_own_property_of_a_class_value(target, &name, line);
pairs.push((Value::Text(name), value));
}
for (name, property) in object.borrow().properties.iter() {
if name.as_str() == BASE
|| name.as_str() == CLASS_NAME
|| name.as_str() == "prototype"
{
continue;
}
pairs.push((Value::Text(property.name.clone()), property.value.clone()));
}
pairs.sort_by(|left, right| {
left.0
.to_text()
.to_lowercase()
.cmp(&right.0.to_text().to_lowercase())
});
return Some(Ok(crate::classes::enumerator::make(
pairs,
crate::classes::enumerator::Alone::TheKey,
)));
}
if object.borrow().class == "func" {
return Some(Ok(crate::classes::enumerator::make(
Vec::new(),
crate::classes::enumerator::Alone::TheKey,
)));
}
let mut own: Vec<(String, Value)> = object
.borrow()
.properties
.iter()
.filter(|(name, _)| name.as_str() != BASE && name.as_str() != CLASS_NAME)
.map(|(_, property)| (property.name.clone(), property.value.clone()))
.collect();
own.sort_by_key(|(name, _)| name.to_lowercase());
let mut pairs: Vec<(Value, Value)> = Vec::with_capacity(own.len());
for (name, value) in own {
let value = match self.the_value_of_the_descriptor(&value, target, &name, line)
{
Ok(Some(value)) => value,
Ok(None) => value,
Err(_) => Value::Text(String::new()),
};
pairs.push((Value::Text(name), value));
}
Some(Ok(crate::classes::enumerator::make(
pairs,
crate::classes::enumerator::Alone::TheKey,
)))
}
"defineprop" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Err(missing()));
};
let descriptor = match self.the_descriptor(arguments.get(1), line) {
Ok(descriptor) => descriptor,
Err(failure) => return Some(Err(failure)),
};
if self.dialect.a_property_that_holds_a_function_is_a_method() {
if matches!(&descriptor, Value::Object(fresh) if fresh.borrow().value_of("value").is_some())
{
put(&mut object.borrow_mut().properties, &name, descriptor);
return Some(Ok(target.clone()));
}
let old = object.borrow().value_of(&name.to_lowercase());
if let (Some(old), Value::Object(fresh)) = (old, &descriptor) {
if self.is_a_descriptor(&old) {
if let Value::Object(before) = &old {
for key in ["get", "set"] {
if fresh.borrow().value_of(key).is_some() {
continue;
}
if let Some(held) = before.borrow().value_of(key) {
put(&mut fresh.borrow_mut().properties, key, held);
}
}
}
}
}
}
put(&mut object.borrow_mut().properties, &name, descriptor);
Some(Ok(target.clone()))
}
"deleteprop" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Err(missing()));
};
let gone = object
.borrow_mut()
.properties
.remove(&name.to_lowercase())
.map(|property| property.value);
Some(Ok(match gone {
None => Value::Text(String::new()),
Some(value) => {
match self.the_value_of_the_descriptor(&value, target, &name, line) {
Ok(Some(value)) => value,
_ => value,
}
}
}))
}
"getownpropdesc" => {
let Some(name) = arguments.first().map(|value| value.to_text()) else {
return Some(Err(missing()));
};
let key = name.to_lowercase();
let value = object.borrow().value_of(&key);
match value {
Some(value) => {
let table = match self.the_members_of_a_descriptor(&value) {
Some(members) => members,
None => {
let mut table = BTreeMap::new();
put(&mut table, "value", value);
table
}
};
Some(Ok(Value::Object(Rc::new(RefCell::new(Object {
class: "object".to_string(),
properties: table,
})))))
}
None => Some(Err(self.no_property(target, &name, line))),
}
}
_ => None,
}
}
pub(crate) fn the_type_of(&self, value: &Value) -> String {
if self.class_name_of(value).is_some() {
return "Class".to_string();
}
match self.class_of(value) {
Some(name) => name,
None => value.the_kind(),
}
}
fn the_class_of_the_value(&self, value: &Value) -> String {
if !self.dialect.every_value_carries_its_class() {
return self.class_of(value).unwrap_or_default();
}
if self.class_name_of(value).is_some() {
return "Class".to_string();
}
if let Value::Object(object) = value {
if object.borrow().class == "prototype" {
let name = object
.borrow()
.value_of(CLASS_NAME)
.map(|value| value.to_text())
.unwrap_or_default();
return crate::classes::the_spelling_of(&name);
}
}
match value {
Value::Int(_) => "Integer".to_string(),
Value::Float(_) => "Float".to_string(),
Value::Text(_) => "String".to_string(),
Value::List(_) => "Array".to_string(),
Value::Reference(_) => "VarRef".to_string(),
Value::Unset | Value::Skipped => String::new(),
Value::Object(_) => self.the_type_of(value),
}
}
pub(crate) fn no_property(&self, target: &Value, name: &str, line: u32) -> RuntimeFailure {
let kind = self.the_type_of(target);
if self.class_name_of(target).is_none() {
if let Some(reason) = crate::classes::the_reason_of_a_class_that_is_not_carried(&kind) {
return RuntimeFailure::Error(RuntimeError {
message: reason.to_string(),
line,
});
}
}
RuntimeFailure::Error(RuntimeError {
message: format!("This value of type \"{kind}\" has no property named {name:?}."),
line,
})
}
pub(crate) fn the_message_of_no_property(
&self,
target: &Value,
name: &str,
line: u32,
) -> String {
match self.no_property(target, name, line) {
RuntimeFailure::Error(error) => error.message,
RuntimeFailure::Detailed(error, _) => error.message,
_ => format!(
"This value of type \"{}\" has no property named {name:?}.",
self.the_type_of(target)
),
}
}
pub(crate) fn the_descriptor(
&self,
value: Option<&Value>,
line: u32,
) -> Result<Value, RuntimeFailure> {
let invalid = || {
RuntimeFailure::Detailed(
RuntimeError {
message: "Parameter #2 of Object.Prototype.DefineProp is invalid.".into(),
line,
},
Detail {
what: String::new(),
extra: value.map(|value| value.to_text()).unwrap_or_default(),
},
)
};
let Some(Value::Object(object)) = value else {
return Err(invalid());
};
let table = object.borrow();
let mut members: BTreeMap<String, Property> = BTreeMap::new();
for key in ["value", "get", "set", "call"] {
if let Some(member) = table.properties.get(key) {
members.insert(key.to_string(), member.clone());
}
}
if members.is_empty() || (members.contains_key("value") && members.len() > 1) {
return Err(invalid());
}
Ok(Value::Object(Rc::new(RefCell::new(Object {
class: DESCRIPTOR.to_string(),
properties: members,
}))))
}
fn is_a_descriptor(&self, value: &Value) -> bool {
let Value::Object(object) = value else {
return false;
};
object.borrow().class == DESCRIPTOR
}
pub(crate) fn the_members_of_a_descriptor(
&self,
value: &Value,
) -> Option<BTreeMap<String, Property>> {
if !self.is_a_descriptor(value) {
return None;
}
let Value::Object(object) = value else {
return None;
};
Some(object.borrow().properties.clone())
}
pub(crate) fn the_value_of_the_descriptor(
&mut self,
value: &Value,
target: &Value,
written: &str,
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
if !self.is_a_descriptor(value) {
return Ok(None);
}
let Value::Object(object) = value else {
return Ok(None);
};
let getter = object.borrow().value_of("get");
let held = object.borrow().value_of("value");
if let Some(getter) = getter {
return Ok(Some(self.call_the_function(&getter, target, &[], line)?));
}
if let Some(held) = held {
return Ok(Some(held));
}
Err(self.no_property(target, written, line))
}
fn the_call_of_the_descriptor(&self, target: &Value, name: &str) -> Option<Value> {
let Value::Object(object) = target else {
return None;
};
let current = object.borrow().value_of(&name.to_lowercase())?;
if !self.is_a_descriptor(¤t) {
return None;
}
let Value::Object(descriptor) = ¤t else {
return None;
};
descriptor.borrow().value_of("call")
}
fn the_value_of_the_descriptor_for_a_call(
&mut self,
target: &Value,
name: &str,
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
let Value::Object(object) = target else {
return Ok(None);
};
let Some(current) = object.borrow().value_of(&name.to_lowercase()) else {
return Ok(None);
};
if !self.is_a_descriptor(¤t) {
return Ok(None);
}
let Value::Object(descriptor) = ¤t else {
return Ok(None);
};
let getter = descriptor.borrow().value_of("get");
let Some(getter) = getter else {
return Ok(None);
};
Ok(Some(self.call_the_function(&getter, target, &[], line)?))
}
fn is_a_function(&self, value: &Value) -> bool {
let Value::Object(object) = value else {
return false;
};
object.borrow().class == "func"
}
fn the_write_of_the_descriptor(
&mut self,
descriptor: &Value,
target: &Value,
value: Value,
written: &str,
line: u32,
) -> Result<(), RuntimeFailure> {
let Value::Object(object) = descriptor else {
return Ok(());
};
let setter = object.borrow().value_of("set");
if let Some(setter) = setter {
self.call_the_function(&setter, target, &[value], line)?;
return Ok(());
}
let holds = object.borrow().properties.contains_key("value");
if holds {
object.borrow_mut().put("value", value);
return Ok(());
}
Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Property is read-only.".to_string(),
line,
},
Detail {
what: String::new(),
extra: written.to_string(),
},
))
}
fn call_the_function(
&mut self,
function: &Value,
target: &Value,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
let mut values = Vec::with_capacity(arguments.len() + 1);
values.push(target.clone());
values.extend_from_slice(arguments);
match crate::classes::func::call_the_value(function, &values, self, line) {
Some(result) => result,
None => Err(self.no_method(target, "Call", line)),
}
}
pub(crate) fn no_method(&self, target: &Value, name: &str, line: u32) -> RuntimeFailure {
let kind = self.the_type_of(target);
if self.class_name_of(target).is_none() {
if let Some(reason) = crate::classes::the_reason_of_a_class_that_is_not_carried(&kind) {
return RuntimeFailure::Error(RuntimeError {
message: reason.to_string(),
line,
});
}
}
RuntimeFailure::Error(RuntimeError {
message: format!("This value of type \"{kind}\" has no method named {name:?}."),
line,
})
}
fn no_item(&self, target: &Value, line: u32) -> RuntimeFailure {
RuntimeFailure::Error(RuntimeError {
message: format!(
"This value of type \"{}\" has no property named \"__Item\".",
self.the_type_of(target)
),
line,
})
}
fn the_name_of_the_method(&self, class: &str, method: &MethodDef) -> String {
let owner = self
.classes
.get(class)
.map(|definition| definition.name.clone())
.unwrap_or_else(|| class.to_string());
format!("{owner}.Prototype.{}", method.name)
}
fn method_reference(&self, class: &str, method: &MethodDef) -> Value {
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(
&mut properties,
"name",
Value::Text(self.the_name_of_the_method(class, method)),
);
let required = method
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count();
put(
&mut properties,
"minparams",
Value::Int(required as i64 + 1),
);
put(
&mut properties,
"maxparams",
Value::Int(method.parameters.len() as i64 + 1),
);
put(&mut properties, "isbuiltin", Value::Int(0));
put(&mut properties, "isvariadic", Value::Int(0));
put(
&mut properties,
PARAMETERS,
the_flags_of_the_parameters(&method.parameters, true),
);
put(
&mut properties,
METHOD_CLASS,
Value::Text(class.to_string()),
);
put(
&mut properties,
METHOD_NAME,
Value::Text(method.name.clone()),
);
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
pub(crate) fn bound_function(&self, object: Value, target: Value) -> Value {
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(&mut properties, "name", Value::Text(String::new()));
put(&mut properties, "minparams", Value::Int(0));
put(&mut properties, "maxparams", Value::Int(0));
put(&mut properties, "isbuiltin", Value::Int(0));
put(&mut properties, "isvariadic", Value::Int(0));
put(&mut properties, BOUND, object);
put(&mut properties, BOUND_TARGET, target);
Value::Object(Rc::new(RefCell::new(Object {
class: "boundfunc".to_string(),
properties,
})))
}
fn the_extension_method(&self, class: &str, member: &str) -> Option<(&'static str, i64, i64)> {
if !self
.dialect
.carries_the_member_of_the_extension(class, member)
{
return None;
}
crate::extensions::the_method_of(class, member)
}
pub(crate) fn method_reference_of_a_class_type(
&self,
class: &str,
spelled: &str,
min: i64,
max: i64,
) -> Value {
let mut properties = BTreeMap::new();
let owner = crate::classes::the_spelling_of(class);
put(
&mut properties,
"name",
Value::Text(format!("{owner}.Prototype.{spelled}")),
);
put(&mut properties, "minparams", Value::Int(min));
put(&mut properties, "maxparams", Value::Int(max));
put(&mut properties, "isbuiltin", Value::Int(0));
put(&mut properties, "isvariadic", Value::Int(0));
put(
&mut properties,
METHOD_CLASS,
Value::Text(class.to_string()),
);
put(
&mut properties,
METHOD_NAME,
Value::Text(spelled.to_string()),
);
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
pub(crate) fn call_a_method_reference(
&mut self,
class: &str,
method: &str,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
if crate::classes::is_type(class) {
if let Some((min, max)) = crate::classes::the_arity_of(class, method) {
let count = arguments.len() as i64;
if count < min + 1 || (max >= 0 && count > max + 1) {
let message = if count < min + 1 {
"Too few parameters passed to function."
} else {
"Too many parameters passed to function."
};
return Err(crate::classes::the_arity_failure(
class, method, message, line,
));
}
}
let Some((this, rest)) = arguments.split_first() else {
return Err(crate::classes::the_arity_failure(
class,
method,
"Too few parameters passed to function.",
line,
));
};
return match crate::classes::call(class, method, this, rest, self, line) {
Some(result) => result,
None => Err(self.no_method(this, method, line)),
};
}
let Some((defining, definition)) = self.find_method_in(class, method) else {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!("There is no method named {method:?} in this class."),
line,
}));
};
let Some((this, rest)) = arguments.split_first() else {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Missing a required parameter.".into(),
line,
}));
};
self.call_method_with(&defining, &definition, this, rest, line)
}
pub(crate) fn call_a_bound_function(
&mut self,
bound: &Value,
target: &Value,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
match target {
Value::Text(method) => self.call_a_method_of_an_object(bound, method, arguments, line),
_ => {
let mut all = Vec::with_capacity(arguments.len() + 1);
all.push(bound.clone());
all.extend_from_slice(arguments);
let class = match target {
Value::Object(object) => object.borrow().class.clone(),
_ => String::new(),
};
match crate::classes::call_the_value(&class, target, &all, self, line) {
Some(result) => result,
None => Err(self.no_method(bound, &target.to_text(), line)),
}
}
}
}
pub(crate) fn call_a_method_of_an_object(
&mut self,
target: &Value,
method: &str,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
if let Some((defining, definition)) = self.find_method_on(target, method) {
return self.call_method_with(&defining, &definition, target, arguments, line);
}
let class = match target {
Value::Object(object) => object.borrow().class.clone(),
_ => String::new(),
};
if crate::classes::is_type(&class) {
if let Some((min, max)) = crate::classes::the_arity_of(&class, method) {
let count = arguments.len() as i64;
if count < min || (max >= 0 && count > max) {
let message = if count < min {
"Too few parameters passed to function."
} else {
"Too many parameters passed to function."
};
return Err(crate::classes::the_arity_failure(
&class, method, message, line,
));
}
}
return match crate::classes::call(&class, method, target, arguments, self, line) {
Some(result) => result,
None => Err(self.no_method(target, method, line)),
};
}
if crate::classes::the_base_object_has_the_method(&method.to_lowercase()) {
return match self.base_method(target, &method.to_lowercase(), arguments, line) {
Some(result) => result,
None => Err(self.no_method(target, method, line)),
};
}
Err(self.no_method(target, method, line))
}
pub(crate) fn read_property(
&mut self,
target: &Value,
name: &str,
line: u32,
) -> Result<Value, RuntimeFailure> {
self.read_property_with(target, name, &[], line)
}
fn read_property_with(
&mut self,
target: &Value,
name: &str,
params: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
self.read_property_fully(target, name, params, line)
.map(|(value, _)| value)
}
fn read_property_fully(
&mut self,
target: &Value,
name: &str,
params: &[Value],
line: u32,
) -> Result<(Value, bool), RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match target {
Value::Skipped => return Ok((Value::Skipped, false)),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
let written = name.to_string();
let name = name.to_lowercase();
let Value::Object(object) = target else {
if name == "__class" {
return Ok((Value::Text(self.the_class_of_the_value(target)), false));
}
if self.dialect.a_member_that_is_not_there_is_answered() {
return Ok((Value::Text(String::new()), false));
}
return Err(self.no_property(target, &written, line));
};
let class = object.borrow().class.clone();
let owner = self.the_class_of_the_prototype(target);
let members = owner.clone().unwrap_or_else(|| class.clone());
if let Some(class) = &owner {
let property = crate::classes::the_property_of_the_prototype(class, &name)
.map(|spelled| spelled.to_string());
if let Some(spelled) = property {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_the_class(
&self.the_spelling_of_the_class(class),
"Prototype",
),
line,
},
Detail {
what: self.the_name_of_a_member(class, &format!("{spelled}.Get")),
extra: String::new(),
},
));
}
}
let ks_class = self.dialect.carries_the_class_of_the_extension(&class);
if self.class_name_of(target).is_none() || ks_class {
if !params.is_empty() {
if let Some(result) =
crate::classes::property_with_params(&class, &name, params, target, self, line)
{
return result.map(|value| (value, true));
}
}
if let Some(result) = crate::classes::property(&class, &name, target, self, line) {
return result.map(|value| (value, false));
}
}
let the_parameters_are_the_getters = self
.the_accessor_of(target, &written)
.map(|access| !access.parameters.is_empty())
.unwrap_or(false);
let given = if the_parameters_are_the_getters {
params
} else {
&[][..]
};
if let Some(value) = self.the_value_of_an_accessor(target, &written, given, line)? {
if self.dialect.the_chain_may_be_skipped()
&& !the_parameters_are_the_getters
&& matches!(value, Value::Unset)
{
return Err(self.the_failure_of_an_absent_value(line));
}
return Ok((value, the_parameters_are_the_getters));
}
if let Some(value) = object.borrow().value_of(&name) {
if let Some(answer) =
self.the_value_of_the_descriptor(&value, target, &written, line)?
{
return Ok((answer, false));
}
if self.dialect.the_chain_may_be_skipped() && matches!(value, Value::Unset) {
return Err(self.the_failure_of_an_absent_value(line));
}
return Ok((value, false));
}
if self.dialect.the_nested_class_is_a_member_of_the_instance() {
if let Some(value) = self.the_class_that_the_v1_holds(target, &name) {
return Ok((value, false));
}
}
if self.class_name_of(target).is_some() {
if let Some(value) = self.the_static_method_of_a_class_value(target, &name, line)? {
return Ok((value, false));
}
if name == "__init" {
return Ok((self.the_init_of_a_class_value(target), false));
}
if let Some(value) = self.the_class_that_a_class_holds(target, &name) {
return Ok((value, false));
}
}
if name == "base" {
if let Some(base) = self.the_base_of_the_value(target) {
return Ok((base, false));
}
}
if name == "__class" {
return Ok((Value::Text(self.the_class_of_the_value(target)), false));
}
if self.class_name_of(target).is_none() {
if let Some((defining, method)) = self.find_the_instance_method_in(&members, &name) {
return Ok((self.method_reference(&defining, &method), false));
}
if let Some((spelled, min, max)) = crate::classes::the_method_of(&members, &name).or_else(|| self.the_extension_method(&members, &name)) {
let reference = self.method_reference_of_a_class_type(&members, spelled, min, max);
return Ok((reference, false));
}
if crate::classes::the_base_object_has_the_method(&name) {
let spelled = crate::classes::the_name_of_a_method_of_the_base_object(&name);
let (min, max) = crate::classes::the_arity_of("object", &name).unwrap_or((0, 0));
let reference =
self.method_reference_of_the_base_object(&spelled, &name, min + 1, max + 1);
return Ok((reference, false));
}
}
if let Some((defining, method)) = self.find_the_instance_method_in(&class, "__get") {
let params = self.the_params(params, line)?;
let value = self.call_method_with(
&defining,
&method,
target,
&[Value::Text(written), params],
line,
)?;
return Ok((value, true));
}
if self.dialect.a_member_that_is_not_there_is_answered() {
return Ok((Value::Text(String::new()), false));
}
Err(self.no_property(target, &written, line))
}
fn write_property(
&mut self,
target: &Value,
name: &str,
value: Value,
line: u32,
) -> Result<(), RuntimeFailure> {
self.write_property_with(target, name, &[], value, line)
}
fn write_property_with(
&mut self,
target: &Value,
name: &str,
params: &[Value],
value: Value,
line: u32,
) -> Result<(), RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match target {
Value::Skipped => return Ok(()),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
let written = name.to_string();
let name = name.to_lowercase();
let Value::Object(object) = target else {
if self
.dialect
.the_write_of_a_property_of_a_value_that_is_not_an_object_is_dropped()
{
return Ok(());
}
if name == "__class" {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Property is read-only.".to_string(),
line,
},
Detail {
what: String::new(),
extra: written,
},
));
}
return Err(self.no_property(target, &written, line));
};
let class = object.borrow().class.clone();
if self.class_name_of(target).is_some() {
return self
.write_the_property_of_a_class_value(target, &class, &name, &written, value, line);
}
if name == "base" {
if !matches!(value, Value::Object(_)) {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_type(TypeName::Object, value.type_name()),
line,
},
Detail {
what: "ObjSetBase".to_string(),
extra: value.to_text(),
},
));
}
let base = value.clone();
return self.set_base_of(target, base, line).map_err(|error| {
RuntimeFailure::Detailed(
error,
Detail {
what: "ObjSetBase".to_string(),
extra: String::new(),
},
)
});
}
if let Some(class) = self.the_class_of_the_prototype(target) {
if self.the_prototype_has_the_member(&class, &name) {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Property is read-only.".to_string(),
line,
},
Detail {
what: String::new(),
extra: written.clone(),
},
));
}
}
if crate::classes::the_property_is_read_only(&class, &name) {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Property is read-only.".to_string(),
line,
},
Detail {
what: String::new(),
extra: written,
},
));
}
if let Some(result) =
crate::classes::set_property(&class, &name, target, value.clone(), self, line)
{
return result;
}
if self.the_write_of_an_accessor(target, &written, params, value.clone(), line)? {
return Ok(());
}
let current = object.borrow().value_of(&name);
if let Some(current) = current {
if self.is_a_descriptor(¤t) {
return self.the_write_of_the_descriptor(¤t, target, value, &written, line);
}
}
if !self.declares_property(&class, &name) {
if let Some((defining, method)) = self.find_method_in(&class, "__set") {
let params = self.the_params(params, line)?;
self.call_method_with(
&defining,
&method,
target,
&[Value::Text(written), params, value],
line,
)?;
return Ok(());
}
}
put(&mut object.borrow_mut().properties, &written, value);
Ok(())
}
fn write_the_property_of_a_class_value(
&mut self,
target: &Value,
class: &str,
name: &str,
written: &str,
value: Value,
line: u32,
) -> Result<(), RuntimeFailure> {
if self
.the_static_methods_of_a_class_value(target)
.contains(&name.to_string())
{
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Property is read-only.".to_string(),
line,
},
Detail {
what: String::new(),
extra: written.to_string(),
},
));
}
if name == "base" {
if !matches!(value, Value::Object(_)) {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_type(TypeName::Object, value.type_name()),
line,
},
Detail {
what: "ObjSetBase".to_string(),
extra: value.to_text(),
},
));
}
let base = value.clone();
return self.set_base_of(target, base, line).map_err(|error| {
RuntimeFailure::Detailed(
error,
Detail {
what: "ObjSetBase".to_string(),
extra: String::new(),
},
)
});
}
let Value::Object(object) = target else {
return Err(self.no_property(target, written, line));
};
if self.the_write_of_an_accessor(target, written, &[], value.clone(), line)? {
return Ok(());
}
if let Some(current) = object.borrow().value_of(name) {
if self.is_a_descriptor(¤t) {
return self.the_write_of_the_descriptor(¤t, target, value, written, line);
}
}
if !self.declares_property(class, name) {
if let Some((defining, method)) = self.find_method_in(class, "__set") {
let params = self.the_params(&[], line)?;
self.call_method_with(
&defining,
&method,
target,
&[Value::Text(written.to_string()), params, value],
line,
)?;
return Ok(());
}
}
put(&mut object.borrow_mut().properties, written, value);
Ok(())
}
fn the_params(&mut self, params: &[Value], line: u32) -> Result<Value, RuntimeFailure> {
match crate::classes::construct("array", params, self, line) {
Some(result) => result,
None => Ok(Value::List(params.to_vec())),
}
}
fn declares_property(&self, class: &str, name: &str) -> bool {
let name = name.to_lowercase();
self.class_chain(class).iter().any(|class| {
self.classes
.get(class)
.map(|definition| {
definition
.properties
.iter()
.any(|property| property.name.to_lowercase() == name)
})
.unwrap_or(false)
})
}
fn declares_an_instance_property(&self, class: &str, name: &str) -> bool {
let name = name.to_lowercase();
self.class_chain(class).iter().any(|class| {
self.classes
.get(class)
.map(|definition| {
definition
.properties
.iter()
.any(|property| !property.is_static && property.name.to_lowercase() == name)
})
.unwrap_or(false)
})
}
fn the_accessor_of(&self, target: &Value, name: &str) -> Option<AccessDef> {
let lower = name.to_lowercase();
let (class, is_static) = match self.class_name_of(target) {
Some(class) => (class, true),
None => {
let class = match self.the_class_of_the_prototype(target) {
Some(class) => class,
None => match target {
Value::Object(object) => object.borrow().class.clone(),
_ => return None,
},
};
(class, false)
}
};
for class in self.class_chain(&class) {
let Some(definition) = self.classes.get(&class) else {
continue;
};
let Some(access) = definition.accessors.get(&lower) else {
continue;
};
if access.is_static == is_static {
return Some(access.clone());
}
}
None
}
fn the_value_of_an_accessor(
&mut self,
target: &Value,
name: &str,
params: &[Value],
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
let Some(access) = self.the_accessor_of(target, name) else {
return Ok(None);
};
let Some(getter) = &access.getter else {
return Err(self.no_property(target, name, line));
};
let value =
self.call_the_body_of_an_accessor(target, &access, getter, line, params, None)?;
Ok(Some(value))
}
fn the_write_of_an_accessor(
&mut self,
target: &Value,
name: &str,
params: &[Value],
value: Value,
line: u32,
) -> Result<bool, RuntimeFailure> {
let Some(access) = self.the_accessor_of(target, name) else {
return Ok(false);
};
let Some(setter) = &access.setter else {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Property is read-only.".to_string(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
));
};
self.call_the_body_of_an_accessor(target, &access, setter, line, params, Some(&value))?;
Ok(true)
}
fn call_the_body_of_an_accessor(
&mut self,
target: &Value,
access: &AccessDef,
body: &AccessBody,
line: u32,
given: &[Value],
written: Option<&Value>,
) -> Result<Value, RuntimeFailure> {
let mut parameters = access.parameters.clone();
let mut values: Vec<Value> = given.to_vec();
if let Some(written) = written {
parameters.push(Parameter {
name: "value".to_string(),
default: None,
variadic: false,
by_ref: false,
optional: false,
});
values.push(written.clone());
}
let method = MethodDef {
name: access.name.clone(),
parameters,
body: body.body.clone(),
declarations: body.declarations.clone(),
is_static: access.is_static,
line: access.line,
body_line: body.line,
};
let class = match self.class_name_of(target) {
Some(class) => class,
None => match self.the_class_of_the_prototype(target) {
Some(class) => class,
None => match target {
Value::Object(object) => object.borrow().class.clone(),
_ => String::new(),
},
},
};
self.call_method_with(&class, &method, target, &values, line)
}
fn the_name_of_a_class(&self, class: &str) -> String {
let name = self
.classes
.get(class)
.map(|definition| definition.name.clone())
.unwrap_or_else(|| class.to_string());
name.rsplit('.').next().unwrap_or(&name).to_string()
}
fn the_class_that_the_v1_holds(&self, target: &Value, name: &str) -> Option<Value> {
let class = match self.class_name_of(target) {
Some(class) => class,
None => match target {
Value::Object(object) => object.borrow().class.clone(),
_ => return None,
},
};
let definition = self.classes.get(&class)?;
let lower = name.to_lowercase();
for nested in &definition.nested {
if self.the_name_of_a_class(nested).to_lowercase() == lower {
return self.class_value_of(nested);
}
}
None
}
fn the_class_that_a_class_holds(&self, target: &Value, name: &str) -> Option<Value> {
let class = self.class_name_of(target)?;
let definition = self.classes.get(&class)?;
let lower = name.to_lowercase();
for nested in &definition.nested {
if self.the_name_of_a_class(nested).to_lowercase() == lower {
return self.class_value_of(nested);
}
}
None
}
fn loop_argument(
&mut self,
arguments: &[Node],
index: usize,
line: u32,
) -> Result<Value, RuntimeFailure> {
let node = arguments.get(index).ok_or_else(|| {
RuntimeFailure::Error(RuntimeError {
message: format!("the loop needs an argument {}.", index + 1),
line,
})
})?;
self.evaluate(node)
}
fn directive(
&mut self,
name: &str,
argument: &str,
line: u32,
) -> Result<String, RuntimeFailure> {
match name {
"notrayicon" => Ok("there is no tray icon to hide".into()),
"hotstring" => Ok("the options of the hotstrings are read when the script is read".into()),
"hotif" => match the_condition_of_a_hotif(argument) {
Ok(condition) => {
self.hotif_condition = condition;
Ok("the condition of the hotkeys that follow is set".into())
}
Err(()) => Err(RuntimeFailure::Error(RuntimeError {
message: "The condition of #HotIf is not carried by this runtime: only the WinActive, WinExist, WinNotActive and WinNotExist forms with a literal title are.".to_string(),
line,
})),
},
"hotiftimeout" => Ok("the question of a window answers at once, so the timeout changes nothing".into()),
"suspendexempt" => match the_boolean_of_a_directive(argument) {
Some(exempt) => {
self.suspend_exempt = exempt;
Ok(if exempt {
"the hotkeys that follow are exempt from Suspend".into()
} else {
"the hotkeys that follow are not exempt from Suspend".into()
})
}
None => Err(RuntimeFailure::Error(RuntimeError {
message: "Parameter #1 invalid.".into(),
line,
})),
},
"noenv" => {
self.no_env = true;
Ok("the environment is not looked up".into())
}
"persistent" => Ok("the runner is one process".into()),
"singleinstance" => Ok("the runner is one process".into()),
"errorstdout" => Ok("the errors are in the report".into()),
"warn" => Ok("the warnings are in the report".into()),
"requires" => self.the_requires(argument, line),
other => match refusal_of_directive(other) {
Some(why) => Err(RuntimeFailure::Error(RuntimeError {
message: why.into(),
line,
})),
None => Err(RuntimeFailure::Error(RuntimeError {
message: format!("{other} is not a directive this runtime knows."),
line,
})),
},
}
}
fn the_requires(&self, argument: &str, line: u32) -> Result<String, RuntimeFailure> {
let argument = argument.trim();
if argument.is_empty() {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Parameter #1 required".into(),
line,
}));
}
if the_requirement::met(self.dialect, argument) {
return Ok(format!(
"this runtime is the {} dialect, and it meets {argument}",
self.dialect.name()
));
}
Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This script requires {argument}. This interpreter is {}.",
self.dialect.name()
),
line,
}))
}
fn apply_assign(
&self,
op: AssignOp,
name: &str,
current: Option<Value>,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.a_value_that_is_not_a_number_is_blank()
&& !matches!(op, AssignOp::Set | AssignOp::Concat | AssignOp::CoalesceSet)
{
let current = match current {
Some(value) => value,
None => Value::Text(String::new()),
};
return self.the_value_of_the_write_of_the_v1(op, ¤t, &value, line);
}
Ok(match op {
AssignOp::Set => value,
AssignOp::CoalesceSet => match current {
Some(Value::Unset) | None => value,
Some(current) => current,
},
AssignOp::Add => {
let written = self.number(&value, line)?;
let current = self.assigned(name, current, line)?;
let a = self.number(¤t, line)?;
match (¤t, &value) {
(Value::Int(a), Value::Int(b)) => Value::Int(a + b),
_ => Value::Float(a + written),
}
}
AssignOp::Subtract => {
let written = self.number(&value, line)?;
let current = self.assigned(name, current, line)?;
let a = self.number(¤t, line)?;
match (¤t, &value) {
(Value::Int(a), Value::Int(b)) => Value::Int(a - b),
_ => Value::Float(a - written),
}
}
AssignOp::Multiply => {
let written = self.number(&value, line)?;
let current = self.assigned(name, current, line)?;
let a = self.number(¤t, line)?;
match (¤t, &value) {
(Value::Int(a), Value::Int(b)) => Value::Int(a * b),
_ => Value::Float(a * written),
}
}
AssignOp::Divide => {
let written = self.number(&value, line)?;
let current = self.assigned(name, current, line)?;
let a = self.number(¤t, line)?;
if written == 0.0 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Value::Float(a / written)
}
AssignOp::IntegerDivide => {
let written = self.integer(&value, line)?;
let current = self.assigned(name, current, line)?;
let a = self.integer(¤t, line)?;
if written == 0 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Value::Int(a / written)
}
AssignOp::Concat => {
let current = match current {
Some(value) => value,
None => Value::Text(String::new()),
};
Value::Text(format!("{}{}", current.to_text(), value.to_text()))
}
AssignOp::BitwiseAnd => {
let written = self.integer(&value, line)?;
let current = self.assigned(name, current, line)?;
Value::Int(self.integer(¤t, line)? & written)
}
AssignOp::BitwiseOr => {
let written = self.integer(&value, line)?;
let current = self.assigned(name, current, line)?;
Value::Int(self.integer(¤t, line)? | written)
}
AssignOp::BitwiseXor => {
let written = self.integer(&value, line)?;
let current = self.assigned(name, current, line)?;
Value::Int(self.integer(¤t, line)? ^ written)
}
AssignOp::ShiftLeft => {
let written = self.shift(&value, line)?;
let current = self.assigned(name, current, line)?;
Value::Int(self.integer(¤t, line)? << written)
}
AssignOp::ShiftRight => {
let written = self.shift(&value, line)?;
let current = self.assigned(name, current, line)?;
Value::Int(self.integer(¤t, line)? >> written)
}
AssignOp::ShiftRightUnsigned => {
let written = self.shift(&value, line)?;
let current = self.assigned(name, current, line)?;
let left = self.integer(¤t, line)? as u64;
Value::Int((left >> written) as i64)
}
})
}
fn the_value_of_the_write_of_the_v1(
&self,
op: AssignOp,
current: &Value,
value: &Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
let a = self.the_number_of_a_value_of_the_v1(current);
let b = self.the_number_of_a_value_of_the_v1(value);
let one = a.to_number().unwrap_or(0.0);
let other = b.to_number().unwrap_or(0.0);
let whole = |one: &Value, other: &Value| match (one, other) {
(Value::Int(one), Value::Int(other)) => Some((*one, *other)),
_ => None,
};
Ok(match op {
AssignOp::CoalesceSet => b.clone(),
AssignOp::Add => match whole(&a, &b) {
Some((one, other)) => Value::Int(one.wrapping_add(other)),
None => Value::Float(one + other),
},
AssignOp::Subtract => match whole(&a, &b) {
Some((one, other)) => Value::Int(one.wrapping_sub(other)),
None => Value::Float(one - other),
},
AssignOp::Multiply => match whole(&a, &b) {
Some((one, other)) => Value::Int(one.wrapping_mul(other)),
None => Value::Float(one * other),
},
AssignOp::Divide => {
if other == 0.0 {
return Ok(Value::Text(String::new()));
}
match whole(&a, &b) {
Some((one, other)) => Value::Int(one.wrapping_div(other)),
None => Value::Float(one / other),
}
}
AssignOp::IntegerDivide => {
let other = self.the_whole_number_of_a_value_of_the_v1(&b);
if other == 0 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Value::Int(
self.the_whole_number_of_a_value_of_the_v1(&a)
.wrapping_div(other),
)
}
AssignOp::BitwiseAnd => Value::Int(
self.the_whole_number_of_a_value_of_the_v1(&a)
& self.the_whole_number_of_a_value_of_the_v1(&b),
),
AssignOp::BitwiseOr => Value::Int(
self.the_whole_number_of_a_value_of_the_v1(&a)
| self.the_whole_number_of_a_value_of_the_v1(&b),
),
AssignOp::BitwiseXor => Value::Int(
self.the_whole_number_of_a_value_of_the_v1(&a)
^ self.the_whole_number_of_a_value_of_the_v1(&b),
),
AssignOp::ShiftLeft => Value::Int(
self.the_whole_number_of_a_value_of_the_v1(&a)
.wrapping_shl(self.the_whole_number_of_a_value_of_the_v1(&b) as u32),
),
AssignOp::ShiftRight => Value::Int(
self.the_whole_number_of_a_value_of_the_v1(&a)
.wrapping_shr(self.the_whole_number_of_a_value_of_the_v1(&b) as u32),
),
AssignOp::ShiftRightUnsigned => Value::Int(
(self.the_whole_number_of_a_value_of_the_v1(&a) as u64
>> (self.the_whole_number_of_a_value_of_the_v1(&b) as u32 & 63))
as i64,
),
AssignOp::Set | AssignOp::Concat => Value::Text(String::new()),
})
}
fn the_number_of_a_value_of_the_v1(&self, value: &Value) -> Value {
match value {
Value::Int(number) => Value::Int(*number),
Value::Float(number) => Value::Float(*number),
other => match crate::v1::the_number_of_a_text(&other.to_text()) {
Some(number) => number,
None => Value::Int(0),
},
}
}
fn the_value_is_a_number_of_the_v1(&self, value: &Value) -> bool {
match value {
Value::Int(_) | Value::Float(_) => true,
other => crate::v1::the_number_of_a_text(&other.to_text()).is_some(),
}
}
fn the_whole_number_of_a_value_of_the_v1(&self, value: &Value) -> i64 {
match value {
Value::Int(number) => *number,
Value::Float(number) => *number as i64,
other => {
crate::v1::the_whole_number_at_the_start_of_a_text(&other.to_text()).unwrap_or(0)
}
}
}
fn the_reason_of_the_short_names_of_the_files(&self, name: &str) -> Option<&'static str> {
if !self.the_short_names_of_the_files_are_refused {
return None;
}
if name.eq_ignore_ascii_case("A_LoopFileShortName")
|| name.eq_ignore_ascii_case("A_LoopFileShortPath")
{
return Some(crate::variables::NO_SHORT_NAMES_OF_THE_FILES);
}
None
}
fn the_value_of_a_variable_of_the_runtime(&self, name: &str) -> Option<Value> {
let rest = crate::variables::spelled(name)?;
if rest == "thisfunc" {
let name = self
.frames
.last()
.map(|frame| frame.name.clone())
.unwrap_or_default();
return Some(Value::Text(name));
}
if rest == "linenumber" {
return Some(Value::Text(String::new()));
}
if !THE_LOOP_VARIABLES.contains(&rest.as_str()) {
return None;
}
if rest == "index" {
Some(Value::Int(0))
} else {
Some(Value::Text(String::new()))
}
}
fn the_index_is_saved(&self) -> Option<Value> {
self.variables.get(&the_key_of("A_Index")).cloned()
}
fn the_index_is_given_back(&mut self, saved: Option<Value>) {
match saved {
Some(value) => self.set_global("A_Index", value),
None => {
self.variables.remove(&the_key_of("A_Index"));
}
}
}
fn the_index_of_the_turn(&self) -> i64 {
self.variables
.get(&the_key_of("A_Index"))
.and_then(|value| value.to_number())
.unwrap_or(0.0) as i64
}
pub(crate) fn the_unassigned(&self, name: &str) -> String {
let key = the_key_of(name);
let local = self.declarations.last().is_some() && !self.lives_in_the_script(&key);
if local {
"This local variable has not been assigned a value.".to_string()
} else {
"This global variable has not been assigned a value.".to_string()
}
}
fn the_keys_of_an_index(
&mut self,
index: &Node,
also: &[Node],
) -> Result<Vec<Value>, RuntimeFailure> {
let mut keys = Vec::with_capacity(1 + also.len());
keys.push(self.evaluate(index)?);
for item in also {
keys.push(self.evaluate(item)?);
}
Ok(keys)
}
fn the_node_of_a_value(value: &Value, line: u32) -> Node {
match value {
Value::Int(number) => Node::Literal {
value: LiteralValue::Integer(*number),
line,
},
Value::Float(number) => Node::Literal {
value: LiteralValue::Float(*number),
line,
},
_ => Node::Literal {
value: LiteralValue::Text(value.to_text()),
line,
},
}
}
fn too_many_parameters_of_an_item(
&self,
class: &str,
set: bool,
line: u32,
) -> RuntimeFailure {
let accessor = if set { "__Item.Set" } else { "__Item.Get" };
RuntimeFailure::Detailed(
RuntimeError {
message: "Too many parameters passed to function.".into(),
line,
},
Detail {
what: String::new(),
extra: crate::classes::the_name_of(class, accessor),
},
)
}
fn index_a_value(
&mut self,
target: &Value,
keys: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match target {
Value::Skipped => return Ok(Value::Skipped),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
if let Value::Object(_) = target {
return self.read_item(target, keys, line);
}
let Some(key) = keys.first() else {
return Err(self.no_item(target, line));
};
let position = key.to_number().unwrap_or(0.0) as i64; let position = position.max(1) as usize;
match target {
Value::List(items) => items.get(position - 1).cloned().ok_or_else(|| {
RuntimeFailure::Error(RuntimeError {
message: "Invalid index.".into(),
line,
})
}),
_ => {
if self.dialect.a_member_that_is_not_there_is_answered() {
return Ok(Value::Text(String::new()));
}
Err(self.no_item(target, line))
}
}
}
fn the_unassigned_failure(&self, name: &str, line: u32) -> RuntimeFailure {
RuntimeFailure::Detailed(
RuntimeError {
message: self.the_unassigned(name),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
)
}
fn the_missing_parameter(&self, name: &str, line: u32) -> RuntimeFailure {
RuntimeFailure::Detailed(
RuntimeError {
message: "Missing a required parameter.".into(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
)
}
pub(crate) fn assigned(
&self,
name: &str,
value: Option<Value>,
line: u32,
) -> Result<Value, RuntimeFailure> {
value.ok_or_else(|| self.the_unassigned_failure(name, line))
}
pub(crate) fn number(&self, value: &Value, line: u32) -> Result<f64, RuntimeFailure> {
value.to_number_strict().map_err(|_| {
RuntimeFailure::Detailed(
RuntimeError {
message: expected_number(value),
line,
},
Detail {
what: String::new(),
extra: the_extra_of_the_value(value),
},
)
})
}
fn the_number_value(&self, value: &Value, line: u32) -> Result<Value, RuntimeFailure> {
match value {
Value::Int(number) => Ok(Value::Int(*number)),
Value::Float(number) => Ok(Value::Float(*number)),
Value::Text(text) => {
let trimmed = text.trim();
if let Some(number) = the_hexadecimal_of_a_text(trimmed) {
return Ok(Value::Int(number));
}
if let Ok(whole) = trimmed.parse::<i64>() {
return Ok(Value::Int(whole));
}
self.number(value, line).map(Value::Float)
}
_ => self.number(value, line).map(Value::Float),
}
}
pub(crate) fn integer(&self, value: &Value, line: u32) -> Result<i64, RuntimeFailure> {
self.the_whole_number(value, line, TypeName::Integer)
}
fn the_whole_number(
&self,
value: &Value,
line: u32,
wants: TypeName,
) -> Result<i64, RuntimeFailure> {
if let Value::Int(number) = value {
return Ok(*number);
}
let number = self.number(value, line)?;
if fract(number) != 0.0 {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_the_kind(wants, &self.the_type_of(value)),
line,
},
Detail {
what: String::new(),
extra: the_extra_of_the_value(value),
},
));
}
Ok(number as i64)
}
pub(crate) fn the_place_of_an_item(&self, value: &Value) -> Option<i64> {
value.to_number().map(|number| trunc(number) as i64)
}
fn the_text_of_the_concat(&self, value: &Value, line: u32) -> Result<String, RuntimeFailure> {
match value {
Value::Text(text) => Ok(text.clone()),
Value::Int(_) | Value::Float(_) => Ok(self.the_text_of(value)),
Value::Object(_) if self.dialect.an_object_has_no_text() => Ok(String::new()),
other => Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_the_kind(TypeName::String, &self.the_type_of(other)),
line,
},
Detail {
what: String::new(),
extra: String::new(),
},
)),
}
}
fn the_number_of_the_v1(&self, node: &Node, value: &Value) -> Option<Value> {
match value {
Value::Int(number) => Some(Value::Int(*number)),
Value::Float(number) => Some(Value::Float(*number)),
Value::Text(text) => {
if self.the_node_is_a_quoted_text(node) {
return None;
}
crate::v1::the_number_of_a_text(text)
}
_ => None,
}
}
fn the_node_is_a_quoted_text(&self, node: &Node) -> bool {
matches!(
node,
Node::Literal {
value: LiteralValue::Text(_),
..
}
)
}
fn the_comparison_of_the_v1(
&self,
left_node: &Node,
right_node: &Node,
left: &Value,
right: &Value,
op: &BinaryOp,
) -> bool {
let numbers = match (
self.the_number_of_the_v1(left_node, left),
self.the_number_of_the_v1(right_node, right),
) {
(Some(left), Some(right)) => Some((
left.to_number().unwrap_or(0.0),
right.to_number().unwrap_or(0.0),
)),
_ => None,
};
self.the_order_of_the_v1(numbers, &left.to_text(), &right.to_text(), op)
}
fn the_order_of_the_v1(
&self,
numbers: Option<(f64, f64)>,
left: &str,
right: &str,
op: &BinaryOp,
) -> bool {
match numbers {
Some((left, right)) => match op {
BinaryOp::Less => left < right,
BinaryOp::Greater => left > right,
BinaryOp::LessEqual => left <= right,
BinaryOp::GreaterEqual => left >= right,
_ => false,
},
None => {
let order = the_order_of_the_texts(left, right, self.case_sense.the_method());
match op {
BinaryOp::Less => order == core::cmp::Ordering::Less,
BinaryOp::Greater => order == core::cmp::Ordering::Greater,
BinaryOp::LessEqual => order != core::cmp::Ordering::Greater,
BinaryOp::GreaterEqual => order != core::cmp::Ordering::Less,
_ => false,
}
}
}
}
fn the_value_of_an_unset_variable(&self, name: &str) -> Value {
if name == "0" {
return Value::Text(String::from("0"));
}
Value::Text(String::new())
}
fn the_comparison_of_a_legacy_if(
&mut self,
left: &Node,
op: BinaryOp,
text: &str,
line: u32,
) -> Result<Value, RuntimeFailure> {
let left_value = self.evaluate(left)?;
let right_text = self.the_substitution_of_the_v1(text, line)?;
let right_number = crate::v1::the_number_of_a_text(&right_text);
let left_number = self.the_number_of_the_v1(left, &left_value);
let answer = match op {
BinaryOp::Equal | BinaryOp::NotEqual => {
let method = self.case_sense.the_method();
let same = match (left_number, right_number) {
(Some(one), Some(other)) => the_same_number(&one, &other),
_ => the_same_text(&left_value.to_text(), &right_text, method),
};
match op {
BinaryOp::Equal => same,
_ => !same,
}
}
_ => {
let numbers = match (left_number, right_number) {
(Some(one), Some(other)) => Some((
one.to_number().unwrap_or(0.0),
other.to_number().unwrap_or(0.0),
)),
_ => None,
};
self.the_order_of_the_v1(numbers, &left_value.to_text(), &right_text, &op)
}
};
Ok(Value::Int(answer as i64))
}
fn the_match_of_a_legacy_if(
&mut self,
left: &Node,
form: LegacyForm,
texts: &[String],
negated: bool,
line: u32,
) -> Result<Value, RuntimeFailure> {
let left_value = self.evaluate(left)?;
let text_of_the_value = left_value.to_text();
let mut items = Vec::new();
for text in texts {
items.push(self.the_substitution_of_the_v1(text, line)?);
}
let holds = match form {
LegacyForm::Between => {
let low = items.first().map(String::as_str).unwrap_or_default();
let high = items.get(1).map(String::as_str).unwrap_or_default();
let numbers = match (
self.the_number_of_the_v1(left, &left_value),
crate::v1::the_number_of_a_text(low),
crate::v1::the_number_of_a_text(high),
) {
(Some(value), Some(low), Some(high)) => Some((
value.to_number().unwrap_or(0.0),
low.to_number().unwrap_or(0.0),
high.to_number().unwrap_or(0.0),
)),
_ => None,
};
match numbers {
Some((value, low, high)) => value >= low && value <= high,
None => {
let method = self.case_sense.the_method();
let at_the_low = the_order_of_the_texts(&text_of_the_value, low, method);
let at_the_high = the_order_of_the_texts(&text_of_the_value, high, method);
at_the_low != core::cmp::Ordering::Less
&& at_the_high != core::cmp::Ordering::Greater
}
}
}
LegacyForm::In => {
let method = self.case_sense.the_method();
items
.iter()
.any(|item| the_same_text(&text_of_the_value, item, method))
}
LegacyForm::Contains => {
let method = self.case_sense.the_method();
items
.iter()
.any(|item| the_text_contains(&text_of_the_value, item, method))
}
};
Ok(Value::Int(if negated { !holds } else { holds } as i64))
}
fn shift(&self, value: &Value, line: u32) -> Result<u32, RuntimeFailure> {
let count = self.integer(value, line)?;
if !(0..64).contains(&count) {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Invalid shift count.".into(),
line,
}));
}
Ok(count as u32)
}
fn increment(
&mut self,
op: UnaryOp,
operand: &Node,
line: u32,
) -> Result<Value, RuntimeFailure> {
let step = match op {
UnaryOp::PreIncrement | UnaryOp::PostIncrement => 1,
_ => -1,
};
match operand {
Node::Var { name, .. } => {
if self
.dialect
.the_increment_of_a_built_in_variable_changes_nothing(name)
{
return Ok(Value::Text(String::new()));
}
let current = match self.lookup(name) {
Some(current) => current,
None if self.dialect.unset_is_blank() => {
self.the_value_of_an_unset_variable(name)
}
None => return Err(self.the_unassigned_failure(name, line)),
};
let stored = self.the_number_after(¤t, step, line)?;
self.assign(name, stored.clone());
Ok(match op {
UnaryOp::PreIncrement | UnaryOp::PreDecrement => stored,
_ => current,
})
}
Node::Property {
target,
name,
line: property_line,
} => {
let target_value = self.evaluate(target)?;
let name = self.the_name_of_the_member(name, *property_line)?;
let current = self.read_property(&target_value, &name, *property_line)?;
let stored = self.the_number_after(¤t, step, *property_line)?;
self.write_property(&target_value, &name, stored.clone(), *property_line)?;
Ok(match op {
UnaryOp::PreIncrement | UnaryOp::PreDecrement => stored,
_ => current,
})
}
Node::Index {
target,
index,
also,
line: item_line,
} => {
let target_value = self.evaluate(target)?;
let keys = self.the_keys_of_an_index(index, also)?;
let current = self.index_a_value(&target_value, &keys, *item_line)?;
let stored = self.the_number_after(¤t, step, *item_line)?;
self.set_item(
&target_value,
&keys,
AssignOp::Set,
stored.clone(),
*item_line,
)?; Ok(match op {
UnaryOp::PreIncrement | UnaryOp::PreDecrement => stored,
_ => current,
})
}
Node::Literal { .. } if self.dialect.the_increment_of_a_literal_is_blank() => {
Ok(Value::Text(String::new()))
}
Node::DynamicName {
pieces,
line: name_line,
} => {
let name = self.the_name_of_the_pieces(pieces, *name_line)?;
let current = match self.the_variable_of_the_name(&name, *name_line)? {
Some(current) => current,
None if self.dialect.unset_is_blank() => {
self.the_value_of_an_unset_variable(&name)
}
None => return Err(self.the_unassigned_failure(&name, line)),
};
let stored = self.the_number_after(¤t, step, line)?;
self.write_a_dynamic_name(&name, AssignOp::Set, stored.clone(), line)?;
Ok(match op {
UnaryOp::PreIncrement | UnaryOp::PreDecrement => stored,
_ => current,
})
}
_ => Err(RuntimeFailure::Error(RuntimeError {
message: "the operator needs a variable to work on".into(),
line,
})),
}
}
fn the_number_after(
&mut self,
current: &Value,
step: i64,
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.a_value_that_is_not_a_number_is_blank() {
return Ok(match self.the_number_of_a_value_of_the_v1(current) {
Value::Int(number) => Value::Int(number.wrapping_add(step)),
Value::Float(number) => Value::Float(number + step as f64),
other => other,
});
}
Ok(match current {
Value::Int(number) => Value::Int(number.wrapping_add(step)),
other => Value::Float(self.number(other, line)? + step as f64),
})
}
fn call(&mut self, name: &str, arguments: &[Node], line: u32) -> Result<Value, RuntimeFailure> {
if let Some(function) = self.functions.get(name).cloned() {
return self.call_function(&function, arguments, line, Route::Written);
}
if self.classes.contains_key(&name.to_lowercase())
|| self.dialect.carries_the_class_of_the_runtime(name)
|| self.dialect.carries_the_class_of_the_extension(name)
{
return self.construct(name, arguments, line);
}
if let Some((class, method)) = self.method_reference_in_a_variable(name) {
let values = self.evaluate_all(arguments)?;
return self.call_a_method_reference(&class, &method, &values, line);
}
if let Some(function) = self.function_in_a_variable(name) {
return self.call_function(&function, arguments, line, Route::ThroughValue);
}
if self.dialect.the_call_of_a_built_in_wins_over_the_variable()
&& self.builtin(name).is_some()
{
return self.call_a_builtin_by_name(name, arguments, line);
}
let from_the_script = self.lookup_variable(name);
let value = match from_the_script {
Some(value) => Some(Ok(value)),
None => self.the_built_in_variable(name),
};
if let Some(value) = value {
let value = value.map_err(|error| {
RuntimeFailure::Error(RuntimeError {
message: error.message,
line,
})
})?;
return self.call_the_value_of(value, arguments, line);
}
self.call_a_builtin_by_name(name, arguments, line)
}
fn call_the_value_of(
&mut self,
value: Value,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match &value {
Value::Skipped => return Ok(Value::Skipped),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
if let Value::Object(object) = &value {
if let Some(class) = self.class_name_of(&value) {
return self.construct(&class, arguments, line);
}
let class = object.borrow().class.clone();
if let Some((defining, method)) = self.find_method_in(&class, "call") {
return self.call_method(&defining, &method, &value, arguments, line);
}
if class != "func" {
if let Ok(function) = self.read_property(&value, "Call", line) {
if matches!(&function, Value::Object(the) if the.borrow().class == "func") {
let values = self.evaluate_all(arguments)?;
return self.call_the_function(&function, &value, &values, line);
}
}
}
let values = self.evaluate_all(arguments)?;
if let Some(result) =
crate::classes::call_the_value(&class, &value, &values, self, line)
{
return result;
}
return Err(self.no_method(&value, "Call", line));
}
Err(self.no_method(&value, "Call", line))
}
fn call_a_builtin_by_name(
&mut self,
name: &str,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
let Some(builtin) =
self.the_builtin_of_the_kind(name, crate::builtins::BuiltinKind::Function)
else {
return Err(self.the_unassigned_failure(name, line));
};
if arguments
.iter()
.any(|argument| matches!(argument, Node::Spread { .. }))
{
let values = self.evaluate_all(arguments)?;
self.the_arity_of_a_builtin(builtin, values.len(), line, Route::ThroughValue)?;
return self.call_builtin(name, &values, line, Route::ThroughValue);
}
self.the_arity_of_a_builtin(builtin, arguments.len(), line, Route::Written)?;
if builtin.name.eq_ignore_ascii_case("IsSet")
&& self.dialect.the_chain_may_be_skipped()
{
if let Some(argument) = arguments.first() {
if !matches!(argument, Node::Var { .. }) {
let answer = self.the_value_of_the_expression_is_set(argument)?;
return Ok(Value::Int(answer as i64));
}
}
}
let mut values = Vec::with_capacity(arguments.len());
let wants_the_name = self
.dialect
.the_place_of_the_argument_that_wants_the_name(builtin.name);
let wants_the_variable = self
.dialect
.the_place_of_the_argument_that_wants_the_variable(builtin.name);
for (index, argument) in arguments.iter().enumerate() {
if wants_the_variable == Some(index) {
if let Node::Var { name, .. } = argument {
values.push(Value::Reference(Reference {
name: name.clone(),
scope: self.the_scope_of(name),
alias: true,
}));
continue;
}
}
if wants_the_name == Some(index) {
if let Node::Var { name, .. } = argument {
values.push(Value::Text(name.clone()));
continue;
}
}
if matches!(argument, Node::Empty { .. }) {
values.push(Value::Unset);
continue;
}
values.push(self.evaluate(argument)?);
}
self.call_builtin(name, &values, line, Route::Written)
}
fn the_arity_of_a_builtin(
&self,
builtin: &crate::builtins::Builtin,
count: usize,
line: u32,
route: Route,
) -> Result<(), RuntimeFailure> {
if count < builtin.min as usize {
return Err(self.the_arity_failure(
"Too few parameters passed to function.",
builtin.name,
route,
line,
));
}
if builtin.max < 255 && count > builtin.max as usize {
return Err(self.the_arity_failure(
"Too many parameters passed to function.",
builtin.name,
route,
line,
));
}
Ok(())
}
fn call_function(
&mut self,
function: &Function,
arguments: &[Node],
line: u32,
route: Route,
) -> Result<Value, RuntimeFailure> {
if arguments
.iter()
.any(|argument| matches!(argument, Node::Spread { .. }))
{
let (values, missing) = self.evaluate_the_arguments(arguments)?;
self.the_arity_of_a_call(function, values.len(), line, Route::ThroughValue)?;
return self.call_function_with(function, &values, line, Route::ThroughValue, &missing);
}
self.the_arity_of_a_call(function, arguments.len(), line, route)?;
let values = self.evaluate_all(arguments)?;
let missing: Vec<bool> = arguments
.iter()
.map(|argument| matches!(argument, Node::Empty { .. }))
.collect();
self.call_function_with(function, &values, line, route, &missing)
}
fn the_arity_of_a_call(
&self,
function: &Function,
count: usize,
line: u32,
route: Route,
) -> Result<(), RuntimeFailure> {
let needed = function
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count();
if count < needed {
if matches!(route, Route::Written) {
return Err(self.the_arity_failure(
"Too few parameters passed to function.",
&function.name,
route,
line,
));
}
let missing = function
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.nth(count)
.map(|parameter| parameter.name.clone())
.unwrap_or_default();
return Err(self.the_missing_parameter(&missing, line));
}
let variadic = function
.parameters
.iter()
.any(|parameter| parameter.variadic);
if !variadic && count > function.parameters.len() {
return Err(self.the_arity_failure(
"Too many parameters passed to function.",
&function.name,
route,
line,
));
}
Ok(())
}
fn call_function_with(
&mut self,
function: &Function,
values: &[Value],
line: u32,
route: Route,
missing: &[bool],
) -> Result<Value, RuntimeFailure> {
self.the_arity_of_a_call(function, values.len(), line, route)?;
let unset: Vec<bool> = values
.iter()
.map(|value| matches!(value, Value::Unset | Value::Skipped))
.collect();
let the_parameter_is_missing = |index: usize| {
missing.get(index).copied().unwrap_or(false)
|| unset.get(index).copied().unwrap_or(false)
};
for (index, parameter) in function.parameters.iter().enumerate() {
if the_parameter_is_missing(index) && parameter.is_required() {
return Err(self.the_missing_parameter(¶meter.name, line));
}
}
let mut scope: BTreeMap<String, Value> = BTreeMap::new();
for (index, parameter) in function.parameters.iter().enumerate() {
let given = values.get(index);
let is_missing = the_parameter_is_missing(index);
if parameter.optional && (is_missing || given.is_none()) {
continue;
}
let value = match given {
Some(value) if !is_missing => value.clone(),
_ => match ¶meter.default {
Some(default) => self.evaluate(default)?,
None => Value::Text(String::new()),
},
};
if parameter.by_ref && given.is_some() && !is_missing {
let Value::Reference(reference) = value else {
return Err(RuntimeFailure::Error(RuntimeError {
message: wants_a_reference(
index + 1,
&function.name,
"a variable reference",
&value,
),
line,
}));
};
let mut alias = reference;
alias.alias = true;
scope.insert(the_key_of(¶meter.name), Value::Reference(alias));
continue;
}
scope.insert(the_key_of(¶meter.name), value);
}
if let Some(index) = function
.parameters
.iter()
.position(|parameter| parameter.variadic)
{
let rest: Vec<Value> = values.iter().skip(index).cloned().collect();
let array = match crate::classes::construct("array", &rest, self, line) {
Some(result) => result?,
None => Value::List(rest),
};
scope.insert(the_key_of(&function.parameters[index].name), array);
}
self.enter_call(line)?;
for closed in &function.closure {
self.scopes.push(closed.clone());
}
self.scopes.push(Rc::new(RefCell::new(scope)));
self.collect_the_nested_functions(&function.body);
self.declarations.push(function.declarations.clone());
self.frames.push(Frame {
name: function.name.clone(),
line,
});
self.label_scopes.push(the_labels_of(&function.body));
let outcome = self.run_block(&function.body);
self.label_scopes.pop();
self.frames.pop();
self.declarations.pop();
self.scopes.pop();
for _ in &function.closure {
self.scopes.pop();
}
self.forget_the_capacities_beyond_the_stack();
self.leave_call();
match outcome {
Ok(()) => Ok(Value::Text(String::new())),
Err(RuntimeFailure::Flow(Flow::Return(value))) => {
Ok(value.unwrap_or(Value::Text(String::new())))
}
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => {
if computed {
Err(self.the_failure_of_a_computed_jump(&name, &function.body, line))
} else {
Err(RuntimeFailure::Fatal(self.the_label_is_not_there(
&name,
&function.body,
line,
)))
}
}
Err(other) => Err(other),
}
}
fn the_scope_around_has(&self, name: &str) -> bool {
let name = the_key_of(name);
self.scopes
.iter()
.any(|scope| scope.borrow().contains_key(&name))
}
fn make_a_closure(&mut self, function: Function) -> String {
self.closures += 1;
let name = format!("\u{1}closure {}", self.closures);
self.functions.insert(name.to_lowercase(), function);
name
}
fn assign_in_the_scope(&mut self, name: &str, value: Value) {
let name = the_key_of(name);
match self.scopes.last() {
Some(scope) => {
scope.borrow_mut().insert(name, value);
}
None => {
self.variables.insert(name, value);
}
}
}
fn write_a_variable(
&mut self,
name: &str,
op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
if self
.dialect
.the_write_of_a_built_in_variable_goes_nowhere(name, op)
{
return Ok(value);
}
if let Some(spelled) = crate::variables::spelled(name) {
if let Some(Ok(current)) = crate::settings::value_of(&spelled) {
let stored = self.apply_assign(op, name, Some(current), value, line)?;
let written = crate::settings::write_of(&spelled, &stored).ok_or_else(|| {
RuntimeFailure::Error(RuntimeError {
message: "the runtime keeps no such setting.".into(),
line,
})
})?;
return written
.map_err(|message| RuntimeFailure::Error(RuntimeError { message, line }));
}
}
match self.the_write_of_the_built_in_variable(name, op, &value, line) {
Some(written) => {
let stored = written.map_err(|mut error| {
if error.line == 0 {
error.line = line;
}
RuntimeFailure::Error(error)
})?;
Ok(stored)
}
None => {
let current = match self.lookup(name) {
Some(value) => Some(value),
None => match self.the_built_in_variable(name) {
Some(Ok(value)) => Some(value),
_ => self.the_value_of_a_variable_of_the_runtime(name),
},
};
self.the_class_is_not_written(name, &value, line)?;
let stored = self.apply_assign(op, name, current, value, line)?;
let stored = match crate::variables::the_kind_of_the_write(name) {
Some(kind) => crate::variables::the_written_value(kind, &stored, line)
.map_err(RuntimeFailure::Error)?,
None => stored,
};
self.assign(name, stored.clone());
Ok(stored)
}
}
}
fn write_a_property(
&mut self,
target: &Node,
name: &str,
op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
let target_value = self.evaluate(target)?;
let current = match op {
AssignOp::Set => self.read_property(&target_value, name, line).ok(),
_ => Some(self.read_property(&target_value, name, line)?),
};
if self
.dialect
.the_compound_write_of_a_thing_that_is_not_a_number_is_dropped()
&& !matches!(op, AssignOp::Set | AssignOp::Concat)
{
if let Some(current) = ¤t {
if !self.the_value_is_a_number_of_the_v1(current) {
return Ok(current.clone());
}
}
}
let stored = self.apply_assign(op, name, current, value, line)?;
self.write_property(&target_value, name, stored.clone(), line)?;
Ok(stored)
}
fn enter_call(&mut self, line: u32) -> Result<(), RuntimeFailure> {
if self.depth >= Self::MAX_DEPTH || self.stack_used() > self.stack_budget {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Function recursion limit exceeded.".into(),
line,
}));
}
self.depth += 1;
Ok(())
}
fn leave_call(&mut self) {
self.depth = self.depth.saturating_sub(1);
}
fn stack_used(&self) -> usize {
self.stack_base.abs_diff(Self::stack_here())
}
fn stack_here() -> usize {
let marker = 0u8;
core::hint::black_box(&marker) as *const u8 as usize
}
pub(crate) fn the_names_of_the_parameters_of_a_function(&self, value: &Value) -> Vec<String> {
let Value::Object(object) = value else {
return Vec::new();
};
let name = {
let borrowed = object.borrow();
match borrowed.value_of(CLOSURE).map(|value| value.to_text()) {
Some(kept) => kept,
None => borrowed
.value_of("name")
.map(|value| value.to_text())
.unwrap_or_default(),
}
};
let function = self
.function_in_a_variable(&name)
.or_else(|| self.functions.get(&name.to_lowercase()).cloned());
match function {
Some(function) => function
.parameters
.iter()
.map(|parameter| parameter.name.clone())
.collect(),
None => Vec::new(),
}
}
pub(crate) fn the_count_of_the_parameters_of_a_function(&self, value: &Value) -> usize {
let Value::Object(object) = value else {
return 0;
};
if let Some(count) = object
.borrow()
.value_of("maxparams")
.and_then(|value| value.to_text().trim().parse::<usize>().ok())
{
return count;
}
let name = {
let borrowed = object.borrow();
match borrowed.value_of(CLOSURE).map(|value| value.to_text()) {
Some(kept) => kept,
None => borrowed
.value_of("name")
.map(|value| value.to_text())
.unwrap_or_default(),
}
};
if let Some(function) = self.function_in_a_variable(&name) {
return function.parameters.len();
}
if let Some(function) = self.functions.get(&name.to_lowercase()).cloned() {
return function.parameters.len();
}
if let Some(Value::List(flags)) = object.borrow().value_of(PARAMETERS) {
return flags.len();
}
0
}
pub(crate) fn call_named(
&mut self,
name: &str,
values: &[Value],
line: u32,
route: Route,
) -> Result<Value, RuntimeFailure> {
if let Some(function) = self.function_in_a_variable(name) {
return self.call_function_with(&function, values, line, route, &[]);
}
if let Some(function) = self.functions.get(&name.to_lowercase()).cloned() {
return self.call_function_with(&function, values, line, route, &[]);
}
self.call_builtin(name, values, line, route)
}
fn function_in_a_variable(&self, name: &str) -> Option<Function> {
let value = self.lookup_variable(name)?;
let Value::Object(object) = &value else {
return None;
};
let object = object.borrow();
if object.class != "func" {
return None;
}
if let Some(closure) = object.value_of(CLOSURE) {
return self
.functions
.get(&closure.to_text().to_lowercase())
.cloned();
}
let function_name = object.value_of("name")?.to_text().to_lowercase();
self.functions.get(&function_name).cloned()
}
fn method_reference_in_a_variable(&self, name: &str) -> Option<(String, String)> {
let value = self.lookup_variable(name)?;
let Value::Object(object) = &value else {
return None;
};
let object = object.borrow();
if object.class != "func" {
return None;
}
let class = object.value_of(METHOD_CLASS)?.to_text();
let method = object.value_of(METHOD_NAME)?.to_text();
Some((class, method))
}
pub(crate) fn the_arity_failure(
&self,
message: &str,
name: &str,
route: Route,
line: u32,
) -> RuntimeFailure {
match route {
Route::Written => RuntimeFailure::Error(RuntimeError {
message: format!("{message}\n Specifically: {name}"),
line,
}),
Route::ThroughValue => RuntimeFailure::Detailed(
RuntimeError {
message: message.to_string(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
),
Route::ThroughTheCall => RuntimeFailure::Detailed(
RuntimeError {
message: message.to_string(),
line,
},
Detail {
what: "Func.Prototype.Call".to_string(),
extra: name.to_string(),
},
),
}
}
pub(crate) fn the_legacy_command(
&mut self,
name: &str,
parameters: &[crate::ast::LegacyParameter],
line: u32,
) -> Result<Value, RuntimeFailure> {
let Some(builtin) =
self.the_builtin_of_the_kind(name, crate::builtins::BuiltinKind::Command)
else {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This line does not contain a recognized action.\n Specifically: {name}"
),
line,
}));
};
let values = self.the_parameters_of_a_legacy_command(builtin, parameters, line)?;
self.call_the_row(builtin, &values, line, Route::Written)
}
pub(crate) fn the_parameters_of_a_legacy_command(
&mut self,
builtin: &'static crate::builtins::Builtin,
parameters: &[crate::ast::LegacyParameter],
line: u32,
) -> Result<Vec<Value>, RuntimeFailure> {
let mut values = Vec::with_capacity(parameters.len());
for (index, parameter) in parameters.iter().enumerate() {
values.push(self.the_parameter_of_a_legacy_command(builtin, index, parameter, line)?);
}
Ok(values)
}
fn the_condition_of_a_legacy_if(
&mut self,
name: &str,
parameters: &[String],
line: u32,
) -> Result<bool, RuntimeFailure> {
let Some(builtin) = self.builtin(name) else {
return Ok(false);
};
let parameters: Vec<crate::ast::LegacyParameter> = parameters
.iter()
.map(|text| crate::ast::LegacyParameter::Text(text.clone()))
.collect();
let values = self.the_parameters_of_a_legacy_command(builtin, ¶meters, line)?;
let answer = self.call_the_row(builtin, &values, line, Route::Written)?;
Ok(answer.truthy())
}
fn the_parameter_of_a_legacy_command(
&mut self,
builtin: &'static crate::builtins::Builtin,
index: usize,
parameter: &crate::ast::LegacyParameter,
line: u32,
) -> Result<Value, RuntimeFailure> {
match builtin.parameters.get(index) {
Some(crate::builtins::Parameter::Output) => {
let name = the_text_of_the_parameter(parameter);
let scope = self.the_scope_of(&name);
Ok(Value::Reference(Reference {
name,
scope,
alias: true,
}))
}
Some(crate::builtins::Parameter::Variable) => {
let name = the_text_of_the_parameter(parameter);
match self.lookup(&name) {
Some(value) => Ok(value),
None if self.dialect.unset_is_blank() => Ok(Value::Text(String::new())),
None => Err(self.the_unassigned_failure(&name, line)),
}
}
_ => match parameter {
crate::ast::LegacyParameter::Expression(node) => self.evaluate(node),
crate::ast::LegacyParameter::Text(text) => {
Ok(Value::Text(self.the_substitution_of_the_v1(text, line)?))
}
},
}
}
fn the_count_of_the_loop(&mut self, node: &Node, line: u32) -> Result<i64, RuntimeFailure> {
if self.dialect.the_count_of_the_loop_is_a_number() {
if let Node::Literal {
value: crate::ast::LiteralValue::Text(text),
..
} = node
{
let text = self.the_substitution_of_the_v1(text, line)?;
return Ok(crate::v1::the_count_of_the_loop(&text));
}
}
Ok(self.evaluate(node)?.to_number().unwrap_or(0.0) as i64)
}
fn the_pattern_of_the_files_of_the_v1(
&mut self,
node: &Node,
arguments: &[Node],
line: u32,
) -> Result<Option<String>, RuntimeFailure> {
let text = match node {
Node::Literal {
value: crate::ast::LiteralValue::Text(text),
..
} => text,
_ => return Ok(None),
};
let text = self
.the_substitution_of_the_v1(text, line)?
.trim()
.to_string();
if arguments.len() == 1 && crate::v1::the_text_is_the_count_of_a_loop(&text) {
return Ok(None);
}
Ok(Some(text))
}
fn the_mode_of_the_loop_of_the_files_of_the_v1(
&mut self,
arguments: &[Node],
line: u32,
) -> Result<u8, RuntimeFailure> {
let Some(node) = arguments.get(1) else {
return Ok(crate::v1::THE_FILES);
};
let text = self.the_text_of_the_parameter_of_the_loop(node, line)?;
match crate::v1::the_mode_of_the_loop_of_the_files(&text) {
Some(mode) => Ok(mode),
None => Err(RuntimeFailure::Error(RuntimeError {
message: format!("Parameter #2 invalid.\n Specifically: {}", text.trim()),
line,
})),
}
}
fn the_flag_of_the_recursion_of_the_v1(
&mut self,
arguments: &[Node],
line: u32,
) -> Result<bool, RuntimeFailure> {
let Some(node) = arguments.get(2) else {
return Ok(false);
};
let text = self.the_text_of_the_parameter_of_the_loop(node, line)?;
Ok(crate::v1::the_flag_asks_for_the_recursion(&text))
}
fn the_text_of_the_parameter_of_the_loop(
&mut self,
node: &Node,
line: u32,
) -> Result<String, RuntimeFailure> {
match node {
Node::Literal {
value: crate::ast::LiteralValue::Text(text),
..
} => Ok(self.the_substitution_of_the_v1(text, line)?),
_ => Ok(self.evaluate(node)?.to_text()),
}
}
fn the_loop_of_the_files_of_the_v1(
&mut self,
pattern: &str,
arguments: &[Node],
body: &[Node],
until: &Option<Box<Node>>,
line: u32,
) -> Result<(), RuntimeFailure> {
let mode = self.the_mode_of_the_loop_of_the_files_of_the_v1(arguments, line)?;
let recurse = self.the_flag_of_the_recursion_of_the_v1(arguments, line)?;
let mut wanted = String::new();
match mode {
crate::v1::THE_FOLDERS => wanted.push('D'),
crate::v1::THE_FILES_AND_THE_FOLDERS => wanted.push('A'),
_ => {}
}
if recurse && mode == crate::v1::THE_FILES {
wanted.push('R');
}
self.the_walk_of_the_files_of_the_v1(pattern, &wanted, body, until, line)
}
fn the_loop_of_the_files_of_the_v1_with_the_kind(
&mut self,
arguments: &[Node],
body: &[Node],
until: &Option<Box<Node>>,
line: u32,
) -> Result<(), RuntimeFailure> {
let pattern = match arguments.get(1) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, line)?,
None => String::new(),
};
let mode = match arguments.get(2) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, line)?,
None => String::new(),
};
if the_letter_that_the_mode_does_not_carry(&mode).is_some() {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!("Parameter #3 invalid.\n Specifically: {}", mode.trim()),
line,
}));
}
self.the_walk_of_the_files_of_the_v1(&pattern, &mode, body, until, line)
}
fn the_walk_of_the_files_of_the_v1(
&mut self,
pattern: &str,
mode: &str,
body: &[Node],
until: &Option<Box<Node>>,
line: u32,
) -> Result<(), RuntimeFailure> {
let folder = self.desktop().working_directory().map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line,
})
})?;
let files = self
.desktop()
.list_files(&folder, pattern, mode)
.map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line,
})
})?;
for (index, file) in files.iter().enumerate() {
self.set_global("A_Index", Value::Int(index as i64 + 1));
let name = the_name_of(file).to_string();
let path = the_path_that_is_relative_to(file, &folder);
self.set_global("A_LoopFileName", Value::Text(name.clone()));
self.set_global(
"A_LoopFileExt",
Value::Text(the_extension_of(&name).to_string()),
);
self.set_global(
"A_LoopFileDir",
Value::Text(the_folder_of(&path).to_string()),
);
self.set_global("A_LoopFilePath", Value::Text(path.clone()));
self.the_short_names_of_the_files_are_refused = true;
self.set_global("A_LoopFileFullPath", Value::Text(path));
self.set_global("A_LoopFileLongPath", Value::Text(file.clone()));
if let Ok(size) = self.desktop().the_size_of_a_file(file) {
self.set_global("A_LoopFileSize", Value::Int(size));
self.set_global("A_LoopFileSizeKB", Value::Int(size / 1024));
self.set_global("A_LoopFileSizeMB", Value::Int(size / 1024 / 1024));
}
if let Ok(letters) = self.desktop().file_attributes(file) {
self.set_global("A_LoopFileAttrib", Value::Text(letters.concat()));
}
if let Ok(times) = self.desktop().file_times(file) {
let offset = crate::files::local_offset(self);
self.set_global(
"A_LoopFileTimeCreated",
Value::Text(crate::files::stamp_of(times.0, offset)),
);
self.set_global(
"A_LoopFileTimeModified",
Value::Text(crate::files::stamp_of(times.1, offset)),
);
self.set_global(
"A_LoopFileTimeAccessed",
Value::Text(crate::files::stamp_of(times.2, offset)),
);
}
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => {}
TheFlowOfALoop::Out(failure) => return Err(failure),
}
if self.the_until_ends_the_loop(until)? {
break;
}
}
Ok(())
}
fn the_read_loop_of_the_v1(
&mut self,
arguments: &[Node],
body: &[Node],
until: &Option<Box<Node>>,
line: u32,
) -> Result<(), RuntimeFailure> {
let path = match arguments.get(1) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, line)?,
None => String::new(),
};
let output = match arguments.get(2) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, line)?,
None => String::new(),
};
let lines = self.desktop().read_file(&path).unwrap_or_default();
self.loop_output_files.push(output);
let mut failure = None;
for (index, line_text) in lines.iter().enumerate() {
self.set_global("A_Index", Value::Int(index as i64 + 1));
self.set_global("A_LoopReadLine", Value::Text(line_text.clone()));
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => continue,
TheFlowOfALoop::Out(other) => {
failure = Some(other);
break;
}
}
if self.the_until_ends_the_loop(until)? {
break;
}
}
self.loop_output_files.pop();
if let Some(other) = failure {
return Err(other);
}
Ok(())
}
fn the_parse_loop_of_the_v1(
&mut self,
arguments: &[Node],
body: &[Node],
until: &Option<Box<Node>>,
line: u32,
) -> Result<(), RuntimeFailure> {
let text = match arguments.get(1) {
Some(Node::LegacyExpression { value, .. }) => self.evaluate(value)?.to_text(),
Some(Node::Literal {
value: crate::ast::LiteralValue::Text(text),
..
}) => {
let name = self.the_substitution_of_the_v1(text.trim(), line)?;
match self.lookup(&name) {
Some(value) => value.to_text(),
None => String::new(),
}
}
Some(node) => self.evaluate(node)?.to_text(),
None => String::new(),
};
let delimiters = match arguments.get(2) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, line)?,
None => String::new(),
};
let comma_separated =
crate::v1::the_delimiters_ask_for_the_comma_separated_values(&delimiters);
let omitted = match arguments.get(3) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, line)?,
None => String::new(),
};
if text.is_empty() {
return Ok(());
}
let pieces: Vec<String> = if comma_separated {
crate::v1::the_fields_of_the_comma_separated_values(&text)
} else if delimiters.is_empty() {
text.chars()
.filter(|character| !omitted.contains(*character))
.map(|character| character.to_string())
.collect()
} else {
split_on_any(&text, &delimiters)
.into_iter()
.map(|piece| {
piece
.trim_matches(|character| omitted.contains(character))
.to_string()
})
.collect()
};
for (index, piece) in pieces.iter().enumerate() {
self.set_global("A_Index", Value::Int(index as i64 + 1));
self.set_global("A_LoopField", Value::Text(piece.clone()));
match the_flow_of_a_loop_body(self.run_block(body)) {
TheFlowOfALoop::Next => {}
TheFlowOfALoop::Break => break,
TheFlowOfALoop::Continue => continue,
TheFlowOfALoop::Out(failure) => return Err(failure),
}
if self.the_until_ends_the_loop(until)? {
break;
}
}
Ok(())
}
fn the_value_of_the_expression_is_set(
&mut self,
expression: &Node,
) -> Result<bool, RuntimeFailure> {
match expression {
Node::Property {
target,
name,
line,
} => {
let target_value = self.evaluate(target)?;
let name = self.the_name_of_the_member(name, *line)?;
match self.read_property(&target_value, &name, *line) {
Ok(Value::Unset) | Ok(Value::Skipped) => Ok(false),
Ok(_) => Ok(true),
Err(failure) if the_member_is_missing(&failure) => Ok(false),
Err(failure) => Err(failure),
}
}
_ => match self.evaluate(expression) {
Ok(Value::Unset) | Ok(Value::Skipped) => Ok(false),
Ok(_) => Ok(true),
Err(failure) if the_failure_is_an_unset_variable(&failure) => Ok(false),
Err(failure) => Err(failure),
},
}
}
fn the_failure_of_an_absent_value(&self, line: u32) -> RuntimeFailure {
RuntimeFailure::Detailed(
RuntimeError {
message: "This value has not been assigned a value.".to_string(),
line,
},
Detail {
what: String::new(),
extra: String::new(),
},
)
}
fn the_absent_answer_of(&self, from: &Value) -> Value {
match from {
Value::Skipped => Value::Skipped,
_ => Value::Unset,
}
}
fn the_expression_is_absent(&mut self, node: &Node) -> Result<bool, RuntimeFailure> {
if let Node::Var { name, .. } = node {
return Ok(self.lookup(name).is_none());
}
match self.evaluate(node) {
Ok(Value::Unset) | Ok(Value::Skipped) => Ok(true),
Ok(_) => Ok(false),
Err(failure) if the_failure_is_an_unset_variable(&failure) => Ok(true),
Err(failure) => Err(failure),
}
}
fn the_until_ends_the_loop(
&mut self,
until: &Option<Box<Node>>,
) -> Result<bool, RuntimeFailure> {
let Some(condition) = until else {
return Ok(false);
};
let value = self.evaluate(condition)?;
Ok(self.the_value_is_true(&value))
}
pub(crate) fn the_substitution_of_the_v1(
&mut self,
text: &str,
line: u32,
) -> Result<String, RuntimeFailure> {
if !text.contains('%') && !text.contains('`') {
return Ok(text.to_string());
}
let mut out = String::with_capacity(text.len());
let chars: Vec<char> = text.chars().collect();
let mut index = 0usize;
while index < chars.len() {
if chars[index] == '`' {
match chars.get(index + 1) {
Some(next) => {
out.push(self.dialect.the_escape_of_the_dialect(*next));
index += 2;
}
None => {
out.push('`');
index += 1;
}
}
continue;
}
if chars[index] == '%' {
if let Some(close) = self.the_closing_percent(&chars, index + 1) {
let name: String = chars[index + 1..close].iter().collect();
match self.the_value_of_the_substitution(name.trim(), line)? {
Some(value) => {
let text = self.the_text_of(&value);
out.push_str(&text);
index = close + 1;
continue;
}
None => {
index = close + 1;
continue;
}
}
}
out.extend(&chars[index..]);
break;
}
out.push(chars[index]);
index += 1;
}
Ok(out)
}
fn the_closing_percent(&self, chars: &[char], from: usize) -> Option<usize> {
let mut index = from;
while index < chars.len() {
match chars[index] {
'`' => index += 2,
'%' => return Some(index),
_ => index += 1,
}
}
None
}
fn the_value_of_a_legacy_assignment(
&mut self,
text: &str,
line: u32,
) -> Result<Value, RuntimeFailure> {
let text = self.the_substitution_of_the_v1(text, line)?;
let text = if self.auto_trim {
text.trim().to_string()
} else {
text
};
Ok(crate::v1::the_number_of_a_legacy_text(&text).unwrap_or(Value::Text(text)))
}
fn the_value_of_the_substitution(
&mut self,
name: &str,
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
if let Some(value) = self.lookup(name) {
return Ok(Some(value));
}
if self.dialect.unset_is_blank() && name == "0" {
return Ok(Some(self.the_value_of_an_unset_variable(name)));
}
if let Some(answer) = self.the_built_in_variable(name) {
return match answer {
Ok(value) => Ok(Some(value)),
Err(error) => Err(RuntimeFailure::Error(RuntimeError {
message: error.message,
line: if error.line == 0 { line } else { error.line },
})),
};
}
if let Some(reason) = self.the_reason_of_the_short_names_of_the_files(name) {
return Err(RuntimeFailure::Error(RuntimeError {
message: reason.to_string(),
line,
}));
}
if let Some(value) = self.the_value_of_a_variable_of_the_runtime(name) {
return Ok(Some(value));
}
if !self.dialect.percent_looks_at_the_environment() {
return Ok(None);
}
if self.no_env {
return Ok(None);
}
match self.desktop().env_get(name) {
Ok(Some(value)) => {
self.warn_about_the_environment_that_is_accessed(name, line);
Ok(Some(Value::Text(value)))
}
Ok(None) => {
self.warn_about_the_variable_that_has_no_value(name, line);
Ok(None)
}
Err(_) => {
self.warn_about_the_variable_that_has_no_value(name, line);
Ok(None)
}
}
}
fn call_builtin(
&mut self,
name: &str,
values: &[Value],
line: u32,
route: Route,
) -> Result<Value, RuntimeFailure> {
let Some(builtin) =
self.the_builtin_of_the_kind(name, crate::builtins::BuiltinKind::Function)
else {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Call to nonexistent function.".into(),
line,
}));
};
self.call_the_row(builtin, values, line, route)
}
fn call_the_row(
&mut self,
builtin: &'static crate::builtins::Builtin,
values: &[Value],
line: u32,
route: Route,
) -> Result<Value, RuntimeFailure> {
if values.len() < builtin.min as usize {
return Err(self.the_arity_failure(
"Too few parameters passed to function.",
builtin.name,
route,
line,
));
}
if builtin.max < 255 && values.len() > builtin.max as usize {
return Err(self.the_arity_failure(
"Too many parameters passed to function.",
builtin.name,
route,
line,
));
}
if values.iter().any(|value| matches!(value, Value::Unset)) {
for (index, value) in values.iter().enumerate() {
if !matches!(value, Value::Unset) {
continue;
}
if index < builtin.min as usize {
return Err(self.the_missing_parameter("", line));
}
}
}
let checks_the_kind = self.dialect.the_built_in_checks_the_kind_of_its_arguments();
let converted = if checks_the_kind {
None
} else {
self.the_numbers_that_the_arguments_hold(builtin.name, values)
};
let values = converted.as_deref().unwrap_or(values);
let decides = crate::builtins::decides_references(builtin.name);
for (index, value) in values.iter().enumerate() {
if !matches!(value, Value::Reference(_))
|| builtin.writes_back(index)
|| decides
|| crate::builtins::refuses_itself(builtin.name)
|| !checks_the_kind
{
continue;
}
if matches!(
crate::builtins::wants(builtin.name, index),
crate::builtins::Wants::Declared(TypeName::VarRef)
) {
continue;
}
let message = match crate::builtins::wants(builtin.name, index) {
crate::builtins::Wants::Declared(kind) => {
requires(index + 1, builtin.name, kind, value)
}
crate::builtins::Wants::Checked(kind) => expects_a_kind(kind, value),
crate::builtins::Wants::Reference(_) => continue,
crate::builtins::Wants::Value => continue,
};
return Err(RuntimeFailure::Detailed(
RuntimeError { message, line },
Detail {
what: builtin.name.to_string(),
extra: String::new(),
},
));
}
for (index, value) in values.iter().enumerate() {
if matches!(value, Value::Reference(_)) || !checks_the_kind {
continue;
}
let message = match crate::builtins::wants(builtin.name, index) {
crate::builtins::Wants::Declared(kind) => {
if accepts(kind, value) {
continue;
}
if kind == TypeName::String
&& matches!(value, Value::Object(_))
&& self.dialect.an_object_has_no_text()
{
continue;
}
requires(index + 1, builtin.name, kind, value)
}
crate::builtins::Wants::Checked(kind) => {
if is_of_the_kind(kind, value) {
continue;
}
expects_a_kind(kind, value)
}
crate::builtins::Wants::Reference(wants) => {
wants_a_reference(index + 1, builtin.name, wants, value)
}
crate::builtins::Wants::Value => continue,
};
let what = match crate::builtins::wants(builtin.name, index) {
crate::builtins::Wants::Reference(_) => String::new(),
_ => builtin.name.to_string(),
};
return Err(RuntimeFailure::Detailed(
RuntimeError { message, line },
Detail {
what,
extra: the_extra_of_the_value(value),
},
));
}
for number in self
.dialect
.the_parameters_that_may_not_be_left_out(builtin.name)
{
if values.len() < *number as usize {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: format!(
"Parameter #{number} of {} must not be omitted in this case.",
builtin.name
),
line,
},
Detail {
what: builtin.name.to_string(),
extra: String::new(),
},
));
}
}
let answered = (builtin.handler)(self, values, line, builtin.variant);
if let Err(error) = answered {
if let Some(value) = self.take_the_thrown_value() {
return Err(RuntimeFailure::Thrown(value));
}
let extra = crate::builtins::the_extra_of(builtin.name, &error.message, values)
.unwrap_or_else(|| the_parameter_that_failed(&error.message, values));
return Err(RuntimeFailure::Detailed(
error,
Detail {
what: builtin.name.to_string(),
extra,
},
));
}
Ok(answered.unwrap())
}
fn the_numbers_that_the_arguments_hold(
&self,
name: &str,
values: &[Value],
) -> Option<Vec<Value>> {
let mut numbers: Option<Vec<Value>> = None;
for (index, value) in values.iter().enumerate() {
if !self.dialect.the_parameter_wants_a_number(name, index) {
continue;
}
if self.dialect.the_parameter_keeps_its_text(name, index) {
continue;
}
if matches!(value, Value::Int(_) | Value::Float(_)) {
continue;
}
let number = crate::v1::the_number_at_the_start_of_a_text(&self.the_text_of(value))
.unwrap_or(Value::Int(0));
let numbers = numbers.get_or_insert_with(|| values.to_vec());
numbers[index] = number;
}
numbers
}
pub(crate) fn desktop(&mut self) -> &mut (dyn crate::runtime::Desktop + 'a) {
&mut *self.desktop
}
pub(crate) fn initial_working_dir(&self) -> Option<&str> {
self.initial_working_dir.as_deref()
}
pub(crate) fn the_output_file_of_the_loop(&self) -> Option<&str> {
self.loop_output_files
.last()
.map(|path| path.as_str())
.filter(|path| !path.is_empty())
}
pub(crate) fn the_file_of_the_loop(&self) -> Option<String> {
self.lookup("A_LoopFileLongPath")
.map(|value| value.to_text())
.filter(|path| !path.is_empty())
}
pub(crate) fn sleep_ms(&mut self, millis: u64) {
self.clock.sleep_ms(millis)
}
pub(crate) fn now_ms(&self) -> u64 {
self.clock.now_ms()
}
pub(crate) fn hotkeys(&mut self) -> &mut Vec<crate::hotkeys::Hotkey> {
&mut self.hotkeys
}
pub fn the_hotkeys(&self) -> &[crate::hotkeys::Hotkey] {
&self.hotkeys
}
pub fn is_suspended(&self) -> bool {
self.suspended
}
pub fn is_paused(&self) -> bool {
self.paused
}
pub fn set_suspended(&mut self, suspended: bool) {
if suspended == self.suspended {
return;
}
self.suspended = suspended;
for (at, hotkey) in self.hotkeys.iter_mut().enumerate() {
let exempt = self.hotkey_is_exempt.get(at).copied().unwrap_or(false);
if suspended {
if let Some(was) = self.hotkey_was_enabled.get_mut(at) {
*was = hotkey.enabled;
}
if !exempt {
hotkey.enabled = false;
}
} else if let Some(was) = self.hotkey_was_enabled.get(at) {
hotkey.enabled = *was;
}
}
}
pub fn set_paused(&mut self, paused: bool) {
self.paused = paused;
}
pub(crate) fn set_exit_callback(&mut self, name: &str, line: u32) {
match self
.exit_callbacks
.iter_mut()
.find(|callback| callback.name.eq_ignore_ascii_case(name))
{
Some(callback) => callback.line = line,
None => self.exit_callbacks.push(Callback {
name: name.to_string(),
line,
}),
}
}
pub(crate) fn set_error_callback(&mut self, name: &str, line: u32) {
match self
.error_callbacks
.iter_mut()
.find(|callback| callback.name.eq_ignore_ascii_case(name))
{
Some(callback) => callback.line = line,
None => self.error_callbacks.push(Callback {
name: name.to_string(),
line,
}),
}
}
pub(crate) fn remove_exit_callback(&mut self, name: &str) {
self.exit_callbacks
.retain(|callback| !callback.name.eq_ignore_ascii_case(name));
}
pub(crate) fn remove_error_callback(&mut self, name: &str) {
self.error_callbacks
.retain(|callback| !callback.name.eq_ignore_ascii_case(name));
}
pub(crate) fn order_exit_callback(&mut self, name: &str, before: bool) {
let Some(at) = self
.exit_callbacks
.iter()
.position(|callback| callback.name.eq_ignore_ascii_case(name))
else {
return;
};
let callback = self.exit_callbacks.remove(at);
if before {
self.exit_callbacks.insert(0, callback);
} else {
self.exit_callbacks.push(callback);
}
}
pub(crate) fn order_error_callback(&mut self, name: &str, before: bool) {
let Some(at) = self
.error_callbacks
.iter()
.position(|callback| callback.name.eq_ignore_ascii_case(name))
else {
return;
};
let callback = self.error_callbacks.remove(at);
if before {
self.error_callbacks.insert(0, callback);
} else {
self.error_callbacks.push(callback);
}
}
pub(crate) fn the_callback(
&self,
value: Option<&Value>,
name: &str,
line: u32,
) -> Result<Callback, RuntimeError> {
let Some(value) = value else {
return Err(RuntimeError {
message: format!(
"Parameter #1 of {name} requires an Object, but received nothing."
),
line,
});
};
let Value::Object(object) = value else {
return Err(RuntimeError {
message: crate::runtime::wants_a_reference(1, name, "an Object", value),
line,
});
};
let object = object.borrow();
if object.class != "func" {
return Err(RuntimeError {
message: format!(
"This value of type \"{}\" has no method named \"Call\".",
value.type_name().name()
),
line,
});
}
let function_name = match object.value_of("name") {
Some(Value::Text(text)) => text.clone(),
_ => String::new(),
};
let takes_two = match self.functions.get(&function_name.to_lowercase()) {
Some(function) => {
let fewest = function
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count();
let variadic = function
.parameters
.iter()
.any(|parameter| parameter.variadic);
fewest <= 2 && (variadic || function.parameters.len() >= 2)
}
None => {
let fewest = number_of(&object.properties, "minparams");
let most = number_of(&object.properties, "maxparams");
fewest <= 2 && most >= 2
}
};
if !takes_two {
return Err(RuntimeError {
message: "Invalid callback function.".into(),
line,
});
}
Ok(Callback {
name: function_name,
line,
})
}
fn ask_the_error_callbacks(&mut self, failure: &RuntimeFailure) -> TheError {
if self.error_callbacks.is_empty() || self.try_active > 0 {
return TheError::Goes;
}
let (value, mode) = match failure {
RuntimeFailure::Error(error) => (self.error_value(error), "Return"),
RuntimeFailure::Detailed(error, detail) => {
(self.error_value_with(error, detail), "Return")
}
RuntimeFailure::Thrown(value) => (value.clone(), "Exit"),
RuntimeFailure::Timeout(timeout) => (
self.error_value(&RuntimeError {
message: timeout.to_string(),
line: 0,
}),
"ExitApp",
),
_ => return TheError::Goes,
};
let mut answer = 0;
let callbacks = self.error_callbacks.clone();
for callback in callbacks {
let values = [value.clone(), Value::Text(mode.to_string())];
if let Ok(said) =
self.call_named(&callback.name, &values, callback.line, Route::Written)
{
let said = said.to_number().unwrap_or(0.0) as i64;
if said != 0 {
answer = said;
break;
}
}
}
match answer {
1 => TheError::Hidden,
-1 if mode == "Return" => TheError::Continues,
-1 => TheError::Hidden,
_ => TheError::Goes,
}
}
pub(crate) fn call_function_by_name(
&mut self,
name: &str,
line: u32,
) -> Result<(), RuntimeFailure> {
let Some(function) = self.functions.get(&name.to_lowercase()).cloned() else {
return Ok(());
};
self.call_function(&function, &[], line, Route::Written)
.map(|_| ())
}
pub(crate) fn wall_clock(&self) -> Option<crate::date::WallClock> {
self.clock.wall_clock()
}
pub(crate) fn set_global(&mut self, name: &str, value: Value) {
self.variables.insert(the_key_of(name), value);
}
pub(crate) fn push_output(&mut self, text: String) {
self.output.push(text);
}
fn the_operand_is_true(&self, node: &Node, value: &Value) -> bool {
if self.dialect.the_text_that_was_written_is_a_string()
&& self.the_node_is_a_quoted_text(node)
{
return match value {
Value::Text(text) => !text.is_empty(),
other => other.truthy(),
};
}
self.the_value_is_true(value)
}
fn the_answer_of_the_boolean(&self, node: &Node, value: &Value) -> Value {
if self.dialect.the_operators_answer_a_number() {
return Value::Int(self.the_operand_is_true(node, value) as i64);
}
value.clone()
}
fn the_value_is_true(&self, value: &Value) -> bool {
if self.dialect.the_text_that_is_a_number_is_false() {
if let Value::Text(text) = value {
return match crate::v1::the_number_of_a_text(text) {
Some(number) => number.truthy(),
None => !text.is_empty(),
};
}
}
value.truthy()
}
fn the_value_of_the_condition(&mut self, condition: &Node) -> Result<Value, RuntimeFailure> {
match self.evaluate(condition) {
Ok(value) => Ok(value),
Err(failure) => {
if !self.dialect.the_failure_of_a_condition_is_not_reported() {
return Err(failure);
}
if !matches!(
failure,
RuntimeFailure::Error(_) | RuntimeFailure::Detailed(_, _)
) {
return Err(failure);
}
Ok(Value::Int(0))
}
}
}
fn evaluate(&mut self, node: &Node) -> Result<Value, RuntimeFailure> {
match node {
Node::Unset { .. } => {
Ok(Value::Text(String::new()))
}
Node::CallValue {
target,
arguments,
line,
} => {
let value = self.evaluate(target)?;
self.call_the_value_of(value, arguments, *line)
} Node::Assign {
name,
op,
value,
line,
} => {
if *op == AssignOp::Set && the_node_is_unset(value) {
self.unset_variable(name);
return Ok(Value::Text(String::new()));
}
let value = self.evaluate(value)?;
self.write_a_variable(name, *op, value, *line)
}
Node::LegacyComparison {
left,
op,
text,
line,
} => {
self.the_comparison_of_a_legacy_if(left, *op, text, *line)
}
Node::LegacyMatch {
left,
form,
texts,
negated,
line,
} => {
self.the_match_of_a_legacy_if(left, *form, texts, *negated, *line)
}
Node::AssignProperty {
target,
name,
op,
value,
line,
} => {
if matches!(&**target, Node::Maybe { .. })
&& self.dialect.the_chain_may_be_skipped()
&& matches!(self.evaluate(target)?, Value::Unset | Value::Skipped)
{
return Ok(Value::Unset);
}
let value = self.evaluate(value)?;
let name = self.the_name_of_the_member(name, *line)?;
self.write_a_property(target, &name, *op, value, *line)
}
Node::AssignIndex {
target,
index,
also,
op,
value,
line,
} => {
if let Node::Property { .. } = &**target {
return self.write_the_property_of_a_parameterised_item(
target, index, also, *op, value, *line,
);
}
let target_value = self.evaluate(target)?;
if self.dialect.the_chain_may_be_skipped()
&& matches!(target_value, Value::Unset)
{
return Ok(Value::Unset);
}
let keys = self.the_keys_of_an_index(index, also)?;
let value = self.evaluate(value)?;
self.set_item(&target_value, &keys, *op, value, *line)
} Node::Literal { value, line } => Ok(match value {
LiteralValue::Integer(number) => Value::Int(*number),
LiteralValue::Float(number) => Value::Float(*number),
LiteralValue::Number(text) => {
let text = crate::v1::the_text_of_the_number_that_fits(text);
if crate::v1::the_number_is_a_number(&text) {
return Ok(match crate::v1::the_number_of_a_text(&text) {
Some(Value::Int(number)) => {
Value::Text(self.integer_format.the_text_of(number))
}
Some(Value::Float(number)) => {
Value::Text(self.float_format.the_text_of(number))
}
_ => Value::Text(text),
});
}
Value::Text(text)
}
LiteralValue::Text(text) => Value::Text(self.interpolate(text, *line)?),
LiteralValue::Bool(flag) => Value::Int(*flag as i64),
}),
Node::ObjectLiteral { items, line } => {
let object = crate::classes::object(self.dialect.class_of_an_object());
if let Value::Object(cell) = &object {
for item in items {
match item {
ObjectItem::Property(name, value) => {
let name = self.the_name_of_the_member(name, *line)?;
let value = self.evaluate(value)?;
if matches!(value, Value::Unset | Value::Skipped)
&& !self.dialect.the_chain_may_be_skipped()
{
continue;
}
put(&mut cell.borrow_mut().properties, &name, value);
}
ObjectItem::LegacyKey(key, value) => {
let key = self.evaluate(key)?;
let value = self.evaluate(value)?;
put(&mut cell.borrow_mut().properties, &key.to_text(), value);
}
ObjectItem::Value(value) => {
self.evaluate(value)?;
}
}
}
}
Ok(object)
}
Node::Lambda {
parameters,
body,
line,
} => {
let function = Function {
name: String::new(),
parameters: parameters.clone(),
body: vec![Node::Return {
value: Some(Box::new((**body).clone())),
line: *line,
}],
declarations: Declarations::default(),
closure: self.scopes.clone(),
};
let captures = crate::warnings::the_names_that_a_node_reads(body)
.iter()
.any(|name| self.the_scope_around_has(name));
let name = self.make_a_closure(function.clone());
Ok(closure_value(&name, &function, captures))
}
Node::ArrayLiteral { items, line } => {
let mut values = Vec::new();
for item in items {
match item {
Some(Node::Spread { value, line }) => {
let spread = self.evaluate(value)?;
for item in self.the_items_of_a_spread(&spread, *line)? {
values.push(Some(item));
}
}
Some(item) => values.push(Some(self.evaluate(item)?)),
None => values.push(None),
}
}
Ok(crate::classes::array::construct_with_holes(
&values, self, *line,
))
}
Node::Maybe { value, from_a_group, .. } => {
if !from_a_group && self.dialect.the_chain_may_be_skipped() {
match &**value {
Node::Property {
target,
name,
line,
} => {
let target_value = self.evaluate(target)?;
let name = self.the_name_of_the_member(name, *line)?;
return match self.read_property(&target_value, &name, *line) {
Ok(Value::Unset) => Ok(Value::Skipped),
Ok(value) => Ok(value),
Err(failure) if the_member_is_not_there(&failure) => {
Ok(Value::Skipped)
}
Err(failure) => Err(failure),
};
}
Node::Index {
target,
index,
also,
line,
} => {
if let Node::Property {
target: object,
name,
line: property_line,
} = &**target
{
let object_value = self.evaluate(object)?;
let name = self.the_name_of_the_member(name, *property_line)?;
let keys = self.the_keys_of_an_index(index, also)?;
let (held, by_meta) = self.read_property_fully(
&object_value,
&name,
&keys,
*property_line,
)?;
if matches!(held, Value::Unset | Value::Skipped) {
return Ok(Value::Skipped);
}
if by_meta {
return Ok(held);
}
return match self.index_a_value(&held, &keys, *line) {
Ok(Value::Unset) => Ok(Value::Skipped),
Ok(value) => Ok(value),
Err(failure) if the_member_is_not_there(&failure) => {
Ok(Value::Skipped)
}
Err(failure) => Err(failure),
};
}
let target_value = self.evaluate(target)?;
if matches!(target_value, Value::Unset | Value::Skipped) {
return Ok(Value::Skipped);
}
let keys = self.the_keys_of_an_index(index, also)?;
return match self.index_a_value(&target_value, &keys, *line) {
Ok(Value::Unset) => Ok(Value::Skipped),
Ok(value) => Ok(value),
Err(failure) if the_member_is_not_there(&failure) => {
Ok(Value::Unset)
}
Err(failure) => Err(failure),
};
}
_ => {}
}
}
match self.evaluate(value) {
Ok(Value::Unset) if *from_a_group => Ok(Value::Unset),
Ok(Value::Unset) => Ok(Value::Skipped),
Ok(value) => Ok(value),
Err(failure) => {
if !*from_a_group
&& (the_failure_is_an_unset_variable(&failure)
|| the_member_is_not_there(&failure))
{
Ok(Value::Skipped)
} else {
Err(failure)
}
}
}
}
Node::Group { items, .. } => {
let mut value = Value::Text(String::new());
for item in items {
value = self.evaluate(item)?;
}
Ok(value)
}
Node::Empty { .. } => {
Ok(Value::Text(String::new()))
}
Node::Legacy { items, .. } => {
let mut value = Value::Text(String::new());
for item in items {
value = self.evaluate(item)?;
}
Ok(value)
}
Node::LegacyControl { condition, .. } => {
self.evaluate(condition)
}
Node::For { line, .. } => {
Err(RuntimeFailure::Error(RuntimeError {
message: "the for loop is not an expression.".into(),
line: *line,
}))
}
Node::Declare { line, .. } => {
Err(RuntimeFailure::Error(RuntimeError {
message: "a declaration is not an expression.".into(),
line: *line,
}))
}
Node::Super { line } => {
Err(RuntimeFailure::Error(RuntimeError {
message: "Syntax error.\n Specifically: super".into(),
line: *line,
}))
}
Node::Var { name, line } => {
if name.eq_ignore_ascii_case("unset") {
return Ok(Value::Unset);
}
match self.lookup(name) {
Some(value) => {
if let Value::Object(object) = &value {
let class = object.borrow().class.clone();
self.initialise_the_class(&class, *line)?;
}
Ok(value)
}
None => match self.the_built_in_variable(name) {
Some(Ok(value)) => Ok(value),
Some(Err(error)) => Err(RuntimeFailure::Error(RuntimeError {
message: error.message,
line: *line,
})),
None => {
if let Some(reason) = self.the_reason_of_the_short_names_of_the_files(name)
{
return Err(RuntimeFailure::Error(RuntimeError {
message: reason.to_string(),
line: *line,
}));
}
match self.the_value_of_a_variable_of_the_runtime(name) {
Some(value) => Ok(value),
None => {
self.warn_about_the_variable_that_has_no_value(name, *line);
if self.dialect.unset_is_blank() {
return Ok(self.the_value_of_an_unset_variable(name));
}
Err(match self.alias_of(name) {
Some(_) => RuntimeFailure::Error(RuntimeError {
message: unassigned_parameter(),
line: *line,
}),
None => self.the_unassigned_failure(name, *line),
})
}
}
}
}
}
}
Node::Unary { op, operand, line } => match op {
UnaryOp::PreIncrement
| UnaryOp::PreDecrement
| UnaryOp::PostIncrement
| UnaryOp::PostDecrement => self.increment(*op, operand, *line),
UnaryOp::Not | UnaryOp::NotWord => {
let value = self.evaluate(operand)?;
Ok(Value::Int(!self.the_operand_is_true(operand, &value) as i64))
}
UnaryOp::Boolean => {
let value = self.evaluate(operand)?;
Ok(self.the_answer_of_the_boolean(operand, &value))
}
UnaryOp::Negate => {
let value = self.evaluate(operand)?; if self.dialect.the_chain_may_be_skipped() && matches!(value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&value));
}
if self.dialect.a_value_that_is_not_a_number_is_blank() {
return Ok(match self.the_number_of_the_v1(operand, &value) {
Some(Value::Int(number)) => Value::Int(number.wrapping_neg()),
Some(Value::Float(number)) => Value::Float(-number),
_ => Value::Text(String::new()),
});
}
Ok(match self.the_number_value(&value, *line)? {
Value::Int(number) => Value::Int(number.wrapping_neg()),
Value::Float(number) => Value::Float(-number),
other => other,
})
}
UnaryOp::Plus => {
let value = self.evaluate(operand)?; if self.dialect.the_chain_may_be_skipped() && matches!(value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&value));
}
if self.dialect.a_value_that_is_not_a_number_is_blank() {
return Ok(value);
}
self.the_number_value(&value, *line)
}
UnaryOp::BitwiseNot => {
let value = self.evaluate(operand)?; if self.dialect.the_chain_may_be_skipped() && matches!(value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&value));
}
Ok(Value::Int(!self.the_whole_number(
&value,
*line,
TypeName::Number,
)?))
}
UnaryOp::Address => {
let Node::Var { name, .. } = operand.as_ref() else {
return Err(RuntimeFailure::Error(RuntimeError {
message: "\"&\" requires a variable.".into(),
line: *line,
}));
};
if let Some(kind) = self.cannot_be_referenced(name) {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This {kind} cannot have its reference taken.\n Specifically: {name}"
),
line: *line,
}));
}
let scope = match self.scopes.len() {
0 => Scope::Global,
depth => Scope::Local(depth - 1),
};
Ok(Value::Reference(Reference {
name: name.clone(),
scope,
alias: false,
}))
}
},
Node::Binary {
op,
left,
right,
line,
} => {
let line = *line;
if *op == BinaryOp::Coalesce {
if let Node::Var { name, .. } = left.as_ref() {
if let Some(value) = self.lookup(name) {
return Ok(value);
}
return self.evaluate(right);
}
if !self.dialect.an_expression_may_be_the_left_of_the_maybe() {
return Err(RuntimeFailure::Error(RuntimeError {
message: "the left side of ?? must be a variable".into(),
line,
}));
}
return match self.evaluate(left) {
Ok(Value::Unset) | Ok(Value::Skipped) => self.evaluate(right),
Ok(value) => Ok(value),
Err(failure) if the_failure_is_an_unset_variable(&failure) => {
self.evaluate(right)
}
Err(failure) => Err(failure),
};
}
if self.dialect.the_absent_value_may_be_the_class_of_the_is()
&& matches!(
op,
BinaryOp::Equal
| BinaryOp::StrictEqual
| BinaryOp::NotEqual
| BinaryOp::StrictNotEqual
)
{
let the_keyword_of_the_absent_value =
|node: &Node| matches!(node, Node::Var { name, .. } if name.eq_ignore_ascii_case("unset"));
let right_is_the_keyword = the_keyword_of_the_absent_value(right);
let left_is_the_keyword = the_keyword_of_the_absent_value(left);
if right_is_the_keyword || left_is_the_keyword {
let other = if right_is_the_keyword {
left.as_ref()
} else {
right.as_ref()
};
let absent = self.the_expression_is_absent(other)?;
let answer = match op {
BinaryOp::Equal | BinaryOp::StrictEqual => absent,
_ => !absent,
};
return Ok(Value::Int(answer as i64));
}
}
if *op == BinaryOp::Is
&& self.dialect.the_absent_value_may_be_the_class_of_the_is()
&& matches!(right.as_ref(), Node::Var { name, .. } if name.eq_ignore_ascii_case("unset"))
{
let answer = match left.as_ref() {
Node::Var { name, .. } => self.lookup(name).is_none(),
_ => match self.evaluate(left) {
Ok(Value::Unset) | Ok(Value::Skipped) => true,
Ok(_) => false,
Err(failure) if the_failure_is_an_unset_variable(&failure) => true,
Err(failure) => return Err(failure),
},
};
return Ok(Value::Int(answer as i64));
}
let left_value = self.evaluate(left)?;
if self.dialect.the_chain_may_be_skipped() && matches!(left_value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&left_value));
}
match op {
BinaryOp::And => {
if !self.the_operand_is_true(left, &left_value) {
return Ok(self.the_answer_of_the_boolean(left, &left_value));
}
if matches!(right.as_ref(), Node::Unset { .. }) {
return Ok(Value::Text(String::new()));
}
let right_value = self.evaluate(right)?;
return Ok(self.the_answer_of_the_boolean(right, &right_value));
}
BinaryOp::Or => {
if self.the_operand_is_true(left, &left_value) {
return Ok(self.the_answer_of_the_boolean(left, &left_value));
}
if matches!(right.as_ref(), Node::Unset { .. }) {
return Ok(Value::Text(String::new()));
}
let right_value = self.evaluate(right)?;
return Ok(self.the_answer_of_the_boolean(right, &right_value));
}
_ => {}
}
let right_value = self.evaluate(right)?;
if self.dialect.the_chain_may_be_skipped() && matches!(right_value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&right_value));
}
let (left_value, right_value) = if self
.dialect
.a_value_that_is_not_a_number_is_blank()
{
if *op == BinaryOp::Add && self.the_node_is_a_quoted_text(left) {
let text =
format!("{}{}", left_value.to_text(), self.the_text_of(&right_value));
return Ok(Value::Text(text));
}
if matches!(
op,
BinaryOp::Less
| BinaryOp::Greater
| BinaryOp::LessEqual
| BinaryOp::GreaterEqual
) {
let answer = self.the_comparison_of_the_v1(
left,
right,
&left_value,
&right_value,
op,
);
return Ok(Value::Int(answer as i64));
}
if matches!(op, BinaryOp::Equal | BinaryOp::NotEqual) {
let method = match op {
BinaryOp::Equal => self.case_sense.the_method_of_the_equal_sign(),
_ => self.case_sense.the_method(),
};
let same = match (
self.the_number_of_the_v1(left, &left_value),
self.the_number_of_the_v1(right, &right_value),
) {
(Some(one), Some(other)) => the_same_number(&one, &other),
_ => {
the_same_text(&left_value.to_text(), &right_value.to_text(), method)
}
};
let answer = match op {
BinaryOp::Equal => same,
_ => !same,
};
return Ok(Value::Int(answer as i64));
}
if matches!(
op,
BinaryOp::StrictEqual
| BinaryOp::StrictNotEqual
| BinaryOp::Concat
| BinaryOp::RegexMatch
) {
(left_value, right_value)
} else {
let left = self.the_number_of_the_v1(left, &left_value);
let right = self.the_number_of_the_v1(right, &right_value);
match (left, right) {
(Some(left), Some(right)) => (left, right),
_ => return Ok(Value::Text(String::new())),
}
}
} else {
(left_value, right_value)
};
Ok(match op {
BinaryOp::Equal => {
Value::Int(values_equal(&left_value, &right_value, false) as i64)
}
BinaryOp::NotEqual => {
Value::Int(!values_equal(&left_value, &right_value, false) as i64)
}
BinaryOp::StrictEqual => {
Value::Int(values_equal(&left_value, &right_value, true) as i64)
}
BinaryOp::StrictNotEqual => {
Value::Int(!values_equal(&left_value, &right_value, true) as i64)
}
BinaryOp::Less => {
let a = self.number(&left_value, line)?;
let b = self.number(&right_value, line)?;
Value::Int((a < b) as i64)
}
BinaryOp::Greater => {
let a = self.number(&left_value, line)?;
let b = self.number(&right_value, line)?;
Value::Int((a > b) as i64)
}
BinaryOp::LessEqual => {
let a = self.number(&left_value, line)?;
let b = self.number(&right_value, line)?;
Value::Int((a <= b) as i64)
}
BinaryOp::GreaterEqual => {
let a = self.number(&left_value, line)?;
let b = self.number(&right_value, line)?;
Value::Int((a >= b) as i64)
}
BinaryOp::Add => {
if self.dialect.add_concatenates()
&& (matches!(left_value, Value::Text(_))
|| matches!(right_value, Value::Text(_)))
{
Value::Text(format!(
"{}{}",
left_value.to_text(),
right_value.to_text()
))
} else {
let a = self.the_number_value(&left_value, line)?;
let b = self.the_number_value(&right_value, line)?;
match (&a, &b) {
(Value::Int(a), Value::Int(b)) => Value::Int(a.wrapping_add(*b)),
_ => Value::Float(
a.to_number().unwrap_or(0.0) + b.to_number().unwrap_or(0.0),
),
}
}
}
BinaryOp::Subtract => {
let a = self.the_number_value(&left_value, line)?;
let b = self.the_number_value(&right_value, line)?;
match (&a, &b) {
(Value::Int(a), Value::Int(b)) => Value::Int(a.wrapping_sub(*b)),
_ => Value::Float(
a.to_number().unwrap_or(0.0) - b.to_number().unwrap_or(0.0),
),
}
}
BinaryOp::Multiply => {
let a = self.the_number_value(&left_value, line)?;
let b = self.the_number_value(&right_value, line)?;
match (&a, &b) {
(Value::Int(a), Value::Int(b)) => Value::Int(a.wrapping_mul(*b)),
_ => Value::Float(
a.to_number().unwrap_or(0.0) * b.to_number().unwrap_or(0.0),
),
}
}
BinaryOp::Divide => {
let a = self.number(&left_value, line)?;
let b = self.number(&right_value, line)?;
if b == 0.0 {
if self.dialect.division_by_zero_is_blank() {
return Ok(Value::Text(String::new()));
}
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Value::Float(a / b)
}
BinaryOp::IntegerDivide => {
let a = self.integer(&left_value, line)?;
let b = self.integer(&right_value, line)?;
if b == 0 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Value::Int(a.wrapping_div(b))
}
BinaryOp::Power => {
let a = self.the_number_value(&left_value, line)?;
let b = self.the_number_value(&right_value, line)?;
if let (Value::Int(base), Value::Int(exponent)) = (&a, &b) {
if *exponent >= 0 && *exponent <= 63 {
if let Some(power) = base.checked_pow(*exponent as u32) {
return Ok(Value::Int(power));
}
}
}
Value::Float(powf(
a.to_number().unwrap_or(0.0),
b.to_number().unwrap_or(0.0),
))
}
BinaryOp::BitwiseAnd => {
let a = self.integer(&left_value, line)?;
let b = self.integer(&right_value, line)?;
Value::Int(a & b)
}
BinaryOp::BitwiseOr => {
let a = self.integer(&left_value, line)?;
let b = self.integer(&right_value, line)?;
Value::Int(a | b)
}
BinaryOp::BitwiseXor => {
let a = self.integer(&left_value, line)?;
let b = self.integer(&right_value, line)?;
Value::Int(a ^ b)
}
BinaryOp::ShiftLeft => {
let a = self.integer(&left_value, line)?;
let b = self.shift(&right_value, line)?;
Value::Int(a.wrapping_shl(b))
}
BinaryOp::ShiftRight => {
let a = self.integer(&left_value, line)?;
let b = self.shift(&right_value, line)?;
Value::Int(a.wrapping_shr(b))
}
BinaryOp::ShiftRightUnsigned => {
let a = self.integer(&left_value, line)? as u64;
let b = self.shift(&right_value, line)?;
Value::Int((a >> b) as i64)
}
BinaryOp::Concat => {
let left_text = self.the_text_of_the_concat(&left_value, line)?;
let right_text = self.the_text_of_the_concat(&right_value, line)?;
Value::Text(format!("{left_text}{right_text}"))
}
BinaryOp::RegexMatch => {
let text = left_value.to_text();
let pattern = right_value.to_text();
match crate::regex::find(&text, &pattern) {
Ok(Some(position)) => Value::Int(position as i64),
Ok(None) => Value::Int(0),
Err(reason) => {
return Err(RuntimeFailure::Error(RuntimeError {
message: reason,
line,
}));
}
}
}
BinaryOp::Is => {
let Some(class) = self.class_name_of(&right_value) else {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: expected_type(
TypeName::Class,
right_value.type_name(),
),
line,
},
Detail {
what: String::new(),
extra: the_extra_of_the_value(&right_value),
},
));
};
let answer = if self.class_name_of(&left_value).is_some() {
class == "class" || class == "object" || class == "any"
} else {
match &left_value {
Value::Object(object) => {
let name = object.borrow().class.clone();
class == "object" || self.class_chain(&name).contains(&class)
}
_ => {
let name = left_value.type_name().name().to_lowercase();
class == "any"
|| class == name
|| self.class_chain(&name).contains(&class)
}
}
};
Value::Int(answer as i64)
}
BinaryOp::And | BinaryOp::Or | BinaryOp::Coalesce => {
unreachable!("handled above")
}
})
}
Node::Call {
name,
arguments,
line,
} => self.call(name, arguments, *line),
Node::New {
path,
arguments,
line,
} => self.new_instance(path, arguments, *line),
Node::MethodCall {
target,
name,
arguments,
line,
} => {
if let Node::Super { .. } = &**target {
let name = self.the_name_of_the_member(name, *line)?;
return self.call_the_method_of_the_base(&name, arguments, *line);
}
let target_value = self.evaluate(target)?;
let name = self.the_name_of_the_member(name, *line)?;
self.call_method_on(&target_value, &name, arguments, *line)
}
Node::Property { target, name, line } => {
if let Node::Super { .. } = &**target {
let name = self.the_name_of_the_member(name, *line)?;
return self.read_the_property_of_the_base(&name, *line);
}
let target_value = self.evaluate(target)?;
let name = self.the_name_of_the_member(name, *line)?;
self.read_property(&target_value, &name, *line)
}
Node::Index {
target,
index,
also,
line,
} => {
if matches!(&**target, Node::Maybe { .. })
&& self.dialect.the_chain_may_be_skipped()
{
let value = self.evaluate(target)?;
if matches!(value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&value));
}
let keys = self.the_keys_of_an_index(index, also)?;
return self.index_a_value(&value, &keys, *line);
}
let keys = self.the_keys_of_an_index(index, also)?;
if let Node::Super { .. } = &**target {
return self.read_the_item_of_the_base(&keys, *line);
} if let Node::Property {
target: object,
name,
line: property_line,
} = &**target
{
let object_value = self.evaluate(object)?;
let name = self.the_name_of_the_member(name, *property_line)?;
let (value, by_meta) = self.read_property_fully(
&object_value,
&name,
&keys,
*property_line,
)?;
if by_meta {
return Ok(value);
}
return self.index_a_value(&value, &keys, *line);
}
let target = self.evaluate(target)?;
self.index_a_value(&target, &keys, *line) }
Node::Ternary {
condition,
then,
otherwise,
..
} => {
let value = self.evaluate(condition)?;
if self.dialect.the_chain_may_be_skipped() && matches!(value, Value::Unset | Value::Skipped) {
return Ok(self.the_absent_answer_of(&value));
}
if self.the_value_is_true(&value) {
self.evaluate(then)
} else {
self.evaluate(otherwise)
}
}
Node::DynamicName { pieces, line } => {
let name = self.the_name_of_the_pieces(pieces, *line)?;
match self.the_variable_of_the_name(&name, *line)? {
Some(value) => Ok(value),
None => {
if self
.dialect
.the_name_that_the_script_builds_and_that_is_not_there_is_answered()
{
return Ok(Value::Text(String::new()));
}
Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Variable not found.".to_string(),
line: *line,
},
Detail {
what: String::new(),
extra: name,
},
))
}
}
}
Node::AssignDynamic {
name,
op,
value,
line,
} => {
let name = self.the_name_of_the_pieces(name, *line)?;
let value = self.evaluate(value)?;
self.write_a_dynamic_name(&name, *op, value, *line)?;
Ok(Value::Text(String::new()))
}
Node::Expression { .. }
| Node::LegacyExpression { .. }
| Node::Block { .. }
| Node::LegacyCall { .. }
| Node::LegacyIf { .. }
| Node::LegacyAssign { .. }
| Node::If { .. }
| Node::Switch { .. }
| Node::While { .. }
| Node::Try { .. }
| Node::Throw { .. }
| Node::Loop { .. }
| Node::Break { .. }
| Node::Continue { .. }
| Node::Spread { .. }
| Node::Label { .. }
| Node::Goto { .. }
| Node::GotoComputed { .. }
| Node::HotkeyDefinition { .. }
| Node::Return { .. }
| Node::ExitApp { .. }
| Node::FunctionDef { .. }
| Node::Directive { .. }
| Node::ClassDef { .. } => Err(RuntimeFailure::Error(RuntimeError {
message: "this is a statement, not an expression".into(),
line: node.line(),
})),
}
}
pub(crate) fn interpolate(&mut self, text: &str, line: u32) -> Result<String, RuntimeError> {
if !text.contains('%') {
return Ok(text.to_string());
}
let mut out = String::with_capacity(text.len());
let chars: Vec<char> = text.chars().collect();
let mut index = 0usize;
while index < chars.len() {
if chars[index] == '%' {
if let Some(offset) = chars[index + 1..].iter().position(|c| *c == '%') {
let close = index + 1 + offset;
let reference: String = chars[index + 1..close].iter().collect();
if let Some(value) = self.resolve_reference(reference.trim(), line)? {
let text = value.as_text().map_err(|got| RuntimeError {
message: expected_type(TypeName::String, got),
line,
})?;
out.push_str(&text);
index = close + 1;
continue;
}
out.push_str(&chars[index..=close].iter().collect::<String>());
index = close + 1;
continue;
}
out.extend(&chars[index..]);
break;
}
out.push(chars[index]);
index += 1;
}
Ok(out)
}
fn write_the_property_of_a_parameterised_item(
&mut self,
property: &Node,
index: &Node,
also: &[Node],
op: AssignOp,
value: &Node,
line: u32,
) -> Result<Value, RuntimeFailure> {
let Node::Property {
target,
name,
line: property_line,
} = property
else {
return Err(RuntimeFailure::Error(RuntimeError {
message: "the target of the write is not a property".into(),
line,
}));
};
let object_value = self.evaluate(target)?;
if self.dialect.the_chain_may_be_skipped()
&& matches!(object_value, Value::Unset | Value::Skipped)
{
return Ok(self.the_absent_answer_of(&object_value));
}
let name = self.the_name_of_the_member(name, *property_line)?;
if !self
.the_accessor_of(&object_value, &name)
.map(|access| !access.parameters.is_empty())
.unwrap_or(false)
{
let (held, _) =
self.read_property_fully(&object_value, &name, &[], *property_line)?;
let keys = self.the_keys_of_an_index(index, also)?;
let value = self.evaluate(value)?;
return self.set_item(&held, &keys, op, value, line);
}
let keys = self.the_keys_of_an_index(index, also)?;
let value = self.evaluate(value)?;
let stored = match op {
AssignOp::Set => value,
_ => {
let (current, _) =
self.read_property_fully(&object_value, &name, &keys, *property_line)?;
self.apply_assign(op, &name, Some(current), value, line)?
}
};
self.write_property_with(&object_value, &name, &keys, stored.clone(), line)?;
Ok(stored)
}
fn set_item(
&mut self,
target: &Value,
keys: &[Value],
op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match target {
Value::Skipped => return Ok(value),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
let Value::Object(object) = target else {
if self.dialect.the_item_of_an_object_is_its_property()
&& self
.dialect
.the_write_of_a_property_of_a_value_that_is_not_an_object_is_dropped()
{
return Ok(value);
}
return Err(self.no_item(target, line));
};
let class = object.borrow().class.clone();
let value = match op {
AssignOp::Set => value,
other => {
let current = self.read_item(target, keys, line)?;
if self
.dialect
.the_compound_write_of_a_thing_that_is_not_a_number_is_dropped()
&& !matches!(op, AssignOp::Set | AssignOp::Concat)
&& !self.the_value_is_a_number_of_the_v1(¤t)
{
return Ok(current);
}
self.apply_assign(other, "the item", Some(current), value, line)?
}
};
if keys.len() > 1 && !self.dialect.the_item_of_an_object_is_its_property() {
if let Some(access) = self.the_accessor_of(target, "__Item") {
let Some(setter) = &access.setter else {
return Err(self.no_item(target, line));
};
self.call_the_body_of_an_accessor(target, &access, setter, line, keys, Some(&value))?;
return Ok(value);
}
if crate::classes::is_type(&class) {
return Err(self.too_many_parameters_of_an_item(&class, true, line));
}
}
let key = keys.first().expect("an item has a parameter");
if let Some(result) =
crate::classes::set_item(&class, key, target, value.clone(), self, line)
{
result?;
return Ok(value);
}
if self.dialect.the_item_of_an_object_is_its_property() {
let name = key.to_text();
let current = match op {
AssignOp::Set => self.read_property(target, &name, line).ok(),
_ => Some(self.read_property(target, &name, line)?),
};
let stored = self.apply_assign(op, &name, current, value, line)?;
self.write_property(target, &name, stored.clone(), line)?;
return Ok(stored);
}
if let Some(access) = self.the_accessor_of(target, "__Item") {
let Some(setter) = &access.setter else {
return Err(self.no_item(target, line));
};
self.call_the_body_of_an_accessor(target, &access, setter, line, keys, Some(&value))?;
return Ok(value);
}
Err(self.no_item(target, line))
}
fn read_item(
&mut self,
target: &Value,
keys: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
if self.dialect.the_chain_may_be_skipped() {
match target {
Value::Skipped => return Ok(Value::Skipped),
Value::Unset => return Err(self.the_failure_of_an_absent_value(line)),
_ => {}
}
}
let Value::Object(object) = target else {
if self.dialect.a_member_that_is_not_there_is_answered() {
return Ok(Value::Text(String::new()));
}
return Err(self.no_item(target, line));
};
let class = object.borrow().class.clone();
if let Some(access) = self.the_accessor_of(target, "__Item") {
let Some(getter) = &access.getter else {
return Err(self.no_item(target, line));
};
if access.parameters.is_empty() {
if keys.len() > 1 {
return Err(self.too_many_parameters_of_an_item(&class, false, line));
}
let value =
self.call_the_body_of_an_accessor(target, &access, getter, line, &[], None)?;
return self.read_item(&value, keys, line);
}
if keys.len() > access.parameters.len() {
return Err(self.too_many_parameters_of_an_item(&class, false, line));
}
let value =
self.call_the_body_of_an_accessor(target, &access, getter, line, keys, None)?;
return Ok(value);
}
if let Some((defining, method)) = self.find_method_in(&class, "__item") {
return Ok(self.method_reference(&defining, &method));
}
if keys.len() > 1
&& !self.dialect.the_item_of_an_object_is_its_property()
&& crate::classes::is_type(&class)
{
return Err(self.too_many_parameters_of_an_item(&class, false, line));
}
let key = keys.first().expect("an item has a parameter");
if let Some(result) = crate::classes::item(&class, key, target, self, line) {
return result;
}
if self.dialect.the_item_of_an_object_is_its_property() {
let name = key.to_text();
return self.read_property(target, &name, line);
}
if let Some(result) = crate::classes::call(&class, "__item", target, keys, self, line) {
return result;
}
if self.dialect.a_member_that_is_not_there_is_answered() {
return Ok(Value::Text(String::new()));
}
Err(self.no_item(target, line))
}
fn resolve_reference(
&mut self,
reference: &str,
line: u32,
) -> Result<Option<Value>, RuntimeError> {
let mut parts = reference.split('.');
let Some(name) = parts.next() else {
return Ok(None);
};
let found = self.lookup(name);
let mut value = match found {
Some(value) => value,
None => match self.the_built_in_variable(name) {
Some(Ok(value)) => value,
Some(Err(error)) => {
return Err(RuntimeError {
message: error.message,
line,
});
}
None => return Ok(None),
},
};
for part in parts {
let Ok(next) = self.read_property(&value, part, line) else {
return Ok(None);
};
value = next;
}
Ok(Some(value))
}
fn the_name_of_the_pieces(
&mut self,
pieces: &[DynamicPiece],
line: u32,
) -> Result<String, RuntimeFailure> {
let mut name = String::new();
for piece in pieces {
match piece {
DynamicPiece::Text(text) => name.push_str(text),
DynamicPiece::Value(value) => {
let value = self.evaluate(value)?;
match &value {
Value::Text(text) => name.push_str(text),
Value::Int(_) | Value::Float(_) => name.push_str(&value.to_text()),
Value::Reference(reference) => name.push_str(&reference.name),
other => {
let kind = other.the_kind();
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"Expected a String or VarRef but got a{} {}.",
the_article_of(&kind),
kind
),
line,
}));
}
}
}
}
}
Ok(name)
}
fn the_name_of_the_member(
&mut self,
name: &MemberName,
line: u32,
) -> Result<String, RuntimeFailure> {
match name {
MemberName::Text(text) => Ok(text.clone()),
MemberName::Dynamic(pieces) => self.the_name_of_the_pieces(pieces, line),
}
}
fn the_variable_of_the_name(
&mut self,
name: &str,
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
if let Some(value) = self.lookup(name) {
return Ok(Some(value));
}
match self.the_built_in_variable(name) {
Some(Ok(value)) => Ok(Some(value)),
Some(Err(error)) => Err(RuntimeFailure::Error(RuntimeError {
message: error.message,
line,
})),
None => Ok(None),
}
}
fn write_a_dynamic_name(
&mut self,
name: &str,
op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
let key = the_key_of(name);
if self.declarations.last().is_some()
&& self
.dialect
.the_dynamic_write_inside_a_function_is_refused()
{
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: self
.dialect
.the_message_of_the_dynamic_write_inside_a_function()
.to_string(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
));
}
let exists = self.lookup_variable(name).is_some() || self.variables.contains_key(&key);
if !exists {
if self
.dialect
.the_name_that_the_script_builds_and_that_is_not_there_is_answered()
{
self.assign(name, Value::Text(String::new()));
} else {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "Variable not found.".to_string(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
));
}
}
let is_local = self
.scopes
.last()
.map(|scope| scope.borrow().contains_key(&key))
.unwrap_or(false)
|| self.is_declared_local(&key);
if self.declarations.last().is_some() && !is_local && !self.lives_in_the_script(&key) {
return Err(RuntimeFailure::Detailed(
RuntimeError {
message: "This dynamic assignment requires a \"global\" declaration."
.to_string(),
line,
},
Detail {
what: String::new(),
extra: name.to_string(),
},
));
}
let current = self.lookup_variable(name);
let stored = self.apply_assign(op, name, current, value, line)?;
self.assign(name, stored.clone());
Ok(stored)
}
}
#[cfg(feature = "std")]
pub(crate) fn sqrt(value: f64) -> f64 {
value.sqrt()
}
#[cfg(not(feature = "std"))]
pub(crate) fn sqrt(value: f64) -> f64 {
crate::math::sqrt(value)
}
#[cfg(feature = "std")]
pub(crate) fn floor(value: f64) -> f64 {
value.floor()
}
#[cfg(not(feature = "std"))]
pub(crate) fn floor(value: f64) -> f64 {
crate::math::floor(value)
}
#[cfg(feature = "std")]
pub(crate) fn ceil(value: f64) -> f64 {
value.ceil()
}
#[cfg(not(feature = "std"))]
pub(crate) fn ceil(value: f64) -> f64 {
crate::math::ceil(value)
}
#[cfg(feature = "std")]
pub(crate) fn round(value: f64) -> f64 {
value.round()
}
#[cfg(not(feature = "std"))]
pub(crate) fn round(value: f64) -> f64 {
crate::math::round(value)
}
#[cfg(feature = "std")]
pub(crate) fn powf(base: f64, exponent: f64) -> f64 {
base.powf(exponent)
}
#[cfg(not(feature = "std"))]
pub(crate) fn powf(base: f64, exponent: f64) -> f64 {
crate::math::pow(base, exponent)
}
#[cfg(feature = "std")]
pub(crate) fn acos(value: f64) -> f64 {
value.acos()
}
#[cfg(not(feature = "std"))]
pub(crate) fn acos(value: f64) -> f64 {
crate::math::acos(value)
}
#[cfg(feature = "std")]
pub(crate) fn asin(value: f64) -> f64 {
value.asin()
}
#[cfg(not(feature = "std"))]
pub(crate) fn asin(value: f64) -> f64 {
crate::math::asin(value)
}
#[cfg(feature = "std")]
pub(crate) fn atan(value: f64) -> f64 {
value.atan()
}
#[cfg(not(feature = "std"))]
pub(crate) fn atan(value: f64) -> f64 {
crate::math::atan(value)
}
#[cfg(feature = "std")]
pub(crate) fn cos(value: f64) -> f64 {
value.cos()
}
#[cfg(not(feature = "std"))]
pub(crate) fn cos(value: f64) -> f64 {
crate::math::cos(value)
}
#[cfg(feature = "std")]
pub(crate) fn sin(value: f64) -> f64 {
value.sin()
}
#[cfg(feature = "std")]
pub(crate) fn atan2(y: f64, x: f64) -> f64 {
y.atan2(x)
}
#[cfg(not(feature = "std"))]
pub(crate) fn atan2(y: f64, x: f64) -> f64 {
crate::math::atan2(y, x)
}
#[cfg(feature = "std")]
pub(crate) fn sinh(value: f64) -> f64 {
value.sinh()
}
#[cfg(not(feature = "std"))]
pub(crate) fn sinh(value: f64) -> f64 {
crate::math::sinh(value)
}
#[cfg(feature = "std")]
pub(crate) fn cosh(value: f64) -> f64 {
value.cosh()
}
#[cfg(not(feature = "std"))]
pub(crate) fn cosh(value: f64) -> f64 {
crate::math::cosh(value)
}
#[cfg(feature = "std")]
pub(crate) fn tanh(value: f64) -> f64 {
value.tanh()
}
#[cfg(not(feature = "std"))]
pub(crate) fn tanh(value: f64) -> f64 {
crate::math::tanh(value)
}
#[cfg(not(feature = "std"))]
pub(crate) fn sin(value: f64) -> f64 {
crate::math::sin(value)
}
#[cfg(feature = "std")]
pub(crate) fn tan(value: f64) -> f64 {
value.tan()
}
#[cfg(not(feature = "std"))]
pub(crate) fn tan(value: f64) -> f64 {
crate::math::tan(value)
}
#[cfg(feature = "std")]
pub(crate) fn exp(value: f64) -> f64 {
value.exp()
}
#[cfg(not(feature = "std"))]
pub(crate) fn exp(value: f64) -> f64 {
crate::math::exp(value)
}
#[cfg(feature = "std")]
pub(crate) fn ln(value: f64) -> f64 {
value.ln()
}
#[cfg(not(feature = "std"))]
pub(crate) fn ln(value: f64) -> f64 {
crate::math::ln(value)
}
#[cfg(feature = "std")]
pub(crate) fn log10(value: f64) -> f64 {
value.log10()
}
#[cfg(not(feature = "std"))]
pub(crate) fn log10(value: f64) -> f64 {
crate::math::log10(value)
}
#[cfg(feature = "std")]
pub(crate) fn fract(value: f64) -> f64 {
value.fract()
}
#[cfg(not(feature = "std"))]
pub(crate) fn fract(value: f64) -> f64 {
value - crate::math::trunc(value)
}
#[cfg(feature = "std")]
fn trunc(value: f64) -> f64 {
value.trunc()
}
#[cfg(not(feature = "std"))]
fn trunc(value: f64) -> f64 {
crate::math::trunc(value)
}
pub(crate) fn powi(value: f64, exponent: i32) -> f64 {
let mut result = 1.0f64;
let mut factor = value;
let mut rest = exponent.unsigned_abs();
while rest > 0 {
if rest & 1 == 1 {
result *= factor;
}
factor *= factor;
rest >>= 1;
}
if exponent < 0 { 1.0 / result } else { result }
}
fn func_value(name: &str, function: &Function) -> Value {
let fewest = function
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count();
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(&mut properties, "name", Value::Text(name.to_string()));
put(&mut properties, "minparams", Value::Int(fewest as i64));
put(
&mut properties,
"maxparams",
Value::Int(function.parameters.len() as i64),
);
put(&mut properties, "isbuiltin", Value::Int(0));
put(&mut properties, "isvariadic", Value::Int(0));
put(
&mut properties,
PARAMETERS,
the_flags_of_the_parameters(&function.parameters, false),
);
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
fn closure_value(name: &str, function: &Function, captures: bool) -> Value {
let value = func_value("", function);
if let Value::Object(object) = &value {
let mut object = object.borrow_mut();
if captures {
object.class = "closure".to_string();
}
object.put(CLOSURE, Value::Text(name.to_string()));
}
value
}
fn builtin_value(name: &str, min: u8, max: u32) -> Value {
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(&mut properties, "name", Value::Text(name.to_string()));
put(&mut properties, "minparams", Value::Int(min as i64));
put(&mut properties, "maxparams", Value::Int(max as i64));
put(&mut properties, "isbuiltin", Value::Int(1));
put(&mut properties, "isvariadic", Value::Int(0));
Value::Object(Rc::new(RefCell::new(Object {
class: "func".to_string(),
properties,
})))
}
fn class_value(name: &str, class: &Class) -> Value {
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(&mut properties, CLASS_NAME, Value::Text(class.name.clone()));
put(&mut properties, "prototype", prototype_value(&class.name));
Value::Object(Rc::new(RefCell::new(Object {
class: name.to_lowercase(),
properties,
})))
}
fn the_text_of_the_parameter(parameter: &crate::ast::LegacyParameter) -> String {
match parameter {
crate::ast::LegacyParameter::Text(text) => text.trim().to_string(),
crate::ast::LegacyParameter::Expression(_) => String::new(),
}
}
fn the_parameter_that_failed(message: &str, values: &[Value]) -> String {
let Some(rest) = message.strip_prefix("Parameter #") else {
return String::new();
};
let Some((number, _)) = rest.split_once(" of ") else {
return String::new();
};
let Ok(number) = number.parse::<usize>() else {
return String::new();
};
values
.get(number.saturating_sub(1))
.map(the_extra_of_the_value)
.unwrap_or_default()
}
pub(crate) fn the_extra_of_the_value(value: &Value) -> String {
match value {
Value::Text(text) if text.is_empty() => "empty string".to_string(),
Value::Text(text) => text.clone(),
Value::Int(_) | Value::Float(_) => value.to_text(),
Value::List(_) | Value::Object(_) | Value::Reference(_) => String::new(),
Value::Unset | Value::Skipped => String::new(),
}
}
pub(crate) fn prototype_value(name: &str) -> Value {
let mut properties: BTreeMap<String, Property> = BTreeMap::new();
put(&mut properties, CLASS_NAME, Value::Text(name.to_string()));
Value::Object(Rc::new(RefCell::new(Object {
class: "prototype".to_string(),
properties,
})))
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum IntegerFormat {
Decimal,
Hexadecimal,
HexadecimalLower,
}
impl IntegerFormat {
pub fn name(&self) -> &'static str {
match self {
IntegerFormat::Decimal => "D",
IntegerFormat::Hexadecimal => "H",
IntegerFormat::HexadecimalLower => "h",
}
}
pub fn the_text_of(&self, number: i64) -> String {
match self {
IntegerFormat::Decimal => number.to_string(),
IntegerFormat::Hexadecimal => the_hexadecimal_text_of(number, true),
IntegerFormat::HexadecimalLower => the_hexadecimal_text_of(number, false),
}
}
}
fn the_hexadecimal_text_of(number: i64, upper: bool) -> String {
let sign = if number < 0 { "-" } else { "" };
let digits = number.unsigned_abs();
if upper {
format!("{sign}0x{digits:X}")
} else {
format!("{sign}0x{digits:x}")
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FloatFormat {
pub width: u32,
pub zeroes: bool,
pub left: bool,
pub decimals: u32,
pub scientific: bool,
pub upper: bool,
}
impl FloatFormat {
pub const DEFAULT: FloatFormat = FloatFormat {
width: 0,
zeroes: false,
left: false,
decimals: 6,
scientific: false,
upper: false,
};
pub fn name(&self) -> String {
let mut name = String::new();
if self.left {
name.push('-');
}
if self.zeroes {
name.push('0');
}
name.push_str(&self.width.to_string());
name.push('.');
name.push_str(&self.decimals.to_string());
if self.scientific {
name.push(if self.upper { 'E' } else { 'e' });
}
name
}
pub fn the_text_of(&self, number: f64) -> String {
if number.is_infinite() {
return if number < 0.0 {
"-1.#INF00".to_string()
} else {
"1.#INF00".to_string()
};
}
let decimals = self.decimals as usize;
let text = if self.scientific {
let formatted = format!("{:.*e}", decimals, number);
let (mantissa, exponent) = match formatted.split_once('e') {
Some((mantissa, exponent)) => (mantissa.to_string(), exponent.to_string()),
None => (formatted.clone(), String::new()),
};
let exponent = match exponent.strip_prefix('-') {
Some(rest) => format!("-{}", the_digits_of_the_exponent(rest)),
None => format!("+{}", the_digits_of_the_exponent(&exponent)),
};
format!("{mantissa}e{exponent}")
} else {
the_text_of_the_number(number, decimals)
};
let width = self.width as usize;
if text.chars().count() >= width {
return text;
}
let padding = width - text.chars().count();
if self.zeroes {
let (sign, rest) = match text.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", text.as_str()),
};
let mut padded = String::from(sign);
padded.push_str(&"0".repeat(padding));
padded.push_str(rest);
padded
} else if self.left {
let mut padded = text;
padded.push_str(&" ".repeat(padding));
padded
} else {
let mut padded = " ".repeat(padding);
padded.push_str(&text);
padded
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CaseSense {
Off,
On,
Locale,
}
impl CaseSense {
pub fn name(&self) -> &'static str {
match self {
CaseSense::Off => "Off",
CaseSense::On => "On",
CaseSense::Locale => "Locale",
}
}
pub fn the_method(&self) -> CaseMethod {
match self {
CaseSense::Off => CaseMethod::Ascii,
CaseSense::On => CaseMethod::Exact,
CaseSense::Locale => CaseMethod::Locale,
}
}
pub fn the_method_of_the_equal_sign(&self) -> CaseMethod {
match self {
CaseSense::Off => CaseMethod::Ascii,
CaseSense::On | CaseSense::Locale => CaseMethod::Locale,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CaseMethod {
Ascii,
Exact,
Locale,
}
pub(crate) fn the_same_text(left: &str, right: &str, method: CaseMethod) -> bool {
match method {
CaseMethod::Ascii => left.eq_ignore_ascii_case(right),
CaseMethod::Exact => left == right,
CaseMethod::Locale => left.to_lowercase() == right.to_lowercase(),
}
}
pub(crate) fn the_same_number(left: &Value, right: &Value) -> bool {
match (left, right) {
(Value::Int(one), Value::Int(other)) => one == other,
_ => left.to_number() == right.to_number(),
}
}
pub(crate) fn the_text_contains(haystack: &str, needle: &str, method: CaseMethod) -> bool {
match method {
CaseMethod::Ascii => haystack
.to_ascii_lowercase()
.contains(&needle.to_ascii_lowercase()),
CaseMethod::Exact => haystack.contains(needle),
CaseMethod::Locale => haystack.to_lowercase().contains(&needle.to_lowercase()),
}
}
pub(crate) fn the_order_of_the_texts(
left: &str,
right: &str,
method: CaseMethod,
) -> core::cmp::Ordering {
match method {
CaseMethod::Ascii => {
let left = left.to_ascii_lowercase();
let right = right.to_ascii_lowercase();
left.cmp(&right)
}
CaseMethod::Exact => left.cmp(right),
CaseMethod::Locale => left.to_lowercase().cmp(&right.to_lowercase()),
}
}
fn the_digits_of_the_exponent(digits: &str) -> String {
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
"000".to_string()
} else if digits.len() < 3 {
format!("0{digits:0>2}")
} else {
digits.to_string()
}
}
fn the_text_of_the_number(number: f64, decimals: usize) -> String {
let negative = number < 0.0;
let exact = format!("{:.16e}", number.abs());
let (mantissa, exponent) = match exact.split_once('e') {
Some((mantissa, exponent)) => (mantissa, exponent),
None => (exact.as_str(), "0"),
};
let digits: String = mantissa
.chars()
.filter(|character| character.is_ascii_digit())
.collect();
let exponent: i32 = exponent.parse().unwrap_or(0);
let point = exponent + 1;
let mut whole = String::new();
let mut fraction = String::new();
if point <= 0 {
whole.push('0');
for _ in 0..-point {
fraction.push('0');
}
fraction.push_str(&digits);
} else {
let point = point as usize;
if point >= digits.len() {
whole.push_str(&digits);
for _ in 0..point - digits.len() {
whole.push('0');
}
} else {
whole.push_str(&digits[..point]);
fraction.push_str(&digits[point..]);
}
}
if fraction.len() > decimals {
if fraction.as_bytes()[decimals] >= b'5' {
let mut index = decimals;
let mut carries = true;
while carries && index > 0 {
index -= 1;
let digit = fraction.as_bytes()[index] - b'0';
if digit == 9 {
fraction.replace_range(index..index + 1, "0");
} else {
fraction.replace_range(index..index + 1, &format!("{}", digit + 1));
carries = false;
}
}
if carries {
let mut index = whole.len();
let mut carries = true;
while carries && index > 0 {
index -= 1;
let digit = whole.as_bytes()[index] - b'0';
if digit == 9 {
whole.replace_range(index..index + 1, "0");
} else {
whole.replace_range(index..index + 1, &format!("{}", digit + 1));
carries = false;
}
}
if carries {
whole.insert(0, '1');
}
}
}
fraction.truncate(decimals);
} else {
for _ in fraction.len()..decimals {
fraction.push('0');
}
}
let mut text = String::new();
if negative {
text.push('-');
}
text.push_str(&whole);
if decimals > 0 {
text.push('.');
text.push_str(&fraction);
}
text
}
pub(crate) fn as_error(failure: RuntimeFailure, line: u32) -> RuntimeError {
match failure {
RuntimeFailure::Error(error) => error,
RuntimeFailure::Detailed(error, _) => error,
_ => RuntimeError {
message: "the runtime cannot answer that.".into(),
line,
},
}
}
fn the_fields_of_a_csv(text: &str) -> Vec<String> {
if text.is_empty() {
return Vec::new();
}
let characters: Vec<char> = text.chars().collect();
let mut fields = Vec::new();
let mut index = 0;
loop {
let mut field = String::new();
if characters.get(index) == Some(&'"') {
index += 1;
loop {
match characters.get(index) {
None => break,
Some('"') => {
if characters.get(index + 1) == Some(&'"') {
field.push('"');
index += 2;
} else {
index += 1;
break;
}
}
Some(character) => {
field.push(*character);
index += 1;
}
}
}
while let Some(character) = characters.get(index) {
if *character == ',' {
break;
}
index += 1;
}
} else {
while let Some(character) = characters.get(index) {
if *character == ',' {
break;
}
field.push(*character);
index += 1;
}
}
fields.push(field);
if characters.get(index) == Some(&',') {
index += 1;
if index >= characters.len() {
fields.push(String::new());
break;
}
continue;
}
break;
}
fields
}
pub(crate) fn split_on_any(text: &str, delimiters: &str) -> Vec<String> {
let mut pieces: Vec<String> = Vec::new();
let mut current = String::new();
for character in text.chars() {
if delimiters.contains(character) {
pieces.push(core::mem::take(&mut current));
continue;
}
current.push(character);
}
pieces.push(current);
pieces
}
fn values_equal(left: &Value, right: &Value, case_sensitive: bool) -> bool {
values_equal_with(
left,
right,
if case_sensitive {
CaseMethod::Exact
} else {
CaseMethod::Ascii
},
)
}
fn values_equal_with(left: &Value, right: &Value, method: CaseMethod) -> bool {
if let (Value::Object(one), Value::Object(other)) = (left, right) {
return Rc::ptr_eq(one, other);
}
if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_)) {
return false;
}
match (left, right) {
(Value::Text(one), Value::Text(other)) => {
return the_same_text(one, other, method);
}
(Value::Text(text), Value::Int(number)) | (Value::Int(number), Value::Text(text)) => {
return match the_number_of_a_text(text) {
Some(number_of_the_text) => number_of_the_text == *number as f64,
None => the_same_text(text, &number.to_string(), method),
};
}
(Value::Text(text), Value::Float(number)) | (Value::Float(number), Value::Text(text)) => {
return match the_number_of_a_text(text) {
Some(number_of_the_text) => number_of_the_text == *number,
None => the_same_text(text, &Value::Float(*number).to_text(), method),
};
}
_ => {}
}
if let (Some(a), Some(b)) = (left.to_number(), right.to_number()) {
return a == b;
}
the_same_text(&left.to_text(), &right.to_text(), method)
}
fn the_member_is_missing(failure: &RuntimeFailure) -> bool {
matches!(
failure,
RuntimeFailure::Error(error) | RuntimeFailure::Detailed(error, _)
if matches!(
crate::classes::error::the_class_of(&error.message),
"PropertyError" | "MethodError" | "UnsetItemError"
)
)
}
fn the_member_is_not_there(failure: &RuntimeFailure) -> bool {
matches!(
failure,
RuntimeFailure::Error(error) | RuntimeFailure::Detailed(error, _)
if matches!(
crate::classes::error::the_class_of(&error.message),
"PropertyError" | "UnsetError" | "UnsetItemError" | "MemberError"
)
)
}
pub(crate) fn the_failure_is_an_unset_variable(failure: &RuntimeFailure) -> bool {
matches!(
failure,
RuntimeFailure::Error(error) | RuntimeFailure::Detailed(error, _)
if crate::classes::error::the_class_of(&error.message) == "UnsetError"
)
}
pub(crate) fn the_message_of(failure: &RuntimeFailure) -> String {
match failure {
RuntimeFailure::Error(error) => error.message.clone(),
RuntimeFailure::Detailed(error, _) => error.message.clone(),
RuntimeFailure::Fatal(error) => error.message.clone(),
RuntimeFailure::Thrown(value) => thrown_message(value),
RuntimeFailure::Timeout(timeout) => timeout.to_string(),
RuntimeFailure::Flow(_) => "the script left a block in the middle of it.".to_string(),
}
}
fn number_of(properties: &BTreeMap<String, Property>, name: &str) -> i64 {
properties
.get(name)
.map(|property| property.value.to_number().unwrap_or(0.0) as i64)
.unwrap_or(0)
}
fn the_key_of_a_declaration(line: u32, name: &str) -> String {
format!("{}:{}", line, the_key_of(name))
}
fn the_key_of(name: &str) -> String {
name.to_lowercase()
}
fn thrown_message(value: &Value) -> String {
match value {
Value::Text(text) => format!("Unhandled exception.\n Specifically: {text}"),
Value::Object(object) => {
let borrowed = object.borrow();
if crate::classes::error::is_a_class(&borrowed.class) {
if let Some(Value::Text(message)) = borrowed.value_of("message") {
if !message.is_empty() {
return message;
}
}
}
"Unhandled exception.".to_string()
}
_ => "Unhandled exception.".to_string(),
}
}
fn the_place_of_the_label(statements: &[Node], name: &str) -> Option<usize> {
statements.iter().position(|statement| match statement {
Node::Label { name: label, .. } => label.eq_ignore_ascii_case(name),
_ => false,
})
}
fn the_labels_of(body: &[Node]) -> Vec<String> {
let mut labels = Vec::new();
collect_the_labels(body, &mut labels);
labels
}
fn collect_the_labels(body: &[Node], labels: &mut Vec<String>) {
for statement in body {
match statement {
Node::Label { name, .. } => labels.push(name.clone()),
Node::HotkeyDefinition { body, .. } => collect_the_labels(body, labels),
Node::If {
branches,
otherwise,
..
} => {
for branch in branches {
collect_the_labels(&branch.body, labels);
}
collect_the_labels(otherwise, labels);
}
Node::Switch { cases, .. } => {
for case in cases {
collect_the_labels(&case.body, labels);
}
}
Node::Block { body, .. }
| Node::While { body, .. }
| Node::Loop { body, .. }
| Node::For { body, .. } => {
collect_the_labels(body, labels);
}
Node::LegacyIf {
body, otherwise, ..
} => {
collect_the_labels(body, labels);
collect_the_labels(otherwise, labels);
}
Node::Try {
body,
catches,
otherwise,
finally,
..
} => {
collect_the_labels(body, labels);
for catch in catches {
collect_the_labels(&catch.body, labels);
}
collect_the_labels(otherwise, labels);
collect_the_labels(finally, labels);
}
_ => {}
}
}
}
pub fn the_builtin_in(
dialect: &'static dyn crate::dialect::Dialect,
name: &str,
) -> Option<&'static crate::builtins::Builtin> {
let wanted = name.to_lowercase();
dialect
.builtins()
.iter()
.find(|builtin| builtin.name.to_lowercase() == wanted)
.or_else(|| dialect.the_builtin_of_the_extension(&wanted))
}
pub fn op_name(statement: &Node) -> &str {
op_name_in(statement, crate::dialect::v2())
}
pub fn op_name_in<'a>(
statement: &'a Node,
dialect: &'static dyn crate::dialect::Dialect,
) -> &'a str {
match statement {
Node::Assign { .. } => "Assign",
Node::AssignIndex { .. } => "AssignIndex",
Node::Call { name, .. } => match the_builtin_in(dialect, name) {
Some(builtin) => builtin.name,
None => "Call",
},
Node::LegacyCall { name, .. } => name,
Node::New { .. } => "New",
Node::LegacyIf { name, .. } => name,
Node::Expression { value, .. } => match the_call_of(value) {
Some(name) => match the_builtin_in(dialect, name) {
Some(builtin) => builtin.name,
None => "Call",
},
None => "Expression",
},
Node::Block { .. } => "Block",
Node::If { .. } => "If",
Node::Switch { .. } => "Switch",
Node::While { .. } => "While",
Node::Try { .. } => "Try",
Node::Throw { .. } => "Throw",
Node::Declare { .. } => "Declare",
Node::Super { .. } => "Super",
Node::Loop { .. } => "Loop",
Node::ArrayLiteral { .. } => "ArrayLiteral",
Node::ObjectLiteral { .. } => "ObjectLiteral",
Node::Lambda { .. } => "Lambda",
Node::For { .. } => "For",
Node::Directive { name, .. } => name,
Node::Break { .. } => "Break",
Node::Continue { .. } => "Continue",
Node::Spread { .. } => "Spread",
Node::Label { .. } => "Label",
Node::Goto { .. } => "Goto",
Node::GotoComputed { .. } => "GotoComputed",
Node::HotkeyDefinition { .. } => "HotkeyDefinition",
Node::Return { .. } => "Return",
Node::ExitApp { .. } => "ExitApp",
Node::FunctionDef { .. } => "FunctionDef",
Node::ClassDef { .. } => "ClassDef",
Node::MethodCall { .. } => "MethodCall",
Node::CallValue { .. } => "CallValue",
Node::Property { .. } => "Property",
Node::AssignProperty { .. } => "AssignProperty",
Node::Literal { .. } => "Literal",
Node::Var { .. } => "Var",
Node::Unary { .. } => "Unary",
Node::Binary { .. } => "Binary",
Node::Unset { .. } => "Unset",
Node::Ternary { .. } => "Ternary",
Node::DynamicName { .. } => "DynamicName",
Node::AssignDynamic { .. } => "AssignDynamic",
Node::Index { .. } => "Index",
Node::Group { .. } => "Group",
Node::Maybe { .. } => "Maybe",
Node::Empty { .. } => "Empty",
Node::Legacy { .. } => "Legacy",
Node::LegacyExpression { .. } => "LegacyExpression",
Node::LegacyControl { .. } => "LegacyControl",
Node::LegacyAssign { .. } => "LegacyAssign",
Node::LegacyComparison { .. } => "LegacyComparison",
Node::LegacyMatch { .. } => "LegacyMatch",
}
}
fn the_call_of(node: &Node) -> Option<&str> {
match node {
Node::Call { name, .. } => Some(name),
Node::Property { target, .. }
| Node::Index { target, .. }
| Node::MethodCall { target, .. } => the_call_of(target),
_ => None,
}
}
pub(crate) enum RuntimeFailure {
Error(RuntimeError),
Detailed(RuntimeError, Detail),
Fatal(RuntimeError),
Thrown(Value),
Timeout(Timeout),
Flow(Flow),
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Detail {
pub what: String,
pub extra: String,
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Route {
Written,
ThroughValue,
ThroughTheCall,
}
impl From<RuntimeError> for RuntimeFailure {
fn from(error: RuntimeError) -> Self {
RuntimeFailure::Error(error)
}
}
impl From<Timeout> for RuntimeFailure {
fn from(timeout: Timeout) -> Self {
RuntimeFailure::Timeout(timeout)
}
}
impl From<Flow> for RuntimeFailure {
fn from(flow: Flow) -> Self {
RuntimeFailure::Flow(flow)
}
}
impl From<String> for RuntimeFailure {
fn from(message: String) -> Self {
RuntimeFailure::Error(RuntimeError { message, line: 0 })
}
}
mod the_requirement {
use crate::dialect::Dialect;
use alloc::vec::Vec;
use core::cmp::Ordering;
#[derive(Clone, Copy)]
enum Range {
AtLeast,
SameMajorAtLeast,
Greater,
Less,
AtMost,
Equal,
NotEqual,
}
pub fn met(dialect: &'static dyn Dialect, argument: &str) -> bool {
let fields: Vec<&str> = argument.split_whitespace().collect();
if fields.len() == 1 {
let word = fields[0];
if word.eq_ignore_ascii_case(dialect.name()) || word.eq_ignore_ascii_case("autohotkey")
{
return true;
}
}
if fields.is_empty() || !fields[0].eq_ignore_ascii_case("autohotkey") {
return false;
}
let Some(requirement) = fields.get(1) else {
return true;
};
if fields.len() > 2 {
return false;
}
let Some((range, required)) = parse(requirement) else {
return false;
};
range.met_by(&required, &dialect.version())
}
impl Range {
fn met_by(self, required: &[u32], current: &(u16, u16, u16, u16)) -> bool {
let current = [
current.0 as u32,
current.1 as u32,
current.2 as u32,
current.3 as u32,
];
let order = compare_versions(¤t, required);
match self {
Range::AtLeast => order.is_ge(),
Range::SameMajorAtLeast => {
required.first().copied().unwrap_or(0) == current[0] && order.is_ge()
}
Range::Greater => order.is_gt(),
Range::Less => order.is_lt(),
Range::AtMost => order.is_le(),
Range::Equal => order.is_eq(),
Range::NotEqual => !order.is_eq(),
}
}
}
fn parse(requirement: &str) -> Option<(Range, Vec<u32>)> {
let mut text = requirement;
let mut range = Range::SameMajorAtLeast;
let operators: [(&str, Range); 6] = [
("<=", Range::AtMost),
(">=", Range::AtLeast),
("<>", Range::NotEqual),
("<", Range::Less),
(">", Range::Greater),
("=", Range::Equal),
];
for (prefix, kind) in operators {
if let Some(rest) = text.strip_prefix(prefix) {
range = kind;
text = rest;
break;
}
}
if let Some(rest) = text.strip_prefix('+') {
range = Range::SameMajorAtLeast;
text = rest;
}
if let Some(rest) = text.strip_suffix('+') {
range = Range::SameMajorAtLeast;
text = rest;
}
if let Some(rest) = text.strip_prefix('v').or_else(|| text.strip_prefix('V')) {
text = rest;
}
if let Some(rest) = text.strip_suffix('-') {
text = rest;
}
let mut parts = Vec::new();
for part in text.split('.') {
if part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
parts.push(part.parse::<u32>().ok()?);
}
if parts.is_empty() || parts.len() > 5 {
return None;
}
Some((range, parts))
}
fn compare_versions(current: &[u32], required: &[u32]) -> Ordering {
let length = current.len().max(required.len());
for index in 0..length {
let here = current.get(index).copied().unwrap_or(0);
let there = required.get(index).copied().unwrap_or(0);
match here.cmp(&there) {
Ordering::Equal => {}
other => return other,
}
}
Ordering::Equal
}
}