Skip to content

fixes # 25846; Uses decltype(auto) type when declaring temporal#25862

Draft
demotomohiro wants to merge 2 commits into
nim-lang:develfrom
demotomohiro:fix-25846
Draft

fixes # 25846; Uses decltype(auto) type when declaring temporal#25862
demotomohiro wants to merge 2 commits into
nim-lang:develfrom
demotomohiro:fix-25846

Conversation

@demotomohiro

@demotomohiro demotomohiro commented Jun 2, 2026

Copy link
Copy Markdown
Contributor
proc testVarRet(x: var int): var int = x

proc testProcTypeParam(prc: proc (x: var int): var int {.nimcall.}) =
  var x = 123
  prc(x) = 321
  echo x

testProcTypeParam(testVarRet)

Nim cpp generates C++ code like following from above Nim code:

#include <iostream>

typedef int& (tyProc)(int& x_p0);

int* testVarRet(int& x) {
  return &x;
}

void testProcTypeParam(tyProc prc) {
  int x = 123;
  auto T1 = prc(x);
  T1 = 321;
  std::cout << x << std::endl;
}

int main()
{
  testProcTypeParam(testVarRet);
}

But the type T1 is int, not int& so the value of local variable x wasn't changed.
This PR changes type of temporal variables from auto to decltype(auto) so that type of temporal variables become reference type when they are initialized with a function with reference return type.

Following C++ shows how auto and decltype(auto) in variable declarations works differently:

#include <iostream>

int& foo(int& x) {
  return x;
}

int main()
{
    int x = 100;
    auto y = foo(x);            // y is int
    decltype(auto) z = foo(x);  // z is int&
    y = 123;
    std::cout << x << ", " << y << std::endl;   // 100, 123
    z = 456;
    std::cout << x << ", " << z << std::endl;   // 456, 456

    int a = 1;
    decltype(auto) b = a;       // b is int
    decltype(auto) c = (a);     // c is int&
    b = 2;
    std::cout << a << ", " << b << std::endl;   // 1, 2
    c = 3;
    std::cout << a << ", " << c << std::endl;   // 3, 3
}

ref #25846

@demotomohiro

Copy link
Copy Markdown
Contributor Author

Need to fix #25870 to pass CI tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant