Skip to content

Evaluate constant expressions during compilation #772

@JukkaL

Description

@JukkaL

CPython does constant folding but mypyc doesn't. This can result in performance reduction in compiled code, so it's important to have this working, at least in common cases.

For example, consider this code:

C: Final = 5
x = [4 * 6 - 3, 1 + C]

This should generate the same code as this:

C: Final = 5
x = [21, 6]

Based on some experimentation, at least these things are supported by CPython:

  • Integer arithmetic
  • Bitwise operations
  • Float arithmetic
  • String operations
    • +
    • *
  • Bytes operations
    • +
    • *
  • Complex + int OR int + Complex
  • Tuple construction
  • Tuple indexing (int index)
  • String indexing (int index)
  • Tuple concatenation

#726 and #619 are related.

For extra credit, we can also detect local variables that have constant values:

def f() -> None:
    x = 'foo'
    y = x + 'bar'   # Simplify to y = 'foobar'
    ...

Metadata

Metadata

Labels

codesizeReducing the amount/verbosity of the C code mypyc generates.speed

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions