blob: c14f96bf714a82209745fc3b1e71f01c584b066a [file] [log] [blame]
Chandler Carruthf8c52812013-12-27 04:28:57 +00001//===- 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 size_t Length = 0;
33
34 if (CommentMarker == '\0') {
35 // If we're not stripping comments, this is simpler.
36 while (Pos[Length] == '\n')
37 ++Length;
38 Pos += Length;
39 LineNumber += Length;
40 Length = 0;
41 } else {
42 // Skip comments and count line numbers, which is a bit more complex.
43 for (;;) {
44 if (*Pos == CommentMarker)
45 do {
46 ++Pos;
47 } while (*Pos != '\0' && *Pos != '\n');
48 if (*Pos != '\n')
49 break;
50 ++Pos;
51 ++LineNumber;
52 }
53 }
54
55 if (*Pos == '\0') {
56 // We've hit the end of the buffer, reset ourselves to the end state.
57 Buffer = 0;
58 CurrentLine = StringRef();
59 return;
60 }
61
62 // Measure the line.
63 do {
64 ++Length;
65 } while (Pos[Length] != '\0' && Pos[Length] != '\n');
66
67 CurrentLine = StringRef(Pos, Length);
68}