Skip to main content

waft_foundation/
diagnostics.rs

1//! Flutter counterpart: `foundation/diagnostics.dart` (everything but JSON serialization).
2
3use std::any::Any;
4use std::cell::OnceCell;
5use std::fmt;
6use std::rc::Rc;
7use std::sync::LazyLock;
8
9use indexmap::IndexMap;
10use serde_json::{Map as JsonMap, Value};
11
12use crate::HandleId;
13
14/// A serialized diagnostics node: Dart's `Map<String, Object?>`, with JSON values.
15///
16/// Dart's `Map` is ordered; [`serde_json::Map`] is, unless another feature makes it so. Keys are
17/// never looked up by order.
18pub type DiagnosticsJsonMap = JsonMap<String, Value>;
19
20/// The various priority levels used to filter which diagnostics are shown and omitted.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
22pub enum DiagnosticLevel {
23    /// Diagnostics that should not be shown.
24    Hidden,
25    /// A diagnostic that is likely to be low value but where the display is
26    /// just as high quality as a diagnostic with a higher level.
27    Fine,
28    /// Diagnostics that should only be shown when performing fine grained
29    /// debugging of an object.
30    Debug,
31    /// Interesting diagnostics that should be typically shown.
32    Info,
33    /// Very important diagnostics that indicate problematic property values.
34    Warning,
35    /// Diagnostics that provide a hint about best practices.
36    Hint,
37    /// Diagnostics that summarize other diagnostics present.
38    Summary,
39    /// Diagnostics that indicate errors or unexpected conditions.
40    Error,
41    /// Special level indicating that no diagnostics should be shown.
42    Off,
43}
44
45impl DiagnosticLevel {
46    /// Dart's `DiagnosticLevel.index`; [`DiagnosticsNode::is_filtered`] compares these.
47    pub fn index(self) -> usize {
48        match self {
49            DiagnosticLevel::Hidden => 0,
50            DiagnosticLevel::Fine => 1,
51            DiagnosticLevel::Debug => 2,
52            DiagnosticLevel::Info => 3,
53            DiagnosticLevel::Warning => 4,
54            DiagnosticLevel::Hint => 5,
55            DiagnosticLevel::Summary => 6,
56            DiagnosticLevel::Error => 7,
57            DiagnosticLevel::Off => 8,
58        }
59    }
60
61    /// Dart's `DiagnosticLevel.name`: the case written in Dart's source, lowerCamel.
62    pub fn name(self) -> &'static str {
63        match self {
64            DiagnosticLevel::Hidden => "hidden",
65            DiagnosticLevel::Fine => "fine",
66            DiagnosticLevel::Debug => "debug",
67            DiagnosticLevel::Info => "info",
68            DiagnosticLevel::Warning => "warning",
69            DiagnosticLevel::Hint => "hint",
70            DiagnosticLevel::Summary => "summary",
71            DiagnosticLevel::Error => "error",
72            DiagnosticLevel::Off => "off",
73        }
74    }
75}
76
77/// Styles for displaying a node in a [`DiagnosticsNode`] tree.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum DiagnosticsTreeStyle {
80    /// A style that does not display the tree.
81    None,
82    /// Sparse style for displaying trees.
83    Sparse,
84    /// Connects a node to its parent with a dashed line.
85    Offstage,
86    /// Slightly more compact version of the [`Sparse`](Self::Sparse) style.
87    Dense,
88    /// Style that enables transitioning from nodes of one style to children of
89    /// another.
90    Transition,
91    /// Style for displaying content describing an error.
92    Error,
93    /// Render the tree just using whitespace without connecting parents to
94    /// children using lines.
95    Whitespace,
96    /// Render the tree without indenting children at all.
97    Flat,
98    /// Render the tree on a single line without showing children.
99    SingleLine,
100    /// Render the tree using a style appropriate for properties that are part
101    /// of an error message.
102    ErrorProperty,
103    /// Render only the immediate properties of a node instead of the full tree.
104    Shallow,
105    /// Render only the children of a node truncating before the tree becomes too
106    /// large.
107    TruncateChildren,
108}
109
110impl DiagnosticsTreeStyle {
111    /// Dart's `DiagnosticsTreeStyle.name`: the case written in Dart's source, lowerCamel.
112    pub fn name(self) -> &'static str {
113        match self {
114            DiagnosticsTreeStyle::None => "none",
115            DiagnosticsTreeStyle::Sparse => "sparse",
116            DiagnosticsTreeStyle::Offstage => "offstage",
117            DiagnosticsTreeStyle::Dense => "dense",
118            DiagnosticsTreeStyle::Transition => "transition",
119            DiagnosticsTreeStyle::Error => "error",
120            DiagnosticsTreeStyle::Whitespace => "whitespace",
121            DiagnosticsTreeStyle::Flat => "flat",
122            DiagnosticsTreeStyle::SingleLine => "singleLine",
123            DiagnosticsTreeStyle::ErrorProperty => "errorProperty",
124            DiagnosticsTreeStyle::Shallow => "shallow",
125            DiagnosticsTreeStyle::TruncateChildren => "truncateChildren",
126        }
127    }
128}
129
130/// Configuration specifying how a particular [`DiagnosticsTreeStyle`] should be
131/// rendered as text art.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct TextTreeConfiguration {
134    /// Prefix to add to the first line to display a child with this style.
135    pub prefix_line_one: String,
136    /// Suffix to add to end of the first line to make its length match the footer.
137    pub suffix_line_one: String,
138    /// Prefix to add to other lines to display a child with this style.
139    pub prefix_other_lines: String,
140    /// Prefix to add to the first line to display the last child of a node with
141    /// this style.
142    pub prefix_last_child_line_one: String,
143    /// Additional prefix to add to other lines of a node if this is the root
144    /// node of the tree.
145    pub prefix_other_lines_root_node: String,
146    /// Prefix to add before each property if the node has children.
147    pub property_prefix_if_children: String,
148    /// Prefix to add before each property if the node does not have children.
149    pub property_prefix_no_children: String,
150    /// Character to use to draw line linking parent to child.
151    pub link_character: String,
152    /// Whitespace to draw instead of the child link character if this node is the
153    /// last child of its parent so no link line is required.
154    pub child_link_space: String,
155    /// Character(s) to use to separate lines.
156    pub line_break: String,
157    /// Whether to place line breaks between properties or to leave all
158    /// properties on one line.
159    pub line_break_properties: bool,
160    /// Text added immediately before the name of the node.
161    pub before_name: String,
162    /// Text added immediately after the name of the node.
163    pub after_name: String,
164    /// Text to add immediately after the description line of a node with
165    /// properties and/or children if the node has a body.
166    pub after_description_if_body: String,
167    /// Text to add immediately after the description line of a node with
168    /// properties and/or children.
169    pub after_description: String,
170    /// Optional string to add before the properties of a node.
171    pub before_properties: String,
172    /// Optional string to add after the properties of a node.
173    pub after_properties: String,
174    /// Mandatory string to add after the properties of a node regardless of
175    /// whether the node has any properties.
176    pub mandatory_after_properties: String,
177    /// Property separator to add between properties.
178    pub property_separator: String,
179    /// Prefix to add to all lines of the body of the tree node.
180    pub body_indent: String,
181    /// Whether the children of a node should be shown.
182    pub show_children: bool,
183    /// Whether to add a blank line at the end of the output for a node if it has
184    /// no children.
185    pub add_blank_line_if_no_children: bool,
186    /// Whether the name should be displayed on the same line as the description.
187    pub is_name_on_own_line: bool,
188    /// Footer to add as its own line at the end of a non-root node.
189    pub footer: String,
190    /// Footer to add even for root nodes.
191    pub mandatory_footer: String,
192    /// Add a blank line between properties and children if both are present.
193    pub is_blank_line_between_properties_and_children: bool,
194}
195
196impl TextTreeConfiguration {
197    /// Creates a configuration with Dart's required arguments; every other
198    /// argument has Dart's default.
199    pub fn new(
200        prefix_line_one: impl Into<String>,
201        prefix_other_lines: impl Into<String>,
202        prefix_last_child_line_one: impl Into<String>,
203        prefix_other_lines_root_node: impl Into<String>,
204        link_character: impl Into<String>,
205        property_prefix_if_children: impl Into<String>,
206        property_prefix_no_children: impl Into<String>,
207    ) -> Self {
208        let link_character = link_character.into();
209        TextTreeConfiguration {
210            prefix_line_one: prefix_line_one.into(),
211            suffix_line_one: String::new(),
212            prefix_other_lines: prefix_other_lines.into(),
213            prefix_last_child_line_one: prefix_last_child_line_one.into(),
214            prefix_other_lines_root_node: prefix_other_lines_root_node.into(),
215            property_prefix_if_children: property_prefix_if_children.into(),
216            property_prefix_no_children: property_prefix_no_children.into(),
217            child_link_space: " ".repeat(dart_len(&link_character)),
218            link_character,
219            line_break: "\n".to_string(),
220            line_break_properties: true,
221            before_name: String::new(),
222            after_name: ":".to_string(),
223            after_description_if_body: String::new(),
224            after_description: String::new(),
225            before_properties: String::new(),
226            after_properties: String::new(),
227            mandatory_after_properties: String::new(),
228            property_separator: String::new(),
229            body_indent: String::new(),
230            show_children: true,
231            add_blank_line_if_no_children: true,
232            is_name_on_own_line: false,
233            footer: String::new(),
234            mandatory_footer: String::new(),
235            is_blank_line_between_properties_and_children: true,
236        }
237    }
238
239    /// Dart `TextTreeConfiguration(lineBreak:)`.
240    pub fn line_break(mut self, line_break: impl Into<String>) -> Self {
241        self.line_break = line_break.into();
242        self
243    }
244
245    /// Dart `TextTreeConfiguration(lineBreakProperties:)`.
246    pub fn line_break_properties(mut self, line_break_properties: bool) -> Self {
247        self.line_break_properties = line_break_properties;
248        self
249    }
250
251    /// Dart `TextTreeConfiguration(beforeName:)`.
252    pub fn before_name(mut self, before_name: impl Into<String>) -> Self {
253        self.before_name = before_name.into();
254        self
255    }
256
257    /// Dart `TextTreeConfiguration(afterName:)`.
258    pub fn after_name(mut self, after_name: impl Into<String>) -> Self {
259        self.after_name = after_name.into();
260        self
261    }
262
263    /// Dart `TextTreeConfiguration(afterDescriptionIfBody:)`.
264    pub fn after_description_if_body(mut self, text: impl Into<String>) -> Self {
265        self.after_description_if_body = text.into();
266        self
267    }
268
269    /// Dart `TextTreeConfiguration(afterDescription:)`.
270    pub fn after_description(mut self, text: impl Into<String>) -> Self {
271        self.after_description = text.into();
272        self
273    }
274
275    /// Dart `TextTreeConfiguration(beforeProperties:)`.
276    pub fn before_properties(mut self, text: impl Into<String>) -> Self {
277        self.before_properties = text.into();
278        self
279    }
280
281    /// Dart `TextTreeConfiguration(afterProperties:)`.
282    pub fn after_properties(mut self, text: impl Into<String>) -> Self {
283        self.after_properties = text.into();
284        self
285    }
286
287    /// Dart `TextTreeConfiguration(mandatoryAfterProperties:)`.
288    pub fn mandatory_after_properties(mut self, text: impl Into<String>) -> Self {
289        self.mandatory_after_properties = text.into();
290        self
291    }
292
293    /// Dart `TextTreeConfiguration(propertySeparator:)`.
294    pub fn property_separator(mut self, text: impl Into<String>) -> Self {
295        self.property_separator = text.into();
296        self
297    }
298
299    /// Dart `TextTreeConfiguration(bodyIndent:)`.
300    pub fn body_indent(mut self, text: impl Into<String>) -> Self {
301        self.body_indent = text.into();
302        self
303    }
304
305    /// Dart `TextTreeConfiguration(showChildren:)`.
306    pub fn show_children(mut self, show_children: bool) -> Self {
307        self.show_children = show_children;
308        self
309    }
310
311    /// Dart `TextTreeConfiguration(addBlankLineIfNoChildren:)`.
312    pub fn add_blank_line_if_no_children(mut self, add: bool) -> Self {
313        self.add_blank_line_if_no_children = add;
314        self
315    }
316
317    /// Dart `TextTreeConfiguration(isNameOnOwnLine:)`.
318    pub fn is_name_on_own_line(mut self, own_line: bool) -> Self {
319        self.is_name_on_own_line = own_line;
320        self
321    }
322
323    /// Dart `TextTreeConfiguration(footer:)`.
324    pub fn footer(mut self, footer: impl Into<String>) -> Self {
325        self.footer = footer.into();
326        self
327    }
328
329    /// Dart `TextTreeConfiguration(mandatoryFooter:)`.
330    pub fn mandatory_footer(mut self, footer: impl Into<String>) -> Self {
331        self.mandatory_footer = footer.into();
332        self
333    }
334
335    /// Dart `TextTreeConfiguration(suffixLineOne:)`.
336    pub fn suffix_line_one(mut self, suffix: impl Into<String>) -> Self {
337        self.suffix_line_one = suffix.into();
338        self
339    }
340
341    /// Dart `TextTreeConfiguration(isBlankLineBetweenPropertiesAndChildren:)`.
342    pub fn is_blank_line_between_properties_and_children(mut self, blank: bool) -> Self {
343        self.is_blank_line_between_properties_and_children = blank;
344        self
345    }
346}
347
348/// Default text tree configuration, for [`DiagnosticsTreeStyle::Sparse`].
349pub fn sparse_text_configuration() -> &'static TextTreeConfiguration {
350    static CONFIG: LazyLock<TextTreeConfiguration> =
351        LazyLock::new(|| TextTreeConfiguration::new("├─", " ", "└─", " ", "│", "│ ", "  "));
352    &CONFIG
353}
354
355/// Dashed configuration, for [`DiagnosticsTreeStyle::Offstage`].
356pub fn dashed_text_configuration() -> &'static TextTreeConfiguration {
357    static CONFIG: LazyLock<TextTreeConfiguration> =
358        LazyLock::new(|| TextTreeConfiguration::new("╎╌", " ", "└╌", " ", "╎", "│ ", "  "));
359    &CONFIG
360}
361
362/// Dense configuration, for [`DiagnosticsTreeStyle::Dense`].
363pub fn dense_text_configuration() -> &'static TextTreeConfiguration {
364    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
365        TextTreeConfiguration::new("├", "", "└", "", "│", "│", " ")
366            .property_separator(", ")
367            .before_properties("(")
368            .after_properties(")")
369            .line_break_properties(false)
370            .add_blank_line_if_no_children(false)
371            .is_blank_line_between_properties_and_children(false)
372    });
373    &CONFIG
374}
375
376/// Configuration that draws a box around a leaf node, for
377/// [`DiagnosticsTreeStyle::Transition`].
378pub fn transition_text_configuration() -> &'static TextTreeConfiguration {
379    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
380        TextTreeConfiguration::new("╞═╦══ ", " ║ ", "╘═╦══ ", "", "│", "", "")
381            .footer(" ╚═══════════")
382            .after_name(" ═══")
383            .after_description_if_body(":")
384            .body_indent("  ")
385            .is_name_on_own_line(true)
386            .add_blank_line_if_no_children(false)
387            .is_blank_line_between_properties_and_children(false)
388    });
389    &CONFIG
390}
391
392/// Configuration that draws a box around a node, for
393/// [`DiagnosticsTreeStyle::Error`].
394pub fn error_text_configuration() -> &'static TextTreeConfiguration {
395    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
396        TextTreeConfiguration::new("╞═╦", " ║ ", "╘═╦", "", "│", "", "")
397            .footer(" ╚═══════════")
398            .before_name("══╡ ")
399            .suffix_line_one(" ╞══")
400            .mandatory_footer("═════")
401            .add_blank_line_if_no_children(false)
402            .is_blank_line_between_properties_and_children(false)
403    });
404    &CONFIG
405}
406
407/// Whitespace only configuration where children are consistently indented,
408/// for [`DiagnosticsTreeStyle::Whitespace`].
409pub fn whitespace_text_configuration() -> &'static TextTreeConfiguration {
410    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
411        TextTreeConfiguration::new("", " ", "", "  ", " ", "", "")
412            .add_blank_line_if_no_children(false)
413            .after_description_if_body(":")
414            .is_blank_line_between_properties_and_children(false)
415    });
416    &CONFIG
417}
418
419/// Whitespace only configuration where children are not indented, for
420/// [`DiagnosticsTreeStyle::Flat`].
421pub fn flat_text_configuration() -> &'static TextTreeConfiguration {
422    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
423        TextTreeConfiguration::new("", "", "", "", "", "", "")
424            .add_blank_line_if_no_children(false)
425            .after_description_if_body(":")
426            .is_blank_line_between_properties_and_children(false)
427    });
428    &CONFIG
429}
430
431/// Render a node as a single line omitting children, for
432/// [`DiagnosticsTreeStyle::SingleLine`].
433pub fn single_line_text_configuration() -> &'static TextTreeConfiguration {
434    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
435        TextTreeConfiguration::new("", "", "", "", "", "  ", "  ")
436            .property_separator(", ")
437            .before_properties("(")
438            .after_properties(")")
439            .line_break("")
440            .line_break_properties(false)
441            .add_blank_line_if_no_children(false)
442            .show_children(false)
443    });
444    &CONFIG
445}
446
447/// Render the name on a line followed by the body and properties on the next
448/// line omitting the children, for [`DiagnosticsTreeStyle::ErrorProperty`].
449pub fn error_property_text_configuration() -> &'static TextTreeConfiguration {
450    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
451        TextTreeConfiguration::new("", "", "", "", "", "  ", "  ")
452            .property_separator(", ")
453            .before_properties("(")
454            .after_properties(")")
455            .line_break_properties(false)
456            .add_blank_line_if_no_children(false)
457            .show_children(false)
458            .is_name_on_own_line(true)
459    });
460    &CONFIG
461}
462
463/// Render a node on multiple lines omitting children, for
464/// [`DiagnosticsTreeStyle::Shallow`].
465pub fn shallow_text_configuration() -> &'static TextTreeConfiguration {
466    static CONFIG: LazyLock<TextTreeConfiguration> = LazyLock::new(|| {
467        TextTreeConfiguration::new("", " ", "", "  ", " ", "", "")
468            .add_blank_line_if_no_children(false)
469            .after_description_if_body(":")
470            .is_blank_line_between_properties_and_children(false)
471            .show_children(false)
472    });
473    &CONFIG
474}
475
476/// The text configuration for `style`, or none for
477/// [`DiagnosticsTreeStyle::None`].
478pub fn text_tree_configuration_for(
479    style: DiagnosticsTreeStyle,
480) -> Option<&'static TextTreeConfiguration> {
481    match style {
482        DiagnosticsTreeStyle::None => None,
483        DiagnosticsTreeStyle::Dense => Some(dense_text_configuration()),
484        DiagnosticsTreeStyle::Sparse => Some(sparse_text_configuration()),
485        DiagnosticsTreeStyle::Offstage => Some(dashed_text_configuration()),
486        DiagnosticsTreeStyle::Whitespace => Some(whitespace_text_configuration()),
487        DiagnosticsTreeStyle::Transition => Some(transition_text_configuration()),
488        DiagnosticsTreeStyle::SingleLine => Some(single_line_text_configuration()),
489        DiagnosticsTreeStyle::ErrorProperty => Some(error_property_text_configuration()),
490        DiagnosticsTreeStyle::Shallow => Some(shallow_text_configuration()),
491        DiagnosticsTreeStyle::Error => Some(error_text_configuration()),
492        DiagnosticsTreeStyle::Flat => Some(flat_text_configuration()),
493        // Truncate children doesn't really need its own text style as the
494        // rendering is quite custom.
495        DiagnosticsTreeStyle::TruncateChildren => Some(whitespace_text_configuration()),
496    }
497}
498
499fn is_single_line(style: Option<DiagnosticsTreeStyle>) -> bool {
500    style == Some(DiagnosticsTreeStyle::SingleLine)
501}
502
503/// Dart's `String.length`: UTF-16 code units.
504fn dart_len(text: &str) -> usize {
505    text.encode_utf16().count()
506}
507
508#[derive(Clone, Copy, PartialEq, Eq)]
509enum WordWrapParseMode {
510    InSpace,
511    InWord,
512    AtBreak,
513}
514
515/// Builder that builds a String with specified prefixes for the first and
516/// subsequent lines.
517struct PrefixedStringBuilder {
518    /// Prefix to add to the first line.
519    prefix_line_one: String,
520    /// Prefix to add to subsequent lines.
521    prefix_other_lines: String,
522    next_prefix_other_lines: Option<String>,
523    wrap_width: usize,
524    /// Buffer containing lines that have already been completely laid out.
525    buffer: String,
526    /// Buffer containing the current line that has not yet been wrapped.
527    current_line: String,
528    /// Pairs of integers indicating the start and end of each block of text
529    /// within `current_line` that can be wrapped.
530    wrappable_ranges: Vec<usize>,
531    num_lines: usize,
532}
533
534impl PrefixedStringBuilder {
535    fn new(prefix_line_one: String, prefix_other_lines: String, wrap_width: usize) -> Self {
536        PrefixedStringBuilder {
537            prefix_line_one,
538            prefix_other_lines,
539            next_prefix_other_lines: None,
540            wrap_width,
541            buffer: String::new(),
542            current_line: String::new(),
543            wrappable_ranges: Vec::new(),
544            num_lines: 0,
545        }
546    }
547
548    fn increment_prefix_other_lines(&mut self, suffix: &str, update_current_line: bool) {
549        let prefix = format!("{}{}", self.prefix_other_lines, suffix);
550        if self.current_line.is_empty() || update_current_line {
551            self.prefix_other_lines = prefix;
552            self.next_prefix_other_lines = None;
553        } else {
554            self.next_prefix_other_lines = Some(prefix);
555        }
556    }
557
558    fn requires_multiple_lines(&self) -> bool {
559        self.num_lines > 1
560            || (self.num_lines == 1 && !self.current_line.is_empty())
561            || (dart_len(&self.current_line) + dart_len(self.current_prefix(true))
562                > self.wrap_width)
563    }
564
565    fn is_current_line_empty(&self) -> bool {
566        self.current_line.is_empty()
567    }
568
569    fn finalize_line(&mut self, add_trailing_line_break: bool) {
570        let first_line = self.buffer.is_empty();
571        let text = std::mem::take(&mut self.current_line);
572
573        if self.wrappable_ranges.is_empty() {
574            // Fast path. There were no wrappable spans of text.
575            self.write_line(&text, add_trailing_line_break, first_line);
576            return;
577        }
578        let lines = Self::word_wrap_line(
579            &text,
580            &self.wrappable_ranges,
581            self.wrap_width,
582            if first_line {
583                dart_len(&self.prefix_line_one)
584            } else {
585                dart_len(&self.prefix_other_lines)
586            },
587            dart_len(&self.prefix_other_lines),
588        );
589        let length = lines.len();
590        for (i, line) in lines.into_iter().enumerate() {
591            self.write_line(&line, add_trailing_line_break || i + 1 < length, first_line);
592        }
593        self.wrappable_ranges.clear();
594    }
595
596    /// Wraps the given string at the given width.
597    ///
598    /// Wrapping occurs at space characters (U+0020). Only the spans listed in
599    /// `wrap_ranges` may be broken.
600    fn word_wrap_line(
601        message: &str,
602        wrap_ranges: &[usize],
603        width: usize,
604        start_offset: usize,
605        other_line_offset: usize,
606    ) -> Vec<String> {
607        let encoded: Vec<u16> = message.encode_utf16().collect();
608        if encoded.len() + start_offset < width {
609            // Nothing to do. The line doesn't wrap.
610            return vec![message.to_string()];
611        }
612        let mut wrapped_line = Vec::new();
613        let mut start_for_length_calculations = -(start_offset as i64);
614        let mut index: usize = 0;
615        let mut mode = WordWrapParseMode::InSpace;
616        let mut last_word_start: usize = 0;
617        let mut last_word_end: Option<usize> = None;
618        let mut start: usize = 0;
619        let mut current_chunk: usize = 0;
620        let space = b' ' as u16;
621
622        // This helper is called with increasing indexes.
623        let mut no_wrap = |index: usize| -> bool {
624            loop {
625                if current_chunk >= wrap_ranges.len() {
626                    break true;
627                }
628                if index < wrap_ranges[current_chunk + 1] {
629                    return index < wrap_ranges[current_chunk];
630                }
631                current_chunk += 2;
632            }
633        };
634
635        loop {
636            match mode {
637                // At start of break point (or start of line); can't break until
638                // the next break.
639                WordWrapParseMode::InSpace => {
640                    while index < encoded.len() && encoded[index] == space {
641                        index += 1;
642                    }
643                    last_word_start = index;
644                    mode = WordWrapParseMode::InWord;
645                }
646                // Looking for a good break point. Treat all text as non
647                // wrappable while `no_wrap` says so.
648                WordWrapParseMode::InWord => {
649                    while index < encoded.len() && (encoded[index] != space || no_wrap(index)) {
650                        index += 1;
651                    }
652                    mode = WordWrapParseMode::AtBreak;
653                }
654                // At start of break point.
655                WordWrapParseMode::AtBreak => {
656                    if (index as i64 - start_for_length_calculations > width as i64)
657                        || (index == encoded.len())
658                    {
659                        // We are over the width line, so break.
660                        if ((index as i64 - start_for_length_calculations) <= width as i64)
661                            || last_word_end.is_none()
662                        {
663                            // We should use this point, because either it doesn't
664                            // actually go over the end (last line), or it does,
665                            // but there was no earlier break point.
666                            last_word_end = Some(index);
667                        }
668                        let end = last_word_end.expect("a break point was chosen");
669                        let line = String::from_utf16(&encoded[start..end])
670                            .expect("a wrap boundary is at a space or the end");
671                        wrapped_line.push(line);
672                        if end >= encoded.len() {
673                            return wrapped_line;
674                        }
675                        // Just yielded a line.
676                        if end == index {
677                            // We broke at the current position; eat all the
678                            // wrappable spaces, then set our start point.
679                            while index < encoded.len() && encoded[index] == space {
680                                index += 1;
681                            }
682                            start = index;
683                            mode = WordWrapParseMode::InWord;
684                        } else {
685                            // We broke at the previous break point, and we're at
686                            // the start of a new one.
687                            debug_assert!(last_word_start > end);
688                            start = last_word_start;
689                            mode = WordWrapParseMode::AtBreak;
690                        }
691                        start_for_length_calculations = start as i64 - other_line_offset as i64;
692                        last_word_end = None;
693                    } else {
694                        // Save this break point; we're not yet over the line
695                        // width.
696                        last_word_end = Some(index);
697                        // Skip to the end of this break point.
698                        mode = WordWrapParseMode::InSpace;
699                    }
700                }
701            }
702        }
703    }
704
705    /// Writes text ensuring the specified prefixes for the first and subsequent
706    /// lines.
707    fn write(&mut self, s: &str, allow_wrap: bool) {
708        if s.is_empty() {
709            return;
710        }
711
712        let lines: Vec<&str> = s.split('\n').collect();
713        for (i, line) in lines.into_iter().enumerate() {
714            if i > 0 {
715                self.finalize_line(true);
716                self.update_prefix();
717            }
718            if !line.is_empty() {
719                if allow_wrap {
720                    let wrap_start = dart_len(&self.current_line);
721                    let wrap_end = wrap_start + dart_len(line);
722                    if self.wrappable_ranges.last() == Some(&wrap_start) {
723                        // Extend the last range.
724                        *self.wrappable_ranges.last_mut().expect("checked above") = wrap_end;
725                    } else {
726                        self.wrappable_ranges.push(wrap_start);
727                        self.wrappable_ranges.push(wrap_end);
728                    }
729                }
730                self.current_line.push_str(line);
731            }
732        }
733    }
734
735    fn update_prefix(&mut self) {
736        if let Some(prefix) = self.next_prefix_other_lines.take() {
737            self.prefix_other_lines = prefix;
738        }
739    }
740
741    fn write_line(&mut self, line: &str, include_line_break: bool, first_line: bool) {
742        let prefixed = format!("{}{}", self.current_prefix(first_line), line);
743        self.buffer.push_str(prefixed.trim_end());
744        if include_line_break {
745            self.buffer.push('\n');
746        }
747        self.num_lines += 1;
748    }
749
750    /// Dart's `_getCurrentPrefix`; the `first_line` argument is unused there
751    /// too: the buffer decides.
752    fn current_prefix(&self, _first_line: bool) -> &str {
753        if self.buffer.is_empty() {
754            &self.prefix_line_one
755        } else {
756            &self.prefix_other_lines
757        }
758    }
759
760    /// Writes lines assuming the lines obey the specified prefixes. Ensures that
761    /// a newline is added if one is not present.
762    fn write_raw_lines(&mut self, lines: &str) {
763        if lines.is_empty() {
764            return;
765        }
766
767        if !self.current_line.is_empty() {
768            self.finalize_line(true);
769        }
770        debug_assert!(self.current_line.is_empty());
771
772        self.buffer.push_str(lines);
773        if !lines.ends_with('\n') {
774            self.buffer.push('\n');
775        }
776        self.num_lines += 1;
777        self.update_prefix();
778    }
779
780    /// Finishes the current line with a stretched version of text.
781    fn write_stretched(&mut self, text: &str, target_line_length: usize) {
782        self.write(text, false);
783        let current_line_length =
784            dart_len(&self.current_line) + dart_len(self.current_prefix(self.buffer.is_empty()));
785        assert!(
786            !self.current_line.is_empty(),
787            "writeStretched needs text on the current line"
788        );
789        let target_length = target_line_length as i64 - current_line_length as i64;
790        if target_length > 0 {
791            assert!(!text.is_empty());
792            let last_char = text.chars().last().expect("text is nonempty");
793            assert_ne!(last_char, '\n');
794            self.current_line
795                .extend(std::iter::repeat_n(last_char, target_length as usize));
796        }
797        // Mark the entire line as not wrappable.
798        self.wrappable_ranges.clear();
799    }
800
801    fn build(mut self) -> String {
802        if !self.current_line.is_empty() {
803            self.finalize_line(false);
804        }
805        self.buffer
806    }
807}
808
809/// Renderer that creates ASCII art representations of trees of
810/// [`DiagnosticsNode`] objects.
811pub struct TextTreeRenderer {
812    wrap_width: usize,
813    wrap_width_properties: usize,
814    min_level: DiagnosticLevel,
815    max_descendents_truncatable_node: i32,
816}
817
818impl TextTreeRenderer {
819    /// Creates a renderer with Dart's defaults.
820    pub fn new() -> Self {
821        TextTreeRenderer {
822            wrap_width: 100,
823            wrap_width_properties: 65,
824            min_level: DiagnosticLevel::Debug,
825            max_descendents_truncatable_node: -1,
826        }
827    }
828
829    /// Dart `TextTreeRenderer(wrapWidth:)`.
830    pub fn wrap_width(mut self, wrap_width: usize) -> Self {
831        self.wrap_width = wrap_width;
832        self
833    }
834
835    /// Dart `TextTreeRenderer(wrapWidthProperties:)`.
836    pub fn wrap_width_properties(mut self, wrap_width_properties: usize) -> Self {
837        self.wrap_width_properties = wrap_width_properties;
838        self
839    }
840
841    /// Dart `TextTreeRenderer(minLevel:)`.
842    pub fn min_level(mut self, min_level: DiagnosticLevel) -> Self {
843        self.min_level = min_level;
844        self
845    }
846
847    /// Dart `TextTreeRenderer(_maxDescendentsTruncatableNode:)`.
848    pub fn max_descendents_truncatable_node(mut self, max: i32) -> Self {
849        self.max_descendents_truncatable_node = max;
850        self
851    }
852
853    /// Text configuration to use to connect this node to a `child`.
854    fn child_text_configuration<'a>(
855        &self,
856        child: &'a dyn DiagnosticsNode,
857        text_style: &'a TextTreeConfiguration,
858    ) -> &'a TextTreeConfiguration {
859        let child_style = child.style();
860        if is_single_line(child_style) || child_style == Some(DiagnosticsTreeStyle::ErrorProperty) {
861            text_style
862        } else {
863            child
864                .text_tree_configuration()
865                .expect("a diagnostics node has a text tree configuration")
866        }
867    }
868
869    /// Renders a [`DiagnosticsNode`] to a String with no prefix.
870    pub fn render(&self, node: &dyn DiagnosticsNode) -> String {
871        self.render_with(node, "", None, None)
872    }
873
874    /// Renders a [`DiagnosticsNode`] to a String.
875    pub fn render_with(
876        &self,
877        node: &dyn DiagnosticsNode,
878        prefix_line_one: &str,
879        prefix_other_lines: Option<&str>,
880        parent_configuration: Option<&TextTreeConfiguration>,
881    ) -> String {
882        let single_line = is_single_line(node.style())
883            && parent_configuration.is_none_or(|parent| !parent.line_break_properties);
884        let mut prefix_line_one = prefix_line_one.to_string();
885        let mut prefix_other_lines = prefix_other_lines
886            .map(str::to_string)
887            .unwrap_or_else(|| prefix_line_one.clone());
888        if let Some(line_prefix) = node.line_prefix() {
889            prefix_line_one.push_str(line_prefix);
890            prefix_other_lines.push_str(line_prefix);
891        }
892
893        let config = node
894            .text_tree_configuration()
895            .expect("a diagnostics node has a text tree configuration");
896        if prefix_other_lines.is_empty() {
897            prefix_other_lines.push_str(&config.prefix_other_lines_root_node);
898        }
899
900        if node.style() == Some(DiagnosticsTreeStyle::TruncateChildren) {
901            // This style is different enough that it isn't worthwhile to reuse
902            // the existing logic.
903            let mut descendants = Vec::new();
904            const MAX_DEPTH: usize = 5;
905            let mut depth = 0;
906            const MAX_LINES: usize = 25;
907            let mut lines = 0;
908            fn visitor(
909                node: &dyn DiagnosticsNode,
910                prefix_other_lines: &str,
911                depth: &mut usize,
912                lines: &mut usize,
913                descendants: &mut Vec<String>,
914            ) {
915                for child in node.get_children() {
916                    if *lines < MAX_LINES {
917                        *depth += 1;
918                        descendants.push(format!(
919                            "{prefix_other_lines}{}{child}",
920                            "  ".repeat(*depth)
921                        ));
922                        if *depth < MAX_DEPTH {
923                            visitor(
924                                child.as_ref(),
925                                prefix_other_lines,
926                                depth,
927                                lines,
928                                descendants,
929                            );
930                        }
931                        *depth -= 1;
932                    } else if *lines == MAX_LINES {
933                        descendants.push(format!(
934                            "{prefix_other_lines}  ...(descendants list truncated after {lines} lines)"
935                        ));
936                    }
937                    *lines += 1;
938                }
939            }
940            visitor(
941                node,
942                &prefix_other_lines,
943                &mut depth,
944                &mut lines,
945                &mut descendants,
946            );
947            let mut information = prefix_line_one;
948            if lines > 1 {
949                information.push_str(&format!(
950                    "This {} had the following descendants (showing up to depth {MAX_DEPTH}):\n",
951                    node.name().unwrap_or("null")
952                ));
953            } else if descendants.len() == 1 {
954                information.push_str(&format!(
955                    "This {} had the following child:\n",
956                    node.name().unwrap_or("null")
957                ));
958            } else {
959                information.push_str(&format!(
960                    "This {} has no descendants.\n",
961                    node.name().unwrap_or("null")
962                ));
963            }
964            information.push_str(&descendants.join("\n"));
965            return information;
966        }
967
968        let mut builder = PrefixedStringBuilder::new(
969            prefix_line_one,
970            prefix_other_lines.clone(),
971            self.wrap_width
972                .max(dart_len(&prefix_other_lines) + self.wrap_width_properties),
973        );
974
975        let mut children = node.get_children();
976
977        let mut description = node.to_description(parent_configuration);
978        if !config.before_name.is_empty() {
979            builder.write(&config.before_name, false);
980        }
981        let wrap_name = !single_line && node.allow_name_wrap();
982        let wrap_description = !single_line && node.allow_wrap();
983        let uppercase_title = node.style() == Some(DiagnosticsTreeStyle::Error);
984        let mut name = node.name().map(str::to_string);
985        if uppercase_title {
986            name = name.map(|name| name.to_uppercase());
987        }
988        if description.is_empty() {
989            if node.show_name()
990                && let Some(name) = &name
991            {
992                builder.write(name, wrap_name);
993            }
994        } else {
995            let mut include_name = false;
996            if let Some(name) = &name
997                && !name.is_empty()
998                && node.show_name()
999            {
1000                include_name = true;
1001                builder.write(name, wrap_name);
1002                if node.show_separator() {
1003                    builder.write(&config.after_name, wrap_name);
1004                }
1005
1006                builder.write(
1007                    if config.is_name_on_own_line || description.contains('\n') {
1008                        "\n"
1009                    } else {
1010                        " "
1011                    },
1012                    wrap_name,
1013                );
1014            }
1015            if !single_line && builder.requires_multiple_lines() && !builder.is_current_line_empty()
1016            {
1017                // Make sure there is a break between the current line and next
1018                // one if there is not one already.
1019                builder.write("\n", false);
1020            }
1021            if include_name {
1022                builder.increment_prefix_other_lines(
1023                    if children.is_empty() {
1024                        &config.property_prefix_no_children
1025                    } else {
1026                        &config.property_prefix_if_children
1027                    },
1028                    true,
1029                );
1030            }
1031
1032            if uppercase_title {
1033                description = description.to_uppercase();
1034            }
1035            builder.write(description.trim_end(), wrap_description);
1036
1037            if !include_name {
1038                builder.increment_prefix_other_lines(
1039                    if children.is_empty() {
1040                        &config.property_prefix_no_children
1041                    } else {
1042                        &config.property_prefix_if_children
1043                    },
1044                    false,
1045                );
1046            }
1047        }
1048        if !config.suffix_line_one.is_empty() {
1049            builder.write_stretched(&config.suffix_line_one, builder.wrap_width);
1050        }
1051
1052        let mut properties: Vec<Rc<dyn DiagnosticsNode>> = node
1053            .get_properties()
1054            .into_iter()
1055            .filter(|node| !node.is_filtered(self.min_level))
1056            .collect();
1057        if self.max_descendents_truncatable_node >= 0 && node.allow_truncate() {
1058            let max = self.max_descendents_truncatable_node as usize;
1059            if properties.len() < max {
1060                properties.truncate(max);
1061                properties.push(Rc::new(message("...")));
1062            }
1063            if max < children.len() {
1064                children.truncate(max);
1065                children.push(Rc::new(message("...")));
1066            }
1067        }
1068
1069        // If the node does not show a separator and there is no description
1070        // then we should not place a separator between the name and the value.
1071        // Essentially in this case the properties are treated a bit like a
1072        // value.
1073        if (!properties.is_empty()
1074            || !children.is_empty()
1075            || node.empty_body_description().is_some())
1076            && (node.show_separator() || !description.is_empty())
1077        {
1078            builder.write(&config.after_description_if_body, false);
1079        }
1080
1081        if config.line_break_properties {
1082            builder.write(&config.line_break, false);
1083        }
1084
1085        if !properties.is_empty() {
1086            builder.write(&config.before_properties, false);
1087        }
1088
1089        builder.increment_prefix_other_lines(&config.body_indent, false);
1090
1091        if node.empty_body_description().is_some()
1092            && properties.is_empty()
1093            && children.is_empty()
1094            && !builder.prefix_line_one.is_empty()
1095        {
1096            builder.write(node.empty_body_description().expect("checked above"), false);
1097            if config.line_break_properties {
1098                builder.write(&config.line_break, false);
1099            }
1100        }
1101
1102        for (i, property) in properties.iter().enumerate() {
1103            if i > 0 {
1104                builder.write(&config.property_separator, false);
1105            }
1106
1107            let property_style = property
1108                .text_tree_configuration()
1109                .expect("a diagnostics node has a text tree configuration");
1110            if is_single_line(property.style()) {
1111                // We have to treat single line properties slightly differently
1112                // to deal with cases where a single line property's output may
1113                // not have a single line break.
1114                let property_render = self.render_with(
1115                    property.as_ref(),
1116                    &property_style.prefix_line_one,
1117                    Some(&format!(
1118                        "{}{}",
1119                        property_style.child_link_space, property_style.prefix_other_lines
1120                    )),
1121                    Some(config),
1122                );
1123                let property_lines: Vec<&str> = property_render.split('\n').collect();
1124                if property_lines.len() == 1 && !config.line_break_properties {
1125                    builder.write(property_lines[0], false);
1126                } else {
1127                    builder.write(&property_render, false);
1128                    if !property_render.ends_with('\n') {
1129                        builder.write("\n", false);
1130                    }
1131                }
1132            } else {
1133                let property_render = self.render_with(
1134                    property.as_ref(),
1135                    &format!(
1136                        "{}{}",
1137                        builder.prefix_other_lines, property_style.prefix_line_one
1138                    ),
1139                    Some(&format!(
1140                        "{}{}{}",
1141                        builder.prefix_other_lines,
1142                        property_style.child_link_space,
1143                        property_style.prefix_other_lines
1144                    )),
1145                    Some(config),
1146                );
1147                builder.write_raw_lines(&property_render);
1148            }
1149        }
1150        if !properties.is_empty() {
1151            builder.write(&config.after_properties, false);
1152        }
1153
1154        builder.write(&config.mandatory_after_properties, false);
1155
1156        if !config.line_break_properties {
1157            builder.write(&config.line_break, false);
1158        }
1159
1160        let prefix_children = config.body_indent.clone();
1161        let prefix_children_raw = format!("{prefix_other_lines}{prefix_children}");
1162        if children.is_empty()
1163            && config.add_blank_line_if_no_children
1164            && builder.requires_multiple_lines()
1165            && !builder.prefix_other_lines.trim_end().is_empty()
1166        {
1167            builder.write(&config.line_break, false);
1168        }
1169
1170        if !children.is_empty() && config.show_children {
1171            if config.is_blank_line_between_properties_and_children
1172                && !properties.is_empty()
1173                && children[0]
1174                    .text_tree_configuration()
1175                    .is_some_and(|config| config.is_blank_line_between_properties_and_children)
1176            {
1177                builder.write(&config.line_break, false);
1178            }
1179
1180            builder.prefix_other_lines = prefix_other_lines.clone();
1181
1182            for i in 0..children.len() {
1183                let child = &children[i];
1184                let child_config = self.child_text_configuration(child.as_ref(), config);
1185                let last = i == children.len() - 1;
1186                let (child_prefix_line_one, child_prefix_other_lines) = if last {
1187                    (
1188                        format!(
1189                            "{prefix_children_raw}{}",
1190                            child_config.prefix_last_child_line_one
1191                        ),
1192                        format!(
1193                            "{prefix_children_raw}{}{}",
1194                            child_config.child_link_space, child_config.prefix_other_lines
1195                        ),
1196                    )
1197                } else {
1198                    let next_child_style =
1199                        self.child_text_configuration(children[i + 1].as_ref(), config);
1200                    (
1201                        format!("{prefix_children_raw}{}", child_config.prefix_line_one),
1202                        format!(
1203                            "{prefix_children_raw}{}{}",
1204                            next_child_style.link_character, child_config.prefix_other_lines
1205                        ),
1206                    )
1207                };
1208                let child_render = self.render_with(
1209                    child.as_ref(),
1210                    &child_prefix_line_one,
1211                    Some(&child_prefix_other_lines),
1212                    Some(config),
1213                );
1214                builder.write_raw_lines(&child_render);
1215                if !child_config.footer.is_empty() {
1216                    builder.prefix_other_lines = prefix_children_raw.clone();
1217                    let footer = format!(
1218                        "{}{}",
1219                        if last {
1220                            &child_config.child_link_space
1221                        } else {
1222                            &child_config.link_character
1223                        },
1224                        child_config.footer
1225                    );
1226                    builder.write(&footer, false);
1227                    if !child_config.mandatory_footer.is_empty() {
1228                        builder.write_stretched(
1229                            &child_config.mandatory_footer,
1230                            builder.wrap_width.max(
1231                                self.wrap_width_properties + dart_len(&child_prefix_other_lines),
1232                            ),
1233                        );
1234                    }
1235                    builder.write(&config.line_break, false);
1236                }
1237            }
1238        }
1239        if parent_configuration.is_none() && !config.mandatory_footer.is_empty() {
1240            builder.write_stretched(&config.mandatory_footer, builder.wrap_width);
1241            builder.write(&config.line_break, false);
1242        }
1243        builder.build()
1244    }
1245}
1246
1247impl Default for TextTreeRenderer {
1248    fn default() -> Self {
1249        Self::new()
1250    }
1251}
1252
1253fn json_put(json: &mut DiagnosticsJsonMap, key: &str, value: Value) {
1254    let _ = json.insert(key.to_string(), value);
1255}
1256
1257fn json_array(nodes: Vec<DiagnosticsJsonMap>) -> Value {
1258    Value::Array(nodes.into_iter().map(Value::Object).collect())
1259}
1260
1261/// A value as Dart's `value.toString()` prints it, from the value's `Display`; a Rust double's
1262/// `Display` drops the `.0` Dart keeps.
1263fn dart_value_to_string(value: &dyn std::any::Any, display: String) -> String {
1264    if let Some(value) = value.downcast_ref::<f64>() {
1265        return dart_double_to_string(*value);
1266    }
1267    if let Some(value) = value.downcast_ref::<f32>() {
1268        return dart_double_to_string(f64::from(*value));
1269    }
1270    display
1271}
1272
1273/// Dart's `double.toString`: the shortest text that reads back as the same value, with `.0` kept
1274/// on an integral one, and Dart's spellings for the three non-finite values.
1275fn dart_double_to_string(value: f64) -> String {
1276    if value.is_nan() {
1277        "NaN".to_string()
1278    } else if value == f64::INFINITY {
1279        "Infinity".to_string()
1280    } else if value == f64::NEG_INFINITY {
1281        "-Infinity".to_string()
1282    } else {
1283        format!("{value:?}")
1284    }
1285}
1286
1287/// The body of Dart's `DiagnosticsNode.toJsonMap`.
1288///
1289/// `owner` is the node as a trait object, for the delegate hooks that take one. Only a sized
1290/// implementation can hand itself over, which is why the trait's provided method passes none: see
1291/// [`json_map_impl`](macro@json_map_impl).
1292macro_rules! to_json_map_body {
1293    ($node:expr, $owner:expr, $delegate:expr) => {{
1294        let owner: Option<&dyn DiagnosticsNode> = $owner;
1295        let delegate: &dyn DiagnosticsSerializationDelegate = $delegate;
1296        let mut json = DiagnosticsJsonMap::new();
1297        json_put(
1298            &mut json,
1299            "description",
1300            Value::String($node.to_description(None)),
1301        );
1302        json_put(
1303            &mut json,
1304            "type",
1305            Value::String($node.type_name().to_string()),
1306        );
1307        if let Some(name) = $node.name() {
1308            json_put(&mut json, "name", Value::String(name.to_string()));
1309        }
1310        if !$node.show_separator() {
1311            json_put(&mut json, "showSeparator", Value::Bool(false));
1312        }
1313        let level = $node.level();
1314        if level != DiagnosticLevel::Info {
1315            json_put(&mut json, "level", Value::String(level.name().to_string()));
1316        }
1317        if !$node.show_name() {
1318            json_put(&mut json, "showName", Value::Bool(false));
1319        }
1320        if let Some(description) = $node.empty_body_description() {
1321            json_put(
1322                &mut json,
1323                "emptyBodyDescription",
1324                Value::String(description.to_string()),
1325            );
1326        }
1327        let style = $node.style();
1328        if let Some(style) = style
1329            && style != DiagnosticsTreeStyle::Sparse
1330        {
1331            json_put(&mut json, "style", Value::String(style.name().to_string()));
1332        }
1333        if $node.allow_truncate() {
1334            json_put(&mut json, "allowTruncate", Value::Bool(true));
1335        }
1336        let children = $node.get_children();
1337        if !children.is_empty() {
1338            json_put(&mut json, "hasChildren", Value::Bool(true));
1339        }
1340        if let Some(prefix) = $node.line_prefix()
1341            && !prefix.is_empty()
1342        {
1343            json_put(&mut json, "linePrefix", Value::String(prefix.to_string()));
1344        }
1345        if !$node.allow_wrap() {
1346            json_put(&mut json, "allowWrap", Value::Bool(false));
1347        }
1348        if $node.allow_name_wrap() {
1349            json_put(&mut json, "allowNameWrap", Value::Bool(true));
1350        }
1351        if let Some(owner) = owner {
1352            for (key, value) in delegate.additional_node_properties(owner, true) {
1353                let _ = json.insert(key, value);
1354            }
1355        }
1356        if delegate.include_properties() {
1357            let properties = $node.get_properties();
1358            let properties = match owner {
1359                Some(owner) => delegate.filter_properties(properties, owner),
1360                None => properties,
1361            };
1362            json_put(
1363                &mut json,
1364                "properties",
1365                json_array(to_json_list(properties, owner, delegate)),
1366            );
1367        }
1368        if delegate.subtree_depth() > 0 {
1369            let children = match owner {
1370                Some(owner) => delegate.filter_children(children, owner),
1371                None => children,
1372            };
1373            json_put(
1374                &mut json,
1375                "children",
1376                json_array(to_json_list(children, owner, delegate)),
1377            );
1378        }
1379        json
1380    }};
1381}
1382
1383/// Implements [`DiagnosticsNode::to_json_map`] with Dart's base body and `self` as the owner its
1384/// property and child lists are filtered against.
1385macro_rules! json_map_impl {
1386    () => {
1387        fn to_json_map(
1388            &self,
1389            delegate: &dyn DiagnosticsSerializationDelegate,
1390        ) -> DiagnosticsJsonMap {
1391            base_json_map(self, delegate)
1392        }
1393    };
1394}
1395
1396/// Dart's `DiagnosticsNode.toJsonMap` body for a node that can name itself as a trait object.
1397///
1398pub fn base_json_map(
1399    node: &dyn DiagnosticsNode,
1400    delegate: &dyn DiagnosticsSerializationDelegate,
1401) -> DiagnosticsJsonMap {
1402    to_json_map_body!(node, Some(node), delegate)
1403}
1404
1405/// Serializes a list of nodes, as Dart's `DiagnosticsNode.toJsonList`.
1406///
1407/// `parent` owns the list: the delegate's truncation and, through it, a node's own filtering see
1408/// it, and it is null only for a node that could not name itself (see [`base_json_map`]).
1409pub fn to_json_list(
1410    nodes: Vec<Rc<dyn DiagnosticsNode>>,
1411    parent: Option<&dyn DiagnosticsNode>,
1412    delegate: &dyn DiagnosticsSerializationDelegate,
1413) -> Vec<DiagnosticsJsonMap> {
1414    let original_node_count = nodes.len();
1415    let mut nodes = delegate.truncate_nodes_list(nodes, parent);
1416    let mut truncated = false;
1417    if nodes.len() != original_node_count {
1418        nodes.push(Rc::new(message("...")));
1419        truncated = true;
1420    }
1421    let mut json: Vec<DiagnosticsJsonMap> = nodes
1422        .iter()
1423        .map(|node| {
1424            let node_delegate = delegate.delegate_for_node(node.as_ref());
1425            node.to_json_map(node_delegate.as_ref())
1426        })
1427        .collect();
1428    if truncated {
1429        json.last_mut()
1430            .expect("a truncated list holds its hint")
1431            .insert("truncated".to_string(), Value::Bool(true));
1432    }
1433    json
1434}
1435
1436/// Defines diagnostics data for a value.
1437///
1438/// Dart's `DiagnosticsNode`. Rust keeps Flutter's member set on a trait because
1439/// each node class has its own storage.
1440pub trait DiagnosticsNode: fmt::Display {
1441    /// Label describing the node, typically shown before a separator.
1442    fn name(&self) -> Option<&str> {
1443        None
1444    }
1445
1446    /// Returns a description with a short summary of the node itself not
1447    /// including children or properties.
1448    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String;
1449
1450    /// Whether to show a separator between [`name`](Self::name) and
1451    /// [`to_description`](Self::to_description).
1452    fn show_separator(&self) -> bool {
1453        true
1454    }
1455
1456    /// Whether the diagnostic should be filtered because its level is lower
1457    /// than `min_level`.
1458    fn is_filtered(&self, min_level: DiagnosticLevel) -> bool {
1459        self.level().index() < min_level.index()
1460    }
1461
1462    /// Priority level of the diagnostic.
1463    fn level(&self) -> DiagnosticLevel {
1464        DiagnosticLevel::Info
1465    }
1466
1467    /// Whether the name of the property should be shown when showing the
1468    /// default view of the tree.
1469    fn show_name(&self) -> bool {
1470        true
1471    }
1472
1473    /// Prefix to include at the start of each line.
1474    fn line_prefix(&self) -> Option<&str> {
1475        None
1476    }
1477
1478    /// Description to show if the node has no displayed properties or children.
1479    fn empty_body_description(&self) -> Option<&str> {
1480        None
1481    }
1482
1483    /// The actual object this diagnostics data is for.
1484    ///
1485    /// A snapshot node ([`DiagnosticableNode`]) does not keep the arena object,
1486    /// so it answers none.
1487    fn value(&self) -> Option<&dyn Any> {
1488        None
1489    }
1490
1491    /// The arena object this node describes, when it describes one.
1492    ///
1493    /// A snapshot node keeps no object, so where Dart's `value` is the object itself, a node
1494    /// built from one names it by handle and answers it here. The JSON does not print it; a
1495    /// serialization delegate adds it as `valueId`.
1496    fn value_id(&self) -> Option<HandleId> {
1497        None
1498    }
1499
1500    /// Dart's `Object.runtimeType.toString()`: the class name, as JSON's `type` prints it.
1501    fn type_name(&self) -> &'static str {
1502        bare_type_name(std::any::type_name::<Self>())
1503    }
1504
1505    /// Hint for how the node should be displayed.
1506    fn style(&self) -> Option<DiagnosticsTreeStyle>;
1507
1508    /// Whether to wrap text onto multiple lines.
1509    fn allow_wrap(&self) -> bool {
1510        false
1511    }
1512
1513    /// Whether to wrap the name onto multiple lines.
1514    fn allow_name_wrap(&self) -> bool {
1515        false
1516    }
1517
1518    /// Whether to allow truncation when displaying the node and its children.
1519    fn allow_truncate(&self) -> bool {
1520        false
1521    }
1522
1523    /// Properties of this node.
1524    fn get_properties(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
1525        Vec::new()
1526    }
1527
1528    /// Children of this node.
1529    fn get_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
1530        Vec::new()
1531    }
1532
1533    /// Configuration specifying how this node should be rendered as text art.
1534    fn text_tree_configuration(&self) -> Option<&TextTreeConfiguration> {
1535        self.style().and_then(text_tree_configuration_for)
1536    }
1537
1538    /// Dart's `_separator`.
1539    fn separator(&self) -> &str {
1540        if self.show_separator() { ":" } else { "" }
1541    }
1542
1543    /// Converts the properties of this node to a form useful for timeline
1544    /// event arguments. Children are omitted.
1545    fn to_timeline_arguments(&self) -> Option<IndexMap<String, String>> {
1546        let mut result = IndexMap::new();
1547        for property in self.get_properties() {
1548            if let Some(name) = property.name() {
1549                result.insert(
1550                    name.to_string(),
1551                    property.to_description(Some(single_line_text_configuration())),
1552                );
1553            }
1554        }
1555        Some(result)
1556    }
1557
1558    /// Serializes the node to a JSON map according to the configuration provided in the
1559    /// [`DiagnosticsSerializationDelegate`]: Dart's `toJsonMap`.
1560    ///
1561    /// Required, where Dart's base class gives a body: a provided method cannot hand `&self` to
1562    /// the delegate as the `&dyn DiagnosticsNode` its hooks are given. A node class starts from
1563    /// [`base_json_map`] (`super.toJsonMap`), or from the JSON of the property it wraps, and adds
1564    /// its own fields.
1565    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap;
1566
1567    /// Returns a string representation compatible with the style of the parent
1568    /// if the node is not the root.
1569    fn to_string_with(
1570        &self,
1571        parent_configuration: Option<&TextTreeConfiguration>,
1572        min_level: DiagnosticLevel,
1573    ) -> String {
1574        if is_single_line(self.style()) {
1575            self.to_string_deep_with("", None, parent_configuration, min_level, 65)
1576        } else {
1577            let description = self.to_description(parent_configuration);
1578            match self.name() {
1579                Some(name) if !name.is_empty() && self.show_name() => {
1580                    if description.contains('\n') {
1581                        format!("{name}{}\n{description}", self.separator())
1582                    } else {
1583                        format!("{name}{} {description}", self.separator())
1584                    }
1585                }
1586                _ => description,
1587            }
1588        }
1589    }
1590
1591    /// Returns a string representation of this node and its descendants with
1592    /// Dart's default arguments.
1593    fn to_string_deep(&self) -> String {
1594        self.to_string_deep_with("", None, None, DiagnosticLevel::Debug, 65)
1595    }
1596
1597    /// Returns a string representation of this node and its descendants.
1598    ///
1599    /// Implementations forward to [`TextTreeRenderer`]; the method is required
1600    /// rather than provided because `self` cannot be coerced to
1601    /// `&dyn DiagnosticsNode` where `Self` is unsized.
1602    fn to_string_deep_with(
1603        &self,
1604        prefix_line_one: &str,
1605        prefix_other_lines: Option<&str>,
1606        parent_configuration: Option<&TextTreeConfiguration>,
1607        min_level: DiagnosticLevel,
1608        wrap_width: usize,
1609    ) -> String;
1610}
1611
1612macro_rules! render_deep_with {
1613    () => {
1614        fn to_string_deep_with(
1615            &self,
1616            prefix_line_one: &str,
1617            prefix_other_lines: Option<&str>,
1618            parent_configuration: Option<&TextTreeConfiguration>,
1619            min_level: DiagnosticLevel,
1620            wrap_width: usize,
1621        ) -> String {
1622            TextTreeRenderer::new()
1623                .min_level(min_level)
1624                .wrap_width(wrap_width)
1625                .render_with(
1626                    self,
1627                    prefix_line_one,
1628                    prefix_other_lines,
1629                    parent_configuration,
1630                )
1631        }
1632    };
1633}
1634
1635impl DiagnosticsNode for Rc<dyn DiagnosticsNode> {
1636    fn name(&self) -> Option<&str> {
1637        (**self).name()
1638    }
1639
1640    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
1641        (**self).to_description(parent_configuration)
1642    }
1643
1644    fn show_separator(&self) -> bool {
1645        (**self).show_separator()
1646    }
1647
1648    fn level(&self) -> DiagnosticLevel {
1649        (**self).level()
1650    }
1651
1652    fn show_name(&self) -> bool {
1653        (**self).show_name()
1654    }
1655
1656    fn line_prefix(&self) -> Option<&str> {
1657        (**self).line_prefix()
1658    }
1659
1660    fn empty_body_description(&self) -> Option<&str> {
1661        (**self).empty_body_description()
1662    }
1663
1664    fn value(&self) -> Option<&dyn Any> {
1665        (**self).value()
1666    }
1667
1668    fn value_id(&self) -> Option<HandleId> {
1669        (**self).value_id()
1670    }
1671
1672    fn type_name(&self) -> &'static str {
1673        (**self).type_name()
1674    }
1675
1676    fn style(&self) -> Option<DiagnosticsTreeStyle> {
1677        (**self).style()
1678    }
1679
1680    fn allow_wrap(&self) -> bool {
1681        (**self).allow_wrap()
1682    }
1683
1684    fn allow_name_wrap(&self) -> bool {
1685        (**self).allow_name_wrap()
1686    }
1687
1688    fn allow_truncate(&self) -> bool {
1689        (**self).allow_truncate()
1690    }
1691
1692    fn get_properties(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
1693        (**self).get_properties()
1694    }
1695
1696    fn get_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
1697        (**self).get_children()
1698    }
1699
1700    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
1701        (**self).to_json_map(delegate)
1702    }
1703
1704    fn to_string_deep_with(
1705        &self,
1706        prefix_line_one: &str,
1707        prefix_other_lines: Option<&str>,
1708        parent_configuration: Option<&TextTreeConfiguration>,
1709        min_level: DiagnosticLevel,
1710        wrap_width: usize,
1711    ) -> String {
1712        (**self).to_string_deep_with(
1713            prefix_line_one,
1714            prefix_other_lines,
1715            parent_configuration,
1716            min_level,
1717            wrap_width,
1718        )
1719    }
1720}
1721
1722/// A property's name, which Dart lets be `null`: a string where there is one, `None` where
1723/// there is not, so a property reads as Dart's does: `IntProperty::new("depth", depth)`.
1724pub trait IntoPropertyName {
1725    fn into_property_name(self) -> Option<String>;
1726}
1727
1728impl IntoPropertyName for &str {
1729    fn into_property_name(self) -> Option<String> {
1730        Some(self.to_owned())
1731    }
1732}
1733
1734impl IntoPropertyName for String {
1735    fn into_property_name(self) -> Option<String> {
1736        Some(self)
1737    }
1738}
1739
1740impl IntoPropertyName for Option<String> {
1741    fn into_property_name(self) -> Option<String> {
1742        self
1743    }
1744}
1745
1746/// Signature for computing the value of a property.
1747///
1748/// It is called the first time the value is read, as Dart's `computeValue` is. Dart catches what
1749/// it throws and shows `EXCEPTION`; a panic here ends the program, as any panic does.
1750pub type ComputePropertyValueCallback<T> = Rc<dyn Fn() -> Option<T>>;
1751
1752enum PropertyValue<T> {
1753    Direct(Option<T>),
1754    Lazy(LazyValue<T>),
1755}
1756
1757struct LazyValue<T> {
1758    compute: ComputePropertyValueCallback<T>,
1759    value: OnceCell<Option<T>>,
1760}
1761
1762/// Dart's `DiagnosticsProperty<T>` fields and shared behavior.
1763///
1764/// The property classes have no inheritance in Rust; each one owns one of these and hands it out
1765/// through `property_data`, as Flutter's subclasses inherit the fields.
1766pub struct PropertyData<T> {
1767    /// Label describing the node.
1768    pub name: Option<String>,
1769    /// Description of the property value, when it is not given by `Display`.
1770    pub description: Option<String>,
1771    /// Description if the property value is null, including `'MISSING'` when
1772    /// `missingIfNull` is set.
1773    pub if_null: Option<String>,
1774    /// Description if the property description would otherwise be empty.
1775    pub if_empty: Option<String>,
1776    /// Whether the name of the property should be shown.
1777    pub show_name: bool,
1778    /// Whether a separator is shown between the name and description.
1779    pub show_separator: bool,
1780    /// The default value of this property. The outer option is Dart's
1781    /// `kNoDefaultValue`; the inner one is a default of null.
1782    pub default_value: Option<Option<T>>,
1783    /// Optional tooltip describing the property.
1784    pub tooltip: Option<String>,
1785    /// Whether a null value makes the property a warning.
1786    pub missing_if_null: bool,
1787    /// Prefix to include at the start of each line.
1788    pub line_prefix: Option<String>,
1789    /// Whether to expose properties and children of the value.
1790    pub expandable_value: bool,
1791    /// Whether to wrap text onto multiple lines.
1792    pub allow_wrap: bool,
1793    /// Whether to wrap the name onto multiple lines.
1794    pub allow_name_wrap: bool,
1795    /// Hint for how the node should be displayed.
1796    pub style: Option<DiagnosticsTreeStyle>,
1797    default_level: DiagnosticLevel,
1798    /// Whether `if_null` was given by the caller rather than filled from
1799    /// `missing_if_null`.
1800    if_null_explicit: bool,
1801    value: PropertyValue<T>,
1802}
1803
1804impl<T> PropertyData<T> {
1805    fn new(name: Option<String>, value: Option<T>) -> Self {
1806        assert_node_name(&name);
1807        PropertyData {
1808            name,
1809            description: None,
1810            if_null: None,
1811            if_empty: None,
1812            show_name: true,
1813            show_separator: true,
1814            default_value: None,
1815            tooltip: None,
1816            missing_if_null: false,
1817            line_prefix: None,
1818            expandable_value: false,
1819            allow_wrap: true,
1820            allow_name_wrap: true,
1821            style: Some(DiagnosticsTreeStyle::SingleLine),
1822            default_level: DiagnosticLevel::Info,
1823            if_null_explicit: false,
1824            value: PropertyValue::Direct(value),
1825        }
1826    }
1827
1828    fn lazy(name: Option<String>, compute: ComputePropertyValueCallback<T>) -> Self {
1829        assert_node_name(&name);
1830        PropertyData {
1831            name,
1832            description: None,
1833            if_null: None,
1834            if_empty: None,
1835            show_name: true,
1836            show_separator: true,
1837            default_value: None,
1838            tooltip: None,
1839            missing_if_null: false,
1840            line_prefix: None,
1841            expandable_value: false,
1842            allow_wrap: true,
1843            allow_name_wrap: true,
1844            style: Some(DiagnosticsTreeStyle::SingleLine),
1845            default_level: DiagnosticLevel::Info,
1846            if_null_explicit: false,
1847            value: PropertyValue::Lazy(LazyValue {
1848                compute,
1849                value: OnceCell::new(),
1850            }),
1851        }
1852    }
1853
1854    /// Returns the value of the property, computing it on first read when the
1855    /// property was built with `lazy`.
1856    pub fn value(&self) -> Option<&T> {
1857        match &self.value {
1858            PropertyValue::Direct(value) => value.as_ref(),
1859            PropertyValue::Lazy(lazy) => lazy.value.get_or_init(|| (lazy.compute)()).as_ref(),
1860        }
1861    }
1862
1863    /// Dart's `ifNull`, including `'MISSING'` when `missingIfNull` is set.
1864    pub fn effective_if_null(&self) -> Option<&str> {
1865        self.if_null.as_deref()
1866    }
1867
1868    fn set_if_null(&mut self, if_null: String) {
1869        self.if_null = Some(if_null);
1870        self.if_null_explicit = true;
1871    }
1872
1873    fn set_missing_if_null(&mut self, missing_if_null: bool) {
1874        self.missing_if_null = missing_if_null;
1875        if missing_if_null {
1876            if self.if_null.is_none() {
1877                self.if_null = Some("MISSING".to_string());
1878            }
1879        } else if !self.if_null_explicit {
1880            self.if_null = None;
1881        }
1882    }
1883
1884    /// Additional properties are exposed when the value is itself a node.
1885    fn expandable_node(&self) -> Option<Rc<dyn DiagnosticsNode>>
1886    where
1887        T: Any,
1888    {
1889        if !self.expandable_value {
1890            return None;
1891        }
1892        self.node_value()
1893    }
1894
1895    /// The value as a node, when it is one: Waft's stand-in for Dart's `value is Diagnosticable`.
1896    ///
1897    /// A `Diagnosticable` value that is not a node cannot be told apart from any other `T`; see
1898    /// `PORTING.md`.
1899    fn node_value(&self) -> Option<Rc<dyn DiagnosticsNode>>
1900    where
1901        T: Any,
1902    {
1903        let value = self.value()?;
1904        let any = value as &dyn Any;
1905        any.downcast_ref::<Rc<dyn DiagnosticsNode>>().cloned()
1906    }
1907}
1908
1909impl<T: Any> PropertyData<T> {
1910    /// Dart's `DiagnosticsProperty.propertyType`.
1911    pub fn property_type(&self) -> &'static str {
1912        bare_type_name(std::any::type_name::<T>())
1913    }
1914
1915    /// The JSON value of Dart's `toJsonMap` value rules: a number, string, bool or null, and
1916    /// nothing for a value that is an object.
1917    fn json_value(&self) -> Option<Value> {
1918        let Some(value) = self.value() else {
1919            return Some(Value::Null);
1920        };
1921        let any = value as &dyn Any;
1922        if let Some(text) = any.downcast_ref::<String>() {
1923            return Some(Value::String(text.clone()));
1924        }
1925        if let Some(flag) = any.downcast_ref::<bool>() {
1926            return Some(Value::Bool(*flag));
1927        }
1928        if let Some(number) = any.downcast_ref::<f64>() {
1929            return Some(json_double(*number));
1930        }
1931        if let Some(number) = any.downcast_ref::<f32>() {
1932            return Some(json_double(f64::from(*number)));
1933        }
1934        if let Some(number) = any.downcast_ref::<i64>() {
1935            return Some(Value::Number((*number).into()));
1936        }
1937        if let Some(number) = any.downcast_ref::<u64>() {
1938            return Some(Value::Number((*number).into()));
1939        }
1940        macro_rules! smaller_number {
1941            ($($type:ty),+) => {
1942                $(
1943                    if let Some(number) = any.downcast_ref::<$type>() {
1944                        return Some(Value::Number((*number as i64).into()));
1945                    }
1946                )+
1947            };
1948        }
1949        smaller_number!(i8, i16, i32, isize);
1950        macro_rules! small_unsigned_number {
1951            ($($type:ty),+) => {
1952                $(
1953                    if let Some(number) = any.downcast_ref::<$type>() {
1954                        return Some(Value::Number((*number as u64).into()));
1955                    }
1956                )+
1957            };
1958        }
1959        small_unsigned_number!(u8, u16, u32, usize);
1960        None
1961    }
1962
1963    /// Dart's `DiagnosticsProperty.toJsonMap`, the JSON every property class starts from.
1964    ///
1965    /// `default_value` is Dart's `defaultValue.toString()`, which Rust cannot print for every `T`;
1966    /// the property class, which knows whether its `T` is `Display`, `Debug` or a list, prints it.
1967    fn json_map(
1968        &self,
1969        node: &dyn DiagnosticsNode,
1970        delegate: &dyn DiagnosticsSerializationDelegate,
1971        default_value: Option<String>,
1972    ) -> DiagnosticsJsonMap {
1973        let mut properties_json: Option<Vec<DiagnosticsJsonMap>> = None;
1974        let mut copied_delegate: Option<Rc<dyn DiagnosticsSerializationDelegate>> = None;
1975        if delegate.expand_property_values()
1976            && delegate.include_properties()
1977            && let Some(value_node) = self.node_value()
1978            && node.get_properties().is_empty()
1979        {
1980            // Exclude children for expanded nodes to avoid cycles.
1981            let copied = delegate.copy_with(Some(0), Some(false));
1982            properties_json = Some(to_json_list(
1983                copied.filter_properties(value_node.get_properties(), node),
1984                Some(node),
1985                copied.as_ref(),
1986            ));
1987            copied_delegate = Some(copied);
1988        }
1989        let delegate: &dyn DiagnosticsSerializationDelegate = match &copied_delegate {
1990            Some(copied) => copied.as_ref(),
1991            None => delegate,
1992        };
1993        let mut json = base_json_map(node, delegate);
1994        if let Some(properties) = properties_json {
1995            json_put(&mut json, "properties", json_array(properties));
1996        }
1997        if let Some(default_value) = default_value {
1998            json_put(&mut json, "defaultValue", Value::String(default_value));
1999        }
2000        if let Some(if_empty) = &self.if_empty {
2001            json_put(&mut json, "ifEmpty", Value::String(if_empty.clone()));
2002        }
2003        if let Some(if_null) = self.effective_if_null() {
2004            json_put(&mut json, "ifNull", Value::String(if_null.to_string()));
2005        }
2006        if let Some(tooltip) = &self.tooltip {
2007            json_put(&mut json, "tooltip", Value::String(tooltip.clone()));
2008        }
2009        json_put(
2010            &mut json,
2011            "missingIfNull",
2012            Value::Bool(self.missing_if_null),
2013        );
2014        // Dart prints a caught exception's `toString`; a computed value here cannot throw, so
2015        // there is no `exception` field to print.
2016        json_put(
2017            &mut json,
2018            "propertyType",
2019            Value::String(self.property_type().to_string()),
2020        );
2021        json_put(
2022            &mut json,
2023            "defaultLevel",
2024            Value::String(self.default_level.name().to_string()),
2025        );
2026        if self.node_value().is_some() {
2027            json_put(&mut json, "isDiagnosticableValue", Value::Bool(true));
2028        }
2029        if let Some(value) = self.json_value() {
2030            json_put(&mut json, "value", value);
2031        }
2032        json
2033    }
2034}
2035
2036/// Dart's JSON for a `double` value: the number, or its text for a non-finite one, which JSON
2037/// cannot carry.
2038fn json_double(value: f64) -> Value {
2039    match serde_json::Number::from_f64(value) {
2040        Some(number) => Value::Number(number),
2041        None => Value::String(dart_double_to_string(value)),
2042    }
2043}
2044
2045/// Dart's `defaultValue.toString()` for a value whose Rust type is `Display`.
2046fn json_default_value<T: fmt::Display + Any>(default_value: &Option<Option<T>>) -> Option<String> {
2047    default_value.as_ref().map(|value| match value {
2048        Some(value) => dart_value_to_string(value as &dyn Any, value.to_string()),
2049        None => "null".to_string(),
2050    })
2051}
2052
2053/// Dart's `defaultValue.toString()` for an `IterableProperty`'s list, which prints as a Dart list.
2054fn json_iterable_default_value<T: fmt::Display + Any>(
2055    default_value: &Option<Option<Vec<T>>>,
2056) -> Option<String> {
2057    default_value.as_ref().map(|value| match value {
2058        Some(values) => format!(
2059            "[{}]",
2060            values
2061                .iter()
2062                .map(|value| dart_value_to_string(value as &dyn Any, value.to_string()))
2063                .collect::<Vec<_>>()
2064                .join(", ")
2065        ),
2066        None => "null".to_string(),
2067    })
2068}
2069
2070/// Dart's `defaultValue.toString()` for an enum, which prints its type and case.
2071fn json_enum_default_value<T: fmt::Debug>(default_value: &Option<Option<T>>) -> Option<String> {
2072    default_value.as_ref().map(|value| match value {
2073        Some(value) => format!(
2074            "{}.{}",
2075            bare_type_name(std::any::type_name::<T>()),
2076            describe_enum(value)
2077        ),
2078        None => "null".to_string(),
2079    })
2080}
2081
2082impl<T> PropertyData<T> {
2083    fn add_tooltip(&self, text: &str) -> String {
2084        match &self.tooltip {
2085            Some(tooltip) => format!("{text} ({tooltip})"),
2086            None => text.to_string(),
2087        }
2088    }
2089
2090    /// Dart's `DiagnosticsProperty.toDescription`, with the subclass's
2091    /// `valueToString` supplied by the caller.
2092    fn to_description_with(
2093        &self,
2094        parent_configuration: Option<&TextTreeConfiguration>,
2095        value_to_string: impl FnOnce(Option<&TextTreeConfiguration>) -> String,
2096    ) -> String {
2097        if let Some(description) = &self.description {
2098            return self.add_tooltip(description);
2099        }
2100
2101        if let Some(if_null) = self.effective_if_null()
2102            && self.value().is_none()
2103        {
2104            return self.add_tooltip(if_null);
2105        }
2106
2107        let mut result = value_to_string(parent_configuration);
2108        if result.is_empty()
2109            && let Some(if_empty) = &self.if_empty
2110        {
2111            result = if_empty.clone();
2112        }
2113        self.add_tooltip(&result)
2114    }
2115}
2116
2117impl<T: PartialEq> PropertyData<T> {
2118    /// Whether the value differs from Dart's `defaultValue`.
2119    pub fn is_interesting(&self) -> bool {
2120        match &self.default_value {
2121            None => true,
2122            Some(default_value) => self.value() != default_value.as_ref(),
2123        }
2124    }
2125
2126    /// Dart's `DiagnosticsProperty.level` before a subclass overrides it.
2127    pub fn base_level(&self) -> DiagnosticLevel {
2128        if self.default_level == DiagnosticLevel::Hidden {
2129            return self.default_level;
2130        }
2131        if self.value().is_none() && self.missing_if_null {
2132            return DiagnosticLevel::Warning;
2133        }
2134        if !self.is_interesting() {
2135            return DiagnosticLevel::Fine;
2136        }
2137        self.default_level
2138    }
2139}
2140
2141impl<T: fmt::Display> PropertyData<T> {
2142    /// Dart's `DiagnosticsProperty.valueToString`.
2143    pub fn base_value_to_string(
2144        &self,
2145        _parent_configuration: Option<&TextTreeConfiguration>,
2146    ) -> String {
2147        match self.value() {
2148            Some(value) => value.to_string(),
2149            None => "null".to_string(),
2150        }
2151    }
2152}
2153
2154impl<T: fmt::Display + PartialEq> PropertyData<T> {
2155    /// Dart's `DiagnosticsProperty.toDescription`.
2156    pub fn base_to_description(
2157        &self,
2158        parent_configuration: Option<&TextTreeConfiguration>,
2159    ) -> String {
2160        self.to_description_with(parent_configuration, |parent| {
2161            self.base_value_to_string(parent)
2162        })
2163    }
2164}
2165
2166fn assert_node_name(name: &Option<String>) {
2167    debug_assert!(
2168        name.as_deref().is_none_or(|name| !name.ends_with(':')),
2169        "Names of diagnostic nodes must not end with colons.\nname:\n  \"{}\"",
2170        name.as_deref().unwrap_or("")
2171    );
2172}
2173
2174/// Property with a value of type `T`.
2175///
2176/// If the default `value.toString()` does not provide an adequate description
2177/// of the value, specify a `description`.
2178pub struct DiagnosticsProperty<T> {
2179    data: PropertyData<T>,
2180}
2181
2182impl<T> DiagnosticsProperty<T> {
2183    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
2184    /// inherited members.
2185    pub fn property_data(&self) -> &PropertyData<T> {
2186        &self.data
2187    }
2188}
2189
2190impl<T> DiagnosticsProperty<T> {
2191    /// Creates a diagnostics property.
2192    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<T>>) -> Self {
2193        let (value, name) = (value.into(), name.into_property_name());
2194        DiagnosticsProperty {
2195            data: PropertyData::new(name, value),
2196        }
2197    }
2198
2199    /// Property with a value that is computed only when needed.
2200    ///
2201    /// Use if computing the value may panic or is expensive.
2202    pub fn lazy(
2203        name: impl IntoPropertyName,
2204        compute_value: ComputePropertyValueCallback<T>,
2205    ) -> Self {
2206        let name = name.into_property_name();
2207        DiagnosticsProperty {
2208            data: PropertyData::lazy(name, compute_value),
2209        }
2210    }
2211
2212    /// Dart `DiagnosticsProperty(description:)`.
2213    pub fn description(mut self, description: impl Into<String>) -> Self {
2214        self.data.description = Some(description.into());
2215        self
2216    }
2217
2218    /// Dart `DiagnosticsProperty(ifNull:)`.
2219    pub fn if_null(mut self, if_null: impl Into<String>) -> Self {
2220        self.data.set_if_null(if_null.into());
2221        self
2222    }
2223
2224    /// Dart `DiagnosticsProperty(ifEmpty:)`.
2225    pub fn if_empty(mut self, if_empty: impl Into<String>) -> Self {
2226        self.data.if_empty = Some(if_empty.into());
2227        self
2228    }
2229
2230    /// Dart `DiagnosticsProperty(showName:)`.
2231    pub fn with_show_name(mut self, show_name: bool) -> Self {
2232        self.data.show_name = show_name;
2233        self
2234    }
2235
2236    /// Dart `DiagnosticsProperty(showSeparator:)`.
2237    pub fn with_show_separator(mut self, show_separator: bool) -> Self {
2238        self.data.show_separator = show_separator;
2239        self
2240    }
2241
2242    /// Dart `DiagnosticsProperty(defaultValue:)`. A default of `None` is
2243    /// Dart's `defaultValue: null`.
2244    pub fn default_value(mut self, default_value: Option<T>) -> Self {
2245        self.data.default_value = Some(default_value);
2246        self
2247    }
2248
2249    /// Dart `DiagnosticsProperty(tooltip:)`.
2250    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
2251        self.data.tooltip = Some(tooltip.into());
2252        self
2253    }
2254
2255    /// Dart `DiagnosticsProperty(missingIfNull:)`.
2256    pub fn missing_if_null(mut self, missing_if_null: bool) -> Self {
2257        self.data.set_missing_if_null(missing_if_null);
2258        self
2259    }
2260
2261    /// Dart `DiagnosticsProperty(linePrefix:)`.
2262    pub fn with_line_prefix(mut self, line_prefix: impl Into<String>) -> Self {
2263        self.data.line_prefix = Some(line_prefix.into());
2264        self
2265    }
2266
2267    /// Dart `DiagnosticsProperty(expandableValue:)`.
2268    pub fn expandable_value(mut self, expandable_value: bool) -> Self {
2269        self.data.expandable_value = expandable_value;
2270        self
2271    }
2272
2273    /// Dart `DiagnosticsProperty(allowWrap:)`.
2274    pub fn with_allow_wrap(mut self, allow_wrap: bool) -> Self {
2275        self.data.allow_wrap = allow_wrap;
2276        self
2277    }
2278
2279    /// Dart `DiagnosticsProperty(allowNameWrap:)`.
2280    pub fn with_allow_name_wrap(mut self, allow_name_wrap: bool) -> Self {
2281        self.data.allow_name_wrap = allow_name_wrap;
2282        self
2283    }
2284
2285    /// Dart `DiagnosticsProperty(style:)`.
2286    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
2287        self.data.style = Some(style);
2288        self
2289    }
2290
2291    /// Dart `DiagnosticsProperty(level:)`.
2292    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
2293        self.data.default_level = level;
2294        self
2295    }
2296
2297    /// The value of the property, computed on first read for a lazy property.
2298    pub fn value(&self) -> Option<&T> {
2299        self.data.value()
2300    }
2301}
2302
2303impl<T> DiagnosticsNode for DiagnosticsProperty<T>
2304where
2305    T: fmt::Display + PartialEq + Any,
2306{
2307    fn name(&self) -> Option<&str> {
2308        self.data.name.as_deref()
2309    }
2310
2311    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
2312        self.data.base_to_description(parent_configuration)
2313    }
2314
2315    fn show_separator(&self) -> bool {
2316        self.data.show_separator
2317    }
2318
2319    fn level(&self) -> DiagnosticLevel {
2320        self.data.base_level()
2321    }
2322
2323    fn show_name(&self) -> bool {
2324        self.data.show_name
2325    }
2326
2327    fn line_prefix(&self) -> Option<&str> {
2328        self.data.line_prefix.as_deref()
2329    }
2330
2331    fn style(&self) -> Option<DiagnosticsTreeStyle> {
2332        self.data.style
2333    }
2334
2335    fn allow_wrap(&self) -> bool {
2336        self.data.allow_wrap
2337    }
2338
2339    fn allow_name_wrap(&self) -> bool {
2340        self.data.allow_name_wrap
2341    }
2342
2343    fn value(&self) -> Option<&dyn Any> {
2344        self.data.value().map(|value| value as &dyn Any)
2345    }
2346
2347    fn get_properties(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
2348        self.data
2349            .expandable_node()
2350            .map(|node| node.get_properties())
2351            .unwrap_or_default()
2352    }
2353
2354    fn get_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
2355        self.data
2356            .expandable_node()
2357            .map(|node| node.get_children())
2358            .unwrap_or_default()
2359    }
2360
2361    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
2362        self.data
2363            .json_map(self, delegate, json_default_value(&self.data.default_value))
2364    }
2365
2366    render_deep_with!();
2367}
2368
2369impl<T> fmt::Display for DiagnosticsProperty<T>
2370where
2371    T: fmt::Display + PartialEq + Any,
2372{
2373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2374        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
2375    }
2376}
2377
2378/// Debugging message displayed like a property.
2379pub struct MessageProperty {
2380    property: DiagnosticsProperty<String>,
2381}
2382
2383impl MessageProperty {
2384    /// The value of the property, always none for a message.
2385    pub fn value(&self) -> Option<&String> {
2386        self.property.value()
2387    }
2388
2389    /// Create a diagnostics property that displays a message.
2390    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
2391        MessageProperty {
2392            property: DiagnosticsProperty::new(Some(name.into()), None).description(message),
2393        }
2394    }
2395
2396    /// Dart `MessageProperty(style:)`.
2397    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
2398        self.property = self.property.with_style(style);
2399        self
2400    }
2401
2402    /// Dart `MessageProperty(level:)`.
2403    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
2404        self.property = self.property.with_level(level);
2405        self
2406    }
2407}
2408
2409impl MessageProperty {
2410    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
2411    /// inherited members.
2412    pub fn property_data(&self) -> &PropertyData<String> {
2413        self.property.property_data()
2414    }
2415}
2416
2417impl DiagnosticsNode for MessageProperty {
2418    fn name(&self) -> Option<&str> {
2419        self.property.name()
2420    }
2421
2422    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
2423        self.property.to_description(parent_configuration)
2424    }
2425
2426    fn level(&self) -> DiagnosticLevel {
2427        self.property.level()
2428    }
2429
2430    fn show_name(&self) -> bool {
2431        self.property.show_name()
2432    }
2433
2434    fn value(&self) -> Option<&dyn Any> {
2435        DiagnosticsNode::value(&self.property)
2436    }
2437
2438    fn style(&self) -> Option<DiagnosticsTreeStyle> {
2439        self.property.style()
2440    }
2441
2442    fn allow_wrap(&self) -> bool {
2443        self.property.allow_wrap()
2444    }
2445
2446    fn allow_name_wrap(&self) -> bool {
2447        self.property.allow_name_wrap()
2448    }
2449
2450    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
2451        let mut json = self.property.property_data().json_map(
2452            self,
2453            delegate,
2454            json_default_value(&self.property.property_data().default_value),
2455        );
2456        // The property's value type is `void` in Dart: its message is a description, and its
2457        // value is always null.
2458        json_put(&mut json, "propertyType", Value::String("void".to_string()));
2459        json
2460    }
2461
2462    render_deep_with!();
2463}
2464
2465impl fmt::Display for MessageProperty {
2466    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2467        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
2468    }
2469}
2470
2471/// Property which encloses its string value in quotes.
2472pub struct StringProperty {
2473    data: PropertyData<String>,
2474    /// Whether the value is enclosed in double quotes.
2475    pub quoted: bool,
2476}
2477
2478impl StringProperty {
2479    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
2480    /// inherited members.
2481    pub fn property_data(&self) -> &PropertyData<String> {
2482        &self.data
2483    }
2484}
2485
2486impl StringProperty {
2487    /// The value of the property.
2488    pub fn value(&self) -> Option<&String> {
2489        self.data.value()
2490    }
2491
2492    /// Create a diagnostics property for strings.
2493    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<String>>) -> Self {
2494        let (value, name) = (value.into(), name.into_property_name());
2495        StringProperty {
2496            data: PropertyData::new(name, value),
2497            quoted: true,
2498        }
2499    }
2500
2501    /// Dart `StringProperty(description:)`.
2502    pub fn description(mut self, description: impl Into<String>) -> Self {
2503        self.data.description = Some(description.into());
2504        self
2505    }
2506
2507    /// Dart `StringProperty(tooltip:)`.
2508    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
2509        self.data.tooltip = Some(tooltip.into());
2510        self
2511    }
2512
2513    /// Dart `StringProperty(showName:)`.
2514    pub fn with_show_name(mut self, show_name: bool) -> Self {
2515        self.data.show_name = show_name;
2516        self
2517    }
2518
2519    /// Dart `StringProperty(defaultValue:)`.
2520    pub fn default_value(mut self, default_value: Option<String>) -> Self {
2521        self.data.default_value = Some(default_value);
2522        self
2523    }
2524
2525    /// Dart `StringProperty(quoted:)`.
2526    pub fn quoted(mut self, quoted: bool) -> Self {
2527        self.quoted = quoted;
2528        self
2529    }
2530
2531    /// Dart `StringProperty(ifEmpty:)`.
2532    pub fn if_empty(mut self, if_empty: impl Into<String>) -> Self {
2533        self.data.if_empty = Some(if_empty.into());
2534        self
2535    }
2536
2537    /// Dart `StringProperty(style:)`.
2538    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
2539        self.data.style = Some(style);
2540        self
2541    }
2542
2543    /// Dart `StringProperty(level:)`.
2544    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
2545        self.data.default_level = level;
2546        self
2547    }
2548
2549    /// Dart's `StringProperty.valueToString`.
2550    pub fn value_to_string(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
2551        let mut text = self
2552            .data
2553            .description
2554            .clone()
2555            .or_else(|| self.data.value().cloned());
2556        if let Some(parent) = parent_configuration
2557            && !parent.line_break_properties
2558        {
2559            // Escape line breaks in multiline strings to avoid confusing
2560            // output when the parent of this node is trying to display all
2561            // properties on the same line.
2562            if let Some(value) = &text {
2563                text = Some(value.replace('\n', "\\n"));
2564            }
2565        }
2566
2567        match text {
2568            Some(text) => {
2569                if self.quoted {
2570                    // An empty value would not appear empty after being
2571                    // surrounded with quotes so we have to handle this case
2572                    // separately.
2573                    if let Some(if_empty) = &self.data.if_empty
2574                        && text.is_empty()
2575                    {
2576                        return if_empty.clone();
2577                    }
2578                    format!("\"{text}\"")
2579                } else {
2580                    text
2581                }
2582            }
2583            None => "null".to_string(),
2584        }
2585    }
2586}
2587
2588impl DiagnosticsNode for StringProperty {
2589    fn name(&self) -> Option<&str> {
2590        self.data.name.as_deref()
2591    }
2592
2593    fn value(&self) -> Option<&dyn Any> {
2594        self.data.value().map(|value| value as &dyn Any)
2595    }
2596
2597    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
2598        let mut json =
2599            self.data
2600                .json_map(self, delegate, json_default_value(&self.data.default_value));
2601        json_put(&mut json, "quoted", Value::Bool(self.quoted));
2602        json
2603    }
2604
2605    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
2606        self.data
2607            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
2608    }
2609
2610    fn show_separator(&self) -> bool {
2611        self.data.show_separator
2612    }
2613
2614    fn level(&self) -> DiagnosticLevel {
2615        self.data.base_level()
2616    }
2617
2618    fn show_name(&self) -> bool {
2619        self.data.show_name
2620    }
2621
2622    fn line_prefix(&self) -> Option<&str> {
2623        self.data.line_prefix.as_deref()
2624    }
2625
2626    fn style(&self) -> Option<DiagnosticsTreeStyle> {
2627        self.data.style
2628    }
2629
2630    fn allow_wrap(&self) -> bool {
2631        self.data.allow_wrap
2632    }
2633
2634    fn allow_name_wrap(&self) -> bool {
2635        self.data.allow_name_wrap
2636    }
2637
2638    render_deep_with!();
2639}
2640
2641impl fmt::Display for StringProperty {
2642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2643        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
2644    }
2645}
2646
2647/// Property describing a `f64` value with an optional unit of measurement.
2648pub struct DoubleProperty {
2649    data: PropertyData<f64>,
2650    /// Optional unit the value is measured in.
2651    pub unit: Option<String>,
2652}
2653
2654impl DoubleProperty {
2655    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
2656    /// inherited members.
2657    pub fn property_data(&self) -> &PropertyData<f64> {
2658        &self.data
2659    }
2660}
2661
2662impl DoubleProperty {
2663    /// The value of the property.
2664    pub fn value(&self) -> Option<&f64> {
2665        self.data.value()
2666    }
2667
2668    /// Create a diagnostics property for doubles.
2669    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<f64>>) -> Self {
2670        let (value, name) = (value.into(), name.into_property_name());
2671        DoubleProperty {
2672            data: PropertyData::new(name, value),
2673            unit: None,
2674        }
2675    }
2676
2677    /// Property with a value that is computed only when needed.
2678    pub fn lazy(
2679        name: impl IntoPropertyName,
2680        compute_value: ComputePropertyValueCallback<f64>,
2681    ) -> Self {
2682        let name = name.into_property_name();
2683        DoubleProperty {
2684            data: PropertyData::lazy(name, compute_value),
2685            unit: None,
2686        }
2687    }
2688
2689    /// Dart `_NumProperty(ifNull:)`.
2690    pub fn if_null(mut self, if_null: impl Into<String>) -> Self {
2691        self.data.set_if_null(if_null.into());
2692        self
2693    }
2694
2695    /// Dart `_NumProperty(unit:)`.
2696    pub fn unit(mut self, unit: impl Into<String>) -> Self {
2697        self.unit = Some(unit.into());
2698        self
2699    }
2700
2701    /// Dart `_NumProperty(tooltip:)`.
2702    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
2703        self.data.tooltip = Some(tooltip.into());
2704        self
2705    }
2706
2707    /// Dart `_NumProperty(defaultValue:)`.
2708    pub fn default_value(mut self, default_value: Option<f64>) -> Self {
2709        self.data.default_value = Some(default_value);
2710        self
2711    }
2712
2713    /// Dart `_NumProperty(showName:)`.
2714    pub fn with_show_name(mut self, show_name: bool) -> Self {
2715        self.data.show_name = show_name;
2716        self
2717    }
2718
2719    /// Dart `_NumProperty(style:)`.
2720    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
2721        self.data.style = Some(style);
2722        self
2723    }
2724
2725    /// Dart `_NumProperty(level:)`.
2726    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
2727        self.data.default_level = level;
2728        self
2729    }
2730
2731    /// String describing just the numeric value without a unit suffix.
2732    pub fn number_to_string(&self) -> String {
2733        debug_format_double(self.data.value().copied())
2734    }
2735
2736    /// Dart's `_NumProperty.valueToString`.
2737    pub fn value_to_string(&self, _parent_configuration: Option<&TextTreeConfiguration>) -> String {
2738        if self.data.value().is_none() {
2739            return "null".to_string();
2740        }
2741        match &self.unit {
2742            Some(unit) => format!("{}{unit}", self.number_to_string()),
2743            None => self.number_to_string(),
2744        }
2745    }
2746}
2747
2748impl DiagnosticsNode for DoubleProperty {
2749    fn name(&self) -> Option<&str> {
2750        self.data.name.as_deref()
2751    }
2752
2753    fn value(&self) -> Option<&dyn Any> {
2754        self.data.value().map(|value| value as &dyn Any)
2755    }
2756
2757    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
2758        let mut json =
2759            self.data
2760                .json_map(self, delegate, json_default_value(&self.data.default_value));
2761        if let Some(unit) = &self.unit {
2762            json_put(&mut json, "unit", Value::String(unit.clone()));
2763        }
2764        json_put(
2765            &mut json,
2766            "numberToString",
2767            Value::String(self.number_to_string()),
2768        );
2769        json
2770    }
2771
2772    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
2773        self.data
2774            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
2775    }
2776
2777    fn show_separator(&self) -> bool {
2778        self.data.show_separator
2779    }
2780
2781    fn level(&self) -> DiagnosticLevel {
2782        self.data.base_level()
2783    }
2784
2785    fn show_name(&self) -> bool {
2786        self.data.show_name
2787    }
2788
2789    fn line_prefix(&self) -> Option<&str> {
2790        self.data.line_prefix.as_deref()
2791    }
2792
2793    fn style(&self) -> Option<DiagnosticsTreeStyle> {
2794        self.data.style
2795    }
2796
2797    fn allow_wrap(&self) -> bool {
2798        self.data.allow_wrap
2799    }
2800
2801    fn allow_name_wrap(&self) -> bool {
2802        self.data.allow_name_wrap
2803    }
2804
2805    render_deep_with!();
2806}
2807
2808impl fmt::Display for DoubleProperty {
2809    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2810        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
2811    }
2812}
2813
2814/// An int valued property with an optional unit the value is measured in.
2815pub struct IntProperty<T = i64> {
2816    data: PropertyData<T>,
2817    /// Optional unit the value is measured in.
2818    pub unit: Option<String>,
2819}
2820
2821impl<T> IntProperty<T> {
2822    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
2823    /// inherited members.
2824    pub fn property_data(&self) -> &PropertyData<T> {
2825        &self.data
2826    }
2827}
2828
2829impl<T> IntProperty<T> {
2830    /// The value of the property.
2831    pub fn value(&self) -> Option<&T> {
2832        self.data.value()
2833    }
2834
2835    /// Create a diagnostics property for integers.
2836    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<T>>) -> Self {
2837        let (value, name) = (value.into(), name.into_property_name());
2838        IntProperty {
2839            data: PropertyData::new(name, value),
2840            unit: None,
2841        }
2842    }
2843
2844    /// Dart `_NumProperty(ifNull:)`.
2845    pub fn if_null(mut self, if_null: impl Into<String>) -> Self {
2846        self.data.set_if_null(if_null.into());
2847        self
2848    }
2849
2850    /// Dart `_NumProperty(unit:)`.
2851    pub fn unit(mut self, unit: impl Into<String>) -> Self {
2852        self.unit = Some(unit.into());
2853        self
2854    }
2855
2856    /// Dart `_NumProperty(defaultValue:)`.
2857    pub fn default_value(mut self, default_value: Option<T>) -> Self {
2858        self.data.default_value = Some(default_value);
2859        self
2860    }
2861
2862    /// Dart `_NumProperty(showName:)`.
2863    pub fn with_show_name(mut self, show_name: bool) -> Self {
2864        self.data.show_name = show_name;
2865        self
2866    }
2867
2868    /// Dart `_NumProperty(style:)`.
2869    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
2870        self.data.style = Some(style);
2871        self
2872    }
2873
2874    /// Dart `_NumProperty(level:)`.
2875    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
2876        self.data.default_level = level;
2877        self
2878    }
2879
2880    /// String describing just the numeric value without a unit suffix.
2881    pub fn number_to_string(&self) -> String
2882    where
2883        T: fmt::Display,
2884    {
2885        self.data
2886            .value()
2887            .map(ToString::to_string)
2888            .unwrap_or_else(|| "null".to_string())
2889    }
2890
2891    /// Dart's `_NumProperty.valueToString`.
2892    pub fn value_to_string(&self, _parent_configuration: Option<&TextTreeConfiguration>) -> String
2893    where
2894        T: fmt::Display,
2895    {
2896        if self.data.value().is_none() {
2897            return "null".to_string();
2898        }
2899        match &self.unit {
2900            Some(unit) => format!("{}{unit}", self.number_to_string()),
2901            None => self.number_to_string(),
2902        }
2903    }
2904}
2905
2906impl<T> DiagnosticsNode for IntProperty<T>
2907where
2908    T: fmt::Display + PartialEq + Any,
2909{
2910    fn name(&self) -> Option<&str> {
2911        self.data.name.as_deref()
2912    }
2913
2914    fn value(&self) -> Option<&dyn Any> {
2915        self.data.value().map(|value| value as &dyn Any)
2916    }
2917
2918    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
2919        let mut json =
2920            self.data
2921                .json_map(self, delegate, json_default_value(&self.data.default_value));
2922        if let Some(unit) = &self.unit {
2923            json_put(&mut json, "unit", Value::String(unit.clone()));
2924        }
2925        json_put(
2926            &mut json,
2927            "numberToString",
2928            Value::String(self.number_to_string()),
2929        );
2930        json
2931    }
2932
2933    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
2934        self.data
2935            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
2936    }
2937
2938    fn show_separator(&self) -> bool {
2939        self.data.show_separator
2940    }
2941
2942    fn level(&self) -> DiagnosticLevel {
2943        self.data.base_level()
2944    }
2945
2946    fn show_name(&self) -> bool {
2947        self.data.show_name
2948    }
2949
2950    fn line_prefix(&self) -> Option<&str> {
2951        self.data.line_prefix.as_deref()
2952    }
2953
2954    fn style(&self) -> Option<DiagnosticsTreeStyle> {
2955        self.data.style
2956    }
2957
2958    fn allow_wrap(&self) -> bool {
2959        self.data.allow_wrap
2960    }
2961
2962    fn allow_name_wrap(&self) -> bool {
2963        self.data.allow_name_wrap
2964    }
2965
2966    render_deep_with!();
2967}
2968
2969impl<T: fmt::Display + PartialEq + Any> fmt::Display for IntProperty<T> {
2970    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2971        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
2972    }
2973}
2974
2975/// Property which clamps a double to between 0 and 1 and formats it as a
2976/// percentage.
2977pub struct PercentProperty {
2978    inner: DoubleProperty,
2979}
2980
2981impl std::ops::Deref for PercentProperty {
2982    type Target = DoubleProperty;
2983
2984    fn deref(&self) -> &Self::Target {
2985        &self.inner
2986    }
2987}
2988
2989impl PercentProperty {
2990    /// The value of the property.
2991    pub fn value(&self) -> Option<&f64> {
2992        self.inner.data.value()
2993    }
2994
2995    /// Create a diagnostics property for doubles that represent percentages or
2996    /// fractions.
2997    pub fn new(name: impl IntoPropertyName, fraction: impl Into<Option<f64>>) -> Self {
2998        let (fraction, name) = (fraction.into(), name.into_property_name());
2999        PercentProperty {
3000            inner: DoubleProperty::new(name, fraction),
3001        }
3002    }
3003
3004    /// Dart `PercentProperty(ifNull:)`.
3005    pub fn if_null(mut self, if_null: impl Into<String>) -> Self {
3006        self.inner = self.inner.if_null(if_null);
3007        self
3008    }
3009
3010    /// Dart `PercentProperty(showName:)`.
3011    pub fn with_show_name(mut self, show_name: bool) -> Self {
3012        self.inner = self.inner.with_show_name(show_name);
3013        self
3014    }
3015
3016    /// Dart `PercentProperty(tooltip:)`.
3017    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
3018        self.inner = self.inner.tooltip(tooltip);
3019        self
3020    }
3021
3022    /// Dart `PercentProperty(unit:)`.
3023    pub fn unit(mut self, unit: impl Into<String>) -> Self {
3024        self.inner = self.inner.unit(unit);
3025        self
3026    }
3027
3028    /// Dart `PercentProperty(level:)`.
3029    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
3030        self.inner = self.inner.with_level(level);
3031        self
3032    }
3033
3034    /// Dart's `PercentProperty.numberToString`.
3035    pub fn number_to_string(&self) -> String {
3036        match self.inner.data.value() {
3037            None => "null".to_string(),
3038            Some(value) => {
3039                let clamped = value.clamp(0.0, 1.0);
3040                format!("{:.1}%", clamped * 100.0)
3041            }
3042        }
3043    }
3044
3045    /// Dart's `PercentProperty.valueToString`.
3046    pub fn value_to_string(&self, _parent_configuration: Option<&TextTreeConfiguration>) -> String {
3047        if self.inner.data.value().is_none() {
3048            return "null".to_string();
3049        }
3050        match &self.inner.unit {
3051            Some(unit) => format!("{} {unit}", self.number_to_string()),
3052            None => self.number_to_string(),
3053        }
3054    }
3055}
3056
3057impl DiagnosticsNode for PercentProperty {
3058    fn name(&self) -> Option<&str> {
3059        self.inner.name()
3060    }
3061
3062    fn value(&self) -> Option<&dyn Any> {
3063        DiagnosticsNode::value(&self.inner)
3064    }
3065
3066    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
3067        // Dart's `PercentProperty` inherits `DoubleProperty`'s JSON; only its number's text is
3068        // its own.
3069        let mut json = self.inner.property_data().json_map(
3070            self,
3071            delegate,
3072            json_default_value(&self.inner.property_data().default_value),
3073        );
3074        if let Some(unit) = &self.inner.unit {
3075            json_put(&mut json, "unit", Value::String(unit.clone()));
3076        }
3077        json_put(
3078            &mut json,
3079            "numberToString",
3080            Value::String(self.number_to_string()),
3081        );
3082        json
3083    }
3084
3085    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3086        self.inner
3087            .data
3088            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
3089    }
3090
3091    fn show_separator(&self) -> bool {
3092        self.inner.show_separator()
3093    }
3094
3095    fn level(&self) -> DiagnosticLevel {
3096        self.inner.level()
3097    }
3098
3099    fn show_name(&self) -> bool {
3100        self.inner.show_name()
3101    }
3102
3103    fn line_prefix(&self) -> Option<&str> {
3104        self.inner.line_prefix()
3105    }
3106
3107    fn style(&self) -> Option<DiagnosticsTreeStyle> {
3108        self.inner.style()
3109    }
3110
3111    fn allow_wrap(&self) -> bool {
3112        self.inner.allow_wrap()
3113    }
3114
3115    fn allow_name_wrap(&self) -> bool {
3116        self.inner.allow_name_wrap()
3117    }
3118
3119    render_deep_with!();
3120}
3121
3122impl fmt::Display for PercentProperty {
3123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3124        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
3125    }
3126}
3127
3128/// Property where the description is either `if_true` or `if_false` depending
3129/// on whether the value is true or false.
3130pub struct FlagProperty {
3131    data: PropertyData<bool>,
3132    /// Description to use if the property value is true.
3133    pub if_true: Option<String>,
3134    /// Description to use if the property value is false.
3135    pub if_false: Option<String>,
3136}
3137
3138impl FlagProperty {
3139    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
3140    /// inherited members.
3141    pub fn property_data(&self) -> &PropertyData<bool> {
3142        &self.data
3143    }
3144}
3145
3146impl FlagProperty {
3147    /// The value of the property.
3148    pub fn value(&self) -> Option<&bool> {
3149        self.data.value()
3150    }
3151
3152    /// Constructs a FlagProperty with the specified descriptions.
3153    ///
3154    /// `show_name` defaults to false as typically `if_true` and `if_false`
3155    /// should be descriptions that make the property name redundant.
3156    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<bool>>) -> Self {
3157        let (value, name) = (value.into(), name.into_property_name());
3158        FlagProperty {
3159            data: PropertyData::new(name, value),
3160            if_true: None,
3161            if_false: None,
3162        }
3163        .with_show_name(false)
3164    }
3165
3166    /// Dart `FlagProperty(ifTrue:)`.
3167    pub fn if_true(mut self, if_true: impl Into<String>) -> Self {
3168        self.if_true = Some(if_true.into());
3169        self
3170    }
3171
3172    /// Dart `FlagProperty(ifFalse:)`.
3173    pub fn if_false(mut self, if_false: impl Into<String>) -> Self {
3174        self.if_false = Some(if_false.into());
3175        self
3176    }
3177
3178    /// Dart `FlagProperty(showName:)`.
3179    pub fn with_show_name(mut self, show_name: bool) -> Self {
3180        self.data.show_name = show_name;
3181        self
3182    }
3183
3184    /// Dart `FlagProperty(defaultValue:)`.
3185    pub fn default_value(mut self, default_value: Option<bool>) -> Self {
3186        self.data.default_value = Some(default_value);
3187        self
3188    }
3189
3190    /// Dart `FlagProperty(level:)`.
3191    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
3192        self.data.default_level = level;
3193        self
3194    }
3195
3196    /// Dart's `FlagProperty.valueToString`.
3197    pub fn value_to_string(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3198        match self.data.value() {
3199            Some(true) if self.if_true.is_some() => self.if_true.clone().expect("checked above"),
3200            Some(false) if self.if_false.is_some() => self.if_false.clone().expect("checked above"),
3201            _ => self.data.base_value_to_string(parent_configuration),
3202        }
3203    }
3204}
3205
3206impl DiagnosticsNode for FlagProperty {
3207    fn name(&self) -> Option<&str> {
3208        self.data.name.as_deref()
3209    }
3210
3211    fn value(&self) -> Option<&dyn Any> {
3212        self.data.value().map(|value| value as &dyn Any)
3213    }
3214
3215    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
3216        let mut json =
3217            self.data
3218                .json_map(self, delegate, json_default_value(&self.data.default_value));
3219        if let Some(if_true) = &self.if_true {
3220            json_put(&mut json, "ifTrue", Value::String(if_true.clone()));
3221        }
3222        if let Some(if_false) = &self.if_false {
3223            json_put(&mut json, "ifFalse", Value::String(if_false.clone()));
3224        }
3225        json
3226    }
3227
3228    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3229        debug_assert!(
3230            self.if_true.is_some() || self.if_false.is_some(),
3231            "ifTrue or ifFalse must be non-null"
3232        );
3233        self.data
3234            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
3235    }
3236
3237    fn show_separator(&self) -> bool {
3238        self.data.show_separator
3239    }
3240
3241    fn level(&self) -> DiagnosticLevel {
3242        let value = self.data.value();
3243        if (value == Some(&true) && self.if_true.is_none())
3244            || (value == Some(&false) && self.if_false.is_none())
3245        {
3246            return DiagnosticLevel::Hidden;
3247        }
3248        self.data.base_level()
3249    }
3250
3251    fn show_name(&self) -> bool {
3252        let value = self.data.value();
3253        if value.is_none()
3254            || (value == Some(&true) && self.if_true.is_none())
3255            || (value == Some(&false) && self.if_false.is_none())
3256        {
3257            // We are missing a description for the flag value so we need to show
3258            // the flag name. The property will have DiagnosticLevel.hidden in
3259            // this case.
3260            return true;
3261        }
3262        self.data.show_name
3263    }
3264
3265    fn line_prefix(&self) -> Option<&str> {
3266        self.data.line_prefix.as_deref()
3267    }
3268
3269    fn style(&self) -> Option<DiagnosticsTreeStyle> {
3270        self.data.style
3271    }
3272
3273    fn allow_wrap(&self) -> bool {
3274        self.data.allow_wrap
3275    }
3276
3277    fn allow_name_wrap(&self) -> bool {
3278        self.data.allow_name_wrap
3279    }
3280
3281    render_deep_with!();
3282}
3283
3284impl fmt::Display for FlagProperty {
3285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3286        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
3287    }
3288}
3289
3290/// Property with an `Iterable<T>` value that can be displayed with different
3291/// [`DiagnosticsTreeStyle`] for custom rendering.
3292pub struct IterableProperty<T> {
3293    data: PropertyData<Vec<T>>,
3294}
3295
3296impl<T> IterableProperty<T> {
3297    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
3298    /// inherited members.
3299    pub fn property_data(&self) -> &PropertyData<Vec<T>> {
3300        &self.data
3301    }
3302}
3303
3304impl<T> IterableProperty<T> {
3305    /// The value of the property.
3306    pub fn value(&self) -> Option<&Vec<T>> {
3307        self.data.value()
3308    }
3309
3310    /// Create a diagnostics property for iterables (e.g. lists).
3311    ///
3312    /// The `if_empty` argument indicates how an iterable value with 0 elements
3313    /// is displayed.
3314    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<Vec<T>>>) -> Self {
3315        let (value, name) = (value.into(), name.into_property_name());
3316        IterableProperty {
3317            data: PropertyData::new(name, value),
3318        }
3319        .if_empty("[]")
3320    }
3321
3322    /// Dart `IterableProperty(defaultValue:)`.
3323    pub fn default_value(mut self, default_value: Option<Vec<T>>) -> Self {
3324        self.data.default_value = Some(default_value);
3325        self
3326    }
3327
3328    /// Dart `IterableProperty(ifNull:)`.
3329    pub fn if_null(mut self, if_null: impl Into<String>) -> Self {
3330        self.data.set_if_null(if_null.into());
3331        self
3332    }
3333
3334    /// Dart `IterableProperty(ifEmpty:)`.
3335    pub fn if_empty(mut self, if_empty: impl Into<String>) -> Self {
3336        self.data.if_empty = Some(if_empty.into());
3337        self
3338    }
3339
3340    /// Dart `IterableProperty(style:)`.
3341    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
3342        self.data.style = Some(style);
3343        self
3344    }
3345
3346    /// Dart `IterableProperty(showName:)`.
3347    pub fn with_show_name(mut self, show_name: bool) -> Self {
3348        self.data.show_name = show_name;
3349        self
3350    }
3351
3352    /// Dart `IterableProperty(showSeparator:)`.
3353    pub fn with_show_separator(mut self, show_separator: bool) -> Self {
3354        self.data.show_separator = show_separator;
3355        self
3356    }
3357
3358    /// Dart `IterableProperty(level:)`.
3359    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
3360        self.data.default_level = level;
3361        self
3362    }
3363
3364    /// Dart's `IterableProperty.valueToString`.
3365    pub fn value_to_string(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String
3366    where
3367        T: fmt::Display + Any,
3368    {
3369        let Some(values) = self.data.value() else {
3370            return "null".to_string();
3371        };
3372
3373        if values.is_empty() {
3374            return self
3375                .data
3376                .if_empty
3377                .clone()
3378                .unwrap_or_else(|| "[]".to_string());
3379        }
3380
3381        let formatted_values: Vec<String> = values
3382            .iter()
3383            .map(|value| {
3384                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
3385                    let any = value as &dyn Any;
3386                    debug_format_double(any.downcast_ref::<f64>().copied())
3387                } else {
3388                    value.to_string()
3389                }
3390            })
3391            .collect();
3392
3393        if let Some(parent) = parent_configuration
3394            && !parent.line_break_properties
3395        {
3396            // Always display the value as a single line and enclose the
3397            // iterable value in brackets to avoid ambiguity.
3398            return format!("[{}]", formatted_values.join(", "));
3399        }
3400
3401        formatted_values.join(if is_single_line(self.data.style) {
3402            ", "
3403        } else {
3404            "\n"
3405        })
3406    }
3407}
3408
3409impl<T> DiagnosticsNode for IterableProperty<T>
3410where
3411    T: fmt::Display + PartialEq + Any,
3412{
3413    fn name(&self) -> Option<&str> {
3414        self.data.name.as_deref()
3415    }
3416
3417    fn value(&self) -> Option<&dyn Any> {
3418        self.data.value().map(|value| value as &dyn Any)
3419    }
3420
3421    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
3422        let mut json = self.data.json_map(
3423            self,
3424            delegate,
3425            json_iterable_default_value(&self.data.default_value),
3426        );
3427        if let Some(values) = self.value() {
3428            let values: Vec<Value> = values
3429                .iter()
3430                .map(|value| {
3431                    Value::String(dart_value_to_string(value as &dyn Any, value.to_string()))
3432                })
3433                .collect();
3434            json_put(&mut json, "values", Value::Array(values));
3435        }
3436        json
3437    }
3438
3439    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3440        self.data
3441            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
3442    }
3443
3444    fn show_separator(&self) -> bool {
3445        self.data.show_separator
3446    }
3447
3448    fn level(&self) -> DiagnosticLevel {
3449        let value = self.data.value();
3450        if self.data.if_empty.is_none()
3451            && value.is_some_and(|value| value.is_empty())
3452            && self.data.base_level() != DiagnosticLevel::Hidden
3453        {
3454            return DiagnosticLevel::Fine;
3455        }
3456        self.data.base_level()
3457    }
3458
3459    fn show_name(&self) -> bool {
3460        self.data.show_name
3461    }
3462
3463    fn line_prefix(&self) -> Option<&str> {
3464        self.data.line_prefix.as_deref()
3465    }
3466
3467    fn style(&self) -> Option<DiagnosticsTreeStyle> {
3468        self.data.style
3469    }
3470
3471    fn allow_wrap(&self) -> bool {
3472        self.data.allow_wrap
3473    }
3474
3475    fn allow_name_wrap(&self) -> bool {
3476        self.data.allow_name_wrap
3477    }
3478
3479    render_deep_with!();
3480}
3481
3482impl<T> fmt::Display for IterableProperty<T>
3483where
3484    T: fmt::Display + PartialEq + Any,
3485{
3486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3487        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
3488    }
3489}
3490
3491/// [`DiagnosticsProperty`] that has an enum as value.
3492///
3493/// The enum value is displayed with its variant name, first character
3494/// lowercased, the way Dart's `Enum.name` prints `deferToChild`.
3495pub struct EnumProperty<T> {
3496    data: PropertyData<T>,
3497}
3498
3499impl<T> EnumProperty<T> {
3500    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
3501    /// inherited members.
3502    pub fn property_data(&self) -> &PropertyData<T> {
3503        &self.data
3504    }
3505}
3506
3507impl<T> EnumProperty<T> {
3508    /// The value of the property.
3509    pub fn value(&self) -> Option<&T> {
3510        self.data.value()
3511    }
3512
3513    /// Create a diagnostics property that displays an enum.
3514    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<T>>) -> Self {
3515        let (value, name) = (value.into(), name.into_property_name());
3516        EnumProperty {
3517            data: PropertyData::new(name, value),
3518        }
3519    }
3520
3521    /// Dart `EnumProperty(defaultValue:)`.
3522    pub fn default_value(mut self, default_value: Option<T>) -> Self {
3523        self.data.default_value = Some(default_value);
3524        self
3525    }
3526
3527    /// Dart `EnumProperty(level:)`.
3528    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
3529        self.data.default_level = level;
3530        self
3531    }
3532}
3533
3534impl<T> DiagnosticsNode for EnumProperty<T>
3535where
3536    T: fmt::Debug + PartialEq + Any,
3537{
3538    fn name(&self) -> Option<&str> {
3539        self.data.name.as_deref()
3540    }
3541
3542    fn value(&self) -> Option<&dyn Any> {
3543        self.data.value().map(|value| value as &dyn Any)
3544    }
3545
3546    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
3547        self.data.json_map(
3548            self,
3549            delegate,
3550            json_enum_default_value(&self.data.default_value),
3551        )
3552    }
3553
3554    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3555        self.data
3556            .to_description_with(parent_configuration, |_| match self.data.value() {
3557                Some(value) => describe_enum(value),
3558                None => "null".to_string(),
3559            })
3560    }
3561
3562    fn show_separator(&self) -> bool {
3563        self.data.show_separator
3564    }
3565
3566    fn level(&self) -> DiagnosticLevel {
3567        self.data.base_level()
3568    }
3569
3570    fn show_name(&self) -> bool {
3571        self.data.show_name
3572    }
3573
3574    fn line_prefix(&self) -> Option<&str> {
3575        self.data.line_prefix.as_deref()
3576    }
3577
3578    fn style(&self) -> Option<DiagnosticsTreeStyle> {
3579        self.data.style
3580    }
3581
3582    fn allow_wrap(&self) -> bool {
3583        self.data.allow_wrap
3584    }
3585
3586    fn allow_name_wrap(&self) -> bool {
3587        self.data.allow_name_wrap
3588    }
3589
3590    render_deep_with!();
3591}
3592
3593impl<T> fmt::Display for EnumProperty<T>
3594where
3595    T: fmt::Debug + PartialEq + Any,
3596{
3597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3598        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
3599    }
3600}
3601
3602/// A property where the important diagnostic information is primarily whether
3603/// the value is present (non-null) or absent (null).
3604pub struct ObjectFlagProperty<T> {
3605    data: PropertyData<T>,
3606    /// Description to use if the property value is not null.
3607    pub if_present: Option<String>,
3608}
3609
3610impl<T> ObjectFlagProperty<T> {
3611    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
3612    /// inherited members.
3613    pub fn property_data(&self) -> &PropertyData<T> {
3614        &self.data
3615    }
3616}
3617
3618impl<T> ObjectFlagProperty<T> {
3619    /// The value of the property.
3620    pub fn value(&self) -> Option<&T> {
3621        self.data.value()
3622    }
3623
3624    /// Create a diagnostics property for values that can be present (non-null)
3625    /// or absent (null).
3626    pub fn new(name: impl IntoPropertyName, value: impl Into<Option<T>>) -> Self {
3627        let (value, name) = (value.into(), name.into_property_name());
3628        ObjectFlagProperty {
3629            data: PropertyData::new(name, value),
3630            if_present: None,
3631        }
3632        .with_show_name(false)
3633    }
3634
3635    /// Shorthand constructor to describe whether the property has a value.
3636    ///
3637    /// Only use if prefixing the property name with the word 'has' is a good
3638    /// flag name.
3639    pub fn has(name: impl Into<String>, value: Option<T>) -> Self {
3640        let name = name.into();
3641        ObjectFlagProperty {
3642            data: PropertyData::new(Some(name.clone()), value),
3643            if_present: Some(format!("has {name}")),
3644        }
3645        .with_show_name(false)
3646    }
3647
3648    /// Dart `ObjectFlagProperty(ifPresent:)`.
3649    pub fn if_present(mut self, if_present: impl Into<String>) -> Self {
3650        self.if_present = Some(if_present.into());
3651        self
3652    }
3653
3654    /// Dart `ObjectFlagProperty(ifNull:)`.
3655    pub fn if_null(mut self, if_null: impl Into<String>) -> Self {
3656        self.data.set_if_null(if_null.into());
3657        self
3658    }
3659
3660    /// Dart `ObjectFlagProperty(showName:)`.
3661    pub fn with_show_name(mut self, show_name: bool) -> Self {
3662        self.data.show_name = show_name;
3663        self
3664    }
3665
3666    /// Dart `ObjectFlagProperty(level:)`.
3667    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
3668        self.data.default_level = level;
3669        self
3670    }
3671
3672    /// Dart's `ObjectFlagProperty.valueToString`.
3673    pub fn value_to_string(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String
3674    where
3675        T: fmt::Display,
3676    {
3677        match self.data.value() {
3678            Some(_) if self.if_present.is_some() => self.if_present.clone().expect("checked above"),
3679            None if self.data.if_null.is_some() => {
3680                self.data.if_null.clone().expect("checked above")
3681            }
3682            _ => self.data.base_value_to_string(parent_configuration),
3683        }
3684    }
3685}
3686
3687impl<T> DiagnosticsNode for ObjectFlagProperty<T>
3688where
3689    T: fmt::Display + Any,
3690{
3691    fn name(&self) -> Option<&str> {
3692        self.data.name.as_deref()
3693    }
3694
3695    fn value(&self) -> Option<&dyn Any> {
3696        self.data.value().map(|value| value as &dyn Any)
3697    }
3698
3699    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
3700        let mut json =
3701            self.data
3702                .json_map(self, delegate, json_default_value(&self.data.default_value));
3703        if let Some(if_present) = &self.if_present {
3704            json_put(&mut json, "ifPresent", Value::String(if_present.clone()));
3705        }
3706        json
3707    }
3708
3709    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3710        debug_assert!(
3711            self.if_present.is_some() || self.data.if_null.is_some(),
3712            "ifPresent or ifNull must be non-null"
3713        );
3714        self.data
3715            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
3716    }
3717
3718    fn show_separator(&self) -> bool {
3719        self.data.show_separator
3720    }
3721
3722    fn level(&self) -> DiagnosticLevel {
3723        let value = self.data.value();
3724        if (value.is_some() && self.if_present.is_none())
3725            || (value.is_none() && self.data.if_null.is_none())
3726        {
3727            return DiagnosticLevel::Hidden;
3728        }
3729        self.data.default_level
3730    }
3731
3732    fn show_name(&self) -> bool {
3733        let value = self.data.value();
3734        if (value.is_some() && self.if_present.is_none())
3735            || (value.is_none() && self.data.if_null.is_none())
3736        {
3737            // We are missing a description for the flag value so we need to show
3738            // the flag name. The property will have DiagnosticLevel.hidden in
3739            // this case.
3740            return true;
3741        }
3742        self.data.show_name
3743    }
3744
3745    fn line_prefix(&self) -> Option<&str> {
3746        self.data.line_prefix.as_deref()
3747    }
3748
3749    fn style(&self) -> Option<DiagnosticsTreeStyle> {
3750        self.data.style
3751    }
3752
3753    fn allow_wrap(&self) -> bool {
3754        self.data.allow_wrap
3755    }
3756
3757    fn allow_name_wrap(&self) -> bool {
3758        self.data.allow_name_wrap
3759    }
3760
3761    render_deep_with!();
3762}
3763
3764impl<T> fmt::Display for ObjectFlagProperty<T>
3765where
3766    T: fmt::Display + Any,
3767{
3768    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3769        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
3770    }
3771}
3772
3773/// A summary of multiple properties, indicating whether each of them is present
3774/// (non-null) or absent (null).
3775pub struct FlagsSummary<T> {
3776    data: PropertyData<IndexMap<String, Option<T>>>,
3777}
3778
3779impl<T> FlagsSummary<T> {
3780    /// The fields and behaviour this property shares with every `DiagnosticsProperty`, Dart's
3781    /// inherited members.
3782    pub fn property_data(&self) -> &PropertyData<IndexMap<String, Option<T>>> {
3783        &self.data
3784    }
3785
3786    /// Create a summary for multiple properties.
3787    pub fn new(name: impl IntoPropertyName, value: IndexMap<String, Option<T>>) -> Self {
3788        let name = name.into_property_name();
3789        FlagsSummary {
3790            data: PropertyData::new(name, Some(value)),
3791        }
3792    }
3793
3794    /// Dart `FlagsSummary(ifEmpty:)`.
3795    pub fn if_empty(mut self, if_empty: impl Into<String>) -> Self {
3796        self.data.if_empty = Some(if_empty.into());
3797        self
3798    }
3799
3800    /// Dart `FlagsSummary(showName:)`.
3801    pub fn with_show_name(mut self, show_name: bool) -> Self {
3802        self.data.show_name = show_name;
3803        self
3804    }
3805
3806    /// Dart `FlagsSummary(showSeparator:)`.
3807    pub fn with_show_separator(mut self, show_separator: bool) -> Self {
3808        self.data.show_separator = show_separator;
3809        self
3810    }
3811
3812    /// Dart `FlagsSummary(level:)`.
3813    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
3814        self.data.default_level = level;
3815        self
3816    }
3817
3818    /// Dart's `FlagsSummary.value`: the map itself, never null.
3819    pub fn value(&self) -> &IndexMap<String, Option<T>> {
3820        self.data
3821            .value()
3822            .expect("a FlagsSummary is built with a map")
3823    }
3824
3825    fn has_non_null_entry(&self) -> bool {
3826        self.value().values().any(Option::is_some)
3827    }
3828
3829    fn formatted_values(&self) -> impl Iterator<Item = &String> {
3830        self.value()
3831            .iter()
3832            .filter_map(|(key, value)| value.is_some().then_some(key))
3833    }
3834
3835    /// Dart's `FlagsSummary.valueToString`.
3836    pub fn value_to_string(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3837        if !self.has_non_null_entry()
3838            && let Some(if_empty) = &self.data.if_empty
3839        {
3840            return if_empty.clone();
3841        }
3842
3843        let formatted_values: Vec<&String> = self.formatted_values().collect();
3844        if let Some(parent) = parent_configuration
3845            && !parent.line_break_properties
3846        {
3847            // Always display the value as a single line and enclose the
3848            // iterable value in brackets to avoid ambiguity.
3849            return format!(
3850                "[{}]",
3851                formatted_values
3852                    .iter()
3853                    .map(|value| value.as_str())
3854                    .collect::<Vec<_>>()
3855                    .join(", ")
3856            );
3857        }
3858
3859        formatted_values
3860            .iter()
3861            .map(|value| value.as_str())
3862            .collect::<Vec<_>>()
3863            .join(if is_single_line(self.data.style) {
3864                ", "
3865            } else {
3866                "\n"
3867            })
3868    }
3869}
3870
3871impl<T> DiagnosticsNode for FlagsSummary<T>
3872where
3873    T: Any,
3874{
3875    fn name(&self) -> Option<&str> {
3876        self.data.name.as_deref()
3877    }
3878
3879    fn value(&self) -> Option<&dyn Any> {
3880        self.data.value().map(|value| value as &dyn Any)
3881    }
3882
3883    fn to_json_map(&self, delegate: &dyn DiagnosticsSerializationDelegate) -> DiagnosticsJsonMap {
3884        let mut json = self.data.json_map(self, delegate, None);
3885        if !self.value().is_empty() {
3886            let values: Vec<Value> = self
3887                .formatted_values()
3888                .map(|value| Value::String(value.clone()))
3889                .collect();
3890            json_put(&mut json, "values", Value::Array(values));
3891        }
3892        json
3893    }
3894
3895    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
3896        self.data
3897            .to_description_with(parent_configuration, |parent| self.value_to_string(parent))
3898    }
3899
3900    fn show_separator(&self) -> bool {
3901        self.data.show_separator
3902    }
3903
3904    fn level(&self) -> DiagnosticLevel {
3905        if !self.has_non_null_entry() && self.data.if_empty.is_none() {
3906            return DiagnosticLevel::Hidden;
3907        }
3908        self.data.default_level
3909    }
3910
3911    fn show_name(&self) -> bool {
3912        self.data.show_name
3913    }
3914
3915    fn line_prefix(&self) -> Option<&str> {
3916        self.data.line_prefix.as_deref()
3917    }
3918
3919    fn style(&self) -> Option<DiagnosticsTreeStyle> {
3920        self.data.style
3921    }
3922
3923    fn allow_wrap(&self) -> bool {
3924        self.data.allow_wrap
3925    }
3926
3927    fn allow_name_wrap(&self) -> bool {
3928        self.data.allow_name_wrap
3929    }
3930
3931    render_deep_with!();
3932}
3933
3934impl<T> fmt::Display for FlagsSummary<T>
3935where
3936    T: Any,
3937{
3938    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3939        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
3940    }
3941}
3942
3943/// Builder to accumulate properties and configuration used to assemble a
3944/// [`DiagnosticsNode`] from a [`Diagnosticable`] object.
3945pub struct DiagnosticPropertiesBuilder {
3946    /// List of properties accumulated so far.
3947    pub properties: Vec<Rc<dyn DiagnosticsNode>>,
3948    /// Default style to use for the node if no style is specified.
3949    pub default_diagnostics_tree_style: DiagnosticsTreeStyle,
3950    /// Description to show if the node has no displayed properties or children.
3951    pub empty_body_description: Option<String>,
3952}
3953
3954impl DiagnosticPropertiesBuilder {
3955    /// Creates a builder with no properties.
3956    pub fn new() -> Self {
3957        DiagnosticPropertiesBuilder {
3958            properties: Vec::new(),
3959            default_diagnostics_tree_style: DiagnosticsTreeStyle::Sparse,
3960            empty_body_description: None,
3961        }
3962    }
3963
3964    /// Creates a builder with the given properties.
3965    pub fn from_properties(properties: Vec<Rc<dyn DiagnosticsNode>>) -> Self {
3966        DiagnosticPropertiesBuilder {
3967            properties,
3968            default_diagnostics_tree_style: DiagnosticsTreeStyle::Sparse,
3969            empty_body_description: None,
3970        }
3971    }
3972
3973    /// Add a property to the list of properties.
3974    pub fn add(&mut self, property: impl DiagnosticsNode + 'static) {
3975        self.properties.push(Rc::new(property));
3976    }
3977
3978    /// Add a property that is already shared.
3979    pub fn add_rc(&mut self, property: Rc<dyn DiagnosticsNode>) {
3980        self.properties.push(property);
3981    }
3982}
3983
3984impl Default for DiagnosticPropertiesBuilder {
3985    fn default() -> Self {
3986        Self::new()
3987    }
3988}
3989
3990/// A trait for objects that can describe themselves with string and
3991/// [`DiagnosticsNode`] representations.
3992///
3993/// Dart's `Diagnosticable`. Its methods do not take `App`: Flutter's
3994/// `debugFillProperties` reads only the object's own fields. Arena values that
3995/// need children are read through [`DiagnosticableTree`].
3996pub trait Diagnosticable: Sized {
3997    /// Dart's `Object.runtimeType` as diagnostics print it: the last segment of
3998    /// the Rust type path, without generic arguments.
3999    fn type_name(&self) -> &'static str {
4000        bare_type_name(std::any::type_name::<Self>())
4001    }
4002
4003    /// Dart's `Object.hashCode` as diagnostics print it: the object's address.
4004    fn identity_hash(&self) -> u64 {
4005        self as *const Self as *const () as usize as u64
4006    }
4007
4008    /// A brief description of this object, usually just the type and the hash.
4009    fn to_string_short(&self) -> String {
4010        describe_identity(self.type_name(), self.identity_hash())
4011    }
4012
4013    /// Add additional properties associated with the node.
4014    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
4015        let _ = properties;
4016    }
4017
4018    /// Returns a debug representation of the object used by debugging tools and
4019    /// by [`DiagnosticsNode::to_string_deep`].
4020    fn to_diagnostics_node(&self) -> DiagnosticableNode {
4021        DiagnosticableNode::new(None, self, None)
4022    }
4023
4024    /// Dart `toDiagnosticsNode(name:, style:)`.
4025    fn to_diagnostics_node_with(
4026        &self,
4027        name: Option<String>,
4028        style: Option<DiagnosticsTreeStyle>,
4029    ) -> DiagnosticableNode {
4030        DiagnosticableNode::new(name, self, style)
4031    }
4032
4033    /// Dart's `toString`: a single-line description with properties and no
4034    /// children.
4035    ///
4036    /// A type that also implements `Display` must call this as
4037    /// `Diagnosticable::to_string` because Rust reports the two methods as
4038    /// ambiguous.
4039    fn to_string(&self) -> String {
4040        self.to_string_at(DiagnosticLevel::Info)
4041    }
4042
4043    /// Dart's `toString(minLevel:)`.
4044    fn to_string_at(&self, min_level: DiagnosticLevel) -> String {
4045        self.to_diagnostics_node_with(None, Some(DiagnosticsTreeStyle::SingleLine))
4046            .to_string_with(None, min_level)
4047    }
4048}
4049
4050/// A trait for objects that can describe their children as well as themselves.
4051///
4052/// Dart's `DiagnosticableTree`. `to_diagnostics_tree_node` is Dart's
4053/// `toDiagnosticsNode` override; it is renamed because Rust reports a call to
4054/// two same-named trait methods as ambiguous.
4055pub trait DiagnosticableTree: Diagnosticable {
4056    /// Returns a node whose properties and children are collected from `self`.
4057    fn to_diagnostics_tree_node(
4058        &self,
4059        name: Option<String>,
4060        style: Option<DiagnosticsTreeStyle>,
4061    ) -> DiagnosticableTreeNode {
4062        DiagnosticableTreeNode::new(name, self, style)
4063    }
4064
4065    /// Returns a list of nodes describing this node's children.
4066    fn debug_describe_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
4067        Vec::new()
4068    }
4069
4070    /// Returns a one-line detailed description of the object, including the
4071    /// same information as [`to_string_deep`](Self::to_string_deep) but without
4072    /// recursing to children.
4073    fn to_string_shallow(&self, joiner: &str, min_level: DiagnosticLevel) -> String {
4074        let mut result = self.to_string_short();
4075        result.push_str(joiner);
4076        let mut builder = DiagnosticPropertiesBuilder::new();
4077        self.debug_fill_properties(&mut builder);
4078        let properties: Vec<String> = builder
4079            .properties
4080            .iter()
4081            .filter(|node| !node.is_filtered(min_level))
4082            .map(ToString::to_string)
4083            .collect();
4084        result.push_str(&properties.join(joiner));
4085        result
4086    }
4087
4088    /// Returns a string representation of this node and its descendants with
4089    /// Dart's default arguments.
4090    fn to_string_deep(&self) -> String {
4091        self.to_string_deep_with("", None, DiagnosticLevel::Debug, 65)
4092    }
4093
4094    /// Returns a string representation of this node and its descendants.
4095    fn to_string_deep_with(
4096        &self,
4097        prefix_line_one: &str,
4098        prefix_other_lines: Option<&str>,
4099        min_level: DiagnosticLevel,
4100        wrap_width: usize,
4101    ) -> String {
4102        self.to_diagnostics_tree_node(None, None)
4103            .to_string_deep_with(
4104                prefix_line_one,
4105                prefix_other_lines,
4106                None,
4107                min_level,
4108                wrap_width,
4109            )
4110    }
4111}
4112
4113/// [`DiagnosticsNode`] that describes a [`Diagnosticable`] value.
4114///
4115/// Flutter keeps the value and fills its builder on first read. Waft builds the
4116/// node eagerly: the value lives in an arena and is read with `&App`, so
4117/// [`from_parts`](Self::from_parts) takes the pieces the caller already
4118/// collected.
4119pub struct DiagnosticableNode {
4120    name: Option<String>,
4121    description: String,
4122    style: DiagnosticsTreeStyle,
4123    properties: Vec<Rc<dyn DiagnosticsNode>>,
4124    empty_body_description: Option<String>,
4125    value_id: Option<HandleId>,
4126}
4127
4128impl DiagnosticableNode {
4129    /// Creates a node for `value`, filling its properties eagerly.
4130    pub fn new(
4131        name: impl IntoPropertyName,
4132        value: &impl Diagnosticable,
4133        style: Option<DiagnosticsTreeStyle>,
4134    ) -> Self {
4135        let name = name.into_property_name();
4136        let mut builder = DiagnosticPropertiesBuilder::new();
4137        value.debug_fill_properties(&mut builder);
4138        let mut node = Self::from_parts(name, value.to_string_short(), builder);
4139        if let Some(style) = style {
4140            node.style = style;
4141        }
4142        node
4143    }
4144
4145    /// Creates a node from a description, properties and style already
4146    /// collected from a value.
4147    ///
4148    /// This is how an arena object's node is built: read the object with
4149    /// `&App`, fill a [`DiagnosticPropertiesBuilder`], and pass both.
4150    pub fn from_parts(
4151        name: impl IntoPropertyName,
4152        description: impl Into<String>,
4153        builder: DiagnosticPropertiesBuilder,
4154    ) -> Self {
4155        let name = name.into_property_name();
4156        assert_node_name(&name);
4157        let DiagnosticPropertiesBuilder {
4158            properties,
4159            default_diagnostics_tree_style,
4160            empty_body_description,
4161        } = builder;
4162        DiagnosticableNode {
4163            name,
4164            description: description.into(),
4165            style: default_diagnostics_tree_style,
4166            properties,
4167            empty_body_description,
4168            value_id: None,
4169        }
4170    }
4171
4172    /// Dart `DiagnosticableNode(style:)`: the node drawn in `style` rather than the one its
4173    /// properties asked for.
4174    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
4175        self.style = style;
4176        self
4177    }
4178
4179    /// Names the arena object this node was read from, so a delegate can print its id without
4180    /// the node holding it; see [`DiagnosticsNode::value_id`].
4181    pub fn with_value_id(mut self, id: HandleId) -> Self {
4182        self.value_id = Some(id);
4183        self
4184    }
4185
4186    /// Dart `DiagnosticableNode(emptyBodyDescription:)`, from the builder.
4187    pub fn with_empty_body_description(mut self, description: impl Into<String>) -> Self {
4188        self.empty_body_description = Some(description.into());
4189        self
4190    }
4191
4192    /// The node's short description.
4193    pub fn description(&self) -> &str {
4194        &self.description
4195    }
4196
4197    /// The node's collected properties.
4198    pub fn properties(&self) -> &[Rc<dyn DiagnosticsNode>] {
4199        &self.properties
4200    }
4201}
4202
4203impl DiagnosticsNode for DiagnosticableNode {
4204    fn name(&self) -> Option<&str> {
4205        self.name.as_deref()
4206    }
4207
4208    fn to_description(&self, _parent_configuration: Option<&TextTreeConfiguration>) -> String {
4209        self.description.clone()
4210    }
4211
4212    fn empty_body_description(&self) -> Option<&str> {
4213        self.empty_body_description.as_deref()
4214    }
4215
4216    fn value_id(&self) -> Option<HandleId> {
4217        self.value_id
4218    }
4219
4220    fn style(&self) -> Option<DiagnosticsTreeStyle> {
4221        Some(self.style)
4222    }
4223
4224    fn get_properties(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
4225        self.properties.clone()
4226    }
4227
4228    json_map_impl!();
4229
4230    render_deep_with!();
4231}
4232
4233impl fmt::Display for DiagnosticableNode {
4234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4235        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
4236    }
4237}
4238
4239/// [`DiagnosticsNode`] for an instance of [`DiagnosticableTree`].
4240pub struct DiagnosticableTreeNode {
4241    inner: DiagnosticableNode,
4242    children: Vec<Rc<dyn DiagnosticsNode>>,
4243}
4244
4245impl DiagnosticableTreeNode {
4246    /// Creates a node for `value`, filling its properties and children eagerly.
4247    pub fn new(
4248        name: impl IntoPropertyName,
4249        value: &impl DiagnosticableTree,
4250        style: Option<DiagnosticsTreeStyle>,
4251    ) -> Self {
4252        let name = name.into_property_name();
4253        let mut builder = DiagnosticPropertiesBuilder::new();
4254        value.debug_fill_properties(&mut builder);
4255        let mut inner = DiagnosticableNode::from_parts(name, value.to_string_short(), builder);
4256        if let Some(style) = style {
4257            inner.style = style;
4258        }
4259        DiagnosticableTreeNode {
4260            inner,
4261            children: value.debug_describe_children(),
4262        }
4263    }
4264
4265    /// Creates a tree node from a description, properties, style and children
4266    /// already collected from a value.
4267    ///
4268    /// This is how an arena object's node is built: read the object and its
4269    /// children with `&App`, fill a [`DiagnosticPropertiesBuilder`], and pass
4270    /// both.
4271    pub fn from_parts(
4272        name: impl IntoPropertyName,
4273        description: impl Into<String>,
4274        builder: DiagnosticPropertiesBuilder,
4275        children: Vec<Rc<dyn DiagnosticsNode>>,
4276    ) -> Self {
4277        let name = name.into_property_name();
4278        DiagnosticableTreeNode {
4279            inner: DiagnosticableNode::from_parts(name, description, builder),
4280            children,
4281        }
4282    }
4283
4284    /// Sets the node's style, as Dart's `toDiagnosticsNode(style:)` does.
4285    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
4286        self.inner.style = style;
4287        self
4288    }
4289
4290    /// Names the arena object this node was read from; see [`DiagnosticsNode::value_id`].
4291    pub fn with_value_id(mut self, id: HandleId) -> Self {
4292        self.inner.value_id = Some(id);
4293        self
4294    }
4295
4296    /// The node's short description.
4297    pub fn description(&self) -> &str {
4298        self.inner.description()
4299    }
4300
4301    /// The node's collected properties.
4302    pub fn properties(&self) -> &[Rc<dyn DiagnosticsNode>] {
4303        self.inner.properties()
4304    }
4305
4306    /// The node's children.
4307    pub fn children(&self) -> &[Rc<dyn DiagnosticsNode>] {
4308        &self.children
4309    }
4310}
4311
4312impl DiagnosticsNode for DiagnosticableTreeNode {
4313    fn name(&self) -> Option<&str> {
4314        self.inner.name()
4315    }
4316
4317    fn to_description(&self, parent_configuration: Option<&TextTreeConfiguration>) -> String {
4318        self.inner.to_description(parent_configuration)
4319    }
4320
4321    fn show_separator(&self) -> bool {
4322        self.inner.show_separator()
4323    }
4324
4325    fn level(&self) -> DiagnosticLevel {
4326        self.inner.level()
4327    }
4328
4329    fn show_name(&self) -> bool {
4330        self.inner.show_name()
4331    }
4332
4333    fn line_prefix(&self) -> Option<&str> {
4334        self.inner.line_prefix()
4335    }
4336
4337    fn empty_body_description(&self) -> Option<&str> {
4338        self.inner.empty_body_description()
4339    }
4340
4341    fn value_id(&self) -> Option<HandleId> {
4342        self.inner.value_id()
4343    }
4344
4345    fn style(&self) -> Option<DiagnosticsTreeStyle> {
4346        self.inner.style()
4347    }
4348
4349    fn allow_wrap(&self) -> bool {
4350        self.inner.allow_wrap()
4351    }
4352
4353    fn allow_name_wrap(&self) -> bool {
4354        self.inner.allow_name_wrap()
4355    }
4356
4357    fn allow_truncate(&self) -> bool {
4358        self.inner.allow_truncate()
4359    }
4360
4361    fn get_properties(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
4362        self.inner.get_properties()
4363    }
4364
4365    fn get_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
4366        self.children.clone()
4367    }
4368
4369    json_map_impl!();
4370
4371    render_deep_with!();
4372}
4373
4374impl fmt::Display for DiagnosticableTreeNode {
4375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4376        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
4377    }
4378}
4379
4380/// [`DiagnosticsNode`] that exists mainly to provide a container for other
4381/// diagnostics that typically lacks a meaningful value of its own.
4382pub struct DiagnosticsBlock {
4383    /// Label describing the node.
4384    pub name: Option<String>,
4385    /// Hint for how the node should be displayed.
4386    pub style: Option<DiagnosticsTreeStyle>,
4387    show_name: bool,
4388    /// Whether a separator is shown between the name and description.
4389    pub show_separator: bool,
4390    /// Prefix to include at the start of each line.
4391    pub line_prefix: Option<String>,
4392    /// The actual object this diagnostics data is for.
4393    pub value: Option<Box<dyn Any>>,
4394    description: String,
4395    /// Priority level of the diagnostic.
4396    pub level: DiagnosticLevel,
4397    /// Whether to allow truncation when displaying the node and its children.
4398    pub allow_truncate: bool,
4399    children: Vec<Rc<dyn DiagnosticsNode>>,
4400    properties: Vec<Rc<dyn DiagnosticsNode>>,
4401}
4402
4403impl DiagnosticsBlock {
4404    /// Creates a diagnostic with no properties or children.
4405    pub fn new() -> Self {
4406        DiagnosticsBlock {
4407            name: None,
4408            style: Some(DiagnosticsTreeStyle::Whitespace),
4409            show_name: true,
4410            show_separator: true,
4411            line_prefix: None,
4412            value: None,
4413            description: String::new(),
4414            level: DiagnosticLevel::Info,
4415            allow_truncate: false,
4416            children: Vec::new(),
4417            properties: Vec::new(),
4418        }
4419    }
4420
4421    /// Dart `DiagnosticsBlock(name:)`.
4422    pub fn with_name(mut self, name: impl Into<String>) -> Self {
4423        let name = name.into();
4424        assert_node_name(&Some(name.clone()));
4425        self.name = Some(name);
4426        self
4427    }
4428
4429    /// Dart `DiagnosticsBlock(style:)`.
4430    pub fn with_style(mut self, style: DiagnosticsTreeStyle) -> Self {
4431        self.style = Some(style);
4432        self
4433    }
4434
4435    /// Dart `DiagnosticsBlock(showName:)`.
4436    pub fn with_show_name(mut self, show_name: bool) -> Self {
4437        self.show_name = show_name;
4438        self
4439    }
4440
4441    /// Dart `DiagnosticsBlock(showSeparator:)`.
4442    pub fn with_show_separator(mut self, show_separator: bool) -> Self {
4443        self.show_separator = show_separator;
4444        self
4445    }
4446
4447    /// Dart `DiagnosticsBlock(linePrefix:)`.
4448    pub fn with_line_prefix(mut self, line_prefix: impl Into<String>) -> Self {
4449        self.line_prefix = Some(line_prefix.into());
4450        self
4451    }
4452
4453    /// Dart `DiagnosticsBlock(value:)`.
4454    pub fn value(mut self, value: impl Any) -> Self {
4455        self.value = Some(Box::new(value));
4456        self
4457    }
4458
4459    /// Dart `DiagnosticsBlock(description:)`.
4460    pub fn description(mut self, description: impl Into<String>) -> Self {
4461        self.description = description.into();
4462        self
4463    }
4464
4465    /// Dart `DiagnosticsBlock(level:)`.
4466    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
4467        self.level = level;
4468        self
4469    }
4470
4471    /// Dart `DiagnosticsBlock(allowTruncate:)`.
4472    pub fn allow_truncate(mut self, allow_truncate: bool) -> Self {
4473        self.allow_truncate = allow_truncate;
4474        self
4475    }
4476
4477    /// Dart `DiagnosticsBlock(children:)`.
4478    pub fn children(mut self, children: Vec<Rc<dyn DiagnosticsNode>>) -> Self {
4479        self.children = children;
4480        self
4481    }
4482
4483    /// Dart `DiagnosticsBlock(properties:)`.
4484    pub fn properties(mut self, properties: Vec<Rc<dyn DiagnosticsNode>>) -> Self {
4485        self.properties = properties;
4486        self
4487    }
4488}
4489
4490impl Default for DiagnosticsBlock {
4491    fn default() -> Self {
4492        Self::new()
4493    }
4494}
4495
4496impl DiagnosticsNode for DiagnosticsBlock {
4497    fn name(&self) -> Option<&str> {
4498        self.name.as_deref()
4499    }
4500
4501    fn value(&self) -> Option<&dyn Any> {
4502        self.value.as_deref()
4503    }
4504
4505    fn to_description(&self, _parent_configuration: Option<&TextTreeConfiguration>) -> String {
4506        self.description.clone()
4507    }
4508
4509    fn show_separator(&self) -> bool {
4510        self.show_separator
4511    }
4512
4513    fn level(&self) -> DiagnosticLevel {
4514        self.level
4515    }
4516
4517    fn show_name(&self) -> bool {
4518        self.show_name && self.name.is_some()
4519    }
4520
4521    fn line_prefix(&self) -> Option<&str> {
4522        self.line_prefix.as_deref()
4523    }
4524
4525    fn style(&self) -> Option<DiagnosticsTreeStyle> {
4526        self.style
4527    }
4528
4529    fn allow_truncate(&self) -> bool {
4530        self.allow_truncate
4531    }
4532
4533    fn get_properties(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
4534        self.properties.clone()
4535    }
4536
4537    fn get_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
4538        self.children.clone()
4539    }
4540
4541    json_map_impl!();
4542
4543    render_deep_with!();
4544}
4545
4546impl fmt::Display for DiagnosticsBlock {
4547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4548        f.write_str(&self.to_string_with(None, DiagnosticLevel::Info))
4549    }
4550}
4551
4552/// A delegate that configures how a hierarchy of [`DiagnosticsNode`]s should be serialized.
4553///
4554/// Dart's `DiagnosticsSerializationDelegate`; implement it to configure how nodes serialize,
4555/// and [`DefaultDiagnosticsSerializationDelegate`] for Dart's `DiagnosticsSerializationDelegate`
4556/// factory.
4557///
4558/// A method that returns a delegate answers an owned one because Rust cannot return `this` from
4559/// `&self`; the default delegate's copies are values, so returning one is indistinguishable.
4560pub trait DiagnosticsSerializationDelegate {
4561    /// Returns a serializable map of additional information that will be included in the
4562    /// serialization of the given [`DiagnosticsNode`].
4563    ///
4564    /// This method is called for every [`DiagnosticsNode`] that's included in the serialization.
4565    fn additional_node_properties(
4566        &self,
4567        node: &dyn DiagnosticsNode,
4568        full_details: bool,
4569    ) -> DiagnosticsJsonMap;
4570
4571    /// Filters the list of [`DiagnosticsNode`]s that will be included as children for the given
4572    /// `owner` node.
4573    ///
4574    /// The callback may return a subset of the children in the provided list or replace the
4575    /// entire list with new child nodes.
4576    fn filter_children(
4577        &self,
4578        nodes: Vec<Rc<dyn DiagnosticsNode>>,
4579        owner: &dyn DiagnosticsNode,
4580    ) -> Vec<Rc<dyn DiagnosticsNode>>;
4581
4582    /// Filters the list of [`DiagnosticsNode`]s that will be included as properties for the given
4583    /// `owner` node.
4584    ///
4585    /// The callback may return a subset of the properties in the provided list or replace the
4586    /// entire list with new property nodes.
4587    fn filter_properties(
4588        &self,
4589        nodes: Vec<Rc<dyn DiagnosticsNode>>,
4590        owner: &dyn DiagnosticsNode,
4591    ) -> Vec<Rc<dyn DiagnosticsNode>>;
4592
4593    /// Truncates the given list of [`DiagnosticsNode`] that will be added to the serialization as
4594    /// children or properties of the `owner` node.
4595    ///
4596    /// The method must return a subset of the provided nodes and may not replace any nodes.
4597    /// Truncating leaves a hint in the serialization that there were additional nodes.
4598    fn truncate_nodes_list(
4599        &self,
4600        nodes: Vec<Rc<dyn DiagnosticsNode>>,
4601        owner: Option<&dyn DiagnosticsNode>,
4602    ) -> Vec<Rc<dyn DiagnosticsNode>>;
4603
4604    /// Returns the delegate to be used for adding the provided [`DiagnosticsNode`] to the
4605    /// serialization.
4606    ///
4607    /// By default, this returns a copy of this delegate with `subtree_depth` reduced by one.
4608    fn delegate_for_node(
4609        &self,
4610        node: &dyn DiagnosticsNode,
4611    ) -> Rc<dyn DiagnosticsSerializationDelegate>;
4612
4613    /// Controls how many levels of children will be included in the serialized hierarchy.
4614    fn subtree_depth(&self) -> i32;
4615
4616    /// Whether to include the properties of a [`DiagnosticsNode`] in the serialization.
4617    fn include_properties(&self) -> bool;
4618
4619    /// Whether properties that have a [`Diagnosticable`] as value should be expanded.
4620    fn expand_property_values(&self) -> bool;
4621
4622    /// Creates a copy of this delegate with the provided values.
4623    fn copy_with(
4624        &self,
4625        subtree_depth: Option<i32>,
4626        include_properties: Option<bool>,
4627    ) -> Rc<dyn DiagnosticsSerializationDelegate>;
4628}
4629
4630/// Dart's `_DefaultDiagnosticsSerializationDelegate`, which
4631/// `DiagnosticsSerializationDelegate(...)` constructs.
4632#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4633pub struct DefaultDiagnosticsSerializationDelegate {
4634    /// Controls how many levels of children will be included.
4635    pub subtree_depth: i32,
4636    /// Whether to include properties in the serialization.
4637    pub include_properties: bool,
4638}
4639
4640impl DefaultDiagnosticsSerializationDelegate {
4641    /// Dart `DiagnosticsSerializationDelegate(subtreeDepth:, includeProperties:)`.
4642    pub fn new(subtree_depth: i32, include_properties: bool) -> Self {
4643        DefaultDiagnosticsSerializationDelegate {
4644            subtree_depth,
4645            include_properties,
4646        }
4647    }
4648}
4649
4650impl DiagnosticsSerializationDelegate for DefaultDiagnosticsSerializationDelegate {
4651    fn additional_node_properties(
4652        &self,
4653        _node: &dyn DiagnosticsNode,
4654        _full_details: bool,
4655    ) -> DiagnosticsJsonMap {
4656        DiagnosticsJsonMap::new()
4657    }
4658
4659    fn filter_children(
4660        &self,
4661        nodes: Vec<Rc<dyn DiagnosticsNode>>,
4662        _owner: &dyn DiagnosticsNode,
4663    ) -> Vec<Rc<dyn DiagnosticsNode>> {
4664        nodes
4665    }
4666
4667    fn filter_properties(
4668        &self,
4669        nodes: Vec<Rc<dyn DiagnosticsNode>>,
4670        _owner: &dyn DiagnosticsNode,
4671    ) -> Vec<Rc<dyn DiagnosticsNode>> {
4672        nodes
4673    }
4674
4675    fn truncate_nodes_list(
4676        &self,
4677        nodes: Vec<Rc<dyn DiagnosticsNode>>,
4678        _owner: Option<&dyn DiagnosticsNode>,
4679    ) -> Vec<Rc<dyn DiagnosticsNode>> {
4680        nodes
4681    }
4682
4683    fn delegate_for_node(
4684        &self,
4685        _node: &dyn DiagnosticsNode,
4686    ) -> Rc<dyn DiagnosticsSerializationDelegate> {
4687        if self.subtree_depth > 0 {
4688            self.copy_with(Some(self.subtree_depth - 1), None)
4689        } else {
4690            Rc::new(*self)
4691        }
4692    }
4693
4694    fn subtree_depth(&self) -> i32 {
4695        self.subtree_depth
4696    }
4697
4698    fn include_properties(&self) -> bool {
4699        self.include_properties
4700    }
4701
4702    fn expand_property_values(&self) -> bool {
4703        false
4704    }
4705
4706    fn copy_with(
4707        &self,
4708        subtree_depth: Option<i32>,
4709        include_properties: Option<bool>,
4710    ) -> Rc<dyn DiagnosticsSerializationDelegate> {
4711        Rc::new(DefaultDiagnosticsSerializationDelegate {
4712            subtree_depth: subtree_depth.unwrap_or(self.subtree_depth),
4713            include_properties: include_properties.unwrap_or(self.include_properties),
4714        })
4715    }
4716}
4717
4718/// A diagnostics node containing only a string `message`, with no name or
4719/// value.
4720///
4721/// Dart's `DiagnosticsNode.message` factory.
4722pub fn message(message: impl Into<String>) -> DiagnosticsProperty<String> {
4723    DiagnosticsProperty::new(Some(String::new()), None)
4724        .description(message)
4725        .with_show_name(false)
4726}
4727
4728/// Returns a 5 character long hexadecimal string generated from the 20
4729/// least-significant bits of `hash_code`.
4730pub fn short_hash(hash_code: u64) -> String {
4731    format!("{:05x}", hash_code & 0xfffff)
4732}
4733
4734/// Returns a summary of the runtime type and hash code of an object.
4735pub fn describe_identity(runtime_type: &str, hash_code: u64) -> String {
4736    format!("{runtime_type}#{}", short_hash(hash_code))
4737}
4738
4739/// The last segment of a Rust type path, without generic arguments: what
4740/// diagnostics print where Dart prints `runtimeType`.
4741pub fn bare_type_name(full_type_name: &'static str) -> &'static str {
4742    let last = full_type_name.rsplit("::").next().unwrap_or(full_type_name);
4743    last.split('<').next().unwrap_or(last)
4744}
4745
4746/// A value whose Dart class does not override `toString`, so Dart prints
4747/// `Instance of 'RoundSliderThumbShape'`.
4748pub struct InstanceOf<T>(pub T);
4749
4750impl<T: fmt::Debug> fmt::Display for InstanceOf<T> {
4751    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4752        let debug = format!("{:?}", self.0);
4753        let name = debug
4754            .split(|c: char| !(c.is_alphanumeric() || c == '_'))
4755            .next()
4756            .unwrap_or(&debug);
4757        write!(f, "Instance of '{name}'")
4758    }
4759}
4760
4761impl<T: PartialEq> PartialEq for InstanceOf<T> {
4762    fn eq(&self, other: &InstanceOf<T>) -> bool {
4763        self.0 == other.0
4764    }
4765}
4766
4767impl<T: Clone> Clone for InstanceOf<T> {
4768    fn clone(&self) -> InstanceOf<T> {
4769        InstanceOf(self.0.clone())
4770    }
4771}
4772
4773/// Dart's `Enum.toString`, the type then the case: what a `DiagnosticsProperty` of an enum
4774/// prints, where [`EnumProperty`] prints the case alone.
4775pub struct DartEnum<T>(pub T);
4776
4777impl<T: fmt::Debug> fmt::Display for DartEnum<T> {
4778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4779        write!(
4780            f,
4781            "{}.{}",
4782            bare_type_name(std::any::type_name::<T>()),
4783            describe_enum(&self.0)
4784        )
4785    }
4786}
4787
4788impl<T: PartialEq> PartialEq for DartEnum<T> {
4789    fn eq(&self, other: &DartEnum<T>) -> bool {
4790        self.0 == other.0
4791    }
4792}
4793
4794impl<T: Clone> Clone for DartEnum<T> {
4795    fn clone(&self) -> DartEnum<T> {
4796        DartEnum(self.0.clone())
4797    }
4798}
4799
4800/// Returns a short description of an enum value: its `Debug` text with the
4801/// first character lowercased, as Dart's `Enum.name` prints `deferToChild`.
4802pub fn describe_enum<T: fmt::Debug>(value: &T) -> String {
4803    let description = format!("{value:?}");
4804    let mut chars = description.chars();
4805    match chars.next() {
4806        None => String::new(),
4807        Some(first) => {
4808            let mut result: String = first.to_lowercase().collect();
4809            result.push_str(chars.as_str());
4810            result
4811        }
4812    }
4813}
4814
4815/// Dart's `debugFormatDouble`: one decimal place, and `Infinity` rather than
4816/// Rust's `inf`.
4817pub fn debug_format_double(value: Option<f64>) -> String {
4818    match value {
4819        None => "null".to_string(),
4820        Some(value) if value.is_nan() => "NaN".to_string(),
4821        Some(value) if value == f64::INFINITY => "Infinity".to_string(),
4822        Some(value) if value == f64::NEG_INFINITY => "-Infinity".to_string(),
4823        Some(value) => format!("{value:.1}"),
4824    }
4825}
4826
4827/// Dart's string interpolation of a nullable value, `'$value'`: the value's `Display`, or
4828/// `null`.
4829pub fn display_or_null<T: fmt::Display>(value: &Option<T>) -> impl fmt::Display + '_ {
4830    DisplayOrNull(value)
4831}
4832
4833struct DisplayOrNull<'a, T>(&'a Option<T>);
4834
4835impl<T: fmt::Display> fmt::Display for DisplayOrNull<'_, T> {
4836    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4837        match self.0 {
4838            Some(value) => value.fmt(f),
4839            None => f.write_str("null"),
4840        }
4841    }
4842}
4843
4844#[cfg(test)]
4845mod tests;