Bug 107437 - nested generic lambdas fail requiring unneded captures
Summary: nested generic lambdas fail requiring unneded captures
Status: ASSIGNED
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 12.2.0
: P3 normal
Target Milestone: ---
Assignee: Patrick Palka
URL:
Keywords: c++-lambda, rejects-valid
Depends on:
Blocks:
 
Reported: 2022-10-27 15:20 UTC by Jordi Vilar
Modified: 2024-03-27 06:33 UTC (History)
4 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2022-12-17 00:00:00


Attachments
failed experiment (1.31 KB, patch)
2023-07-04 15:03 UTC, Jason Merrill
Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description Jordi Vilar 2022-10-27 15:20:01 UTC
This simple valid code fails to compile with all recent versions of gcc, but compiles nicely with clang (and even msvc!)

(live demo on complier explorer: https://godbolt.org/z/eM1b9e6s9)

// compile with just -std=c++20
#include <array>
#include <functional>
#include <type_traits>

void test()
{
    std::invoke([]<typename T>(auto N, std::type_identity<T>)
    {
        using vector_type = std::array<T, N>;
        static_assert(N == std::tuple_size_v<vector_type>);
        std::invoke([]<std::size_t... i>(std::index_sequence<i...>)
        {
            static_assert(std::conjunction_v<std::is_same<std::tuple_element_t<i, vector_type>, T>...>);
        }, std::make_index_sequence<N>{});
    }, std::integral_constant<std::size_t, 3>{}, std::type_identity<int>{});
}

It issues the diagnostics output:
<source>: In instantiation of 'test()::<lambda(auto:3, std::type_identity<T>)> [with T = int; auto:3 = std::integral_constant<long unsigned int, 3>]':
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/type_traits:2565:26:   required by substitution of 'template<class _Fn, class ... _Args> static std::__result_of_success<decltype (declval<_Fn>()((declval<_Args>)()...)), std::__invoke_other> std::__result_of_other_impl::_S_test(int) [with _Fn = test()::<lambda(auto:3, std::type_identity<T>)>; _Args = {std::integral_constant<long unsigned int, 3>, std::type_identity<int>}]'
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/type_traits:2576:55:   required from 'struct std::__result_of_impl<false, false, test()::<lambda(auto:3, std::type_identity<T>)>, std::integral_constant<long unsigned int, 3>, std::type_identity<int> >'
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/type_traits:2581:12:   required from 'struct std::__invoke_result<test()::<lambda(auto:3, std::type_identity<T>)>, std::integral_constant<long unsigned int, 3>, std::type_identity<int> >'
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/type_traits:3022:12:   required from 'struct std::invoke_result<test()::<lambda(auto:3, std::type_identity<T>)>, std::integral_constant<long unsigned int, 3>, std::type_identity<int> >'
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/type_traits:3034:11:   required by substitution of 'template<class _Fn, class ... _Args> using invoke_result_t = typename std::invoke_result::type [with _Fn = test()::<lambda(auto:3, std::type_identity<T>)>; _Args = {std::integral_constant<long unsigned int, 3>, std::type_identity<int>}]'
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/functional:107:5:   required by substitution of 'template<class _Callable, class ... _Args> constexpr std::invoke_result_t<_Fn, _Args ...> std::invoke(_Callable&&, _Args&& ...) [with _Callable = test()::<lambda(auto:3, std::type_identity<T>)>; _Args = {std::integral_constant<long unsigned int, 3>, std::type_identity<int>}]'
<source>:7:16:   required from here
<source>:13:32: error: 'N' is not captured
   13 |             static_assert(std::conjunction_v<std::is_same<std::tuple_element_t<i, vector_type>, T>...>);
      |                           ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:11:21: note: the lambda has no capture-default
   11 |         std::invoke([]<std::size_t... i>(std::index_sequence<i...>)
      |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   12 |         {
      |         ~            
   13 |             static_assert(std::conjunction_v<std::is_same<std::tuple_element_t<i, vector_type>, T>...>);
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   14 |         }, std::make_index_sequence<N>{});
      |         ~            
<source>:7:37: note: 'std::integral_constant<long unsigned int, 3> N' declared here
    7 |     std::invoke([]<typename T>(auto N, std::type_identity<T>)
      |                                ~~~~~^
Comment 1 Jordi Vilar 2022-10-27 15:31:49 UTC
BTW, capturing (the unneded!) N in the nested lambda, raises a beautiful error:

error: integral expression '(std::integral_constant<long unsigned int, 3>::value_type)N' is not constant.

Should I fill a new issue for this?
Comment 2 Andrew Pinski 2022-11-01 23:05:26 UTC
I suspect this is the same as PR 105518.
Comment 3 GCC Commits 2022-12-17 16:25:03 UTC
The master branch has been updated by Patrick Palka <ppalka@gcc.gnu.org>:

https://gcc.gnu.org/g:982629bea416df976686467f235e09cb1a5531cc

commit r13-4761-g982629bea416df976686467f235e09cb1a5531cc
Author: Patrick Palka <ppalka@redhat.com>
Date:   Sat Dec 17 11:24:44 2022 -0500

    c++: constantness of non-dependent NTTP argument [PR107437]
    
    Here we're rejecting the use of the lambda capture of 't' (of empty
    type) as a template argument ultimately because convert_nontype_argument
    checks constantness using is_constant_expression, which returns false
    for lambda captures since want_rval=false.  But in this case I believe
    an lvalue-to-rvalue conversion of the argument is implied, so we should
    be using is_rvalue_constant_expression instead (which would return true
    here).
    
    However, it doesn't seem necessary to consider constantness at all
    when deciding whether to instantiate a non-dependent argument in
    convert_nontype_argument.  So this patch gets rid of the problematic
    constantness test altogether, which incidentally also fixes the similar
    dg-ice'd testcase from PR87765.  This is in line with a similar
    change we made to finish_decltype_type in r12-7564-gec0f53a3a542e7.
    
            PR c++/107437
            PR c++/87765
    
    gcc/cp/ChangeLog:
    
            * pt.cc (convert_nontype_argument): Relax is_nondep_const_expr
            test to !inst_dep_expr_p.
    
    gcc/testsuite/ChangeLog:
    
            * g++.dg/cpp1y/lambda-generic-107437.C: New test.
            * g++.dg/cpp1z/constexpr-lambda26.C: Remove dg-ice.
Comment 4 Patrick Palka 2022-12-17 16:34:17 UTC
The capturing version of the testcase is now accepted on trunk, unfortunately we still reject the original non-capturing version.

Another workaround that's accepted by GCC 9+ is to avoid using N in an evaluated context in the definition of vector_type:

  using vector_type = std::array<T, decltype(N){}>;
Comment 5 Patrick Palka 2022-12-17 16:39:22 UTC
Reduced version of the original testcase:

struct integral_constant {
  constexpr operator int() const { return 42; }
};

template<int N>
struct A {
  static constexpr int value = N;
};

template<class T>
struct B {
  static constexpr int value = T::value;
};

template<class T>
void f(T t) {
  using alias = A<t>;
  [](auto) {
    B<alias> a; // { dg-bogus "'t' is not captured" }
    return a.value;
  }(0);
}

template void f(integral_constant);
Comment 6 GCC Commits 2023-06-28 19:44:06 UTC
The master branch has been updated by Patrick Palka <ppalka@gcc.gnu.org>:

https://gcc.gnu.org/g:4cf64d9cc2faf4001f037a50a350abd0f95f3e29

commit r14-2170-g4cf64d9cc2faf4001f037a50a350abd0f95f3e29
Author: Patrick Palka <ppalka@redhat.com>
Date:   Wed Jun 28 15:43:33 2023 -0400

    c++: ahead of time variable template-id coercion [PR89442]
    
    This patch makes us coerce the arguments of a variable template-id ahead
    of time, as we do for class template-ids, which causes us to immediately
    diagnose template parm/arg kind mismatches and arity mismatches.
    
    Unfortunately this causes a regression in cpp1z/constexpr-if20.C: coercing
    the variable template-id m<ar, as> ahead of time means we strip it of
    typedefs, yielding m<typename C<i>::q, typename C<j>::q>, but in this
    stripped form we're directly using 'i' and so we expect to have captured
    it.  This is a variable template version of PR107437.
    
            PR c++/89442
            PR c++/107437
    
    gcc/cp/ChangeLog:
    
            * cp-tree.h (lookup_template_variable): Add complain parameter.
            * parser.cc (cp_parser_template_id): Pass tf_warning_or_error
            to lookup_template_variable.
            * pt.cc (lookup_template_variable): Add complain parameter.
            Coerce template arguments here ...
            (finish_template_variable): ... instead of here.
            (lookup_and_finish_template_variable): Check for error_mark_node
            result from lookup_template_variable.
            (tsubst_copy) <case TEMPLATE_ID_EXPR>: Pass complain to
            lookup_template_variable.
            (instantiate_template): Use build2 instead of
            lookup_template_variable to build a TEMPLATE_ID_EXPR
            for most_specialized_partial_spec.
    
    gcc/testsuite/ChangeLog:
    
            * g++.dg/cpp/pr64127.C: Expect "expected unqualified-id at end
            of input" error.
            * g++.dg/cpp0x/alias-decl-ttp1.C: Fix template parameter/argument
            kind mismatch for variable template has_P_match_V.
            * g++.dg/cpp1y/pr72759.C: Expect "template argument 1 is invalid"
            error.
            * g++.dg/cpp1z/constexpr-if20.C: XFAIL test due to bogus "'i' is
            not captured" error.
            * g++.dg/cpp1z/noexcept-type21.C: Fix arity of variable template d.
            * g++.dg/diagnostic/not-a-function-template-1.C: Add default
            template argument to variable template A so that A<> is valid.
            * g++.dg/parse/error56.C: Don't expect "ISO C++ forbids
            declaration with no type" error.
            * g++.dg/parse/template30.C: Don't expect "parse error in
            template argument list" error.
            * g++.dg/cpp1y/var-templ82.C: New test.
Comment 7 Jason Merrill 2023-07-04 15:03:44 UTC
Created attachment 55466 [details]
failed experiment

I wondered if keeping function-local typedefs would be a simple fix, but a number of modules tests regress with this patch.  I guess that's because of problems with entries in the specialization hash tables referring to function-local typedefs that we can't then reconnect when loading the module.  Really such entries (if we do add them) shouldn't persist after we're done compiling the function.