1 /**
2 	Build settings definitions.
3 
4 	Copyright: © 2013-2014 rejectedsoftware e.K.
5 	License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
6 	Authors: Sönke Ludwig
7 */
8 module dub.compilers.buildsettings;
9 
10 import dub.internal.vibecompat.inet.path;
11 
12 import std.array : array;
13 import std.algorithm : filter, any;
14 import std.path : globMatch;
15 import std.typecons : BitFlags;
16 import std.algorithm.iteration : uniq;
17 import std.range : chain;
18 
19 /// BuildPlatform specific settings, like needed libraries or additional
20 /// include paths.
21 struct BuildSettings {
22 	import dub.internal.vibecompat.data.serialization : byName;
23 
24 	TargetType targetType;
25 	string targetPath;
26 	string targetName;
27 	string workingDirectory;
28 	string mainSourceFile;
29 	string[] dflags;
30 	string[] lflags;
31 	string[] libs;
32 	string[] linkerFiles;
33 	string[] sourceFiles;
34 	string[] copyFiles;
35 	string[] extraDependencyFiles;
36 	string[] versions;
37 	string[] debugVersions;
38 	string[] versionFilters;
39 	string[] debugVersionFilters;
40 	string[] importPaths;
41 	string[] stringImportPaths;
42 	string[] importFiles;
43 	string[] stringImportFiles;
44 	string[] preGenerateCommands;
45 	string[] postGenerateCommands;
46 	string[] preBuildCommands;
47 	string[] postBuildCommands;
48 	string[] preRunCommands;
49 	string[] postRunCommands;
50 	string[string] environments;
51 	string[string] buildEnvironments;
52 	string[string] runEnvironments;
53 	string[string] preGenerateEnvironments;
54 	string[string] postGenerateEnvironments;
55 	string[string] preBuildEnvironments;
56 	string[string] postBuildEnvironments;
57 	string[string] preRunEnvironments;
58 	string[string] postRunEnvironments;
59 	@byName BuildRequirements requirements;
60 	@byName BuildOptions options;
61 
62 	BuildSettings dup()
63 	const {
64 		import std.traits: FieldNameTuple;
65 		import std.algorithm: map;
66 		import std.typecons: tuple;
67 		import std.array: assocArray;
68 		BuildSettings ret;
69 		foreach (m; FieldNameTuple!BuildSettings) {
70 			static if (is(typeof(__traits(getMember, ret, m) = __traits(getMember, this, m).dup)))
71 				__traits(getMember, ret, m) = __traits(getMember, this, m).dup;
72 			else static if (is(typeof(add(__traits(getMember, ret, m), __traits(getMember, this, m)))))
73 				add(__traits(getMember, ret, m), __traits(getMember, this, m));
74 			else static if (is(typeof(__traits(getMember, ret, m) = __traits(getMember, this, m))))
75 				__traits(getMember, ret, m) = __traits(getMember, this, m);
76 			else static assert(0, "Cannot duplicate BuildSettings." ~ m);
77 		}
78 		assert(ret.targetType == targetType);
79 		assert(ret.targetName == targetName);
80 		assert(ret.importPaths == importPaths);
81 		return ret;
82 	}
83 
84 	void add(in BuildSettings bs)
85 	{
86 		addDFlags(bs.dflags);
87 		addLFlags(bs.lflags);
88 		addLibs(bs.libs);
89 		addLinkerFiles(bs.linkerFiles);
90 		addSourceFiles(bs.sourceFiles);
91 		addCopyFiles(bs.copyFiles);
92 		addExtraDependencyFiles(bs.extraDependencyFiles);
93 		addVersions(bs.versions);
94 		addDebugVersions(bs.debugVersions);
95 		addVersionFilters(bs.versionFilters);
96 		addDebugVersionFilters(bs.debugVersionFilters);
97 		addImportPaths(bs.importPaths);
98 		addStringImportPaths(bs.stringImportPaths);
99 		addImportFiles(bs.importFiles);
100 		addStringImportFiles(bs.stringImportFiles);
101 		addPreGenerateCommands(bs.preGenerateCommands);
102 		addPostGenerateCommands(bs.postGenerateCommands);
103 		addPreBuildCommands(bs.preBuildCommands);
104 		addPostBuildCommands(bs.postBuildCommands);
105 		addPreRunCommands(bs.preRunCommands);
106 		addPostRunCommands(bs.postRunCommands);
107 	}
108 
109 	void addDFlags(in string[] value...) { dflags = chain(dflags, value.dup).uniq.array; }
110 	void prependDFlags(in string[] value...) { prepend(dflags, value); }
111 	void removeDFlags(in string[] value...) { remove(dflags, value); }
112 	void addLFlags(in string[] value...) { lflags ~= value; }
113 	void addLibs(in string[] value...) { add(libs, value); }
114 	void addLinkerFiles(in string[] value...) { add(linkerFiles, value); }
115 	void addSourceFiles(in string[] value...) { add(sourceFiles, value); }
116 	void prependSourceFiles(in string[] value...) { prepend(sourceFiles, value); }
117 	void removeSourceFiles(in string[] value...) { removePaths(sourceFiles, value); }
118 	void addCopyFiles(in string[] value...) { add(copyFiles, value); }
119 	void addExtraDependencyFiles(in string[] value...) { add(extraDependencyFiles, value); }
120 	void addVersions(in string[] value...) { add(versions, value); }
121 	void addDebugVersions(in string[] value...) { add(debugVersions, value); }
122 	void addVersionFilters(in string[] value...) { add(versionFilters, value); }
123 	void addDebugVersionFilters(in string[] value...) { add(debugVersionFilters, value); }
124 	void addImportPaths(in string[] value...) { add(importPaths, value); }
125 	void addStringImportPaths(in string[] value...) { add(stringImportPaths, value); }
126 	void prependStringImportPaths(in string[] value...) { prepend(stringImportPaths, value); }
127 	void addImportFiles(in string[] value...) { add(importFiles, value); }
128 	void addStringImportFiles(in string[] value...) { addSI(stringImportFiles, value); }
129 	void addPreGenerateCommands(in string[] value...) { add(preGenerateCommands, value, false); }
130 	void addPostGenerateCommands(in string[] value...) { add(postGenerateCommands, value, false); }
131 	void addPreBuildCommands(in string[] value...) { add(preBuildCommands, value, false); }
132 	void addPostBuildCommands(in string[] value...) { add(postBuildCommands, value, false); }
133 	void addPreRunCommands(in string[] value...) { add(preRunCommands, value, false); }
134 	void addPostRunCommands(in string[] value...) { add(postRunCommands, value, false); }
135 	void addEnvironments(in string[string] value) { add(environments, value); }
136 	void updateEnvironments(in string[string] value) { update(environments, value); }
137 	void addBuildEnvironments(in string[string] value) { add(buildEnvironments, value); }
138 	void updateBuildEnvironments(in string[string] value) { update(buildEnvironments, value); }
139 	void addRunEnvironments(in string[string] value) { add(runEnvironments, value); }
140 	void updateRunEnvironments(in string[string] value) { update(runEnvironments, value); }
141 	void addPreGenerateEnvironments(in string[string] value) { add(preGenerateEnvironments, value); }
142 	void updatePreGenerateEnvironments(in string[string] value) { update(preGenerateEnvironments, value); }
143 	void addPostGenerateEnvironments(in string[string] value) { add(postGenerateEnvironments, value); }
144 	void updatePostGenerateEnvironments(in string[string] value) { update(postGenerateEnvironments, value); }
145 	void addPreBuildEnvironments(in string[string] value) { add(preBuildEnvironments, value); }
146 	void updatePreBuildEnvironments(in string[string] value) { update(preBuildEnvironments, value); }
147 	void addPostBuildEnvironments(in string[string] value) { add(postBuildEnvironments, value); }
148 	void updatePostBuildEnvironments(in string[string] value) { update(postBuildEnvironments, value); }
149 	void addPreRunEnvironments(in string[string] value) { add(preRunEnvironments, value); }
150 	void updatePreRunEnvironments(in string[string] value) { update(preRunEnvironments, value); }
151 	void addPostRunEnvironments(in string[string] value) { add(postRunEnvironments, value); }
152 	void updatePostRunEnvironments(in string[string] value) { update(postRunEnvironments, value); }
153 	void addRequirements(in BuildRequirement[] value...) { foreach (v; value) this.requirements |= v; }
154 	void addRequirements(in BuildRequirements value) { this.requirements |= value; }
155 	void addOptions(in BuildOption[] value...) { foreach (v; value) this.options |= v; }
156 	void addOptions(in BuildOptions value) { this.options |= value; }
157 	void removeOptions(in BuildOption[] value...) { foreach (v; value) this.options &= ~v; }
158 	void removeOptions(in BuildOptions value) { this.options &= ~value; }
159 
160 private:
161 	static auto filterDuplicates(T)(ref string[] arr, in T vals, bool noDuplicates = true)
162 	{
163 		return noDuplicates
164 			? vals.filter!(filtered => !arr.any!(item => item == filtered)).array
165 			: vals;
166 	}
167 
168 	// Append vals to arr without adding duplicates.
169 	static void add(ref string[] arr, in string[] vals, bool noDuplicates = true)
170 	{
171 		// vals might contain duplicates, add each val individually
172 		foreach (val; vals)
173 			arr ~= filterDuplicates(arr, [val], noDuplicates);
174 	}
175 	// Append vals to AA
176 	static void add(ref string[string] aa, in string[string] vals)
177 	{
178 		// vals might contain duplicated keys, add each val individually
179 		foreach (key, val; vals)
180 			if (key !in aa)
181 				aa[key] = val;
182 	}
183 	// Update vals to AA
184 	static void update(ref string[string] aa, in string[string] vals)
185 	{
186 		// If there are duplicate keys, they will be ignored and overwritten.
187 		foreach (key, val; vals)
188 			aa[key] = val;
189 	}
190 
191 	unittest
192 	{
193 		auto ary = ["-dip1000", "-vgc"];
194 		BuildSettings.add(ary, ["-dip1000", "-vgc"]);
195 		assert(ary == ["-dip1000", "-vgc"]);
196 		BuildSettings.add(ary, ["-dip1001", "-vgc"], false);
197 		assert(ary == ["-dip1000", "-vgc", "-dip1001", "-vgc"]);
198 		BuildSettings.add(ary, ["-dupflag", "-notdupflag", "-dupflag"]);
199 		assert(ary == ["-dip1000", "-vgc", "-dip1001", "-vgc", "-dupflag", "-notdupflag"]);
200 	}
201 
202 	// Prepend arr by vals without adding duplicates.
203 	static void prepend(ref string[] arr, in string[] vals, bool noDuplicates = true)
204 	{
205 		import std.range : retro;
206 		// vals might contain duplicates, add each val individually
207 		foreach (val; vals.retro)
208 			arr = filterDuplicates(arr, [val], noDuplicates) ~ arr;
209 	}
210 
211 	unittest
212 	{
213 		auto ary = ["-dip1000", "-vgc"];
214 		BuildSettings.prepend(ary, ["-dip1000", "-vgc"]);
215 		assert(ary == ["-dip1000", "-vgc"]);
216 		BuildSettings.prepend(ary, ["-dip1001", "-vgc"], false);
217 		assert(ary == ["-dip1001", "-vgc", "-dip1000", "-vgc"]);
218 		BuildSettings.prepend(ary, ["-dupflag", "-notdupflag", "-dupflag"]);
219 		assert(ary == ["-notdupflag", "-dupflag", "-dip1001", "-vgc", "-dip1000", "-vgc"]);
220 	}
221 
222 	// add string import files (avoids file name duplicates in addition to path duplicates)
223 	static void addSI(ref string[] arr, in string[] vals)
224 	{
225 		bool[string] existing;
226 		foreach (v; arr) existing[NativePath(v).head.name] = true;
227 		foreach (v; vals) {
228 			auto s = NativePath(v).head.name;
229 			if (s !in existing) {
230 				existing[s] = true;
231 				arr ~= v;
232 			}
233 		}
234 	}
235 
236 	unittest
237 	{
238 		auto ary = ["path/foo.txt"];
239 		BuildSettings.addSI(ary, ["path2/foo2.txt"]);
240 		assert(ary == ["path/foo.txt", "path2/foo2.txt"]);
241 		BuildSettings.addSI(ary, ["path2/foo.txt"]); // no duplicate basenames
242 		assert(ary == ["path/foo.txt", "path2/foo2.txt"]);
243 	}
244 
245 	static bool pathMatch(string path, string pattern)
246 	{
247 		import std.functional : memoize;
248 
249 		alias nativePath = memoize!((string stringPath) => NativePath(stringPath));
250 
251 		return nativePath(path) == nativePath(pattern) || globMatch(path, pattern);
252 	}
253 
254 	static void removeValuesFromArray(alias Match)(ref string[] arr, in string[] vals)
255 	{
256 		bool matches(string s)
257 		{
258 			return vals.any!(item => Match(s, item));
259 		}
260 		arr = arr.filter!(s => !matches(s)).array;
261 	}
262 
263 	static void removePaths(ref string[] arr, in string[] vals)
264 	{
265 		removeValuesFromArray!(pathMatch)(arr, vals);
266 	}
267 
268 	unittest
269 	{
270 		auto ary = ["path1", "root/path1", "root/path2", "root2/path1"];
271 		BuildSettings.removePaths(ary, ["path1"]);
272 		assert(ary == ["root/path1", "root/path2", "root2/path1"]);
273 		BuildSettings.removePaths(ary, ["*/path1"]);
274 		assert(ary == ["root/path2"]);
275 		BuildSettings.removePaths(ary, ["foo", "bar", "root/path2"]);
276 		assert(ary == []);
277 	}
278 
279 	static void remove(ref string[] arr, in string[] vals)
280 	{
281 		removeValuesFromArray!((a, b) => a == b)(arr, vals);
282 	}
283 
284 	unittest
285 	{
286 		import std..string : join;
287 
288 		auto ary = ["path1", "root/path1", "root/path2", "root2/path1"];
289 		BuildSettings.remove(ary, ["path1"]);
290 		assert(ary == ["root/path1", "root/path2", "root2/path1"]);
291 		BuildSettings.remove(ary, ["root/path*"]);
292 		assert(ary == ["root/path1", "root/path2", "root2/path1"]);
293 		BuildSettings.removePaths(ary, ["foo", "root/path2", "bar", "root2/path1"]);
294 		assert(ary == ["root/path1"]);
295 		BuildSettings.remove(ary, ["root/path1", "foo"]);
296 		assert(ary == []);
297 	}
298 }
299 
300 enum BuildSetting {
301 	dflags            = 1<<0,
302 	lflags            = 1<<1,
303 	libs              = 1<<2,
304 	sourceFiles       = 1<<3,
305 	copyFiles         = 1<<4,
306 	versions          = 1<<5,
307 	debugVersions     = 1<<6,
308 	importPaths       = 1<<7,
309 	stringImportPaths = 1<<8,
310 	options           = 1<<9,
311 	none = 0,
312 	commandLine = dflags|copyFiles,
313 	commandLineSeparate = commandLine|lflags,
314 	all = dflags|lflags|libs|sourceFiles|copyFiles|versions|debugVersions|importPaths|stringImportPaths|options,
315 	noOptions = all & ~options
316 }
317 
318 enum TargetType {
319 	autodetect,
320 	none,
321 	executable,
322 	library,
323 	sourceLibrary,
324 	dynamicLibrary,
325 	staticLibrary,
326 	object
327 }
328 
329 enum BuildRequirement {
330 	none = 0,                     /// No special requirements
331 	allowWarnings        = 1<<0,  /// Warnings do not abort compilation
332 	silenceWarnings      = 1<<1,  /// Don't show warnings
333 	disallowDeprecations = 1<<2,  /// Using deprecated features aborts compilation
334 	silenceDeprecations  = 1<<3,  /// Don't show deprecation warnings
335 	disallowInlining     = 1<<4,  /// Avoid function inlining, even in release builds
336 	disallowOptimization = 1<<5,  /// Avoid optimizations, even in release builds
337 	requireBoundsCheck   = 1<<6,  /// Always perform bounds checks
338 	requireContracts     = 1<<7,  /// Leave assertions and contracts enabled in release builds
339 	relaxProperties      = 1<<8,  /// DEPRECATED: Do not enforce strict property handling (-property)
340 	noDefaultFlags       = 1<<9,  /// Do not issue any of the default build flags (e.g. -debug, -w, -property etc.) - use only for development purposes
341 }
342 
343 	struct BuildRequirements {
344 		import dub.internal.vibecompat.data.serialization : ignore;
345 
346 		@ignore BitFlags!BuildRequirement values;
347 		this(BuildRequirement req) { values = req; }
348 
349 		alias values this;
350 	}
351 
352 enum BuildOption {
353 	none = 0,                     /// Use compiler defaults
354 	debugMode = 1<<0,             /// Compile in debug mode (enables contracts, -debug)
355 	releaseMode = 1<<1,           /// Compile in release mode (disables assertions and bounds checks, -release)
356 	coverage = 1<<2,              /// Enable code coverage analysis (-cov)
357 	debugInfo = 1<<3,             /// Enable symbolic debug information (-g)
358 	debugInfoC = 1<<4,            /// Enable symbolic debug information in C compatible form (-gc)
359 	alwaysStackFrame = 1<<5,      /// Always generate a stack frame (-gs)
360 	stackStomping = 1<<6,         /// Perform stack stomping (-gx)
361 	inline = 1<<7,                /// Perform function inlining (-inline)
362 	noBoundsCheck = 1<<8,         /// Disable all bounds checking (-noboundscheck)
363 	optimize = 1<<9,              /// Enable optimizations (-O)
364 	profile = 1<<10,              /// Emit profiling code (-profile)
365 	unittests = 1<<11,            /// Compile unit tests (-unittest)
366 	verbose = 1<<12,              /// Verbose compiler output (-v)
367 	ignoreUnknownPragmas = 1<<13, /// Ignores unknown pragmas during compilation (-ignore)
368 	syntaxOnly = 1<<14,           /// Don't generate object files (-o-)
369 	warnings = 1<<15,             /// Enable warnings (-wi)
370 	warningsAsErrors = 1<<16,     /// Treat warnings as errors (-w)
371 	ignoreDeprecations = 1<<17,   /// Do not warn about using deprecated features (-d)
372 	deprecationWarnings = 1<<18,  /// Warn about using deprecated features (-dw)
373 	deprecationErrors = 1<<19,    /// Stop compilation upon usage of deprecated features (-de)
374 	property = 1<<20,             /// DEPRECATED: Enforce property syntax (-property)
375 	profileGC = 1<<21,            /// Profile runtime allocations
376 	pic = 1<<22,                  /// Generate position independent code
377 	betterC = 1<<23,              /// Compile in betterC mode (-betterC)
378 	lowmem = 1<<24,               /// Compile in lowmem mode (-lowmem)
379 
380 	// for internal usage
381 	_docs = 1<<25,                // Write ddoc to docs
382 	_ddox = 1<<26                 // Compile docs.json
383 }
384 
385 	struct BuildOptions {
386 		import dub.internal.vibecompat.data.serialization : ignore;
387 
388 		@ignore BitFlags!BuildOption values;
389 		this(BuildOption opt) { values = opt; }
390 		this(BitFlags!BuildOption v) { values = v; }
391 
392 		alias values this;
393 	}
394 
395 /**
396 	All build options that will be inherited upwards in the dependency graph
397 
398 	Build options in this category fulfill one of the following properties:
399 	$(UL
400 		$(LI The option affects the semantics of the generated code)
401 		$(LI The option affects if a certain piece of code is valid or not)
402 		$(LI The option enabled meta information in dependent projects that are useful for the dependee (e.g. debug information))
403 	)
404 */
405 enum BuildOptions inheritedBuildOptions = BuildOption.debugMode | BuildOption.releaseMode
406 	| BuildOption.coverage | BuildOption.debugInfo | BuildOption.debugInfoC
407 	| BuildOption.alwaysStackFrame | BuildOption.stackStomping | BuildOption.inline
408 	| BuildOption.noBoundsCheck | BuildOption.profile | BuildOption.ignoreUnknownPragmas
409 	| BuildOption.syntaxOnly | BuildOption.warnings	| BuildOption.warningsAsErrors
410 	| BuildOption.ignoreDeprecations | BuildOption.deprecationWarnings
411 	| BuildOption.deprecationErrors | BuildOption.property | BuildOption.profileGC
412 	| BuildOption.pic;