Skip to main content

alef_backend_csharp/
gen_visitor.rs

1/// Generate C# visitor support: IVisitor interface, NodeContext/VisitResult records,
2/// VisitorCallbacks (P/Invoke delegate struct), and ConvertWithVisitor method.
3///
4/// # P/Invoke delegate callback strategy
5///
6/// C# uses `[UnmanagedFunctionPointer]` delegate types to create `IntPtr` function pointers
7/// that can be passed through the `HTMHtmVisitorCallbacks` C struct.
8///
9/// - `NodeContext`: a `record` with fields from `HTMHtmNodeContext`.
10/// - `VisitResult`: a discriminated union using a record class hierarchy.
11/// - `IVisitor`: an interface with default no-op implementations for all 40 callbacks.
12/// - `VisitorCallbacks`: an internal class that allocates `GCHandle`s for all delegate
13///   instances and writes them into a marshalled struct layout matching the C struct.
14/// - `ConvertWithVisitor`: static method on the wrapper class that creates the delegate
15///   struct, calls `htm_visitor_create`, `htm_convert_with_visitor`, deserialises JSON.
16use alef_core::hash::{self, CommentStyle};
17use heck::ToSnakeCase;
18
19// ---------------------------------------------------------------------------
20// Callback specification table
21// ---------------------------------------------------------------------------
22
23pub struct CallbackSpec {
24    /// Field name in `HTMHtmVisitorCallbacks`.
25    pub c_field: &'static str,
26    /// C# interface method name (PascalCase).
27    pub cs_method: &'static str,
28    /// XML doc summary.
29    pub doc: &'static str,
30    /// Extra parameters beyond `NodeContext` in the C# interface.
31    pub extra: &'static [ExtraParam],
32    /// If true, add `bool isHeader` (only visit_table_row).
33    pub has_is_header: bool,
34}
35
36pub struct ExtraParam {
37    /// C# parameter name in the interface.
38    pub cs_name: &'static str,
39    /// C# type in the interface method signature.
40    pub cs_type: &'static str,
41    /// P/Invoke types for each raw C parameter (one or more per Java param).
42    pub pinvoke_types: &'static [&'static str],
43    /// C# expression to decode the raw P/Invoke args (vars named `raw<CsName>N`).
44    pub decode: &'static str,
45}
46
47pub const CALLBACKS: &[CallbackSpec] = &[
48    CallbackSpec {
49        c_field: "visit_text",
50        cs_method: "VisitText",
51        doc: "Called for text nodes.",
52        extra: &[ExtraParam {
53            cs_name: "text",
54            cs_type: "string",
55            pinvoke_types: &["IntPtr"],
56            decode: "Marshal.PtrToStringUTF8(rawText0)!",
57        }],
58        has_is_header: false,
59    },
60    CallbackSpec {
61        c_field: "visit_element_start",
62        cs_method: "VisitElementStart",
63        doc: "Called before entering any element.",
64        extra: &[],
65        has_is_header: false,
66    },
67    CallbackSpec {
68        c_field: "visit_element_end",
69        cs_method: "VisitElementEnd",
70        doc: "Called after exiting any element; receives the default markdown output.",
71        extra: &[ExtraParam {
72            cs_name: "output",
73            cs_type: "string",
74            pinvoke_types: &["IntPtr"],
75            decode: "Marshal.PtrToStringUTF8(rawOutput0)!",
76        }],
77        has_is_header: false,
78    },
79    CallbackSpec {
80        c_field: "visit_link",
81        cs_method: "VisitLink",
82        doc: "Called for anchor links. title is null when the attribute is absent.",
83        extra: &[
84            ExtraParam {
85                cs_name: "href",
86                cs_type: "string",
87                pinvoke_types: &["IntPtr"],
88                decode: "Marshal.PtrToStringUTF8(rawHref0)!",
89            },
90            ExtraParam {
91                cs_name: "text",
92                cs_type: "string",
93                pinvoke_types: &["IntPtr"],
94                decode: "Marshal.PtrToStringUTF8(rawText0)!",
95            },
96            ExtraParam {
97                cs_name: "title",
98                cs_type: "string?",
99                pinvoke_types: &["IntPtr"],
100                decode: "rawTitle0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawTitle0)",
101            },
102        ],
103        has_is_header: false,
104    },
105    CallbackSpec {
106        c_field: "visit_image",
107        cs_method: "VisitImage",
108        doc: "Called for images. title is null when absent.",
109        extra: &[
110            ExtraParam {
111                cs_name: "src",
112                cs_type: "string",
113                pinvoke_types: &["IntPtr"],
114                decode: "Marshal.PtrToStringUTF8(rawSrc0)!",
115            },
116            ExtraParam {
117                cs_name: "alt",
118                cs_type: "string",
119                pinvoke_types: &["IntPtr"],
120                decode: "Marshal.PtrToStringUTF8(rawAlt0)!",
121            },
122            ExtraParam {
123                cs_name: "title",
124                cs_type: "string?",
125                pinvoke_types: &["IntPtr"],
126                decode: "rawTitle0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawTitle0)",
127            },
128        ],
129        has_is_header: false,
130    },
131    CallbackSpec {
132        c_field: "visit_heading",
133        cs_method: "VisitHeading",
134        doc: "Called for heading elements h1-h6. id is null when absent.",
135        extra: &[
136            ExtraParam {
137                cs_name: "level",
138                cs_type: "uint",
139                pinvoke_types: &["uint"],
140                decode: "rawLevel0",
141            },
142            ExtraParam {
143                cs_name: "text",
144                cs_type: "string",
145                pinvoke_types: &["IntPtr"],
146                decode: "Marshal.PtrToStringUTF8(rawText0)!",
147            },
148            ExtraParam {
149                cs_name: "id",
150                cs_type: "string?",
151                pinvoke_types: &["IntPtr"],
152                decode: "rawId0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawId0)",
153            },
154        ],
155        has_is_header: false,
156    },
157    CallbackSpec {
158        c_field: "visit_code_block",
159        cs_method: "VisitCodeBlock",
160        doc: "Called for code blocks. lang is null when absent.",
161        extra: &[
162            ExtraParam {
163                cs_name: "lang",
164                cs_type: "string?",
165                pinvoke_types: &["IntPtr"],
166                decode: "rawLang0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawLang0)",
167            },
168            ExtraParam {
169                cs_name: "code",
170                cs_type: "string",
171                pinvoke_types: &["IntPtr"],
172                decode: "Marshal.PtrToStringUTF8(rawCode0)!",
173            },
174        ],
175        has_is_header: false,
176    },
177    CallbackSpec {
178        c_field: "visit_code_inline",
179        cs_method: "VisitCodeInline",
180        doc: "Called for inline code elements.",
181        extra: &[ExtraParam {
182            cs_name: "code",
183            cs_type: "string",
184            pinvoke_types: &["IntPtr"],
185            decode: "Marshal.PtrToStringUTF8(rawCode0)!",
186        }],
187        has_is_header: false,
188    },
189    CallbackSpec {
190        c_field: "visit_list_item",
191        cs_method: "VisitListItem",
192        doc: "Called for list items.",
193        extra: &[
194            ExtraParam {
195                cs_name: "ordered",
196                cs_type: "bool",
197                pinvoke_types: &["int"],
198                decode: "rawOrdered0 != 0",
199            },
200            ExtraParam {
201                cs_name: "marker",
202                cs_type: "string",
203                pinvoke_types: &["IntPtr"],
204                decode: "Marshal.PtrToStringUTF8(rawMarker0)!",
205            },
206            ExtraParam {
207                cs_name: "text",
208                cs_type: "string",
209                pinvoke_types: &["IntPtr"],
210                decode: "Marshal.PtrToStringUTF8(rawText0)!",
211            },
212        ],
213        has_is_header: false,
214    },
215    CallbackSpec {
216        c_field: "visit_list_start",
217        cs_method: "VisitListStart",
218        doc: "Called before processing a list.",
219        extra: &[ExtraParam {
220            cs_name: "ordered",
221            cs_type: "bool",
222            pinvoke_types: &["int"],
223            decode: "rawOrdered0 != 0",
224        }],
225        has_is_header: false,
226    },
227    CallbackSpec {
228        c_field: "visit_list_end",
229        cs_method: "VisitListEnd",
230        doc: "Called after processing a list.",
231        extra: &[
232            ExtraParam {
233                cs_name: "ordered",
234                cs_type: "bool",
235                pinvoke_types: &["int"],
236                decode: "rawOrdered0 != 0",
237            },
238            ExtraParam {
239                cs_name: "output",
240                cs_type: "string",
241                pinvoke_types: &["IntPtr"],
242                decode: "Marshal.PtrToStringUTF8(rawOutput0)!",
243            },
244        ],
245        has_is_header: false,
246    },
247    CallbackSpec {
248        c_field: "visit_table_start",
249        cs_method: "VisitTableStart",
250        doc: "Called before processing a table.",
251        extra: &[],
252        has_is_header: false,
253    },
254    CallbackSpec {
255        c_field: "visit_table_row",
256        cs_method: "VisitTableRow",
257        doc: "Called for table rows. cells contains the cell text values.",
258        extra: &[ExtraParam {
259            cs_name: "cells",
260            cs_type: "string[]",
261            pinvoke_types: &["IntPtr", "UIntPtr"],
262            decode: "DecodeCells(rawCells0, (long)(ulong)rawCells1)",
263        }],
264        has_is_header: true,
265    },
266    CallbackSpec {
267        c_field: "visit_table_end",
268        cs_method: "VisitTableEnd",
269        doc: "Called after processing a table.",
270        extra: &[ExtraParam {
271            cs_name: "output",
272            cs_type: "string",
273            pinvoke_types: &["IntPtr"],
274            decode: "Marshal.PtrToStringUTF8(rawOutput0)!",
275        }],
276        has_is_header: false,
277    },
278    CallbackSpec {
279        c_field: "visit_blockquote",
280        cs_method: "VisitBlockquote",
281        doc: "Called for blockquote elements.",
282        extra: &[
283            ExtraParam {
284                cs_name: "content",
285                cs_type: "string",
286                pinvoke_types: &["IntPtr"],
287                decode: "Marshal.PtrToStringUTF8(rawContent0)!",
288            },
289            ExtraParam {
290                cs_name: "depth",
291                cs_type: "ulong",
292                pinvoke_types: &["UIntPtr"],
293                decode: "(ulong)rawDepth0",
294            },
295        ],
296        has_is_header: false,
297    },
298    CallbackSpec {
299        c_field: "visit_strong",
300        cs_method: "VisitStrong",
301        doc: "Called for strong/bold elements.",
302        extra: &[ExtraParam {
303            cs_name: "text",
304            cs_type: "string",
305            pinvoke_types: &["IntPtr"],
306            decode: "Marshal.PtrToStringUTF8(rawText0)!",
307        }],
308        has_is_header: false,
309    },
310    CallbackSpec {
311        c_field: "visit_emphasis",
312        cs_method: "VisitEmphasis",
313        doc: "Called for emphasis/italic elements.",
314        extra: &[ExtraParam {
315            cs_name: "text",
316            cs_type: "string",
317            pinvoke_types: &["IntPtr"],
318            decode: "Marshal.PtrToStringUTF8(rawText0)!",
319        }],
320        has_is_header: false,
321    },
322    CallbackSpec {
323        c_field: "visit_strikethrough",
324        cs_method: "VisitStrikethrough",
325        doc: "Called for strikethrough elements.",
326        extra: &[ExtraParam {
327            cs_name: "text",
328            cs_type: "string",
329            pinvoke_types: &["IntPtr"],
330            decode: "Marshal.PtrToStringUTF8(rawText0)!",
331        }],
332        has_is_header: false,
333    },
334    CallbackSpec {
335        c_field: "visit_underline",
336        cs_method: "VisitUnderline",
337        doc: "Called for underline elements.",
338        extra: &[ExtraParam {
339            cs_name: "text",
340            cs_type: "string",
341            pinvoke_types: &["IntPtr"],
342            decode: "Marshal.PtrToStringUTF8(rawText0)!",
343        }],
344        has_is_header: false,
345    },
346    CallbackSpec {
347        c_field: "visit_subscript",
348        cs_method: "VisitSubscript",
349        doc: "Called for subscript elements.",
350        extra: &[ExtraParam {
351            cs_name: "text",
352            cs_type: "string",
353            pinvoke_types: &["IntPtr"],
354            decode: "Marshal.PtrToStringUTF8(rawText0)!",
355        }],
356        has_is_header: false,
357    },
358    CallbackSpec {
359        c_field: "visit_superscript",
360        cs_method: "VisitSuperscript",
361        doc: "Called for superscript elements.",
362        extra: &[ExtraParam {
363            cs_name: "text",
364            cs_type: "string",
365            pinvoke_types: &["IntPtr"],
366            decode: "Marshal.PtrToStringUTF8(rawText0)!",
367        }],
368        has_is_header: false,
369    },
370    CallbackSpec {
371        c_field: "visit_mark",
372        cs_method: "VisitMark",
373        doc: "Called for mark/highlight elements.",
374        extra: &[ExtraParam {
375            cs_name: "text",
376            cs_type: "string",
377            pinvoke_types: &["IntPtr"],
378            decode: "Marshal.PtrToStringUTF8(rawText0)!",
379        }],
380        has_is_header: false,
381    },
382    CallbackSpec {
383        c_field: "visit_line_break",
384        cs_method: "VisitLineBreak",
385        doc: "Called for line break elements.",
386        extra: &[],
387        has_is_header: false,
388    },
389    CallbackSpec {
390        c_field: "visit_horizontal_rule",
391        cs_method: "VisitHorizontalRule",
392        doc: "Called for horizontal rule elements.",
393        extra: &[],
394        has_is_header: false,
395    },
396    CallbackSpec {
397        c_field: "visit_custom_element",
398        cs_method: "VisitCustomElement",
399        doc: "Called for custom or unknown elements.",
400        extra: &[
401            ExtraParam {
402                cs_name: "tagName",
403                cs_type: "string",
404                pinvoke_types: &["IntPtr"],
405                decode: "Marshal.PtrToStringUTF8(rawTagName0)!",
406            },
407            ExtraParam {
408                cs_name: "html",
409                cs_type: "string",
410                pinvoke_types: &["IntPtr"],
411                decode: "Marshal.PtrToStringUTF8(rawHtml0)!",
412            },
413        ],
414        has_is_header: false,
415    },
416    CallbackSpec {
417        c_field: "visit_definition_list_start",
418        cs_method: "VisitDefinitionListStart",
419        doc: "Called before a definition list.",
420        extra: &[],
421        has_is_header: false,
422    },
423    CallbackSpec {
424        c_field: "visit_definition_term",
425        cs_method: "VisitDefinitionTerm",
426        doc: "Called for definition term elements.",
427        extra: &[ExtraParam {
428            cs_name: "text",
429            cs_type: "string",
430            pinvoke_types: &["IntPtr"],
431            decode: "Marshal.PtrToStringUTF8(rawText0)!",
432        }],
433        has_is_header: false,
434    },
435    CallbackSpec {
436        c_field: "visit_definition_description",
437        cs_method: "VisitDefinitionDescription",
438        doc: "Called for definition description elements.",
439        extra: &[ExtraParam {
440            cs_name: "text",
441            cs_type: "string",
442            pinvoke_types: &["IntPtr"],
443            decode: "Marshal.PtrToStringUTF8(rawText0)!",
444        }],
445        has_is_header: false,
446    },
447    CallbackSpec {
448        c_field: "visit_definition_list_end",
449        cs_method: "VisitDefinitionListEnd",
450        doc: "Called after a definition list.",
451        extra: &[ExtraParam {
452            cs_name: "output",
453            cs_type: "string",
454            pinvoke_types: &["IntPtr"],
455            decode: "Marshal.PtrToStringUTF8(rawOutput0)!",
456        }],
457        has_is_header: false,
458    },
459    CallbackSpec {
460        c_field: "visit_form",
461        cs_method: "VisitForm",
462        doc: "Called for form elements. action and method may be null.",
463        extra: &[
464            ExtraParam {
465                cs_name: "action",
466                cs_type: "string?",
467                pinvoke_types: &["IntPtr"],
468                decode: "rawAction0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawAction0)",
469            },
470            ExtraParam {
471                cs_name: "method",
472                cs_type: "string?",
473                pinvoke_types: &["IntPtr"],
474                decode: "rawMethod0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawMethod0)",
475            },
476        ],
477        has_is_header: false,
478    },
479    CallbackSpec {
480        c_field: "visit_input",
481        cs_method: "VisitInput",
482        doc: "Called for input elements. name and value may be null.",
483        extra: &[
484            ExtraParam {
485                cs_name: "inputType",
486                cs_type: "string",
487                pinvoke_types: &["IntPtr"],
488                decode: "Marshal.PtrToStringUTF8(rawInputType0)!",
489            },
490            ExtraParam {
491                cs_name: "name",
492                cs_type: "string?",
493                pinvoke_types: &["IntPtr"],
494                decode: "rawName0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawName0)",
495            },
496            ExtraParam {
497                cs_name: "value",
498                cs_type: "string?",
499                pinvoke_types: &["IntPtr"],
500                decode: "rawValue0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawValue0)",
501            },
502        ],
503        has_is_header: false,
504    },
505    CallbackSpec {
506        c_field: "visit_button",
507        cs_method: "VisitButton",
508        doc: "Called for button elements.",
509        extra: &[ExtraParam {
510            cs_name: "text",
511            cs_type: "string",
512            pinvoke_types: &["IntPtr"],
513            decode: "Marshal.PtrToStringUTF8(rawText0)!",
514        }],
515        has_is_header: false,
516    },
517    CallbackSpec {
518        c_field: "visit_audio",
519        cs_method: "VisitAudio",
520        doc: "Called for audio elements. src may be null.",
521        extra: &[ExtraParam {
522            cs_name: "src",
523            cs_type: "string?",
524            pinvoke_types: &["IntPtr"],
525            decode: "rawSrc0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawSrc0)",
526        }],
527        has_is_header: false,
528    },
529    CallbackSpec {
530        c_field: "visit_video",
531        cs_method: "VisitVideo",
532        doc: "Called for video elements. src may be null.",
533        extra: &[ExtraParam {
534            cs_name: "src",
535            cs_type: "string?",
536            pinvoke_types: &["IntPtr"],
537            decode: "rawSrc0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawSrc0)",
538        }],
539        has_is_header: false,
540    },
541    CallbackSpec {
542        c_field: "visit_iframe",
543        cs_method: "VisitIframe",
544        doc: "Called for iframe elements. src may be null.",
545        extra: &[ExtraParam {
546            cs_name: "src",
547            cs_type: "string?",
548            pinvoke_types: &["IntPtr"],
549            decode: "rawSrc0 == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(rawSrc0)",
550        }],
551        has_is_header: false,
552    },
553    CallbackSpec {
554        c_field: "visit_details",
555        cs_method: "VisitDetails",
556        doc: "Called for details elements.",
557        extra: &[ExtraParam {
558            cs_name: "open",
559            cs_type: "bool",
560            pinvoke_types: &["int"],
561            decode: "rawOpen0 != 0",
562        }],
563        has_is_header: false,
564    },
565    CallbackSpec {
566        c_field: "visit_summary",
567        cs_method: "VisitSummary",
568        doc: "Called for summary elements.",
569        extra: &[ExtraParam {
570            cs_name: "text",
571            cs_type: "string",
572            pinvoke_types: &["IntPtr"],
573            decode: "Marshal.PtrToStringUTF8(rawText0)!",
574        }],
575        has_is_header: false,
576    },
577    CallbackSpec {
578        c_field: "visit_figure_start",
579        cs_method: "VisitFigureStart",
580        doc: "Called before a figure element.",
581        extra: &[],
582        has_is_header: false,
583    },
584    CallbackSpec {
585        c_field: "visit_figcaption",
586        cs_method: "VisitFigcaption",
587        doc: "Called for figcaption elements.",
588        extra: &[ExtraParam {
589            cs_name: "text",
590            cs_type: "string",
591            pinvoke_types: &["IntPtr"],
592            decode: "Marshal.PtrToStringUTF8(rawText0)!",
593        }],
594        has_is_header: false,
595    },
596    CallbackSpec {
597        c_field: "visit_figure_end",
598        cs_method: "VisitFigureEnd",
599        doc: "Called after a figure element.",
600        extra: &[ExtraParam {
601            cs_name: "output",
602            cs_type: "string",
603            pinvoke_types: &["IntPtr"],
604            decode: "Marshal.PtrToStringUTF8(rawOutput0)!",
605        }],
606        has_is_header: false,
607    },
608];
609
610// ---------------------------------------------------------------------------
611// Public API
612// ---------------------------------------------------------------------------
613
614/// Returns `(filename, content)` pairs for all visitor-related C# files.
615///
616/// IVisitor.cs and VisitorCallbacks.cs are superseded by IVisitor and VisitorCallbacks
617/// in TraitBridges.cs which use the HtmlVisitorBridge approach. They are intentionally
618/// excluded here; stale committed copies are removed by delete_superseded_visitor_files.
619pub fn gen_visitor_files(namespace: &str) -> Vec<(String, String)> {
620    vec![
621        ("NodeContext.cs".to_string(), gen_node_context(namespace)),
622        ("VisitResult.cs".to_string(), gen_visit_result(namespace)),
623    ]
624}
625
626/// Generate the P/Invoke declarations needed in NativeMethods.cs for visitor FFI.
627///
628/// Parameters:
629/// - `namespace`: C# namespace (unused, kept for compatibility)
630/// - `lib_name`: Native library name (unused, kept for compatibility)
631/// - `prefix`: C FFI function name prefix (e.g., "htm")
632/// - `trait_name`: Name of the visitor trait (e.g., "HtmlVisitor") for bridge function names
633/// - `options_field`: Field name in options to set visitor on (e.g., "visitor")
634pub fn gen_native_methods_visitor(
635    namespace: &str,
636    lib_name: &str,
637    prefix: &str,
638    trait_name: &str,
639    options_field: &str,
640) -> String {
641    use crate::template_env::render;
642    use minijinja::Value;
643
644    // Generate function names:
645    // htm_htm_html_visitor_bridge_new, htm_htm_html_visitor_bridge_free, htm_options_set_visitor
646    let trait_snake = trait_name.to_snake_case();
647    let bridge_snake = format!("{prefix}_{trait_snake}_bridge");
648    let fn_bridge_new = format!("{prefix}_{bridge_snake}_new");
649    let fn_bridge_free = format!("{prefix}_{bridge_snake}_free");
650    let fn_options_set = format!("{prefix}_options_set_{options_field}");
651
652    let mut out = String::from("\n");
653    out.push_str(&render(
654        "native_methods_visitor.jinja",
655        Value::from_serialize(serde_json::json!({
656            "fn_bridge_new": fn_bridge_new,
657            "fn_bridge_free": fn_bridge_free,
658            "fn_options_set": fn_options_set,
659        })),
660    ));
661
662    let _ = namespace;
663    let _ = lib_name;
664    out
665}
666
667/// DEPRECATED: gen_convert_with_visitor_method is no longer used.
668/// The visitor logic is now integrated into the main Convert() method in gen_wrapper_function,
669/// which creates the HtmlVisitorBridge and uses htm_options_set_visitor instead.
670#[allow(dead_code)]
671pub fn gen_convert_with_visitor_method(exception_name: &str, prefix: &str) -> String {
672    let _ = exception_name;
673    let _ = prefix;
674    String::new()
675}
676
677// ---------------------------------------------------------------------------
678// Individual file generators
679// ---------------------------------------------------------------------------
680
681fn gen_node_context(namespace: &str) -> String {
682    use crate::template_env::render;
683    use minijinja::Value;
684
685    let mut out = String::with_capacity(1024);
686    out.push_str(&hash::header(CommentStyle::DoubleSlash));
687    out.push_str("#nullable enable\n");
688    out.push('\n');
689    out.push_str("using System;\n");
690    out.push('\n');
691    out.push_str(&render(
692        "namespace_decl.jinja",
693        Value::from_serialize(serde_json::json!({
694            "namespace": namespace,
695        })),
696    ));
697    out.push_str("/// <summary>Context passed to every visitor callback.</summary>\n");
698    out.push_str("public record NodeContext(\n");
699    out.push_str("    /// <summary>Coarse-grained node type tag.</summary>\n");
700    out.push_str("    NodeType NodeType,\n");
701    out.push_str("    /// <summary>HTML element tag name (e.g. \"div\").</summary>\n");
702    out.push_str("    string TagName,\n");
703    out.push_str("    /// <summary>DOM depth (0 = root).</summary>\n");
704    out.push_str("    ulong Depth,\n");
705    out.push_str("    /// <summary>0-based sibling index.</summary>\n");
706    out.push_str("    ulong IndexInParent,\n");
707    out.push_str("    /// <summary>Parent element tag name, or null at the root.</summary>\n");
708    out.push_str("    string? ParentTag,\n");
709    out.push_str("    /// <summary>True when this element is treated as inline.</summary>\n");
710    out.push_str("    bool IsInline\n");
711    out.push_str(");\n");
712    out
713}
714
715fn gen_visit_result(namespace: &str) -> String {
716    use crate::template_env::render;
717    use minijinja::Value;
718
719    let mut out = String::with_capacity(2048);
720    out.push_str(&hash::header(CommentStyle::DoubleSlash));
721    out.push_str("#nullable enable\n");
722    out.push('\n');
723    out.push_str("using System;\n");
724    out.push('\n');
725    out.push_str(&render(
726        "namespace_decl.jinja",
727        Value::from_serialize(serde_json::json!({
728            "namespace": namespace,
729        })),
730    ));
731    out.push_str("/// <summary>Controls how the visitor affects the conversion pipeline.</summary>\n");
732    out.push_str("public abstract record VisitResult\n");
733    out.push_str("{\n");
734    out.push_str("    private VisitResult() {}\n");
735    out.push('\n');
736    out.push_str("    /// <summary>Proceed with default conversion.</summary>\n");
737    out.push_str("    public sealed record Continue : VisitResult;\n");
738    out.push('\n');
739    out.push_str("    /// <summary>Omit this element from output entirely.</summary>\n");
740    out.push_str("    public sealed record Skip : VisitResult;\n");
741    out.push('\n');
742    out.push_str("    /// <summary>Keep original HTML verbatim.</summary>\n");
743    out.push_str("    public sealed record PreserveHtml : VisitResult;\n");
744    out.push('\n');
745    out.push_str("    /// <summary>Replace with custom Markdown.</summary>\n");
746    out.push_str("    public sealed record Custom(string Markdown) : VisitResult;\n");
747    out.push('\n');
748    out.push_str("    /// <summary>Abort conversion with an error message.</summary>\n");
749    out.push_str("    public sealed record Error(string Message) : VisitResult;\n");
750    out.push('\n');
751    out.push_str("    internal string ToFfiJson() => this switch {\n");
752    out.push_str("        VisitResult.Continue => \"\\\"Continue\\\"\",\n");
753    out.push_str("        VisitResult.Skip => \"\\\"Skip\\\"\",\n");
754    out.push_str("        VisitResult.PreserveHtml => \"\\\"PreserveHtml\\\"\",\n");
755    out.push_str("        VisitResult.Custom c => \"{{\\\"Custom\\\":\" + System.Text.Json.JsonSerializer.Serialize(c.Markdown) + \"}}\",\n");
756    out.push_str("        VisitResult.Error e => \"{{\\\"Error\\\":\" + System.Text.Json.JsonSerializer.Serialize(e.Message) + \"}}\",\n");
757    out.push_str("        _ => \"\\\"Continue\\\"\"\n");
758    out.push_str("    };\n");
759    out.push_str("}\n");
760    out
761}
762
763// gen_ivisitor and gen_visitor_callbacks were removed: IVisitor and VisitorCallbacks
764// are now handwritten in TraitBridges.cs (HtmlVisitorBridge pattern). Generating them
765// here produced dead code that conflicted with the handwritten implementations.