Created
July 30, 2021 21:52
-
-
Save Lokno/8006166f6ab9de1c101914b9bd02cd89 to your computer and use it in GitHub Desktop.
Python3 Script that takes a file of C variable declarations and produces a C function that prints the variables to std out
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| import sys | |
| if len(sys.argv) != 3: | |
| print(f' usage: {sys.argv[0]:s} <declaration file> <name>') | |
| sys.exit(0) | |
| array_re = re.compile( "([A-Za-z_ ]+) +([a-zA-Z0-9_]+)\[([0-9]+)\];?\n" ) | |
| value_re = re.compile( "([A-Za-z_ ]+) +([a-zA-Z0-9_]+);?\n" ) | |
| with open(sys.argv[1]) as f: | |
| file_str = f.read() | |
| arrays = array_re.findall(file_str) | |
| values = value_re.findall(file_str) | |
| types = {'unsigned int' : 'u', | |
| 'int' : 'd', | |
| 'long' : 'ld', | |
| 'long long' : 'lld', | |
| 'unsigned long' : 'lu', | |
| 'unsigned long long' : 'llu', | |
| 'char' : 's', | |
| 'unsigned char' : 'u', | |
| 'size_t' : 'lu', | |
| 'float' : 'f', | |
| 'double' : 'f' } | |
| out_str = f'void print_{sys.argv[2]:s}({sys.argv[2]:s}* p)\n{{\n' | |
| for val_type,val_name in values: | |
| orig_type = val_type | |
| new_type = False | |
| while val_type not in types.keys(): | |
| new_type = True | |
| val_type = input('Type \'%s\' unrecognized for value \'%s\'.\nPlease enter a known type:' % (val_type,val_name)) | |
| if new_type: | |
| types[orig_type] = types[val_type] | |
| out_str += f' printf("{val_name:s} : %{types[val_type]:s}\\n", p->{val_name:s});\n' | |
| for arr_type,arr_name,count in arrays: | |
| orig_type = arr_type | |
| new_type = False | |
| while arr_type not in types.keys(): | |
| new_type = True | |
| arr_type = input('Type \'%s\' unrecognized for array \'%s\'.\nPlease enter a known type:' % (arr_type,arr_name)) | |
| if new_type: | |
| types[orig_type] = types[arr_type] | |
| if types[arr_type] == 's': | |
| out_str += f' printf("{arr_name:s} : %s\\n", p->{arr_name:s})\n' | |
| else: | |
| out_str += f' printf("{arr_name:s} : [%{types[arr_type]:s}", p->{arr_name:s}[0]); for(int i = 1; i < {count:s}; ++i ) {{ printf(",%{types[arr_type]:s}", p->{arr_name:s}[i]); }} printf("]\\n");\n' | |
| out_str += '}' | |
| print(out_str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment