use cel::common::ast::{CallExpr, Expr};
use ferricel_types::functions::RuntimeFunction;
use walrus::InstrSeqBuilder;
use crate::compiler::{
context::{CompilerContext, CompilerEnv},
expr::compile_expr,
helpers::compile_call_binary,
};
fn is_format_namespace_call(call_expr: &CallExpr) -> bool {
matches!(
&call_expr.target,
Some(t) if matches!(&t.expr, Expr::Ident(name) if name == "format")
)
}
pub fn compile_k8s_format_function(
func_name: &str,
call_expr: &CallExpr,
body: &mut InstrSeqBuilder,
env: &CompilerEnv,
ctx: &CompilerContext,
module: &mut walrus::Module,
) -> Result<(), anyhow::Error> {
if is_format_namespace_call(call_expr) {
let runtime_fn = match func_name {
"named" => {
if call_expr.args.len() != 1 {
anyhow::bail!("format.named() expects 1 argument");
}
compile_expr(&call_expr.args[0].expr, body, env, ctx, module)?;
body.call(env.get(RuntimeFunction::K8sFormatNamed));
return Ok(());
}
"dns1123Label" => RuntimeFunction::K8sFormatDns1123Label,
"dns1123Subdomain" => RuntimeFunction::K8sFormatDns1123Subdomain,
"dns1035Label" => RuntimeFunction::K8sFormatDns1035Label,
"qualifiedName" => RuntimeFunction::K8sFormatQualifiedName,
"dns1123LabelPrefix" => RuntimeFunction::K8sFormatDns1123LabelPrefix,
"dns1123SubdomainPrefix" => RuntimeFunction::K8sFormatDns1123SubdomainPrefix,
"dns1035LabelPrefix" => RuntimeFunction::K8sFormatDns1035LabelPrefix,
"labelValue" => RuntimeFunction::K8sFormatLabelValue,
"uri" => RuntimeFunction::K8sFormatUri,
"uuid" => RuntimeFunction::K8sFormatUuid,
"byte" => RuntimeFunction::K8sFormatByte,
"date" => RuntimeFunction::K8sFormatDate,
"datetime" => RuntimeFunction::K8sFormatDatetime,
_ => anyhow::bail!("Unknown format constructor: format.{}()", func_name),
};
if !call_expr.args.is_empty() {
anyhow::bail!("format.{}() takes no arguments", func_name);
}
body.call(env.get(runtime_fn));
return Ok(());
}
if func_name == "validate" {
return compile_call_binary(
call_expr,
"validate",
RuntimeFunction::K8sFormatValidate,
body,
env,
ctx,
module,
);
}
anyhow::bail!("Unknown Kubernetes format function: {}", func_name)
}