Hejsil / mecha

A parser combinator library for Zig
MIT License
453 stars 20 forks source link

How to parse string literals? #38

Closed notramo closed 2 years ago

notramo commented 2 years ago

Is this library capable of parsing string literals? I'm interested in parsing two type of strings: double quote: "this can be anything inside, except double quote" slash: // this is a comment, until the end of the line

I guess some parser is needed that reads everything until a specified parser succeeds. E.g.

var StringLiteral = mecha.readUntil(
  mecha.string("\n");
);
// or maybe
var StringLiteral = mecha.combine(.{
  mecha.string("//"),
  mecha.matchAnyChar,
  mecha.string("\n")
})
Hejsil commented 2 years ago

How about

var StringLiteral = mecha.combine(.{
  mecha.string("//"),
  mecha.many(mecha.ascii.not('\n'), .{ .collect = false }),
  mecha.string("\n"),
})
notramo commented 2 years ago

I had to modify it, because the mecha.ascii.not() function accepts a parser instead of u8, but othervise this solution is sufficient.

var StringLiteral = mecha.combine(.{
  mecha.string("//"),
  mecha.many(mecha.ascii.not(mecha.string("\n")), .{ .collect = false }),
  mecha.string("\n"),
})

Thank you!