File: amalgamate.py

package info (click to toggle)
simdutf 7.7.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,244 kB
  • sloc: cpp: 60,074; ansic: 14,226; python: 3,364; sh: 321; makefile: 12
file content (488 lines) | stat: -rwxr-xr-x 16,337 bytes parent folder | download
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#!/usr/bin/env python3
#
# Creates the amalgamated source files.

import argparse
import sys
import os.path
import subprocess
import os
import pathlib
import re
import shutil
import datetime

if sys.version_info[0] < 3:
    sys.stdout.write("Sorry, requires Python 3.x or better\n")
    sys.exit(1)


SCRIPTPATH = os.path.dirname(os.path.abspath(sys.argv[0]))
PROJECTPATH = os.path.dirname(SCRIPTPATH)


class Context:
    pass


context = Context()


def main():
    (args, enabled_features) = parse_args()

    print(f"SCRIPTPATH={SCRIPTPATH} PROJECTPATH={PROJECTPATH}")
    print("We are about to amalgamate all simdutf files into one source file.")
    print("See https://www.sqlite.org/amalgamation.html and https://en.wikipedia.org/wiki/Single_Compilation_Unit for rationale.")

    context.args             = args
    context.enabled_features = enabled_features
    context.zipname          = 'singleheader.zip'
    context.timestamp        = get_timestamp()
    if enabled_features != known_features:
        context.read_file = filter_features
    else:
        context.read_file = read_file

    print(f"timestamp is {context.timestamp}")

    create_files()
    if args.zip:
        create_zip()

    print("Done with all files generation.")
    print(f"Files have been written to directory: {context.args.output_dir}")

    if args.readme:
        print_instructions()


known_features = {
    'SIMDUTF_FEATURE_DETECT_ENCODING',
    'SIMDUTF_FEATURE_LATIN1',
    'SIMDUTF_FEATURE_ASCII',
    'SIMDUTF_FEATURE_BASE64',
    'SIMDUTF_FEATURE_UTF8',
    'SIMDUTF_FEATURE_UTF16',
    'SIMDUTF_FEATURE_UTF32',
}


def parse_args():
    p = argparse.ArgumentParser("SIMDUTF tool for amalgmation")
    p.add_argument("--source-dir",
                   default=os.path.join(PROJECTPATH, "src"),
                   metavar="SRC",
                   help="Source dir")
    p.add_argument("--include-dir",
                   default=os.path.join(PROJECTPATH, "include"),
                   metavar="INC",
                   help="Include dir")
    p.add_argument("--output-dir",
                   default=os.path.join(SCRIPTPATH),
                   metavar="DIR",
                   help="Output directory")
    p.add_argument("--no-zip",
                   default=True,
                   action='store_false',
                   dest='zip',
                   help="Do not create .zip file")
    p.add_argument("--no-readme",
                   default=True,
                   action='store_false',
                   dest='readme',
                   help="Do not show readme after creating files")
    p.add_argument("--with-utf8",
                   default=None,
                   action='store_true',
                   help="Include UTF-8 support")
    p.add_argument("--with-utf16",
                   default=None,
                   action='store_true',
                   help="Include UTF-16 support")
    p.add_argument("--with-utf32",
                   default=None,
                   action='store_true',
                   help="Include UTF-32 support")
    p.add_argument("--with-base64",
                   default=None,
                   action='store_true',
                   help="Include Base64 support")
    p.add_argument("--with-detect-enc",
                   default=None,
                   action='store_true',
                   help="Include encoding detection support")
    p.add_argument("--with-ascii",
                   default=None,
                   action='store_true',
                   help="Include ASCII support")
    p.add_argument("--with-latin1",
                   default=None,
                   action='store_true',
                   help="Include Latin1 support")
    p.add_argument("--debug-sources",
                   default=False,
                   action='store_true',
                   help="Include exact source location in amalgamated sources")

    args = p.parse_args()

    items = (
        ("AMALGAMATE_SOURCE_PATH", "source_dir"),
        ("AMALGAMATE_INCLUDE_PATH", "include_dir"),
        ("AMALGAMATE_OUTPUT_PATH", "output_dir"),
    )
    for var, attribute in items:
        if var in os.environ:
            val = os.environ[var]
            print(f"using env variable {var}={val}")
            setattr(args, attribute, val)

    enabled_features = set()
    if args.with_utf8:
        enabled_features.add('SIMDUTF_FEATURE_UTF8')
    if args.with_utf16:
        enabled_features.add('SIMDUTF_FEATURE_UTF16')
    if args.with_utf32:
        enabled_features.add('SIMDUTF_FEATURE_UTF32')
    if args.with_base64:
        enabled_features.add('SIMDUTF_FEATURE_BASE64')
    if args.with_detect_enc:
        enabled_features.add('SIMDUTF_FEATURE_DETECT_ENCODING')
    if args.with_ascii:
        enabled_features.add('SIMDUTF_FEATURE_ASCII')
    if args.with_latin1:
        enabled_features.add('SIMDUTF_FEATURE_LATIN1')

    if not enabled_features:
        enabled_features = set(known_features)

    return (args, enabled_features)


