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.
Install: $ npm install -g nearley (or try nearley live in your browser here!)
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
Compile your grammar:
$ nearleyc csscolor.ne -o csscolor.js
Test your grammar:
$ nearley-test -i "#00ff00" csscolor.js
Parse results:
[ [ '#', [ '0' ], [ '0' ], [ 'f' ], [ 'f' ], [ '0' ], [ '0' ] ] ]
Turn your grammar into a generator:
$ nearley-unparse -n 3 csscolor.js
#Ab21F2
rgb ( -29.889%,7,8172)
#a40
You try it! Type a CSS color here:
…and the parsed output will appear here!
Create beautiful railroad diagrams to document your grammar formally. See a demo here.
$ nearley-railroad csscolor.ne -o csscolor.html