cpp_code_analysis 0.4.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
//! # Rendering a declaration
//!
//! **The hover card's code block is generated, never sliced.** A declaration's own text is the wrong thing to show: it
//! carries the vendor's macro noise (`& _CLR_OR_THIS_CALL read(…)`), the line breaks the file happened to use, and the
//! spelling of one particular declaration rather than the shape of the thing. So every character here comes from the
//! analysis's model — [`Type`]s printed by their own writer, parameters parsed out of the recorded list, the template
//! head built from the declaration's parameters — and this module is the **only** place the hover's code block is
//! composed.
//!
//! # What a reconstructed line looks like
//!
//! ```text
//!   template <class _Tp, class _Alloc = std::allocator<_Tp>>
//!   void push_back(const _Tp& __x)
//!
//!   template <class _Kty, class _Ty>
//!   class map
//!
//!   using size_type = std::size_t;
//!   static constexpr int kWidth = …;
//!   enum class Color
//! ```
//!
//! The shape is rust-analyzer's: the item alone, one line where it fits, the template head above it, and no body. What
//! differs is what C++ a reader needs and Rust has no equivalent for — the trailing `const`/`&`/`&&` that tells two
//! overloads apart, `= …` for a defaulted argument, and the template head's kinds (`class`/`typename`/a non-type type),
//! which the syntax supplies when the declaring file is at hand.
//!
//! # What is *not* rendered
//!
//! A **body**, an **initializer** (beyond a constant whose value the analysis folded), and a **(doc) comment**: the first
//! two are not the interface, and the third is documentation, which [`crate::sema::documentation`] formats elsewhere.
//! Interpolation is the rule for everything else: a type the index could not resolve is printed as the name that was
//! written, because that is the model's honest answer and not a copy of the line.

use cpp_parser::CppAstNode;
use cpp_parser::{CppDeclaration, CppSyntaxNode, CppTemplateDecl};

use crate::sema::types::parse_type_spelling;
use crate::{DeclFact, DeclKind, DeclModifiers};

/// **One parameter of a function, rebuilt** — its type as the model prints it, its own name, and whether it has a
/// default argument.
///
/// The default's **value** is not kept: it is an expression in the declaration's text, and a signature is about what can
/// be written at a call, which is "this parameter may be left off". [`Parameter::default`] is `Some` exactly then, and
/// the *rendering* is `= …` (or the name, when the declaration wrote one, because `npos` is what a reader recognises).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Parameter {
    pub ty: String,
    pub name: Option<String>,
    pub default: Option<String>,
    pub variadic: bool,
}

impl Parameter {
    fn said(&self) -> String {
        if self.variadic && self.ty.is_empty() {
            return "...".to_string();
        }
        let mut out = self.ty.clone();
        if let Some(name) = &self.name {
            if !out.is_empty() {
                out.push(' ');
            }
            out.push_str(name);
        }
        if let Some(default) = &self.default {
            out.push_str(" = ");
            out.push_str(default);
        }
        out
    }
}

/// **A template parameter, as the head writes it** — `class T`, `typename T = int`, `int N`, `class... Args`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateParameter {
    /// `class`, `typename`, or the written type of a non-type parameter (`int`, `std::size_t`).
    pub keyword: String,
    pub name: String,
    pub default: Option<String>,
    pub pack: bool,
    /// A non-type parameter's type is a type; a type parameter's keyword is not.
    pub is_type: bool,
}

/// **The declaration's line, or lines, rebuilt** — the code block a hover shows.
///
/// `syntax` is the declaration's own node when the declaring file is at hand. It supplies the three things a fact does
/// not record: whether the class was written `class`, `struct` or `union` (and whether an enum is scoped), the kinds of
/// a template head's parameters, and the access of a base. Without it the rendering is still complete for everything
/// whose facts carry the answer, and a class whose keyword is unknown is rendered by name alone rather than guessed at.
///
/// `value` is a constant the analysis folded — an enumerator's number, a `constexpr` initializer — and is shown only
/// where it is part of what the name *is*.
pub fn an_item(
    fact: &DeclFact,
    syntax: Option<&CppDeclaration>,
    value: Option<i64>,
) -> Vec<String> {
    let mut lines = Vec::new();
    // **A reflection annotation is part of the declaration**, not decoration around it: `UCLASS(Blueprintable)` is what
    // makes an Unreal class a class as far as the engine is concerned, and the fact records the macro and its arguments.
    // Rendered as `NAME(arg, arg)` from those parts — generated, like everything else in this block.
    if let Some(reflection) = &fact.reflection() {
        lines.push(reflection.said());
    }
    if let Some(head) = a_template_head(fact, syntax) {
        lines.push(head);
        // **A constrained variable template writes its clause under the head**, and the card used to drop it:
        //
        // ```cpp
        // template <typename T>
        //     requires std::copyable<T>
        // constexpr bool copyable_v = true;
        // ```
        //
        // reported from `concepts.cpp:67` as "copyable_v 缺少 requires 相关的渲染". A *function's* clause is part of its
        // signature (`a_function` prints it after the parameter list, where the language writes it), so it is not
        // repeated here — only the kinds whose signature has no place for one get the line.
        if !matches!(fact.kind, DeclKind::Function)
            && let Some(clause) = fact
                .requires_clause()
                .filter(|clause| !clause.trim().is_empty())
                .filter(|clause| !clause.trim().is_empty())
        {
            lines.push(clause.to_string());
        }
    }
    lines.push(a_line(fact, syntax, value));
    lines
}

