LLVM API Documentation
00001 //===- LineIterator.cpp - Implementation of line iteration ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 00010 #include "llvm/Support/LineIterator.h" 00011 #include "llvm/Support/MemoryBuffer.h" 00012 00013 using namespace llvm; 00014 00015 line_iterator::line_iterator(const MemoryBuffer &Buffer, bool SkipBlanks, 00016 char CommentMarker) 00017 : Buffer(Buffer.getBufferSize() ? &Buffer : nullptr), 00018 CommentMarker(CommentMarker), SkipBlanks(SkipBlanks), LineNumber(1), 00019 CurrentLine(Buffer.getBufferSize() ? Buffer.getBufferStart() : nullptr, 00020 0) { 00021 // Ensure that if we are constructed on a non-empty memory buffer that it is 00022 // a null terminated buffer. 00023 if (Buffer.getBufferSize()) { 00024 assert(Buffer.getBufferEnd()[0] == '\0'); 00025 // Make sure we don't skip a leading newline if we're keeping blanks 00026 if (SkipBlanks || *Buffer.getBufferStart() != '\n') 00027 advance(); 00028 } 00029 } 00030 00031 void line_iterator::advance() { 00032 assert(Buffer && "Cannot advance past the end!"); 00033 00034 const char *Pos = CurrentLine.end(); 00035 assert(Pos == Buffer->getBufferStart() || *Pos == '\n' || *Pos == '\0'); 00036 00037 if (*Pos == '\n') { 00038 ++Pos; 00039 ++LineNumber; 00040 } 00041 if (!SkipBlanks && *Pos == '\n') { 00042 // Nothing to do for a blank line. 00043 } else if (CommentMarker == '\0') { 00044 // If we're not stripping comments, this is simpler. 00045 size_t Blanks = 0; 00046 while (Pos[Blanks] == '\n') 00047 ++Blanks; 00048 Pos += Blanks; 00049 LineNumber += Blanks; 00050 } else { 00051 // Skip comments and count line numbers, which is a bit more complex. 00052 for (;;) { 00053 if (*Pos == '\n' && !SkipBlanks) 00054 break; 00055 if (*Pos == CommentMarker) 00056 do { 00057 ++Pos; 00058 } while (*Pos != '\0' && *Pos != '\n'); 00059 if (*Pos != '\n') 00060 break; 00061 ++Pos; 00062 ++LineNumber; 00063 } 00064 } 00065 00066 if (*Pos == '\0') { 00067 // We've hit the end of the buffer, reset ourselves to the end state. 00068 Buffer = nullptr; 00069 CurrentLine = StringRef(); 00070 return; 00071 } 00072 00073 // Measure the line. 00074 size_t Length = 0; 00075 while (Pos[Length] != '\0' && Pos[Length] != '\n') { 00076 ++Length; 00077 } 00078 00079 CurrentLine = StringRef(Pos, Length); 00080 }