1# 2# Copyright 2019 Advanced Micro Devices, Inc. 3# 4# SPDX-License-Identifier: MIT 5# 6""" 7Helper script that was used during the generation of the JSON data. 8 9 usage: python3 canonicalize.py FILE 10 11Reads the register database from FILE, performs canonicalization 12(de-duplication of enums and register types, implicitly sorting JSON by name) 13and attempts to deduce missing register types. 14 15Notes about deduced register types as well as the output JSON are printed on 16stdout. 17""" 18 19from collections import defaultdict 20import json 21import re 22import sys 23 24from regdb import RegisterDatabase, deduplicate_enums, deduplicate_register_types 25 26RE_number = re.compile('[0-9]+') 27 28def deduce_missing_register_types(regdb): 29 """ 30 This is a heuristic for filling in missing register types based on 31 sequentially named registers. 32 """ 33 buckets = defaultdict(list) 34 for regmap in regdb.register_mappings(): 35 buckets[RE_number.sub('0', regmap.name)].append(regmap) 36 37 for bucket in buckets.values(): 38 if len(bucket) <= 1: 39 continue 40 41 regtypenames = set( 42 regmap.type_ref for regmap in bucket if hasattr(regmap, 'type_ref') 43 ) 44 if len(regtypenames) == 1: 45 regtypename = regtypenames.pop() 46 for regmap in bucket: 47 if not hasattr(regmap, 'type_ref'): 48 print('Deducing {0} -> {1}'.format(regmap.name, regtypename), file=sys.stderr) 49 regmap.type_ref = regtypename 50 51 52def json_canonicalize(filp, chips = None): 53 regdb = RegisterDatabase.from_json(json.load(filp)) 54 55 if chips is not None: 56 for regmap in regdb.register_mappings(): 57 assert not hasattr(regmap, 'chips') 58 regmap.chips = [chips] 59 60 deduplicate_enums(regdb) 61 deduplicate_register_types(regdb) 62 deduce_missing_register_types(regdb) 63 regdb.garbage_collect() 64 65 return regdb.encode_json_pretty() 66 67 68def main(): 69 print(json_canonicalize(open(sys.argv[1], 'r'), sys.argv[2])) 70 71if __name__ == '__main__': 72 main() 73 74# kate: space-indent on; indent-width 4; replace-tabs on; 75