resb/text/
reader.rs

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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

mod parse_state;

use std::{borrow::Cow, fmt};

use nom::{
    branch::alt,
    bytes::complete::{tag, take, take_until, take_while1},
    character::complete::{hex_digit1, i32, multispace1, not_line_ending, u32},
    combinator::{eof, map, map_parser, map_res, opt, peek, value},
    error::{context, convert_error, make_error, ContextError, ParseError, VerboseError},
    multi::{many0, separated_list0},
    sequence::{delimited, pair, preceded, terminated},
    Finish, IResult, Parser,
};

use crate::bundle::{Int28, Key, Resource, ResourceBundle, Table};

use self::parse_state::ParseState;

/// Generates appropriate parsers for type ID strings.
///
/// A type may have one or more aliases. Note that if one type alias appears at
/// the beginning of another, the longer alias must appear first.
macro_rules! type_id {
    ($(#[$meta:meta])* $name:ident, $tag:literal) => {
        $(#[$meta])*
        fn $name<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
        where
            E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>
        {
            context(stringify!($name), preceded(tag(":"),
                tag($tag)
            ))(input)
        }
    };

    ($(#[$meta:meta])* $name:ident, $( $tag:literal ),+) => {
        $(#[$meta])*
        fn $name<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
        where
            E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>
        {
            context(stringify!($name), preceded(tag(":"), alt((
                $( tag($tag) ),+
            ))))(input)
        }
    };
}

type_id!(
    /// Reads a root table resource type ID. Note that `"(nofallback)"` may only
    /// appear on the root resource.
    root_table_type,
    "table(nofallback)",
    "table"
);
type_id!(
    /// Reads a string resource type ID.
    string_type,
    "string"
);
type_id!(
    /// Reads an array resource type ID.
    array_type,
    "array"
);
type_id!(
    /// Reads a table resource type ID.
    table_type,
    "table"
);
type_id!(
    /// Reads a binary resource type ID.
    binary_type,
    "binary",
    "bin"
);
type_id!(
    /// Reads an integer resource type ID.
    integer_type,
    "integer",
    "int"
);
type_id!(
    /// Reads an integer vector resource type ID.
    int_vector_type,
    "intvector"
);
type_id!(
    /// Reads an import resource type ID.
    import_type,
    "import"
);
type_id!(
    /// Reads an include resource type ID.
    include_type,
    "include"
);
type_id!(
    /// Reads a resource alias type ID.
    alias_type,
    "alias"
);

/// Reads any type ID which may appear as a leaf in the resource tree.
fn type_id_no_root<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "type_id",
        alt((
            string_type,
            array_type,
            table_type,
            binary_type,
            integer_type,
            int_vector_type,
            import_type,
            include_type,
            alias_type,
        )),
    )(input)
}

/// Reads one or more of the core set of ASCII characters used in keys.
///
/// It is presently unclear which characters appear in keys in practice, so in
/// the interest of a simplified parse, only characters which have been
/// encountered in real files are supported.
fn invariant_chars<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "invariant_chars",
        take_while1(|c: char| c.is_alphanumeric() || c == '-'),
    )(input)
}

/// Reads a single-line comment up to but not including the final newline.
fn eol_comment<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context("eol_comment", preceded(tag("//"), not_line_ending))(input)
}

/// Reads a multi-line comment.
///
/// Does not support nested comments.
fn delimited_comment<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "delimited_comment",
        delimited(tag("/*"), take_until("*/"), tag("*/")),
    )(input)
}

/// Reads one single-line or multi-line comment.
fn comment<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context("comment", alt((eol_comment, delimited_comment)))(input)
}

/// Reads a string.
///
/// Strings may be quote-delimited or not. While the partial specification
/// indicates that adjacent strings are combined, this is not supported in the
/// current version of the parser. No support for character escapes is
/// indicated.
///
/// The specification is unclear on how string encoding is to be handled, so
/// this parser assumes that strings are to be well-formed in the same encoding
/// as the rest of the file and representable in Unicode.
///
/// The specification also allows for the use of `\u` and `\U` literals. Support
/// for these has also been omitted for the time being.
///
/// See [`Reader`] for more details on the specification.
fn string<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, &'a str, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "string",
        map(
            token(alt((
                delimited(tag("\""), take_until("\""), tag("\"")),
                invariant_chars,
            ))),
            |value| value.input(),
        ),
    )(input)
}

/// Reads a signed or unsigned 32-bit integer.
fn integer<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, u32, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context("integer", token(alt((u32, map(i32, |value| value as u32)))))(input)
}

/// Reads and discards any number of comments and any amount of whitespace.
fn discardable<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, (), E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context("discardable", value((), many0(alt((comment, multispace1)))))(input)
}

/// Reads a single token as specified by the provided parser, surrounded by any
/// number of comments and any amount of whitespace.
fn token<'a, F, O, E>(mut parser: F) -> impl FnMut(ParseState<'a>) -> IResult<ParseState<'a>, O, E>
where
    F: Parser<ParseState<'a>, O, E>,
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context("token", move |input: ParseState<'a>| {
        let (rest, _) = discardable.parse(input)?;
        let (rest, token) = parser.parse(rest)?;
        let (rest, _) = discardable.parse(rest)?;

        Ok((rest, token))
    })
}

/// Generates appropriate matchers for simple string tokens.
macro_rules! simple_token {
    ($name:ident, $str:expr) => {
        fn $name<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ParseState<'a>, E>
        where
            E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
        {
            context(stringify!($name), token(tag($str)))(input)
        }
    };
}

simple_token!(left_brace, "{");
simple_token!(right_brace, "}");
simple_token!(comma, ",");

/// Reads a table key.
fn key<'a, E>(state: ParseState<'a>) -> IResult<ParseState<'a>, Key<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    let input = state.clone();
    context(
        "key",
        map(
            terminated(
                string,
                // If the string is not followed by a resource, as indicated by
                // the presence of a type ID or resource delimiter, it is not a
                // key and we shouldn't record it.
                peek(alt((type_id_no_root, left_brace))),
            ),
            |key| {
                let key = Key::from(key);
                state.encounter_key(key.clone());

                key
            },
        ),
    )(input)
}

/// Reads a single table entry, consisting of a key and an associated resource.
fn table_entry<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, (Key<'a>, Resource<'a>), E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context("table_entry", pair(key, resource))(input)
}

/// Generates a parser for a resource body, consisting of a resource
/// type-specific body layout delimited by curly braces.
macro_rules! resource_body {
    ($body_parser:expr) => {
        delimited(left_brace, $body_parser, right_brace)
    };
}

/// Generates a parser for a resource with a mandatory type ID.
macro_rules! resource {
    ($type:ident, $body_parser:expr) => {
        preceded($type, resource_body!($body_parser))
    };
}

/// Generates a parser for a resource with an optional type ID.
macro_rules! resource_opt_tag {
    ($type:ident, $body_parser:expr) => {
        preceded(opt($type), resource_body!($body_parser))
    };
}

/// Reads the body of a table resource, consisting of any number of key-resource
/// pair entries.
fn table_body<'a, E>(state: ParseState<'a>) -> IResult<ParseState<'a>, Table<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    let (state, entries) = context("table_body", many0(table_entry)).parse(state)?;

    // Build the table struct itself.
    let mut table = Table::new();
    for (k, v) in entries {
        table.insert(k, v);
    }

    Ok((state, table))
}

/// Reads a table resource, consisting of key-resource pairs.
///
/// Though it is not required in the resource bundle text, the final in-memory
/// representation sorts these pairs lexically by key.
fn table_resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "table_resource",
        map(resource_opt_tag!(table_type, table_body), Resource::Table),
    )(input)
}

/// Reads the root table resource, noting whether locale fallback is disabled.
fn root_table_resource<'a, E>(
    input: ParseState<'a>,
) -> IResult<ParseState<'a>, (bool, Resource<'a>), E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    // Determine whether locale fallback is enabled by the type ID of the table,
    // if present. The type ID is optional for tables, so it's okay if we don't
    // find one, at which point we default to enabling locale fallback.
    let (input, is_fallback_enabled) = opt(root_table_type).parse(input)?;
    let is_fallback_enabled =
        is_fallback_enabled.map_or(true, |type_id| type_id.input() != "table(nofallback)");

    // Read the body of the root resource itself.
    let (input, resource) = map(resource_body!(table_body), Resource::Table).parse(input)?;

    Ok((input, (is_fallback_enabled, resource)))
}

/// Reads an array resource consisting of any number of hetereogeneously-typed
/// resources, optionally separated by commas.
fn array_resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    // Note that `nom`'s `separated_list0` parser requires that the separator
    // always consume, so we can't use it for optional commas. However, the
    // partial specification allows for trailing commas, so `terminated` works
    // fine here.
    context(
        "array_resource",
        map(
            resource_opt_tag!(array_type, many0(terminated(resource, opt(comma)))),
            Resource::Array,
        ),
    )(input)
}

