Parse a .msg file from a string
(source: &str, package: &str, path: &Path)
| 12 | |
| 13 | /// Parse a .msg file from a string |
| 14 | pub fn parse_msg_string(source: &str, package: &str, path: &Path) -> Result<ParsedMessage> { |
| 15 | let name = path |
| 16 | .file_stem() |
| 17 | .context("Invalid filename")? |
| 18 | .to_str() |
| 19 | .context("Non-UTF8 filename")? |
| 20 | .to_string(); |
| 21 | |
| 22 | let mut fields = Vec::new(); |
| 23 | let mut constants = Vec::new(); |
| 24 | |
| 25 | for (line_num, line) in source.lines().enumerate() { |
| 26 | let line = strip_comment(line).trim(); |
| 27 | if line.is_empty() { |
| 28 | continue; |
| 29 | } |
| 30 | |
| 31 | // Check if this is a constant (contains '=' but not bounded string/array like string<=255 or uint8[<=10]) |
| 32 | let is_constant = if let Some(eq_pos) = line.find('=') { |
| 33 | // Check if the '=' is part of '<=' which is used for bounded types |
| 34 | if eq_pos > 0 && line.as_bytes().get(eq_pos - 1) == Some(&b'<') { |
| 35 | // This is a bounded type, not a constant |
| 36 | false |
| 37 | } else { |
| 38 | // Check if there are brackets before the '=' |
| 39 | let before_eq = &line[..eq_pos]; |
| 40 | // If there's an opening bracket without a closing one, the '=' is inside brackets |
| 41 | let open_brackets = before_eq.matches('[').count(); |
| 42 | let close_brackets = before_eq.matches(']').count(); |
| 43 | // It's a constant if brackets are balanced (not inside an array spec) |
| 44 | open_brackets == close_brackets |
| 45 | } |
| 46 | } else { |
| 47 | false |
| 48 | }; |
| 49 | |
| 50 | if is_constant { |
| 51 | match parse_constant(line, line_num) { |
| 52 | Ok(c) if !c.name.is_empty() => constants.push(c), |
| 53 | Ok(_) => {} // Skip constants with empty name |
| 54 | Err(_) => {} // Skip invalid constants |
| 55 | } |
| 56 | } else { |
| 57 | fields.push(parse_field(line, package, line_num)?); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | Ok(ParsedMessage { |
| 62 | name, |
| 63 | package: package.to_string(), |
| 64 | fields, |
| 65 | constants, |
| 66 | source: source.to_string(), |
| 67 | path: path.to_path_buf(), |
| 68 | }) |
| 69 | } |
| 70 | |
| 71 | #[cfg(test)] |