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