ruchy 4.1.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// NOTEBOOK-004: Rich HTML Output Formatting
// Phase 4: Notebook Excellence - HTML Rendering for Rich Output
//
// This module provides HTML formatting for notebook output:
// - Code syntax highlighting
// - Error messages with formatting
// - HTML tables for DataFrames
// - Value formatting with type information
//
// Quality Requirements:
// - Cyclomatic Complexity: ≤10 per function (Toyota Way)
// - Line Coverage: ≥85%
// - Branch Coverage: ≥90%

/// HTML formatter for notebook output
///
/// Converts plain text output into formatted HTML with syntax highlighting,
/// tables, and rich error display.
///
/// # Examples
///
/// ```
/// use ruchy::notebook::html::HtmlFormatter;
///
/// let formatter = HtmlFormatter::new();
/// let html = formatter.format_value("42");
/// assert!(html.contains("42"));
/// ```
#[derive(Debug, Clone)]
pub struct HtmlFormatter {
    /// Enable syntax highlighting
    syntax_highlighting: bool,
    /// Enable line numbers in code blocks
    line_numbers: bool,
    /// CSS theme (light/dark)
    theme: String,
}

impl Default for HtmlFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl HtmlFormatter {
    /// Create a new HTML formatter with default settings
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::html::HtmlFormatter;
    ///
    /// let formatter = HtmlFormatter::new();
    /// assert_eq!(formatter.theme(), "light");
    /// ```
    pub fn new() -> Self {
        Self {
            syntax_highlighting: true,
            line_numbers: false,
            theme: "light".to_string(),
        }
    }

    /// Create a formatter with custom theme
    pub fn with_theme(theme: String) -> Self {
        Self {
            syntax_highlighting: true,
            line_numbers: false,
            theme,
        }
    }

    /// Enable or disable syntax highlighting
    pub fn set_syntax_highlighting(&mut self, enabled: bool) {
        self.syntax_highlighting = enabled;
    }

    /// Enable or disable line numbers
    pub fn set_line_numbers(&mut self, enabled: bool) {
        self.line_numbers = enabled;
    }

    /// Set the theme
    pub fn set_theme(&mut self, theme: String) {
        self.theme = theme;
    }

    /// Get the current theme
    pub fn theme(&self) -> &str {
        &self.theme
    }

    /// Format a plain value as HTML
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::html::HtmlFormatter;
    ///
    /// let formatter = HtmlFormatter::new();
    /// let html = formatter.format_value("42");
    /// assert!(html.contains("42"));
    /// assert!(html.contains("<span"));
    /// ```
    pub fn format_value(&self, value: &str) -> String {
        format!(
            r#"<div class="notebook-output"><span class="output-value">{}</span></div>"#,
            html_escape(value)
        )
    }

