use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::collections::BTreeSet;
use alloc::collections::VecDeque;
use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::time::Duration;
use core::cell::RefCell;
use crate::ast::{
AccessBody, AccessDef, AssignOp, BinaryOp, Declarations, DeclareKind, DynamicPiece, LegacyForm,
LiteralValue, LoopKind, MemberName, MethodDef, Node, ObjectItem, Parameter, PropertyDef,
UnaryOp,
};
use crate::hotkeys::Condition;
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";
const THE_GAP_OF_A_WAIT: u64 = 5;
#[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)
}
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,
}
}
fn the_operator_is_a_comparison(op: &BinaryOp) -> bool {
matches!(
op,
BinaryOp::Equal
| BinaryOp::NotEqual
| BinaryOp::StrictEqual
| BinaryOp::StrictNotEqual
| BinaryOp::Less
| BinaryOp::Greater
| BinaryOp::LessEqual
| BinaryOp::GreaterEqual
)
}
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 => matches!(
value,
Value::Object(object) if object.borrow().class == "comvalue"
),
_ => 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,
dialect: &'static dyn crate::dialect::Dialect,
) -> Result<Option<Condition>, ()> {
let text = argument.trim();
if text.is_empty() {
return Ok(None);
}
if let Some(open) = text.find('(') {
let name = text[..open].trim().to_lowercase();
if let Some(close) = text.rfind(')') {
if close > open {
let inside = text[open + 1..close].trim();
if inside.is_empty() {
if !name.is_empty()
&& name
.chars()
.all(|letter| letter.is_alphanumeric() || letter == '_')
{
return Ok(Some(Condition::Function(name)));
}
} else if let Some(title) = inside
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
{
if !title.contains('"') {
let condition = match name.as_str() {
"winactive" => Some(Condition::WindowActive(title.into())),
"winexist" => Some(Condition::WindowExists(title.into())),
"winnotactive" => Some(Condition::WindowNotActive(title.into())),
"winnotexist" => Some(Condition::WindowNotExist(title.into())),
_ => None,
};
if let Some(condition) = condition {
return Ok(Some(condition));
}
}
}
}
}
}
match crate::parser::parse_the_expression(text, dialect) {
Ok(node) => Ok(Some(Condition::Expression {
node,
text: text.to_string(),
})),
Err(_) => Err(()),
}
}
fn the_condition_of_a_v1_if(
name: &str,
argument: &str,
dialect: &'static dyn crate::dialect::Dialect,
) -> Result<Option<Condition>, ()> {
match name {
"if" => the_condition_of_a_hotif(argument, dialect),
"ifwinactive" => {
let title = argument.split(',').next().unwrap_or("").trim();
let title = title.trim_matches('"');
if title.is_empty() {
return Ok(None);
}
Ok(Some(Condition::WindowActive(title.into())))
}
_ => Ok(None),
}
}
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,
}
}
fn the_number_of_a_directive(
argument: &str,
name: &str,
line: u32,
) -> Result<f64, RuntimeFailure> {
let argument = argument.trim();
let argument = argument.strip_prefix(',').unwrap_or(argument).trim();
match argument.parse::<f64>() {
Ok(number) => Ok(number),
Err(_) => Err(RuntimeFailure::Error(RuntimeError {
message: format!("Parameter #1 of {name} is invalid."),
line,
})),
}
}
pub fn refusal_of_directive(_name: &str) -> Option<&'static str> {
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 BOUND_ARGS: &str = "bound arguments";
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";
#[cfg(feature = "std")]
pub struct SharedCell<T>(std::sync::Arc<ReentrantInner<T>>);
#[cfg(not(feature = "std"))]
pub struct SharedCell<T>(alloc::rc::Rc<core::cell::RefCell<T>>);
#[cfg(feature = "std")]
struct ReentrantInner<T> {
data: core::cell::UnsafeCell<T>,
state: std::sync::Mutex<LockState>,
ready: std::sync::Condvar,
}
#[cfg(feature = "std")]
struct LockState {
owner: Option<std::thread::ThreadId>,
count: usize,
}
#[cfg(feature = "std")]
unsafe impl<T: Send> Send for ReentrantInner<T> {}
#[cfg(feature = "std")]
unsafe impl<T: Send> Sync for ReentrantInner<T> {}
#[cfg(feature = "std")]
pub struct ReentrantGuard<'a, T> {
inner: &'a ReentrantInner<T>,
}
#[cfg(feature = "std")]
impl<T> core::ops::Deref for ReentrantGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.inner.data.get() }
}
}
#[cfg(feature = "std")]
impl<T> core::ops::DerefMut for ReentrantGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.data.get() }
}
}
#[cfg(feature = "std")]
impl<T> Drop for ReentrantGuard<'_, T> {
fn drop(&mut self) {
let mut state = self.inner.state.lock().unwrap();
state.count -= 1;
if state.count == 0 {
state.owner = None;
self.inner.ready.notify_one();
}
}
}
#[cfg(feature = "std")]
pub type CellGuard<'a, T> = ReentrantGuard<'a, T>;
#[cfg(not(feature = "std"))]
pub type CellGuard<'a, T> = core::cell::Ref<'a, T>;
#[cfg(feature = "std")]
pub type CellGuardMut<'a, T> = ReentrantGuard<'a, T>;
#[cfg(not(feature = "std"))]
pub type CellGuardMut<'a, T> = core::cell::RefMut<'a, T>;
impl<T> SharedCell<T> {
pub fn new(value: T) -> Self {
#[cfg(feature = "std")]
return SharedCell(std::sync::Arc::new(ReentrantInner {
data: core::cell::UnsafeCell::new(value),
state: std::sync::Mutex::new(LockState {
owner: None,
count: 0,
}),
ready: std::sync::Condvar::new(),
}));
#[cfg(not(feature = "std"))]
return SharedCell(alloc::rc::Rc::new(core::cell::RefCell::new(value)));
}
pub fn borrow(&self) -> CellGuard<'_, T> {
#[cfg(feature = "std")]
return self.lock();
#[cfg(not(feature = "std"))]
return self.0.borrow();
}
pub fn borrow_mut(&self) -> CellGuardMut<'_, T> {
#[cfg(feature = "std")]
return self.lock();
#[cfg(not(feature = "std"))]
return self.0.borrow_mut();
}
#[cfg(feature = "std")]
fn lock(&self) -> ReentrantGuard<'_, T> {
let me = std::thread::current().id();
let mut state = self.0.state.lock().unwrap();
loop {
match state.owner {
Some(owner) if owner == me => {
state.count += 1;
break;
}
None => {
state.owner = Some(me);
state.count = 1;
break;
}
Some(_) => {
state = self.0.ready.wait(state).unwrap();
}
}
}
drop(state);
ReentrantGuard { inner: &self.0 }
}
#[cfg(feature = "std")]
fn try_lock(&self) -> Option<ReentrantGuard<'_, T>> {
let me = std::thread::current().id();
let mut state = self.0.state.lock().unwrap();
match state.owner {
Some(owner) if owner == me => {
state.count += 1;
drop(state);
Some(ReentrantGuard { inner: &self.0 })
}
None => {
state.owner = Some(me);
state.count = 1;
drop(state);
Some(ReentrantGuard { inner: &self.0 })
}
Some(_) => None,
}
}
pub(crate) fn ptr_eq(a: &Self, b: &Self) -> bool {
#[cfg(feature = "std")]
return std::sync::Arc::ptr_eq(&a.0, &b.0);
#[cfg(not(feature = "std"))]
return alloc::rc::Rc::ptr_eq(&a.0, &b.0);
}
pub(crate) fn as_ptr(cell: &Self) -> *const core::ffi::c_void {
#[cfg(feature = "std")]
return std::sync::Arc::as_ptr(&cell.0) as *const core::ffi::c_void;
#[cfg(not(feature = "std"))]
return alloc::rc::Rc::as_ptr(&cell.0) as *const core::ffi::c_void;
}
}
impl<T> Clone for SharedCell<T> {
fn clone(&self) -> Self {
SharedCell(self.0.clone())
}
}
impl<T: PartialEq> PartialEq for SharedCell<T> {
fn eq(&self, other: &Self) -> bool {
if Self::ptr_eq(self, other) {
return true;
}
*self.borrow() == *other.borrow()
}
}
impl<T: core::fmt::Debug> core::fmt::Debug for SharedCell<T> {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(feature = "std")]
match self.try_lock() {
Some(guard) => guard.fmt(formatter),
None => formatter.write_str("SharedCell { locked }"),
}
#[cfg(not(feature = "std"))]
match self.0.try_borrow() {
Ok(guard) => guard.fmt(formatter),
Err(_) => formatter.write_str("SharedCell { borrowed }"),
}
}
}
type ScopeTable = SharedCell<BTreeMap<String, Value>>;
type TheMemoryOfTheVariables = RefCell<BTreeMap<(u8, String), Box<[u8]>>>;
#[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(SharedCell<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 value_ref(&self, key: &str) -> Option<&Value> {
self.properties.get(key).map(|property| &property.value)
}
pub fn value_mut(&mut self, key: &str) -> Option<&mut Value> {
self.properties.get_mut(key).map(|property| &mut property.value)
}
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>,
pub is_struct: bool,
pub fields: Vec<crate::ast::FieldDef>,
}
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();
}
crate::classes::the_spelling_of(&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 {}
type TheMessage = (i64, i64, i64, i64, Vec<(Value, Vec<Value>)>);
pub trait Clock {
fn now_ms(&self) -> u64;
fn since_the_machine_started(&self) -> Option<u64> {
None
}
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
}
#[cfg(windows)]
fn since_the_machine_started(&self) -> Option<u64> {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetTickCount() -> u32;
}
Some(unsafe { GetTickCount() } as u64)
}
#[cfg(not(windows))]
fn since_the_machine_started(&self) -> Option<u64> {
None
}
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 since_the_machine_started(&self) -> Option<u64> {
match self {
ClockSource::Borrowed(clock) => clock.since_the_machine_started(),
#[cfg(feature = "std")]
ClockSource::System(clock) => clock.since_the_machine_started(),
}
}
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 slow: 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 reload: bool,
pub elapsed_ms: u64,
pub variables: BTreeMap<String, Value>,
}
pub(crate) enum Flow {
Break(u32),
Continue(u32),
Return(Option<Value>),
Exit(i32),
Reload,
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>,
closure_frames: Vec<String>,
}
struct Timer {
name: String,
function: Option<Value>,
period: u64,
once: bool,
last: u64,
priority: i64,
}
#[derive(Clone)]
pub(crate) struct Callback {
pub name: String,
pub line: u32,
}
#[derive(Debug, Clone)]
struct Frame {
name: String,
line: u32,
closed_frames: Vec<String>,
parameters: BTreeSet<String>,
force_local: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThreadState {
pub priority: i64,
pub uninterruptible_ms: i64,
pub uninterruptible_lines: i64,
pub allow_timers: bool,
}
impl Default for ThreadState {
fn default() -> Self {
Self {
priority: 0,
uninterruptible_ms: 0,
uninterruptible_lines: 0,
allow_timers: true,
}
}
}
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>,
the_warning_of_the_unset_read: Option<(u32, String, crate::warnings::WarningMode)>,
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>,
#[cfg(feature = "std")]
shared_globals: Option<crate::desktop::SharedGlobals>,
guis: Vec<Value>,
pointers: Vec<(Value, i64)>,
buffer_addresses: Vec<(i64, Value)>,
groups: Vec<(String, Vec<String>)>,
last_window: Option<String>,
last_window_of_the_v1: Option<String>,
default_listview_of_the_v1: Option<(String, u64)>,
default_window_of_the_v1: String,
default_treeview_of_the_v1: Option<(String, u64)>,
clipboard_watcher: Option<String>,
menus_of_the_v1: Vec<crate::v1::menus::TheMenu>,
the_callback_of_a_menu_that_is_waiting: Option<String>,
message_handlers: BTreeMap<i64, Value>,
legacy_message_handlers: BTreeMap<i64, String>,
image_lists: Vec<(i64, Vec<i64>)>,
image_list_addresses: i64,
icon_of_the_script: Option<(String, i64)>,
tray_menu: Option<Value>,
initial_working_dir: Option<String>,
scopes: Vec<ScopeTable>,
label_scopes: Vec<Vec<String>>,
in_the_body_of_a_hotkey: bool,
in_the_pump: bool,
a_hotkey_is_being_dispatched: bool,
critical: bool,
the_events_that_wait: Vec<String>,
the_jump_the_pump_asked_for: Option<RuntimeFailure>,
declarations: Vec<Declarations>,
super_globals: BTreeSet<String>,
the_name_is_built: bool,
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>,
script_path: Option<String>,
script_args: Vec<String>,
thread_state: ThreadState,
interrupt_last_ms: u64,
interrupt_lines: u64,
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: VecDeque<Step>,
slow_steps: Vec<Step>,
details_formatted: usize,
output: Vec<String>,
notes: Vec<String>,
started_ms: u64,
steps_taken: usize,
depth: usize,
stack_base: usize,
stack_budget: usize,
timers: Vec<Timer>,
posted_callbacks: Vec<Callback>,
the_statements_of_the_script: Rc<Vec<Node>>,
hotkeys: Vec<crate::hotkeys::Hotkey>,
exit_requested: Option<i32>,
exit_callbacks: Vec<Callback>,
error_callbacks: Vec<Callback>,
try_active: usize,
failure_hidden: bool,
caught_value: Option<Value>,
string_capacities: BTreeMap<(u8, String), i64>,
string_memory: RefCell<Vec<String>>,
string_buffers: RefCell<Vec<Option<Box<[u16]>>>>,
variable_memory: TheMemoryOfTheVariables,
owned_memory: TheMemoryOfTheVariables,
builtin_values: RefCell<BTreeMap<String, Value>>,
random_seed: u64,
hotkeys_are_not_watched: bool,
callbacks_running: u32,
hotif_condition: Option<crate::hotkeys::Condition>,
finally_labels: Vec<Vec<String>>,
suspended: bool,
paused: bool,
persistent: bool,
resident: bool,
no_budget: bool,
#[cfg(feature = "std")]
trace: bool,
the_desktop_cannot_wait: bool,
suspend_exempt: bool,
hotkey_is_exempt: Vec<bool>,
hotkey_was_enabled: Vec<bool>,
reload_requested: bool,
thrown_value: Option<Value>,
thread: 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_RECORDED_STEPS: usize = 4_000;
pub const MAX_SLOW_STEPS: usize = 64;
pub const MAX_FORMATTED_DETAILS: usize = 50_000;
pub const MAX_DETAIL_CHARS: usize = 240;
pub const SLOW_STEP_MS: u64 = 100;
pub const MAX_ALIAS_DEPTH: usize = 64;
pub const MAX_DEPTH: usize = 1000;
pub const MAX_STACK: usize = 8 * 1024 * 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 {
string_capacities: BTreeMap::new(),
string_memory: RefCell::new(Vec::new()),
string_buffers: RefCell::new(Vec::new()),
variable_memory: RefCell::new(BTreeMap::new()),
owned_memory: RefCell::new(BTreeMap::new()),
builtin_values: RefCell::new(BTreeMap::new()),
random_seed: 0,
hotkeys_are_not_watched: false,
callbacks_running: 0,
in_the_pump: false,
a_hotkey_is_being_dispatched: false,
critical: false,
the_events_that_wait: Vec::new(),
the_jump_the_pump_asked_for: None,
hotif_condition: None,
finally_labels: Vec::new(),
suspended: false,
paused: false,
persistent: false,
resident: false,
no_budget: false,
#[cfg(feature = "std")]
#[cfg(feature = "std")]
trace: the_trace_is_asked(),
the_desktop_cannot_wait: false,
suspend_exempt: false,
hotkey_is_exempt: Vec::new(),
hotkey_was_enabled: Vec::new(),
reload_requested: false,
thrown_value: None,
thread: None,
desktop,
clock: ClockSource::System(SystemClock::new()),
dialect: crate::dialect::v2(),
no_env: false,
warnings: Vec::new(),
the_warning_of_the_unset_read: None,
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(),
#[cfg(feature = "std")]
shared_globals: None,
guis: Vec::new(),
pointers: Vec::new(),
buffer_addresses: Vec::new(),
groups: Vec::new(),
last_window: None,
last_window_of_the_v1: None,
default_listview_of_the_v1: None,
default_window_of_the_v1: String::new(),
default_treeview_of_the_v1: None,
menus_of_the_v1: Vec::new(),
the_callback_of_a_menu_that_is_waiting: None,
clipboard_watcher: None,
message_handlers: BTreeMap::new(),
legacy_message_handlers: BTreeMap::new(),
image_lists: Vec::new(),
image_list_addresses: 0,
icon_of_the_script: None,
tray_menu: None,
statics: BTreeMap::new(),
statics_run: BTreeMap::new(),
initial_working_dir,
scopes: Vec::new(),
label_scopes: Vec::new(),
in_the_body_of_a_hotkey: false,
declarations: Vec::new(),
super_globals: BTreeSet::new(),
the_name_is_built: false,
current_classes: Vec::new(),
frames: Vec::new(),
loop_output_files: Vec::new(),
the_short_names_of_the_files_are_refused: false,
source: Vec::new(),
script_path: None,
script_args: Vec::new(),
thread_state: ThreadState::default(),
interrupt_last_ms: 0,
interrupt_lines: 0,
auto_execute_line: 0,
functions: BTreeMap::new(),
closures: 0,
classes: BTreeMap::new(),
class_values: RefCell::new(BTreeMap::new()),
initialised: RefCell::new(BTreeSet::new()),
steps: VecDeque::new(),
slow_steps: Vec::new(),
details_formatted: 0,
output: Vec::new(),
notes: Vec::new(),
started_ms: 0,
steps_taken: 0,
depth: 0,
stack_base: Self::stack_here(),
stack_budget: Self::MAX_STACK,
timers: Vec::new(),
posted_callbacks: Vec::new(),
the_statements_of_the_script: Rc::new(Vec::new()),
hotkeys: Vec::new(),
exit_requested: 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 {
guis: Vec::new(),
pointers: Vec::new(),
buffer_addresses: Vec::new(),
groups: Vec::new(),
last_window: None,
last_window_of_the_v1: None,
default_listview_of_the_v1: None,
default_window_of_the_v1: String::new(),
default_treeview_of_the_v1: None,
menus_of_the_v1: Vec::new(),
the_callback_of_a_menu_that_is_waiting: None,
clipboard_watcher: None,
message_handlers: BTreeMap::new(),
legacy_message_handlers: BTreeMap::new(),
image_lists: Vec::new(),
image_list_addresses: 0,
icon_of_the_script: None,
tray_menu: None,
desktop,
clock: ClockSource::Borrowed(clock),
random_seed: 0,
dialect: crate::dialect::v2(),
no_env: false,
warnings: Vec::new(),
the_warning_of_the_unset_read: None,
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(),
#[cfg(feature = "std")]
shared_globals: None,
statics: BTreeMap::new(),
statics_run: BTreeMap::new(),
initial_working_dir,
string_capacities: BTreeMap::new(),
string_memory: RefCell::new(Vec::new()),
string_buffers: RefCell::new(Vec::new()),
variable_memory: RefCell::new(BTreeMap::new()),
owned_memory: RefCell::new(BTreeMap::new()),
builtin_values: RefCell::new(BTreeMap::new()),
scopes: Vec::new(),
label_scopes: Vec::new(),
in_the_body_of_a_hotkey: false,
declarations: Vec::new(),
super_globals: BTreeSet::new(),
the_name_is_built: false,
current_classes: Vec::new(),
frames: Vec::new(),
loop_output_files: Vec::new(),
the_short_names_of_the_files_are_refused: false,
source: Vec::new(),
script_path: None,
script_args: Vec::new(),
thread_state: ThreadState::default(),
interrupt_last_ms: 0,
interrupt_lines: 0,
auto_execute_line: 0,
functions: BTreeMap::new(),
closures: 0,
classes: BTreeMap::new(),
class_values: RefCell::new(BTreeMap::new()),
initialised: RefCell::new(BTreeSet::new()),
steps: VecDeque::new(),
slow_steps: Vec::new(),
details_formatted: 0,
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(),
posted_callbacks: Vec::new(),
the_statements_of_the_script: Rc::new(Vec::new()),
hotkeys: Vec::new(),
hotkeys_are_not_watched: false,
callbacks_running: 0,
in_the_pump: false,
a_hotkey_is_being_dispatched: false,
critical: false,
the_events_that_wait: Vec::new(),
the_jump_the_pump_asked_for: None,
hotif_condition: None,
finally_labels: Vec::new(),
suspended: false,
paused: false,
persistent: false,
resident: false,
no_budget: false,
#[cfg(feature = "std")]
trace: the_trace_is_asked(),
the_desktop_cannot_wait: false,
suspend_exempt: false,
hotkey_is_exempt: Vec::new(),
hotkey_was_enabled: Vec::new(),
reload_requested: false,
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_globals(mut self, globals: Vec<(String, Value)>) -> Self {
for (name, value) in globals {
self.set_global(&name, value);
}
self
}
#[cfg(feature = "std")]
pub fn with_shared_globals(
mut self,
shared: crate::desktop::SharedGlobals,
) -> Self {
self.shared_globals = Some(shared);
self
}
#[cfg(feature = "std")]
pub fn the_shared_globals(&self) -> Option<crate::desktop::SharedGlobals> {
self.shared_globals.clone()
}
#[cfg(feature = "std")]
pub fn share_the_globals(&mut self) -> crate::desktop::SharedGlobals {
if let Some(shared) = &self.shared_globals {
return shared.clone();
}
let shared: crate::desktop::SharedGlobals =
std::sync::Arc::new(std::sync::Mutex::new(std::collections::BTreeMap::new()));
if let Ok(mut store) = shared.lock() {
for (name, value) in &self.variables {
if !matches!(value, Value::Reference(_) | Value::Unset) {
store.insert(name.clone(), value.clone());
}
}
}
self.shared_globals = Some(shared.clone());
shared
}
fn read_shared_global(&self, name: &str) -> Option<Value> {
#[cfg(feature = "std")]
{
let shared = self.shared_globals.as_ref()?;
let store = shared.lock().ok()?;
store.get(name).cloned()
}
#[cfg(not(feature = "std"))]
{
let _ = name;
None
}
}
fn write_shared_global(&self, name: &str, value: &Value) {
#[cfg(feature = "std")]
{
if let Some(shared) = &self.shared_globals {
if let Ok(mut store) = shared.lock() {
if matches!(value, Value::Reference(_) | Value::Unset) {
store.remove(name);
} else {
store.insert(name.to_string(), value.clone());
}
}
}
}
#[cfg(not(feature = "std"))]
{
let _ = (name, value);
}
}
pub fn with_script_path(mut self, path: &str) -> Self {
self.script_path = Some(path.to_string());
self
}
pub fn with_args(mut self, args: Vec<String>) -> Self {
let items: Vec<Value> = args.iter().cloned().map(Value::Text).collect();
self.variables
.insert("a_args".to_string(), crate::classes::array::of_items(items));
self.script_args = args;
self
}
pub fn script_path(&self) -> Option<&str> {
self.script_path.as_deref()
}
pub fn the_source(&self) -> String {
self.source.join("
")
}
pub fn the_dialect_name(&self) -> &'static str {
self.dialect.the_name_to_parse_again()
}
pub fn the_globals_as_thread_values(&self) -> Vec<(String, crate::desktop::ThreadValue)> {
self.variables
.iter()
.filter_map(|(name, value)| {
let crossed = match value {
Value::Int(_) | Value::Float(_) | Value::Text(_) | Value::List(_) => {
crate::desktop::ThreadValue::of_value(value)
}
Value::Object(object)
if object.borrow().class.eq_ignore_ascii_case("array") =>
{
crate::desktop::ThreadValue::of_value(value)
}
_ => return None,
};
Some((name.clone(), crossed))
})
.collect()
}
pub fn the_thread_state(&self) -> ThreadState {
self.thread_state
}
pub(crate) fn the_thread_is_interruptible(&self) -> bool {
let ms = self.thread_state.uninterruptible_ms;
let lines = self.thread_state.uninterruptible_lines;
if ms <= 0 && lines <= 0 {
return true;
}
let now = self.now_ms();
let time_ok = ms > 0 && now.saturating_sub(self.interrupt_last_ms) >= ms as u64;
let lines_ok = lines > 0 && self.interrupt_lines >= lines as u64;
time_ok || lines_ok
}
pub fn set_the_thread_state(&mut self, state: ThreadState) {
self.thread_state = state;
}
pub fn with_dialect(mut self, dialect: &'static dyn crate::dialect::Dialect) -> Self {
self.dialect = dialect;
#[cfg(test)]
let _turn = crate::settings::TheDefaults::take();
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);
}
fn the_built_ins_of_the_event_are_saved(
&self,
) -> Vec<(&'static str, Option<Value>)> {
const THE_NAMES: &[&str] = &[
"A_GuiWidth",
"A_GuiHeight",
"A_Gui",
"A_EventInfo",
"ErrorLevel",
];
THE_NAMES
.iter()
.map(|name| (*name, self.variables.get(&the_key_of(name)).cloned()))
.collect()
}
fn the_built_ins_of_the_event_are_given_back(
&mut self,
saved: Vec<(&'static str, Option<Value>)>,
) {
for (name, value) in saved {
match value {
Some(value) => self.set_global(name, value),
None => {
let key = the_key_of(name);
self.write_shared_global(&key, &Value::Unset);
self.variables.remove(&key);
}
}
}
}
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 {
if self.no_budget {
return u64::MAX;
}
let limit = self.timeout.as_millis() as u64;
limit.saturating_sub(self.elapsed_ms())
}
pub(crate) fn the_budget_is_over(&self) -> bool {
!self.no_budget && self.elapsed_ms() >= self.timeout.as_millis() as u64
}
fn register_the_hotkeys_of_the_v1(&mut self, statements: &[Node]) -> Result<(), RuntimeError> {
let mut condition = self.hotif_condition.clone();
for statement in statements {
match statement {
Node::Directive {
name,
argument,
line,
} if name == "if" || name == "ifwinactive" => {
condition = the_condition_of_a_v1_if(name, argument, self.dialect).map_err(|_| {
RuntimeError {
message: "The condition of the #If is not one valid expression.".to_string(),
line: *line,
}
})?;
}
Node::HotkeyDefinition {
name, body, line, ..
} => {
crate::hotkeys::register_the_hotkey_of_the_v1(
self,
name,
body.clone(),
*line,
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(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.the_script_asked_to_stay(true);
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, self.dialect) {
Ok(condition) => self.hotif_condition = condition,
Err(()) => {
return Err(RuntimeError {
message: "The condition of #HotIf is not one valid expression.".to_string(),
line: *line,
})
}
}
}
}
}
Ok(())
}
pub fn run(mut self, statements: &[Node]) -> Report {
let outcome = self.run_the_script(statements);
self.finish_the_run(statements, outcome)
}
pub fn run_the_function(
mut self,
statements: &[Node],
name: &str,
args: &[Value],
) -> (Report, Value) {
self.the_statements_of_the_script = Rc::new(statements.to_vec());
self.collect_functions(statements);
self.collect_the_super_globals(statements);
self.label_scopes.push(the_labels_of(statements));
let mut answer = Value::Unset;
let outcome = match self.call_named(name, args, 0, Route::Written) {
Ok(value) => {
answer = value;
Ok(())
}
Err(failure) => Err(failure),
};
let report = self.finish_the_run(statements, outcome);
(report, answer)
}
pub fn run_and_stay(&mut self, statements: &[Node]) -> Report {
let mut outcome = self.run_the_script(statements);
if (self.resident || self.persistent) && !the_run_failed(&outcome) {
if let Err(failure) = self.stay_alive(statements) {
outcome = Err(failure);
}
}
self.finish_the_run(statements, outcome)
}
fn stay_alive(&mut self, statements: &[Node]) -> Result<(), RuntimeFailure> {
let _ = self.desktop().tray_of_the_script_is_shown();
let outcome = self.the_run_stays_alive(statements);
let _ = self.desktop().tray_of_the_script_is_removed();
outcome
}
fn the_run_stays_alive(&mut self, statements: &[Node]) -> Result<(), RuntimeFailure> {
loop {
if self.exit_requested.is_some() || self.reload_requested {
return Ok(());
}
if self.desktop().tray_exit_was_asked() {
return Ok(());
}
if !self.no_budget && self.elapsed_ms() > self.timeout.as_millis() as u64 {
return Ok(());
}
self.run_timers(statements)?;
self.run_posted_callbacks()?;
self.the_events_are_answered(statements, 0)
.map_err(RuntimeFailure::Error)?;
self.run_the_events_of_the_com(0)?;
self.the_hotkeys_that_fired_run(statements)?;
self.the_machine_is_waited();
}
}
pub(crate) fn the_run_waits_for(
&mut self,
millis: u64,
line: u32,
) -> Result<(), RuntimeFailure> {
let until = self.now_ms() + millis;
loop {
let left = until.saturating_sub(self.now_ms());
if left == 0 {
break;
}
let statements = self.the_statements_of_the_script.clone();
let answer = self.the_events_of_the_machine_are_run(&statements, line);
answer?;
self.sleep_ms(left.min(THE_GAP_OF_A_WAIT));
}
Ok(())
}
fn the_events_of_the_machine_are_run(
&mut self,
statements: &[Node],
line: u32,
) -> Result<(), RuntimeFailure> {
if !self.critical {
self.run_timers(statements)?;
self.run_posted_callbacks()?;
}
self.the_events_are_answered(statements, line)
.map_err(RuntimeFailure::Error)?;
self.run_the_events_of_the_com(0)?;
if self.critical {
return Ok(());
}
self.the_hotkeys_that_fired_run(statements)?;
Ok(())
}
fn the_hotkeys_that_fired_run(&mut self, statements: &[Node]) -> Result<(), RuntimeFailure> {
if self.hotkeys_are_not_watched {
return Ok(());
}
self.a_hotkey_is_being_dispatched = true;
let script = self.the_statements_of_the_script.clone();
let answer = crate::hotkeys::run_fired(self, script.as_slice());
self.a_hotkey_is_being_dispatched = false;
match answer {
Ok(()) => Ok(()),
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)
};
Err(failure)
}
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}"
));
Ok(())
} else {
Err(failure)
}
}
}
}
fn the_machine_is_waited(&mut self) {
match self.desktop().wait_for_event(50) {
Ok(_arrived) => {}
Err(reason) => {
if !self.the_desktop_cannot_wait {
self.the_desktop_cannot_wait = true;
self.note(format!(
"the run waits with the clock of the runtime: {reason}"
));
}
self.clock.sleep_ms(10);
}
}
}
pub(crate) fn the_script_is_persistent(&self) -> bool {
self.persistent
}
pub(crate) fn the_script_asked_to_stay(&mut self, asked: bool) {
self.persistent = asked;
}
pub fn with_resident(mut self, resident: bool) -> Self {
self.resident = resident;
self
}
pub fn with_no_budget(mut self, no_budget: bool) -> Self {
self.no_budget = no_budget;
self
}
fn run_the_script(&mut self, statements: &[Node]) -> Result<(), RuntimeFailure> {
self.the_statements_of_the_script = Rc::new(statements.to_vec());
self.collect_functions(statements);
self.collect_the_super_globals(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)
};
let line_file = match &self.script_path {
Some(path) => Value::Text(path.clone()),
None => Value::Text("*".to_string()),
};
self.set_global("A_LineFile", line_file);
if self.dialect.the_statics_are_initialised_at_load() {
self.the_statics_are_initialised_at_load(statements)?;
}
self.label_scopes.push(the_labels_of(statements));
match registered {
Ok(()) => self.run_block(statements),
Err(failure) => Err(RuntimeFailure::Error(failure)),
}
}
fn the_statics_are_initialised_at_load(
&mut self,
statements: &[Node],
) -> Result<(), RuntimeFailure> {
for statement in statements {
match statement {
Node::FunctionDef {
name,
body,
declarations,
..
} => {
self.the_statics_of_a_body_are_initialised(
name,
body,
declarations,
)?;
}
Node::ClassDef {
name,
methods,
properties,
..
} => {
let key = name.to_lowercase();
if self.classes.contains_key(&key)
&& self.initialised.borrow_mut().insert(key.clone())
{
for property in properties {
if !property.is_static {
continue;
}
let Some(value) = &property.value else {
continue;
};
let value = self.evaluate(value)?;
let Some(class_value) = self.class_value_of(&key) else {
continue;
};
if let Value::Object(object) = class_value {
put(&mut object.borrow_mut().properties, &property.name, value);
}
}
}
for method in methods {
let frame = self.the_name_of_the_method(&key, method);
self.the_statics_of_a_body_are_initialised(
&frame,
&method.body,
&method.declarations,
)?;
}
}
_ => {}
}
}
Ok(())
}
fn the_statics_of_a_body_are_initialised(
&mut self,
frame: &str,
body: &[Node],
declarations: &Declarations,
) -> Result<(), RuntimeFailure> {
let statics: Vec<&Node> = body
.iter()
.filter(|statement| {
matches!(statement, Node::Declare { scope: DeclareKind::Static, .. })
})
.collect();
if statics.is_empty() {
return Ok(());
}
self.frames.push(Frame {
name: frame.to_string(),
line: 0,
closed_frames: Vec::new(),
parameters: BTreeSet::new(),
force_local: false,
});
self.declarations.push(declarations.clone());
for statement in statics {
self.execute(statement)?;
}
self.declarations.pop();
self.frames.pop();
Ok(())
}
fn finish_the_run(
&mut self,
statements: &[Node],
outcome: Result<(), RuntimeFailure>,
) -> Report {
#[cfg(feature = "std")]
crate::memory::forget_all();
let mut error = None;
let mut error_line = None;
let mut exit_code = None;
let mut reload = false;
match outcome {
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::Reload)) => {
reload = true;
exit_code = Some(0);
}
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));
}
}
if self.failure_hidden {
error = None;
error_line = None;
}
#[cfg(feature = "std")]
if let Some(ref message) = error {
if std::env::var_os("AHK_DEBUG_ERRORS").is_some()
|| std::env::var_os("AHK_DEBUG_CALLBACK").is_some()
{
eprintln!(
"AHK runtime error before OnExit (line {:?}): {}",
error_line, message
);
}
}
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)];
let answer = if self.functions.contains_key(&callback.name.to_lowercase()) {
self.call_named(&callback.name, &values, callback.line, Route::Written)
} else {
let statements = self.the_statements_of_the_script.clone();
self.run_the_callback_of_the_v1_menu(&callback.name, statements.as_slice(), callback.line)
.map(|_| Value::Int(0))
};
match answer {
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();
reload = reload || self.the_script_asked_to_run_again();
Report {
ok: error.is_none(),
steps: core::mem::take(&mut self.steps).into_iter().collect(),
slow: core::mem::take(&mut self.slow_steps),
output: core::mem::take(&mut self.output),
warnings: core::mem::take(&mut self.warnings),
notes: core::mem::take(&mut self.notes),
error,
error_line,
exit_code,
reload,
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);
}
}
let the_unset_mode = if self.dialect.is_the_v1() {
(self.modes.var_unset != crate::warnings::WarningMode::Off)
.then_some(self.modes.var_unset)
} else {
[
self.modes.var_unset,
self.modes.use_unset_local,
self.modes.use_unset_global,
]
.into_iter()
.find(|mode| *mode != crate::warnings::WarningMode::Off)
};
if let Some(mode) = the_unset_mode {
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_the_unset_read_again(&mut self, value: &Node) {
if !self.dialect.is_the_v1() {
return;
}
if !matches!(value, Node::Var { .. }) {
return;
}
if let Some((line, message, mode)) = self.the_warning_of_the_unset_read.take() {
self.warn(line, message, mode);
}
}
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;
}
let message = format!(
"This variable has not been assigned a value.\n Specifically: {name} ({kind})"
);
self.warn(line, message.clone(), mode);
self.the_warning_of_the_unset_read = Some((line, message, 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_the_super_globals(&mut self, statements: &[Node]) {
if !self.variables.contains_key("a_args") {
let items: Vec<Value> = self
.script_args
.iter()
.cloned()
.map(Value::Text)
.collect();
self.variables
.insert("a_args".to_string(), crate::classes::array::of_items(items));
}
if !self.dialect.is_the_v1() {
return;
}
self.super_globals = the_super_globals_of_the_script(statements);
self.super_globals.insert("a_args".to_string());
if !self.script_args.is_empty() {
self.variables
.entry("0".to_string())
.or_insert_with(|| Value::Text(self.script_args.len().to_string()));
for (index, arg) in self.script_args.iter().enumerate() {
self.variables
.entry((index + 1).to_string())
.or_insert_with(|| Value::Text(arg.clone()));
}
}
}
fn collect_functions(&mut self, statements: &[Node]) {
for statement in statements {
match statement {
Node::ClassDef {
name,
extends,
methods,
properties,
accessors,
nested,
is_struct,
fields,
..
} => {
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,
is_struct: *is_struct,
fields: fields.clone(),
},
);
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(),
closure_frames: 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(),
closure_frames: self.frames.iter().map(|frame| frame.name.clone()).collect(),
};
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 scope = if self.a_hotkey_is_being_dispatched {
self.label_scopes.first()
} else {
self.label_scopes.last()
};
let Some(scope) = scope 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> {
self.run_the_statements_of_a_block_from(statements, 0)
}
fn run_the_statements_of_a_block_from(
&mut self,
statements: &[Node],
from: usize,
) -> Result<(), RuntimeFailure> {
let mut index = from;
while index < statements.len() {
let statement = &statements[index];
self.interrupt_lines = self.interrupt_lines.saturating_add(1);
self.set_global("A_LineNumber", Value::Int(statement.line() as i64));
let slow = the_slow_threshold();
let started = if slow > 0 {
Some(self.now_ms())
} else {
None
};
let outcome = self.execute(statement);
if let Some(started) = started {
let elapsed = self.now_ms().saturating_sub(started);
#[cfg(feature = "std")]
if elapsed >= slow {
eprintln!(
"SLOW {} ms line {} op {}",
elapsed,
statement.line(),
op_name_in(statement, self.dialect)
);
}
#[cfg(not(feature = "std"))]
let _ = elapsed;
}
match outcome {
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),
},
}
self.the_machine_is_pumped(statements)?;
if let Some(jump) = self.the_jump_the_pump_asked_for.take() {
match jump {
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,
}));
}
},
other => return Err(other),
}
}
if self.the_section_that_runs()
&& 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)));
}
if self.reload_requested {
return Err(RuntimeFailure::Flow(Flow::Reload));
}
index += 1;
}
Ok(())
}
fn the_machine_is_pumped(&mut self, statements: &[Node]) -> Result<(), RuntimeFailure> {
if self.in_the_pump
|| self.callbacks_running > 0
|| self.in_the_body_of_a_hotkey
|| !self.the_thread_is_interruptible()
{
return Ok(());
}
self.interrupt_last_ms = self.now_ms();
self.interrupt_lines = 0;
self.in_the_pump = true;
let answer = self.the_machine_is_pumped_now(statements);
self.in_the_pump = false;
answer
}
fn the_machine_is_pumped_now(
&mut self,
statements: &[Node],
) -> Result<(), RuntimeFailure> {
if !self.critical {
self.run_timers(statements)?;
self.run_posted_callbacks()?;
}
self.the_events_are_answered(statements, 0)
.map_err(RuntimeFailure::Error)?;
self.run_the_events_of_the_com(0)?;
if self.critical || self.hotkeys_are_not_watched {
return Ok(());
}
self.a_hotkey_is_being_dispatched = true;
let script = self.the_statements_of_the_script.clone();
let answer = crate::hotkeys::run_fired(self, script.as_slice());
self.a_hotkey_is_being_dispatched = false;
match answer {
Ok(()) => Ok(()),
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => {
if self.the_jump_the_pump_asked_for.is_none() {
self.the_jump_the_pump_asked_for =
Some(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
}));
}
Ok(())
}
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}"
));
Ok(())
} else {
Err(failure)
}
}
}
}
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 scopes = core::mem::take(&mut self.scopes);
let answer = self.run_block(body);
let answer = match answer {
Err(RuntimeFailure::Flow(Flow::Goto {
name,
line,
computed,
})) => self.the_jump_of_the_hotkey_goes_on_at_the_label(&name, line, computed),
other => other,
};
self.scopes = scopes;
self.in_the_body_of_a_hotkey = was_in_the_body;
match answer {
Err(RuntimeFailure::Flow(Flow::Return(_))) => Ok(()),
other => other,
}
}
fn the_jump_of_the_hotkey_goes_on_at_the_label(
&mut self,
name: &str,
line: u32,
computed: bool,
) -> Result<(), RuntimeFailure> {
let statements = self.the_statements_of_the_script.clone();
let Some(place) = the_place_of_the_label(statements.as_slice(), name) else {
return Err(RuntimeFailure::Flow(Flow::Goto {
name: name.to_string(),
line,
computed,
}));
};
match self.run_the_statements_of_a_block_from(&statements, place) {
Ok(()) => Ok(()),
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);
}
if self.dialect.is_the_v1()
&& catches.is_empty()
&& matches!(
failure,
Some(RuntimeFailure::Error(_))
| Some(RuntimeFailure::Detailed(_, _))
| Some(RuntimeFailure::Thrown(_))
)
{
return Ok(());
}
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.script_path().unwrap_or(""),
&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.script_path().unwrap_or(""),
&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 {
let file = match &self.script_path {
Some(path) => path.clone(),
None => String::new(),
};
format!("{file} ({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, statements: &[Node]) -> Result<(), RuntimeFailure> {
if !self.thread_state.allow_timers || self.paused {
return Ok(());
}
if self.desktop().the_menu_is_visible() {
return Ok(());
}
let now = self.now_ms();
let mut due: Vec<(i64, usize, String, Option<Value>)> = Vec::new();
let mut spent: Vec<usize> = Vec::new();
for (index, timer) in self.timers.iter_mut().enumerate() {
if now.saturating_sub(timer.last) < timer.period {
continue;
}
timer.last = now;
crate::trace::timer(&timer.name, the_period_in_the_trace(timer.period, timer.once));
if timer.once {
spent.push(index);
}
due.push((
timer.priority,
index,
timer.name.clone(),
timer.function.clone(),
));
}
for index in spent.into_iter().rev() {
self.timers.remove(index);
}
due.sort_by_key(|(priority, index, _, _)| (*priority, *index));
for (_, _, name, function) in due {
if let Some(function) = function {
match crate::classes::func::call_the_value(&function, &[], self, 0) {
Some(Ok(_)) => {}
Some(Err(failure)) => return Err(failure),
None => {}
}
continue;
}
if let Some(function) = self.functions.get(&name.to_lowercase()).cloned() {
self.call_function(&function, &[], 0, Route::Written)?;
continue;
}
self.run_the_subroutine_of_the_label(statements, &name)?;
}
Ok(())
}
fn run_the_subroutine_of_the_label(
&mut self,
statements: &[Node],
name: &str,
) -> Result<(), RuntimeFailure> {
let Some(place) = the_place_of_the_label(statements, name) else {
return Ok(());
};
let mut rest = Vec::new();
for statement in &statements[place..] {
if matches!(statement, Node::Label { .. }) {
continue;
}
if matches!(statement, Node::Return { .. }) {
break;
}
rest.push(statement.clone());
}
match self.run_the_statements_of_a_block(&rest) {
Ok(()) => Ok(()),
Err(RuntimeFailure::Flow(Flow::Return(_))) => Ok(()),
Err(failure) => Err(failure),
}
}
pub(crate) fn add_the_timer_with_a_function(
&mut self,
name: &str,
function: Option<Value>,
period: u64,
priority: i64,
once: bool,
) {
let last = self.now_ms();
self.timers.push(Timer {
name: name.to_string(),
function,
period,
last,
priority,
once,
});
}
pub(crate) fn delete_timer(&mut self, name: &str) {
let wanted = name.to_lowercase();
self.timers
.retain(|timer| timer.name.to_lowercase() != wanted);
}
pub(crate) fn post_callback(&mut self, callback: Callback) {
self.posted_callbacks.push(callback);
}
fn run_posted_callbacks(&mut self) -> Result<(), RuntimeFailure> {
if self.posted_callbacks.is_empty() {
return Ok(());
}
let callbacks = core::mem::take(&mut self.posted_callbacks);
for callback in callbacks {
self.call_named(&callback.name, &[], callback.line, Route::Written)?;
}
Ok(())
}
pub(crate) fn run_the_callback_of_the_v1_menu(
&mut self,
name: &str,
statements: &[Node],
line: u32,
) -> Result<(), RuntimeFailure> {
if self.functions.contains_key(&name.to_lowercase()) {
return self.call_named(name, &[], line, Route::Written).map(|_| ());
}
if let Some(place) = the_place_of_the_label(statements, name) {
let mut body = Vec::new();
for statement in statements.iter().skip(place + 1) {
if matches!(statement, Node::Label { .. }) {
break;
}
body.push(statement.clone());
}
return self.run_the_body_of_a_hotkey(&body);
}
Err(RuntimeFailure::Error(RuntimeError {
message: format!("Call to nonexistent function.
Specifically: {name}"),
line,
}))
}
pub(crate) fn exit_with(&mut self, code: i32) {
self.exit_requested = Some(code);
}
pub(crate) fn ask_for_the_script_to_run_again(&mut self) {
self.reload_requested = true;
}
pub(crate) fn the_script_asked_to_run_again(&self) -> bool {
self.reload_requested
}
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;
#[cfg(feature = "std")]
if self.trace {
eprintln!("{} {}", statement.line(), op_name_in(statement, self.dialect));
}
match self.frames.last_mut() {
Some(frame) => frame.line = statement.line(),
None => self.auto_execute_line = statement.line(),
}
if !self.no_budget && !self.persistent && 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.no_budget && self.elapsed_ms() >= self.timeout.as_millis() as u64 {
return Err(RuntimeFailure::Timeout(Timeout {
seconds: self.timeout.as_secs_f64(),
}));
}
let mut detail = String::new();
let tracing = self.details_formatted < Self::MAX_FORMATTED_DETAILS;
let started = self.now_ms();
let result: Result<(), RuntimeFailure> = (|| {
match statement {
Node::VarRef { .. } => {
}
Node::Assign {
name,
op,
value,
line,
} => {
if *op == AssignOp::Set && the_node_is_unset(value) {
self.unset_variable(name);
if tracing {
detail = format!("{name} = ");
}
} else {
self.the_warning_of_the_unset_read = None;
let the_value = self.evaluate(value)?;
self.warn_the_unset_read_again(value);
let value = the_value;
if *op == AssignOp::Set && matches!(value, Value::Unset | Value::Skipped) {
self.unset_variable(name);
if tracing {
detail = format!("{name} = ");
}
} else {
let stored = self.write_a_variable(name, *op, value, *line)?;
if tracing {
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::AssignCall {
call,
op,
value,
line,
} => {
let target = self.evaluate(call)?;
let value = self.evaluate(value)?;
let stored = self.the_default_member_is_written(&target, *op, value, *line)?;
detail = format!("= {}", 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::CallDynamic {
name,
arguments,
line,
} => {
let resolved = self.the_name_of_the_pieces(name, *line)?;
let value = self.call(&resolved, 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 self.the_budget_is_over() {
self.the_index_is_given_back(saved);
return Err(RuntimeFailure::Timeout(Timeout {
seconds: self.timeout.as_secs_f64(),
}));
}
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 } => {
match self.the_super_class_object() {
Some(class_object) => detail = class_object.to_text(),
None => {
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;
}
if *scope == DeclareKind::Static {
self.mark_the_static_as_ran(*line, &declared.name);
}
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);
}
}
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;
if self.the_loop_is_fast(body, until, otherwise) {
let result =
self.run_the_fast_loop(body, count.max(0));
self.the_index_is_given_back(saved);
result?;
return Ok(());
}
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.no_budget
&& !self.persistent
&& 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 => {
let key = match arguments.first() {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, *line)?,
None => String::new(),
};
let mode = match arguments.get(1) {
Some(node) => self.the_text_of_the_parameter_of_the_loop(node, *line)?,
None => String::new(),
};
let quiet = self
.dialect()
.a_key_of_the_registry_that_cannot_be_opened_is_not_a_failure();
let entries = match self.desktop().registry_enumerate(&key, &mode, quiet)
{
Ok(entries) => entries,
Err(reason) => {
if quiet {
Vec::new()
} else {
return Err(RuntimeFailure::Error(RuntimeError {
message: reason,
line: *line,
}));
}
}
};
turns = entries.len();
let mut failure = None;
for (index, entry) in entries.iter().enumerate() {
self.set_global("A_Index", Value::Int(index as i64 + 1));
self.set_global("A_LoopRegName", Value::Text(entry.name.clone()));
self.set_global("A_LoopRegType", Value::Text(entry.kind.clone()));
self.set_global("A_LoopRegKey", Value::Text(entry.root.clone()));
self.set_global("A_LoopRegSubKey", Value::Text(entry.subkey.clone()));
self.set_global(
"A_LoopRegTimeModified",
Value::Text(entry.modified.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 let Some(other) = failure {
self.the_index_is_given_back(saved);
return Err(other);
}
}
}
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::Gosub { name, line } => {
let mut target = name.clone();
if target.contains('%') {
target = self.the_substitution_of_the_v1(&target, *line)?;
}
let statements = self.the_statements_of_the_script.clone();
if let Some(place) = the_place_of_the_label(statements.as_slice(), &target) {
let mut body = Vec::new();
for statement in statements.iter().skip(place + 1) {
if matches!(statement, Node::Label { .. }) {
break;
}
body.push(statement.clone());
}
match self.run_block(&body) {
Err(RuntimeFailure::Flow(Flow::Return(_))) => {}
other => other?,
}
} else {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"Nonexistent label.\n Specifically: {target}"
),
line: *line,
}));
}
}
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, tail, .. } => {
let value = match value {
Some(node) => Some(self.evaluate(node)?),
None => None,
};
for item in tail {
self.evaluate(item)?;
}
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();
}
}
Ok(())
})();
let elapsed_ms = self.now_ms().saturating_sub(started);
let op = op_name_in(statement, self.dialect);
let mut step = Step {
line: statement.line(),
op: op.to_string(),
detail: if tracing {
self.details_formatted += 1;
detail
} else {
String::new()
},
ok: result.is_ok(),
elapsed_ms,
};
if let Err(failure) = &result {
step.detail = the_reason_of_the_failure(failure);
}
self.remember_the_step(step);
result
}
fn remember_the_step(&mut self, mut step: Step) {
if step.elapsed_ms >= the_threshold_of_the_slow_list() {
if step.detail.len() > Self::MAX_DETAIL_CHARS {
step.detail.truncate(Self::MAX_DETAIL_CHARS);
}
self.slow_steps.push(step.clone());
while self.slow_steps.len() > Self::MAX_SLOW_STEPS {
let mut slowest = 0;
for (index, other) in self.slow_steps.iter().enumerate().skip(1) {
if other.elapsed_ms < self.slow_steps[slowest].elapsed_ms {
slowest = index;
}
}
self.slow_steps.remove(slowest);
}
}
self.steps.push_back(step);
while self.steps.len() > Self::MAX_RECORDED_STEPS {
self.steps.pop_front();
}
}
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)?;
let wanted = if self.dialect.the_for_is_the_one_of_the_v1() {
2
} else {
variables.len()
};
let enumerator = if self.dialect.the_for_is_the_one_of_the_v1() {
let Some(pairs) = self.the_pairs_of_the_v1(&object, line)? else {
for (name, value) in saved {
self.restore_variable(&name, value);
}
return Ok(());
};
crate::classes::enumerator::make(pairs, crate::classes::enumerator::Alone::TheValue)
} else {
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 self.the_budget_is_over() {
outcome = Err(RuntimeFailure::Timeout(Timeout {
seconds: self.timeout.as_secs_f64(),
}));
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_pairs_of_the_v1(
&mut self,
object: &Value,
line: u32,
) -> Result<Option<Vec<(Value, Value)>>, RuntimeFailure> {
let Value::Object(cell) = object else {
return Ok(None);
};
let is_array = cell.borrow().properties.contains_key("array state");
let mut numeric: BTreeMap<i64, Value> = BTreeMap::new();
if is_array {
let count = Node::Literal {
value: LiteralValue::Integer(2),
line,
};
let enumerator = self.call_method_on(object, "__enum", &[count], line)?;
for (key, value) in crate::classes::enumerator::the_pairs_of(&enumerator) {
let Some(number) = key.to_number() else { continue };
numeric.insert(number as i64, value);
}
}
let mut text: Vec<(Value, Value)> = Vec::new();
{
let borrowed = cell.borrow();
for (name, property) in borrowed.properties.iter() {
if name.as_str() == BASE
|| name.as_str() == CLASS_NAME
|| name.as_str() == "prototype"
|| name.as_str() == "array state"
{
continue;
}
match name.parse::<i64>() {
Ok(number) => {
numeric.insert(number, property.value.clone());
}
Err(_) => text.push((
Value::Text(property.name.clone()),
property.value.clone(),
)),
}
}
}
let mut pairs: Vec<(Value, Value)> = numeric
.into_iter()
.map(|(number, value)| (Value::Int(number), value))
.collect();
pairs.extend(text);
Ok(Some(pairs))
}
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());
}
}
}
pub(crate) 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(self.the_builtin_value_kept(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)
|| (self.dialect.the_struct_keyword_is_known()
&& crate::structs::is_a_struct_class_name(&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 (self.dialect.the_struct_keyword_is_known()
&& crate::structs::is_a_struct_class_name(&key))
|| 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 SharedCell::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_borrowed_key(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)
|| THE_BUILT_INS_OF_THE_EVENT.contains(&&*name);
if self.dialect.the_scope_of_a_function_is_its_own()
&& !self.scopes.is_empty()
&& !owned
&& !self.lives_in_the_script(&name)
{
return None;
}
if let Some(value) = self.read_shared_global(&name) {
return Some(value);
}
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(self.the_builtin_value_kept(builtin.name, builtin.min, max))
}
fn the_builtin_value_kept(&self, name: &str, min: u8, max: u32) -> Value {
let key = name.to_lowercase();
let mut kept = self.builtin_values.borrow_mut();
if let Some(value) = kept.get(&key) {
return value.clone();
}
let value = builtin_value(name, min, max);
kept.insert(key, value.clone());
value
}
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()?;
if let Some(value) = self.statics.get(&frame.name).and_then(|held| held.get(name)).cloned() {
return Some(value);
}
for closed in frame.closed_frames.iter().rev() {
if let Some(value) = self.statics.get(closed).and_then(|held| held.get(name)).cloned() {
return Some(value);
}
}
None
}
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.dialect.is_the_v1() {
return Ok(());
}
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> {
let mut target = reference.clone();
for _ in 0..Self::MAX_ALIAS_DEPTH {
match self.read_the_variable(&target) {
Some(Value::Reference(inner)) if inner.alias => target = inner,
other => return other,
}
}
None
}
pub(crate) fn the_variable_of_the_reference(&self, reference: &Reference) -> Reference {
let mut target = reference.clone();
for _ in 0..Self::MAX_ALIAS_DEPTH {
match self.read_the_variable(&target) {
Some(Value::Reference(inner)) if inner.alias => target = inner,
_ => break,
}
}
target
}
fn read_the_variable(&self, reference: &Reference) -> Option<Value> {
if reference.name.is_empty() {
return None;
}
let name = the_key_of(&reference.name);
if let Some(value) = self.the_static_of_the_frame(&name) {
return Some(value);
}
match reference.scope {
Scope::Global => self
.read_shared_global(&name)
.or_else(|| 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;
};
let reference = self.the_variable_of_the_reference(reference);
if reference.name.is_empty() {
return;
}
let name = the_key_of(&reference.name);
if self.is_declared_static(&name) {
self.the_statics_of_the_frame().insert(name, written);
return;
}
match reference.scope {
Scope::Global => {
self.write_shared_global(&name, &written);
self.write_the_global(&name, written);
}
Scope::Local(depth) => {
if let Some(scope) = self.scopes.get(depth) {
scope.borrow_mut().insert(name, written);
}
}
}
}
pub(crate) fn write_reference_suffix(&mut self, value: &Value, suffix: &str, written: Value) {
let Value::Reference(reference) = value else {
return;
};
let reference = self.the_variable_of_the_reference(reference);
if reference.name.is_empty() {
return;
}
let name = the_key_of(&format!("{}{}", reference.name, suffix));
match reference.scope {
Scope::Global => {
self.write_shared_global(&name, &written);
self.write_the_global(&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,
}
}
fn the_scope_of_the_number(number: u8) -> Scope {
match number {
0 => Scope::Global,
other => Scope::Local(other.saturating_sub(1) as usize),
}
}
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);
}
fn the_variable_memory_key(reference: &Reference) -> (u8, String) {
(
Self::the_scope_number(reference.scope),
the_key_of(&reference.name),
)
}
pub(crate) fn the_capacity_buffer(
&mut self,
reference: &Reference,
capacity: i64,
fill: u8,
) -> i64 {
let reference = self.the_variable_of_the_reference(reference);
let key = Self::the_variable_memory_key(&reference);
self.owned_memory.borrow_mut().remove(&key);
if capacity < 0 {
self.variable_memory.borrow_mut().remove(&key);
return 0;
}
let mut memory = self.variable_memory.borrow_mut();
let buffer = memory
.entry(key)
.or_insert_with(|| vec![fill; capacity as usize].into_boxed_slice());
if buffer.len() != capacity as usize {
*buffer = vec![fill; capacity as usize].into_boxed_slice();
}
buffer.as_ptr() as i64
}
fn the_text_is_written_into_the_buffer(&mut self, name: &str, value: &Value) {
if !self.dialect.is_the_v1() {
return;
}
let key = (
Self::the_scope_number(self.the_scope_of(name)),
the_key_of(name),
);
let text = value.to_text();
{
let mut memory = self.owned_memory.borrow_mut();
if let Some(buffer) = memory.get_mut(&key) {
let mut bytes = Vec::new();
for unit in text.encode_utf16() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
bytes.extend_from_slice(&[0, 0]);
if bytes.len() > buffer.len() {
*buffer = bytes.into_boxed_slice();
} else {
buffer[..bytes.len()].copy_from_slice(&bytes);
}
return;
}
}
let mut memory = self.variable_memory.borrow_mut();
let Some(buffer) = memory.get_mut(&key) else {
return;
};
let mut offset = 0;
for unit in text.encode_utf16() {
if offset + 2 > buffer.len() {
break;
}
let bytes = unit.to_le_bytes();
buffer[offset] = bytes[0];
buffer[offset + 1] = bytes[1];
offset += 2;
}
if offset + 2 <= buffer.len() {
buffer[offset] = 0;
buffer[offset + 1] = 0;
}
}
pub(crate) fn the_variable_address(&mut self, reference: &Reference) -> i64 {
let reference = self.the_variable_of_the_reference(reference);
let key = Self::the_variable_memory_key(&reference);
if let Some(buffer) = self.variable_memory.borrow().get(&key) {
return buffer.as_ptr() as i64;
}
let text = match self.read_reference(&reference) {
Some(value) => value.to_text(),
None => String::new(),
};
if self.dialect.is_the_v1() {
if let Some(buffer) = self.owned_memory.borrow().get(&key) {
return buffer.as_ptr() as i64;
}
return self.the_block_of_the_variable(&key, &text);
}
self.the_address_of_a_text(&text)
}
fn the_block_of_the_variable(&mut self, key: &(u8, String), text: &str) -> i64 {
let mut bytes = Vec::new();
for unit in text.encode_utf16() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
bytes.extend_from_slice(&[0, 0]);
bytes.resize(bytes.len() + 64, 0);
let mut memory = self.owned_memory.borrow_mut();
let buffer = memory
.entry(key.clone())
.or_insert_with(|| bytes.into_boxed_slice());
buffer.as_ptr() as i64
}
pub(crate) fn the_variable_at_an_address_is_read_back(&mut self, address: i64) {
let Some((key, _)) = self.the_key_and_the_place_at_an_address(address) else {
return;
};
let Some(bytes) = self.the_bytes_at_an_address(address) else {
return;
};
let reference = Reference {
name: key.1.clone(),
scope: Self::the_scope_of_the_number(key.0),
alias: false,
};
let length = self
.read_reference(&reference)
.map(|value| value.to_text().chars().count())
.unwrap_or(0);
let text = crate::dll::decode(&bytes, crate::dll::NativeType::WStr);
let text: String = text.chars().take(length).collect();
self.write_reference(&Value::Reference(reference), Value::Text(text));
}
fn the_key_and_the_place_at_an_address(
&self,
address: i64,
) -> Option<((u8, String), usize)> {
for memory in [&self.variable_memory, &self.owned_memory] {
let memory = memory.borrow();
for (key, buffer) in memory.iter() {
let start = buffer.as_ptr() as i64;
if address >= start && address < start + buffer.len() as i64 {
return Some((key.clone(), (address - start) as usize));
}
}
}
None
}
pub(crate) fn the_bytes_at_an_address(&self, address: i64) -> Option<Vec<u8>> {
if let Some((key, at)) = self.the_key_and_the_place_at_an_address(address) {
if let Some(buffer) = self.variable_memory.borrow().get(&key) {
return Some(buffer[at..].to_vec());
}
if let Some(buffer) = self.owned_memory.borrow().get(&key) {
return Some(buffer[at..].to_vec());
}
return None;
}
let buffers = self.string_buffers.borrow();
for block in buffers.iter().flatten() {
if block.as_ptr() as i64 == address {
let mut bytes = Vec::with_capacity(block.len() * 2);
for unit in block.iter() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
return Some(bytes);
}
}
None
}
pub(crate) fn the_bytes_are_written_at_an_address(
&mut self,
address: i64,
bytes: &[u8],
) -> Option<Reference> {
let (key, at) = self.the_key_and_the_place_at_an_address(address)?;
let (scope, name) = (
Self::the_scope_of_the_number(key.0),
key.1.clone(),
);
{
let mut memory = self.variable_memory.borrow_mut();
if let Some(buffer) = memory.get_mut(&key) {
let room = buffer.len().saturating_sub(at);
let count = bytes.len().min(room);
buffer[at..at + count].copy_from_slice(&bytes[..count]);
return Some(Reference {
name,
scope,
alias: false,
});
}
}
{
let mut memory = self.owned_memory.borrow_mut();
let buffer = memory.get_mut(&key)?;
let room = buffer.len().saturating_sub(at);
let count = bytes.len().min(room);
buffer[at..at + count].copy_from_slice(&bytes[..count]);
}
Some(Reference {
name,
scope,
alias: false,
})
}
pub(crate) fn the_bytes_are_written_at_a_text(&mut self, address: i64, bytes: &[u8]) -> bool {
if bytes.len() % 2 != 0 {
return false;
}
let mut buffers = self.string_buffers.borrow_mut();
for block in buffers.iter_mut().flatten() {
if block.as_ptr() as i64 == address {
for (unit, bytes) in block.iter_mut().zip(bytes.chunks_exact(2)) {
*unit = u16::from_le_bytes([bytes[0], bytes[1]]);
}
return true;
}
}
false
}
pub(crate) fn the_value_of_the_expression_text(
&mut self,
text: &str,
line: u32,
) -> Result<Value, RuntimeFailure> {
let node = crate::parser::parse_the_expression(text, self.dialect).map_err(|error| {
RuntimeFailure::Error(RuntimeError {
message: error.message,
line,
})
})?;
self.evaluate(&node)
}
pub(crate) fn the_address_of_a_text(&mut self, text: &str) -> i64 {
let place = {
let mut memory = self.string_memory.borrow_mut();
match memory.iter().position(|candidate| candidate == text) {
Some(place) => place,
None => {
memory.push(text.to_string());
memory.len() - 1
}
}
};
let mut buffers = self.string_buffers.borrow_mut();
while buffers.len() <= place {
buffers.push(None);
}
if buffers[place].is_none() {
let wide: Vec<u16> = text.encode_utf16().chain(core::iter::once(0)).collect();
buffers[place] = Some(wide.into_boxed_slice());
}
buffers[place].as_ref().expect("the block was just made").as_ptr() as i64
}
pub(crate) fn remember_a_buffer_at(&mut self, address: i64, buffer: Value) {
if !self
.buffer_addresses
.iter()
.any(|(held, _)| *held == address)
{
self.buffer_addresses.push((address, buffer));
}
}
pub(crate) fn the_buffer_at(&self, address: i64) -> Option<Value> {
self.buffer_addresses
.iter()
.find(|(held, _)| *held == address)
.map(|(_, buffer)| buffer.clone())
}
pub(crate) fn the_text_at_an_address(&self, address: i64) -> Option<String> {
let buffers = self.string_buffers.borrow();
let block = buffers.iter().flatten().find(|block| block.as_ptr() as i64 == address)?;
let end = block.iter().position(|&letter| letter == 0).unwrap_or(block.len());
Some(String::from_utf16_lossy(&block[..end]))
}
pub(crate) fn assign_the_variable(&mut self, name: &str, value: Value) {
self.assign(name, value);
}
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_borrowed_key(name);
if self.is_declared_static(&name) {
self.the_statics_of_the_frame().insert(name.into_owned(), value);
return;
}
if self.lives_in_the_script(&name) {
self.write_shared_global(&name, &value);
self.write_the_global(&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.into_owned(), value);
return;
}
}
}
match self.scopes.last() {
Some(scope) => {
scope.borrow_mut().insert(name.into_owned(), value);
}
None => {
self.write_shared_global(&name, &value);
self.write_the_global(&name, value);
}
}
}
fn write_the_global(&mut self, name: &str, value: Value) {
if crate::trace::the_vars_are_asked()
&& !the_runtime_owns_the_variable(name)
&& self.variables.get(name) != Some(&value)
{
crate::trace::variable(name, &value.to_text());
}
if let Some(slot) = self.variables.get_mut(name) {
*slot = value;
} else {
self.variables.insert(name.to_string(), 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;
}
if self.the_frame_takes_the_name(name) {
return false;
}
if frame.assume_global {
return true;
}
self.the_name_is_a_super_global(name)
}
fn the_frame_takes_the_name(&self, name: &str) -> bool {
let Some(frame) = self.frames.last() else {
return false;
};
frame.parameters.contains(name)
}
fn the_name_is_a_super_global(&self, name: &str) -> bool {
if !self.dialect.is_the_v1() {
return false;
}
if self.the_name_is_built {
return false;
}
let Some(frame) = self.frames.last() else {
return false;
};
if frame.force_local {
return false;
}
self.super_globals.contains(name)
}
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<SharedCell<Object>> {
let mut chain: Vec<SharedCell<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| SharedCell::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<SharedCell<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 the_struct_layout(&self, class: &str) -> Option<crate::structs::Layout> {
if !self.dialect.the_struct_keyword_is_known() {
return None;
}
let key = class.to_lowercase();
if let Some(kind) = crate::structs::numeric(&key) {
let size = kind.width();
return Some(crate::structs::Layout {
fields: Vec::new(),
size,
align: crate::structs::alignment_of(size),
});
}
if key == "struct" {
return Some(crate::structs::Layout { fields: Vec::new(), size: 0, align: 1 });
}
let definition = self.classes.get(&key)?;
if !definition.is_struct {
return None;
}
let mut fields = Vec::new();
let mut offset = 0usize;
let mut max_align = 1usize;
for field in &definition.fields {
let type_key = field.type_name.to_lowercase();
let (field_type, size, align) =
if let Some(kind) = crate::structs::numeric(&type_key) {
let size = kind.width();
(crate::structs::FieldType::Numeric(kind), size, crate::structs::alignment_of(size))
} else {
let nested = self.the_struct_layout(&type_key)?;
(crate::structs::FieldType::Struct(type_key), nested.size, nested.align)
};
offset = crate::structs::align_up(offset, align);
fields.push(crate::structs::FieldLayout {
name: field.name.to_lowercase(),
offset,
field_type,
});
offset += size;
max_align = max_align.max(align);
}
let size = crate::structs::align_up(offset, max_align);
Some(crate::structs::Layout { fields, size, align: max_align })
}
fn is_struct_instance(&self, value: &Value) -> bool {
if !self.dialect.the_struct_keyword_is_known() {
return false;
}
let Value::Object(object) = value else {
return false;
};
if self.class_name_of(value).is_some() {
return false;
}
let class = object.borrow().class.clone();
if crate::structs::is_a_struct_class_name(&class) {
return true;
}
self.classes.get(&class).map(|d| d.is_struct).unwrap_or(false)
}
fn struct_owner_and_offset(&self, target: &Value) -> (Value, i64) {
let Value::Object(object) = target else {
return (target.clone(), 0);
};
let obj = object.borrow();
let owner = obj.value_of("struct owner").unwrap_or_else(|| target.clone());
let offset = obj
.value_of("struct offset")
.map(|v| v.to_number().unwrap_or(0.0) as i64)
.unwrap_or(0);
(owner, offset)
}
fn construct_struct(
&mut self,
class: &str,
layout: &crate::structs::Layout,
values: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
let object = self.the_object_of_a_class(class);
crate::classes::buffer::allocate(&object, layout.size);
if let Some(kind) = crate::structs::numeric(class) {
if let Some(value) = values.first() {
crate::classes::buffer::write_numbers(&object, 0, &[(kind, value.clone())], line)?;
}
return Ok(object);
}
for (index, field) in layout.fields.iter().enumerate() {
if let (Some(value), crate::structs::FieldType::Numeric(kind)) =
(values.get(index), &field.field_type)
{
crate::classes::buffer::write_numbers(
&object,
field.offset as i64,
&[(*kind, value.clone())],
line,
)?;
}
}
let definition = self.classes.get(&class.to_lowercase()).cloned();
if let Some(definition) = definition {
for field_def in &definition.fields {
let Some(initializer) = &field_def.initializer else {
continue;
};
let Some(field) = layout
.fields
.iter()
.find(|f| f.name == field_def.name.to_lowercase())
else {
continue;
};
let mut scope = BTreeMap::new();
scope.insert("this".to_string(), object.clone());
self.scopes.push(SharedCell::new(scope));
let value = self.evaluate(initializer);
self.scopes.pop();
let value = value?;
if let crate::structs::FieldType::Numeric(kind) = &field.field_type {
crate::classes::buffer::write_numbers(
&object,
field.offset as i64,
&[(*kind, value)],
line,
)?;
}
}
}
Ok(object)
}
fn read_struct_property(
&self,
target: &Value,
name: &str,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let Value::Object(object) = target else {
return None;
};
let class = object.borrow().class.clone();
let layout = self.the_struct_layout(&class)?;
let (owner, offset) = self.struct_owner_and_offset(target);
match name {
"size" => Some(Ok(Value::Int(layout.size as i64))),
"ptr" => Some(
crate::classes::buffer::ptr_of(&owner, line).map(|p| Value::Int(p + offset)),
),
"__value" => crate::structs::numeric(&class).map(|kind| {
crate::classes::buffer::read_number(&owner, offset, kind, line)
}),
_ => {
let field = layout.fields.iter().find(|f| f.name == name)?;
match &field.field_type {
crate::structs::FieldType::Numeric(kind) => Some(
crate::classes::buffer::read_number(
&owner,
offset + field.offset as i64,
*kind,
line,
),
),
crate::structs::FieldType::Struct(struct_class) => {
let view = self.the_object_of_a_class(struct_class);
if let Value::Object(view_object) = &view {
put(&mut view_object.borrow_mut().properties, "struct owner", owner.clone());
put(
&mut view_object.borrow_mut().properties,
"struct offset",
Value::Int(offset + field.offset as i64),
);
}
Some(Ok(view))
}
}
}
}
}
fn write_struct_field(
&self,
target: &Value,
name: &str,
value: &Value,
line: u32,
) -> Result<bool, RuntimeFailure> {
let Value::Object(object) = target else {
return Ok(false);
};
let class = object.borrow().class.clone();
let Some(layout) = self.the_struct_layout(&class) else {
return Ok(false);
};
let (owner, offset) = self.struct_owner_and_offset(target);
if name == "__value" {
if let Some(kind) = crate::structs::numeric(&class) {
crate::classes::buffer::write_numbers(&owner, offset, &[(kind, value.clone())], line)?;
return Ok(true);
}
}
if let Some(field) = layout.fields.iter().find(|f| f.name == name) {
if let crate::structs::FieldType::Numeric(kind) = &field.field_type {
crate::classes::buffer::write_numbers(
&owner,
offset + field.offset as i64,
&[(*kind, value.clone())],
line,
)?;
return Ok(true);
}
}
Ok(false)
}
fn construct(
&mut self,
class: &str,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if let Some(layout) = self.the_struct_layout(class) {
let values = self.evaluate_all(arguments)?;
return self.construct_struct(class, &layout, &values, line);
}
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 let Some(layout) = self.the_struct_layout(class) {
return self.construct_struct(class, &layout, values, line);
}
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(SharedCell::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(SharedCell::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: &SharedCell<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 the_super_class_object(&self) -> Option<Value> {
self.class_name_of(&self.the_this())?;
let base = self.the_base_of_the_running_method()?;
self.class_value_of(&base)
}
fn call_the_method_of_the_base(
&mut self,
name: &str,
arguments: &[Node],
line: u32,
) -> Result<Value, RuntimeFailure> {
if let Some(class_object) = self.the_super_class_object() {
return self.call_method_on(&class_object, name, arguments, line);
}
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> {
if let Some(class_object) = self.the_super_class_object() {
return self.read_property(&class_object, name, line);
}
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> {
if let Some(class_object) = self.the_super_class_object() {
return self.index_a_value(&class_object, keys, line);
}
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()));
}
}
if self.dialect.the_item_of_an_object_is_its_property()
&& name.eq_ignore_ascii_case("haskey")
{
if let Some(answer) = self.the_haskey_of_the_v1(target, arguments, line)? {
return Ok(answer);
}
}
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()
&& self.the_class_of_the_prototype(target).is_none()
{
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 values = self.the_aliases_of_the_v1(arguments, values, &method.parameters);
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 {
match value {
Value::Reference(reference) => {
let mut alias = reference;
alias.alias = true;
scope.insert(the_key_of(¶meter.name), Value::Reference(alias));
continue;
}
value if self.dialect.is_the_v1() => {
scope.insert(the_key_of(¶meter.name), value);
continue;
}
value => {
return Err(RuntimeFailure::Error(RuntimeError {
message: wants_a_reference(
index + 1,
&method.name,
"a variable reference",
&value,
),
line,
}));
}
}
}
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(SharedCell::new(scope));
self.current_classes.push(class.to_lowercase());
self.frames.push(Frame {
name: frame,
line,
closed_frames: Vec::new(),
parameters: the_names_of_the_parameters(&method.parameters),
force_local: the_body_is_in_the_force_local_mode(&method.body),
});
self.collect_the_nested_functions(&method.body);
self.declarations.push(method.declarations.clone());
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),
}
}
pub(crate) 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) => SharedCell::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_and_its_base(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_and_its_base(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());
}
if class == "gui" {
for nested in crate::classes::gui::the_nested_names() {
let member = nested
.strip_prefix("Gui.")
.unwrap_or(nested)
.to_string();
names.push(member);
}
}
}
}
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(SharedCell::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(SharedCell::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(SharedCell::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(SharedCell::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(SharedCell::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))),
"minindex" => Some(Ok(the_index_of_the_v1(
crate::classes::array::the_indexes_with_a_value(target)
.first()
.copied(),
))),
"maxindex" => Some(Ok(the_index_of_the_v1(
crate::classes::array::the_indexes_with_a_value(target)
.last()
.copied(),
))),
"haskey" => {
let Some(key) = arguments.first() else {
return Some(Ok(Value::Text(String::new())));
};
Some(Ok(Value::Int(
self.the_key_of_the_v1_is_there(target, key) as i64
)))
}
_ => None,
}
}
fn the_haskey_of_the_v1(
&mut self,
target: &Value,
arguments: &[Node],
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
let Some(argument) = arguments.first() else {
return Ok(None);
};
let key = match argument {
Node::Literal {
value: LiteralValue::Number(text),
..
} => match text.trim().parse::<i64>() {
Ok(number) => TheKeyOfTheV1::TheNumber(number),
Err(_) => return Ok(None),
},
Node::Literal {
value: LiteralValue::Text(text),
..
} => TheKeyOfTheV1::TheText(self.interpolate(text, line)?),
_ => return Ok(None),
};
let Value::Object(object) = target else {
return Ok(None);
};
let answer = if object.borrow().properties.contains_key("array state") {
match key {
TheKeyOfTheV1::TheNumber(number) => crate::classes::array::has_the_key(target, number),
TheKeyOfTheV1::TheText(text) => object
.borrow()
.properties
.contains_key(&text.to_lowercase()),
}
} else {
let name = match key {
TheKeyOfTheV1::TheNumber(number) => number.to_string(),
TheKeyOfTheV1::TheText(text) => text,
};
object
.borrow()
.properties
.contains_key(&name.to_lowercase())
};
Ok(Some(Value::Int(answer as i64)))
}
fn the_key_of_the_v1_is_there(&self, target: &Value, key: &Value) -> bool {
let Value::Object(object) = target else {
return false;
};
if object.borrow().properties.contains_key("array state") {
let Some(index) = the_index_of_the_key_of_the_v1(key) else {
let name = key.to_text().to_lowercase();
return object.borrow().properties.contains_key(&name);
};
return crate::classes::array::has_the_key(target, index);
}
let name = key.to_text();
object
.borrow()
.properties
.contains_key(&name.to_lowercase())
}
fn the_static_of_the_class_of_the_value(&self, target: &Value, name: &str) -> Option<Value> {
let Value::Object(object) = target else {
return None;
};
let class = object.borrow().class.clone();
let class_value = self.class_value_of(&class)?;
let Value::Object(class_object) = class_value else {
return None;
};
class_object.borrow().value_of(name)
}
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_and_its_base(&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_and_its_base(&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) => SharedCell::ptr_eq(one, base),
_ => false,
}) as i64)));
}
let chain = self.the_chain_of_the_bases(target);
Some(Ok(Value::Int(
chain.iter().any(|object| SharedCell::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") {
object.borrow().properties.contains_key(&lower)
&& !the_intrinsic_member_of_a_function(&lower)
} 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,
)));
}
let the_class = object.borrow().class.clone();
let is_a_function = matches!(the_class.as_str(), "func" | "closure");
let mut own: Vec<(String, Value)> = object
.borrow()
.properties
.iter()
.filter(|(name, _)| {
name.as_str() != BASE
&& name.as_str() != CLASS_NAME
&& !(is_a_function && the_intrinsic_member_of_a_function(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(SharedCell::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(SharedCell::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 the_rewritten_call_of(
&mut self,
target: &Value,
arguments: &[Value],
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let call = self.the_call_of_the_descriptor(target, "Call")?;
Some(self.call_the_function(&call, target, arguments, line))
}
pub fn the_callback_runs(
&mut self,
function: &Value,
arguments: &[Value],
) -> Result<Value, RuntimeError> {
self.callbacks_running += 1;
let answer = crate::classes::func::call_the_value(function, arguments, self, 0);
self.callbacks_running -= 1;
match answer {
Some(result) => result.map_err(|failure| as_error(failure, 0)),
None => Err(RuntimeError {
message: "the callback is not a function.".to_string(),
line: 0,
}),
}
}
pub fn the_callback_of_a_name_runs(
&mut self,
name: &str,
arguments: &[Value],
) -> Result<Value, RuntimeError> {
self.callbacks_running += 1;
let answer = self.call_named(name, arguments, 0, crate::runtime::Route::Written);
self.callbacks_running -= 1;
answer.map_err(|failure| as_error(failure, 0))
}
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(SharedCell::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(SharedCell::new(Object {
class: "boundfunc".to_string(),
properties,
}))
}
pub(crate) fn bound_function_with_args(&self, args: Vec<Value>, target: Value) -> Value {
let first = args.first().cloned().unwrap_or(Value::Text(String::new()));
let value = self.bound_function(first, target);
if let Value::Object(object) = &value {
put(
&mut object.borrow_mut().properties,
BOUND_ARGS,
Value::List(args),
);
}
value
}
pub(crate) fn call_the_bound_args(
&mut self,
bound: &[Value],
target: &Value,
arguments: &[Value],
line: u32,
) -> Result<Value, RuntimeFailure> {
let mut merged: Vec<Value> = Vec::with_capacity(bound.len() + arguments.len());
let mut given = arguments.iter();
for slot in bound {
if matches!(slot, Value::Text(text) if text.is_empty()) {
merged.push(given.next().cloned().unwrap_or(Value::Text(String::new())));
} else {
merged.push(slot.clone());
}
}
merged.extend(given.cloned());
let class = match target {
Value::Object(object) => object.borrow().class.clone(),
_ => String::new(),
};
match crate::classes::call_the_value(&class, target, &merged, self, line) {
Some(result) => result,
None => Err(self.no_method(target, &target.to_text(), line)),
}
}
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(SharedCell::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();
if self.is_struct_instance(target) {
if let Some(result) = self.read_struct_property(target, &name, line) {
return result.map(|value| (value, false));
}
}
if name == "size" {
if let Some(class) = self.class_name_of(target) {
if let Some(layout) = self.the_struct_layout(&class) {
return Ok((Value::Int(layout.size as i64), false));
}
}
}
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
|| self.dialect.the_class_value_hands_over_its_methods()
{
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));
}
{
let mut base = self.the_base_of_the_value(target);
let mut depth = 0;
while let Some(current) = base {
if depth >= 64 {
break;
}
depth += 1;
if let Value::Object(base_object) = ¤t {
if let Some(value) = base_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));
}
}
base = self.the_base_of_the_value(¤t);
}
}
if self
.dialect
.the_static_of_a_class_is_a_member_of_the_instance()
{
if let Some(value) = self.the_static_of_the_class_of_the_value(target, &name) {
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()
|| self.dialect.the_class_value_hands_over_its_methods()
{
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();
if self.is_struct_instance(target) && self.write_struct_field(target, &name, &value, line)? {
return Ok(());
}
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 lower = name.to_lowercase();
if class == "gui" {
if let Some(nested) = crate::classes::gui::the_nested_of_the_window(&lower) {
return self.class_value_of(nested);
}
}
let definition = self.classes.get(&class)?;
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, self.dialect) {
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 one valid expression.".to_string(),
line,
})),
},
"if" | "ifwinactive" => match the_condition_of_a_v1_if(name, argument, self.dialect) {
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 the #If is not one valid expression.".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" => {
self.persistent = true;
Ok("the script stays alive after its statements".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),
"inputlevel" => {
the_number_of_a_directive(argument, "#InputLevel", line)?;
Ok("the level of the keyboard is the one of the box".into())
}
"clipboardtimeout" => {
the_number_of_a_directive(argument, "#ClipboardTimeout", line)?;
Ok("the timeout of the clipboard is the one of the box".into())
}
"winactivateforce" => {
Ok("the window of the box is activated the way it wants".into())
}
"maxmem" => Ok("the memory of a variable is not limited by this runtime".into()),
"commentflag" => Ok("the comment flag is read when the script is read".into()),
"escapechar" => Ok("the escape character is read when the script is read".into()),
"installkeybdhook" => Ok("the keyboard is watched with the hook of the tree".into()),
"installmousehook" => Ok("the mouse is watched with the hook of the tree".into()),
"menumaskkey" => Ok("the mask key is the one of the tree".into()),
"keyhistory" => Ok("the history of the keys is not kept by this runtime".into()),
"maxhotkeysperinterval" | "hotkeyinterval" | "hotkeymodifiertimeout" => {
Ok("the hotkeys are not rate-limited by this runtime".into())
}
"iftimeout" => Ok("the condition of a hotkey answers at once".into()),
"usehook" => Ok("the hook of the keyboard is the one of the box".into()),
"maxthreads" => {
the_number_of_a_directive(argument, "#MaxThreads", line)?;
Ok("the runtime is one thread".into())
}
"maxthreadsperhotkey" => {
the_number_of_a_directive(argument, "#MaxThreadsPerHotkey", line)?;
Ok("the runtime is one thread".into())
}
"maxthreadsbuffer" => {
let arg = argument.trim();
let arg = arg.strip_prefix(',').unwrap_or(arg).trim();
let value = match arg.to_ascii_lowercase().as_str() {
"" | "0" | "off" => 0.0,
"1" | "on" => 1.0,
_ => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Parameter #1 of #MaxThreadsBuffer is invalid.".into(),
line,
}));
}
};
let _ = value;
Ok("the buffer of the threads is the one of the box".into())
}
"dllload" => {
let name = argument.trim();
self.desktop()
.load_library(name)
.map_err(|why| RuntimeFailure::Error(RuntimeError { message: why, line }))?;
Ok(format!("the library {name} is loaded"))
}
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 {
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 / 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 {
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::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("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_value_of_a_literal_in_a_container(&self, node: &Node, value: Value) -> Value {
let Node::Literal {
value: LiteralValue::Number(text),
..
} = node
else {
return value;
};
let text = crate::v1::the_text_of_the_number_that_fits(text);
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,
}
}
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 self.dialect.the_index_with_a_comma_is_a_chain() && keys.len() > 1 {
let mut current = target.clone();
for key in keys {
current = self.index_a_value(¤t, core::slice::from_ref(key), line)?;
}
return Ok(current);
}
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_in_the_maths(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)
}
pub(crate) 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_default_member_is_written(
&mut self,
target: &Value,
_op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
if let Some(object) = crate::classes::comvalue::the_object_of(target) {
let com = crate::classes::comvalue::the_com_value_of(&value);
self.desktop()
.com_default_is_written(&object, com)
.map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line,
})
})?;
}
Ok(value)
}
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))
}
LegacyForm::Is => {
let kind = items.first().map(String::as_str).unwrap_or_default();
crate::v1::the_value_is_of_the_type(&text_of_the_value, kind)
}
};
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.to_lowercase()).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)
|| (self.dialect.the_struct_keyword_is_known()
&& crate::structs::is_a_struct_class_name(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);
}
if let Some(value) = self.lookup(name) {
if self.the_call_of_the_descriptor(&value, "Call").is_some() {
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);
}
for (index, argument) in arguments.iter().enumerate() {
if !matches!(argument, Node::Empty { .. }) {
continue;
}
if index < builtin.min as usize {
return Err(self.the_missing_parameter("", line));
}
}
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);
let keeps_the_variable = self
.dialect
.every_argument_that_is_a_variable_keeps_it(builtin.name);
for (index, argument) in arguments.iter().enumerate() {
if keeps_the_variable {
if let Node::Var { name, .. } = argument {
values.push(Value::Reference(Reference {
name: name.clone(),
scope: self.the_scope_of(name),
alias: false,
}));
continue;
}
}
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 values = self.the_aliases_of_the_v1(arguments, values, &function.parameters);
let missing: Vec<bool> = arguments
.iter()
.map(|argument| matches!(argument, Node::Empty { .. }))
.collect();
self.call_function_with(function, &values, line, route, &missing)
}
fn the_aliases_of_the_v1(
&mut self,
arguments: &[Node],
mut values: Vec<Value>,
parameters: &[crate::ast::Parameter],
) -> Vec<Value> {
if !self.dialect.is_the_v1() {
return values;
}
for (index, parameter) in parameters.iter().enumerate() {
if !parameter.by_ref || index >= values.len() {
continue;
}
if let Some(Node::Var { name, .. }) = arguments.get(index) {
let scope = self.the_scope_of(name);
values[index] = Value::Reference(Reference {
name: name.clone(),
scope,
alias: true,
});
}
}
values
}
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 {
match value {
Value::Reference(reference) => {
let mut alias = reference;
alias.alias = true;
scope.insert(the_key_of(¶meter.name), Value::Reference(alias));
continue;
}
value if self.dialect.is_the_v1() => {
scope.insert(the_key_of(¶meter.name), value);
continue;
}
value => {
return Err(RuntimeFailure::Error(RuntimeError {
message: wants_a_reference(
index + 1,
&function.name,
"a variable reference",
&value,
),
line,
}));
}
}
}
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(SharedCell::new(scope));
self.frames.push(Frame {
name: function.name.clone(),
line,
closed_frames: function.closure_frames.clone(),
parameters: the_names_of_the_parameters(&function.parameters),
force_local: the_body_is_in_the_force_local_mode(&function.body),
});
self.collect_the_nested_functions(&function.body);
self.declarations.push(function.declarations.clone());
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.write_shared_global(&name, &value);
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 = if matches!(op, AssignOp::Set) {
None
} else {
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());
self.the_text_is_written_into_the_buffer(name, &stored);
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 fn the_number_of_parameters_of(&self, name: &str) -> Option<usize> {
self.functions
.get(&name.to_lowercase())
.map(|function| {
function
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count()
})
}
pub fn the_declared_parameters_of(&self, name: &str) -> Option<usize> {
self.functions
.get(&name.to_lowercase())
.map(|function| function.parameters.len())
}
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> {
if self.dialect.is_the_v1() && name.eq_ignore_ascii_case("critical") {
let word = match parameters.first() {
Some(crate::ast::LegacyParameter::Text(text)) => text.trim().to_string(),
Some(crate::ast::LegacyParameter::Expression(node)) => {
self.evaluate(node)?.to_text().trim().to_string()
}
None => String::new(),
};
self.critical = word.is_empty()
|| word.eq_ignore_ascii_case("on")
|| the_leading_number_of(&word).is_some_and(|number| number != 0);
return Ok(Value::Int(0));
}
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, dereferenced) =
self.the_name_of_the_output(&the_text_of_the_parameter(parameter), line)?;
let scope = if dereferenced {
Scope::Global
} else {
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 => match self.the_built_in_variable(&name) {
Some(Ok(value)) => Ok(value),
Some(Err(error)) => Err(RuntimeFailure::Error(error)),
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_name_of_the_output(
&mut self,
text: &str,
line: u32,
) -> Result<(String, bool), RuntimeFailure> {
let trimmed = text.trim();
let inner = trimmed
.strip_prefix('%')
.and_then(|rest| rest.strip_suffix('%'))
.map(|name| name.trim())
.filter(|name| !name.is_empty());
let Some(inner) = inner else {
return Ok((trimmed.to_string(), false));
};
Ok((
match self.the_value_of_the_substitution(inner, line)? {
Some(value) => self.the_text_of(&value).trim().to_string(),
None => String::new(),
},
true,
))
}
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_loop_is_fast(&self, body: &[Node], until: &Option<Box<Node>>, otherwise: &Option<Vec<Node>>) -> bool {
if !self.scopes.is_empty()
|| until.is_some()
|| otherwise.as_ref().is_some_and(|v| !v.is_empty())
|| body.is_empty()
{
return false;
}
body.iter().all(|statement| self.the_statement_is_fast(statement))
}
fn the_statement_is_fast(&self, statement: &Node) -> bool {
match statement {
Node::Assign { name, value, .. } => {
self.the_name_is_a_fast_variable(name) && self.the_expression_is_fast(value)
}
Node::Expression { value, .. } => match value.as_ref() {
Node::Unary { op, operand, .. } => {
matches!(
op,
crate::ast::UnaryOp::PostIncrement
| crate::ast::UnaryOp::PostDecrement
| crate::ast::UnaryOp::PreIncrement
| crate::ast::UnaryOp::PreDecrement
) && matches!(operand.as_ref(), Node::Var { name, .. } if self.the_name_is_a_fast_variable(name))
}
_ => false,
},
_ => false,
}
}
fn the_name_is_a_fast_variable(&self, name: &str) -> bool {
let key = the_borrowed_key(name);
!key.starts_with("a_")
&& !self.functions.contains_key(&*key)
&& !self.classes.contains_key(&*key)
&& !crate::classes::is_type(&key)
}
fn the_expression_is_fast(&self, expression: &Node) -> bool {
match expression {
Node::Literal { value, .. } => matches!(
value,
crate::ast::LiteralValue::Integer(_)
| crate::ast::LiteralValue::Float(_)
| crate::ast::LiteralValue::Bool(_)
),
Node::Var { name, .. } => self.the_name_is_a_fast_variable(name),
Node::Unary { op, operand, .. } => {
matches!(
op,
crate::ast::UnaryOp::Negate
| crate::ast::UnaryOp::Plus
| crate::ast::UnaryOp::Not
| crate::ast::UnaryOp::BitwiseNot
) && self.the_expression_is_fast(operand)
}
Node::Binary { op, left, right, .. } => {
use crate::ast::BinaryOp::*;
matches!(
op,
Add | Subtract | Multiply | Divide | IntegerDivide | Power
| BitwiseAnd | BitwiseOr | BitwiseXor
| ShiftLeft | ShiftRight | ShiftRightUnsigned
) && self.the_expression_is_fast(left)
&& self.the_expression_is_fast(right)
}
Node::Group { items, .. } => {
items.len() == 1 && self.the_expression_is_fast(&items[0])
}
_ => false,
}
}
fn run_the_fast_loop(
&mut self,
body: &[Node],
count: i64,
) -> Result<(), RuntimeFailure> {
let mut names: Vec<String> = Vec::new();
for statement in body {
self.collect_the_fast_names(statement, &mut names);
}
let mut registers: Vec<Value> = names
.iter()
.map(|name| {
self.variables
.get(&*the_borrowed_key(name))
.cloned()
.unwrap_or(Value::Unset)
})
.collect();
let the_index = |name: &str| -> usize {
names
.iter()
.position(|n| n.eq_ignore_ascii_case(name))
.unwrap_or(0)
};
let mut turn = 1i64;
let mut last_pump = self.now_ms();
let outcome = (|| -> Result<(), RuntimeFailure> {
while turn <= count {
if turn % 256 == 0 {
let now = self.now_ms();
if now.saturating_sub(last_pump) >= 10 {
last_pump = now;
self.the_fast_loop_is_pumped()?;
if let Some(jump) = self.the_jump_the_pump_asked_for.take() {
return Err(jump);
}
}
}
for statement in body {
match statement {
Node::Assign { name, op, value, line } => {
let value = self.eval_the_fast_expression(
value, ®isters, &the_index, *line,
)?;
let index = the_index(name);
registers[index] = if matches!(op, AssignOp::Set) {
value
} else {
self.apply_assign(
*op,
name,
Some(registers[index].clone()),
value,
*line,
)?
};
}
Node::Expression { value, .. } => {
if let Node::Unary { op, operand, line } = value.as_ref() {
if let Node::Var { name, .. } = operand.as_ref() {
let delta = match op {
crate::ast::UnaryOp::PostIncrement
| crate::ast::UnaryOp::PreIncrement => 1i64,
_ => -1i64,
};
let index = the_index(name);
registers[index] = match ®isters[index] {
Value::Int(number) => {
Value::Int(number.wrapping_add(delta))
}
other => self.apply_assign(
AssignOp::Add,
name,
Some(other.clone()),
Value::Int(delta),
*line,
)?,
};
}
}
}
_ => {}
}
}
turn += 1;
}
Ok(())
})();
for (name, register) in names.iter().zip(registers) {
self.write_the_global(&the_borrowed_key(name), register);
}
outcome
}
fn the_fast_loop_is_pumped(&mut self) -> Result<(), RuntimeFailure> {
let statements = self.the_statements_of_the_script.clone();
self.the_machine_is_pumped(&statements)
}
fn collect_the_fast_names(&self, node: &Node, names: &mut Vec<String>) {
match node {
Node::Assign { name, value, .. } => {
if !names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
names.push(name.clone());
}
self.collect_the_fast_names(value, names);
}
Node::Var { name, .. } => {
if !names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
names.push(name.clone());
}
}
Node::Unary { operand, .. } => self.collect_the_fast_names(operand, names),
Node::Binary { left, right, .. } => {
self.collect_the_fast_names(left, names);
self.collect_the_fast_names(right, names);
}
Node::Group { items, .. } => {
for item in items {
self.collect_the_fast_names(item, names);
}
}
Node::Expression { value, .. } => self.collect_the_fast_names(value, names),
_ => {}
}
}
fn eval_the_fast_expression(
&self,
expression: &Node,
registers: &[Value],
the_index: &dyn Fn(&str) -> usize,
_line: u32,
) -> Result<Value, RuntimeFailure> {
match expression {
Node::Literal { value, .. } => Ok(match value {
crate::ast::LiteralValue::Integer(number) => Value::Int(*number),
crate::ast::LiteralValue::Float(number) => Value::Float(*number),
crate::ast::LiteralValue::Bool(answer) => Value::Int(*answer as i64),
_ => Value::Unset,
}),
Node::Var { name, .. } => Ok(registers[the_index(name)].clone()),
Node::Group { items, .. } => {
self.eval_the_fast_expression(&items[0], registers, the_index, _line)
}
Node::Unary { op, operand, line } => {
let value =
self.eval_the_fast_expression(operand, registers, the_index, *line)?;
match op {
crate::ast::UnaryOp::Negate => {
Ok(match self.the_number_value(&value, *line)? {
Value::Int(number) => Value::Int(number.wrapping_neg()),
Value::Float(number) => Value::Float(-number),
other => other,
})
}
crate::ast::UnaryOp::Plus => self.the_number_value(&value, *line),
crate::ast::UnaryOp::Not | crate::ast::UnaryOp::NotWord => {
Ok(Value::Int(!value.truthy() as i64))
}
crate::ast::UnaryOp::BitwiseNot => Ok(Value::Int(
!self.the_whole_number(&value, *line, TypeName::Number)?,
)),
_ => Ok(Value::Unset),
}
}
Node::Binary { op, left, right, line } => {
let left =
self.eval_the_fast_expression(left, registers, the_index, *line)?;
let right =
self.eval_the_fast_expression(right, registers, the_index, *line)?;
self.the_fast_binary_value(*op, &left, &right, *line)
}
_ => Ok(Value::Unset),
}
}
fn the_fast_binary_value(
&self,
op: BinaryOp,
left: &Value,
right: &Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
use crate::ast::BinaryOp::*;
match op {
Add | Subtract | Multiply => {
let a = self.the_number_value(left, line)?;
let b = self.the_number_value(right, line)?;
Ok(match (&a, &b) {
(Value::Int(a), Value::Int(b)) => Value::Int(match op {
Add => a.wrapping_add(*b),
Subtract => a.wrapping_sub(*b),
_ => a.wrapping_mul(*b),
}),
_ => {
let a = a.to_number().unwrap_or(0.0);
let b = b.to_number().unwrap_or(0.0);
Value::Float(match op {
Add => a + b,
Subtract => a - b,
_ => a * b,
})
}
})
}
Divide => {
let a = self.number(left, line)?;
let b = self.number(right, line)?;
if b == 0.0 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Ok(Value::Float(a / b))
}
IntegerDivide => {
let a = self.integer(left, line)?;
let b = self.integer(right, line)?;
if b == 0 {
return Err(RuntimeFailure::Error(RuntimeError {
message: "Divide by zero.".into(),
line,
}));
}
Ok(Value::Int(a.wrapping_div(b)))
}
Power => {
let a = self.the_number_value(left, line)?;
let b = self.the_number_value(right, 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));
}
}
}
Ok(Value::Float(powf(
a.to_number().unwrap_or(0.0),
b.to_number().unwrap_or(0.0),
)))
}
BitwiseAnd | BitwiseOr | BitwiseXor => {
let a = self.integer(left, line)?;
let b = self.integer(right, line)?;
Ok(Value::Int(match op {
BitwiseAnd => a & b,
BitwiseOr => a | b,
_ => a ^ b,
}))
}
ShiftLeft | ShiftRight | ShiftRightUnsigned => {
let a = self.integer(left, line)?;
let b = self.shift(right, line)?;
Ok(Value::Int(match op {
ShiftLeft => a.wrapping_shl(b),
ShiftRight => a.wrapping_shr(b),
_ => ((a as u64) >> b) as i64,
}))
}
_ => Ok(Value::Unset),
}
}
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(_) | Value::Unset) || !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
}
#[cfg(feature = "std")]
pub(crate) fn the_menu_of_the_script_is_shown(
&mut self,
menu: u64,
x: Option<i32>,
y: Option<i32>,
) -> Result<Option<String>, String> {
let desktop: *mut (dyn crate::runtime::Desktop + 'a) = self.desktop();
let previous = crate::callback::set_current(self);
let answer = match (x, y) {
(Some(x), Some(y)) => unsafe { (*desktop).menu_show_at(menu, x, y) },
_ => unsafe { (*desktop).menu_show(menu) },
};
crate::callback::clear_current(previous);
answer
}
#[cfg(not(feature = "std"))]
pub(crate) fn the_menu_of_the_script_is_shown(
&mut self,
menu: u64,
x: Option<i32>,
y: Option<i32>,
) -> Result<Option<String>, String> {
let desktop: *mut (dyn crate::runtime::Desktop + 'a) = self.desktop();
match (x, y) {
(Some(x), Some(y)) => unsafe { (*desktop).menu_show_at(menu, x, y) },
_ => unsafe { (*desktop).menu_show(menu) },
}
}
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) {
if let Err(failure) = self.run_the_events_of_the_com(millis) {
let message = the_message_of(&failure);
self.note(format!("the function of the event failed: {message}"));
}
self.clock.sleep_ms(millis)
}
#[cfg(feature = "std")]
fn the_events_of_the_com_are_taken(&mut self, wait_ms: u64) -> Vec<crate::desktop::ComEvent> {
let desktop: *mut (dyn crate::runtime::Desktop + 'a) = self.desktop();
let previous = crate::callback::set_current(self);
let events = unsafe { (*desktop).com_events_are_taken(wait_ms) };
crate::callback::clear_current(previous);
events
}
#[cfg(not(feature = "std"))]
fn the_events_of_the_com_are_taken(&mut self, wait_ms: u64) -> Vec<crate::desktop::ComEvent> {
let desktop: *mut (dyn crate::runtime::Desktop + 'a) = self.desktop();
unsafe { (*desktop).com_events_are_taken(wait_ms) }
}
pub(crate) fn run_the_events_of_the_com(&mut self, wait_ms: u64) -> Result<(), RuntimeFailure> {
let events = self.the_events_of_the_com_are_taken(wait_ms);
for event in events {
let Some(function) = self.the_function_of_the_script(&event.name) else {
continue;
};
let object = crate::classes::comvalue::the_value(event.object, event.kind, 0);
let mut values: Vec<Value> = event
.arguments
.iter()
.map(|argument| match argument {
crate::desktop::ComValue::Number(number) => {
if *number == crate::math::trunc(*number)
&& number.abs() < (i64::MAX as f64)
{
Value::Int(*number as i64)
} else {
Value::Float(*number)
}
}
crate::desktop::ComValue::Text(text) => Value::Text(text.clone()),
crate::desktop::ComValue::Pointer(pointer) => Value::Int(*pointer as i64),
})
.collect();
values.push(object);
let answer = crate::classes::func::call_the_value(&function, &values, self, 0);
match answer {
Some(Ok(_)) | None => {}
Some(Err(failure)) => return Err(failure),
}
}
Ok(())
}
pub(crate) fn now_ms(&self) -> u64 {
self.clock.now_ms()
}
pub(crate) fn tick_count(&self) -> u64 {
self.clock.since_the_machine_started().unwrap_or_else(|| self.clock.now_ms())
}
pub(crate) fn hotkeys(&mut self) -> &mut Vec<crate::hotkeys::Hotkey> {
&mut self.hotkeys
}
pub(crate) fn run_the_body_of_a_label(
&mut self,
name: &str,
statements: &[Node],
line: u32,
) -> Result<(), RuntimeFailure> {
let Some(place) = the_place_of_the_label(statements, name) else {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!("Nonexistent label.\n Specifically: {name}"),
line,
}));
};
let mut body = Vec::new();
for statement in statements.iter().skip(place + 1) {
if matches!(statement, Node::Label { .. }) {
break;
}
body.push(statement.clone());
}
self.run_the_body_of_a_hotkey(&body)
}
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 is_critical(&self) -> bool {
self.critical
}
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) {
let key = the_borrowed_key(name);
self.write_shared_global(&key, &value);
self.write_the_global(&key, 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))
}
}
}
pub(crate) fn the_truth_of_the_expression(
&mut self,
node: &Node,
) -> Result<bool, RuntimeFailure> {
Ok(self.evaluate(node)?.truthy())
}
fn evaluate(&mut self, node: &Node) -> Result<Value, RuntimeFailure> {
match node {
Node::VarRef { name, .. } => Ok(Value::Reference(Reference {
name: name.clone(),
scope: self.the_scope_of(name),
alias: false,
})),
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 name.is_empty() {
self.evaluate(value)?;
return Ok(Value::Text(String::new()));
}
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::AssignCall {
call,
op,
value,
line,
} => {
let target = self.evaluate(call)?;
let value = self.evaluate(value)?;
self.the_default_member_is_written(&target, *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)?;
self.the_warning_of_the_unset_read = None;
let the_value = self.evaluate(value)?;
self.warn_the_unset_read_again(value);
let the_value =
self.the_value_of_a_literal_in_a_container(value, the_value);
let value = the_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 the_value = self.evaluate(value)?;
let the_value =
self.the_value_of_a_literal_in_a_container(value, the_value);
put(&mut cell.borrow_mut().properties, &key.to_text(), the_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())),
tail: Vec::new(),
line: *line,
}],
declarations: Declarations::default(),
closure: self.scopes.clone(),
closure_frames: self.frames.iter().map(|frame| frame.name.clone()).collect(),
};
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) => {
let value = self.evaluate(item)?;
values.push(Some(
self.the_value_of_a_literal_in_a_container(item, value),
));
}
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 } => {
if let Some(class_object) = self.the_super_class_object() {
return Ok(class_object);
}
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 name = match operand.as_ref() {
Node::Var { name, .. } => name,
Node::Assign { name, .. } => {
self.evaluate(operand)?;
name
}
_ => {
return Err(RuntimeFailure::Error(RuntimeError {
message: "\"&\" requires a variable.".into(),
line: *line,
}));
}
};
if self.dialect.is_the_v1() {
let reference = Reference {
name: name.clone(),
scope: self.the_scope_of(name),
alias: false,
};
let address = self.the_variable_address(&reference);
return Ok(Value::Int(address));
}
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));
}
self.the_warning_of_the_unset_read = None;
let left_value = self.evaluate(left)?;
if the_operator_is_a_comparison(op) {
self.warn_the_unset_read_again(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));
}
_ => {}
}
self.the_warning_of_the_unset_read = None;
let right_value = self.evaluate(right)?;
if the_operator_is_a_comparison(op) {
self.warn_the_unset_read_again(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 => {
if self.dialect.is_the_v1() {
let a = left_value.to_number().ok_or_else(|| {
RuntimeFailure::Error(RuntimeError {
message: expected_number(&left_value),
line,
})
})?;
let b = right_value.to_number().ok_or_else(|| {
RuntimeFailure::Error(RuntimeError {
message: expected_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,
}));
}
let whole = (a / b) as i64;
return Ok(if matches!(
(&left_value, &right_value),
(Value::Int(_), Value::Int(_))
) {
Value::Int(whole)
} else {
Value::Float(whole as f64)
});
}
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::CallDynamic {
name,
arguments,
line,
} => {
let resolved = self.the_name_of_the_pieces(name, *line)?;
self.call(&resolved, 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)?;
let built = self.the_name_is_built;
self.the_name_is_built = true;
let answer = self.the_variable_of_the_name(&name, *line);
self.the_name_is_built = built;
match answer? {
Some(value) => Ok(value),
None => {
if self.dialect.is_the_v1() {
if let Some(value) = self.the_global_of_the_dynamic_name(&name) {
return Ok(value);
}
}
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::Gosub { .. }
| 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));
};
if self.dialect.the_index_with_a_comma_is_a_chain() && keys.len() > 1 {
let mut current = target.clone();
for key in &keys[..keys.len() - 1] {
let next = self.index_a_value(¤t, core::slice::from_ref(key), line)?;
current = match next {
Value::Object(_) => next,
_ => {
let nested = crate::classes::array::of_items(Vec::new());
self.set_item(
¤t,
core::slice::from_ref(key),
AssignOp::Set,
nested.clone(),
line,
)?;
nested
}
};
}
let last = keys.last().expect("keys has at least two elements");
return self.set_item(¤t, core::slice::from_ref(last), op, value, 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,
}));
}
}
}
}
}
if !self.dialect.the_name_that_the_script_builds_is_legal(&name) {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"The following variable name contains an illegal character:\n\"{name}\""
),
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 the_global_of_the_dynamic_name(&self, name: &str) -> Option<Value> {
let key = the_borrowed_key(name);
if self.is_declared_local(&key) {
return Some(Value::Text(String::new()));
}
if self.the_frame_takes_the_name(&key) {
return Some(Value::Text(String::new()));
}
if let Some(value) = self.read_shared_global(&key) {
return Some(value);
}
self.variables.get(&*key).cloned()
}
fn write_a_dynamic_name(
&mut self,
name: &str,
op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
let built = self.the_name_is_built;
self.the_name_is_built = true;
let answer = self.write_the_name_that_the_script_builds(name, op, value, line);
self.the_name_is_built = built;
answer
}
fn write_the_name_that_the_script_builds(
&mut self,
name: &str,
op: AssignOp,
value: Value,
line: u32,
) -> Result<Value, RuntimeFailure> {
let key = the_key_of(name);
if self.dialect.is_the_v1() && name.is_empty() {
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(),
},
));
}
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(),
},
));
}
if self.declarations.last().is_some() && self.dialect.is_the_v1() {
let is_local = self
.scopes
.last()
.map(|scope| scope.borrow().contains_key(&key))
.unwrap_or(false)
|| self.is_declared_local(&key);
if !is_local {
let current = self.variables.get(&key).cloned();
let stored = self.apply_assign(op, name, current, value, line)?;
self.write_the_global(&key, stored.clone());
self.write_shared_global(&key, &stored);
return Ok(stored);
}
}
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) {
if self.dialect.is_the_v1() {
let current = self.lookup_variable(&key);
let stored = self.apply_assign(op, name, current, value, line)?;
self.write_the_global(&key, stored.clone());
self.write_shared_global(&key, &stored);
return Ok(stored);
}
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)
}
pub(crate) fn the_callback_with_one_argument(
&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_one = match self.functions.get(&function_name.to_lowercase()) {
Some(function) => {
!function.parameters.is_empty()
|| function
.parameters
.iter()
.any(|parameter| parameter.variadic)
}
None => number_of(&object.properties, "maxparams") >= 1,
};
if !takes_one {
return Err(RuntimeError {
message: "Invalid callback function.".into(),
line,
});
}
Ok(Callback {
name: function_name,
line,
})
}
pub fn variable_names(&self) -> Vec<(String, String)> {
self.variables
.iter()
.map(|(name, value)| (name.clone(), value.to_text()))
.collect()
}
pub fn the_clipboard_watcher(&self) -> Option<&str> {
self.clipboard_watcher.as_deref()
}
pub fn set_the_clipboard_watcher(&mut self, name: Option<String>) {
self.clipboard_watcher = name;
}
pub fn the_icon_of_the_script(&self) -> Option<&(String, i64)> {
self.icon_of_the_script.as_ref()
}
pub fn set_the_icon_of_the_script(&mut self, file: String, number: i64) {
self.icon_of_the_script = Some((file, number));
}
pub fn take_an_image_list(&mut self, address: i64) -> bool {
let before = self.image_lists.len();
self.image_lists.retain(|(held, _)| *held != address);
before != self.image_lists.len()
}
pub fn put_an_image_in_a_list(&mut self, address: i64, image: i64) -> Option<i64> {
let list = self
.image_lists
.iter_mut()
.find(|(held, _)| *held == address)?;
list.1.push(image);
Some(list.1.len() as i64)
}
pub fn make_an_image_list(&mut self) -> i64 {
self.image_list_addresses += 1;
let address = IMAGE_LIST_ADDRESS_BASE + self.image_list_addresses;
self.image_lists.push((address, Vec::new()));
address
}
pub fn the_last_window(&self) -> Option<&str> {
self.last_window.as_deref()
}
pub(crate) fn the_menus_of_the_v1(&mut self) -> &mut Vec<crate::v1::menus::TheMenu> {
&mut self.menus_of_the_v1
}
pub(crate) fn the_callback_of_a_menu_is_waiting(&mut self, callback: String) {
self.the_callback_of_a_menu_that_is_waiting = Some(callback);
}
pub(crate) fn the_waiting_callback_of_a_menu(&mut self) -> Option<String> {
self.the_callback_of_a_menu_that_is_waiting.take()
}
pub fn remember_the_last_window(&mut self, id: &str) {
self.last_window = Some(id.to_string());
}
pub(crate) fn the_last_window_of_the_v1(&self) -> Option<&str> {
self.last_window_of_the_v1.as_deref()
}
pub(crate) fn assign_the_variable_of_the_pseudo_array(&mut self, name: &str, value: Value) {
self.assign(name, value);
}
pub(crate) fn remember_the_last_window_of_the_v1(&mut self, id: &str) {
self.last_window_of_the_v1 = Some(id.to_string());
}
pub(crate) fn remember_the_default_window_of_the_v1(&mut self, name: &str) {
self.default_window_of_the_v1 = name.to_string();
}
pub(crate) fn the_default_window_of_the_v1(&self) -> &str {
&self.default_window_of_the_v1
}
pub(crate) fn the_default_listview_of_the_v1(&self) -> Option<(String, u64)> {
self.default_listview_of_the_v1.clone()
}
pub(crate) fn the_default_treeview_of_the_v1(&self) -> Option<(String, u64)> {
self.default_treeview_of_the_v1.clone()
}
pub(crate) fn remember_the_listview_of_the_v1(&mut self, window: &str, number: u64) {
self.default_listview_of_the_v1 = Some((window.to_string(), number));
}
pub(crate) fn remember_the_treeview_of_the_v1(&mut self, window: &str, number: u64) {
self.default_treeview_of_the_v1 = Some((window.to_string(), number));
}
pub fn close_a_group(&mut self, group: &str) {
self.groups
.retain(|(name, _)| !name.eq_ignore_ascii_case(group));
}
pub fn the_titles_of_a_group(&self, group: &str) -> Vec<String> {
self.groups
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(group))
.map(|(_, titles)| titles.clone())
.unwrap_or_default()
}
pub fn add_to_group(&mut self, group: &str, title: &str) {
let entry = self
.groups
.iter_mut()
.find(|(name, _)| name.eq_ignore_ascii_case(group));
match entry {
Some((_, titles)) => {
if !titles.iter().any(|held| held == title) {
titles.push(title.to_string());
}
}
None => self
.groups
.push((group.to_string(), vec![title.to_string()])),
}
}
pub fn the_message_handler(&self, number: i64) -> Option<&Value> {
self.message_handlers.get(&number)
}
pub fn remember_a_message_handler(&mut self, number: i64, function: Value) {
if !matches!(function, Value::Object(_)) {
return;
}
self.message_handlers.insert(number, function);
}
pub fn forget_a_message_handler(&mut self, number: i64) {
self.message_handlers.remove(&number);
}
pub fn the_legacy_message_handler(&self, number: i64) -> Option<&str> {
self.legacy_message_handlers
.get(&number)
.map(String::as_str)
}
pub fn remember_a_legacy_message_handler(&mut self, number: i64, name: String) {
self.legacy_message_handlers.insert(number, name);
}
pub fn forget_a_legacy_message_handler(&mut self, number: i64) -> Option<String> {
self.legacy_message_handlers.remove(&number)
}
#[cfg(feature = "std")]
pub(crate) fn the_method_of_the_qualified_name(&self, name: &str) -> Option<Value> {
let (class, method) = name.rsplit_once('.')?;
let class = class.trim();
let method = method.trim().to_lowercase();
if class.is_empty() || method.is_empty() {
return None;
}
for one in self.class_chain(&class.to_lowercase()) {
let Some(definition) = self.classes.get(&one) else {
continue;
};
let Some(found) = definition.methods.get(&method) else {
continue;
};
return Some(self.method_reference(&one, found));
}
None
}
pub fn the_function_named(&self, name: &str) -> Option<(&str, usize)> {
let function = self.functions.get(&name.to_lowercase())?;
let required = function
.parameters
.iter()
.filter(|parameter| parameter.is_required())
.count();
Some((function.name.as_str(), required))
}
pub fn the_message_runs(
&mut self,
msg: i64,
wparam: i64,
lparam: i64,
hwnd: i64,
) -> Option<i64> {
let function = self.the_message_handler(msg)?.clone();
let arguments = [
Value::Int(wparam),
Value::Int(lparam),
Value::Int(msg),
Value::Int(hwnd),
];
let arguments = self.the_arguments_of_the_handler(&function, &arguments);
self.callbacks_running += 1;
let answer = crate::classes::func::call_the_value(&function, &arguments, self, 0);
self.callbacks_running -= 1;
match answer? {
Ok(value) => value.to_number().map(|number| number as i64),
Err(_) => None,
}
}
fn the_parameters_of_the_handler(&self, handler: &Value) -> Option<usize> {
let name = match handler {
Value::Object(object) => {
let borrowed = object.borrow();
let kept = borrowed.value_of(CLOSURE).map(|value| value.to_text());
match kept {
Some(kept) if !kept.is_empty() => kept,
_ => borrowed.value_of("name").map(|value| value.to_text())?,
}
}
_ => handler.to_text(),
};
if name.is_empty() {
return None;
}
self.functions
.get(&name.to_lowercase())
.map(|function| function.parameters.len())
}
fn the_arguments_of_the_handler(&self, handler: &Value, arguments: &[Value]) -> Vec<Value> {
if !self.dialect.legacy_commands() {
return arguments.to_vec();
}
match self.the_parameters_of_the_handler(handler) {
Some(count) => arguments.iter().take(count).cloned().collect(),
None => arguments.to_vec(),
}
}
pub fn the_guis(&self) -> &[Value] {
&self.guis
}
pub fn the_object_of(&self, number: i64) -> Option<Value> {
let index = number - 0x1000;
if index < 0 {
return None;
}
self.pointers.get(index as usize).map(|held| held.0.clone())
}
pub fn the_pointer_of(&mut self, value: &Value) -> i64 {
let found = self
.pointers
.iter()
.position(|held| match (&held.0, value) {
(Value::Object(first), Value::Object(second)) => SharedCell::ptr_eq(first, second),
_ => held.0 == *value,
});
let index = match found {
Some(index) => index,
None => {
self.pointers.push((value.clone(), 0));
self.pointers.len() - 1
}
};
0x1000 + index as i64
}
#[cfg(feature = "std")]
fn the_events_of_the_machine_are_taken(&mut self) -> Result<Vec<String>, String> {
let desktop: *mut (dyn crate::runtime::Desktop + 'a) = self.desktop();
let previous = crate::callback::set_current(self);
let events = unsafe { (*desktop).gui_events() };
crate::callback::clear_current(previous);
events
}
#[cfg(not(feature = "std"))]
fn the_events_of_the_machine_are_taken(&mut self) -> Result<Vec<String>, String> {
let desktop: *mut (dyn crate::runtime::Desktop + 'a) = self.desktop();
unsafe { (*desktop).gui_events() }
}
pub fn the_events_are_answered(
&mut self,
statements: &[Node],
line: u32,
) -> Result<(), RuntimeError> {
if self.callbacks_running > 0 {
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!("the pump of the machine is skipped: a callback of the machine runs");
}
return Ok(());
}
if let Some(callback) = self.the_waiting_callback_of_a_menu() {
if let Err(failure) =
self.run_the_callback_of_the_v1_menu(&callback, statements, line)
{
if let Some(error) = the_failure_of_a_handler(failure, line) {
return Err(error);
}
}
}
let Ok(mut events) = self.the_events_of_the_machine_are_taken() else {
return Ok(());
};
if !self.the_events_that_wait.is_empty() {
let mut waiting = core::mem::take(&mut self.the_events_that_wait);
waiting.append(&mut events);
events = waiting;
}
let mut pending: Vec<(Value, Vec<Value>)> = Vec::new();
let mut messages: Vec<TheMessage> = Vec::new();
for event in events {
let mut pieces = event.splitn(2, ':');
let name = pieces.next().unwrap_or("").to_lowercase();
let number = pieces.next().map(str::to_string);
if name.is_empty() {
continue;
}
if name == "tray-exit" {
self.exit_requested = Some(0);
continue;
}
if name == "menu" {
let Some(item) = &number else { continue };
let found = self.the_guis().iter().find_map(|gui| {
let Value::Object(window) = gui else {
return None;
};
let menu = window.borrow().properties.get("on:menu")?.value.clone();
let (function, position) =
crate::classes::menu::the_callback_of(&menu, item, line)?;
Some((
function,
vec![Value::Text(item.clone()), Value::Int(position), menu],
))
});
if let Some(found) = found {
pending.push(found);
}
continue;
}
if name == "v1menu" {
let Some(callback) = &number else { continue };
if callback.is_empty() {
continue;
}
if let Err(failure) =
self.run_the_callback_of_the_v1_menu(callback, statements, line)
{
if let Some(error) = the_failure_of_a_handler(failure, line) {
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!(
"v1menu {callback:?} failed: {} (line {})",
error.message, error.line
);
}
return Err(error);
}
}
continue;
}
if name == "v1ctrl" {
let Some(payload) = &number else { continue };
let mut parts = payload.splitn(6, ':');
let ctrl_hwnd: i64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
let callback = parts.next().unwrap_or("").to_string();
let gui_name = parts.next().unwrap_or("").to_string();
let ctrl_name = parts.next().unwrap_or("").to_string();
let event_name = parts.next().unwrap_or("Normal").to_string();
let event_info: i64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
if callback.is_empty() {
continue;
}
let prev_gui = self.lookup("A_Gui");
let prev_ctrl = self.lookup("A_GuiControl");
let prev_event = self.lookup("A_GuiEvent");
let prev_ctrl_event = self.lookup("A_GuiControlEvent");
let prev_info = self.lookup("A_EventInfo");
self.set_global("A_Gui", Value::Text(gui_name));
self.set_global("A_GuiControl", Value::Text(ctrl_name));
self.set_global("A_GuiEvent", Value::Text(event_name.clone()));
self.set_global("A_GuiControlEvent", Value::Text(event_name.clone()));
self.set_global("A_EventInfo", Value::Int(event_info));
let result = if the_place_of_the_label(statements, &callback).is_some() {
self.run_the_callback_of_the_v1_menu(&callback, statements, line)
} else if let Some(func) = self.functions.get(&callback.to_lowercase()).cloned() {
let event_args = [
Value::Int(ctrl_hwnd),
Value::Text(event_name),
Value::Int(event_info),
Value::Text(String::new()),
];
let is_variadic = func.parameters.last().is_some_and(|p| p.variadic);
let take = if is_variadic {
event_args.len()
} else {
event_args.len().min(func.parameters.len())
};
self.call_named(&callback, &event_args[..take], line, Route::Written)
.map(|_| ())
} else {
Ok(())
};
if let Some(v) = prev_gui {
self.set_global("A_Gui", v);
}
if let Some(v) = prev_ctrl {
self.set_global("A_GuiControl", v);
}
if let Some(v) = prev_event {
self.set_global("A_GuiEvent", v);
}
if let Some(v) = prev_ctrl_event {
self.set_global("A_GuiControlEvent", v);
}
if let Some(v) = prev_info {
self.set_global("A_EventInfo", v);
}
if let Err(failure) = result {
if let Some(error) = the_failure_of_a_handler(failure, line) {
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!(
"v1ctrl {callback:?} failed: {} (line {})",
error.message, error.line
);
}
return Err(error);
}
}
continue;
}
if name == "v1close" {
let Some(payload) = &number else { continue };
let mut parts = payload.splitn(3, ':');
let gui_name = parts.next().unwrap_or("").to_string();
let label_prefix = parts.next().unwrap_or("").to_string();
let target_label = if !label_prefix.is_empty() {
format!("{label_prefix}Close")
} else if gui_name.is_empty() || gui_name == "1" {
"GuiClose".to_string()
} else {
format!("{gui_name}GuiClose")
};
let has_handler = self.functions.contains_key(&target_label.to_lowercase())
|| the_place_of_the_label(statements, &target_label).is_some();
if has_handler {
let prev_gui = self.lookup("A_Gui");
self.set_global("A_Gui", Value::Text(gui_name));
let result =
self.run_the_callback_of_the_v1_menu(&target_label, statements, line);
if let Some(v) = prev_gui {
self.set_global("A_Gui", v);
}
if let Err(failure) = result {
if let Some(error) = the_failure_of_a_handler(failure, line) {
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!(
"v1close {target_label:?} failed: {} (line {})",
error.message, error.line
);
}
return Err(error);
}
}
} else {
let _ = self.desktop().v1_gui_hide(&gui_name);
}
continue;
}
if name == "v1size" {
let Some(item) = &number else { continue };
let mut parts = item.split(':');
let label = parts.next().unwrap_or("").to_string();
if label.is_empty() {
continue;
}
let kind = parts.next().and_then(|it| it.parse::<i64>().ok()).unwrap_or(1);
let width = parts.next().and_then(|it| it.parse::<i64>().ok()).unwrap_or(0);
let height = parts.next().and_then(|it| it.parse::<i64>().ok()).unwrap_or(0);
let handle = parts.next().and_then(|it| it.parse::<i64>().ok()).unwrap_or(0);
let kind = match kind {
1 | 6 => 1,
2 | 7 => 2,
_ => 0,
};
if kind == 0 && width == 0 && height == 0 {
continue;
}
let arguments = [
Value::Int(handle),
Value::Int(kind),
Value::Int(width),
Value::Int(height),
];
let saved = self.the_built_ins_of_the_event_are_saved();
self.set_global("A_GuiWidth", Value::Int(width));
self.set_global("A_GuiHeight", Value::Int(height));
self.set_global("A_EventInfo", Value::Int(kind));
self.set_the_error_level(Value::Int(kind));
self.set_global("A_Gui", Value::Text(the_name_of_the_gui(&label)));
let script = self.the_statements_of_the_script.clone();
let outcome = if the_place_of_the_label(script.as_slice(), &label).is_some() {
let before = self.lookup("A_ThisLabel");
self.set_global("A_ThisLabel", Value::Text(label.clone()));
let answer =
self.run_the_body_of_a_label(&label, script.as_slice(), line);
if let Some(value) = before {
self.set_global("A_ThisLabel", value);
}
answer
} else if let Some(func) = self.functions.get(&label.to_lowercase()).cloned() {
let is_variadic = func.parameters.last().is_some_and(|p| p.variadic);
let take = if is_variadic {
arguments.len()
} else {
arguments.len().min(func.parameters.len())
};
self.call_named(&label, &arguments[..take], line, Route::Written)
.map(|_| ())
} else {
Ok(())
};
self.the_built_ins_of_the_event_are_given_back(saved);
let error = match outcome {
Ok(()) => None,
Err(failure) => the_failure_of_a_handler(failure, line),
};
if let Some(error) = error {
return Err(error);
}
continue;
}
if name == "message" {
let Some(item) = &number else { continue };
let mut parts = item.split(':');
let Ok(number) = parts.next().unwrap_or("").parse::<i64>() else {
continue;
};
let wparam = parts.next().and_then(|p| p.parse::<i64>().ok()).unwrap_or(0);
let lparam = parts.next().and_then(|p| p.parse::<i64>().ok()).unwrap_or(0);
let hwnd = parts.next().and_then(|p| p.parse::<i64>().ok()).unwrap_or(0);
let arguments = vec![
Value::Int(wparam),
Value::Int(lparam),
Value::Int(number),
Value::Int(hwnd),
];
let mut handlers: Vec<(Value, Vec<Value>)> = Vec::new();
if let Some(legacy) = self.the_legacy_message_handler(number) {
let handler = Value::Text(legacy.to_string());
let arguments = self.the_arguments_of_the_handler(&handler, &arguments);
handlers.push((handler, arguments));
}
if let Some(function) = self.the_message_handler(number).cloned() {
let arguments = self.the_arguments_of_the_handler(&function, &arguments);
handlers.push((function, arguments));
}
if handlers.is_empty() {
continue;
}
messages.push((hwnd, number, wparam, lparam, handlers));
continue;
}
if name == "tray" {
let menu = self.the_tray_menu(line);
let Some(default) = crate::classes::menu::the_default_of(&menu) else {
continue;
};
let (function, position) =
match crate::classes::menu::the_callback_of(&menu, &default, line) {
Some(found) => found,
None => continue,
};
pending.push((
function,
vec![Value::Text(default), Value::Int(position), menu],
));
continue;
}
let key = format!("on:{name}");
let found = self.the_guis().iter().find_map(|gui| {
let Value::Object(window) = gui else {
return None;
};
let window = window.borrow();
let (holder, about) = match &number {
Some(number) => {
let held = window.properties.get(&format!("control:{number}"))?;
(held.value.clone(), Some(held.value.clone()))
}
None => (gui.clone(), None),
};
let Value::Object(object) = &holder else {
return None;
};
let handler = object.borrow().properties.get(&key)?.value.clone();
let Value::Object(_) = &handler else {
return None;
};
Some((handler, about))
});
if let Some((function, about)) = found {
pending.push((function, about.into_iter().collect()));
}
}
for (function, arguments) in pending {
match &function {
Value::Object(_) => {
if let Some(Err(failure)) =
crate::classes::func::call_the_value(&function, &arguments, self, line)
{
if let Some(error) = the_failure_of_a_handler(failure, line) {
return Err(error);
}
}
}
_ => {
if let Err(failure) = self
.call_function_by_name_with(&function.to_text(), &arguments, line)
{
if let Some(error) = the_failure_of_a_handler(failure, line) {
return Err(error);
}
}
}
}
}
for (hwnd, message, wparam, lparam, handlers) in messages {
crate::trace::gui_message(hwnd, message, wparam, lparam);
for (handler, arguments) in handlers {
let answer = match self.the_message_handler_runs(&handler, &arguments, line) {
Ok(answer) => answer,
Err(failure) => match the_failure_of_a_handler(failure, line) {
Some(error) => return Err(error),
None => continue,
},
};
let Some(answer) = answer else { continue };
if !answer.to_text().is_empty() {
break;
}
}
}
Ok(())
}
fn the_message_handler_runs(
&mut self,
handler: &Value,
arguments: &[Value],
line: u32,
) -> Result<Option<Value>, RuntimeFailure> {
match handler {
Value::Object(_) => match crate::classes::func::call_the_value(handler, arguments, self, line)
{
Some(result) => result.map(Some),
None => Ok(None),
},
_ => self
.call_named(&handler.to_text(), arguments, line, Route::Written)
.map(Some),
}
}
pub(crate) fn call_a_function_for_a_built_in(
&mut self,
name: &str,
arguments: &[Value],
line: u32,
) -> Result<(), RuntimeError> {
self.call_named(name, arguments, line, Route::Written)
.map(|_| ())
.map_err(|failure| match failure {
RuntimeFailure::Error(error) => error,
RuntimeFailure::Detailed(error, _) => error,
RuntimeFailure::Fatal(error) => error,
_ => RuntimeError {
message: "the function of the clipboard change could not be called."
.to_string(),
line,
},
})
}
fn call_function_by_name_with(
&mut self,
name: &str,
arguments: &[Value],
line: u32,
) -> Result<(), RuntimeFailure> {
self.call_named(name, arguments, line, Route::Written)
.map(|_answer| ())
}
pub fn the_tray_menu(&mut self, line: u32) -> Value {
if let Some(menu) = &self.tray_menu {
return menu.clone();
}
let menu = crate::classes::menu::construct(&[], self, line)
.unwrap_or_else(|_| crate::classes::object_with("Menu", vec![]));
let _ = crate::classes::menu::set_property(
"Default",
&menu,
&Value::Text("&Open".to_string()),
self,
line,
);
self.tray_menu = Some(menu.clone());
menu
}
pub fn remember_a_gui(&mut self, object: &Value) {
let already = self.guis.iter().any(|held| match (held, object) {
(Value::Object(first), Value::Object(second)) => SharedCell::ptr_eq(first, second),
_ => false,
});
if !already {
self.guis.push(object.clone());
}
}
}
#[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(SharedCell::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 the_intrinsic_member_of_a_function(name: &str) -> bool {
matches!(
name,
"name"
| "minparams"
| "maxparams"
| "isbuiltin"
| "isvariadic"
| PARAMETERS
| CLOSURE
| BOUND
| BOUND_TARGET
| METHOD_CLASS
| METHOD_NAME
)
}
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(SharedCell::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(SharedCell::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(),
}
}
#[cfg(feature = "std")]
fn the_trace_is_asked() -> bool {
static THE_ANSWER: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*THE_ANSWER.get_or_init(|| std::env::var_os("AHK_TRACE").is_some())
}
#[cfg(feature = "std")]
fn the_slow_threshold() -> u64 {
static THE_ANSWER: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
*THE_ANSWER.get_or_init(|| {
std::env::var("AHK_SLOW")
.ok()
.and_then(|value| value.trim().parse::<u64>().ok())
.unwrap_or(0)
})
}
#[cfg(not(feature = "std"))]
fn the_slow_threshold() -> u64 {
0
}
pub(crate) fn the_extra_of_the_value_in_the_maths(value: &Value) -> String {
match value {
Value::Text(text) if text.is_empty() => String::new(),
_ => the_extra_of_the_value(value),
}
}
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(SharedCell::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,
},
}
}
pub(crate) fn the_failure_of_a_handler(
failure: RuntimeFailure,
line: u32,
) -> Option<RuntimeError> {
match failure {
RuntimeFailure::Flow(Flow::Return(_)) => None,
other => Some(as_error(other, 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 SharedCell::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 the_borrowed_key(name: &str) -> alloc::borrow::Cow<'_, str> {
if name.is_ascii() && !name.bytes().any(|byte| byte.is_ascii_uppercase()) {
alloc::borrow::Cow::Borrowed(name)
} else {
alloc::borrow::Cow::Owned(name.to_lowercase())
}
}
fn the_period_in_the_trace(period: u64, once: bool) -> i64 {
let _ = once;
period.min(i64::MAX as u64) as i64
}
fn the_runtime_owns_the_variable(name: &str) -> bool {
match name.strip_prefix("a_") {
Some(rest) => crate::variables::THE_RUNTIME_OWNS.contains(&rest),
None => false,
}
}
fn the_run_failed(outcome: &Result<(), RuntimeFailure>) -> bool {
match outcome {
Ok(()) => false,
Err(RuntimeFailure::Flow(Flow::Break(_)))
| Err(RuntimeFailure::Flow(Flow::Continue(_)))
| Err(RuntimeFailure::Flow(Flow::Return(_))) => false,
Err(_) => true,
}
}
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_name_of_the_gui(label: &str) -> String {
const THE_SUFFIX: &str = "GuiSize";
if label.len() > THE_SUFFIX.len()
&& label[label.len() - THE_SUFFIX.len()..].eq_ignore_ascii_case(THE_SUFFIX)
{
return label[..label.len() - THE_SUFFIX.len()].to_string();
}
"1".to_string()
}
const THE_BUILT_INS_OF_THE_EVENT: &[&str] = &[
"a_guiwidth",
"a_guiheight",
"a_gui",
"a_eventinfo",
];
fn the_labels_of(body: &[Node]) -> Vec<String> {
let mut labels = Vec::new();
collect_the_labels(body, &mut labels);
labels
}
fn the_names_of_the_parameters(parameters: &[Parameter]) -> BTreeSet<String> {
parameters
.iter()
.map(|parameter| parameter.name.to_lowercase())
.collect()
}
fn the_body_is_in_the_force_local_mode(body: &[Node]) -> bool {
matches!(
body.first(),
Some(Node::Declare {
scope: DeclareKind::Local,
names,
..
}) if names.is_empty()
)
}
fn the_super_globals_of_the_script(statements: &[Node]) -> BTreeSet<String> {
let mut names = BTreeSet::new();
the_super_globals_of_a_level(statements, &mut names);
names
}
fn the_super_globals_of_a_level(statements: &[Node], names: &mut BTreeSet<String>) {
for statement in statements {
match statement {
Node::Declare {
scope: DeclareKind::Global,
names: declared,
..
} => {
for declared in declared {
names.insert(declared.name.to_lowercase());
}
}
Node::Block { body, .. } => the_super_globals_of_a_level(body, names),
Node::LegacyIf {
body, otherwise, ..
} => {
the_super_globals_of_a_level(body, names);
the_super_globals_of_a_level(otherwise, names);
}
Node::If {
branches,
otherwise,
..
} => {
for branch in branches {
the_super_globals_of_a_level(&branch.body, names);
}
the_super_globals_of_a_level(otherwise, names);
}
Node::Switch { cases, .. } => {
for case in cases {
the_super_globals_of_a_level(&case.body, names);
}
}
Node::While { body, otherwise, .. }
| Node::Loop { body, otherwise, .. }
| Node::For { body, otherwise, .. } => {
the_super_globals_of_a_level(body, names);
if let Some(otherwise) = otherwise {
the_super_globals_of_a_level(otherwise, names);
}
}
Node::Try {
body,
catches,
otherwise,
finally,
..
} => {
the_super_globals_of_a_level(body, names);
for catch in catches {
the_super_globals_of_a_level(&catch.body, names);
}
the_super_globals_of_a_level(otherwise, names);
the_super_globals_of_a_level(finally, names);
}
_ => {}
}
}
}
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))
}
fn the_reason_of_the_failure(failure: &RuntimeFailure) -> String {
match failure {
RuntimeFailure::Error(error) => error.message.clone(),
RuntimeFailure::Detailed(error, detail) => {
if detail.extra.is_empty() {
error.message.clone()
} else {
format!("{} {}", error.message, detail.extra)
}
}
RuntimeFailure::Fatal(error) => error.message.clone(),
RuntimeFailure::Thrown(value) => value.to_text(),
RuntimeFailure::Timeout(timeout) => {
format!("the script ran for more than {} seconds", timeout.seconds)
}
RuntimeFailure::Flow(_) => String::new(),
}
}
fn the_threshold_of_the_slow_list() -> u64 {
let asked = the_slow_threshold();
if asked > 0 {
return asked;
}
Runtime::SLOW_STEP_MS
}
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::VarRef { .. } => "VarRef",
Node::Assign { .. } => "Assign",
Node::AssignIndex { .. } => "AssignIndex",
Node::Call { name, .. } => match the_builtin_in(dialect, name) {
Some(builtin) => builtin.name,
None => "Call",
},
Node::CallDynamic { .. } => "CallDynamic",
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::Gosub { .. } => "Gosub",
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::AssignCall { .. } => "AssignCall",
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, pre_release)) = parse(requirement) else {
return false;
};
range.met_by(&required, pre_release, &dialect.version())
}
impl Range {
fn met_by(
self,
required: &[u32],
pre_release: bool,
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, pre_release);
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>, bool)> {
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;
}
let pre_release = text.contains('-');
if let Some(at) = text.find('-') {
text = &text[..at];
}
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, pre_release))
}
fn compare_versions(current: &[u32], required: &[u32], pre_release: bool) -> 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,
}
}
if pre_release {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
fn the_index_of_the_v1(index: Option<i64>) -> Value {
match index {
Some(index) => Value::Int(index),
None => Value::Text(String::new()),
}
}
enum TheKeyOfTheV1 {
TheNumber(i64),
TheText(String),
}
fn the_index_of_the_key_of_the_v1(key: &Value) -> Option<i64> {
match key {
Value::Int(number) => Some(*number),
Value::Text(text) => text.trim().parse::<i64>().ok(),
_ => None,
}
}
fn the_leading_number_of(text: &str) -> Option<i64> {
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 start = end;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
}
if end == start {
return None;
}
text[..end].parse::<i64>().ok()
}
const IMAGE_LIST_ADDRESS_BASE: i64 = 0x3000_0000;
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
use crate::desktop::{
Clipboard, Com, Dialogs, Hotkeys, Keyboard, Machine, Native, Network, Pictures, Pointer,
Processes, Screen, Sound, Timers, Windows,
};
struct TheFake {
fired: Option<String>,
event: Option<String>,
arrived: Vec<String>,
windows: Vec<String>,
}
impl Desktop for TheFake {}
impl Keyboard for TheFake {
fn type_text(&mut self, _text: &str) -> Result<String, String> {
Ok(String::new())
}
fn press_key(&mut self, _key: &str, _modifiers: &[String]) -> Result<String, String> {
Ok(String::new())
}
}
impl Pointer for TheFake {
fn click(
&mut self,
_x: i64,
_y: i64,
_button: &str,
_count: u32,
) -> Result<String, String> {
Ok(String::new())
}
}
impl Screen for TheFake {
fn capture(
&mut self,
_x: i64,
_y: i64,
_width: i64,
_height: i64,
_kind: &str,
) -> Result<String, String> {
Ok(String::new())
}
fn pixel(&mut self, _x: i64, _y: i64) -> Result<String, String> {
Ok("#000000".to_string())
}
}
impl Windows for TheFake {
fn gui_events(&mut self) -> Result<Vec<String>, String> {
let mut events = core::mem::take(&mut self.windows);
events.append(&mut self.arrived);
Ok(events)
}
fn watch_a_message(&mut self, _number: i64) -> Result<(), String> {
if let Some(event) = self.event.take() {
self.arrived.push(event);
}
Ok(())
}
}
impl Processes for TheFake {
fn run(&mut self, _program: &str, _arguments: &str) -> Result<(i32, String, String), String> {
Ok((0, String::new(), String::new()))
}
}
impl Files for TheFake {
fn working_directory(&mut self) -> Result<String, String> {
Ok(String::new())
}
fn initial_working_directory(&mut self) -> Result<String, String> {
Ok(String::new())
}
}
impl Clipboard for TheFake {}
impl Timers for TheFake {}
impl Hotkeys for TheFake {
fn register_hotkey(&mut self, _name: &str) -> Result<String, String> {
Ok(String::new())
}
fn fired_hotkey(&mut self) -> Result<Option<String>, String> {
Ok(self.fired.take())
}
}
impl Native for TheFake {}
impl Com for TheFake {}
impl Pictures for TheFake {}
impl Network for TheFake {}
impl Sound for TheFake {}
impl Machine for TheFake {}
impl Dialogs for TheFake {}
fn run(script: &str) -> Report {
run_with_events(script, None)
}
fn run_with_events(script: &str, event: Option<&str>) -> Report {
let statements =
crate::parse_with(script, crate::dialect::v1()).expect("the script of the v1 parses");
let mut desktop = TheFake {
fired: Some("F1".to_string()),
event: event.map(|text| text.to_string()),
arrived: Vec::new(),
windows: Vec::new(),
};
Runtime::new(&mut desktop, Duration::from_secs(60))
.with_dialect(crate::dialect::v1())
.run(&statements)
}
fn run_with_the_events_of_the_windows(script: &str, events: &[&str]) -> Report {
let statements =
crate::parse_with(script, crate::dialect::v1()).expect("the script of the v1 parses");
let mut desktop = TheFake {
fired: Some("F1".to_string()),
event: None,
arrived: Vec::new(),
windows: events.iter().map(|text| text.to_string()).collect(),
};
Runtime::new(&mut desktop, Duration::from_secs(60))
.with_dialect(crate::dialect::v1())
.run(&statements)
}
#[test]
fn the_hotkey_that_is_pressed_while_a_function_computes_runs_at_once() {
let report = run(
"out := 0\n\
theFunction() {\n\
global out\n\
out := out * 10 + 1\n\
Hotkey, F1, theHotkey\n\
Loop 3 {\n\
x := 1\n\
}\n\
out := out * 10 + 3\n\
}\n\
theHotkey() {\n\
global out\n\
out := out * 10 + 2\n\
}\n\
theFunction()\n",
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("123".to_string())
);
}
#[test]
fn the_body_of_a_hotkey_does_not_write_into_the_locals_of_the_function() {
let report = run(
"out := 0\n\
globalMine := 0\n\
theFunction()\n\
TheLabel:\n\
mine := 2\n\
globalMine := 2\n\
Return\n\
theFunction() {\n\
global out\n\
global globalMine\n\
local mine\n\
mine := 1\n\
Hotkey, F1, TheLabel\n\
Loop 3 {\n\
x := 1\n\
}\n\
out := mine * 10 + globalMine\n\
}\n",
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("12".to_string())
);
}
#[test]
fn the_message_that_arrives_during_a_critical_section_is_not_lost() {
let report = run_with_events(
"out := 0\n\
Handler(wParam, lParam, msg, hwnd) {\n\
global out\n\
out := out * 10 + 10\n\
return\n\
}\n\
theFunction() {\n\
global out\n\
Critical, on\n\
OnMessage(0x404, \"Handler\")\n\
Loop 3 {\n\
x := 1\n\
}\n\
Critical, off\n\
out := out + 1\n\
}\n\
theFunction()\n",
Some("message:1028:0:0:0"),
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("11".to_string())
);
}
#[test]
fn the_window_that_is_resized_runs_the_label_of_the_event() {
let report = run_with_the_events_of_the_windows(
"out := 0\n\
theFunction()\n\
Return\n\
PVwinGuiSize:\n\
out := out * 10 + 1\n\
Return\n\
PVwinGuiSize(GuiHwnd, EventInfo, Width, Height) {\n\
global out\n\
out := out * 10 + 2\n\
}\n\
theFunction() {\n\
global out\n\
Loop 3 {\n\
x := 1\n\
}\n\
}\n",
&["v1size:PVwinGuiSize:0:300:200:4321"],
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("1".to_string())
);
}
#[test]
fn the_label_of_the_event_reads_the_facts_of_the_event() {
let report = run_with_the_events_of_the_windows(
"out := 0\n\
theFunction()\n\
Return\n\
PVwinGuiSize:\n\
out := A_GuiWidth \",\" A_GuiHeight \",\" A_EventInfo \",\" ErrorLevel \",\" A_Gui\n\
Return\n\
theFunction() {\n\
Loop 3 {\n\
x := 1\n\
}\n\
}\n",
&["v1size:PVwinGuiSize:0:300:200:4321"],
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("300,200,0,0,PVwin".to_string())
);
}
#[test]
fn the_function_of_the_event_runs_when_the_label_of_it_is_not_there() {
let report = run_with_the_events_of_the_windows(
"out := 0\n\
theFunction()\n\
Return\n\
PVwinGuiSize(GuiHwnd, EventInfo, Width, Height) {\n\
global out\n\
out := GuiHwnd \",\" EventInfo \",\" Width \",\" Height\n\
}\n\
theFunction() {\n\
Loop 3 {\n\
x := 1\n\
}\n\
}\n",
&["v1size:PVwinGuiSize:0:300:200:4321"],
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("4321,0,300,200".to_string())
);
}
#[test]
fn the_window_of_the_script_without_a_name_runs_the_label_guisize() {
let report = run_with_the_events_of_the_windows(
"out := 0\n\
theFunction()\n\
Return\n\
GuiSize:\n\
out := A_Gui\n\
Return\n\
theFunction() {\n\
Loop 3 {\n\
x := 1\n\
}\n\
}\n",
&["v1size:GuiSize:0:300:200:4321"],
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("1".to_string())
);
}
#[test]
fn the_window_that_is_resized_with_a_client_area_of_zero_runs_no_label() {
let report = run_with_the_events_of_the_windows(
"out := 0\n\
theFunction()\n\
Return\n\
PVwinGuiSize:\n\
out := out * 10 + 1\n\
Return\n\
theFunction() {\n\
Loop 3 {\n\
x := 1\n\
}\n\
}\n",
&["v1size:PVwinGuiSize:0:0:0:4321"],
);
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("out").map(|value| value.to_text()),
Some("0".to_string())
);
}
#[test]
fn the_for_of_the_v1_walks_the_properties_of_an_object() {
let report = run("o := {b: 1, a: 2}\n\
keys := \"\"\n\
values := \"\"\n\
turns := 0\n\
for k, v in o {\n\
keys := keys k \" \"\n\
values := values v \" \"\n\
turns := turns + 1\n\
}\n");
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("keys").map(|value| value.to_text()),
Some("a b ".to_string())
);
assert_eq!(
report.variables.get("values").map(|value| value.to_text()),
Some("2 1 ".to_string())
);
assert_eq!(
report.variables.get("turns").map(|value| value.to_text()),
Some("2".to_string())
);
}
#[test]
fn the_for_of_the_v1_walks_the_items_and_the_properties_of_an_array() {
let report = run("a := [1, 2]\n\
a.name := \"x\"\n\
keys := \"\"\n\
values := \"\"\n\
for k, v in a {\n\
keys := keys k \" \"\n\
values := values v \" \"\n\
}\n");
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("keys").map(|value| value.to_text()),
Some("1 2 name ".to_string())
);
assert_eq!(
report.variables.get("values").map(|value| value.to_text()),
Some("1 2 x ".to_string())
);
}
#[test]
fn the_for_of_the_v1_over_a_value_that_is_not_an_object_has_no_turn() {
let report = run("turns := 0\n\
for k, v in 5\n\
turns := turns + 1\n");
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("turns").map(|value| value.to_text()),
Some("0".to_string())
);
}
#[test]
fn the_haskey_of_the_v1_tells_a_number_from_its_text() {
let report = run("a := [1, 2]\n\
keynumber := a.HasKey(1)\n\
keytext := a.HasKey(\"1\")\n\
keymissing := a.HasKey(5)\n\
keyproperty := 0\n\
a.name := \"x\"\n\
keyproperty := a.HasKey(\"name\")\n");
assert!(report.ok, "{:?} at line {:?}", report.error, report.error_line);
assert_eq!(
report.variables.get("keynumber").map(|value| value.to_text()),
Some("1".to_string())
);
assert_eq!(
report.variables.get("keytext").map(|value| value.to_text()),
Some("0".to_string())
);
assert_eq!(
report.variables.get("keymissing").map(|value| value.to_text()),
Some("0".to_string())
);
assert_eq!(
report.variables.get("keyproperty").map(|value| value.to_text()),
Some("1".to_string())
);
}
}