use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use crate::builtins::BuiltinHandler;
use crate::runtime::{Runtime, RuntimeError, Value};
mod chars;
mod commands;
mod controls;
mod dates;
mod families;
mod files;
mod hotkeys;
mod keys;
mod kinds;
mod labels;
mod loops;
mod math;
pub(crate) mod memory;
pub(crate) mod menus;
mod names;
mod numbers;
mod parameters;
mod strings;
mod sub_commands;
mod table;
mod variables;
mod windows;
pub(crate) use names::on_error;
pub(crate) use names::the_command_has_a_body;
pub(crate) use names::the_command_is_the_else;
pub(crate) use names::the_illegal_letters_of_a_name;
pub(crate) use names::the_place_of_the_argument_that_wants_the_name;
pub(crate) use names::the_place_of_the_argument_that_wants_the_variable;
pub(crate) use names::every_argument_that_is_a_variable_keeps_it;
pub(crate) use names::{
else_of_the_v1, if_equal, if_exist, if_greater, if_greater_or_equal, if_in_string,
if_less, if_less_or_equal, if_msg_box, if_not_equal, if_not_exist, if_not_in_string,
if_win_active, if_win_exist, if_win_not_active, if_win_not_exist,
the_type_of_the_is_is_known, the_value_is_of_the_type,
};
pub use table::BUILTINS;
pub use variables::{
carries as carries_variable, may_not_be_declared, refusal_of as refusal_of_variable,
};
pub(crate) use chars::chr;
pub(crate) use dates::{the_date_of_the_v1, the_text_is_a_number_of_days};
pub(crate) use kinds::{keeps_its_text, the_output_may_be_blank, wants_a_number};
pub(crate) use labels::the_label_of_the_command;
pub(crate) use labels::the_refusal_of_a_goto;
pub(crate) use labels::the_word_of_a_hotkey;
pub(crate) use loops::the_delimiters_ask_for_the_comma_separated_values;
pub(crate) use loops::the_fields_of_the_comma_separated_values;
pub(crate) use loops::the_flag_asks_for_the_recursion;
pub(crate) use loops::the_mode_of_the_loop_of_the_files;
pub(crate) use loops::the_refusal_of_the_name_of_the_parse_loop;
pub(crate) use loops::the_refusal_of_the_parameters_of_the_loop;
pub(crate) use loops::the_refusal_of_the_reg_mode;
pub(crate) use sub_commands::the_text_begins_with_a_root_of_the_registry;
pub(crate) use loops::{THE_FILES, THE_FILES_AND_THE_FOLDERS, THE_FOLDERS};
pub(crate) use hotkeys::TheName;
pub(crate) use hotkeys::is_the_name_of_a_command;
pub(crate) use hotkeys::the_context_of_the_v1_is_refused_in_a_hotkey;
pub(crate) use hotkeys::the_name_of_a_hotkey;
pub(crate) use math::{
abs, acos, asin, atan, ceil, cos, exp, floor, ln, log, max, min, modulo, round, sin, sqrt, tan,
};
pub(crate) use crate::builtins::critical;
pub(crate) use numbers::{
the_count_of_the_loop, the_number_at_the_start_of_a_text, the_number_is_a_number,
the_number_of_a_text, the_text_is_a_float, the_text_is_a_hex, the_text_is_the_count_of_a_loop,
the_text_of_the_number_that_fits, the_whole_number_at_the_start_of_a_text,
the_whole_number_of_a_hex,
};
pub(crate) use parameters::is_the_name_of_a_variable;
pub(crate) use parameters::is_the_name_of_a_variable_that_may_carry_a_point;
pub(crate) use parameters::the_refusal_of_a_parameter;
pub(crate) use parameters::the_refusal_of_the_arity;
pub(crate) use parameters::the_refusal_of_the_name_of_a_variable;
pub(crate) use parameters::the_refusal_of_the_percent_sign_of_a_parameter;
pub(crate) use parameters::the_refusal_of_the_percent_sign_of_an_expression;
pub(crate) use parameters::the_refusal_of_the_point_of_an_operand;
pub(crate) use parameters::the_refusal_of_the_text_of_a_member;
pub(crate) use parameters::the_text_is_an_expression_of_the_v1;
pub(crate) use sub_commands::the_parameter_may_not_be_blank;
pub(crate) use sub_commands::the_refusal_of_a_sub_command;
pub(crate) use strings::{in_str, sub_str};
pub(crate) use names::{
auto_trim, coord_mode_of_the_v1, file_encoding_of_the_v1, file_read_line, func, input,
is_by_ref, is_func, is_set, object, set_batch_lines, set_control_delay_of_the_v1,
set_detect_hidden_text_of_the_v1, set_detect_hidden_windows_of_the_v1, set_format,
set_key_delay_of_the_v1, set_mouse_delay_of_the_v1, set_store_caps_lock_mode_of_the_v1,
set_win_delay_of_the_v1, string_case_sense, transform,
};
pub const VARIABLES: &[&str] = &[
"A_Args",
"A_AutoTrim",
"A_BatchLines",
"A_CaretX",
"A_CaretY",
"A_DefaultGui",
"A_DefaultListView",
"A_DefaultTreeView",
"A_ExitReason",
"A_FormatFloat",
"A_FormatInteger",
"A_Gui",
"A_GuiControl",
"A_GuiControlEvent",
"A_GuiEvent",
"A_GuiHeight",
"A_GuiWidth",
"A_GuiX",
"A_GuiY",
"A_IPAddress1",
"A_IsUnicode",
"A_NumBatchLines",
"A_OSType",
"A_StringCaseSense",
"A_ThisLabel",
"A_ThisMenu",
"A_ThisMenuItem",
"A_ThisMenuItemPos",
];
pub const DIRECTIVES: &[&str] = &[
"commentflag",
"escapechar",
"hotkeyinterval",
"hotkeymodifiertimeout",
"if",
"iftimeout",
"ifwinactive",
"installkeybdhook",
"installmousehook",
"keyhistory",
"maxhotkeysperinterval",
"maxmem",
"menumaskkey",
"noenv",
"persistent",
];
pub fn carries_directive(name: &str) -> bool {
let wanted = name.to_lowercase();
DIRECTIVES.iter().any(|carried| *carried == wanted)
}
pub(crate) fn lookup_variable(name: &str, rt: &mut Runtime) -> Option<Result<Value, RuntimeError>> {
variables::lookup(name, rt)
}
pub(crate) fn the_number_of_a_legacy_text(text: &str) -> Option<Value> {
let mut body = text;
if let Some(rest) = body.strip_prefix('+') {
body = rest;
} else if let Some(rest) = body.strip_prefix('-') {
body = rest;
}
if body.is_empty() || !body.chars().all(|character| character.is_ascii_digit()) {
return None;
}
text.parse::<i64>().ok().map(Value::Int)
}
pub(crate) fn write_variable(
name: &str,
op: crate::ast::AssignOp,
value: &Value,
line: u32,
rt: &mut Runtime,
) -> Option<Result<Value, RuntimeError>> {
variables::write(name, op, value, line, rt)
}
pub(crate) fn is_read_only(name: &str) -> bool {
variables::is_read_only(name)
}
pub(crate) fn hotstring_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let text = values
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let invalid = RuntimeError {
message: "Parameter #1 of Hotstring is invalid.".to_string(),
line,
};
let Some(rest) = text.strip_prefix("::") else {
return Err(invalid);
};
let Some((trigger, action)) = rest.split_once("::") else {
return Err(invalid);
};
let definition = format!(":{trigger}:");
crate::builtins::hotstring(
rt,
&[Value::Text(definition), Value::Text(action.to_string())],
line,
1,
)
}
fn the_answer_goes_into_the_first_output(
rt: &mut Runtime<'_>,
name: &str,
values: &[Value],
line: u32,
handler: BuiltinHandler,
flavour: u8,
) -> Result<Value, RuntimeError> {
let answer = handler(rt, values.get(1..).unwrap_or(&[]), line, flavour)?;
write_the_answer(rt, name, values, 0, answer.clone(), line)?;
Ok(answer)
}
pub(crate) fn write_the_answer(
rt: &mut Runtime<'_>,
name: &str,
values: &[Value],
at: usize,
answer: Value,
line: u32,
) -> Result<(), RuntimeError> {
let Some(value) = values.get(at) else {
return Ok(());
};
if !matches!(value, Value::Reference(_)) {
return Err(RuntimeError {
message: crate::runtime::wants_a_reference(at + 1, name, "a VarRef", value),
line,
});
}
rt.write_reference(value, answer);
Ok(())
}
pub(crate) fn env_get(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(rt, "EnvGet", values, line, crate::builtins::env_get, 0)
}
pub(crate) fn env_set(
rt: &mut Runtime<'_>,
values: &[Value],
_line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let name = values
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let value = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
match rt.desktop().env_set(&name, &value) {
Ok(answer) => {
rt.set_the_error_level(Value::Int(0));
Ok(Value::Text(answer))
}
Err(reason) => {
rt.set_the_error_level(Value::Int(1));
rt.note(format!(
"the variable of the environment was not set: {reason}"
));
Ok(Value::Text(value))
}
}
}
pub(crate) fn env_update(
_rt: &mut Runtime<'_>,
_values: &[Value],
_line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
Ok(Value::Text(String::new()))
}
pub(crate) fn file_get_attrib(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_of_a_file_of_the_loop(
rt,
"FileGetAttrib",
values,
line,
crate::builtins::file_get_attrib,
4,
)
}
pub(crate) fn file_get_size(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_of_a_file_of_the_loop(
rt,
"FileGetSize",
values,
line,
crate::builtins::file_get_size,
4,
)
}
pub(crate) fn file_get_time(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_of_a_file_of_the_loop(
rt,
"FileGetTime",
values,
line,
crate::builtins::file_get_time,
4,
)
}
pub(crate) fn file_read(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_of_a_file_command(rt, "FileRead", values, line, crate::builtins::file_read, 0)
}
pub(crate) fn format_time(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"FormatTime",
values,
line,
crate::builtins::format_time,
2,
)
}
pub(crate) fn get_key_state(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let is_the_command = variant == 0;
let name = if is_the_command {
values.get(1)
} else {
values.first()
};
let answer = match (is_the_command, the_state_of_a_key(rt, name, line)?) {
(true, Some(true)) => Value::Text("D".to_string()),
(true, Some(false)) => Value::Text("U".to_string()),
(false, Some(true)) => Value::Int(1),
(false, Some(false)) => Value::Int(0),
(_, None) => Value::Text(String::new()),
};
if is_the_command {
write_the_answer(rt, "GetKeyState", values, 0, answer.clone(), line)?;
}
Ok(answer)
}
fn the_state_of_a_key(
rt: &mut Runtime<'_>,
name: Option<&Value>,
_line: u32,
) -> Result<Option<bool>, RuntimeError> {
let name = name.map(|value| value.to_text()).unwrap_or_default();
let name = name.trim();
if !keys::is_the_name_of_a_key(name) {
return Ok(None);
}
match rt.desktop().key_is_down(name) {
Ok(down) => Ok(Some(down)),
Err(_) => Ok(None),
}
}
pub(crate) fn ini_read(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
match crate::builtins::ini_read(rt, values.get(1..).unwrap_or(&[]), line, 4) {
Ok(answer) => {
write_the_answer(rt, "IniRead", values, 0, answer.clone(), line)?;
Ok(answer)
}
Err(failure) => {
write_the_answer(rt, "IniRead", values, 0, Value::Text(String::new()), line)?;
rt.note(format!("the command IniRead did not do the thing: {failure}"));
Ok(Value::Text(String::new()))
}
}
}
pub(crate) fn ini_write(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::files::ini_write(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn ini_delete(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::files::ini_delete(rt, values, line, variant);
match answer {
Ok(value) => Ok(value),
Err(failure) => {
rt.note(format!("the command IniDelete did not do the thing: {failure}"));
Ok(Value::Text(String::new()))
}
}
}
pub(crate) fn pixel_get_color(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"PixelGetColor",
values,
line,
crate::builtins::pixel_get_color,
0,
)
}
pub(crate) fn random(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(rt, "Random", values, line, crate::builtins::random, 0)
}
pub(crate) fn win_get_title(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
match crate::builtins::win_get_title(rt, values.get(1..).unwrap_or(&[]), line, variant) {
Ok(answer) => {
write_the_answer(rt, "WinGetTitle", values, 0, answer.clone(), line)?;
Ok(answer)
}
Err(failure) => {
write_the_answer(rt, "WinGetTitle", values, 0, Value::Text(String::new()), line)?;
rt.note(format!(
"the command WinGetTitle did not do the thing: {failure}"
));
Ok(Value::Text(String::new()))
}
}
}
pub(crate) fn set_working_dir(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::builtins::set_working_dir(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_install(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::builtins::file_install(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn string_len(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"StringLen",
values,
line,
crate::builtins::str_len,
0,
)
}
pub(crate) fn string_mid(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"StringMid",
values,
line,
crate::builtins::sub_str,
0,
)
}
pub(crate) fn string_get_pos(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let haystack = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let needle = values
.get(2)
.map(|value| value.to_text())
.unwrap_or_default();
let occurrence = values
.get(3)
.map(|value| value.to_text())
.unwrap_or_default();
let offset = values
.get(4)
.and_then(|value| value.to_number())
.unwrap_or(0.0);
let (from_the_right, number) = the_occurrence_of_the_v1(&occurrence, line)?;
let method = rt.case_sense().the_method();
let offset = if offset < 0.0 {
0usize
} else {
offset as usize
};
let characters: Vec<char> = haystack.chars().collect();
let needle_characters: Vec<char> = needle.chars().collect();
let (text, from) = if from_the_right {
let end = characters.len().saturating_sub(offset);
(characters[..end].to_vec(), 0usize)
} else {
let from = offset.min(characters.len());
(characters[from..].to_vec(), from)
};
let places = the_places_of_the_needle(&text, &needle_characters, method);
let place = if number == 0 {
None
} else if from_the_right {
places.iter().rev().nth(number - 1).copied()
} else {
places.get(number - 1).copied()
};
let answer = match place {
Some(place) => Value::Int((place + from) as i64),
None => Value::Int(-1),
};
rt.set_the_error_level(Value::Int(if place.is_some() { 0 } else { 1 }));
write_the_answer(rt, "StringGetPos", values, 0, answer.clone(), line)?;
Ok(answer)
}
fn the_occurrence_of_the_v1(text: &str, line: u32) -> Result<(bool, usize), RuntimeError> {
let wanted = text.trim();
if !parameters::is_an_occurrence(wanted) {
return Err(RuntimeError {
message: format!("Parameter #4 invalid.\n Specifically: {wanted}"),
line,
});
}
let Some(first) = wanted.chars().next() else {
return Ok((false, 1));
};
let from_the_right = match first {
'L' | 'l' => false,
'R' | 'r' => true,
_ => return Ok((true, 1)),
};
let number = wanted[1..].trim().parse::<usize>().unwrap_or(0);
Ok((from_the_right, number))
}
fn the_places_of_the_needle(
text: &[char],
needle: &[char],
method: crate::runtime::CaseMethod,
) -> Vec<usize> {
let mut places = Vec::new();
if needle.len() > text.len() {
return places;
}
let wanted: String = needle.iter().collect();
for at in 0..=(text.len() - needle.len()) {
let found: String = text[at..at + needle.len()].iter().collect();
if crate::runtime::the_same_text(&found, &wanted, method) {
places.push(at);
}
}
places
}
pub(crate) fn string_replace(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let haystack = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let needle = values
.get(2)
.map(|value| value.to_text())
.unwrap_or_default();
let replacement = values
.get(3)
.map(|value| value.to_text())
.unwrap_or_default();
let every = values
.get(4)
.map(|value| value.to_text())
.unwrap_or_default();
let method = rt.case_sense().the_method();
let limit = if the_replace_all_of_the_v1(&every) {
usize::MAX
} else {
1
};
let (answer, count) =
the_text_with_the_needle_in_it(&haystack, &needle, &replacement, limit, method);
rt.set_the_error_level(Value::Int(if the_use_error_level_of_the_v1(&every) {
count as i64
} else {
0
}));
write_the_answer(
rt,
"StringReplace",
values,
0,
Value::Text(answer.clone()),
line,
)?;
Ok(Value::Text(answer))
}
fn the_replace_all_of_the_v1(text: &str) -> bool {
let wanted = text.trim();
if the_use_error_level_of_the_v1(wanted) {
return true;
}
wanted.contains('a') || wanted.contains('A') || wanted.contains('1')
}
fn the_use_error_level_of_the_v1(text: &str) -> bool {
text.trim().to_lowercase().contains("useerrorlevel")
}
fn the_text_with_the_needle_in_it(
haystack: &str,
needle: &str,
replacement: &str,
limit: usize,
method: crate::runtime::CaseMethod,
) -> (String, usize) {
let characters: Vec<char> = haystack.chars().collect();
let needle_characters: Vec<char> = needle.chars().collect();
let places = the_places_of_the_needle(&characters, &needle_characters, method);
let mut answer = String::new();
let mut at = 0usize;
let mut count = 0usize;
for place in places {
if place < at || count >= limit {
break;
}
answer.extend(characters[at..place].iter());
answer.push_str(replacement);
at = place + needle_characters.len();
count += 1;
}
answer.extend(characters[at.min(characters.len())..].iter());
(answer, count)
}
pub(crate) fn str_replace(
rt: &mut Runtime<'_>,
values: &[Value],
_line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let haystack = values
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let needle = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let replacement = values
.get(2)
.map(|value| value.to_text())
.unwrap_or_default();
let limit = values
.get(4)
.and_then(|value| value.to_number())
.unwrap_or(-1.0);
let method = rt.case_sense().the_method();
let limit = if limit < 0.0 {
usize::MAX
} else {
limit as usize
};
let (answer, count) =
the_text_with_the_needle_in_it(&haystack, &needle, &replacement, limit, method);
if let Some(Value::Reference(_)) = values.get(3) {
rt.write_reference(&values[3], Value::Int(count as i64));
}
Ok(Value::Text(answer))
}
pub(crate) fn string_split(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"StringSplit",
values,
line,
crate::builtins::str_split,
0,
)
}
pub(crate) fn string_trim_left(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let text = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let count = values
.get(2)
.and_then(|value| value.to_number())
.unwrap_or(0.0)
.max(0.0) as usize;
let answer = Value::Text(text.chars().skip(count).collect());
write_the_answer(rt, "StringTrimLeft", values, 0, answer.clone(), line)?;
Ok(answer)
}
pub(crate) fn string_trim_right(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let text = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let count = values
.get(2)
.and_then(|value| value.to_number())
.unwrap_or(0.0)
.max(0.0) as usize;
let letters: Vec<char> = text.chars().collect();
let keep = letters.len().saturating_sub(count);
let answer = Value::Text(letters[..keep].iter().collect());
write_the_answer(rt, "StringTrimRight", values, 0, answer.clone(), line)?;
Ok(answer)
}
pub(crate) fn string_lower(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"StringLower",
values,
line,
crate::builtins::change_case,
0,
)
}
pub(crate) fn string_upper(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"StringUpper",
values,
line,
crate::builtins::change_case,
1,
)
}
pub(crate) fn string_right(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let text = values.get(1).cloned().unwrap_or(Value::Text(String::new()));
let count = values
.get(2)
.and_then(|value| value.to_number())
.unwrap_or(0.0) as i64;
let part = if count <= 0 {
Value::Text(String::new())
} else {
crate::builtins::sub_str(rt, &[text, Value::Int(-count)], line, 0)?
};
write_the_answer(rt, "StringRight", values, 0, part.clone(), line)?;
Ok(part)
}
pub(crate) fn file_append(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
if values.get(1).is_none() && rt.the_output_file_of_the_loop().is_none() {
rt.set_the_error_level(Value::Int(1));
rt.note("the command FileAppend did not do the thing: the text has no file to go to.");
return Ok(Value::Text(String::new()));
}
let mut values = values.to_vec();
let mut translation = true;
if let Some(name) = values.get(1).cloned() {
let text = name.to_text();
if text == "*" || text == "**" {
} else if let Some(rest) = text.strip_prefix('*') {
translation = false;
values[1] = Value::Text(rest.to_string());
}
}
if let Some(text) = values.first().cloned() {
if text.to_text().contains("\r\n") {
translation = false;
}
}
let answer = crate::files::file_append_with_the_translation(
rt,
&values,
line,
variant,
translation,
);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_create_dir(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let path = values
.first()
.map(|value| value.to_text())
.unwrap_or_default();
if let Ok(attributes) = rt.desktop().attributes_of_the_pattern(&path, "D") {
if attributes.iter().any(|attribute| attribute.contains('D')) {
rt.set_the_error_level(Value::Int(0));
return Ok(Value::Text(String::new()));
}
}
let answer = crate::builtins::dir_create(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_set_attrib(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let Some(values) = the_values_of_the_file_of_the_loop(rt, values) else {
rt.set_the_error_level(Value::Int(1));
rt.note("the command FileSetAttrib did not do the thing: there is no file of a loop.");
return Ok(Value::Text(String::new()));
};
let answer = crate::files::file_set_attrib(rt, &values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_copy_dir(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::files::dir_copy(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_move_dir(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::files::dir_move(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_remove_dir(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::builtins::dir_delete(rt, values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
pub(crate) fn file_copy(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let from = crate::files::the_name_of_a_file(values, 0, 1, "FileCopy", line)?;
let to = crate::files::the_name_of_a_file(values, 1, 2, "FileCopy", line)?;
let overwrite = crate::files::flag_of(values, 2, "FileCopy", line)?;
let files = files::the_files_of_the_pattern(rt, &from, line)?;
let mut failed = 0;
for file in files {
let destination = if files::is_a_pattern(&from) {
files::the_path_in_the_folder(&to, files::the_name_of_the_file(&file))
} else {
to.clone()
};
if let Err(reason) = rt.desktop().copy_file(&file, &destination, overwrite) {
failed += 1;
rt.note(format!("the file {file} was not copied: {reason}"));
}
}
rt.set_the_error_level(Value::Int(failed));
Ok(Value::Text(String::new()))
}
pub(crate) fn file_delete(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let path = crate::files::the_name_of_a_file(values, 0, 1, "FileDelete", line)?;
let files = if files::is_a_pattern(&path) {
files::the_files_of_the_pattern(rt, &path, line)?
} else {
vec![path.clone()]
};
let mut failed = 0;
for file in files {
if let Err(reason) = rt.desktop().delete_file(&file) {
failed += 1;
rt.note(format!("the file {file} was not deleted: {reason}"));
}
}
rt.set_the_error_level(Value::Int(failed));
Ok(Value::Text(String::new()))
}
pub(crate) fn file_move(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let from = crate::files::the_name_of_a_file(values, 0, 1, "FileMove", line)?;
let to = crate::files::the_name_of_a_file(values, 1, 2, "FileMove", line)?;
let overwrite = crate::files::flag_of(values, 2, "FileMove", line)?;
let files = files::the_files_of_the_pattern(rt, &from, line)?;
let mut failed = 0;
for file in files {
let destination = if files::is_a_pattern(&from) {
files::the_path_in_the_folder(&to, files::the_name_of_the_file(&file))
} else {
to.clone()
};
if let Err(reason) = rt.desktop().move_file(&file, &destination, overwrite) {
failed += 1;
rt.note(format!("the file {file} was not moved: {reason}"));
}
}
rt.set_the_error_level(Value::Int(failed));
Ok(Value::Text(String::new()))
}
pub(crate) fn file_set_time(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let Some(values) = the_values_of_the_file_of_the_loop(rt, values) else {
rt.set_the_error_level(Value::Int(1));
rt.note("the command FileSetTime did not do the thing: there is no file of a loop.");
return Ok(Value::Text(String::new()));
};
let answer = crate::files::file_set_time(rt, &values, line, variant);
the_error_level_of_a_command_that_goes_on(rt, answer)
}
fn the_error_level_of_a_command_that_goes_on(
rt: &mut Runtime<'_>,
answer: Result<Value, RuntimeError>,
) -> Result<Value, RuntimeError> {
match answer {
Ok(value) => {
rt.set_the_error_level(Value::Int(0));
Ok(value)
}
Err(failure) => {
rt.set_the_error_level(Value::Int(1));
rt.note(format!(
"the command did not do the thing: {}",
failure.message
));
Ok(Value::Text(String::new()))
}
}
}
fn the_answer_of_a_file_command(
rt: &mut Runtime<'_>,
name: &str,
values: &[Value],
line: u32,
handler: BuiltinHandler,
flavour: u8,
) -> Result<Value, RuntimeError> {
let answer = handler(rt, values.get(1..).unwrap_or(&[]), line, flavour);
let answer = the_error_level_of_a_command_that_goes_on(rt, answer)?;
write_the_answer(rt, name, values, 0, answer.clone(), line)?;
Ok(answer)
}
fn the_values_of_the_file_of_the_loop(
rt: &mut Runtime<'_>,
values: &[Value],
) -> Option<Vec<Value>> {
let file = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
if !file.is_empty() {
return Some(values.to_vec());
}
let current = rt.the_file_of_the_loop()?;
let mut values = values.to_vec();
if values.len() < 2 {
values.push(Value::Text(current));
} else {
values[1] = Value::Text(current);
}
Some(values)
}
fn the_answer_of_a_file_of_the_loop(
rt: &mut Runtime<'_>,
name: &str,
values: &[Value],
line: u32,
handler: BuiltinHandler,
flavour: u8,
) -> Result<Value, RuntimeError> {
let Some(values) = the_values_of_the_file_of_the_loop(rt, values) else {
rt.set_the_error_level(Value::Int(1));
rt.note(format!(
"the command {name} did not do the thing: there is no file of a loop."
));
write_the_answer(rt, name, values, 0, Value::Text(String::new()), line)?;
return Ok(Value::Text(String::new()));
};
the_answer_of_a_file_command(rt, name, &values, line, handler, flavour)
}
pub(crate) fn file_select_file(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"FileSelectFile",
values,
line,
crate::builtins::file_select,
0,
)
}
pub(crate) fn file_select_folder(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
the_answer_goes_into_the_first_output(
rt,
"FileSelectFolder",
values,
line,
crate::builtins::dir_select,
0,
)
}
pub(crate) fn input_box_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::builtins::input_box(rt, values.get(1..).unwrap_or(&[]), line, 0)?;
let text = match rt.read_property(&answer, "Value", line) {
Ok(value) => value,
Err(failure) => {
return Err(RuntimeError {
message: crate::runtime::the_message_of(&failure),
line,
});
}
};
write_the_answer(rt, "InputBox", values, 0, text, line)?;
Ok(answer)
}
pub(crate) fn run_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
run_or_wait_of_the_v1(rt, values, line, false)
}
pub(crate) fn run_wait_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
run_or_wait_of_the_v1(rt, values, line, true)
}
fn run_or_wait_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
waits: bool,
) -> Result<Value, RuntimeError> {
let target = values
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let dir = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let options = values
.get(2)
.map(|value| value.to_text())
.unwrap_or_default();
let says = the_options_say_use_error_level(&options);
if waits {
let (pid, code, stdout, stderr) = match rt.desktop().run_and_wait(&target, &dir) {
Ok(answer) => answer,
Err(reason) => {
if says {
rt.set_the_error_level(Value::Text("ERROR".into()));
}
return Err(RuntimeError {
message: reason,
line,
});
}
};
if !stdout.trim().is_empty() {
rt.push_output(stdout.trim_end().to_string());
}
if !stderr.trim().is_empty() {
rt.push_output(stderr.trim_end().to_string());
}
rt.set_the_error_level(Value::Int(code as i64));
write_the_answer(rt, "RunWait", values, 3, Value::Int(pid as i64), line)?;
return Ok(Value::Int(code as i64));
}
let pid = match rt.desktop().launch(&target, &dir) {
Ok(pid) => pid,
Err(reason) => {
if says {
rt.set_the_error_level(Value::Text("ERROR".into()));
}
return Err(RuntimeError {
message: reason,
line,
});
}
};
if says {
rt.set_the_error_level(Value::Int(0));
}
write_the_answer(rt, "Run", values, 3, Value::Int(pid as i64), line)?;
Ok(Value::Int(pid as i64))
}
fn the_options_say_use_error_level(options: &str) -> bool {
options.to_lowercase().contains("useerrorlevel")
}
pub(crate) fn clip_wait_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let answer = crate::builtins::clip_wait(rt, values, line, variant)?;
let expired = matches!(answer, Value::Int(0));
rt.set_the_error_level(Value::Int(if expired { 1 } else { 0 }));
Ok(answer)
}
pub(crate) fn dll_call_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
match crate::builtins::dll_call_with_the_kind(rt, values, line) {
Ok(answer) => {
rt.set_the_error_level(Value::Int(0));
Ok(answer)
}
Err((kind, error)) => {
rt.set_the_error_level(Value::Int(the_code_of_the_failure(kind)));
rt.note(format!("the call did not go: {}", error.message));
Ok(Value::Text(String::new()))
}
}
}
fn the_code_of_the_failure(kind: crate::dll::NativeFailureKind) -> i64 {
match kind {
crate::dll::NativeFailureKind::Invalid => -2,
crate::dll::NativeFailureKind::NoLibrary => -3,
crate::dll::NativeFailureKind::NoFunction => -4,
}
}
pub(crate) fn sound_play_of_the_v1(
rt: &mut Runtime<'_>,
values: &[Value],
_line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let name = values
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let name = name.trim();
if name.starts_with('*') {
rt.set_the_error_level(Value::Int(0));
return Ok(Value::Int(1));
}
let played = rt.desktop().sound_play(name);
rt.set_the_error_level(Value::Int(if played.is_err() { 1 } else { 0 }));
Ok(Value::Int(1))
}
pub(crate) fn string_left(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let text = values.get(1).cloned().unwrap_or(Value::Text(String::new()));
let count = values.get(2).cloned().unwrap_or(Value::Text(String::new()));
let part = crate::builtins::sub_str(rt, &[text, Value::Int(1), count], line, 0)?;
write_the_answer(rt, "StringLeft", values, 0, part.clone(), line)?;
Ok(part)
}
fn env_arithmetic(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
name: &str,
operation: TheArithmetic,
) -> Result<Value, RuntimeError> {
let Some(variable) = values.first() else {
return Ok(Value::Text(String::new()));
};
let Value::Reference(reference) = variable else {
return Err(RuntimeError {
message: crate::runtime::wants_a_reference(1, name, "a VarRef", variable),
line,
});
};
if let Some(units) = values.get(2) {
if !units.to_text().trim().is_empty() {
return the_arithmetic_of_the_date(rt, values, line, name, operation, &units.to_text());
}
}
let current = rt
.read_reference(reference)
.map(|value| value.to_text())
.unwrap_or_default();
let current = crate::v1::the_number_at_the_start_of_a_text(¤t);
let other = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let other = crate::v1::the_number_at_the_start_of_a_text(&other);
let left = the_number_of_the_v1(¤t);
let right = the_number_of_the_v1(&other);
let whole =
!matches!(current, Some(Value::Float(_))) && !matches!(other, Some(Value::Float(_)));
let answer = match operation {
TheArithmetic::Add => left + right,
TheArithmetic::Subtract => left - right,
TheArithmetic::Multiply => left * right,
TheArithmetic::Divide => {
if right == 0.0 {
rt.write_reference(variable, Value::Text(String::new()));
return Ok(Value::Text(String::new()));
}
if whole {
((left as i64) / (right as i64)) as f64
} else {
left / right
}
}
};
let value = if whole {
Value::Int(answer as i64)
} else {
Value::Float(answer)
};
rt.write_reference(variable, value.clone());
Ok(value)
}
fn the_arithmetic_of_the_date(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
name: &str,
operation: TheArithmetic,
units: &str,
) -> Result<Value, RuntimeError> {
let Some(variable) = values.first() else {
return Ok(Value::Text(String::new()));
};
let Value::Reference(reference) = variable else {
return Err(RuntimeError {
message: crate::runtime::wants_a_reference(1, name, "a VarRef", variable),
line,
});
};
let Some(clock) = rt.wall_clock() else {
return Err(RuntimeError {
message: "the date of the machine is not known.".to_string(),
line,
});
};
let unit = the_number_of_the_unit_of_the_time(units);
let text = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
match operation {
TheArithmetic::Add => {
let Some(amount) = crate::v1::the_number_at_the_start_of_a_text(&text) else {
return the_variable_is_empty(rt, variable);
};
let amount = the_number_of_the_v1(&Some(amount)) * unit as f64;
let base_text = rt
.read_reference(reference)
.map(|value| value.to_text())
.unwrap_or_default();
let base_time = if base_text.trim().is_empty() {
the_file_time_of_the_machine(&clock.local)
} else {
let Some(base_number) =
crate::v1::the_number_at_the_start_of_a_text(&base_text)
else {
return the_variable_is_empty(rt, variable);
};
let whole = the_number_of_the_v1(&Some(base_number)) as i64;
let Some(base_date) = crate::v1::the_date_of_the_v1(&whole.to_string()) else {
return the_variable_is_empty(rt, variable);
};
the_file_time_of_the_machine(&base_date)
};
let file_time = base_time
.wrapping_add(the_hundred_of_nanoseconds_of_the_amount(amount));
let millis = (file_time / 10_000) as i64 - THE_MILLIS_BETWEEN_1601_AND_1970;
let date = crate::date::from_unix_millis(millis);
if !(THE_FIRST_YEAR..=THE_LAST_YEAR).contains(&date.year) {
return the_variable_is_empty(rt, variable);
}
let answer = crate::date::the_number_text(&date);
rt.write_reference(variable, Value::Text(answer.clone()));
Ok(Value::Text(answer))
}
TheArithmetic::Subtract => {
if text.is_empty() {
rt.write_reference(variable, Value::Int(0));
return Ok(Value::Int(0));
}
let Some(number) = crate::v1::the_number_at_the_start_of_a_text(&text) else {
return the_variable_is_empty(rt, variable);
};
let whole = the_number_of_the_v1(&Some(number)) as i64;
let Some(date) = crate::v1::the_date_of_the_v1(&whole.to_string()) else {
return the_variable_is_empty(rt, variable);
};
let difference =
crate::date::to_unix_millis(&clock.local) - crate::date::to_unix_millis(&date);
let answer = difference / 1000 / unit;
rt.write_reference(variable, Value::Int(answer));
Ok(Value::Int(answer))
}
_ => Ok(Value::Text(String::new())),
}
}
fn the_variable_is_empty(rt: &mut Runtime<'_>, variable: &Value) -> Result<Value, RuntimeError> {
rt.write_reference(variable, Value::Text(String::new()));
Ok(Value::Text(String::new()))
}
const THE_HUNDRED_OF_NANOSECONDS: u64 = 10_000_000;
const THE_MILLIS_BETWEEN_1601_AND_1970: i64 = 11_644_473_600_000;
const THE_FIRST_YEAR: i64 = 1601;
const THE_LAST_YEAR: i64 = 30827;
fn the_file_time_of_the_machine(local: &crate::date::DateTime) -> u64 {
let millis = crate::date::to_unix_millis(local) + THE_MILLIS_BETWEEN_1601_AND_1970;
(millis as u64) * 10_000
}
fn the_hundred_of_nanoseconds_of_the_amount(amount: f64) -> u64 {
let whole = amount as i64;
let fraction = amount - whole as f64;
(whole as u64)
.wrapping_mul(THE_HUNDRED_OF_NANOSECONDS)
.wrapping_add((fraction * THE_HUNDRED_OF_NANOSECONDS as f64) as u64)
}
fn the_number_of_the_unit_of_the_time(units: &str) -> i64 {
match units
.trim()
.chars()
.next()
.map(|letter| letter.to_ascii_uppercase())
{
Some('M') => 60,
Some('H') => 3600,
Some('D') => 86400,
_ => 1,
}
}
#[derive(Clone, Copy)]
enum TheArithmetic {
Add,
Subtract,
Multiply,
Divide,
}
fn the_number_of_the_v1(value: &Option<Value>) -> f64 {
match value {
Some(Value::Int(number)) => *number as f64,
Some(Value::Float(number)) => *number,
_ => 0.0,
}
}
pub(crate) fn env_add(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
env_arithmetic(rt, values, line, "EnvAdd", TheArithmetic::Add)
}
pub(crate) fn env_sub(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
env_arithmetic(rt, values, line, "EnvSub", TheArithmetic::Subtract)
}
pub(crate) fn env_mult(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
env_arithmetic(rt, values, line, "EnvMult", TheArithmetic::Multiply)
}
pub(crate) fn env_div(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
env_arithmetic(rt, values, line, "EnvDiv", TheArithmetic::Divide)
}