cel_parser/registered_ops.rs
1//! Persistent operation and record metadata shared by independent host libraries.
2//!
3//! Register a function marker once, then add disjoint operand signatures from any
4//! installer. Ordinary calls and direct member lookup share the same emitters:
5//!
6//! ```
7//! use cel_parser::{OpLookup, OperationSignature, ResolvedLeafType};
8//! use cel_runtime::ValueType;
9//! #[derive(Clone)]
10//! struct Identity;
11//! let mut lookup = OpLookup::new();
12//! lookup.register_function("identity", Identity).unwrap();
13//! let ty = ResolvedLeafType::new("u32", ValueType::leaf::<u32>());
14//! lookup.register_operation(OperationSignature {
15//! name: "identity", operands: vec![ty.clone().into()], result: ty.into(),
16//! emit: Box::new(|segment, _| segment.op1(|value: u32| value)),
17//! }).unwrap();
18//! assert_eq!(lookup.operation_signatures("identity").count(), 1);
19//! ```
20
21use std::any::TypeId;
22
23use anyhow::{Result, ensure};
24use cel_runtime::{DynSegment, ValueType};
25
26use crate::{ExprSpan, OpLookup, ParseError, ResolvedLeafType, ResolvedType, SourceSpan};
27
28/// Emits an operation after the complete operand signature has matched.
29///
30/// - Precondition: the stack ends with the declared operand descriptors.
31/// - Postcondition: success replaces those operands with the declared result.
32///
33/// Emitters validate fallible setup before changing the segment. The lookup uniquely owns
34/// each emitter and invokes it only while compiling; segments own the emitted operations.
35/// Boxing a zero-sized, captureless closure does not allocate.
36///
37/// # Examples
38/// See [`OpLookup::register_operation`] for a registered emitter.
39pub type OperationEmitter = Box<dyn Fn(&mut DynSegment, SourceSpan) -> Result<()> + Send + Sync>;
40
41/// Consumes source-order fields using source-position to schema-position indices,
42/// the ambient stack byte offset, and the expression span.
43///
44/// The lookup uniquely owns this compile-time callback. Boxing a zero-sized,
45/// captureless closure does not allocate.
46///
47/// # Examples
48/// See [`OpLookup::register_record`] for source-order field construction.
49pub type RecordEmitter =
50 Box<dyn Fn(&mut DynSegment, &[usize], usize, SourceSpan) -> Result<()> + Send + Sync>;
51
52/// Describes one named operation with complete concrete operand and result identities.
53///
54/// The emitter consumes exactly `operands` and produces exactly `result`.
55///
56/// # Examples
57/// See [`OpLookup::register_operation`] for signature construction.
58pub struct OperationSignature {
59 /// The shared operation name.
60 pub name: &'static str,
61 /// Operands in source order, including the receiver for member lookup.
62 pub operands: Vec<ResolvedType>,
63 /// The single result's complete type.
64 pub result: ResolvedType,
65 /// The implementation used by both direct lookup and ordinary calls.
66 pub emit: OperationEmitter,
67}
68
69/// Describes one required record field.
70///
71/// # Examples
72/// See [`OpLookup::register_record`] for declaring required fields.
73pub struct RecordField {
74 /// The source field name.
75 pub name: &'static str,
76 /// The field's complete concrete type.
77 pub ty: ResolvedType,
78}
79
80/// Describes a named record's required fields and construction implementation.
81///
82/// # Examples
83/// See [`OpLookup::register_record`] for constructing and installing a schema.
84pub struct RecordSchema {
85 /// The constructed type, whose source name keys this schema.
86 pub ty: ResolvedLeafType,
87 /// Required fields in canonical constructor order.
88 pub fields: Vec<RecordField>,
89 /// The constructor, invoked only after field validation.
90 pub emit: RecordEmitter,
91}
92
93/// Stores the first marker selected for a function name.
94pub(crate) struct RegisteredFunction {
95 pub(crate) name: &'static str,
96 pub(crate) marker: ResolvedLeafType,
97 pub(crate) emit: OperationEmitter,
98}
99
100/// Holds permanent registrations independently of transient parser scopes.
101#[derive(Default)]
102pub(crate) struct RegisteredOps {
103 pub(crate) operations: Vec<OperationSignature>,
104 pub(crate) functions: Vec<RegisteredFunction>,
105 marker_names: Vec<(TypeId, &'static str)>,
106 pub(crate) records: Vec<RecordSchema>,
107}
108
109/// Compares concrete recursive identities without treating diagnostic names as identity.
110///
111/// - Complexity: O(n) in recursive descriptor nodes.
112fn same_type(left: &ResolvedType, right: &ResolvedType) -> bool {
113 match (left.complete_value_type(), right.complete_value_type()) {
114 (Ok(left), Ok(right)) => left.same_shape(&right),
115 _ => false,
116 }
117}
118
119/// Matches the complete runtime descriptor, never just an erased array marker.
120///
121/// - Complexity: O(n) in recursive descriptor nodes.
122fn matches_type(expected: &ResolvedType, actual: &ValueType) -> bool {
123 expected
124 .complete_value_type()
125 .is_ok_and(|expected| expected.same_shape(actual))
126}
127
128impl OpLookup {
129 /// Validates required named fields and emits one record from their original stack order.
130 ///
131 /// Field descriptors must match exactly, including recursive array identities. Validation
132 /// never changes the segment; only a fully validated constructor invokes its emitter.
133 ///
134 /// - Precondition: the stack ends with one value per field, starting at `ambient_start`.
135 /// - Complexity: O(r + f² + f * d) for r schemas, f fields and descriptor depth d.
136 ///
137 /// # Errors
138 /// Returns an error for unknown records, unknown/duplicate/missing fields, mismatched
139 /// field types, or a constructor emitter's setup failure.
140 ///
141 /// # Examples
142 /// ```
143 /// use cel_parser::{CELParser, OpLookup, RecordSchema, ResolvedLeafType};
144 /// use cel_runtime::ValueType;
145 /// let mut lookup = OpLookup::new();
146 /// lookup.register_record(RecordSchema {
147 /// ty: ResolvedLeafType::new("Empty", ValueType::leaf::<()>()),
148 /// fields: vec![],
149 /// emit: Box::new(|s, _, _, _| { s.just(()); Ok(()) }),
150 /// }).unwrap();
151 /// CELParser::new(lookup).parse_str("Empty {}").unwrap().call0::<()>().unwrap();
152 /// ```
153 pub fn construct_record(
154 &self,
155 name: &str,
156 fields: &[(String, ExprSpan)],
157 ambient_start: usize,
158 segment: &mut DynSegment,
159 start: proc_macro2::Span,
160 end: proc_macro2::Span,
161 ) -> crate::Result<()> {
162 let error = |message| ParseError::new_range(message, start, end);
163 let schema = self
164 .record_schema(name)
165 .ok_or_else(|| error(format!("unknown record `{name}`")))?;
166 let mut mapping = Vec::with_capacity(fields.len());
167 for (index, (field, span)) in fields.iter().enumerate() {
168 let schema_index = schema
169 .fields
170 .iter()
171 .position(|candidate| candidate.name == field)
172 .ok_or_else(|| {
173 ParseError::new_range(
174 format!("unknown field `{field}` in record `{name}`"),
175 span.start,
176 span.end,
177 )
178 })?;
179 if fields[..index]
180 .iter()
181 .any(|(previous, _)| previous == field)
182 {
183 return Err(ParseError::new_range(
184 format!("duplicate field `{field}` in record `{name}`"),
185 span.start,
186 span.end,
187 ));
188 }
189 mapping.push(schema_index);
190 }
191 if let Some(missing) = schema
192 .fields
193 .iter()
194 .enumerate()
195 .find(|(index, _)| !mapping.contains(index))
196 {
197 return Err(error(format!(
198 "missing field `{}` in record `{name}`",
199 missing.1.name
200 )));
201 }
202 let operands = segment.peek_stack_infos(fields.len());
203 debug_assert_eq!(operands.len(), fields.len());
204 debug_assert_eq!(
205 segment.stack_offset_before_top(fields.len()).ok(),
206 Some(ambient_start)
207 );
208 for ((actual, &schema_index), (field, span)) in operands.iter().zip(&mapping).zip(fields) {
209 let expected = &schema.fields[schema_index].ty;
210 if !matches_type(expected, &actual.value_type) {
211 return Err(ParseError::new_range(
212 format!(
213 "field `{field}`: type mismatch: expected `{}`",
214 expected.display_name()
215 ),
216 span.start,
217 span.end,
218 ));
219 }
220 }
221 (schema.emit)(
222 segment,
223 &mapping,
224 ambient_start,
225 SourceSpan::from_proc_macro2_range(start, end),
226 )
227 .map_err(|err| error(err.to_string()))?;
228 segment
229 .annotate_top(
230 schema
231 .ty
232 .complete_value_type()
233 .map_err(|err| error(err.to_string()))?
234 .clone(),
235 )
236 .map_err(|err| error(err.to_string()))
237 }
238
239 /// Registers one persistent named operation without replacing existing overloads.
240 ///
241 /// # Errors
242 /// Returns an error for unavailable complete factories or unrepresentable layouts, and
243 /// duplicate operand identities, including return-type-only overloads.
244 ///
245 /// - Complexity: O(s * a * d) for s signatures, a operands and descriptor depth d.
246 ///
247 /// # Examples
248 /// See the [registration tutorial](crate::registered_ops).
249 pub fn register_operation(&mut self, signature: OperationSignature) -> Result<()> {
250 for operand in &signature.operands {
251 operand.complete_value_type()?;
252 }
253 signature.result.complete_value_type()?;
254 ensure!(
255 !self.operation_signatures(signature.name).any(|existing| {
256 existing.operands.len() == signature.operands.len()
257 && existing
258 .operands
259 .iter()
260 .zip(&signature.operands)
261 .all(|(a, b)| same_type(a, b))
262 }),
263 "duplicate operation signature for `{}`",
264 signature.name
265 );
266 self.registered.operations.push(signature);
267 Ok(())
268 }
269
270 /// Binds a persistent callable name, retaining its first marker across installers.
271 ///
272 /// Markers require `Send + Sync` so lookup retains its thread-safety guarantees.
273 ///
274 /// # Errors
275 /// Returns an error if this marker type has already named a distinct function.
276 ///
277 /// - Complexity: O(f) for f registered marker types.
278 ///
279 /// # Examples
280 /// See the [registration tutorial](crate::registered_ops).
281 pub fn register_function<M: Clone + Send + Sync + 'static>(
282 &mut self,
283 name: &'static str,
284 marker: M,
285 ) -> Result<()> {
286 let marker_type = TypeId::of::<M>();
287 ensure!(
288 self.registered
289 .marker_names
290 .iter()
291 .all(|(ty, bound_name)| *ty != marker_type || *bound_name == name),
292 "function marker already names another function"
293 );
294 if !self.registered.marker_names.contains(&(marker_type, name)) {
295 self.registered.marker_names.push((marker_type, name));
296 }
297 if !self
298 .registered
299 .functions
300 .iter()
301 .any(|function| function.name == name)
302 {
303 self.registered.functions.push(RegisteredFunction {
304 name,
305 marker: ResolvedLeafType::new(name, ValueType::cloneable_leaf::<M>()),
306 emit: Box::new(move |segment, _| {
307 segment.just(marker.clone());
308 Ok(())
309 }),
310 });
311 }
312 Ok(())
313 }
314
315 /// Registers a persistent record schema keyed by its source type name.
316 ///
317 /// # Errors
318 /// Returns an error for unavailable complete factories or unrepresentable layouts, a
319 /// duplicate schema name, or duplicate field names.
320 ///
321 /// - Complexity: O(r + f²) for r schemas and f fields.
322 ///
323 /// # Examples
324 /// ```
325 /// use cel_parser::{OpLookup, RecordSchema, ResolvedLeafType};
326 /// use cel_runtime::ValueType;
327 /// let mut lookup = OpLookup::new();
328 /// lookup.register_record(RecordSchema {
329 /// ty: ResolvedLeafType::new("Unit", ValueType::leaf::<()>()),
330 /// fields: vec![],
331 /// emit: Box::new(|segment, _, _, _| { segment.just(()); Ok(()) }),
332 /// }).unwrap();
333 /// assert!(lookup.record_schema("Unit").is_some());
334 /// ```
335 pub fn register_record(&mut self, schema: RecordSchema) -> Result<()> {
336 schema.ty.complete_value_type()?;
337 for field in &schema.fields {
338 field.ty.complete_value_type()?;
339 }
340 ensure!(
341 self.record_schema(schema.ty.type_name()).is_none(),
342 "duplicate record schema `{}`",
343 schema.ty.type_name()
344 );
345 for (index, field) in schema.fields.iter().enumerate() {
346 ensure!(
347 !schema.fields[..index]
348 .iter()
349 .any(|other| other.name == field.name),
350 "duplicate record field `{}`",
351 field.name
352 );
353 }
354 self.registered.records.push(schema);
355 Ok(())
356 }
357
358 /// Iterates persistent signatures named `name` in registration order.
359 ///
360 /// - Complexity: O(s) to exhaust s registered signatures.
361 ///
362 /// # Examples
363 /// See the [registration tutorial](crate::registered_ops).
364 pub fn operation_signatures(&self, name: &str) -> impl Iterator<Item = &OperationSignature> {
365 self.registered
366 .operations
367 .iter()
368 .filter(move |signature| signature.name == name)
369 }
370
371 /// Returns the persistent schema with the given source type name.
372 ///
373 /// - Complexity: O(r) for r registered schemas.
374 ///
375 /// # Examples
376 /// See [`Self::register_record`].
377 pub fn record_schema(&self, name: &str) -> Option<&RecordSchema> {
378 self.registered
379 .records
380 .iter()
381 .find(|schema| schema.ty.type_name() == name)
382 }
383
384 /// Dispatches a registered signature only after every operand descriptor matches.
385 ///
386 /// Declining a signature leaves operand descriptors and emitted operations unchanged.
387 ///
388 /// # Errors
389 /// Returns the selected emitter's setup error.
390 ///
391 /// - Complexity: O(s * a * d) for s signatures, a operands and descriptor depth d.
392 pub(crate) fn lookup_registered_operation(
393 &self,
394 name: &str,
395 segment: &mut DynSegment,
396 arity: usize,
397 span: SourceSpan,
398 ) -> Result<bool> {
399 let operands = segment.peek_stack_infos(arity);
400 if operands.len() != arity {
401 return Ok(false);
402 }
403 for signature in self.operation_signatures(name) {
404 if signature.operands.len() == arity
405 && signature
406 .operands
407 .iter()
408 .zip(operands)
409 .all(|(expected, actual)| matches_type(expected, &actual.value_type))
410 {
411 (signature.emit)(segment, span)?;
412 segment.annotate_top(signature.result.complete_value_type()?.clone())?;
413 return Ok(true);
414 }
415 }
416 Ok(false)
417 }
418
419 /// Resolves a bare registered name or a marker-qualified ordinary call.
420 ///
421 /// # Errors
422 /// Returns a selected scope/emitter error or a checked stack-offset error.
423 ///
424 /// - Complexity: O(f + k + s * a * d + n) for f functions, k scopes,
425 /// s signatures, a operands, descriptor depth d and n ambient stack entries.
426 pub(crate) fn lookup_registered(
427 &self,
428 name: &str,
429 segment: &mut DynSegment,
430 arity: usize,
431 span: SourceSpan,
432 library_only: bool,
433 ) -> Result<bool> {
434 if arity == 0
435 && let Some(function) = self.registered.functions.iter().find(|f| f.name == name)
436 {
437 (function.emit)(segment, span)?;
438 return Ok(true);
439 }
440 if name == "()" && arity > 0 {
441 let operands = segment.peek_stack_infos(arity);
442 if operands.len() != arity {
443 return Ok(false);
444 }
445 let marker_type = operands[0].value_type.type_id();
446 if let Some(function) = self
447 .registered
448 .functions
449 .iter()
450 .find(|f| f.marker.type_id() == marker_type)
451 {
452 let ambient_start = segment.stack_offset_before_top(arity)?;
453 if self.lookup_direct_operation_scoped(
454 function.name,
455 segment,
456 arity - 1,
457 span,
458 library_only,
459 )? {
460 segment.make_tuple(2, ambient_start)?;
461 segment.tuple_index(1)?;
462 return Ok(true);
463 }
464 return Ok(false);
465 }
466 }
467 self.lookup_registered_operation(name, segment, arity, span)
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474
475 /// Supplies a complete scalar descriptor for registration contracts.
476 fn scalar<T: 'static>(name: &'static str) -> ResolvedType {
477 ResolvedLeafType::new(name, ValueType::leaf::<T>()).into()
478 }
479
480 /// Schema validation rejects duplicate fields and successful construction retains its descriptor.
481 #[test]
482 fn record_schema_validation_precedes_construction() {
483 let mut lookup = OpLookup::new();
484 let invalid = RecordSchema {
485 ty: ResolvedLeafType::new("Invalid", ValueType::leaf::<u8>()),
486 fields: vec![
487 RecordField {
488 name: "x",
489 ty: scalar::<i32>("i32"),
490 },
491 RecordField {
492 name: "x",
493 ty: scalar::<i32>("i32"),
494 },
495 ],
496 emit: Box::new(|_, _, _, _| panic!("invalid schema must not be installed")),
497 };
498 assert!(lookup.register_record(invalid).is_err());
499 assert!(lookup.record_schema("Invalid").is_none());
500 lookup
501 .register_record(RecordSchema {
502 ty: ResolvedLeafType::new("Empty", ValueType::leaf::<u8>()),
503 fields: Vec::new(),
504 emit: Box::new(|segment, mapping, ambient, _| {
505 assert!(mapping.is_empty());
506 assert_eq!(ambient, 0);
507 segment.just(9u8);
508 Ok(())
509 }),
510 })
511 .unwrap();
512 let mut segment = DynSegment::new::<()>();
513 lookup
514 .construct_record(
515 "Empty",
516 &[],
517 0,
518 &mut segment,
519 proc_macro2::Span::call_site(),
520 proc_macro2::Span::call_site(),
521 )
522 .unwrap();
523 assert_eq!(
524 segment.peek_stack_infos(1)[0].value_type.type_name(),
525 "Empty"
526 );
527 assert_eq!(segment.call0::<u8>().unwrap(), 9);
528 }
529
530 /// Builds one signature whose execution adds an observable offset.
531 fn increment() -> OperationSignature {
532 OperationSignature {
533 name: "increment",
534 operands: vec![scalar::<i32>("i32")],
535 result: scalar::<i32>("i32"),
536 emit: Box::new(|segment, _| {
537 segment.op1r(|value: i32| {
538 value
539 .checked_add(1)
540 .ok_or_else(|| anyhow::anyhow!("overflow"))
541 })
542 }),
543 }
544 }
545
546 /// Aliases compare by complete identity, while nested element mismatches remain distinct.
547 #[test]
548 fn complete_identity_does_not_depend_on_diagnostic_names() {
549 assert!(same_type(&scalar::<i32>("i32"), &scalar::<i32>("Alias")));
550 assert!(!same_type(&scalar::<i32>("i32"), &scalar::<u32>("i32")));
551 let array = ResolvedType::Array {
552 element: Box::new(scalar::<i32>("i32")),
553 };
554 assert!(matches_type(
555 &array,
556 &ValueType::array(ValueType::leaf::<i32>())
557 ));
558 assert!(!matches_type(
559 &array,
560 &ValueType::array(ValueType::leaf::<u32>())
561 ));
562 }
563
564 /// Duplicate rejection preserves the first signature and its working emitter.
565 #[test]
566 fn registration_and_dispatch_preserve_the_first_overload() {
567 let mut lookup = OpLookup::new();
568 lookup.register_operation(increment()).unwrap();
569 let mut duplicate = increment();
570 duplicate.result = scalar::<bool>("bool");
571 assert!(lookup.register_operation(duplicate).is_err());
572 assert_eq!(lookup.operation_signatures("increment").count(), 1);
573 assert_eq!(lookup.operation_signatures("missing").count(), 0);
574 let mut segment = DynSegment::new::<()>();
575 segment.just(41i32);
576 assert!(
577 !lookup
578 .lookup_registered_operation(
579 "missing",
580 &mut segment,
581 1,
582 SourceSpan::new(1, 0, 1, 1)
583 )
584 .unwrap()
585 );
586 assert!(
587 lookup
588 .lookup_registered_operation(
589 "increment",
590 &mut segment,
591 1,
592 SourceSpan::new(1, 0, 1, 1)
593 )
594 .unwrap()
595 );
596 assert_eq!(segment.call0::<i32>().unwrap(), 42);
597 }
598
599 /// A marker cannot identify two functions and metadata agrees with executable dispatch.
600 #[test]
601 fn function_markers_have_one_name_and_emit_the_registered_value() {
602 let mut lookup = OpLookup::new();
603 lookup.register_function("marker", 17u8).unwrap();
604 assert!(lookup.register_function("other", 18u8).is_err());
605 let expr = crate::Parser::<crate::AstContext>::new(OpLookup::new())
606 .parse_str_ast("marker")
607 .unwrap();
608 let (ty, diagnostics) = crate::ty::check_expr_with_type_resolver(
609 &expr,
610 &|_| crate::Ty::Any,
611 crate::builtin_type_resolver().as_ref(),
612 &lookup,
613 );
614 assert_eq!(ty, crate::Ty::U8);
615 assert!(diagnostics.is_empty());
616 let mut segment = DynSegment::new::<()>();
617 assert!(
618 lookup
619 .lookup_registered(
620 "marker",
621 &mut segment,
622 0,
623 SourceSpan::new(1, 0, 1, 1),
624 false
625 )
626 .unwrap()
627 );
628 assert_eq!(segment.call0::<u8>().unwrap(), 17);
629 }
630}