add a raw_ostream::indent method, to be used like:
[oota-llvm.git] / lib / Support / raw_ostream.cpp
1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
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 implements support for bulk buffered stream output.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/System/Process.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include <ostream>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 #if defined(HAVE_UNISTD_H)
27 # include <unistd.h>
28 #endif
29 #if defined(HAVE_FCNTL_H)
30 # include <fcntl.h>
31 #endif
32
33 #if defined(_MSC_VER)
34 #include <io.h>
35 #include <fcntl.h>
36 #ifndef STDIN_FILENO
37 # define STDIN_FILENO 0
38 #endif
39 #ifndef STDOUT_FILENO
40 # define STDOUT_FILENO 1
41 #endif
42 #ifndef STDERR_FILENO
43 # define STDERR_FILENO 2
44 #endif
45 #endif
46
47 using namespace llvm;
48
49 raw_ostream::~raw_ostream() {
50   // raw_ostream's subclasses should take care to flush the buffer
51   // in their destructors.
52   assert(OutBufCur == OutBufStart &&
53          "raw_ostream destructor called with non-empty buffer!");
54
55   if (BufferMode == InternalBuffer)
56     delete [] OutBufStart;
57
58   // If there are any pending errors, report them now. Clients wishing
59   // to avoid llvm_report_error calls should check for errors with
60   // has_error() and clear the error flag with clear_error() before
61   // destructing raw_ostream objects which may have errors.
62   if (Error)
63     llvm_report_error("IO failure on output stream.");
64 }
65
66 // An out of line virtual method to provide a home for the class vtable.
67 void raw_ostream::handle() {}
68
69 size_t raw_ostream::preferred_buffer_size() {
70   // BUFSIZ is intended to be a reasonable default.
71   return BUFSIZ;
72 }
73
74 void raw_ostream::SetBuffered() {
75   // Ask the subclass to determine an appropriate buffer size.
76   if (size_t Size = preferred_buffer_size())
77     SetBufferSize(Size);
78   else
79     // It may return 0, meaning this stream should be unbuffered.
80     SetUnbuffered();
81 }
82
83 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, 
84                                     BufferKind Mode) {
85   assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) || 
86           (Mode != Unbuffered && BufferStart && Size >= 64)) &&
87          "stream must be unbuffered, or have >= 64 bytes of buffer");
88   // Make sure the current buffer is free of content (we can't flush here; the
89   // child buffer management logic will be in write_impl).
90   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
91
92   if (BufferMode == InternalBuffer)
93     delete [] OutBufStart;
94   OutBufStart = BufferStart;
95   OutBufEnd = OutBufStart+Size;
96   OutBufCur = OutBufStart;
97   BufferMode = Mode;
98
99   assert(OutBufStart <= OutBufEnd && "Invalid size!");
100 }
101
102 raw_ostream &raw_ostream::operator<<(unsigned long N) {
103   // Zero is a special case.
104   if (N == 0)
105     return *this << '0';
106   
107   char NumberBuffer[20];
108   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
109   char *CurPtr = EndPtr;
110   
111   while (N) {
112     *--CurPtr = '0' + char(N % 10);
113     N /= 10;
114   }
115   return write(CurPtr, EndPtr-CurPtr);
116 }
117
118 raw_ostream &raw_ostream::operator<<(long N) {
119   if (N <  0) {
120     *this << '-';
121     N = -N;
122   }
123   
124   return this->operator<<(static_cast<unsigned long>(N));
125 }
126
127 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
128   // Output using 32-bit div/mod when possible.
129   if (N == static_cast<unsigned long>(N))
130     return this->operator<<(static_cast<unsigned long>(N));
131
132   char NumberBuffer[20];
133   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
134   char *CurPtr = EndPtr;
135   
136   while (N) {
137     *--CurPtr = '0' + char(N % 10);
138     N /= 10;
139   }
140   return write(CurPtr, EndPtr-CurPtr);
141 }
142
143 raw_ostream &raw_ostream::operator<<(long long N) {
144   if (N <  0) {
145     *this << '-';
146     N = -N;
147   }
148   
149   return this->operator<<(static_cast<unsigned long long>(N));
150 }
151
152 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
153   // Zero is a special case.
154   if (N == 0)
155     return *this << '0';
156
157   char NumberBuffer[20];
158   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
159   char *CurPtr = EndPtr;
160
161   while (N) {
162     uintptr_t x = N % 16;
163     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
164     N /= 16;
165   }
166
167   return write(CurPtr, EndPtr-CurPtr);
168 }
169
170 raw_ostream &raw_ostream::operator<<(const void *P) {
171   *this << '0' << 'x';
172
173   return write_hex((uintptr_t) P);
174 }
175
176 void raw_ostream::flush_nonempty() {
177   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
178   size_t Length = OutBufCur - OutBufStart;
179   OutBufCur = OutBufStart;
180   write_impl(OutBufStart, Length);
181 }
182
183 raw_ostream &raw_ostream::write(unsigned char C) {
184   // Group exceptional cases into a single branch.
185   if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
186     if (BUILTIN_EXPECT(!OutBufStart, false)) {
187       if (BufferMode == Unbuffered) {
188         write_impl(reinterpret_cast<char*>(&C), 1);
189         return *this;
190       }
191       // Set up a buffer and start over.
192       SetBuffered();
193       return write(C);
194     }
195
196     flush_nonempty();
197   }
198
199   *OutBufCur++ = C;
200   return *this;
201 }
202
203 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
204   // Group exceptional cases into a single branch.
205   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
206     if (BUILTIN_EXPECT(!OutBufStart, false)) {
207       if (BufferMode == Unbuffered) {
208         write_impl(Ptr, Size);
209         return *this;
210       }
211       // Set up a buffer and start over.
212       SetBuffered();
213       return write(Ptr, Size);
214     }
215
216     // Write out the data in buffer-sized blocks until the remainder
217     // fits within the buffer.
218     do {
219       size_t NumBytes = OutBufEnd - OutBufCur;
220       copy_to_buffer(Ptr, NumBytes);
221       flush_nonempty();
222       Ptr += NumBytes;
223       Size -= NumBytes;
224     } while (OutBufCur+Size > OutBufEnd);
225   }
226
227   copy_to_buffer(Ptr, Size);
228
229   return *this;
230 }
231
232 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
233   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
234
235   // Handle short strings specially, memcpy isn't very good at very short
236   // strings.
237   switch (Size) {
238   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
239   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
240   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
241   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
242   case 0: break;
243   default:
244     memcpy(OutBufCur, Ptr, Size);
245     break;
246   }
247
248   OutBufCur += Size;
249 }
250
251 // Formatted output.
252 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
253   // If we have more than a few bytes left in our output buffer, try
254   // formatting directly onto its end.
255   size_t NextBufferSize = 127;
256   if (OutBufEnd-OutBufCur > 3) {
257     size_t BufferBytesLeft = OutBufEnd-OutBufCur;
258     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
259     
260     // Common case is that we have plenty of space.
261     if (BytesUsed < BufferBytesLeft) {
262       OutBufCur += BytesUsed;
263       return *this;
264     }
265     
266     // Otherwise, we overflowed and the return value tells us the size to try
267     // again with.
268     NextBufferSize = BytesUsed;
269   }
270   
271   // If we got here, we didn't have enough space in the output buffer for the
272   // string.  Try printing into a SmallVector that is resized to have enough
273   // space.  Iterate until we win.
274   SmallVector<char, 128> V;
275   
276   while (1) {
277     V.resize(NextBufferSize);
278     
279     // Try formatting into the SmallVector.
280     size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
281     
282     // If BytesUsed fit into the vector, we win.
283     if (BytesUsed <= NextBufferSize)
284       return write(&V[0], BytesUsed);
285     
286     // Otherwise, try again with a new size.
287     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
288     NextBufferSize = BytesUsed;
289   }
290 }
291
292 /// indent - Insert 'NumSpaces' spaces.
293 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
294   const char *Spaces = "                ";
295
296   // Usually the indentation is small, handle it with a fastpath.
297   if (NumSpaces <= 16)
298     return write(Spaces, NumSpaces);
299   
300   while (NumSpaces) {
301     unsigned NumToWrite = std::min(NumSpaces, 16U);
302     write(Spaces, NumToWrite);
303     NumSpaces -= NumToWrite;
304   }
305   return *this;
306 }
307
308
309 //===----------------------------------------------------------------------===//
310 //  Formatted Output
311 //===----------------------------------------------------------------------===//
312
313 // Out of line virtual method.
314 void format_object_base::home() {
315 }
316
317 //===----------------------------------------------------------------------===//
318 //  raw_fd_ostream
319 //===----------------------------------------------------------------------===//
320
321 /// raw_fd_ostream - Open the specified file for writing. If an error
322 /// occurs, information about the error is put into ErrorInfo, and the
323 /// stream should be immediately destroyed; the string will be empty
324 /// if no error occurred.
325 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
326                                std::string &ErrorInfo) : pos(0) {
327   ErrorInfo.clear();
328
329   // Handle "-" as stdout.
330   if (Filename[0] == '-' && Filename[1] == 0) {
331     FD = STDOUT_FILENO;
332     // If user requested binary then put stdout into binary mode if
333     // possible.
334     if (Binary)
335       sys::Program::ChangeStdoutToBinary();
336     ShouldClose = false;
337     return;
338   }
339   
340   int Flags = O_WRONLY|O_CREAT|O_TRUNC;
341 #ifdef O_BINARY
342   if (Binary)
343     Flags |= O_BINARY;
344 #endif
345   if (!Force)
346     Flags |= O_EXCL;
347   FD = open(Filename, Flags, 0664);
348   if (FD < 0) {
349     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
350     ShouldClose = false;
351   } else {
352     ShouldClose = true;
353   }
354 }
355
356 raw_fd_ostream::~raw_fd_ostream() {
357   if (FD >= 0) {
358     flush();
359     if (ShouldClose)
360       if (::close(FD) != 0)
361         error_detected();
362   }
363 }
364
365 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
366   assert (FD >= 0 && "File already closed.");
367   pos += Size;
368   if (::write(FD, Ptr, Size) != (ssize_t) Size)
369     error_detected();
370 }
371
372 void raw_fd_ostream::close() {
373   assert (ShouldClose);
374   ShouldClose = false;
375   flush();
376   if (::close(FD) != 0)
377     error_detected();
378   FD = -1;
379 }
380
381 uint64_t raw_fd_ostream::seek(uint64_t off) {
382   flush();
383   pos = ::lseek(FD, off, SEEK_SET);
384   if (pos != off)
385     error_detected();
386   return pos;  
387 }
388
389 size_t raw_fd_ostream::preferred_buffer_size() {
390 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
391   assert(FD >= 0 && "File not yet open!");
392   struct stat statbuf;
393   if (fstat(FD, &statbuf) == 0) {
394     // If this is a terminal, don't use buffering. Line buffering
395     // would be a more traditional thing to do, but it's not worth
396     // the complexity.
397     if (S_ISCHR(statbuf.st_mode) && isatty(FD))
398       return 0;
399     // Return the preferred block size.
400     return statbuf.st_blksize;
401   }
402   error_detected();
403 #endif
404   return raw_ostream::preferred_buffer_size();
405 }
406
407 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
408                                          bool bg) {
409   if (sys::Process::ColorNeedsFlush())
410     flush();
411   const char *colorcode =
412     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
413     : sys::Process::OutputColor(colors, bold, bg);
414   if (colorcode) {
415     size_t len = strlen(colorcode);
416     write(colorcode, len);
417     // don't account colors towards output characters
418     pos -= len;
419   }
420   return *this;
421 }
422
423 raw_ostream &raw_fd_ostream::resetColor() {
424   if (sys::Process::ColorNeedsFlush())
425     flush();
426   const char *colorcode = sys::Process::ResetColor();
427   if (colorcode) {
428     size_t len = strlen(colorcode);
429     write(colorcode, len);
430     // don't account colors towards output characters
431     pos -= len;
432   }
433   return *this;
434 }
435
436 //===----------------------------------------------------------------------===//
437 //  raw_stdout/err_ostream
438 //===----------------------------------------------------------------------===//
439
440 // Set buffer settings to model stdout and stderr behavior.
441 // Set standard error to be unbuffered by default.
442 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
443 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
444                                                         true) {}
445
446 // An out of line virtual method to provide a home for the class vtable.
447 void raw_stdout_ostream::handle() {}
448 void raw_stderr_ostream::handle() {}
449
450 /// outs() - This returns a reference to a raw_ostream for standard output.
451 /// Use it like: outs() << "foo" << "bar";
452 raw_ostream &llvm::outs() {
453   static raw_stdout_ostream S;
454   return S;
455 }
456
457 /// errs() - This returns a reference to a raw_ostream for standard error.
458 /// Use it like: errs() << "foo" << "bar";
459 raw_ostream &llvm::errs() {
460   static raw_stderr_ostream S;
461   return S;
462 }
463
464 /// nulls() - This returns a reference to a raw_ostream which discards output.
465 raw_ostream &llvm::nulls() {
466   static raw_null_ostream S;
467   return S;
468 }
469
470 //===----------------------------------------------------------------------===//
471 //  raw_os_ostream
472 //===----------------------------------------------------------------------===//
473
474 raw_os_ostream::~raw_os_ostream() {
475   flush();
476 }
477
478 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
479   OS.write(Ptr, Size);
480 }
481
482 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
483
484 //===----------------------------------------------------------------------===//
485 //  raw_string_ostream
486 //===----------------------------------------------------------------------===//
487
488 raw_string_ostream::~raw_string_ostream() {
489   flush();
490 }
491
492 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
493   OS.append(Ptr, Size);
494 }
495
496 //===----------------------------------------------------------------------===//
497 //  raw_svector_ostream
498 //===----------------------------------------------------------------------===//
499
500 // The raw_svector_ostream implementation uses the SmallVector itself as the
501 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
502 // always pointing past the end of the vector, but within the vector
503 // capacity. This allows raw_ostream to write directly into the correct place,
504 // and we only need to set the vector size when the data is flushed.
505
506 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
507   // Set up the initial external buffer. We make sure that the buffer has at
508   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
509   // make sure that we don't grow the buffer unnecessarily on destruction (when
510   // the data is flushed). See the FIXME below.
511   OS.reserve(OS.size() + 128);
512   SetBuffer(OS.end(), OS.capacity() - OS.size());
513 }
514
515 raw_svector_ostream::~raw_svector_ostream() {
516   // FIXME: Prevent resizing during this flush().
517   flush();
518 }
519
520 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
521   assert(Ptr == OS.end() && OS.size() + Size <= OS.capacity() &&
522          "Invalid write_impl() call!");
523
524   // We don't need to copy the bytes, just commit the bytes to the
525   // SmallVector.
526   OS.set_size(OS.size() + Size);
527
528   // Grow the vector if necessary.
529   if (OS.capacity() - OS.size() < 64)
530     OS.reserve(OS.capacity() * 2);
531
532   // Update the buffer position.
533   SetBuffer(OS.end(), OS.capacity() - OS.size());
534 }
535
536 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
537
538 StringRef raw_svector_ostream::str() {
539   flush();
540   return StringRef(OS.begin(), OS.size());
541 }
542
543 //===----------------------------------------------------------------------===//
544 //  raw_null_ostream
545 //===----------------------------------------------------------------------===//
546
547 raw_null_ostream::~raw_null_ostream() {
548 #ifndef NDEBUG
549   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
550   // with raw_null_ostream, but it's better to have raw_null_ostream follow
551   // the rules than to change the rules just for raw_null_ostream.
552   flush();
553 #endif
554 }
555
556 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
557 }
558
559 uint64_t raw_null_ostream::current_pos() {
560   return 0;
561 }