/// **The declaration's own line**, without a template head — what an overload list prints per declaration.
pub fn a_line(fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option<i64>) -> String {
    match fact.kind {
        DeclKind::Function => a_function(fact),
        DeclKind::Type if fact.type_of.is_some() => {
            format!(
                "using {} = {};",
                fact.name,
                a_type_with_its_written_qualifiers(
                    fact.type_of.as_deref().unwrap_or(""),
                    the_written_qualifiers(syntax),
                )
            )
        }
        DeclKind::Type => a_class(fact, syntax),
        DeclKind::Variable => a_variable(fact, value, syntax),
        DeclKind::Namespace => match &fact.type_of {
            Some(target) => format!("namespace {} = {target}", fact.name),
            None => format!("namespace {}", fact.name),
        },
        DeclKind::MacroLike | DeclKind::Other => a_variable(fact, value, syntax),
    }
}

/// **The `template <…>` line**, when this declaration is itself the template.
///
/// A **member** of a class template carries the class's parameter names in [`DeclFact::parameters`] — the member-list
/// builder puts them there so a use's arguments can be paired — and they are not the member's own: printing them said
/// "`std::pair::second` — a variable template over `_T1`, `_T2`". So the head is rendered only when the declaration is
/// the template, which the fact says by having **no scope** (a template at file or namespace scope) and the syntax says
/// exactly (a `TemplateDecl` child).
///
/// The kinds (`class` vs `typename` vs a non-type type) and the defaults are the syntax's where it is present; the fact's
/// `parameters`/`parameter_defaults` cover the rest, with `class` as the keyword — the standard spelling for a type
/// parameter, and the only one a fact cannot distinguish.
fn a_template_head(fact: &DeclFact, syntax: Option<&CppDeclaration>) -> Option<String> {
    if let Some(syntax) = syntax
        && let Some(head) = syntax.child::<CppTemplateDecl>()
        && let Some(list) = head.get_param_list()
    {
        let parameters: Vec<TemplateParameter> = list
            .get_params()
            .map(|parameter| a_template_parameter(&parameter))
            .collect();
        if !parameters.is_empty() {
            return Some(a_head(&parameters));
        }
    }
    // **The fact's own parameters, and only when the declaration is the template.** A member of a class template has
    // them too, which is why the scope decides — see this function's documentation.
    if fact.scope.is_some() || fact.parameters().is_empty() {
        return None;
    }
    let parameters: Vec<TemplateParameter> = fact
        .parameters()
        .iter()
        .enumerate()
        .filter(|(_, name)| !name.is_empty())
        .map(|(at, name)| TemplateParameter {
            keyword: "class".to_string(),
            name: name.clone(),
            default: fact
                .parameter_defaults()
                .get(at)
                .filter(|default| !default.trim().is_empty())
                .map(|default| a_default(default)),
            pack: false,
            is_type: true,
        })
        .collect();
    (!parameters.is_empty()).then(|| a_head(&parameters))
}

fn a_head(parameters: &[TemplateParameter]) -> String {
    let said: Vec<String> = parameters.iter().map(a_template_parameter_said).collect();
    format!("template <{}>", said.join(", "))
}

fn a_template_parameter_said(parameter: &TemplateParameter) -> String {
    let mut out = parameter.keyword.clone();
    if parameter.pack {
        out.push_str("...");
    }
    if !parameter.name.is_empty() {
        out.push(' ');
        out.push_str(&parameter.name);
    }
    if let Some(default) = &parameter.default {
        out.push_str(" = ");
        out.push_str(default);
    }
    out
}

/// One template parameter, read from the syntax — the only place its **kind** is written.
fn a_template_parameter(parameter: &cpp_parser::CppTemplateParam) -> TemplateParameter {
    let written = parameter.syntax().text().to_string();
    let name = parameter
        .get_name()
        .map(|name| name.get_name_text().to_string())
        .unwrap_or_default();
    // **The default, at a top-level `=`.** `class A = std::array<int, 3>` has a bracket pair and a comma in its
    // default; splitting at the first `=` byte works for it and would not for a parameter whose *name* is followed by
    // `=` inside a template argument.
    let (declared, default) = match split_at_a_top_level_default(&written) {
        Some((declared, default)) => (declared, Some(a_default(default))),
        None => (written.as_str(), None),
    };
    let declared = declared.trim_end();
    let pack = declared.contains("...");
    let is_type = parameter.is_type_param();
    let keyword = if is_type {
        // `class` and `typename` mean the same thing; the declaration's own word is kept when it has one.
        if declared.trim_start().starts_with("typename") {
            "typename".to_string()
        } else {
            "class".to_string()
        }
    } else {
        // A non-type parameter: what stands before the name is its type, rendered canonically.
        let before_the_name = match declared.find(&name) {
            Some(at) if !name.is_empty() => &declared[..at],
            _ => declared,
        };
        // **The pack's dots are the head's, not the type's.** `char... Digits` writes `...` before the name, and
        // `pack` puts them back once — keeping them in the keyword rendered `char......`.
        a_type(before_the_name.trim_end().trim_end_matches('.').trim_end())
    };
    TemplateParameter {
        keyword,
        name,
        default,
        pack,
        is_type,
    }
}

