ctb_formats_dcdata/support/
column_spec.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Unified parser and validator for the overloaded Aliases / Base / Chain / Syntax column.
21//!
22//! This column appears as Column 6 in Format category tables (`"Base/Related Format/Category,
23//! Chain (@), or Syntax (:)"`) and Column 9 in Dc category tables and unified schemas
24//! (`"Aliases; >=xref, <=decompos., :=Dc syntax, @chain"`).
25//!
26//! It parses comma-separated directives:
27//! - `@implies(...)`: Logically implied format, supertype, or capability requirement using Dc shorthand syntax.
28//! - `@based_on(...)`: Historical ancestry, lineage, or parent format reference using Dc shorthand syntax.
29//! - `@chain(...)` or `@(...)`: Format composition specification DSL.
30//! - `:<syntax>`: Document Character syntax rule DSL.
31//! - `><xref>`: Cross-reference.
32//! - `<<tag>payload>`: Decomposition tag (`<approx>`, `<equiv>`, `<semantic>`, etc.).
33//! - Bare words: Permitted as aliases in Character tables; disallowed in Format tables.
34
35#[allow(
36    unused_imports,
37    clippy::wildcard_imports,
38    reason = "Standard workspace module prelude"
39)]
40use crate::utilities::*;
41
42use crate::report::ValidationReport;
43use ctb_storage_minimal::shorthand::is_valid_shorthand;
44
45/// Parsed formal alias with kind and alias name.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct ParsedFormalAlias {
48    pub kind: String,
49    pub alias: String,
50}
51
52/// Structured representation of parsed elements from an Aliases / Base / Chain / Syntax cell.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct ParsedAliasesOrBaseColumn {
55    /// Plain aliases (character tables only).
56    pub aliases: Vec<String>,
57    /// Formal aliases extracted from `@formalAliasCorrection(...)`, `@formalAliasControl(...)`, etc.
58    pub formal_aliases: Vec<ParsedFormalAlias>,
59    /// Formats / capabilities logically implied by this format, extracted from `@implies(...)`.
60    pub implies: Vec<String>,
61    /// Ancestor / historical lineage formats extracted from `@based_on(...)`.
62    pub based_on: Vec<String>,
63    /// Cross-reference targets extracted from `@xref(...)` and `><target>`.
64    pub cross_references: Vec<String>,
65    /// Decomposition expressions extracted from `<<tag>payload>`.
66    pub decompositions: Vec<String>,
67    /// Annotations extracted from `@annotation(...)`.
68    pub annotations: Vec<String>,
69    /// Syntax specification string extracted from `:<syntax>`.
70    pub syntax_raw: Option<String>,
71    /// Format specification DSL string extracted from `@chain(...)` or `@(...)`.
72    pub format_spec_raw: Option<String>,
73    /// Rust identifier extracted from `@ident(...)`.
74    pub rust_ident: Option<String>,
75    /// Nicknames extracted from `@nick(...)`.
76    pub nicknames: Vec<String>,
77    /// OS associations extracted from `@os(...)` containing format shorthands.
78    pub os_associations: Vec<String>,
79    /// Canonical title / true name extracted from `@title(...)`.
80    pub title: Option<String>,
81    /// Default line ending extracted from `@default_line_ending(...)`.
82    pub default_line_ending: Option<String>,
83    /// Format variant category key extracted from `@vary_as("...")`.
84    pub vary_as: Option<String>,
85    /// Format variant categories that vary for this format, extracted from `@varies(...)`.
86    pub varies: Vec<ctb_storage_minimal::shorthand::DcShorthand>,
87    /// File magic description strings extracted from `@magic_name(...)`.
88    pub magic_names: Vec<String>,
89    /// Opening target character closed by this character, extracted from `@closes(...)`.
90    pub closes: Option<ctb_storage_minimal::shorthand::DcShorthand>,
91    /// Indicates whether this character or format's programmatic identifier (`@ident` / `Ident`) is marked stable via `@stable_ident()`.
92    pub stable_ident: bool,
93}
94
95/// Parses and validates the contents of an Aliases / Base / Chain / Syntax column cell.
96///
97/// Enforces RFC4180 spacing and comma rules:
98/// - No leading or trailing whitespace.
99/// - Every comma must be followed by exactly one space (`", "`).
100/// - No whitespace before a comma.
101/// - No consecutive commas or leading/trailing commas.
102///
103/// When `is_format_table` is `true`, bare format names lacking a directive are rejected with
104/// an error instructing migration to `@implies(...)` or `@based_on(...)`.
105pub fn parse_aliases_or_base_column(
106    raw: &str,
107    file_path: &str,
108    line_no: usize,
109    report: &mut ValidationReport,
110    is_format_table: bool,
111) -> ParsedAliasesOrBaseColumn {
112    let mut parsed = ParsedAliasesOrBaseColumn::default();
113    let col_name = if is_format_table {
114        "Base/Related Format"
115    } else {
116        "Aliases"
117    };
118
119    if raw.trim().is_empty() {
120        if !raw.is_empty() {
121            report.add_error(
122                file_path,
123                Some(line_no),
124                Some(col_name),
125                format!("Cell consists solely of whitespace in {col_name} column: '{raw}'"),
126                Some("Leave the cell blank if there are no directives or aliases"),
127            );
128        }
129        return parsed;
130    }
131
132    if raw.starts_with(char::is_whitespace) {
133        report.add_error(
134            file_path,
135            Some(line_no),
136            Some(col_name),
137            format!(
138                "Cell has leading whitespace in {col_name} column: '{raw}'"
139            ),
140            Some("Remove leading spaces from the cell"),
141        );
142    }
143    if raw.ends_with(char::is_whitespace) {
144        report.add_error(
145            file_path,
146            Some(line_no),
147            Some(col_name),
148            format!(
149                "Cell has trailing whitespace in {col_name} column: '{raw}'"
150            ),
151            Some("Remove trailing spaces from the cell"),
152        );
153    }
154
155    // Tokenize on commas while checking spacing rules.
156    // Parentheses in format specs or syntax rules can contain commas or complex nested syntax,
157    // but top-level column items are separated by ", ".
158    let chars: Vec<(usize, char)> = raw.char_indices().collect();
159    let num_chars = chars.len();
160    let mut item_start = 0_usize;
161    let mut paren_depth = 0_usize;
162    let mut bracket_depth = 0_usize;
163    let mut in_quotes = false;
164    let mut is_escaped = false;
165
166    for (i, &(byte_idx, ch)) in chars.iter().enumerate() {
167        if is_escaped {
168            is_escaped = false;
169            continue;
170        }
171        if ch == '\\' {
172            is_escaped = true;
173            continue;
174        }
175        if ch == '"' {
176            in_quotes = !in_quotes;
177            continue;
178        }
179        if in_quotes {
180            continue;
181        }
182        match ch {
183            '(' => paren_depth = paren_depth.saturating_add(1),
184            ')' => paren_depth = paren_depth.saturating_sub(1),
185            '[' => bracket_depth = bracket_depth.saturating_add(1),
186            ']' => bracket_depth = bracket_depth.saturating_sub(1),
187            ',' if paren_depth == 0 && bracket_depth == 0 => {
188                // Check space before comma
189                if i > 0 {
190                    if let Some(&(_, prev_ch)) = chars.get(i.saturating_sub(1))
191                    {
192                        if prev_ch.is_whitespace() {
193                            let snippet_start = raw.floor_char_boundary(
194                                byte_idx.saturating_sub(10),
195                            );
196                            let snippet_end = raw.ceil_char_boundary(
197                                byte_idx.saturating_add(1).min(raw.len()),
198                            );
199                            #[expect(
200                                clippy::expect_used,
201                                reason = "floor_char_boundary and ceil_char_boundary guarantee valid UTF-8 char boundaries with snippet_start <= snippet_end <= raw.len()"
202                            )]
203                            let snippet = raw
204                                .get(snippet_start..snippet_end)
205                                .expect("char-boundary slice is valid");
206                            report.add_error(
207                                file_path,
208                                Some(line_no),
209                                Some(col_name),
210                                format!(
211                                    "Extra space before ',' in {col_name} column: '{snippet}'"
212                                ),
213                                Some("Do not place spaces before commas"),
214                            );
215                        }
216                    }
217                } else {
218                    report.add_error(
219                        file_path,
220                        Some(line_no),
221                        Some(col_name),
222                        format!("Leading comma in {col_name} column: '{raw}'"),
223                        Some("Remove leading comma"),
224                    );
225                }
226
227                // Check space after comma
228                let next_i = i.saturating_add(1);
229                if next_i >= num_chars {
230                    report.add_error(
231                        file_path,
232                        Some(line_no),
233                        Some(col_name),
234                        format!("Trailing comma in {col_name} column: '{raw}'"),
235                        Some("Remove trailing comma"),
236                    );
237                } else if let Some(&(_, next_ch)) = chars.get(next_i) {
238                    if next_ch == ',' {
239                        report.add_error(
240                            file_path,
241                            Some(line_no),
242                            Some(col_name),
243                            format!("Consecutive commas in {col_name} column: '{raw}'"),
244                            Some("Remove redundant comma"),
245                        );
246                    } else if next_ch != ' ' {
247                        let snippet_end = raw.ceil_char_boundary(
248                            byte_idx.saturating_add(15).min(raw.len()),
249                        );
250                        #[expect(
251                            clippy::expect_used,
252                            reason = "byte_idx is from char_indices() and ceil_char_boundary guarantees valid UTF-8 char boundary >= byte_idx"
253                        )]
254                        let snippet = raw
255                            .get(byte_idx..snippet_end)
256                            .expect("char-boundary slice is valid");
257                        report.add_error(
258                            file_path,
259                            Some(line_no),
260                            Some(col_name),
261                            format!("Missing space after ',' in {col_name} column: '{snippet}'"),
262                            Some("Ensure every comma is followed by a single space (e.g. ', ')"),
263                        );
264                    } else {
265                        let next_next_i = next_i.saturating_add(1);
266                        if let Some(&(_, after_space_ch)) =
267                            chars.get(next_next_i)
268                        {
269                            if after_space_ch.is_whitespace() {
270                                let snippet_end = raw.ceil_char_boundary(
271                                    byte_idx.saturating_add(15).min(raw.len()),
272                                );
273                                #[expect(
274                                    clippy::expect_used,
275                                    reason = "byte_idx is from char_indices() and ceil_char_boundary guarantees valid UTF-8 char boundary >= byte_idx"
276                                )]
277                                let snippet = raw
278                                    .get(byte_idx..snippet_end)
279                                    .expect("char-boundary slice is valid");
280                                report.add_error(
281                                    file_path,
282                                    Some(line_no),
283                                    Some(col_name),
284                                    format!(
285                                        "Multiple spaces after ',' in {col_name} column: '{snippet}'"
286                                    ),
287                                    Some("Use exactly one space after each comma"),
288                                );
289                            }
290                        }
291                    }
292                }
293
294                if let Some(item_raw) = raw.get(item_start..byte_idx) {
295                    process_column_item(
296                        item_raw,
297                        file_path,
298                        line_no,
299                        report,
300                        is_format_table,
301                        col_name,
302                        &mut parsed,
303                    );
304                }
305
306                item_start = byte_idx.saturating_add(1);
307            }
308            _ => {}
309        }
310    }
311
312    if in_quotes {
313        report.add_error(
314            file_path,
315            Some(line_no),
316            Some(col_name),
317            format!("Unterminated string quote in {col_name} column: '{raw}'"),
318            Some("Ensure all double quotes are closed"),
319        );
320    }
321
322    if let Some(last_raw) = raw.get(item_start..) {
323        process_column_item(
324            last_raw,
325            file_path,
326            line_no,
327            report,
328            is_format_table,
329            col_name,
330            &mut parsed,
331        );
332    }
333
334    parsed
335}
336
337/// Unescapes a double-quoted string payload inside a directive (e.g. `"foo \"bar\""` -> `foo "bar"`).
338fn unescape_quoted_directive_payload(raw: &str) -> Option<String> {
339    let trimmed = raw.trim();
340    let content = trimmed.strip_prefix('"')?.strip_suffix('"')?;
341    let mut res = String::with_capacity(content.len());
342    let mut chars = content.chars().peekable();
343    while let Some(c) = chars.next() {
344        if c == '\\' {
345            if let Some(&next_c) = chars.peek() {
346                if next_c == '"' || next_c == '\\' {
347                    res.push(next_c);
348                    chars.next();
349                    continue;
350                }
351            }
352            res.push('\\');
353        } else {
354            res.push(c);
355        }
356    }
357    Some(res)
358}
359
360fn process_column_item(
361    item_raw: &str,
362    file_path: &str,
363    line_no: usize,
364    report: &mut ValidationReport,
365    is_format_table: bool,
366    col_name: &str,
367    parsed: &mut ParsedAliasesOrBaseColumn,
368) {
369    let item_trimmed = item_raw.trim();
370    if item_trimmed.is_empty() {
371        return;
372    }
373
374    if item_trimmed.starts_with('@') {
375        if let Some(inner) = item_trimmed.strip_prefix("@implies(") {
376            if let Some(stripped) = inner.strip_suffix(')') {
377                let val = stripped.trim();
378                if val.is_empty() {
379                    report.add_error(
380                        file_path,
381                        Some(line_no),
382                        Some(col_name),
383                        format!("Empty '@implies()' directive in {col_name} column: '{item_trimmed}'"),
384                        Some("Specify a format shorthand inside @implies(...) (e.g. '@implies(f271)')"),
385                    );
386                } else {
387                    validate_shorthand_expr(
388                        val, file_path, line_no, report, col_name, "@implies",
389                    );
390                    parsed.implies.push(val.to_string());
391                }
392            } else {
393                report.add_error(
394                    file_path,
395                    Some(line_no),
396                    Some(col_name),
397                    format!("Malformed '@implies(...)': missing closing parenthesis in '{item_trimmed}'"),
398                    Some("Ensure '@implies(...)' closes with a parenthesis"),
399                );
400            }
401        } else if let Some(inner) = item_trimmed.strip_prefix("@based_on(") {
402            if let Some(stripped) = inner.strip_suffix(')') {
403                let val = stripped.trim();
404                if val.is_empty() {
405                    report.add_error(
406                        file_path,
407                        Some(line_no),
408                        Some(col_name),
409                        format!("Empty '@based_on()' directive in {col_name} column: '{item_trimmed}'"),
410                        Some("Specify a format shorthand inside @based_on(...) (e.g. '@based_on(f580)')"),
411                    );
412                } else {
413                    validate_shorthand_expr(
414                        val,
415                        file_path,
416                        line_no,
417                        report,
418                        col_name,
419                        "@based_on",
420                    );
421                    parsed.based_on.push(val.to_string());
422                }
423            } else {
424                report.add_error(
425                    file_path,
426                    Some(line_no),
427                    Some(col_name),
428                    format!("Malformed '@based_on(...)': missing closing parenthesis in '{item_trimmed}'"),
429                    Some("Ensure '@based_on(...)' closes with a parenthesis"),
430                );
431            }
432        } else if item_trimmed.starts_with("@base(") {
433            report.add_error(
434                file_path,
435                Some(line_no),
436                Some(col_name),
437                format!("Directive '@base(...)' is deprecated and ambiguous: '{item_trimmed}'"),
438                Some("Use '@implies(...)' for capability/property entailment or '@based_on(...)' for historical ancestry/derivation"),
439            );
440        } else if let Some(inner) = item_trimmed.strip_prefix("@xref(") {
441            if let Some(stripped) = inner.strip_suffix(')') {
442                let target = stripped.trim();
443                if target.is_empty() {
444                    report.add_error(
445                        file_path,
446                        Some(line_no),
447                        Some(col_name),
448                        format!("Empty '@xref()' directive in {col_name} column: '{item_trimmed}'"),
449                        Some("Specify a target shorthand inside @xref(...) (e.g. '@xref(u22ee)')"),
450                    );
451                } else if !is_valid_shorthand(target) {
452                    report.add_error(
453                        file_path,
454                        Some(line_no),
455                        Some(col_name),
456                        format!("Invalid target shorthand in '@xref({target})'"),
457                        Some("Specify a valid shorthand like 'u22ee', short Dc, or format 'f161'"),
458                    );
459                } else {
460                    parsed.cross_references.push(target.to_string());
461                }
462            } else {
463                report.add_error(
464                    file_path,
465                    Some(line_no),
466                    Some(col_name),
467                    format!("Malformed '@xref(...)': missing closing parenthesis in '{item_trimmed}'"),
468                    Some("Ensure '@xref(...)' closes with a parenthesis"),
469                );
470            }
471        } else if let Some(inner) = item_trimmed.strip_prefix("@annotation(") {
472            if let Some(stripped) = inner.strip_suffix(')') {
473                if let Some(unescaped) =
474                    unescape_quoted_directive_payload(stripped)
475                {
476                    parsed.annotations.push(unescaped);
477                } else {
478                    report.add_error(
479                        file_path,
480                        Some(line_no),
481                        Some(col_name),
482                        format!("Malformed '@annotation(...)': content must be enclosed in double quotes in '{item_trimmed}'"),
483                        Some("Use '@annotation(\"...\")' with internal quotes escaped as '\\\"'"),
484                    );
485                }
486            } else {
487                report.add_error(
488                    file_path,
489                    Some(line_no),
490                    Some(col_name),
491                    format!("Malformed '@annotation(...)': missing closing parenthesis in '{item_trimmed}'"),
492                    Some("Ensure '@annotation(...)' closes with a parenthesis"),
493                );
494            }
495        } else if item_trimmed.starts_with("@formalAlias") {
496            let formal_types = [
497                ("Correction", "@formalAliasCorrection("),
498                ("Control", "@formalAliasControl("),
499                ("Alternate", "@formalAliasAlternate("),
500                ("Figment", "@formalAliasFigment("),
501                ("Abbreviation", "@formalAliasAbbreviation("),
502            ];
503            let mut matched = false;
504            for (kind, prefix) in formal_types {
505                if let Some(inner) = item_trimmed.strip_prefix(prefix) {
506                    matched = true;
507                    if let Some(stripped) = inner.strip_suffix(')') {
508                        if let Some(unescaped) =
509                            unescape_quoted_directive_payload(stripped)
510                        {
511                            parsed.formal_aliases.push(ParsedFormalAlias {
512                                kind: kind.to_string(),
513                                alias: unescaped,
514                            });
515                        } else {
516                            report.add_error(
517                                file_path,
518                                Some(line_no),
519                                Some(col_name),
520                                format!("Malformed '{prefix}...)': alias must be enclosed in double quotes in '{item_trimmed}'"),
521                                Some("Use '@formalAlias<Type>(\"...\")'"),
522                            );
523                        }
524                    } else {
525                        report.add_error(
526                            file_path,
527                            Some(line_no),
528                            Some(col_name),
529                            format!("Malformed '{prefix}...)': missing closing parenthesis in '{item_trimmed}'"),
530                            Some("Ensure directive closes with a parenthesis"),
531                        );
532                    }
533                    break;
534                }
535            }
536            if !matched {
537                report.add_error(
538                    file_path,
539                    Some(line_no),
540                    Some(col_name),
541                    format!("Unknown formal alias directive '{item_trimmed}' in {col_name} column"),
542                    Some("Supported formal alias directives are: @formalAliasCorrection, @formalAliasControl, @formalAliasAlternate, @formalAliasFigment, @formalAliasAbbreviation"),
543                );
544            }
545        } else if item_trimmed.starts_with("@chain(")
546            || item_trimmed.starts_with("@(")
547        {
548            parsed.format_spec_raw = Some(item_trimmed.to_string());
549        } else if let Some(inner) = item_trimmed.strip_prefix("@ident(") {
550            if let Some(stripped) = inner.strip_suffix(')') {
551                if let Some(unescaped) =
552                    unescape_quoted_directive_payload(stripped)
553                {
554                    if let Err(e) = crate::validate_rust_identifier(&unescaped)
555                    {
556                        report.add_error(
557                            file_path,
558                            Some(line_no),
559                            Some(col_name),
560                            format!("Invalid Rust identifier in '@ident(\"{unescaped}\")': {e}"),
561                            Some("Identifier must be a valid Rust identifier (e.g. '@ident(\"TarGz\")')"),
562                        );
563                    }
564                    parsed.rust_ident = Some(unescaped);
565                } else {
566                    report.add_error(
567                        file_path,
568                        Some(line_no),
569                        Some(col_name),
570                        format!("Malformed '@ident(...)': content must be enclosed in double quotes in '{item_trimmed}'"),
571                        Some("Use '@ident(\"...\")' with internal quotes escaped as '\\\"'"),
572                    );
573                }
574            } else {
575                report.add_error(
576                    file_path,
577                    Some(line_no),
578                    Some(col_name),
579                    format!("Malformed '@ident(...)': missing closing parenthesis in '{item_trimmed}'"),
580                    Some("Ensure '@ident(...)' closes with a parenthesis"),
581                );
582            }
583        } else if let Some(inner) = item_trimmed.strip_prefix("@nick(") {
584            if let Some(stripped) = inner.strip_suffix(')') {
585                if let Some(unescaped) =
586                    unescape_quoted_directive_payload(stripped)
587                {
588                    if unescaped.trim().is_empty() {
589                        report.add_error(
590                            file_path,
591                            Some(line_no),
592                            Some(col_name),
593                            format!("Empty '@nick()' in '{item_trimmed}'"),
594                            Some("Provide a non-empty nickname string inside '@nick(\"...\")'"),
595                        );
596                    } else {
597                        parsed.nicknames.push(unescaped);
598                    }
599                } else {
600                    report.add_error(
601                        file_path,
602                        Some(line_no),
603                        Some(col_name),
604                        format!("Malformed '@nick(...)': content must be enclosed in double quotes in '{item_trimmed}'"),
605                        Some("Use '@nick(\"...\")' with internal quotes escaped as '\\\"'"),
606                    );
607                }
608            } else {
609                report.add_error(
610                    file_path,
611                    Some(line_no),
612                    Some(col_name),
613                    format!("Malformed '@nick(...)': missing closing parenthesis in '{item_trimmed}'"),
614                    Some("Ensure '@nick(...)' closes with a parenthesis"),
615                );
616            }
617        } else if let Some(inner) = item_trimmed.strip_prefix("@magic_name(") {
618            if let Some(stripped) = inner.strip_suffix(')') {
619                if let Some(unescaped) =
620                    unescape_quoted_directive_payload(stripped)
621                {
622                    if unescaped.trim().is_empty() {
623                        report.add_error(
624                            file_path,
625                            Some(line_no),
626                            Some(col_name),
627                            format!("Empty '@magic_name()' in '{item_trimmed}'"),
628                            Some("Provide a non-empty description string inside '@magic_name(\"...\")'"),
629                        );
630                    } else {
631                        parsed.magic_names.push(unescaped);
632                    }
633                } else {
634                    report.add_error(
635                        file_path,
636                        Some(line_no),
637                        Some(col_name),
638                        format!("Malformed '@magic_name(...)': content must be enclosed in double quotes in '{item_trimmed}'"),
639                        Some("Use '@magic_name(\"...\")' with internal quotes escaped as '\\\"'"),
640                    );
641                }
642            } else {
643                report.add_error(
644                    file_path,
645                    Some(line_no),
646                    Some(col_name),
647                    format!("Malformed '@magic_name(...)': missing closing parenthesis in '{item_trimmed}'"),
648                    Some("Ensure '@magic_name(...)' closes with a parenthesis"),
649                );
650            }
651        } else if let Some(inner) = item_trimmed.strip_prefix("@os(") {
652            if let Some(stripped) = inner.strip_suffix(')') {
653                let os_val = stripped.trim();
654                if os_val.is_empty() {
655                    report.add_error(
656                        file_path,
657                        Some(line_no),
658                        Some(col_name),
659                        format!("Empty '@os()' directive in {col_name} column: '{item_trimmed}'"),
660                        Some("Specify a format shorthand inside @os(...) (e.g. '@os(f405)')"),
661                    );
662                } else {
663                    for token in os_val.split(',') {
664                        let token_trimmed = token.trim();
665                        if token_trimmed.is_empty() {
666                            report.add_error(
667                                file_path,
668                                Some(line_no),
669                                Some(col_name),
670                                format!("Empty OS shorthand token in '{item_trimmed}'"),
671                                Some("Provide a non-empty format shorthand in '@os(...)'"),
672                            );
673                            continue;
674                        }
675                        match ctb_storage_minimal::shorthand::parse_format_shorthand(token_trimmed) {
676                            Ok(_) => {
677                                parsed.os_associations.push(token_trimmed.to_string());
678                            }
679                            Err(_) => {
680                                report.add_error(
681                                    file_path,
682                                    Some(line_no),
683                                    Some(col_name),
684                                    format!("Invalid format shorthand '{token_trimmed}' in '@os(...)'. Only format shorthands (e.g. 'f405') are supported"),
685                                    Some("Use format shorthands like 'f405' (MacOs), 'f402' (Windows), 'f492' (Unix)"),
686                                );
687                            }
688                        }
689                    }
690                }
691            } else {
692                report.add_error(
693                    file_path,
694                    Some(line_no),
695                    Some(col_name),
696                    format!("Malformed '@os(...)': missing closing parenthesis in '{item_trimmed}'"),
697                    Some("Ensure '@os(...)' closes with a parenthesis"),
698                );
699            }
700        } else if let Some(inner) = item_trimmed.strip_prefix("@title(") {
701            if let Some(stripped) = inner.strip_suffix(')') {
702                if let Some(unescaped) =
703                    unescape_quoted_directive_payload(stripped)
704                {
705                    if unescaped.trim().is_empty() {
706                        report.add_error(
707                            file_path,
708                            Some(line_no),
709                            Some(col_name),
710                            format!("Empty '@title()' in '{item_trimmed}'"),
711                            Some("Provide a non-empty title string inside '@title(\"... \")'"),
712                        );
713                    } else if parsed.title.is_some() {
714                        report.add_error(
715                            file_path,
716                            Some(line_no),
717                            Some(col_name),
718                            format!("Duplicate '@title()' directive in '{item_trimmed}'"),
719                            Some("Only one @title directive is permitted per entry"),
720                        );
721                    } else {
722                        parsed.title = Some(unescaped);
723                    }
724                } else {
725                    report.add_error(
726                        file_path,
727                        Some(line_no),
728                        Some(col_name),
729                        format!("Malformed '@title(...)': content must be enclosed in double quotes in '{item_trimmed}'"),
730                        Some("Use '@title(\"... \")' with internal quotes escaped as '\\\"'"),
731                    );
732                }
733            } else {
734                report.add_error(
735                    file_path,
736                    Some(line_no),
737                    Some(col_name),
738                    format!("Malformed '@title(...)': missing closing parenthesis in '{item_trimmed}'"),
739                    Some("Ensure '@title(...)' closes with a parenthesis"),
740                );
741            }
742        } else if let Some(inner) =
743            item_trimmed.strip_prefix("@default_line_ending(")
744        {
745            if let Some(stripped) = inner.strip_suffix(')') {
746                let val =
747                    stripped.trim().trim_matches('"').to_ascii_lowercase();
748                if val.is_empty() {
749                    report.add_error(
750                        file_path,
751                        Some(line_no),
752                        Some(col_name),
753                        format!("Empty '@default_line_ending()' in '{item_trimmed}'"),
754                        Some("Specify a line ending name (e.g. 'crlf', 'cr', 'lf') inside '@default_line_ending(...)'"),
755                    );
756                } else if !matches!(
757                    val.as_str(),
758                    "lf" | "cr" | "crlf" | "lfcr" | "rs" | "nl"
759                ) {
760                    report.add_error(
761                        file_path,
762                        Some(line_no),
763                        Some(col_name),
764                        format!("Unknown line ending '{val}' in '{item_trimmed}'"),
765                        Some("Supported line endings are 'lf', 'cr', 'crlf', 'lfcr', 'rs', 'nl'"),
766                    );
767                } else {
768                    parsed.default_line_ending = Some(val);
769                }
770            } else {
771                report.add_error(
772                    file_path,
773                    Some(line_no),
774                    Some(col_name),
775                    format!("Malformed '@default_line_ending(...)': missing closing parenthesis in '{item_trimmed}'"),
776                    Some("Ensure '@default_line_ending(...)' closes with a parenthesis"),
777                );
778            }
779        } else if let Some(inner) = item_trimmed.strip_prefix("@vary_as(") {
780            if let Some(stripped) = inner.strip_suffix(')') {
781                if let Some(unescaped) =
782                    unescape_quoted_directive_payload(stripped)
783                {
784                    if unescaped.trim().is_empty() {
785                        report.add_error(
786                            file_path,
787                            Some(line_no),
788                            Some(col_name),
789                            format!("Empty '@vary_as()' in '{item_trimmed}'"),
790                            Some("Provide a non-empty variant category name inside '@vary_as(\"... \")'"),
791                        );
792                    } else if parsed.vary_as.is_some() {
793                        report.add_error(
794                            file_path,
795                            Some(line_no),
796                            Some(col_name),
797                            format!("Duplicate '@vary_as()' directive in '{item_trimmed}'"),
798                            Some("Only one @vary_as directive is permitted per entry"),
799                        );
800                    } else {
801                        parsed.vary_as = Some(unescaped);
802                    }
803                } else {
804                    report.add_error(
805                        file_path,
806                        Some(line_no),
807                        Some(col_name),
808                        format!("Malformed '@vary_as(...)': content must be enclosed in double quotes in '{item_trimmed}'"),
809                        Some("Use '@vary_as(\"... \")' with internal quotes escaped as '\\\"'"),
810                    );
811                }
812            } else {
813                report.add_error(
814                    file_path,
815                    Some(line_no),
816                    Some(col_name),
817                    format!("Malformed '@vary_as(...)': missing closing parenthesis in '{item_trimmed}'"),
818                    Some("Ensure '@vary_as(...)' closes with a parenthesis"),
819                );
820            }
821        } else if let Some(inner) = item_trimmed.strip_prefix("@varies(") {
822            if let Some(stripped) = inner.strip_suffix(')') {
823                let val = stripped.trim();
824                if val.is_empty() {
825                    report.add_error(
826                        file_path,
827                        Some(line_no),
828                        Some(col_name),
829                        format!("Empty '@varies()' directive in {col_name} column: '{item_trimmed}'"),
830                        Some("Specify one or more format variant category shorthands inside @varies(...) (e.g. '@varies(f354)')"),
831                    );
832                } else {
833                    for token in val.split(',') {
834                        let token_trimmed = token.trim();
835                        if token_trimmed.is_empty() {
836                            report.add_error(
837                                file_path,
838                                Some(line_no),
839                                Some(col_name),
840                                format!("Empty token in '@varies(...)' in '{item_trimmed}'"),
841                                Some("Provide comma-separated format variant category shorthands (e.g. '@varies(f354, f355)')"),
842                            );
843                            continue;
844                        }
845                        match ctb_storage_minimal::shorthand::DcShorthand::parse(
846                            token_trimmed,
847                        ) {
848                            Ok(shorthand) => {
849                                parsed.varies.push(shorthand);
850                            }
851                            Err(_) => {
852                                report.add_error(
853                                    file_path,
854                                    Some(line_no),
855                                    Some(col_name),
856                                    format!("Invalid Dc shorthand '{token_trimmed}' in '@varies(...)': '{item_trimmed}'"),
857                                    Some("Specify valid format variant category shorthands (e.g. 'f354')"),
858                                );
859                            }
860                        }
861                    }
862                }
863            } else {
864                report.add_error(
865                    file_path,
866                    Some(line_no),
867                    Some(col_name),
868                    format!("Malformed '@varies(...)': missing closing parenthesis in '{item_trimmed}'"),
869                    Some("Ensure '@varies(...)' closes with a parenthesis"),
870                );
871            }
872        } else if let Some(inner) = item_trimmed.strip_prefix("@closes(") {
873            if let Some(stripped) = inner.strip_suffix(')') {
874                let trimmed = stripped.trim();
875                match ctb_storage_minimal::shorthand::DcShorthand::parse(
876                    trimmed,
877                ) {
878                    Ok(target) => {
879                        parsed.closes = Some(target);
880                    }
881                    Err(e) => {
882                        report.add_error(
883                            file_path,
884                            Some(line_no),
885                            Some(col_name),
886                            format!("Invalid target in '@closes({trimmed})': {e}"),
887                            Some("Provide a valid Dc target inside '@closes(...)', e.g. '@closes(547)'"),
888                        );
889                    }
890                }
891            } else {
892                report.add_error(
893                    file_path,
894                    Some(line_no),
895                    Some(col_name),
896                    format!("Malformed '@closes(...)': missing closing parenthesis in '{item_trimmed}'"),
897                    Some("Ensure '@closes(...)' closes with a parenthesis"),
898                );
899            }
900        } else if item_trimmed == "@stable_ident()" {
901            parsed.stable_ident = true;
902        } else if let Some(inner) = item_trimmed.strip_prefix("@stable_ident(")
903        {
904            if let Some(body) = inner.strip_suffix(')') {
905                if body.trim().is_empty() {
906                    parsed.stable_ident = true;
907                } else {
908                    report.add_error(
909                        file_path,
910                        Some(line_no),
911                        Some(col_name),
912                        format!("Malformed '@stable_ident()': expected empty parentheses in '{item_trimmed}'"),
913                        Some("Use '@stable_ident()' without arguments"),
914                    );
915                    parsed.stable_ident = true;
916                }
917            } else {
918                report.add_error(
919                    file_path,
920                    Some(line_no),
921                    Some(col_name),
922                    format!("Malformed '@stable_ident(...)': missing closing parenthesis in '{item_trimmed}'"),
923                    Some("Ensure '@stable_ident()' closes with a parenthesis"),
924                );
925                parsed.stable_ident = true;
926            }
927        } else if item_trimmed == "@stable_ident" {
928            report.add_error(
929                file_path,
930                Some(line_no),
931                Some(col_name),
932                format!("Malformed '@stable_ident': missing parentheses in '{item_trimmed}'"),
933                Some("Use '@stable_ident()' with empty parentheses"),
934            );
935            parsed.stable_ident = true;
936        } else {
937            report.add_error(
938                file_path,
939                Some(line_no),
940                Some(col_name),
941                format!("Unknown directive '{item_trimmed}' in {col_name} column"),
942                Some("Supported '@' directives are '@implies(...)', '@based_on(...)', '@chain(...)', '@xref(...)', '@formalAlias<Type>(...)', '@annotation(...)', '@ident(...)', '@stable_ident()', '@nick(...)', '@os(...)', '@title(...)', '@default_line_ending(...)', '@magic_name(...)', '@vary_as(...)', '@varies(...)', and '@closes(...)'"),
943            );
944        }
945    } else if item_trimmed.starts_with('=') {
946        report.add_error(
947            file_path,
948            Some(line_no),
949            Some(col_name),
950            format!("Legacy chain syntax '=' is deprecated: '{item_trimmed}'. Use '@chain(...)' instead"),
951            Some("Update to '@chain(...)' format specification syntax"),
952        );
953    } else if item_trimmed.starts_with(':') {
954        if item_trimmed.contains("  ") {
955            report.add_error(
956                file_path,
957                Some(line_no),
958                Some(col_name),
959                format!("Multiple consecutive spaces in syntax declaration: '{item_trimmed}'"),
960                Some("Use single spaces in syntax declarations"),
961            );
962        }
963        parsed.syntax_raw = Some(item_trimmed.to_string());
964    } else if let Some(rest) = item_trimmed.strip_prefix('>') {
965        if !rest.starts_with('<') && rest.starts_with(char::is_whitespace) {
966            // Reason for fallback: cross-reference target token after whitespace defaults to empty string
967            let token = rest.split_whitespace().next().unwrap_or("");
968            report.add_error(
969                file_path,
970                Some(line_no),
971                Some(col_name),
972                format!("Extra space before '{token}' in cross-reference: '> {token}'"),
973                Some(
974                    "Cross-reference '>' must be followed immediately by target without spaces (e.g. '>32')",
975                ),
976            );
977        }
978        parsed.cross_references.push(item_trimmed.to_string());
979    } else if item_trimmed.starts_with('<') {
980        if let Some((tag_raw, payload)) = item_trimmed.split_once('>') {
981            // Reason for fallback: starts_with('<') confirmed above, strip '<' prefix to extract tag name
982            let tag_name = tag_raw.strip_prefix('<').unwrap_or(tag_raw);
983            let tag_full = format!("{tag_raw}>");
984            if tag_name.is_empty() {
985                report.add_error(
986                    file_path,
987                    Some(line_no),
988                    Some(col_name),
989                    format!("Empty decomposition tag: '<>' in '{item_trimmed}'"),
990                    Some("Provide a tag name between angle brackets (e.g. '<approx>', '<equiv>')"),
991                );
992            } else {
993                if tag_name.starts_with(char::is_whitespace) {
994                    report.add_error(
995                        file_path,
996                        Some(line_no),
997                        Some(col_name),
998                        format!("Extra space after '<' in decomposition tag: '{tag_full}'"),
999                        Some("Remove leading space inside '<...>' tag"),
1000                    );
1001                }
1002                if tag_name.ends_with(char::is_whitespace) {
1003                    report.add_error(
1004                        file_path,
1005                        Some(line_no),
1006                        Some(col_name),
1007                        format!("Extra space before '>' in decomposition tag: '{tag_full}'"),
1008                        Some("Remove trailing space inside '<...>' tag"),
1009                    );
1010                }
1011                if tag_name.trim().contains(char::is_whitespace) {
1012                    report.add_error(
1013                        file_path,
1014                        Some(line_no),
1015                        Some(col_name),
1016                        format!("Whitespace inside decomposition tag: '{tag_full}'"),
1017                        Some("Remove whitespace from decomposition tag name (e.g. '<approx>')"),
1018                    );
1019                }
1020            }
1021            if payload.starts_with(char::is_whitespace) {
1022                // Reason for fallback: payload with trailing whitespace and no token defaults to empty string
1023                let first_token = payload
1024                    .split(|c: char| c.is_whitespace() || c == ',')
1025                    .find(|s| !s.is_empty())
1026                    .unwrap_or("");
1027                let full_sample = if first_token.is_empty() {
1028                    tag_full.clone()
1029                } else {
1030                    format!("{tag_full} {first_token}")
1031                };
1032                report.add_error(
1033                    file_path,
1034                    Some(line_no),
1035                    Some(col_name),
1036                    if first_token.is_empty() {
1037                        format!("Extra space after closing tag in decomposition: '{tag_full}'")
1038                    } else {
1039                        format!("Extra space before '{first_token}' in decomposition: '{full_sample}'")
1040                    },
1041                    Some(
1042                        "Decomposition tags must be followed immediately by target without spaces (e.g. '<tag>{token}')",
1043                    ),
1044                );
1045                let trimmed_payload = payload.trim_start();
1046                let corrected = format!("{tag_full}{trimmed_payload}");
1047                parsed.decompositions.push(corrected);
1048            } else {
1049                parsed.decompositions.push(item_trimmed.to_string());
1050            }
1051
1052            if payload.trim().contains("  ") {
1053                report.add_error(
1054                    file_path,
1055                    Some(line_no),
1056                    Some(col_name),
1057                    format!(
1058                        "Multiple spaces between tokens in decomposition payload: '{tag_full}{payload}'"
1059                    ),
1060                    Some("Use single spaces between decomposition tokens"),
1061                );
1062            }
1063        } else {
1064            report.add_error(
1065                file_path,
1066                Some(line_no),
1067                Some(col_name),
1068                format!("Unclosed decomposition tag: '{item_trimmed}'"),
1069                Some("Close tag with '>'"),
1070            );
1071            parsed.decompositions.push(item_trimmed.to_string());
1072        }
1073    } else {
1074        // Bare item without a prefix/directive
1075        if is_format_table {
1076            report.add_error(
1077                file_path,
1078                Some(line_no),
1079                Some(col_name),
1080                format!("Bare base format '{item_trimmed}' is disallowed in format tables. Use '@implies(...)', '@based_on(...)', or appropriate directive instead"),
1081                Some("Wrap format references in '@implies(shorthand)' (e.g. '@implies(f271)') or '@based_on(shorthand)' (e.g. '@based_on(f580)')"),
1082            );
1083            parsed.based_on.push(item_trimmed.to_string());
1084        } else {
1085            if item_trimmed.contains("  ") {
1086                report.add_error(
1087                    file_path,
1088                    Some(line_no),
1089                    Some(col_name),
1090                    format!(
1091                        "Multiple consecutive spaces in alias: '{item_trimmed}'"
1092                    ),
1093                    Some("Use single spaces between words in aliases"),
1094                );
1095            }
1096            parsed.aliases.push(item_trimmed.to_string());
1097        }
1098    }
1099}
1100
1101/// Validates that tokens in an `@implies(...)` or `@based_on(...)` expression conform to Dc shorthand syntax,
1102/// or (for `@implies`) a bracketed Dc syntax construct (e.g. `@implies([identifier:Routine])`).
1103fn validate_shorthand_expr(
1104    expr: &str,
1105    file_path: &str,
1106    line_no: usize,
1107    report: &mut ValidationReport,
1108    col_name: &str,
1109    directive_name: &str,
1110) {
1111    let trimmed = expr.trim();
1112    if directive_name == "@implies"
1113        && trimmed.starts_with('[')
1114        && trimmed.ends_with(']')
1115    {
1116        if let Err(e) = crate::syntax::parse_dc_syntax(&format!(":{trimmed}")) {
1117            report.add_error(
1118                file_path,
1119                Some(line_no),
1120                Some(col_name),
1121                format!("Invalid syntax construct '{trimmed}' in '@implies({expr})': {e}"),
1122                Some("Ensure bracketed expression inside '@implies([...])' is valid Dc syntax"),
1123            );
1124        }
1125        return;
1126    }
1127
1128    // Split by operational delimiters &, |, (, ) to validate atomic identifiers
1129    for token in expr
1130        .split(['&', '|', '(', ')'])
1131        .map(str::trim)
1132        .filter(|t| !t.is_empty())
1133    {
1134        if !is_valid_shorthand(token) {
1135            report.add_error(
1136                file_path,
1137                Some(line_no),
1138                Some(col_name),
1139                format!(
1140                    "Invalid Dc shorthand token '{token}' in '{directive_name}({expr})'. Must use format shorthands (e.g. 'f161')"
1141                ),
1142                Some("Ensure all format references inside directive use Dc shorthand syntax"),
1143            );
1144        }
1145    }
1146}
1147
1148#[cfg(test)]
1149#[allow(
1150    clippy::panic,
1151    clippy::expect_used,
1152    clippy::unwrap_used,
1153    clippy::unwrap_in_result,
1154    clippy::panic_in_result_fn,
1155    clippy::indexing_slicing,
1156    clippy::arithmetic_side_effects,
1157    reason = "Standard repository test boilerplate"
1158)]
1159mod tests {
1160    use super::*;
1161
1162    #[crate::ctb_test]
1163    fn test_parse_aliases_or_base_column_directives() {
1164        let mut report = ValidationReport::new();
1165        let parsed = parse_aliases_or_base_column(
1166            "@based_on(f580), @implies(f398), @chain(f161 > f35)",
1167            "test.csv",
1168            1,
1169            &mut report,
1170            true,
1171        );
1172        assert!(
1173            !report.has_errors(),
1174            "Report errors: {}",
1175            report.format_report()
1176        );
1177        assert_eq!(parsed.based_on, vec!["f580"]);
1178        assert_eq!(parsed.implies, vec!["f398"]);
1179        assert_eq!(
1180            parsed.format_spec_raw.as_deref(),
1181            Some("@chain(f161 > f35)")
1182        );
1183    }
1184
1185    #[crate::ctb_test]
1186    fn test_legacy_base_directive_fails_validation() {
1187        let mut report = ValidationReport::new();
1188        let _ = parse_aliases_or_base_column(
1189            "@base(f161)",
1190            "test.csv",
1191            1,
1192            &mut report,
1193            true,
1194        );
1195        assert!(report.has_errors());
1196        let err = report.format_report();
1197        assert!(
1198            err.contains("Directive '@base(...)' is deprecated and ambiguous")
1199        );
1200    }
1201
1202    #[crate::ctb_test]
1203    fn test_bare_base_in_format_table_fails_validation() {
1204        let mut report = ValidationReport::new();
1205        let _ = parse_aliases_or_base_column(
1206            "Tar, @chain(f161 > f35)",
1207            "test.csv",
1208            1,
1209            &mut report,
1210            true,
1211        );
1212        assert!(report.has_errors());
1213        let err = report.format_report();
1214        assert!(
1215            err.contains(
1216                "Bare base format 'Tar' is disallowed in format tables"
1217            )
1218        );
1219    }
1220
1221    #[crate::ctb_test]
1222    fn test_bare_alias_in_character_table_succeeds() {
1223        let mut report = ValidationReport::new();
1224        let parsed = parse_aliases_or_base_column(
1225            "dot, point, >32, <approx>u2e",
1226            "test.csv",
1227            1,
1228            &mut report,
1229            false,
1230        );
1231        assert!(
1232            !report.has_errors(),
1233            "Report errors: {}",
1234            report.format_report()
1235        );
1236        assert_eq!(parsed.aliases, vec!["dot", "point"]);
1237        assert_eq!(parsed.cross_references, vec![">32"]);
1238        assert_eq!(parsed.decompositions, vec!["<approx>u2e"]);
1239    }
1240
1241    #[crate::ctb_test]
1242    fn test_parse_formal_aliases_xrefs_and_annotations() {
1243        let mut report = ValidationReport::new();
1244        let parsed = parse_aliases_or_base_column(
1245            r#"@formalAliasCorrection("PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET"), @formalAliasAbbreviation("NUL"), @xref(u22ee), @annotation("misspelling of \"BRACKET\" in character name is a known defect"), @annotation("German, note with comma")"#,
1246            "test.csv",
1247            1,
1248            &mut report,
1249            false,
1250        );
1251        assert!(
1252            !report.has_errors(),
1253            "Report errors: {}",
1254            report.format_report()
1255        );
1256        assert_eq!(
1257            parsed.formal_aliases,
1258            vec![
1259                ParsedFormalAlias {
1260                    kind: "Correction".to_string(),
1261                    alias: "PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET".to_string(),
1262                },
1263                ParsedFormalAlias {
1264                    kind: "Abbreviation".to_string(),
1265                    alias: "NUL".to_string(),
1266                }
1267            ]
1268        );
1269        assert_eq!(parsed.cross_references, vec!["u22ee"]);
1270        assert_eq!(
1271            parsed.annotations,
1272            vec![
1273                "misspelling of \"BRACKET\" in character name is a known defect",
1274                "German, note with comma",
1275            ]
1276        );
1277    }
1278
1279    #[crate::ctb_test]
1280    fn test_parse_ident_and_nick_directives() {
1281        let mut report = ValidationReport::default();
1282        let parsed = parse_aliases_or_base_column(
1283            r#"@ident("TarGz"), @nick("tgz"), @nick("tar-gz"), @based_on(f161)"#,
1284            "test_format.csv",
1285            1,
1286            &mut report,
1287            true,
1288        );
1289        assert!(!report.has_errors(), "Errors: {}", report.format_report());
1290        assert_eq!(parsed.rust_ident.as_deref(), Some("TarGz"));
1291        assert_eq!(parsed.nicknames, vec!["tgz", "tar-gz"]);
1292        assert_eq!(parsed.based_on, vec!["f161"]);
1293
1294        // Test invalid ident fails validation
1295        let mut err_report = ValidationReport::default();
1296        let _ = parse_aliases_or_base_column(
1297            r#"@ident("123Invalid")"#,
1298            "test_format.csv",
1299            1,
1300            &mut err_report,
1301            true,
1302        );
1303        assert!(err_report.has_errors());
1304        assert!(
1305            err_report
1306                .format_report()
1307                .contains("Invalid Rust identifier")
1308        );
1309    }
1310
1311    #[crate::ctb_test]
1312    fn test_parse_os_directive() {
1313        let mut report = ValidationReport::default();
1314        let parsed = parse_aliases_or_base_column(
1315            r"@os(f405), @os(f406), @implies(f161)",
1316            "test_format.csv",
1317            1,
1318            &mut report,
1319            true,
1320        );
1321        assert!(!report.has_errors(), "Errors: {}", report.format_report());
1322        assert_eq!(parsed.os_associations, vec!["f405", "f406"]);
1323        assert_eq!(parsed.implies, vec!["f161"]);
1324
1325        // Test invalid OS token (non-shorthand text like "macos" is disallowed)
1326        let mut err_report = ValidationReport::default();
1327        let _ = parse_aliases_or_base_column(
1328            r"@os(macos)",
1329            "test_format.csv",
1330            1,
1331            &mut err_report,
1332            true,
1333        );
1334        assert!(err_report.has_errors());
1335        assert!(
1336            err_report
1337                .format_report()
1338                .contains("Invalid format shorthand 'macos' in '@os(...)'")
1339        );
1340    }
1341
1342    #[crate::ctb_test]
1343    fn test_parse_title_directive() {
1344        let mut report = ValidationReport::default();
1345        let parsed = parse_aliases_or_base_column(
1346            r#"@title("GNU/Linux"), @implies(f390)"#,
1347            "test_format.csv",
1348            1,
1349            &mut report,
1350            true,
1351        );
1352        assert!(!report.has_errors(), "Errors: {}", report.format_report());
1353        assert_eq!(parsed.title.as_deref(), Some("GNU/Linux"));
1354        assert_eq!(parsed.implies, vec!["f390"]);
1355
1356        // Test empty title
1357        let mut err_report = ValidationReport::default();
1358        let _ = parse_aliases_or_base_column(
1359            r#"@title("")"#,
1360            "test_format.csv",
1361            1,
1362            &mut err_report,
1363            true,
1364        );
1365        assert!(err_report.has_errors());
1366        assert!(err_report.format_report().contains("Empty '@title()'"));
1367
1368        // Test duplicate title
1369        let mut dup_report = ValidationReport::default();
1370        let _ = parse_aliases_or_base_column(
1371            r#"@title("First"), @title("Second")"#,
1372            "test_format.csv",
1373            1,
1374            &mut dup_report,
1375            true,
1376        );
1377        assert!(dup_report.has_errors());
1378        assert!(dup_report.format_report().contains("Duplicate '@title()'"));
1379    }
1380
1381    #[crate::ctb_test]
1382    fn test_parse_vary_as_and_varies_directives() {
1383        let mut report = ValidationReport::new();
1384        let parsed = parse_aliases_or_base_column(
1385            r#"@vary_as("radix"), @varies(f354, f355)"#,
1386            "test_format.csv",
1387            1,
1388            &mut report,
1389            true,
1390        );
1391        assert!(
1392            !report.has_errors(),
1393            "Report errors: {}",
1394            report.format_report()
1395        );
1396        assert_eq!(parsed.vary_as.as_deref(), Some("radix"));
1397        assert_eq!(
1398            parsed.varies,
1399            vec![
1400                ctb_storage_minimal::shorthand::DcShorthand::Format(354),
1401                ctb_storage_minimal::shorthand::DcShorthand::Format(355),
1402            ]
1403        );
1404    }
1405
1406    #[crate::ctb_test]
1407    fn test_parse_magic_name_directive() {
1408        let mut report = ValidationReport::new();
1409        let parsed = parse_aliases_or_base_column(
1410            r#"@magic_name("SCO compress -H (LZH) data"), @magic_name("compacted data")"#,
1411            "test_format.csv",
1412            1,
1413            &mut report,
1414            true,
1415        );
1416        assert!(
1417            !report.has_errors(),
1418            "Report errors: {}",
1419            report.format_report()
1420        );
1421        assert_eq!(
1422            parsed.magic_names,
1423            vec!["SCO compress -H (LZH) data", "compacted data"]
1424        );
1425
1426        let mut err_report = ValidationReport::new();
1427        let _ = parse_aliases_or_base_column(
1428            r#"@magic_name("")"#,
1429            "test_format.csv",
1430            1,
1431            &mut err_report,
1432            true,
1433        );
1434        assert!(err_report.has_errors());
1435        assert!(err_report.format_report().contains("Empty '@magic_name()'"));
1436    }
1437
1438    #[crate::ctb_test]
1439    fn test_parse_stable_ident_directive() {
1440        let mut report = ValidationReport::new();
1441        let parsed = parse_aliases_or_base_column(
1442            r#"@ident("Natural1"), @stable_ident()"#,
1443            "test_category.csv",
1444            1,
1445            &mut report,
1446            false,
1447        );
1448        assert!(
1449            !report.has_errors(),
1450            "Report errors: {}",
1451            report.format_report()
1452        );
1453        assert!(parsed.stable_ident);
1454        assert_eq!(parsed.rust_ident.as_deref(), Some("Natural1"));
1455
1456        let mut err_report = ValidationReport::new();
1457        let parsed_err = parse_aliases_or_base_column(
1458            r#"@ident("Natural1"), @stable_ident(foo)"#,
1459            "test_category.csv",
1460            1,
1461            &mut err_report,
1462            false,
1463        );
1464        assert!(err_report.has_errors());
1465        assert!(
1466            err_report
1467                .format_report()
1468                .contains("Malformed '@stable_ident()'")
1469        );
1470        assert!(parsed_err.stable_ident);
1471    }
1472}