-
Notifications
You must be signed in to change notification settings - Fork 2
/
autocomplete.h
108 lines (101 loc) · 2.11 KB
/
autocomplete.h
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
#pragma once
#include "parse.h"
namespace sparqlxx
{
#ifdef SPARQLXX_DOC
#define _autocomplete_iequals(a, b, c) true
#else
inline bool _autocomplete_iequals(const string& a, const string& b, int count)
{
for (size_t i = 0; i < count; ++i)
if (tolower(a[i]) != tolower(b[i]))
return false;
return true;
}
#endif
/* Find possible completions of the given SPARQL query.
* @buffer user input
*
* @return vector of possible completions
*/
inline auto autocomplete(const std::string& buffer) -> std::vector<std::string>
{
try
{
parse(buffer + std::string{"\0", 1});
}
catch (parse_error& e)
{
if (buffer.size() && buffer[buffer.size() - 1] != ' ' && e.got[0] == '\0')
return {std::string{" "}};
if (e.got[e.got.size() - 1] == '\0')
{
bool can_end = false;
auto matches = std::vector<std::string>{};
for (auto ex : e.expected)
{
auto got = e.got.substr(0, e.got.size() - 1);
if (ex == "end")
{
if (got.size() == 0)
can_end = true;
continue;
}
if (ex == "Var")
{
ex = "?";
if (got.size() && (got[0] == '?' || got[0] == '$'))
{
if (got.size() > 1)
return {std::string{" "}};
else
return {};
}
}
if (ex == "Iri")
{
ex = "<";
if (got.size() && got[0] == '<')
return {got + ">"};
}
if (ex == "BlankNode")
{
ex = "_:";
if (got.size() >= 2 && got[0] == '_' && got[1] == ':')
{
if (got.size() >= 3)
return {std::string{" "}};
else
return {};
}
}
if (ex == "Literal")
{
ex = "\"";
if (got.size() && (got[0] == '"' || got[0] == '\''))
return {got + got[0]};
}
if (ex == "int")
{
if (got.size())
{
try
{
std::stoi(got);
return {got};
}
catch (std::invalid_argument&) {}
}
continue;
}
if (_autocomplete_iequals(ex, e.got, e.got.size() - 1))
matches.emplace_back(ex);
}
if (matches.size() || can_end)
return matches;
}
throw;
}
return {};
}
}