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