File size: 4,982 Bytes
93e3ef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Extract MathML test inputs from the MathCAT test suite (MIT licence).

Usage: mathcat_tests.py --work DIR --out DIR

Makes a shallow sparse clone of github.com/NSoiffer/MathCAT limited to
`tests/` and `LICENSE` (into `DIR/mathcat` if absent).  The tests are Rust
files whose MathML sits in string literals.  A small tokenizer reads the
literals (normal strings with escapes, raw strings `r#"..."#`), skipping
comments and character literals, and every `<math>` element inside a
literal value is taken as written after the literal is unescaped.
Distinct elements are kept; `count` is the number of occurrences.
"""
import argparse
import os
import re
import subprocess
from datetime import date

import corpus_common as cc

REPO = "https://github.com/NSoiffer/MathCAT"
ESC = {"n": "\n", "t": "\t", "r": "\r", "0": "\0", "\\": "\\", '"': '"', "'": "'"}


def rust_strings(src):
    """Yield (value, line) for each string literal of a Rust source text."""
    i, n, line = 0, len(src), 1
    while i < n:
        c = src[i]
        if c == "\n":
            line += 1
            i += 1
        elif src.startswith("//", i):
            j = src.find("\n", i)
            i = n if j < 0 else j
        elif src.startswith("/*", i):
            j = src.find("*/", i + 2)
            j = n if j < 0 else j + 2
            line += src.count("\n", i, j)
            i = j
        elif c == "r" and re.match(r'r#*"', src[i:i + 12]) and (i == 0 or not (src[i - 1].isalnum() or src[i - 1] == "_")):
            hashes = re.match(r"r(#*)\"", src[i:i + 12]).group(1)
            start = i + 2 + len(hashes)
            end = src.find('"' + hashes, start)
            if end < 0:
                return
            yield src[start:end], line
            line += src.count("\n", i, end)
            i = end + 1 + len(hashes)
        elif c == '"':
            j, out = i + 1, []
            while j < n and src[j] != '"':
                if src[j] == "\\":
                    nx = src[j + 1]
                    if nx == "\n":      # line continuation: skip whitespace
                        j += 2
                        while j < n and src[j] in " \t\r\n":
                            j += 1
                        continue
                    if nx == "u":
                        k = src.index("}", j)
                        out.append(chr(int(src[j + 3:k], 16)))
                        j = k + 1
                        continue
                    if nx == "x":
                        out.append(chr(int(src[j + 2:j + 4], 16)))
                        j += 4
                        continue
                    out.append(ESC.get(nx, nx))
                    j += 2
                else:
                    out.append(src[j])
                    j += 1
            yield "".join(out), line
            line += src.count("\n", i, j)
            i = j + 1
        elif c == "'":
            m = re.match(r"'(\\.[^']*|[^\\'])'", src[i:i + 12])
            i += m.end() if m else 1
        else:
            i += 1


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--work", required=True)
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    dest = os.path.join(a.work, "mathcat")
    if not os.path.isdir(dest):
        cc.sparse_clone(REPO, dest, ["/tests/", "/LICENSE"])
    commit = subprocess.run(["git", "-C", dest, "rev-parse", "HEAD"], capture_output=True,
                            text=True, check=True).stdout.strip()
    lurl = "%s/blob/%s/LICENSE" % (REPO, commit)
    w = cc.Writer("mathcat-tests")
    docs, today = [], date.today().isoformat()
    for root, _, files in sorted(os.walk(os.path.join(dest, "tests"))):
        for fn in sorted(files):
            if not fn.endswith(".rs"):
                continue
            path = os.path.relpath(os.path.join(root, fn), dest)
            src = open(os.path.join(root, fn), encoding="utf-8").read()
            n = 0
            for value, line in rust_strings(src):
                for s, e in cc.find_spans(value):
                    m = value[s:e]
                    n += 1
                    w.add(m, producer="MathCAT test suite", licence="MIT", licence_url=lurl,
                          origin="%s/blob/%s/%s#L%d" % (REPO, commit, path, line),
                          context=cc.context_of(m), markup=cc.classify_markup(m))
            if n:
                docs.append(dict(origin="%s/blob/%s/%s" % (REPO, commit, path), title=path,
                                 authors="Neil Soiffer and MathCAT contributors",
                                 licence="MIT", licence_url=lurl,
                                 access_url="%s/raw/%s/%s" % (REPO, commit, path),
                                 retrieved=today, formulas=n))
    w.stats["distinct_found"] = len(w)
    w.write(a.out, docs)
    cc.log("mathcat rows", len(w), "found", w.found, "files", len(docs))


if __name__ == "__main__":
    main()