A Gura parser for Rust

Related tags

Parsing rust parser
Overview

Gura Rust parser

CI

IMPORTANT: if you need to use Gura in a more user-friendly way, you have at your disposal Serde Gura which allows you to perform Serialization/Deserialization with ease.

This repository contains the implementation of a Gura (compliant with version 1.0.0) format parser for Rust lang.

Documentation - Cargo

Installation

Add the dependency to your Cargo.toml:

[dependencies]
gura = "0.4.2"

Usage

use gura::{dump, parse, GuraType};

fn main() {
    let gura_string = r##"
# This is a Gura document.
title: "Gura Example"

an_object:
    username: "Stephen"
    pass: "Hawking"

# Line breaks are OK when inside arrays
hosts: [
  "alpha",
  "omega"
]"##;

    // Parse: transforms a Gura string into a dictionary
    let parsed = parse(&gura_string).unwrap();

    // Debug and Display
    // println!("{:#?}", parsed);
    // println!("{}", parsed);

    // Access a specific field
    println!("Title -> {}", parsed["title"]);

    // Iterate over structure
    println!("\nHosts:");
    if let GuraType::Array(hosts) = &parsed["hosts"] {
        for host in hosts.iter() {
            println!("Host -> {}", *host);
        }
    }

    // Dump: transforms a dictionary into a Gura string
    let string_again = dump(&parsed);
    println!("\n+++++ Dump result +++++");
    println!("{}", string_again);
}

Contributing

All kind of contribution is welcome! If you want to contribute just:

  1. Fork this repository.
  2. Create a new branch and introduce there your new changes.
  3. Make a Pull Request!

Or you can join to our community in Discord!

Tests

To run all the tests: cargo test

License

This repository is distributed under the terms of the MIT license.

