Compare commits

...

22 Commits

Author SHA1 Message Date
ToruNiina
3bf4ac0965 doc: update Fuzzy search section 2019-09-01 14:50:01 +09:00
ToruNiina
d53026837a test: add test for find<T> and check throw 2019-09-01 14:46:46 +09:00
ToruNiina
6d31cccc5b feat: throw if multiple keys match to the key 2019-09-01 14:45:56 +09:00
ToruNiina
99e46813f4 doc: add Fuzzy search section to README 2019-08-31 20:11:31 +09:00
ToruNiina
c0df39ca49 test: add test for find_fuzzy 2019-08-31 19:30:19 +09:00
ToruNiina
3e6747cfeb feat: add find_fuzzy and suggeston
Add the following
- find_fuzzy<T>(val, "key")
- find<T>(val, "key", FuzzyMatcher) to suggest typo
- levenstein_matcher
2019-08-31 19:28:50 +09:00
ToruNiina
4cebd660fd refactor: use as_xxx to cast toml value
and store rvalue reference as a value instead of lvalue
2019-08-31 18:22:36 +09:00
ToruNiina
43907de365 refactor: check key types in find(v, k1, k2, ...)
ks should be convertible to toml::key
2019-08-31 17:28:07 +09:00
ToruNiina
9b43171b65 refactor: split get.hpp to get/find.hpp 2019-08-31 14:49:00 +09:00
ToruNiina
c9543d8d9e test: add test of find_or with conversion 2019-08-31 13:05:05 +09:00
ToruNiina
15b68a89c6 fix: suppress warnings by forwarding argument 2019-08-31 13:04:25 +09:00
ToruNiina
7a1b5bd64e fix: skip whitespaces without newline 2019-08-26 18:16:09 +09:00
ToruNiina
e332e018db feat: allow raw tab characters in basic strings
This feature is planned to be incorporated in toml v1.0.0 but not
released yet.
2019-08-21 11:19:47 +09:00
ToruNiina
b1ec6d87bd chore: update patch version 2019-08-07 15:58:28 +09:00
ToruNiina
8dded288b4 Merge branch 'master' into find-or-value 2019-08-07 14:58:56 +09:00
ToruNiina
0f491c7f3a fix: add overload for find_or with toml::value 2019-08-07 14:55:30 +09:00
ToruNiina
5edf43a1d2 test: add missing include file to test code 2019-07-23 22:32:32 +09:00
ToruNiina
cffc605505 fix: stop including iostream 2019-07-23 22:27:20 +09:00
ToruNiina
fb91936a1d fix #76: correct version description in CMakeLists 2019-07-21 13:16:48 +09:00
ToruNiina
8833292858 doc: rearrange toml::find section in README 2019-07-19 20:42:47 +09:00
ToruNiina
3fe04aff77 doc: fix sample script in README 2019-07-19 20:13:12 +09:00
ToruNiina
138f030b5d doc: fix sample codes in README 2019-07-18 17:39:24 +09:00
12 changed files with 1374 additions and 378 deletions

View File

@@ -5,9 +5,9 @@ project(toml11)
set(toml11_VERSION_MAYOR 3) set(toml11_VERSION_MAYOR 3)
set(toml11_VERSION_MINOR 0) set(toml11_VERSION_MINOR 0)
set(toml11_VERSION_PATCH 0) set(toml11_VERSION_PATCH 1)
set(toml11_VERSION set(toml11_VERSION
"${toml11_VERSION_MAYOR}.${toml11_VERSION_MINOR}.${toml11_VERSION_PATCH}-beta" "${toml11_VERSION_MAYOR}.${toml11_VERSION_MINOR}.${toml11_VERSION_PATCH}"
) )
option(toml11_BUILD_TEST "Build toml tests" ON) option(toml11_BUILD_TEST "Build toml tests" ON)

225
README.md
View File

