Giving the extensible shell extensible input

Compared with other shells, the way that es reads input from scripts or from an interactive terminal session has historically been badly lacking. Whereas interactive features tend to be a major, or the only, attractive feature of many shells, in es the support for interactivity is meager—and support for customizing that behavior is almost nonexistent.

To some degree this is intentional: es, coming from rc, tries to be relatively minimalist by default. Unlike, for example, fish, the default behavior when dropping into es for the first time will probably always be a simple prompt:

; 

But whatever the defaults are, es is intended to be extensible. It should be perfectly possible to get a more advanced interactive setup akin to fish—and, in fact, being able to do more with input has been a long-term desire for both users and authors of the shell. The fact that this has been impossible thus far has all come down to problems in implementation.

How input works

Like other shells, es can be given shell input in a few forms: an argument (when invoked with es -c); a named file which is opened and read (es script.es); or via standard input (es with no arguments).

When first given an input, depending on which type of input it is, the shell decides whether it should be treated as “interactive”. Interactivity can be forced by the user with the -i flag, but typically the decision is made automatically based on whether the input is both stdin (fd 0) and a TTY (based on the isatty(3) library call). Based on this, one of the two loop functions is called in order to read and execute the input: %interactive-loop if interactive, or %batch-loop otherwise.

These two loop functions are the central part of the es runtime. At their core, they contain a call to %parse, which reads and parses the input and produces a command, and then an invocation of that command.

This looks something like the following. Note that %parse also takes the prompt as its argument list, making something like:

forever {
	let (cmd = <={%parse $prompt}) {
		$cmd
	}
}

There is more to the real loop functions than this, and they are complex and important enough to deserve their own entire page of documentation, but this is accurate as far as the call to %parse goes.

But consider that %parse call. It makes plenty of sense that a function called %parse would perform parsing, of course. But why is %parse also responsible for reading shell input? After all, the shell has other mechanisms to read files. And why does %parse take $prompt as arguments? Can the reading behavior in %parse be changed at all? It’s that exact behavior that we would want to get at, if we want to make es capable of fancy interactivity à la fish or zsh.

Unfortunately, if we try to look at the definition of %parse to get more answers, we get:

; whatis %parse
$&parse

Everything that %parse does is locked away within the $&parse primitive.

$&parse does too much

Given what the $&parse primitive actually does, it would more accurately be called $&readfromshellinputandparse. $&parse does do what it claims to, parse unstructured input to produce a code fragment, but to actually get at that input, it reads from the shell’s input using either special buffered read logic (which can’t be used anywhere else) or readline(3) (which also can’t be called any other way in es).

As it turns out, all this hard-coding is determined by internal details of how the parser interacts with the shell’s memory management. Es’ garbage collector needs to track every bit of shell state to know what can be safely corrected. The parser, which is yacc-generated code unaware of the conventions of the rest of the codebase, holds references to garbage-collected data while it is running, and doesn’t maintain the garbage collector’s reference list, because it has no idea there is such a thing. This means that while the parser is active, the garbage collector may have an invalid list of live references, so it can’t correctly run. Since es code requires garbage collection, it can’t run while the parser is active.

This stinks! A quirk of memory management forces so much to be hard-coded inside of $&parse, where it’s all completely inflexible and invisible to the user. And, because it has the shell’s readline call buried inside of it, there’s nothing like a $&readline primitive that users can call, either—and no way at all to use readline to get any input that won’t then be processed by the parser. In a shell which has been praised for its orthogonality, this is a glaring deficiency.

So, how should we fix this?

As an exercise, let’s forget the implementation and imagine how a hypothetical $&parse should behave from a user’s point of view. At first blush, we want a $&parse which

  1. takes a string argument containing unstructured es code, and
  2. returns code fragment corresponding with that string.

However, this runs into a problem: for most languages, including es, it’s actually impossible to know how much input the parser will need before doing the parsing. Consider the following contrived es snippet as an example:

{
	echo <=%read
	echo <=%read
} << EOF
hello world
goodbye world
EOF

echo hello world
echo goodbye world

The first seven lines must be parsed together to produce a single code fragment, but the remaining three must be parsed separately. But other than by actually parsing, it’s hard to know this; you have to track the {s and }s, and, worse, you have to know when the heredoc starts and ends. You could, potentially, do a sort of pre-parsing pass to figure out how to delimit commands, but it simply isn’t worth it.

Instead, the parser is given a mechanism to request input as it needs it. This is how the internal yacc-generated parser in es works. In the yacc world, the mechanism is a function named yylex(). In es, since we have fancy things like higher-order functions, we can give %parse a reader command as an argument. This might look like, to adapt the previous loop function snippet,

forever {
	let (cmd = <={%parse %read}) {
		$cmd
	}
}

The change between the original loop and what we have here is very small—we’ve just gone from the original {%parse $prompt} to {%parse %read}. (We’ve lost $prompt in this change, but that will be addressed in a second.)

In this case, %read is that reader command that we give to %parse to call whenever it wants to read more input. When $&parse runs, it redirects the internally-managed shell input (whether it’s a file or a string from the command line) to the standard input of %read. This reader command will be called at least once, and potentially many more times, until the parser has received enough input to produce a completely-parsed command.

So, this is our goal design for $&parse.

How do we get interactive features, like prompting, readline, history, and so on, on top of this?

Let’s reorient the design here so that instead of changing how %parse is called within the loop functions, we’re instead producing a %parse function which works the same as before on top of our new $&parse primitive.

We have no way to call readline, so we will have to add one: call it $&readline. We’ll talk about this new primitive in more detail later, but for now it suffices to say that $&readline should take one optional argument, a prompt, and return either a line of input or the empty list, with the same semantics as $&read. (Conveniently, these are also essentially the exact calling semantics of the readline(3) function.) To make things consistent for folks who do and do not include readline in their es, we define a %read-line function which wraps $&readline if present and otherwise is defined as @ prompt {echo -n $prompt; %read}.

We already have a hook function for writing to history, %write-history, so we also need to add a call to that. Putting these things together, with the appropriate scaffolding, creates a %parse which looks like:

fn %parse prompt {
	if %is-interactive {
		let (in = (); p = $prompt(1))
		unwind-protect {
			$&parse {
				let (r = <={%read-line $p}) {
					in = $in $r
					p = $prompt(2)
					result $r
				}
			}
		} {
			if {!~ $#fn-%write-history 0 && !~ $#in 0} {
				%write-history <={%flatten \n $in}
			}
		}
	} {
		$&parse  # fall back to built-in read
	}
}
The new definition of %parse.

The interactive logic is wrapped in an %is-interactive check, for obvious reasons. We also buffer the input that gets read and write it to shell history, and there is also a little logic for picking the right prompt at the right time. Note that a couple specific behaviors become visible here, now that they’re in es script, and they can be changed:

So now we have a new $&parse that has less built-in behavior, and a new %parse which wraps it to maintain the same behavior that it had before.

Reimplementing $&parse

This is the part of the page where I reveal that this change has already been made to es; as of quite recently, $&parse has been reimplemented to take a reader command, and %parse has been rewritten to wrap this new $&parse and provide the same calling convention as before.

So, how was the memory management problem resolved in order to make this possible?

Fixing that took a couple different attempts. My first angle was to fix the parser so that any live references it was holding would be in the GC’s root list. I tried implementing this with a hand-written parser with the appropriate Ref() macro calls scattered throughout the parser code, but I abandoned this when it was turning out to be obnoxiously slow to run.

My next attempt was to rewrite the parser using the lemon parser generator from the SQLite project. Lemon is a pretty great parser generator which has two features in particular that I was interested in: it allows a lot of control over how the parser code is generated, and it generates a “push-style” parser. Together, these two things meant that while the shell was reading input, all the state held by the parser could be encapsulated in a single Parser object which could be wired up so the entire parser could be GC’d as one big blob. This ended up running into some of the same problems as the first attempt.

In general, I was finding that swapping out the entire es parser was too big of a change for what I was going for. Despite not wanting to change anything about the grammar of the language or the actual behavior of the parser, I was swapping the whole thing out, potentially introducing either any number of bugs or a serious performance regression. So I shelved the idea for a while to work on other things.

What brought me back to this goal was the realization that I didn’t have to change the parser in order to change how it performs memory management—I could change the memory management system instead. So, to keep the parser’s untracked memory references safe, I moved them “out of the way”.

In addition to the existing memory “spaces”, for non-garbage-collected and garbage-collected objets, I added a third kind of memory, which I called pspace, for “parser space”. Pspace is a variation on GC space, with one critical difference: it is only ever collected once, where exactly one pointer and its referents are copied out to some other space (typically GC space), at which point the pspace is destroyed. The point of this is that while the shell can’t know which references are live during parsing, it certainly knows what’s live once parsing has finished—the parse tree.

This allowed me to get a proof-of-concept going of this new $&parse, at which point I immediately ran into a new problem. I had forgotten that, because code coming from places like the environment is stored in an unparsed string form, merely running es script often (and at unpredictable times) requires parsing it. Being able to run the parser in the middle of another parse run, therefore, is necessary.

This was yet another hurdle for the shell’s yacc-generated parser, and this time, unfortunately, there was no clear workaround: a portable (POSIX) yacc-based compiler simply must rely on static (global) variables, which means that having two running concurrently in a single thread is not going to work. However, while digging around, I found that yacc parser generators these days seem to be a total duopoly: you can have bison, or you can have byacc. Unlike with C compilers, I couldn’t find any alternatives to try out at all.

So, I cheesed it—es can still be built with either bison or byacc, but it requires at least one non-portable extension which both of them support. To make up for this, I decided to also put the generated parser into the repo, so that anybody just building the shell won’t need a yacc at all.

The extension in question is the line

%define api.pure full

which moves the statically-allocated variables involved in parsing—particularly yylval—into the parameter lists of the parser functions.

After this, the rest of the concurrent parsing work was a matter of moving other static variables into the stack. I defined a new Parser struct which absorbed all of this state, as well as the members of the Input struct which only live over the course of a single parse. Finally, at this point, the changes to actually implement the $&parse described above could begin.

Doing this, after everything else, was actually reasonably simple. There is a function fill() which is called to, well, fill the input buffer used by the lexical analyzer. This function would previously call either readline or read (not the primitive; custom, internal logic of the Input). Changing it to call a command was a matter of saving the command given to $&parse in the Parser, and then looking it up and calling it at fill() time.

The major effort had to do with decisions about small behavioral corner-cases with the EOF and NUL characters.

Historically, the EOF character had a fairly traumatic impact on an Input. If one was encountered, the Input would be put into what could be called “EOF mode”, where it would only ever again return EOF characters. I suspect this was fairly robust for the rc-like behavior intended by the authors, but it was noted a long time ago that it prevented the shell from being capable of something like csh’s ignoreeof. For those using the new-style $&parse, it can also lead to surprising behavior, where an EOF generated by the shell’s input file descriptor can lead to a reader command later not even being called—even if the reader command doesn’t read from that file descriptor. So that has now been changed; more discretion is given to the reader command. Another way that the reader command has more discretion than before is if there is no input file descriptor at all. Previously, that would immediately trigger an EOF, but now the reader command is called, with its standard input redirected to /dev/null so that it has the chance to produce an EOF or not on its own.

As far as NUL characters go, that is largely a matter of the $&read primitive.…

The $&read and $&readline primitives

Es gained the $&read primitive relatively late in its Paul Haahr-implemented era, with the 0.9-alpha1 release. As with some other features added during this period, it didn’t get much of a chance to be “battle tested”, which left it relatively unoptimized, and with some small bugs: in particular, it was completely incapable—to the point of crashing the shell—of reading NUL bytes. Because of this, $&read needed some improvements before it could become the primary mechanism for reading shell input.

The first change was for performance: Historically, $&read would only read one byte at a time, so as to avoid over-reading from a non-seekable file descriptor such as a pipe. This meant that just reading an eight-kilobyte script (the size of my own .esrc at the time of writing) would require eight thousand read(3) calls, which is a pretty significant inefficiency even with modern kernels and libcs which do their best to cache things. This was fixed, for seekable file descriptors, by reading into a probably-larger-than-one-line buffer and seeking to the correct character before returning.

The second change was for NUL bytes. The crash when $&read encountered a NUL was fixed a year or two ago, but because the goal at the time was to merely fix a crashing bug, it was only replaced with an exception. This was still insufficient to replace the existing, intentional, tested behavior for shell input, which was to skip any NUL bytes and print a warning to standard error.

To make this work in a reasonably simple way, I changed $&read so that if it reads a line which contains a NUL character, it splits its return value on that NUL. This should actually work quite well with things like GNU’s find -print0, but also allows skipping the NUL byte or throwing an exception on one. However, it does create a problem: because reading NUL bytes is rare enough that it caused the shell to crash for decades without anybody bothering to introduce a fix, introducing a %read which almost always returns a list of length zero or one, but rarely returns more, creates a lurking mechanism for issues. To fix this, %read is written by default to join any lines that have more than one element, effectively adding behavior to skip NULs. This is reasonably consistent with other shells’ read builtins, and still allows users to opt into other forms of handling NULs when context demands it.

The freshly-added $&readline primitive also required some design decisions. In particular, the major question is this: when working with a standard input which isn’t a terminal, what is the best behavior? Should $&readline still call readline(3), with all the noisy prompting and echoing that implies, or should it configure readline to behave more like $&read, or should it just fall back to calling $&read directly?

My expectation is that a user who wants to use readline typically does not want to have the extra mess of readline unless they are reading from a TTY. This is consistent with the behavior of the shell itself when it implicitly decides whether to be interactive. Unfortunately, no mechanism currently exists in es to allow a user to test if a file descriptor is a TTY, and I have hesitated to add even more behavior to the shell for the sake of this change. Because of this, $&readline falls back to $&read if its standard input is not a TTY. In the future, this should probably be changed so that $&readline is more straightforwardly a wrapper around readline(3).

This decision also introduces a small backwards-incompatibility in the shell. Previously, the following behavior would occur if input was given to es -i on standard input:

; echo 'echo hello world' | es -i
; echo hello world
hello world
; ; 

What’s happening here is that, even though this es’ standard input is not a TTY, because -i has been explicitly provided and its input is the shell’s standard input, readline is called; the extra output here is its prompt and the input it reads being echoed to its standard output.

With the $&readline primitive, that logic has changed. Instead of calling readline when the shell is interactive and the input is the shell’s input, readline is called when the shell is interactive and the input is a TTY. This only really causes a change in the case given above:

; echo 'echo hello world' | es -i
hello world
; 

Different shells have different behavior in this case, so the old behavior is clearly not a universal requirement, and the TTY-based behavior is easier to explain and reason about without getting into details of shell internals. However, this is a change, and it marks a change from rc’s precedent, so it is worth calling out.

Performance

Despite some of the considerations above, the major downside of the implementation thus far is its impact on shell performance. This impact is to some degree inevitable, since migrating any behavior from C to es is going to worsen performance. However, most of it isn’t inherent to the change here, but is instead fixable in the long term.

Some of the changes are internal. For example, a number of buffers and other bits of state that were previously retained across parser calls are now allocated and freed each time, so with certain workloads, allocations have increased quite a bit.

Some of the changes are external: previously the shell would read scripts and other non-interactive input in multiple-kilobyte chunks, but now files are read line-by-line, which means that in order to read a script, calls to read(3) and lseek(3) are an order of magnitude more numerous. Fixing this would require creating a read-in-chunks mechanism in es. Some experimentation thus far suggests that this is the major factor, and that adding this read-in-chunks mechanism would make most of the performance impact disappear.

Implications and further work

In this post, I avoided describing in too much detail how the shell goes about tracking the shell input’s file descriptor. This is because that tracking is inscrutable, internal shell magic which is arranged by the $&parse primitive. The new $&parse, just like the old one, uses this internal magic, exposing it to the reader command as its standard input.

So, while the reader command itself has been exposed to users, all the logic around opening and managing file inputs, remains internal and magic. In particular, we still can’t just use $&parse as a normal function:

; # can you explain the following behavior?
; echo 'hello world' | echo <={$&parse $&read}

; 

Exposing these built-in behaviors and making shell input less magical would be a good path forward. An improvement on the current state of the art would be some mechanism for file descriptors (or, more generally, “handles”) to be lexically scoped. This would provide a more robust way to isolate state between different parts of the shell runtime.

I have been playing around with the idea of “variable-bound file handles”, a mechanism for opening an internal file descriptor which is bound directly to a variable, not exposing a user-visible file descriptor. As I imagine it, these handles would be reference-counted and automatically closed when the last variable reference is dropped. In addition, some metadata could be stored about the handle, such as its filename and, potentially, the current line number; this metadata could effectively eat much of what remains in the shell’s magic Input struct.

The work done on inputs helps make $&parse into a more orthogonal, normal primitive, but it also does the same with the readline library. Previously, readline was relatively deeply integrated into the input-reading code, and at one point support for the alternative editline library was dropped, presumably because it was too obnoxious to support its integration alongside that of readline. Now, everything to do with readline is nearly fully isolated into a single file which defines a few primitives which can be hooked into the shell, plus a few bits of initial.es which do that hooking.

Formalizing and extending how this readline integration works, and making it into a repeatable pattern for other optional libraries, seems like a promising path forward for the shell. The idea here would be a mechanism where users could specify a C file which defines a set of primitives, along with an es script which wraps those primitives in functions to integrate into the shell at build time.

A system like this could reduce the stakes of contributing to upstream es by allowing people to offer code that is only included if opted-into at build time. Further sophistication could then be developed, such as dynamic runtime primitives using dlopen(3), and namespacing of primitives to better express notions such as “which version of $&parse are you using?” These would make es even more extensible than it is, and would allow a single es binary to be extended to contain more primitives as desired.

Of course, in addition to all this, there are extensibility improvements that, thanks to this work, are now possible for $&readline itself. Now that it is possible to run es script while parsing, we can add custom key bindings and a completion hook (or multiple completion hooks, depending on the design). Programmable completion logic would be useful in its own right, but custom key bindings should also allow for integration with things like the funny shell history server atuin, such that iterating through or searching shell history would consult the remote server. These extensions to $&readline represent the most immediate and significant usability improvement for users of the shell who aren’t deep into implementation.