basalt

tests/types.py

"""Check expected behavior and identical diagnostics through the two public frontends."""
from pathlib import Path
import os
import random
import subprocess
import tempfile

ROOT = Path(__file__).resolve().parents[1]
VM = Path(os.getenv("BASALT", ROOT / "basalt")).resolve()
ENV = dict(os.environ, BASALT=str(VM))

with tempfile.TemporaryDirectory() as directory:
    src, exe = Path(directory)/"suite.bas", Path(directory)/"suite"

    def both(source, expected="", *, failure=None, args=()):
        src.write_text(source)
        subprocess.run(["sh", ROOT/"build-native.sh", src, exe], check=True, env=ENV)
        for cmd in ([VM,"run",src,*args], [exe,*args]):
            p = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
            assert p.stdout == expected, (cmd, p)
            if failure:
                assert p.returncode == 1 and failure in p.stderr, (cmd,p)
            else:
                assert p.returncode == 0, (cmd,p)

    def reject(source, diagnostic):
        src.write_text(source)
        for mode in ["run","emit-c"]:
            p = subprocess.run([VM,mode,src], capture_output=True,text=True,timeout=5)
            assert p.returncode == 1 and diagnostic in p.stderr and not p.stdout, (p,source)

    both((ROOT/"examples/shapes.bas").read_text(), "Shape: rectangle\n7.5\nShape: rectangle\n20\n")
    both((ROOT/"benchmarks/dispatch.bas").read_text(), "88\n", args=["4"])
    both('''FUNCTION fact(n AS INT) AS INT
    IF n <= 1 THEN
        RETURN 1
    ENDIF
    LET local AS INT = n
    RETURN fact(n-1) * local
END FUNCTION
PRINT fact(10)
PRINT fact(0)
''', "3628800\n1\n")
    both('''CLASS Box
    PRIVATE FIELD value AS INT
    SUB Init(n AS INT)
        SELF.value=n
    END SUB
    FUNCTION Get() AS INT
        RETURN SELF.value
    END FUNCTION
END CLASS
LET a=NEW Box(7)
LET b=NEW Box(9)
LET alias=a
PRINT alias.Get()
PRINT b.Get()
PRINT alias=a
''',"7\n9\n1\n")
    both('''ENUM Mode
    Read
    Write
END ENUM
DIM table AS Map<Mode,String> = NEW Map<Mode,String>()
table[Mode.Read]="hello"
PRINT table[Mode.Read]
PRINT HAS(table,Mode.Write)
DIM counts AS Map<String,Int> = NEW Map<String,Int>()
counts["a"+"b"]=9
counts["ab"]=10
PRINT counts["ab"]
PRINT LEN(counts)
LET values=NEW Int[4]
values[1]=3
values[3]=4
LET sum=0
FOR EACH value IN values
    sum=sum+value
NEXT
PRINT sum
DIM matrix AS Int[][] = NEW Int[][2]
matrix[0]=values
PRINT matrix[0][3]
''',"hello\n0\n10\n1\n7\n4\n")
    both('''LET names=NEW String[2]
PRINT names[1]
LET data=NEW Map<Int,Int>()
LET i=0
WHILE i<1000
    data[i]=i*2
    i=i+1
WEND
PRINT LEN(data)
PRINT data[111]
PRINT data[999]
''',"\n1000\n222\n1998\n")
    both('''CONST on AS Bool = TRUE
LET ok=FALSE AND (1 / 0 = 0)
ok=on OR (1 / 0 = 0)
PRINT ok
PRINT NOT FALSE AND TRUE
PRINT "abc" = "a" + "bc"
PRINT 2 + 1.5
PRINT 5 / 2.0
PRINT -1.25e1
''',"1\n1\n1\n3.5\n2.5\n-12.5\n")
    both('''LET bytes=BUFFER(3)
CALL PUTBYTE(bytes,0,65)
LET snapshot=STRING(bytes)
CALL PUTBYTE(bytes,0,66)
CALL FREE(bytes)
PRINT snapshot+"!"
PRINT INT(-7.9)
PRINT FLOAT("-2.5")
PRINT INT("-9223372036854775808")
PRINT STRING(TRUE)
PRINT BOOL(0.5)
''',"A!\n-7\n-2.5\n-9223372036854775808\ntrue\n1\n")
    for source, why in [
        ("DIM x AS Int = 2.3","expected Int"),
        ("DIM s AS String = 2","expected String"),
        ("LET a=NEW INT[2]\na[0]=TRUE","expected Int"),
        ("LET a=NEW Map<String,Int>()\na[1]=0","expected String"),
        ("LET a=NEW Map<Float,Int>()","map key"),
        ("CONST x=2\nx=3","read-only"),
        ("CLASS X\nPRIVATE FIELD n AS INT\nEND CLASS\nLET x=NEW X()\nPRINT x.n","private field"),
        ("FUNCTION bad(x AS INT) AS INT\nIF x THEN\nRETURN 2\nENDIF\nEND FUNCTION","without RETURN"),
        ("INTERFACE I\nFUNCTION f() AS INT\nEND INTERFACE\nCLASS A IMPLEMENTS I\nEND CLASS","missing interface"),
        ("CLASS A\nFUNCTION f() AS INT\nRETURN 1\nEND FUNCTION\nEND CLASS\nCLASS B EXTENDS A\nFUNCTION f() AS BOOL","override signature"),
        ("CLASS A\nEND CLASS\nCLASS B\nEND CLASS\nDIM a AS A = NEW B()","expected A"),
        ("FUNCTION f(x AS FLOAT) AS FLOAT\nRETURN x\nEND FUNCTION\nPRINT f()","expected 1 arguments"),
        ("LET x=1\nFUNCTION f() AS INT\nRETURN x\nEND FUNCTION","unknown variable"),
        ("DIM x AS Imaginary","unknown value type"),
    ]:
        reject(source, why)
    for source, why in [
        ("LET a=NEW Int[1]\nPRINT a[-1]","line 2: index out of bounds"),
        ("CLASS A\nFIELD n AS INT\nEND CLASS\nDIM a AS A\nPRINT a.n","line 5: null"),
        ('LET m=NEW Map<String,Int>()\nPRINT m["missing"]',"line 2: missing map key"),
        ('PRINT INT("12x")',"line 1: invalid Int text"),
        ("PRINT INT(1e50)","line 1: Float outside Int range"),
        ("PRINT 1.0 / 0","line 1: division by zero"),
        ("FUNCTION f() AS INT\nRETURN f()\nEND FUNCTION\nPRINT f()","call depth exceeded"),
    ]:
        both(source,failure=why)

    both((ROOT/"examples/tensors.bas").read_text(), "0\n3\n7\n3.6666666666666665\n")
    both("LET x=NEW Float[2]\nx[0]=2\nx[1]=-1\nLET b=NEW Float[1]\nb[0]=1\n"
         "CALL ML_DENSE_RELU(x,x,b,b)\nPRINT b[0]\nCALL ML_AFFINE_RELU(x,2,1,x)\nPRINT x[1]", "6\n0\n")
    both("LET x=NEW Float[1]\nCALL ML_DENSE_RELU(x,x,x,x)",failure="must not alias")
    both("LET x=NEW Float[3]\nLET y=NEW Float[2]\nPRINT ML_MSE(x,y)",failure="equal nonempty")
    both("LET x=NEW Float[0]\nPRINT ML_MSE(x,x)",failure="nonempty")
    reject("LET x=NEW Int[2]\nPRINT ML_MSE(x,x)","expected Float[]")

    # Verify optimized affine iteration against a scalar Python oracle.
    rng=random.Random(83)
    lines, out=[], []
    for k in range(55):
        i, n = rng.randrange(-30,8), rng.randrange(-10,80)
        x, a, b = (rng.getrandbits(64) for _ in range(3))
        lines += [f"LET i={i}", f"LET x={x}", f"WHILE i<{n}",
                  f"x=x*{a}+{b}", "i=i+1", "WEND", "PRINT x", "PRINT i"]
        for _ in range(i,n):
            x=(x*a+b)%(1<<64)
        out += [str(x-(1<<64) if x>>63 else x), str(max(i,n))]
    both("\n".join(lines),"\n".join(out)+"\n")
print("PASS: types, objects, interfaces, arrays, maps, recursion, diagnostics and affine optimization")