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
//! User-defined macros (`\def` and friends)

use texcraft_stdext::algorithms::substringsearch::Matcher;
use texcraft_stdext::collections::groupingmap;
use texcraft_stdext::collections::nevec::Nevec;
use texcraft_stdext::nevec;
use texlang::token::trace;
use texlang::traits::*;
use texlang::*;

pub const DEF_DOC: &str = "Define a custom macro";

/// Get the `\def` command.
pub fn get_def<S: TexlangState>() -> command::BuiltIn<S> {
    command::BuiltIn::new_execution(def_primitive_fn).with_tag(def_tag())
}

/// Get the `\gdef` command.
pub fn get_gdef<S: TexlangState>() -> command::BuiltIn<S> {
    command::BuiltIn::new_execution(gdef_primitive_fn).with_tag(def_tag())
}

static DEF_TAG: command::StaticTag = command::StaticTag::new();

pub fn def_tag() -> command::Tag {
    DEF_TAG.get()
}

fn def_primitive_fn<S: TexlangState>(
    def_token: token::Token,
    input: &mut vm::ExecutionInput<S>,
) -> Result<(), Box<error::Error>> {
    parse_and_set_macro(def_token, input, false)
}

fn gdef_primitive_fn<S: TexlangState>(
    def_token: token::Token,
    input: &mut vm::ExecutionInput<S>,
) -> Result<(), Box<error::Error>> {
    parse_and_set_macro(def_token, input, true)
}

fn parse_and_set_macro<S: TexlangState>(
    _: token::Token,
    input: &mut vm::ExecutionInput<S>,
    set_globally_override: bool,
) -> Result<(), Box<error::Error>> {
    let mut scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
    if set_globally_override {
        scope = groupingmap::Scope::Global;
    }
    let target = token::CommandRef::parse(input)?;
    let (prefix, raw_parameters, replacement_end_token) =
        parse_prefix_and_parameters(input.unexpanded())?;
    let parameters: Vec<texmacro::Parameter> = raw_parameters
        .into_iter()
        .map(|a| match a {
            RawParameter::Undelimited => texmacro::Parameter::Undelimited,
            RawParameter::Delimited(vec) => texmacro::Parameter::Delimited(Matcher::new(vec)),
        })
        .collect();
    let mut replacement =
        parse_replacement_text(input.unexpanded(), replacement_end_token, parameters.len())?;
    for r in replacement.iter_mut() {
        if let texmacro::Replacement::Tokens(tokens) = r {
            tokens.reverse();
        }
    }
    let user_defined_macro = texmacro::Macro::new(prefix, parameters, replacement);
    input
        .commands_map_mut()
        .insert_macro(target, user_defined_macro, scope);
    Ok(())
}

enum RawParameter {
    Undelimited,
    Delimited(Nevec<token::Token>),
}

impl RawParameter {
    fn push(&mut self, t: token::Token) {
        match self {
            RawParameter::Undelimited => {
                *self = RawParameter::Delimited(nevec![t]);
            }
            RawParameter::Delimited(vec) => {
                vec.push(t);
            }
        }
    }
}

fn char_to_parameter_index(c: char) -> Option<usize> {
    match c {
        '1' => Some(0),
        '2' => Some(1),
        '3' => Some(2),
        '4' => Some(3),
        '5' => Some(4),
        '6' => Some(5),
        '7' => Some(6),
        '8' => Some(7),
        '9' => Some(8),
        _ => None,
    }
}

