1 /**
2 	Generator for VisualD project files
3 
4 	Copyright: © 2012-2013 Matthias Dondorff
5 	License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
6 	Authors: Matthias Dondorff
7 */
8 module dub.generators.visuald;
9 
10 import dub.compilers.compiler;
11 import dub.generators.generator;
12 import dub.internal.utils;
13 import dub.internal.vibecompat.core.file;
14 import dub.internal.vibecompat.core.log;
15 import dub.package_;
16 import dub.packagemanager;
17 import dub.project;
18 
19 import std.algorithm;
20 import std.array;
21 import std.conv;
22 import std.exception;
23 import std.format;
24 import std..string : format;
25 import std.uuid;
26 
27 
28 // Dubbing is developing dub...
29 //version = DUBBING;
30 
31 // TODO: handle pre/post build commands
32 
33 
34 class VisualDGenerator : ProjectGenerator {
35 	private {
36 		PackageManager m_pkgMgr;
37 		string[string] m_projectUuids;
38 	}
39 
40 	this(Project project)
41 	{
42 		super(project);
43 		m_pkgMgr = project.packageManager;
44 	}
45 
46 	override void generateTargets(GeneratorSettings settings, in TargetInfo[string] targets)
47 	{
48 		logDebug("About to generate projects for %s, with %s direct dependencies.", m_project.rootPackage.name, m_project.rootPackage.getAllDependencies().length);
49 		generateProjectFiles(settings, targets);
50 		generateSolutionFile(settings, targets);
51 	}
52 
53 	private {
54 		void generateSolutionFile(GeneratorSettings settings, in TargetInfo[string] targets)
55 		{
56 			auto ret = appender!(char[])();
57 			auto configs = m_project.getPackageConfigs(settings.platform, settings.config);
58 			auto some_uuid = generateUUID();
59 
60 			// Solution header
61 			ret.put("Microsoft Visual Studio Solution File, Format Version 11.00\n");
62 			ret.put("# Visual Studio 2010\n");
63 
64 			bool[string] visited;
65 			void generateSolutionEntry(string pack) {
66 				if (pack in visited) return;
67 				visited[pack] = true;
68 
69 				auto ti = targets[pack];
70 
71 				auto uuid = guid(pack);
72 				ret.formattedWrite("Project(\"%s\") = \"%s\", \"%s\", \"%s\"\n",
73 					some_uuid, pack, projFileName(pack), uuid);
74 
75 				if (ti.linkDependencies.length && ti.buildSettings.targetType != TargetType.staticLibrary) {
76 					ret.put("\tProjectSection(ProjectDependencies) = postProject\n");
77 					foreach (d; ti.linkDependencies)
78 						if (!isHeaderOnlyPackage(d, targets)) {
79 							// TODO: clarify what "uuid = uuid" should mean
80 							ret.formattedWrite("\t\t%s = %s\n", guid(d), guid(d));
81 						}
82 					ret.put("\tEndProjectSection\n");
83 				}
84 
85 				ret.put("EndProject\n");
86 
87 				foreach (d; ti.dependencies) generateSolutionEntry(d);
88 			}
89 
90 			auto mainpack = m_project.rootPackage.name;
91 
92 			generateSolutionEntry(mainpack);
93 
94 			// Global section contains configurations
95 			ret.put("Global\n");
96 			ret.put("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n");
97 			ret.formattedWrite("\t\t%s|%s = %s|%s\n",
98 				settings.buildType,
99 				settings.platform.architecture[0].vsArchitecture,
100 				settings.buildType,
101 				settings.platform.architecture[0].vsArchitecture);
102 			ret.put("\tEndGlobalSection\n");
103 			ret.put("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n");
104 
105 			const string[] sub = ["ActiveCfg", "Build.0"];
106 			const string[] conf = [settings.buildType~"|"~settings.platform.architecture[0].vsArchitecture];
107 			foreach (t; targets.byKey)
108 				foreach (c; conf)
109 					foreach (s; sub)
110 						formattedWrite(ret, "\t\t%s.%s.%s = %s\n", guid(t), c, s, c);
111 
112 			// TODO: for all dependencies
113 			ret.put("\tEndGlobalSection\n");
114 
115 			ret.put("\tGlobalSection(SolutionProperties) = preSolution\n");
116 			ret.put("\t\tHideSolutionNode = FALSE\n");
117 			ret.put("\tEndGlobalSection\n");
118 			ret.put("EndGlobal\n");
119 
120 			// Writing solution file
121 			logDebug("About to write to .sln file with %s bytes", to!string(ret.data.length));
122 			auto sln = openFile(solutionFileName(), FileMode.createTrunc);
123 			scope(exit) sln.close();
124 			sln.put(ret.data);
125 			sln.flush();
126 
127 			logInfo("Solution '%s' generated.", solutionFileName());
128 		}
129 
130 
131 		void generateProjectFiles(GeneratorSettings settings, in TargetInfo[string] targets)
132 		{
133 			bool[string] visited;
134 			void performRec(string name) {
135 				if (name in visited) return;
136 				visited[name] = true;
137 				generateProjectFile(name, settings, targets);
138 				foreach (d; targets[name].dependencies)
139 					performRec(d);
140 			}
141 
142 			performRec(m_project.rootPackage.name);
143 		}
144 
145 		bool isHeaderOnlyPackage(string pack, in TargetInfo[string] targets)
146 		const {
147 			auto buildsettings = targets[pack].buildSettings;
148 			if (!buildsettings.sourceFiles.any!(f => f.endsWith(".d"))())
149 				return true;
150 			return false;
151 		}
152 
153 		void generateProjectFile(string packname, GeneratorSettings settings, in TargetInfo[string] targets)
154 		{
155 			import dub.compilers.utils : isLinkerFile;
156 
157 			auto ret = appender!(char[])();
158 
159 			auto root_package_path = m_project.rootPackage.path;
160 			auto basepath = NativePath(".dub/");
161 			if (!isWritableDir(basepath, true))
162 				throw new Exception(".dub is not writeable");
163 			ret.put("<DProject>\n");
164 			ret.formattedWrite("  <ProjectGuid>%s</ProjectGuid>\n", guid(packname));
165 
166 			// Several configurations (debug, release, unittest)
167 			generateProjectConfiguration(ret, packname, settings.buildType, settings, targets);
168 			//generateProjectConfiguration(ret, packname, "release", settings, targets);
169 			//generateProjectConfiguration(ret, packname, "unittest", settings, targets);
170 
171 			// Add all files
172 			auto files = targets[packname].buildSettings;
173 			SourceFile[string] sourceFiles;
174 			void addSourceFile(NativePath file_path, NativePath structure_path, SourceFile.Action action)
175 			{
176 				auto key = file_path.toString();
177 				auto sf = sourceFiles.get(key, SourceFile.init);
178 				sf.filePath = file_path;
179 				if (sf.action == SourceFile.Action.none) {
180 					sf.action = action;
181 					sf.structurePath = structure_path;
182 				}
183 				sourceFiles[key] = sf;
184 			}
185 
186 			void addFile(string s, SourceFile.Action action) {
187 				auto sp = NativePath(s);
188 				assert(sp.absolute, format("Source path in %s expected to be absolute: %s", packname, s));
189 				//if( !sp.absolute ) sp = pack.path ~ sp;
190 				addSourceFile(sp.relativeTo(getWorkingDirectory() ~ basepath), determineStructurePath(sp, targets[packname]), action);
191 			}
192 
193 			foreach (p; targets[packname].packages)
194 				if (!p.recipePath.empty)
195 					addFile(p.recipePath.toNativeString(), SourceFile.Action.none);
196 
197 			if (files.targetType == TargetType.staticLibrary)
198 				foreach(s; files.sourceFiles.filter!(s => !isLinkerFile(settings.platform, s))) addFile(s, SourceFile.Action.build);
199 			else
200 				foreach(s; files.sourceFiles.filter!(s => !s.endsWith(".lib"))) addFile(s, SourceFile.Action.build);
201 
202 			foreach(s; files.importFiles) addFile(s, SourceFile.Action.none);
203 			foreach(s; files.stringImportFiles) addFile(s, SourceFile.Action.none);
204 			findFilesMatchingGlobs(root_package_path, files.copyFiles, s => addFile(s, SourceFile.Action.copy));
205 			findFilesMatchingGlobs(root_package_path, files.extraDependencyFiles, s => addFile(s, SourceFile.Action.none));
206 
207 			// Create folders and files
208 			ret.formattedWrite("  <Folder name=\"%s\">", getPackageFileName(packname));
209 			typeof(NativePath.init.head)[] lastFolder;
210 			foreach(source; sortedSources(sourceFiles.values)) {
211 				logDebug("source looking at %s", source.structurePath);
212 				auto cur = source.structurePath.parentPath.bySegment.array;
213 				if(lastFolder != cur) {
214 					size_t same = 0;
215 					foreach(idx; 0..min(lastFolder.length, cur.length))
216 						if(lastFolder[idx] != cur[idx]) break;
217 						else same = idx+1;
218 
219 					const decrease = lastFolder.length - min(lastFolder.length, same);
220 					const increase = cur.length - min(cur.length, same);
221 
222 					foreach(unused; 0..decrease)
223 						ret.put("\n    </Folder>");
224 					foreach(idx; 0..increase)
225 						ret.formattedWrite("\n    <Folder name=\"%s\">", cur[same + idx].name);
226 					lastFolder = cur;
227 				}
228 				final switch (source.action) with (SourceFile.Action)
229 				{
230 					case none:
231 						ret.formattedWrite("\n      <File path=\"%s\" tool=\"None\" />", source.filePath.toNativeString());
232 						break;
233 					case build:
234 						ret.formattedWrite("\n      <File path=\"%s\" />", source.filePath.toNativeString());
235 						break;
236 					case copy:
237 						ret.formattedWrite("\n      <File customcmd=\"copy /Y $(InputPath) $(TargetDir)\" path=\"%s\" tool=\"Custom\" />", source.filePath.toNativeString());
238 						break;
239 				}
240 			}
241 			// Finalize all open folders
242 			foreach(unused; 0..lastFolder.length)
243 				ret.put("\n    </Folder>");
244 			ret.put("\n  </Folder>\n</DProject>");
245 
246 			logDebug("About to write to '%s.visualdproj' file %s bytes", getPackageFileName(packname), ret.data.length);
247 			auto proj = openFile(projFileName(packname), FileMode.createTrunc);
248 			scope(exit) proj.close();
249 			proj.put(ret.data);
250 			proj.flush();
251 		}
252 
253 		void generateProjectConfiguration(Appender!(char[]) ret, string pack, string type, GeneratorSettings settings, in TargetInfo[string] targets)
254 		{
255 			auto buildsettings = targets[pack].buildSettings.dup;
256 			auto basepath = NativePath(".dub/");
257 
258 			string[] getSettings(string setting)(){ return __traits(getMember, buildsettings, setting); }
259 			string[] getPathSettings(string setting)()
260 			{
261 				auto settings = getSettings!setting();
262 				auto ret = new string[settings.length];
263 				foreach (i; 0 .. settings.length) {
264 					// \" is interpreted as an escaped " by cmd.exe, so we need to avoid that
265 					auto p = NativePath(settings[i]).relativeTo(getWorkingDirectory() ~ basepath);
266 					p.endsWithSlash = false;
267 					ret[i] = '"' ~ p.toNativeString() ~ '"';
268 				}
269 				return ret;
270 			}
271 
272 			if (buildsettings.targetType == TargetType.none)
273 				return;
274 
275 			foreach(architecture; settings.platform.architecture) {
276 				auto arch = architecture.vsArchitecture;
277 				ret.formattedWrite("  <Config name=\"%s\" platform=\"%s\">\n", to!string(type), arch);
278 
279 				// debug and optimize setting
280 				ret.formattedWrite("    <symdebug>%s</symdebug>\n", buildsettings.options & BuildOption.debugInfo ? "1" : "0");
281 				ret.formattedWrite("    <optimize>%s</optimize>\n", buildsettings.options & BuildOption.optimize ? "1" : "0");
282 				ret.formattedWrite("    <useInline>%s</useInline>\n", buildsettings.options & BuildOption.inline ? "1" : "0");
283 				ret.formattedWrite("    <release>%s</release>\n", buildsettings.options & BuildOption.releaseMode ? "1" : "0");
284 
285 				// Lib or exe?
286 				enum
287 				{
288 					Executable = 0,
289 					StaticLib = 1,
290 					DynamicLib = 2
291 				}
292 
293 				int output_type = StaticLib; // library
294 				string output_ext = "lib";
295 				if (buildsettings.targetType == TargetType.executable)
296 				{
297 					output_type = Executable;
298 					output_ext = "exe";
299 				}
300 				else if (buildsettings.targetType == TargetType.dynamicLibrary)
301 				{
302 					output_type = DynamicLib;
303 					output_ext = "dll";
304 				}
305 				auto bin_path = pack == m_project.rootPackage.name ? NativePath(buildsettings.targetPath) : NativePath("lib/");
306 				bin_path.endsWithSlash = true;
307 				ret.formattedWrite("    <lib>%s</lib>\n", output_type);
308 				ret.formattedWrite("    <exefile>%s%s.%s</exefile>\n", bin_path.toNativeString(), buildsettings.targetName, output_ext);
309 
310 				// include paths and string imports
311 				string imports = join(getPathSettings!"importPaths"(), " ");
312 				string stringImports = join(getPathSettings!"stringImportPaths"(), " ");
313 				ret.formattedWrite("    <imppath>%s</imppath>\n", imports);
314 				ret.formattedWrite("    <fileImppath>%s</fileImppath>\n", stringImports);
315 
316 				ret.formattedWrite("    <program>%s</program>\n", "$(DMDInstallDir)windows\\bin\\dmd.exe"); // FIXME: use the actually selected compiler!
317 				ret.formattedWrite("    <additionalOptions>%s</additionalOptions>\n", getSettings!"dflags"().join(" "));
318 
319 				// Add version identifiers
320 				string versions = join(getSettings!"versions"(), " ");
321 				ret.formattedWrite("    <versionids>%s</versionids>\n", versions);
322 
323 				// Add libraries, system libs need to be suffixed by ".lib".
324 				string linkLibs = join(map!(a => a~".lib")(getSettings!"libs"()), " ");
325 				string addLinkFiles = join(getSettings!"sourceFiles"().filter!(s => s.endsWith(".lib"))(), " ");
326 				if (arch == "x86") addLinkFiles ~= " phobos.lib";
327 				if (output_type != StaticLib) ret.formattedWrite("    <libfiles>%s %s</libfiles>\n", linkLibs, addLinkFiles);
328 
329 				// Unittests
330 				ret.formattedWrite("    <useUnitTests>%s</useUnitTests>\n", buildsettings.options & BuildOption.unittests ? "1" : "0");
331 
332 				// Better C
333 				ret.formattedWrite("    <betterC>%s</betterC>\n", buildsettings.options & BuildOption.betterC ? "1" : "0");
334 
335 				// compute directory for intermediate files (need dummy/ because of how -op determines the resulting path)
336 				size_t ndummy = 0;
337 				foreach (f; buildsettings.sourceFiles) {
338 					auto rpath = NativePath(f).relativeTo(getWorkingDirectory() ~ basepath);
339 					size_t nd = 0;
340 					foreach (s; rpath.bySegment)
341 						if (s == "..")
342 							nd++;
343 					if (nd > ndummy) ndummy = nd;
344 				}
345 				string intersubdir = replicate("dummy/", ndummy) ~ getPackageFileName(pack);
346 
347 				ret.put("    <obj>0</obj>\n");
348 				ret.put("    <link>0</link>\n");
349 				ret.put("    <subsystem>0</subsystem>\n");
350 				ret.put("    <multiobj>0</multiobj>\n");
351 				int singlefilemode;
352 				final switch (settings.buildMode) with (BuildMode) {
353 					case separate: singlefilemode = 2; break;
354 					case allAtOnce: singlefilemode = 0; break;
355 					case singleFile: singlefilemode = 1; break;
356 					//case compileOnly: singlefilemode = 3; break;
357 				}
358 				ret.formattedWrite("    <singleFileCompilation>%s</singleFileCompilation>\n", singlefilemode);
359 				ret.formattedWrite("    <mscoff>%s</mscoff>", buildsettings.dflags.canFind("-m32mscoff") ? "1" : "0");
360 				ret.put("    <oneobj>0</oneobj>\n");
361 				ret.put("    <trace>0</trace>\n");
362 				ret.put("    <quiet>0</quiet>\n");
363 				ret.formattedWrite("    <verbose>%s</verbose>\n", buildsettings.options & BuildOption.verbose ? "1" : "0");
364 				ret.put("    <vtls>0</vtls>\n");
365 				ret.put("    <cpu>0</cpu>\n");
366 				ret.formattedWrite("    <isX86_64>%s</isX86_64>\n", arch == "x64" ? 1 : 0);
367 				ret.put("    <isLinux>0</isLinux>\n");
368 				ret.put("    <isOSX>0</isOSX>\n");
369 				ret.put("    <isWindows>0</isWindows>\n");
370 				ret.put("    <isFreeBSD>0</isFreeBSD>\n");
371 				ret.put("    <isSolaris>0</isSolaris>\n");
372 				ret.put("    <isDragonFlyBSD>0</isDragonFlyBSD>\n");
373 				ret.put("    <scheduler>0</scheduler>\n");
374 				ret.put("    <useDeprecated>0</useDeprecated>\n");
375 				ret.put("    <useAssert>0</useAssert>\n");
376 				ret.put("    <useInvariants>0</useInvariants>\n");
377 				ret.put("    <useIn>0</useIn>\n");
378 				ret.put("    <useOut>0</useOut>\n");
379 				ret.put("    <useArrayBounds>0</useArrayBounds>\n");
380 				ret.formattedWrite("    <noboundscheck>%s</noboundscheck>\n", buildsettings.options & BuildOption.noBoundsCheck ? "1" : "0");
381 				ret.put("    <useSwitchError>0</useSwitchError>\n");
382 				ret.put("    <preservePaths>1</preservePaths>\n");
383 				ret.formattedWrite("    <warnings>%s</warnings>\n", buildsettings.options & BuildOption.warningsAsErrors ? "1" : "0");
384 				ret.formattedWrite("    <infowarnings>%s</infowarnings>\n", buildsettings.options & BuildOption.warnings ? "1" : "0");
385 				ret.formattedWrite("    <checkProperty>%s</checkProperty>\n", buildsettings.options & BuildOption.property ? "1" : "0");
386 				ret.formattedWrite("    <genStackFrame>%s</genStackFrame>\n", buildsettings.options & BuildOption.alwaysStackFrame ? "1" : "0");
387 				ret.put("    <pic>0</pic>\n");
388 				ret.formattedWrite("    <cov>%s</cov>\n", buildsettings.options & BuildOption.coverage ? "1" : "0");
389 				ret.put("    <nofloat>0</nofloat>\n");
390 				ret.put("    <Dversion>2</Dversion>\n");
391 				ret.formattedWrite("    <ignoreUnsupportedPragmas>%s</ignoreUnsupportedPragmas>\n", buildsettings.options & BuildOption.ignoreUnknownPragmas ? "1" : "0");
392 				ret.formattedWrite("    <compiler>%s</compiler>\n", settings.compiler.name == "ldc" ? 2 : settings.compiler.name == "gdc" ? 1 : 0);
393 				ret.formattedWrite("    <otherDMD>0</otherDMD>\n");
394 				ret.formattedWrite("    <outdir>%s</outdir>\n", bin_path.toNativeString());
395 				ret.formattedWrite("    <objdir>obj/%s/%s</objdir>\n", to!string(type), intersubdir);
396 				ret.put("    <objname />\n");
397 				ret.put("    <libname />\n");
398 				ret.put("    <doDocComments>0</doDocComments>\n");
399 				ret.put("    <docdir />\n");
400 				ret.put("    <docname />\n");
401 				ret.put("    <modules_ddoc />\n");
402 				ret.put("    <ddocfiles />\n");
403 				ret.put("    <doHdrGeneration>0</doHdrGeneration>\n");
404 				ret.put("    <hdrdir />\n");
405 				ret.put("    <hdrname />\n");
406 				ret.put("    <doXGeneration>1</doXGeneration>\n");
407 				ret.put("    <xfilename>$(IntDir)\\$(TargetName).json</xfilename>\n");
408 				ret.put("    <debuglevel>0</debuglevel>\n");
409 				ret.put("    <versionlevel>0</versionlevel>\n");
410 				ret.put("    <debugids />\n");
411 				ret.put("    <dump_source>0</dump_source>\n");
412 				ret.put("    <mapverbosity>0</mapverbosity>\n");
413 				ret.put("    <createImplib>0</createImplib>\n");
414 				ret.put("    <defaultlibname />\n");
415 				ret.put("    <debuglibname />\n");
416 				ret.put("    <moduleDepsFile />\n");
417 				ret.put("    <run>0</run>\n");
418 				ret.put("    <runargs />\n");
419 				ret.put("    <runCv2pdb>1</runCv2pdb>\n");
420 				ret.put("    <pathCv2pdb>$(VisualDInstallDir)cv2pdb\\cv2pdb.exe</pathCv2pdb>\n");
421 				ret.put("    <cv2pdbPre2043>0</cv2pdbPre2043>\n");
422 				ret.put("    <cv2pdbNoDemangle>0</cv2pdbNoDemangle>\n");
423 				ret.put("    <cv2pdbEnumType>0</cv2pdbEnumType>\n");
424 				ret.put("    <cv2pdbOptions />\n");
425 				ret.put("    <objfiles />\n");
426 				ret.put("    <linkswitches />\n");
427 				ret.put("    <libpaths />\n");
428 				ret.put("    <deffile />\n");
429 				ret.put("    <resfile />\n");
430 				auto wdir = NativePath(buildsettings.workingDirectory);
431 				if (!wdir.absolute) wdir = m_project.rootPackage.path ~ wdir;
432 				ret.formattedWrite("    <debugworkingdir>%s</debugworkingdir>\n",
433 					wdir.relativeTo(getWorkingDirectory() ~ basepath).toNativeString());
434 				ret.put("    <preBuildCommand />\n");
435 				ret.put("    <postBuildCommand />\n");
436 				ret.put("    <filesToClean>*.obj;*.cmd;*.build;*.dep</filesToClean>\n");
437 				ret.put("  </Config>\n");
438 			} // foreach(architecture)
439 		}
440 
441 		void performOnDependencies(const Package main, string[string] configs, void delegate(const Package pack) op)
442 		{
443 			foreach (p; m_project.getTopologicalPackageList(false, main, configs)) {
444 				if (p is main) continue;
445 				op(p);
446 			}
447 		}
448 
449 		string generateUUID() const {
450 			import std..string;
451 			return "{" ~ toUpper(randomUUID().toString()) ~ "}";
452 		}
453 
454 		string guid(string projectName) {
455 			if(projectName !in m_projectUuids)
456 				m_projectUuids[projectName] = generateUUID();
457 			return m_projectUuids[projectName];
458 		}
459 
460 		auto solutionFileName() const {
461 			version(DUBBING) return getPackageFileName(m_project.rootPackage) ~ ".dubbed.sln";
462 			else return getPackageFileName(m_project.rootPackage.name) ~ ".sln";
463 		}
464 
465 		NativePath projFileName(string pack) const {
466 			auto basepath = NativePath(".dub/");
467 			version(DUBBING) return basepath ~ (getPackageFileName(pack) ~ ".dubbed.visualdproj");
468 			else return basepath ~ (getPackageFileName(pack) ~ ".visualdproj");
469 		}
470 	}
471 
472 	// TODO: nice folders
473 	private struct SourceFile {
474 		NativePath structurePath;
475 		NativePath filePath;
476 		enum Action { none, build, copy };
477 		Action action = Action.none;
478 
479 		size_t toHash() const nothrow @trusted { return structurePath.toHash() ^ filePath.toHash() ^ (action * 0x1f3e7b2c); }
480 		int opCmp(ref const SourceFile rhs) const { return sortOrder(this, rhs); }
481 		// "a < b" for folder structures (deepest folder first, else lexical)
482 		private final static int sortOrder(ref const SourceFile a, ref const SourceFile b) {
483 			assert(!a.structurePath.empty);
484 			assert(!b.structurePath.empty);
485 			static if (is(typeof(a.structurePath.nodes))) { // vibe.d < 0.8.2
486 				auto as = a.structurePath.nodes;
487 				auto bs = b.structurePath.nodes;
488 			} else {
489 				auto as = a.structurePath.bySegment.array;
490 				auto bs = b.structurePath.bySegment.array;
491 			}
492 
493 			// Check for different folders, compare folders only (omit last one).
494 			for(uint idx=0; idx<min(as.length-1, bs.length-1); ++idx)
495 				if(as[idx] != bs[idx])
496 					return as[idx].name.cmp(bs[idx].name);
497 
498 			if(as.length != bs.length) {
499 				// If length differ, the longer one is "smaller", that is more
500 				// specialized and will be put out first.
501 				return as.length > bs.length? -1 : 1;
502 			}
503 			else {
504 				// Both paths indicate files in the same directory, use lexical
505 				// ordering for those.
506 				return as[$-1].name.cmp(bs[$-1].name);
507 			}
508 		}
509 	}
510 
511 	private auto sortedSources(SourceFile[] sources) {
512 		return sort(sources);
513 	}
514 
515 	unittest {
516 		SourceFile[] sfs = [
517 			{ NativePath("b/file.d"), NativePath("") },
518 			{ NativePath("b/b/fileA.d"), NativePath("") },
519 			{ NativePath("a/file.d"), NativePath("") },
520 			{ NativePath("b/b/fileB.d"), NativePath("") },
521 			{ NativePath("b/b/b/fileA.d"), NativePath("") },
522 			{ NativePath("b/c/fileA.d"), NativePath("") },
523 		];
524 		auto sorted = sort(sfs);
525 		SourceFile[] sortedSfs;
526 		foreach(sr; sorted)
527 			sortedSfs ~= sr;
528 		assert(sortedSfs[0].structurePath == NativePath("a/file.d"), "1");
529 		assert(sortedSfs[1].structurePath == NativePath("b/b/b/fileA.d"), "2");
530 		assert(sortedSfs[2].structurePath == NativePath("b/b/fileA.d"), "3");
531 		assert(sortedSfs[3].structurePath == NativePath("b/b/fileB.d"), "4");
532 		assert(sortedSfs[4].structurePath == NativePath("b/c/fileA.d"), "5");
533 		assert(sortedSfs[5].structurePath == NativePath("b/file.d"), "6");
534 	}
535 }
536 
537 private NativePath determineStructurePath(NativePath file_path, in ProjectGenerator.TargetInfo target)
538 {
539 	foreach (p; target.packages) {
540 		if (file_path.startsWith(p.path))
541 			return NativePath(getPackageFileName(p.name)) ~ file_path.relativeTo(p.path);
542 	}
543 	return NativePath("misc/") ~ file_path.head;
544 }
545 
546 private string getPackageFileName(string pack)
547 {
548 	return pack.replace(":", "_");
549 }
550 
551 private @property string vsArchitecture(string architecture)
552 {
553 	switch(architecture) {
554 		default: logWarn("Unsupported platform('%s'), defaulting to x86", architecture); goto case;
555 		case "x86", "x86_mscoff": return "Win32";
556 		case "x86_64": return "x64";
557 	}
558 }