The Cruiser Parser Library

Written by on June 1st, 2007 in Ajax News.

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

Parse away.

Source: Ajaxian
Original Article: http://ajaxian.com/archives/the-cruiser-parser-library

Leave a Reply

You must be logged in to post a comment.



Site Navigation