Debian Codegraph @

gcc/d/dmd/utils.d

raw
1 /**
2 * This module defines some utility functions for DMD.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/utils.d, _utils.d)
8 * Documentation: https://dlang.org/phobos/dmd_utils.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/utils.d
10 */
11
12 module dmd.utils;
13
14 import core.stdc.string;
15 import dmd.errors;
16 import dmd.location;
17 import dmd.root.file;
18 import dmd.root.filename;
19 import dmd.common.outbuffer;
20 import dmd.root.string;
21
22 nothrow:
23
24 /**
25 * Normalize path by turning forward slashes into backslashes
26 *
27 * Params:
28 * src = Source path, using unix-style ('/') path separators
29 *
30 * Returns:
31 * A newly-allocated string with '/' turned into backslashes
32 */
33 const(char)* toWinPath(const(char)* src)
34 {
35 if (src is null)
36 return null;
37 char* result = strdup(src);
38 char* p = result;
39 while (*p != '\0')
40 {
41 if (*p == '/')
42 *p = '\\';
43 p++;
44 }
45 return result;
46 }
47
48
49 /**
50 * Reads a file, terminate the program on error
51 *
52 * Params:
53 * loc = The line number information from where the call originates
54 * filename = Path to file
55 * buf = append contents of file to
56 * Returns:
57 * true on failure
58 */
59 bool readFile(Loc loc, const(char)[] filename, ref OutBuffer buf)
60 {
61 if (File.read(filename, buf))
62 {
63 error(loc, "error reading file `%.*s`", cast(int)filename.length, filename.ptr);
64 return true;
65 }
66 return false;
67 }
68
69
70 /**
71 * Writes a file, terminate the program on error
72 *
73 * Params:
74 * loc = The line number information from where the call originates
75 * filename = Path to file
76 * data = Full content of the file to be written
77 * Returns:
78 * false on error
79 */
80 extern (D) bool writeFile(Loc loc, const(char)[] filename, const void[] data)
81 {
82 if (!ensurePathToNameExists(Loc.initial, filename))
83 return false;
84 if (!File.update(filename, data))
85 {
86 error(loc, "error writing file '%.*s'", cast(int) filename.length, filename.ptr);
87 return false;
88 }
89 return true;
90 }
91
92
93 /**
94 * Ensure the root path (the path minus the name) of the provided path
95 * exists, and terminate the process if it doesn't.
96 *
97 * Params:
98 * loc = The line number information from where the call originates
99 * name = a path to check (the name is stripped)
100 * Returns:
101 * false on error
102 */
103 bool ensurePathToNameExists(Loc loc, const(char)[] name)
104 {
105 const char[] pt = FileName.path(name);
106 if (pt.length)
107 {
108 if (!FileName.ensurePathExists(pt))
109 {
110 error(loc, "cannot create directory %*.s", cast(int) pt.length, pt.ptr);
111 FileName.free(pt.ptr);
112 return false;
113 }
114 }
115 FileName.free(pt.ptr);
116 return true;
117 }
118
119
120 /**
121 * Takes a path, and escapes '(', ')' and backslashes
122 *
123 * Params:
124 * buf = Buffer to write the escaped path to
125 * fname = Path to escape
126 */
127 void escapePath(OutBuffer* buf, const(char)* fname) pure
128 {
129 while (1)
130 {
131 switch (*fname)
132 {
133 case 0:
134 return;
135 case '(':
136 case ')':
137 case '\\':
138 buf.writeByte('\\');
139 goto default;
140 default:
141 buf.writeByte(*fname);
142 break;
143 }
144 fname++;
145 }
146 }
147
148 /**
149 * Convert string to integer.
150 *
151 * Params:
152 * T = Type of integer to parse
153 * val = Variable to store the result in
154 * p = slice to start of string digits
155 * max = max allowable value (inclusive), defaults to `T.max`
156 *
157 * Returns:
158 * `false` on error, `true` on success
159 */
160 bool parseDigits(T)(ref T val, const(char)[] p, const T max = T.max)
161 @safe pure @nogc nothrow
162 {
163 import core.checkedint : mulu, addu, muls, adds;
164
165 // mul* / add* doesn't support types < int
166 static if (T.sizeof < int.sizeof)
167 {
168 int value;
169 alias add = adds;
170 alias mul = muls;
171 }
172 // unsigned
173 else static if (T.min == 0)
174 {
175 T value;
176 alias add = addu;
177 alias mul = mulu;
178 }
179 else
180 {
181 T value;
182 alias add = adds;
183 alias mul = muls;
184 }
185
186 bool overflow;
187 foreach (char c; p)
188 {
189 if (c > '9' || c < '0')
190 return false;
191 value = mul(value, 10, overflow);
192 value = add(value, uint(c - '0'), overflow);
193 }
194 // If it overflows, value must be > to `max` (since `max` is `T`)
195 val = cast(T) value;
196 return !overflow && value <= max;
197 }
198
199 ///
200 @safe pure nothrow @nogc unittest
201 {
202 byte b;
203 ubyte ub;
204 short s;
205 ushort us;
206 int i;
207 uint ui;
208 long l;
209 ulong ul;
210
211 assert(b.parseDigits("42") && b == 42);
212 assert(ub.parseDigits("42") && ub == 42);
213
214 assert(s.parseDigits("420") && s == 420);
215 assert(us.parseDigits("42000") && us == 42_000);
216
217 assert(i.parseDigits("420000") && i == 420_000);
218 assert(ui.parseDigits("420000") && ui == 420_000);
219
220 assert(l.parseDigits("42000000000") && l == 42_000_000_000);
221 assert(ul.parseDigits("82000000000") && ul == 82_000_000_000);
222
223 assert(!b.parseDigits(ubyte.max.stringof));
224 assert(!b.parseDigits("WYSIWYG"));
225 assert(!b.parseDigits("-42"));
226 assert(!b.parseDigits("200"));
227 assert(ub.parseDigits("200") && ub == 200);
228 assert(i.parseDigits(int.max.stringof) && i == int.max);
229 assert(i.parseDigits("420", 500) && i == 420);
230 assert(!i.parseDigits("420", 400));
231 }
232
233 /**
234 * Cast a `ubyte[]` to an array of larger integers as if we are on a big endian architecture
235 * Params:
236 * data = array with big endian data
237 * size = 1 for ubyte[], 2 for ushort[], 4 for uint[], 8 for ulong[]
238 * Returns: copy of `data`, with bytes shuffled if compiled for `version(LittleEndian)`
239 */
240 ubyte[] arrayCastBigEndian(const ubyte[] data, size_t size) @safe
241 {
242 ubyte[] impl(T)()
243 {
244 auto result = new T[](data.length / T.sizeof);
245 foreach (i; 0 .. result.length)
246 {
247 result[i] = 0;
248 foreach (j; 0 .. T.sizeof)
249 {
250 result[i] |= T(data[i * T.sizeof + j]) << ((T.sizeof - 1 - j) * 8);
251 }
252 }
253 return cast(ubyte[]) result;
254 }
255 switch (size)
256 {
257 case 1: return data.dup;
258 case 2: return impl!ushort;
259 case 4: return impl!uint;
260 case 8: return impl!ulong;
261 default: assert(0);
262 }
263 }
264
265 unittest
266 {
267 ubyte[] data = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22];
268 assert(cast(ulong[]) arrayCastBigEndian(data, 8) == [0xAABBCCDDEEFF1122]);
269 assert(cast(uint[]) arrayCastBigEndian(data, 4) == [0xAABBCCDD, 0xEEFF1122]);
270 assert(cast(ushort[]) arrayCastBigEndian(data, 2) == [0xAABB, 0xCCDD, 0xEEFF, 0x1122]);
271 assert(cast(ubyte[]) arrayCastBigEndian(data, 1) == data);
272 }