chapel-lang / chapel

a Productive Parallel Programming Language
https://chapel-lang.org
Other
1.75k stars 410 forks source link

Should Chapel have a `declval` equivalent? #24897

Open DanilaFe opened 3 weeks ago

DanilaFe commented 3 weeks ago

Some code in our standard library works by default-initializing a value of a certain type, and then checking this value to see if various methods on it resolve. For instance, the following chpl__sumType code in the standard library:

  proc chpl__sumType(type eltType) type {
   if chpl_sumTypeIsSame(eltType) {
    return eltType;
   } else {
    // The answer may or may not be 'eltType'.
    var x: eltType;
    if isArray(x) {
      type xET = x.eltType;
      type xST = chpl__sumType(xET);
      if xET == xST then
        return eltType;
      else
        return [x.domain] xST;
    } else {
      use Reflection;
      if ! canResolve("+", x, x) then
        // Issue a user-friendly error.
        compilerError("+ reduce cannot be used on values of the type ",
                      eltType:string);
      return (x + x).type;
    }
   }
  }

However, this is troublesome; as https://github.com/chapel-lang/chapel/issues/24886 notes, if the value doesn't have a default initializer, then the function will fail. In the case of owned classes, the operation will eventually fail later, as well -- default values are used as the additive identity. But the general question is the following: should we be able to get a handle on an element of a type T, ignoring its constructibility, for the purposes of metaprogramming? This would match the semantics of C++'s declval, which is disallowed at runtime, but can be used to magically manifest an element of a type for metaprogramming purposes.