Skip to content

Commit 783d0c6

Browse files
authored
Merge pull request #61722 from mikepinkerton/nodiscard
Test various nodiscard return cases.
2 parents 2b07049 + 5c6348c commit 783d0c6

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

test/Interop/Cxx/class/Inputs/module.modulemap

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ module MutabilityAnnotations {
6363
requires cplusplus
6464
}
6565

66+
module NoDiscard {
67+
header "nodiscard.h"
68+
requires cplusplus
69+
}
70+
6671
module ProtocolConformance {
6772
header "protocol-conformance.h"
6873
requires cplusplus
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#ifndef TEST_INTEROP_CXX_CLASS_NODISCARD_H
2+
#define TEST_INTEROP_CXX_CLASS_NODISCARD_H
3+
4+
[[nodiscard]] int NoDiscardAdd(int x, int y);
5+
6+
class NoDiscardMultiply {
7+
public:
8+
NoDiscardMultiply() {}
9+
~NoDiscardMultiply() {}
10+
11+
[[nodiscard]] int Multiply(int x, int y) { return x * y; }
12+
13+
int Divide(int x, int y) { return x / y; }
14+
};
15+
16+
struct [[nodiscard]] NoDiscardError {
17+
public:
18+
NoDiscardError(int value) : value_(value) {}
19+
int value_;
20+
};
21+
22+
NoDiscardError NoDiscardReturnError(int x, int y);
23+
24+
#endif
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Test various aspects of the C++ `nodiscard` keyword.
2+
3+
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop
4+
5+
import NoDiscard
6+
7+
// Test a function.
8+
9+
// CORRECT: return value not discarded.
10+
var value = NoDiscardAdd(5, 10)
11+
12+
// CORRECT: warning when return value is discarded.
13+
NoDiscardAdd(10, 10) // expected-warning {{result of call to 'NoDiscardAdd' is unused}}
14+
15+
16+
// Test methods in a class.
17+
18+
// CORRECT: return value not discarded.
19+
var multiplier = NoDiscardMultiply()
20+
value = multiplier.Multiply(10, 10)
21+
22+
// CORRECT: warning when return value is discarded
23+
multiplier.Multiply(50, 50) // expected-warning {{result of call to 'Multiply' is unused}}
24+
25+
// CORRECT: return value not discarded.
26+
value = multiplier.Divide(100, 10)
27+
28+
// CORRECT: method has no annotation, thus no warning
29+
multiplier.Divide(100, 10)
30+
31+
32+
// Test a struct marked with nodiscard as a return value from a function.
33+
34+
let error: NoDiscardError = NoDiscardReturnError(10, 10)
35+
36+
// INCORRECT: NoDiscardError is declared nodiscard, so ignoring the
37+
// return value of NoDiscardReturnError() should be a warning, but isn't.
38+
// Filed as: https://github.com/apple/swift/issues/59002
39+
NoDiscardReturnError(50, 50)

0 commit comments

Comments
 (0)