11 ms·
The Hardest Program I've Ever Written (2015)
- otakucode 8y agoI know this is a stupid question, and please forgive me for asking it... but just how wide do monitors need to get or how high do resolutions need to go before longer lines become reasonable?
- EvilTerran 8y agoIt's not about monitor size or resolution - text just gets hard to read once lines exceed a certain width, because the eye starts losing track of which line it's on as it sweeps from the end of one line to the start of the next. That's true for prose as well as code - and code has the additional complexity of having to keep track of possibly-deeply-nested paired pieces of syntax (parentheses, braces etc); that part can be made easier with indentation, but not if everything's on one line. Wider screens still have their advantages even if you keep your text narrow, mind - when you want to display multiple things side-by-side; the halves of a diff, or your code & a reference, for example.
- tomatsu 8y agoWith a larger monitor I'd use the additional space for another document or window.
- saagarjha 8y ago> It reads in a string and writes out a string. That’s usually where a lot of the hard problems lie, in my experience. Parsers, compilers, interpreters, sanitizers, and of course formatters are always a deep dive into formal language theory, where the limits are often fundamental rather than technical and you have to make tradeoffs to get a solution that works well.
- choeger 8y agoI really hope the author did some research. There is a very old work from Derek Oppen that has been adapted to the functional world later. The principles sound very similar to the OP's approach. It would be a shame if so much work went into reinventing the wheel...
- baby 8y agoI read once that this is the difference between research and hacking. Research is about researching related work and the field and ensuring that we’re not re-inventing the wheel. Hacking is about writing code as fast as possible.
- gnulinux 8y agoA good software engineer should be able to do both of them successfully.
- munificent 8y agoYes, I read a few papers and poked around the source of gofmt, clang-format and a couple of others. They weren't as helpful as I'd hoped, but I got a few ideas from them here and there. Most of the implementation of a formatter is grunt-work stuff that's fairly specific to the grammar of the input language, the style rules it's trying to apply, and the weird vagaries of whatever parser or lexer you're using. There isn't that much I found I could take away from them. The most useful research I did was actually around graph search algorithms. Branch-and-bound and most of the other stock pathfinding algorithms didn't work, but they gave me the pieces I needed to get to something that did. Dynamic programming and memoization was key too. I got to use so many fundamental data structures and algorithms in this program. It was a joy.
- dkrikun 8y agoI hope we can have a library for this kind of formatting so each new $hotlanguage can have $hotlanguagefmt easily..
- sbhn 8y agoSpeaking of hot new languages, check out ArnoldC https://github.com/lhartikk/ArnoldC https://github.com/lhartikk/ArnoldC
- dguo 8y agoThere's an effort to make a plugin system for Prettier so that it can format languages other than JS and company. See https://prettier.io/docs/en/plugins.html https://prettier.io/docs/en/plugins.html
- srean 8y agoPretty printers are hard. "We sat down one morning," recalls Steele. "I was at the keyboard, and he was at my elbow," says Steele. "He was perfectly willing to let me type, but he was also telling me what to type. The programming session lasted 10 hours. Throughout that entire time, Steele says, neither he nor Stallman took a break or made any small talk. By the end of the session, they had managed to hack the pretty print source code to just under 100 lines. "My fingers were on the keyboard the whole time," Steele recalls, "but it felt like both of our ideas were flowing onto the screen. He told me what to type, and I typed it." The length of the session revealed itself when Steele finally left the AI Lab. Standing outside the building at 545 Tech Square, he was surprised to find himself surrounded by nighttime darkness. As a programmer, Steele was used to marathon coding sessions. Still, something about this session was different. Working with Stallman had forced Steele to block out all external stimuli and focus his entire mental energies on the task at hand. Looking back, Steele says he found the Stallman mind-meld both exhilarating and scary at the same time. "My first thought afterward was: it was a great experience, very intense, and that I never wanted to do it again in my life." - Guy Steele Heck! to get a taste one can take a stab at writing a formatter for printing a floating point number.
- davedx 8y agoHah! Yes. I recently did a coding test for a job where one of the tasks was to write a formatter for Dutch license plates. Typically these are in the format XX-99-YY, but there are... exceptions. At first glance it seems like it won't be too hard. But it ended up sucking up something like half of the whole coding test time. I did beat it, with a lot of help from unit tests, but formatting is indeed a tougher problem than you'd expect.
- Someone 8y agohttps://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Netherlands#Current_series https://en.wikipedia.org/wiki/Vehicle_registration_plates_of... is complex, indeed, but I don’t see how formatting would be difficult. How do they store those, other than as the formatted string? Parsing/validity checking, on the other hand, could be cumbersome.
- bjoli 8y agoThe hardest thing I ever wrote was an inliner for a language I made myself. You'd think it is a simple problem, but soon you will have a rabid animal on a leash and you will be struggling to restrain it. I gave the source to a friend who modified it a bit and commited it to a language that was mentioned a couple of times on HN in the early days. It has since been replaced, but was used for a good 5 years.
- sillysaurus3 8y agoCan you expand on some of the problems? I was going to write an inliner for a Lisp I was working on for a couple years. Emacs seems to have a decent one. But I know there are tricky corner cases.
- nappy-doo 8y agoWriting a simple inliner isn't too bad, writing a good one is hard. Let's pretend you just "copy/paste" the code into place, there's the question of deciding when/if to copy/paste the code in -- what heuristic do you use. Now there's constant propagation, possibly more doing dead code (from constant propagation), dependency reanalysis (because you've changed the basic block, possibly adding more basic blocks). There are reasons the resultant code could even be less efficient (register pressure for locals for the inline code comes to mind), and there's i-cache complexities that come from blowing up your code size. Inlining is really hard.
- bjoli 8y agonappy-doo answered the question very well. One thing that should be mentioned is that a bad inliner actually removes information that might be useful for future optimisations. Reading the inliners of languages like chez scheme or ghc is enough to give me a hardon.
- scarface74 8y agoSide tangent: He mentioned the algorithm questions he had to study to pass the interview and that knowing the algorithms came in handy. If you are interviewing for Google, Facebook, Amazon, or Netflix, etc. solving problems that have never been solved at thier scale, algorithm questions are important. If you just want someone to right the next software as a service CRUD app, don't waste my time.
- alexbecker 8y agoSpeaking as a former Googler, many (most?) Googlers never work on complex algorithms at huge scale. The interview questions are often completely irrelevant to their work.
- scarface74 8y agoDo you think that even at Google the algorithm questions are useless and shouldn’t be asked? I was trying to give Google the benefit of the doubt.
- alexbecker 8y ago"At Google" is such a broad category that no single answer suffices. For anyone working on the hot-path of search/ads/knowledge graph back-end, sure, they need to know their algorithms. Same for the language teams like Nystrom is on. For a front-end engineer, which is what I was at Google (exclusively in Dart fwiw)? Probably not. I implemented a graph traversal exactly once. However, Google uses the same interview process for all software engineers, and mostly decides what job they will do after deciding whether to hire them. So they really can't tailor their questions without changing their entire process. I think they should change it, but I understand why they haven't.
- vjeux 8y agoI read this before working on prettier and it was a bit scary to be honest :) I wasn’t convinced that the exhaustive approach with weigths was a good idea. It makes it computationally super intensive and hard to predict what the printer would do. Instead prettier runs on a simple idea: if something doesn’t fit in one line, break the outermost parent. This simple rule (implemented via the Wadler IR) is efficient to implement and makes the output generally look good. Then the hard part was to go through the very looong (took me ~6 months full time) process of adding special cases for every constructs that human write in a special way. There is nothing in there that’s hard at a computer science level, it’s just a lot of special cases. I don’t believe that there’s a general solution for it, you just need to slog through it. And the last annoying thing are comments, they can be everywhere and are super annoying to print correctly. Overall, it wasn’t really hard, but a lot of work.
- ukulele 8y agoFirst, thanks for putting the work in on prettier! It's a great tool, and it's helping a lot of devs & teams. I find your approach much more reasonable than the one outlined in the article, which to me feels like complexity for complexity's sake. There might be some minor win to breaking lines by analyzing billions of possibilities, but it just seems like overkill, and it's certainly not predictable for the programmer.
- skybrian 8y agoAs another alternative, gofmt solved it a different way, by not having a limit on line length. I haven't seen it add line breaks at all.
- vjeux 8y agogofmt took a different approach where it respects the author's line breaks. So the following are all going to remain as is with gofmt: f(a, b) f( a, b) f(a, b, ) f(a, b) f( a, b, ) My original motivation for prettier was this particular example where I was sick of having to add/remove all those newlines when the line would go below or above 80 columns. So prettier only allows the following two forms and will format code for you as you save: f(a, b) f( a, b, )
- zaroth 8y agoreturn doughnutFryer .start() .then((_) => _frostingGlazer.start()) .then((_) => Future.wait([ _conveyorBelts.start(), sprinkleSprinkler.start(), sauceDripper.start() ])) ... ... > (The funny names are because this was sanitized from internal code.) And for about 3 seconds I was really excited to learn more about who wrote this code!
- AceJohnny2 8y agoReminds me of Steve Yegge's introduction of js2-mode, a new JavaScript mode for Emacs, and how hard it was to get its indentation right: Amazingly, surprisingly, counterintuitively, the indentation problem is almost totally orthogonal to parsing and syntax validation. I'd never have guessed it. But for indentation you care about totally different things that don't matter at all to parsers. Say you have a JavaScript argument list: it's just (blah, blah, blah): a paren-delimited, comma-separated, possibly empty list of identifiers. Parsing that is pretty easy. But for indentation purposes, that list is rife with possibility! http://steve-yegge.blogspot.com/2008/03/js2-mode-new-javascript-mode-for-emacs.html http://steve-yegge.blogspot.com/2008/03/js2-mode-new-javascr...
- _xgw 8y agoCouldn't you start from Dart's BNF grammar, create a BNF grammar of "formatted" Dart and then format the code accordingly?
- ORioN63 8y agoYou could, but in reality it won't work very well due to recursive rules.
- munificent 8y agoMaybe. If you think of the formatted output as a grammar that includes whitespace, you'll probably discover it is very context-sensitive. Then determining what context to synthesize when making the translation is probably more or less equivalent to how you'd otherwise write the formatter.
- _asummers 8y agoNot nearly as difficult, but I recently did a large project on converting Erlang Dialyzer output into Elixir friendly output in the Dialyxir[0] project, which involved a lot of lexing and parsing and pretty printing, though I was fortunately able to take advantage of the Elixir code formatter for a lot of the heavy lifting for output. My grammar rules, while better than they've been, are still pretty bad, but they seem to work well enough in practice for most programs that I've seen. The tl;dr for that project is that it runs dialyzer, finds the relevant Warning module for each warning, which will pretty print parts of the error output into a larger explanation, which involves taking the output, lexing it, parsing it, then pretty printing the IR back into Elixir, then running through the formatter. [0] https://github.com/jeremyjh/dialyxir https://github.com/jeremyjh/dialyxir
- fizixer 8y ago> you’d expect it to do something pretty deep right? ... Nope. It reads in a string and writes out a string. If an optimizing compiler takes in a program decides to spit out the executable in a string (in base-64 format) which can later be converted to binary, using xxd for example, that makes the optimizing compiler "not pretty deep"? Automated code formatting is fairly deep as far as I'm concerned.
- hyperpallium 8y ago> Yes, I really did brute force all of the combinations at first. It let me focus on getting the output correct before I worried about performance. The programmer spoke correctly.
- doug1001 8y agoi'm a regular reader of this blog; there's always something non-obvious (at least to me) plus just really fine, fine writing--eg, "Some Dart users really dig a functional style and appear to be playing a game where whoever crams the most work before a single semicolon wins." sort of the Dave Eggers of software engineering
- gcb0 8y agosounds like a case of bruteforcing a simple task with a pile of hacks. can't imagine why all that mess is saner then putting a pretty printer on the other end of the language parser. also this mess will be extremely non deterministic, depending on machine speed etc
- Myrmornis 8y agoOn reading this, does it seem like the language parser itself should demand that the code is formatted correctly, rather than relying on a separate tool to format the code? I.e. incorrectly formatted code would be a syntax error. That way all this hard work is off-loaded on human brains. They'll complain a bit but in practice will pick up very quickly where the line-breaks go. (This would probably have to be a decision made by the language designers from the outset.)