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