/// **A function or method**, rebuilt: `static constexpr int f(const T& value) const & noexcept`.
fn a_function(fact: &DeclFact) -> String {
    let mut out = String::new();
    for (bit, word) in [
        (DeclModifiers::STATIC, "static "),
        (DeclModifiers::INLINE, "inline "),
        (DeclModifiers::CONSTEXPR, "constexpr "),
        (DeclModifiers::CONSTEVAL, "consteval "),
        (DeclModifiers::CONSTINIT, "constinit "),
        (DeclModifiers::VIRTUAL, "virtual "),
        (DeclModifiers::EXPLICIT, "explicit "),
    ] {
        if fact.modifiers.bits() & bit.bits() != 0 {
            out.push_str(word);
        }
    }
    if let Some(returns) = fact
        .returns
        .as_deref()
        .filter(|returns| !returns.trim().is_empty())
    {
        out.push_str(&a_type(returns));
        out.push(' ');
    }
    out.push_str(&fact.name);
    match fact.parameter_list() {
        Some(list) => {
            let parameters: Vec<String> = parameters(list).iter().map(Parameter::said).collect();
            out.push('(');
            out.push_str(&parameters.join(", "));
            out.push(')');
        }
        // **A function with no recorded list is still a function**: the parentheses and an ellipsis say "there are
        // parameters this build did not read", rather than printing a name that looks like a variable.
        None => out.push_str("(…)"),
    }
    out.push_str(&a_trailing(fact));
    out
}

/// **What a function writes after its parameter list** — the half that tells two overloads apart.
fn a_trailing(fact: &DeclFact) -> String {
    let mut out = String::new();
    for (bit, word) in [
        (DeclModifiers::CONST, " const"),
        (DeclModifiers::VOLATILE, " volatile"),
        (DeclModifiers::RVALUE_REFERENCE, " &&"),
        (DeclModifiers::LVALUE_REFERENCE, " &"),
        (DeclModifiers::OVERRIDE, " override"),
        (DeclModifiers::FINAL, " final"),
    ] {
        if fact.modifiers.bits() & bit.bits() != 0 {
            out.push_str(word);
        }
    }
    if fact.modifiers.bits() & DeclModifiers::DELETED.bits() != 0 {
        out.push_str(" = delete");
    } else if fact.modifiers.bits() & DeclModifiers::DEFAULTED.bits() != 0 {
        out.push_str(" = default");
    }
    if let Some(clause) = fact
        .requires_clause()
        .filter(|clause| !clause.trim().is_empty())
    {
        // **The clause is stored as the file wrote it, keyword included** — `requires (x > 0)`,
        // `requires requires { fn(1); }` — so the renderer must not add a second keyword: measured, every constrained
        // declaration's card read `requires requires (sizeof(T) > 2)`, and the nested form read
        // `requires requires requires { fn(1); }`. A clause stored without the keyword (a hand-built fact in a test)
        // still gets one, which is why the check is on the text and not on a flag.
        out.push(' ');
        if !clause.trim_start().starts_with("requires") {
            out.push_str("requires ");
        }
        out.push_str(clause.trim());
    }
    out
}

/// **A class, struct, union or enum** — the keyword from the syntax, and the bases by name.
fn a_class(fact: &DeclFact, syntax: Option<&CppDeclaration>) -> String {
    let keyword = syntax.and_then(a_class_keyword);
    let mut out = String::new();
    // **No keyword, no guess.** A fact records `Type` and not which word introduced it, and printing `class` for a
    // `struct` would be a guess dressed as a fact. Without the declaring file the name alone is what is known.
    if let Some(keyword) = keyword {
        out.push_str(&keyword);
        out.push(' ');
    }
    out.push_str(&fact.name);
    let bases: Vec<String> = fact
        .bases()
        .iter()
        .filter(|base| !base.trim().is_empty())
        .map(|base| a_type(base))
        .collect();
    if !bases.is_empty() {
        out.push_str(" : ");
        out.push_str(&bases.join(", "));
    }
    out
}

/// The keyword a class-like definition was written with, from its own syntax — `class shared_ptr`, `struct S`,
/// `union U`, `enum class Color`.
fn a_class_keyword(declaration: &CppDeclaration) -> Option<String> {
    // **The node kind is the keyword.** A class-like definition has one of three syntax kinds, and the parser chose it
    // from the word the file wrote — so this is the fact, not a guess.
    if let Some(class) = declaration.get_class_def() {
        return Some(
            match (class.is_struct(), class.is_union()) {
                (true, _) => "struct",
                (_, true) => "union",
                _ => "class",
            }
            .to_string(),
        );
    }
    if let Some(enumeration) = declaration.get_enum_def() {
        return Some(match enumeration.is_scoped() {
            true => "enum class".to_string(),
            false => "enum".to_string(),
        });
    }
    None
}

/// **A variable, a constant or an enumerator.**
///
/// The initializer is not part of the interface, so it is not shown; the **value** is when the analysis folded one,
/// because for an enumerator (`Red = 3`) or a `constexpr` constant the number *is* what the name means.
fn a_variable(fact: &DeclFact, value: Option<i64>, syntax: Option<&CppDeclaration>) -> String {
    let mut out = String::new();
    for (bit, word) in [
        (DeclModifiers::STATIC, "static "),
        (DeclModifiers::INLINE, "inline "),
        (DeclModifiers::CONSTEXPR, "constexpr "),
        (DeclModifiers::CONSTEVAL, "consteval "),
    ] {
        if fact.modifiers.bits() & bit.bits() != 0 {
            out.push_str(word);
        }
    }
    if let Some(ty) = fact.type_of.as_deref().filter(|ty| !ty.trim().is_empty()) {
        // **The qualifiers the fact drops.** `declared_type_of` strips `const` and `volatile` on purpose — it is a
        // spelling to look a class up by, and a qualifier changes nothing about which class that is — so
        // `static const Widget* first` recorded `Widget*`. A card that hides `const` tells the reader the variable may be
        // written through, which is the one thing it may not. The syntax still has them, so they are read from the
        // declaration's own specifier sequence; a `Foo* const p` writes its `const` in the declarator, where it
        // qualifies the pointer and not the type named here.
        out.push_str(&a_type_with_its_written_qualifiers(
            ty,
            the_written_qualifiers(syntax),
        ));
        out.push(' ');
    }
    out.push_str(&fact.name);
    if let Some(value) = value {
        out.push_str(&format!(" = {value}"));
    }
    out
}

