use alloc::format;
use alloc::string::{String, ToString};
use core::time::Duration;
use crate::builtins;
use crate::desktop::{
Clipboard, Desktop, Dialogs, Files, Hotkeys, Keyboard, Machine, Native, Network, Pictures,
Pointer, Processes, Screen, Sound, Timers, Windows,
};
use crate::dialect::Dialect;
use crate::runtime::{Clock, Runtime};
const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const MESSAGE_LIMIT: usize = 200;
const PROBES: &[(&str, &str)] = &[
("Abs", "FileAppend(Abs(-3), \"*\")"),
("Ceil", "FileAppend(Ceil(1.2), \"*\")"),
("Floor", "FileAppend(Floor(1.8), \"*\")"),
("Round", "FileAppend(Round(1.5), \"*\")"),
("Sqrt", "FileAppend(Sqrt(9), \"*\")"),
("Mod", "FileAppend(Mod(7, 3), \"*\")"),
("Max", "FileAppend(Max(1, 2), \"*\")"),
("Min", "FileAppend(Min(1, 2), \"*\")"),
("Chr", "FileAppend(Chr(65), \"*\")"),
("Ord", "FileAppend(Ord(\"A\"), \"*\")"),
("StrLen", "FileAppend(StrLen(\"abc\"), \"*\")"),
("SubStr", "FileAppend(SubStr(\"abc\", 2), \"*\")"),
("StrUpper", "FileAppend(StrUpper(\"abc\"), \"*\")"),
("StrLower", "FileAppend(StrLower(\"ABC\"), \"*\")"),
("StrReplace", "FileAppend(StrReplace(\"abc\", \"b\", \"x\"), \"*\")"),
("Trim", "FileAppend(Trim(\" a \"), \"*\")"),
("StrCompare", "FileAppend(StrCompare(\"a\", \"b\"), \"*\")"),
("StrSplit", "FileAppend(StrSplit(\"a,b\", \",\").Length, \"*\")"),
("Sort", "FileAppend(Sort(\"233`n40\", \"N\"), \"*\")"),
("Format", "FileAppend(Format(\"{:05d}\", 42), \"*\")"),
("RegExMatch", "FileAppend(RegExMatch(\"abc123\", \"\\d+\", &m), \"*\")"),
("RegExReplace", "FileAppend(RegExReplace(\"abc123\", \"\\d+\", \"X\"), \"*\")"),
("InStr", "FileAppend(InStr(\"abcabc\", \"bc\", \"Off\", 4), \"*\")"),
("DateAdd", "FileAppend(DateAdd(\"20200101000000\", 1, \"Days\"), \"*\")"),
("DateDiff", "FileAppend(DateDiff(\"20200110000000\", \"20200101000000\", \"Days\"), \"*\")"),
("Type", "FileAppend(Type(42), \"*\")"),
("IsObject", "FileAppend(IsObject({}), \"*\")"),
("IsNumber", "FileAppend(IsNumber(\"12\"), \"*\")"),
("Integer", "FileAppend(Integer(\"0x1F\"), \"*\")"),
("Float", "FileAppend(Float(\"1.5\"), \"*\")"),
("String", "FileAppend(String(42), \"*\")"),
("Push", "a := []\na.Push(1, 2)\nFileAppend(a.Length, \"*\")"),
("Pop", "a := [1, 2]\nFileAppend(a.Pop(), \"*\")"),
("InsertAt", "a := [1]\na.InsertAt(1, 0)\nFileAppend(a[1], \"*\")"),
("RemoveAt", "a := [1, 2]\na.RemoveAt(1)\nFileAppend(a.Length, \"*\")"),
("Set", "m := Map()\nm.Set(\"a\", 1)\nFileAppend(m.Count, \"*\")"),
("Count", "m := Map(\"a\", 1)\nFileAppend(m.Count, \"*\")"),
("Array.Length", "a := [1, 2]\nFileAppend(a.Length, \"*\")"),
("Array.__Item", "a := [7]\nFileAppend(a[1], \"*\")"),
("Map.Get", "m := Map(\"a\", 1)\nFileAppend(m.Get(\"a\"), \"*\")"),
("Map.Has", "m := Map(\"a\", 1)\nFileAppend(m.Has(\"a\"), \"*\")"),
("Map.Delete", "m := Map(\"a\", 1)\nm.Delete(\"a\")\nFileAppend(m.Count, \"*\")"),
("Map.__Item", "m := Map()\nm[\"a\"] := 1\nFileAppend(m[\"a\"], \"*\")"),
("Error", "e := Error(\"boom\")\nFileAppend(e.Message, \"*\")"),
("IsSet", "u := unset\nFileAppend(IsSet(u), \"*\")"),
(
"Loop",
"i := 0\nLoop {\n i += 1\n}\nUntil i >= 3\nFileAppend(i, \"*\")",
),
(
"Object.__Item",
"class Store {\n __Item[key] {\n get => \"got\"\n }\n}\ns := Store()\ns[1] := \"one\"\nFileAppend(\"reached\", \"*\")",
),
("FloatPrinting", "FileAppend(1 / 3, \"*\")"),
("VerCompare", "FileAppend(VerCompare(\"1.2\", \"1.10\"), \"*\")"),
];
pub fn behaviour_of(dialect: &'static dyn Dialect, name: &str) -> Option<String> {
if dialect.name().eq_ignore_ascii_case("v2") {
if let Some(snippet) = snippet_of(name) {
return Some(the_run_of(snippet));
}
}
the_refusal_of(dialect, name)
}
fn snippet_of(name: &str) -> Option<&'static str> {
for (probed, snippet) in PROBES {
if probed.eq_ignore_ascii_case(name) {
return Some(snippet);
}
}
let (_, bare) = name.rsplit_once('.')?;
for (probed, snippet) in PROBES {
if probed.eq_ignore_ascii_case(bare) {
return Some(snippet);
}
}
None
}
fn the_refusal_of(dialect: &'static dyn Dialect, name: &str) -> Option<String> {
if let Some(reason) = dialect.refusal_of_variable(name) {
return Some(format!("refusal: {reason}"));
}
let builtin = dialect
.builtins()
.iter()
.find(|builtin| builtin.name.eq_ignore_ascii_case(name))
.or_else(|| dialect.the_builtin_of_the_extension(name))?;
builtins::refusal_of_the(builtin).map(|reason| format!("refusal: {reason}"))
}
fn the_run_of(snippet: &str) -> String {
let statements = match crate::parse(snippet) {
Ok(statements) => statements,
Err(error) => return format!("error: {}", one_line(&error.message)),
};
let mut desktop = ProbeDesktop;
let mut clock = ProbeClock;
let report = Runtime::with_clock(&mut desktop, &mut clock, PROBE_TIMEOUT).run(&statements);
match report.error {
Some(message) => format!("error: {}", one_line(&message)),
None if report.ok => "value".to_string(),
None => "error: the run stopped without a message".to_string(),
}
}
fn one_line(message: &str) -> String {
let mut out = String::with_capacity(message.len().min(MESSAGE_LIMIT));
for (count, character) in message.chars().enumerate() {
if count >= MESSAGE_LIMIT {
break;
}
out.push(if character == '\n' || character == '\r' {
' '
} else {
character
});
}
out
}
struct ProbeClock;
impl Clock for ProbeClock {
fn now_ms(&self) -> u64 {
0
}
fn sleep_ms(&mut self, _millis: u64) {}
}
struct ProbeDesktop;
impl Desktop for ProbeDesktop {}
impl Keyboard for ProbeDesktop {
fn type_text(&mut self, _text: &str) -> Result<String, String> {
Ok(String::new())
}
fn press_key(&mut self, _name: &str, _modifiers: &[String]) -> Result<String, String> {
Ok(String::new())
}
}
impl Pointer for ProbeDesktop {
fn click(&mut self, _x: i64, _y: i64, _button: &str, _count: u32) -> Result<String, String> {
Ok(String::new())
}
}
impl Screen for ProbeDesktop {
fn capture(
&mut self,
_x: i64,
_y: i64,
_width: i64,
_height: i64,
_filename: &str,
) -> Result<String, String> {
Ok(String::new())
}
fn pixel(&mut self, _x: i64, _y: i64) -> Result<String, String> {
Ok("#000000".to_string())
}
}
impl Processes for ProbeDesktop {
fn run(&mut self, _command: &str, _window: &str) -> Result<(i32, String, String), String> {
Ok((0, String::new(), String::new()))
}
}
impl Windows for ProbeDesktop {}
impl Files for ProbeDesktop {}
impl Clipboard for ProbeDesktop {}
impl Timers for ProbeDesktop {}
impl Hotkeys for ProbeDesktop {}
impl Native for ProbeDesktop {}
impl Sound for ProbeDesktop {}
impl Machine for ProbeDesktop {}
impl Dialogs for ProbeDesktop {}
impl Network for ProbeDesktop {}
impl Pictures for ProbeDesktop {}
#[cfg(test)]
mod tests {
use super::*;
use crate::dialect;
fn the_answer(name: &str) -> String {
behaviour_of(dialect::v2(), name).expect("the name has a probe or a refusal")
}
fn the_shape_of(answer: &str) -> &'static str {
if answer == "value" {
"value"
} else if answer.starts_with("error: ") {
"error"
} else if answer.starts_with("refusal: ") {
"refusal"
} else {
"other"
}
}
#[test]
fn the_table_has_the_names_of_the_audit_and_the_names_of_the_language() {
for name in [
"Format",
"RegExMatch",
"Sort",
"DateAdd",
"DateDiff",
"InStr",
"IsSet",
"Integer",
"Loop",
"Object.__Item",
"FloatPrinting",
] {
assert!(
snippet_of(name).is_some(),
"the known gap {name} has no probe"
);
}
assert!(PROBES.len() >= 40, "the table has {} probes", PROBES.len());
let mut names: Vec<&str> = PROBES.iter().map(|(name, _)| *name).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), PROBES.len(), "a probe is written twice");
for (name, snippet) in PROBES {
assert!(!name.is_empty() && !snippet.is_empty());
assert!(
snippet.contains("FileAppend("),
"{name} does not print its answer"
);
}
}
#[test]
fn the_answer_of_the_known_gaps_is_what_the_tree_does_today() {
for name in ["Format", "FloatPrinting"] {
assert_eq!(
the_answer(name),
"value",
"{name} answers with a value today"
);
}
assert_eq!(the_answer("RegExMatch"), "value");
assert_eq!(the_answer("Sort"), "value");
assert_eq!(the_answer("DateAdd"), "value");
assert_eq!(the_answer("DateDiff"), "value");
assert_eq!(the_answer("InStr"), "value");
assert_eq!(the_answer("IsSet"), "value");
assert_eq!(the_answer("Loop"), "value");
assert_eq!(
the_answer("Object.__Item"),
"error: This value of type \"Store\" has no property named \"__Item\"."
);
assert_eq!(the_answer("Integer"), "value");
}
#[test]
fn the_primitive_classes_convert_a_value() {
for name in ["Integer", "Float", "String"] {
assert_eq!(the_answer(name), "value", "{name}");
}
}
#[test]
fn the_names_of_the_language_answer_with_a_value() {
for name in [
"Abs", "Ceil", "Floor", "Round", "Sqrt", "Mod", "Max", "Min", "Chr", "Ord", "StrLen",
"SubStr", "StrUpper", "StrLower", "StrReplace", "Trim", "StrCompare", "StrSplit",
"RegExReplace", "Type", "IsObject", "IsNumber", "Push", "Pop", "InsertAt",
"RemoveAt", "Set", "Count", "Array.Length", "Array.__Item", "Map.Get", "Map.Has",
"Map.Delete", "Map.__Item", "Error", "VerCompare",
] {
assert_eq!(
the_answer(name),
"value",
"{name} answers with a value today: {}",
the_answer(name)
);
}
}
#[test]
fn the_snippets_stay_in_the_language() {
for (name, snippet) in PROBES {
for forbidden in [
"MsgBox",
"Sleep",
"InputBox",
"FileSelect",
"DirSelect",
"FileOpen",
"FileDelete",
"FileCopy",
"FileMove",
"FileRead",
"SetTimer",
"Hotkey",
"Run(",
"Download",
"Clipboard",
"Send",
"Click",
"PixelGetColor",
] {
assert!(
!snippet.contains(forbidden),
"{name} asks the machine for {forbidden}"
);
}
assert_eq!(
snippet.matches("FileAppend(").count(),
1,
"{name} writes more than the console"
);
assert!(
snippet.contains(", \"*\")"),
"{name} does not write to the console"
);
}
}
#[test]
fn a_name_without_a_probe_and_without_a_refusal_has_no_behaviour() {
assert!(behaviour_of(dialect::v2(), "NoSuchNameOfAnyKind").is_none());
assert!(behaviour_of(dialect::v2(), "A_UserName").is_none());
}
#[test]
fn a_refused_name_answers_with_its_reason() {
let answer = the_answer("WinActivate");
assert!(answer.starts_with("refusal: "), "{answer}");
assert_eq!(
answer,
"refusal: this is a name of Windows, and this desktop is not Windows."
);
}
#[test]
fn the_method_of_a_class_is_named_with_its_class_or_without_it() {
assert_eq!(the_answer("Push"), "value");
assert_eq!(
behaviour_of(dialect::v2(), "Array.Push"),
behaviour_of(dialect::v2(), "Push")
);
assert_eq!(
behaviour_of(dialect::v2(), "ARRAY.PUSH"),
behaviour_of(dialect::v2(), "Push")
);
assert_eq!(the_answer("Array.Length"), "value");
assert!(behaviour_of(dialect::v2(), "Length").is_none());
assert_eq!(the_answer("Map.Get"), "value");
assert!(behaviour_of(dialect::v2(), "Get").is_none());
}
#[test]
fn the_v1_runs_no_probe_of_the_v2() {
assert!(behaviour_of(dialect::v1(), "Abs").is_none());
}
#[test]
fn the_snippet_of_every_probe_parses() {
for (name, snippet) in PROBES {
assert!(
crate::parse(snippet).is_ok(),
"{name} does not parse: {:?}",
crate::parse(snippet).err().map(|error| error.message)
);
}
}
#[test]
fn every_answer_is_one_line() {
for (name, _) in PROBES {
let answer = the_answer(name);
assert!(!answer.contains('\n'), "{name} answers in more than a line");
assert!(!answer.contains('\r'), "{name} answers in more than a line");
assert!(
answer.chars().count() <= MESSAGE_LIMIT + "error: ".len(),
"{name} answers with more than the limit"
);
assert_ne!(the_shape_of(&answer), "other", "{name}: {answer}");
}
}
}