nearley.js2.0.0

Parsers turn strings of characters into meaningful data structures (like a JSON object!). nearley is a fast, feature-rich, and modern parser toolkit for JavaScript. nearley is an npm Staff Pick.

nearley 101

  1. Install: $ npm install -g nearley (or try nearley live in your browser here!)
  2. Write your grammar:
    # Match a CSS color
    # http://www.w3.org/TR/css3-color/#colorunits
    
    @builtin "whitespace.ne" # `_` means arbitrary amount of whitespace
    @builtin "number.ne"     # `int`, `decimal`, and `percentage` number primitives
    
    csscolor -> "#" hexdigit hexdigit hexdigit hexdigit hexdigit hexdigit
              | "#" hexdigit hexdigit hexdigit
              | "rgb"  _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")"
              | "hsl"  _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ ")"
              | "rgba" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")"
              | "hsla" _ "(" _ colnum _ "," _ colnum _ "," _ colnum _ "," _ decimal _ ")"
    
    hexdigit -> [a-fA-F0-9]
    colnum   -> int | percentage
    
  3. Compile your grammar:
    $ nearleyc csscolor.ne -o csscolor.js
  4. Test your grammar:
    $ nearley-test -i "#00ff00" csscolor.js
    Parse results: 
    [ [ '#', [ '0' ], [ '0' ], [ 'f' ], [ 'f' ], [ '0' ], [ '0' ] ] ]
    
  5. Turn your grammar into a generator:
    $ nearley-unparse -n 3 csscolor.js
    #Ab21F2
    rgb  ( -29.889%,7,8172)
    #a40
    
  6. You try it! Type a CSS color here:
    …and the parsed output will appear here!
    
  7. Create beautiful railroad diagrams to document your grammar formally.
    $ nearley-railroad csscolor.ne -o csscolor.html
    Output looks like:
    /[a-fA-F0-9]/

    See a bigger example here.

Features

Projects using nearley

Excited? Get started on Github, visit us on npm, explore nearley in your browser on the playground, or try out the calculator demo for more action.