msg_tool\output_scripts/
po.rs

1//! tools to process gettext po/pot files
2//!
3//! See [spec](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html)
4use crate::types::*;
5use anyhow::{Result, anyhow};
6use std::collections::{HashMap, HashSet};
7use unicode_segmentation::UnicodeSegmentation;
8
9#[derive(Debug)]
10/// A comment line
11pub enum Comment {
12    /// Translator comment, starting with `# `
13    Translator(String),
14    /// Extracted comment, starting with `#.`.
15    Extracted(String),
16    /// Reference, starting with `#:`.
17    Reference(String),
18    /// Flag, starting with `#,`.
19    Flag(Vec<String>),
20    /// Previous untranslated string, starting with `#|`.
21    Previous(String),
22    /// Previous message block, starting with `#~`.
23    PreviousStr(String),
24}
25
26#[derive(Debug)]
27/// A line in a .po file.
28pub enum PoLine {
29    /// A comment line, starting with `#`.
30    Comment(Comment),
31    /// A msgid line
32    MsgId(String),
33    /// A msgstr line
34    MsgStr(String),
35    /// A msgctxt line
36    MsgCtxt(String),
37    /// A msgid_plural line
38    MsgIdPlural(String),
39    /// A msgstr[n] line
40    MsgStrN(usize, String),
41    /// Empty line
42    EmptyLine,
43}
44
45fn dump_text_in_multi_lines(s: &str) -> Result<String> {
46    if s.contains("\n") {
47        let mut result = Vec::new();
48        result.push("\"\"".to_string());
49        let mut s = s;
50        while let Some(pos) = s.find('\n') {
51            let line = &s[..pos + 1];
52            result.push(format!("\"{}\"", escape_c_str(line)?));
53            s = &s[pos + 1..];
54        }
55        if !s.is_empty() {
56            result.push(format!("\"{}\"", escape_c_str(s)?));
57        }
58        Ok(result.join("\n"))
59    } else {
60        Ok(format!("\"{}\"", escape_c_str(s)?))
61    }
62}
63
64impl PoLine {
65    fn dump(&self) -> Result<String> {
66        Ok(match self {
67            PoLine::Comment(c) => match c {
68                Comment::Translator(s) => format!("# {}", s),
69                Comment::Extracted(s) => format!("#. {}", s),
70                Comment::Reference(s) => format!("#: {}", s),
71                Comment::Flag(flags) => format!("#, {}", flags.join(", ")),
72                Comment::Previous(s) => format!("#| {}", s),
73                Comment::PreviousStr(s) => format!("#~ {}", s),
74            },
75            PoLine::MsgId(s) => format!("msgid {}", dump_text_in_multi_lines(s)?),
76            PoLine::MsgStr(s) => format!("msgstr {}", dump_text_in_multi_lines(s)?),
77            PoLine::MsgCtxt(s) => format!("msgctxt {}", dump_text_in_multi_lines(s)?),
78            PoLine::MsgIdPlural(s) => format!("msgid_plural {}", dump_text_in_multi_lines(s)?),
79            PoLine::MsgStrN(n, s) => format!("msgstr[{}] {}", n, dump_text_in_multi_lines(s)?),
80            PoLine::EmptyLine => String::new(),
81        })
82    }
83}
84
85#[derive(Debug)]
86pub enum MsgStr {
87    Single(String),
88    Plural(Vec<(usize, String)>),
89}
90
91#[derive(Debug)]
92pub struct PoEntry {
93    comments: Vec<Comment>,
94    msgctxt: Option<String>,
95    msgid: String,
96    msgid_plural: Option<String>,
97    msgstr: MsgStr,
98}
99
100/// Escapes a string according to C-style rules.
101///
102/// This function handles common escape sequences like \n, \t, \", \\, etc.
103/// For other ASCII control characters or non-printable characters, it uses octal notation (e.g., \0, \177).
104///
105/// # Arguments
106/// * `s`: The string slice to be escaped.
107///
108/// # Returns
109/// A `Result<String>` containing the new escaped string.
110pub fn escape_c_str(s: &str) -> Result<String> {
111    let mut escaped = String::with_capacity(s.len());
112    for c in s.chars() {
113        match c {
114            '\n' => escaped.push_str("\\n"),
115            '\r' => escaped.push_str("\\r"),
116            '\t' => escaped.push_str("\\t"),
117            '\\' => escaped.push_str("\\\\"),
118            '\"' => escaped.push_str("\\\""),
119            '\0' => escaped.push_str("\\0"),
120            '\x08' => escaped.push_str("\\b"),
121            '\x0c' => escaped.push_str("\\f"),
122            '\x0b' => escaped.push_str("\\v"),
123            '\x07' => escaped.push_str("\\a"),
124            c if c.is_ascii_control() && c != '\n' && c != '\r' && c != '\t' => {
125                escaped.push_str(&format!("\\{:03o}", c as u8));
126            }
127            _ => escaped.push(c),
128        }
129    }
130    Ok(escaped)
131}
132
133/// Unescapes a string that has been escaped C-style.
134///
135/// This function parses common escape sequences (like \n, \t, \", \\) as well as
136/// octal (\ooo) and hexadecimal (\xHH) escape notations.
137///
138/// # Arguments
139/// * `s`: The string slice containing C-style escape sequences.
140///
141/// # Returns
142/// A `Result<String>` containing the new unescaped string.
143/// If an invalid escape sequence is encountered, an error is returned.
144pub fn unescape_c_str(s: &str) -> Result<String> {
145    let mut unescaped = String::with_capacity(s.len());
146    let mut chars = s.chars().peekable();
147
148    while let Some(c) = chars.next() {
149        if c == '\\' {
150            match chars.next() {
151                Some('n') => unescaped.push('\n'),
152                Some('r') => unescaped.push('\r'),
153                Some('t') => unescaped.push('\t'),
154                Some('b') => unescaped.push('\x08'),
155                Some('f') => unescaped.push('\x0c'),
156                Some('v') => unescaped.push('\x0b'),
157                Some('a') => unescaped.push('\x07'),
158                Some('\\') => unescaped.push('\\'),
159                Some('\'') => unescaped.push('\''),
160                Some('\"') => unescaped.push('\"'),
161                Some('?') => unescaped.push('?'),
162                Some(o @ '0'..='7') => {
163                    let mut octal = String::new();
164                    octal.push(o);
165                    while let Some(peek_char) = chars.peek() {
166                        if peek_char.is_digit(8) && octal.len() < 3 {
167                            octal.push(chars.next().unwrap());
168                        } else {
169                            break;
170                        }
171                    }
172                    let value = u8::from_str_radix(&octal, 8).map_err(|e| {
173                        anyhow!("Invalid octal escape sequence: \\{}: {}", octal, e)
174                    })?;
175                    unescaped.push(value as char);
176                }
177                // --- FIX START: Reworked hexadecimal parsing logic ---
178                Some('x') => {
179                    let mut hex = String::new();
180
181                    // Read the first character, which must be a hex digit
182                    if let Some(c1) = chars.peek() {
183                        if c1.is_ascii_hexdigit() {
184                            hex.push(chars.next().unwrap());
185                        } else {
186                            // Handle cases like \xG
187                            return Err(anyhow!(
188                                "Invalid hex escape sequence: \\x followed by non-hex character '{}'",
189                                c1
190                            ));
191                        }
192                    } else {
193                        // Handle cases where \x is at the end of the string
194                        return Err(anyhow!(
195                            "Invalid hex escape sequence: \\x must be followed by a hex digit"
196                        ));
197                    }
198
199                    // Try to read the second character, which must also be a hex digit
200                    if let Some(c2) = chars.peek() {
201                        if c2.is_ascii_hexdigit() {
202                            hex.push(chars.next().unwrap());
203                        } else {
204                            // Handle cases like \xFG
205                            // We have successfully parsed one digit (like F), but it's followed by an invalid hex character (like G)
206                            // As per the test requirements, this should be an error
207                            return Err(anyhow!(
208                                "Invalid hex escape sequence: \\x{} followed by non-hex character '{}'",
209                                hex,
210                                c2
211                            ));
212                        }
213                    }
214
215                    let value =
216                        u8::from_str_radix(&hex, 16).expect("Hex parsing should be valid here");
217                    unescaped.push(value as char);
218                }
219                // --- FIX END ---
220                Some(other) => {
221                    return Err(anyhow!("Unknown escape sequence: \\{}", other));
222                }
223                None => {
224                    return Err(anyhow!("String cannot end with a single backslash"));
225                }
226            }
227        } else {
228            unescaped.push(c);
229        }
230    }
231    Ok(unescaped)
232}
233
234pub struct PoDumper {
235    entries: Vec<PoLine>,
236}
237
238impl PoDumper {
239    pub fn new() -> Self {
240        Self {
241            entries: Vec::new(),
242        }
243    }
244
245    fn gen_start_str(encoding: Encoding) -> String {
246        let mut map = HashMap::new();
247        let content_type = match encoding.charset() {
248            Some(e) => format!("text/plain; charset={}", e),
249            None => String::from("text/plain"),
250        };
251        map.insert("Content-Type", content_type);
252        map.insert("X-Generator", String::from("msg-tool"));
253        map.insert("MIME-Version", String::from("1.0"));
254        let mut result = String::new();
255        for (k, v) in map {
256            result.push_str(&format!("{}: {}\n", k, v));
257        }
258        result
259    }
260
261    pub fn dump_extended(
262        mut self,
263        entries: &[ExtendedMessage],
264        encoding: Encoding,
265    ) -> Result<String> {
266        self.add_entry(PoEntry {
267            comments: vec![
268                Comment::Translator(String::from("Generated by msg-tool")),
269                Comment::Flag(vec![String::from("fuzzy")]),
270            ],
271            msgctxt: None,
272            msgid: String::new(),
273            msgid_plural: None,
274            msgstr: MsgStr::Single(Self::gen_start_str(encoding)),
275        });
276        let mut added = HashSet::new();
277        let mut added_messages: HashMap<(&String, &Option<String>), usize> = HashMap::new();
278        for entry in entries {
279            let count = added_messages
280                .get(&(&entry.source, &entry.name))
281                .map(|&s| s)
282                .unwrap_or(0);
283            let inadded = added.contains(&entry.source);
284            let mut comments = Vec::new();
285            if let Some(name) = &entry.name {
286                comments.push(Comment::Translator(format!("NAME: {}", name)));
287            }
288            if let Some(llm) = &entry.llm {
289                comments.push(Comment::Translator(format!(
290                    "LLM: {}",
291                    llm.replace("\n", "\\n")
292                )));
293            }
294            self.add_entry(PoEntry {
295                comments,
296                msgctxt: if count > 0 || inadded {
297                    Some(format!(
298                        "{}{}",
299                        entry.name.as_ref().map(|s| s.as_str()).unwrap_or(""),
300                        count
301                    ))
302                } else {
303                    None
304                },
305                msgid: entry.source.clone(),
306                msgid_plural: None,
307                msgstr: MsgStr::Single(entry.translated.clone()),
308            });
309            added_messages.insert((&entry.source, &entry.name), count + 1);
310            if !inadded {
311                added.insert(&entry.source);
312            }
313        }
314        let mut result = String::new();
315        for line in &self.entries {
316            result.push_str(&line.dump()?);
317            result.push('\n');
318        }
319        Ok(result)
320    }
321
322    pub fn dump(mut self, entries: &[Message], encoding: Encoding) -> Result<String> {
323        self.add_entry(PoEntry {
324            comments: vec![
325                Comment::Translator(String::from("Generated by msg-tool")),
326                Comment::Flag(vec![String::from("fuzzy")]),
327            ],
328            msgctxt: None,
329            msgid: String::new(),
330            msgid_plural: None,
331            msgstr: MsgStr::Single(Self::gen_start_str(encoding)),
332        });
333        let mut added: HashSet<&String> = HashSet::new();
334        let mut added_messages: HashMap<(&String, &Option<String>), usize> = HashMap::new();
335        for entry in entries {
336            let count = added_messages
337                .get(&(&entry.message, &entry.name))
338                .map(|&s| s)
339                .unwrap_or(0);
340            let inadded = added.contains(&entry.message);
341            self.add_entry(PoEntry {
342                comments: entry
343                    .name
344                    .as_ref()
345                    .map(|name| vec![Comment::Translator(format!("NAME: {}", name))])
346                    .unwrap_or_default(),
347                msgctxt: if count > 0 || inadded {
348                    Some(format!(
349                        "{}{}",
350                        entry.name.as_ref().map(|s| s.as_str()).unwrap_or(""),
351                        count
352                    ))
353                } else {
354                    None
355                },
356                msgid: entry.message.clone(),
357                msgid_plural: None,
358                msgstr: MsgStr::Single(String::new()),
359            });
360            added_messages.insert((&entry.message, &entry.name), count + 1);
361            if !inadded {
362                added.insert(&entry.message);
363            }
364        }
365        let mut result = String::new();
366        for line in &self.entries {
367            result.push_str(&line.dump()?);
368            result.push('\n');
369        }
370        Ok(result)
371    }
372
373    fn add_entry(&mut self, entry: PoEntry) {
374        for comment in entry.comments {
375            self.entries.push(PoLine::Comment(comment));
376        }
377        if let Some(ctx) = entry.msgctxt {
378            self.entries.push(PoLine::MsgCtxt(ctx));
379        }
380        self.entries.push(PoLine::MsgId(entry.msgid));
381        let is_plural = entry.msgid_plural.is_some();
382        if let Some(plural) = entry.msgid_plural {
383            self.entries.push(PoLine::MsgIdPlural(plural));
384        }
385        match entry.msgstr {
386            MsgStr::Single(s) => {
387                if is_plural {
388                    self.entries.push(PoLine::MsgStrN(0, s));
389                } else {
390                    self.entries.push(PoLine::MsgStr(s));
391                }
392            }
393            MsgStr::Plural(v) => {
394                for (n, s) in v {
395                    self.entries.push(PoLine::MsgStrN(n, s));
396                }
397            }
398        }
399        self.entries.push(PoLine::EmptyLine);
400    }
401}
402
403pub struct PoParser<'a> {
404    texts: Vec<&'a str>,
405    pos: usize,
406    llm_mark: Option<&'a str>,
407}
408
409impl<'a> PoParser<'a> {
410    pub fn new(s: &'a str, llm_mark: Option<&'a str>) -> Self {
411        Self {
412            texts: s.graphemes(true).collect(),
413            pos: 0,
414            llm_mark,
415        }
416    }
417
418    pub fn parse_lines(&mut self) -> Result<Vec<PoLine>> {
419        let mut lines = Vec::new();
420        while let Some(f) = self.next_line() {
421            let f = f.trim();
422            if f.starts_with("#") {
423                if f.len() < 2 {
424                    return Err(anyhow!("Invalid comment line: {}", f));
425                }
426                let c = &f[1..];
427                if c.starts_with(' ') {
428                    lines.push(PoLine::Comment(Comment::Translator(c[1..].to_string())));
429                } else if c.starts_with('.') {
430                    lines.push(PoLine::Comment(Comment::Extracted(
431                        c[1..].trim_start().to_string(),
432                    )));
433                } else if c.starts_with(':') {
434                    lines.push(PoLine::Comment(Comment::Reference(
435                        c[1..].trim_start().to_string(),
436                    )));
437                } else if c.starts_with(',') {
438                    let flags = c[1..].split(',').map(|s| s.trim().to_string()).collect();
439                    lines.push(PoLine::Comment(Comment::Flag(flags)));
440                } else if c.starts_with('|') {
441                    lines.push(PoLine::Comment(Comment::Previous(
442                        c[1..].trim_start().to_string(),
443                    )));
444                } else if c.starts_with('~') {
445                    lines.push(PoLine::Comment(Comment::PreviousStr(
446                        c[1..].trim_start().to_string(),
447                    )));
448                } else {
449                    return Err(anyhow!("Unknown comment type: {}", f));
450                }
451            } else if f.starts_with("msgid ") {
452                let content = self.read_string_literal(&f[6..])?;
453                lines.push(PoLine::MsgId(content));
454            } else if f.starts_with("msgstr ") {
455                let content = self.read_string_literal(&f[7..])?;
456                lines.push(PoLine::MsgStr(content));
457            } else if f.starts_with("msgctxt ") {
458                let content = self.read_string_literal(&f[8..])?;
459                lines.push(PoLine::MsgCtxt(content));
460            } else if f.starts_with("msgid_plural ") {
461                let content = self.read_string_literal(&f[13..])?;
462                lines.push(PoLine::MsgIdPlural(content));
463            } else if f.starts_with("msgstr[") {
464                let end_bracket = f
465                    .find(']')
466                    .ok_or_else(|| anyhow!("Invalid msgstr[n] line: {}", f))?;
467                let index_str = &f[7..end_bracket];
468                let index: usize = index_str
469                    .parse()
470                    .map_err(|_| anyhow!("Invalid index in msgstr[n]: {}", index_str))?;
471                let content = self.read_string_literal(&f[end_bracket + 1..])?;
472                lines.push(PoLine::MsgStrN(index, content));
473            } else if f.trim().is_empty() {
474                lines.push(PoLine::EmptyLine);
475            } else if f.starts_with('"') {
476                // This is a continuation of a previous string.
477                // According to GNU gettext manual, a string literal cannot appear on its own.
478                // It must follow a keyword. However, some tools generate this.
479                // We will append it to the last string-like element.
480                let content = self.read_string_literal(&f)?;
481                if let Some(last_line) = lines.last_mut() {
482                    match last_line {
483                        PoLine::MsgId(s) => s.push_str(&content),
484                        PoLine::MsgStr(s) => s.push_str(&content),
485                        PoLine::MsgCtxt(s) => s.push_str(&content),
486                        PoLine::MsgIdPlural(s) => s.push_str(&content),
487                        PoLine::MsgStrN(_, s) => s.push_str(&content),
488                        _ => return Err(anyhow!("Orphan string literal continuation: {}", f)),
489                    }
490                } else {
491                    return Err(anyhow!("Orphan string literal continuation: {}", f));
492                }
493            } else {
494                return Err(anyhow!("Unknown line type: {}", f));
495            }
496        }
497        Ok(lines)
498    }
499
500    fn read_string_literal(&mut self, s: &str) -> Result<String> {
501        let mut content = String::new();
502        let current_line_str = s.trim();
503        if current_line_str.starts_with('"') && current_line_str.ends_with('"') {
504            content.push_str(&unescape_c_str(
505                &current_line_str[1..current_line_str.len() - 1],
506            )?);
507        } else {
508            return Err(anyhow!("Invalid string literal: {}", s));
509        }
510
511        while let Some(peeked_line) = self.peek_line() {
512            if peeked_line.trim().starts_with('"') {
513                self.next_line(); // consume it
514                let trimmed_line = peeked_line.trim();
515                if trimmed_line.starts_with('"') && trimmed_line.ends_with('"') {
516                    content.push_str(&unescape_c_str(&trimmed_line[1..trimmed_line.len() - 1])?);
517                } else {
518                    return Err(anyhow!(
519                        "Invalid string literal continuation: {}",
520                        peeked_line
521                    ));
522                }
523            } else {
524                break;
525            }
526        }
527        Ok(content)
528    }
529
530    pub fn parse_entries(&mut self) -> Result<Vec<PoEntry>> {
531        let lines = self.parse_lines()?;
532        let mut entries = Vec::new();
533        let mut current_entry_lines: Vec<PoLine> = Vec::new();
534
535        for line in lines {
536            if let PoLine::EmptyLine = line {
537                if !current_entry_lines.is_empty() {
538                    entries.push(self.build_entry_from_lines(current_entry_lines)?);
539                    current_entry_lines = Vec::new();
540                }
541            } else {
542                current_entry_lines.push(line);
543            }
544        }
545
546        if !current_entry_lines.is_empty() {
547            entries.push(self.build_entry_from_lines(current_entry_lines)?);
548        }
549
550        Ok(entries)
551    }
552
553    fn build_entry_from_lines(&self, lines: Vec<PoLine>) -> Result<PoEntry> {
554        let mut comments = Vec::new();
555        let mut msgctxt: Option<String> = None;
556        let mut msgid: Option<String> = None;
557        let mut msgid_plural: Option<String> = None;
558        let mut msgstr: Option<String> = None;
559        let mut msgstr_plural: Vec<(usize, String)> = Vec::new();
560
561        for line in lines {
562            match line {
563                PoLine::Comment(c) => comments.push(c),
564                PoLine::MsgCtxt(s) => {
565                    if msgctxt.is_some() {
566                        return Err(anyhow!("Duplicate msgctxt in entry"));
567                    }
568                    msgctxt = Some(s);
569                }
570                PoLine::MsgId(s) => {
571                    if msgid.is_some() {
572                        return Err(anyhow!("Duplicate msgid in entry"));
573                    }
574                    msgid = Some(s);
575                }
576                PoLine::MsgIdPlural(s) => {
577                    if msgid_plural.is_some() {
578                        return Err(anyhow!("Duplicate msgid_plural in entry"));
579                    }
580                    msgid_plural = Some(s);
581                }
582                PoLine::MsgStr(s) => {
583                    if msgstr.is_some() {
584                        return Err(anyhow!("Duplicate msgstr in entry"));
585                    }
586                    msgstr = Some(s);
587                }
588                PoLine::MsgStrN(n, s) => {
589                    if msgstr_plural.iter().any(|(i, _)| *i == n) {
590                        return Err(anyhow!("Duplicate msgstr[{}] in entry", n));
591                    }
592                    msgstr_plural.push((n, s));
593                }
594                PoLine::EmptyLine => {
595                    // This should not be reached if called from parse_entries
596                    return Err(anyhow!("Unexpected empty line in build_entry_from_lines"));
597                }
598            }
599        }
600
601        let final_msgstr = if !msgstr_plural.is_empty() {
602            if msgstr.is_some() {
603                return Err(anyhow!(
604                    "Mixing msgstr and msgstr[n] in the same entry is not allowed"
605                ));
606            }
607            MsgStr::Plural(msgstr_plural)
608        } else {
609            MsgStr::Single(msgstr.unwrap_or_default())
610        };
611
612        Ok(PoEntry {
613            comments,
614            msgctxt,
615            msgid: msgid.ok_or_else(|| anyhow!("Entry is missing msgid"))?,
616            msgid_plural,
617            msgstr: final_msgstr,
618        })
619    }
620
621    fn peek(&self) -> Option<&'a str> {
622        self.texts.get(self.pos).copied()
623    }
624
625    fn peek_line(&self) -> Option<String> {
626        let mut line = String::new();
627        let mut current_pos = self.pos;
628        while let Some(c) = self.texts.get(current_pos).copied() {
629            current_pos += 1;
630            if c == "\n" || c == "\r\n" {
631                break;
632            }
633            line.push_str(c);
634        }
635        if line.is_empty() && current_pos >= self.texts.len() {
636            None
637        } else {
638            Some(line)
639        }
640    }
641
642    fn next_line(&mut self) -> Option<String> {
643        let mut line = String::new();
644        while let Some(c) = self.next() {
645            if c == "\n" || c == "\r\n" {
646                break;
647            }
648            line.push_str(c);
649        }
650        if line.is_empty() && self.peek().is_none() {
651            None
652        } else {
653            Some(line)
654        }
655    }
656
657    fn next(&mut self) -> Option<&'a str> {
658        let r = self.texts.get(self.pos).copied();
659        if r.is_some() {
660            self.pos += 1;
661        }
662        r
663    }
664
665    pub fn parse_as_vec(&mut self) -> Result<Vec<(String, String)>> {
666        let mut map = Vec::new();
667        let mut llm = None;
668        for (i, entry) in self.parse_entries()?.into_iter().enumerate() {
669            if entry.msgid.is_empty() && i == 0 {
670                // This is the header entry, skip it
671                continue;
672            }
673            for comment in &entry.comments {
674                if let Comment::Translator(s) = comment {
675                    let s = s.trim();
676                    if s.starts_with("NAME:") {
677                        // name = Some(s[5..].trim().to_string());
678                    } else if s.starts_with("LLM:") {
679                        llm = Some(s[4..].trim().replace("\\n", "\n"));
680                    }
681                }
682            }
683            let message = match entry.msgstr {
684                MsgStr::Single(s) => {
685                    let s = s.trim();
686                    if s.is_empty() {
687                        llm.take()
688                            .map(|mut llm| {
689                                if let Some(mark) = self.llm_mark {
690                                    llm.push_str(mark);
691                                }
692                                llm
693                            })
694                            .unwrap_or_else(|| {
695                                String::from(if entry.msgid.is_empty() { "" } else { "" })
696                            })
697                    } else {
698                        let mut tmp = s.to_string();
699                        if let Some(llm) = llm.take() {
700                            if tmp == llm {
701                                if let Some(mark) = self.llm_mark {
702                                    tmp.push_str(mark);
703                                }
704                            }
705                        }
706                        tmp
707                    }
708                }
709                MsgStr::Plural(_) => {
710                    return Err(anyhow!("Plural msgstr not supported in this context"));
711                }
712            };
713            map.push((entry.msgid, message));
714        }
715        Ok(map)
716    }
717
718    pub fn parse(&mut self) -> Result<Vec<Message>> {
719        let mut messages = Vec::new();
720        let mut llm = None;
721        let mut name = None;
722        for (i, entry) in self.parse_entries()?.into_iter().enumerate() {
723            if entry.msgid.is_empty() && i == 0 {
724                // This is the header entry, skip it
725                continue;
726            }
727            for comment in &entry.comments {
728                if let Comment::Translator(s) = comment {
729                    let s = s.trim();
730                    if s.starts_with("NAME:") {
731                        name = Some(s[5..].trim().to_string());
732                    } else if s.starts_with("LLM:") {
733                        llm = Some(s[4..].trim().replace("\\n", "\n"));
734                    }
735                }
736            }
737            let message = match entry.msgstr {
738                MsgStr::Single(s) => {
739                    let s = s.trim();
740                    if s.is_empty() {
741                        llm.take()
742                            .map(|mut llm| {
743                                if let Some(mark) = self.llm_mark {
744                                    llm.push_str(mark);
745                                }
746                                llm
747                            })
748                            .unwrap_or_else(|| {
749                                String::from(if entry.msgid.is_empty() { "" } else { "" })
750                            })
751                    } else {
752                        let mut tmp = s.to_string();
753                        if let Some(llm) = llm.take() {
754                            if tmp == llm {
755                                if let Some(mark) = self.llm_mark {
756                                    tmp.push_str(mark);
757                                }
758                            }
759                        }
760                        tmp
761                    }
762                }
763                MsgStr::Plural(_) => {
764                    return Err(anyhow!("Plural msgstr not supported in this context"));
765                }
766            };
767            let m = Message::new(message, name.take());
768            messages.push(m);
769        }
770        Ok(messages)
771    }
772
773    pub fn parse_as_extend(&mut self) -> Result<Vec<ExtendedMessage>> {
774        let mut messages = Vec::new();
775        for (i, entry) in self.parse_entries()?.into_iter().enumerate() {
776            if entry.msgid.is_empty() && i == 0 {
777                // This is the header entry, skip it
778                continue;
779            }
780            let mut name = None;
781            let mut llm = None;
782            for comment in &entry.comments {
783                if let Comment::Translator(s) = comment {
784                    let s = s.trim();
785                    if s.starts_with("NAME:") {
786                        name = Some(s[5..].trim().to_string());
787                    } else if s.starts_with("LLM:") {
788                        llm = Some(s[4..].trim().replace("\\n", "\n"));
789                    }
790                }
791            }
792            let message = match entry.msgstr {
793                MsgStr::Single(s) => s,
794                MsgStr::Plural(_) => {
795                    return Err(anyhow!("Plural msgstr not supported in this context"));
796                }
797            };
798            let m = ExtendedMessage {
799                name: name,
800                source: entry.msgid,
801                translated: message,
802                llm: llm,
803            };
804            messages.push(m);
805        }
806        Ok(messages)
807    }
808}
809
810// --- Unit Tests ---
811#[cfg(test)]
812mod c_escape_tests {
813    use super::*;
814
815    #[test]
816    fn test_escape_basic() {
817        assert_eq!(escape_c_str("hello world").unwrap(), "hello world");
818    }
819
820    #[test]
821    fn test_escape_quotes_and_slashes() {
822        assert_eq!(
823            escape_c_str(r#"he"llo\world"#).unwrap(),
824            r#"he\"llo\\world"#
825        );
826    }
827
828    #[test]
829    fn test_escape_control_chars() {
830        assert_eq!(escape_c_str("a\nb\tc\rd").unwrap(), r#"a\nb\tc\rd"#);
831        assert_eq!(escape_c_str("\0").unwrap(), r#"\0"#);
832    }
833
834    #[test]
835    fn test_escape_other_control_chars_as_octal() {
836        assert_eq!(escape_c_str("\x07").unwrap(), r#"\a"#);
837        assert_eq!(escape_c_str("\x7f").unwrap(), r#"\177"#);
838    }
839
840    #[test]
841    fn test_unescape_basic() {
842        assert_eq!(unescape_c_str("hello world").unwrap(), "hello world");
843    }
844
845    #[test]
846    fn test_unescape_quotes_and_slashes() {
847        assert_eq!(
848            unescape_c_str(r#"he\"llo\\world"#).unwrap(),
849            r#"he"llo\world"#
850        );
851    }
852
853    #[test]
854    fn test_unescape_control_chars() {
855        assert_eq!(unescape_c_str(r#"a\nb\tc\rd"#).unwrap(), "a\nb\tc\rd");
856    }
857
858    #[test]
859    fn test_unescape_octal() {
860        assert_eq!(unescape_c_str(r#"\101"#).unwrap(), "A");
861        assert_eq!(unescape_c_str(r#"\60"#).unwrap(), "0");
862        assert_eq!(unescape_c_str(r#"\0"#).unwrap(), "\0");
863        assert_eq!(unescape_c_str(r#"\177"#).unwrap(), "\x7f");
864        assert_eq!(unescape_c_str(r#"hello\101world"#).unwrap(), "helloAworld");
865    }
866
867    #[test]
868    fn test_unescape_hex() {
869        assert_eq!(unescape_c_str(r#"\x41"#).unwrap(), "A");
870        assert_eq!(unescape_c_str(r#"\x30"#).unwrap(), "0");
871        assert_eq!(unescape_c_str(r#"\x7F"#).unwrap(), "\x7f");
872        assert_eq!(unescape_c_str(r#"\x7f"#).unwrap(), "\x7f");
873        assert_eq!(unescape_c_str(r#"hello\x41world"#).unwrap(), "helloAworld");
874        // A single hex digit is also valid
875        assert_eq!(unescape_c_str(r#"\xF"#).unwrap(), "\x0f");
876    }
877
878    #[test]
879    fn test_unescape_mixed() {
880        let original = "A\tB\"C\\D\0E";
881        let escaped = r#"A\tB\"C\\D\0E"#;
882        assert_eq!(unescape_c_str(escaped).unwrap(), original);
883    }
884
885    #[test]
886    fn test_unescape_invalid_sequence() {
887        assert!(unescape_c_str(r#"\q"#).is_err());
888        assert!(unescape_c_str(r#"hello\"#).is_err());
889        assert!(unescape_c_str(r#"\x"#).is_err());
890        // New: test \x followed immediately by an invalid character
891        assert!(unescape_c_str(r#"\xG"#).is_err());
892        // This should now pass
893        assert!(unescape_c_str(r#"\xFG"#).is_err());
894        assert!(unescape_c_str(r#"\8"#).is_err());
895    }
896}