use quote::ToTokens;
use crate::apply::{Apply, check_expand_limit, err_ty};
use crate::parse::parse_primitive;
use crate::types::*;
pub(crate) fn map_range(
start: usize, end: usize, inclusive: bool, f: impl Fn(usize) -> Ty,
) -> Ty {
let end_mark = if inclusive { "=" } else { "" };
let ns: Vec<_> =
if inclusive { (start..=end).collect() } else { (start..end).collect() };
if ns.is_empty() {
return err_ty(&format!(
"batch-impl: 范围 `{}..{}{}` 为空(起始不小于结束),不会生成任何 impl",
start, end, end_mark
));
}
if let Some(e) = check_expand_limit(
&format!("范围 `{}..{}{}`", start, end, end_mark),
ns.len(),
) {
return e;
}
TyArray(ns.into_iter().map(f).collect()).into()
}
fn tuple_pow(mut elems: Vec<Ty>, n: usize) -> Ty {
if let Some(e) = check_expand_limit(&format!("元组 `^{}`", n), n) {
return e;
}
match elems.len() {
0 => pow_empty(n),
1 => pow_single(elems.remove(0), n),
_ => pow_cartesian(elems, n),
}
}
fn pow_empty(n: usize) -> Ty {
if n == 0 {
return TyTuple(vec![]).into();
}
let params = fresh_params(n);
let param_names = params.iter().map(|p| p.to_token_stream()).collect::<Vec<_>>();
TyTypeParam {
params: param_names.into_iter().map(|n| (n, None)).collect(),
bindings: vec![],
}
.apply(TyTuple(params).into())
}
fn pow_single(template: Ty, n: usize) -> Ty {
if let Ty::TypeParam(tp) = template {
if tp.params.len() != 1 || tp.params[0].1.is_some() {
return err_ty(
"batch-impl: (<Trait>)⁁ 中意外收到了 bound 参数,这是内部错误",
);
}
let params = fresh_params(n);
let param_names =
params.iter().map(|p| p.to_token_stream()).collect::<Vec<_>>();
let bound_tokens = tp.params[0].0.clone().into_iter().collect::<Vec<_>>();
return TyTypeParam {
params: param_names
.into_iter()
.map(|n| (n, parse_primitive(&bound_tokens, None).into()))
.collect(),
bindings: vec![],
}
.apply(TyTuple(params).into());
}
TyTuple((0..n).map(|_| template.clone()).collect()).into()
}
fn pow_cartesian(elems: Vec<Ty>, n: usize) -> Ty {
let mut combos = vec![vec![]];
for _ in 0..n {
let mut next = vec![];
for existing in &combos {
for elem in &elems {
let mut extended = existing.clone();
extended.push(elem.clone());
next.push(extended);
}
}
if let Some(e) = check_expand_limit("元组笛卡尔积", next.len()) {
return e;
}
combos = next;
}
TyArray(combos.into_iter().map(instantiate_combo).collect()).into()
}
fn instantiate_combo(elems: Vec<Ty>) -> Ty {
let mut tuple_elems = vec![];
let mut param_decls = vec![];
for elem in elems {
match elem {
Ty::TypeParam(tp) => {
let name = fresh_param();
let params = tp
.params
.iter()
.map(|(_, bound)| (name.clone(), bound.clone()))
.collect();
param_decls.push(TyTypeParam { params, bindings: vec![] });
tuple_elems.push(TyPrimitive(name).into());
}
_ => tuple_elems.push(elem),
}
}
let tuple = TyTuple(tuple_elems).into();
if param_decls.is_empty() {
return tuple;
}
let mut merged = TyTypeParam { params: vec![], bindings: vec![] };
for tp in param_decls {
merged.extend(tp);
}
merged.apply(tuple)
}
fn fresh_params(n: usize) -> Vec<Ty> {
(0..n).map(|_| TyPrimitive(fresh_param()).into()).collect()
}
impl Apply for TyTuple {
fn apply_help(mut self, o: Ty) -> Ty {
match o {
Ty::Num(TyNum(n)) => tuple_pow(self.0, n),
_ => {
self.0.push(o);
self.into()
}
}
}
}
impl Apply for TyGroup {
fn apply_help(self, o: Ty) -> Ty {
match o {
Ty::Num(TyNum(n)) => tuple_pow(vec![*self.0], n),
_ => self.0.apply(o),
}
}
}
impl Apply for TyFn {
fn apply_help(self, o: Ty) -> Ty {
match self {
TyFn(None, None, is_unsafe) => match o {
Ty::Tuple(t) => TyFn(t.0.into(), None, is_unsafe).into(),
_ => err_ty(
"batch-impl: `fn` 前缀右侧必须是元组类型,如 fn^(i32, u32)",
),
},
TyFn(Some(params), None, is_unsafe) => {
TyFn(params.into(), o.into(), is_unsafe).into()
}
TyFn(Some(_), Some(_), _) => {
err_ty("batch-impl: `fn` 类型已有返回类型,不能重复应用")
}
TyFn(None, Some(_), _) => {
err_ty("batch-impl: `fn` 类型缺少参数列表,内部错误")
}
}
}
}
impl Apply for TyWithCode {
fn apply_help(self, o: Ty) -> Ty {
let inner = match self.0 {
Some(t) => t.apply(o),
None => o,
};
TyWithCode(inner.into(), self.1).into()
}
}
impl Apply for TyWithAttr {
fn apply_help(self, o: Ty) -> Ty {
TyWithAttr(self.0, o.into()).into()
}
}
impl Apply for TyTypeParam {
fn apply_help(self, o: Ty) -> Ty {
TyWithType(self, o.into()).into()
}
}
impl Apply for TyNum {
fn apply_help(self, _: Ty) -> Ty {
err_ty(&format!(
"batch-impl: 数字 `{}` 不能作为左侧操作数,只能出现在右侧(如 T^{})",
self.0, self.0
))
}
}
impl Apply for TyRange {
fn apply_help(self, _: Ty) -> Ty {
let end_mark = if self.inclusive { "=" } else { "" };
err_ty(&format!(
"batch-impl: 范围 `{}..{}{}` 不能作为左侧操作数,只能出现在右侧(如 T^{}..{}{})",
self.start, self.end, end_mark, self.start, self.end, end_mark
))
}
}
impl Apply for TyPrimitiveArray {
fn apply_help(self, o: Ty) -> Ty {
match (self.0, self.1) {
(None, None) => TyPrimitiveArray(o.into(), None).into(),
(Some(elem), None) => {
TyPrimitiveArray(elem.into(), o.to_token_stream().into()).into()
}
_ => err_ty("batch-impl: 定长数组 `[T; N]` 不能作为左侧操作数"),
}
}
}
impl Apply for TyWithTrait {
fn apply_help(self, o: Ty) -> Ty {
TyWithTrait(self.0, self.1.apply(o).into()).into()
}
}
impl Apply for TyWithType {
fn apply_help(self, o: Ty) -> Ty {
TyWithType(self.0, self.1.apply(o).into()).into()
}
}
impl Apply for TyWithWhere {
fn apply_help(self, o: Ty) -> Ty {
let inner = match self.0 {
Some(t) => t.apply(o),
None => o,
};
TyWithWhere(inner.into(), self.1).into()
}
}