Debian Codegraph @

clang/test/Sema/c2x-nodiscard.c

raw
1 // RUN: %clang_cc1 -fsyntax-only -std=c2x -verify %s
2
3 // This is the latest version of nodiscard that we support.
4 _Static_assert(__has_c_attribute(nodiscard) == 202003L);
5
6 struct [[nodiscard]] S1 { // ok
7 int i;
8 };
9 struct [[nodiscard, nodiscard]] S2 { // ok
10 int i;
11 };
12 struct [[nodiscard("Wrong")]] S3 {
13 int i;
14 };
15
16 struct S3 get_s3(void);
17
18 [[nodiscard]] int f1(void);
19 enum [[nodiscard]] E1 { One };
20
21 [[nodiscard]] int i; // expected-warning {{'nodiscard' attribute only applies to Objective-C methods, enums, structs, unions, classes, functions, function pointers, and typedefs}}
22
23 struct [[nodiscard]] S4 {
24 int i;
25 };
26 struct S4 get_s(void);
27
28 enum [[nodiscard]] E2 { Two };
29 enum E2 get_e(void);
30
31 [[nodiscard]] int get_i(void);
32
33 void f2(void) {
34 get_s(); // expected-warning {{ignoring return value of type 'S4' declared with 'nodiscard' attribute}}
35 get_s3(); // expected-warning {{ignoring return value of type 'S3' declared with 'nodiscard' attribute: Wrong}}
36 get_i(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
37 get_e(); // expected-warning {{ignoring return value of type 'E2' declared with 'nodiscard' attribute}}
38
39 // Okay, warnings are not encouraged
40 (void)get_s();
41 (void)get_s3();
42 (void)get_i();
43 (void)get_e();
44
45 One; // expected-warning {{expression result unused}}
46 (enum E2)(0); // expected-warning {{expression result unused}}
47 (struct S4){1}; // expected-warning {{expression result unused}}
48 }
49
50 struct [[nodiscard]] error_info{
51 int i;
52 };
53
54 struct error_info enable_missile_safety_mode(void);
55 void launch_missiles(void);
56 void test_missiles(void) {
57 enable_missile_safety_mode(); // expected-warning {{ignoring return value of type 'error_info' declared with 'nodiscard'}}
58 launch_missiles();
59 }
60
61 [[nodiscard]] int f3();
62
63 void GH104391() {
64 #define M (unsigned int) f3()
65 M; // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
66 }
67
68 [[nodiscard]] typedef int NoDInt; // expected-warning {{'[[nodiscard]]' attribute ignored when applied to a typedef}}
69 typedef __attribute__((warn_unused)) int WUInt; // expected-warning {{'warn_unused' attribute only applies to structs, unions, and classes}}
70 typedef __attribute__((warn_unused_result)) int WURInt;
71 NoDInt get_nodint();
72 WUInt get_wuint();
73 WURInt get_wurint();
74
75 void f4(void) {
76 get_nodint(); // no warning because attribute is ignored
77 get_wuint(); // no warning because attribute is ignored
78 get_wurint(); // expected-warning {{ignoring return value of type 'WURInt' declared with 'warn_unused_result' attribute}}
79 }