/// Reads an integer resource, consisting of a single 28-bit integer.
///
/// These integers have no inherent signedness; consumers specify whether a
/// signed or unsigned integer is desired. Because of this, note that 28-bit
/// integers require special handling in-memory. See [`Int28`] for more details.
fn int_resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "int_resource",
        map(resource!(integer_type, integer), |value| {
            Resource::Integer(Int28::from(value))
        }),
    )(input)
}

/// Reads an integer vector resource, consisting of any number of 32-bit
/// integers separated by commas. A trailing comma is optional.
fn int_vector_resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "int_vector_resource",
        map(
            resource!(
                int_vector_type,
                terminated(separated_list0(comma, integer), opt(comma))
            ),
            Resource::IntVector,
        ),
    )(input)
}

/// Reads a single byte represented as a pair of hex digits, each representing a
/// nibble of the byte. The high nibble is listed first.
fn binary_byte(input: &str) -> IResult<&str, u8> {
    context(
        "binary_byte",
        map_res(map_parser(take(2usize), hex_digit1), |word| {
            u8::from_str_radix(word, 16)
        }),
    )(input)
}

/// Reads a binary resource, consisting of a string of any number of paired hex
/// digits representing byte values.
///
/// See [`binary_byte`].
fn binary_resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    let (rest, string) = resource!(binary_type, string).parse(input.clone())?;

    let (_, elements) = match many0(binary_byte).parse(string) {
        Ok(elements) => elements,
        Err(err) => {
            println!("{err}");
            return Err(nom::Err::Error(make_error(
                input,
                nom::error::ErrorKind::HexDigit,
            )));
        }
    };

    Ok((rest, Resource::Binary(Cow::from(elements))))
}

/// Reads a string resource.
///
/// Unlike other resources, a string may appear bare, without delimiting
/// braces.
///
/// See [`string`] for more details on the representation of strings.
fn string_resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "string_resource",
        map(
            alt((resource_opt_tag!(string_type, string), string)),
            |value| Resource::String(Cow::from(value)),
        ),
    )(input)
}

/// Reads a single resource.
fn resource<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, Resource<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "resource",
        alt((
            int_resource,
            int_vector_resource,
            string_resource,
            binary_resource,
            table_resource,
            array_resource,
        )),
    )(input)
}

/// Reads a complete resource bundle.
fn bundle<'a, E>(input: ParseState<'a>) -> IResult<ParseState<'a>, ResourceBundle<'a>, E>
where
    E: ParseError<ParseState<'a>> + ContextError<ParseState<'a>>,
{
    context(
        "bundle",
        map(
            terminated(
                pair(
                    // Note that the name of the bundle is a string and not a key,
                    // and it is not included in the list of keys in the bundle.
                    string,
                    root_table_resource,
                ),
                eof,
            ),
            |(name, (is_locale_fallback_enabled, root))| {
                ResourceBundle::new(Cow::from(name), root, is_locale_fallback_enabled)
            },
        ),
    )(input)
}

/// The `Reader` struct provides a means of parsing a [`ResourceBundle`] from
/// a string representing the contents of a text-based resource bundle file.
///
/// Note that the partial [specification] of the text-based format allows for
/// files to be in encodings other than UTF-8 and indicates that autodetection
/// of encoding should occur. At present, `Reader` only supports input as
/// UTF-8.
///
/// [specification]: https://github.com/unicode-org/icu-docs/blob/main/design/bnf_rb.txt
#[derive(Debug)]
#[non_exhaustive]
pub struct Reader;

impl Reader {
    /// Parses the given string into a resource bundle.
    ///
    /// Returns the parsed resource bundle and a list of the keys encountered in
    /// the resource bundle in the order they were encountered.
    pub fn read(input: &str) -> Result<(ResourceBundle, Vec<Key>), TextParserError> {
        let input = ParseState::new(input);

        let (final_state, bundle) = bundle::<VerboseError<ParseState>>(input.clone())
            .finish()
            .map_err(|err| TextParserError {
                trace: convert_error(input, err),
            })?;

        let keys_in_discovery_order = final_state.take_keys().into_iter().collect();

        Ok((bundle, keys_in_discovery_order))
    }
}

#[derive(Debug)]
pub struct TextParserError {
    trace: String,
}

impl fmt::Display for TextParserError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "Parse error while reading text bundle:\n{}",
            self.trace
        ))
    }
}