Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
288 lines (245 loc) · 12.2 KB
/
Copy pathparser.py
File metadata and controls
288 lines (245 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import re
import clang.cindex
import json
import subprocess
import tempfile
import os
from pathlib import Path
from parser.families import all_families
from parser.extractors import (
callback_proto,
extract_callback,
extract_function,
extract_struct,
extract_enum,
extract_macro,
)
from parser.type_resolver import resolve_idl_types
def _compiler_system_includes() -> list[str]:
"""The C compiler's system header search path (builtin resource dir,
``/usr/local/include``, ``/usr/include/<triple>``, ``/usr/include``).
The pip ``libclang`` wheel ships the shared library but *not* a configured
system include path, so the amalgamation fails to find ``<stdbool.h>`` /
``<setjmp.h>`` / ``size_t`` and every ``bool`` / ``uint8`` / ``Datum`` field
degrades to ``int`` with ``get_offset`` returning ``-1``. ``provision-meos``
installs ``clang``, so ask the installed compiler for its own search list
(``clang -E -v``) rather than guessing paths; every entry there is added as
``-isystem`` so a real MEOS compile and this parse see the same headers.
"""
for cc in ("clang", "cc", "gcc"):
try:
out = subprocess.run(
[cc, "-E", "-x", "c", "-v", os.devnull],
capture_output=True, text=True, check=True).stderr
except Exception:
continue
dirs, capture = [], False
for line in out.splitlines():
if line.startswith("#include <...> search starts here:"):
capture = True
continue
if line.startswith("End of search list."):
break
if capture:
d = line.strip()
if d and os.path.isdir(d):
dirs.append(d)
if dirs:
return dirs
return []
def _clang_extra_args() -> list[str]:
"""Include paths clang needs to resolve MEOS types to their real C types.
Without a configured search path the MEOS headers' standard-library
includes (``<stdbool.h>`` / ``<stddef.h>`` / ``size_t``) fail, degrading
every struct field to ``int`` at offset ``-1`` — unusable for the FFI
bindings (``#[repr(C)]`` structs, cgo/cffi field access). Add the
compiler's own system search path, and the external family (H3 / GDAL /
PROJ) headers when present. ``size_t`` is force-included via
``-include stddef.h`` because ``meos.h`` uses it without an explicit
``#include``.
The catalog is derived from the *installed* MEOS headers (the generated
``meos_export.h`` written by ``make install``), which splice
``postgres_ext_defs.in.h`` in place of the source tree's
``#include <postgres.h>`` — so they are self-contained and no PostgreSQL
server headers are needed here.
"""
args: list[str] = []
system = _compiler_system_includes()
for d in system:
args.append(f"-isystem{d}")
if args:
args += ["-include", "stddef.h"]
# The external families install their headers in a directory of their own below a system
# directory, /usr/include for a package and /usr/local/include for a source build, which a
# MEOS header names bare (`#include <h3api.h>`): unseen, H3Index parses as the integer it
# stands for and loses its typedef
for base in dict.fromkeys(system + ["/usr/include"]):
for sub in ("h3", "gdal", "proj"):
d = os.path.join(base, sub)
if os.path.isdir(d):
args.append(f"-isystem{d}")
return args
def merge_meta(idl: dict, meta_path: Path) -> dict:
with open(meta_path) as f:
meta = json.load(f)
for fn in idl["functions"]:
if fn["name"] in meta.get("functions", {}):
fn.update(meta["functions"][fn["name"]])
for struct in idl["structs"]:
if struct["name"] in meta.get("types", {}):
struct.update(meta["types"][struct["name"]])
return idl
#: The directories of MobilityDB's header tree holding a stand-in for the header of a
#: library a build may lack. MobilityDB's build reads `geos-none/geos_c.h` only where GEOS
#: is absent, and installs it then in place of GEOS's own `geos_c.h`
#: (`meos/CMakeLists.txt`, under `if(NOT GEOS)`), so no installed header tree holds both.
#: What a stand-in declares is that library's API rather than MEOS's, and read beside the
#: library's own header, which `meos_internal_geo.h` includes, every type it declares is a
#: redefinition clang drops: its enums would enter the catalog nameless and valueless.
STAND_IN_DIRS = frozenset({"geos-none"})
def meos_headers(headers_dir: Path) -> list[Path]:
"""The headers of the tree the parse reads, in order: those an install of MEOS ships,
the tree's own less its stand-ins (#STAND_IN_DIRS) for a library's header. It is the one
list #build_entry_point includes and #parse_meos owns, so the two read the same tree."""
return sorted(h for h in headers_dir.glob("**/*.h")
if not STAND_IN_DIRS & set(h.relative_to(headers_dir).parts[:-1]))
def parse_meos(entry: Path, include_dir: Path,
extra_headers: tuple[Path, ...] = ()) -> dict:
index = clang.cindex.Index.create()
extra_dirs = sorted({h.parent.resolve() for h in extra_headers})
tu = index.parse(str(entry), args=[
"-x", "c",
"-std=c11",
f"-I{include_dir}",
*(f"-I{d}" for d in extra_dirs),
"-DMEOS",
# Define the MEOS ``UNUSED`` attribute macro on the command line so it is
# always in scope: the amalgamated entry point may parse a header that
# uses ``UNUSED`` (e.g. ``Datum dist UNUSED``) before temporal.h defines
# it, and an undefined ``UNUSED`` makes clang error on the declarator and
# silently drop the remaining parameters of that prototype.
"-DUNUSED=__attribute__((unused))",
# Define each optional family MobilityDB's ``ALL=ON`` build defines, so
# declarations guarded by ``#if <FAMILY>`` in the core headers (e.g.
# ``#if POINTCLOUD`` around ``meos_initialize_pointcloud`` in meos.h)
# enter the catalog — the family headers themselves are unguarded, but a
# handful of core-header declarations are gated. The list is read from
# MobilityDB's own ``if(ALL) foreach`` block rather than restated here,
# so a family added there is compiled in with no edit.
*(f"-D{family}=1" for family in all_families()),
] + _clang_extra_args(),
# Record ``#define`` macro definitions as cursors so the public
# object-like integer macros (WKB / WKT variant flags, ``MEOS_FLAG_*``)
# can be extracted into the catalog — an ``enum`` walk never sees them.
options=clang.cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
# Collect all .h files belonging to the project
own_files = {str(p.resolve()) for p in meos_headers(include_dir)}
own_files.update(str(h.resolve()) for h in extra_headers)
# First pass: build a mapping "anonymous struct location -> typedef name", and
# record every typedef of the unit, the C library's and an external family's
# (`h3api.h`) included, as the type it names one step down: the chain
# #normalize_canonical of parser/typerecover.py follows to state a scalar.
typedef_map: dict[str, str] = {}
typedefs: dict[str, str] = {}
for node in tu.cursor.walk_preorder():
if node.kind == clang.cindex.CursorKind.TYPEDEF_DECL:
typedefs.setdefault(node.spelling,
node.underlying_typedef_type.spelling)
loc = node.location.file
if not loc or str(Path(loc.name).resolve()) not in own_files:
continue
if node.kind == clang.cindex.CursorKind.TYPEDEF_DECL:
# A typedef names an anonymous record when the record IS the type it
# defines (`typedef struct {...} ways_record;`); a typedef whose type only
# contains it, a function pointer taking a `ways_record *`
# (`ways_fetch_fn`), names something else
canonical = node.underlying_typedef_type.get_canonical().spelling
m = re.fullmatch(r"(?:struct|union)\s+\(unnamed at ([^)]+)\)", canonical)
if m:
typedef_map[m.group(1)] = node.spelling
functions, structs, enums, macros, callbacks = [], [], [], [], []
for node in tu.cursor.walk_preorder():
loc = node.location.file
if not loc or str(Path(loc.name).resolve()) not in own_files:
continue # skip stdlib, system headers, etc.
if node.kind == clang.cindex.CursorKind.MACRO_DEFINITION:
macro = extract_macro(node)
if macro:
macros.append(macro)
continue
if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
# A `static` (or `static inline`) function a header defines has no
# external symbol: the library exports nothing a binding could call.
if node.storage_class == clang.cindex.StorageClass.STATIC:
continue
functions.append(extract_function(node))
elif node.kind == clang.cindex.CursorKind.STRUCT_DECL and node.spelling:
struct = extract_struct(node)
# Resolve anonymous struct names via typedef_map
m = re.search(r"\(unnamed at ([^)]+)\)", struct["name"])
if m:
typedef_name = typedef_map.get(m.group(1))
if typedef_name:
struct["name"] = typedef_name
else:
continue
structs.append((struct, node.is_definition()))
elif node.kind == clang.cindex.CursorKind.ENUM_DECL and node.spelling:
enums.append(extract_enum(node))
elif node.kind == clang.cindex.CursorKind.TYPEDEF_DECL:
proto = callback_proto(node)
if proto is not None:
callbacks.append(extract_callback(node, proto))
# Deduplicate by name (keep first occurrence)
def _dedup(items: list) -> list:
seen: set[str] = set()
result = []
for item in items:
if item["name"] not in seen:
seen.add(item["name"])
result.append(item)
return result
def _dedup_structs(items: list) -> list:
"""One record per structure, as #_dedup keeps one per name, read from its
definition when the unit holds one: a forward declaration (`struct varlena;`)
met before the definition has no fields, and a structure only ever declared
(opaque, `struct NumericData;`) keeps its declaration. The structure keeps the
place where the parse first meets it."""
order, chosen = [], {}
for struct, is_def in items:
name = struct["name"]
if name not in chosen:
order.append(name)
chosen[name] = (struct, is_def)
elif is_def and not chosen[name][1]:
chosen[name] = (struct, is_def)
return [chosen[name][0] for name in order]
functions = _dedup(functions)
structs = _dedup_structs(structs)
enums = _dedup(enums)
macros = _dedup(macros)
callbacks = _dedup(callbacks)
# `_typedefs` serves the type passes of run.py and leaves the catalog with them.
idl = {"functions": functions, "structs": structs, "enums": enums,
"macros": macros, "callbacks": callbacks, "_typedefs": typedefs}
# Resolve types if the mappings file exists
mappings_path = Path("./meta/type-mappings.json")
return resolve_idl_types(idl, mappings_path)
def build_entry_point(headers_dir: Path,
extra_headers: tuple[Path, ...] = ()) -> str:
lines = []
for h in meos_headers(headers_dir):
lines.append(f'#include "{h.resolve()}"')
for h in extra_headers:
lines.append(f'#include "{h.resolve()}"')
return "\n".join(lines)
def parse_all_headers(headers_dir: Path,
extra_headers: tuple[Path, ...] = ()) -> dict:
entry_src = build_entry_point(headers_dir, extra_headers)
with tempfile.NamedTemporaryFile(suffix=".h", mode="w", delete=False) as f:
f.write(entry_src)
tmp_path = f.name
try:
return parse_meos(Path(tmp_path), headers_dir, extra_headers)
finally:
os.unlink(tmp_path)