Debian Codegraph @

libphobos/scripts/tests_extractor.d

raw
1 #!/usr/bin/env dub
2 /++dub.sdl:
3 name "tests_extractor"
4 dependency "libdparse" version="~>0.24.0"
5 dflags "-fall-instantiations" platform="gdc"
6 +/
7 // Written in the D programming language.
8
9 import dparse.ast;
10 import std.algorithm;
11 import std.conv;
12 import std.exception;
13 import std.experimental.logger;
14 import std.file;
15 import std.path;
16 import std.range;
17 import std.stdio;
18
19 class TestVisitor : ASTVisitor
20 {
21 File outFile;
22 ubyte[] sourceCode;
23 string moduleName;
24
25 this(File outFile, ubyte[] sourceCode)
26 {
27 this.outFile = outFile;
28 this.sourceCode = sourceCode;
29 }
30
31 alias visit = ASTVisitor.visit;
32
33 override void visit(const Module m)
34 {
35 if (m.moduleDeclaration !is null)
36 {
37 moduleName = m.moduleDeclaration.moduleName.identifiers.map!(i => i.text).join(".");
38 }
39 else
40 {
41 // Fallback: convert the file path to its module path, e.g. std/uni.d -> std.uni
42 moduleName = outFile.name.replace(".d", "").replace(dirSeparator, ".").replace(".package", "");
43 }
44 m.accept(this);
45 }
46
47 override void visit(const Declaration decl)
48 {
49 if (decl.unittest_ !is null && decl.unittest_.comment !is null)
50 print(decl.unittest_, decl.attributes);
51
52 decl.accept(this);
53 }
54
55 override void visit(const ConditionalDeclaration decl)
56 {
57 bool skipTrue;
58
59 // Check if it's a version that should be skipped
60 if (auto vcd = decl.compileCondition.versionCondition)
61 {
62 if (vcd.token.text == "StdDdoc")
63 skipTrue = true;
64 }
65
66 // Search if/version block
67 if (!skipTrue)
68 {
69 foreach (d; decl.trueDeclarations)
70 visit(d);
71 }
72
73 // Search else block
74 foreach (d; decl.falseDeclarations)
75 visit(d);
76 }
77
78 private:
79
80 void print(const Unittest u, const Attribute[] attributes)
81 {
82 static immutable predefinedAttributes = ["nogc", "system", "nothrow", "safe", "trusted", "pure"];
83
84 // Write system attributes
85 foreach (attr; attributes)
86 {
87 // pure and nothrow
88 if (attr.attribute.type != 0)
89 {
90 import dparse.lexer : str;
91 const attrText = attr.attribute.type.str;
92 outFile.write(text(attrText, " "));
93 }
94
95 const atAttribute = attr.atAttribute;
96 if (atAttribute is null)
97 continue;
98
99 const atText = atAttribute.identifier.text;
100
101 // Ignore custom attributes (@myArg)
102 if (!predefinedAttributes.canFind(atText))
103 continue;
104
105 outFile.write(text("@", atText, " "));
106 }
107
108 // Write the unittest block
109 outFile.write("unittest\n{\n");
110 scope(exit) outFile.writeln("}\n");
111
112 // Add an import to the current module
113 outFile.writefln(" import %s;", moduleName);
114
115 // Write the content of the unittest block (but skip the first brace)
116 auto k = cast(immutable(char)[]) sourceCode[u.blockStatement.startLocation .. u.blockStatement.endLocation];
117 k.findSkip("{");
118 outFile.write(k);
119
120 // If the last line contains characters, we want to add an extra line
121 // for increased visual beauty
122 if (k[$ - 1] != '\n')
123 outFile.writeln;
124 }
125 }
126
127 bool parseFile(File inFile, File outFile)
128 {
129 import dparse.lexer;
130 import dparse.parser : parseModule;
131 import dparse.rollback_allocator : RollbackAllocator;
132 import std.array : uninitializedArray;
133
134 if (inFile.size == 0)
135 return false;
136
137 ubyte[] sourceCode = uninitializedArray!(ubyte[])(to!size_t(inFile.size));
138 inFile.rawRead(sourceCode);
139 LexerConfig config;
140 auto cache = StringCache(StringCache.defaultBucketCount);
141 auto tokens = getTokensForParser(sourceCode, config, &cache);
142
143 RollbackAllocator rba;
144 auto m = parseModule(tokens.array, inFile.name, &rba);
145 auto visitor = new TestVisitor(outFile, sourceCode);
146 visitor.visit(m);
147 return visitor.outFile.size != 0;
148 }
149
150 void parseFileDir(string inputDir, string fileName, string outputDir)
151 {
152 import std.path : buildPath, dirSeparator, buildNormalizedPath;
153
154 // File name without its parent directory, e.g. std/uni.d
155 string fileNameNormalized = (inputDir == "." ? fileName : fileName.replace(inputDir, ""));
156
157 // Remove leading dots or slashes
158 while (!fileNameNormalized.empty && fileNameNormalized[0] == '.')
159 fileNameNormalized = fileNameNormalized[1 .. $];
160 if (fileNameNormalized.length >= dirSeparator.length &&
161 fileNameNormalized[0 .. dirSeparator.length] == dirSeparator)
162 fileNameNormalized = fileNameNormalized[dirSeparator.length .. $];
163
164 // Convert the file path to a nice output file, e.g. std/uni.d -> std_uni.d
165 string outName = fileNameNormalized.replace(dirSeparator, "_");
166 auto outFile = buildPath(outputDir, outName);
167
168 // Removes the output file if nothing was written
169 if (!parseFile(File(fileName), File(outFile, "w")))
170 remove(outFile);
171 }
172
173 void main(string[] args)
174 {
175 import std.getopt;
176
177 string inputDir;
178 string outputDir = "./out";
179 string modulePrefix;
180
181 auto helpInfo = getopt(args, config.required,
182 "inputdir|i", "Folder to start the recursive search for unittest blocks (can be a single file)", &inputDir,
183 "outputdir|o", "Folder to which the extracted test files should be saved (stdout for a single file)", &outputDir,
184 );
185
186 if (helpInfo.helpWanted)
187 {
188 return defaultGetoptPrinter(`phobos_tests_extractor
189 Searches the input directory recursively for public unittest blocks, i.e.
190 unittest blocks that are annotated with three slashes (///).
191 The tests will be extracted as one file for each source file
192 to the output directory.
193 `, helpInfo.options);
194 }
195
196 inputDir = inputDir.asNormalizedPath.array;
197 outputDir= outputDir.asNormalizedPath.array;
198
199 if (!exists(outputDir))
200 mkdir(outputDir);
201
202 // If the module prefix is std -> add a dot for the next modules to follow
203 if (!modulePrefix.empty)
204 modulePrefix ~= '.';
205
206 DirEntry[] files;
207
208 if (inputDir.isFile)
209 {
210 stderr.writeln("ignoring ", inputDir);
211 return;
212 }
213 else
214 {
215 files = dirEntries(inputDir, SpanMode.depth).filter!(
216 a => a.name.endsWith(".d") && !a.name.canFind(".git")).array;
217 }
218
219 foreach (file; files)
220 {
221 stderr.writeln("parsing ", file);
222 parseFileDir(inputDir, file, outputDir);
223 }
224 }