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 : line_iterator(Buffer
.getMemBufferRef(), SkipBlanks
, CommentMarker
) {}
38 line_iterator::line_iterator(const MemoryBufferRef
&Buffer
, bool SkipBlanks
,
40 : Buffer(Buffer
.getBufferSize() ? std::optional
<MemoryBufferRef
>(Buffer
)
42 CommentMarker(CommentMarker
), SkipBlanks(SkipBlanks
),
43 CurrentLine(Buffer
.getBufferSize() ? Buffer
.getBufferStart() : nullptr,
45 // Ensure that if we are constructed on a non-empty memory buffer that it is
46 // a null terminated buffer.
47 if (Buffer
.getBufferSize()) {
48 assert(Buffer
.getBufferEnd()[0] == '\0');
49 // Make sure we don't skip a leading newline if we're keeping blanks
50 if (SkipBlanks
|| !isAtLineEnd(Buffer
.getBufferStart()))
55 void line_iterator::advance() {
56 assert(Buffer
&& "Cannot advance past the end!");
58 const char *Pos
= CurrentLine
.end();
59 assert(Pos
== Buffer
->getBufferStart() || isAtLineEnd(Pos
) || *Pos
== '\0');
61 if (skipIfAtLineEnd(Pos
))
63 if (!SkipBlanks
&& isAtLineEnd(Pos
)) {
64 // Nothing to do for a blank line.
65 } else if (CommentMarker
== '\0') {
66 // If we're not stripping comments, this is simpler.
67 while (skipIfAtLineEnd(Pos
))
70 // Skip comments and count line numbers, which is a bit more complex.
72 if (isAtLineEnd(Pos
) && !SkipBlanks
)
74 if (*Pos
== CommentMarker
)
77 } while (*Pos
!= '\0' && !isAtLineEnd(Pos
));
78 if (!skipIfAtLineEnd(Pos
))
85 // We've hit the end of the buffer, reset ourselves to the end state.
86 Buffer
= std::nullopt
;
87 CurrentLine
= StringRef();
93 while (Pos
[Length
] != '\0' && !isAtLineEnd(&Pos
[Length
])) {
97 CurrentLine
= StringRef(Pos
, Length
);