summaryrefslogtreecommitdiffstats
path: root/clang-query/QueryParser.cpp
blob: 38903e3e9bff9cb30b4a4aabd6a29f548682f5f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//===---- QueryParser.cpp - clang-query command parser --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "QueryParser.h"
#include "Query.h"
#include "QuerySession.h"
#include "clang/ASTMatchers/Dynamic/Parser.h"
#include "clang/Basic/CharInfo.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"

#include <set>

using namespace llvm;
using namespace clang::ast_matchers::dynamic;

namespace clang {
namespace query {

// Lex any amount of whitespace followed by a "word" (any sequence of
// non-whitespace characters) from the start of region [Begin,End).  If no word
// is found before End, return StringRef().  Begin is adjusted to exclude the
// lexed region.
StringRef QueryParser::lexWord() {
  while (true) {
    if (Begin == End)
      return StringRef(Begin, 0);

    if (!isWhitespace(*Begin))
      break;

    ++Begin;
  }

  const char *WordBegin = Begin;

  while (true) {
    ++Begin;

    if (Begin == End || isWhitespace(*Begin))
      return StringRef(WordBegin, Begin - WordBegin);
  }
}

// This is the StringSwitch-alike used by lexOrCompleteWord below. See that
// function for details.
template <typename T> struct QueryParser::LexOrCompleteWord {
  StringSwitch<T> Switch;

  QueryParser *P;
  StringRef Word;
  // Set to the completion point offset in Word, or StringRef::npos if
  // completion point not in Word.
  size_t WordCompletionPos;

  LexOrCompleteWord(QueryParser *P, StringRef Word, size_t WCP)
      : Switch(Word), P(P), Word(Word), WordCompletionPos(WCP) {}

  template <unsigned N>
  LexOrCompleteWord &Case(const char (&S)[N], const T &Value,
                          bool IsCompletion = true) {
    StringRef CaseStr(S, N - 1);

    if (WordCompletionPos == StringRef::npos)
      Switch.Case(S, Value);
    else if (N != 1 && IsCompletion && WordCompletionPos <= CaseStr.size() &&
             CaseStr.substr(0, WordCompletionPos) ==
                 Word.substr(0, WordCompletionPos))
      P->Completions.push_back(LineEditor::Completion(
          (CaseStr.substr(WordCompletionPos) + " ").str(), CaseStr));
    return *this;
  }

  T Default(const T& Value) const {
    return Switch.Default(Value);
  }
};

// Lexes a word and stores it in Word. Returns a LexOrCompleteWord<T> object
// that can be used like a llvm::StringSwitch<T>, but adds cases as possible
// completions if the lexed word contains the completion point.
template <typename T>
QueryParser::LexOrCompleteWord<T>
QueryParser::lexOrCompleteWord(StringRef &Word) {
  Word = lexWord();
  size_t WordCompletionPos = StringRef::npos;
  if (CompletionPos && CompletionPos <= Word.data() + Word.size()) {
    if (CompletionPos < Word.data())
      WordCompletionPos = 0;
    else
      WordCompletionPos = CompletionPos - Word.data();
  }
  return LexOrCompleteWord<T>(this, Word, WordCompletionPos);
}

QueryRef QueryParser::parseSetBool(bool QuerySession::*Var) {
  StringRef ValStr;
  unsigned Value = lexOrCompleteWord<unsigned>(ValStr)
                      .Case("false", 0)
                      .Case("true", 1)
                      .Default(~0u);
  if (Value == ~0u) {
    return new InvalidQuery("expected 'true' or 'false', got '" + ValStr + "'");
  }
  return new SetQuery<bool>(Var, Value);
}

QueryRef QueryParser::parseSetOutputKind() {
  StringRef ValStr;
  unsigned OutKind = lexOrCompleteWord<unsigned>(ValStr)
                         .Case("diag", OK_Diag)
                         .Case("print", OK_Print)
                         .Case("dump", OK_Dump)
                         .Default(~0u);
  if (OutKind == ~0u) {
    return new InvalidQuery("expected 'diag', 'print' or 'dump', got '" +
                            ValStr + "'");
  }
  return new SetQuery<OutputKind>(&QuerySession::OutKind, OutputKind(OutKind));
}

QueryRef QueryParser::endQuery(QueryRef Q) {
  const char *Extra = Begin;
  if (!lexWord().empty())
    return new InvalidQuery("unexpected extra input: '" +
                            StringRef(Extra, End - Extra) + "'");
  return Q;
}

enum ParsedQueryKind {
  PQK_Invalid,
  PQK_NoOp,
  PQK_Help,
  PQK_Match,
  PQK_Set
};

enum ParsedQueryVariable {
  PQV_Invalid,
  PQV_Output,
  PQV_BindRoot
};

QueryRef QueryParser::doParse() {
  StringRef CommandStr;
  ParsedQueryKind QKind = lexOrCompleteWord<ParsedQueryKind>(CommandStr)
                              .Case("", PQK_NoOp)
                              .Case("help", PQK_Help)
                              .Case("m", PQK_Match, /*IsCompletion=*/false)
                              .Case("match", PQK_Match)
                              .Case("set", PQK_Set)
                              .Default(PQK_Invalid);

  switch (QKind) {
  case PQK_NoOp:
    return new NoOpQuery;

  case PQK_Help:
    return endQuery(new HelpQuery);

  case PQK_Match: {
    if (CompletionPos) {
      std::vector<MatcherCompletion> Comps = Parser::completeExpression(
          StringRef(Begin, End - Begin), CompletionPos - Begin);
      for (std::vector<MatcherCompletion>::iterator I = Comps.begin(),
                                                    E = Comps.end();
           I != E; ++I) {
        Completions.push_back(
            LineEditor::Completion(I->TypedText, I->MatcherDecl));
      }
      return QueryRef();
    } else {
      Diagnostics Diag;
      Optional<DynTypedMatcher> Matcher =
          Parser::parseMatcherExpression(StringRef(Begin, End - Begin), &Diag);
      if (!Matcher) {
        std::string ErrStr;
        llvm::raw_string_ostream OS(ErrStr);
        Diag.printToStreamFull(OS);
        return new InvalidQuery(OS.str());
      }
      return new MatchQuery(*Matcher);
    }
  }

  case PQK_Set: {
    StringRef VarStr;
    ParsedQueryVariable Var = lexOrCompleteWord<ParsedQueryVariable>(VarStr)
                                  .Case("output", PQV_Output)
                                  .Case("bind-root", PQV_BindRoot)
                                  .Default(PQV_Invalid);
    if (VarStr.empty())
      return new InvalidQuery("expected variable name");
    if (Var == PQV_Invalid)
      return new InvalidQuery("unknown variable: '" + VarStr + "'");

    QueryRef Q;
    switch (Var) {
    case PQV_Output:
      Q = parseSetOutputKind();
      break;
    case PQV_BindRoot:
      Q = parseSetBool(&QuerySession::BindRoot);
      break;
    case PQV_Invalid:
      llvm_unreachable("Invalid query kind");
    }

    return endQuery(Q);
  }

  case PQK_Invalid:
    return new InvalidQuery("unknown command: " + CommandStr);
  }

  llvm_unreachable("Invalid query kind");
}

QueryRef QueryParser::parse(StringRef Line) {
  return QueryParser(Line).doParse();
}

std::vector<LineEditor::Completion> QueryParser::complete(StringRef Line,
                                                          size_t Pos) {
  QueryParser P(Line);
  P.CompletionPos = Line.data() + Pos;

  P.doParse();
  return P.Completions;
}

} // namespace query
} // namespace clang