Skip to content

Instantly share code, notes, and snippets.

@borman
Created October 26, 2014 21:28

Revisions

  1. borman created this gist Oct 26, 2014.
    29 changes: 29 additions & 0 deletions sourcecodegen_wtf.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    def unary(symbol, priority):
    # XXX: BRAIN DAMAGE HAZARD AHEAD
    # Consider prioritize's argument: what's it for?
    # Isn't it expected to be a number?
    # How dare it work and work correctly?
    # Turns out, Python mixed-type comparison semantics are exploited in an
    # awkward way. Python specifies that when no other rules apply, e.g. no
    # overridden comparison magic-methods on any side, it falls back to
    # comparing both sides' type names.
    # One could grep CPython sources for `default_3way_compare' function that
    # defines comparison logic. It also turns out that when comparing a number
    # vs. a non-number, number has an _empty_ type name.
    # As one may observe, '' is less than 'function'
    # Thus, for all int values ``v`` holds:
    # - v < prioritize
    # - prioritize > v
    # - prioritize == prioritize
    # So, ``prioritize`` is effectively is used as an `infinity' constant.
    @prioritize(prioritize)
    def visit(self, node):
    yield symbol
    child = self.visit(node.expr)
    if child.priority < priority:
    yield '('
    yield child
    yield ')'
    else:
    yield child
    return visit