/// **`const ` and `volatile ` as the declaration wrote them**, from its specifier sequence — `""` when there are none or
/// the declaration's syntax is not at hand.
fn the_written_qualifiers(syntax: Option<&CppDeclaration>) -> &'static str {
    the_qualifiers_in(
        syntax
            .map(|declaration| declaration.syntax())
            .map(|syntax| syntax as &CppSyntaxNode),
    )
}

/// **[`the_written_qualifiers`] for any node that carries a specifier sequence** — a `Declaration` or a `Parameter`.
///
/// A parameter is the case the declaration union does not cover: `[](auto const& value)` keeps its `const` in the
/// parameter's own `DeclSpecifierSeq`, and the nearest `CppDeclaration` above it is the function, whose specifiers say
/// nothing about the parameter. Measured: the card printed `auto& value`, and the operator's card printed
/// `std::string& left` for `std::string const& left`.
pub fn the_qualifiers_of_node(syntax: Option<&CppSyntaxNode>) -> &'static str {
    the_qualifiers_in(syntax)
}

fn the_qualifiers_in(syntax: Option<&CppSyntaxNode>) -> &'static str {
    let specifiers = syntax.and_then(|syntax| {
        syntax
            .children()
            .find(|child| {
                cpp_parser::CppSyntaxKind::from(child.kind())
                    == cpp_parser::CppSyntaxKind::DeclSpecifierSeq
            })
            .and_then(cpp_parser::CppDeclSpecifierSeq::cast)
    });
    let Some(specifiers) = specifiers else {
        return "";
    };
    use cpp_parser::CppTokenKind;
    let volatile = specifiers.has_keyword(CppTokenKind::VolatileKeyword);
    let constant = specifiers.has_keyword(CppTokenKind::ConstKeyword);
    match (constant, volatile) {
        (true, true) => "const volatile ",
        (true, false) => "const ",
        (false, true) => "volatile ",
        (false, false) => "",
    }
}

/// **A type, as the model writes it** — parsed from the recorded spelling and printed by [`Type`]'s own writer, which is
/// what turns `std::vector<std::string> &` into `std::vector<std::string>&` and drops the `typename` disambiguator.
///
/// The spelling is the *input*; the output is generated. A spelling this layer cannot parse is printed back as a name,
/// which is the model's answer for a type it does not model — not a copy of the declaration.
///
/// **[`a_type`], with the qualifiers the declaration wrote in front of it** — and never twice.
///
/// A declaration's recorded type now carries its **leading `const`** (`static constexpr const char* Name` records
/// `const char*`, not `char*` — see `read_specifiers_named`), and the *syntax* still has the same word. Printing both
/// gave `const const Widget*` and `using Name = const const char*`, which is what `a_variable_keeps_its_qualifiers`
/// and `an_alias_is_a_using_line` caught. `volatile` is still only in the syntax, so it is still prepended here.
pub fn a_type_with_its_written_qualifiers(written: &str, qualifiers: &str) -> String {
    let printed = a_type(written);
    let qualifiers = qualifiers.trim();
    if qualifiers.is_empty() {
        return printed;
    }
    let mut missing: Vec<&str> = Vec::new();
    for word in qualifiers.split_whitespace() {
        if !printed.starts_with(word) {
            missing.push(word);
        }
    }
    match missing.is_empty() {
        true => printed,
        false => format!("{} {printed}", missing.join(" ")),
    }
}

/// **A type, as the model writes it** — see [`a_type`], which this function is the qualified form of.
pub fn a_type(written: &str) -> String {
    let written = written.trim();
    if written.is_empty() {
        return String::new();
    }
    // **The qualifiers are part of the spelling and the model does not carry them.** `Type` answers *which class* a
    // spelling names, so `const std::string&` is the same `Type` as `std::string&` — right for a member lookup, and
    // wrong for a popup, where the qualifier is the one word that says whether the object may be written through.
    // Measured on the reported screen: `[](auto const& value)` hovered as `auto& value`, and
    // `bool operator()(std::string const& left, …)` as `std::string& left`.
    //
    // Only a **top-level** qualifier is read here; a `const` inside a template argument (`std::vector<const int>`)
    // belongs to that argument and stays where it is written — see [`the_top_level_qualifiers`].
    let (qualifiers, core) = the_top_level_qualifiers(written);
    let printed = parse_type_spelling(&core).to_string();
    // **Not added twice.** The model keeps a *builtin*'s qualifier — `char*` is printed `const char*`, the one type it
    // normalises that way — so a qualifier the printed type already carries is left to it.
    if qualifiers.is_empty() || printed.starts_with("const") || printed.starts_with("volatile") {
        return printed;
    }
    format!("{qualifiers}{printed}")
}

/// **The `const`/`volatile` words written at the top level of a type spelling**, and what is left of it.
///
/// `std::string const&` and `const std::string&` are the same type, and both are written — so both are found and both
/// come back in front, where a reader expects them.
///
/// A qualifier **inside** a template argument is not one of these: `std::vector<const int>` holds `const int` as an
/// argument, and moving that word out would print `const std::vector<int>`, which is a different type. The depth
/// counter is what tells the two apart; `(`/`[` open a depth too, because a function's parameter list and an array
/// bound are the same shape.
fn the_top_level_qualifiers(written: &str) -> (String, String) {
    let mut qualifiers = String::new();
    let mut core = String::new();
    let mut depth = 0i32;
    let mut past_the_declarator = false;

    let push_to_core = |core: &mut String, text: &str, glue: bool| {
        if !glue
            && !core.is_empty()
            && !core.ends_with(|character: char| "<([:".contains(character))
        {
            core.push(' ');
        }
        core.push_str(text);
    };

    for word in written.split_whitespace() {
        // `const&` is one word: the qualifier and the reference that follows it, and the reference belongs to the type.
        let name_end = word
            .find(|character: char| {
                !(character.is_alphanumeric() || character == '_' || character == ':')
            })
            .unwrap_or(word.len());
        let (name, punctuation) = word.split_at(name_end);

        let opening = word
            .bytes()
            .filter(|byte| matches!(byte, b'<' | b'(' | b'['))
            .count() as i32;
        let closing = word
            .bytes()
            .filter(|byte| matches!(byte, b'>' | b')' | b']'))
            .count() as i32;

        if depth == 0 && !past_the_declarator && matches!(name, "const" | "volatile") {
            if !qualifiers.is_empty() {
                qualifiers.push(' ');
            }
            qualifiers.push_str(name);
            // The punctuation the word carried (`&`, `*`) is the type's, and it goes where it was — glued.
            if !punctuation.is_empty() {
                push_to_core(&mut core, punctuation, true);
            }
        } else {
            push_to_core(&mut core, word, false);
            // **A `const` after a `*` or a `&` qualifies the pointer, not the type** — `Foo* const p` says the *pointer*
            // cannot be reassigned, and a card that moved the word to the front would say the pointee cannot be
            // written through. Everything after the first declarator operator is left where it is written, which is
            // what the model's own `const char * const` → `const char*` already did.
            if word.contains('*') || word.contains('&') {
                past_the_declarator = true;
            }
        }
        depth += opening - closing;
    }

    (
        if qualifiers.is_empty() {
            String::new()
        } else {
            format!("{qualifiers} ")
        },
        core,
    )
}

/// **The parameters of a recorded `parameter_list`**, rebuilt — types canonical, names kept, defaults summarised.
///
/// The split is at a **top-level comma**: `std::pair<int, int>` is one parameter, `void (*cb)(int, int)` is one too. A
/// list whose parentheses do not balance answers what it could read, which is the conservative direction for a popup.
pub fn parameters(written: &str) -> Vec<Parameter> {
    let inner = written.trim();
    let inner = inner.strip_prefix('(').unwrap_or(inner);
    let inner = inner.strip_suffix(')').unwrap_or(inner);
    split_at_top_level_commas(inner)
        .into_iter()
        .map(|parameter| a_parameter(parameter.trim()))
        .collect()
}

fn a_parameter(written: &str) -> Parameter {
    if written.is_empty() {
        return Parameter {
            ty: String::new(),
            name: None,
            default: None,
            variadic: false,
        };
    }
    if written == "..." || written == "…" {
        return Parameter {
            ty: String::new(),
            name: None,
            default: None,
            variadic: true,
        };
    }
    // **The default, at a top-level `=`.** `operator=` and `==` are not defaults, and neither is a `=` inside a
    // template argument or a parenthesised expression.
    let (declared, default) = match split_at_a_top_level_default(written) {
        Some((declared, default)) => (declared, Some(a_default(default))),
        None => (written, None),
    };
    let declared = declared.trim();
    let (ty, name) = a_type_and_its_name(declared);
    Parameter {
        ty,
        name,
        default,
        variadic: false,
    }
}

/// **The last identifier of a parameter is its name**, unless it is a keyword or part of the type — `const char* const`
/// has none, `const _Tp& __x` has `__x`, and `int (*cb)(int)` has `cb`.
fn a_type_and_its_name(written: &str) -> (String, Option<String>) {
    // A function pointer's name is inside its parentheses: `int (*cb)(int)`.
    if let Some(name) = a_name_in_parentheses(written) {
        return (a_type(written), Some(name));
    }
    let words: Vec<(usize, &str)> = identifier_runs(written);
    let Some((at, last)) = words.last().copied() else {
        return (a_type(written), None);
    };
    if is_a_keyword(last) {
        return (a_type(written), None);
    }
    // **The name is a *declared* name**, so what follows it is nothing but punctuation the declarator may carry —
    // an array extent, a trailing qualifier — and what precedes it is a type, not another name (`ns::Widget` is a type
    // and `Widget` is its last segment, not a parameter name).
    let after = written[at + last.len()..].trim();
    let before = &written[..at];
    // **A space counts, and it is the ordinary case**: `int n` has `int ` before `n`, and a test that trimmed it away
    // found no name in the commonest parameter there is.
    let follows_a_type = before.ends_with(char::is_whitespace)
        || before.trim_end().ends_with(['*', '&', '>', ']', ')']);
    let is_not_qualified = !before.trim_end().ends_with("::");
    let is_a_declarator_end = after.is_empty() || after.starts_with('[');
    if follows_a_type && is_not_qualified && is_a_declarator_end {
        let ty = written[..at].trim();
        (a_type(ty), Some(last.to_string()))
    } else {
        (a_type(written), None)
    }
}

