Skip to content

Commit ffa0d3f

Browse files
committed
let error_printer example print source line of parse error
Showing a typical use case for `toml::get_line`.
1 parent 2ca7ac6 commit ffa0d3f

File tree

1 file changed

+73
-2
lines changed

1 file changed

+73
-2
lines changed

examples/error_printer.cpp

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,77 @@ namespace
104104

105105
inline constexpr auto divider =
106106
"################################################################################"sv;
107+
108+
void print_string(std::string_view str)
109+
{
110+
// clang-format off
111+
constexpr std::string_view control_char_escapes[] =
112+
{
113+
"\\u0000"sv,
114+
"\\u0001"sv,
115+
"\\u0002"sv,
116+
"\\u0003"sv,
117+
"\\u0004"sv,
118+
"\\u0005"sv,
119+
"\\u0006"sv,
120+
"\\u0007"sv,
121+
"\\b"sv,
122+
"\\t"sv,
123+
"\\n"sv,
124+
"\\u000B"sv,
125+
"\\f"sv,
126+
"\\r"sv,
127+
"\\u000E"sv,
128+
"\\u000F"sv,
129+
"\\u0010"sv,
130+
"\\u0011"sv,
131+
"\\u0012"sv,
132+
"\\u0013"sv,
133+
"\\u0014"sv,
134+
"\\u0015"sv,
135+
"\\u0016"sv,
136+
"\\u0017"sv,
137+
"\\u0018"sv,
138+
"\\u0019"sv,
139+
"\\u001A"sv,
140+
"\\u001B"sv,
141+
"\\u001C"sv,
142+
"\\u001D"sv,
143+
"\\u001E"sv,
144+
"\\u001F"sv,
145+
};
146+
// clang-format on
147+
148+
for (char c : str)
149+
{
150+
if (c >= 0 && static_cast<std::size_t>(c) < std::size(control_char_escapes))
151+
{
152+
std::cout << control_char_escapes[static_cast<std::size_t>(c)];
153+
}
154+
else
155+
{
156+
if (c == '\\')
157+
{
158+
std::cout << '\\';
159+
}
160+
std::cout << c;
161+
}
162+
}
163+
}
164+
165+
void print_parse_error(std::string_view doc, const toml::parse_error& err)
166+
{
167+
std::cout << err;
168+
169+
auto line_num = err.source().begin.line;
170+
171+
if (auto line = toml::get_line(doc, line_num))
172+
{
173+
std::cout << "\nLine "sv << line_num << ": "sv;
174+
print_string(*line);
175+
}
176+
std::cout << "\n\n"sv;
177+
}
107178
}
108179

109180
int main()
@@ -118,11 +189,11 @@ int main()
118189
}
119190
catch (const toml::parse_error& err)
120191
{
121-
std::cout << err << "\n\n"sv;
192+
print_parse_error(str, err);
122193
}
123194
#else
124195
if (auto result = toml::parse(str); !result)
125-
std::cout << result.error() << "\n\n"sv;
196+
print_parse_error(str, result.error());
126197
#endif
127198
};
128199

0 commit comments

Comments
 (0)