Repository navigation
Description
While there are still a number of high-level design issues to sort out, I think we're approaching a kind of uncanny valley in the design repo where it's difficult to get more concrete without having a more formal specification (of module structure, loading, runtime semantics, text and binary representations, etc).
I'd like to propose that we create a new WebAssembly/spec repo that contains:
- a more-formal specification (more on this below)
- a unit test suite testing everything in (1)
- a reference interpreter of everything in (1) that can run (2)
and that we keep the 3 in sync as we land into the repo. Discussion would still continue in the design repo until all features were relatively well understood before getting nailed down in the spec repo.
To avoid cyclically blocking on the specification of the binary/text format, and following the lead of llvm-wasm, I'd propose we start with representing wasm module ASTs as S-Exprs (in the tests and reference interpreter). This will allow llvm-wasm to run end-to-end tests.
The big question is how to write the formal specification. To be clear, this doesn't have to be in the final form that would be standardized; just something concise that lets us be fully specific. One idea we've talked about already is to have an operational semantics. In my opinion, the advantages include:
- operational semantics makes it easier to reason on both sides (producing and consuming wasm); and
- this is a widely used technique for expressing language semantics in the language research community and the introductory material (e.g. [1][2]) is taught in many PL courses.
The problem with operational semantics is that they are often written using a symbolic formalism that isn't very easy to get into and you need some non-ASCII tool (like Tex) to make it look nice. However, at the heart of it, all the symbolism is usually expressing is some pattern match on the current state and then how to compute the next state(s). That sounds like something we can express using code!
So, my proposal is that we initially express our operational semantics in a popular typed functional language (e.g., ML or Haskell). To make this clear, I'll give a short sketch of how this might look in ML (disclaimer: I haven't written any ML in a while...).
First, we'd define our AST as an algebraic data type (one of the perks of using a functional language). A highly incomplete, but hopefully suggestive example:
type wasm_module = { exports : export_section;
functions : function_section }
and export_section = export list
and export = { function_index : int }
and function_section = func list
and func = { arguments : local_type list;
return : local_type;
locals : local_type list;
body : expr }
and local_type = Int32 | Int64 | Float32 | Float64
and expr = If of expr * expr * expr
| Forever of expr
| Block of expr list
| GetLocal of int
| SetLocal of int * expr
| Add of expr * expr
| I32Literal of int32
Next, we'd define an execution state as another type:
type state = int array (* linear memory, ideally we'd have a uint8... *)
There is no explicit evaluation stack necessary assuming that execution is defined by recursive evaluation. With these two types, the meat of the specification can be defined as functions that use these types:
let well_formed (m:wasm_module) : bool =
(* check types, indices in bounds, and other AOT criteria that issue errors *)
let initial_state (m:wasm_module) : state =
(* a wasm_module determines the initial state before the first function executes *)
let evaluate (m:wasm_module) (s:state) (export:int) (args:value list) : state * value =
(* evaluate a call to export given args; return the result and new state *)
let to_binary (m:wasm_module) : int list =
(* define the binary format by mapping from the AST to a sequence of bytes *)
let to_text (m:wasm_module) : char list =
(* define the text format by mapping from the AST to a sequence of chars *)
In my opinion, the advantages of defining our semantics in code include:
- The spec could be the reference implementation (with some scaffolding to slurp in files, parse the S-Expressions, and print results).
- The combination of static type system and unit test suite will catch a lot of the silly nonsensical bugs that tend to creep into prose specs.
- By being able to "run" the spec against the test suite, we'll have a pretty strong confidence that we're defining and testing what we think we are.
- I expect most people working on WebAssembly either already know or could quickly pick up a typed functional language (esp. the small, idiomatic subset we'd stick to within the spec).
A few additional notes:
- There is precedent for defining semantics in code. For example, the ill-fated ES4 was being defined in ML.
- We can use the language's module system to separate out all the things the wasm semantics want to depend on, like IEEE754-defined operations. That is, we could have an IEEE754 module that is taken for granted by the wasm spec and called to implement different wasm ops.
- Nondeterminism can be expressed by idiomatic use of a special random-value-returning function. Some tests can declare there should be no nondeterminism so this special function would trigger a failure. Other tests could specify a range of acceptable output values and the test could be run multiple times with different random seed values to more-exhaustively (but, of course, not definitely) validate.
- An obvious cliff where this all gets really complicated is the memory model when we get threads. One option is to do the usual jump to a separately (non-operationally) defined happens-before relation (just like C++). However, there is also good precedent [1] for defining memory models operationally which claim that the operational style is simpler to reason about. Fortunately, I think we can make this decision later on, after we've fully defined the semantics of single-threaded execution.
- Watching the K framework overview just now (as suggested by @titzer), it seems like it could actually be pretty nice to use instead of a classic typed functional language: it allows direct execution (like the reference interpreter discussed above), has nice pretty output, reasonable ASCII input. Does anyone have any experience with this tool? If nothing else, I'll play with it for a while and see how easy it is to use.
Activity
jfbastien commentedon Jul 31, 2015
Broad strokes sgtm.
@kg was working on a syntax today. It was more of a tokenizer, which required a validator on the resulting tree. That's nice because we spec wasm in terms of strings for operations, so the grammar stays the same, just the strings that are "known" to the validator change.
Operational semantics / interpreter is the next step.
On non-determinism: use taint tracking instead or random? Agreed threads are still hard, but tsan-like tools can help. A formalization of the memory model would also be nice!
m4b commentedon Jul 31, 2015
W.r.t. memory model specs:
As for other things, I'm definitely of the opinion that some nice, hard, formal specs would be great; so people (me included) can start hacking on some things with a more firm direction. And being completely biased, I like the idea of using an ML dialect for a spec/interpreter. I'll write one regardless of the decision on that end :)
lukewagner commentedon Jul 31, 2015
@jfbastien Nondeterminism isn't necessarily a bad thing that requires tainting; it just means that the semantics gives the machine several options and one is taken. Now, in the specific case of nondeterminism resulting from a racey load, it might make sense to produce a single, tainted value instead of a nondeterministically-chosen random value. We'll just have to think through the ramifications (such as including a new taint value in every value type and adding an "if tainted" check in every single operation and what this buys us).
kg commentedon Jul 31, 2015
My plan at present was to formalize a simple grammar for an s-expression representation, essentially tokenizing a simple text format that you can use to describe a whole wasm module.
Then based on that, a parsing/validation layer that converts the tokenized sexprs into a valid wasm module, using the opcode definitions from ASTSemantics, etc - essentially a description of how to map the abstract sexprs and the abstract ASTSemantics to each other.
@jfbastien and I thought it made sense to define the sexpr grammar in very simple EBNF, and then implement it and a basic validation layer in a straightforward ML. Like you describe, the upsides of having it be in code instead of prose are significant.
I've roughed out the grammar and I'm moving on to prototyping and starting to feel out the parsing layer and interaction with ASTSemantics. Ideally we can find a way to map most of what's in ASTSemantics so that it translates very naturally to ML type definitions and then we can easily round-trip those between sexpr and AST.
lukewagner commentedon Jul 31, 2015
I've been assuming that, given an ML (or other language) type definition, the mapping to/from S-Expressions would be pretty mechanical (once you decide on the convention for how to represent tuples, records, and variants); do you not expect that to be the case? Assuming so, I think the only thing we need to define is the type definition and all the parsing would follow from that. Alternatively, if we go the K Framework route, you define your syntax in an annotated EBNF and it takes care of all the parsing for you (it's like a type definition + a free parser).
lukewagner commentedon Aug 4, 2015
From a comment in #263, a proposed addition to the above plan is that we first focus our efforts on defining the AST and its execution, and postpone defining the text/binary representations (
to_text/to_binaryabove) until after we can compile large codebases to the AST (represented as S-Expressions). This could be achieved by making enough progress on llvm-wasm and/or by modifyingpack-asmjsin polyfill-prototype-1 to compile asm.js to S-Expressions. This would allow us to pretty easily conduct apples-to-apples, real-world experiments. In the meantime, engines could consume S-Expressions directly in order to experiment with the semantic design. Given our current goals of only standardizing the bottom layer of the binary encoding, it should not take long to go from an engine consuming S-Expressions to an engine consuming layer 0.rossberg commentedon Aug 4, 2015
This sounds like an excellent plan. I'm obviously biased, too, but IME having an AST definition and a clean reference implementation in s.th like ML indeed is the most productive way of prototyping a spec: readable, with valuable sanity checking, and typically fast turn-around for changes or experimentation.
(The advantage of using the K framework is less clear to me. It is interesting, but still has a long way to go before it becomes a comparably stable and durable technology. If you want something formal but mechanised, plain Coq would probably be a much safer choice at this time.)
@lukewagner, you didn't define the type
value. ;)BrendanEich commentedon Aug 5, 2015
KJS (not to be confused with old KDE JavaScript) link:
http://fsl.cs.illinois.edu/index.php/KJS:_A_Complete_Formal_Semantics_of_JavaScript
When @titzer and @samth concur, I listen.
naturaltransformation commentedon Aug 5, 2015
Another possibility is Lem http://www.cl.cam.ac.uk/~pes20/lem/, which can generate an OCaml reference implementation (the executable aspect) and scripts for multiple theorem provers including Coq, Isabelle/HOL in addition to LaTeX typeset files. It has been used successfully to model C++11 and multiprocessor concurrency.
lukewagner commentedon Aug 12, 2015
We have agreement to go ahead with this basic plan in the spec repo using ML for now for rapid iteration and reserving the option to switch to a more formal framework once things have stabilized. I don't see anything left to do here, so closing this issue.
lukewagner commentedon Aug 19, 2015
I just wanted to give an update: to demonstrate the flavor of what a K spec looks like, the author of KJS (the K formalization of JS) prototyped a K definition of what's currently in ml-proto over the weekend. It's impressively concise. The K folks have said they'd be interested to continue prototyping as the ML-spec evolves. I still think it's a good idea to hack full speed ahead on the ML proto for now, but I'd like to consider K again once things stabilize. (The test suite, SExpr language etc would stay the same, of course.)
AndrewScheidecker commentedon Sep 11, 2015
FYI I have a path now in WAVM to translate ASM.JS code into the spec interpreter syntax via the polyfill-prototype-1 encoding. There's an example of a small program (plus a lot of libc++ code) here: https://github.com/AndrewScheidecker/WAVM/blob/master/Test/Benchmark/a.out.wast