    /// Format code with syntax highlighting
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::html::HtmlFormatter;
    ///
    /// let formatter = HtmlFormatter::new();
    /// let html = formatter.format_code("let x = 42");
    /// assert!(html.contains("let"));
    /// assert!(html.contains("x"));
    /// ```
    pub fn format_code(&self, code: &str) -> String {
        if self.syntax_highlighting {
            self.format_code_with_highlighting(code)
        } else {
            format!(r#"<pre class="notebook-code">{}</pre>"#, html_escape(code))
        }
    }

    /// Format an error message with styling
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::html::HtmlFormatter;
    ///
    /// let formatter = HtmlFormatter::new();
    /// let html = formatter.format_error("Parse error: unexpected token");
    /// assert!(html.contains("error"));
    /// assert!(html.contains("Parse error"));
    /// ```
    pub fn format_error(&self, error: &str) -> String {
        format!(
            r#"<div class="notebook-error"><span class="error-icon">❌</span> <span class="error-message">{}</span></div>"#,
            html_escape(error)
        )
    }

    /// Format a table (for `DataFrames`)
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::notebook::html::HtmlFormatter;
    ///
    /// let formatter = HtmlFormatter::new();
    /// let headers = vec!["Name", "Age"];
    /// let rows = vec![
    ///     vec!["Alice", "30"],
    ///     vec!["Bob", "25"],
    /// ];
    /// let html = formatter.format_table(&headers, &rows);
    /// assert!(html.contains("<table"));
    /// assert!(html.contains("Alice"));
    /// ```
    pub fn format_table(&self, headers: &[&str], rows: &[Vec<&str>]) -> String {
        let mut html = String::from(r#"<table class="notebook-table">"#);

        // Headers
        html.push_str("<thead><tr>");
        for header in headers {
            html.push_str(&format!("<th>{}</th>", html_escape(header)));
        }
        html.push_str("</tr></thead>");

        // Rows
        html.push_str("<tbody>");
        for row in rows {
            html.push_str("<tr>");
            for cell in row {
                html.push_str(&format!("<td>{}</td>", html_escape(cell)));
            }
            html.push_str("</tr>");
        }
        html.push_str("</tbody>");

        html.push_str("</table>");
        html
    }

    /// Format a list as HTML
    pub fn format_list(&self, items: &[&str]) -> String {
        let mut html = String::from(r#"<ul class="notebook-list">"#);
        for item in items {
            html.push_str(&format!("<li>{}</li>", html_escape(item)));
        }
        html.push_str("</ul>");
        html
    }

    /// Format code with syntax highlighting (internal)
    fn format_code_with_highlighting(&self, code: &str) -> String {
        let mut html = String::from(r#"<pre class="notebook-code syntax-highlighted">"#);

        // Simple keyword highlighting (can be enhanced with proper syntax highlighter)
        let keywords = [
            "let", "fn", "if", "else", "for", "while", "match", "return", "struct", "enum", "impl",
            "trait", "pub", "mut", "const", "static",
        ];

        let mut highlighted = html_escape(code);
        for keyword in &keywords {
            // Simple replacement (not regex for simplicity)
            highlighted = highlighted.replace(
                &format!(" {keyword} "),
                &format!(r#" <span class="keyword">{keyword}</span> "#),
            );
        }

        html.push_str(&highlighted);
        html.push_str("</pre>");
        html
    }

    /// Check if syntax highlighting is enabled
    pub fn syntax_highlighting_enabled(&self) -> bool {
        self.syntax_highlighting
    }

    /// Check if line numbers are enabled
    pub fn line_numbers_enabled(&self) -> bool {
        self.line_numbers
    }
}

/// Escape HTML special characters
///
/// # Examples
///
/// ```
/// use ruchy::notebook::html::html_escape;
///
/// assert_eq!(html_escape("<script>"), "&lt;script&gt;");
/// assert_eq!(html_escape("a & b"), "a &amp; b");
/// ```
pub fn html_escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

#[cfg(test)]
mod tests {
    use super::*;

    // RED PHASE: Write tests that define expected behavior

    #[test]
    fn test_notebook_004_html_formatter_creation() {
        let formatter = HtmlFormatter::new();
        assert_eq!(formatter.theme(), "light");
        assert!(formatter.syntax_highlighting_enabled());
        assert!(!formatter.line_numbers_enabled());
    }

    #[test]
    fn test_notebook_004_html_formatter_with_theme() {
        let formatter = HtmlFormatter::with_theme("dark".to_string());
        assert_eq!(formatter.theme(), "dark");
    }

    #[test]
    fn test_notebook_004_format_value() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_value("42");

        assert!(html.contains("notebook-output"));
        assert!(html.contains("42"));
        assert!(html.contains("<div"));
    }

    #[test]
    fn test_notebook_004_format_value_escapes_html() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_value("<script>alert('xss')</script>");

        assert!(html.contains("&lt;script&gt;"));
        assert!(!html.contains("<script>"));
    }

    #[test]
    fn test_notebook_004_format_code() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_code("let x = 42");

        assert!(html.contains("<pre"));
        assert!(html.contains('x'));
        assert!(html.contains("42"));
    }

    #[test]
    fn test_notebook_004_format_code_with_highlighting() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_code("let x = 42");

        assert!(html.contains("syntax-highlighted"));
    }

    #[test]
    fn test_notebook_004_format_code_without_highlighting() {
        let mut formatter = HtmlFormatter::new();
        formatter.set_syntax_highlighting(false);
        let html = formatter.format_code("let x = 42");

        assert!(!html.contains("syntax-highlighted"));
        assert!(html.contains("<pre"));
    }

    #[test]
    fn test_notebook_004_format_error() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_error("Parse error: unexpected token");

        assert!(html.contains("notebook-error"));
        assert!(html.contains("Parse error"));
        assert!(html.contains(""));
    }

    #[test]
    fn test_notebook_004_format_error_escapes_html() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_error("<script>alert('error')</script>");

