Skip to content

Instantly share code, notes, and snippets.

@john-science
Last active July 9, 2018 17:47
Show Gist options
  • Save john-science/3eba6ef87dc4d3ffab5abac4d0329b8b to your computer and use it in GitHub Desktop.
Save john-science/3eba6ef87dc4d3ffab5abac4d0329b8b to your computer and use it in GitHub Desktop.
Just make random edits until it compiles.
#!/usr/bin/env python
"""
XKCD Compile
Usage: compile_xkcd.py [FILE.c]
Compile your C code XKCD style.
Exactly one file must be specified.
Inspired by XKCD: https://xkcd.com/1513/
UNDER CONSTRUCTION
Probable Path: Clang exposes their AST parser/lexer
https://stackoverflow.com/questions/18560019/how-to-view-clang-ast
"""
import os
import sys
def main():
""" parse command-line and direct the primary tasks
"""
if len(sys.argv) > 1:
file_path = sys.argv[1]
else:
usage()
# execute code
xkcd = XKCD_Compiler(file_path)
xkcd.compile()
def usage():
''' Print the help menu.
'''
print(__doc__.strip())
exit()
class XKCD_Compiler(object):
def __init__(self, file_path, max_iter=10000):
self.original = file_path
self.file_path = file_path.rstrip('.c') + '_new.c'
self.code = list(open(self.original, 'r').readlines())
self.max_iterations = max_iter
def compile(self):
''' Make random edits to a file
until it compiles using GCC.
'''
i = 0
while self.does_compile() and i < self.max_iterations:
self.random_edits()
i += 1
def does_compile(self):
''' Try to compile the file
(assumes you have GCC and a Linux env)
'''
# TODO: turn off some safety flags
return os.system('gcc ' + self.file_path + ' 2> /dev/null')
def random_edits(self):
''' Make random C-esque edits to the code.
'''
# TODO: Magic
# TODO: 1) Remove comments: gcc -fpreprocessed -dD -E test.c
# https://stackoverflow.com/questions/2394017/remove-comments-from-c-c-code
# TODO: 2) remove whitespace and obfuscate variables?
# TODO: 3) make "random" C-like edits?
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment