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
//! Implementation of TeX user defined macros.

use crate::command;
use crate::error;
use crate::parse;
use crate::token;
use crate::token::Token;
use crate::traits::*;
use crate::vm;
use colored::*;
use texcraft_stdext::algorithms::substringsearch::Matcher;

/// A TeX Macro.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Macro {
    prefix: Vec<Token>,
    parameters: Vec<Parameter>,
    replacements: Vec<Replacement>,
}

impl Macro {
    pub fn replacements(&self) -> &[Replacement] {
        &self.replacements
    }
}

/// A token list or parameter in a replacement text.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Replacement {
    /// A list of tokens.
    Tokens(Vec<Token>),

    /// A parameter.
    ///
    /// In order to be valid, the parameters index must be less than the number
    /// of parameters in the macro.
    Parameter(usize),
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Parameter {
    Undelimited,
    Delimited(Matcher<Token>),
}

// Input type for macro hooks
pub struct HookInput<'a, S> {
    pub vm: &'a vm::VM<S>,
    pub token: Token,
    pub tex_macro: &'a Macro,
    pub arguments: &'a [&'a [Token]],
    pub reverse_expansion: &'a [Token],
}

pub fn no_op_hook<S>(_: HookInput<S>) {}

impl Macro {
    pub fn call<S: TexlangState>(
        &self,
        token: Token,
        input: &mut vm::ExpansionInput<S>,
    ) -> Result<(), Box<command::Error>> {
        remove_tokens_from_stream(&self.prefix, input.unexpanded())?;
        let mut argument_indices: Vec<(usize, usize)> = Default::default();
        let mut argument_tokens = input.checkout_token_buffer();
        for (i, parameter) in self.parameters.iter().enumerate() {
            let start_index = argument_tokens.len();
            let trim_outer_braces =
                parameter.parse_argument(&token, input, i, &mut argument_tokens)?;
            let element = match trim_outer_braces {
                true => (start_index + 1, argument_tokens.len() - 1),
                false => (start_index, argument_tokens.len()),
            };
            argument_indices.push(element);
        }

        let mut arguments: Vec<&[Token]> = Default::default();
        for (i, j) in &argument_indices {
            let slice = argument_tokens.get(*i..*j).unwrap();
            arguments.push(slice);
        }

        let result = input.expansions_mut();
        let num_tokens = Macro::perform_replacement(&self.replacements, &arguments, result);

        // To keep the borrow checker happy we need to downgrade result to a shared reference.
        let result = input.expansions();
        S::post_macro_expansion_hook(
            token,
            input,
            self,
            &arguments,
            &result[result.len() - num_tokens..result.len()],
        );

        input.return_token_buffer(argument_tokens);
        Ok(())
    }

    pub fn doc(&self, interner: &token::CsNameInterner) -> String {
        let mut d = String::default();
        d.push_str("User defined macro\n\n");
        d.push_str(&format![
            "{}\n{}",
            "Parameters definition".italic(),
            pretty_print_prefix_and_parameters(&self.prefix, &self.parameters, interner),
        ]);
        d.push_str(&format![
            "\n\n{} `{}`\n",
            "Replacement definition:".italic(),
            pretty_print_replacement_text(&self.replacements),
        ]);
        d
    }

    /// Create a new macro.
    pub fn new(
        prefix: Vec<Token>,
        parameters: Vec<Parameter>,
        replacement_text: Vec<Replacement>,
    ) -> Macro {
        Macro {
            prefix,
            parameters,
            replacements: replacement_text,
        }
    }

    fn perform_replacement(
        replacements: &[Replacement],
        arguments: &[&[Token]],
        result: &mut Vec<Token>,
    ) -> usize {
        let mut output_size = 0;
        for replacement in replacements.iter() {
            output_size += match replacement {
                Replacement::Tokens(tokens) => tokens.len(),
                Replacement::Parameter(i) => arguments.get(*i).unwrap().len(),
            };
        }
        result.reserve(output_size);
        for replacement in replacements.iter().rev() {
            match replacement {
                Replacement::Tokens(tokens) => {
                    result.extend(tokens);
                }
                Replacement::Parameter(i) => {
                    result.extend(arguments.get(*i).unwrap().iter().rev().copied());
                }
            }
        }
        output_size
    }
}