        assert!(html.contains("&lt;script&gt;"));
        assert!(!html.contains("<script>"));
    }

    #[test]
    fn test_notebook_004_format_table() {
        let formatter = HtmlFormatter::new();
        let headers = vec!["Name", "Age"];
        let rows = vec![vec!["Alice", "30"], vec!["Bob", "25"]];

        let html = formatter.format_table(&headers, &rows);

        assert!(html.contains("<table"));
        assert!(html.contains("<thead"));
        assert!(html.contains("<tbody"));
        assert!(html.contains("Name"));
        assert!(html.contains("Alice"));
        assert!(html.contains("30"));
    }

    #[test]
    fn test_notebook_004_format_empty_table() {
        let formatter = HtmlFormatter::new();
        let headers: Vec<&str> = vec![];
        let rows: Vec<Vec<&str>> = vec![];

        let html = formatter.format_table(&headers, &rows);

        assert!(html.contains("<table"));
        assert!(html.contains("<thead"));
        assert!(html.contains("<tbody"));
    }

    #[test]
    fn test_notebook_004_format_list() {
        let formatter = HtmlFormatter::new();
        let items = vec!["Item 1", "Item 2", "Item 3"];

        let html = formatter.format_list(&items);

        assert!(html.contains("<ul"));
        assert!(html.contains("<li>Item 1</li>"));
        assert!(html.contains("<li>Item 2</li>"));
    }

    #[test]
    fn test_notebook_004_html_escape() {
        assert_eq!(html_escape("<script>"), "&lt;script&gt;");
        assert_eq!(html_escape("a & b"), "a &amp; b");
        assert_eq!(html_escape("\"quoted\""), "&quot;quoted&quot;");
        assert_eq!(html_escape("'single'"), "&#39;single&#39;");
    }

    #[test]
    fn test_notebook_004_formatter_settings() {
        let mut formatter = HtmlFormatter::new();

        formatter.set_syntax_highlighting(false);
        assert!(!formatter.syntax_highlighting_enabled());

        formatter.set_line_numbers(true);
        assert!(formatter.line_numbers_enabled());

        formatter.set_theme("dark".to_string());
        assert_eq!(formatter.theme(), "dark");
    }

    #[test]
    fn test_notebook_004_formatter_clone() {
        let formatter = HtmlFormatter::new();
        let cloned = formatter.clone();

        assert_eq!(formatter.theme(), cloned.theme());
        assert_eq!(
            formatter.syntax_highlighting_enabled(),
            cloned.syntax_highlighting_enabled()
        );
    }

    #[test]
    fn test_notebook_004_formatter_debug() {
        let formatter = HtmlFormatter::new();
        let debug_str = format!("{formatter:?}");

        assert!(debug_str.contains("HtmlFormatter"));
        assert!(debug_str.contains("light"));
    }

    #[test]
    fn test_notebook_004_format_multiline_code() {
        let formatter = HtmlFormatter::new();
        let code = "fn main() {\n    let x = 42;\n}";
        let html = formatter.format_code(code);

        assert!(html.contains("fn"));
        assert!(html.contains("main"));
        assert!(html.contains("42"));
    }

    #[test]
    fn test_notebook_004_format_special_characters() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_value("a < b && c > d");

        assert!(html.contains("&lt;"));
        assert!(html.contains("&gt;"));
        assert!(html.contains("&amp;"));
    }

    #[test]
    fn test_notebook_004_format_unicode() {
        let formatter = HtmlFormatter::new();
        let html = formatter.format_value("Hello 世界 🌍");

        assert!(html.contains("Hello 世界 🌍"));
    }

    #[test]
    fn test_notebook_004_table_with_special_chars() {
        let formatter = HtmlFormatter::new();
        let headers = vec!["<Name>", "&Age"];
        let rows = vec![vec!["Alice & Bob", "<30>"]];

        let html = formatter.format_table(&headers, &rows);

        assert!(html.contains("&lt;Name&gt;"));
        assert!(html.contains("&amp;Age"));
        assert!(html.contains("Alice &amp; Bob"));
    }

    // PROPERTY TESTS: Verify robustness with random inputs
    #[cfg(test)]
    mod property_tests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn html_formatter_never_panics_on_value(value: String) {
                let formatter = HtmlFormatter::new();
                let _ = formatter.format_value(&value);
            }

            #[test]
            fn html_formatter_never_panics_on_code(code: String) {
                let formatter = HtmlFormatter::new();
                let _ = formatter.format_code(&code);
            }

            #[test]
            fn html_formatter_never_panics_on_error(error: String) {
                let formatter = HtmlFormatter::new();
                let _ = formatter.format_error(&error);
            }

            #[test]
            fn html_escape_handles_any_string(input: String) {
                let escaped = html_escape(&input);
                // Should not panic and should not contain unescaped special chars
                assert!(!escaped.contains("<script>"));
            }

            #[test]
            fn html_formatter_escapes_dangerous_tags(
                tag in "<(script|iframe|object|embed)[^>]*>"
            ) {
                let formatter = HtmlFormatter::new();
                let html = formatter.format_value(&tag);
                // Should be escaped
                assert!(!html.contains(&tag));
                assert!(html.contains("&lt;"));
            }

            #[test]
            fn html_table_handles_any_headers(
                headers in prop::collection::vec("[a-zA-Z0-9]{1,20}", 0..10)
            ) {
                let formatter = HtmlFormatter::new();
                let header_refs: Vec<&str> = headers.iter().map(std::string::String::as_str).collect();
                let rows: Vec<Vec<&str>> = vec![];
                let html = formatter.format_table(&header_refs, &rows);
                assert!(html.contains("<table"));
            }

            #[test]
            fn html_list_handles_any_items(
                items in prop::collection::vec(".*", 0..20)
            ) {
                let formatter = HtmlFormatter::new();
                let item_refs: Vec<&str> = items.iter().map(std::string::String::as_str).collect();
                let html = formatter.format_list(&item_refs);
                assert!(html.contains("<ul"));
            }

            #[test]
            fn html_formatter_theme_preserved(
                theme in "[a-z]{4,10}"
            ) {
                let formatter = HtmlFormatter::with_theme(theme.clone());
                assert_eq!(formatter.theme(), theme);
            }

            #[test]
            fn html_escape_reversible_safe_chars(
                input in "[a-zA-Z0-9 ]{1,100}"
            ) {
                let escaped = html_escape(&input);
                // Safe characters should remain unchanged
                assert_eq!(escaped, input);
            }

            #[test]
            fn html_formatter_output_always_valid_structure(
                value in ".*"
            ) {
                let formatter = HtmlFormatter::new();
                let html = formatter.format_value(&value);
                // Should have proper HTML structure
                assert!(html.starts_with("<div"));
                assert!(html.ends_with("</div>"));
            }

            #[test]
            fn html_code_output_always_has_pre_tag(
                code in ".*"
            ) {
                let formatter = HtmlFormatter::new();
                let html = formatter.format_code(&code);
                assert!(html.contains("<pre"));
                assert!(html.contains("</pre>"));
            }

            #[test]
            fn html_error_always_has_error_class(
                error in ".*"
            ) {
                let formatter = HtmlFormatter::new();
                let html = formatter.format_error(&error);
                assert!(html.contains("notebook-error"));
                assert!(html.contains(""));
            }

            #[test]
            fn html_formatter_settings_are_independent(
                highlighting: bool,
                line_numbers: bool
            ) {
                let mut formatter = HtmlFormatter::new();
                formatter.set_syntax_highlighting(highlighting);
                formatter.set_line_numbers(line_numbers);

                assert_eq!(formatter.syntax_highlighting_enabled(), highlighting);
                assert_eq!(formatter.line_numbers_enabled(), line_numbers);
            }

            #[test]
            fn html_table_structure_valid_for_any_size(
                row_count in 0usize..20,
                col_count in 0usize..10
            ) {
                let formatter = HtmlFormatter::new();
                let headers: Vec<&str> = (0..col_count).map(|_| "H").collect();
                let rows: Vec<Vec<&str>> = (0..row_count)
                    .map(|_| (0..col_count).map(|_| "C").collect())
                    .collect();

                let html = formatter.format_table(&headers, &rows);
                assert!(html.contains("<table"));
                assert!(html.contains("</table>"));
            }

            #[test]
            fn html_escape_ampersand_first(
                input in ".*&.*"
            ) {
                let escaped = html_escape(&input);
                // Ampersand should be escaped
                if input.contains('&') {
                    assert!(escaped.contains("&amp;"));
                }
            }

            #[test]
            fn html_formatter_clone_preserves_settings(
                theme in "[a-z]{4,8}",
                highlighting: bool
            ) {
                let mut formatter = HtmlFormatter::with_theme(theme.clone());
                formatter.set_syntax_highlighting(highlighting);

                let cloned = formatter.clone();

                assert_eq!(cloned.theme(), theme);
                assert_eq!(cloned.syntax_highlighting_enabled(), highlighting);
            }
        }
    }
}