poexam 0.0.11

Blazingly fast PO linter.
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// SPDX-FileCopyrightText: 2026 Sébastien Helleu <flashcode@flashtux.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

//! Format iterator: return format strings.

use crate::po::format::{FormatParser, MatchFmtPos, language::Language};

pub struct FormatPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }
}

/// Iterator returning format strings of a string, according to the given language.
///
/// For example in C language, with the string `Hello, %d %s world!`, it will return
/// `%d` and `%s` with their positions in the string.
impl<'a> Iterator for FormatPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some((_, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
            if is_format {
                let start = self.pos;
                self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                return Some(MatchFmtPos {
                    s: &self.s[start..self.pos],
                    start,
                    end: self.pos,
                });
            }
            self.pos = new_pos;
        }
        None
    }
}

pub struct FormatWordPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatWordPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }
}

/// Iterator returning words of a string, according to the given language, skipping
/// format strings.
///
/// For example in C language, with the string `Hello, %d %s world!`, it will return
/// `Hello` and `world` with their positions in the string.
impl<'a> Iterator for FormatWordPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut idx_start = None;
        let mut idx_end = None;
        let mut start_apostrophe = false;

        while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
            if is_format {
                if idx_start.is_some() {
                    break;
                }
                self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                continue;
            }
            if idx_start.is_none() && c == '\'' {
                start_apostrophe = true;
            }
            if c.is_alphanumeric()
                || (idx_start.is_some() && (c == '-' || c == '\'' || c == '') || (c == 'ʼ'))
            {
                if idx_start.is_none() {
                    idx_start = Some(self.pos);
                }
                idx_end = Some(new_pos);
                self.pos = new_pos;
            } else if idx_start.is_some() {
                break;
            } else {
                self.pos = new_pos;
            }
        }
        match (idx_start, idx_end) {
            (Some(start), Some(end)) => {
                let s = &self.s[start..end];
                if start_apostrophe && let Some(s2) = s.strip_suffix('\'') {
                    Some(MatchFmtPos {
                        s: s2,
                        start,
                        end: end - 1,
                    })
                } else {
                    Some(MatchFmtPos { s, start, end })
                }
            }
            _ => None,
        }
    }
}

pub struct FormatAcronymPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatAcronymPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }
}

/// Iterator returning acronyms of a string, according to the given language,
/// skipping format strings.
///
/// An acronym is a word of length ≥ 2 chars whose Python-equivalent
/// `str.isupper()` returns true: at least one cased character is present and
/// none is lowercase. Caseless characters (digits, etc.) are allowed.
///
/// Words are alphanumeric runs (boundaries: any non-alphanumeric character
/// including apostrophes, hyphens, spaces and punctuation), so `API` in
/// `l'API` is recognized as well as `MP3` and `B2B`. `URLs` and `Json` are
/// not acronyms (they contain a lowercase letter).
///
/// For example with the string `Use the HTTP API for %s and l'API`, it will
/// return `HTTP`, `API` and `API` with their positions in the string.
impl<'a> Iterator for FormatAcronymPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let mut idx_start = None;
            let mut idx_end = None;
            let mut has_upper = false;
            let mut has_lower = false;
            while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
                if is_format {
                    if idx_start.is_some() {
                        break;
                    }
                    self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                    continue;
                }
                if c.is_alphanumeric() {
                    if idx_start.is_none() {
                        idx_start = Some(self.pos);
                        has_upper = false;
                        has_lower = false;
                    }
                    if c.is_uppercase() {
                        has_upper = true;
                    } else if c.is_lowercase() {
                        has_lower = true;
                    }
                    idx_end = Some(new_pos);
                    self.pos = new_pos;
                } else if idx_start.is_some() {
                    break;
                } else {
                    self.pos = new_pos;
                }
            }
            match (idx_start, idx_end) {
                (Some(start), Some(end)) => {
                    let word = &self.s[start..end];
                    if has_upper && !has_lower && word.chars().count() >= 2 {
                        return Some(MatchFmtPos {
                            s: word,
                            start,
                            end,
                        });
                    }
                    // Not an all-uppercase word, or too short — keep scanning.
                }
                _ => return None,
            }
        }
    }
}

pub struct FormatAcceleratorPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
    marker: char,
}

impl<'a> FormatAcceleratorPos<'a> {
    pub fn new(s: &'a str, language: Language, marker: char) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
            marker,
        }
    }
}

/// Iterator returning keyboard accelerator markers of a string, according to the
/// given language, skipping format strings.
///
/// An accelerator is the `marker` character (e.g. `&`) immediately followed by an
/// alphanumeric character. A doubled marker (e.g. `&&`) is an escaped literal and
/// is not an accelerator: both characters are skipped. A trailing marker, or a
/// marker followed by whitespace or punctuation, is treated as a literal and
/// ignored (this avoids false positives on prose such as "Drag & drop"). Only the
/// marker character is returned, not the accelerated character, so its span is
/// always one character wide.
///
/// For example with marker `&` and the string `&File and E&xit`, it will return
/// the `&` at positions 0 and 11.
impl<'a> Iterator for FormatAcceleratorPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
            if is_format {
                self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                continue;
            }
            if c == self.marker {
                let start = self.pos;
                match self.s[new_pos..].chars().next() {
                    // Doubled marker is an escaped literal: skip both characters.
                    Some(next) if next == self.marker => {
                        self.pos = new_pos + self.marker.len_utf8();
                    }
                    // Marker before an alphanumeric character: an accelerator.
                    Some(next) if next.is_alphanumeric() => {
                        self.pos = new_pos;
                        return Some(MatchFmtPos {
                            s: &self.s[start..new_pos],
                            start,
                            end: new_pos,
                        });
                    }
                    // Trailing marker, or marker before whitespace/punctuation: literal.
                    _ => self.pos = new_pos,
                }
                continue;
            }
            self.pos = new_pos;
        }
        None
    }
}

pub struct FormatUrlPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatUrlPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }
}

/// Iterator returning URLs of a string, according to the given language, skipping
/// format strings.
///
/// For example in C language, with the string `Hello, %d %s world! https://example.com`,
/// it will return `https://example.com` with its position in the string.
///
/// Angle brackets around URLs are handled, e.g. `Hello, %d %s world! <https://example.com>`
/// (the angle brackets are not included in the returned URL).
impl<'a> Iterator for FormatUrlPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut idx_start = None;
        let mut idx_end = None;
        loop {
            while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
                if is_format {
                    self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                    continue;
                }
                if !c.is_whitespace() {
                    if idx_start.is_none() {
                        idx_start = Some(self.pos);
                    }
                    idx_end = Some(new_pos);
                    self.pos = new_pos;
                } else if idx_start.is_some() {
                    break;
                } else {
                    self.pos = new_pos;
                }
            }
            match (idx_start, idx_end) {
                (Some(mut start), Some(mut end)) => {
                    let mut s = &self.s[start..end];
                    if s.starts_with('<') && s.ends_with('>') {
                        s = &s[1..s.len() - 1];
                        start += 1;
                        end -= 1;
                    }
                    if s.contains("://") && s.contains('.') {
                        return Some(MatchFmtPos { s, start, end });
                    }
                    idx_start = None;
                    idx_end = None;
                }
                _ => return None,
            }
        }
    }
}

pub struct FormatEmailPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatEmailPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }

    /// Simple check for email validity: check that it contains exactly one '@' and that
    /// local and domain parts are not empty and contain only allowed characters, with
    /// relaxed rules (e.g. allow language formats like `%s` or `{0}`).
    fn is_valid_email(email: &str) -> bool {
        email.find('@').is_some_and(|pos_arobase| {
            let local = &email[..pos_arobase];
            let domain = &email[pos_arobase + 1..];
            !local.is_empty()
                && !domain.is_empty()
                && local.chars().all(|c| {
                    c.is_alphanumeric()
                        || c == '.'
                        || c == '-'
                        || c == '_'
                        || c == '+'
                        || c == '%'
                        || c == '{'
                        || c == '}'
                        || c == '$'
                        || c == '"'
                        || c == ''
                        || c == ''
                        || c == '«'
                        || c == '»'
                })
                && domain.chars().all(|c| {
                    c.is_alphanumeric()
                        || c == '.'
                        || c == '-'
                        || c == '%'
                        || c == '{'
                        || c == '}'
                        || c == '$'
                        || c == '"'
                        || c == ''
                        || c == ''
                        || c == '«'
                        || c == '»'
                })
                && domain.contains('.')
        })
    }
}

/// Iterator returning emails of a string, according to the given language, skipping
/// format strings.
///
/// For example in C language, with the string `Please send email to: user@example.com`,
/// it will return `user@example.com` with its position in the string.
///
/// Angle brackets around emails are handled, e.g. `Please send email to: <user@example.com>`
/// (the angle brackets are not included in the returned email).
impl<'a> Iterator for FormatEmailPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut idx_start = None;
        let mut idx_end = None;
        loop {
            while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
                if is_format {
                    self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                    continue;
                }
                if !c.is_whitespace() {
                    if idx_start.is_none() {
                        idx_start = Some(self.pos);
                    }
                    idx_end = Some(new_pos);
                    self.pos = new_pos;
                } else if idx_start.is_some() {
                    break;
                } else {
                    self.pos = new_pos;
                }
            }
            match (idx_start, idx_end) {
                (Some(mut start), Some(mut end)) => {
                    let mut s = &self.s[start..end];
                    if s.starts_with('<') && s.ends_with('>') {
                        s = &s[1..s.len() - 1];
                        start += 1;
                        end -= 1;
                    }
                    if Self::is_valid_email(s) {
                        return Some(MatchFmtPos { s, start, end });
                    }
                    idx_start = None;
                    idx_end = None;
                }
                _ => return None,
            }
        }
    }
}

pub struct FormatPathPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatPathPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }

    /// Check if a string is a path: it starts with '/' or './' or '../' or '~/'.
    fn is_path(path: &str) -> bool {
        if path.starts_with("./") || path.starts_with("../") || path.starts_with("~/") {
            return true;
        }
        if path.starts_with('/')
            && let Some(pos) = path[1..].find('/')
            && pos > 0
            && !path[pos + 2..].is_empty()
        {
            return true;
        }
        false
    }
}

/// Iterator returning paths of a string, according to the given language, skipping
/// format strings.
///
/// For example in C language, with the string `Hello, %d %s world! /tmp/output.txt`,
/// it will return `/tmp/output.txt` with its position in the string.
impl<'a> Iterator for FormatPathPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut idx_start = None;
        let mut idx_end = None;
        loop {
            while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
                if is_format {
                    self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                    continue;
                }
                if !c.is_whitespace() {
                    if idx_start.is_none() {
                        idx_start = Some(self.pos);
                    }
                    idx_end = Some(new_pos);
                    self.pos = new_pos;
                } else if idx_start.is_some() {
                    break;
                } else {
                    self.pos = new_pos;
                }
            }
            match (idx_start, idx_end) {
                (Some(start), Some(end)) => {
                    let s = &self.s[start..end];
                    if Self::is_path(s) {
                        return Some(MatchFmtPos { s, start, end });
                    }
                    idx_start = None;
                    idx_end = None;
                }
                _ => return None,
            }
        }
    }
}

pub struct FormatHtmlTagPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatHtmlTagPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }
}

/// Iterator returning HTML tags of a string, according to the given language, skipping
/// format strings.
///
/// For example with the string `Hello <b>world</b>`, it will return
/// `<b>` and `</b>` with their positions in the string.
///
/// Tags with attributes are also matched, e.g. `<a href="...">`.
/// Quoted attribute values (double or single quotes) are handled so that
/// a `>` inside quotes does not end the tag prematurely.
impl<'a> Iterator for FormatHtmlTagPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) {
            if is_format {
                self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                continue;
            }
            if c == '<' {
                // Check the next character is a letter or '/' (tag start).
                let tag_start = self.pos;
                if let Some(next_ch) = self.s[new_pos..].chars().next()
                    && (next_ch.is_ascii_alphabetic() || next_ch == '/')
                    && let Some(tag_end) = self.find_tag_end(new_pos)
                {
                    self.pos = tag_end;
                    return Some(MatchFmtPos {
                        s: &self.s[tag_start..tag_end],
                        start: tag_start,
                        end: tag_end,
                    });
                }
            }
            self.pos = new_pos;
        }
        None
    }
}

impl FormatHtmlTagPos<'_> {
    /// Find the end of an HTML tag starting after `<`, handling quoted attribute values.
    /// Returns the byte position after the closing `>`, or `None` if not found.
    fn find_tag_end(&self, start: usize) -> Option<usize> {
        let mut pos = start;
        while pos < self.len {
            let c = self.s.as_bytes()[pos];
            match c {
                b'>' => return Some(pos + 1),
                b'"' | b'\'' => {
                    // Skip quoted attribute value.
                    pos += 1;
                    while pos < self.len && self.s.as_bytes()[pos] != c {
                        pos += 1;
                    }
                    if pos < self.len {
                        // Skip closing quote.
                        pos += 1;
                    }
                }
                _ => pos += 1,
            }
        }
        None
    }
}

pub struct FormatFunctionPos<'a> {
    s: &'a str,
    len: usize,
    pos: usize,
    fmt: Language,
}

impl<'a> FormatFunctionPos<'a> {
    pub fn new(s: &'a str, language: Language) -> Self {
        Self {
            s,
            len: s.len(),
            pos: 0,
            fmt: language,
        }
    }
}

/// Iterator returning function calls of a string, according to the given language,
/// skipping format strings.
///
/// A function call is a name (ASCII word characters and dots), optionally with
/// `::` or `->` separators followed by more name parts, ending with `()`.
///
/// For example with the string `Use foo() and bar.baz() and Class::method()`,
/// it will return `foo()`, `bar.baz()` and `Class::method()` with their
/// positions in the string.
impl<'a> Iterator for FormatFunctionPos<'a> {
    type Item = MatchFmtPos<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        'outer: loop {
            // Find the start: the first ASCII word character (alphanumeric or `_`).
            // Skip format strings and any other characters.
            let start;
            loop {
                let (c, new_pos, is_format) = self.fmt.next_char(self.s, self.pos)?;
                if is_format {
                    self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                    continue;
                }
                if c.is_ascii_alphanumeric() || c == '_' {
                    start = self.pos;
                    self.pos = new_pos;
                    break;
                }
                self.pos = new_pos;
            }

            // Walk forward, accepting name characters (`\w`, `.`), separators (`::`, `->`)
            // and format strings (transparent: included in the match span but not in the
            // syntactic name). Stop at `()` (success) or any other character (failure).
            loop {
                let bytes = self.s.as_bytes();
                // Try separator `::` or `->`.
                if self.pos + 2 <= self.len {
                    let two = &bytes[self.pos..self.pos + 2];
                    if two == b"::" || two == b"->" {
                        self.pos += 2;
                        continue;
                    }
                }
                // Try `()`.
                if self.pos + 2 <= self.len
                    && bytes[self.pos] == b'('
                    && bytes[self.pos + 1] == b')'
                {
                    let end = self.pos + 2;
                    self.pos = end;
                    return Some(MatchFmtPos {
                        s: &self.s[start..end],
                        start,
                        end,
                    });
                }
                // Get the next char (may be the start of a format string).
                let Some((c, new_pos, is_format)) = self.fmt.next_char(self.s, self.pos) else {
                    // End of string reached without finding `()`.
                    return None;
                };
                if is_format {
                    self.pos = self.fmt.find_end_format(self.s, new_pos, self.len);
                    continue;
                }
                if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
                    self.pos = new_pos;
                    continue;
                }
                // Not a valid character in a function name: abandon the current attempt
                // and resume scanning for a new start from the same position.
                continue 'outer;
            }
        }
    }
}