js_of_ocaml
js_of_ocaml copied to clipboard
Standalone javascript file for evaluating ocaml and display type information
Is there a way to generate a standalone javascript file for evaluating ocaml and display type information http://ocsigen.org/js_of_ocaml/2.8.2/files/toplevel/index.html
This will be very helpful for tools like Try Reason and Klipse.
Here:
;; jbuild
(executable
((name evaluator)
(flags (:standard -w A-4-39-40-41-42-44-45 -warn-error A-26-32-58-60 -safe-string -short-paths -strict-sequence -bin-annot -absname -g))
(js_of_ocaml ((flags (:standard --toplevel --linkall +weak.js +toplevel.js +dynlink.js))))
(preprocess (pps (js_of_ocaml-ppx)))
(libraries (js_of_ocaml js_of_ocaml-compiler js_of_ocaml-toplevel compiler-libs))))
(* evaluator.ml *)
let () =
JsooTop.initialize ()
let execute code =
let code = Js.to_string code in
let buffer = Buffer.create 100 in
let formatter = Format.formatter_of_buffer buffer in
JsooTop.execute true formatter code;
Js.string (Buffer.contents buffer)
let () =
Js.export "evaluator" (
object%js
val execute = execute
end)
And build using jbuilder build evaluator.bc.js
.
It installs a global evaluator
with a method execute
: console.log(evaluator.execute("5 + 6;;"));
. The result is a string of the form <varname> : <type> = <value>
(like in the OCaml toplevel; I'm not sure if one can extract the type separately).
For the lazy, I've uploaded the result here: https://gist.githubusercontent.com/copy/7d8d94b6540769abcc507609f4589f95/raw/ad972a2ddbdfd3e851128834e1f12193141621d4/gistfile1.txt
@copy That is fantastic!!!! cc: @chenglou
Here is a jsfiddle that shows it in action. It is also awesome that when we evaluate subsequent code snippets, the variables defined in the previous snippets are available: this is exactly what I need for Klipse.
However, I have notices that when we load both bucklescript and the evaluator script on the same page, it breaks. See this jsfiddle. Is it expected? Can we fix it? This is important because with Klipse, you can have on the same page, ocaml snippet for evaluation and for translation. Therefore, we need both bucklescript and the evaluator script on the same page.
The bucklescript you're using is compiled with js_of_ocaml. It's likely that they interfere badly with each other. I'm not sure I understand you last statement ? You seem to imply that buckescript cannot act as a toplevel
@hhugo is there a way to generate a bucklescript that is not compiled with js_of_ocaml?
It's likely that they interfere badly with each other.
This should be fixed in js_of_ocaml, shouldn't it?
@viebel I don't think so, but maybe we can summon @bobzhang.
I'd suggest to load both scripts in a web worker. That way they won't interfere with each other and also don't block the main thread when a computation takes too long.
The initial issue has been answered. Closing