www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 15288] New: The exponentiation operator ^^ doesn't follow the

https://issues.dlang.org/show_bug.cgi?id=15288

          Issue ID: 15288
           Summary: The exponentiation operator ^^ doesn't follow the
                    standard type promotion rules.
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: thomas.bockman gmail.com

Currently, the exponentiation operator `x ^^ y` always returns a value of the
same type as the base `x`.

I believe this should be changed to follow type promotion rules like those used
by the conceptually related shift operators, or by the Phobos `std.math.pow()`
function.

Key changes needed:
1. Promote small integral types (like `byte` or `ushort`) to `int`, as all
other operators do.
2. If the exponent is floating-point, promote the base to floating-point as
well.

Benefits:
1. Aligning the behaviour of exponentiation with the other operators is
necessary to satisfy the "principle of least surprise".
2. Promoting small integer types generally leads to more efficient code
generation.

The following sample code highlights the discrepancies between the built-in
operator and the Phobos function:

module main;

import std.stdio;
import std.traits : Unqual, NumericTypeList;
import std.math : pow;

void main(string[] args) {
    foreach(N; NumericTypeList) {
        foreach(M; NumericTypeList) {
            const builtIn = cast(N)1 ^^ cast(M)1;
            const phobos = pow(cast(N)1, cast(M)1);

            static if(!is(typeof(builtIn) == typeof(phobos))) {
                writeln("(" ~ N.stringof ~ ") ^^ (" ~ M.stringof ~ ") == " ~
Unqual!(typeof(builtIn)).stringof);
                writeln("pow(" ~ N.stringof ~ ", " ~ M.stringof ~ ") == " ~
Unqual!(typeof(phobos)).stringof);
                writeln();
            }
        }
    }

    stdin.readln();
}

--
Nov 05 2015