Library to parse JavaScript in opam?

Hello,

Is there a library to parse JavaScript code in opam? I know of many OCaml projects dealing with JavaScript, but I have not found an easy way to have a JS parser to use in my project.

Best,
Alan

There is a parser in js_of_ocaml, I don’t remember how reliable it is, but it worked for my use. Here is the piece of code to parse a file.

There is also a parser in facebook/pffff, but the code seems outdated and hard to extract.

3 Likes

https://opam.ocaml.org/packages/flow_parser/

This is part of Facebook’s Flow typechecker for JavaScript, and Flow is used to type the hugely popular React.js library. It is highly likely to be kept up to date.

Looks like the entry points are here: https://github.com/facebook/flow/blob/0970415dd8f880cbd736c86a37205aff8e5c84ab/src/parser/parser_flow.ml#L370

EDIT: although they haven’t been publishing to Opam for quite a while. You should probably pin to the most recent version, https://github.com/facebook/flow/blob/31aa95d9fe7c9d100a071a66506797593b5ef2b6/flow_parser.opam

1 Like

Thanks, this is most useful!

I’ve looked at Flow, but I did not know they released the parser separately. I hope I can use it as a library. Thanks for the investigation!

It’s fairly easy:

$ opam pin add flow_parser https://github.com/facebook/flow.git
[flow_parser.0.80.0] synchronised from git+https://github.com/facebook/flow.git
flow_parser is now pinned to git+https://github.com/facebook/flow.git (version 0.125.1)
... # prompts to continue rest of install
$ utop
utop # #require "flow_parser";;
utop # Parser_flow.program "var x = 1;";;
- : (Loc.t, Loc.t) Flow_ast.Program.t * (Loc.t * Parse_error.t) list =
... (* the parsed AST here *)

The AST is pretty noisy with location info, but it seem to work :slight_smile:

5 Likes