Support/PathV2: Add native implementation.
[oota-llvm.git] / lib / Support / PathV2.cpp
1 //===-- PathV2.cpp - Implement OS Path Concept ------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the operating system PathV2 API.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/PathV2.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include <cctype>
17
18 namespace {
19   using llvm::StringRef;
20
21   bool is_separator(const char value) {
22     switch(value) {
23 #ifdef LLVM_ON_WIN32
24     case '\\': // fall through
25 #endif
26     case '/': return true;
27     default: return false;
28     }
29   }
30
31 #ifdef LLVM_ON_WIN32
32   const StringRef separators = "\\/";
33   const char       prefered_separator = '\\';
34 #else
35   const StringRef separators = "/";
36   const char      prefered_separator = '/';
37 #endif
38
39   StringRef find_first_component(const StringRef  &path) {
40     // Look for this first component in the following order.
41     // * empty (in this case we return an empty string)
42     // * either C: or {//,\\}net.
43     // * {/,\}
44     // * {.,..}
45     // * {file,directory}name
46
47     if (path.empty())
48       return path;
49
50     // C:
51     if (path.size() >= 2 && std::isalpha(path[0]) && path[1] == ':')
52       return StringRef(path.begin(), 2);
53
54     // //net
55     if ((path.size() > 2) &&
56         (path.startswith("\\\\") || path.startswith("//")) &&
57         (path[2] != '\\' && path[2] != '/')) {
58       // Find the next directory separator.
59       size_t end = path.find_first_of("\\/", 2);
60       if (end == StringRef::npos)
61         return path;
62       else
63         return StringRef(path.begin(), end);
64     }
65
66     // {/,\}
67     if (path[0] == '\\' || path[0] == '/')
68       return StringRef(path.begin(), 1);
69
70     if (path.startswith(".."))
71       return StringRef(path.begin(), 2);
72
73     if (path[0] == '.')
74       return StringRef(path.begin(), 1);
75
76     // * {file,directory}name
77     size_t end = path.find_first_of("\\/", 2);
78     if (end == StringRef::npos)
79       return path;
80     else
81       return StringRef(path.begin(), end);
82
83     return StringRef();
84   }
85
86   size_t filename_pos(const StringRef &str) {
87     if (str.size() == 2 &&
88         is_separator(str[0]) &&
89         is_separator(str[1]))
90       return 0;
91
92     if (str.size() > 0 && is_separator(str[str.size() - 1]))
93       return str.size() - 1;
94
95     size_t pos = str.find_last_of(separators, str.size() - 1);
96
97 #ifdef LLVM_ON_WIN32
98     if (pos == StringRef::npos)
99       pos = str.find_last_of(':', str.size() - 2);
100 #endif
101
102     if (pos == StringRef::npos ||
103         (pos == 1 && is_separator(str[0])))
104       return 0;
105
106     return pos + 1;
107   }
108
109   size_t root_dir_start(const StringRef &str) {
110     // case "c:/"
111 #ifdef LLVM_ON_WIN32
112     if (str.size() > 2 &&
113         str[1] == ':' &&
114         is_separator(str[2]))
115       return 2;
116 #endif
117
118     // case "//"
119     if (str.size() == 2 &&
120         is_separator(str[0]) &&
121         str[0] == str[1])
122       return StringRef::npos;
123
124     // case "//net"
125     if (str.size() > 3 &&
126         is_separator(str[0]) &&
127         str[0] == str[1] &&
128         !is_separator(str[2])) {
129       return str.find_first_of(separators, 2);
130     }
131
132     // case "/"
133     if (str.size() > 0 && is_separator(str[0]))
134       return 0;
135
136     return StringRef::npos;
137   }
138
139   size_t parent_path_end(const StringRef &path) {
140     size_t end_pos = filename_pos(path);
141
142     bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
143
144     // Skip separators except for root dir.
145     size_t root_dir_pos = root_dir_start(StringRef(path.begin(), end_pos));
146
147     while(end_pos > 0 &&
148           (end_pos - 1) != root_dir_pos &&
149           is_separator(path[end_pos - 1]))
150       --end_pos;
151
152     if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
153       return StringRef::npos;
154
155     return end_pos;
156   }
157 }
158
159 namespace llvm {
160 namespace sys  {
161 namespace path {
162
163 const_iterator begin(const StringRef &path) {
164   const_iterator i;
165   i.Path      = path;
166   i.Component = find_first_component(path);
167   i.Position  = 0;
168   return i;
169 }
170
171 const_iterator end(const StringRef &path) {
172   const_iterator i;
173   i.Path      = path;
174   i.Position  = path.size();
175   return i;
176 }
177
178 const_iterator &const_iterator::operator++() {
179   assert(Position < Path.size() && "Tried to increment past end!");
180
181   // Increment Position to past the current component
182   Position += Component.size();
183
184   // Check for end.
185   if (Position == Path.size()) {
186     Component = StringRef();
187     return *this;
188   }
189
190   // Both POSIX and Windows treat paths that begin with exactly two separators
191   // specially.
192   bool was_net = Component.size() > 2 &&
193     is_separator(Component[0]) &&
194     Component[1] == Component[0] &&
195     !is_separator(Component[2]);
196
197   // Handle separators.
198   if (is_separator(Path[Position])) {
199     // Root dir.
200     if (was_net
201 #ifdef LLVM_ON_WIN32
202         // c:/
203         || Component.endswith(":")
204 #endif
205         ) {
206       Component = StringRef(Path.begin() + Position, 1);
207       return *this;
208     }
209
210     // Skip extra separators.
211     while (Position != Path.size() &&
212            is_separator(Path[Position])) {
213       ++Position;
214     }
215
216     // Treat trailing '/' as a '.'.
217     if (Position == Path.size()) {
218       --Position;
219       Component = ".";
220       return *this;
221     }
222   }
223
224   // Find next component.
225   size_t end_pos = Path.find_first_of(separators, Position);
226   if (end_pos == StringRef::npos)
227     end_pos = Path.size();
228   Component = StringRef(Path.begin() + Position, end_pos - Position);
229
230   return *this;
231 }
232
233 const_iterator &const_iterator::operator--() {
234   // If we're at the end and the previous char was a '/', return '.'.
235   if (Position == Path.size() &&
236       Path.size() > 1 &&
237       is_separator(Path[Position - 1])
238 #ifdef LLVM_ON_WIN32
239       && Path[Position - 2] != ':'
240 #endif
241       ) {
242     --Position;
243     Component = ".";
244     return *this;
245   }
246
247   // Skip separators unless it's the root directory.
248   size_t root_dir_pos = root_dir_start(Path);
249   size_t end_pos = Position;
250
251   while(end_pos > 0 &&
252         (end_pos - 1) != root_dir_pos &&
253         is_separator(Path[end_pos - 1]))
254     --end_pos;
255
256   // Find next separator.
257   size_t start_pos = filename_pos(StringRef(Path.begin(), end_pos));
258   Component = StringRef(Path.begin() + start_pos, end_pos - start_pos);
259   Position = start_pos;
260   return *this;
261 }
262
263 bool const_iterator::operator==(const const_iterator &RHS) const {
264   return Path.begin() == RHS.Path.begin() &&
265          Position == RHS.Position;
266 }
267
268 bool const_iterator::operator!=(const const_iterator &RHS) const {
269   return !(*this == RHS);
270 }
271
272 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
273   return Position - RHS.Position;
274 }
275
276 error_code root_path(const StringRef &path, StringRef &result) {
277   const_iterator b = begin(path),
278                  pos = b,
279                  e = end(path);
280   if (b != e) {
281     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
282     bool has_drive =
283 #ifdef LLVM_ON_WIN32
284       b->endswith(":");
285 #else
286       false;
287 #endif
288
289     if (has_net || has_drive) {
290       if ((++pos != e) && is_separator((*pos)[0])) {
291         // {C:/,//net/}, so get the first two components.
292         result = StringRef(path.begin(), b->size() + pos->size());
293         return make_error_code(errc::success);
294       } else {
295         // just {C:,//net}, return the first component.
296         result = *b;
297         return make_error_code(errc::success);
298       }
299     }
300
301     // POSIX style root directory.
302     if (is_separator((*b)[0])) {
303       result = *b;
304       return make_error_code(errc::success);
305     }
306
307     // No root_path.
308     result = StringRef();
309     return make_error_code(errc::success);
310   }
311
312   // No path :(.
313   result = StringRef();
314   return make_error_code(errc::success);
315 }
316
317 error_code root_name(const StringRef &path, StringRef &result) {
318   const_iterator b = begin(path),
319                  e = end(path);
320   if (b != e) {
321     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
322     bool has_drive =
323 #ifdef LLVM_ON_WIN32
324       b->endswith(":");
325 #else
326       false;
327 #endif
328
329     if (has_net || has_drive) {
330       // just {C:,//net}, return the first component.
331       result = *b;
332       return make_error_code(errc::success);
333     }
334   }
335
336   // No path or no name.
337   result = StringRef();
338   return make_error_code(errc::success);
339 }
340
341 error_code root_directory(const StringRef &path, StringRef &result) {
342   const_iterator b = begin(path),
343                  pos = b,
344                  e = end(path);
345   if (b != e) {
346     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
347     bool has_drive =
348 #ifdef LLVM_ON_WIN32
349       b->endswith(":");
350 #else
351       false;
352 #endif
353
354     if ((has_net || has_drive) &&
355         // {C:,//net}, skip to the next component.
356         (++pos != e) && is_separator((*pos)[0])) {
357       result = *pos;
358       return make_error_code(errc::success);
359     }
360
361     // POSIX style root directory.
362     if (!has_net && is_separator((*b)[0])) {
363       result = *b;
364       return make_error_code(errc::success);
365     }
366   }
367
368   // No path or no root.
369   result = StringRef();
370   return make_error_code(errc::success);
371 }
372
373 error_code has_root_name(const Twine &path, bool &result) {
374   SmallString<128> storage;
375   StringRef p = path.toStringRef(storage);
376
377   if (error_code ec = root_name(p, p)) return ec;
378   result = !p.empty();
379   return make_error_code(errc::success);
380 }
381
382 error_code has_root_directory(const Twine &path, bool &result) {
383   SmallString<128> storage;
384   StringRef p = path.toStringRef(storage);
385
386   if (error_code ec = root_directory(p, p)) return ec;
387   result = !p.empty();
388   return make_error_code(errc::success);
389 }
390
391 error_code relative_path(const StringRef &path, StringRef &result) {
392   StringRef root;
393   if (error_code ec = root_path(path, root)) return ec;
394   result = StringRef(path.begin() + root.size(), path.size() - root.size());
395   return make_error_code(errc::success);
396 }
397
398 error_code append(SmallVectorImpl<char> &path, const Twine &a,
399                                                const Twine &b,
400                                                const Twine &c,
401                                                const Twine &d) {
402   SmallString<32> a_storage;
403   SmallString<32> b_storage;
404   SmallString<32> c_storage;
405   SmallString<32> d_storage;
406
407   SmallVector<StringRef, 4> components;
408   if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
409   if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
410   if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
411   if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
412
413   for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
414                                                   e = components.end();
415                                                   i != e; ++i) {
416     bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
417     bool component_has_sep = !i->empty() && is_separator((*i)[0]);
418     bool is_root_name;
419     if (error_code ec = has_root_name(*i, is_root_name)) return ec;
420
421     if (path_has_sep) {
422       // Strip separators from beginning of component.
423       size_t loc = i->find_first_not_of(separators);
424       StringRef c = StringRef(i->begin() + loc, i->size() - loc);
425
426       // Append it.
427       path.append(c.begin(), c.end());
428       continue;
429     }
430
431     if (!component_has_sep && !(path.empty() && is_root_name)) {
432       // Add a separator.
433       path.push_back(prefered_separator);
434     }
435
436     path.append(i->begin(), i->end());
437   }
438
439   return make_error_code(errc::success);
440 }
441
442 error_code make_absolute(SmallVectorImpl<char> &path) {
443   StringRef p(path.data(), path.size());
444
445   bool rootName, rootDirectory;
446   if (error_code ec = has_root_name(p, rootName)) return ec;
447   if (error_code ec = has_root_directory(p, rootDirectory)) return ec;
448
449   // Already absolute.
450   if (rootName && rootDirectory)
451     return make_error_code(errc::success);
452
453   // All of the following conditions will need the current directory.
454   SmallString<128> current_dir;
455   if (error_code ec = current_path(current_dir)) return ec;
456
457   // Relative path. Prepend the current directory.
458   if (!rootName && !rootDirectory) {
459     // Append path to the current directory.
460     if (error_code ec = append(current_dir, p)) return ec;
461     // Set path to the result.
462     path.swap(current_dir);
463     return make_error_code(errc::success);
464   }
465
466   if (!rootName && rootDirectory) {
467     StringRef cdrn;
468     if (error_code ec = root_name(current_dir, cdrn)) return ec;
469     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
470     if (error_code ec = append(curDirRootName, p)) return ec;
471     // Set path to the result.
472     path.swap(curDirRootName);
473     return make_error_code(errc::success);
474   }
475
476   if (rootName && !rootDirectory) {
477     StringRef pRootName;
478     StringRef bRootDirectory;
479     StringRef bRelativePath;
480     StringRef pRelativePath;
481     if (error_code ec = root_name(p, pRootName)) return ec;
482     if (error_code ec = root_directory(current_dir, bRootDirectory)) return ec;
483     if (error_code ec = relative_path(current_dir, bRelativePath)) return ec;
484     if (error_code ec = relative_path(p, pRelativePath)) return ec;
485
486     SmallString<128> res;
487     if (error_code ec = append(res, pRootName, bRootDirectory,
488                                     bRelativePath, pRelativePath)) return ec;
489     path.swap(res);
490     return make_error_code(errc::success);
491   }
492
493   llvm_unreachable("All rootName and rootDirectory combinations should have "
494                    "occurred above!");
495 }
496
497 error_code parent_path(const StringRef &path, StringRef &result) {
498   size_t end_pos = parent_path_end(path);
499   if (end_pos == StringRef::npos)
500     result = StringRef();
501   else
502     result = StringRef(path.data(), end_pos);
503   return make_error_code(errc::success);
504 }
505
506 error_code remove_filename(SmallVectorImpl<char> &path) {
507   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
508   if (end_pos == StringRef::npos)
509     return make_error_code(errc::success);
510   path.set_size(end_pos);
511   return make_error_code(errc::success);
512 }
513
514 error_code replace_extension(SmallVectorImpl<char> &path,
515                              const Twine &extension) {
516   StringRef p(path.begin(), path.size());
517   SmallString<32> ext_storage;
518   StringRef ext = extension.toStringRef(ext_storage);
519
520   // Erase existing extension.
521   size_t pos = p.find_last_of('.');
522   if (pos != StringRef::npos && pos >= filename_pos(p))
523     path.set_size(pos);
524
525   // Append '.' if needed.
526   if (ext.size() > 0 && ext[0] != '.')
527     path.push_back('.');
528
529   // Append extension.
530   path.append(ext.begin(), ext.end());
531   return make_error_code(errc::success);
532 }
533
534 error_code native(const Twine &path, SmallVectorImpl<char> &result) {
535   // Clear result.
536   result.set_size(0);
537 #ifdef LLVM_ON_WIN32
538   SmallString<128> path_storage;
539   StringRef p = path.toStringRef(path_storage);
540   result.reserve(p.size());
541   for (StringRef::const_iterator i = p.begin(),
542                                  e = p.end();
543                                  i != e;
544                                  ++i) {
545     if (*i == '/')
546       result.push_back('\\');
547     else
548       result.push_back(*i);
549   }
550 #else
551   path.toVector(result);
552 #endif
553   return make_error_code(errc::success);
554 }
555
556 }
557 }
558 }
559
560 // Include the truly platform-specific parts.
561 #if defined(LLVM_ON_UNIX)
562 #include "Unix/PathV2.inc"
563 #endif
564 #if defined(LLVM_ON_WIN32)
565 #include "Windows/PathV2.inc"
566 #endif