def doinclude(file, line):
    for directory in [context.args.include_dir, context.args.source_dir]:
        path = os.path.join(directory, file)
        if os.path.exists(path):
            # generic includes are included multiple times
            if re.match('.*generic/.*.h', file):
                dofile(directory, file)
            # begin/end_implementation are also included multiple times
            elif re.match('.*/begin.h', file):
                dofile(directory, file)
            elif re.match('.*/end.h', file):
                dofile(directory, file)
            elif file not in context.found_includes:
                context.found_includes.add(file)
                dofile(directory, file)
            else:
                pass

            return

    # If we don't recognize it, just emit the #include
    print(line, file=context.fid)


def dofile(prepath, filename):
    file = os.path.join(prepath, filename)
    fid  = context.fid
    RELFILE = os.path.relpath(file, PROJECTPATH)
    # Last lines are always ignored. Files should end by an empty lines.
    print(f"/* begin file {RELFILE} */", file=fid)
    includepattern = re.compile(r'^\s*#\s*include "(.*)"')
    redefines_simdutf_implementation = re.compile(r'^#define\s+SIMDUTF_IMPLEMENTATION\s+(.*)')
    undefines_simdutf_implementation = re.compile(r'^#undef\s+SIMDUTF_IMPLEMENTATION\s*$')
    uses_simdutf_implementation = re.compile('SIMDUTF_IMPLEMENTATION([^_a-zA-Z0-9]|$)')
    for line in context.read_file(file):
        s = includepattern.search(line)
        if s:
            includedfile = s.group(1)
            # include all from simdutf.cpp except simdutf.h
            if includedfile == "simdutf.h" and filename == "simdutf.cpp":
                print(line, file=fid)
                continue

            if includedfile.startswith('../'):
                includedfile = includedfile[2:]
            # we explicitly include simdutf headers, one time each (unless they are generic, in which case multiple times is fine)
            doinclude(includedfile, line)
        else:
            # does it contain a redefinition of SIMDUTF_IMPLEMENTATION ?
            s = redefines_simdutf_implementation.search(line)
            if s:
                context.current_implementation = s.group(1)
                print(f"// redefining SIMDUTF_IMPLEMENTATION to \"{context.current_implementation}\"\n// {line}", file=fid)
            elif undefines_simdutf_implementation.search(line):
                # Don't include #undef SIMDUTF_IMPLEMENTATION since we're handling it ourselves
                pass
            else:
                # copy the line, with SIMDUTF_IMPLEMENTATION replace to what it is currently defined to
                print(uses_simdutf_implementation.sub(context.current_implementation+"\\1", line), file=fid)

    print(f"/* end file {RELFILE} */", file=fid)


