Repository navigation
Description
Related to #440.
Current situation
The current public API of Boa, that can be found here for Boa 0.8.0 and can be seen offline running cargo doc --open for the master branch, is far from optimal. We have 3 global functions:
exec(): That creates a new lexer, parser, Realm and interpreter, and isolates the execution of a given JavaScript string, and return a string with the result.forward(): That will receive an already initialized interpreter and a JavaScript string and will lex, parse and execute this code in the initialized interpreter, and return the result as a string.forward_val(): That will work the same way asforward()but will return aResultValue, which will indicate if the execution was successful or not.
Then, we have the following modules public:
syntax: which includes:ast: the AST implementation (nodes, constants, keywords, builtin types, positions, spans, tokens, operations, punctuators...), with some re-exports to make life easier.lexer: The tokenizer/lexer implementation, that turns a string into a vector of tokens. (this is changing in Started with the new lexer implementation #432)parser: The parser implementation, with its error and a couple of parsers (ScriptandScriptBody), which turns a vector of tokens into aStatementList, that can then be executed with an interpreter.
realm, which includes the implementation of aRealm, an interesting helper function to register a global function, and makes public the global object, environment, and the lexical environment. This in theory allows anyone to add stuff to the global environment, but it's a bit cumbersome.builtins: Where we have the builtin objects such asArray,Number,JSONand more, and also the implementations ofValueand object properties. And the initialization function.environment, which has modules for each of the environments and the global trait, everything exposed because therealmhas public members so that they can be modified.exec: We only contain theInterpreter, with just two public functions:new()andto_string(). The first creates a new interpreter with a givenRealm, and the second one converts aValueto a string. It also contains theExecutabletrait, that allows callingrun()on any AST node passing the interpreter so that it runs it.
Finally, we also have some re-exports to make things easier to use.
Problem description
When a user wants to use Boa for their projects, I can imagine the following use cases:
- They want to interpret JavaScript from a file or a stored String and get the result.
- They want to interpret JavaScript that is coming from a socket with a
Readinterface and get the result by streaming the bytes. - They want to extend our engine by providing new global functions and objects, so that with the JavaScript they can either perform more rich things in their setup (for example by providing an API for a browser window), or because they want to add JavaScript helpers for common actions in their setup. This also includes things as being the scripting language of a complex platform.
- They want to change the
globalobject, for example, because they want it to be thewindowor aframe.
I cannot think of anything else, but there might be others. In this context, our current API is very poor. It does allow most of this (except for the Read interface, that is being worked on in #432). But, it is very difficult to do it if you are not an expert in Boa.
Proposed solution
I think we should go for a global Boa structure. This structure should have a default() function (implementing the default() trait, that would setup a clean environment for the execution. Then a interpret() function that would receive either a &str or a u8 (Read) stream (we might need two functions) and return a ResultValue. We could then call to_string() on this if we needed to show it, for example, or on the Ok/Err variants.
It should also have a new() or with_global_obj() function that would require a custom global object. Note that we don't need to expose all the Gc stuff here, as we would be owning the global object.
One option is for it to receive the full Realm, but I think it's best if we didn't expose the complexity of a Realm. In any case, that global object should be wrapped, to provide an easy to use API:
- It should have a
register_global_object()function, that would just receive a name and aNativeObject. The currentregister_global_func()should be kept (maybe renamining toregister_global_function().
The NativeObject should just implement a trait, and should easily be boxable, or we could use dynamic dispatch. This trait should allow adding native methods to the object, and should implement a way of retrieving and setting fields. I want to be vague about this, because #419 should give us a clear path.
So, what do you think? What could we improve?
Activity
jasonwilliams commentedon Jun 2, 2020
yeah we don't need to expose that really.
For ergonomics we should make it easy to add your own native function to the global object.
Are there any existing standards/interfaces we should be following?
HalidOdat commentedon Jun 2, 2020
Speaking of standard/interfaces we should follow the Rust API Guidelines
Razican commentedon Jun 2, 2020
Not that I know of. We could check how V8 and SpiderMonkey interface with browsers, for example.
HalidOdat commentedon Jun 2, 2020
Neon crate has a nice API. that's were i got the idea of
ctx.throw_range_error(msg)The
ctx.throw_range_error(msg)andctx.throw_type_error(msg)should be public to the userHalidOdat commentedon Jun 4, 2020
In the future we might want to have some kind of procedural macro to make it easy to interoperate from native to javascript
wasm-bindgenhas this and it's awesome, for example:We could have something like this, instead of
wasm_bindgenwe could have to beboa, for example:And the
boaproc macro would automatically generate an init function, so the user only has to call it (Answer::init(global)).For the function:
Where it takes
Selfinstead ofValuewe could have proc macro downcast it toSelfand use it as if it was a native type, this could be done with internal state soAnswerwould requireInternalStatetrait, we could also implement this with troughboaproc marco.This is for objects and methods but we can have something similar for functions.
BTW: I'm just brainstorming.
What do you think?
Razican commentedon Jun 4, 2020
This would be awesome. I would automatically rename to camelCase, though, since that's the usual pattern in JavaScript, and maybe allow to specify the name if needed.
jasonwilliams commentedon Jun 4, 2020
This might need to be
register_global_property(), as global object usually refers to the top level global object itselfwindoworglobalThisetc.I like how in the random crate you have an option to just use it directly without much setup https://rust-random.github.io/book/guide-start.html i think using
Default()helps with this, we should be able to get users up and running pretty quickly.Whats a simple use case? You pass in a string (or path to file) then get a value back.
we could have a fast-path function which gives you back a ValueData enum.
I think
fromString()andfromFile()would be the most explicit and easiest to understand right?How much of this do we want to follow:
https://tc39.es/ecma262/#sec-execution-contexts
Embedding V8 example
For some inspiration this is V8
https://chromium.googlesource.com/v8/v8/+/branch-heads/5.8/samples/hello-world.cc
HalidOdat commentedon Jun 8, 2020
Here is V8 API https://v8.dev/docs/embed (it also has some examples)
jasonwilliams commentedon Jun 9, 2020
#461 implements
Defaultfor Realm which right now includes all the builtins.Here's a Q
Should the
DefaultRealm be empty or have all the builtIns Boa provides?I don't see why anyone would want the empty realm.
Razican commentedon Jun 9, 2020
I think it should have all the builtins, since that should be the "default" behaviour. We can have a
Realm::empty()method, that creates an empty Realm.4 remaining items
HalidOdat commentedon Aug 10, 2020
Yes. you can do this, I have been looking at making this a bit nicer, how
mlua/rlua/quickjs-rshandles functions, something like:Right now we pass the interpreter as the context, but this is not what we want, the interpreter is only a implementation detail, we might remove the
Interpreterto switch to aVmdesign which is a better and faster option. so we wrap the implementation detail e.g theInterpreter, this should make switching Executors designs in the future not breaking changes and easier to implement as well something like:We could also have different contexts for different things
CallContextfor function call contexts:Something similar to
neoncrateContextsThere will be a trait maybe called
FromValueandToValuethat take a context and returnSelf.And two other traits
FromValueMultiandToValueMultithat is implemented on tupels so we can do(name, lastname, age): (String, String, u8)what we did with the closure, we could also implementFromValueMultion a singleT: FromValueso we could so something like:
These methods of passing arguments enables us to have in a way variadic parameters.
We can pass also a function it does not have to be a closure:
Questions that need answers for the API:
FromValueof()unit should benullorundefined? At first it seemsnullbut at second glance in rust unit is returned in every function that has an explicit()return or no return value provided and in js when you don't return anythingundefinedis return, so maybeFromValueof()should beundefined?Defaulttrait onFromValue: Defaultso we can default construct the rust type that implememtsFromValueT: FromValuedo we throw an exception, or default construct it? I would say throw an exception.Right now these are the only thing that popped into my mind, but there are probably more.
What do you think?
Razican commentedon Aug 11, 2020
I would say it should be
undefined. If I develop a Rust function that is callable from JS, I don't expect my Rust function to return anything valuable if I'm not returning it on purpose. I would return aValue::null()if I really need to return anullvalue.Good question. I would just follow whatever happens in JS when you add more arguments to any function. So for example, the
new Date()constructor will receive at most 7 parameters, but if I call it like this:Then the rest of the parameters are just ignored. So I think we should just ignore them too. There is one especial case. What if we want the Rust function to receive a variable number of arguments? In that case, I would say we need a way of calling that function with a slice of the argument list.
So, all Rust functions should have a signature such as:
We can even create a type (
NativeFunction) or something like this and expose it, so that it's easy to handle. Then, we should be able to easily transform those values to Rust with the context at hand.I think this should be solved with the idea above. There is no way in Rust to specify a variable number of arguments, so we will need to make all Rust functions accept a slice of arguments, and then the function itself can check if the number and type of arguments is correct.
Overal, I think this is the way to go, and it looks easy to use. I don't think we can just use any Rust function from JavaScript, but I do think we can allow users to create wrappers with lists of arguments. If we had to create a default wrapper, I would just ignore extra arguments and give a
TypeErrorwhen encountering a type that is not correct, but I do think that many of the Boa users will want to create functions with variable number of arguments, and I do think it's more spec-friendly.Even if we provide a default wrapper for most native Rust functions, I still think we have to expose this, to allow for customizing the behaviour in case the number or types of the arguments is not the expected one.
HalidOdat commentedon Aug 11, 2020
Agreed. this is the way to go if we want to match what js does, in rust.
About the variadic arguments, one way of doing is as you said:
&[Value]would implementFromValueMultiand it should definetaly be possible do this. also there is a second way remember that I defined aCallContextas:and we can implement on
CallContextarguments()method which returns the&[Value]:The equivelent in js is:
This matches nicely with javascript and Rust :)
What if we want to have typed arguments with variadic?
This should be possible by specializing the parameters:
so we could do:
we would have more overloads no just
(A, B, &[Value]), the implementation will include some macro magic so we don't have to write them by hand.The
&[Value]will be empty if only two arguments were supplied and I don't think it should throw it two or more are supplied. Also if we want to access the first arguments to the last one we usecontext.arguments(), if we want a continuation we use the&[Value]in(_, _, &[Value])which is offset by the number of arguments that precede it.also
FromValueMultiwill have a method maybe calledlen/length:so for
(A, B, C)it should be3for(A, B, &[Value])it should be2the number of expected values not including the catch all&[Value]. This way allows us to know the length of a function without specifying manually.Also forgot to mention if
Valueis passed as a parameter(String, Value, &[Value])it is any value.jcdickinson commentedon Aug 11, 2020
FWIW the current internal API is pretty awesome. I've used the ChakraCore integration API in the past, which is designed to be usable for integration (unlike V8), and Boa feels way more ergonomic than even that. The effort involved for a large public interface (
Date) was minimal. Additional abstractions (e.g.#[boa],FromValueMulti) could then operate against this raw public API.IMO simply adding a public
set_datamethod (backed byObjectData::Any<std::any::Any>) would go a long way.Razican commentedon Aug 12, 2020
My experience with overloading stuff is that you have to decide where to stop, and it will increase compile times a lot (I'm looking at you,
diesel). Do we need all this type checking?It's not easy to define a good and only way of going from Rust values to JS values and vice-versa. We can just use
&[Value](probably on the context is good), and let the users deal with value conversions.What would this do? We were talking about adding functions, but something similar could be done to add new objects.
HalidOdat commentedon Aug 12, 2020
If I was a user of
BoaI would love to have this abstraction, I have usedmluaand I love it, it's so easy to get started with minimal setup. while the compilation time will increase by a small amount, I think it's worth having this abstraction. We can have a compromise for this we can put it in a feature flag (FromValue,ToValue,FromValueMulti,ToValueMulti, and all the overload, we can put these in a file and use#[cfg(feature = "name")], this way its the same as#[cfg(test)]), like boaattribteflag for#[boa]if a user does not want to have this abstraction they can disable it and use the raw API.What do you think? @Razican
Razican commentedon Aug 12, 2020
I like the idea of having it behind a feature flag.
HalidOdat commentedon Aug 16, 2020
We have the
Value::to_unit32andValue::to_int32()that convert the value to au32ori32should we rename it toValue::to_u32andValue::to_i32? to match with Rustsu32andi32convention or stick to the specs naming. These are rust functions, so IMO we should rename them.What is your opinion?
Razican commentedon Aug 16, 2020
Yes, I think we should stay close to Rust naming conventions.