compiler module supports 'statements as expressions'

Discussion in 'Python' started by Tom Locke, May 4, 2004.

  1. Tom Locke

    Tom Locke Guest

    Hi,

    I am writing a compiler (in python) that targets python byte-code,
    using compiler.ast and compiler.pycodegen.

    The language is lisp-like in that there is no statement / expression
    separation.

    e.g. I can do (in a python-like syntax)

    print (if x: "yes" else: "no")

    or

    while line = raw_input("> "); line != "":
    print line

    Having hacked away for a short while on a translator to make these
    things into separate statements that would be legal in Python, I was
    VERY surprised when I accidentally discovered that this seems to be
    LEGAL at the byte-code level. (CPython 2.3.3, Win XP)

    compiler.pycodegen.ModuleCodeGenerator generates working code for AST
    fragments like these:

    Printnl([If([(Name('x'), Stmt([Const('yes')]))],
    Stmt([Const('no')]))],
    None)

    and

    While(Stmt([Assign([AssName('line', 'OP_ASSIGN')],
    CallFunc(Name('raw_input'), [Const('> ')],
    None, None)),
    Compare(Name('line'), [('!=', Const(''))])]),
    Stmt([Printnl([Name('line')], None)]), None)]))

    AST 'statement' nodes, when used in an expression context, evaluate as
    follows.

    If: value of the executed clause

    Stmt: value of the last statement in the list

    While and Assign: Undefined – python crashes if you try to do
    something with these values.

    This is really very helpful for me – it's just the semantics I wanted!

    I think I'm right in saying that there's no legal Python that parses
    into ASTs like these, right?

    Can I rely on this?? Is it there for a reason? (e.g. to support
    certain optimizations?) Is this just serendipity – the 'natural'
    behavior of the stack based byte-code interpreter?

    Thanks,

    Tom.
    Tom Locke, May 4, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Neil Zanella
    Replies:
    8
    Views:
    1,167
    mfmehdi
    Oct 20, 2006
  2. Wei-Chao Hsu
    Replies:
    1
    Views:
    320
    jacob navia
    Jul 26, 2004
  3. Harry George
    Replies:
    6
    Views:
    362
    Bart Nessux
    Feb 23, 2004
  4. Vince
    Replies:
    12
    Views:
    736
    Martin Gregorie
    Jan 21, 2008
  5. John Crichton
    Replies:
    6
    Views:
    253
    John Crichton
    Jul 12, 2010
Loading...

Share This Page