' Polymorphic types: type discriminator + UNION variant record
#COMPILE EXE
#DIM ALL

%DT_NONE = 0
%DT_INTEGER = 1
%DT_DOUBLE = 2
%DT_STRING = 3
%DT_BOOLEAN = 4

TYPE Variant
    dtype AS LONG
    UNION
        intVal AS LONG
        dblVal AS DOUBLE
        strVal AS STRING
        boolVal AS LONG
    END UNION
END TYPE

FUNCTION PBMAIN() AS LONG
    LOCAL v1 AS Variant
    LOCAL v2 AS Variant
    LOCAL v3 AS Variant
    LOCAL v4 AS Variant
    LOCAL s AS STRING
    LOCAL dt AS LONG
    LOCAL iv AS LONG
    LOCAL bv AS LONG
    LOCAL stmp AS STRING

    PRINT "=== Polymorphic Types (Variant Records) ==="
    PRINT

    v1.dtype = %DT_INTEGER
    v1.intVal = 42
    v2.dtype = %DT_DOUBLE
    v2.dblVal = 3.14159
    v3.dtype = %DT_STRING
    v3.strVal = LEFT$("Hello Variant!" + SPACE$(32), 32)
    v4.dtype = %DT_BOOLEAN
    v4.boolVal = 1

    PRINT "Individual variants:"
    dt = v1.dtype
    IF dt = %DT_INTEGER THEN
        iv = v1.intVal
        s = "int(" & FORMAT$(iv) & ")"
    END IF
    PRINT "  v1: " & s
    dt = v2.dtype
    IF dt = %DT_DOUBLE THEN
        s = "dbl(" & FORMAT$(v2.dblVal, "#0.000") & ")"
    END IF
    PRINT "  v2: " & s
    dt = v3.dtype
    IF dt = %DT_STRING THEN
        stmp = TRIM$(v3.strVal)
        s = "str(" & CHR$(34) & stmp & CHR$(34) & ")"
    END IF
    PRINT "  v3: " & s
    dt = v4.dtype
    IF dt = %DT_BOOLEAN THEN
        bv = v4.boolVal
        IF bv THEN s = "bool(true)" ELSE s = "bool(false)"
    END IF
    PRINT "  v4: " & s
    PRINT

    v1.dtype = %DT_INTEGER
    v1.intVal = 32
    v2.dtype = %DT_DOUBLE
    v2.dblVal = 75000.0
    v3.dtype = %DT_STRING
    v3.strVal = LEFT$("Alice Smith" + SPACE$(32), 32)
    v4.dtype = %DT_BOOLEAN
    v4.boolVal = 0

    PRINT "Updated variants:"
    dt = v1.dtype
    IF dt = %DT_INTEGER THEN
        iv = v1.intVal
        s = "int(" & FORMAT$(iv) & ")"
    END IF
    PRINT "  age: " & s
    dt = v2.dtype
    IF dt = %DT_DOUBLE THEN
        s = "dbl(" & FORMAT$(v2.dblVal, "#0.000") & ")"
    END IF
    PRINT "  salary: " & s
    dt = v3.dtype
    IF dt = %DT_STRING THEN
        stmp = TRIM$(v3.strVal)
        s = "str(" & CHR$(34) & stmp & CHR$(34) & ")"
    END IF
    PRINT "  name: " & s
    dt = v4.dtype
    IF dt = %DT_BOOLEAN THEN
        bv = v4.boolVal
        IF bv THEN s = "bool(true)" ELSE s = "bool(false)"
    END IF
    PRINT "  active: " & s
    PRINT

    PRINT "Polymorphic type tests complete."
    FUNCTION = 0
END FUNCTION
