Skip to content

Commit

Permalink
chore: update README
Browse files Browse the repository at this point in the history
  • Loading branch information
norskeld committed Nov 28, 2021
1 parent 2c41ea5 commit f8620b5
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ Below is an example of parsing nested tuples like `(1, 2, (3, 4))` into an AST.
<summary>Click to show the tuples example.</summary>

```ts
import { choice, defer, list, map, opt, regexp, string, tmid } from '@nrsk/sigma/combinators'
import { map, sequence, choice, sepBy, takeMid } from '@nrsk/sigma/combinators'
import { defer, integer, string, wsOpt } from '@nrsk/sigma/parsers'
import { run } from '@nrsk/sigma'

/* AST. */
Expand All @@ -46,10 +47,10 @@ interface ListNode {

/* Mapping functions to turn parsed string values into AST nodes. */

function toNumber(value: string): NumberNode {
function toNumber(value: number): NumberNode {
return {
type: 'number',
value: +value
value
}
}

Expand All @@ -63,38 +64,38 @@ function toList(value: Array<NumberNode | ListNode>): ListNode {
/* Parsers. */

// Non-Terminals.
const Space = regexp(/\s+/g, 'whitespace')
const Integer = regexp(/\d+/g, 'integer')
const Space = wsOpt()
const Integer = integer()

// Terminals.
const OperParen = string('(')
const CloseParen = string(')')
const Comma = tmid(opt(Space), string(','), opt(Space))
const Comma = sequence(Space, string(','), Space)

// Composites. Deferred initialization allows us to use recursion and mutual calls between parsers.
const TupleNumber = defer<NumberNode>()
const TupleElement = defer<NumberNode | ListNode>()
const TupleNumber = defer<NumberNode>()
const TupleList = defer<ListNode>()

TupleNumber.with(
map(
Integer,
toNumber
)
)

TupleElement.with(
choice(
TupleList,
TupleNumber
)
)

TupleNumber.with(
map(
Integer,
toNumber
)
)

TupleList.with(
map(
tmid(
takeMid(
OperParen,
list(TupleElement, Comma),
sepBy(TupleElement, Comma),
CloseParen
),
toList
Expand Down

0 comments on commit f8620b5

Please sign in to comment.