1//===- LineIterator.h - Iterator to read a text buffer's lines --*- C++ -*-===//
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#ifndef LLVM_SUPPORT_LINEITERATOR_H__
11#define LLVM_SUPPORT_LINEITERATOR_H__
12
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Support/DataTypes.h"
15#include <iterator>
16
17namespace llvm {
18
19class MemoryBuffer;
20
21/// \brief A forward iterator which reads non-blank text lines from a buffer.
22///
23/// This class provides a forward iterator interface for reading one line at
24/// a time from a buffer. When default constructed the iterator will be the
25/// "end" iterator.
26///
27/// The iterator also is aware of what line number it is currently processing
28/// and can strip comment lines given the comment-starting character.
29///
30/// Note that this iterator requires the buffer to be nul terminated.
31class line_iterator
32    : public std::iterator<std::forward_iterator_tag, StringRef> {
33  const MemoryBuffer *Buffer;
34  char CommentMarker;
35
36  unsigned LineNumber;
37  StringRef CurrentLine;
38
39public:
40  /// \brief Default construct an "end" iterator.
41  line_iterator() : Buffer(nullptr) {}
42
43  /// \brief Construct a new iterator around some memory buffer.
44  explicit line_iterator(const MemoryBuffer &Buffer, char CommentMarker = '\0');
45
46  /// \brief Return true if we've reached EOF or are an "end" iterator.
47  bool is_at_eof() const { return !Buffer; }
48
49  /// \brief Return true if we're an "end" iterator or have reached EOF.
50  bool is_at_end() const { return is_at_eof(); }
51
52  /// \brief Return the current line number. May return any number at EOF.
53  int64_t line_number() const { return LineNumber; }
54
55  /// \brief Advance to the next (non-empty, non-comment) line.
56  line_iterator &operator++() {
57    advance();
58    return *this;
59  }
60  line_iterator operator++(int) {
61    line_iterator tmp(*this);
62    advance();
63    return tmp;
64  }
65
66  /// \brief Get the current line as a \c StringRef.
67  StringRef operator*() const { return CurrentLine; }
68  const StringRef *operator->() const { return &CurrentLine; }
69
70  friend bool operator==(const line_iterator &LHS, const line_iterator &RHS) {
71    return LHS.Buffer == RHS.Buffer &&
72           LHS.CurrentLine.begin() == RHS.CurrentLine.begin();
73  }
74
75  friend bool operator!=(const line_iterator &LHS, const line_iterator &RHS) {
76    return !(LHS == RHS);
77  }
78
79private:
80  /// \brief Advance the iterator to the next line.
81  void advance();
82};
83}
84
85#endif // LLVM_SUPPORT_LINEITERATOR_H__
86