1 //===- LineIterator.cpp - Implementation of line iteration ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/LineIterator.h"
10 #include "llvm/Support/MemoryBuffer.h"
14 static bool isAtLineEnd(const char *P
) {
17 if (*P
== '\r' && *(P
+ 1) == '\n')
22 static bool skipIfAtLineEnd(const char *&P
) {
27 if (*P
== '\r' && *(P
+ 1) == '\n') {
34 line_iterator::line_iterator(const MemoryBuffer
&Buffer
, bool SkipBlanks
,
36 : Buffer(Buffer
.getBufferSize() ? &Buffer
: nullptr),
37 CommentMarker(CommentMarker
), SkipBlanks(SkipBlanks
), LineNumber(1),
38 CurrentLine(Buffer
.getBufferSize() ? Buffer
.getBufferStart() : nullptr,
40 // Ensure that if we are constructed on a non-empty memory buffer that it is
41 // a null terminated buffer.
42 if (Buffer
.getBufferSize()) {
43 assert(Buffer
.getBufferEnd()[0] == '\0');
44 // Make sure we don't skip a leading newline if we're keeping blanks
45 if (SkipBlanks
|| !isAtLineEnd(Buffer
.getBufferStart()))
50 void line_iterator::advance() {
51 assert(Buffer
&& "Cannot advance past the end!");
53 const char *Pos
= CurrentLine
.end();
54 assert(Pos
== Buffer
->getBufferStart() || isAtLineEnd(Pos
) || *Pos
== '\0');
56 if (skipIfAtLineEnd(Pos
))
58 if (!SkipBlanks
&& isAtLineEnd(Pos
)) {
59 // Nothing to do for a blank line.
60 } else if (CommentMarker
== '\0') {
61 // If we're not stripping comments, this is simpler.
62 while (skipIfAtLineEnd(Pos
))
65 // Skip comments and count line numbers, which is a bit more complex.
67 if (isAtLineEnd(Pos
) && !SkipBlanks
)
69 if (*Pos
== CommentMarker
)
72 } while (*Pos
!= '\0' && !isAtLineEnd(Pos
));
73 if (!skipIfAtLineEnd(Pos
))
80 // We've hit the end of the buffer, reset ourselves to the end state.
82 CurrentLine
= StringRef();
88 while (Pos
[Length
] != '\0' && !isAtLineEnd(&Pos
[Length
])) {
92 CurrentLine
= StringRef(Pos
, Length
);