// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later

/* This file is part of the dynarmic project.
 * Copyright (c) 2016 MerryMage
 * SPDX-License-Identifier: 0BSD
 *
 * Original version of table by Lioncash.
 */

#pragma once

#include <algorithm>
#include <functional>
#include <optional>
#include <vector>

#include "dynarmic/mcl/bit.hpp"
#include "common/common_types.h"

#include "dynarmic/frontend/decoder/decoder_detail.h"
#include "dynarmic/frontend/decoder/matcher.h"

namespace Dynarmic::A32 {

template<typename Visitor>
using ArmMatcher = Decoder::Matcher<Visitor, u32>;

template<typename Visitor>
using ArmDecodeTable = std::array<std::vector<ArmMatcher<Visitor>>, 0x1000>;

namespace detail {
inline size_t ToFastLookupIndexArm(u32 instruction) noexcept {
    return ((instruction >> 4) & 0x00F) | ((instruction >> 16) & 0xFF0);
}
}  // namespace detail

template<typename V>
static ArmDecodeTable<V> GetArmDecodeTable() noexcept {
    ArmDecodeTable<V> table{};
    for (size_t i = 0; i < table.size(); ++i) {
        // PLEASE HEAP ELLIDE
        for (auto const& e : std::vector<ArmMatcher<V>>{
#define INST(fn, name, bitstring) DYNARMIC_DECODER_GET_MATCHER(ArmMatcher, fn, name, Decoder::detail::StringToArray<32>(bitstring)),
#include "./arm.inc"
#undef INST
        }) {
            auto const expect = detail::ToFastLookupIndexArm(e.GetExpected());
            auto const mask = detail::ToFastLookupIndexArm(e.GetMask());
            if ((i & mask) == expect) {
                table[i].push_back(e);
            }
        }
    }
    return table;
}

template<typename V>
static std::optional<std::reference_wrapper<const ArmMatcher<V>>> DecodeArm(u32 instruction) noexcept {
    alignas(64) static const auto table = GetArmDecodeTable<V>();
    const auto matches_instruction = [instruction](const auto& matcher) {
        return matcher.Matches(instruction);
    };
    const auto& subtable = table[detail::ToFastLookupIndexArm(instruction)];
    auto iter = std::find_if(subtable.begin(), subtable.end(), matches_instruction);
    return iter != subtable.end() ? std::optional<std::reference_wrapper<const ArmMatcher<V>>>(*iter) : std::nullopt;
}

template<typename V>
static std::optional<std::string_view> GetNameARM(u32 inst) noexcept {
    std::vector<std::pair<std::string_view, ArmMatcher<V>>> list = {
#define INST(fn, name, bitstring) { name, DYNARMIC_DECODER_GET_MATCHER(ArmMatcher, fn, name, Decoder::detail::StringToArray<32>(bitstring)) },
#include "./arm.inc"
#undef INST
    };
    auto const iter = std::find_if(list.cbegin(), list.cend(), [inst](auto const& m) {
        return m.second.Matches(inst);
    });
    return iter != list.cend() ? std::optional{iter->first} : std::nullopt;
}

}  // namespace Dynarmic::A32
