Friday, June 1st, 2007

The Cruiser Parser Library

Category: JavaScript, Library, Prototype

Dan Yoder has recently developed a small (2.5k) JavaScript library for creating top-down recursive descent LLk parsers, Cruiser.

Dan uses it himself to parse stylesheets, to support CSS3 selectors.

Here is the parser:

javascript

  1. with ( Parser.Operators ) {
  2.   var g = Behaviors.Stylesheet.Grammar;
  3.   var t = Behaviors.Stylesheet.Translator;
  4.   // basic tokens
  5.   g.lbrace = token('{'); g.rbrace = token('}');
  6.   g.lparen = token(/\(/); g.rparen = token(/\)/);
  7.   g.colon = token(':'); g.semicolon = token(';');
  8.   // attributes
  9.   g.attrName = token(/[\w\-\d]+/);
  10.   g.attrValue = token(/[^;\}]+/);
  11.   g.attr = pair(g.attrName,g.attrValue,g.colon);
  12.   g.attrList = list(g.attr,g.semicolon,true);
  13.   g.style = process(
  14.     between(g.lbrace,g.attrList,g.rbrace),t.style);
  15.   // style rules
  16.   g.selector = token(/[^\{]+/);
  17.   g.rule = each(g.selector,g.style);
  18.   g.rules = process(many(g.rule),t.rules);
  19.   // comments
  20.   g.inlineComment = token(/\x2F\x2F[^\n]\n/);
  21.   g.multilineComment = token(/\x2F\x2A.*?\x2A\x2F/);
  22.   g.comments = ignore(
  23.     any(g.inlineComment,g.multilineComment));
  24.   // parser
  25.   Behaviors.Stylesheet._parse = process(
  26.     many(any(g.comments,g.rules)),t.parse);
  27. }

Parse away.

Posted by Dion Almaer at 8:36 am
6 Comments

+++--
3.4 rating from 16 votes

6 Comments »

Comments feed TrackBack URI

now for those who have no clue what you’re talking about… what would I use this for? :-)

Comment by boodie — June 1, 2007

That would be 2.5k, plus cruiser.js (4.5k) plus Prototype 1.5.1 (21.36k) equals 28.36k.

Comment by Johan Sundström — June 1, 2007

I don’t understand why devs fail to understand how to truley use JavaScript and their Frameworks.
The code is around 17kb if you use it right.
http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
http://code.google.com/p/minify/
http://www.devpro.it/php5_id_145.html
http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files

Comment by Todd — June 1, 2007

This is a niche kind of library that I am personally *very* interested in. Thanks much for the lead, Dion.

Comment by Steven Levithan — June 1, 2007

On a related note, has anyone heard of a javascript parser that can read in an XML dtd and turn it into some kind of useable properties?

Comment by Mike Ritchie — June 3, 2007

@Mike Ritchie,
Here’s a lead: http://xmljs.sourceforge.net/
Or you could try to pull it off yourself using Cruiser.

Comment by Steve — June 3, 2007

Leave a comment

You must be logged in to post a comment.