LineIterator.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
1//===- LineIterator.cpp - Implementation of line iteration ----------------===//
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#include "llvm/Support/LineIterator.h"
11#include "llvm/Support/MemoryBuffer.h"
12
13using namespace llvm;
14
15line_iterator::line_iterator(const MemoryBuffer &Buffer, char CommentMarker)
16    : Buffer(Buffer.getBufferSize() ? &Buffer : 0),
17      CommentMarker(CommentMarker), LineNumber(1),
18      CurrentLine(Buffer.getBufferSize() ? Buffer.getBufferStart() : 0, 0) {
19  // Ensure that if we are constructed on a non-empty memory buffer that it is
20  // a null terminated buffer.
21  if (Buffer.getBufferSize()) {
22    assert(Buffer.getBufferEnd()[0] == '\0');
23    advance();
24  }
25}
26
27void line_iterator::advance() {
28  assert(Buffer && "Cannot advance past the end!");
29
30  const char *Pos = CurrentLine.end();
31  assert(Pos == Buffer->getBufferStart() || *Pos == '\n' || *Pos == '\0');
32
33  if (CommentMarker == '\0') {
34    // If we're not stripping comments, this is simpler.
35    size_t Blanks = 0;
36    while (Pos[Blanks] == '\n')
37      ++Blanks;
38    Pos += Blanks;
39    LineNumber += Blanks;
40  } else {
41    // Skip comments and count line numbers, which is a bit more complex.
42    for (;;) {
43      if (*Pos == CommentMarker)
44        do {
45          ++Pos;
46        } while (*Pos != '\0' && *Pos != '\n');
47      if (*Pos != '\n')
48        break;
49      ++Pos;
50      ++LineNumber;
51    }
52  }
53
54  if (*Pos == '\0') {
55    // We've hit the end of the buffer, reset ourselves to the end state.
56    Buffer = 0;
57    CurrentLine = StringRef();
58    return;
59  }
60
61  // Measure the line.
62  size_t Length = 0;
63  do {
64    ++Length;
65  } while (Pos[Length] != '\0' && Pos[Length] != '\n');
66
67  CurrentLine = StringRef(Pos, Length);
68}
69