@@ -47,8 +47,9 @@ int main()
- [Decoding a toml file](#decoding-a-toml-file) - [Decoding a toml file](#decoding-a-toml-file)
- [In the case of syntax error](#in-the-case-of-syntax-error) - [In the case of syntax error](#in-the-case-of-syntax-error)
- [Invalid UTF-8 Codepoints](#invalid-utf-8-codepoints) - [Invalid UTF-8 Codepoints](#invalid-utf-8-codepoints)
- [Finding a toml value](#finding-a-toml-value-from-a-table) - [Finding a toml value](#finding-a-toml-value)
- [In the case of type error](#in-the-case-of-type-error) - [Finding a value in a table](#finding-a-value-in-a-table)
- [In case of error](#in-case-of-error)
- [Dotted keys](#dotted-keys) - [Dotted keys](#dotted-keys)
- [Casting a toml value](#casting-a-toml-value) - [Casting a toml value](#casting-a-toml-value)
- [Checking value type](#checking-value-type) - [Checking value type](#checking-value-type)
@@ -101,7 +102,7 @@ to pass a filename to the `toml::parse` function.
```cpp ```cpp
const std::string fname("sample.toml"); const std::string fname("sample.toml");
const toml::table data = toml::parse(fname); const toml::value data = toml::parse(fname);
``` ```
If it encounters an error while opening a file, it will throw `std::runtime_error`. If it encounters an error while opening a file, it will throw `std::runtime_error`.
@@ -185,7 +186,7 @@ representing unicode character is not a valid UTF-8 codepoint.
| ^--------- should be in [0x00..0x10FFFF] | ^--------- should be in [0x00..0x10FFFF]
``` ```
## Finding a toml value from a table ## Finding a toml value
After parsing successfully, you can obtain the values from the result of After parsing successfully, you can obtain the values from the result of
`toml::parse` using `toml::find` function. `toml::parse` using `toml::find` function.
@@ -196,8 +197,6 @@ answer = 42
pi = 3.14 pi = 3.14
numbers = [1,2,3] numbers = [1,2,3]
time = 1979-05-27T07:32:00Z time = 1979-05-27T07:32:00Z
[tab]
key = "value"
``` ```
``` cpp ``` cpp
@@ -206,23 +205,16 @@ const auto answer = toml::find<std::int64_t >(data, "answer");
const auto pi = toml::find<double >(data, "pi"); const auto pi = toml::find<double >(data, "pi");
const auto numbers = toml::find<std::vector<int>>(data, "numbers"); const auto numbers = toml::find<std::vector<int>>(data, "numbers");
const auto timepoint = toml::find<std::chrono::system_clock::time_point>(data, "time"); const auto timepoint = toml::find<std::chrono::system_clock::time_point>(data, "time");
const auto tab = toml::find<toml::table>(data, "tab");
const auto key = toml::find<std::string>(tab, "key");
``` ```
If the value does not exist, `toml::find` throws an error with the location of By default, `toml::find` returns a `toml::value`.
the table.
```console ```cpp
terminate called after throwing an instance of 'std::out_of_range' const toml::value& answer = toml::find(data, "answer");
what(): [error] key "answer" not found
--> example.toml
6 | [tab]
| ~~~~~ in this table
``` ```
When you pass an exact TOML type that does not require type conversion, When you pass an exact TOML type that does not require type conversion,
`toml::get` returns a reference without copying the value. `toml::find` returns a reference without copying the value.
```cpp ```cpp
const auto data = toml::parse("sample.toml"); const auto data = toml::parse("sample.toml");
@@ -232,12 +224,6 @@ const auto& answer = toml::find<toml::integer>(data, "answer");
If the specified type requires conversion, you can't take a reference to the value. If the specified type requires conversion, you can't take a reference to the value.
See also [underlying types](#underlying-types). See also [underlying types](#underlying-types).
By default, `toml::find` returns a `toml::value`.
```cpp
const toml::value& answer = toml::find(data, "answer");
```
**NOTE**: For some technical reason, automatic conversion between `integer` and **NOTE**: For some technical reason, automatic conversion between `integer` and
`floating` is not supported. If you want to get a floating value even if a value `floating` is not supported. If you want to get a floating value even if a value
has integer value, you need to convert it manually after obtaining a value, has integer value, you need to convert it manually after obtaining a value,
@@ -250,44 +236,40 @@ double x = vx.is_floating() ? vx.as_floating(std::nothrow) :
// floating nor integer. // floating nor integer.
``` ```
---- ### Finding a value in a table
`toml::find` accepts arbitrary number of keys to find a value buried in a There are several way to get a value defined in a table.
deep recursion of tables. First, you can get a table as a normal value and find a value from the table.
```toml
[fruit]
name = "apple"
[fruit.physical]
color = "red"
shape = "round"
```
``` cpp
const auto data = toml::parse("fruit.toml");
const auto& fruit = toml::find(data, "fruit");
const auto name = toml::find<std::string>(fruit, "apple");
const auto& physical = toml::find(fruit, "physical");
const auto color = toml::find<std::string>(fruit, "color");
const auto shape = toml::find<std::string>(fruit, "shape");
```
Here, variable `fruit` is a `toml::value` and can be used as the first argument
of `toml::find`.
Second, you can pass as many arguments as the number of subtables to `toml::find`.
```cpp ```cpp
// # expecting the following example.toml const auto data = toml::parse("fruit.toml");
// answer.to.the.ultimate.question = 42 const auto color = toml::find<std::string>(data, "fruit", "physical", "color");
// # is equivalent to {"answer": {"to":{"the":{"ultimate:{"question":42}}}}} const auto shape = toml::find<std::string>(data, "fruit", "physical", "shape");
const toml::table data = toml::parse("example.toml");
const int a = toml::find<int>(data, "answer", "to", "the", "ultimate", "question");
``` ```
Of course, alternatively, you can call `toml::find` as many as you need.
### In the case of type error
If the specified type differs from the actual value contained, it throws
`toml::type_error` that inherits `std::exception`.
Similar to the case of syntax error, toml11 also displays clean error messages.
The error message when you choose `int` to get `string` value would be like this.
```console
terminate called after throwing an instance of 'toml::type_error'
what(): [error] toml::value bad_cast to integer
--> example.toml
3 | title = "TOML Example"
| ~~~~~~~~~~~~~~ the actual type is string
```
**NOTE**: In order to show this kind of error message, all the toml values have
a pointer to represent its range in a file. The entire contents of a file is
shared by `toml::value`s and remains on the heap memory. It is recommended to
destruct all the `toml::value` classes after configuring your application
if you have a large TOML file compared to the memory resource.
### Dotted keys ### Dotted keys
TOML v0.5.0 has a new feature named "dotted keys". TOML v0.5.0 has a new feature named "dotted keys".
@@ -309,14 +291,15 @@ shape = "round"
You can get both of the above tables with the same c++ code. You can get both of the above tables with the same c++ code.
```cpp ```cpp
const auto physical = toml::find<toml::table>(data, "physical"); const auto physical = toml::find(data, "physical");
const auto color = toml::find<std::string>(physical, "color"); const auto color = toml::find<std::string>(physical, "color");
``` ```
The following code does not work for the above toml file. The following code does not work for the above toml file.
```cpp ```cpp
const auto color = toml::find<std::string>(data, "physical.color"); // does not work // XXX this does not work!
const auto color = toml::find<std::string>(data, "physical.color");
``` ```
The above code works with the following toml file. The above code works with the following toml file.
@@ -327,6 +310,117 @@ The above code works with the following toml file.
# NOT {"physical": {"color": "orange"}}. # NOT {"physical": {"color": "orange"}}.
``` ```
### In case of error
If the value does not exist, `toml::find` throws an error with the location of
the table.
```console
terminate called after throwing an instance of 'std::out_of_range'
what(): [error] key "answer" not found
--> example.toml
6 | [tab]
| ~~~~~ in this table
```
**Note**: It is recommended to find a table as `toml::value` because it has much information
compared to `toml::table`, which is an alias of
`std::unordered_map<std::string, toml::value>`. Since `toml::table` does not have
any information about toml file, such as where the table was defined in the file.
----
If the specified type differs from the actual value contained, it throws
`toml::type_error` that inherits `std::exception`.
Similar to the case of syntax error, toml11 also displays clean error messages.
The error message when you choose `int` to get `string` value would be like this.
```console
terminate called after throwing an instance of 'toml::type_error'
what(): [error] toml::value bad_cast to integer
--> example.toml
3 | title = "TOML Example"
| ~~~~~~~~~~~~~~ the actual type is string
```
**NOTE**: In order to show this kind of error message, all the toml values have
a pointer to represent its range in a file. The entire contents of a file is
shared by `toml::value`s and remains on the heap memory. It is recommended to
destruct all the `toml::value` classes after configuring your application
if you have a large TOML file compared to the memory resource.
### Fuzzy Search
To find a value, you can use `find_fuzzy` instead of `find`.
```toml
[foobar]
# typo!
anseer = 42
```
```cpp
const auto data = toml::parse("sample.toml");
const auto foobar = toml::find(data, "foobar");
const auto answer = toml::find_fuzzy<int>(data, "answer"); // it finds "anseer".
```
When the specified key is not found, `toml::find_fuzzy` calculates
[levenstein distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
between the specified key and other keys.
If it finds a key that is 1 away from the specified key by the Levenstein
distance, it returns the corresponding value.
To allow a more distant string, you can explicitly pass `toml::levenstein_matcher`
to `find_fuzzy`.
```cpp
toml::levenstein_matcher lev(2); // allow distance <= 2
const auto answer = toml::find_fuzzy<int>(data, "answer", lev);
```
You can also use your own distance metric. Implement your `fuzzy_matcher` that
has `operator()` that takes two strings and returns true if two strings resemble
each other.
```cpp
struct fuzzy_matcher
{
bool operator()(const std::string& lhs, const std::string& rhs) const
{
// return true if lhs matches with rhs.
}
};
```
If there are multiple keys that meets the condition, it throws `runtime_error`.
However, in many cases, rather than just allowing typographical errors,
you will want to suggest it and encouledge users to correct it.
If you pass a `fuzzy_matcher` to `toml::find`, a suggestion will be displayed
in the error message.
```cpp
toml::levenstein_matcher lev(1); // finds keys within distance <= 1
const auto answer = toml::find<int>(data, "answer", lev); // it throws!
```
```console
terminate called after throwing an instance of 'std::out_of_range'
what(): [error] key "answer" not found.
--> hoge.toml
1 | [foobar]
| ~~~~~~~~ in this table
...
2 | anseer = 42
| ~~ did you mean this here?
```
Note: Currently, `find_fuzzy` and `find(value, key, matcher)` take only one key.
The codes like `find_fuzzy(value, key1, key2, key3)` do not work.
## Casting a toml value ## Casting a toml value
### `toml::get` ### `toml::get`
@@ -348,18 +442,22 @@ contain one of the following types.
- It depends. See [customizing containers](#customizing-containers) for detail. - It depends. See [customizing containers](#customizing-containers) for detail.
To get a value inside, you can use `toml::get<T>()`. The usage is the same as To get a value inside, you can use `toml::get<T>()`. The usage is the same as
`toml::find<T>` (actually, `toml::find` internally uses `toml::get`). `toml::find<T>` (actually, `toml::find` internally uses `toml::get` after casting
a value to `toml::table`).
``` cpp ``` cpp
const toml::value data = toml::parse("sample.toml"); const toml::value data = toml::parse("sample.toml");
const toml::value answer_ = toml::get<toml::table >(data).at("answer") const toml::value answer_ = toml::get<toml::table >(data).at("answer");
const std::int64_t answer = toml::get<std::int64_t>(answer_); const std::int64_t answer = toml::get<std::int64_t>(answer_);
``` ```
When you pass an exact TOML type that does not require type conversion, When you pass an exact TOML type that does not require type conversion,
`toml::get` returns a reference through which you can modify the content. `toml::get` returns a reference through which you can modify the content
(if the `toml::value` is `const`, it returns `const` reference).
```cpp ```cpp
toml::value data = toml::parse("sample.toml");
toml::value answer_ = toml::get<toml::table >(data).at("answer");
toml::integer& answer = toml::get<toml::integer>(answer_); toml::integer& answer = toml::get<toml::integer>(answer_);
answer = 6 * 9; // write to data.answer. now `answer_` contains 54. answer = 6 * 9; // write to data.answer. now `answer_` contains 54.
``` ```
@@ -426,8 +524,6 @@ class value {
} // toml } // toml
``` ```
## Checking value type ## Checking value type
You can check the type of a value by `is_xxx` function. You can check the type of a value by `is_xxx` function.
@@ -1392,8 +1488,9 @@ Between v2 and v3, those interfaces are rearranged.
- See [Casting a toml::value](#casting-a-tomlvalue) and [Checking value type](#checking-value-type) for detail. - See [Casting a toml::value](#casting-a-tomlvalue) and [Checking value type](#checking-value-type) for detail.
- An overload of `toml::find` for `toml::table` has been dropped. Use `toml::value` version instead. - An overload of `toml::find` for `toml::table` has been dropped. Use `toml::value` version instead.
- Because type conversion between a table and a value causes ambiguity while overload resolution - Because type conversion between a table and a value causes ambiguity while overload resolution
- Since `toml::parse` now returns a `toml::value`, this feature becomes less important.
- Also because `toml::table` is a normal STL container, implementing utility function is easy. - Also because `toml::table` is a normal STL container, implementing utility function is easy.
- See [Finding a toml::value](#finding-a-tomlvalue) for detail. - See [Finding a toml::value](#finding-a-toml-value) for detail.
- An overload of `operator<<` and `toml::format` for `toml::table`s are dropped. - An overload of `operator<<` and `toml::format` for `toml::table`s are dropped.
- Use `toml::value` instead. - Use `toml::value` instead.
- See [Serializing TOML data](#serializing-toml-data) for detail. - See [Serializing TOML data](#serializing-toml-data) for detail.

View File

@@ -27,6 +27,7 @@ set(TEST_NAMES
test_get_or test_get_or
test_find test_find
test_find_or test_find_or
test_find_fuzzy
test_expect test_expect
test_parse_file test_parse_file
test_serialize_file test_serialize_file

350
tests/test_find_fuzzy.cpp Normal file
View File

@@ -0,0 +1,350 @@
#define BOOST_TEST_MODULE "test_find_fuzzy"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
BOOST_AUTO_TEST_CASE(test_levenstein_distance)
{
const toml::levenstein_matcher lev(1);
// distance == 0
{
const std::string s1("foobar");
const std::string s2 = s1;
BOOST_TEST(lev.distance(s1, s2) == 0);
}
{
const std::string s1("foobar");
const std::string s2("foobaz");
BOOST_TEST(lev.distance(s1, s2) == 1);
}
{
const std::string s1("foobar"); // insertion (+x)
const std::string s2("fooxbar");
BOOST_TEST(lev.distance(s1, s2) == 1);
}
{
const std::string s1("foobar");
const std::string s2("fooar"); // insertion(+b)
BOOST_TEST(lev.distance(s1, s2) == 1);
}
// distance > 1
{
const std::string s1("foobar");
const std::string s2("fooquux");
BOOST_TEST(lev.distance(s1, s2) == 4);
}
{
const std::string s1("foobar");
const std::string s2("fooqu");
BOOST_TEST(s1 != s2);
BOOST_TEST(lev.distance(s1, s2) == 3);
}
}
BOOST_AUTO_TEST_CASE(test_find_fuzzy)
{
{
toml::value v{
{"keu", "value"} // typo! key -> keu
};
BOOST_TEST(toml::find_fuzzy(v, "key") == toml::value("value"));
BOOST_CHECK_THROW(toml::find_fuzzy(v, "kiwi"), std::out_of_range);
static_assert(std::is_same<
toml::value&, decltype(toml::find_fuzzy(v, "key"))>::value, "");
toml::find_fuzzy(v, "key") = "foobar";
BOOST_TEST(toml::find(v, "keu") == toml::value("foobar"));
}
{
const toml::value v{
{"keu", "value"} // typo! key -> keu
};
BOOST_TEST(toml::find_fuzzy(v, "key") == toml::value("value"));
BOOST_CHECK_THROW(toml::find_fuzzy(v, "kiwi"), std::out_of_range);
static_assert(std::is_same<
toml::value const&, decltype(toml::find_fuzzy(v, "key"))>::value, "");
}
{
toml::value v{
{"keu", "value"} // typo! key -> keu
};
BOOST_TEST(toml::find_fuzzy(std::move(v), "key") == toml::value("value"));
static_assert(std::is_same<
toml::value&&, decltype(toml::find_fuzzy(std::move(v), "key"))>::value, "");
}
{
toml::value v{
{"keu", "value"} // typo! key -> keu
};
BOOST_CHECK_THROW(toml::find_fuzzy(std::move(v), "kiwi"), std::out_of_range);
static_assert(std::is_same<
toml::value&&, decltype(toml::find_fuzzy(std::move(v), "key"))>::value, "");
}
// find with conversion
{
toml::value v{
{"keu", 42} // typo! key -> keu
};
BOOST_TEST(toml::find_fuzzy<int>(v, "key") == 42);
BOOST_CHECK_THROW(toml::find_fuzzy<int>(v, "kiwi"), std::out_of_range);
static_assert(std::is_same<int,
decltype(toml::find_fuzzy<int>(v, "key"))>::value, "");
}
{
const toml::value v{
{"keu", 42} // typo! key -> keu
};
BOOST_TEST(toml::find_fuzzy<int>(v, "key") == 42);
BOOST_CHECK_THROW(toml::find_fuzzy<int>(v, "kiwi"), std::out_of_range);
static_assert(std::is_same<int,
decltype(toml::find_fuzzy<int>(v, "key"))>::value, "");
}
{
toml::value v{
{"keu", 42} // typo! key -> keu
};
BOOST_TEST(toml::find_fuzzy<int>(std::move(v), "key") == 42);
static_assert(std::is_same<int,
decltype(toml::find_fuzzy<int>(std::move(v), "key"))>::value, "");
}
{
toml::value v{
{"keu", 42} // typo! key -> keu
};
BOOST_CHECK_THROW(toml::find_fuzzy<int>(std::move(v), "kiwi"), std::out_of_range);
}
}
BOOST_AUTO_TEST_CASE(test_find_fuzzy_throw)
{
{
toml::value v{
{"keu", "value"}, // typo! key -> keu
{"ky", "value"} // typo! key -> ky
};
BOOST_CHECK_THROW(toml::find_fuzzy(v, "key"), std::out_of_range);
}
{
const toml::value v{
{"keu", "value"}, // typo! key -> keu
{"ky", "value"} // typo! key -> ky
};
BOOST_CHECK_THROW(toml::find_fuzzy(v, "key"), std::out_of_range);
}
{
toml::value v{
{"keu", "value"}, // typo! key -> keu
{"ky", "value"} // typo! key -> ky
};
BOOST_CHECK_THROW(toml::find_fuzzy(std::move(v), "key"), std::out_of_range);
}
{
toml::value v{
{"keu", 42}, // typo! key -> keu
{"ky", 42} // typo! key -> ky
};
BOOST_CHECK_THROW(toml::find_fuzzy<int>(v, "key"), std::out_of_range);
}
{
const toml::value v{
{"keu", 42}, // typo! key -> keu
{"ky", 42} // typo! key -> ky
};
BOOST_CHECK_THROW(toml::find_fuzzy<int>(v, "key"), std::out_of_range);
}
{
toml::value v{
{"keu", 42}, // typo! key -> keu
{"ky", 42} // typo! key -> ky
};
BOOST_CHECK_THROW(toml::find_fuzzy<int>(std::move(v), "key"), std::out_of_range);
}
}
BOOST_AUTO_TEST_CASE(test_find_throw_typo_aware_exception)
{
using namespace toml::literals::toml_literals;
const toml::levenstein_matcher lev(1);
{
toml::value v = u8R"(
keu = "value"
)"_toml;
BOOST_CHECK_THROW(toml::find(v, "key", lev), std::out_of_range);
try
{
const auto& ret = toml::find(v, "key", lev);
(void)ret; // suppress unused variable
}
catch(const std::out_of_range& oor)
{
// exception.what() should include the typo-ed key name
const std::string what(oor.what());
BOOST_TEST(what.find("keu") != std::string::npos);
// std::cout << what << std::endl;
}
static_assert(std::is_same<
toml::value&, decltype(toml::find(v, "key"))>::value, "");
}
{
const toml::value v = u8R"(
keu = "value"
)"_toml;
BOOST_CHECK_THROW(toml::find(v, "key", lev), std::out_of_range);
try
{
const auto& ret = toml::find(v, "key", lev);
(void)ret;
}
catch(const std::out_of_range& oor)
{
// exception.what() should include the typo-ed key name
const std::string what(oor.what());
BOOST_TEST(what.find("keu") != std::string::npos);
// std::cout << what << std::endl;
}
static_assert(std::is_same<
toml::value const&, decltype(toml::find(v, "key"))>::value, "");
}
{
toml::value v = u8R"(
keu = "value"
)"_toml;
bool thrown = false; // since it moves, we need to check both once
try
{
const auto& ret = toml::find(std::move(v), "key", lev);
(void)ret;
}
catch(const std::out_of_range& oor)
{
// exception.what() should include the typo-ed key name
const std::string what(oor.what());
BOOST_TEST(what.find("keu") != std::string::npos);
thrown = true;
// std::cout << what << std::endl;
}
BOOST_TEST(thrown);
static_assert(std::is_same<
toml::value&, decltype(toml::find(v, "key"))>::value, "");
}
}
BOOST_AUTO_TEST_CASE(test_find_throw_conversion_typo_aware_exception)
{
using namespace toml::literals::toml_literals;
const toml::levenstein_matcher lev(1);
{
toml::value v = u8R"(
keu = 42
)"_toml;
BOOST_CHECK_THROW(toml::find<int>(v, "key", lev), std::out_of_range);
try
{
const auto& ret = toml::find<int>(v, "key", lev);
(void)ret; // suppress unused variable
}
catch(const std::out_of_range& oor)
{
// exception.what() should include the typo-ed key name
const std::string what(oor.what());
BOOST_TEST(what.find("keu") != std::string::npos);
// std::cout << what << std::endl;
}
static_assert(std::is_same<int,
decltype(toml::find<int>(v, "key"))>::value, "");
}
{
const toml::value v = u8R"(
keu = 42
)"_toml;
BOOST_CHECK_THROW(toml::find<int>(v, "key", lev), std::out_of_range);
try
{
const auto& ret = toml::find<int>(v, "key", lev);
(void)ret;
}
catch(const std::out_of_range& oor)
{
// exception.what() should include the typo-ed key name
const std::string what(oor.what());
BOOST_TEST(what.find("keu") != std::string::npos);
// std::cout << what << std::endl;
}
static_assert(std::is_same<int,
decltype(toml::find<int>(v, "key"))>::value, "");
}
{
toml::value v = u8R"(
keu = 42
)"_toml;
bool thrown = false; // since it moves, we need to check both once
try
{
const auto& ret = toml::find<int>(std::move(v), "key", lev);
(void)ret;
}
catch(const std::out_of_range& oor)
{
// exception.what() should include the typo-ed key name
const std::string what(oor.what());
BOOST_TEST(what.find("keu") != std::string::npos);
thrown = true;
// std::cout << what << std::endl;
}
BOOST_TEST(thrown);
static_assert(std::is_same<int,
decltype(toml::find<int>(v, "key"))>::value, "");
}
}

View File

@@ -358,3 +358,36 @@ BOOST_AUTO_TEST_CASE(test_find_or_string)
BOOST_TEST("bazqux" == toml::find_or(v2, "key", lit)); BOOST_TEST("bazqux" == toml::find_or(v2, "key", lit));
} }
} }
BOOST_AUTO_TEST_CASE(test_find_or_map)
{
using map_type = std::map<std::string, std::string>;
{
const toml::value v1{
{"key", {{"key", "value"}}}
};
const auto key = toml::find_or(v1, "key", map_type{});
const auto key2 = toml::find_or(v1, "key2", map_type{});
BOOST_TEST(!key.empty());
BOOST_TEST(key2.empty());
BOOST_TEST(key.size() == 1u);
BOOST_TEST(key.at("key") == "value");
}
{
const toml::value v1{
{"key", {{"key", "value"}}}
};
const auto key = toml::find_or<map_type>(v1, "key", map_type{});
const auto key2 = toml::find_or<map_type>(v1, "key2", map_type{});
BOOST_TEST(!key.empty());
BOOST_TEST(key2.empty());
BOOST_TEST(key.size() == 1u);
BOOST_TEST(key.at("key") == "value");
}
}

View File

@@ -6,6 +6,7 @@
#include <boost/test/included/unit_test.hpp> #include <boost/test/included/unit_test.hpp>
#endif #endif
#include <toml.hpp> #include <toml.hpp>
#include <iostream>
// to check it successfully compiles. it does not check the formatted string. // to check it successfully compiles. it does not check the formatted string.

View File

@@ -45,6 +45,16 @@ BOOST_AUTO_TEST_CASE(test_file_as_literal)
b = "baz" b = "baz"
)"_toml; )"_toml;
BOOST_TEST(r == v);
}
{
const toml::value r{
{"array_of_tables", toml::array{toml::table{}}}
};
const toml::value v = u8R"(
[[array_of_tables]]
)"_toml;
BOOST_TEST(r == v); BOOST_TEST(r == v);
} }
} }