impl Parameter {
    pub fn parse_argument<S: TexlangState>(
        &self,
        macro_token: &Token,
        input: &mut vm::ExpansionInput<S>,
        index: usize,
        result: &mut Vec<Token>,
    ) -> Result<bool, Box<command::Error>> {
        match self {
            Parameter::Undelimited => {
                Parameter::parse_undelimited_argument(macro_token, input, index + 1, result)?;
                Ok(false)
            }
            Parameter::Delimited(matcher_factory) => Parameter::parse_delimited_argument(
                macro_token,
                input.unexpanded(),
                matcher_factory,
                index + 1,
                result,
            ),
        }
    }

    fn parse_delimited_argument<T: vm::TokenStream>(
        macro_token: &Token,
        stream: &mut T,
        matcher_factory: &Matcher<Token>,
        param_num: usize,
        result: &mut Vec<Token>,
    ) -> Result<bool, Box<command::Error>> {
        let mut matcher = matcher_factory.start();
        let mut scope_depth = 0;

        // This handles the case of a macro whose argument ends with the special #{ tokens. In this special case the parsing
        // will end with a scope depth of 1, because the last token parsed will be the { and all braces before that will
        // be balanced.
        let closing_scope_depth = match matcher_factory.substring().last().value() {
            token::Value::BeginGroup(_) => 1,
            _ => 0,
        };
        let start_index = result.len();
        while let Some(token) = stream.next()? {
            match token.value() {
                token::Value::BeginGroup(_) => {
                    scope_depth += 1;
                }
                token::Value::EndGroup(_) => {
                    scope_depth -= 1;
                }
                _ => (),
            };
            let matches_delimiter = matcher.next(&token);
            result.push(token);
            if scope_depth == closing_scope_depth && matches_delimiter {
                // Remove the suffix.
                for _ in 0..matcher_factory.substring().len() {
                    result.pop();
                }
                return Ok(Parameter::should_trim_outer_braces_if_present(
                    &result[start_index..],
                ));
            }
        }
        return Err(error::SimpleEndOfInputError::new(stream.vm(),format![
            "unexpected end of input while reading argument #{param_num} for the macro {macro_token}"
        ]).into());
        /*
        TODO
        .add_note(format![
            "this argument is delimited and must be suffixed by the tokens `{}`",
            matcher_factory.substring()
        ]);
        if let Some(first_token) = result.first() {
            e = e.add_token_context(first_token, "the argument started here:");
            e = e.add_note(format![
                "{} tokens were read for the argument so far",
                result.len()
            ]);
        } else {
            e = e.add_note("no tokens were read for the argument so far");
        }
        Err(e
            .add_token_context(macro_token, "the macro invocation started here:")
            .cast())
         */
    }

    fn should_trim_outer_braces_if_present(list: &[Token]) -> bool {
        if list.len() <= 1 {
            return false;
        }
        match list[0].value() {
            token::Value::BeginGroup(_) => (),
            _ => {
                return false;
            }
        }
        match list[list.len() - 1].value() {
            token::Value::EndGroup(_) => (),
            _ => {
                return false;
            }
        }
        true
    }

    fn parse_undelimited_argument<S: TexlangState>(
        macro_token: &Token,
        input: &mut vm::ExpansionInput<S>,
        param_num: usize,
        result: &mut Vec<Token>,
    ) -> Result<(), Box<command::Error>> {
        parse::SpacesUnexpanded::parse(input)?;
        let input = input.unexpanded();
        let _opening_brace = match input.next()? {
            None => {
                return Err(error::SimpleEndOfInputError::new(input.vm(), format![
                    "unexpected end of input while reading argument #{param_num} for the macro {macro_token}"
                ]).into())
            }
            Some(token) => match token.value() {
                token::Value::BeginGroup(_) => token,
                _ => {
                    result.push(token);
                    return Ok(());
                }
            },
        };
        match parse::finish_parsing_balanced_tokens(input, result)? {
            true => Ok(()),
            false => Err(error::SimpleEndOfInputError::new(input.vm(), format![
                "unexpected end of input while reading argument #{param_num} for the macro {macro_token}"
            ]).into()),
            /* TODO
            .add_note(format![
            "this argument started with a `{opening_brace}` and must be finished with a matching closing brace"
        ])
            .add_token_context(&opening_brace, "the argument started here:")
            .add_token_context(macro_token, "the macro invocation started here:")
            .cast()),
             */
        }
    }
}

fn colored_parameter_number(n: usize) -> String {
    let color = match n {
        1 => |s: String| s.bright_yellow(),
        _ => |s: String| s.bright_blue(),
    };
    format![
        "{}{}",
        color("#".to_string()).bold(),
        color(n.to_string()).bold()
    ]
}

pub fn pretty_print_prefix_and_parameters(
    prefix: &[Token],
    parameters: &[Parameter],
    interner: &token::CsNameInterner,
) -> String {
    let mut d = String::default();
    if prefix.is_empty() {
        d.push_str(" . No prefix\n");
    } else {
        d.push_str(&format![
            " . Prefix: `{}`\n",
            token::write_tokens(prefix, interner)
        ]);
    }

    d.push_str(&format![" . Parameters ({}):\n", parameters.len()]);
    let mut parameter_number = 1;
    for parameter in parameters {
        match parameter {
            Parameter::Undelimited => {
                d.push_str(&format![
                    "    {}: undelimited\n",
                    colored_parameter_number(parameter_number),
                ]);
            }
            Parameter::Delimited(factory) => {
                d.push_str(&format![
                    "    {}: delimited by `{}`\n",
                    colored_parameter_number(parameter_number),
                    token::write_tokens(factory.substring(), interner)
                ]);
            }
        }
        parameter_number += 1;
    }

    d.push_str(" . Full argument specification: `");
    d.push_str(&token::write_tokens(prefix, interner));
    let mut parameter_number = 1;
    for parameter in parameters {
        d.push_str(&colored_parameter_number(parameter_number));
        if let Parameter::Delimited(factory) = parameter {
            d.push_str(token::write_tokens(factory.substring(), interner).as_str());
        }
        parameter_number += 1;
    }
    d.push('`');
    d
}

pub fn pretty_print_replacement_text(replacements: &[Replacement]) -> String {
    let mut b = String::default();
    for replacement in replacements.iter() {
        match replacement {
            Replacement::Parameter(i) => {
                b.push_str(colored_parameter_number(*i + 1).as_str());
            }
            Replacement::Tokens(_) => {
                b.push_str("TODO");
            }
        }
    }
    b
}

/// Removes the provided vector of tokens from the front of the stream.
///
/// Returns an error if the stream does not start with the tokens.
pub fn remove_tokens_from_stream<T: vm::TokenStream>(
    tokens: &[Token],
    stream: &mut T,
) -> Result<(), Box<command::Error>> {
    for prefix_token in tokens.iter() {
        let stream_token =
            match stream.next()? {
                None => return Err(error::SimpleEndOfInputError::new(
                    stream.vm(),
                    "unexpected end of input while matching the prefix for a user-defined macro",
                    // TODO: add everything we've matched so far, and what we were expecting
                )
                .into()),
                Some(token) => token,
            };
        if &stream_token != prefix_token {
            /*
            let note = match &prefix_token.value {
                ControlSequence(_) => {
                    format!["expected a control sequence token \\{}", "name"]
                }
                _ => format![ //Character(c, catcode) => format![
                    "expected a character token with value 'todo' and catcode todo",
                    //c, catcode
                ],
            };
             */
            return Err(error::SimpleTokenError::new(
                stream.vm(),
                stream_token,
                "unexpected token while matching the prefix for a user-defined macro",
            )
            .into());
        }
    }
    Ok(())
}