1 //===- LineIterator.cpp - Implementation of line iteration ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Support/LineIterator.h"
11 #include "llvm/Support/MemoryBuffer.h"
15 static bool isAtLineEnd(const char *P
) {
18 if (*P
== '\r' && *(P
+ 1) == '\n')
23 static bool skipIfAtLineEnd(const char *&P
) {
28 if (*P
== '\r' && *(P
+ 1) == '\n') {
35 line_iterator::line_iterator(const MemoryBuffer
&Buffer
, bool SkipBlanks
,
37 : Buffer(Buffer
.getBufferSize() ? &Buffer
: nullptr),
38 CommentMarker(CommentMarker
), SkipBlanks(SkipBlanks
), LineNumber(1),
39 CurrentLine(Buffer
.getBufferSize() ? Buffer
.getBufferStart() : nullptr,
41 // Ensure that if we are constructed on a non-empty memory buffer that it is
42 // a null terminated buffer.
43 if (Buffer
.getBufferSize()) {
44 assert(Buffer
.getBufferEnd()[0] == '\0');
45 // Make sure we don't skip a leading newline if we're keeping blanks
46 if (SkipBlanks
|| !isAtLineEnd(Buffer
.getBufferStart()))
51 void line_iterator::advance() {
52 assert(Buffer
&& "Cannot advance past the end!");
54 const char *Pos
= CurrentLine
.end();
55 assert(Pos
== Buffer
->getBufferStart() || isAtLineEnd(Pos
) || *Pos
== '\0');
57 if (skipIfAtLineEnd(Pos
))
59 if (!SkipBlanks
&& isAtLineEnd(Pos
)) {
60 // Nothing to do for a blank line.
61 } else if (CommentMarker
== '\0') {
62 // If we're not stripping comments, this is simpler.
63 while (skipIfAtLineEnd(Pos
))
66 // Skip comments and count line numbers, which is a bit more complex.
68 if (isAtLineEnd(Pos
) && !SkipBlanks
)
70 if (*Pos
== CommentMarker
)
73 } while (*Pos
!= '\0' && !isAtLineEnd(Pos
));
74 if (!skipIfAtLineEnd(Pos
))
81 // We've hit the end of the buffer, reset ourselves to the end state.
83 CurrentLine
= StringRef();
89 while (Pos
[Length
] != '\0' && !isAtLineEnd(&Pos
[Length
])) {
93 CurrentLine
= StringRef(Pos
, Length
);