Support/PathV2: Fix append to not add a slash to empty or root paths.
[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 make_absolute(SmallVectorImpl<char> &path) {
428   StringRef p(path.data(), path.size());
429
430   bool rootName = false, rootDirectory = false;
431   if (error_code ec = has_root_name(p, rootName)) return ec;
432   if (error_code ec = has_root_directory(p, rootDirectory)) return ec;
433
434   // Already absolute.
435   if (rootName && rootDirectory)
436     return success;
437
438   // All of the following conditions will need the current directory.
439   SmallString<128> current_dir;
440   if (error_code ec = current_path(current_dir)) return ec;
441
442   // Relative path. Prepend the current directory.
443   if (!rootName && !rootDirectory) {
444     // Append path to the current directory.
445     if (error_code ec = append(current_dir, p)) return ec;
446     // Set path to the result.
447     path.swap(current_dir);
448     return success;
449   }
450
451   if (!rootName && rootDirectory) {
452     StringRef cdrn;
453     if (error_code ec = root_name(current_dir, cdrn)) return ec;
454     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
455     if (error_code ec = append(curDirRootName, p)) return ec;
456     // Set path to the result.
457     path.swap(curDirRootName);
458     return success;
459   }
460
461   if (rootName && !rootDirectory) {
462     StringRef pRootName;
463     StringRef bRootDirectory;
464     StringRef bRelativePath;
465     StringRef pRelativePath;
466     if (error_code ec = root_name(p, pRootName)) return ec;
467     if (error_code ec = root_directory(current_dir, bRootDirectory)) return ec;
468     if (error_code ec = relative_path(current_dir, bRelativePath)) return ec;
469     if (error_code ec = relative_path(p, pRelativePath)) return ec;
470
471     SmallString<128> res;
472     if (error_code ec = append(res, pRootName, bRootDirectory,
473                                     bRelativePath, pRelativePath)) return ec;
474     path.swap(res);
475     return success;
476   }
477
478   llvm_unreachable("All rootName and rootDirectory combinations should have "
479                    "occurred above!");
480 }
481
482 error_code parent_path(const StringRef &path, StringRef &result) {
483   size_t end_pos = parent_path_end(path);
484   if (end_pos == StringRef::npos)
485     result = StringRef();
486   else
487     result = StringRef(path.data(), end_pos);
488   return success;
489 }
490
491 error_code remove_filename(SmallVectorImpl<char> &path) {
492   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
493   if (end_pos == StringRef::npos)
494     return success;
495   path.set_size(end_pos);
496   return success;
497 }
498
499 error_code replace_extension(SmallVectorImpl<char> &path,
500                              const Twine &extension) {
501   StringRef p(path.begin(), path.size());
502   SmallString<32> ext_storage;
503   StringRef ext = extension.toStringRef(ext_storage);
504
505   // Erase existing extension.
506   size_t pos = p.find_last_of('.');
507   if (pos != StringRef::npos && pos >= filename_pos(p))
508     path.set_size(pos);
509
510   // Append '.' if needed.
511   if (ext.size() > 0 && ext[0] != '.')
512     path.push_back('.');
513
514   // Append extension.
515   path.append(ext.begin(), ext.end());
516   return success;
517 }
518
519 error_code native(const Twine &path, SmallVectorImpl<char> &result) {
520   // Clear result.
521   result.set_size(0);
522 #ifdef LLVM_ON_WIN32
523   SmallString<128> path_storage;
524   StringRef p = path.toStringRef(path_storage);
525   result.reserve(p.size());
526   for (StringRef::const_iterator i = p.begin(),
527                                  e = p.end();
528                                  i != e;
529                                  ++i) {
530     if (*i == '/')
531       result.push_back('\\');
532     else
533       result.push_back(*i);
534   }
535 #else
536   path.toVector(result);
537 #endif
538   return success;
539 }
540
541 error_code filename(const StringRef &path, StringRef &result) {
542   result = *(--end(path));
543   return success;
544 }
545
546 error_code stem(const StringRef &path, StringRef &result) {
547   StringRef fname;
548   if (error_code ec = filename(path, fname)) return ec;
549   size_t pos = fname.find_last_of('.');
550   if (pos == StringRef::npos)
551     result = fname;
552   else
553     if ((fname.size() == 1 && fname == ".") ||
554         (fname.size() == 2 && fname == ".."))
555       result = fname;
556     else
557       result = StringRef(fname.begin(), pos);
558
559   return success;
560 }
561
562 error_code extension(const StringRef &path, StringRef &result) {
563   StringRef fname;
564   if (error_code ec = filename(path, fname)) return ec;
565   size_t pos = fname.find_last_of('.');
566   if (pos == StringRef::npos)
567     result = StringRef();
568   else
569     if ((fname.size() == 1 && fname == ".") ||
570         (fname.size() == 2 && fname == ".."))
571       result = StringRef();
572     else
573       result = StringRef(fname.begin() + pos, fname.size() - pos);
574
575   return success;
576 }
577
578 error_code has_root_name(const Twine &path, bool &result) {
579   SmallString<128> path_storage;
580   StringRef p = path.toStringRef(path_storage);
581
582   if (error_code ec = root_name(p, p)) return ec;
583
584   result = !p.empty();
585   return success;
586 }
587
588 error_code has_root_directory(const Twine &path, bool &result) {
589   SmallString<128> path_storage;
590   StringRef p = path.toStringRef(path_storage);
591
592   if (error_code ec = root_directory(p, p)) return ec;
593
594   result = !p.empty();
595   return success;
596 }
597
598 error_code has_root_path(const Twine &path, bool &result) {
599   SmallString<128> path_storage;
600   StringRef p = path.toStringRef(path_storage);
601
602   if (error_code ec = root_path(p, p)) return ec;
603
604   result = !p.empty();
605   return success;
606 }
607
608 error_code has_filename(const Twine &path, bool &result) {
609   SmallString<128> path_storage;
610   StringRef p = path.toStringRef(path_storage);
611
612   if (error_code ec = filename(p, p)) return ec;
613
614   result = !p.empty();
615   return success;
616 }
617
618 error_code has_parent_path(const Twine &path, bool &result) {
619   SmallString<128> path_storage;
620   StringRef p = path.toStringRef(path_storage);
621
622   if (error_code ec = parent_path(p, p)) return ec;
623
624   result = !p.empty();
625   return success;
626 }
627
628 error_code has_stem(const Twine &path, bool &result) {
629   SmallString<128> path_storage;
630   StringRef p = path.toStringRef(path_storage);
631
632   if (error_code ec = stem(p, p)) return ec;
633
634   result = !p.empty();
635   return success;
636 }
637
638 error_code has_extension(const Twine &path, bool &result) {
639   SmallString<128> path_storage;
640   StringRef p = path.toStringRef(path_storage);
641
642   if (error_code ec = extension(p, p)) return ec;
643
644   result = !p.empty();
645   return success;
646 }
647
648 error_code is_absolute(const Twine &path, bool &result) {
649   SmallString<128> path_storage;
650   StringRef p = path.toStringRef(path_storage);
651
652   bool rootDir = false,
653        rootName = false;
654   if (error_code ec = has_root_directory(p, rootDir)) return ec;
655 #ifdef LLVM_ON_WIN32
656   if (error_code ec = has_root_name(p, rootName)) return ec;
657 #else
658   rootName = true;
659 #endif
660
661   result = rootDir && rootName;
662   return success;
663 }
664
665 error_code is_relative(const Twine &path, bool &result) {
666   bool res;
667   error_code ec = is_absolute(path, res);
668   result = !res;
669   return ec;
670 }
671
672 } // end namespace path
673
674 namespace fs {
675
676 error_code create_directories(const Twine &path, bool &existed) {
677   SmallString<128> path_storage;
678   StringRef p = path.toStringRef(path_storage);
679
680   StringRef parent;
681   bool parent_exists;
682   if (error_code ec = path::parent_path(p, parent)) return ec;
683   if (error_code ec = fs::exists(parent, parent_exists)) return ec;
684
685   if (!parent_exists)
686     return create_directories(parent, existed);
687
688   return create_directory(p, existed);
689 }
690
691 } // end namespace fs
692 } // end namespace sys
693 } // end namespace llvm
694
695 // Include the truly platform-specific parts.
696 #if defined(LLVM_ON_UNIX)
697 #include "Unix/PathV2.inc"
698 #endif
699 #if defined(LLVM_ON_WIN32)
700 #include "Windows/PathV2.inc"
701 #endif