198 points · by matt_d · 3y ago · 184 comments
> if I were to design a [...] language, it would push me toward indentation-sensitivity.
> That’s a notable shift from my prior perspective, where
> I felt that whitespace-insensitivity was preferrable to indentation-sensitivity.
I'm starting to have the same change of perspective for a different reason: widespread use of formatters. One of the drawbacks of white-space sensitivity is the accidental mixing of distinct white-spaces (e.g., tabs and spaces). Using a formatter eliminates this problem because all white-spaces are normalized.
I’ve switched my perspectives on whitespace significance. It makes for shorter source code but comes with a signal to noise problem. If there’s a mistake in the indentation it’s harder to determine intent. Versus if you expect well formatted and indented code (I love auto formatters like cargo fmt), and syntax to declare intent, then your tools can make better guesses and suggestions than if you only have one signal.
The other problem I’ve found working with Python is I often want to copy code and paste into my REPL but it’s usually inside of another context so I get an indentation error.
While I like significant whitespace, I LOVE tooling that understands my intent and helps me fix it. I’ll trade slightly more verbosity if it means better tooling. Though obviously I’m quite biased.
We still use a loosely representation (text) for a semantically very rich data format (code). When you look at this objectively that's madness.
We should finally use proper editors for our semantically rich data format instead of "dumb" text editors. (Which are by now actually not so dumb, and which do again completely crazy things to re-extract the semantic information from a representation that inherently erased this information while we're used a loosely text representation).
We should imho eventually switch to "binary source code" and start using proper tools to edit this data.
What we do currently is like editing Excel sheets in a hex editor…
Binary source code (or at least something in the ballpark of XML tech) would also solve a lot of other problems: For example the rendering of the data on screen would be independent form the actual data on disc. This means bitching around "code style" and even partly syntax could finally end. The stuff on screen could be rendered with the help of some "style sheets". Everybody would get the preferred look & feel for their code. (We do this already partly with syntax highlighting; we "just" need to extend this concept). Also things like version control, dependencies, and such, could be build in. Proper indices for searching (and refactoring code) could be also added (things that our editors today compute anyway, but in some ad hoc and very language specific way). Compilation of such code would be faster as all the parsing wouldn't be needed (as it would happen already in the editor; actually, also what is already done today, only that we than again throw away this information for no reason, so the compiler "may" regenerate it over and over on every run, instead that this stuff ends up in a kind of database which could be even part of the "binary source code" format).
I guess some innovative editor features nobody even considered until now would be also enable this way.
It's time for progress!
(Most likely, as almost always, someone will come up with some references to very old systems that did already this because they were ahead of their time; let's see what new stuff I'm going to learn this time :-D).
A lot of the ideas you're pitching have been pitched before and died for the same reason: parsing text is easy for humans and computers. Although I'd quibble with some minor points, like "compilation of such code would be faster". The major bottlenecks in a compiler are codegen, optimization, and linking compilation units. Even bad parsers are extremely fast.
Here's one: Alice Pascal
> In a syntax directed editor, you edit a program, not a piece of text. The editor works directly on the program as a tree -- matching the syntax trees by which the language is structured. The units you work with are not lines and characters but terms, expressions, statements and blocks.
Can you elucidate?
I completely agree with all your points on significant whitespace for programming languages. Where I think it makes a lot more sense though is for structured static data. My quality of live would be worsened without the likes of Haml, Sass and YAML.
I enjoy using slim in my views though prefer scss to sass. I think for many of those tools either misindentations raise an error (like failing a yaml schema validation) or result in incorrect but observable behavior (content isn’t in a div as expected).
It really comes down to how the tool is supposed to be used and how failures are handled.
In general I think that’s the difference between a good experience and a great one: when we can have beautiful failures that help us learn.
This makes no sense.
If the arguments against significant whitespace are valid for executable code they're also valid for markup.
If it's fine to use significant whitespace for markup / data literals even the perceived drawbacks apply than it would be equally fine for executable code.
Im not saying that more syntax is always better, but sometimes that extra bit that seems needless is helpful to clarify to the program “yep I meant what I wrote”
If there's an indentation mistake in an indentation sensitive language, then there's a mistake. Why does intent matter? Intent is lost because there is a mistake.
> Intent is lost because there is a mistake.
The signal is reduced but not gone. In a language like Ruby I can tell you plus or minus a few lines exactly where the problem is.
I discovered something really surprising regarding whitespace awareness of others, TL;DR that many juniors fundamentally misunderstand "tabs vs spaces", thinking that "tab" means the tab key rather than the tab character.
As a follow up to migrating a bunch of repos and discovering every possible combination of "wrong" indentation... I asked what people's preferences were, my assumption that the cause of this mess was different people working on the same repo with differing preferences. Only to find that this was not the case at all, they were mostly from the same individual. And those individuals had a severe misunderstanding of what "tab" vs "spaces" meant. Essentially many people are either not aware of the tab character or not aware that the tab key does not necessarily insert a tab character due to auto indent features. So those people interpret "using tabs" as "using the tab keyboard key", getting confused at why anyone would be using the space bar.
I then realised that the source of this misunderstanding comes from auto-indent defaults in modern text editors. The automatic, per-line indentation type detection, combined with automatic space insertion and automatic navigation over spaces when using cursor keys makes tabs and spaces indistinguishable unless you either turn these features off or render invisibles. This becomes a problem when chunks of code are pasted from somewhere else with different indentation styles, since they act as seeds of an indentation type that start to propagate and compete with adjacent line indentations. The worst combinations are competing space-based indentation levels, e.g 2 vs 4 spaces, when these are adjacent the automatic indentation behaviour cannot figure out which is correct since 2*2 = 1*4, 4*4 = 2*8 etc etc. This can make it impossible to set e.g a closing bracket onto the correct indent level. Rather than realise the auto indent is insufficient, It seems that novices will just submit to the editor - thinking it is somehow broken.
So rather than enforce a tab/space/indentation level style guide: I said I didn't care what they preferred, so long as they turned on invisibles and made sure their code is self-consistent by manually selecting an indentation style/level. i.e I've ended up mandating specific text editor settings rather than a style guide.
https://www.theverge.com/22684730/students-file-folder-direc...
Let's face it: The new generation has no clue how computers work.
Not that this would be a big surprise. My grandma also didn't know how computers work. That's not some knowledge you get born with. You need to learn it.
But the new generation never learned about "real" computers. They're just consumers of user grade entertainment and communication devices, until they get in contact with "real" computers the first time in university or on the job. (So exactly like for the generation of the now grand parents).
> The automatic, per-line indentation type detection, combined with automatic space insertion and automatic navigation over spaces when using cursor keys […]
That's absolutely crazy shit just to simulate the behavior of tabs with spaces!
If we would just use tabs (like they were invented, namely for indentation) there wouldn't be any issue.
The editor vendors should stop all this craziness described above and we would be good. Nobody is printing their source code any more on a line printer! Which was the only reason ever to actually use spaces for indentation. It's incredible how bullshit form the 70' still causes issues today even the actual reason for that bullshit can be found at best with luck in a museum.
Also makes it hard to copy a snippet to run inside a REPL or whatever.
In general just a huge amount of pain, and the "good thing" about how it forces well formatted code I've never seen as an issue with autoformatters and linters in othet languages.
That's exactly the same "clean up" you need to do if you did something wrong while copy & pasting code without the useless block delimiters.
The rest is made up as someone pointed out already: Exactly this story comes up every time but in reality it never happens. (Besides when someone tries hard to get it wrong by all means only to prove their made up point).
Formatters will no save you from the many, many, many cases where indentation is simply ambiguous.
Edit: that is, if you go towards only indentation like Python and YAML
IDEA with its powerful formatters frequently struggles to properly format either of them, resulting in invalid code.
I've found an easier solution is to forbid tabs outside string literals. You can't do the same with spaces.
That's only true most of the time, not all of the time.
If you ever want to output source code programmatically, then indentation becomes a big pain all over again.
The challenge you are refuting is about building said tools. Just because existing tools have pushed through this challenge doesn't mean it's not both tech debt for those existing tools and a challenge for any new tool in the space.
I think the best argument imo is that whitespace has to be properly maintained per line which adds computational cost and statefulness.
And maybe the right answer is to import a compiler's worth of tooling to output a bit of code. But to me that seems like needless overhead, since meaningful whitespace isn't really a positive to begin with.
That's why code gen should be done on the AST level.
Just use the right tool for the job.
s/^spaces|^tabs/whatever_width_you_want/g
that's what every editor does when you set indentation width to N spaces or TAB width to Xin language
whitespace
doesn’t matter so
much!
Yeah, I've gone from hating this, to accepting it (after using Python), to wanting it if I were to design a language (after using Haskell/Purescript/Idris).
> Based on this experience alone, if I were to design a non-S-Expression-based language, it would push me toward indentation-sensitivity.
The catch is that it's a pain to parse. Haskell and Python do token injection. Idris has some manual checks (with lots of holes/exceptions) and explicitly passes around an indentation (in some places). A few others conflate parsing and lexing.
I've settled on having a `(layoutRow, layoutCol)` in the state and requiring `col > layoutCol || row == layoutRow && col == layoutCol`. This lets you setup the off-sides layout and still accept the first token at that column.
Then fixing a lot of bugs due to people (including myself) getting indentation wrong when refactoring python got me wondering.
Then languages servers convinced me indentation is best left to editors and that the cost of braces, semi-colons, etc... is tiny compared to the huge benefit of knowing with 100% certainty and at zero cognitive cost where a block starts and ends.
But you are right, the cost of it is pretty high - not just copy/paste, but it's tricky to parse, auto-formatting is harder, LSP support (changing code) is harder, renaming variables and functions is harder, etc. (Haskell-like languages are worse than Python because they don't always start a new indentation level on a new line, so renaming can change the indentation level.) So it's probably not worth it.
And I will add, like the sibling commenter, I like the auto-format on save of Go. When writing Go, I'll type whatever, often on one line, and let the formatter take care of making it pretty.
The other advantage is that it standardizes formatting for a given repo making diffs more relevant.
Ironically, I believe Python PEP 8 is what started and normalised the idea of taking formating decisions away from developers.
Constant matters. Ahead-of-time compilation (AOT) and just-in-time compilation (JIT) are a lot faster than interpretation [1,2], sometimes by a factor of >100 in the case of C vs pure python [3]. This gap is noticeable for a program taking more than a few seconds to run. Except for performance-critical tasks, my preference is JIT-based languages without a manual compilation step, such as LuaJIT, Javascript-V8/Node.js and Dart. Nonetheless, these language implementations are much harder to develop than interpreters.
[1] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
[2] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
[3] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
Not in these exercises. They're focused on algorithms and their asymptotic complexity.
> There was never a time where rewriting in another language felt like the right way to get better performance.
Similarly, for small exercise problems, dynamic typing rarely hurts, but for large collaborative projects, static typing starts to show its advantages.
So this was not related to AoC but instead to building a language.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
Java code JIT compiled is usually significantly faster than when AoT compiled.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
Plus ça change, plus c'est la même chose
26 Programming Languages in 25 Days - https://news.ycombinator.com/item?id=34161410 - Dec 2022 (74 comments)
I don't think any proponents of static typing would expect small problems like these to really show the benefits of static typing though. If you were trying to decide whether comments were worth it you would conclude from AoC that they are not, which is clearly the wrong conclusion in general.
The author does say they have extensive experience of Haskell and Standard ML so presumably they have experience with the enormous benefits of static typing at "real program" scale so it's a strange conclusion IMO.
IIRC, if one pedantically types a typical NxM transformation matrix, one may need NM different explicit types. (or maybe this was just a problem when derivatives were involved?)
In a dependently typed language like Idris?
Most likely even Java's generics would solve this issue.
Who would have though! It's like this would have been the whole goal of this trick
Yes it forces clean indentation, but it gives the writer the burden to take care of it. That sucks. Let the computer do the work.
An IDE with proper language support for a whitespace-aware language should be able to parse the AST figuring out the code structure from the indentation level; then it could reformat it at the proper indent level when you copy and paste it elsewhere, just like it does with a delimiter-based language.
No; it is not decidable where a block ends and the next line of the out block starts when there is no marker for block ends ('}', or 'END', etc).
Just because you paste a bunch of code after `then` in Python doesn't mean all of it goes into `then`.
Indentation-sensitivity seemed like a great idea in 1983. I'm not convinced today.
Personally I think it causes more problems in interpreted languages, a lot of those disappear with a compiler with thoughtful error messages like Scala.
Surely neither OCaml nor Haskell are in the top 20 of any "Most Used Programming Languages" list.
I will give you that for highly specialized domains, those lists would look different (eg in some niche OCaml would be high while Rust would be low, or R high where C++ is lower down the list) , but it is telling that Scala comes in at #32 when compared to other languages that, I think, occupy a similar problem space.
Of course, Python is #1 on the TIOBE list (and have had a strong showing for years), which I ascribe to the overall productivity and wide application domain fit. So, whether or not white space is objectively bad (for any language or only some languages), it hasn’t detracted so much from Python’s popularity.
But also C# has indentation-sensitivity. Otherwise multi-line strings would not work.
I could imagine that other popular languages copied or will copy the same trick as C# does.
Some of their recent work: https://www.uab.edu/news/health/item/13224-clinical-trial-fo...
> Of existing languages, Racket (paired with Typed Racket) probably comes closest to what I feel is the sweet spot for language design, and it may explain why I seem to pick it more than most other languages when given a choice.
Racket is great, and I'm coming to appreciate it more as I spend my spare time with it. I didn't really start enjoying it until I stopped trying to pretend it was Python with delimiters. Expressions are fundamental to Racket in a way that goes way beyond syntax.
This is typical of all (truly) functional languages, in my experience. They are expression-oriented rather than statement-oriented. You'll find similar behavior in, e.g., OCaml and Haskell. And since it was inspired by OCaml, you'll also find that Rust has an interesting expression-oriented approach to imperative programming, where they have essentially adopted the idea that "statements" are just unit-producing expressions that can be sequenced.
> Tactic: Do translation more than optimization
This rings especially true - "you can write Java in any language", or whatever sort of language shaped your thinking. Even after years of using different languages my prototyping code is often inherently imperative and I have to actively rewrite it to be functional.
let ast = <:expr< 1 + 2 >>
would be the way to write the AST: +
/ \
1 2
and you could compose those in various ways, eg: let ast2 = <:expr< $ast$ + 3 >>
Of course it was all safe at compile time. The main issue with it was it was quite complicated and terribly badly documented. > (eval '(display (+ 5 6)) (interaction-environment))
11 eval 'print ("hello, $some_user_input")'> Based on this experience alone, if I were to design a non-S-Expression-based language, it would push me toward indentation-sensitivity.
> That’s a notable shift from my prior perspective, where I felt that whitespace-insensitivity was preferrable to indentation-sensitivity.
Welcome to the club! I just wrote some new thoughts on this today: https://breckyunits.com/useTheSpine.html
Also, Python has existed for decades and still there is little further adoption of indentation-sensitivity. It doesn't seem like a wave of indentation-sensitive languages will be coming any time soon.
Ah you reminded me. A curious phenomenon I've observed with Prettier in JS and fmt in Go is languages are moving to standardized whitespace, but as you said, not yet deriving information from it. I don't know enough about Java or Rust but I suspect they probably both have adopted a Prettier/fmt like convention where all code is formatted on save. So it seems like we are moving to a world where it will be a simple flip of a switch to then start having popular languages extract meaning from the whitespace.
> Also, Python has existed for decades and still there is little further adoption of indentation-sensitivity. It doesn't seem like a wave of indentation-sensitive languages will be coming any time soon.
I think it's coming big time this year. I think our Scroll (https://scroll.pub/) will catch fire and be the go to language instead of Markdown by the end of the year. Then with the increasing success of TreeBase (powering PLDB and others) we will start to see JSON fall for config formats and document storage databases. A lot more will happen to, data vis will be a big one, but those 2 I'm reasonably certain of happening in 2023.
But why would I want to extract meaning from whitespace if I have all the information I need from other mechanisms (eg. braces, brackets, keywords)?
The dualities static vs dynamic, whitespace insensitive vs sensitive, brackets vs nobrackets, pascal/fortran/style vs algol, interpreted vs compiled, dynamic scope vs lexical scope, aot compiled vs jit compiled, functional vs oop are all dualities that a language must bear with the ramifications of that decision. I don't think it's obvious that one category of the duality is ALWAYS superior to the other in every scenario.
Obviously we would prefer a language that is expressive, easy to read and compiled for performance and avoids errors at compile time. Does this language exist?
And that is as easy to write as a scripting language such as Python or Ruby. Python is extremely fast to write scripts for.
I'm working on my own programming language and it resembles Javascript, so it is C style brackets and semicolons. In the interests of getting running fast, I compile to my own imaginary assembly language which is a switch based interpreter. This means I can work on the frontend and backend of the language in parallel. My language is a multithreaded language and can communicate integers between threads. I am still designing compound struct sharing between threads. Since this enters the move vs copy or by reference or by value semantics problem. If I send an object/struct/hash/list by copy then the code is slow. If I do it by reference, I have memory management to worry about if I plan to rewrite my language in a compiled language and not rely on Java's garbage collection.
On eatonphil's discord we talk programming language design.
I see that you tried Julia. You can kind of write DSLs in it using macros. E.g. Turing.jl ( https://turing.ml/dev/ ) off the top of my head. There was a little blog post about it as well ( https://julialang.org/blog/2017/08/dsl/ )
Seems to be a heavily debated topic.
Scala has very strong support for eDSL (and I personally think this is good) but many people who used or use Scala are constantly arguing against it.
Most likely the "With great power …" thingy applies here. You can indeed create a big mess with overused DSLs.
Smalltalk allows me to do live programming with great ease. This is a huge productivity amplifier. Smalltalk's productivity is much higher than that of any major language in use today.
About "type-related programming bugs." I once took endeavour to write cycle-accurate MIPS CPU simulation in Haskell. Most of the errors I uncovered were easily preventable with the types - mark integers with their size in bits and you will never add instruction pointer to an unaligned offset. Haskell did not had proper types at the time but later I used that trick quite successfully.
With the types you can eliminate whole classes of logic errors. They just will not appear before end user.
Dynamic languages are strictly only viable for throwaway code, or very small programs (where small means something up to two pages of code max, or so).
Either "safe and sane refactoring" isn't necessary to create value. Or you're just wrong.
Most startups do exactly this.
That's even a valid strategy: Concentrate on the business case only, redo the code when you get successful and have the money to rewrite everything. (Of course quite some companies misses of missed the right time to throw away everything and rewrite it. This results later on in a huge and very expensive PITA; some of the companies affected even started to build their own compilers and static checkers for the languages they use; just look who pays for static type checkers for Python or Ruby).
I don't understand this. I don't really encounter situations where the data structures are "straightforward" that type inference isn't able to handle on its own (or at most with explicit type specification for just a few variables).
It would surprise me if Rust isn't smart enough to infer that the type of the dictionary is "Optional<Integer>" or "Integer | None". I haven't used Rust myself, but every language that I've used with type inference and algebraic data types will make this inference on its own.
I also did a similar challenge this year, though I had to drop some of the more exotic languages that you kept in. Nice work.
It has optional options-in lazyness for the few times you really need it.
Or just rolling it yourself with e.g. a python generator
How should this happen? You can hear even form the horses mouth that laziness by default was a big mistake.
> dynamic dispatch everywhere
Big mistake of most "OO language" indeed.
Rust got this right. Static dispatch is the default (simple and fast!) but you can have dynamic dispatch where it makes sense. I hope this design will be copied in the future everywhere. Maybe even some language manage to get rid of their mistake and switch to the sane design (looking at you Scala, just make type-classes first-class, but keep OOP for the cases where it makes sense).