fn parse_prefix_and_parameters<S: TexlangState>(
    input: &mut vm::UnexpandedStream<S>,
) -> command::Result<(Vec<token::Token>, Vec<RawParameter>, Option<token::Token>)> {
    let mut prefix = Vec::new();
    let mut parameters = Vec::new();
    let mut replacement_end_token = None;

    while let Some(token) = input.next()? {
        match token.value() {
            token::Value::BeginGroup(_) => {
                return Ok((prefix, parameters, replacement_end_token));
            }
            token::Value::EndGroup(_) => {
                return Err(error::SimpleTokenError::new(
                    input.vm(),
                    token,
                    "unexpected end group token while parsing the parameter of a macro definition",
                )
                .into());
            }
            token::Value::Parameter(_) => {
                let parameter_token = match input.next()? {
                    None => {
                        return Err(error::SimpleEndOfInputError::new(input.vm(),
                "unexpected end of input while reading the token after a parameter token").into());
                        // TODO .add_note("a parameter token must be followed by a single digit number, another parameter token, or a closing brace {.")
                    }
                    Some(token) => token,
                };
                match parameter_token.value() {
                    token::Value::BeginGroup(_) => {
                        // In this case we end the group according to the special #{ rule
                        replacement_end_token = Some(parameter_token);
                        match parameters.last_mut() {
                            None => {
                                prefix.push(parameter_token);
                            }
                            Some(spec) => {
                                spec.push(parameter_token);
                            }
                        }
                        return Ok((prefix, parameters, replacement_end_token));
                    }
                    token::Value::CommandRef(..) => {
                        return Err(error::SimpleTokenError::new(
                            input.vm(),
                            parameter_token,
                            "unexpected control sequence after a parameter token",
                        )
                        .into());
                        // TODO: are we sure we really know what's going on here?
                        // TODO "a parameter token must be followed by a single digit number, another parameter token, or a closing brace {.")
                    }
                    _ => {
                        let c = parameter_token.char().unwrap();
                        let parameter_index = match char_to_parameter_index(c) {
                            None => {
                                return Err(error::SimpleTokenError::new(
                                    input.vm(),
                                    parameter_token,
                                    "unexpected character after a parameter token",
                                )
                                .into());
                                // TODO .add_note("a parameter token must be followed by a single digit number, another parameter token, or a closing brace {.")
                            }
                            Some(n) => n,
                        };
                        if parameter_index != parameters.len() {
                            return Err(InvalidParameterNumberError {
                                parameter_number_token: input.trace(parameter_token),
                                parameter_index,
                                parameters_so_far: parameters.len(),
                            }
                            .into());
                        }
                        parameters.push(RawParameter::Undelimited);
                    }
                }
            }
            _ => match parameters.last_mut() {
                None => {
                    prefix.push(token);
                }
                Some(parameter) => {
                    parameter.push(token);
                }
            },
        }
    }
    Err(error::SimpleEndOfInputError::new(
        input.vm(),
        "unexpected end of input while reading the parameter text of a macro",
    )
    .into())
    // TODO .add_note("the parameter text of a macro must end with a closing brace { or another token with catcode 1 (begin group)")
}

