@@ -1,49 +1,38 @@
// SPDX-FileCopyrightText: 2021-2022 Robin Lindén <dev@robinlinden.eu>
// SPDX-FileCopyrightText: 2021-2023 Robin Lindén <dev@robinlinden.eu>
//
// SPDX-License-Identifier: BSD-2-Clause
#include "html2/token.h"
#include "util/overloaded.h"
#include <fmt/format.h>
#include <optional>
#include <ostream>
#include <sstream>
#include <string>
#include <utility>
#include <variant>
namespace html2 {
namespace {
class TokenStringifier {
public:
static std::string to_string(Token const &token) { return std::visit(TokenStringifier{}, token); }
std::string operator()(DoctypeToken const &t) {
return fmt::format("Doctype {} {} {}",
t.name.value_or(R"("")"),
t.public_identifier.value_or(R"("")"),
t.system_identifier.value_or(R"("")"));
}
std::string operator()(StartTagToken const &t) { return fmt::format("StartTag {} {}", t.tag_name, t.self_closing); }
std::string operator()(EndTagToken const &t) { return fmt::format("EndTag {} {}", t.tag_name, t.self_closing); }
std::string operator()(CommentToken const &t) { return fmt::format("Comment {}", t.data); }
std::string operator()(CharacterToken const &t) { return fmt::format("Character {}", t.data); }
std::string operator()(EndOfFileToken const &) { return "EndOfFile"; }
};
} // namespace
std::string to_string(Token const &token) {
auto try_print = []<typename T>(std::ostream &os, std::optional<T> maybe_value) {
if (maybe_value) {
os << ' ' << *maybe_value;
} else {
os << R"( "")";
}
};
std::stringstream ss;
std::visit(util::Overloaded{
[&](DoctypeToken const &t) {
ss << "Doctype";
try_print(ss, t.name);
try_print(ss, t.public_identifier);
try_print(ss, t.system_identifier);
},
[&ss](StartTagToken const &t) {
ss << "StartTag " << t.tag_name << ' ' << (t.self_closing ? "true" : "false");
},
[&ss](EndTagToken const &t) {
ss << "EndTag " << t.tag_name << ' ' << (t.self_closing ? "true" : "false");
},
[&ss](CommentToken const &t) { ss << "Comment " << t.data; },
[&ss](CharacterToken const &t) { ss << "Character " << t.data; },
[&ss](EndOfFileToken const &) { ss << "EndOfFile"; },
},
token);
return std::move(ss).str();
return TokenStringifier::to_string(token);
}
} // namespace html2