Skip to content

Commit

Permalink
Readme
Browse files Browse the repository at this point in the history
  • Loading branch information
barsdeveloper committed Dec 15, 2023
1 parent 6e71085 commit da1c643
Show file tree
Hide file tree
Showing 3 changed files with 169 additions and 12 deletions.
144 changes: 142 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,142 @@
# parser-nostrum
Tiny LL parser written in model JS
# Parsernostrum

Parsernostrum is a small LL parsing combinator library for JavaScript, designed to be very simple leveraging modern JavaScript features and keeping code size to a minimum, particularly usefull in frontend contexts. It offers a set of tools to create robust and maintainable parsers with very little code.

## Getting started

```sh
npm install parsernostrum
```

Import Parsernostrum and use it to create custom parsers tailored to your specific parsing needs.

```JavaScript
import P from "parsernostrum"
```

Then you have access to the following tools:

### `str(string)`
Parses exact string literals.
```JavaScript
regexp(regexp, group)
```

### `regexp(regexp)`
Parses a regular expression and possibly returns a captured group.
```JavaScript
P.regexp(/\d+/)
```

### `regexpGroups(regexp)`
Parses a regular expression returns all its captured groups exactly as returned by the `RegExp.exec()` method.
```JavaScript
P.regexpGroups(/begin\s*(\w*)\s*(\w*)\s*end/)
```

### `seq(...parsers)`
Combines parsers sequentially.
```JavaScript
P.seq(P.str("hello"), P.str("world"))
```

### `alt(...parsers)`
Offers alternative parsers succeeds if any parser matches.
```JavaScript
P.alt(P.str("yes"), P.str("no"))
```

### `lookahead(parser)`
Checks what's ahead in the string without consuming it.
```JavaScript
P.lookahead(P.str("hello"))
```

### `lazy(parser)`
Delays parser evaluation, useful for recursive parsers.
```JavaScript
const matcheParentheses = P.seq(
P.str("("),
P.alt(
P.lazy(() => matcheParentheses),
P.regexp(/\w*/),
),
P.str(")"),
)
```
[!WARNING]
LL parsers do not generally support left recursion. It is therefore important that your recursive parsers always have an actual parser as the first element (in this case P.str("("))). Otherwise the code will result in a runtime infinite recursion exception.
In general it is always possible to rewrite a grammar to remove left recursion.

### `.times(min, max)`
Matches a parser a specified number of times.
```JavaScript
myParser.times(3) // expect to have exactly three occurrences
myParser.times(1, 2) // expect to have one or two occurrences
```

### `.many()`
Matches a parser zero or more times.
```JavaScript
myParser.many()
```

### `.atLeast(n)`
Ensures a parser matches at least `n` times.
```JavaScript
myParser.atLeast(2)
```

### `.atMost(n)`
Limits a parser match to at most `n` times.
```JavaScript
myParser.atMost(5)
```

### `.opt()`
Makes a parser optional.
```JavaScript
myParser.opt()
```

### `.sepBy(separator)`
Parses a list of elements separated by a given separator.
```JavaScript
myParser.sepBy(P.regexp(/\s*,\s*/))
```

### `.skipSpace()`
Consumes whitespace following the match of myParser and returns what myParser produced.
```JavaScript
myParser.skipSpace()
```

### `.map(fn)`
Applies a function to transform the parser's result.
```JavaScript
myParser.map(n => `Number: ${n}`)
```

### `.chain(fn)`
Chains the output of one parser to another.
```JavaScript
const p = P.regexp(/[([{]/).chain(v => (
{
"(": P.str(")"),
"[": P.str("]"),
"{": P.str("}"),
}[v].map(closingParenthesis => v + closingParenthesis)
))
```

### `.assert(fn)`
Asserts a condition on the parsed result. If the method returns false, the parser is considered failed even though the actual parser matched the input.
```JavaScript
P.numberNatural.assert(n => n % 2 == 0) // Will even numbers only
```

### `.join(value)`
Joins the results of a parser into a single string.
```JavaScript
myParser.join(", ")
```
17 changes: 17 additions & 0 deletions tests/advanced.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { test, expect } from "@playwright/test"
import httpServer from "http-server"
import JsonGrammar from "../src/grammars/JsonGrammar.js"
import MathGrammar from "../src/grammars/MathGrammar.js"
import P from "../src/Parsernostrum.js"
import sample1 from "./sample1.js"
import sample2 from "./sample2.js"

Expand All @@ -19,6 +20,22 @@ test.afterAll(async () => {
webserver.close()
})

test("Matched parentheses", async ({ page }) => {
/** @type {P<any>} */
const matcheParentheses = P.seq(
P.str("("),
P.alt(
P.lazy(() => matcheParentheses),
P.regexp(/\w*/),
),
P.str(")"),
)
expect(matcheParentheses.parse("()")).toBeTruthy()
expect(matcheParentheses.parse("(a)")).toBeTruthy()
expect(matcheParentheses.parse("(((((b)))))")).toBeTruthy()
expect(() => matcheParentheses.parse("(()")).toThrow()
})

test("Arithmetic", async ({ page }) => {
const expression = MathGrammar.expression
expect(expression.parse("1")).toEqual(1)
Expand Down
20 changes: 10 additions & 10 deletions tests/simple.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,16 +212,16 @@ test("Join", async ({ page }) => {
})

test("Chain", async ({ page }) => {
const p = P.regexp(/\w+ /).chain(v => {
switch (v) {
case "first ": return P.str("second")
case "alpha ": return P.str("beta")
case "a ": return P.str("b")
}
})
expect(p.parse("first second")).toEqual("second")
expect(p.parse("alpha beta")).toEqual("beta")
expect(p.parse("a b")).toEqual("b")
const p = P.regexp(/[([{]/).chain(v => (
{
"(": P.str(")"),
"[": P.str("]"),
"{": P.str("}"),
}[v].map(closingParenthesis => v + closingParenthesis)
))
expect(p.parse("()")).toEqual("()")
expect(p.parse("[]")).toEqual("[]")
expect(p.parse("{}")).toEqual("{}")
expect(() => p.parse("hello")).toThrowError()
})

Expand Down

0 comments on commit da1c643

Please sign in to comment.