]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/d/dmd/utils.c
e3ea8c19e50432196ed60cfa77fc001dd6099698
[thirdparty/gcc.git] / gcc / d / dmd / utils.c
1
2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved
4 * written by Walter Bright
5 * http://www.digitalmars.com
6 * Distributed under the Boost Software License, Version 1.0.
7 * http://www.boost.org/LICENSE_1_0.txt
8 */
9
10 #include <string.h>
11 #include "mars.h"
12 #include "globals.h"
13 #include "root/file.h"
14 #include "root/filename.h"
15 #include "root/outbuffer.h"
16
17 /**
18 * Normalize path by turning forward slashes into backslashes
19 *
20 * Params:
21 * src = Source path, using unix-style ('/') path separators
22 *
23 * Returns:
24 * A newly-allocated string with '/' turned into backslashes
25 */
26 const char * toWinPath(const char *src)
27 {
28 if (src == NULL)
29 return NULL;
30
31 char *result = strdup(src);
32 char *p = result;
33 while (*p != '\0')
34 {
35 if (*p == '/')
36 *p = '\\';
37 p++;
38 }
39 return result;
40 }
41
42 /**
43 * Reads a file, terminate the program on error
44 *
45 * Params:
46 * loc = The line number information from where the call originates
47 * f = a `ddmd.root.file.File` handle to read
48 */
49 void readFile(Loc loc, File *f)
50 {
51 if (f->read())
52 {
53 error(loc, "Error reading file '%s'", f->name->toChars());
54 fatal();
55 }
56 }
57
58 /**
59 * Writes a file, terminate the program on error
60 *
61 * Params:
62 * loc = The line number information from where the call originates
63 * f = a `ddmd.root.file.File` handle to write
64 */
65 void writeFile(Loc loc, File *f)
66 {
67 if (f->write())
68 {
69 error(loc, "Error writing file '%s'", f->name->toChars());
70 fatal();
71 }
72 }
73
74 /**
75 * Ensure the root path (the path minus the name) of the provided path
76 * exists, and terminate the process if it doesn't.
77 *
78 * Params:
79 * loc = The line number information from where the call originates
80 * name = a path to check (the name is stripped)
81 */
82 void ensurePathToNameExists(Loc loc, const char *name)
83 {
84 const char *pt = FileName::path(name);
85 if (*pt)
86 {
87 if (FileName::ensurePathExists(pt))
88 {
89 error(loc, "cannot create directory %s", pt);
90 fatal();
91 }
92 }
93 FileName::free(pt);
94 }
95
96 /**
97 * Takes a path, and escapes '(', ')' and backslashes
98 *
99 * Params:
100 * buf = Buffer to write the escaped path to
101 * fname = Path to escape
102 */
103 void escapePath(OutBuffer *buf, const char *fname)
104 {
105 while (1)
106 {
107 switch (*fname)
108 {
109 case 0:
110 return;
111 case '(':
112 case ')':
113 case '\\':
114 buf->writeByte('\\');
115 /* fall through */
116 default:
117 buf->writeByte(*fname);
118 break;
119 }
120 fname++;
121 }
122 }