/// The name of a function-pointer parameter — the identifier inside `(* … )`.
fn a_name_in_parentheses(written: &str) -> Option<String> {
    let open = written.find("(*")?;
    let rest = &written[open + 2..];
    let close = rest.find(')')?;
    let inside = rest[..close].trim();
    let name = inside.trim_start_matches(['&', '*']).trim();
    (!name.is_empty()
        && name
            .chars()
            .all(|character| character.is_alphanumeric() || character == '_'))
    .then(|| name.to_string())
}

/// Every run of identifier characters, with its byte offset.
fn identifier_runs(written: &str) -> Vec<(usize, &str)> {
    let mut runs = Vec::new();
    let mut start = None;
    for (at, character) in written.char_indices() {
        match (character.is_alphanumeric() || character == '_', start) {
            (true, None) => start = Some(at),
            (false, Some(from)) => {
                runs.push((from, &written[from..at]));
                start = None;
            }
            _ => {}
        }
    }
    if let Some(from) = start {
        runs.push((from, &written[from..]));
    }
    runs
}

/// The words that cannot be a declared name — a parameter written `const char* const` has no name, and its last word
/// is a qualifier.
fn is_a_keyword(word: &str) -> bool {
    matches!(
        word,
        "const"
            | "volatile"
            | "constexpr"
            | "consteval"
            | "constinit"
            | "static"
            | "inline"
            | "mutable"
            | "unsigned"
            | "signed"
            | "long"
            | "short"
            | "int"
            | "char"
            | "float"
            | "double"
            | "void"
            | "bool"
            | "auto"
            | "struct"
            | "class"
            | "union"
            | "enum"
            | "typename"
    )
}

/// **A default argument, as the signature shows it** — the name or number the declaration wrote when it is a single
/// word (`npos`, `0`, `true`, `nullptr`), and `…` for an expression whose value is the initializer's business, not the
/// interface's.
fn a_default(written: &str) -> String {
    let written = written.trim();
    if written.is_empty() {
        return "…".to_string();
    }
    let single_word = written
        .chars()
        .all(|character| character.is_alphanumeric() || matches!(character, '_' | '.' | '+' | '-'));
    if single_word {
        return written.to_string();
    }
    "…".to_string()
}

/// **Split at top-level commas**, counting `<>`, `()` and `[]` as nesting — `std::map<int, int>, int` is two parameters
/// and `void (*)(int, int)` is one.
fn split_at_top_level_commas(written: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0i32;
    let mut start = 0usize;
    for (at, character) in written.char_indices() {
        match character {
            '<' | '(' | '[' => depth += 1,
            '>' | ')' | ']' => depth -= 1,
            ',' if depth == 0 => {
                parts.push(&written[start..at]);
                start = at + 1;
            }
            _ => {}
        }
    }
    parts.push(&written[start..]);
    parts
}

/// The default argument's `=`, at depth zero and not part of `==`, `<=`, `>=` or `!=`.
fn split_at_a_top_level_default(written: &str) -> Option<(&str, &str)> {
    let bytes = written.as_bytes();
    let mut depth = 0i32;
    for (at, byte) in bytes.iter().enumerate() {
        match byte {
            b'<' | b'(' | b'[' => depth += 1,
            b'>' | b')' | b']' => depth -= 1,
            b'=' if depth == 0 => {
                let before = written[..at].trim_end();
                let ends_with_operator = before.ends_with(['=', '!', '<', '>']);
                let starts_with_equals = bytes.get(at + 1) == Some(&b'=');
                if !ends_with_operator && !starts_with_equals {
                    return Some((&written[..at], &written[at + 1..]));
                }
            }
            _ => {}
        }
    }
    None
}

/// **An expanded specifier sequence, split into the attributes and the words.**
///
/// A macro before a declaration expands to that declaration's *specifiers*. The CUDA project's
/// `#define AI __inline__ __attribute__((always_inline))` and `#define FLAT AI __attribute__((cold))` make
/// `FLAT int f_flat(int x)` mean
///
/// ```text
/// __attribute__((always_inline)) __attribute__((cold))
/// inline int f_flat(int x)
/// ```
///
/// — the attributes above, the specifier words in front of the type. The split is:
///
/// * **attributes** — `__attribute__((…))`, `__declspec(…)`, `alignas(…)`, `__launch_bounds__(…)`, `__pragma(…)` and
///   `[[…]]`, each with its balanced group;
/// * **specifiers** — every other word, as written, except that `__inline__`, `__inline` and `__forceinline` are the
///   one specifier a reader knows as `inline`. A quoted string stays one word (`extern "C"`).
///
/// The hover puts the first line above the declaration and the second in front of its type, which is the form a
/// compiler's diagnostics print and the one the reporter of this defect wrote out.
pub fn attributes_and_specifiers(expanded: &str) -> (Vec<String>, Vec<String>) {
    let mut attributes = Vec::new();
    let mut specifiers = Vec::new();
    let mut rest = expanded.trim_start();
    while !rest.is_empty() {
        if rest.starts_with("[[") {
            // `[[nodiscard]]`, `[[deprecated("…")]]` — to the closing `]]`, which is the attribute's own end.
            let end = rest.find("]]").map_or(rest.len(), |end| end + 2);
            attributes.push(rest[..end].to_string());
            rest = rest[end..].trim_start();
            continue;
        }
        // **A quoted string is one word** — `extern "C"` names a linkage, not two specifiers.
        if rest.starts_with('"') || rest.starts_with('\'') {
            let quote = rest.chars().next().unwrap_or('"');
            let mut end = rest.len();
            let mut escaped = false;
            for (at, character) in rest.char_indices().skip(1) {
                if escaped {
                    escaped = false;
                    continue;
                }
                if character == '\\' {
                    escaped = true;
                    continue;
                }
                if character == quote {
                    end = at + character.len_utf8();
                    break;
                }
            }
            specifiers.push(rest[..end].to_string());
            rest = rest[end..].trim_start();
            continue;
        }
        let word_end = rest
            .find(|character: char| !(character.is_alphanumeric() || character == '_'))
            .unwrap_or(rest.len());
        if word_end == 0 {
            // A character that starts no word — a comma, a `*`: kept as a token so nothing is lost.
            let end = rest.chars().next().map_or(1, char::len_utf8);
            specifiers.push(rest[..end].to_string());
            rest = rest[end..].trim_start();
            continue;
        }
        let word = &rest[..word_end];
        let after = rest[word_end..].trim_start();
        let takes_a_group = matches!(
            word,
            "__attribute__"
                | "__attribute"
                | "__declspec"
                | "alignas"
                | "__launch_bounds__"
                | "__pragma"
        );
        if takes_a_group && after.starts_with('(') {
            let mut depth = 0i32;
            let mut close = None;
            for (at, character) in after.char_indices() {
                match character {
                    '(' => depth += 1,
                    ')' => {
                        depth -= 1;
                        if depth == 0 {
                            close = Some(at + 1);
                            break;
                        }
                    }
                    _ => {}
                }
            }
            let Some(close) = close else {
                // An unbalanced group is the rest of the text; the callers show it as written.
                attributes.push(rest.to_string());
                break;
            };
            attributes.push(format!("{word}{}", &after[..close]));
            rest = after[close..].trim_start();
            continue;
        }
        specifiers.push(match word {
            "__inline__" | "__inline" | "__forceinline" => "inline".to_string(),
            other => other.to_string(),
        });
        rest = after;
    }
    (attributes, specifiers)
}

