-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReturnLocalRefRule.cpp
More file actions
104 lines (88 loc) · 2.75 KB
/
Copy pathReturnLocalRefRule.cpp
File metadata and controls
104 lines (88 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
*
* @file ReturnLocalRefRule.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
*
*/
#include <vix/cli/errors/IErrorRule.hpp>
#include <vix/cli/errors/CodeFrame.hpp>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <memory>
#include <string>
#include <vix/cli/Style.hpp>
using namespace vix::cli::style;
namespace vix::cli::errors
{
namespace
{
std::string to_lower_ascii(std::string text)
{
std::transform(
text.begin(),
text.end(),
text.begin(),
[](unsigned char c)
{
return static_cast<char>(std::tolower(c));
});
return text;
}
} // namespace
class ReturnLocalRefRule final : public IErrorRule
{
public:
bool match(const CompilerError &err) const override
{
const std::string message = to_lower_ascii(err.message);
const bool mentionsReturn =
message.find("return") != std::string::npos ||
message.find("returned") != std::string::npos ||
message.find("returning") != std::string::npos;
const bool localAddress =
message.find("address of local") != std::string::npos ||
message.find("address of stack memory") != std::string::npos ||
message.find("reference to local") != std::string::npos ||
message.find("reference to stack") != std::string::npos ||
(message.find("local variable") != std::string::npos &&
message.find("returned") != std::string::npos);
const bool stackLifetime =
message.find("stack memory") != std::string::npos ||
message.find("temporary") != std::string::npos ||
message.find("does not live long enough") != std::string::npos;
return mentionsReturn && (localAddress || stackLifetime);
}
bool handle(
const CompilerError &err,
const ErrorContext &ctx) const override
{
std::cerr << RED
<< "error: returning local object reference"
<< RESET << "\n";
printCodeFrame(err, ctx);
std::cerr << YELLOW
<< "hint: "
<< RESET
<< "return by value or ensure the referenced object outlives the function"
<< "\n";
std::cerr << GREEN
<< "at: "
<< RESET
<< err.file << ":" << err.line << ":" << err.column
<< "\n";
return true;
}
};
std::unique_ptr<IErrorRule> makeReturnLocalRefRule()
{
return std::make_unique<ReturnLocalRefRule>();
}
} // namespace vix::cli::errors