]> git.lizzy.rs Git - rust.git/blob - src/etc/extract-tests.py
docs: Make supplemental tutorials testable
[rust.git] / src / etc / extract-tests.py
1 # Script for extracting compilable fragments from markdown
2 # documentation. See prep.js for a description of the format
3 # recognized by this tool. Expects a directory fragements/ to exist
4 # under the current directory, and writes the fragments in there as
5 # individual .rs files.
6
7 import sys, re;
8
9 if len(sys.argv) < 3:
10     print("Please provide an input filename")
11     sys.exit(1)
12
13 filename = sys.argv[1]
14 dest = sys.argv[2]
15 f = open(filename)
16 lines = f.readlines()
17 f.close()
18
19 cur = 0
20 line = ""
21 chapter = ""
22 chapter_n = 0
23
24 while cur < len(lines):
25     line = lines[cur]
26     cur += 1
27     chap = re.match("# (.*)", line);
28     if chap:
29         chapter = re.sub(r"\W", "_", chap.group(1)).lower()
30         chapter_n = 1
31     elif re.match("~~~", line):
32         # Parse the tags that open a code block in the pandoc format:
33         # ~~~ {.tag1 .tag2}
34         tags = re.findall("\.([\w-]*)", line)
35         block = ""
36         ignore = "notrust" in tags or "ignore" in tags
37         # Some tags used by the language ref that indicate not rust
38         ignore |= "ebnf" in tags
39         ignore |= "abnf" in tags
40         ignore |= "keyword" in tags
41         ignore |= "field" in tags
42         ignore |= "precedence" in tags
43         xfail = "xfail-test" in tags
44         while cur < len(lines):
45             line = lines[cur]
46             cur += 1
47             if re.match("~~~", line):
48                 break
49             else:
50                 # Lines beginning with '# ' are turned into valid code
51                 line = re.sub("^# ", "", line)
52                 # Allow elipses in code snippets
53                 line = re.sub("\.\.\.", "/*...*/", line)
54                 block += line
55         if not ignore:
56             if not re.search(r"\bfn main\b", block):
57                 block = "fn main() {\n" + block + "\n}\n"
58             if not re.search(r"\bextern mod std\b", block):
59                 block = "extern mod std;\n" + block;
60             if xfail:
61                 block = "// xfail-test\n" + block
62             filename = (dest + "/" + str(chapter)
63                         + "_" + str(chapter_n) + ".rs")
64             chapter_n += 1
65             f = open(filename, 'w')
66             f.write(block)
67             f.close()