Register Now
/** * @package WordPress * @subpackage Enterprise_LAMP */

Jared Forsyth: CodeTalker by example: translate

Posted on | July 29, 2010 | No Comments

This post looks better on my blog

This is the third in a four-part series, in which I demonstrate how to build a CSS parser using CodeTalker:

To get the code for this:

git clone git://github.com/jabapyth/css.git

Translation

[for the impatient, here's the final code ].

Like everything else in CodeTalker, translation is mean to be straightforward; you have an abstract syntax tree, which is cool, but what you really want is...in this case, an object which represents a stylesheet. So you have a StyleSheet class and a RuleSet class, but how do you go from AST to that?

In general, you'll create one translation rule for each grammar rule. Here's the code for our stylesheet rule to refresh your memory.

def style_sheet(rule):
    rule | ([charset], star(import_), star(section))
    rule.astAttrs = {
            'charset': charset,
            'imports': [import_],
            'sections': [section],
        }

And here's what it takes to translate it:

@t.translates(ast.StyleSheet)
def stylesheet(node):
    ss = StyleSheet()
    if node.charset is not None:
        ss.charset = t.translate(node.charset)
    ss.imports = list((imp.source, imp.media) for imp in node.imports)
    ss.rules = []
    for section in node.sections:
        if isinstance(section, ast.Ruleset): # right now I'm not dealing
                                             # with other kinds of sections (media, page, font_face)
            rule = t.translate(section)
            if rule is not None:
                ss.rules.append(rule)
    return ss

Create the object, populate it with the AST node, and then return it. And register the function w/ the translator object.

Comments

Leave a Reply






Warning: include(/home/remarkwit/enterpriselamp.org/wp-content/themes/Enterprise_LAMP/r_sidebar.php) [function.include]: failed to open stream: No such file or directory in /home/remarkwit/enterpriselamp.org/wp-content/themes/Enterprise_LAMP/index.php on line 36

Warning: include() [function.include]: Failed opening '/home/remarkwit/enterpriselamp.org/wp-content/themes/Enterprise_LAMP/r_sidebar.php' for inclusion (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/remarkwit/enterpriselamp.org/wp-content/themes/Enterprise_LAMP/index.php on line 36