use super::expressions::{operand, string};
use super::types::{Environment, Ty, union};
use super::{Placeholder, Run, Signature};
use crate::ast::{CallArgs, Expr, ExprKind, Literal};
use crate::shape::TypeDesc;
use crate::span::Span;
use std::collections::BTreeSet;
struct Builtin {
required: usize,
parameters: Vec<Ty>,
variadic: Option<Ty>,
returns: Ty,
}
impl Builtin {
fn new(required: usize, parameters: Vec<Ty>, returns: Ty) -> Self {
Self {
required,
parameters,
variadic: None,
returns,
}
}
fn with_rest(mut self, parameter: Ty) -> Self {
self.variadic = Some(parameter);
self
}
}
fn number() -> Ty {
Ty::Union(vec![Ty::Int, Ty::Float])
}
fn keys() -> Ty {
Ty::Union(vec![Ty::String, Ty::list(Ty::String)])
}
fn attribute_keys() -> Ty {
Ty::Union(vec![
Ty::String,
Ty::list(Ty::String),
Ty::map(Ty::String, Ty::String),
])
}
fn list_or_map() -> Ty {
Ty::Union(vec![Ty::list(Ty::Any), Ty::map(Ty::String, Ty::Any)])
}
fn helper(name: &str) -> Option<Builtin> {
use Ty::*;
let a = Builtin::new;
if let Some(method) = name.strip_prefix("str::") {
let text_or_list = || Union(vec![String, Ty::list(String)]);
return Some(match method {
"replace" => a(
3,
vec![text_or_list(), text_or_list(), String, Bool],
String,
),
"replace_first" | "replace_last" | "replace_start" | "replace_end" => {
a(3, vec![String, String, String], String)
}
"replace_array" => a(3, vec![String, Ty::list(String.optional()), String], String),
"remove" => a(2, vec![keys(), String, Bool], String),
"swap" => a(2, vec![Ty::map(String, String), String], String),
"substr_replace" | "substr_replace_values" => a(2, vec![Any, Any, Any, Any], Any),
"replace_matches" => a(3, vec![keys(), Any, String, Int], String),
"match" | "match_first" => a(2, vec![String, String], String),
"match_all" => a(2, vec![String, String], Ty::list(String)),
"is_match" => a(2, vec![keys(), String], Bool),
"is" => a(2, vec![keys(), String, Bool], Bool),
"parse_callback" => a(
1,
vec![String, String.optional()],
Tuple(vec![String, String.optional()]),
),
"random" => a(0, vec![Int], String),
"password" => a(0, vec![Int, Bool, Bool, Bool, Bool], String),
"uuid" | "ordered_uuid" => a(0, vec![], String),
"uuid7" | "ulid" => a(0, vec![Date.optional()], String),
_ => {
let mut signature = string_method(method)?;
signature.required += 1;
signature.parameters.insert(0, String);
signature
}
});
}
if let Some(method) = name.strip_prefix("number::") {
return Some(match method {
"parse" | "parse_with" => a(1, vec![String, Int, Int], Union(vec![Int, Float, Bool])),
"parse_int" => a(1, vec![String], Union(vec![Int, Bool])),
"parse_float" => a(1, vec![String], Union(vec![Float, Bool])),
"trim" => a(1, vec![number()], number()),
"clamp" => a(3, vec![number(), number(), number()], number()),
"pairs" | "pairs_with" => a(
2,
vec![number(), number(), number(), number()],
Ty::list(Ty::list(number())),
),
_ => {
let mut signature = number_method(method)?;
signature.required += 1;
signature.parameters.insert(0, number());
signature
}
});
}
Some(match name {
"filled" | "blank" | "empty" => a(1, vec![Any], Bool),
"route" => a(1, vec![String, Any, Bool], String),
"url" | "asset" => a(1, vec![String], String),
"vendor_asset" => a(2, vec![String, String], String),
"vite" => a(1, vec![keys()], Html).with_rest(String),
"csrf_field" | "head" | "vite_react_refresh" => a(0, vec![], Html),
"csrf_token" | "csp_nonce" => a(0, vec![], String),
"route_is" | "feature" => a(1, vec![String], Bool),
"old" => a(1, vec![String, Any], Any),
"session" | "config" => a(1, vec![String], Any),
"error" => a(1, vec![String, String], String.optional()),
"date" => a(1, vec![Union(vec![String, Date])], Date),
"now" => a(0, vec![], Date),
"json" | "js" => a(1, vec![Any, Any, Int], Html),
"e" | "nl2br" => a(1, vec![String], Html),
"number_format" | "php::number_format" | "php::number_format_with" => a(
1,
vec![number(), Int, String.optional(), String.optional()],
String,
),
"round" | "php::round" => a(1, vec![number(), Int], Float),
"__" | "trans" => a(
1,
vec![String, Ty::map(String, Any), String.optional()],
String,
),
"trans_choice" => a(
2,
vec![String, number(), Ty::map(String, Any), String.optional()],
String,
),
"php::echo" | "php::strval" => a(1, vec![Any], String),
"php::boolval" => a(1, vec![Any], Bool),
"php::intval" => a(1, vec![Any], Int),
"php::floatval" => a(1, vec![Any], Float),
"php::loose_eq" => a(2, vec![Any, Any], Bool),
"php::sprintf" | "sprintf" => a(1, vec![String], String).with_rest(Any),
"php::sprintf_bytes" => a(1, vec![String], Ty::list(Int)).with_rest(Any),
"php::json_encode" => a(1, vec![Any, Any], String),
"php::ucfirst" | "php::lcfirst" | "php::strtolower" | "php::strtoupper" => {
a(1, vec![String], String)
}
"php::ucwords" | "php::ucwords_with" => a(1, vec![String, String], String),
"php::array_filter" => a(1, vec![Any, Any], Any),
"php::array_values" => a(1, vec![Any], Ty::list(Any)),
"php::addslashes" | "php::stripslashes" | "php::quotemeta" | "php::strrev"
| "php::bin2hex" | "php::urlencode" | "php::urldecode" | "php::rawurlencode"
| "php::rawurldecode" | "php::base64_encode" | "php::mb_strtoupper"
| "php::mb_strtolower" => a(1, vec![String], String),
"php::base64_decode" => a(1, vec![String, Bool], Union(vec![String, Bool])),
"php::nl2br" => a(1, vec![String, Bool], String),
"php::e" => a(1, vec![Any, Bool], String),
"php::str_pad" | "php::mb_str_pad" => a(2, vec![String, Int, String, Int], String),
"php::wordwrap" => a(1, vec![String, Int, String, Bool], String),
"php::str_repeat" => a(2, vec![String, Int], String),
"php::trim" | "php::ltrim" | "php::rtrim" => a(1, vec![String, String.optional()], String),
"php::strlen" => a(1, vec![Any], Int),
"php::mb_strlen" => a(1, vec![String, String.optional()], Int),
"php::mb_strwidth" | "php::crc32" => a(1, vec![String], Int),
"php::str_word_count" => a(
1,
vec![
String,
Union(vec![Int, String]).optional(),
String.optional(),
],
Int,
),
"php::mb_strpos" => a(
2,
vec![String, String, Int, String.optional()],
Union(vec![Int, Bool]),
),
"php::substr_count" => a(2, vec![String, String, Int, Int.optional()], Int),
"php::substr" | "php::mb_substr" => a(2, vec![String, Int, Int.optional()], String),
"php::mb_strimwidth" => a(3, vec![String, Int, Int, String], String),
"php::mb_str_split" => a(1, vec![String, Int], Ty::list(String)),
"php::explode" => a(2, vec![String, String, Int], Ty::list(String)),
"php::implode" => a(1, vec![Any, Any], String),
"php::http_build_query" => a(1, vec![Any, String, String.optional(), Int], String),
"php::strtr" => a(2, vec![String, Any], String),
"php::str_replace" | "php::str_ireplace" => a(3, vec![Any, Any, Any], Any),
"php::strip_tags" => a(1, vec![String, keys().optional()], String),
"php::htmlspecialchars" | "php::htmlentities" => a(
1,
vec![String, Int, Union(vec![String, Bool]).optional(), Bool],
String,
),
"php::htmlspecialchars_decode" => a(1, vec![String, Int], String),
"php::html_entity_decode" => a(1, vec![String, Int, String.optional()], String),
_ => return None,
})
}
fn string_method(name: &str) -> Option<Builtin> {
use Ty::*;
let a = Builtin::new;
Some(match name {
"len" => a(0, vec![], Int),
"length" => a(0, vec![String.optional()], Int),
"word_count" => a(0, vec![String], Int),
"is_empty" | "is_not_empty" | "is_ascii" => a(0, vec![], Bool),
"starts_with" | "ends_with" | "doesnt_start_with" | "doesnt_end_with" => {
a(1, vec![keys()], Bool)
}
"contains" | "contains_any" | "doesnt_contain" | "is" => a(1, vec![keys(), Bool], Bool),
"contains_all" => a(1, vec![Ty::list(String), Bool], Bool),
"is_json" | "is_ulid" => a(0, vec![], Bool),
"is_url" => a(0, vec![Ty::list(String).optional()], Bool),
"is_uuid" => a(0, vec![Union(vec![String, Int]).optional()], Bool),
"to_ascii_uppercase" | "to_ascii_lowercase" | "to_lowercase" | "to_uppercase" | "upper"
| "lower" | "title" | "headline" | "ucfirst" | "lcfirst" | "camel" | "kebab" | "studly"
| "pascal" | "apa" | "squish" | "numbers" | "reverse" | "singular" | "pluralize"
| "to_string" => a(0, vec![], String),
"trim" | "ltrim" | "rtrim" | "ucwords" | "snake" | "ascii" | "deduplicate"
| "transliterate" => a(0, vec![String], String),
"after" | "after_last" | "before" | "before_last" | "start" | "finish" => {
a(1, vec![String], String)
}
"chop_start" | "chop_end" => a(1, vec![keys()], String),
"replace" => a(2, vec![keys(), keys(), Bool], String),
"replace_first" | "replace_last" | "replace_start" | "replace_end" | "between"
| "between_first" => a(2, vec![String, String], String),
"wrap" | "unwrap" => a(1, vec![String, String.optional()], String),
"replace_array" => a(2, vec![String, Ty::list(String)], String),
"swap" => a(1, vec![Ty::map(String, String)], String),
"remove" => a(1, vec![keys(), Bool], String),
"append" | "prepend" => a(0, vec![], String).with_rest(Union(vec![String, Int, Float])),
"limit" => a(0, vec![Int, String, Bool], String),
"words" => a(0, vec![Int, String], String),
"plural" | "plural_studly" | "plural_pascal" => a(0, vec![number()], String),
"plural_with_count" => a(1, vec![number()], String),
"slug" => a(0, vec![String, String, Ty::map(String, String)], String),
"mask" => a(2, vec![String, Int, Int], String),
"pad_left" | "pad_right" | "pad_both" => a(1, vec![Int, String], String),
"substr" => a(1, vec![Int, Int.optional(), String.optional()], String),
"substr_replace" => a(1, vec![keys(), Int, Int.optional()], String),
"substr_count" => a(1, vec![String, Int, Int.optional()], Int),
"char_at" => a(1, vec![Int], Union(vec![String, Bool])),
"take" => a(1, vec![Int], String),
"position" => a(
1,
vec![String, Int, String.optional()],
Union(vec![Int, Bool]),
),
"counted" => a(1, vec![number()], String),
"excerpt" => a(0, vec![String, Ty::map(String, Any)], String.optional()),
"is_match" => a(1, vec![keys()], Bool),
"match" | "match_first" => a(1, vec![String], String),
"match_all" => a(1, vec![String], Ty::list(String)),
"replace_matches" => a(2, vec![keys(), Any, Int], String),
"repeat" => a(1, vec![Int], String),
"word_wrap" => a(0, vec![Int, String, Bool], String),
"split" => a(1, vec![String], Ty::list(String)),
"explode" => a(1, vec![String, Int], Ty::list(String)),
"ucsplit" => a(0, vec![], Ty::list(String)),
"split_once" => a(1, vec![String], Tuple(vec![String, String]).optional()),
"markdown" | "inline_markdown" => a(0, vec![Any], String),
"cmp" => a(1, vec![String], Int),
_ => return None,
})
}
fn number_method(name: &str) -> Option<Builtin> {
use Ty::*;
let a = Builtin::new;
Some(match name {
"format" | "format_with" | "percentage" | "percentage_with" => {
a(0, vec![Int.optional(), Int.optional(), String, Int], String)
}
"file_size" | "file_size_with" | "abbreviate" | "abbreviate_with" => {
a(0, vec![Int.optional(), Int.optional()], String)
}
"for_humans" | "for_humans_with" => {
a(0, vec![Int.optional(), Int.optional(), Bool], String)
}
"currency" | "currency_with" => a(
0,
vec![String.optional(), Int.optional(), Int.optional(), String],
Union(vec![String, Bool]),
),
"ordinal" | "spell_ordinal" => a(0, vec![String, Int], String),
"spell" | "spell_with" => a(0, vec![Int.optional(), Int.optional(), String, Int], String),
_ => return None,
})
}
fn fixed_method(receiver: &Ty, name: &str) -> Option<Builtin> {
use Ty::*;
let a = Builtin::new;
if name == "to_string" && printable(receiver) {
return Some(a(0, vec![], String));
}
if matches!(name, "is_some" | "is_none") {
return Some(a(0, vec![], Bool));
}
if name == "unwrap_or" {
return match receiver {
Option(inner) => Some(a(1, vec![*inner.clone()], *inner.clone())),
Null => Some(a(1, vec![Any], Any)),
_ => Some(a(1, vec![receiver.clone()], receiver.clone())),
};
}
Some(match receiver {
String | Html => return string_method(name),
Int | Float => match name {
"abs" | "floor" | "ceil" => a(0, vec![], receiver.clone()),
"round" => a(0, vec![Int], receiver.clone()),
"min" | "max" | "pow" => a(1, vec![receiver.clone()], receiver.clone()),
"clamp" => a(
2,
vec![receiver.clone(), receiver.clone()],
receiver.clone(),
),
"cmp" => a(1, vec![receiver.clone()], Int),
_ => return number_method(name),
},
Range => match name {
"rev" => a(0, vec![], Range),
"step_by" => a(1, vec![Int], Range),
_ => return None,
},
Date => match name {
"format" => a(1, vec![String], String),
"translated_format" | "iso_format" => a(1, vec![String, String.optional()], String),
"calendar" | "diff_for_humans" => {
a(0, vec![Date.optional(), String.optional()], String)
}
"locale" => a(0, vec![String], Date),
"to_date_string"
| "to_time_string"
| "to_date_time_string"
| "to_datetime_string"
| "to_iso_string"
| "to_iso8601_string" => a(0, vec![], String),
"is_past" | "is_future" | "is_today" => a(0, vec![], Bool),
"year" | "month" | "day" | "hour" | "minute" | "second" => a(0, vec![], Int),
"add_day"
| "add_days"
| "sub_day"
| "sub_days"
| "add_month"
| "add_months"
| "sub_month"
| "sub_months"
| "add_year"
| "add_years"
| "sub_year"
| "sub_years"
| "add_hour"
| "add_hours"
| "sub_hour"
| "sub_hours"
| "add_week"
| "add_weeks"
| "sub_week"
| "sub_weeks"
| "add_month_no_overflow"
| "add_months_no_overflow"
| "sub_month_no_overflow"
| "sub_months_no_overflow" => a(0, vec![number()], Date),
"start_of_month" | "end_of_month" | "start_of_day" | "end_of_day"
| "start_of_quarter" | "end_of_quarter" | "start_of_year" | "end_of_year" | "copy" => {
a(0, vec![], Date)
}
"start_of_week" | "end_of_week" => a(0, vec![Int.optional()], Date),
"add_span" | "sub_span" | "set_timezone" => a(1, vec![String], Date),
"between" => a(2, vec![Date, Date, Bool], Bool),
"between_included" | "between_excluded" => a(2, vec![Date, Date], Bool),
"eq" | "ne" | "gt" | "gte" | "lt" | "lte" => a(1, vec![Date], Bool),
"diff_in_days" | "diff_in_hours" | "diff_in_minutes" | "diff_in_seconds"
| "diff_in_weeks" | "diff_in_months" | "diff_in_years" => {
a(0, vec![Date.optional(), Bool, Bool], Float)
}
_ => return None,
},
Slot => match name {
"is_empty" | "is_not_empty" => a(0, vec![], Bool),
"to_html" => a(0, vec![], Html),
_ => return string_method(name),
},
Attributes => match name {
"class" | "style" => a(1, vec![Union(vec![String, list_or_map()])], Attributes),
"merge" => a(0, vec![list_or_map(), Bool], Attributes),
"set_attributes" => a(1, vec![Union(vec![Attributes, list_or_map()])], Attributes),
"offset_set" => a(2, vec![String, Any], Attributes),
"offset_unset" => a(1, vec![String], Attributes),
"offset_get" => a(1, vec![String], Any),
"offset_exists" => a(1, vec![String], Bool),
"all" => a(0, vec![attribute_keys().optional()], Ty::map(String, Any)),
"get_attributes" | "to_array" | "json_serialize" | "get_iterator" => {
a(0, vec![], Ty::map(String, Any))
}
"only" | "except" => a(1, vec![attribute_keys().optional()], Attributes),
"only_props" | "except_props" => a(
1,
vec![Union(vec![keys(), Ty::map(String, Any)])],
Attributes,
),
"where_starts_with" | "where_doesnt_start_with" | "that_start_with" => {
a(1, vec![attribute_keys()], Attributes)
}
"get" => a(1, vec![String, Any], Any),
"first" => a(0, vec![Any], Any),
"has" | "has_any" | "missing" => a(1, vec![attribute_keys()], Bool),
"is_empty" | "is_not_empty" => a(0, vec![], Bool),
"prepends" => a(1, vec![Any], Any),
"to_html" => a(0, vec![], Html),
_ => return None,
},
Errors => match name {
"has" => a(1, vec![keys()], Bool),
"first" => a(0, vec![String, String], String),
"get" => a(1, vec![String, String], Ty::list(String)),
"all" => a(0, vec![String], Ty::list(String)),
"any" | "is_empty" => a(0, vec![], Bool),
"bag" => a(1, vec![String], Errors),
_ => return None,
},
Paginator(item) => match name {
"per_page" | "count" | "len" => a(0, vec![], Int),
"total" | "last_page" | "current_page" | "first_item" | "last_item" => {
a(0, vec![], Int.optional())
}
"has_pages" | "has_more_pages" | "on_first_page" | "on_last_page" | "is_empty"
| "is_not_empty" => a(0, vec![], Bool),
"links" => a(0, vec![String, Ty::map(String, Any)], Html),
"url" => a(1, vec![Int], String.optional()),
"next_page_url" | "previous_page_url" => a(0, vec![], String.optional()),
"get_url_range" => a(2, vec![Int, Int], PageUrls.optional()),
"appends" => a(
1,
vec![
Union(vec![String, Ty::list(Any), Ty::map(Any, Any)]).optional(),
Any,
],
receiver.clone(),
),
"fragment" => a(0, vec![String.optional()], String.optional()),
"on_each_side" => a(1, vec![Int], receiver.clone()),
"items" => a(0, vec![], Ty::list(*item.clone())),
_ => return None,
},
PageUrls => match name {
"len" => a(0, vec![], Int),
"get" => a(1, vec![Int, Any], String.optional()),
"contains_key" => a(1, vec![Int], Bool),
"is_empty" | "is_not_empty" => a(0, vec![], Bool),
"keys" => a(0, vec![], Ty::list(Int)),
"values" => a(0, vec![], Ty::list(String)),
_ => return None,
},
Union(_) => {
let (key, item) = receiver.list_or_map()?;
match name {
"len" => a(0, vec![], Int),
"is_empty" | "is_not_empty" => a(0, vec![], Bool),
"keys" => a(0, vec![], Ty::list(key)),
"values" => a(0, vec![], Ty::list(item)),
_ => return None,
}
}
_ => return None,
})
}
pub(super) fn printable(ty: &Ty) -> bool {
match ty {
Ty::Option(inner) => printable(inner),
Ty::Union(types) => types.iter().all(printable),
Ty::Nominal(TypeDesc::Display { .. }, _)
| Ty::String
| Ty::Text
| Ty::Html
| Ty::Date
| Ty::Slot
| Ty::Attributes
| Ty::Int
| Ty::Float
| Ty::Bool
| Ty::Null => true,
ty => ty.unknown(),
}
}
struct Collection {
key: Ty,
item: Ty,
keyed: bool,
}
impl Collection {
fn preserving(&self, item: Ty) -> Ty {
if self.keyed {
Ty::map(self.key.clone(), item)
} else {
Ty::list(item)
}
}
}
impl Run<'_, '_> {
pub(super) fn check_signature(
&mut self,
name: &str,
signature: &Signature,
args: &[Expr],
span: Span,
env: &mut Environment,
) -> Ty {
let parameters: Vec<_> = signature.parameters.iter().cloned().map(Ty::from).collect();
let required = parameters
.iter()
.rposition(|ty| !matches!(self.resolve(ty), Ty::Option(_)))
.map_or(0, |i| i + 1);
let sig = Builtin {
required,
parameters,
variadic: signature.variadic.clone().map(Ty::from),
returns: Ty::from(signature.returns.clone()),
};
let actual = self.arguments(args, env);
self.apply(name, sig, args, &actual, span)
}
fn arguments(&mut self, args: &[Expr], env: &mut Environment) -> Vec<Ty> {
args.iter()
.map(|arg| self.expr(operand(arg), env))
.collect()
}
fn apply(
&mut self,
name: &str,
signature: Builtin,
args: &[Expr],
actual: &[Ty],
span: Span,
) -> Ty {
let max = signature
.variadic
.is_none()
.then_some(signature.parameters.len());
self.arity(name, args.len(), signature.required, max, span);
for (index, (arg, ty)) in args.iter().zip(actual).enumerate() {
if let Some(expected) = signature
.parameters
.get(index)
.or(signature.variadic.as_ref())
{
self.require(ty, expected, arg.span, "argument-type");
}
}
signature.returns
}
pub(super) fn arity(
&mut self,
name: &str,
actual: usize,
min: usize,
max: Option<usize>,
span: Span,
) {
if actual < min || max.is_some_and(|max| actual > max) {
let count = match max {
Some(max) if min == max => format!("{min}"),
Some(max) => format!("{min} to {max}"),
None => format!("at least {min}"),
};
self.error(
"argument-count",
span,
format!("`{name}` expects {count} arguments, received {actual}"),
);
}
}
pub(super) fn call(
&mut self,
callee: &Expr,
args: &CallArgs,
span: Span,
env: &mut Environment,
) -> Ty {
let ExprKind::Path(path) = &callee.kind else {
let bound = self.expr(callee, env);
return self.call_value(bound, &args.values, span, env);
};
let name = path.join("::");
if env.bindings.contains_key(&name) {
let bound = self.expr(callee, env);
return self.call_value(bound, &args.values, span, env);
}
if name.starts_with("php::") && !self.report.php_calls.iter().any(|(at, _)| *at == span) {
self.report.php_calls.push((span, name.clone()));
}
let values = &args.values;
match name.as_str() {
"isset" | "empty" => {
self.arity(&name, values.len(), 1, Some(1), span);
for arg in values {
self.guarded(operand(arg), env);
}
return Ty::Bool;
}
"Some" => {
self.arity(&name, values.len(), 1, Some(1), span);
return self
.arguments(values, env)
.into_iter()
.next()
.unwrap_or(Ty::Error)
.optional();
}
"format" => return self.format(values, span, env),
"todo" => {
self.arguments(values, env);
self.error("migration-todo", span, "unresolved migration TODO");
return Ty::Error;
}
"php::array_filter" | "php::array_values" => {
let max = if name == "php::array_filter" { 2 } else { 1 };
self.arity(&name, values.len(), 1, Some(max), span);
let Some(arg) = values.first() else {
return Ty::Error;
};
let input = self.expr(arg, env);
let (key, item) = self.iterable(&input, arg.span);
if let Some(callback) = values.get(1) {
let result = self.closure(callback, &[item.clone(), key.clone()], env);
self.require(&result, &Ty::Bool, callback.span, "closure-result");
}
for extra in values.iter().skip(2) {
self.expr(extra, env);
}
return if max == 1 {
Ty::list(item)
} else {
Ty::map(key, item)
};
}
_ => {}
}
let registration = env
.helpers
.get(&name)
.or_else(|| self.config.helpers.get(&name))
.cloned();
if let Some(signature) = ®istration
&& name != "route"
{
return self.check_signature(&name, signature, values, span, env);
}
let actual = self.arguments(values, env);
if name == "route" {
self.route(values, &actual, span);
}
if name == "old"
&& let Some(default) = actual.get(1)
{
if let Some(sig) = helper("old") {
self.apply(&name, sig, values, &actual, span);
}
self.unchecked(
"old-input",
span,
"old input is supplied by the request at runtime",
);
return default.clone();
}
if let Some(sig) = helper(&name) {
return self.apply(&name, sig, values, &actual, span);
}
self.error(
"unknown-helper",
callee.span,
format!("unknown helper `{name}`"),
);
Ty::Error
}
fn call_value(&mut self, bound: Ty, args: &[Expr], span: Span, env: &mut Environment) -> Ty {
let actual = self.arguments(args, env);
match bound {
Ty::Attributes => self.apply(
"attribute bag",
Builtin::new(0, vec![list_or_map()], Ty::Html),
args,
&actual,
span,
),
Ty::Closure(params, result) => {
let required = params.len();
self.apply(
"closure",
Builtin::new(required, params, *result),
args,
&actual,
span,
)
}
other if other.unknown() => other,
other => {
self.error(
"not-callable",
span,
format!("{} cannot be called", other.label()),
);
Ty::Error
}
}
}
pub(super) fn method(
&mut self,
receiver: &Expr,
ty: &Ty,
name: &str,
args: &CallArgs,
span: Span,
env: &mut Environment,
) -> Ty {
let values = &args.values;
let registered = match ty {
Ty::Nominal(TypeDesc::Ref(id), _) => {
self.config.methods.get(&(id.to_string(), name.to_owned()))
}
Ty::Service(id) => self.config.methods.get(&(id.clone(), name.to_owned())),
_ => None,
};
if let Some(sig) = registered {
return self.check_signature(name, sig, values, span, env);
}
let resolved = self.resolve(ty);
if resolved == Ty::Any {
self.arguments(values, env);
self.unchecked(
"any-method",
span,
format!("method `{name}` is resolved at runtime"),
);
return Ty::Any;
}
if resolved.unknown() {
self.arguments(values, env);
return resolved;
}
if resolved == Ty::String && name == "parse" {
self.arguments(values, env);
self.arity(name, values.len(), 0, Some(0), span);
if let [annotation] = args.types.as_slice()
&& matches!(annotation.as_str(), "i64" | "f64")
{
return if annotation == "i64" {
Ty::Int.optional()
} else {
Ty::Float.optional()
};
}
self.error(
"parse-type",
span,
"`parse` needs one supported type argument",
);
return Ty::Error;
}
if !args.types.is_empty() {
self.error(
"unexpected-type-arguments",
span,
format!("`{name}` does not accept type arguments"),
);
}
if resolved == Ty::Slot && name == "has_actual_content" {
self.arity(name, values.len(), 0, Some(1), span);
if let Some(callback) = values.first() {
self.attribute_callback(callback, &[Ty::String], env);
}
for extra in values.iter().skip(1) {
self.expr(extra, env);
}
return Ty::Bool;
}
if resolved == Ty::Attributes && matches!(name, "when" | "unless") {
self.arity(name, values.len(), 2, Some(3), span);
if let Some(condition) = values.first() {
let actual = if matches!(condition.kind, ExprKind::Closure { .. }) {
self.attribute_callback(condition, &[Ty::Attributes], env)
} else {
match self.expr(condition, env) {
Ty::Closure(params, result) => {
self.arity(name, params.len(), 0, Some(1), condition.span);
if let Some(expected) = params.first() {
self.require(
&Ty::Attributes,
expected,
condition.span,
"closure-parameter",
);
}
*result
}
value => value,
}
};
self.require(&actual, &Ty::Bool, condition.span, "argument-type");
}
let mut returns = vec![Ty::Attributes];
for callback in values.iter().skip(1).take(2) {
let returned = self.attribute_callback(callback, &[Ty::Attributes, Ty::Bool], env);
if !matches!(returned, Ty::Null | Ty::Attributes) && !returns.contains(&returned) {
returns.push(returned);
}
}
for extra in values.iter().skip(3) {
self.expr(extra, env);
}
return if returns.len() == 1 {
Ty::Attributes
} else {
Ty::Union(returns)
};
}
if resolved == Ty::Attributes && name == "filter" {
self.arity(name, values.len(), 1, Some(1), span);
if let Some(callback) = values.first() {
let result = self.attribute_callback(callback, &[Ty::Any, Ty::String], env);
self.require(&result, &Ty::Bool, callback.span, "closure-result");
}
for extra in values.iter().skip(1) {
self.expr(extra, env);
}
return Ty::Attributes;
}
if let Some(mut sig) = fixed_method(&resolved, name) {
let actual = self.arguments(values, env);
if resolved == Ty::Date && name == "locale" && values.is_empty() {
sig.returns = Ty::String;
}
if resolved == Ty::PageUrls
&& name == "get"
&& let Some(default) = actual.get(1)
{
sig.returns = if self.potentially_missing(default) {
union(Ty::String, self.present_type(default.clone())).optional()
} else {
union(Ty::String, default.clone())
};
}
if matches!(resolved, Ty::Paginator(_)) && name == "fragment" {
sig.returns = match actual.first().map(|value| self.resolve(value)) {
None | Some(Ty::Null) => sig.returns,
Some(Ty::String) => resolved.clone(),
_ => union(sig.returns, resolved.clone()),
};
}
if resolved == Ty::Null && name == "unwrap_or" {
self.apply(name, sig, values, &actual, span);
return actual.into_iter().next().unwrap_or(Ty::Error);
}
return self.apply(name, sig, values, &actual, span);
}
if matches!(
resolved,
Ty::List(..) | Ty::ListLiteral(_) | Ty::Map(..) | Ty::Record(_)
) {
let (key, item) = self.iterable(&resolved, receiver.span);
let keyed = matches!(resolved, Ty::Map(..) | Ty::Record(_));
let collection = Collection { key, item, keyed };
if matches!(name, "push" | "prepend" | "insert" | "retain" | "pop") {
return self.mutation(receiver, &collection, name, args, span, env);
}
if let Some(result) = self.collection(&collection, name, values, span, env) {
return result;
}
}
self.arguments(values, env);
self.error(
"unknown-method",
span,
format!("no method `{name}` on {}", self.type_name(ty)),
);
Ty::Error
}
fn attribute_callback(&mut self, expr: &Expr, arguments: &[Ty], env: &mut Environment) -> Ty {
match &expr.kind {
ExprKind::Closure { params, .. } if params.is_empty() => self.closure(expr, &[], env),
_ => self.closure(expr, arguments, env),
}
}
fn mutation(
&mut self,
receiver: &Expr,
collection: &Collection,
name: &str,
args: &CallArgs,
span: Span,
env: &mut Environment,
) -> Ty {
let root = self.mutable_target(receiver, env);
let values = &args.values;
let count = match name {
"insert" => 2,
"pop" => 0,
_ => 1,
};
self.arity(name, values.len(), count, Some(count), span);
let mut inferred = None;
for (index, arg) in values.iter().enumerate() {
if name == "retain" && index == 0 {
let result =
self.closure(arg, &[collection.item.clone(), collection.key.clone()], env);
self.require(&result, &Ty::Bool, arg.span, "closure-result");
} else {
let actual = self.expr(arg, env);
let expected = if name == "insert" && index == 0 {
&collection.key
} else {
&collection.item
};
self.require(&actual, expected, arg.span, "argument-type");
if *expected == Ty::Infer && matches!(receiver.kind, ExprKind::Path(_)) {
inferred = Some(collection.preserving(actual));
}
}
}
if let Some(root) = root {
env.write(&root, inferred);
}
if name == "pop" || name == "insert" && collection.keyed {
collection.item.clone().optional()
} else {
Ty::Null
}
}
fn collection(
&mut self,
collection: &Collection,
name: &str,
args: &[Expr],
span: Span,
env: &mut Environment,
) -> Option<Ty> {
use Ty::*;
let item = &collection.item;
let key = &collection.key;
let signature = collection_signature(name, args.len(), item, key)?;
let reduce_initial = matches!(name, "reduce" | "reduce_with_keys")
.then(|| args.get(1).map(|arg| self.expr(arg, env)).unwrap_or(Null));
self.arity(name, args.len(), signature.min, signature.max, span);
let mut outputs = Vec::new();
for (index, arg) in args.iter().enumerate() {
let parameter = signature.parameters.get(index).or(signature.rest.as_ref());
let parameter = if matches!(parameter, Some(Param::ItemOrPredicate))
&& matches!(&arg.kind, ExprKind::Closure { .. })
{
Some(&Param::Predicate)
} else {
parameter
};
let actual = match parameter {
Some(Param::Selector) => self.selector(arg, item, key, env),
Some(Param::Predicate) => {
let result = self.closure(arg, &[item.clone(), key.clone()], env);
self.require(&result, &Bool, arg.span, "closure-result");
result
}
Some(Param::ItemOrPredicate) => {
let actual = self.expr(arg, env);
self.require(&actual, item, arg.span, "argument-type");
actual
}
Some(Param::Mapper) => self.closure(arg, &[item.clone(), key.clone()], env),
Some(Param::SpreadMapper) => {
let mut parameters = match self.resolve(item) {
Ty::Tuple(items) | Ty::ListLiteral(items) => items,
Ty::List(element, Some(length)) if length <= 64 => vec![*element; length],
Ty::List(element, _) => {
self.unchecked(
"map-spread-length",
arg.span,
"the number of spread arguments depends on list length",
);
let length = if let ExprKind::Closure { params, .. } = &arg.kind {
params.len()
} else {
1
};
vec![*element; length]
}
other => {
self.error(
"map-spread-item",
arg.span,
format!("cannot spread {}", other.label()),
);
Vec::new()
}
};
parameters.push(key.clone());
self.closure(arg, ¶meters, env)
}
Some(Param::Comparator(expected)) => {
let result = self.closure(arg, &[expected.clone(), expected.clone()], env);
self.require(&result, &Int, arg.span, "closure-result");
result
}
Some(Param::Reducer) => {
let initial = reduce_initial.clone().unwrap_or(Null);
let result =
self.closure(arg, &[initial.clone(), item.clone(), key.clone()], env);
if initial != Null {
self.require(&result, &initial, arg.span, "closure-result");
}
result
}
Some(Param::WhereValue) => {
let actual = self.expr(arg, env);
if index == 1 && args.len() == 3 {
self.require(&actual, &String, arg.span, "argument-type");
} else if let Some(selected) = outputs.first() {
self.require(&actual, selected, arg.span, "argument-type");
}
actual
}
Some(Param::WhereList) => {
let actual = self.expr(arg, env);
if let Some(selected) = outputs.first() {
self.require(
&actual,
&Ty::list(selected.clone()),
arg.span,
"argument-type",
);
}
actual
}
Some(Param::Typed(expected)) => {
let actual = if index == 1
&& let Some(initial) = &reduce_initial
{
initial.clone()
} else {
self.expr(arg, env)
};
self.require(&actual, expected, arg.span, "argument-type");
actual
}
None => self.expr(arg, env),
};
outputs.push(actual);
}
let selected = outputs.first().unwrap_or(item).clone();
let preserved = collection.preserving(item.clone());
let result = match signature.output {
Output::Fixed(ty) => ty,
Output::Preserved => preserved,
Output::Map => collection.preserving(selected),
Output::Values => Ty::list(item.clone()),
Output::Groups | Output::Keyed => {
self.require(
&selected,
&Union(vec![String, Int]),
args.first().map_or(span, |a| a.span),
"collection-key",
);
let value = if matches!(signature.output, Output::Groups) {
Ty::list(item.clone())
} else {
item.clone()
};
Ty::map(String, value)
}
Output::Pluck => outputs.get(1).map_or_else(
|| Ty::list(selected.clone()),
|key| Ty::map(key.clone(), selected.clone()),
),
Output::First => {
self.unchecked(
"collection-element",
span,
"collection may have no matching element at runtime",
);
if matches!(name, "first" | "last") {
outputs.get(1).map_or_else(
|| item.clone(),
|default| union(item.clone(), default.clone()),
)
} else {
item.clone()
}
}
Output::Selected => selected,
Output::Chunk if name == "chunk" && collection.keyed => {
let part = match args.get(1).map(|arg| &operand(arg).kind) {
None | Some(ExprKind::Literal(Literal::Bool(true))) => preserved,
Some(ExprKind::Literal(Literal::Bool(false))) => Ty::list(item.clone()),
Some(_) => union(Ty::list(item.clone()), preserved),
};
Ty::list(part)
}
Output::Chunk => Ty::list(preserved),
Output::Partition => Tuple(vec![preserved.clone(), preserved]),
Output::Numeric | Output::Average => {
self.require(
&selected,
&number(),
args.first().map_or(span, |arg| arg.span),
"aggregate-type",
);
if matches!(signature.output, Output::Average) {
Float
} else {
selected
}
}
Output::Pairs | Output::Flat | Output::Buckets => {
let (mapped_key, mapped_item) =
self.iterable(&selected, args.first().map_or(span, |arg| arg.span));
match signature.output {
Output::Flat => collection.preserving(mapped_item),
Output::Buckets => Ty::map(mapped_key, Ty::list(mapped_item)),
_ => Ty::map(mapped_key, mapped_item),
}
}
Output::Flatten => {
let mut value = item.clone();
let mut seen = Vec::new();
while !seen.contains(&value)
&& matches!(
self.resolve(&value),
Ty::List(..) | Ty::ListLiteral(_) | Ty::Map(..) | Ty::Record(_)
)
{
seen.push(value.clone());
value = self.iterable(&value, span).1;
}
Ty::list(value)
}
Output::Zip => {
let mut items = vec![item.clone()];
for (ty, expr) in outputs.iter().zip(args) {
items.push(self.iterable(ty, expr.span).1);
}
Ty::list(Tuple(items))
}
};
Some(result)
}
fn selector(&mut self, arg: &Expr, item: &Ty, key: &Ty, env: &mut Environment) -> Ty {
if matches!(arg.kind, ExprKind::Closure { .. }) {
return self.closure(arg, &[item.clone(), key.clone()], env);
}
if let Some(path) = string(arg) {
return path.split('.').fold(item.clone(), |value, field| {
self.read_field(&value, field, arg.span, false)
});
}
let actual = self.expr(arg, env);
self.require(&actual, &Ty::String, arg.span, "selector-type");
self.unchecked(
"dynamic-selector",
arg.span,
"collection field selector is computed at runtime",
);
Ty::Any
}
fn format(&mut self, args: &[Expr], span: Span, env: &mut Environment) -> Ty {
let actual = self.arguments(args, env);
let Some(format) = args.first().and_then(string) else {
self.error(
"format-literal",
span,
"`format` requires a literal format string",
);
return Ty::Error;
};
let mut chars = format.chars().peekable();
let mut positional = 0;
while let Some(c) = chars.next() {
if c != '{' && c != '}' {
continue;
}
if chars.next_if_eq(&c).is_some() {
continue;
}
if c == '}' {
self.error(
"format-placeholder",
args[0].span,
"unmatched closing brace in format string",
);
break;
}
let mut name = std::string::String::new();
while chars.peek().is_some_and(|c| *c != '}') {
name.extend(chars.next());
}
if chars.next().is_none() {
self.error(
"format-placeholder",
args[0].span,
"unclosed placeholder in format string",
);
break;
}
if name.is_empty() {
positional += 1;
} else if identifier(&name) {
let ty = self.name(&[name], args[0].span, env, false);
self.require_printable(&ty, args[0].span);
} else {
self.error(
"format-placeholder",
args[0].span,
format!("invalid format placeholder `{name}`"),
);
}
}
self.arity(
"format",
args.len(),
positional + 1,
Some(positional + 1),
span,
);
for (arg, ty) in args.iter().zip(actual).skip(1) {
self.require_printable(&ty, arg.span);
}
Ty::String
}
pub(super) fn require_printable(&mut self, ty: &Ty, span: Span) {
if !printable(ty) && !printable(&self.resolve(ty)) {
self.error(
"not-printable",
span,
format!("{} cannot be printed", self.type_name(ty)),
);
}
}
fn route(&mut self, args: &[Expr], actual: &[Ty], span: Span) {
let Some(first) = args.first() else {
return;
};
let Some(name) = string(operand(first)) else {
self.unchecked(
"dynamic-route",
first.span,
"route name is computed at runtime",
);
return;
};
let Some(placeholders) = self.config.routes.get(name).or_else(|| {
let suffix = format!("::{name}");
let mut matching = self
.config
.routes
.iter()
.filter(|(route, _)| route.ends_with(&suffix));
let (_, definition) = matching.next()?;
matching.next().is_none().then_some(definition)
}) else {
self.error(
"unknown-route",
first.span,
format!("unknown route `{name}`"),
);
return;
};
let expression = args.get(1).map(operand);
let parameters = actual.get(1).map(|ty| self.resolve(ty));
let at = expression.map_or(span, |expr| expr.span);
let mut named = None;
let items = match parameters {
Some(Ty::ListLiteral(items) | Ty::Tuple(items)) => items,
Some(Ty::Record(fields)) => {
named = Some(fields);
Vec::new()
}
Some(Ty::List(item, Some(length))) => {
vec![*item; length.min(placeholders.len().saturating_add(1))]
}
Some(Ty::List(..) | Ty::Map(..) | Ty::Any) => {
self.unchecked(
"dynamic-route-parameters",
at,
"route parameter keys or count are only known at runtime",
);
return;
}
Some(Ty::Null) | None => Vec::new(),
Some(Ty::Error) => return,
Some(_) => vec![actual[1].clone()],
};
let missing: Vec<_> = placeholders
.iter()
.enumerate()
.filter(|(i, placeholder)| {
let value = if let Some(fields) = &named {
fields.get(&placeholder.name)
} else {
items.get(*i)
};
!placeholder.optional && value.is_none_or(|ty| matches!(self.resolve(ty), Ty::Null))
})
.map(|(_, p)| p.name.as_str())
.collect();
if !missing.is_empty() || items.len() > placeholders.len() {
let placeholders = placeholders
.iter()
.map(|p| format!("{{{}}}", p.name))
.collect::<Vec<_>>()
.join(" and ");
let supplied = named.as_ref().map_or_else(
|| match items.len() {
1 => "one positional value".into(),
count => format!("{count} positional values"),
},
|fields| {
format!(
"named keys {}",
fields.keys().cloned().collect::<Vec<_>>().join(", ")
)
},
);
self.error(
"route-parameters",
at,
format!(
"route `{name}` has placeholders {placeholders}; this call passes {supplied}"
),
);
}
for (index, placeholder) in placeholders.iter().enumerate() {
let value = if let Some(fields) = &named {
fields.get(&placeholder.name)
} else {
items.get(index)
};
if let Some(value) = value
&& !(value == &Ty::Null && missing.contains(&placeholder.name.as_str()))
{
self.route_value(value, placeholder, at);
}
}
}
fn route_value(&mut self, ty: &Ty, param: &Placeholder, span: Span) {
let expected = Ty::from(param.ty.clone());
let expected = if param.optional {
expected.optional()
} else {
expected
};
if self.members(ty).is_some() || matches!(self.resolve(ty), Ty::Map(..)) {
if let Some(key) = ¶m.model_key {
let value = self.read_field(ty, key, span, false);
self.require(&value, &expected, span, "route-parameter-type");
} else {
self.error(
"route-model-key",
span,
format!("route parameter `{}` has no model key", param.name),
);
}
} else {
self.require(ty, &expected, span, "route-parameter-type");
}
}
}
enum Param {
Typed(Ty),
Selector,
Mapper,
SpreadMapper,
Predicate,
ItemOrPredicate,
Comparator(Ty),
Reducer,
WhereValue,
WhereList,
}
enum Output {
Fixed(Ty),
Preserved,
Map,
Values,
Groups,
Keyed,
Pluck,
First,
Selected,
Chunk,
Partition,
Numeric,
Average,
Pairs,
Buckets,
Flat,
Flatten,
Zip,
}
struct CollectionSignature {
min: usize,
max: Option<usize>,
parameters: Vec<Param>,
rest: Option<Param>,
output: Output,
}
fn collection_signature(
name: &str,
arity: usize,
item: &Ty,
key: &Ty,
) -> Option<CollectionSignature> {
use Output::*;
use Param::*;
use Ty::{Any, Bool, Int, String};
let (min, params, output) = match name {
"len" => (0, vec![], Fixed(Int)),
"is_empty" | "is_not_empty" | "contains_one_item" | "contains_many_items" => {
(0, vec![], Fixed(Bool))
}
"to_json" | "to_pretty_json" => (0, vec![], Fixed(String)),
"to_css_classes" | "to_css_styles" | "query" => (0, vec![], Fixed(String)),
"map" | "transform" => (1, vec![Mapper], Map),
"map_spread" => (1, vec![SpreadMapper], Map),
"map_with_keys" => (1, vec![Mapper], Pairs),
"map_to_dictionary" | "map_to_groups" => (1, vec![Mapper], Buckets),
"flat_map" => (1, vec![Mapper], Flat),
"reduce" | "reduce_with_keys" => (1, vec![Reducer, Typed(Any)], Selected),
"filter" | "reject" => (0, vec![Predicate], Preserved),
"every" => (1, vec![Predicate], Fixed(Bool)),
"where_by" => (1, vec![Predicate], Preserved),
"where" | "where_strict" => (1, vec![Selector, WhereValue, WhereValue], Preserved),
"where_in"
| "where_in_strict"
| "where_not_in"
| "where_not_in_strict"
| "where_between"
| "where_not_between" => (2, vec![Selector, WhereList], Preserved),
"where_null" | "where_not_null" => (1, vec![Selector], Preserved),
"first_where" => (1, vec![Selector, WhereValue, WhereValue], First),
"contains" | "contains_strict" | "some" | "doesnt_contain" | "doesnt_contain_strict"
if arity >= 2 =>
{
(2, vec![Selector, WhereValue, WhereValue], Fixed(Bool))
}
"contains" | "contains_strict" | "some" | "doesnt_contain" | "doesnt_contain_strict" => {
(1, vec![ItemOrPredicate], Fixed(Bool))
}
"first" | "last" | "first_or_fail" | "sole" => {
(0, vec![Predicate, Typed(item.clone())], First)
}
"pluck" => (1, vec![Selector, Selector], Pluck),
"key_by" => (1, vec![Selector], Keyed),
"group_by" => (1, vec![Selector, Typed(Bool)], Groups),
"keys" => (0, vec![], Fixed(Ty::list(key.clone()))),
"values" => (0, vec![], Values),
"sum" => (0, vec![Selector], Numeric),
"avg" | "average" | "median" => (0, vec![Selector], Average),
"min" | "max" => (0, vec![Selector], Selected),
"join" => (1, vec![Typed(String), Typed(String)], Fixed(String)),
"partition" => (1, vec![Predicate], Partition),
"chunk" => (1, vec![Typed(Int), Typed(Bool)], Chunk),
"sliding" => (1, vec![Typed(Int), Typed(Int)], Chunk),
"split_in" | "split" => (1, vec![Typed(Int)], Chunk),
"chunk_while" | "chunk_by" => (1, vec![Predicate], Chunk),
"flatten" => (0, vec![Typed(Int)], Flatten),
"collapse" | "collapse_with_keys" => (0, vec![], Flatten),
"take" | "skip" => (1, vec![Typed(Int)], Preserved),
"nth" => (1, vec![Typed(Int), Typed(Int)], Values),
"slice" => (1, vec![Typed(Int), Typed(Int)], Preserved),
"for_page" => (2, vec![Typed(Int), Typed(Int)], Preserved),
"take_until" | "take_while" | "skip_until" | "skip_while" => {
(1, vec![Predicate], Preserved)
}
"rev" | "all" | "collect" | "to_array" | "to_base" | "json_serialize" | "sort_desc" => {
(0, vec![], Preserved)
}
"sort" => (0, vec![Comparator(item.clone())], Preserved),
"sort_keys_using" => (1, vec![Comparator(key.clone())], Preserved),
"sort_keys" | "sort_recursive" => (0, vec![Typed(Int), Typed(Bool)], Preserved),
"sort_keys_desc" | "sort_recursive_desc" => (0, vec![Typed(Int)], Preserved),
"sort_by" => (1, vec![Selector, Typed(Int), Typed(Bool)], Preserved),
"sort_by_desc" => (1, vec![Selector, Typed(Int)], Preserved),
"unique" | "duplicates" => (0, vec![Selector, Typed(Bool)], Preserved),
"unique_strict" | "duplicates_strict" => (0, vec![Selector], Preserved),
"get" => (
1,
vec![Typed(key.clone()), Typed(item.clone())],
Fixed(item.clone().optional()),
),
"contains_key" => (1, vec![Typed(key.clone())], Fixed(Bool)),
"only" | "except" => (
1,
vec![Typed(Ty::Union(vec![key.clone(), Ty::list(key.clone())]))],
Preserved,
),
"merge" | "concat" | "union" | "diff" | "intersect" | "diff_keys" | "intersect_by_keys" => {
(
1,
vec![Typed(Ty::Union(vec![
Ty::list(item.clone()),
Ty::map(key.clone(), item.clone()),
]))],
Preserved,
)
}
"zip" | "cross_join" => {
return Some(CollectionSignature {
min: 1,
max: None,
parameters: Vec::new(),
rest: Some(Typed(Any)),
output: Zip,
});
}
_ => return None,
};
Some(CollectionSignature {
min,
max: Some(params.len()),
parameters: params,
rest: None,
output,
})
}
fn identifier(text: &str) -> bool {
let mut chars = text.chars();
chars.next().is_some_and(|c| c == '_' || c.is_alphabetic())
&& chars.all(|c| c == '_' || c.is_alphanumeric())
}
pub(super) fn flag_names() -> BTreeSet<&'static str> {
[
"pretty_print",
"hex_tag",
"hex_amp",
"hex_apos",
"hex_quot",
"unescaped_slashes",
"unescaped_unicode",
"preserve_zero_fraction",
"force_object",
"throw_on_error",
]
.into_iter()
.collect()
}