#[cfg(test)]
mod tests {
    use super::*;
    use cpp_parser::{CppParser, ParserConfig};

    /// **The fact and the node of one declaration in `source`** — what a hover has when the declaring file is at hand.
    fn rendered(source: &str, name: &str) -> Vec<String> {
        let tree = CppParser::parse(source, ParserConfig::default());
        assert_eq!(tree.get_errors(), [], "the fixture must parse cleanly");
        let root = tree.get_red_root();
        let scopes = crate::sema::scopes::build_scopes(&root, &crate::NoMacroBodies);
        let (facts, _) = crate::sema::declarations::build_facts(
            &scopes,
            &crate::preprocess(source, tree.get_tokens()),
            &root,
            &[],
            true,
        );
        let fact = facts
            .iter()
            .find(|fact| fact.name == name)
            .unwrap_or_else(|| panic!("{name} must be a fact: {facts:?}"));
        // **The node at the name**, which is how the session finds it — a template's declaration starts at
        // `template`, and a class's fact starts at `class`, so a range match on the fact's start finds neither.
        let declaration =
            cpp_parser::token_at(&root, fact.name_range.start_offset).and_then(|token| {
                token
                    .parent_ancestors()
                    .find_map(cpp_parser::CppDeclaration::cast)
            });
        an_item(fact, declaration.as_ref(), None)
    }

    /// **A function is rebuilt**, not quoted: canonical types, the parameters' names kept, defaults said, and the
    /// trailing qualifiers that tell two overloads apart.
    #[test]
    fn a_function_is_rebuilt_from_its_facts() {
        let lines = rendered(
            "int total(const Widget& w, int scale = 2, ...) const &;\n",
            "total",
        );
        assert_eq!(
            lines,
            ["int total(const Widget& w, int scale = 2, ...) const &"]
        );
    }

    /// **A template head is the declaration's own**, with the kind and default the syntax writes.
    #[test]
    fn a_template_head_keeps_its_kinds_and_defaults() {
        let lines = rendered(
            "template <typename T, typename Alloc = std::allocator<T>>\nclass Box : public Base<T> { };\n",
            "Box",
        );
        assert_eq!(lines[0], "template <typename T, typename Alloc = …>");
        assert_eq!(lines[1], "class Box : Base<T>");
    }

    /// **A non-type parameter and a pack** are the two shapes a fact cannot describe — the syntax is what knows.
    #[test]
    fn a_non_type_parameter_and_a_pack_are_read_from_the_syntax() {
        let lines = rendered(
            "template <int N, char... Digits>\nconstexpr int count();\n",
            "count",
        );
        assert_eq!(lines[0], "template <int N, char... Digits>");
        assert_eq!(lines[1], "constexpr int count()");
    }

    /// **A class says which word introduced it**, because the node's kind is that word.
    #[test]
    fn a_class_says_its_own_keyword() {
        assert_eq!(rendered("struct S { };\n", "S")[0], "struct S");
        assert_eq!(rendered("union U { int a; };\n", "U")[0], "union U");
        assert_eq!(
            rendered("enum class Color { Red };\n", "Color")[0],
            "enum class Color"
        );
    }

    /// **An alias is a `using` line**, whatever the file wrote it as — the target rendered by the type writer.
    #[test]
    fn an_alias_is_a_using_line() {
        assert_eq!(
            rendered("using Size = unsigned long;\n", "Size"),
            ["using Size = unsigned long;"]
        );
        assert_eq!(
            rendered("typedef const char* Name;\n", "Name"),
            ["using Name = const char*;"]
        );
    }

    /// **A variable keeps its qualifiers and its type**, and shows a folded constant's value.
    #[test]
    fn a_variable_keeps_its_qualifiers() {
        assert_eq!(
            rendered("static const Widget* first;\n", "first"),
            ["static const Widget* first"]
        );
    }

