118 points · by tosh · 8y ago · 145 comments
Edit: one more thing I forgot to add: this is a nightmare for tooling. I know there’s the contingent that wonders why you’d ever want anything more than vim or emacs, but for the rest of us, this just means refactoring/code navigation/syntax highlighting/autocomplete/static code analysis are totally broken.
For example there's a library in Rust which provides a `json` macro with syntax like so:
json!({
"foo": "bar",
"qux": baz
});
where `baz` can be a Rust string or integer. Note: this will typecheck, so if you provide something weird as `baz` then it won't compile, but otherwise the syntax is identical to standard JSON syantax.I think that being able to think symbolically about one’s code is a vital skill for a programmer (and, more generally, that the capability of thinking abstractly is a vital skill for a learnéd human being). Thus, if someone lacks that skill, perhaps he should probably not be a programmer? That may sound revolutionary, or elitist, but I think most of us would agree that someone who can’t effectively reason about a depth-first tree traversal will have trouble as a professional software developer; mayn’t that also be the same of someone who can’t effectively reason about computational structure?
Your comment re. macros & fragmentation makes me wonder if you’ve ever used Lisp’s macros: I think that they actually mitigate against fragmentation, as e.g. CLOS started out as macros atop Lisp and ended up being standardised as part of it. Lisp’s packages help manage namespace collisions, and thus prevent fragmentation by making differences manageable.
And Lisp tooling typically handles macros very well indeed.
I really like your example, because it nicely highlights how much of a tooling problem this really is.
To call a subroutine, you'll have to arrange your argument values on the stack, then do the call instruction, after which your target procedure pushes the return address to the stack...
Except that almost no one does it this way anymore. I usually never think about all this stuff when I call `foo()`.
Writing a macro in C/C++ is the equivalent of doing the whole legwork to call functions yourself.
What I find really surprising, though, is that we haven't ever arrived at the point where we think that "most programmers can't be trusted with arbitrary mutability". It's everywhere, and since the C/C++ days, it got worse with many languages. I absolutely hate the house-of-cards code I regularly deal with in C# because people would have to write a couple of additional lines to encapsulate the internal state of their types properly. So instead, you get mutable public members or properties everywhere... * sigh *.
It's not that you can't trust people to make good decisions or invest in understanding what they're doing. It's that in real life people take shortcuts. Time constraints, deadline pressures, a brief skimming of a StackOverflow answer with no followup or further exploration - any of these can lead to code that does the job, is ignored until only one person is left who understands it, and needs to be parsed out and refactored. I think you can only trust programmers with macros (or functions, or pointers, or object-oriented programming) if you have good practices in place to handle technical debt (clean naming, clean separation of concerns, adequate testing, etc.).
As a side note: the other big part about macros is YAGNI. Macros are fancy, but I've yet to come across a use case for it that can't be replaced with a simple function call. I'm also curious about how one would test a macro.
The same way you test any other kind of function call?
For starters, macros are mandatory for out-of-order execution; anywhere you need arguments to be manipulated before evaluation must be done in a macro. E.g., a short-circuiting "or" function is impossible without being either a macro or built-in to the language.
Another common use case is efficiency. Any substantial computation you do at compile/eval-time never has do be done at runtime. I've worked on a Clojure router that compiles its nested route structure into efficient string-matching/regex code before it ever gets turned into machine code. Other languages either have to re-parse the routes, or find a way to cache a more efficient representation as part of an extra build step.
In broad strokes, I really like that composition is increasingly being favored over inheritance. But I've also inherited some deeply Byzantine amalgamations of decorators and abstract factories that certainly do eliminate a lot of boilerplate. But they do it at the cost of sometimes making it very difficult to understand where certain behaviors are coming from.
The worst is, most of them are ones that I inherited from my past self. The specialized knowledge it takes to maintain an application that's been written this way apparently fades quite quickly.
The problem space is very, VERY well understood. The patterns have been bikeshedded to death almost 20 years ago. It's super boring, there's not many interesting left, and it's awesome because of it. Of course, software engineers hate this in general because they get way too much enjoyment out of figuring out how to save 2 lines of code for their own good ;)
I think if a lot of developers programmed with this mindset we'd be in a much better place. The best example I can think of off the top of my head is people choosing Vue over React "for it's simplicity". You're really just taking the little bits of ritual and reliance on JS fundamentals that React contains (which isn't that much in the first place) and moving that complexity into a DSL with a big transpilation footprint.
It makes sense from a "I want to play around and build features quick" perspective, but it's a horrid decision in terms of the complexity of the software and the number of moving parts it contains. Unless like many you (foolishly) believe the law of leaky abstractions doesn't apply in JS land for whatever reason.
Proper macros make that complexity much more accessible. That is, if things work correctly, you still don't notice, but if they don't, you get to easily fix them (though you still have to pay the cost of understanding it first).
Macros can be seen as incidental tooling reduced to only essential complexity. For comparison, a typical JS transpilation toolchain seems more like 80% of incidental complexity.
Production size and evaluation times are a thing with react apps.
The author cites Lisp macros. C macros, or C++ template metaprogramming, are to Lisp Macros as a 19th century locomotive is to a state-of-the-art MagLev train.
>I would actually argue that macros might be why Lisp didn’t become mainstream; it creates a lot of fragmentation.
This has no substance. Please take a look at how macros are used in Lisp.
>this is a nightmare for tooling
Not in Lisp.
And I don’t buy the argument that it’s just because Lisp has been around a long time. Python is almost 30 years old but there’s one canonical version. And seriously, I bet there are a lot of pythonistas that would change things about, for example, the object system if they could (explicit “self” comes to mind), but if they did that the community would fragment with some people using the original system and others using an alternative and it would be hard to integrate new libraries and know the rules of the module you’re working in. It’s a trade off no doubt, but it seems like most people have voted that a rich ecosystem of libraries without compatibility issues is more important to them.
Most other languages, derived from Lisp, are incompatible - like Ruby is incompatible with Perl. Thus Scheme is called Scheme and not Lexical Liwp - it's now a new language family - the family of Scheme dialects - which are grounded in RXRS reports as language standard.
It's good that there is only one/two Pythons - but Python competes with a zillion other scripting languages - or they compete with Python. And they are not compatible at all.
A typical library should usually define more functions/methods than datatypes/classes, more datatypes/classes than interfaces and more functions/methods than macros. The exception is libraries which only provide some particular macros or interfaces or whatever.
I self-inflicted some pretty awful debugging woes due to C++ macros a few years back. VC++ is incapable of stepping into/through macros - so a logical error in my macro had to be solved with good-old printf debugging. I learned my lesson about using macros sparingly.
This can obviously be alleviated with source maps. This presents a new set of dilemmas: does the developer want to debug the macro in its macro form, or its expanded form? Does the developer only want to debug a specific macro in expanded form, while keeping other macros expanded? How do you even debug a "case macro" in macro form? How do you debug the case macro code while it is expanding?
The evil elitist in me wants to qualify that as "99.99999999% of JS programmers".
The amount of time I hit that pulled out of my butt rule in daily code reviews is above and beyond what you would expect. Also what attribute of JS programmers would preclude them to abusing macros or templates more than c or c++ programmers already do?
Well, we have tools that work. Why would we use tools that don’t work? It just seems weird to me, when a solution to a problem exists, to not use it.
I actually think baking in the ability to add language constructs with macros is exceptionally useful and allows concepts to be expressed very clearly. A great example of this is Ecto which allows you to generate SQL directly from within the language.
from p in Friends.Person, where: p.last_name == "Smith"
Will produce a select query at compile time, no ORM in sight taking up resources and getting in-between you and the database.It probably helps rather a lot that Elixir leaves all the low-level bits to Erlang, and if you check both elixir-lang/elixir and erlang/otp… Elixir is a minor player (according to tokei there are 1417963 lines of Erlang, 306349 lines of C — headers excluded — and 120090 lines of Elixir across the current masters of both repositories)
A great example is destructuring, which someone wrote a macro for, around version 1.2 or so, that got bundled with the language shortly after. You can't do that without changing the language, or being able to extend it with macros.
But in practice, having community-written macros means you'll get several versions of the same one, and there often won't be any clear winner since each will have strengths and weaknesses, and at least some authors will be unwilling to merge or add features or change their version, so that you end up with a bunch of almost-perfect macros and have to settle for their annoying bugs that you know you could fix in 5 minutes if you just made a private fork, but then you end up in the xkcd-standards paradox.
Babel showed that you can successfully achieve the same thing macros do, but outside of the language, by writing a compiler and just targets the language you want to execute. No need for macros to get destructuring, just enable the "destructuring" plugin.
Unfortunately, Babel misses the mark on this dream, because literally every Babel "plugin" is actually implemented in Babel's core library and all the plugins do is just enable a flag or two in the core parser/compiler. It doesn't expose any parser or compiler for you, and you can't actually add new tokens without forking Babel.
I admit I never worked with Babel on the plugin-writing side, but that sounds much more complex than writing macros.
With Clojure macros, and Lisp macros in general, one of the important part is that they run within the same system as the rest of your code. That is, macro logic can be split out to regular functions, that will be executed at compile-time. Macros can reuse functions you wrote to be used at runtime. This property makes a language and your codebase much more coherent wrt. macro use.
Basically, you shouldn't pull in a dependency that permeates your entire codebase. That it is a macro based library shouldn't change this. Right?
Language features often blur this, because people attach an unreasonably high level of trust on them not changing. Used to be, this was completely warranted. Truth to tell, probably mostly warranted even today.
However, this does mean you go at a much slower pace pulling in those features. And, the more any of these permeate what you are doing, the less you are in control of what it is you are doing. Probably fine for many cases, but this is the definition of technical debt. You are taking out a loan on someone else's technical asset (code) to accomplish your goal.
I liken this to being a kitchen builder. If you are just trying to build a few quick kitchen's in standard layouts, Ikea/HomeDepot/Lowes all have fabricated cabinets that are actually quite serviceable and likely build what you want. As soon as you are getting non-standard, those will start to cause some grief, and having not built up experience with custom cabinets is likely to be a source of trouble.
[1] http://stevelosh.com/blog/2018/07/fun-with-macros-if-let/
Is your point that you shouldn’t use new syntax until it gets into the ES standard?
macro swap {
rule { ($x, $y) } => {
var tmp = $x;
$x = $y;
$y = tmp;
}
}
var foo = 5;
var tmp = 6;
swap(foo, tmp);
the article says it expands to this: var foo = 5;
var tmp$1 = 6;
var tmp$2 = foo;
foo = tmp$1;
tmp$1 = tmp$2;
Is that really true? The statement "var tmp = 6" appears in the source code before the place the macro is invoked. Can a sweet macro reach back and modify statements that occurred earlier in the file? var foo = 5;
var tmp = 6;
var tmp$1 = foo;
foo = tmp;
tmp = tmp$1;This was back in 2014 though and sweet has changed a ton since then, so the output is probably different
Oh, believe me, they are NOT.
But whatever.
Why not teach them about macros and have code reviews on things they submit, just like you would normally?
Also, does this macro system have a concept of quoting/unquoting?
With babel-macros, one can write macros that look exactly like function calls. Or, more accurately, one can make any valid syntactical construct expand as a macro. Webpack and friends also do this to an extent with loaders.
In the current Javascript landscape, I don't generally see macros being used for syntactical sugar as much as they are used for code generation: things like "take this SVG file and generate a React component that renders it" or "generate the boilerplate to inject this stylesheet that I added via a ES6 import declaration".
I still like it a lot as an idea, but maybe not in the way it was originally intended. In the last four years people have built parser libraries for JS (of varying kinds), and of course you have what became Babel. And Webpack. You might as well see them as way of plugging in features into the language you're writing and taking macros to an extreme, because it's not pure JS any more.
Yet most of that could be represented as macro definitions if you were to put the work into it. So I actually like the idea of Sweet.js as a really simple way to experiment with JS syntax without investing in parsing a language from scratch, or trying to plug it into Babel.
In the context of JS itself though, it's not a solution I would promote as sustainable. As soon as you see the idea of macros you start to want to think of everything as a macro ("because it produces more optimal code!" or whatever) and then you get a codebase that cannot possibly be maintained, because changing one line of code in your macro isn't always the same as changing the same line inside a function.
It can be. Used judiciously, they can reduce boilerplate and help highlight the important parts of the codebase.
The problem is that they're catnip to a certain type of developer. If they're allowed to proliferate in an uncontrolled way, you can easily end up with unmaintainable code.
Worst case, you'll end up with someone implementing a half-arsed type system at which point you may as well delete the repository (ok, slight exaggeration).
I can't really comment on whether or not JS would be a better language with a good macro system. My guess is probably not but I have no evidence for that.
For example, macros and functions are nearly the same thing: one runs at compile time, the other at runtime. But they both have documentation, and you can jump to a macro's definition the same way you would for a function. You can also compose them together and generate new ones on the fly, etc.
Basically, a lot of the problems with macros in other languages is that macros are considered this special type of not-really-a-function. It's either templating sugarcoat, or restricted turing-noncomplete layer. But if you treat macros as literally functions that just happen to run at compile time, the problems are reduced. And if you treat them with discipline and document what they do, and show examples, and add test cases, then you never have to worry -- just like normal software.
One helpful rule of thumb: If you copy some functionality more than twice, it's probably time to make it a function. If you define a set of functions repeatedly -- like test cases -- or find yourself writing the same pattern over and over, or if you can generate most of your structure automatically based on e.g. "I know this is a React component", it might be time to write a macro.
If this concept sounds intriguing to anyone, I highly encourage you to check out Lumen: https://github.com/sctb/lumen
It's a Lisp that's literally javascript:
Compiled code: https://github.com/sctb/lumen/blob/master/bin/reader.js
Original code: https://github.com/sctb/lumen/blob/master/reader.l
So if you understand Javascript, then there's not much to learn. And you can use it in your own projects right away.
Most of Lumen's brevity is thanks to macros.
(One hack for quickly understanding Lumen: read the tests. Every language feature is meticulously demo'd: https://github.com/sctb/lumen/blob/master/test.l)
Proper macros (Lisp, Scheme, Julia, etc.) are just as readable as functions, since they basically are functions that operate on ASTs.
> Versus proper compiler features (async, =>, type system) + a proper code design.
Macros are a proper compiler/interpreter feature, and enable proper code design.
Relying on the language in place of the facility to write reusable macros is like relying on stdlib in place of the facility to write reusable functions. Sure, ideally you want the common needs to be covered out of the box, but not everything is common enough needs where the solution space is well-enough explored for a standard solution to be the right choice even as a default.
e.g.:
import {insertSnippet} from "polish-and-release-this-someday"
import {mstBoilerplate} from "./some-local-snippet-store"
insertSnippet(mstBoilerplate, {name : "XCardModel"})
//#region mstBoilerplate 20180911
export interface XCardModelInstance extends Instance<typeof XCardModelImpl> {}
export interface XCardModelCreation extends TypeHelp.Id<typeof XCardModelImpl["CreationType"]> {}
export interface XCardModelSnapshot extends TypeHelp.Id<typeof XCardModelImpl["SnapshotType"]> {}
export interface XCardModel extends TypeHelp.Id<typeof XCardModelImpl> {
Type: XCardModelInstance
CreationType: XCardModelCreation
SnapshotType: XCardModelSnapshot
}
export const XCardModel: XCardModel = XCardModelImpl
//#endregion mstBoilerplate 20180911
This means a simple editor extension and very simple command-line tools can be written to expand / refresh the "insertSnippet" lines as needed. mstBoilerplate, basically is a template literal string in typescript / javascript land but you can use whatever makes sense for your language. So this is useful for language that don't want to / can't support macros natively. You end up getting a lot of the boilerplate reduction power, and everything just works.I feel for a lot of cases this works better than macros, the expanded code is checked into version control so there is nothing hidden going on, debugging works, if the code ends up needing to be specialized a bit, it's pretty easy to erase the insertSnippet line / comment lines and start modifying.
In my scenario I’d like to extend the code folding mechanism to show inherited methods and macro expansions inline, folded by default. Then you could drill into a five function and/or macro code flow, without ever leaving the current editor window, if the code has good cohesion.
And if it doesn’t, then this is more incentive to fix your code.
So.. which one is it?
It's almost the case of "one compiler to rule them all", though IMO pervasive changes (like adding a type system) are better done at the compiler-level rather than the macro-level.
Also, macros typically do not carry state between macro instantiations.
As such, with a macro it would be very hard to eliminate null from the language.
Therefore, we need compilers.
Is that really all that different from where much of mainstream javascript-land has ended up?
It might take a moment to familiarize oneself with macros or a DSL, but does that not almost precisely define react component definitions?
Component definitions execute some javascript then spit back JSX and these JSX components can be used in a DSL that doesn't follow javascript syntax?
Pretty much everything it actually "does" for your code is implemented as a plugin, and writing new plugins is relatively trivial if you're familiar with the AST objects and concepts.
Call it macro or AST manipulation, the effect is the same; the language becomes practically infinitely malleable. The only real limits to what JS+Babel can express are those imposed by the host environment (aka DOM APIs, no manual memory mangement, etc.).
To specifically address your last question regarding JSX: Code such as `<MyComponent attribute={value}>Child Contents</MyComponent` becomes something like `createElement(MyComponent, { attribute: value}, ["Child Contents"])` (sorry, I'm going off of memory here).
The transformation is applied by Babel, so it's parsed from the file as a string, transformed into an AST (with the help of the JSX plugin), and re-written back out as vanilla JavaScript to be executed by your browser / server process.
Surprisingly, the answer seems to be no.
Experienced react devs rely heavily on metacomponents: components that take other components as input, and return a combined component as output. It's like oldschool template metaprogramming in C++, but you end up merely wanting to stab yourself in the eye with a fork rather than hurl yourself out the nearest office window.
A proper macro system would make this pattern unnecessary, because you would rely on macros to generate the specialized components. It would spit out react code that you'd otherwise have to write -- or that you'd have to write a metacomponent for.
Note that a metacomponent is not the same as a macro. It's similar, but it still operates at runtime.
Here's a rule of thumb. Can your macro system embed the contents of your /etc/passwd file as a string literal into your codebase? If the answer is no, then you're missing out on significant power.
That is an example of something you might not actually want to do, though embedding a file from the code repository (e.g. as https://doc.rust-lang.org/std/macro.include_str.html does in rust) is a reasonable and common thing to want to do at build time.
> Can you imagine the code that loads a configuration file directly into the code and the ops team unable to reconfigure things?
Yes! That's what code is, actually! Code is stuff you put in a file which can't be configured easily, but is thus consistent between all deployments of the software.
It often actually makes it easier for a problem to be found and reproduced if configuration is baked into the binary vs varying based on the environment the code is run in. In a way, docker images are a means of statically compiling a bunch of random stuff (like /etc/passwd) into your application at build time to remove more environmental variables.
Really, loading a configuration file into the binary statically at build time isn't much different from having `const SOME_VARIABLE = "some value"` in your source code... the only difference is how you, the programmer, chose to represent that constant.
The line between "configuration" and "code constants" is very thin, so I don't think what you say is a sensible criticism.
Do you know if anyone is actually doing this?
edit: As it turns out, https://github.com/facebook/create-react-app/pull/3675, yes!
That aside I don't see what's the problem is with cross compiling to an other language. Other than if your writing a compiler why not compile to machine code. Honestly, I think code generators are better than macros.
Use typescript if you want, but I don't really see the issue. There are funny things related to implicit type conversion and some rules produce funny and unintuitive outcomes. These conversion can be very handy on the other sides.
"Math.min() > Math.max()" and they are damn right that this is true!
> Just use PHP 7! There are funny things related to implicit type conversion and some rules produce funny and unintuitive outcomes. These conversion can be very handy on the other sides.
> "PHP_INT_MIN < PHP_INT_MAX" and they are damn right that this is true!
Feeling the perception difference?
[citation needed]
Let the browser be a document viewer.
Failing that, finalize Web Assembly's design to the point that the browser is just yet another general purpose VM.
WebIDL then defines the APIs accessible to any language that gets compiled into Web Assembly.
My issue with those is, they are less sandboxed than JS is. Why would I want to put one-off things all over my disk and system? While I'm willing to install native applications from the package manager for big things I really need, I do not want to do so for simple one-off interactive things, so I really like that I can just do such things in the browser without installing them. Things like simple games, mathematical demonstrations, ...
I think the value of sandboxed self contained interactive apps that can do graphics, input, sound, that run from a link, is tremendous to humanity.
Of course on the opposite side, one problem is the usage of so much JS for simple articles of text and photos. Those would be more pleasant to read if they were just text and photos and nothing more.
That would require deploying on at least five wildly incompatible native platforms, and break when they change architecture.
The web is not so much an integration layer as the no-mans-land of the platform lockin wars; it's a space that doesn't "belong" to any one platform owner, which is both its great benefit and great disadvantage.
With unblockable banners, uninspectable unmodifiable code and other garbage.
The current state of affairs is just perfect balance, webassembly can seriously hurt the user if it ever gets good-enough direct access to DOM.
This is essentially the idea with WebAssembly. But, for web applications you need security and platform independence, so it's not actual machine code.