Comments
  • Use raw string literals

    Use raw string literals

    So there is no need the escape the double quotes inside that string.

    Quoting https://doc.rust-lang.org/reference/tokens.html#raw-string-literals Raw string literals do not process any escapes. They start with the character U+0072 (r), followed by zero or more of the character U+0023 (#) and a U+0022 (double-quote) character. The raw string body can contain any sequence of Unicode characters and is terminated only by another U+0022 (double-quote) character, followed by the same number of U+0023 (#) characters that preceded the opening U+0022 (double-quote) character.

    opened by stappersg 4
  • Fix cargo-clippy warnings

    Fix cargo-clippy warnings

    clippy is a good linter. Ran it an it comes up with roughly 50 warnings. Should be marked as a beginner issue, as almost any of these lints are good to learn rust.

    opened by meltinglava 4
  • accessing fields of structure

    accessing fields of structure

    Summary: Help request a.k.a. missing an example

    How to get content of a gura array of structures into an array of rust structures?

    The rust structure would allow access to each field to the structure.

    Say I have the this code:

    use gura::{parse, GuraType};
    
    fn main() {
        let gura_string = r##"
    # This is a Gura document.
    
    # Array of objects
    tango_singers: [
        user1:
            name: "Carlos"
            surname: "Gardel"
            year_of_birth: 1890,
        user2:
            name: "Aníbal"
            surname: "Troilo"
            year_of_birth: 1914
    ]"##
        .to_string();
    
        // Parse: transforms a Gura string into a dictionary
        let parsed = parse(&gura_string).unwrap();
    
        // // Debug and Display
        // println!("{:#?}", parsed);
        // println!("{}", parsed);
    
        // Iterate over structure
        println!("\nTango singers:");
        if let GuraType::Array(tango_singers) = &parsed["tango_singers"] {
            for i in tango_singers.iter() {
                println!("tango singer -> {}", *i);
            }
        }
    }
    

    What should replace the

                println!("tango singer -> {}", *i);
    

    so that content of i gets copied in a struct?

    opened by stappersg 3
  • Fix clippy lint

    Fix clippy lint

    • This is mostly the result of cargo clippy --all --fix
    • The exceptions are the transformations from s.push_str(&format!(...)) -> write!(s, ...), which clippy would not automate.
    opened by parasyte 2
  • Wish:  check on key present

    Wish: check on key present

    To avoid runtime errors with output like

    thread 'main' panicked at 'IndexMap: key not found', src/main.rs:25:23
    

    is some check on key present needed.

    In case such functionality already exists, please where at https://docs.rs/gura/0.3.4/gura/ I should find it.

    opened by stappersg 2
  • Optional Serde support

    Optional Serde support

    Hey, I really appreciate this project (the format itself and this implementation) :heart: and I plan to use it in one of my personal projects. However as of right now, this library is not as ergonomic as it could be which is why I am currently holding off on using it. Specifically, it lacks integration with serde.

    With Serde support, one could write things like:

    use serde::{Serialize, Deserialize};
    
    #[derive(Serialize, Deserialize, Debug)]
    struct Point { x: i32, y: i32 }
    
    fn main() {
        let point = Point { x: 1, y: 2 };
    
        let serialized = gura::to_string(&point).unwrap();
        let deserialized: Point = gura::from_str(&serialized).unwrap();
    }
    

    That is, without much boilerplate, one can (de-)serialize almost arbitrary structs and enums to/from Gura. The parsing and rendering in the user code gets hidden away by Serde.

    Yet I have to mention that Serde is quite a big dependency. Thus it's advisable to make use of Rust's/Cargo's feature system and allow the user to either opt in or opt out of Serde (depending on your preference as the library author). For prior art, take a look at serde_json.

    Serde is well known in the Rust community and for every major format there exists a crate with Serde support: JSON, XML, YAML, TOML, JSON5, BSON, RON, you name it.

    If I had more time at hand, I would definitely implement this by myself and make a pull request but sadly I do not.

    Thank you for your work!

    opened by fmease 2
  • Fix panic when import paths exist but are not readable

    Fix panic when import paths exist but are not readable

    • Also fixes a potential race condition when the file is deleted after the exists check passes.

    Tested with examples/noaccess.rs:

    // Basic Gura parser usage example
    use gura::parse;
    
    fn main() -> Result<(), String> {
        let gura_string = r##"
    import "examples/noaccess.ura"
    ]"##;
    
        // Parse: transforms a Gura string into a dictionary
        let parsed = parse(gura_string).map_err(|e| e.to_string())?;
    
        println!("Parsed:\n{:?}", parsed);
    
        Ok(())
    }
    

    Create an unreadable file and try it:

    $ touch examples/noaccess.ura
    $ chmod -r examples/noaccess.ura
    $ cargo run --example noaccess
       Compiling gura v0.5.0 (/Users/parasyte/other-projects/gura-rs-parser)
        Finished dev [unoptimized + debuginfo] target(s) in 1.62s
         Running `target/debug/examples/noaccess`
    thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 13, kind: PermissionDenied, message: "Permission denied" }', src/parser.rs:634:63
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    
    opened by parasyte 1
  • Remove check than get to match on get

    Remove check than get to match on get

    We can use a Cow to not allocate to a string when we have this case.

    I know this pattern is common in other languages to check for something and then get it. However in rust if we are interested in the value we can just get it and match the returned Option. It removes double indexing in the map for the case.

    opened by meltinglava 1
  • Move generater functions to statics with lazy_static

    Move generater functions to statics with lazy_static

    qoute from lazy_static docs

    Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

    Which is exactly whats happening here. Also cleaned up use statements.

    opened by meltinglava 1
Owner
Gura Config Lang
Gura configuration language by JWare
Gura Config Lang
Website for Microformats Rust parser (using 'microformats-parser'/'mf2')

Website for Microformats Rust parser (using 'microformats-parser'/'mf2')

Microformats 5 Jul 19, 2022
A native Rust port of Google's robots.txt parser and matcher C++ library.

robotstxt A native Rust port of Google's robots.txt parser and matcher C++ library. Native Rust port, no third-part crate dependency Zero unsafe code

Folyd 72 Dec 11, 2022
Rust parser combinator framework

nom, eating data byte by byte nom is a parser combinators library written in Rust. Its goal is to provide tools to build safe parsers without compromi