    /// **A `const` written on a type is printed back**, whichever side of the name it is on.
    ///
    /// `Type` answers *which class* a spelling names, so `const std::string&` and `std::string&` are the same `Type` —
    /// correct for a member lookup and wrong for a popup, where the qualifier is the one word that says whether the
    /// object may be written through. Measured: `a_type("std::string const&")` printed `std::string&` and
    /// `a_type("auto const&")` printed `auto&`, which is how `[](auto const& value)` hovered as `auto& value` and
    /// `bool operator()(std::string const& left, …)` as `std::string& left`.
    ///
    /// Only a **top-level** qualifier moves: `std::vector<const int>&` keeps its argument as written, because
    /// `const int` there is part of the type argument and not a qualifier of the outer type.
    #[test]
    fn a_typed_qualifier_is_printed_back() {
        assert_eq!(a_type("std::string const&"), "const std::string&");
        assert_eq!(a_type("const std::string&"), "const std::string&");
        assert_eq!(a_type("auto const&"), "const auto&");
        assert_eq!(a_type("const volatile Widget*"), "const volatile Widget*");
        assert_eq!(
            a_type("std::vector<const int>&"),
            "std::vector<const int>&",
            "a qualifier inside a template argument is part of the argument"
        );
        assert_eq!(
            rendered("void f(std::string const& left);\n", "f"),
            ["void f(const std::string& left)"],
            "and a parameter list keeps it, which is where the report saw it lost"
        );
    }

    /// **A parameter list is parsed**, not sliced: names are dropped from types, defaults summarised, packs said once.
    #[test]
    fn a_parameter_list_is_parsed() {
        let parameters = parameters("(const std::map<int, int>& table, int n = npos, ...)");
        assert_eq!(
            parameters,
            [
                Parameter {
                    ty: "const std::map<int, int>&".to_string(),
                    name: Some("table".to_string()),
                    default: None,
                    variadic: false,
                },
                Parameter {
                    ty: "int".to_string(),
                    name: Some("n".to_string()),
                    default: Some("npos".to_string()),
                    variadic: false,
                },
                Parameter {
                    ty: String::new(),
                    name: None,
                    default: None,
                    variadic: true,
                },
            ]
        );
    }

    /// **A type is printed by the model**: `T &` is `T&`, `T* const` loses the qualifier that does not name a class,
    /// and the `typename` disambiguator is not part of a type.
    /// **A constrained function's card does not repeat the keyword** — the fact stores the clause as written.
    ///
    /// Measured before: `requires requires (sizeof(T) > 2)` for a simple constraint, and
    /// `requires requires requires { fn(1); }` for a nested requirement — the renderer added `requires ` in front of a
    /// clause that already began with it.
    #[test]
    fn a_constrained_function_does_not_repeat_its_keyword() {
        let lines = rendered(
            "template <typename T>\nvoid f(int x) requires (sizeof(T) > 2) {}\n",
            "f",
        );
        assert_eq!(
            lines,
            [
                "template <typename T>",
                "void f(int x) requires (sizeof(T) > 2)"
            ],
            "one keyword, as the file writes it"
        );

        let lines = rendered(
            "template <typename Fn>\nvoid g(Fn &&fn) requires requires { fn(1); } { fn(1); }\n",
            "g",
        );
        assert_eq!(
            lines,
            [
                "template <typename Fn>",
                "void g(Fn&& fn) requires requires { fn(1); }"
            ],
            "the nested requirement keeps both, and no third"
        );
    }

    #[test]
    fn a_type_is_printed_by_the_model() {
        assert_eq!(
            a_type("std::vector<std::string> &"),
            "std::vector<std::string>&"
        );
        // **The pointer's own `const` is part of the type.** It used to be printed as `const char*` — the word
        // dropped — and that is the same drop that made `const char*` and `char const*` two types and turned eight
        // correct calls in Lua 5.5.0 into findings (see `parse_type_spelling`). A `const`-qualified pointer is
        // spelled where it is written.
        assert_eq!(a_type("const char * const"), "const char* const");
        assert_eq!(a_type("char const*"), "const char*");
        assert_eq!(a_type("typename Alloc::value_type"), "Alloc::value_type");
    }

    /// **An expansion is split where a card draws the line**: attributes above, specifiers in front of the type.
    #[test]
    fn an_expansion_is_split_into_attributes_and_specifiers() {
        assert_eq!(
            attributes_and_specifiers(
                "__inline__ __attribute__((always_inline)) __attribute__((cold))"
            ),
            (
                vec![
                    "__attribute__((always_inline))".to_string(),
                    "__attribute__((cold))".to_string()
                ],
                vec!["inline".to_string()]
            ),
            "`__inline__` is the specifier a reader calls `inline`"
        );
        assert_eq!(
            attributes_and_specifiers("[[nodiscard]] inline"),
            (
                vec!["[[nodiscard]]".to_string()],
                vec!["inline".to_string()]
            )
        );
        assert_eq!(
            attributes_and_specifiers("__declspec(dllexport)"),
            (vec!["__declspec(dllexport)".to_string()], vec![])
        );
        assert_eq!(
            attributes_and_specifiers("__launch_bounds__(256)"),
            (vec!["__launch_bounds__(256)".to_string()], vec![])
        );
        assert_eq!(
            attributes_and_specifiers("__global__"),
            (vec![], vec!["__global__".to_string()])
        );
        assert_eq!(
            attributes_and_specifiers("extern \"C\""),
            (vec![], vec!["extern".to_string(), "\"C\"".to_string()]),
            "a quoted string is one specifier"
        );
    }
}