Created
October 4, 2015 20:51
-
-
Save nabijaczleweli/3fb698046c2796562f7a to your computer and use it in GitHub Desktop.
Optimizing BF transpiler
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
| #!/usr/bin/python3 | |
| import sys | |
| import itertools | |
| def print_header(): | |
| print('#include <stdio.h>') | |
| print() | |
| print() | |
| print('int main() {') | |
| print() | |
| print('char wholemem[30000] = {};') | |
| print('char * mem = wholemem;') | |
| print() | |
| def print_footer(): | |
| print() | |
| print("putchar('\\n');") | |
| print('}') | |
| source_character_set = { | |
| '<': lambda x: 'mem -= {};'.format(x), | |
| '>': lambda x: 'mem += {};'.format(x), | |
| '+': lambda x: '*mem += {};'.format(x), | |
| '-': lambda x: '*mem -= {};'.format(x), | |
| '.': lambda x: 'putchar(*mem);' * x, | |
| ',': lambda x: '*mem = getchar();' * x, | |
| '[': lambda x: 'while(*mem) {' * x, | |
| ']': lambda x: '}' * x, | |
| } | |
| def main(): | |
| print_header() | |
| if len(sys.argv) == 1 or sys.argv[1] == '-': | |
| program = sys.stdin.read() | |
| else: | |
| with open(sys.argv[1], 'r') as program_file: | |
| program = program_file.read() | |
| for ch, rep in itertools.groupby(filter(lambda c: c in source_character_set, program)): | |
| print(source_character_set[ch](len(list(rep)))) | |
| print_footer() | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment