#!/usr/bin/env bash
# Copyright 2025 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Regenerate AArch64 system register constants.
# This is the WRONG WAY to parse XML - don't try this at home.

cd "$(dirname "$0")"

echo >special.txt
for reg in SysReg_xml_A_profile-2024-12/AArch64-*.xml; do
    data="$(grep -T -E -A13 'accessor="(MRS|MSR)' $reg; echo --)"

    while IFS= read -r -d '--' reg; do
        if [[ -z "$reg" ]]; then
            continue
        fi

        reg_name="$(echo $reg | grep access_mechanism | awk '{ print $3 }' | tr -d '"')"

        if [[ -z "$reg_name" ]]; then
            continue
        fi

        op0="$(echo $reg | grep -E -o 'n="op0" v="0b[01]+' | awk '{ print $2 }' | sed -e 's/v="//')"
        op1="$(echo $reg | grep -E -o 'n="op1" v="0b[01]+' | awk '{ print $2 }' | sed -e 's/v="//')"
        crn="$(echo $reg | grep -E -o 'n="CRn" v="0b[01]+' | awk '{ print $2 }' | sed -e 's/v="//')"
        crm="$(echo $reg | grep -E -o 'n="CRm" v="0b[01]+' | awk '{ print $2 }' | sed -e 's/v="//')"
        op2="$(echo $reg | grep -E -o 'n="op2" v="0b[01]+' | awk '{ print $2 }' | sed -e 's/v="//')"

        # skip parameterized regs
        if [[ ${#op0} -ne 4 || ${#op1} -ne 5 || ${#crn} -ne 6 || ${#crm} -ne 6 || ${#op2} -ne 5 ]]; then
            echo $reg_name >> special.txt
            continue
        fi

        # prefix with the numeric value for sorting
        printf "${op0}${op1}${crn}${crm}${op2}\tpub const %-19s : AArch64SysRegId = AArch64SysRegId::new_unchecked(${op0}, ${op1}, ${crn}, ${crm}, ${op2});\n" "${reg_name}"
    done <<< "$data"
done > gen-unsorted.rs

cat >src/gen.rs <<EOF
/* automatically generated by gen.sh - do not manually edit */

#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(non_upper_case_globals)]

use crate::AArch64SysRegId;

//                                                                                Op0    Op1     CRn     CRm    Op2
EOF

# Sort numerically, remove duplicates, and trim the sorting prefix.
sort gen-unsorted.rs | uniq | cut -f2- -d$'\t' >> src/gen.rs
rm gen-unsorted.rs

echo "These registers may require special handling:"
sort special.txt | uniq | sed -e 's/&lt;/</g' -e 's/&gt;/>/g'
