zephir-lang / zephir

Zephir is a compiled high-level language aimed to ease the creation of C-extensions for PHP
https://zephir-lang.com
MIT License
3.29k stars 467 forks source link

Variable type char to string conversion give compilation errors #1629

Open flyingangel opened 6 years ago

flyingangel commented 6 years ago

The following code will generate errors at compilation due to type char to string conversion. Also (char) cast will throw an unknown type error.

    public static function getRandom(int length, string keyspace = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -> string {
        int i, nb, max;
        string ch; // --> automatic cast to string
        array pieces = [];

        let max = (int)mb_strlen(keyspace, "8bit") - 1;

        for i in range(0, length) {
            let nb = (int)random_int(0, max);
            let ch = keyspace[nb];
            let pieces[] = ch; // ----> the cause of error here and cannot use cast (char)
        }

        return implode("", pieces);
    }

compile-errors.log

sergeyklay commented 6 years ago

@flyingangel Why do we need transform particular data type to another one? At least using such unobvious way. As I know there is no issue when we use var ch; (variable data type). Right?

flyingangel commented 6 years ago

Indeed, var type will pass the compiler.

Just want to point out that there's a problem when trying to store the uchar or char type in an array as in :

let ch = keyspace[nb]; // --> return uchar from string
let pieces[] = ch; // --> store uchar

But our ch is defined as char so it's probably one of the cause. But if I declare uchar ch; or a cast (uchar) keyspace[nb] the compiler will refuse

Note that I consider this bug because it forces me to declare var ch; in advance. If you try to store directly in the array without the intermediate step, the compiler will refuse : let pieces[] = keyspace[nb];

Not a big bug but I suppose for now it's preferably to avoid messing with non PHP-native variable type.

Ticket can be closed but it's good that in the future we more support for type casting between different types : char, uchar, string, boolean var type should be only the last resort, a workaround, when the return type is really unknown (which is unlikely) or mixed Also test if each type is "storable" in an array.

3 test cases in attachment test.txt