View File

@@ -37,5 +37,6 @@
#include "toml/literal.hpp" #include "toml/literal.hpp"
#include "toml/serializer.hpp" #include "toml/serializer.hpp"
#include "toml/get.hpp" #include "toml/get.hpp"
#include "toml/find.hpp"
#endif// TOML_FOR_MODERN_CPP #endif// TOML_FOR_MODERN_CPP

786
toml/find.hpp Normal file
View File

@@ -0,0 +1,786 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_FIND_HPP
#define TOML11_FIND_HPP
#include "get.hpp"
#include <numeric>
namespace toml
{
// ----------------------------------------------------------------------------
// these overloads do not require to set T. and returns value itself.
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V> const& find(const basic_value<C, M, V>& v, const key& ky)
{
const auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>& find(basic_value<C, M, V>& v, const key& ky)
{
auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>&& find(basic_value<C, M, V>&& v, const key& ky)
{
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return std::move(tab.at(ky));
}
// ----------------------------------------------------------------------------
// find<T>(value, key);
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V> const&>()))
find(const basic_value<C, M, V>& v, const key& ky)
{
const auto& tab = v.as_table();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(tab.at(ky));
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&>()))
find(basic_value<C, M, V>& v, const key& ky)
{
auto& tab = v.as_table();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(tab.at(ky));
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&&>()))
find(basic_value<C, M, V>&& v, const key& ky)
{
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(std::move(tab.at(ky)));
}
// --------------------------------------------------------------------------
// toml::find(toml::value, toml::key, Ts&& ... keys)
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
detail::enable_if_t<detail::conjunction<std::is_convertible<Ts, std::string>...
>::value, const basic_value<C, M, V>&>
find(const basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
detail::enable_if_t<detail::conjunction<std::is_convertible<Ts, std::string>...
>::value, basic_value<C, M, V>&>
find(basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
detail::enable_if_t<detail::conjunction<std::is_convertible<Ts, std::string>...
>::value, basic_value<C, M, V>&&>
find(basic_value<C, M, V>&& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find(::toml::find(std::move(v), ky), std::forward<Ts>(keys)...);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
detail::enable_if_t<detail::conjunction<std::is_convertible<Ts, std::string>...
>::value, decltype(get<T>(std::declval<const basic_value<C, M, V>&>()))>
find(const basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find<T>(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
detail::enable_if_t<detail::conjunction<std::is_convertible<Ts, std::string>...
>::value, decltype(get<T>(std::declval<basic_value<C, M, V>&>()))>
find(basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find<T>(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
detail::enable_if_t<detail::conjunction<std::is_convertible<Ts, std::string>...
>::value, decltype(get<T>(std::declval<basic_value<C, M, V>&&>()))>
find(basic_value<C, M, V>&& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find<T>(::toml::find(std::move(v), ky), std::forward<Ts>(keys)...);
}
// ===========================================================================
// find_or(value, key, fallback)
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V> const&
find_or(const basic_value<C, M, V>& v, const key& ky,
const basic_value<C, M, V>& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>&
find_or(basic_value<C, M, V>& v, const toml::key& ky, basic_value<C, M, V>& opt)
{
if(!v.is_table()) {return opt;}
auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return tab[ky];
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>
find_or(basic_value<C, M, V>&& v, const toml::key& ky, basic_value<C, M, V>&& opt)
{
if(!v.is_table()) {return std::move(opt);}
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0) {return std::move(opt);}
return std::move(tab[ky]);
}
// ---------------------------------------------------------------------------
// exact types (return type can be a reference)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_exact_toml_type<T, basic_value<C, M, V>>::value, T> const&
find_or(const basic_value<C, M, V>& v, const key& ky, const T& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_exact_toml_type<T, basic_value<C, M, V>>::value, T>&
find_or(basic_value<C, M, V>& v, const toml::key& ky, T& opt)
{
if(!v.is_table()) {return opt;}
auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab[ky], opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_exact_toml_type<T, basic_value<C, M, V>>::value, T>&&
find_or(basic_value<C, M, V>&& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return std::forward<T>(opt);}
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0) {return std::forward<T>(opt);}
return get_or(std::move(tab[ky]), std::forward<T>(opt));
}
// ---------------------------------------------------------------------------
// std::string (return type can be a reference)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<std::is_same<T, std::string>::value, std::string> const&
find_or(const basic_value<C, M, V>& v, const key& ky, const T& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<std::is_same<T, std::string>::value, std::string>&
find_or(basic_value<C, M, V>& v, const toml::key& ky, T& opt)
{
if(!v.is_table()) {return opt;}
auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<std::is_same<T, std::string>::value, std::string>
find_or(basic_value<C, M, V>&& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return std::forward<T>(opt);}
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0) {return std::forward<T>(opt);}
return get_or(std::move(tab.at(ky)), std::forward<T>(opt));
}
// ---------------------------------------------------------------------------
// string literal (deduced as std::string)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_string_literal<typename std::remove_reference<T>::type>::value,
std::string>
find_or(const basic_value<C, M, V>& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return std::string(opt);}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return std::string(opt);}
return get_or(tab.at(ky), std::forward<T>(opt));
}
// ---------------------------------------------------------------------------
// others (require type conversion and return type cannot be lvalue reference)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<detail::conjunction<
// T is not an exact toml type
detail::negation<detail::is_exact_toml_type<
typename std::remove_cv<typename std::remove_reference<T>::type>::type,
basic_value<C, M, V>>>,
// T is not std::string
detail::negation<std::is_same<std::string,
typename std::remove_cv<typename std::remove_reference<T>::type>::type>>,
// T is not a string literal
detail::negation<detail::is_string_literal<
typename std::remove_reference<T>::type>>
>::value, typename std::remove_cv<typename std::remove_reference<T>::type>::type>
find_or(const basic_value<C, M, V>& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return std::forward<T>(opt);}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return std::forward<T>(opt);}
return get_or(tab.at(ky), std::forward<T>(opt));
}
// ============================================================================
// expect
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
result<T, std::string> expect(const basic_value<C, M, V>& v) noexcept
{
try
{
return ok(get<T>(v));
}
catch(const std::exception& e)
{
return err(e.what());
}
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
result<T, std::string>
expect(const basic_value<C, M, V>& v, const toml::key& k) noexcept
{
try
{
return ok(find<T>(v, k));
}
catch(const std::exception& e)
{
return err(e.what());
}
}
template<typename T, typename Table>
detail::enable_if_t<detail::conjunction<
detail::is_map<Table>, detail::is_basic_value<typename Table::mapped_type>
>::value, result<T, std::string>>
expect(const Table& t, const toml::key& k,
std::string tablename = "unknown table") noexcept
{
try
{
return ok(find<T>(t, k, std::move(tablename)));
}
catch(const std::exception& e)
{
return err(e.what());
}
}
// ===========================================================================
// find_fuzzy
// ---------------------------------------------------------------------------
// default fuzzy matcher; levenstein distance (all cost is 1)
struct levenstein_matcher
{
levenstein_matcher(): tolerance(1) {}
levenstein_matcher(const std::uint32_t tol): tolerance(tol) {}
~levenstein_matcher() = default;
levenstein_matcher(levenstein_matcher const&) = default;
levenstein_matcher(levenstein_matcher &&) = default;
levenstein_matcher& operator=(levenstein_matcher const&) = default;
levenstein_matcher& operator=(levenstein_matcher &&) = default;
template<typename charT, typename traitsT, typename Alloc1, typename Alloc2>
bool operator()(const std::basic_string<charT, traitsT, Alloc1>& lhs,
const std::basic_string<charT, traitsT, Alloc2>& rhs) const
{
return this->distance(lhs, rhs) <= this->tolerance;
}
template<typename charT, typename traitsT, typename Alloc1, typename Alloc2>
std::uint32_t distance(
const std::basic_string<charT, traitsT, Alloc1>& lhs,
const std::basic_string<charT, traitsT, Alloc2>& rhs) const
{
// force `lhs.size() <= rhs.size()`
if(lhs.size() > rhs.size()) {return this->distance(rhs, lhs);}
std::vector<std::uint32_t> matrix(lhs.size() + 1u);
std::iota(matrix.begin(), matrix.end(), 0);
for(const charT r : rhs)
{
std::uint32_t prev_diag = matrix.front();
matrix.front() += 1;
for(std::size_t i=0; i<lhs.size(); ++i)
{
const charT l = lhs[i];
if(traitsT::eq(l, r))
{
std::swap(matrix[i+1], prev_diag);
}
else
{
const auto tmp = matrix[i+1];
matrix[i+1] = std::min(prev_diag, std::min(matrix[i], matrix[i+1])) + 1;
prev_diag = tmp;
}
}
}
return matrix.back();
}
private:
std::uint32_t tolerance;
};
// ---------------------------------------------------------------------------
// toml::find_fuzzy<T>(v, "tablename", FuzzyMatcher);
namespace detail
{
template<typename Iterator, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
Iterator find_unique(
Iterator iter, const Iterator end, const basic_value<C, M, V>& v,
const toml::key& k, const FuzzyMatcher& match)
{
Iterator found = end;
for(; iter != end; ++iter)
{
if(match(iter->first, k))
{
if(found != end)
{
throw std::out_of_range(detail::format_underline(
concat_to_string("[error] key \"", k, "\" not found."),
{
{std::addressof(detail::get_region(v)),"in this table"},
{std::addressof(detail::get_region(found->second)),
"did you mean this here?"},
{std::addressof(detail::get_region(iter->second)),
"or this?"}
}));
}
found = iter;
}
}
return found;
}
} // detail
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher = levenstein_matcher>
auto find_fuzzy(const basic_value<C, M, V>& v, const key& ky,
const FuzzyMatcher match = levenstein_matcher(1))
-> decltype(find<T>(std::declval<const basic_value<C, M, V>&>(), ky))
{
try
{
return find<T>(v, ky);
}
catch(const std::out_of_range& oor)
{
const auto& t = v.as_table();
const auto found = detail::find_unique(t.begin(), t.end(), v, ky, match);
if(found != t.end())
{
return get<T>(found->second);
}
throw;
}
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher = levenstein_matcher>
auto find_fuzzy(basic_value<C, M, V>& v, const key& ky,
const FuzzyMatcher match = levenstein_matcher(1))
-> decltype(find<T>(std::declval<basic_value<C, M, V>&>(), ky))
{
try
{
return find<T>(v, ky);
}
catch(const std::out_of_range& oor)
{
auto& t = v.as_table();
const auto found = detail::find_unique(t.begin(), t.end(), v, ky, match);
if(found != t.end())
{
return get<T>(found->second);
}
throw;
}
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher = levenstein_matcher>
auto find_fuzzy(basic_value<C, M, V>&& v_, const key& ky,
const FuzzyMatcher match = levenstein_matcher(1))
-> decltype(find<T>(std::declval<basic_value<C, M, V>&&>(), ky))
{
basic_value<C, M, V> v = v_; // to re-use later, store it once
try
{
return std::move(find<T>(v, ky)); // pass lref, move later
}
catch(const std::out_of_range& oor)
{
auto& t = v.as_table(); // because v is used here
const auto found = detail::find_unique(t.begin(), t.end(), v, ky, match);
if(found != t.end())
{
return get<T>(std::move(found->second));
}
throw;
}
}
// ---------------------------------------------------------------------------
// no-template-argument case (by default, return toml::value).
// toml::find_fuzzy(v, "tablename", FuzzyMatcher);
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher = levenstein_matcher>
basic_value<C, M, V> const&
find_fuzzy(const basic_value<C, M, V>& v, const key& ky,
const FuzzyMatcher match = levenstein_matcher(1))
{
try
{
return find(v, ky);
}
catch(const std::out_of_range& oor)
{
const auto& t = v.as_table();
const auto found = detail::find_unique(t.begin(), t.end(), v, ky, match);
if(found != t.end())
{
return found->second;
}
throw;
}
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher = levenstein_matcher>
basic_value<C, M, V>&
find_fuzzy(basic_value<C, M, V>& v, const key& ky,
const FuzzyMatcher match = levenstein_matcher(1))
{
try
{
return find(v, ky);
}
catch(const std::out_of_range& oor)
{
auto& t = v.as_table();
const auto found = detail::find_unique(t.begin(), t.end(), v, ky, match);
if(found != t.end())
{
return found->second;
}
throw;
}
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher = levenstein_matcher>
basic_value<C, M, V>&&
find_fuzzy(basic_value<C, M, V>&& v_, const key& ky,
const FuzzyMatcher match = levenstein_matcher(1))
{
basic_value<C, M, V> v = v_; // to re-use later, store it once
try
{
return std::move(find(v, ky));
}
catch(const std::out_of_range& oor)
{
auto& t = v.as_table();
const auto found = detail::find_unique(t.begin(), t.end(), v, ky, match);
if(found != t.end())
{
return std::move(found->second);
}
throw;
}
}
// ===========================================================================
// find(v, k, matcher)
//
// when matcher is passed, check a key that matches exists or not. if it exists,
// suggest that in the error message
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
basic_value<C, M, V> const&
find(const basic_value<C, M, V>& v, const key& ky, FuzzyMatcher match)
{
const auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
for(const auto& kv : tab)
{
if(match(kv.first, ky))
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found."), {
{std::addressof(detail::get_region(v)), "in this table"},
{std::addressof(detail::get_region(kv.second)),
"did you mean this?"}
}));
}
}
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
basic_value<C, M, V>&
find(basic_value<C, M, V>& v, const key& ky, FuzzyMatcher match)
{
auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
for(const auto& kv : tab)
{
if(match(kv.first, ky))
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found."), {
{std::addressof(detail::get_region(v)), "in this table"},
{std::addressof(detail::get_region(kv.second)),
"did you mean this?"}
}));
}
}
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
basic_value<C, M, V>&&
find(basic_value<C, M, V>&& v, const key& ky, FuzzyMatcher match)
{
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0)
{
for(const auto& kv : tab)
{
if(match(kv.first, ky))
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found."), {
{std::addressof(detail::get_region(v)), "in this table"},
{std::addressof(detail::get_region(kv.second)),
"did you mean this?"}
}));
}
}
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return std::move(tab.at(ky));
}
// ----------------------------------------------------------------------------
// find<T>(value, key, fuzzy_matcher);
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
detail::enable_if_t<
detail::negation<std::is_convertible<FuzzyMatcher, std::string>>::value,
decltype(::toml::get<T>(std::declval<basic_value<C, M, V> const&>()))>
find(const basic_value<C, M, V>& v, const key& ky, FuzzyMatcher match)
{
const auto& tab = v.as_table();
if(tab.count(ky) == 0)
{
for(const auto& kv : tab)
{
if(match(kv.first, ky))
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found."), {
{std::addressof(detail::get_region(v)), "in this table"},
{std::addressof(detail::get_region(kv.second)),
"did you mean this here?"}
}));
}
}
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(tab.at(ky));
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
detail::enable_if_t<
detail::negation<std::is_convertible<FuzzyMatcher, std::string>>::value,
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&>()))>
find(basic_value<C, M, V>& v, const key& ky, FuzzyMatcher match)
{
auto& tab = v.as_table();
if(tab.count(ky) == 0)
{
for(const auto& kv : tab)
{
if(match(kv.first, ky))
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found."), {
{std::addressof(detail::get_region(v)), "in this table"},
{std::addressof(detail::get_region(kv.second)),
"did you mean this here?"}
}));
}
}
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(tab.at(ky));
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename FuzzyMatcher>
detail::enable_if_t<
detail::negation<std::is_convertible<FuzzyMatcher, std::string>>::value,
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&&>()))>
find(basic_value<C, M, V>&& v, const key& ky, FuzzyMatcher match)
{
auto tab = v.as_table();
if(tab.count(ky) == 0)
{
for(const auto& kv : tab)
{
if(match(kv.first, ky))
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found."), {
{std::addressof(detail::get_region(v)), "in this table"},
{std::addressof(detail::get_region(kv.second)),
"did you mean this here?"}
}));
}
}
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(std::move(tab.at(ky)));
}
} // toml
#endif// TOML11_FIND_HPP

