7814
Ta
tiny-c-agent / files
tiny-c-agent / tools / gen_queries.py
2.1 KB
1#!/usr/bin/env python3 2"""Generates src/queries.generated.c from the tree-sitter queries in vendor/. 3 4The .scm files under vendor/queries/ are the source of truth. Run 5`make queries` after changing one; the output is committed, so normal builds 6read no query files from disk. 7""" 8 9import os 10import sys 11 12DIR = "vendor/queries" 13OUT = "src/queries.generated.c" 14 15 16def cstr(s): 17 out = ['"'] 18 for ch in s: 19 if ch == "\\": 20 out.append("\\\\") 21 elif ch == '"': 22 out.append('\\"') 23 elif ch == "\n": 24 out.append("\\n") 25 elif ch == "\t": 26 out.append("\\t") 27 elif ch == "\r": 28 out.append("\\r") 29 elif ch == "?": 30 # Escape ? so "??" followed by a trigraph letter cannot be read as 31 # a trigraph under strict -std=c11. 32 out.append("\\?") 33 else: 34 out.append(ch) 35 out.append('"') 36 return "".join(out) 37 38 39def main(): 40 base = sys.argv[1] if len(sys.argv) > 1 else DIR 41 out_path = sys.argv[2] if len(sys.argv) > 2 else OUT 42 43 langs = sorted( 44 d for d in os.listdir(base) 45 if os.path.isfile(os.path.join(base, d, "highlights.scm")) 46 ) 47 48 lines = [ 49 "// Generated by tools/gen_queries.py from vendor/queries. Do not edit.", 50 "// Refresh with `make queries`.", 51 "", 52 '#include "queries.h"', 53 "", 54 "static const tiny_query tiny_queries[] = {", 55 ] 56 for lang in langs: 57 with open(os.path.join(base, lang, "highlights.scm")) as f: 58 body = f.read() 59 lines.append(" {%s,\n %s}," % (cstr(lang), cstr(body))) 60 lines += [ 61 "};", 62 "", 63 "const char *tiny_query_for(const char *lang) {", 64 " for (size_t i = 0; i < sizeof tiny_queries / sizeof tiny_queries[0]; i++)", 65 " if (strcmp(tiny_queries[i].lang, lang) == 0) return tiny_queries[i].text;", 66 " return NULL;", 67 "}", 68 "", 69 ] 70 71 with open(out_path, "w") as f: 72 f.write("\n".join(lines)) 73 print("wrote %s (%d languages: %s)" % (out_path, len(langs), " ".join(langs))) 74 75 76if __name__ == "__main__": 77 main()