use super::*;
pub(super) type Typed = (Option<Ty>, ExprId);
pub(super) type MethodSig<'a> = (&'a str, Vec<Ty>, Method, Ty);
pub(super) const BUILTIN_NAMES: &[&str] = &[
"random",
"random_float",
"seen",
"visited",
"to_int",
"to_float",
"range",
];
impl Builtin {
pub(super) fn from_name(name: &str) -> Option<Self> {
match name {
"to_int" => Some(Builtin::ToInt),
"to_float" => Some(Builtin::ToFloat),
"seen" => Some(Builtin::Seen),
"visited" => Some(Builtin::Visited),
"random" => Some(Builtin::Random),
"random_float" => Some(Builtin::RandomFloat),
"range" => Some(Builtin::Range),
_ => None,
}
}
pub(super) fn params(self) -> &'static [Ty] {
match self {
Builtin::ToInt => &[Ty::Float],
Builtin::ToFloat => &[Ty::Int],
Builtin::Seen | Builtin::Visited => &[Ty::Str],
Builtin::Random | Builtin::Range => &[Ty::Int, Ty::Int],
Builtin::RandomFloat => &[],
}
}
pub(super) fn ret(self) -> Ty {
match self {
Builtin::Range => Ty::List(Box::new(Ty::Int)),
Builtin::ToInt | Builtin::Random => Ty::Int,
Builtin::ToFloat | Builtin::RandomFloat => Ty::Float,
Builtin::Seen | Builtin::Visited => Ty::Bool,
}
}
}
pub(super) enum Target {
Module(usize),
Package,
}
#[derive(Debug, Default)]
pub(super) struct LabelRefs {
pub(super) stop_ids: Vec<String>,
pub(super) targets: Vec<u32>,
}
#[derive(Debug, Clone, Default)]
pub(super) enum RetTy {
#[default]
None,
Ty(Ty),
Bad,
}
#[derive(Debug, Clone, Default)]
pub(super) struct Sig {
pub(super) params: Vec<Option<Ty>>,
pub(super) names: Vec<String>,
pub(super) defaults: Vec<Option<Value>>,
pub(super) ret: RetTy,
}
#[derive(Debug, Clone, Default)]
pub(super) struct ParamSpec {
pub(super) name: Option<String>,
pub(super) default: Option<Value>,
}
impl Sig {
pub(super) fn specs(&self) -> Vec<ParamSpec> {
self.names
.iter()
.zip(&self.defaults)
.map(|(n, d)| ParamSpec {
name: Some(n.clone()),
default: d.clone(),
})
.collect()
}
}
impl Sig {
pub(super) fn callable(&self) -> bool {
!self.params.is_empty() || !matches!(self.ret, RetTy::None)
}
}
pub(super) struct ChoiceState {
pub(super) ignored: bool,
pub(super) cmd: u32,
pub(super) options: Vec<IrChoiceOpt>,
pub(super) info: StopInfo,
pub(super) refs_before: (usize, usize),
}
pub(super) struct ModDecl {
pub(super) name: String,
pub(super) global_map: HashMap<String, (u32, Ty)>,
pub(super) label_map: HashMap<String, u32>,
pub(super) fn_map: HashMap<String, u32>,
pub(super) identities: HashMap<String, String>,
pub(super) early_identities: HashMap<String, String>,
pub(super) poisoned: HashSet<String>,
pub(super) imports: HashMap<String, usize>,
pub(super) pkg_imports: HashSet<String>,
pub(super) bad_imports: HashSet<String>,
pub(super) type_map: HashMap<String, u32>,
}
pub(super) struct LabelCtx {
pub(super) ir: Ir,
pub(super) locals: Vec<LocalInfo>,
pub(super) scopes: Vec<HashMap<String, (u32, Option<Ty>)>>,
pub(super) ids: HashSet<String>,
pub(super) refs: LabelRefs,
pub(super) loop_depth: u32,
pub(super) name: String,
pub(super) ret: RetTy,
pub(super) in_fn: bool,
pub(super) live: lambda::FnLive,
pub(super) lets: LetUse,
}
#[derive(Default)]
pub(super) struct LetUse {
pub(super) decls: Vec<(u32, String, Pos)>,
pub(super) read: HashSet<u32>,
}
pub(super) struct ImportSite {
pub(super) module: usize,
pub(super) local: String,
pub(super) path: String,
pub(super) pos: Pos,
}
pub(super) struct Compiler<'a> {
pub(super) registry: &'a Registry,
pub(super) diags: Vec<Diagnostic>,
pub(super) modules: Vec<ModDecl>,
pub(super) module_index: HashMap<String, usize>,
pub(super) used_imports: std::cell::RefCell<HashSet<(usize, String)>>,
pub(super) import_sites: Vec<ImportSite>,
pub(super) module_last: HashMap<String, usize>,
pub(super) cur_mod: usize,
pub(super) globals: Vec<GlobalInfo>,
pub(super) sigs: Vec<Sig>,
pub(super) fn_sigs: Vec<Sig>,
pub(super) commands: Vec<String>,
pub(super) natives: Vec<String>,
pub(super) host_vars: Vec<String>,
pub(super) cur: Option<LabelCtx>,
pub(super) literals: Vec<LiteralArg>,
pub(super) types: Vec<TypeDecl>,
pub(super) registry_types: usize,
pub(super) types_ready: bool,
pub(super) pending_keys: Vec<(usize, Pos, Ty)>,
pub(super) require_text_ids: bool,
pub(super) id_sites: Vec<IdSite>,
pub(super) local_types: Vec<(usize, Pos, String)>,
pub(super) repl: Option<repl::ReplState>,
pub(super) reg_overflow: Vec<(usize, Pos)>,
pub(super) unused_vars: Vec<(usize, Pos, String)>,
pub(super) fn_total: u32,
pub(super) lambdas: Vec<Option<FnCode>>,
pub(super) hofs: HashMap<lambda::Hof, u32>,
pub(super) migrate_expr: bool,
}
impl Compiler<'_> {
pub(super) fn impure_use(&mut self, pos: Pos, what: &'static str) -> bool {
if !self.migrate_expr {
return false;
}
self.error(pos, DiagCode::MigrateImpureExpr, vec![("what", s(what))]);
true
}
}
pub(super) struct TargetInfo {
pub(super) place: PlaceRef,
pub(super) ty: Option<Ty>,
pub(super) steps: Vec<PathStep>,
pub(super) indices: Vec<ExprId>,
}
pub(super) enum PathItem<'e> {
Field(&'e str, Pos),
Index(&'e Expr, Pos),
}
pub(super) type ArmBinding = (u32, Option<(String, Pos)>, Option<Ty>);
#[derive(Default)]
pub(super) struct Coverage {
pub(super) catch_all: bool,
pub(super) bools: [bool; 2],
pub(super) some: bool,
pub(super) none: bool,
pub(super) variants: HashSet<String>,
pub(super) lits: HashSet<String>,
}
impl Coverage {
pub(super) fn complete(&self, ty: Option<&Ty>, decl: Option<&TypeDecl>) -> bool {
if self.catch_all {
return true;
}
match ty {
Some(Ty::Bool) => self.bools[0] && self.bools[1],
Some(Ty::Option(_)) => self.some && self.none,
Some(Ty::Enum(_)) => match decl.map(|d| &d.kind) {
Some(TypeKind::Enum { variants }) => {
variants.iter().all(|v| self.variants.contains(&v.name))
}
_ => false,
},
_ => false,
}
}
pub(super) fn missing(&self, ty: &Ty, decl: Option<&TypeDecl>) -> Vec<String> {
if self.catch_all {
return Vec::new();
}
match ty {
Ty::Bool => [(false, "false"), (true, "true")]
.iter()
.filter(|(b, _)| !self.bools[usize::from(*b)])
.map(|(_, n)| (*n).to_string())
.collect(),
Ty::Option(_) => {
let mut out = Vec::new();
if !self.none {
out.push("None".to_string());
}
if !self.some {
out.push("Some(_)".to_string());
}
out
}
Ty::Enum(_) => match decl.map(|d| &d.kind) {
Some(TypeKind::Enum { variants }) => variants
.iter()
.filter(|v| !self.variants.contains(&v.name))
.map(|v| {
let short =
crate::value::short_type_name(&decl.expect("宣言").name).to_string();
if v.args.is_empty() {
format!("{short}.{}", v.name)
} else {
let holes = vec!["_"; v.args.len()].join(", ");
format!("{short}.{}({holes})", v.name)
}
})
.collect(),
_ => vec!["_".to_string()],
},
_ => vec!["_".to_string()],
}
}
}
pub(super) struct VariantRef<'e> {
pub(super) ty: u32,
pub(super) variant: &'e str,
pub(super) args: &'e [Expr],
pub(super) pos: Pos,
}
pub(super) struct LiteralArg {
pub(super) module: usize,
pub(super) pos: Pos,
pub(super) seen: bool,
pub(super) text: String,
}
pub(super) fn s(v: &str) -> DiagArg {
DiagArg::Str(v.to_string())
}
pub(super) fn name_args(name: &str, suggestions: Vec<String>) -> Vec<(&'static str, DiagArg)> {
let mut args = vec![("name", s(name))];
if !suggestions.is_empty() {
args.push(("suggestions", DiagArg::List(suggestions)));
}
args
}
pub(super) fn bindable(t: &Ty) -> bool {
match t {
Ty::Int | Ty::Float | Ty::Bool | Ty::Str | Ty::Identity | Ty::Struct(_) | Ty::Enum(_) => {
true
}
Ty::List(i) | Ty::Option(i) => bindable(i),
Ty::Map(k, v) => bindable(k) && bindable(v),
_ => false,
}
}
pub(super) fn numeric_ok(t: &Ty, int_only: bool) -> bool {
match t {
Ty::Int => true,
Ty::Float => !int_only,
_ => false,
}
}