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
// Copyright 2024 New Vector Ltd.
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

use std::fmt::Formatter;

use pad::{Alignment, PadStr};
use serde::Serialize;
use serde_json::{ser::PrettyFormatter, Value};
use thiserror::Error;

use super::{ArgumentList, Message};
use crate::sprintf::message::{
    ArgumentReference, PaddingSpecifier, Part, Placeholder, TypeSpecifier,
};

macro_rules! format_placeholder {
    ($value:expr, $type:literal, $placeholder:expr) => {
        format_step_plus_sign!($value, $type, $placeholder, "",)
    };
    ($value:expr, $placeholder:expr) => {
        format_placeholder!($value, "", $placeholder)
    };
}

macro_rules! format_step_plus_sign {
    ($value:expr, $type:literal, $placeholder:expr, $modifiers:expr, $($argk:ident = $argv:expr),* $(,)?) => {{
        if $placeholder.plus_sign {
            format_step_zero!(
                $value,
                $type,
                $placeholder,
                concat!($modifiers, "+"),
                $($argk = $argv),*
            )
        } else {
            format_step_zero!(
                $value,
                $type,
                $placeholder,
                $modifiers,
                $($argk = $argv),*
            )
        }
    }};
}

macro_rules! format_step_zero {
    ($value:expr, $type:literal, $placeholder:expr, $modifiers:expr, $($argk:ident = $argv:expr),* $(,)?) => {{
        if $placeholder.padding_specifier_is_zero() {
            format_step_width!(
                $value,
                $type,
                $placeholder,
                concat!($modifiers, "0"),
                $($argk = $argv),*
            )
        } else {
            format_step_width!(
                $value,
                $type,
                $placeholder,
                $modifiers,
                $($argk = $argv),*
            )
        }
    }};
}

macro_rules! format_step_width {
    ($value:expr, $type:literal, $placeholder:expr, $modifiers:expr, $($argk:ident = $argv:expr),* $(,)?) => {{
        if let Some(width) = $placeholder.numeric_width() {
            format_step_precision!(
                $value,
                $type,
                $placeholder,
                concat!($modifiers, "width$"),
                width = width,
                $($argk = $argv),*
            )
        } else {
            format_step_precision!(
                $value,
                $type,
                $placeholder,
                $modifiers,
                $($argk = $argv),*
            )
        }
    }};
}

macro_rules! format_step_precision {
    ($value:expr, $type:literal, $placeholder:expr, $modifiers:expr, $($argk:ident = $argv:expr),* $(,)?) => {{
        if let Some(precision) = $placeholder.precision {
            format_end!(
                $value,
                $type,
                $placeholder,
                concat!($modifiers, ".precision$"),
                precision = precision,
                $($argk = $argv),*
            )
        } else {
            format_end!(
                $value,
                $type,
                $placeholder,
                $modifiers,
                $($argk = $argv),*
            )
        }
    }};
}

macro_rules! format_end {
    ($value:expr, $type:literal, $placeholder:expr, $modifiers:expr, $($argk:ident = $argv:expr),* $(,)?) => {
        format!(concat!("{value:", $modifiers, $type, "}"), value = $value, $($argk = $argv),*)
    };
}

#[derive(Debug)]
pub enum ValueType {
    String,
    Number,
    Float,
    Null,
    Bool,
    Array,
    Object,
}

impl ValueType {
    fn of_value(value: &Value) -> Self {
        match value {
            Value::String(_) => Self::String,
            Value::Number(_) => Self::Number,
            Value::Null => Self::Null,
            Value::Bool(_) => Self::Bool,
            Value::Array(_) => Self::Array,
            Value::Object(_) => Self::Object,
        }
    }
}

#[derive(Debug, Error)]
pub enum FormatError {
    #[error("Can't format a {value_type:?} as a %{type_specifier}")]
    InvalidTypeSpecifier {
        type_specifier: TypeSpecifier,
        value_type: ValueType,
    },

    #[error("Unsupported type specifier %{type_specifier}")]
    UnsupportedTypeSpecifier { type_specifier: TypeSpecifier },

    #[error("Unexpected number type")]
    NumberIsNotANumber,

    #[error("Unknown named argument {name}")]
    UnknownNamedArgument { name: String },

    #[error("Unknown indexed argument {index}")]
    UnknownIndexedArgument { index: usize },

    #[error("Not enough arguments")]
    NotEnoughArguments,

    #[error("Can't serialize value")]
    Serialize(#[from] serde_json::Error),

    #[error("Can't convert value to UTF-8")]
    InvalidUtf8(#[from] std::string::FromUtf8Error),
}

fn find_value<'a>(
    arguments: &'a ArgumentList,
    requested_argument: Option<&ArgumentReference>,
    current_index: usize,
) -> Result<&'a Value, FormatError> {
    match requested_argument {
        Some(ArgumentReference::Named(name)) => arguments
            .get_by_name(name)
            .ok_or(FormatError::UnknownNamedArgument { name: name.clone() }),

        Some(ArgumentReference::Indexed(index)) => arguments
            .get_by_index(*index - 1)
            .ok_or(FormatError::UnknownIndexedArgument { index: *index }),

        None => arguments
            .get_by_index(current_index)
            .ok_or(FormatError::NotEnoughArguments),
    }
}

/// An approximation of JS's Number.prototype.toPrecision
fn to_precision(number: f64, mut placeholder: Placeholder) -> String {
    // If the precision is not set, then we just format the number as normal
    let Some(precision) = placeholder.precision else {
        return format_placeholder!(number, &placeholder);
    };

    // This treats NaN, Infinity, -Infinity and zero without any special handling
    if !number.is_normal() {
        return format_placeholder!(number, &placeholder);
    }

    // This tells us how many numbers are before the decimal point
    // This lossy cast is fine because we only care about the order of magnitude,
    // and special cases are handled above
    #[allow(clippy::cast_possible_truncation)]
    let log10 = number.abs().log10().floor() as i64;
    let precision_i64 = precision.try_into().unwrap_or(i64::MAX);
    // We can fit the number in the precision, so we just format it as normal
    if log10 > 0 && log10 <= precision_i64 || number.abs() < 10.0 {
        // We remove the number of digits before the decimal point from the precision
        placeholder.precision = Some(precision - 1 - log10.try_into().unwrap_or(0usize));
        format_placeholder!(number, &placeholder)
    } else {
        // Else in scientific notation there is always one digit before the decimal
        // point
        placeholder.precision = Some(precision - 1);
        format_placeholder!(number, "e", &placeholder)
    }
}

