johnynek / bosatsu

A python-ish pure and total functional programming language
Apache License 2.0
226 stars 11 forks source link

More improvements to MatchString codegen on Python #1269

Closed johnynek closed 1 day ago

johnynek commented 1 day ago

I am mostly doing this to just practice improving code generation on an easier target than C. Since I can run the tests under python I have good confidence the changes make sense. Also, the generated code is fairly easy to read.

With this PR, these examples:

def starts_with_foo(s): s matches "foo${_}"
def ends_with_foo(s): s matches "${_}foo"
def contains_foo(s): s matches "${_}foo${_}"
def contains_foo_bar(s): s matches "${_}foo${_}bar${_}"

compile to:

def starts_with_foo(s):
    ___t14 = 0
    return s.startswith("foo", 0)

def ends_with_foo(s):
    ___t15 = 0
    return s.endswith("foo")

def contains_foo(s):
    ___t16 = 0
    return "foo" in s

def contains_foo_bar(s):
    ___t17 = 0
    ___t18 = 0
    ___t19 = False
    ___t20 = s.find("foo", ___t18)
    if ___t20 > -1:
        ___t21 = ___t20 + 3
        if s.find("bar", ___t21) > -1:
            ___t19 = True
            ___t18 = -1
        else:
            ___t18 = ___t20 + 1
    else:
        ___t18 = -1
    return ___t19