1 /// Copyright: Copyright (c) 2021 Andrey Penechko.
2 /// License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
3 /// Authors: Andrey Penechko.
4 module vox.fe.passes.read_source;
5 
6 import vox.all;
7 
8 void pass_read_source(ref CompilationContext ctx, CompilePassPerModule[] subPasses)
9 {
10 	size_t start = ctx.sourceBuffer.length;
11 	foreach(ref file; ctx.files.data)
12 	{
13 		if (file.content)
14 		{
15 			ctx.sourceBuffer.put(SOI_CHAR);
16 			ctx.sourceBuffer.put(file.content);
17 			ctx.sourceBuffer.put(EOI_CHAR);
18 
19 			file.length = cast(uint)(file.content.length + 2);
20 			file.start = cast(uint)start;
21 			start += file.length;
22 		}
23 		else
24 		{
25 			import std.file : exists;
26 			import std.path : absolutePath;
27 			import std.stdio : File;
28 
29 			if (!exists(file.name))
30 			{
31 				ctx.error("File `%s` not found", absolutePath(file.name));
32 				return;
33 			}
34 
35 			ctx.sourceBuffer.put(SOI_CHAR);
36 			auto f = File(file.name, "r");
37 			size_t fileLength = f.size;
38 			char[] sourceBuffer = ctx.sourceBuffer.voidPut(fileLength);
39 			if (fileLength) {
40 				// rawRead doesn't support reading into empty sourceBuffer
41 				char[] result = f.rawRead(sourceBuffer);
42 				ctx.assertf(result.length == fileLength,
43 					"File read failed due to mismatch. File size is %s bytes, while read %s bytes",
44 					fileLength, result.length);
45 			}
46 			f.close();
47 			ctx.sourceBuffer.put(EOI_CHAR);
48 
49 			file.content = cast(string)sourceBuffer;
50 			file.length = cast(uint)(fileLength + 2);
51 			file.start = cast(uint)start;
52 			start += file.length;
53 		}
54 
55 		if (ctx.bundleInputs) {
56 			import std.string : stripRight;
57 			ctx.bundleBuffer.put("--- ");
58 			ctx.bundleBuffer.put(file.name);
59 			ctx.bundleBuffer.put("\n");
60 			ctx.bundleBuffer.put(file.content.stripRight);
61 			ctx.bundleBuffer.put("\n");
62 		}
63 
64 		if (ctx.printSource) {
65 			import std.stdio : writeln, writefln;
66 			writefln("// Source `%s`", file.name);
67 			writeln(file.content);
68 		}
69 	}
70 }