fn parse_replacement_text<S: TexlangState>(
    input: &mut vm::UnexpandedStream<S>,
    opt_final_token: Option<token::Token>,
    num_parameters: usize,
) -> command::Result<Vec<texmacro::Replacement>> {
    // TODO: could we use a pool of vectors to avoid some of the allocations here?
    let mut result = vec![];
    let mut scope_depth = 0;
    let push = |result: &mut Vec<texmacro::Replacement>, token| match result.last_mut() {
        Some(texmacro::Replacement::Tokens(tokens)) => {
            tokens.push(token);
        }
        _ => {
            result.push(texmacro::Replacement::Tokens(vec![token]));
        }
    };

    while let Some(token) = input.next()? {
        match token.value() {
            token::Value::BeginGroup(_) => {
                scope_depth += 1;
            }
            token::Value::EndGroup(_) => {
                if scope_depth == 0 {
                    if let Some(final_token) = opt_final_token {
                        push(&mut result, final_token);
                    }
                    return Ok(result);
                }
                scope_depth -= 1;
            }
            token::Value::Parameter(_) => {
                let parameter_token = match input.next()? {
                    None => {
                        return Err(error::SimpleEndOfInputError::new(
                            input.vm(),
                            "unexpected end of input while reading a parameter number",
                        )
                        .into())
                    }
                    Some(token) => token,
                };
                let c = match parameter_token.value() {
                    token::Value::CommandRef(..) => {
                        return Err(error::SimpleTokenError::new(
                            input.vm(),
                            parameter_token,
                            "unexpected character while reading a parameter number",
                        )
                        .into());
                        // TODO .add_note("expected a number between 1 and 9 inclusive")
                    }
                    token::Value::Parameter(_) => {
                        push(&mut result, parameter_token);
                        continue;
                    }
                    _ => parameter_token.char().unwrap(),
                };

                let parameter_index = match char_to_parameter_index(c) {
                    None => {
                        return Err(error::SimpleTokenError::new(
                            input.vm(),
                            parameter_token,
                            "unexpected character while reading a parameter number",
                        )
                        .into());
                        // TODO .add_note("expected a number between 1 and 9 inclusive")
                    }
                    Some(n) => n,
                };
                if parameter_index >= num_parameters {
                    return Err(error::SimpleTokenError::new(
                        input.vm(),
                        parameter_token,
                        "unexpected character while reading a parameter number",
                    )
                    .into());

                    /* TODO
                            var msg string
                            switch numParams {
                            case 0:
                                msg = "no parameter token because this macro has 0 parameters"
                            case 1:
                                msg = "the number 1 because this macro has only 1 parameter"
                            default:
                                msg = fmt.Sprintf(
                                    "a number between 1 and %[1]d inclusive because this macro has only %[1]d parameters",
                                    numParams)
                            }
                            return nil, errors.NewUnexpectedTokenError(t, msg, "the number "+t.Value(), parsingArgumentTemplate)
                    */
                }
                result.push(texmacro::Replacement::Parameter(parameter_index));
                continue;
            }
            _ => {}
        }

        push(&mut result, token);
    }

    Err(error::SimpleEndOfInputError::new(
        input.vm(),
        "unexpected end of input while reading a parameter number",
    )
    .into())
}

#[derive(Debug)]
struct InvalidParameterNumberError {
    parameter_number_token: trace::SourceCodeTrace,
    parameter_index: usize,
    parameters_so_far: usize,
}

impl error::TexError for InvalidParameterNumberError {
    fn kind(&self) -> error::Kind {
        error::Kind::Token(&self.parameter_number_token)
    }

    fn title(&self) -> String {
        format!["unexpected parameter number {}", self.parameter_index + 1]
    }

    fn notes(&self) -> Vec<error::display::Note> {
        vec![format![
            "this macro has {} parameter(s) so far, so parameter number #{} was expected.",
            self.parameters_so_far,
            self.parameters_so_far + 1
        ]
        .into()]
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    use super::*;
    use crate::prefix;

    #[derive(Default, serde::Serialize, serde::Deserialize)]
    struct State {
        prefix: prefix::Component,
        testing: texlang_testing::TestingComponent,
    }

    implement_has_component![State {
        prefix: prefix::Component,
        testing: texlang_testing::TestingComponent,
    }];

    impl TexlangState for State {
        fn variable_assignment_scope_hook(
            state: &mut Self,
        ) -> texcraft_stdext::collections::groupingmap::Scope {
            prefix::variable_assignment_scope_hook(state)
        }
        fn recoverable_error_hook(
            vm: &vm::VM<Self>,
            recoverable_error: Box<error::Error>,
        ) -> Result<(), Box<error::Error>> {
            texlang_testing::TestingComponent::recoverable_error_hook(vm, recoverable_error)
        }
    }

    fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
        HashMap::from([
            ("def", get_def()),
            ("gdef", get_gdef()),
            ("global", prefix::get_global()),
            ("assertGlobalIsFalse", prefix::get_assert_global_is_false()),
        ])
    }

    texlang_testing::test_suite![
        state(State),
        options(
            texlang_testing::TestOption::BuiltInCommands(built_in_commands),
            texlang_testing::TestOption::AllowUndefinedCommands(true),
        ),
        expansion_equality_tests(
            (def_parsed_successfully, r"\def\A{abc}", ""),
            (output_is_correct, r"\def\A{abc}\A", "abc"),
            (active_char, r"\def~{abc}~", "abc"),
            (output_twice, "\\def\\A{abc}\\A\\A", "abcabc"),
            (parse_one_parameter, "\\def\\A#1{a-#1-b}", ""),
            (one_undelimited_parameter, "\\def\\A#1{a-#1-b}\\A1", "a-1-b"),
            (
                one_undelimited_parameter_multiple_times,
                "\\def\\A#1{#1 #1 #1}\\A1",
                "1 1 1"
            ),
            (
                one_undelimited_parameter_multiple_tokens,
                "\\def\\A#1{a-#1-b}\\A{123}",
                "a-123-b"
            ),
            (
                two_undelimited_parameters,
                "\\def\\A#1#2{#2-#1}\\A56",
                "6-5"
            ),
            (
                two_undelimited_parameters_multiple_token_inputs,
                "\\def\\A#1#2{#2-#1}\\A{abc}{xyz}",
                "xyz-abc"
            ),
            (
                consume_prefix_correctly,
                "\\def\\A fgh{567}\\A fghi",
                "567i"
            ),
            (
                one_undelimited_parameter_with_prefix,
                "\\def\\A abc#1{y#1z}\\A abcdefg",
                "ydzefg"
            ),
            (
                one_undelimited_parameter_with_prefix_multiple_tokens,
                "\\def\\A abc#1{y#1z}\\A abcdefg",
                "ydzefg"
            ),
            (
                one_delimited_parameter,
                "\\def\\A #1xxx{y#1z}\\A abcxxx",
                "yabcz"
            ),
            (
                one_delimited_parameter_empty,
                "\\def\\A #1xxx{y#1z}\\A xxx",
                "yz"
            ),
            (
                one_delimited_parameter_with_scope,
                "\\def\\A #1xxx{#1}\\A abc{123xxx}xxx",
                "abc{123xxx}"
            ),
            (
                one_delimited_parameter_with_prefix,
                "\\def\\A a#1c{x#1y}\\A abcdef",
                "xbydef"
            ),
            (
                two_delimited_parameters_with_prefix,
                r"\def\A a#1c#2e{x#2y#1z}\A abcdef",
                "xdybzf"
            ),
            (
                one_delimited_parameter_grouped_value,
                r"\def\A #1c{x#1y}\A {Hello}c",
                "xHelloy"
            ),
            (
                parameter_brace_special_case,
                r"\def\A #{Mint says }\A{hello}",
                "Mint says {hello}"
            ),
            (
                grouping,
                r"\def\A{Hello}\A{\def\A{World}\A}\A",
                r"HelloWorldHello"
            ),
            (
                grouping_global,
                r"\def\A{Hello}\A{\global\def\A{World}\A}\A",
                r"HelloWorldWorld"
            ),
            (
                gdef,
                r"\def\A{Hello}\A{\gdef\A{World}\A}\A",
                r"HelloWorldWorld"
            ),
            (
                gdef_global,
                r"\def\A{Hello}\A{\global\gdef\A{World}\A}\A",
                r"HelloWorldWorld"
            ),
            (
                def_takes_global,
                r"\global\def\A{Hello}\assertGlobalIsFalse",
                r""
            ),
            (
                gdef_takes_global,
                r"\global\gdef\A{Hello}\assertGlobalIsFalse",
                r""
            ),
            (
                texbook_exercise_20_1,
                r"\def\mustnt{I must not talk in class.}%
          \def\five{\mustnt\mustnt\mustnt\mustnt\mustnt}%
          \def\twenty{\five\five\five\five}%
          \def\punishment{\twenty\twenty\twenty\twenty\twenty}%
          \punishment",
                "I must not talk in class.".repeat(100)
            ),
            (
                texbook_exercise_20_2,
                r"\def\a{\b}%
          \def\b{A\def\a{B\def\a{C\def\a{\b}}}}%
          \def\puzzle{\a\a\a\a\a}%
          \puzzle",
                "ABCAB"
            ),
            (
                texbook_exercise_20_3_part_1,
                "\\def\\row#1{(#1_1,\\ldots,#1_n)}\\row{\\bf x}",
                "(\\bf x_1,\\ldots,\\bf x_n)"
            ),
            (
                texbook_exercise_20_3_part_2,
                "\\def\\row#1{(#1_1,\\ldots,#1_n)}\\row{{\\bf x}}",
                "({\\bf x}_1,\\ldots,{\\bf x}_n)"
            ),
            (
                texbook_exercise_20_4_part_1,
                r#"\def\mustnt#1#2{I must not #1 in #2.}%
           \def\five#1#2{\mustnt{#1}{#2}\mustnt{#1}{#2}\mustnt{#1}{#2}\mustnt{#1}{#2}\mustnt{#1}{#2}}%
           \def\twenty#1#2{\five{#1}{#2}\five{#1}{#2}\five{#1}{#2}\five{#1}{#2}}%
           \def\punishment#1#2{\twenty{#1}{#2}\twenty{#1}{#2}\twenty{#1}{#2}\twenty{#1}{#2}\twenty{#1}{#2}}%
           \punishment{run}{the halls}"#,
                "I must not run in the halls.".repeat(100)
            ),
            (
                texbook_exercise_20_4_part_2,
                r#"\def\mustnt{I must not \doit\ in \thatplace.}%
           \def\five{\mustnt\mustnt\mustnt\mustnt\mustnt}%
           \def\twenty{\five\five\five\five}%
           \def\punishment#1#2{\def\doit{#1}\def\thatplace{#2}\twenty\twenty\twenty\twenty\twenty}%
           \punishment{run}{the halls}"#,
                r"I must not run\ in the halls.".repeat(100)
            ),
            (
                texbook_exercise_20_5,
                r"\def\a#1{\def\b##1{##1#1}}\a!\b{Hello}",
                "Hello!"
            ),
            (
                texbook_exercise_20_5_temp,
                r"\def\b#1{#1!}\b{Hello}",
                "Hello!"
            ),
            (
                texbook_exercise_20_5_example_below,
                "\\def\\a#1#{\\hbox to #1}\\a3pt{x}",
                "\\hbox to 3pt{x}"
            ),
            (
                texbook_exercise_20_6,
                r"\def\b#1{And #1, World!}\def\a#{\b}\a{Hello}",
                "And Hello, World!"
            ),
            (
                space_in_undelimited_param_1,
                r"\def\Hello#1#2{Hello-#1-#2-World}\Hello A B C",
                r"Hello-A-B-World C",
            ),
            (
                space_in_undelimited_param_2,
                r"\def\Space{ }\def\Hello#1#2{Hello-#1-#2-World}\Hello\Space B C",
                r"Hello- -B-World C",
            ),
        ),
        serde_tests((
            serde_basic,
            r"\def\helloWorld{Hello World} ",
            r"\helloWorld"
        ),),
        failure_tests(
            (end_of_input_scanning_target, "\\def"),
            (end_of_input_scanning_argument_text, "\\def\\A"),
            (end_of_input_scanning_replacement, "\\def\\A{"),
            (end_of_input_scanning_nested_replacement, "\\def\\A{{}"),
            (end_of_input_reading_parameter_number, "\\def\\A#"),
            (end_of_input_scanning_argument, "\\def\\A#1{} \\A"),
            (
                end_of_input_reading_value_for_parameter,
                "\\def\\A#1{} \\A{this {is parameter 1 but it never ends}"
            ),
            (end_of_input_reading_prefix, "\\def\\A abc{} \\A ab"),
            (
                end_of_input_reading_delimiter,
                "\\def\\A #1abc{} \\A {first parameter}ab"
            ),
            (unexpected_token_target, "\\def a"),
            (unexpected_token_argument, "\\def\\A }"),
            (unexpected_token_parameter_number, "\\def\\A #a}"),
            (unexpected_parameter_number_in_argument, "\\def\\A #2{}"),
            (unexpected_parameter_token_in_replacement, "\\def\\A #1{#a}"),
            (unexpected_parameter_number_in_replacement, "\\def\\A {#2}"),
            (
                unexpected_parameter_number_in_replacement_2,
                "\\def\\A #1{#2}"
            ),
            (unexpected_token_in_prefix, "\\def\\A abc{d} \\A abd"),
            // (recursive, r"\def\recursive{\recursive} \recursive"),
        ),
    ];
}