#[allow(clippy::too_many_lines, clippy::match_same_arms)]
fn format_value(value: &Value, placeholder: &Placeholder) -> Result<String, FormatError> {
    match (value, &placeholder.type_specifier) {
        (Value::Number(number), ts @ TypeSpecifier::BinaryNumber) => {
            if let Some(number) = number.as_u64() {
                Ok(format_placeholder!(number, "b", placeholder))
            } else if let Some(number) = number.as_i64() {
                Ok(format_placeholder!(number, "b", placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: *ts,
                    value_type: ValueType::Float,
                })
            }
        }
        (v, ts @ TypeSpecifier::BinaryNumber) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (Value::String(string), TypeSpecifier::CharacterAsciiValue) if string.len() == 1 => {
            Ok(format_placeholder!(string, placeholder))
        }
        (Value::Number(n), TypeSpecifier::CharacterAsciiValue) => {
            if let Some(character) = n
                .as_u64()
                .and_then(|n| u32::try_from(n).ok())
                .and_then(|n| char::try_from(n).ok())
            {
                Ok(format_placeholder!(character, placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: TypeSpecifier::CharacterAsciiValue,
                    value_type: ValueType::Number,
                })
            }
        }
        (v, ts @ TypeSpecifier::CharacterAsciiValue) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (
            Value::Number(number),
            ts @ (TypeSpecifier::DecimalNumber | TypeSpecifier::IntegerNumber),
        ) => {
            if let Some(number) = number.as_u64() {
                Ok(format_placeholder!(number, placeholder))
            } else if let Some(number) = number.as_i64() {
                Ok(format_placeholder!(number, placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: *ts,
                    value_type: ValueType::Float,
                })
            }
        }
        (v, ts @ (TypeSpecifier::DecimalNumber | TypeSpecifier::IntegerNumber)) => {
            Err(FormatError::InvalidTypeSpecifier {
                type_specifier: *ts,
                value_type: ValueType::of_value(v),
            })
        }

        (Value::Number(number), ts @ TypeSpecifier::UnsignedDecimalNumber) => {
            if let Some(number) = number.as_u64() {
                Ok(format_placeholder!(number, placeholder))
            } else if let Some(number) = number.as_i64() {
                // Truncate to a i32 and then u32 to mimic JS's behaviour
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let number = number as i32 as u32;
                Ok(format_placeholder!(number, placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: *ts,
                    value_type: ValueType::Float,
                })
            }
        }
        (v, ts @ TypeSpecifier::UnsignedDecimalNumber) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (Value::Number(number), TypeSpecifier::ScientificNotation) => {
            if let Some(number) = number.as_u64() {
                Ok(format_placeholder!(number, "e", placeholder))
            } else if let Some(number) = number.as_i64() {
                Ok(format_placeholder!(number, "e", placeholder))
            } else if let Some(number) = number.as_f64() {
                Ok(format_placeholder!(number, "e", placeholder))
            } else {
                // This should never happen
                Err(FormatError::NumberIsNotANumber)
            }
        }
        (v, ts @ TypeSpecifier::ScientificNotation) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (Value::Number(number), TypeSpecifier::FloatingPointNumber) => {
            if let Some(number) = number.as_u64() {
                Ok(format_placeholder!(number, placeholder))
            } else if let Some(number) = number.as_i64() {
                Ok(format_placeholder!(number, placeholder))
            } else if let Some(number) = number.as_f64() {
                Ok(format_placeholder!(number, placeholder))
            } else {
                // This should never happen
                Err(FormatError::NumberIsNotANumber)
            }
        }
        (v, ts @ TypeSpecifier::FloatingPointNumber) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (Value::Number(number), TypeSpecifier::FloatingPointNumberWithSignificantDigits) => {
            if let Some(number) = number.as_f64() {
                Ok(to_precision(number, placeholder.clone()))
            } else {
                // This might happen if the integer is too big to be represented as a f64
                Err(FormatError::NumberIsNotANumber)
            }
        }
        (v, ts @ TypeSpecifier::FloatingPointNumberWithSignificantDigits) => {
            Err(FormatError::InvalidTypeSpecifier {
                type_specifier: *ts,
                value_type: ValueType::of_value(v),
            })
        }

        (Value::Number(number), ts @ TypeSpecifier::OctalNumber) => {
            if let Some(number) = number.as_u64() {
                Ok(format_placeholder!(number, "o", placeholder))
            } else if let Some(number) = number.as_i64() {
                // Truncate to a i32 and then u32 to mimic JS's behaviour
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let number = number as i32 as u32;
                Ok(format_placeholder!(number, "o", placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: *ts,
                    value_type: ValueType::Float,
                })
            }
        }
        (v, ts @ TypeSpecifier::OctalNumber) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (Value::String(string), TypeSpecifier::String) => {
            Ok(format_placeholder!(string, placeholder))
        }
        (Value::Number(number), TypeSpecifier::String) => {
            let string = format!("{number}");
            Ok(format_placeholder!(string, placeholder))
        }
        (v, ts @ TypeSpecifier::String) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (Value::Bool(boolean), TypeSpecifier::TrueOrFalse) => {
            Ok(format_placeholder!(boolean, placeholder))
        }
        (v, ts @ TypeSpecifier::TrueOrFalse) => Err(FormatError::InvalidTypeSpecifier {
            type_specifier: *ts,
            value_type: ValueType::of_value(v),
        }),

        (v, TypeSpecifier::TypeOfArgument) => match v {
            Value::String(_) => Ok("string".to_owned()),
            Value::Number(_) => Ok("number".to_owned()),
            Value::Null => Ok("null".to_owned()),
            Value::Bool(_) => Ok("boolean".to_owned()),
            Value::Array(_) => Ok("array".to_owned()),
            Value::Object(_) => Ok("object".to_owned()),
        },

        // Unimplemented
        (_v, TypeSpecifier::PrimitiveValue) => Err(FormatError::UnsupportedTypeSpecifier {
            type_specifier: placeholder.type_specifier,
        }),

        (Value::Number(n), ts @ TypeSpecifier::HexadecimalNumberLowercase) => {
            if let Some(number) = n.as_u64() {
                Ok(format_placeholder!(number, "x", placeholder))
            } else if let Some(number) = n.as_i64() {
                // Truncate to a i32 and then u32 to mimic JS's behaviour
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let number = number as i32 as u32;
                Ok(format_placeholder!(number, "x", placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: *ts,
                    value_type: ValueType::Float,
                })
            }
        }
        (v, ts @ TypeSpecifier::HexadecimalNumberLowercase) => {
            Err(FormatError::InvalidTypeSpecifier {
                type_specifier: *ts,
                value_type: ValueType::of_value(v),
            })
        }

        (Value::Number(n), ts @ TypeSpecifier::HexadecimalNumberUppercase) => {
            if let Some(number) = n.as_u64() {
                Ok(format_placeholder!(number, "X", placeholder))
            } else if let Some(number) = n.as_i64() {
                // Truncate to a i32 and then u32 to mimic JS's behaviour
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let number = number as i32 as u32;
                Ok(format_placeholder!(number, "X", placeholder))
            } else {
                Err(FormatError::InvalidTypeSpecifier {
                    type_specifier: *ts,
                    value_type: ValueType::Float,
                })
            }
        }
        (v, ts @ TypeSpecifier::HexadecimalNumberUppercase) => {
            Err(FormatError::InvalidTypeSpecifier {
                type_specifier: *ts,
                value_type: ValueType::of_value(v),
            })
        }

        (value, TypeSpecifier::Json) => {
            let mut json = Vec::new();
            if let Some(width) = placeholder.width {
                let indent = b" ".repeat(width);
                let mut serializer = serde_json::Serializer::with_formatter(
                    &mut json,
                    PrettyFormatter::with_indent(indent.as_slice()),
                );
                value.serialize(&mut serializer)?;
            } else {
                let mut serializer = serde_json::Serializer::new(&mut json);
                value.serialize(&mut serializer)?;
            };
            let json = String::from_utf8(json)?;
            Ok(format_placeholder!(json, placeholder))
        }
    }
}

