• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2017 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This is a "No Compile Test" suite.
6// http://dev.chromium.org/developers/testing/no-compile-tests
7
8#include "base/containers/span.h"
9
10#include <array>
11#include <set>
12#include <string>
13#include <string_view>
14#include <vector>
15
16namespace base {
17
18class Base {
19};
20
21class Derived : Base {
22};
23
24// A default constructed span must have an extent of 0 or dynamic_extent.
25void DefaultSpanWithNonZeroStaticExtentDisallowed() {
26  span<int, 1u> span;  // expected-error {{no matching constructor for initialization of 'span<int, 1U>'}}
27}
28
29// A span with static extent constructed from an array must match the size of
30// the array.
31void SpanFromArrayWithNonMatchingStaticExtentDisallowed() {
32  int array[] = {1, 2, 3};
33  span<int, 1u> span(array);  // expected-error {{no matching constructor for initialization of 'span<int, 1U>'}}
34}
35
36// A span with static extent constructed from another span must match the
37// extent.
38void SpanFromOtherSpanWithMismatchingExtentDisallowed() {
39  std::array<int, 3> array = {1, 2, 3};
40  span<int, 3u> span3(array);
41  span<int, 4u> span4(span3);  // expected-error {{no matching constructor for initialization of 'span<int, 4U>'}}
42}
43
44// Converting a dynamic span to a static span should not be allowed.
45void DynamicSpanToStaticSpanDisallowed() {
46  span<int> dynamic_span;
47  span<int, 3u> static_span = dynamic_span;  // expected-error-re {{no viable conversion from 'span<[...], (default) dynamic_extent aka {{.*}}>' to 'span<[...], 3>'}}
48}
49
50// Internally, this is represented as a pointer to pointers to Derived. An
51// implicit conversion to a pointer to pointers to Base must not be allowed.
52// If it were allowed, then something like this would be possible:
53//   Cat** cats = GetCats();
54//   Animals** animals = cats;
55//   animals[0] = new Dog();  // Uh oh!
56void DerivedToBaseConversionDisallowed() {
57  span<Derived*> derived_span;
58  span<Base*> base_span(derived_span);  // expected-error {{no matching constructor for initialization of 'span<Base *>'}}
59}
60
61// Similarly, converting a span<int*> to span<const int*> requires internally
62// converting T** to const T**. This is also disallowed, as it would allow code
63// to violate the contract of const.
64void PtrToConstPtrConversionDisallowed() {
65  span<int*> non_const_span;
66  span<const int*> const_span(non_const_span);  // expected-error {{no matching constructor for initialization of 'span<const int *>'}}
67}
68
69// A const container should not be convertible to a mutable span.
70void ConstContainerToMutableConversionDisallowed() {
71  const std::vector<int> v = {1, 2, 3};
72  span<int> span1(v);             // expected-error {{no matching constructor for initialization of 'span<int>'}}
73  span<int, 2u> span2({1, 2});    // expected-error {{no matching constructor for initialization of 'span<int, 2U>'}}
74}
75
76// A dynamic const container should not be implicitly convertible to a static span.
77void ImplicitConversionFromDynamicConstContainerToStaticSpanDisallowed() {
78  const std::vector<int> v = {1, 2, 3};
79  span<const int, 3u> span = v;  // expected-error {{no viable conversion from 'const std::vector<int>' to 'span<const int, 3U>'}}
80}
81
82// A dynamic mutable container should not be implicitly convertible to a static span.
83void ImplicitConversionFromDynamicMutableContainerToStaticSpanDisallowed() {
84  std::vector<int> v = {1, 2, 3};
85  span<int, 3u> span = v;  // expected-error {{no viable conversion from 'std::vector<int>' to 'span<int, 3U>'}}
86}
87
88// Fixed-extent span construction from an initializer list is explicit.
89void InitializerListConstructionIsExplicit() {
90  span<const int, 3u> s = {{1, 2, 3}};  // expected-error {{chosen constructor is explicit in copy-initialization}}
91}
92
93// A std::set() should not satisfy the requirements for conversion to a span.
94void StdSetConversionDisallowed() {
95  std::set<int> set;
96  span<int> span1(set.begin(), 0u);                // expected-error {{no matching constructor for initialization of 'span<int>'}}
97  span<int> span2(set.begin(), set.end());         // expected-error {{no matching constructor for initialization of 'span<int>'}}
98  span<int> span3(set);                            // expected-error {{no matching constructor for initialization of 'span<int>'}}
99}
100
101// Static views of spans with static extent must not exceed the size.
102void OutOfRangeSubviewsOnStaticSpan() {
103  std::array<int, 3> array = {1, 2, 3};
104  span<int, 3u> span(array);
105  auto first = span.first<4>();          // expected-error@*:* {{no matching member function for call to 'first'}}
106  auto last = span.last<4>();            // expected-error@*:* {{no matching member function for call to 'last'}}
107  auto subspan1 = span.subspan<4>();     // expected-error@*:* {{no matching member function for call to 'subspan'}}
108  auto subspan2 = span.subspan<0, 4>();  // expected-error@*:* {{no matching member function for call to 'subspan'}}
109}
110
111// Discarding the return value of empty() is not allowed.
112void DiscardReturnOfEmptyDisallowed() {
113  span<int> s;
114  s.empty();  // expected-error {{ignoring return value of function}}
115}
116
117// Getting elements of an empty span with static extent is not allowed.
118void RefsOnEmptyStaticSpanDisallowed() {
119  span<int, 0u> s;
120  s.front();  // expected-error@*:* {{invalid reference to function 'front': constraints not satisfied}}
121  s.back();   // expected-error@*:* {{invalid reference to function 'back': constraints not satisfied}}
122}
123
124// Calling swap on spans with different extents is not allowed.
125void SwapWithDifferentExtentsDisallowed() {
126  std::array<int, 3> array = {1, 2, 3};
127  span<int, 3u> static_span(array);
128  span<int> dynamic_span(array);
129  std::swap(static_span, dynamic_span);  // expected-error {{no matching function for call to 'swap'}}
130}
131
132// as_writable_bytes should not be possible for a const container.
133void AsWritableBytesWithConstContainerDisallowed() {
134  const std::vector<int> v = {1, 2, 3};
135  span<uint8_t> bytes = as_writable_bytes(span(v));  // expected-error {{no matching function for call to 'as_writable_bytes'}}
136}
137
138void ConstVectorDeducesAsConstSpan() {
139  const std::vector<int> v;
140  span<int> s = span(v);  // expected-error-re@*:* {{no viable conversion from 'span<{{.*}}, [...]>' to 'span<int, [...]>'}}
141}
142
143// A span can only be constructed from a range rvalue when the element type is
144// read-only or the range is a borrowed range.
145void SpanFromNonConstRvalueRange() {
146  std::array<bool, 3> arr = {true, false, true};
147  [[maybe_unused]] auto a = span(std::move(arr));  // expected-error {{no matching conversion}}
148
149  std::string str = "ok";
150  [[maybe_unused]] auto b = span(std::move(str));  // expected-error {{no matching conversion}}
151
152  std::u16string str16 = u"ok";
153  [[maybe_unused]] auto c = span(std::move(str16));  // expected-error {{no matching conversion}}
154
155  std::vector<int> vec = {1, 2, 3, 4, 5};
156  [[maybe_unused]] auto d = span(std::move(vec));  // expected-error {{no matching conversion}}
157}
158
159void Dangling() {
160  // `std::array` destroyed at the end of the full expression.
161  [[maybe_unused]] auto a = span<const int>(std::to_array({1, 2, 3}));     // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
162  [[maybe_unused]] auto b = span<const int, 3>(std::to_array({1, 2, 3}));  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
163
164  // Range destroyed at the end of the full expression.
165  [[maybe_unused]] auto c = span<const int>(std::vector<int>({1, 2, 3}));     // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
166  [[maybe_unused]] auto d = span<const int, 3>(std::vector<int>({1, 2, 3}));  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
167
168  // Here the `std::string` is an lvalue, but the `std::vector`s that copy its
169  // data aren't.
170  std::string str = "123";
171  [[maybe_unused]] auto e =
172      span<const char>(std::vector<char>(str.begin(), str.end()));  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
173  [[maybe_unused]] auto f =
174      span<const char, 3>(std::vector<char>(str.begin(), str.end()));  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
175
176  // `std::string_view`'s safety depends on the life of the referred-to buffer.
177  // Here the underlying data is destroyed before the end of the full
178  // expression.
179  [[maybe_unused]] auto g =
180      span<const char>(std::string_view(std::string("123")));  // expected-error {{object backing the pointer will be destroyed at the end of the full-expression}}
181  [[maybe_unused]] auto h =
182      span<const char, 3>(std::string_view(std::string("123")));  // expected-error {{object backing the pointer will be destroyed at the end of the full-expression}}
183  // TODO(https://github.com/llvm/llvm-project/issues/111768) Detect dangling
184  // usage sufficient to enable this testcase.
185#if 0
186  [[maybe_unused]] auto i = as_byte_span(std::string_view(std::string("123")));  // expected-error {{object backing the pointer will be destroyed at the end of the full-expression}}
187#endif
188
189  // Spans must not outlast a referred-to C-style array. It's tricky to create
190  // an object of C-style array type (not an initializer list) that is destroyed
191  // before the end of the full expression, so instead test the case where the
192  // referred-to array goes out of scope before the referring span.
193  [] {
194    int arr[3] = {1, 2, 3};
195    return span<int>(arr);  // expected-error-re {{address of stack memory associated with local variable {{.*}}returned}}
196  }();
197  [] {
198    int arr[3] = {1, 2, 3};
199    return span<int, 3>(arr);  // expected-error-re {{address of stack memory associated with local variable {{.*}}returned}}
200  }();
201
202  // TODO(https://github.com/llvm/llvm-project/issues/99685) Detect dangling
203  // usage sufficient to enable this testcase.
204#if 0
205  []() -> std::optional<span<int>> {
206    int arr[3] = {1, 2, 3};
207    return span<int>(arr);  // expected-error-re {{address of stack memory associated with local variable {{.*}}returned}}
208  }();
209#endif
210
211  // span's `std::array` constructor takes lvalue refs, so to test the non-const
212  // `element_type` case, use the same technique as above.
213  [] {
214    std::array arr{1, 2, 3};
215    return span<int>(arr);  // expected-error-re + {{address of stack memory associated with local variable {{.*}}returned}}
216  }();
217  [] {
218    std::array arr{1, 2, 3};
219    return span<int, 3>(arr);  // expected-error-re + {{address of stack memory associated with local variable {{.*}}returned}}
220  }();
221}
222
223void NotSizeTSize() {
224  std::vector<int> vector = {1, 2, 3};
225  // Using distinct enum types causes distinct span template instantiations, so
226  // we get assertion failures below where we expect.
227  enum Length1 { kSize1 = -1 };
228  enum Length2 { kSize2 = -1 };
229  span s(vector.data(), kSize2);  // expected-error@*:* {{no matching function for call to 'strict_cast'}}
230}
231
232void BadConstConversionsWithStdSpan() {
233  int kData[] = {10, 11, 12};
234  {
235    span<const int, 3u> fixed_base_span(kData);
236    std::span<int, 3u> s(fixed_base_span);  // expected-error {{no matching constructor}}
237  }
238  {
239    std::span<const int, 3u> fixed_std_span(kData);
240    span<int, 3u> s(fixed_std_span);  // expected-error {{no matching constructor}}
241  }
242}
243
244void FromVolatileArrayDisallowed() {
245  static volatile int array[] = {1, 2, 3};
246  span<int> s(array);  // expected-error {{no matching constructor for initialization of 'span<int>'}}
247}
248
249void FixedSizeCopyTooSmall() {
250  const int src[] = {1, 2, 3};
251  int dst[2];
252  span(dst).copy_from(span(src));  // expected-error@*:* {{no matching member function}}
253
254  span(dst).copy_from(src);  // expected-error@*:* {{no matching member function}}
255
256  span(dst).copy_prefix_from(src);  // expected-error@*:* {{no matching member function}}
257}
258
259void FixedSizeCopyFromNonSpan() {
260  int dst[2];
261  // The copy_from() template overload is not selected.
262  span(dst).copy_from(5);  // expected-error@*:* {{no matching member function for call to 'copy_from'}}
263}
264
265void FixedSizeSplitAtOutOfBounds() {
266  const int arr[] = {1, 2, 3};
267  span(arr).split_at<4u>();  // expected-error@*:* {{no matching member function for call to 'split_at'}}
268}
269
270void DerefEmpty() {
271  constexpr span<int, 0> kEmptySpan;
272  [[maybe_unused]] int i = kEmptySpan[0];  // expected-error {{no viable overloaded operator[] for type 'const span<int, 0>'}}
273}
274
275void FromRefLifetimeBoundErrorForIntLiteral() {
276  // Testing that `LIFETIME_BOUND` works as intended.
277  [[maybe_unused]] auto wont_work = span_from_ref<const int>(123);        // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
278  [[maybe_unused]] auto wont_work2 = byte_span_from_ref<const int>(123);  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
279}
280
281void FromRefLifetimeBoundErrorForTemporaryStringObject() {
282  // Testing that `LIFETIME_BOUND` works as intended.
283  [[maybe_unused]] auto wont_work =
284      span_from_ref<const std::string>("temporary string");  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
285  [[maybe_unused]] auto wont_work2 =
286      as_byte_span(std::string("temporary string"));  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
287}
288
289void InitializerListLifetime() {
290  // `std::initializer_list` destroyed at the end of the full expression.
291  [[maybe_unused]] auto wont_work = span<const int>({1, 2});      // expected-error-re {{array backing local initializer list {{.*}}will be destroyed at the end of the full-expression}}
292  [[maybe_unused]] auto wont_work2 = span<const int, 3>({1, 2});  // expected-error-re {{array backing local initializer list {{.*}}will be destroyed at the end of the full-expression}}
293  [[maybe_unused]] auto wont_work3 = as_byte_span({1, 2});        // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
294}
295
296void FromCStringThatIsntStaticLifetime() {
297  [[maybe_unused]] auto wont_work = span_from_cstring({'a', 'b', '\0'});        // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
298  [[maybe_unused]] auto wont_work2 = byte_span_from_cstring({'a', 'b', '\0'});  // expected-error-re {{temporary whose address is used as value of local variable {{.*}}will be destroyed at the end of the full-expression}}
299}
300
301void CompareFixedSizeMismatch() {
302  const int arr[] = {1, 2, 3};
303  const int arr2[] = {1, 2, 3, 4};
304  (void)(span(arr) == arr2);  // expected-error@*:* {{invalid operands to binary expression}}
305  (void)(span(arr) == span(arr2));  // expected-error@*:* {{invalid operands to binary expression}}
306}
307
308void CompareNotComparable() {
309  struct NoEq { int i; };
310  static_assert(!std::equality_comparable<NoEq>);
311
312  const NoEq arr[] = {{1}, {2}, {3}};
313  (void)(span(arr) == arr);  // expected-error@*:* {{invalid operands to binary expression}}
314  (void)(span(arr) == span(arr));  // expected-error@*:* {{invalid operands to binary expression}}
315
316  struct SelfEq {
317    constexpr bool operator==(SelfEq s) const { return i == s.i; }
318    int i;
319  };
320  static_assert(std::equality_comparable<SelfEq>);
321  static_assert(!std::equality_comparable_with<SelfEq, int>);
322
323  const SelfEq self_arr[] = {{1}, {2}, {3}};
324  const int int_arr[] = {1, 2, 3};
325
326  (void)(span(self_arr) == int_arr);  // expected-error@*:* {{invalid operands to binary expression}}
327  (void)(span(self_arr) == span(int_arr));  // expected-error@*:* {{invalid operands to binary expression}}
328
329  // Span's operator== works on `const T` and thus won't be able to use the
330  // non-const operator here. We get this from equality_comparable which also
331  // requires it.
332  struct NonConstEq {
333    constexpr bool operator==(NonConstEq s) { return i == s.i; }
334    int i;
335  };
336  const NonConstEq non_arr[] = {{1}, {2}, {3}};
337  (void)(span(non_arr) == non_arr);  // expected-error@*:* {{invalid operands to binary expression}}
338  (void)(span(non_arr) == span(non_arr));  // expected-error@*:* {{invalid operands to binary expression}}
339}
340
341void AsStringViewNotBytes() {
342  const int arr[] = {1, 2, 3};
343  as_string_view(span(arr));  // expected-error@*:* {{no matching function for call to 'as_string_view'}}
344}
345
346void SpanFromCstrings() {
347  static const char with_null[] = { 'a', 'b', '\0' };
348  span_from_cstring(with_null);
349
350  // Can't call span_from_cstring and friends with a non-null-terminated char
351  // array.
352  static const char no_null[] = { 'a', 'b' };
353  span_from_cstring(no_null);  // expected-error@*:* {{no matching function for call to 'span_from_cstring'}}
354  span_with_nul_from_cstring(no_null);  // expected-error@*:* {{no matching function for call to 'span_with_nul_from_cstring'}}
355  byte_span_from_cstring(no_null);  // expected-error@*:* {{no matching function for call to 'byte_span_from_cstring'}}
356  byte_span_with_nul_from_cstring(no_null);  // expected-error@*:* {{no matching function for call to 'byte_span_with_nul_from_cstring'}}
357}
358
359}  // namespace base
360