13 ms·
Zig, parser combinators, and why they're awesome
- unwind 6y agoMeta: the final word in the target page's title ("awesome") is missing from the submission title. It becomes a little hard to
- smoldesu 6y agoAt first I didn't understand, but now I think I get
- agumonkey 6y agoread it ps: people, it wasn't an order, just a metacomment about pruned suffixes
- Jtsummers 6y agoWhenever you make a submission, always check the title. The automatic title editing from HN often makes sense, but not always.
- dang 6y agoWe've made the title awesome again.
- dilap 6y agoI'm confused about "callconv(.Inline)" on the function pointer. Isn't a function pointer not inlinable by its very nature?
- FnControlOption 6y agoI haven't dug into this yet, but the table of contents appears to be broken.
- slimsag 6y agoAuthor here, looks like I messed up one of the links by accident. Should be fixed now :)
- ncmncm 6y agoZig is more capable than I thought. It looks like there are definite plans to make it moreso, and more interesting.
- kristoff_it 6y agoThe "more ergonomic C" crowd is missing some important nuance.
- andrepd 6y agoYep. It can be "C but good" or it can be "a language with all these fancy features". It can't be both at the same time.
- dralley 6y agoZig is pretty close to being both at once, simply because they've found clever ways of combining existing features to avoid needing entirely separate features to accomplish the same goals. e.g. They avoid the macro system by leaning hard on compile-time evaluation, leveraging dead code elimination to replace preprocessor/macro-driven conditional compilation. They get generics in a similar way, by letting compile-time functions construct types. Varargs are implemented with anonymous structs, and modules are also secretly just structs, which makes interop with C much simpler. It's actually deeply impressive how far they've been able to go with a language that actually has quite a small number of separate constructs, and it doesn't feel hobbled by doing so.
- socialdemocrat 6y agoThis is all about creating orthogonal features. In any system where you are able to create a small number of features which combine in very flexible ways you can achieve a minimalist language together with immense expressiveness. Zig is in that category. It takes some powerful ideas and combine them in ways that gives Zig a lot of power despite a small feature set.
- johnnycerberus 6y ago
- kristoff_it 6y agoAnother interesting parser combinator written in Zig is Mecha. https://github.com/Hejsil/mecha https://github.com/Hejsil/mecha
- slimsag 6y ago(author here) Mecha looks really nice! One difference that makes Mecha's look really nice/simple is they are being built at compile time, whereas the ones I outline in this blog post are being built at runtime (with the intention of later building parsers at runtime _based on other parsers output_. Or, at least that's what I gleaned from a quick skim of Mecha. Very excited to play around with it soon!
- kristoff_it 6y agoYou got it right! I think it's nice to be able to contrast the two implementations :)
- breck 6y agoI absolutely love parser combinators, and years ago I did a huge rewrite of my compiler compiler so that it'd have the easiest possible parser combinators: simple string concatenation. grammarA + grammarB = grammarC. You can play with that here (https://jtree.treenotation.org/designer/ https://jtree.treenotation.org/designer/). You still need to make a line change or two (good design after all, requires some integration), but it just works. Haven't seen anything beat it and not sure if that's possible. (Note: I do apologize for the crappy UX, and it's high on the priority list to give the app a refresh)
- adsweedler 6y agoAwesome app. Do you plan on using it for anything in particular? Or are you just creating it as a passion project. It's totally cool. *** Learning about https://treenotation.org/ https://treenotation.org/ (linking this for other people, not for you, Breck :P), and I like what I see. My first impression was: "tree notation is like lisp, but with python indenting". But then looking at it more and I see it's much more like YAML or CSV or whatever. But then I read: > We no longer need to store our data in error prone CSV, XML, or JSON. Tree Notation gives us a simpler, more powerful encoding for data with lots of new advanced features And I didn't understand! Tree notation seems equivalent to these. Like at a certain level, it's all just data. Now, the major benefit is that you're supposed to think differently about what you're doing when using tree notation. Would love to hear your opinion about this conjecture. *** Not getting into the beautiful and amazing work that's been done WITH tree notation (yet), that's a whole other conversation!
- breck 6y ago> Do you plan on using it for anything in particular? It's hard to believe, but I use that thing everyday, haha. To me every problem is a nail solvable with my DSL hammer. > are you just creating it as a passion project. I want other people to use it, but it took a while for me to be truly confident that it will work and the underlying math is sound (that 2-d languages are better than 1-d langs). So just in the past week formed a corporation (https://publicdomaincompany.com/ https://publicdomaincompany.com/) and growing the team and are actually going to try and make a good user experience and help people use these technologies to solve their problems. > Would love to hear your opinion about this conjecture. I always think of code now in 2 and 3 dimensions. To me after many years this is just second nature but it's not an obvious thing and not sure I've ever met anyone else that does this. I gave an early talk about it in 2017 (https://www.youtube.com/watch?v=ldVtDlbOUMA https://www.youtube.com/watch?v=ldVtDlbOUMA) at ForwardJS (there should be an actual recording out there on the web somewhere but I can't find it). Traditionally all programming languages are 1-D, read by a single read head that moves linearly from start to finish (with some backtracking, but always just along 1 axis in order), building up an AST and then going from there. There's no reason it has to be that way, it's just the way things developed with our 1-D register machines. Human beings do not process language this way at all. Not even close. If you have a physical newspaper by you, pick it up and pay attention to the way your eyes parse things. You'll likely notice a random access pattern, with your eyes moving constantly across both the x and y axis, and you parsing the semantics by things like position, font size, layout, etc. To me it's so obvious that this is the way computer languages should work. Their shouldn't be lots of physical transformations of the code, using cryptic syntax characters like ( and " and [ and { as hacks to provide instructions to the parser. Code should be written in accordance with a strict grammar, yes, but it should also be written in way pleasing to the human eye and the way human brains work. We should make human languages that machines can understand instead of making machine languages that humans can understand. Anyway, I'm rambling on and on, but this is the bigger idea than simply the tree notation implementation, which is really just a subset of a whole new world of possibilities in 2d and 3d languages. (here's another recent one showcasing the new possibilities: https://www.youtube.com/watch?t=145&v=vn2aJA5ANUc&feature=youtu.be https://www.youtube.com/watch?t=145&v=vn2aJA5ANUc&feature=yo... — when I write Tree Code I see spreadsheets and vice versa) Also, when I play with legos now I see code, and when I write code I see legos. That's a hard thing to communicate and an early tool I wrote called Ohayo shows it off a bit, but need to write a single function that takes a tree program and spits out a lego vis (something like LDraw), and maybe that will help explain the idea https://github.com/treenotation/research/issues/33 https://github.com/treenotation/research/issues/33
- lhorie 6y agoInteresting read, especially as someone poking w/ writing a parser in zig for fun :) One area of improvement worth mentioning in this area is that currently zig errors cannot be tagged with extra information, which tends to be important for surfacing things like line numbers in parsing errors. There was a proposal[0] to improve this and it's not the end of the world for me anyways (as a workaround, I'm toying with returning error tokens similar to what treesitter does) On a different note, there's another cool zig thing I found recently that is mildly related to parsing: a common thing in parsers is mapping a parsed string to some pre-specified token type (e.g. the string `"if"` maps to an enum value `.if` or some such so you can later pattern match tokens efficiently). The normal way to avoid O(n) linear search over the keyword space is to use a hashmap (naively, one would use a runtime std.StringHashMap in zig). But I found an article from Andrew[0] about a comptime hashmap where a perfect hashing strategy is computed at comptime since we already know the search space ahead of time! Really neat stuff. [0] https://github.com/ziglang/zig/issues/2647 https://github.com/ziglang/zig/issues/2647 [1] https://andrewkelley.me/post/string-matching-comptime-perfect-hashing-zig.html https://andrewkelley.me/post/string-matching-comptime-perfec...
- slimsag 6y agoSuper interesting, thanks for sharing! I'd be curious to learn more about how you workaround the lack of extra info in error types in practice? Are you just returning e.g. a struct with additional info?
- lhorie 6y agoYes, e.g. `const Token = struct { kind: Kind, otherStuff: ... }`, where Kind is an enum where one of the values is Kind.error. Then since switch is exhaustive, you can just pattern match on kind as you iterate over tokens to handle the error case at whatever syntactic context is most appropriate. The nice side-effect about this approach is that rather than following the standard error flow of bailing early and unwinding stack, you can keep parsing and collecting errors as you go.
- eperdew 6y ago
- Koshkin 6y agoSo... why are they awesome, again? Is this some kind of functional approach to parsing? (I know that functions compose very well.)
- amir734jj 6y agoThe only parser combinator experience I have is with FParsec in F# and Haskell parsec. I am not sure if non (purely) functional programming language is suitable for parser combinators. Yes, it works but why?
- slimsag 6y agoPerformance. I'm looking to try implementing a regexp-like engine via a runtime parser generator built using parser combinators and _hoping_ to get performance near what optimized regex engines get. Seems like an interesting way to get nice, performant template parsing without having the performance overhead that higher level languages typically bring. This is all speculative, though - I haven't actually done it yet, so maybe I'll find its incredibly slow and a bad idea :)
- eperdew 6y agoI'm not sure if this is done in practice, but in theory, if you compile a regex to a DFA, you can then minimize the DFA. I don't know if you can do anything similar with parser combinators, but if not, that could be a potential performance gap to watch out for.
- slimsag 6y agoI imagine this works for regex engines like RE2 that don't support backtracking, but would not be possible if supporting more advanced regex features like backtracking? I definitely have more to learn about automata and FSMs :)
- burntsushi 6y agoHi again. :-) In practice, production grade general purpose regex engines are never implemented with formal DFAs in all cases. They take too long to build and use way too much memory, especially when Unicode is involved. For example: $ regex-cli debug dfa dense '(?-u)\w{10}' -qm parse time: 45.418µs translate time: 14.626µs compile nfa time: 373.919µs compile dense dfa time: 564.7µs dense dfa memory: 5436 dense alphabet length: 23 dense stride: 32 $ regex-cli debug dfa dense '\w{10}' -qm parse time: 41.344µs translate time: 27.072µs compile nfa time: 6.360692ms compile dense dfa time: 1.038092145s dense dfa memory: 2998332 dense alphabet length: 115 dense stride: 128 And this is including oodles of tricks for shrink the DFA's size. (Note though that the above examples minimize the DFA, which adds significant time. Without minimization, the latter is about an order of magnitude faster.) So even this simple regex is 3MB in size. Finally, DFAs can grow exponentially in the size of the regex, which means you can't really use them with untrusted regexes. In practice, regex engines like RE2 use a hybrid NFA/DFA, or "lazy DFA." The DFA is computed at search time and cached. If too much cache is used, then the regex engine falls back to an NFA simulation. Beating the performance of a DFA without going into more exotic things like vectorized algorithms or more specialized regex engines (bit-parallel NFAs) is pretty tricky. And also, do not repeat the same mistake that the OP seems to make: conflating what DFA and NFA mean. A lot of people like to call things like PCRE an "NFA" implementation, but it's not, because meaningfully more powerful than what an NFA can do. General purpose regex engines tend to be split between ones that are based on finite automata and ones that are based on backtracking.
- olah_1 6y agoI wish someone would teach low level programming from scratch with Zig
- thdn 6y agox2
- AnIdiotOnTheNet 6y agoCan you clarify what "low level" means to you?
- olah_1 6y agoCode that manages and manipulates memory, network stuff, GUI. Basically anything more intensive than client-side JavaScript
- Jakobeha 6y agoI see a lot of articles posted on HN about Zig. What's so special about Zig, and how does it fill its own niche with other languages like Go and Rust?
- abnercoimbre 6y agoIf you can spare 60-90 minutes, I hosted [0] a conversation with the creator of Zig, as well as Odin, plus a former co-worker who's a compiler engineer. They're all vibing in the same space that try to fill the niche we believe is missing. [0] https://media.handmade-seattle.com/the-race-to-replace-c-and-cpp/ https://media.handmade-seattle.com/the-race-to-replace-c-and...
- kristoff_it 6y agoThat's a great window on programming languages that exist in the systems programming space but that are not Rust, C or C++.
- tiddles 6y agoThank you for doing this! I've listened to this and a few other episodes with Andrew and Ginger Bill, and they're very interesting, I highly recommend them.
- gameswithgo 6y agoAs a rough high level overview: Rust is what you might imagine if starting over from scratch with C++, with a big emphasis on memory and type safety. Zig is more like starting over from scratch with C, with a moderate emphasis on safety (no garbage collection or borrow checker, but undefined behavior handled more sanely than C)
- k__ 6y agoI had the impression Rust was more compatible with C than C++.
- 6y ago
- z92 6y agoChecked Zig. Doesn't have a memory manager. It's "free all at program termination" or manually manage memory like C.
- anderspitman 6y agoIt does have some nice improvements over C though, such as defer-style deallocation, which can help with many potential bugs.
- socialdemocrat 6y agoIt is much better structured than C. Everything in the standard library that allocated memory takes an allocator as first argument. And you got cleanup with defer statements. Together this makes the memory management story very different from C.
- preommr 6y agoIs Zig the new cool kid on the block?
- txdv 6y agothe coolest
- socialdemocrat 6y agoIt is! Almost as cool as Julia ;-) There are some pretty cool ideas in there, which I think are worth getting familiar with even if you never end up using Zig at all. I suspect some of the ideas will get copied by other languages.
- linkdd 6y agoOne of the best thing about parser combinators is that I was writing them before knowing what it was. My first programming language being C[1], all you had was functions and composition, it's the natural pattern to write parsers. [1] - Well, in truth it was GML from Game Maker 6, but I quickly went to learn C :p
- 127 6y agoUnfortunately, the library story is quite limited, so for me this doesn't really justify spending more than a day looking into. Currently using Nim, which has better library support. Maybe it's possible to cross-compile Nim/Zig libraries? Also, it's quite difficult to find pure C libs, seems everything is C++ at some level.
- socialdemocrat 6y agoGuess it depends on what you want to do. I imagined I'd might use it for small Unix tools, simple 2D games, micro-controller stuff, maybe simple compilers. But I get your point. Would be nice with the kind of selection you find in the Go standard library. But then again they don't have Google resources.
- mtzet 6y agoWhile having nice libraries is always great, I'd also like to plug the simple zig std library functions. I was very pleasantly surprised by how easy was to start parsing simple stuff using std.mem.tokenize() and std.mem.split(). Somehow watching Andrew programming some Advent of Code using these very simple functions made it 'click' for me how parsers are just ordinary programs.
- vanderZwan 6y agoI was already slightly familiar with parser combinators but still really enjoyed this article to see how one might implement them in Zig, which I've looked at but not written anything in myself. For another introduction to parser combinators, I can recommend the Parser Combinators From Scratch series on the Low-Level JavaScript YouTube channel. In general he has a lot of really nice videos that are great introductions to low-level programming concepts, especially for people who mainly know JavaScript. [0] https://www.youtube.com/playlist?list=PLP29wDx6QmW5yfO1LAgO8kU3aQEj8SIrU https://www.youtube.com/playlist?list=PLP29wDx6QmW5yfO1LAgO8...
- patricius 6y agoWould Zig be considered suitable for application programming? Or for programming a web API over HTTP? Or is it mostly suited for low-level programming?
- MaxBarraclough 6y agoZig is, very roughly speaking, competing with the C language. We might say that Zig is to C what Rust is to C++, again, very very roughly. There's at least one Zig HTTP server framework out there [0] but it's not really what the language is intended for. [0] https://github.com/frmdstryr/zhp https://github.com/frmdstryr/zhp
- cztomsik 6y agoOT: If anyone is looking for good parser-combinator lib in rust, here's one lesser-known (not mine) https://github.com/J-F-Liu/pom https://github.com/J-F-Liu/pom