Browse Source

Starting to learn Nom using Foamfiles

master
Julio Biason 2 years ago
parent
commit
569136d884
  1. 32
      nomfoamtest/Cargo.lock
  2. 9
      nomfoamtest/Cargo.toml
  3. 73
      nomfoamtest/src/foam.rs
  4. 5
      nomfoamtest/src/main.rs

32
nomfoamtest/Cargo.lock generated

@ -0,0 +1,32 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "memchr"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "nomfoamtest"
version = "0.1.0"
dependencies = [
"nom",
]

9
nomfoamtest/Cargo.toml

@ -0,0 +1,9 @@
[package]
name = "nomfoamtest"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nom = "7.1.3"

73
nomfoamtest/src/foam.rs

@ -0,0 +1,73 @@
//! Foam format parser.
use std::str::FromStr;
use nom::bytes::complete::is_not;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_until;
use nom::IResult;
#[derive(Debug, Clone, PartialEq)]
struct Comment {
comment: String,
}
impl FromStr for Comment {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
comment: s.trim().to_string(),
})
}
}
fn multiline_comment(input: &str) -> IResult<&str, Comment> {
let (input, _) = tag("/*")(input)?;
let (input, content) = take_until("*/")(input)?;
let (input, _) = tag("*/")(input)?;
Ok((input, Comment::from_str(content).unwrap()))
}
fn singleline_comment(input: &str) -> IResult<&str, Comment> {
let (input, _) = tag("//")(input)?;
let (input, content) = is_not("\n\r")(input)?;
Ok((input, Comment::from_str(content).unwrap()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_multiline_comment() {
let text = "/* this is comment */";
let result = multiline_comment(text);
assert_eq!(
result,
Ok((
"",
Comment {
comment: "this is comment".to_string()
}
))
)
}
#[test]
fn test_singleline_comment() {
let text = "// this is comment";
let result = singleline_comment(text);
assert_eq!(
result,
Ok((
"",
Comment {
comment: "this is comment".to_string()
}
))
)
}
}

5
nomfoamtest/src/main.rs

@ -0,0 +1,5 @@
mod foam;
fn main() {
println!("Hello, world!");
}
Loading…
Cancel
Save