constexpr.carbon 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. //
  5. // INCLUDE-FILE: toolchain/testing/testdata/min_prelude/full.carbon
  6. //
  7. // AUTOUPDATE
  8. // TIP: To test this file alone, run:
  9. // TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/check/testdata/interop/cpp/constexpr.carbon
  10. // TIP: To dump output, run:
  11. // TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/check/testdata/interop/cpp/constexpr.carbon
  12. // --- bool.carbon
  13. library "[[@TEST_NAME]]";
  14. import Cpp inline '''
  15. constexpr bool b = true;
  16. ''';
  17. class C(B:! bool) {}
  18. fn F() -> C(Cpp.b);
  19. let x: C(true) = F();
  20. // --- int.carbon
  21. library "[[@TEST_NAME]]";
  22. import Cpp inline '''
  23. constexpr int i = 123;
  24. ''';
  25. class C(I:! i32) {}
  26. fn F() -> C(Cpp.i);
  27. let x: C(123) = F();
  28. // --- float.carbon
  29. library "[[@TEST_NAME]]";
  30. import Cpp inline '''
  31. constexpr float flt = 123.5;
  32. ''';
  33. class C(V:! f32) {}
  34. fn F() -> C(Cpp.flt);
  35. let x: C(123.5) = F();
  36. // --- pointer.carbon
  37. library "[[@TEST_NAME]]";
  38. import Cpp inline '''
  39. int i = 123;
  40. constexpr int* _Nonnull ptr = &i;
  41. ''';
  42. class C(V:! i32*) {}
  43. fn F() -> C(Cpp.ptr);
  44. let x: C(&Cpp.i) = F();
  45. // --- function.carbon
  46. library "[[@TEST_NAME]]";
  47. import Cpp inline '''
  48. constexpr int f(int a, int b) { return a + b; }
  49. ''';
  50. let a: array(i32, Cpp.f(1, 2)) = (1, 2, 3);
  51. // --- fail_invalid_constant_eval.carbon
  52. library "[[@TEST_NAME]]";
  53. import Cpp inline '''
  54. constexpr int arr[1] = {0};
  55. constexpr int f(int a) {
  56. return arr[a];
  57. }
  58. ''';
  59. // CHECK:STDERR: fail_invalid_constant_eval.carbon:[[@LINE+10]]:26: error: call to immediate function 'f' is not a constant expression [CppInteropParseError]
  60. // CHECK:STDERR: 21 | let a: array(i32, Cpp.f(5)) = (1, 2, 3);
  61. // CHECK:STDERR: | ^
  62. // CHECK:STDERR: fail_invalid_constant_eval.carbon:[[@LINE-7]]:10: note: cannot refer to element 5 of array of 1 element in a constant expression [CppInteropParseNote]
  63. // CHECK:STDERR: 7 | return arr[a];
  64. // CHECK:STDERR: | ^
  65. // CHECK:STDERR: fail_invalid_constant_eval.carbon:[[@LINE+4]]:26: note: in call to 'f(5)' [CppInteropParseNote]
  66. // CHECK:STDERR: 21 | let a: array(i32, Cpp.f(5)) = (1, 2, 3);
  67. // CHECK:STDERR: | ^
  68. // CHECK:STDERR:
  69. let a: array(i32, Cpp.f(5)) = (1, 2, 3);