Created
July 4, 2025 19:53
-
-
Save faresbakhit/ea552a4b4da7ce4b090c590cca4209a2 to your computer and use it in GitHub Desktop.
drealias - like ddemangle but for aliases
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/python | |
| import glob | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| MAPPINGS_FILE = "mappings.drealias" | |
| def process_aliases(s): | |
| alias_line = "\nalias " | |
| i, p = 0, "" | |
| while True: | |
| alias_name_start = s.find(alias_line, i) | |
| if alias_name_start == -1: | |
| p += s[i:] | |
| return p | |
| alias_name_start = alias_name_start + len(alias_line) | |
| alias_name_end = alias_name_start | |
| while s[alias_name_end].isalnum(): | |
| alias_name_end += 1 | |
| alias_name = s[alias_name_start:alias_name_end] | |
| semicolon = s.find(";", alias_name_end) + 1 | |
| if semicolon == 0: | |
| raise RuntimeError("`alias` without a semicolon (`;`)") | |
| p += s[i:semicolon] + f'pragma(msg, {alias_name}.stringof); pragma(msg, "{alias_name}");' | |
| i = semicolon | |
| def main(): | |
| if (len(sys.argv) > 1 and sys.argv[1] == "-f") or not os.path.exists(MAPPINGS_FILE): | |
| for file in glob.glob("source/*.d"): | |
| shutil.copyfile(file, file + ".tmp") | |
| try: | |
| for file in glob.glob("source/*.d"): | |
| with open(file, "r") as fp: | |
| contents = fp.read() | |
| contents = process_aliases(contents) | |
| with open(file, "w") as fp: | |
| fp.write(contents) | |
| result = subprocess.run(["dub", "build", "-b=syntax", "-q"], stderr=subprocess.PIPE, text=True) | |
| lines = result.stderr.splitlines() | |
| mappings = [(lines[i], lines[i + 1]) for i in range(0, len(lines), 2)] | |
| mappings.sort(key=lambda pair: len(pair[0])) | |
| for i1, (key1, value1) in enumerate(mappings): | |
| for i2, (key2, value2) in enumerate(mappings[i1+1:], i1+1): | |
| mappings[i2] = mappings[i2][0].replace(key1, value1), value2 | |
| with open(MAPPINGS_FILE, "w") as fp: | |
| for key, value in mappings: | |
| fp.write(key + "\n" + value + "\n") | |
| finally: | |
| for file in glob.glob("source/*.d"): | |
| os.replace(file + ".tmp", file) | |
| else: | |
| with open(MAPPINGS_FILE) as fp: | |
| lines = [line.strip() for line in fp] | |
| mappings = [(lines[i], lines[i + 1]) for i in range(0, len(lines), 2)] | |
| for line in sys.stdin: | |
| for key, value in mappings: | |
| line = line.replace(key, value) | |
| sys.stdout.write(line) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment