use crate::compile::{compile, compile_with_warnings};
use crate::program::Program;
use crate::registry::Sugar;
use crate::texts::TextTable;
use crate::vm::*;
pub(super) fn ui_registry(sugars: &[Sugar], extra: impl FnOnce(&mut Registry)) -> Registry {
let mut r = Registry::new();
r.stop::<(String,), ()>("ui.say").unwrap();
for sugar in sugars {
match sugar {
Sugar::Quote => r
.stop::<(Option<crate::Identity>, String), ()>("ui.say_as")
.unwrap(),
Sugar::Choice => r
.stop::<(Vec<String>, Vec<Option<String>>), i64>("ui.choose")
.unwrap(),
other => panic!("登録しない糖衣: {other:?}"),
};
}
extra(&mut r);
r.bind(Sugar::Plain, "ui.say").unwrap();
if sugars.contains(&Sugar::Quote) {
r.bind(Sugar::Quote, "ui.say_as").unwrap();
}
if sugars.contains(&Sugar::Choice) {
r.bind(Sugar::Choice, "ui.choose").unwrap();
}
r
}
pub(super) fn compile_ok(src: &str, reg: &Registry) -> Program {
match compile(src, "main", reg) {
Ok(p) => p,
Err(d) => panic!("コンパイルできない: {d:?}\n{src}"),
}
}
pub(super) fn error_codes(src: &str, reg: &Registry) -> Vec<&'static str> {
match compile(src, "main", reg) {
Ok(_) => Vec::new(),
Err(d) => d.iter().map(|d| d.code.as_str()).collect(),
}
}
pub(super) fn diag_codes(src: &str, reg: &Registry) -> Vec<&'static str> {
match compile_with_warnings(src, "main", reg) {
Ok((_, w)) => w.iter().map(|d| d.code.as_str()).collect(),
Err(d) => d.iter().map(|d| d.code.as_str()).collect(),
}
}
pub(super) fn text_of(y: &Yield) -> String {
match y {
Yield::Stop { args, .. } => args.last().map(Value::to_text).unwrap_or_default(),
Yield::End => "<end>".to_string(),
}
}
pub(super) fn args_of(y: &Yield) -> Vec<Value> {
match y {
Yield::Stop { args, .. } => args.clone(),
Yield::End => Vec::new(),
}
}
pub(super) fn var(vm: &Vm<'_>, name: &str) -> Value {
vm.variables()
.into_iter()
.find(|v| v.name == name)
.unwrap_or_else(|| panic!("変数 {name} がない"))
.value
}
pub(super) fn resume(vm: &mut Vm<'_>) {
let is_choice = matches!(
vm.current(),
Some(Yield::Stop { args, .. }) if matches!(args.first(), Some(Value::List(_)))
);
let v = if is_choice {
Value::Int(0)
} else {
Value::Unit
};
vm.resume(Input::Return(v)).unwrap();
}
pub(super) fn run_all(vm: &mut Vm<'_>, limit: usize) -> Vec<String> {
let mut out = Vec::new();
if vm.is_stopped() {
resume(vm);
}
for _ in 0..limit {
match vm.run() {
Ok(Yield::End) => {
out.push("<end>".to_string());
break;
}
Ok(y) => {
out.push(text_of(&y));
resume(vm);
}
Err(e) => {
out.push(format!("<{}>", e.kind.code()));
break;
}
}
}
out
}
pub(super) fn texts_with(src: &str, reg: &Registry, cfg: VmConfig, limit: usize) -> Vec<String> {
let prog = compile_ok(src, reg);
let mut vm = Vm::new(&prog, reg, cfg).unwrap();
run_all(&mut vm, limit)
}
pub(super) fn table(pairs: &[(&str, &str)]) -> TextTable {
let mut t = TextTable::new("en");
for (k, v) in pairs {
t.insert(*k, *v).unwrap();
}
t
}