If things look a little dusty around here, it's because I'm away on a mission for two years. I'll be back in August 2012, but in the mean time feel free to fork my projects on github.
CodeTalker by example: translate
Jul 29, 2010
by Jared

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.

blog comments powered by Disqus