Functional Reactive Bindings, Part 1: The Language
Functional Reactive Bindings, FRB, is a language and a runtime for keeping JavaScript objects consistent with each other. In their simplest form, bindings provide the illusion that two objects have the same property. Changing the property on one object causes the same change in the other.
bind(object, "a.b", {"<->": "c.d"});
I wrote FRB in the fall of 2012 for MontageJS, and in January of 2013 it replaced Montage’s bindings outright. Later I showed it in a talk, The Design Pattern That Shall Not Be Named, as the first of three examples, and described what became of it: it blew up into probably the largest README in all of npm, describing an entire language for observing property changes, propagating change through arrays, and making incremental changes to sliding windows into arrays. And then React happened, and it never saw the light of day.
Folks are not going to use FRB now. So this is not a manual. The useful exercise is to show how to make such a thing: what each combinator computes, how it stays live, and how the pieces fit together. This is the first of four parts.
- The language: the expression grammar, its parser, and the syntax tree. You are here.
- The combinators: the observer each expression compiles to, one by one, with what flows in, what flows out, and what it costs.
- Binders and integration: two-way bindings, the algebra that makes them possible, and how Montage, my Tengwar editor, and Gutentag each meet FRB.
- What I would do over.
Everything here is checked against FRB as I left it, at commit
dcad2e1
of February 2015, the last before the 2016 work that moved it to Collections
5.
Under Collections 1.2.1, its 896
tests still pass on Node 26, and every result printed in these articles came
from running the example there.
A taste #
Here is a binding that keeps an order total.
var bind = require("frb/bind");
var model = {rows: [
{price: 2, quantity: 3},
{price: 5, quantity: 1}
]};
var view = {};
bind(view, "total", {"<-": "rows.map{price * quantity}.sum()", source: model});
view.total // 11
model.rows[1].quantity = 4;
view.total // 26
model.rows.push({price: 1, quantity: 1});
view.total // 27
There are no wrappers here, no observable containers and no set calls.
The model is a plain object with a plain array of plain objects.
FRB arranges for each of them to report its changes, and the total follows
every change synchronously, before the statement that caused it returns.
It also does not recompute the total from scratch. Changing one quantity replaces one product in the mapped array, and the sum subtracts the old product and adds the new one. Pushing a row splices one product onto the end of the mapped array, and the sum adds it. That is the whole design: every expression becomes an observer that turns small changes in into small changes out.
The layers #
FRB is a stack of small modules, and each layer only talks to the one below it.
- Collections makes plain objects and arrays dispatch changes. An observed property gets a getter and setter. An observed array gets mutation methods that report each change as a range change: the values added, the values removed, and the index where that happened. Maps report map changes, a key and its new value.
- Observers (
observers.js) are functions that watch a value and emit new values, and the makers that combine observers into bigger observers. - Binders (
binders.js) are the other side: given an observer for a source, they keep a target in step with it. - Compilers (
compile-observer.js,compile-binder.js) walk a syntax tree once and build the tree of observer or binder functions for it, so nothing is parsed while the graph is being watched. Two more compile the same tree into a one-shot evaluator and an assigner, for reading or writing a path without setting up observers. - The parser (
parse.js,grammar.pegjs) turns text into a syntax tree of plain JSON. bind,observe,computeandBindings.defineBindingssit on top, and are all most people ever saw.
This part is about the language and its parser. The next is about observers, the part that does the work.
The language #
An FRB expression is evaluated against a scope.
The scope holds a value, the object the expression starts from, and a few
other things beside it.
The empty expression is that value, and so is this.
this the value
a.b property b of property a of the value
items.0 a numeric property
items[index] a computed property
$limit property limit of the parameters
$ the parameters themselves
#all the element with id "all" in the scope's document
@owner the component labeled "owner", for Montage
Calling a function is a method call on the left operand.
x.foo(y) means “foo of x and y”.
Every name can be a function, and the compiler decides what it means, as we
will see.
items.sum() the sum of items
items.view(start, length)
words.join(", ")
A block is an expression evaluated once for each value of a collection, in a nested scope whose value is that element.
items.map{price * quantity}
items.filter{!done}
items.some{done}
items.every{done}
people.sorted{age}
words.group{.0}
people.min{age}
Any other function written with a block means the function of the map:
items.sum{price} is items.map{price}.sum().
Inside a block, ^ reaches out to the enclosing scope, so
items.map{this * ^factor} multiplies each item by the factor of the
outer value.
And x.(expression) evaluates an expression with x as its value:
object.(a + b).
There are tuples, [a, b], and records, {a: x, b: y}, which build arrays
and objects whose content follows their expressions.
The operators, from loosest to tightest:
a ? b : c conditional
|| or
&& and
== != < <= > >= <=> comparison
+ - arithmetic
* / % rem multiplicative
** // %% power, root, logarithm
?? default
! + - unary not, number and negation
. [] () {} property, index, call and block chains
% is a proper modulo, toward negative infinity, and rem the remainder,
toward zero.
a // 2 is the square root of a, and a %% b the logarithm of a in base
b.
There is no syntax node for !=: the parser writes a != b as !(a == b),
which, as the README put it, “makes it easier to rotate the syntax tree
algebraically”.
That rotation is how two-way bindings work, in part 3.
The syntax tree #
The parser’s output is plain JSON.
Every node has a type.
Leaves carry a value, an id or a label, and every other node has
args, the syntax trees of its operands.
parse("a.b")
{"type": "property", "args": [
{"type": "property", "args": [
{"type": "value"},
{"type": "literal", "value": "a"}
]},
{"type": "literal", "value": "b"}
]}
A property is not a name but an operation of two operands, an object and a
key, and both of them are expressions.
items[index] has the same shape with a property where the literal was.
So the language has one way to look something up, and the combinator that
does it can observe the key as easily as the object.
Here is the tree for the taste above.
parse("rows.map{price * quantity}.sum()")
Function calls take the name of the function as the node type, with the
object they were called on as their first argument: sum, view, join.
That is why any name can be a function.
The block forms get their own types (mapBlock, filterBlock,
someBlock, everyBlock, sortedBlock, sortedSetBlock, groupBlock,
groupMapBlock, minBlock and maxBlock), with the collection and the
block’s expression as their two arguments.
A few forms are rewritten on the way in, so that the compilers see fewer kinds of node.
a != b {"type": "not", "args": [{"type": "equals", ...}]}
sum{x} {"type": "sum", "args": [{"type": "mapBlock", ...}]}
$id {"type": "property", "args": [{"type": "parameters"}, ...]}
^name {"type": "parent", "args": [...]}
object.(a + b) {"type": "with", "args": [..., {"type": "add", ...}]}
The parser #
The grammar is
grammar.pegjs,
540 lines for PEG.js, which generates the parser in
grammar.js.
It is a classic precedence climb: one rule per level, each calling the next
tighter level for its operands and folding the results to the left.
The interesting rule is the one for chains.
A primary value is followed by any number of ., […], call and block
suffixes, and each suffix produces not a node but a function from the node
before it to a new node.
The pipe rule folds them over the head.
pipe
= head:value tail:chain* {
for (var i = 0; i < tail.length; i++) {
head = tail[i](head);
}
return head;
}
So rows.map{price * quantity}.sum() is value, then a function that wraps
its argument in a property rows, then one that wraps that in a
mapBlock, then one that wraps that in sum.
The block suffix decides there whether a name is one of the ten block forms,
or a plain function written with a block, which it rewrites as the function
of a mapBlock.
The last alternative of value matches nothing at all and returns
{"type": "value"}.
That is what makes the empty expression mean this, and it has a sharp
edge: a + is not an error but a + this.
When the parse does fail, parse puts the location in the message:
Expected end of input but "{" found on line 1 column 10
PEG.js came in June of 2013. The first parser, from September of 2012, was written by hand, in a style that I would later show as the third example of the same talk. Every state of the parser is a function that accepts one character and returns the next state. A production is a function that accepts a callback, and the callback returns the state that follows the production.
// lib/parser.js
function makeExpect(expected) {
return function (callback, loc) {
return function (character, loc) {
if (character === expected) {
return callback(character, loc);
} else {
return callback(null, loc)(character, loc);
}
};
};
}
If the character is the one expected, the callback gets it and says what
comes next.
If not, the callback gets null, and the character is replayed into
whatever state the callback returns, so a production can decline without
consuming anything.
Operators came from a trie of their tokens, one state per character, which
could back up through rewind callbacks when a longer token fell through.
That is the design pattern that shall not be named: a function that takes a
callback, where the callback returns something of the same kind as the
function.
As we will see, FRB’s observers are built the same way, with cancelers where
the parser has states.
The parser memoizes its results by the text of the expression. The same expression parsed twice gives the same tree, so the trees must be treated as immutable. That was a break when it came in, in v0.2.18, because Montage had been modifying trees to reserialize expressions with different component names.
Back to text #
stringify.js
goes the other way, and writes a tree in a normal form, with only the
parentheses that the precedence table in
language.js
calls for.
rows.map{ price*quantity }.sum() → rows.sum{price * quantity}
(a + b) * c → (a + b) * c
a + (b * c) → a + b * c
The normal form is not just tidiness. Montage serialized bindings as text, and when it wrote a component back out it parsed each binding, replaced the components in it with their labels in the new serialization, and stringified the result. FRB also uses it to say what a binding is doing when you turn on tracing.
A sheet #
One more start rule hides at the bottom of the grammar, labeled “MCS extensions”, from June of 2013. It parses a sheet: blocks of bindings, assignments and event handlers, one block for each component label, a little like CSS.
grammar.parse(
"@all { checked <-> @todos.every{checked} }\n" +
"@list < 'ui/list' { content <- @owner.items; on action -> @owner.handleAction }",
{startRule: "sheet"}
)
That returns a sheet with two blocks.
The second names a module for its prototype, and holds a bind statement and
an event statement.
FRB itself never compiled a sheet; only stringify knew one.
It was a sketch of where the language was going, and part 4 is
about that.
Making one #
If you set out to make your own, the language is the easy part, and these are the decisions that made the rest easy.
- Parse to plain data. A syntax tree of JSON can be memoized, serialized, compared, rewritten, and stringified, and every later stage is a function of it.
- Make lookup an operator. With properties as
property(object, key), there is one combinator for every kind of path, and keys can be live. - Rewrite sugar early.
!=, the block forms of functions,$and^all become nodes the compilers already know. - Leave function names open. Since a call is a node named for its function, a compiler can look the name up in a table and fall back to something generic for names it does not know.
- Keep a normal form. You will want to write trees back out.
Functional Reactive Bindings:
- The Language
- The Combinators
- Binders and Integration
- What I Would Do Over