Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example json parser for lalrpop
Browse files Browse the repository at this point in the history
dburgener committed Sep 14, 2023
1 parent 280485c commit f59460d
Showing 5 changed files with 581 additions and 3 deletions.
490 changes: 487 additions & 3 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions examples/lalrpop-app/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "lalrpop-app"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "lalrpop-app"
path = "app.rs"

[build-dependencies]
lalrpop = { version = "0.20", features = ["lexer", "unicode"] }

[dependencies]
lalrpop-util = { version = "0.20", features = ["lexer", "unicode"] }
23 changes: 23 additions & 0 deletions examples/lalrpop-app/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
extern crate lalrpop_util;

use std::env;
use std::fs;

#[rustfmt::skip]
#[allow(clippy::all)]
mod json;

fn main() {
let src = fs::read_to_string(env::args().nth(1).expect("Expected file argument"))
.expect("Failed to read file");

match json::ValueParser::new().parse(&src) {
Ok(json) => {
println!("{:#?}", json);
}
Err(err) => {
eprintln!("{}", err);
std::process::exit(1);
}
}
}
5 changes: 5 additions & 0 deletions examples/lalrpop-app/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
extern crate lalrpop;

fn main() {
lalrpop::process_root().unwrap()
}
52 changes: 52 additions & 0 deletions examples/lalrpop-app/json.lalrpop
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
grammar;

// https://datatracker.ietf.org/doc/html/rfc7159

Object: () = {
"{" Comma<Member> "}"
};

Member: () = {
String ":" Value,
};

pub Value: () = {
Object,
Array,
Number,
String,
"false",
"null",
"true"
};

Array: () = {
"[" Comma<Value> "]"
};

Number: () = {
"-"? Int Frac? Exp?
};

Int: () = {
"0",
r"[1-9][0-9]*"
};

Frac: () = {
r"\.[0-9]+"
};

Exp: () = {
r"[eE][-+]?[0-9]+"
};

String: () = {
r#""[^"]*""#
};

Comma<V>: Vec<V> = {
<v: (<V> ",")*> <e: V?> => {
v.into_iter().chain(e).collect()
}
};

0 comments on commit f59460d

Please sign in to comment.