1#!/usr/bin/python 2# 3# Copyright (C) 2023 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16# 17 18import json 19import re 20import sys 21 22# Add numbers to the names of fields to rearrange them better. 23# They would be removed from final file. 24field_substitute = { 25 'name' : '|000|name', 26 'variants' : '|001|variants', 27 'insn' : '|002|insn', 28 'feature' : '|003|feature', 29 'nan' : '|003|nan', 30 'usage' : '|003|usage', 31 'in' : '|004|in', 32 'out' : '|005|out', 33 'comment' : '|010|comment' 34} 35 36def Version(str): 37 result = [] 38 isdigit = False 39 word = '' 40 for char in str + ('a' if str[-1:].isdigit() else '0'): 41 if char.isdigit() == isdigit: 42 word += char 43 else: 44 if isdigit: 45 result.append(('0' * 1000 + word)[-1000:]) 46 else: 47 result.append((word + ' ' * 1000)[:1000]) 48 isdigit = not isdigit 49 word = char 50 return '.'.join(result) 51 52 53def main(argv): 54 # Usage: prettify_ir_binding.py <file.json> 55 56 with open(argv[1]) as file: 57 json_bindings = json.load(file) 58 59 out_bindings = [] 60 license_text = [] 61 for binding in json_bindings: 62 new_binding = {} 63 if isinstance(binding, str): 64 license_text.append(binding) 65 else: 66 for field, value in binding.items(): 67 new_binding[field_substitute[field]] = value 68 out_bindings.append(new_binding) 69 70 out_bindings = license_text + sorted(out_bindings, 71 key=lambda binding: 72 Version(binding[field_substitute['name']] + 73 str(binding.get(field_substitute['variants'], '')) + 74 str(binding.get(field_substitute['usage'], '')) + 75 str(binding.get(field_substitute['nan'], '')) + 76 str(binding.get(field_substitute['feature'], '')))) 77 78 text = json.dumps(out_bindings, indent=2, sort_keys=True) 79 80 # Remove numbers from names of fields 81 text = re.sub('[|][0-9][0-9][0-9][|]', '', text) 82 83 def replace_if_short(match): 84 match = match.group() 85 replace = ' '.join(match.split()) 86 if len(replace) < 90: 87 return replace 88 else: 89 return match 90 91 # Make short lists one-liners 92 text = re.sub('[\[{][^][{}]*[]}]', replace_if_short, text) 93 94 # Remove trailing spaces 95 text = re.sub(' $', '', text, flags=re.MULTILINE) 96 97 # Fix the license 98 text = re.sub('\\\\u201c', '“', text, flags=re.MULTILINE) 99 text = re.sub('\\\\u201d', '”', text, flags=re.MULTILINE) 100 101 with open(argv[1], 'w') as file: 102 print(text, file=file) 103 104if __name__ == '__main__': 105 sys.exit(main(sys.argv)) 106