View File

@@ -420,161 +420,31 @@ T get(const basic_value<C, M, V>& v)
return ::toml::from<T>::from_toml(v); return ::toml::from<T>::from_toml(v);
} }
// ============================================================================
// find and get
// ----------------------------------------------------------------------------
// these overloads do not require to set T. and returns value itself.
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V> const& find(const basic_value<C, M, V>& v, const key& ky)
{
const auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>& find(basic_value<C, M, V>& v, const key& ky)
{
auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return tab.at(ky);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>&& find(basic_value<C, M, V>&& v, const key& ky)
{
auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return std::move(tab.at(ky));
}
// ----------------------------------------------------------------------------
// find<T>(value, key);
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V> const&>()))
find(const basic_value<C, M, V>& v, const key& ky)
{
const auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(tab.at(ky));
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&>()))
find(basic_value<C, M, V>& v, const key& ky)
{
auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(tab.at(ky));
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&&>()))
find(basic_value<C, M, V>&& v, const key& ky)
{
auto& tab = v.template cast<value_t::table>();
if(tab.count(ky) == 0)
{
throw std::out_of_range(detail::format_underline(concat_to_string(
"[error] key \"", ky, "\" not found"), {
{std::addressof(detail::get_region(v)), "in this table"}
}));
}
return ::toml::get<T>(std::move(tab.at(ky)));
}
// --------------------------------------------------------------------------
// toml::find(toml::value, toml::key, Ts&& ... keys)
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
const basic_value<C, M, V>&
find(const basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
basic_value<C, M, V>&
find(basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
basic_value<C, M, V>&&
find(basic_value<C, M, V>&& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find(::toml::find(std::move(v), ky), std::forward<Ts>(keys)...);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
decltype(::toml::get<T>(std::declval<const basic_value<C, M, V>&>()))
find(const basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find<T>(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&>()))
find(basic_value<C, M, V>& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find<T>(::toml::find(v, ky), std::forward<Ts>(keys)...);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V,
typename ... Ts>
decltype(::toml::get<T>(std::declval<basic_value<C, M, V>&&>()))
find(basic_value<C, M, V>&& v, const ::toml::key& ky, Ts&& ... keys)
{
return ::toml::find<T>(::toml::find(std::move(v), ky), std::forward<Ts>(keys)...);
}
// ============================================================================ // ============================================================================
// get_or(value, fallback) // get_or(value, fallback)
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V> const&
get_or(const basic_value<C, M, V>& v, const basic_value<C, M, V>&)
{
return v;
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>&
get_or(basic_value<C, M, V>& v, basic_value<C, M, V>&)
{
return v;
}
template<typename C,
template<typename ...> class M, template<typename ...> class V>
basic_value<C, M, V>
get_or(basic_value<C, M, V>&& v, basic_value<C, M, V>&&)
{
return v;
}
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// specialization for the exact toml types (return type becomes lvalue ref) // specialization for the exact toml types (return type becomes lvalue ref)
@@ -723,162 +593,5 @@ get_or(const basic_value<C, M, V>& v, T&& opt)
} }
} }
// ===========================================================================
// find_or(value, key, fallback)
// ---------------------------------------------------------------------------
// exact types (return type can be a reference)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_exact_toml_type<T, basic_value<C, M, V>>::value, T> const&
find_or(const basic_value<C, M, V>& v, const key& ky, const T& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_exact_toml_type<T, basic_value<C, M, V>>::value, T>&
find_or(basic_value<C, M, V>& v, const toml::key& ky, T& opt)
{
if(!v.is_table()) {return opt;}
auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab[ky], opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_exact_toml_type<T, basic_value<C, M, V>>::value, T>&&
find_or(basic_value<C, M, V>&& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return opt;}
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(std::move(tab[ky]), std::forward<T>(opt));
}
// ---------------------------------------------------------------------------
// std::string (return type can be a reference)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<std::is_same<T, std::string>::value, std::string> const&
find_or(const basic_value<C, M, V>& v, const key& ky, const T& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<std::is_same<T, std::string>::value, std::string>&
find_or(basic_value<C, M, V>& v, const toml::key& ky, T& opt)
{
if(!v.is_table()) {return opt;}
auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), opt);
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<std::is_same<T, std::string>::value, std::string>
find_or(basic_value<C, M, V>&& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return std::forward<T>(opt);}
auto tab = std::move(v).as_table();
if(tab.count(ky) == 0) {return std::forward<T>(opt);}
return get_or(std::move(tab.at(ky)), std::forward<T>(opt));
}
// ---------------------------------------------------------------------------
// string literal (deduced as std::string)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<
detail::is_string_literal<typename std::remove_reference<T>::type>::value,
std::string>
find_or(const basic_value<C, M, V>& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return std::string(opt);}
return get_or(tab.at(ky), std::forward<T>(opt));
}
// ---------------------------------------------------------------------------
// others (require type conversion and return type cannot be lvalue reference)
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
detail::enable_if_t<detail::conjunction<
detail::negation<detail::is_exact_toml_type<
typename std::remove_cv<typename std::remove_reference<T>::type>::type,
basic_value<C, M, V>>>,
detail::negation<std::is_same<std::string,
typename std::remove_cv<typename std::remove_reference<T>::type>::type>>,
detail::negation<detail::is_string_literal<
typename std::remove_reference<T>::type>>
>::value, T>
find_or(const basic_value<C, M, V>& v, const toml::key& ky, T&& opt)
{
if(!v.is_table()) {return opt;}
const auto& tab = v.as_table();
if(tab.count(ky) == 0) {return opt;}
return get_or(tab.at(ky), std::forward<T>(opt));
}
// ============================================================================
// expect
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
result<T, std::string> expect(const basic_value<C, M, V>& v) noexcept
{
try
{
return ok(get<T>(v));
}
catch(const std::exception& e)
{
return err(e.what());
}
}
template<typename T, typename C,
template<typename ...> class M, template<typename ...> class V>
result<T, std::string>
expect(const basic_value<C, M, V>& v, const toml::key& k) noexcept
{
try
{
return ok(find<T>(v, k));
}
catch(const std::exception& e)
{
return err(e.what());
}
}
template<typename T, typename Table>
detail::enable_if_t<detail::conjunction<
detail::is_map<Table>, detail::is_basic_value<typename Table::mapped_type>
>::value, result<T, std::string>>
expect(const Table& t, const toml::key& k,
std::string tablename = "unknown table") noexcept
{
try
{
return ok(find<T>(t, k, std::move(tablename)));
}
catch(const std::exception& e)
{
return err(e.what());
}
}
} // toml } // toml
#endif// TOML11_GET #endif// TOML11_GET

