1#[allow(
27 unused_imports,
28 clippy::wildcard_imports,
29 reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32
33use anyhow::{Result, bail, ensure};
34use ctb_storage_minimal::shorthand::DcShorthand;
35use serde::{Deserialize, Serialize};
36
37use super::ast::{
38 FormatExpr, FormatOp, MAX_FORMAT_EXPR_DEPTH, MAX_FORMAT_EXPR_NODES,
39 ParamBinding, ParamValue,
40};
41use crate::dc::{
42 DC_BEGIN_ASSOCIATIVITY_GROUP, DC_BEGIN_PARAMETER,
43 DC_END_ASSOCIATIVITY_GROUP, DC_END_PARAMETER, DC_FORMAT_PARAM_APPLICATION,
44 DC_TYPE_CONVERSION, DC_TYPE_INTERSECTION, DC_TYPE_TRANSFORMATION,
45 DC_TYPE_TRANSMUTATION, DC_TYPE_UNION, DcChar,
46};
47use crate::syntax::{DcRole, SyntaxRuleResolver};
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub enum DcToken {
52 Dc(DcShorthand),
54 NamedType(String),
56}
57
58impl std::fmt::Display for DcToken {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 match self {
61 Self::Dc(shorthand) => write!(f, "{shorthand}"),
62 Self::NamedType(name) => write!(f, "{name}"),
63 }
64 }
65}
66
67impl Serialize for DcToken {
68 fn serialize<S>(
69 &self,
70 serializer: S,
71 ) -> std::result::Result<S::Ok, S::Error>
72 where
73 S: serde::Serializer,
74 {
75 serializer.serialize_str(&self.to_string())
76 }
77}
78
79impl<'de> Deserialize<'de> for DcToken {
80 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
81 where
82 D: serde::Deserializer<'de>,
83 {
84 let s = String::deserialize(deserializer)?;
85 if let Ok(shorthand) = DcShorthand::parse(&s) {
86 Ok(Self::Dc(shorthand))
87 } else {
88 Ok(Self::NamedType(s))
89 }
90 }
91}
92
93impl DcToken {
94 #[must_use]
96 pub fn from_short_dc(dc: DcChar) -> Self {
97 #[expect(
98 clippy::expect_used,
99 reason = "Caller passes compile-time short Dc constant"
100 )]
101 Self::Dc(DcShorthand::Short(
102 dc.to_short_dc().expect("dc is a short Dc constant"),
103 ))
104 }
105
106 #[must_use]
108 pub fn fills_role_with(
109 &self,
110 role: DcRole,
111 resolver: &dyn SyntaxRuleResolver,
112 ) -> bool {
113 match self {
114 Self::Dc(sh) => {
115 if let Ok(gid) = sh.to_global_id() {
116 resolver.token_fills_role(gid, role)
117 } else {
118 false
119 }
120 }
121 _ => false,
122 }
123 }
124}
125
126#[must_use]
132pub fn encode_dc_stream(expr: &FormatExpr) -> Vec<DcToken> {
133 let mut tokens = Vec::new();
134 encode_expr_recursive(expr, true, &mut tokens);
135 tokens
136}
137
138#[must_use]
140pub fn encode_dc_stream_string(expr: &FormatExpr) -> String {
141 let tokens = encode_dc_stream(expr);
142 let parts: Vec<String> = tokens.iter().map(ToString::to_string).collect();
143 parts.join(" ")
144}
145
146fn encode_expr_recursive(
147 expr: &FormatExpr,
148 is_tail: bool,
149 tokens: &mut Vec<DcToken>,
150) {
151 match expr {
152 FormatExpr::Dc(shorthand) => {
153 tokens.push(DcToken::Dc(*shorthand));
154 }
155 FormatExpr::NamedType(name) => {
156 tokens.push(DcToken::NamedType(name.clone()));
157 }
158 FormatExpr::Convert(left, right) => {
159 tokens.push(DcToken::from_short_dc(FormatOp::Convert.dc_char()));
160 encode_expr_recursive(left, false, tokens);
161 encode_expr_recursive(right, is_tail, tokens);
162 }
163 FormatExpr::Transmute(left, right) => {
164 tokens.push(DcToken::from_short_dc(FormatOp::Transmute.dc_char()));
165 encode_expr_recursive(left, false, tokens);
166 encode_expr_recursive(right, is_tail, tokens);
167 }
168 FormatExpr::Transform(left, right) => {
169 tokens.push(DcToken::from_short_dc(FormatOp::Transform.dc_char()));
170 encode_expr_recursive(left, false, tokens);
171 encode_expr_recursive(right, is_tail, tokens);
172 }
173 FormatExpr::Union(children) => {
174 encode_variable_arity_op(
175 FormatOp::Union,
176 children,
177 is_tail,
178 tokens,
179 );
180 }
181 FormatExpr::Intersection(children) => {
182 encode_variable_arity_op(
183 FormatOp::Intersection,
184 children,
185 is_tail,
186 tokens,
187 );
188 }
189 FormatExpr::Apply { target, params } => {
190 tokens.push(DcToken::from_short_dc(DC_FORMAT_PARAM_APPLICATION));
191 encode_expr_recursive(target, false, tokens);
192 for param in params {
193 tokens.push(DcToken::from_short_dc(DC_BEGIN_PARAMETER));
194 tokens.push(DcToken::NamedType(param.name.clone()));
195 match ¶m.value {
196 ParamValue::Integer(n) => {
197 tokens.push(DcToken::NamedType(n.to_string()));
198 }
199 ParamValue::Dc(dc) => {
200 tokens.push(DcToken::Dc(*dc));
201 }
202 ParamValue::Ident(id) => {
203 tokens.push(DcToken::NamedType(id.clone()));
204 }
205 ParamValue::String(s) => {
206 tokens.push(DcToken::NamedType(format!(
207 "\"{}\"",
208 s.replace('"', "\\\"")
209 )));
210 }
211 ParamValue::Expr(e) => {
212 encode_expr_recursive(e, false, tokens);
213 }
214 }
215 tokens.push(DcToken::from_short_dc(DC_END_PARAMETER));
216 }
217 }
218 }
219}
220
221fn encode_variable_arity_op(
222 op: FormatOp,
223 children: &[FormatExpr],
224 is_tail: bool,
225 tokens: &mut Vec<DcToken>,
226) {
227 if children.is_empty() {
228 return;
229 }
230 tokens.push(DcToken::from_short_dc(op.dc_char()));
231 let count = children.len();
232 for (idx, child) in children.iter().enumerate() {
233 let is_last = idx.saturating_add(1) == count;
234 encode_expr_recursive(child, is_tail && is_last, tokens);
235 }
236 if !is_tail {
237 tokens.push(DcToken::from_short_dc(DC_END_ASSOCIATIVITY_GROUP));
238 }
239}
240
241pub fn decode_dc_stream_string(input: &str) -> Result<FormatExpr> {
247 decode_dc_stream_string_with_resolver(
248 input,
249 crate::syntax::default_syntax_resolver().as_ref(),
250 )
251}
252
253pub fn decode_dc_stream_string_with_resolver(
259 input: &str,
260 resolver: &dyn SyntaxRuleResolver,
261) -> Result<FormatExpr> {
262 let tokens = parse_tokens_from_str(input)?;
263 decode_dc_stream_with_resolver(&tokens, resolver)
264}
265
266fn parse_tokens_from_str(input: &str) -> Result<Vec<DcToken>> {
269 let mut tokens = Vec::new();
270 for part in input.split_whitespace() {
271 match part {
272 "&" => tokens.push(DcToken::from_short_dc(DC_TYPE_UNION)),
273 "|" => tokens.push(DcToken::from_short_dc(DC_TYPE_INTERSECTION)),
274 ">" => tokens.push(DcToken::from_short_dc(DC_TYPE_CONVERSION)),
275 "!" => tokens.push(DcToken::from_short_dc(DC_TYPE_TRANSMUTATION)),
276 ":" => tokens.push(DcToken::from_short_dc(DC_TYPE_TRANSFORMATION)),
277 "(" => tokens
278 .push(DcToken::from_short_dc(DC_BEGIN_ASSOCIATIVITY_GROUP)),
279 ")" => {
280 tokens.push(DcToken::from_short_dc(DC_END_ASSOCIATIVITY_GROUP));
281 }
282 _ => {
283 if let Ok(shorthand) = DcShorthand::parse(part) {
284 tokens.push(DcToken::Dc(shorthand));
285 } else {
286 tokens.push(DcToken::NamedType(part.to_string()));
287 }
288 }
289 }
290 }
291 Ok(tokens)
292}
293
294pub(crate) fn is_closing_token(
296 token: &DcToken,
297 resolver: &dyn SyntaxRuleResolver,
298) -> bool {
299 token.fills_role_with(DcRole::EndAssociativityGroup, resolver)
300 || matches!(token, DcToken::NamedType(s) if s == ")")
301}
302
303fn format_op_from_token(
304 token: &DcToken,
305 resolver: &dyn SyntaxRuleResolver,
306) -> Option<FormatOp> {
307 [
308 FormatOp::Union,
309 FormatOp::Transform,
310 FormatOp::Convert,
311 FormatOp::Transmute,
312 FormatOp::Intersection,
313 ]
314 .into_iter()
315 .find(|&op| token.fills_role_with(op.role(), resolver))
316}
317
318pub fn decode_dc_stream(tokens: &[DcToken]) -> Result<FormatExpr> {
323 decode_dc_stream_with_resolver(
324 tokens,
325 crate::syntax::default_syntax_resolver().as_ref(),
326 )
327}
328
329pub fn decode_dc_stream_with_resolver(
334 tokens: &[DcToken],
335 resolver: &dyn SyntaxRuleResolver,
336) -> Result<FormatExpr> {
337 ensure!(!tokens.is_empty(), "Empty Dc token stream");
338 let mut pos = 0usize;
339 let expr = decode_recursive(tokens, &mut pos, 0, false, resolver)?;
340
341 ensure!(
342 pos == tokens.len(),
343 "Trailing unused tokens in Dc stream starting at token index {pos}"
344 );
345
346 let depth = expr.depth();
347 ensure!(
348 depth <= MAX_FORMAT_EXPR_DEPTH,
349 "Decoded format expression depth {depth} exceeds maximum allowed depth {MAX_FORMAT_EXPR_DEPTH}"
350 );
351
352 let nodes = expr.node_count();
353 ensure!(
354 nodes <= MAX_FORMAT_EXPR_NODES,
355 "Decoded format expression node count {nodes} exceeds maximum allowed nodes {MAX_FORMAT_EXPR_NODES}"
356 );
357
358 Ok(expr)
359}
360
361fn decode_recursive(
362 tokens: &[DcToken],
363 pos: &mut usize,
364 depth: usize,
365 in_variable_arity: bool,
366 resolver: &dyn SyntaxRuleResolver,
367) -> Result<FormatExpr> {
368 ensure!(
369 depth <= MAX_FORMAT_EXPR_DEPTH,
370 "Dc token stream nesting exceeds maximum depth limit of {MAX_FORMAT_EXPR_DEPTH}"
371 );
372 let Some(token) = tokens.get(*pos) else {
373 bail!("Unexpected end of Dc token stream: missing operand");
374 };
375 *pos = pos.saturating_add(1);
376
377 if token.fills_role_with(DcRole::BeginAssociativityGroup, resolver) {
378 let Some(op_token) = tokens.get(*pos) else {
380 bail!(
381 "Unexpected end of stream after group start '298': expected operator"
382 );
383 };
384 *pos = pos.saturating_add(1);
385
386 if op_token.fills_role_with(DcRole::FormatParamApplication, resolver) {
387 let target = decode_recursive(
388 tokens,
389 pos,
390 depth.saturating_add(1),
391 false,
392 resolver,
393 )?;
394 let params = decode_apply_params(
395 tokens,
396 pos,
397 depth.saturating_add(1),
398 resolver,
399 )?;
400 return Ok(FormatExpr::Apply {
401 target: Box::new(target),
402 params,
403 });
404 }
405
406 let op = format_op_from_token(op_token, resolver).ok_or_else(|| {
407 anyhow::anyhow!(
408 "Invalid operator in Dc group: expected operator 300, 301, 302, 303, or 516, found '{op_token}'"
409 )
410 })?;
411
412 match op {
413 FormatOp::Convert | FormatOp::Transmute | FormatOp::Transform => {
414 let left = decode_recursive(
415 tokens,
416 pos,
417 depth.saturating_add(1),
418 false,
419 resolver,
420 )?;
421 let right = decode_recursive(
422 tokens,
423 pos,
424 depth.saturating_add(1),
425 false,
426 resolver,
427 )?;
428
429 let Some(closing) = tokens.get(*pos) else {
430 bail!(
431 "Unclosed Dc associativity group: expected terminating '299'"
432 );
433 };
434 *pos = pos.saturating_add(1);
435 ensure!(
436 is_closing_token(closing, resolver),
437 "Expected terminating '299' for Dc group, found '{closing}'"
438 );
439
440 Ok(match op {
441 FormatOp::Convert => {
442 FormatExpr::Convert(Box::new(left), Box::new(right))
443 }
444 FormatOp::Transmute => {
445 FormatExpr::Transmute(Box::new(left), Box::new(right))
446 }
447 FormatOp::Transform => {
448 FormatExpr::Transform(Box::new(left), Box::new(right))
449 }
450 FormatOp::Union | FormatOp::Intersection => unreachable!(),
451 })
452 }
453 FormatOp::Union | FormatOp::Intersection => {
454 let mut children = Vec::new();
455 while *pos < tokens.len() {
456 if let Some(tok) = tokens.get(*pos) {
457 if is_closing_token(tok, resolver) {
458 *pos = pos.saturating_add(1);
459 break;
460 }
461 }
462 let child = decode_recursive(
463 tokens,
464 pos,
465 depth.saturating_add(1),
466 true,
467 resolver,
468 )?;
469 children.push(child);
470 }
471 ensure!(
472 children.len() >= 2,
473 "Variable-arity operator requires at least 2 operands, found {}",
474 children.len()
475 );
476 if op == FormatOp::Union {
477 Ok(FormatExpr::Union(children))
478 } else {
479 Ok(FormatExpr::Intersection(children))
480 }
481 }
482 }
483 } else if let Some(op) = format_op_from_token(token, resolver) {
484 match op {
485 FormatOp::Convert | FormatOp::Transmute | FormatOp::Transform => {
486 let left = decode_recursive(
487 tokens,
488 pos,
489 depth.saturating_add(1),
490 false,
491 resolver,
492 )?;
493 let right = decode_recursive(
494 tokens,
495 pos,
496 depth.saturating_add(1),
497 in_variable_arity,
498 resolver,
499 )?;
500
501 if !in_variable_arity {
504 if let Some(tok) = tokens.get(*pos) {
505 if is_closing_token(tok, resolver) {
506 *pos = pos.saturating_add(1);
507 }
508 }
509 }
510
511 Ok(match op {
512 FormatOp::Convert => {
513 FormatExpr::Convert(Box::new(left), Box::new(right))
514 }
515 FormatOp::Transmute => {
516 FormatExpr::Transmute(Box::new(left), Box::new(right))
517 }
518 FormatOp::Transform => {
519 FormatExpr::Transform(Box::new(left), Box::new(right))
520 }
521 FormatOp::Union | FormatOp::Intersection => unreachable!(),
522 })
523 }
524 FormatOp::Union | FormatOp::Intersection => {
525 let mut children = Vec::new();
526 while *pos < tokens.len() {
527 if let Some(tok) = tokens.get(*pos) {
528 if is_closing_token(tok, resolver) {
529 *pos = pos.saturating_add(1);
530 break;
531 }
532 }
533 let child = decode_recursive(
534 tokens,
535 pos,
536 depth.saturating_add(1),
537 true,
538 resolver,
539 )?;
540 children.push(child);
541 }
542 ensure!(
543 children.len() >= 2,
544 "Variable-arity operator requires at least 2 operands, found {}",
545 children.len()
546 );
547 if op == FormatOp::Union {
548 Ok(FormatExpr::Union(children))
549 } else {
550 Ok(FormatExpr::Intersection(children))
551 }
552 }
553 }
554 } else if token.fills_role_with(DcRole::FormatParamApplication, resolver) {
555 let target = decode_recursive(
556 tokens,
557 pos,
558 depth.saturating_add(1),
559 false,
560 resolver,
561 )?;
562 let params = decode_apply_params(
563 tokens,
564 pos,
565 depth.saturating_add(1),
566 resolver,
567 )?;
568 Ok(FormatExpr::Apply {
569 target: Box::new(target),
570 params,
571 })
572 } else if token.fills_role_with(DcRole::EndAssociativityGroup, resolver) {
573 bail!(
574 "Unexpected closing group '299' without matching opening operator or group"
575 );
576 } else {
577 match token {
578 DcToken::Dc(shorthand) => Ok(FormatExpr::Dc(*shorthand)),
579 DcToken::NamedType(name) => Ok(FormatExpr::NamedType(name.clone())),
580 }
581 }
582}
583
584fn decode_apply_params(
586 tokens: &[DcToken],
587 pos: &mut usize,
588 depth: usize,
589 resolver: &dyn SyntaxRuleResolver,
590) -> Result<Vec<ParamBinding>> {
591 let mut params = Vec::new();
592 while *pos < tokens.len() {
593 let Some(tok) = tokens.get(*pos) else {
594 break;
595 };
596 if tok.fills_role_with(DcRole::BeginParameter, resolver) {
597 *pos = pos.saturating_add(1);
598 let Some(name_tok) = tokens.get(*pos) else {
599 bail!(
600 "Unexpected end of stream: expected parameter name after '258'"
601 );
602 };
603 *pos = pos.saturating_add(1);
604 let name = match name_tok {
605 DcToken::NamedType(s) => s.clone(),
606 DcToken::Dc(sh) => sh.to_string(),
607 };
608
609 let Some(val_tok) = tokens.get(*pos) else {
610 bail!(
611 "Unexpected end of stream: expected parameter value for '{name}'"
612 );
613 };
614 *pos = pos.saturating_add(1);
615 let value = match val_tok {
616 DcToken::Dc(sh) => {
617 if val_tok.fills_role_with(
618 DcRole::BeginAssociativityGroup,
619 resolver,
620 ) || val_tok.fills_role_with(
621 DcRole::FormatParamApplication,
622 resolver,
623 ) || format_op_from_token(val_tok, resolver).is_some()
624 {
625 *pos = pos.saturating_sub(1);
626 let sub = decode_recursive(
627 tokens,
628 pos,
629 depth.saturating_add(1),
630 false,
631 resolver,
632 )?;
633 ParamValue::Expr(Box::new(sub))
634 } else if let DcShorthand::Short(id) = sh {
635 ParamValue::Integer(i64::from(*id))
636 } else {
637 ParamValue::Dc(*sh)
638 }
639 }
640 DcToken::NamedType(s) => {
641 if let Ok(num) = s.parse::<i64>() {
642 ParamValue::Integer(num)
643 } else if let Some(stripped) = s
644 .strip_prefix('"')
645 .and_then(|str_val| str_val.strip_suffix('"'))
646 {
647 ParamValue::String(stripped.replace("\\\"", "\""))
648 } else if let Ok(sh) = DcShorthand::parse(s) {
649 ParamValue::Dc(sh)
650 } else {
651 ParamValue::Ident(s.clone())
652 }
653 }
654 };
655
656 let Some(end_tok) = tokens.get(*pos) else {
657 bail!(
658 "Unexpected end of stream: expected '259' closing parameter '{name}'"
659 );
660 };
661 *pos = pos.saturating_add(1);
662 ensure!(
663 end_tok.fills_role_with(DcRole::EndParameter, resolver),
664 "Expected Dc 259 ('End parameter'), found '{end_tok}'"
665 );
666
667 params.push(ParamBinding { name, value });
668 } else {
669 break;
670 }
671 }
672 Ok(params)
673}