def get_timestamp():
    # Get the generation date from git, so the output is reproducible.
    # The %ci specifier gives the unambiguous ISO 8601 format, and
    # does not change with locale and timezone at time of generation.
    # Forcing it to be UTC is difficult, because it needs to be portable
    # between gnu date and busybox date.
    try:
        # avoid git going outside simdutf, which could happen when
        # unpacking a release tarball inside a subdirectory of an unrelated
        # git repository. that would lead to picking up the timestamp of the
        # unrelated git repository.
        simdroot = pathlib.Path(SCRIPTPATH).absolute().parent
        GIT_CEILING_DIRECTORIES = str(simdroot.parent)
        ret = subprocess.run(['git', '-C', SCRIPTPATH, 'show', '-s', '--format=%ci', 'HEAD'],
                             stdout=subprocess.PIPE,
                             env=dict(os.environ, GIT_CEILING_DIRECTORIES=GIT_CEILING_DIRECTORIES))

        if ret.returncode != 0:
            print(f"git called resulted in non-zero exit code {ret.returncode}")
            print("timestamp based on current time")
            return str(datetime.datetime.now())

        return ret.stdout.decode('utf-8').strip()
    except (UnicodeDecodeError, FileNotFoundError):
        print("UnicodeDecodeError or FileNotFoundError, timestamp based on current time")
        return str(datetime.datetime.now())


def create_files():
    outdir    = context.args.output_dir
    timestamp = context.timestamp

    os.makedirs(outdir, exist_ok=True)
    AMAL_H = os.path.join(outdir, "simdutf.h")
    AMAL_C = os.path.join(outdir, "simdutf.cpp")

    context.found_includes = set()
    context.current_implementation = ''

    # this list excludes the "src/generic headers"
    ALLCFILES = ["simdutf.cpp"]

    # order matters
    ALLCHEADERS = ["simdutf.h"]

    print(f"Creating {AMAL_H}")
    with open(AMAL_H, 'w') as f:
        context.fid = f
        print(f"/* auto-generated on {timestamp}. Do not edit! */", file=f)
        for header in ALLCHEADERS:
            doinclude(header, f"ERROR {header} not found")

    print(f"Creating {AMAL_C}")
    with open(AMAL_C, 'w') as f:
        context.fid = f
        print(f"/* auto-generated on {timestamp}. Do not edit! */", file=f)
        for cpp in ALLCFILES:
            doinclude(cpp, f"ERROR {cpp} not found")

    # copy the README and DEMOCPP
    if SCRIPTPATH != outdir:
        for name in ["amalgamation_demo.cpp", "README.md"]:
            path = os.path.join(SCRIPTPATH, name)
            print(f"Creating {outdir}/{name}")
            shutil.copy2(path, outdir)


def create_zip():
    import zipfile
    outdir = context.args.output_dir

    path = os.path.join(outdir, context.zipname)
    print(f"Creating {path}")
    with zipfile.ZipFile(path, 'w') as zf:
        for name in ["simdutf.cpp", "simdutf.h", "amalgamation_demo.cpp", "README.md"]:
            source = os.path.join(outdir, name)
            zf.write(source, name)


def print_instructions():
    README = os.path.join(context.args.output_dir, "README.md")
    print()
    print("Giving final instructions:")
    print()
    sys.stdout.write(open(README).read())
    print()


def read_file(file):
    with open(file, 'r') as f:
        for line in f:
            yield line.rstrip()