pub enum FormattedMessagePart<'a> {
    /// A literal text part of the message. It should not be escaped.
    Text(&'a str),
    /// A placeholder part of the message. It should be escaped.
    Placeholder(String),
}

impl<'a> FormattedMessagePart<'a> {
    fn len(&self) -> usize {
        match self {
            FormattedMessagePart::Text(text) => text.len(),
            FormattedMessagePart::Placeholder(placeholder) => placeholder.len(),
        }
    }
}

impl std::fmt::Display for FormattedMessagePart<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            FormattedMessagePart::Text(text) => write!(f, "{text}"),
            FormattedMessagePart::Placeholder(placeholder) => write!(f, "{placeholder}"),
        }
    }
}

pub struct FormattedMessage<'a> {
    parts: Vec<FormattedMessagePart<'a>>,
    total_len: usize,
}

impl FormattedMessage<'_> {
    /// Returns the length of the formatted message (not the number of parts).
    #[must_use]
    pub fn len(&self) -> usize {
        self.total_len
    }

    /// Returns `true` if the formatted message is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.total_len == 0
    }

    /// Returns the list of parts of the formatted message.
    #[must_use]
    pub fn parts(&self) -> &[FormattedMessagePart<'_>] {
        &self.parts
    }
}

impl std::fmt::Display for FormattedMessage<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for part in &self.parts {
            write!(f, "{part}")?;
        }
        Ok(())
    }
}

impl Message {
    /// Format the message with the given arguments.
    ///
    /// # Errors
    ///
    /// Returns an error if the message can't be formatted with the given
    /// arguments.
    pub fn format(&self, arguments: &ArgumentList) -> Result<String, FormatError> {
        self.format_(arguments).map(|fm| fm.to_string())
    }

    #[doc(hidden)]
    pub fn format_(&self, arguments: &ArgumentList) -> Result<FormattedMessage<'_>, FormatError> {
        let mut parts = Vec::with_capacity(self.parts().len());

        // Holds the current index of the placeholder we are formatting, which is used
        // by non-named, non-indexed placeholders
        let mut current_placeholder = 0usize;
        // Compute the total length of the formatted message
        let mut total_len = 0usize;
        for part in self.parts() {
            let formatted = match part {
                Part::Percent => FormattedMessagePart::Text("%"),
                Part::Text(text) => FormattedMessagePart::Text(text),
                Part::Placeholder(placeholder) => {
                    let value = find_value(
                        arguments,
                        placeholder.requested_argument.as_ref(),
                        current_placeholder,
                    )?;

                    let formatted = format_value(value, placeholder)?;

                    // Do the extra padding which std::fmt can't really do
                    let formatted = if let Some(width) = placeholder.width {
                        let spacer = placeholder
                            .padding_specifier
                            .map_or(' ', PaddingSpecifier::char);

                        let alignment = if placeholder.left_align {
                            Alignment::Left
                        } else {
                            Alignment::Right
                        };

                        formatted.pad(width, spacer, alignment, false)
                    } else {
                        formatted
                    };

                    current_placeholder += 1;
                    FormattedMessagePart::Placeholder(formatted)
                }
            };
            total_len += formatted.len();
            parts.push(formatted);
        }

        Ok(FormattedMessage { parts, total_len })
    }
}