Skip to content

Commit cb34735

Browse files
authored
let error_printer example print source line of parse error (#259)
1 parent 2ca7ac6 commit cb34735

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

examples/error_printer.cpp

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

105105
inline constexpr auto divider =
106106
"################################################################################"sv;
107+
108+
void print_string(std::string_view str)
109+
{
110+
for (char c : str)
111+
{
112+
if (c >= 0 && static_cast<std::size_t>(c) < std::size(toml::impl::control_char_escapes))
113+
{
114+
std::cout << toml::impl::control_char_escapes[static_cast<std::size_t>(c)];
115+
}
116+
else
117+
{
118+
if (c == '\\')
119+
{
120+
std::cout << '\\';
121+
}
122+
std::cout << c;
123+
}
124+
}
125+
}
126+
127+
void print_parse_error(std::string_view doc, const toml::parse_error& err)
128+
{
129+
std::cout << err;
130+
131+
auto line_num = err.source().begin.line;
132+
133+
if (auto line = toml::get_line(doc, line_num))
134+
{
135+
std::cout << "\nLine "sv << line_num << ": "sv;
136+
print_string(*line);
137+
}
138+
std::cout << "\n\n"sv;
139+
}
107140
}
108141

109142
int main()
@@ -118,11 +151,11 @@ int main()
118151
}
119152
catch (const toml::parse_error& err)
120153
{
121-
std::cout << err << "\n\n"sv;
154+
print_parse_error(str, err);
122155
}
123156
#else
124157
if (auto result = toml::parse(str); !result)
125-
std::cout << result.error() << "\n\n"sv;
158+
print_parse_error(str, result.error());
126159
#endif
127160
};
128161

0 commit comments

Comments
 (0)