1 //===--------------------- StringLexer.cpp -----------------------*- C++-*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Utility/StringLexer.h"
10 
11 #include <algorithm>
12 #include <assert.h>
13 
14 using namespace lldb_utility;
15 
16 StringLexer::StringLexer(std::string s) : m_data(s), m_position(0) {}
17 
18 StringLexer::StringLexer(const StringLexer &rhs)
19     : m_data(rhs.m_data), m_position(rhs.m_position) {}
20 
21 StringLexer::Character StringLexer::Peek() { return m_data[m_position]; }
22 
23 bool StringLexer::NextIf(Character c) {
24   auto val = Peek();
25   if (val == c) {
26     Next();
27     return true;
28   }
29   return false;
30 }
31 
32 std::pair<bool, StringLexer::Character>
33 StringLexer::NextIf(std::initializer_list<Character> cs) {
34   auto val = Peek();
35   for (auto c : cs) {
36     if (val == c) {
37       Next();
38       return {true, c};
39     }
40   }
41   return {false, 0};
42 }
43 
44 bool StringLexer::AdvanceIf(const std::string &token) {
45   auto pos = m_position;
46   bool matches = true;
47   for (auto c : token) {
48     if (!NextIf(c)) {
49       matches = false;
50       break;
51     }
52   }
53   if (!matches) {
54     m_position = pos;
55     return false;
56   }
57   return true;
58 }
59 
60 StringLexer::Character StringLexer::Next() {
61   auto val = Peek();
62   Consume();
63   return val;
64 }
65 
66 bool StringLexer::HasAtLeast(Size s) {
67   return (m_data.size() - m_position) >= s;
68 }
69 
70 void StringLexer::PutBack(Size s) {
71   assert(m_position >= s);
72   m_position -= s;
73 }
74 
75 std::string StringLexer::GetUnlexed() {
76   return std::string(m_data, m_position);
77 }
78 
79 void StringLexer::Consume() { m_position++; }
80 
81 StringLexer &StringLexer::operator=(const StringLexer &rhs) {
82   if (this != &rhs) {
83     m_data = rhs.m_data;
84     m_position = rhs.m_position;
85   }
86   return *this;
87 }
88