11 ms·
Stop Writing JavaScript Compilers. Make Macros Instead (2014)
- nialv7 8y ago> so they (C macros) are pointless except for a few trivial things Oh, believe me, they are NOT.
- jedimastert 8y agoRight? This seems a little obnoxious. I could totally see doing all of the things he talked about with C macros. But whatever.
- hw_penfold 8y agohttps://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule
- ChrisSD 8y agoSince C macros are glorified copy/paste, you can do anything with C macros... which was the point, I think.
- KingMob 8y ago??? Not sure what you're getting at. You can't actually use the language itself from inside a C macro, like you could a Lisp.
- deleted 8y ago[deleted]
- loosetypes 8y agoSo CL macros often follow the pattern of several forms of processing before returning a quasiquoted expression using the results of those earlier forms. That is, some regular code lisp code, followed up by, I guess I'll call it, a DSL. 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?
- zdragnar 8y agoBabel, the defacto JSX (and ES2015+ syntax) "compiler" has basically become a general purpose AST manipulation engine. 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.
- shawn 8y agoIt might take a moment to familiarize oneself with macros or a DSL, but does that not almost precisely define react component definitions? 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.
- coding123 8y agoHopefully etc/password is a bad example? Security issues aside, I feel like reading files that are configuration in nature are best done "at runtime" not compile time. Can you imagine the code that loads a configuration file directly into the code and the ops team unable to reconfigure things? That would be the epitome of "well it worked in MY build".
- romanovcode 8y ago> when run through the sweet.js compiler. So.. which one is it?
- castlegloom 8y agoTypeScript it is, then.
- carry_bit 8y agoThe title says writing compilers, not using compilers. 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.
- fithisux 8y agoBut there is Biwascheme.
- anfilt 8y agoHonestly, can we just stop writing java-script. Even better remove java-script from webpages. Oh wait that boat sailed a while ago. 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.
- gnode 8y ago> Honestly, can we just stop writing java-script. Even better remove java-script from webpages. > Other than if your writing a compiler why not compile to machine code This is essentially the idea with WebAssembly. But, for web applications you need security and platform independence, so it's not actual machine code.
- Aardwolf 8y agoWhich method do you propose instead for people to run interactive applications?
- pjmlp 8y agoInternet protocols and native applications. 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.
- gear54rus 8y ago> general purpose VM 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.
- pjmlp 8y agoI fail to see how that is any different from minified JS.
- lolive 8y agoI have never used macros. Is it really that much productive and readable? Versus proper compiler features (async, =>, type system) + a proper code design.
- infinite8s 8y agoThose compiler features were all implemented as macros at some point in the history of language design. The thing about macros is that they allow you to experiment with language design in the language you are working with (which is obviously much easier when your language is homoiconic).
- lucozade 8y ago> Is it really that much productive and readable? 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.
- shawn 8y agoEmacs is a very important ecosystem that effectively uses macros. The danger of macro overcomplication is real, and emacs' conventions are the primary way they avoid introducing problems. 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 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 https://github.com/sctb/lumen/blob/master/bin/reader.js Original code: https://github.com/sctb/lumen/blob/master/reader.l 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 https://github.com/sctb/lumen/blob/master/test.l)
- andy_ppp 8y agoAfter using Elixir I love that 90.1% (according to github) of the language is written in Elixir and the excellent macros system is a major reason for this. 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.
- masklinn 8y ago> After using Elixir I love that 90.1% (according to github) of the language is written in Elixir and the excellent macros system is a major reason for this. 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)
- sdegutis 8y agoClojure had this same property, and it seems like a benefit at first: because new "language features" aren't tied to releases of the language, anyone can create them and instantly share them with the community for everyone to immediately start using. 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.
- overgard 8y agoIts not exactly equivalent, but having spent the last month debugging a nightmare of C++ template meta programming mixed with a lot of C macros... I think things like this can be nice if they’re applied tastefully but I wouldn’t trust 99% of programmers to be judicious with these things. As someone else said, it’s catnip to a certain type of coder. It also creates a really nasty implicit dependency — you can’t pull out individual components because they’re dependent on the DSL, and who knows what dependencies the DSL pulls in? I would actually argue that macros might be why Lisp didn’t become mainstream; it creates a lot of fragmentation. Most people don’t even want to learn the syntax of their build system, asking them to learn some weird language extensions they can’t take to their next job seems like a rough sell 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.
- tincholio 8y ago>but I wouldn’t trust 99% of programmers to be judicious with these things The evil elitist in me wants to qualify that as "99.99999999% of JS programmers".
- deleted 8y ago[deleted]
- mitchty 8y agoYou've obviously not met many C programmers. I have a new general rule: if it confuses clang-format, it probably shouldn't be a macro in the first place. 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?
- sdegutis 8y agoLanguages, macros, libraries, and apps are in descending order of how many people will use them and how tightly coupled they are to their problem domain. Thus they should be designed and created in descending order of experience and domain expertise. Very few people should create languages, a few more macros, etc.
- antihero 8y agoPlease no, I'd much prefer the logic of taking nice things like types and new features and having them implemented by a central team that knows what they're doing as opposed to being implemented on a per-team/project basis by people have no idea what they they are doing.
- jjnoakes 8y agoDo you let the people who have "no idea what they are doing" write functions too? Put code into production? You pay them right? You train them? Why not teach them about macros and have code reviews on things they submit, just like you would normally?
- benjaminjackman 8y agoSomething I have been experimenting with what I call "persistent snippets", over frustration with boilerplate. Basically when inserting a snippet into an editor it leaves behind a magic comment, that lists the parameters of the snippet, and wraps the snippet code in a //#region to enable folding in editors and languages that support that. 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.
- hinkley 8y agoInteresting. I had the opposite idea a while back, inspired by a coworker who struggled greatly with indirection. 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.
- deleted 8y ago[deleted]
- platz 8y agoMacros typically have limited scope compared to a compiler, and tend to operate locally. 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.
- tzs 8y agoIn this example: 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?
- jlongster 8y agoMacros cannot reach back like that, no. The renaming of the variable is due to sweet's hygiene system that operates on the program as a whole - if two variables with the same name exist in the same scope it will rename them to ensure uniqueness.
- ianbicking 8y agoBut then shouldn't the rewriting be like this? var foo = 5; var tmp = 6; var tmp$1 = foo; foo = tmp; tmp = tmp$1;
- jlongster 8y agoIt could rewrite it like that, yeah, but sweet renaming all collided variables, likely to make it clear that they collided. It doesn't try to keep the distinction between what a macro introduced and what was already in scope (not worth the complexity). This was back in 2014 though and sweet has changed a ton since then, so the output is probably different
- pmarreck 8y agoThis was written in 2014. What's the js macro scene look like today? Has Sweet grown in usage/utility? Also, does this macro system have a concept of quoting/unquoting?
- amelius 8y agoHow do you define in what order macros are applied?
- KingMob 8y agoDunno about sweet.js, but in Lisps, it's usually source order. E.g., read the next token, is it at the head of the list and names a macro, if so, call the macro function, and pass in the code as the param, take the output and replace the macro form with the expanded version, resume reading...
- ljm 8y agoI remember when Sweet.js was first announced, I was excited by it so I started playing around. 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.
- dang 8y agoDiscussed at the time: https://news.ycombinator.com/item?id=7025261 https://news.ycombinator.com/item?id=7025261
- lhorie 8y agoWorth noting that sweet.js mostly fell by the sidelines after Babel came along. 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".