Created
October 18, 2019 10:25
-
-
Save ceymard/ecc0bf877e97c3407709e45be5fabda3 to your computer and use it in GitHub Desktop.
zig parsing ideas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn assertGrammarRule(comptime T: type) void { | |
} | |
pub fn ZeroOrMore(comptime T: type) type { | |
assertGrammarRule(T); | |
} | |
pub fn Peek(comptime T: type) type { | |
} | |
/// Returns an optional rule | |
pub fn Opt(comptime T: type) type { | |
} | |
pub fn Either(comptime T: ...) type { | |
// | |
} | |
/// Node is a tagged union | |
pub const Node = union(enum) { | |
Number: *Number, | |
BinOp: *BinOp, | |
pub const Number = struct { | |
n: []const u8 // this will be converted afterwards. | |
}; | |
pub const BinOp = struct { | |
lhs: *Node, | |
op: u8, | |
rhs: *Node | |
}; | |
} | |
pub const Token(comptime def: []const u8) type { | |
return struct { | |
parsed: []const u8, | |
} | |
} | |
pub const Either(comptime args: ...) type { | |
return struct { | |
} | |
} | |
pub const Tk_Number = Token("\\d+") // its result is a string | |
pub fn Number(num: Tk_Number) Node { | |
return Node.Number{.n = num.parsed}; | |
} | |
pub fn ParenthesizedExpression( | |
_1: Token("("), | |
e: Rule(Multiply), | |
_2: Token(")") | |
) Node { | |
return e | |
} | |
pub fn Expression(e: Either(Number, ParenthesizedEpression)) Node { | |
return e | |
} | |
pub fn Add( | |
lhs: Rule(Expression), | |
op: Either("+", "-"), | |
rhs: Rule(Expression) | |
) Node { | |
return Node.BinOp{.lhs = lhs, .op = op.str, .rhs: rhs}; | |
} | |
pub fn Multiply( | |
lhs: Rule(Addition), | |
op: Either("*", "/"), | |
rhs: Rule(Expression) | |
) Node { | |
return Node.BinOp{.lhs = lhs, .op = op.str, .rhs: rhs}; | |
} | |
pub fn TopLevelDecl(n: Either(Expression, Multiply)) Node { | |
return n | |
} | |
pub const parser = generate_parser( | |
allocator, // because some rules will have to instanciate arrays | |
TopLevelDecl, | |
"\\s*" // ignore whitespace | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment