4 ms·
Transpiling is a cool idea. Although erasing syntax differences between languages is easy, erasing semantic differences is extremely hard. The simplest example
by yeputons 5y ago
Transpiling is a cool idea. Although erasing syntax differences between languages is easy, erasing semantic differences is extremely hard. The simplest example being garbage collection: if you transpile to C, you have to track garbage yourself and collect it. You either end up leaking some memory, double-freeing, writing your own GC or prohibiting some code to be transpiled to C.
There are more subtle ways. For example, overflow of signed 32-bit int is:
* Well-defined in Java. I assume in C# as well.
* Well defined differently in Python: it starts doing arbitrary precision arithmetics.
* Well defined differently in JavaScript, because there are no integers, only IEEE 754-like 64-bit floating point numbers.
* Completely undefined behavior in C and C++. See the "Signed overflow" section at https://en.cppreference.com/w/cpp/language/ub https://en.cppreference.com/w/cpp/language/ub and https://godbolt.org/z/y4vIi1 https://godbolt.org/z/y4vIi1 specifically, if you assume reasoning about undefined behavior is allowed in general case.
- rightbyte 5y agoWhen generating C you can quite easily cast all signed to unsigned, do the operation, and cast back, if you want to avoid signed overflow.
- mek6800d2 5y agoExcept that doing so does NOT avoid signed overflow. You're converting effectively w-1 bits of precision (plus a sign bit) to w bits of precision, doing the calculation, and then converting w bits of precision back to w-1 bits of precision -- that only works for a limited range of input values. Using int32_t and uint32_t, try adding -2147483648 and -1. The arithmetic result should be -2147483649, but a program converting back and forth between signed and unsigned will produce 2147483647 -- wrong answer and wrong sign.
- MauranKilom 5y agoYou do avoid "signed overflow" in the sense of the C and C++ specifications by working on unsigned numbers. "signed overflow" is UB, "unsigned overflow" is not. Of course you will never be able to obtain an unrepresentable value (such as -2147483649) through a workaround, and if you cast back to signed you get the wrapped result (which, indeed, may have an unexpected sign). But the point of transpiling to operations on unsigned numbers is to avoid UB, not to escape basic computational bounds.