View File

@@ -115,7 +115,8 @@ using lex_local_time = lex_partial_time;
// =========================================================================== // ===========================================================================
using lex_quotation_mark = character<'"'>; using lex_quotation_mark = character<'"'>;
using lex_basic_unescaped = exclude<either<in_range<0x00, 0x1F>, using lex_basic_unescaped = exclude<either<in_range<0x00, 0x08>, // 0x09 (tab)
in_range<0x0a, 0x1F>, // is allowed
character<0x22>, character<0x5C>, character<0x22>, character<0x5C>,
character<0x7F>>>; character<0x7F>>>;
using lex_escape = character<'\\'>; using lex_escape = character<'\\'>;
@@ -137,7 +138,8 @@ using lex_basic_string = sequence<lex_quotation_mark,
lex_quotation_mark>; lex_quotation_mark>;
using lex_ml_basic_string_delim = repeat<lex_quotation_mark, exactly<3>>; using lex_ml_basic_string_delim = repeat<lex_quotation_mark, exactly<3>>;
using lex_ml_basic_unescaped = exclude<either<in_range<0x00, 0x1F>, using lex_ml_basic_unescaped = exclude<either<in_range<0x00, 0x08>, // 0x09
in_range<0x0a, 0x1F>, // is tab
character<0x5C>, character<0x5C>,
character<0x7F>, character<0x7F>,
lex_ml_basic_string_delim>>; lex_ml_basic_string_delim>>;

View File

@@ -8,7 +8,8 @@
#include "lexer.hpp" #include "lexer.hpp"
#include "types.hpp" #include "types.hpp"
#include "value.hpp" #include "value.hpp"
#include <iostream> #include <fstream>
#include <sstream>
#include <cstring> #include <cstring>
namespace toml namespace toml
@@ -1750,6 +1751,7 @@ parse_ml_table(location<Container>& loc)
using skip_line = repeat< using skip_line = repeat<
sequence<maybe<lex_ws>, maybe<lex_comment>, lex_newline>, at_least<1>>; sequence<maybe<lex_ws>, maybe<lex_comment>, lex_newline>, at_least<1>>;
skip_line::invoke(loc); skip_line::invoke(loc);
lex_ws::invoke(loc);
table_type tab; table_type tab;
while(loc.iter() != loc.end()) while(loc.iter() != loc.end())