Advertisement
Guest User

Untitled

a guest
Jun 29th, 2020
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import subprocess
  4. import sys
  5. import re
  6. import os
  7.  
  8. [src] = [arg for arg in sys.argv[1:] if arg.endswith('.cpp')]
  9. argv = [arg for arg in sys.argv[1:] if arg != src]
  10. src_tmp = src.rsplit('.', 1)[0] + '.tmp.cpp'
  11. includes, lines = [], []
  12.  
  13. with open(src, 'r') as infile:
  14.     for line in infile:
  15.         if re.match(r"#include\s*<[^>]*>", line):
  16.             includes.append(line)
  17.         else:
  18.             lines.append(line)
  19.  
  20. with open(src_tmp, 'w') as tmpfile:
  21.     tmpfile.writelines(lines)
  22.  
  23. output = subprocess.check_output(['g++', '-E', '-C', src_tmp] + argv).decode('utf-8')
  24. # Remove preprocessor artifacts.
  25. lines = [line + '\n' for line in output.splitlines()
  26.          if not line.startswith('# ')]
  27.  
  28. # At this point you could write your own post-processing routine.
  29. # This perticular one removes duplicate "using namespace ...;"
  30. # and duplicate empty lines.
  31. nlines = []
  32. found_namespaces = set()
  33. for line in lines:
  34.     if not line.strip() and nlines and not nlines[-1].strip():
  35.         continue
  36.     if line.strip() == ';':
  37.         continue
  38.     match = re.match(r"using\s+namespace\s+([^;]+);", line)
  39.     if match:
  40.         match = match[1]
  41.         if match in found_namespaces:
  42.             continue
  43.         found_namespaces.add(match)
  44.     nlines.append(line)
  45. lines = nlines
  46. output = "".join(includes + lines)
  47.  
  48. os.remove(src_tmp)
  49. print(output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement