418 points · by aaronbrethorst · 1y ago · 274 comments
https://news.ycombinator.com/item?id=36310130 - Rewriting the Ruby parser (2023-06-13, 176 comments)
I remember being taught to use yacc in our compiler course because "writing it by hand is too hard". But looks like Ruby joins the growing list of languages that have hand-written parsers, apparently working with generated parsers turned out to be even harder in the long run.
That said, replacing a ~16k line parse.y[1] with a 22k line prism.c[2] is a pretty bold move.
Writing a parser by hand requires understanding the theory of parsing and understanding your implementation language. Writing a parser with a parser generator requires understanding the theory of parsing, your implementation language, and a gigantic black box that tries unsuccessfully to abstract away the theory of parsing.
The time spent learning and troubleshooting the black box is almost always better spent putting together your own simple set of helper methods for writing a parser and then using them to write your own. The final result ends up being far easier to maintain than the version where you pull in a generator as a dependency.
Unless I had a relatively simple grammar or had very strict performance requirements (like in the case of Ruby), I would not trust a hand rolled parser on a CFG by someone who isn’t dedicated to the craft. (PEGs are simpler so maybe).
I’ve written recursive descent parsers by hand and they look very simple until you have to deal with ambiguous cases.
Do people who write predictive recursive descent parsers (LL(k)) really calculate first/follow sets by hand? What if the grammar requires backtracking?
It's not that uncommon to have an implementation with code that is lengthier but with an obvious pattern, while the smarter compressed implementation whose understanding is not necessary trivial to grab even for people seasoned to metaprogramming, reflexivity and so on.
Not to say that is what happen here, the point here was to recall that number of lines is not an absolute linear metrics.
I've been writing parsers for simple (and sometimes not so simple) languages ever since i was in middle school and learned about recursive descent parsing from a book (i didn't knew it was called like that back then, the book had a section on writing an expression parser and i just kept adding stuff) - that was in the 90s.
I wonder why yacc, etc were made in the first place since to me they always felt more complicated and awkward to work with than writing a simple recursive descent parser that works with the parsed text or builds whatever structure you want.
Was it resource constraints that by the 90s didn't really exist anymore but their need in previous decades ended up shaping how parsers were meant to be written?
When hand-rolling a parser, there could be accidental ambiguities in the definition of your grammar, which you don't notice because the recursive descent parser just takes whatever possibility happened to be checked first in your particular implementation.
When that happens, future or alternative implementations will be harder to create because they need to be bug-for-bug compatible with whatever choice the reference implementation takes for those obscure edge cases.
Is that a problem? Just use a grammar formalism with ordered choice.
In practice, parser generators are always at least a little disappointing, but that nagging feeling that it _should_ work remains.
Edit: also the other sense of academic, if you have to teach students how to do parsing, and need to teach formal grammar, then getting two birds with one stone is very appealing.
Even then, yacc and bison are pretty solid overall. I believe Postgres still uses a yacc grammar today, as another high profile example. I'd arguebthr parsing of SQL is one or the least interesting thi.gs an RDBMS does, though.
"Yeah there's an unbalanced parentheses...somewhere near this point... might actually be unbalanced, or you missed a comma or semicolon. You tell me."
This is generally my #1 reason for using a manual parser — nobody has yet made a pretty good syntax error handling / reporting for parser generators or parser combinators.
It's genuinely very complex — I read the whole literature on that as of 2019 (there's surprisingly little). You basically have to inject custom logic, though there are a few heuristics that you can prepackage and can be useful in a lot of places. But the custom aspect of it means this doesn't play nice with traditional LL/LR parser generators. It could be done for parser combinators (PEG etc) however. Didn't have enough time in my PhD thesis to play with this, and I moved on to other things, but I'm hoping someone will make this eventually.
In every other case having a grammar in form of parser generator macros should be better and preferrred, since it is well portable to other languages and tools and lends itself to be more readable (with good naming).
Someone pointed this out https://news.ycombinator.com/item?id=42323293
If I cannot refactor my services, I shall refactor Ruby instead.
Personally I have learnt this lesson back in 2000's, in the age of AOLServer, Vignette, and our own Safelayer product. All based on Apache, IIS and Tcl.
We were early adopters of .NET, when it was only available to MSFT Partners and never again, using scripting languages without compilers, for full blown applications.
Those learnings are the foundations of OutSystems, same ideas, built with a powerful runtime, with the hindsight of our experiences.
The push for Python performance and JIT compilation has little to do with AI and more to do with Python's explosion in adoption for backend server applications in the 2010s, as well as the dedication of smaller projects like PyPy that existed largely because it was possible to make them exist. The ML/AI boom helped spread Python even farther and wider, yes, but none of the core language performance improvements are all that relevant for ML or AI.
As another commenter pointed out, the performance bottlenecks in AI specifically have essentially to do with the CPython runtime performance. The only exception is in the pre-processing of very large text corpora, and that alone has hardly been a blip on the radar of the people working on CPython performance.
Moreover, most of the "Python performance" projects that do sit closer to machine learning use cases (Cython-Numpy integration, Numba, Nuitka) are more or less orthogonal to the more recent push for Python interpreter performance.
Cython itself and MypyC are mainly relevant because they are intended to be general-ish purpose performance boosters for CPython, and in doing so helped fill the need for greater performance in "hot and loopy" code such as network protocols, linters, and iterators. Cython also acted as a convenient glue layer for ad-hoc C library binding. But neither project is all that closely related to AI or to the various JIT compilers that have arisen over the years.
Woah, your mention of “Vignette” just brought back a flood of memories I think my subconscious may have blocked out to save my sanity.
Isn't most of the work in Python AI projects done in C or C++ extensions anyway?
They eventually left and founded OutSystems with what we learned since the Intervento days, OutSystems is of the greatest startup stories in the Portuguese industry.
This was all during dotcom wave from the 2000's, instead I left to CERN.
Reference: https://x.com/ShopifyEng/status/1863953413559472291
[1] https://shopify.engineering/running-apache-kafka-on-kubernet...
[2] https://shopify.engineering/lessons-learned-apache-airflow-s...
Their entire cluster was 2.4 million CPU cores (without more info on what the cores were). This includes not only Ruby web applications that handle requests, but also other infrastructure. Asynchronous processing, database servers, message queue processing, data workflows etc, etc, etc. You cannot run a back of the envelope calculation and say 0.85 requests per second per core and that is why they're optimising Ruby. While that might be the end result and a commentary on contemporary software architecture as a whole, it does not tell you much about the performance of the Ruby part of the equation in isolation.
They had bursts of 280 million rpm (4.6 million rps) with average of 2.8 million rps.
Indeed, it doesn't. However, it would be a fairly safe bet to assume it was the slowest part of their architecture. I keep wondering how the numbers would change if Ruby were to be replaced with something else.
For example, doing some loop unrolling for a piece of code with a known & small-enough fixed-size iteration. As another example, doing away with some dynamic dispatch / method lookup for a call site, or inlining methods - especially handy given Ruby's first class support for dynamic code generation, execution, redefinition (monkey patching).
From https://railsatscale.com/2023-12-04-ruby-3-3-s-yjit-faster-w...,
> In particular, YJIT is now able to better handle calls with splats as well as optional parameters, it’s able to compile exception handlers, and it can handle megamorphic call sites and instance variable accesses without falling back to the interpreter.
> We’ve also implemented specialized inlined primitives for certain core method calls such as Integer#!=, String#!=, Kernel#block_given?, Kernel#is_a?, Kernel#instance_of?, Module#===, and more. It also inlines trivial Ruby methods that only return a constant value such as #blank? and specialized #present? from Rails. These can now be used without needing to perform expensive method calls in most cases.
Shopify has introduced a bunch of very nice improvements to the usability of the Ruby language and their introductions have been seen in a very positive light.
Also, I'm pretty sure both Shopify for Ruby and Facebook for their custom PHP stuff are both considered good moves.
Just now, I was surprised to see that the package seems to be getting put into the official Arch repos, so my eight years of very minimal volunteer service seem to be at an end. I still think I'm going to remember doing this and smile a little every Christmas morning for years to come!
2. Also wondering what upside could Ruby / Rails gain on a hypothetical Java Generational ZGC like GC? Or if current GC is even a bottleneck anywhere in most Rails applications.
Ruby's GC needs are likely to be very far from the needs of JVM and .NET languages, so I expect it to be both much simpler but also relatively sufficient for the time being. Default Ruby implementation uses GIL so the resulting allocation behavior is likely to be nowhere near the saturation of throughput of a competent GC design.
Also, if you pay attention to the notes discussing the optimizations implemented in Ruby 3.4, you'll see that such JIT design is effectively in its infancy - V8, RyuJIT (and its predecessors) and OpenJDK's HotSpot did all this as a bare minimum more than 10 years ago.
This is a welcome change for the Ruby ecosystem itself I guess but it's not going to change the performance ladder.
Railsbench is 5.8% faster with 3.4 over 3.3
So already something else from Jikes days.
If it's an alternative to the `|x|` syntax when using only one block variable, then I like that.
The `&:` doesn't work in that context
&: is very nice, but not enough.
Currently stuck on trying to get Ruby 3 working.
And if that isn't happening and there's no other development on the codebase, why bother upgrading it?
Probably just need to spend more time understanding exactly what changed and how to convert stuff.
In contrast to the mess that is Python. For instance, in Ruby it is natural that each or map are methods of Array or Hash rather than global functions which receive an Array or Hash argument.
This goes as far as having the not operator '!' as a method on booleans:
false.! == true
Once you have understood it, it is a very beautiful language.
Stuff like map() is generic iteration, over any structure that exposes iteration. When it's a member function, it means that every collection has to implement map itself basically. When it's separate, the collections only need to provide the interface needed to iterate over it, and the generic map() will just use that.
Taking OOP more seriously, this kind of thing should be implemented through inheritance, interfaces, mixins, etc. Even though I've got used to it, Python has these inconsistencies that sometimes it wants to be more OOP, sometimes it wants to be more FP.
Ruby has chosen OOP as its size, and implements nicely those functional operations as methods (same for Kotlin, for example). That makes easy for composing them:
# Sum of the square of even elements of a list, in Ruby
my_list.filter{|x| x % 2 == 0}.map{|x| x * 2}.sum
Python could do something like that, but we quickly fall in a parentheses hell:
# The same code, in Python
sum(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, my_list)))
Languages that have chosen the FP path more seriously implement function composition. They could do the same way as Python, but composition makes it more readable:
# The same code, in Haskell
sum . map (^ 2) . filter (\x -> x `mod` 2 == 0) $ my_list
PS: I know that I it would be better to use comprehensions in both Python and Haskell, but these are general examples
That might looks really anecdotal, but on practice for example that's is probably the biggest obstacle to providing fully localized version of Ruby for example.
The second biggest challenge to do so would probably be the convention of using majuscule to mark a constant, which thus requires a bicameral writing system. That is rather ironic given that none of the three writing system of Japanese is bicameral (looks fair to exclude romaniji here). Though this can be somehow circumvented with tricks like
``` # Define a global method dynamically Object.send(:define_method, :lowercase_constant) do "This is a constant-like value" end
# Usage puts lowercase_constant ```
Awesome, but with great power come great responsibility ;)
You end up feeling and steered to the the right idiomatic way of doing things is the satisfying way.
The well-known Rails framework uses this to great effect, however, some people argue that the choice of "convention over configuration" and extensive use of meta-programming, derisively called "magic", make it less suitable for inexperienced teams because they get too much rope to hang themselves and the lack of explicitness starts working against you if you're not careful.
That's not even close to true. Even setting aside APL and its descendants, even setting aside Perl, any of the functional programming languages like Haskell and Scala are less verbose.
(The relative lack of success of those languages should indicate why minimizing verbosity is a poor aim to target.)
thread = Thread.new do # thread code end
...
thread.join
In this example we can see that it's not magic, only concise.
I wrote more about it here: https://news.ycombinator.com/item?id=40763640
var thread = new Thread(() -> {
// Thread code
});
thread.start();
// ...
thread.join();Also you don't want all and everything being the results of spells you don't have a clue how they are cast.
Why doesn't clojure fit the bill here?
I wouldn't say niche, but the killer app of Ruby is Rails, a web framework similar to Django. In fact, many people treat them as they are the same. But there are big projects that use Ruby and that are not related to Rails. As far as I remember: Metasploit, Homebrew, Vagrant and Jekyll.
Personally I think Ruby is amazing language for writing shell scripts. I write a blog post about it, you can see it and its discussion here: https://news.ycombinator.com/item?id=40763640
What’s the conspiracy theory here? Why would anyone be paying people to hype Ruby? What could possibly be the end goal?
I wouldn't have had this much control of my own environment with another language, so that all of these are pure Ruby:
- My window manager - My shell - My terminal, including the font renderer. - My editor - My desktop manager
That's less than 10k lines of code. I've taken it a bit to the extreme, but I wouldn't have had the time to if I had to fight a more verbose language.
https://github.com/vidarh/rubywm
Beware that one of the joys of writing these for my own use is that I've only added the features I use, and fixed bugs that matter to me, and "clean enough to be readable for me" is very different from best practice for a bigger project.
I'm slowly extracting the things I'm willing to more generally support into gems, though.
It's also got a bunch of semi-functional-programming paradigms throughout that make life quite a bit easier when you get used to using them.
Honestly, if it had types by default and across all / most of its packages easily (no. Sorbet + Rails is pain, or at least was last I tried), I'd probably recommend it over a lot of other languages.
1) It has differences in behavior with certain classes and is not a drop-in replacement.
2) It always compiles, so it's kind of slow to compile-test
I've tend to have found Kotlin to be the direction I'm more happy going with. It speaks to my particular itches for me personally, more effectively. I can absolutely see how it's a very effective choice.
I wish the TypeScript/React integration was easier. Say what you will but there's no way you can achieve interactivity and convenience of React (et al) UIs with Turbo/Hotwire in a meaningful time.
Have you tried either Inertia (https://github.com/inertiajs/inertia-rails) or vite-ruby (https://vite-ruby.netlify.app/)? Both look very promising.
I don’t think it needs a niche. :)
A simple example: `3.days.ago` is a very commonly used idiom in Rails projects. Under the hood, it extends the base Number class with `def days` to produce a duration and then extends duration with `def ago` to apply the duration to the current time.
Taking that concept to a bigger extreme is this mostly unnecessary library: https://github.com/sshaw/yymmdd
`yyyy-mm-dd(datestr)` will parse a date str that matches yyyy-mm-dd format. It looks like a special DSL, but it's just Ruby. `dd(datestr)` produces a `DatePart`. Then it's just operator overloading on subtraction to capture the rest of the format and return the parsed date.
That library feels unnecessary, but the entire thing is 100 lines of code. The ease of bending the language to fit a use case led to a very rich ecosystem. The challenge is consistency and predictability, especially with a large team.
Where it shines now is in it's width and depth. There are thousands of well documented libraries built by millions of dev's.
If you want to do something; near anything, ruby has a gem for it. It's power today is that it is omni.
Overall, a pleasant and expressive language with an incredible community. Python ends up "winning" because of pytorch + pandas, but is (imo) a worse language to work in + with.
https://evilmartians.com/chronicles/viewcomponent-in-the-wil...
https://thoughtbot.com/blog/hotwire-turbo-streaming-viewcomp...
Nginx was starting to get popular and overtake Apache on installs, and people were enamored with its performance and idea of “no blocking, ever” and “callbacks for everything”, which the nginx codebase sorta takes to the extreme. The c10k problem and all that.
When JavaScript got a good engine in v8, Node was lauded as this way to do what nginx was doing, but automatically and by default: you simply couldn’t write blocking code so waiting on I/O will never bottleneck your incoming connections. Maximum concurrency because your web server could go right back to serving the next request concurrently while any I/O was happening. But no “real” multithreading so you didn’t have to worry about mutexes or anything. I remember being slightly jealous of that as a Rails developer, because webrick/unicorn/etc had a worker pool and every worker could only handle one request at a time, and fixing that could only happen if everything was async, which it basically wasn’t.
JavaScript becoming a popular language in its own right due to frontend was certainly the most important factor, but it wasn’t the only one.
http://widgetsandshit.com/teddziuba/2011/10/node-js-is-cance...
Worst of all, they made npm packages dead easy, so most of them don't even have a readme file, not to mention inline docs like POD or RDoc. This is how you end up with spam pacakges, malware in npm and lpad disasters.
Good news is we have WASM now, so you can write backend and frontend code in basically whatever language you want.
And the latter lets you operate on the same level of abstraction as Rust and C++ compilers do.
For dynamic languages? Stuff like Clojure, JRuby, Boo, are definitely not faster than V8 JavaScript...
I mean Truffle Ruby is as fast as V8 already and MRI yJIT and jRuby are catching up fast.
It could also be argued that JVM is the gold standard JIT.
I think that shows that Google doesn’t have a monopoly on great JIT engineers.
According to which benchmark? At my hand [1], node is ~60% faster than TruffleRuby and over an order of magnitude faster than yjit v3.3.0.
[1] https://github.com/attractivechaos/plb2?tab=readme-ov-file#a...
v8 and node are 15 years old. That's when this actually mattered and js on the backend took off.
That said you do have things like https://opalrb.com/
I finally got it installed and then followed some tutorials only to see that Rails' html.erb files have completely broken syntax highlighting in VSCode and other editors. I facepalmed and though I tried to search for a fix online, I couldn't find one. I saw posts mentioning it in forums and yet not a single solution posted.
So I gave up. I tried in Mac, Windows and Linux. If someone here knows how to fix the broken highlighter, that can be my Christmas gift today, but for the most part I've moved on.
You should be able to do
$ asdf plugin add ruby
$ asdf list all ruby (you'll see 3.4.1, the latest is available)
$ asdf install ruby 3.4.1
And now you can use Ruby 3.4.1 with no issues. Follow that up with
$ gem install bundler
$ gem install rails
$ rails new ...
I used to use ruby a lot - mostly just because it's the nicest language for scripting things on unix. I can remember trying to get it set up a year or so ago and finding the process difficult (think I was using rvm).
https://github.com/rbenv/ruby-build/wiki#suggested-build-env...
probably good idea to point people here before they install ruby, since it'll compile for minutes then tell you it's missing a dependency, and you have to start the whole process over.
Ruby itself works okay on bare-metal Windows, but virtually guaranteed any decent size Rails project will use some native gem that's a nightmare to get to build on Windows.
Try Crystal if you want less dynamic typing.
That being said, Matz also isn't a fan of static typing. Static type annotations exist in the form of RBS, but no one that matters in the Ruby eco-system is pushing static type annotations in .rb files themselves.
Also, after seeing TypeScript, I'm very happy about that.