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

Upgrade to snake_case builtins and PNC #27

Merged
merged 12 commits into from
Jan 24, 2025
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
33 changes: 0 additions & 33 deletions .github/workflows/generate-docs.yaml

This file was deleted.

38 changes: 38 additions & 0 deletions .github/workflows/www.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Simple workflow for deploying static content to GitHub Pages
name: Deploy www/ to GH Pages

on:
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false

jobs:
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
# Upload docs/ folder
path: "./www"
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
24 changes: 13 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,30 @@ A simple [Parser Combinator](https://en.wikipedia.org/wiki/Parser_combinator) pa

```roc
color : Parser Utf8 [Red, Green, Blue]
color =
oneOf [
const Red |> skip (string "red"),
const Green |> skip (string "green"),
const Blue |> skip (string "blue"),
]

expect parseStr color "green" == Ok Green
color =
one_of(
[
const(Red) |> skip(string("red")),
const(Green) |> skip(string("green")),
const(Blue) |> skip(string("blue")),
],
)

expect parse_str(color, "green") == Ok(Green)
```

Also includes modules to parse the following formats (with various levels of maturity);
Includes modules to parse the following (with various levels of maturity);
- Utf-8 Strings
- CSV
- XML
- Markdown
- HTTP

## Documentation
## Documentation

See [lukewilliamboswell.github.io/roc-parser/](https://lukewilliamboswell.github.io/roc-parser/)

Locally generate docs using `roc docs package/main.roc`
Locally generate docs using `roc docs package/main.roc`

## Contributing

Expand Down
33 changes: 33 additions & 0 deletions docs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/usr/bin/env bash

# https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -euxo pipefail

# Function to validate version number format (x.y.z)
validate_version() {
if [[ ! $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: Version number must be in format x.y.z (e.g., 0.12.0)"
exit 1
fi
}

# Check if version argument is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <version>"
echo "Example: $0 0.12.0"
exit 1
fi

VERSION=$1

# Validate version number
validate_version "$VERSION"

# Run roc docs with validated version
roc docs --root-dir "/roc-parser/$VERSION/" package/main.roc

# Create new version directory in www/
mkdir www/$VERSION

# Move generated docs to version directory
mv generated-docs/* www/$VERSION
69 changes: 34 additions & 35 deletions examples/csv-movies.roc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
app [main] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.16.0/O00IPk-Krg_diNS2dVWlI0ZQP794Vctxzv0ha96mK0E.tar.br",
app [main!] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.19.0/bi5zubJ-_Hva9vxxPq4kNx4WHX6oFs8OP6Ad0tCYlrY.tar.br",
parser: "../package/main.roc",
}

Expand All @@ -9,7 +9,7 @@ import parser.String
import cli.Stdout
import cli.Stderr

MovieInfo := { title : Str, releaseYear : U64, actors : List Str }
MovieInfo := { title : Str, release_year : U64, actors : List Str }

input : Str
input =
Expand All @@ -18,50 +18,49 @@ input =
Caddyshack,1980,\"Chevy Chase,Rodney Dangerfield,Ted Knight,Michael O'Keefe,Bill Murray\"
"""

main =
when CSV.parseStr movieInfoParser input is
Ok movies ->
moviesString =
main! = |_args|
when CSV.parse_str(movie_info_parser, input) is
Ok(movies) ->
movies_string =
movies
|> List.map movieInfoExplanation
|> Str.joinWith ("\n")
nMovies = List.len movies |> Num.toStr
|> List.map(movie_info_explanation)
|> Str.join_with("\n")

Stdout.line "$(nMovies) movies were found:\n\n$(moviesString)\n\nParse success!\n"
n_movies = List.len(movies) |> Num.to_str

Err problem ->
Stdout.line!("${n_movies} movies were found:\n\n${movies_string}\n\nParse success!\n")

Err(problem) ->
when problem is
ParsingFailure failure ->
Stderr.line "Parsing failure: $(failure)\n"
ParsingFailure(failure) ->
Stderr.line!("Parsing failure: ${failure}\n")

ParsingIncomplete leftover ->
leftoverStr = leftover |> List.map String.strFromUtf8 |> List.map (\val -> "\"$(val)\"") |> Str.joinWith ", "
ParsingIncomplete(leftover) ->
leftover_str = leftover |> List.map(String.str_from_utf8) |> List.map(|val| "\"${val}\"") |> Str.join_with(", ")

Stderr.line "Parsing incomplete. Following leftover fields while parsing a record: $(leftoverStr)\n"
Stderr.line!("Parsing incomplete. Following leftover fields while parsing a record: ${leftover_str}\n")

SyntaxError error ->
Stderr.line "Parsing failure. Syntax error in the CSV: $(error)"
SyntaxError(error) ->
Stderr.line!("Parsing failure. Syntax error in the CSV: ${error}")

movieInfoParser =
CSV.record (\title -> \releaseYear -> \actors -> @MovieInfo { title, releaseYear, actors })
|> P.keep (CSV.field CSV.string)
|> P.keep (CSV.field CSV.u64)
|> P.keep (CSV.field actorsParser)
movie_info_parser =
CSV.record(|title| |release_year| |actors| @MovieInfo({ title, release_year, actors }))
|> P.keep(CSV.field(CSV.string))
|> P.keep(CSV.field(CSV.u64))
|> P.keep(CSV.field(actors_parser))

actorsParser =
CSV.string
|> P.map \val -> Str.splitOn val ","
actors_parser = CSV.string |> P.map(|val| Str.split_on(val, ","))

movieInfoExplanation = \@MovieInfo { title, releaseYear, actors } ->
enumeratedActors = enumerate actors
releaseYearStr = Num.toStr releaseYear
movie_info_explanation = |@MovieInfo({ title, release_year, actors })|
enumerated_actors = enumerate(actors)
release_year_str = Num.to_str(release_year)

"The movie '$(title)' was released in $(releaseYearStr) and stars $(enumeratedActors)"
"The movie '${title}' was released in ${release_year_str} and stars ${enumerated_actors}"

enumerate : List Str -> Str
enumerate = \elements ->
{ before: inits, others: last } = List.splitAt elements (List.len elements - 1)
enumerate = |elements|
{ before: inits, others: last } = List.split_at(elements, (List.len(elements) - 1))

last
|> List.prepend (inits |> Str.joinWith ", ")
|> Str.joinWith " and "
|> List.prepend((inits |> Str.join_with(", ")))
|> Str.join_with(" and ")
64 changes: 33 additions & 31 deletions examples/letters.roc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
app [main] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.16.0/O00IPk-Krg_diNS2dVWlI0ZQP794Vctxzv0ha96mK0E.tar.br",
app [main!] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.19.0/bi5zubJ-_Hva9vxxPq4kNx4WHX6oFs8OP6Ad0tCYlrY.tar.br",
parser: "../package/main.roc",
}

Expand All @@ -8,53 +8,55 @@ import cli.Stderr
import parser.Parser
import parser.String

main =
main! = |_args|

result : Result (List Letter) [ParsingFailure Str, ParsingIncomplete Str]
result = String.parseStr (Parser.many letterParser) "AAAiBByAABBwBtCCCiAyArBBx"
result = String.parse_str(Parser.many(letter_parser), "AAAiBByAABBwBtCCCiAyArBBx")

when result |> Result.map countLetterAs is
Ok count -> Stdout.line "I counted $(Num.toStr count) letter A's!"
Err _ -> Stderr.line "Failed while parsing input"
when result |> Result.map_ok(count_letter_as) is
Ok(count) -> Stdout.line!("I counted ${Num.to_str(count)} letter A's!")
Err(_) -> Stderr.line!("Failed while parsing input")

Letter : [A, B, C, Other]

# Helper to check if a letter is an A tag
isA = \l -> l == A
is_a = |l|
l == A

# Count the number of Letter A's
countLetterAs : List Letter -> U64
countLetterAs = \letters ->
count_letter_as : List Letter -> U64
count_letter_as = |letters|
letters
|> List.keepIf isA
|> List.map \_ -> 1
|> List.keep_if(is_a)
|> List.map(|_| 1)
|> List.sum

# Build a custom parser to convert utf8 input into Letter tags
letterParser : Parser.Parser (List U8) Letter
letterParser = Parser.buildPrimitiveParser \input ->

valResult =
when input is
[] -> Err (ParsingFailure "Nothing to parse")
['A', ..] -> Ok A
['B', ..] -> Ok B
['C', ..] -> Ok C
_ -> Ok Other

valResult
|> Result.map \val -> { val, input: List.dropFirst input 1 }
letter_parser : Parser.Parser (List U8) Letter
letter_parser = Parser.build_primitive_parser(
|input|
val_result =
when input is
[] -> Err(ParsingFailure("Nothing to parse"))
['A', ..] -> Ok(A)
['B', ..] -> Ok(B)
['C', ..] -> Ok(C)
_ -> Ok(Other)

val_result
|> Result.map_ok(|val| { val, input: List.drop_first(input, 1) }),
)

# Test we can parse a single B letter
expect
input = "B"
parser = letterParser
result = String.parseStr parser input
result == Ok B
parser = letter_parser
result = String.parse_str(parser, input)
result == Ok(B)

# Test we can parse a number of different letters
expect
input = "BCXA"
parser = Parser.many letterParser
result = String.parseStr parser input
result == Ok [B, C, Other, A]
parser = Parser.many(letter_parser)
result = String.parse_str(parser, input)
result == Ok([B, C, Other, A])
41 changes: 26 additions & 15 deletions examples/markdown.roc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
app [main] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.16.0/O00IPk-Krg_diNS2dVWlI0ZQP794Vctxzv0ha96mK0E.tar.br",
app [main!] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.19.0/bi5zubJ-_Hva9vxxPq4kNx4WHX6oFs8OP6Ad0tCYlrY.tar.br",
parser: "../package/main.roc",
}

Expand All @@ -24,18 +24,29 @@ content =
```
"""

main =
String.parseStr Markdown.all content
|> Result.map \nodes -> renderContent "" nodes
|> Result.withDefault "PARSING ERROR"
|> Stdout.line
main! = |_args|
String.parse_str(Markdown.all, content)
|> Result.map_ok(|nodes| render_content(nodes, ""))
|> Result.with_default("PARSING ERROR")
|> Stdout.line!

renderContent : Str, List Markdown.Markdown -> Str
renderContent = \acc, nodes ->
render_content : List Markdown.Markdown, Str -> Str
render_content = |nodes, buf|
when nodes is
[] -> acc
[Heading level str, .. as rest] -> Str.concat acc "HEADING: $(Inspect.toStr level) $(str)\n" |> renderContent rest
[Link { alt, href }, .. as rest] -> Str.concat acc "LINK: $(Inspect.toStr { alt, href })\n" |> renderContent rest
[Image { alt, href }, .. as rest] -> Str.concat acc "IMAGE: $(Inspect.toStr { alt, href })\n" |> renderContent rest
[Code { ext, pre }, .. as rest] -> Str.concat acc "CODE: $(Inspect.toStr { ext, pre })\n" |> renderContent rest
[TODO line, .. as rest] -> Str.concat acc "TODO: $(line)\n" |> renderContent rest
[] ->
buf # base case

[Heading(level, str), .. as rest] ->
render_content(rest, Str.concat(buf, "HEADING: ${Inspect.to_str(level)} ${str}\n"))

[Link({ alt, href }), .. as rest] ->
render_content(rest, Str.concat(buf, "LINK: ${Inspect.to_str({ alt, href })}\n"))

[Image({ alt, href }), .. as rest] ->
render_content(rest, Str.concat(buf, "IMAGE: ${Inspect.to_str({ alt, href })}\n"))

[Code({ ext, pre }), .. as rest] ->
render_content(rest, Str.concat(buf, "CODE: ${Inspect.to_str({ ext, pre })}\n"))

[TODO(line), .. as rest] ->
render_content(rest, Str.concat(buf, "TODO: ${line}\n"))
Loading