header_utils
Loading...
Searching...
No Matches
string_interpolate.h
1
4
5#pragma once
6
7#include "eval.h"
8#include "sexps.h"
9#include "json_helpers.h"
10
11namespace ghassanpl
12{
13 template <typename FUNC>
14 std::string interpolate_simple(std::string_view str, FUNC&& func)
15 {
16 static_assert(std::invocable<FUNC, std::string_view> && std::constructible_from<std::string, std::invoke_result_t<FUNC, std::string_view>>, "function must take a stringable and return a string");
17 std::string result;
18 while (!str.empty())
19 {
20 result += string_ops::consume_until_delim(str, '[');
21 if (str.empty()) break;
22 if (string_ops::consume(str, '['))
23 result += '[';
24 else
25 {
26 auto key = string_ops::consume_until_delim(str, ']');
27 result += func(key);
28 }
29 }
30 return result;
31 }
32
33 template <bool SYNTAX>
34 std::string interpolate_eval(std::string_view str, eval::environment<SYNTAX>& env)
35 {
36 std::string result;
37 while (!str.empty())
38 {
39 result += string_ops::consume_until(str, '[');
40 if (str.empty()) break;
41 str.remove_prefix(1);
42 if (string_ops::consume(str, '['))
43 result += '[';
44 else
45 {
46 using eval::value;
48 value call_result = env.eval(call);
50 using std::to_string;
51 using nlohmann::to_string;
52 using ghassanpl::string_ops::to_string;
53 if constexpr (requires { { to_string(val) }; })
54 result += to_string(val);
55 });
56 }
57 }
58 return result;
59 }
60
62}
constexpr auto bit_count
Equal to the number of bits in the type.
Definition bits.h:33
auto visit(nlohmann::json const &j, VISIT_FUNC &&func)
Calls func with the actual value inside j; similar to std::visit
std::string_view consume_until(std::string_view &str, FUNC &&pred)
Consumes characters from the beginning of str until one matches pred(str[0]), exclusive.
Definition string_ops.h:788
char consume(std::string_view &str)
Consumes and returns the first character in the str, or \0 if no more characters.
Definition string_ops.h:652
std::string_view consume_until_delim(std::string_view &str, char c)
Consumes characters from the beginning of str until one is equal to c, inclusive.
Definition string_ops.h:844
auto consume_list(std::string_view &sexp_str, std::array< char, 2 > braces={ '[', ']' }) -> nlohmann::json
Consumes space-delimited elements until close-brace or end-of-string.
Definition sexps.h:91
Primary namespace for everything in this library.
Definition align+rec2.h:10