0

I'm working on a parsing library that converts text into the desired data by declaring the steps and then getting the data.

Is it possible to iteratively create a (flat) tuple that contains all the variables?
(Or if you know a better solution, that'd be good too)

Desired:

Parser::parse(my_string) // returns Parser<()>
.parse_int()             // returns Parser<(i32)>
.parse_string()          // returns Parser<(i32, &str)>
.parse_bool()            // returns Parser<(i32, &str, bool)>
.finish();               // returns Result<(i32, &str, bool), ParseError>

What I can do is nesting deeper and deeper by wrapping the existing value in a tuple. Currently:

Parser::parse(my_string) // returns Parser<()>
.parse_int()             // returns Parser<((), i32)>
.parse_string()          // returns Parser<(((), i32), &str)>
.parse_bool()            // returns Parser<((((), i32), &str), bool)>
.finish();               // returns Result<((((), i32), &str), bool)), ParseError>

Here the parse_int function works somewhat like this:

impl<D> Parser<D> {
    pub fn parse_int(self) -> Parser<(D, i32)> {
        let value = // Parse the int

        return Parser {
            ...
            data: (self.data, value)
        }
    }
}

Of course this nested tuple would be horrible to work with.

Geoxion
  • 448
  • 1
  • 4
  • 14
  • 1
    Kinda, yes. Though it's a bit ugly. But it'd only need to flatten once, so only one specialization is really necessary. – Geoxion Aug 14 '20 at 17:18
  • This kind of predetermined parsed structure certainely has it's uses. However to really take advantage of it, you need to already statically know which values of which type you will parse at what time. Why then build your parsed structure incrementally, and not already determine it when building your parser? – L. Riemer Aug 14 '20 at 17:51
  • @L.Riemer this is for an embedded application. I want the footprint to be as low as possible. – Geoxion Aug 14 '20 at 21:02
  • So you continuously parse more data, and that in significant amounts, over the course of the entire program? Cause that is the only scenario in which that strategy would come with an overhead. And by the way, in that scenario your initial design would ... not make a lot of sense. – L. Riemer Aug 14 '20 at 21:10

0 Answers0