Skip to content

Truly independent web browser

2.2 KB
Raw Blame
/*
 * Copyright (c) 2025, Sam Atkins <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/HashTable.h>
#include <LibWeb/CSS/Parser/ErrorReporter.h>

namespace Web::CSS::Parser {

String serialize_parsing_error(ParsingError const& error)
{
    return error.visit(
        [](UnknownPropertyError const& error) {
            return MUST(String::formatted("Unknown property '{}' in {} rule.", error.property_name, error.rule_name));
        },
        [](UnknownRuleError const& error) {
            return MUST(String::formatted("Unknown rule '{}'.", error.rule_name));
        },
        [](InvalidPropertyError const& error) {
            return MUST(String::formatted("Property '{}' in {} rule has invalid value `{}`.", error.property_name, error.rule_name, error.value_string));
        },
        [](InvalidRuleError const& error) {
            return MUST(String::formatted("'{}' rule with prelude `{}` is invalid: {}", error.rule_name, error.prelude, error.description));
        },
        [](InvalidRuleLocationError const& error) {
            return MUST(String::formatted("'{}' rule is invalid inside {}", error.inner_rule_name, error.outer_rule_name));
        },
        [](SyntaxDiagnosticError const& error) {
            auto description = error.code == SyntaxDiagnosticCode::BadString ? "Bad string token"sv : "Bad URL token"sv;
            return MUST(String::formatted("{} at {}:{}-{}:{}.", description, error.start_line, error.start_column, error.end_line, error.end_column));
        });
}

ErrorReporter& ErrorReporter::the()
{
    static ErrorReporter& error_reporter = *new ErrorReporter;
    return error_reporter;
}

void ErrorReporter::report(ParsingError&& error)
{
    if (auto existing = m_errors.get(error); existing.has_value()) {
        existing->occurrences++;
        return;
    }

    dbgln_if(CSS_PARSER_DEBUG, "CSS parsing error: {}", serialize_parsing_error(error));
    m_errors.set(move(error), { .occurrences = 1 });
}

void ErrorReporter::dump() const
{
    // TODO: Organise this in some way?
    dbgln("{} CSS errors reported:", m_errors.size());
    for (auto const& [error, metadata] : m_errors) {
        dbgln("- {} ({} occurrences)", serialize_parsing_error(error), metadata.occurrences);
    }
}

}