def filter_features(file):
    """
    Design:

    * Feature macros SIMDUTF_FEATURE_foo must not be nested.
    * All #endifs must contain a comment with the repeated condition.
    """
    current_features = None
    start_if_line = None
    enabled = True
    prev_line = ''

    root_header = file.endswith("/implementation.h")

    with open(file, 'r') as f:
        lines = [line.rstrip() for line in f.readlines()]
        for (lineno, line) in enumerate(lines, 1):
            if line is None:
                continue

            if root_header and line.startswith('#define SIMDUTF_FEATURE'):
                # '#define SIMDUTF_FEATURE_FOO 1'
                tmp = line.split()
                assert len(tmp) == 3, line
                assert tmp[2] == '1'
                flag = tmp[1]

                if flag in context.enabled_features:
                    yield line
                else:
                    yield f'#define {flag} 0'

            elif line.startswith('#if SIMDUTF_FEATURE'):
                if start_if_line is not None:
                    raise ValueError(f"{file}:{lineno}: feature block already opened at line {start_if_line}")

                prefix_len = len('#if ')
                if line.endswith('\\'):
                    nextline = lines[lineno]
                    lines[lineno] = None

                    expr = line[prefix_len:-1] + nextline
                else:
                    expr = line[prefix_len:]

                current_features = get_features(file, lineno, expr)
                start_if_line = lineno
                enabled = current_features.evaluate(context.enabled_features)
            elif line.startswith('#endif') and line.find('// SIMDUTF_FEATURE') > 0:
                if start_if_line is None:
                    raise ValueError(f"{file}:{lineno}: feature block not opened, orphan #endif found")

                _, _, expr = line.partition('//')
                if lineno < len(lines):
                    nextline = lines[lineno].lstrip()
                    if nextline.startswith('//') and nextline.find('SIMDUTF_FEATURE') > 0:
                        expr += nextline[len('//'):]
                        lines[lineno] = None

                features = get_features(file, lineno, expr)
                if str(features) != str(current_features):
                    raise ValueError(f"{file}:{lineno}: feature #endif condition different than opening #if at {start_if_line}")

                enabled = True
                start_if_line = None
                current_features = None
            elif enabled:
                if context.args.debug_sources and not prev_line.endswith('\\'):
                    RELFILE = os.path.relpath(file, PROJECTPATH)
                    yield f"// {RELFILE}:{lineno}"

                if line or (not line and prev_line):
                    yield line

                prev_line = line


def get_features(file, lineno, line):
    try:
        return parse_condition(line)
    except Exception as e:
        raise ValueError(f"{file}:{lineno}: {e}")


class Token:
    def __init__(self, name):
        if name not in known_features:
            raise ValueError(f"unknown feature name '{name}'")

        self.name = name

    def evaluate(self, enabled_features):
        return self.name in enabled_features

    def __str__(self):
        return self.name


class And:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def evaluate(self, enabled_features):
        a = self.a.evaluate(enabled_features)
        b = self.b.evaluate(enabled_features)

        return a and b

    def __str__(self):
        return '(%s && %s)' % (self.a, self.b)


class Or:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def evaluate(self, enabled_features):
        a = self.a.evaluate(enabled_features)
        b = self.b.evaluate(enabled_features)

        return a or b

    def __str__(self):
        return '(%s || %s)' % (self.a, self.b)


def parse_condition(s):
    tokens = [t for t in re.split('( |\\(|\\)|&&|\\|\\|)', s) if t not in ('', ' ')]
    stack  = []

    expr = None
    for token in tokens:
        if token == '&&':
            stack.append(token)
        elif token == '||':
            stack.append(token)
        elif token == '(':
            stack.append(expr)
            expr = None
        elif token == ')':
            prev = stack.pop()
            op   = stack.pop()
            if op == '&&':
                expr = And(prev, expr)
            elif op == '||':
                expr = Or(prev, expr)
            else:
                assert False, op
        else:
            e = Token(token)
            if expr is None:
                expr = e
            else:
                assert stack, "empty expression stack"
                op = stack.pop()
                if op == '&&':
                    expr = And(expr, e)
                elif op == '||':
                    expr = Or(expr, e)
                else:
                    assert False, op

    return expr


if __name__ == '__main__':
    main()