Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds empty symbols, fixes #2 #18

Merged
merged 6 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ wasm-bindgen = { version = "0.2.83", optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
colored = { version = "2.1" }

[dev-dependencies]
[target.'cfg(target_family = "wasm")'.dev-dependencies]
wasm-bindgen-test = { version = "0.3.36" }

[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }

[features]
Expand Down
306 changes: 248 additions & 58 deletions README.md

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions assets/grammars/correct/g9.lr
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
P -> E

E -> T Ep

Ep -> '+' T Ep
Ep -> ''

T -> F Tp

Tp -> '*' F Tp
Tp -> ''

F -> '(' E ')'
F -> %int

%int -> /[0-9]+/
4 changes: 4 additions & 0 deletions assets/grammars/correct/optional.lr
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
P -> O 'x' O 'z'

O -> 'y'
O -> ''
15 changes: 12 additions & 3 deletions bindings/typescript/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@ import fs from "fs/promises";

async function init() {
console.log("Starting build...");
await fs
.unlink("./src/pkg/dotlr_bg.wasm.d.ts")
.catch(() => console.warn("No dotlr_bg.wasm.d.ts found"));
execSync("tsc", { stdio: "inherit" });
await fs.cp("./src/pkg", "./dist/pkg", { recursive: true });
await fs.unlink("./dist/pkg/package.json");
await fs.unlink("./dist/pkg/README.md");
await fs.unlink("./dist/pkg/.gitignore");
await fs
.unlink("./dist/pkg/package.json")
.catch(() => console.warn("No package.json found"));
await fs
.unlink("./dist/pkg/README.md")
.catch(() => console.warn("No README.md found"));
await fs
.unlink("./dist/pkg/.gitignore")
.catch(() => console.warn("No .gitignore found"));
console.log("Build complete");
}

Expand Down
6 changes: 4 additions & 2 deletions bindings/typescript/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export type Token<C = string, R = string> = {
value: R
} | {
type: 'Eof'
} | {
type: 'Empty'
}

//prettier-ignore
Expand Down Expand Up @@ -153,14 +155,14 @@ export type Action = {
}
export type Span = {
offset: number;
len: number;
length: number;
column: number;
line: number;
};

export type Spanned<T> = {
span: Span;
value: T;
object: T;
};

export type FirstTable<T extends Token = Token> = Map<string, T[]>;
Expand Down
3 changes: 2 additions & 1 deletion bindings/typescript/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {

export function stringifyToken(token: Token, noApostrophes = false) {
if (token.type === "Eof") return "$";
if (token.type === "Empty") return "ε";
if (token.type === "Regex") return `%${token.value}`;
if (token.type === "Constant")
return noApostrophes ? token.value : `'${token.value}'`;
Expand Down Expand Up @@ -86,7 +87,7 @@ export function stringifyTree(

if (tree.type === "Terminal") {
const { token, slice } = tree.value;
if (token.type !== "Eof") {
if (token.type !== "Eof" && token.type !== "Empty") {
result += `${indent}${linePrefix}${token.value} [${slice}]\n`;
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion examples/calculator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn evaluate(tree: Tree<'_>) -> f64 {
_ => unreachable!(),
}
},
Token::Constant(_) | Token::Eof => {
Token::Constant(_) | Token::Eof | Token::Empty => {
unreachable!();
},
}
Expand Down
2 changes: 1 addition & 1 deletion examples/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl From<Tree<'_>> for Value {
_ => unreachable!(),
}
},
Token::Eof => {
Token::Eof | Token::Empty => {
unreachable!();
},
}
Expand Down
9 changes: 4 additions & 5 deletions src/automaton.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::prelude::*;


/// Item of a state of an LR(1) automaton.
/// Item of a state of an LR(1) or an LALR(1) automaton.
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -60,7 +60,7 @@ impl Display for Item {
}


/// State of an LR(1) automaton.
/// State of an LR(1) or an LALR(1) automaton.
#[derive(Clone, Debug, Default, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
Expand Down Expand Up @@ -159,7 +159,7 @@ impl State {
fn compute_transitions(&self, state_counter: &mut usize) -> Vec<(AtomicPattern, State)> {
let mut transitions = IndexMap::<AtomicPattern, State>::new();
for item in self.items.iter() {
if item.dot == item.rule.pattern().len() {
if item.dot == item.rule.pattern().len() || item.rule().is_empty_pattern() {
continue;
}

Expand All @@ -184,7 +184,7 @@ impl PartialEq for State {
}


/// LR(1) automaton of a grammar.
/// LR(1) or LALR(1) automaton of a grammar.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
Expand Down Expand Up @@ -256,7 +256,6 @@ impl Automaton {
*transition_target = *transition_map.get(transition_target).unwrap();
}
}

Automaton { states: final_states }
}
}
Expand Down
66 changes: 35 additions & 31 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,37 +84,6 @@ pub enum ParserError {
Conflict { parser: Box<Parser>, state: usize, token: Token },
}

#[cfg(feature = "wasm")]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct WasmParserError {
error: ParserError,
}

#[cfg(feature = "wasm")]
impl WasmParserError {
pub fn new(error: ParserError) -> Self {
WasmParserError { error }
}
}

#[cfg(feature = "wasm")]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl WasmParserError {
pub fn to_string_wasm(&self) -> String {
format!("{}", self.error)
}
pub fn serialize(&self) -> Result<JsValue, JsValue> {
serde_wasm_bindgen::to_value(&self.error).map_err(JsValue::from)
}
pub fn into_conflict_parser(self) -> Result<Parser, JsValue> {
match self.error {
//&Box<Parser>
ParserError::Conflict { parser, .. } => Ok(*parser),
_ => Err(JsValue::from("Error is not a conflict")),
}
}
}


/// Parsing error of an input tried to be parsed with a parser.
#[cfg_attr(feature = "serde", derive(Serialize))]
Expand Down Expand Up @@ -161,3 +130,38 @@ pub enum ParsingError {
)]
UnexpectedEof { expected: SmallVec<[Token; 2]>, span: Span },
}


/// Parser error of a parser tried to be constructed from a grammar (WASM).
#[cfg(feature = "wasm")]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct WasmParserError(ParserError);

#[cfg(feature = "wasm")]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl WasmParserError {
/// Prints the parser error to a string.
pub fn to_string_wasm(&self) -> String {
format!("{}", self.0)
}

/// Serializes the parser error to a JavaScript value.
pub fn serialize(&self) -> Result<JsValue, JsValue> {
serde_wasm_bindgen::to_value(&self.0).map_err(JsValue::from)
}

/// Converts the parser error to the conflicted parser if error was a conflict error.
pub fn into_conflict_parser(self) -> Result<Parser, JsValue> {
match self.0 {
ParserError::Conflict { parser, .. } => Ok(*parser),
_ => Err(JsValue::from("ParserError is not a `Conflict` error")),
}
}
}

#[cfg(feature = "wasm")]
impl From<ParserError> for WasmParserError {
fn from(error: ParserError) -> WasmParserError {
WasmParserError(error)
}
}
Loading
Loading