Geoffroy Couprie 7.6k Jan 7, 2023
Parsing Expression Grammar (PEG) parser generator for Rust

Parsing Expression Grammars in Rust Documentation | Release Notes rust-peg is a simple yet flexible parser generator that makes it easy to write robus

Kevin Mehall 1.2k Dec 30, 2022
A fast monadic-style parser combinator designed to work on stable Rust.

Chomp Chomp is a fast monadic-style parser combinator library designed to work on stable Rust. It was written as the culmination of the experiments de

Martin Wernstål 228 Oct 31, 2022
A parser combinator library for Rust

combine An implementation of parser combinators for Rust, inspired by the Haskell library Parsec. As in Parsec the parsers are LL(1) by default but th

Markus Westerlind 1.1k Dec 28, 2022
LR(1) parser generator for Rust

LALRPOP LALRPOP is a Rust parser generator framework with usability as its primary goal. You should be able to write compact, DRY, readable grammars.

null 2.4k Jan 7, 2023
A typed parser generator embedded in Rust code for Parsing Expression Grammars

Oak Compiled on the nightly channel of Rust. Use rustup for managing compiler channels. You can download and set up the exact same version of the comp

Pierre Talbot 138 Nov 25, 2022
Rust query string parser with nesting support

What is Queryst? This is a fork of the original, with serde and serde_json updated to 0.9 A query string parsing library for Rust inspired by https://

Stanislav Panferov 67 Nov 16, 2022
Soon to be AsciiDoc parser implemented in rust!

pagliascii "But ASCII Doc, I am Pagliascii" Soon to be AsciiDoc parser implemented in rust! This project is the current implementation of the requeste

Lukas Wirth 49 Dec 11, 2022
PEG parser for YAML written in Rust 🦀

yaml-peg PEG parser (pest) for YAML written in Rust ?? Quick Start ⚡️ # Run cargo run -- --file example_files/test.yaml # Output { "xmas": "true",

Visarut Phusua 4 Sep 17, 2022
This project aims to implement a CSS(less like) parser in rust. Currently the code is targeting the PostCSS AST.

CSS(less like) parser written in rust (WIP) This project aims to implement a CSS(less like) parser in rust. Currently the code is targeting the PostCS

Huang Liuhaoran 21 Aug 23, 2022
MRT/BGP data parser written in Rust.

BGPKIT Parser BGPKIT Parser aims to provides the most ergonomic MRT/BGP message parsing Rust API. BGPKIT Parser has the following features: performant

BGPKIT 46 Dec 19, 2022
This project aims to implement a CSS(less like) parser in rust. Currently the code is targeting the PostCSS AST. Very early stage, do not use in production.

CSS(less like) parser written in rust (WIP) This project aims to implement a CSS(less like) parser in rust. Currently the code is targeting the PostCS

Huang Liuhaoran 21 Aug 23, 2022
A feature-few, no-allocation JSON parser in `no_std` rust.

Small JSON Parser in no_std This library reads and parses JSON strings. Its intended use case is to read a JSON payload once. It does not serialise da

Robert Spencer 18 Nov 29, 2022
Front Matter parser for Rust.

fronma Front Matter parser for Rust. Usage Add this crate as a dependency: [dependencies] fronma = "~0.1" then use fronma::parser::parse to parse text

Ryo Nakamura 6 Nov 19, 2021
A Rust crate for LL(k) parser combinators.

oni-comb-rs (鬼昆布,おにこんぶ) A Rust crate for LL(k) parser combinators. Main project oni-comb-parser-rs Sub projects The following is projects implemented

Junichi Kato 24 Nov 3, 2022
gors is an experimental go toolchain written in rust (parser, compiler).

gors gors is an experimental go toolchain written in rust (parser, compiler). Install Using git This method requires the Rust toolchain to be installe

Aymeric Beaumet 12 Dec 14, 2022
🕑 A personal git log and MacJournal output parser, written in rust.

?? git log and MacJournal export parser A personal project, written in rust. WORK IN PROGRESS; NOT READY This repo consolidates daily activity from tw

Steven Black 4 Aug 17, 2022