From 434a775202e6f3605f923d2f0a28a9ade0408a4d Mon Sep 17 00:00:00 2001 From: Tindy X <49061470+tindy2013@users.noreply.github.com> Date: Wed, 15 Nov 2023 17:59:09 +0800 Subject: [PATCH] Update local dependencies --- include/inja.hpp | 2687 ++---- include/jpcre2.hpp | 98 +- include/nlohmann/json.hpp | 11600 ++++++++++--------------- src/generator/template/templates.cpp | 4 +- 4 files changed, 5424 insertions(+), 8965 deletions(-) diff --git a/include/inja.hpp b/include/inja.hpp index c8ee88893..d8a9744b0 100644 --- a/include/inja.hpp +++ b/include/inja.hpp @@ -1,10 +1,10 @@ /* - ___ _ Version 3.3 + ___ _ Version 3.4.0 |_ _|_ __ (_) __ _ https://github.com/pantor/inja | || '_ \ | |/ _` | Licensed under the MIT License . | || | | || | (_| | - |___|_| |_|/ |\__,_| Copyright (c) 2018-2021 Lars Berscheid - |__/ + |___|_| |_|/ |\__,_| Copyright (c) 2018-2023 Lars Berscheid + |__/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights @@ -25,1464 +25,49 @@ SOFTWARE. #ifndef INCLUDE_INJA_INJA_HPP_ #define INCLUDE_INJA_INJA_HPP_ -#include +#include "nlohmann/json.hpp" namespace inja { #ifndef INJA_DATA_TYPE - using json = nlohmann::json; +using json = nlohmann::json; #else - using json = INJA_DATA_TYPE; +using json = INJA_DATA_TYPE; #endif -} - -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(INJA_NOEXCEPTION) - #ifndef INJA_THROW - #define INJA_THROW(exception) throw exception - #endif -#else - #include - #ifndef INJA_THROW - #define INJA_THROW(exception) std::abort(); std::ignore = exception - #endif - #ifndef INJA_NOEXCEPTION - #define INJA_NOEXCEPTION - #endif -#endif - -// #include "environment.hpp" -#ifndef INCLUDE_INJA_ENVIRONMENT_HPP_ -#define INCLUDE_INJA_ENVIRONMENT_HPP_ - -#include -#include -#include -#include -#include - -// #include "config.hpp" -#ifndef INCLUDE_INJA_CONFIG_HPP_ -#define INCLUDE_INJA_CONFIG_HPP_ - -#include -#include - -// #include "string_view.hpp" -// Copyright 2017-2019 by Martin Moene -// -// string-view lite, a C++17-like string_view for C++98 and later. -// For more information see https://github.com/martinmoene/string-view-lite -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - - -#ifndef NONSTD_SV_LITE_H_INCLUDED -#define NONSTD_SV_LITE_H_INCLUDED - -#define string_view_lite_MAJOR 1 -#define string_view_lite_MINOR 4 -#define string_view_lite_PATCH 0 - -#define string_view_lite_VERSION \ - nssv_STRINGIFY(string_view_lite_MAJOR) "." nssv_STRINGIFY(string_view_lite_MINOR) "." nssv_STRINGIFY( \ - string_view_lite_PATCH) - -#define nssv_STRINGIFY(x) nssv_STRINGIFY_(x) -#define nssv_STRINGIFY_(x) #x - -// string-view lite configuration: - -#define nssv_STRING_VIEW_DEFAULT 0 -#define nssv_STRING_VIEW_NONSTD 1 -#define nssv_STRING_VIEW_STD 2 - -#if !defined(nssv_CONFIG_SELECT_STRING_VIEW) -#define nssv_CONFIG_SELECT_STRING_VIEW (nssv_HAVE_STD_STRING_VIEW ? nssv_STRING_VIEW_STD : nssv_STRING_VIEW_NONSTD) -#endif - -#if defined(nssv_CONFIG_SELECT_STD_STRING_VIEW) || defined(nssv_CONFIG_SELECT_NONSTD_STRING_VIEW) -#error nssv_CONFIG_SELECT_STD_STRING_VIEW and nssv_CONFIG_SELECT_NONSTD_STRING_VIEW are deprecated and removed, please use nssv_CONFIG_SELECT_STRING_VIEW=nssv_STRING_VIEW_... -#endif - -#ifndef nssv_CONFIG_STD_SV_OPERATOR -#define nssv_CONFIG_STD_SV_OPERATOR 0 -#endif - -#ifndef nssv_CONFIG_USR_SV_OPERATOR -#define nssv_CONFIG_USR_SV_OPERATOR 1 -#endif - -#ifdef nssv_CONFIG_CONVERSION_STD_STRING -#define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS nssv_CONFIG_CONVERSION_STD_STRING -#define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS nssv_CONFIG_CONVERSION_STD_STRING -#endif - -#ifndef nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS -#define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS 1 -#endif - -#ifndef nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -#define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS 1 -#endif - -// Control presence of exception handling (try and auto discover): - -#ifndef nssv_CONFIG_NO_EXCEPTIONS -#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND) -#define nssv_CONFIG_NO_EXCEPTIONS 0 -#else -#define nssv_CONFIG_NO_EXCEPTIONS 1 -#endif -#endif - -// C++ language version detection (C++20 is speculative): -// Note: VC14.0/1900 (VS2015) lacks too much from C++14. - -#ifndef nssv_CPLUSPLUS -#if defined(_MSVC_LANG) && !defined(__clang__) -#define nssv_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG) -#else -#define nssv_CPLUSPLUS __cplusplus -#endif -#endif - -#define nssv_CPP98_OR_GREATER (nssv_CPLUSPLUS >= 199711L) -#define nssv_CPP11_OR_GREATER (nssv_CPLUSPLUS >= 201103L) -#define nssv_CPP11_OR_GREATER_ (nssv_CPLUSPLUS >= 201103L) -#define nssv_CPP14_OR_GREATER (nssv_CPLUSPLUS >= 201402L) -#define nssv_CPP17_OR_GREATER (nssv_CPLUSPLUS >= 201703L) -#define nssv_CPP20_OR_GREATER (nssv_CPLUSPLUS >= 202000L) - -// use C++17 std::string_view if available and requested: - -#if nssv_CPP17_OR_GREATER && defined(__has_include) -#if __has_include( ) -#define nssv_HAVE_STD_STRING_VIEW 1 -#else -#define nssv_HAVE_STD_STRING_VIEW 0 -#endif -#else -#define nssv_HAVE_STD_STRING_VIEW 0 -#endif - -#define nssv_USES_STD_STRING_VIEW \ - ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_STD) || \ - ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_DEFAULT) && nssv_HAVE_STD_STRING_VIEW)) - -#define nssv_HAVE_STARTS_WITH (nssv_CPP20_OR_GREATER || !nssv_USES_STD_STRING_VIEW) -#define nssv_HAVE_ENDS_WITH nssv_HAVE_STARTS_WITH - -// -// Use C++17 std::string_view: -// - -#if nssv_USES_STD_STRING_VIEW - -#include - -// Extensions for std::string: - -#if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS - -namespace nonstd { - -template > -std::basic_string to_string(std::basic_string_view v, - Allocator const &a = Allocator()) { - return std::basic_string(v.begin(), v.end(), a); -} - -template -std::basic_string_view to_string_view(std::basic_string const &s) { - return std::basic_string_view(s.data(), s.size()); -} - -// Literal operators sv and _sv: - -#if nssv_CONFIG_STD_SV_OPERATOR - -using namespace std::literals::string_view_literals; - -#endif - -#if nssv_CONFIG_USR_SV_OPERATOR - -inline namespace literals { -inline namespace string_view_literals { - -constexpr std::string_view operator"" _sv(const char *str, size_t len) noexcept // (1) -{ - return std::string_view {str, len}; -} - -constexpr std::u16string_view operator"" _sv(const char16_t *str, size_t len) noexcept // (2) -{ - return std::u16string_view {str, len}; -} - -constexpr std::u32string_view operator"" _sv(const char32_t *str, size_t len) noexcept // (3) -{ - return std::u32string_view {str, len}; -} - -constexpr std::wstring_view operator"" _sv(const wchar_t *str, size_t len) noexcept // (4) -{ - return std::wstring_view {str, len}; -} - -} // namespace string_view_literals -} // namespace literals - -#endif // nssv_CONFIG_USR_SV_OPERATOR - -} // namespace nonstd - -#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS - -namespace nonstd { - -using std::basic_string_view; -using std::string_view; -using std::u16string_view; -using std::u32string_view; -using std::wstring_view; - -// literal "sv" and "_sv", see above - -using std::operator==; -using std::operator!=; -using std::operator<; -using std::operator<=; -using std::operator>; -using std::operator>=; - -using std::operator<<; - -} // namespace nonstd - -#else // nssv_HAVE_STD_STRING_VIEW - -// -// Before C++17: use string_view lite: -// - -// Compiler versions: -// -// MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0) -// MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002) -// MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003) -// MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) -// MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) -// MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) -// MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) -// MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) -// MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) -// MSVC++ 14.1 _MSC_VER >= 1910 (Visual Studio 2017) - -#if defined(_MSC_VER) && !defined(__clang__) -#define nssv_COMPILER_MSVC_VER (_MSC_VER) -#define nssv_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * (5 + (_MSC_VER < 1900))) -#else -#define nssv_COMPILER_MSVC_VER 0 -#define nssv_COMPILER_MSVC_VERSION 0 -#endif - -#define nssv_COMPILER_VERSION(major, minor, patch) (10 * (10 * (major) + (minor)) + (patch)) - -#if defined(__clang__) -#define nssv_COMPILER_CLANG_VERSION nssv_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) -#else -#define nssv_COMPILER_CLANG_VERSION 0 -#endif - -#if defined(__GNUC__) && !defined(__clang__) -#define nssv_COMPILER_GNUC_VERSION nssv_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#else -#define nssv_COMPILER_GNUC_VERSION 0 -#endif - -// half-open range [lo..hi): -#define nssv_BETWEEN(v, lo, hi) ((lo) <= (v) && (v) < (hi)) - -// Presence of language and library features: - -#ifdef _HAS_CPP0X -#define nssv_HAS_CPP0X _HAS_CPP0X -#else -#define nssv_HAS_CPP0X 0 -#endif - -// Unless defined otherwise below, consider VC14 as C++11 for variant-lite: - -#if nssv_COMPILER_MSVC_VER >= 1900 -#undef nssv_CPP11_OR_GREATER -#define nssv_CPP11_OR_GREATER 1 -#endif - -#define nssv_CPP11_90 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1500) -#define nssv_CPP11_100 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1600) -#define nssv_CPP11_110 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1700) -#define nssv_CPP11_120 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1800) -#define nssv_CPP11_140 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1900) -#define nssv_CPP11_141 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1910) - -#define nssv_CPP14_000 (nssv_CPP14_OR_GREATER) -#define nssv_CPP17_000 (nssv_CPP17_OR_GREATER) - -// Presence of C++11 language features: - -#define nssv_HAVE_CONSTEXPR_11 nssv_CPP11_140 -#define nssv_HAVE_EXPLICIT_CONVERSION nssv_CPP11_140 -#define nssv_HAVE_INLINE_NAMESPACE nssv_CPP11_140 -#define nssv_HAVE_NOEXCEPT nssv_CPP11_140 -#define nssv_HAVE_NULLPTR nssv_CPP11_100 -#define nssv_HAVE_REF_QUALIFIER nssv_CPP11_140 -#define nssv_HAVE_UNICODE_LITERALS nssv_CPP11_140 -#define nssv_HAVE_USER_DEFINED_LITERALS nssv_CPP11_140 -#define nssv_HAVE_WCHAR16_T nssv_CPP11_100 -#define nssv_HAVE_WCHAR32_T nssv_CPP11_100 - -#if !((nssv_CPP11_OR_GREATER && nssv_COMPILER_CLANG_VERSION) || nssv_BETWEEN(nssv_COMPILER_CLANG_VERSION, 300, 400)) -#define nssv_HAVE_STD_DEFINED_LITERALS nssv_CPP11_140 -#else -#define nssv_HAVE_STD_DEFINED_LITERALS 0 -#endif - -// Presence of C++14 language features: - -#define nssv_HAVE_CONSTEXPR_14 nssv_CPP14_000 - -// Presence of C++17 language features: - -#define nssv_HAVE_NODISCARD nssv_CPP17_000 - -// Presence of C++ library features: - -#define nssv_HAVE_STD_HASH nssv_CPP11_120 - -// C++ feature usage: - -#if nssv_HAVE_CONSTEXPR_11 -#define nssv_constexpr constexpr -#else -#define nssv_constexpr /*constexpr*/ -#endif - -#if nssv_HAVE_CONSTEXPR_14 -#define nssv_constexpr14 constexpr -#else -#define nssv_constexpr14 /*constexpr*/ -#endif - -#if nssv_HAVE_EXPLICIT_CONVERSION -#define nssv_explicit explicit -#else -#define nssv_explicit /*explicit*/ -#endif - -#if nssv_HAVE_INLINE_NAMESPACE -#define nssv_inline_ns inline -#else -#define nssv_inline_ns /*inline*/ -#endif - -#if nssv_HAVE_NOEXCEPT -#define nssv_noexcept noexcept -#else -#define nssv_noexcept /*noexcept*/ -#endif - -//#if nssv_HAVE_REF_QUALIFIER -//# define nssv_ref_qual & -//# define nssv_refref_qual && -//#else -//# define nssv_ref_qual /*&*/ -//# define nssv_refref_qual /*&&*/ -//#endif - -#if nssv_HAVE_NULLPTR -#define nssv_nullptr nullptr -#else -#define nssv_nullptr NULL -#endif - -#if nssv_HAVE_NODISCARD -#define nssv_nodiscard [[nodiscard]] -#else -#define nssv_nodiscard /*[[nodiscard]]*/ -#endif - -// Additional includes: - -#include -#include -#include -#include -#include -#include // std::char_traits<> - -#if !nssv_CONFIG_NO_EXCEPTIONS -#include -#endif - -#if nssv_CPP11_OR_GREATER -#include -#endif - -// Clang, GNUC, MSVC warning suppression macros: - -#if defined(__clang__) -#pragma clang diagnostic ignored "-Wreserved-user-defined-literal" -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wuser-defined-literals" -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wliteral-suffix" -#endif // __clang__ - -#if nssv_COMPILER_MSVC_VERSION >= 140 -#define nssv_SUPPRESS_MSGSL_WARNING(expr) [[gsl::suppress(expr)]] -#define nssv_SUPPRESS_MSVC_WARNING(code, descr) __pragma(warning(suppress : code)) -#define nssv_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable : codes)) -#else -#define nssv_SUPPRESS_MSGSL_WARNING(expr) -#define nssv_SUPPRESS_MSVC_WARNING(code, descr) -#define nssv_DISABLE_MSVC_WARNINGS(codes) -#endif - -#if defined(__clang__) -#define nssv_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") -#elif defined(__GNUC__) -#define nssv_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") -#elif nssv_COMPILER_MSVC_VERSION >= 140 -#define nssv_RESTORE_WARNINGS() __pragma(warning(pop)) -#else -#define nssv_RESTORE_WARNINGS() -#endif - -// Suppress the following MSVC (GSL) warnings: -// - C4455, non-gsl : 'operator ""sv': literal suffix identifiers that do not -// start with an underscore are reserved -// - C26472, gsl::t.1 : don't use a static_cast for arithmetic conversions; -// use brace initialization, gsl::narrow_cast or gsl::narow -// - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead - -nssv_DISABLE_MSVC_WARNINGS(4455 26481 26472) - // nssv_DISABLE_CLANG_WARNINGS( "-Wuser-defined-literals" ) - // nssv_DISABLE_GNUC_WARNINGS( -Wliteral-suffix ) - - namespace nonstd { - namespace sv_lite { - -#if nssv_CPP11_OR_GREATER - - namespace detail { - - // Expect tail call optimization to make length() non-recursive: - - template inline constexpr std::size_t length(CharT *s, std::size_t result = 0) { - return *s == '\0' ? result : length(s + 1, result + 1); - } - - } // namespace detail - -#endif // nssv_CPP11_OR_GREATER - - template > class basic_string_view; - - // - // basic_string_view: - // - - template */ - > - class basic_string_view { - public: - // Member types: - - typedef Traits traits_type; - typedef CharT value_type; - - typedef CharT *pointer; - typedef CharT const *const_pointer; - typedef CharT &reference; - typedef CharT const &const_reference; - - typedef const_pointer iterator; - typedef const_pointer const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - - // 24.4.2.1 Construction and assignment: - - nssv_constexpr basic_string_view() nssv_noexcept : data_(nssv_nullptr), size_(0) {} - -#if nssv_CPP11_OR_GREATER - nssv_constexpr basic_string_view(basic_string_view const &other) nssv_noexcept = default; -#else - nssv_constexpr basic_string_view(basic_string_view const &other) nssv_noexcept : data_(other.data_), - size_(other.size_) {} -#endif - - nssv_constexpr basic_string_view(CharT const *s, size_type count) nssv_noexcept // non-standard noexcept - : data_(s), - size_(count) {} - - nssv_constexpr basic_string_view(CharT const *s) nssv_noexcept // non-standard noexcept - : data_(s) -#if nssv_CPP17_OR_GREATER - , - size_(Traits::length(s)) -#elif nssv_CPP11_OR_GREATER - , - size_(detail::length(s)) -#else - , - size_(Traits::length(s)) -#endif - { - } - - // Assignment: - -#if nssv_CPP11_OR_GREATER - nssv_constexpr14 basic_string_view &operator=(basic_string_view const &other) nssv_noexcept = default; -#else - nssv_constexpr14 basic_string_view &operator=(basic_string_view const &other) nssv_noexcept { - data_ = other.data_; - size_ = other.size_; - return *this; - } -#endif - - // 24.4.2.2 Iterator support: - - nssv_constexpr const_iterator begin() const nssv_noexcept { return data_; } - nssv_constexpr const_iterator end() const nssv_noexcept { return data_ + size_; } - - nssv_constexpr const_iterator cbegin() const nssv_noexcept { return begin(); } - nssv_constexpr const_iterator cend() const nssv_noexcept { return end(); } - - nssv_constexpr const_reverse_iterator rbegin() const nssv_noexcept { return const_reverse_iterator(end()); } - nssv_constexpr const_reverse_iterator rend() const nssv_noexcept { return const_reverse_iterator(begin()); } - - nssv_constexpr const_reverse_iterator crbegin() const nssv_noexcept { return rbegin(); } - nssv_constexpr const_reverse_iterator crend() const nssv_noexcept { return rend(); } - - // 24.4.2.3 Capacity: - - nssv_constexpr size_type size() const nssv_noexcept { return size_; } - nssv_constexpr size_type length() const nssv_noexcept { return size_; } - nssv_constexpr size_type max_size() const nssv_noexcept { return (std::numeric_limits::max)(); } - - // since C++20 - nssv_nodiscard nssv_constexpr bool empty() const nssv_noexcept { return 0 == size_; } - - // 24.4.2.4 Element access: - - nssv_constexpr const_reference operator[](size_type pos) const { return data_at(pos); } - - nssv_constexpr14 const_reference at(size_type pos) const { -#if nssv_CONFIG_NO_EXCEPTIONS - assert(pos < size()); -#else - if (pos >= size()) { - throw std::out_of_range("nonstd::string_view::at()"); - } -#endif - return data_at(pos); - } - - nssv_constexpr const_reference front() const { return data_at(0); } - nssv_constexpr const_reference back() const { return data_at(size() - 1); } - - nssv_constexpr const_pointer data() const nssv_noexcept { return data_; } - - // 24.4.2.5 Modifiers: - - nssv_constexpr14 void remove_prefix(size_type n) { - assert(n <= size()); - data_ += n; - size_ -= n; - } - - nssv_constexpr14 void remove_suffix(size_type n) { - assert(n <= size()); - size_ -= n; - } - - nssv_constexpr14 void swap(basic_string_view &other) nssv_noexcept { - using std::swap; - swap(data_, other.data_); - swap(size_, other.size_); - } - - // 24.4.2.6 String operations: - - size_type copy(CharT *dest, size_type n, size_type pos = 0) const { -#if nssv_CONFIG_NO_EXCEPTIONS - assert(pos <= size()); -#else - if (pos > size()) { - throw std::out_of_range("nonstd::string_view::copy()"); - } -#endif - const size_type rlen = (std::min)(n, size() - pos); - - (void)Traits::copy(dest, data() + pos, rlen); - - return rlen; - } - - nssv_constexpr14 basic_string_view substr(size_type pos = 0, size_type n = npos) const { -#if nssv_CONFIG_NO_EXCEPTIONS - assert(pos <= size()); -#else - if (pos > size()) { - throw std::out_of_range("nonstd::string_view::substr()"); - } -#endif - return basic_string_view(data() + pos, (std::min)(n, size() - pos)); - } - - // compare(), 6x: - - nssv_constexpr14 int compare(basic_string_view other) const nssv_noexcept // (1) - { - if (const int result = Traits::compare(data(), other.data(), (std::min)(size(), other.size()))) { - return result; - } - - return size() == other.size() ? 0 : size() < other.size() ? -1 : 1; - } - - nssv_constexpr int compare(size_type pos1, size_type n1, basic_string_view other) const // (2) - { - return substr(pos1, n1).compare(other); - } - - nssv_constexpr int compare(size_type pos1, size_type n1, basic_string_view other, size_type pos2, - size_type n2) const // (3) - { - return substr(pos1, n1).compare(other.substr(pos2, n2)); - } - - nssv_constexpr int compare(CharT const *s) const // (4) - { - return compare(basic_string_view(s)); - } - - nssv_constexpr int compare(size_type pos1, size_type n1, CharT const *s) const // (5) - { - return substr(pos1, n1).compare(basic_string_view(s)); - } - - nssv_constexpr int compare(size_type pos1, size_type n1, CharT const *s, size_type n2) const // (6) - { - return substr(pos1, n1).compare(basic_string_view(s, n2)); - } - - // 24.4.2.7 Searching: - - // starts_with(), 3x, since C++20: - - nssv_constexpr bool starts_with(basic_string_view v) const nssv_noexcept // (1) - { - return size() >= v.size() && compare(0, v.size(), v) == 0; - } - - nssv_constexpr bool starts_with(CharT c) const nssv_noexcept // (2) - { - return starts_with(basic_string_view(&c, 1)); - } - - nssv_constexpr bool starts_with(CharT const *s) const // (3) - { - return starts_with(basic_string_view(s)); - } - - // ends_with(), 3x, since C++20: - - nssv_constexpr bool ends_with(basic_string_view v) const nssv_noexcept // (1) - { - return size() >= v.size() && compare(size() - v.size(), npos, v) == 0; - } - - nssv_constexpr bool ends_with(CharT c) const nssv_noexcept // (2) - { - return ends_with(basic_string_view(&c, 1)); - } - - nssv_constexpr bool ends_with(CharT const *s) const // (3) - { - return ends_with(basic_string_view(s)); - } - - // find(), 4x: - - nssv_constexpr14 size_type find(basic_string_view v, size_type pos = 0) const nssv_noexcept // (1) - { - return assert(v.size() == 0 || v.data() != nssv_nullptr), - pos >= size() ? npos : to_pos(std::search(cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq)); - } - - nssv_constexpr14 size_type find(CharT c, size_type pos = 0) const nssv_noexcept // (2) - { - return find(basic_string_view(&c, 1), pos); - } - - nssv_constexpr14 size_type find(CharT const *s, size_type pos, size_type n) const // (3) - { - return find(basic_string_view(s, n), pos); - } - - nssv_constexpr14 size_type find(CharT const *s, size_type pos = 0) const // (4) - { - return find(basic_string_view(s), pos); - } - - // rfind(), 4x: - - nssv_constexpr14 size_type rfind(basic_string_view v, size_type pos = npos) const nssv_noexcept // (1) - { - if (size() < v.size()) { - return npos; - } - - if (v.empty()) { - return (std::min)(size(), pos); - } - - const_iterator last = cbegin() + (std::min)(size() - v.size(), pos) + v.size(); - const_iterator result = std::find_end(cbegin(), last, v.cbegin(), v.cend(), Traits::eq); - - return result != last ? size_type(result - cbegin()) : npos; - } - - nssv_constexpr14 size_type rfind(CharT c, size_type pos = npos) const nssv_noexcept // (2) - { - return rfind(basic_string_view(&c, 1), pos); - } - - nssv_constexpr14 size_type rfind(CharT const *s, size_type pos, size_type n) const // (3) - { - return rfind(basic_string_view(s, n), pos); - } - - nssv_constexpr14 size_type rfind(CharT const *s, size_type pos = npos) const // (4) - { - return rfind(basic_string_view(s), pos); - } - - // find_first_of(), 4x: - - nssv_constexpr size_type find_first_of(basic_string_view v, size_type pos = 0) const nssv_noexcept // (1) - { - return pos >= size() ? npos - : to_pos(std::find_first_of(cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq)); - } - - nssv_constexpr size_type find_first_of(CharT c, size_type pos = 0) const nssv_noexcept // (2) - { - return find_first_of(basic_string_view(&c, 1), pos); - } - - nssv_constexpr size_type find_first_of(CharT const *s, size_type pos, size_type n) const // (3) - { - return find_first_of(basic_string_view(s, n), pos); - } - - nssv_constexpr size_type find_first_of(CharT const *s, size_type pos = 0) const // (4) - { - return find_first_of(basic_string_view(s), pos); - } - - // find_last_of(), 4x: - - nssv_constexpr size_type find_last_of(basic_string_view v, size_type pos = npos) const nssv_noexcept // (1) - { - return empty() ? npos - : pos >= size() ? find_last_of(v, size() - 1) - : to_pos(std::find_first_of(const_reverse_iterator(cbegin() + pos + 1), crend(), - v.cbegin(), v.cend(), Traits::eq)); - } - - nssv_constexpr size_type find_last_of(CharT c, size_type pos = npos) const nssv_noexcept // (2) - { - return find_last_of(basic_string_view(&c, 1), pos); - } - - nssv_constexpr size_type find_last_of(CharT const *s, size_type pos, size_type count) const // (3) - { - return find_last_of(basic_string_view(s, count), pos); - } - - nssv_constexpr size_type find_last_of(CharT const *s, size_type pos = npos) const // (4) - { - return find_last_of(basic_string_view(s), pos); - } - - // find_first_not_of(), 4x: - - nssv_constexpr size_type find_first_not_of(basic_string_view v, size_type pos = 0) const nssv_noexcept // (1) - { - return pos >= size() ? npos : to_pos(std::find_if(cbegin() + pos, cend(), not_in_view(v))); - } - - nssv_constexpr size_type find_first_not_of(CharT c, size_type pos = 0) const nssv_noexcept // (2) - { - return find_first_not_of(basic_string_view(&c, 1), pos); - } - - nssv_constexpr size_type find_first_not_of(CharT const *s, size_type pos, size_type count) const // (3) - { - return find_first_not_of(basic_string_view(s, count), pos); - } - - nssv_constexpr size_type find_first_not_of(CharT const *s, size_type pos = 0) const // (4) - { - return find_first_not_of(basic_string_view(s), pos); - } - - // find_last_not_of(), 4x: - - nssv_constexpr size_type find_last_not_of(basic_string_view v, size_type pos = npos) const nssv_noexcept // (1) - { - return empty() ? npos - : pos >= size() - ? find_last_not_of(v, size() - 1) - : to_pos(std::find_if(const_reverse_iterator(cbegin() + pos + 1), crend(), not_in_view(v))); - } - - nssv_constexpr size_type find_last_not_of(CharT c, size_type pos = npos) const nssv_noexcept // (2) - { - return find_last_not_of(basic_string_view(&c, 1), pos); - } - - nssv_constexpr size_type find_last_not_of(CharT const *s, size_type pos, size_type count) const // (3) - { - return find_last_not_of(basic_string_view(s, count), pos); - } - - nssv_constexpr size_type find_last_not_of(CharT const *s, size_type pos = npos) const // (4) - { - return find_last_not_of(basic_string_view(s), pos); - } - - // Constants: - -#if nssv_CPP17_OR_GREATER - static nssv_constexpr size_type npos = size_type(-1); -#elif nssv_CPP11_OR_GREATER - enum : size_type { npos = size_type(-1) }; -#else - enum { npos = size_type(-1) }; -#endif - - private: - struct not_in_view { - const basic_string_view v; - - nssv_constexpr explicit not_in_view(basic_string_view v) : v(v) {} - - nssv_constexpr bool operator()(CharT c) const { return npos == v.find_first_of(c); } - }; - - nssv_constexpr size_type to_pos(const_iterator it) const { return it == cend() ? npos : size_type(it - cbegin()); } - - nssv_constexpr size_type to_pos(const_reverse_iterator it) const { - return it == crend() ? npos : size_type(crend() - it - 1); - } - - nssv_constexpr const_reference data_at(size_type pos) const { -#if nssv_BETWEEN(nssv_COMPILER_GNUC_VERSION, 1, 500) - return data_[pos]; -#else - return assert(pos < size()), data_[pos]; -#endif - } - - private: - const_pointer data_; - size_type size_; - - public: -#if nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS - - template - basic_string_view(std::basic_string const &s) nssv_noexcept : data_(s.data()), - size_(s.size()) {} - -#if nssv_HAVE_EXPLICIT_CONVERSION - - template explicit operator std::basic_string() const { - return to_string(Allocator()); - } - -#endif // nssv_HAVE_EXPLICIT_CONVERSION - -#if nssv_CPP11_OR_GREATER - - template > - std::basic_string to_string(Allocator const &a = Allocator()) const { - return std::basic_string(begin(), end(), a); - } - -#else - - std::basic_string to_string() const { return std::basic_string(begin(), end()); } - - template std::basic_string to_string(Allocator const &a) const { - return std::basic_string(begin(), end(), a); - } - -#endif // nssv_CPP11_OR_GREATER - -#endif // nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS - }; - - // - // Non-member functions: - // - - // 24.4.3 Non-member comparison functions: - // lexicographically compare two string views (function template): - - template - nssv_constexpr bool operator==(basic_string_view lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) == 0; - } - - template - nssv_constexpr bool operator!=(basic_string_view lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) != 0; - } - - template - nssv_constexpr bool operator<(basic_string_view lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) < 0; - } - - template - nssv_constexpr bool operator<=(basic_string_view lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) <= 0; - } - - template - nssv_constexpr bool operator>(basic_string_view lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) > 0; - } - - template - nssv_constexpr bool operator>=(basic_string_view lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) >= 0; - } - - // Let S be basic_string_view, and sv be an instance of S. - // Implementations shall provide sufficient additional overloads marked - // constexpr and noexcept so that an object t with an implicit conversion - // to S can be compared according to Table 67. - -#if !nssv_CPP11_OR_GREATER || nssv_BETWEEN(nssv_COMPILER_MSVC_VERSION, 100, 141) - - // accomodate for older compilers: - - // == - - template - nssv_constexpr bool operator==(basic_string_view lhs, char const *rhs) nssv_noexcept { - return lhs.compare(rhs) == 0; - } - - template - nssv_constexpr bool operator==(char const *lhs, basic_string_view rhs) nssv_noexcept { - return rhs.compare(lhs) == 0; - } - - template - nssv_constexpr bool operator==(basic_string_view lhs, - std::basic_string rhs) nssv_noexcept { - return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; - } - - template - nssv_constexpr bool operator==(std::basic_string rhs, - basic_string_view lhs) nssv_noexcept { - return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; - } - - // != - - template - nssv_constexpr bool operator!=(basic_string_view lhs, char const *rhs) nssv_noexcept { - return lhs.compare(rhs) != 0; - } - - template - nssv_constexpr bool operator!=(char const *lhs, basic_string_view rhs) nssv_noexcept { - return rhs.compare(lhs) != 0; - } - - template - nssv_constexpr bool operator!=(basic_string_view lhs, - std::basic_string rhs) nssv_noexcept { - return lhs.size() != rhs.size() && lhs.compare(rhs) != 0; - } - - template - nssv_constexpr bool operator!=(std::basic_string rhs, - basic_string_view lhs) nssv_noexcept { - return lhs.size() != rhs.size() || rhs.compare(lhs) != 0; - } - - // < - - template - nssv_constexpr bool operator<(basic_string_view lhs, char const *rhs) nssv_noexcept { - return lhs.compare(rhs) < 0; - } - - template - nssv_constexpr bool operator<(char const *lhs, basic_string_view rhs) nssv_noexcept { - return rhs.compare(lhs) > 0; - } - - template - nssv_constexpr bool operator<(basic_string_view lhs, - std::basic_string rhs) nssv_noexcept { - return lhs.compare(rhs) < 0; - } - - template - nssv_constexpr bool operator<(std::basic_string rhs, - basic_string_view lhs) nssv_noexcept { - return rhs.compare(lhs) > 0; - } - - // <= - - template - nssv_constexpr bool operator<=(basic_string_view lhs, char const *rhs) nssv_noexcept { - return lhs.compare(rhs) <= 0; - } - - template - nssv_constexpr bool operator<=(char const *lhs, basic_string_view rhs) nssv_noexcept { - return rhs.compare(lhs) >= 0; - } - - template - nssv_constexpr bool operator<=(basic_string_view lhs, - std::basic_string rhs) nssv_noexcept { - return lhs.compare(rhs) <= 0; - } - - template - nssv_constexpr bool operator<=(std::basic_string rhs, - basic_string_view lhs) nssv_noexcept { - return rhs.compare(lhs) >= 0; - } - - // > - - template - nssv_constexpr bool operator>(basic_string_view lhs, char const *rhs) nssv_noexcept { - return lhs.compare(rhs) > 0; - } - - template - nssv_constexpr bool operator>(char const *lhs, basic_string_view rhs) nssv_noexcept { - return rhs.compare(lhs) < 0; - } - - template - nssv_constexpr bool operator>(basic_string_view lhs, - std::basic_string rhs) nssv_noexcept { - return lhs.compare(rhs) > 0; - } - - template - nssv_constexpr bool operator>(std::basic_string rhs, - basic_string_view lhs) nssv_noexcept { - return rhs.compare(lhs) < 0; - } - - // >= - - template - nssv_constexpr bool operator>=(basic_string_view lhs, char const *rhs) nssv_noexcept { - return lhs.compare(rhs) >= 0; - } - - template - nssv_constexpr bool operator>=(char const *lhs, basic_string_view rhs) nssv_noexcept { - return rhs.compare(lhs) <= 0; - } - - template - nssv_constexpr bool operator>=(basic_string_view lhs, - std::basic_string rhs) nssv_noexcept { - return lhs.compare(rhs) >= 0; - } - - template - nssv_constexpr bool operator>=(std::basic_string rhs, - basic_string_view lhs) nssv_noexcept { - return rhs.compare(lhs) <= 0; - } - -#else // newer compilers: - -#define nssv_BASIC_STRING_VIEW_I(T, U) typename std::decay>::type - -#if nssv_BETWEEN(nssv_COMPILER_MSVC_VERSION, 140, 150) -#define nssv_MSVC_ORDER(x) , int = x -#else -#define nssv_MSVC_ORDER(x) /*, int=x*/ -#endif - - // == - - template - nssv_constexpr bool operator==(basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept { - return lhs.compare(rhs) == 0; - } - - template - nssv_constexpr bool operator==(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; - } - - // != - - template - nssv_constexpr bool operator!=(basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept { - return lhs.size() != rhs.size() || lhs.compare(rhs) != 0; - } - - template - nssv_constexpr bool operator!=(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) != 0; - } - - // < - - template - nssv_constexpr bool operator<(basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept { - return lhs.compare(rhs) < 0; - } - - template - nssv_constexpr bool operator<(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) < 0; - } - - // <= - - template - nssv_constexpr bool operator<=(basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept { - return lhs.compare(rhs) <= 0; - } - - template - nssv_constexpr bool operator<=(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) <= 0; - } - - // > - - template - nssv_constexpr bool operator>(basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept { - return lhs.compare(rhs) > 0; - } - - template - nssv_constexpr bool operator>(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) > 0; - } - - // >= - - template - nssv_constexpr bool operator>=(basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept { - return lhs.compare(rhs) >= 0; - } - - template - nssv_constexpr bool operator>=(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs) nssv_noexcept { - return lhs.compare(rhs) >= 0; - } - -#undef nssv_MSVC_ORDER -#undef nssv_BASIC_STRING_VIEW_I - -#endif // compiler-dependent approach to comparisons - - // 24.4.4 Inserters and extractors: - - namespace detail { - - template void write_padding(Stream &os, std::streamsize n) { - for (std::streamsize i = 0; i < n; ++i) - os.rdbuf()->sputc(os.fill()); - } - - template Stream &write_to_stream(Stream &os, View const &sv) { - typename Stream::sentry sentry(os); - - if (!os) - return os; - - const std::streamsize length = static_cast(sv.length()); - - // Whether, and how, to pad: - const bool pad = (length < os.width()); - const bool left_pad = pad && (os.flags() & std::ios_base::adjustfield) == std::ios_base::right; - - if (left_pad) - write_padding(os, os.width() - length); - - // Write span characters: - os.rdbuf()->sputn(sv.begin(), length); - - if (pad && !left_pad) - write_padding(os, os.width() - length); - - // Reset output stream width: - os.width(0); - - return os; - } - - } // namespace detail - - template - std::basic_ostream &operator<<(std::basic_ostream &os, - basic_string_view sv) { - return detail::write_to_stream(os, sv); - } - - // Several typedefs for common character types are provided: - - typedef basic_string_view string_view; - typedef basic_string_view wstring_view; -#if nssv_HAVE_WCHAR16_T - typedef basic_string_view u16string_view; - typedef basic_string_view u32string_view; -#endif - - } // namespace sv_lite -} // namespace nonstd::sv_lite - -// -// 24.4.6 Suffix for basic_string_view literals: -// - -#if nssv_HAVE_USER_DEFINED_LITERALS - -namespace nonstd { -nssv_inline_ns namespace literals { - nssv_inline_ns namespace string_view_literals { - -#if nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS - - nssv_constexpr nonstd::sv_lite::string_view operator"" sv(const char *str, size_t len) nssv_noexcept // (1) - { - return nonstd::sv_lite::string_view {str, len}; - } - - nssv_constexpr nonstd::sv_lite::u16string_view operator"" sv(const char16_t *str, size_t len) nssv_noexcept // (2) - { - return nonstd::sv_lite::u16string_view {str, len}; - } - - nssv_constexpr nonstd::sv_lite::u32string_view operator"" sv(const char32_t *str, size_t len) nssv_noexcept // (3) - { - return nonstd::sv_lite::u32string_view {str, len}; - } - - nssv_constexpr nonstd::sv_lite::wstring_view operator"" sv(const wchar_t *str, size_t len) nssv_noexcept // (4) - { - return nonstd::sv_lite::wstring_view {str, len}; - } - -#endif // nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS - -#if nssv_CONFIG_USR_SV_OPERATOR - - nssv_constexpr nonstd::sv_lite::string_view operator"" _sv(const char *str, size_t len) nssv_noexcept // (1) - { - return nonstd::sv_lite::string_view {str, len}; - } - - nssv_constexpr nonstd::sv_lite::u16string_view operator"" _sv(const char16_t *str, size_t len) nssv_noexcept // (2) - { - return nonstd::sv_lite::u16string_view {str, len}; - } - - nssv_constexpr nonstd::sv_lite::u32string_view operator"" _sv(const char32_t *str, size_t len) nssv_noexcept // (3) - { - return nonstd::sv_lite::u32string_view {str, len}; - } - - nssv_constexpr nonstd::sv_lite::wstring_view operator"" _sv(const wchar_t *str, size_t len) nssv_noexcept // (4) - { - return nonstd::sv_lite::wstring_view {str, len}; - } - -#endif // nssv_CONFIG_USR_SV_OPERATOR - } -} -} // namespace nonstd +} // namespace inja +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(INJA_NOEXCEPTION) +#ifndef INJA_THROW +#define INJA_THROW(exception) throw exception #endif - -// -// Extensions for std::string: -// - -#if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS - -namespace nonstd { -namespace sv_lite { - -// Exclude MSVC 14 (19.00): it yields ambiguous to_string(): - -#if nssv_CPP11_OR_GREATER && nssv_COMPILER_MSVC_VERSION != 140 - -template > -std::basic_string to_string(basic_string_view v, - Allocator const &a = Allocator()) { - return std::basic_string(v.begin(), v.end(), a); -} - #else - -template std::basic_string to_string(basic_string_view v) { - return std::basic_string(v.begin(), v.end()); -} - -template -std::basic_string to_string(basic_string_view v, Allocator const &a) { - return std::basic_string(v.begin(), v.end(), a); -} - -#endif // nssv_CPP11_OR_GREATER - -template -basic_string_view to_string_view(std::basic_string const &s) { - return basic_string_view(s.data(), s.size()); -} - -} // namespace sv_lite -} // namespace nonstd - -#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS - -// -// make types and algorithms available in namespace nonstd: -// - -namespace nonstd { - -using sv_lite::basic_string_view; -using sv_lite::string_view; -using sv_lite::wstring_view; - -#if nssv_HAVE_WCHAR16_T -using sv_lite::u16string_view; +#include +#ifndef INJA_THROW +#define INJA_THROW(exception) \ + std::abort(); \ + std::ignore = exception #endif -#if nssv_HAVE_WCHAR32_T -using sv_lite::u32string_view; +#ifndef INJA_NOEXCEPTION +#define INJA_NOEXCEPTION #endif - -// literal "sv" - -using sv_lite::operator==; -using sv_lite::operator!=; -using sv_lite::operator<; -using sv_lite::operator<=; -using sv_lite::operator>; -using sv_lite::operator>=; - -using sv_lite::operator<<; - -#if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -using sv_lite::to_string; -using sv_lite::to_string_view; #endif -} // namespace nonstd - -// 24.4.5 Hash support (C++11): +// #include "environment.hpp" +#ifndef INCLUDE_INJA_ENVIRONMENT_HPP_ +#define INCLUDE_INJA_ENVIRONMENT_HPP_ -// Note: The hash value of a string view object is equal to the hash value of -// the corresponding string object. +#include +#include +#include +#include +#include +#include -#if nssv_HAVE_STD_HASH +// #include "config.hpp" +#ifndef INCLUDE_INJA_CONFIG_HPP_ +#define INCLUDE_INJA_CONFIG_HPP_ #include - -namespace std { - -template <> struct hash { -public: - std::size_t operator()(nonstd::string_view v) const nssv_noexcept { - return std::hash()(std::string(v.data(), v.size())); - } -}; - -template <> struct hash { -public: - std::size_t operator()(nonstd::wstring_view v) const nssv_noexcept { - return std::hash()(std::wstring(v.data(), v.size())); - } -}; - -template <> struct hash { -public: - std::size_t operator()(nonstd::u16string_view v) const nssv_noexcept { - return std::hash()(std::u16string(v.data(), v.size())); - } -}; - -template <> struct hash { -public: - std::size_t operator()(nonstd::u32string_view v) const nssv_noexcept { - return std::hash()(std::u32string(v.data(), v.size())); - } -}; - -} // namespace std - -#endif // nssv_HAVE_STD_HASH - -nssv_RESTORE_WARNINGS() - -#endif // nssv_HAVE_STD_STRING_VIEW -#endif // NONSTD_SV_LITE_H_INCLUDED +#include // #include "template.hpp" #ifndef INCLUDE_INJA_TEMPLATE_HPP_ @@ -1498,22 +83,21 @@ nssv_RESTORE_WARNINGS() #define INCLUDE_INJA_NODE_HPP_ #include +#include #include // #include "function_storage.hpp" #ifndef INCLUDE_INJA_FUNCTION_STORAGE_HPP_ #define INCLUDE_INJA_FUNCTION_STORAGE_HPP_ +#include #include -// #include "string_view.hpp" - - namespace inja { -using Arguments = std::vector; -using CallbackFunction = std::function; -using VoidCallbackFunction = std::function; +using Arguments = std::vector; +using CallbackFunction = std::function; +using VoidCallbackFunction = std::function; /*! * \brief Class for builtin functions and user-defined callbacks. @@ -1567,13 +151,11 @@ class FunctionStorage { Super, Join, Callback, - ParenLeft, - ParenRight, None, }; struct FunctionData { - explicit FunctionData(const Operation &op, const CallbackFunction &cb = CallbackFunction{}) : operation(op), callback(cb) {} + explicit FunctionData(const Operation& op, const CallbackFunction& cb = CallbackFunction {}): operation(op), callback(cb) {} const Operation operation; const CallbackFunction callback; }; @@ -1582,52 +164,52 @@ class FunctionStorage { const int VARIADIC {-1}; std::map, FunctionData> function_storage = { - {std::make_pair("at", 2), FunctionData { Operation::At }}, - {std::make_pair("default", 2), FunctionData { Operation::Default }}, - {std::make_pair("divisibleBy", 2), FunctionData { Operation::DivisibleBy }}, - {std::make_pair("even", 1), FunctionData { Operation::Even }}, - {std::make_pair("exists", 1), FunctionData { Operation::Exists }}, - {std::make_pair("existsIn", 2), FunctionData { Operation::ExistsInObject }}, - {std::make_pair("first", 1), FunctionData { Operation::First }}, - {std::make_pair("float", 1), FunctionData { Operation::Float }}, - {std::make_pair("int", 1), FunctionData { Operation::Int }}, - {std::make_pair("isArray", 1), FunctionData { Operation::IsArray }}, - {std::make_pair("isBoolean", 1), FunctionData { Operation::IsBoolean }}, - {std::make_pair("isFloat", 1), FunctionData { Operation::IsFloat }}, - {std::make_pair("isInteger", 1), FunctionData { Operation::IsInteger }}, - {std::make_pair("isNumber", 1), FunctionData { Operation::IsNumber }}, - {std::make_pair("isObject", 1), FunctionData { Operation::IsObject }}, - {std::make_pair("isString", 1), FunctionData { Operation::IsString }}, - {std::make_pair("last", 1), FunctionData { Operation::Last }}, - {std::make_pair("length", 1), FunctionData { Operation::Length }}, - {std::make_pair("lower", 1), FunctionData { Operation::Lower }}, - {std::make_pair("max", 1), FunctionData { Operation::Max }}, - {std::make_pair("min", 1), FunctionData { Operation::Min }}, - {std::make_pair("odd", 1), FunctionData { Operation::Odd }}, - {std::make_pair("range", 1), FunctionData { Operation::Range }}, - {std::make_pair("round", 2), FunctionData { Operation::Round }}, - {std::make_pair("sort", 1), FunctionData { Operation::Sort }}, - {std::make_pair("upper", 1), FunctionData { Operation::Upper }}, - {std::make_pair("super", 0), FunctionData { Operation::Super }}, - {std::make_pair("super", 1), FunctionData { Operation::Super }}, - {std::make_pair("join", 2), FunctionData { Operation::Join }}, + {std::make_pair("at", 2), FunctionData {Operation::At}}, + {std::make_pair("default", 2), FunctionData {Operation::Default}}, + {std::make_pair("divisibleBy", 2), FunctionData {Operation::DivisibleBy}}, + {std::make_pair("even", 1), FunctionData {Operation::Even}}, + {std::make_pair("exists", 1), FunctionData {Operation::Exists}}, + {std::make_pair("existsIn", 2), FunctionData {Operation::ExistsInObject}}, + {std::make_pair("first", 1), FunctionData {Operation::First}}, + {std::make_pair("float", 1), FunctionData {Operation::Float}}, + {std::make_pair("int", 1), FunctionData {Operation::Int}}, + {std::make_pair("isArray", 1), FunctionData {Operation::IsArray}}, + {std::make_pair("isBoolean", 1), FunctionData {Operation::IsBoolean}}, + {std::make_pair("isFloat", 1), FunctionData {Operation::IsFloat}}, + {std::make_pair("isInteger", 1), FunctionData {Operation::IsInteger}}, + {std::make_pair("isNumber", 1), FunctionData {Operation::IsNumber}}, + {std::make_pair("isObject", 1), FunctionData {Operation::IsObject}}, + {std::make_pair("isString", 1), FunctionData {Operation::IsString}}, + {std::make_pair("last", 1), FunctionData {Operation::Last}}, + {std::make_pair("length", 1), FunctionData {Operation::Length}}, + {std::make_pair("lower", 1), FunctionData {Operation::Lower}}, + {std::make_pair("max", 1), FunctionData {Operation::Max}}, + {std::make_pair("min", 1), FunctionData {Operation::Min}}, + {std::make_pair("odd", 1), FunctionData {Operation::Odd}}, + {std::make_pair("range", 1), FunctionData {Operation::Range}}, + {std::make_pair("round", 2), FunctionData {Operation::Round}}, + {std::make_pair("sort", 1), FunctionData {Operation::Sort}}, + {std::make_pair("upper", 1), FunctionData {Operation::Upper}}, + {std::make_pair("super", 0), FunctionData {Operation::Super}}, + {std::make_pair("super", 1), FunctionData {Operation::Super}}, + {std::make_pair("join", 2), FunctionData {Operation::Join}}, }; public: - void add_builtin(nonstd::string_view name, int num_args, Operation op) { - function_storage.emplace(std::make_pair(static_cast(name), num_args), FunctionData { op }); + void add_builtin(std::string_view name, int num_args, Operation op) { + function_storage.emplace(std::make_pair(static_cast(name), num_args), FunctionData {op}); } - void add_callback(nonstd::string_view name, int num_args, const CallbackFunction &callback) { - function_storage.emplace(std::make_pair(static_cast(name), num_args), FunctionData { Operation::Callback, callback }); + void add_callback(std::string_view name, int num_args, const CallbackFunction& callback) { + function_storage.emplace(std::make_pair(static_cast(name), num_args), FunctionData {Operation::Callback, callback}); } - FunctionData find_function(nonstd::string_view name, int num_args) const { + FunctionData find_function(std::string_view name, int num_args) const { auto it = function_storage.find(std::make_pair(static_cast(name), num_args)); if (it != function_storage.end()) { return it->second; - // Find variadic function + // Find variadic function } else if (num_args > 0) { it = function_storage.find(std::make_pair(static_cast(name), VARIADIC)); if (it != function_storage.end()) { @@ -1635,7 +217,7 @@ class FunctionStorage { } } - return FunctionData { Operation::None }; + return FunctionData {Operation::None}; } }; @@ -1643,8 +225,6 @@ class FunctionStorage { #endif // INCLUDE_INJA_FUNCTION_STORAGE_HPP_ -// #include "string_view.hpp" - // #include "utils.hpp" #ifndef INCLUDE_INJA_UTILS_HPP_ #define INCLUDE_INJA_UTILS_HPP_ @@ -1652,6 +232,7 @@ class FunctionStorage { #include #include #include +#include #include // #include "exceptions.hpp" @@ -1674,67 +255,64 @@ struct InjaError : public std::runtime_error { const SourceLocation location; - explicit InjaError(const std::string &type, const std::string &message) + explicit InjaError(const std::string& type, const std::string& message) : std::runtime_error("[inja.exception." + type + "] " + message), type(type), message(message), location({0, 0}) {} - explicit InjaError(const std::string &type, const std::string &message, SourceLocation location) - : std::runtime_error("[inja.exception." + type + "] (at " + std::to_string(location.line) + ":" + - std::to_string(location.column) + ") " + message), + explicit InjaError(const std::string& type, const std::string& message, SourceLocation location) + : std::runtime_error("[inja.exception." + type + "] (at " + std::to_string(location.line) + ":" + std::to_string(location.column) + ") " + message), type(type), message(message), location(location) {} }; struct ParserError : public InjaError { - explicit ParserError(const std::string &message, SourceLocation location) : InjaError("parser_error", message, location) {} + explicit ParserError(const std::string& message, SourceLocation location): InjaError("parser_error", message, location) {} }; struct RenderError : public InjaError { - explicit RenderError(const std::string &message, SourceLocation location) : InjaError("render_error", message, location) {} + explicit RenderError(const std::string& message, SourceLocation location): InjaError("render_error", message, location) {} }; struct FileError : public InjaError { - explicit FileError(const std::string &message) : InjaError("file_error", message) {} - explicit FileError(const std::string &message, SourceLocation location) : InjaError("file_error", message, location) {} + explicit FileError(const std::string& message): InjaError("file_error", message) {} + explicit FileError(const std::string& message, SourceLocation location): InjaError("file_error", message, location) {} }; -struct JsonError : public InjaError { - explicit JsonError(const std::string &message, SourceLocation location) : InjaError("json_error", message, location) {} +struct DataError : public InjaError { + explicit DataError(const std::string& message, SourceLocation location): InjaError("data_error", message, location) {} }; } // namespace inja #endif // INCLUDE_INJA_EXCEPTIONS_HPP_ -// #include "string_view.hpp" - namespace inja { namespace string_view { -inline nonstd::string_view slice(nonstd::string_view view, size_t start, size_t end) { +inline std::string_view slice(std::string_view view, size_t start, size_t end) { start = std::min(start, view.size()); end = std::min(std::max(start, end), view.size()); return view.substr(start, end - start); } -inline std::pair split(nonstd::string_view view, char Separator) { +inline std::pair split(std::string_view view, char Separator) { size_t idx = view.find(Separator); - if (idx == nonstd::string_view::npos) { - return std::make_pair(view, nonstd::string_view()); + if (idx == std::string_view::npos) { + return std::make_pair(view, std::string_view()); } - return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, nonstd::string_view::npos)); + return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, std::string_view::npos)); } -inline bool starts_with(nonstd::string_view view, nonstd::string_view prefix) { +inline bool starts_with(std::string_view view, std::string_view prefix) { return (view.size() >= prefix.size() && view.compare(0, prefix.size(), prefix) == 0); } } // namespace string_view -inline SourceLocation get_source_location(nonstd::string_view content, size_t pos) { +inline SourceLocation get_source_location(std::string_view content, size_t pos) { // Get line and offset position (starts at 1:1) auto sliced = string_view::slice(content, 0, pos); std::size_t last_newline = sliced.rfind("\n"); - if (last_newline == nonstd::string_view::npos) { + if (last_newline == std::string_view::npos) { return {1, sliced.length() + 1}; } @@ -1752,14 +330,14 @@ inline SourceLocation get_source_location(nonstd::string_view content, size_t po return {count_lines + 1, sliced.length() - last_newline}; } -inline void replace_substring(std::string& s, const std::string& f, - const std::string& t) -{ - if (f.empty()) return; - for (auto pos = s.find(f); // find first occurrence of f - pos != std::string::npos; // make sure f was found - s.replace(pos, f.size(), t), // replace with t, and - pos = s.find(f, pos + t.size())) // find next occurrence of f +inline void replace_substring(std::string& s, const std::string& f, const std::string& t) { + if (f.empty()) { + return; + } + for (auto pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f {} } @@ -1768,7 +346,6 @@ inline void replace_substring(std::string& s, const std::string& f, #endif // INCLUDE_INJA_UTILS_HPP_ - namespace inja { class NodeVisitor; @@ -1776,7 +353,7 @@ class BlockNode; class TextNode; class ExpressionNode; class LiteralNode; -class JsonNode; +class DataNode; class FunctionNode; class ExpressionListNode; class StatementNode; @@ -1789,7 +366,6 @@ class ExtendsStatementNode; class BlockStatementNode; class SetStatementNode; - class NodeVisitor { public: virtual ~NodeVisitor() = default; @@ -1798,7 +374,7 @@ class NodeVisitor { virtual void visit(const TextNode& node) = 0; virtual void visit(const ExpressionNode& node) = 0; virtual void visit(const LiteralNode& node) = 0; - virtual void visit(const JsonNode& node) = 0; + virtual void visit(const DataNode& node) = 0; virtual void visit(const FunctionNode& node) = 0; virtual void visit(const ExpressionListNode& node) = 0; virtual void visit(const StatementNode& node) = 0; @@ -1821,16 +397,15 @@ class AstNode { size_t pos; - AstNode(size_t pos) : pos(pos) { } - virtual ~AstNode() { } + AstNode(size_t pos): pos(pos) {} + virtual ~AstNode() {} }; - class BlockNode : public AstNode { public: std::vector> nodes; - explicit BlockNode() : AstNode(0) {} + explicit BlockNode(): AstNode(0) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -1841,7 +416,7 @@ class TextNode : public AstNode { public: const size_t length; - explicit TextNode(size_t pos, size_t length): AstNode(pos), length(length) { } + explicit TextNode(size_t pos, size_t length): AstNode(pos), length(length) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -1850,7 +425,7 @@ class TextNode : public AstNode { class ExpressionNode : public AstNode { public: - explicit ExpressionNode(size_t pos) : AstNode(pos) {} + explicit ExpressionNode(size_t pos): AstNode(pos) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -1861,22 +436,22 @@ class LiteralNode : public ExpressionNode { public: const json value; - explicit LiteralNode(const json& value, size_t pos) : ExpressionNode(pos), value(value) { } + explicit LiteralNode(std::string_view data_text, size_t pos): ExpressionNode(pos), value(json::parse(data_text)) {} void accept(NodeVisitor& v) const { v.visit(*this); } }; -class JsonNode : public ExpressionNode { +class DataNode : public ExpressionNode { public: const std::string name; const json::json_pointer ptr; - static std::string convert_dot_to_json_ptr(nonstd::string_view ptr_name) { + static std::string convert_dot_to_ptr(std::string_view ptr_name) { std::string result; do { - nonstd::string_view part; + std::string_view part; std::tie(part, ptr_name) = string_view::split(ptr_name, '.'); result.push_back('/'); result.append(part.begin(), part.end()); @@ -1884,7 +459,7 @@ class JsonNode : public ExpressionNode { return result; } - explicit JsonNode(nonstd::string_view ptr_name, size_t pos) : ExpressionNode(pos), name(ptr_name), ptr(json::json_pointer(convert_dot_to_json_ptr(ptr_name))) { } + explicit DataNode(std::string_view ptr_name, size_t pos): ExpressionNode(pos), name(ptr_name), ptr(json::json_pointer(convert_dot_to_ptr(ptr_name))) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -1906,102 +481,103 @@ class FunctionNode : public ExpressionNode { Op operation; std::string name; - int number_args; // Should also be negative -> -1 for unknown number + int number_args; // Can also be negative -> -1 for unknown number std::vector> arguments; CallbackFunction callback; - explicit FunctionNode(nonstd::string_view name, size_t pos) : ExpressionNode(pos), precedence(8), associativity(Associativity::Left), operation(Op::Callback), name(name), number_args(1) { } - explicit FunctionNode(Op operation, size_t pos) : ExpressionNode(pos), operation(operation), number_args(1) { + explicit FunctionNode(std::string_view name, size_t pos) + : ExpressionNode(pos), precedence(8), associativity(Associativity::Left), operation(Op::Callback), name(name), number_args(0) {} + explicit FunctionNode(Op operation, size_t pos): ExpressionNode(pos), operation(operation), number_args(1) { switch (operation) { - case Op::Not: { - number_args = 1; - precedence = 4; - associativity = Associativity::Left; - } break; - case Op::And: { - number_args = 2; - precedence = 1; - associativity = Associativity::Left; - } break; - case Op::Or: { - number_args = 2; - precedence = 1; - associativity = Associativity::Left; - } break; - case Op::In: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::Equal: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::NotEqual: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::Greater: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::GreaterEqual: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::Less: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::LessEqual: { - number_args = 2; - precedence = 2; - associativity = Associativity::Left; - } break; - case Op::Add: { - number_args = 2; - precedence = 3; - associativity = Associativity::Left; - } break; - case Op::Subtract: { - number_args = 2; - precedence = 3; - associativity = Associativity::Left; - } break; - case Op::Multiplication: { - number_args = 2; - precedence = 4; - associativity = Associativity::Left; - } break; - case Op::Division: { - number_args = 2; - precedence = 4; - associativity = Associativity::Left; - } break; - case Op::Power: { - number_args = 2; - precedence = 5; - associativity = Associativity::Right; - } break; - case Op::Modulo: { - number_args = 2; - precedence = 4; - associativity = Associativity::Left; - } break; - case Op::AtId: { - number_args = 2; - precedence = 8; - associativity = Associativity::Left; - } break; - default: { - precedence = 1; - associativity = Associativity::Left; - } + case Op::Not: { + number_args = 1; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::And: { + number_args = 2; + precedence = 1; + associativity = Associativity::Left; + } break; + case Op::Or: { + number_args = 2; + precedence = 1; + associativity = Associativity::Left; + } break; + case Op::In: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Equal: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::NotEqual: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Greater: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::GreaterEqual: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Less: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::LessEqual: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Add: { + number_args = 2; + precedence = 3; + associativity = Associativity::Left; + } break; + case Op::Subtract: { + number_args = 2; + precedence = 3; + associativity = Associativity::Left; + } break; + case Op::Multiplication: { + number_args = 2; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::Division: { + number_args = 2; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::Power: { + number_args = 2; + precedence = 5; + associativity = Associativity::Right; + } break; + case Op::Modulo: { + number_args = 2; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::AtId: { + number_args = 2; + precedence = 8; + associativity = Associativity::Left; + } break; + default: { + precedence = 1; + associativity = Associativity::Left; + } } } @@ -2014,8 +590,8 @@ class ExpressionListNode : public AstNode { public: std::shared_ptr root; - explicit ExpressionListNode() : AstNode(0) { } - explicit ExpressionListNode(size_t pos) : AstNode(pos) { } + explicit ExpressionListNode(): AstNode(0) {} + explicit ExpressionListNode(size_t pos): AstNode(pos) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -2024,7 +600,7 @@ class ExpressionListNode : public AstNode { class StatementNode : public AstNode { public: - StatementNode(size_t pos) : AstNode(pos) { } + StatementNode(size_t pos): AstNode(pos) {} virtual void accept(NodeVisitor& v) const = 0; }; @@ -2033,9 +609,9 @@ class ForStatementNode : public StatementNode { public: ExpressionListNode condition; BlockNode body; - BlockNode *const parent; + BlockNode* const parent; - ForStatementNode(BlockNode *const parent, size_t pos) : StatementNode(pos), parent(parent) { } + ForStatementNode(BlockNode* const parent, size_t pos): StatementNode(pos), parent(parent) {} virtual void accept(NodeVisitor& v) const = 0; }; @@ -2044,7 +620,7 @@ class ForArrayStatementNode : public ForStatementNode { public: const std::string value; - explicit ForArrayStatementNode(const std::string& value, BlockNode *const parent, size_t pos) : ForStatementNode(parent, pos), value(value) { } + explicit ForArrayStatementNode(const std::string& value, BlockNode* const parent, size_t pos): ForStatementNode(parent, pos), value(value) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -2056,7 +632,8 @@ class ForObjectStatementNode : public ForStatementNode { const std::string key; const std::string value; - explicit ForObjectStatementNode(const std::string& key, const std::string& value, BlockNode *const parent, size_t pos) : ForStatementNode(parent, pos), key(key), value(value) { } + explicit ForObjectStatementNode(const std::string& key, const std::string& value, BlockNode* const parent, size_t pos) + : ForStatementNode(parent, pos), key(key), value(value) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -2068,13 +645,13 @@ class IfStatementNode : public StatementNode { ExpressionListNode condition; BlockNode true_statement; BlockNode false_statement; - BlockNode *const parent; + BlockNode* const parent; const bool is_nested; bool has_false_statement {false}; - explicit IfStatementNode(BlockNode *const parent, size_t pos) : StatementNode(pos), parent(parent), is_nested(false) { } - explicit IfStatementNode(bool is_nested, BlockNode *const parent, size_t pos) : StatementNode(pos), parent(parent), is_nested(is_nested) { } + explicit IfStatementNode(BlockNode* const parent, size_t pos): StatementNode(pos), parent(parent), is_nested(false) {} + explicit IfStatementNode(bool is_nested, BlockNode* const parent, size_t pos): StatementNode(pos), parent(parent), is_nested(is_nested) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -2085,7 +662,7 @@ class IncludeStatementNode : public StatementNode { public: const std::string file; - explicit IncludeStatementNode(const std::string& file, size_t pos) : StatementNode(pos), file(file) { } + explicit IncludeStatementNode(const std::string& file, size_t pos): StatementNode(pos), file(file) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -2096,24 +673,24 @@ class ExtendsStatementNode : public StatementNode { public: const std::string file; - explicit ExtendsStatementNode(const std::string& file, size_t pos) : StatementNode(pos), file(file) { } + explicit ExtendsStatementNode(const std::string& file, size_t pos): StatementNode(pos), file(file) {} void accept(NodeVisitor& v) const { v.visit(*this); - }; + } }; class BlockStatementNode : public StatementNode { public: const std::string name; BlockNode block; - BlockNode *const parent; + BlockNode* const parent; - explicit BlockStatementNode(BlockNode *const parent, const std::string& name, size_t pos) : StatementNode(pos), name(name), parent(parent) { } + explicit BlockStatementNode(BlockNode* const parent, const std::string& name, size_t pos): StatementNode(pos), name(name), parent(parent) {} void accept(NodeVisitor& v) const { v.visit(*this); - }; + } }; class SetStatementNode : public StatementNode { @@ -2121,7 +698,7 @@ class SetStatementNode : public StatementNode { const std::string key; ExpressionListNode expression; - explicit SetStatementNode(const std::string& key, size_t pos) : StatementNode(pos), key(key) { } + explicit SetStatementNode(const std::string& key, size_t pos): StatementNode(pos), key(key) {} void accept(NodeVisitor& v) const { v.visit(*this); @@ -2139,7 +716,6 @@ class SetStatementNode : public StatementNode { // #include "node.hpp" - namespace inja { /*! @@ -2152,11 +728,11 @@ class StatisticsVisitor : public NodeVisitor { } } - void visit(const TextNode&) { } - void visit(const ExpressionNode&) { } - void visit(const LiteralNode&) { } + void visit(const TextNode&) {} + void visit(const ExpressionNode&) {} + void visit(const LiteralNode&) {} - void visit(const JsonNode&) { + void visit(const DataNode&) { variable_counter += 1; } @@ -2170,8 +746,8 @@ class StatisticsVisitor : public NodeVisitor { node.root->accept(*this); } - void visit(const StatementNode&) { } - void visit(const ForStatementNode&) { } + void visit(const StatementNode&) {} + void visit(const ForStatementNode&) {} void visit(const ForArrayStatementNode& node) { node.condition.accept(*this); @@ -2189,20 +765,20 @@ class StatisticsVisitor : public NodeVisitor { node.false_statement.accept(*this); } - void visit(const IncludeStatementNode&) { } + void visit(const IncludeStatementNode&) {} - void visit(const ExtendsStatementNode&) { } + void visit(const ExtendsStatementNode&) {} void visit(const BlockStatementNode& node) { node.block.accept(*this); } - void visit(const SetStatementNode&) { } + void visit(const SetStatementNode&) {} public: unsigned int variable_counter; - explicit StatisticsVisitor() : variable_counter(0) { } + explicit StatisticsVisitor(): variable_counter(0) {} }; } // namespace inja @@ -2210,7 +786,6 @@ class StatisticsVisitor : public NodeVisitor { #endif // INCLUDE_INJA_STATISTICS_HPP_ - namespace inja { /*! @@ -2221,8 +796,8 @@ struct Template { std::string content; std::map> block_storage; - explicit Template() { } - explicit Template(const std::string& content): content(content) { } + explicit Template() {} + explicit Template(const std::string& content): content(content) {} /// Return number of variables (total number, not distinct ones) in the template int count_variables() { @@ -2323,7 +898,6 @@ struct RenderConfig { #include #include #include -#include #include // #include "config.hpp" @@ -2346,9 +920,7 @@ struct RenderConfig { #define INCLUDE_INJA_TOKEN_HPP_ #include - -// #include "string_view.hpp" - +#include namespace inja { @@ -2393,12 +965,12 @@ struct Token { Unknown, Eof, }; - + Kind kind {Kind::Unknown}; - nonstd::string_view text; + std::string_view text; explicit constexpr Token() = default; - explicit constexpr Token(Kind kind, nonstd::string_view text) : kind(kind), text(text) {} + explicit constexpr Token(Kind kind, std::string_view text): kind(kind), text(text) {} std::string describe() const { switch (kind) { @@ -2448,16 +1020,15 @@ class Lexer { Number, }; - const LexerConfig &config; + const LexerConfig& config; State state; MinusState minus_state; - nonstd::string_view m_in; + std::string_view m_in; size_t tok_start; size_t pos; - - Token scan_body(nonstd::string_view close, Token::Kind closeKind, nonstd::string_view close_trim = nonstd::string_view(), bool trim = false) { + Token scan_body(std::string_view close, Token::Kind closeKind, std::string_view close_trim = std::string_view(), bool trim = false) { again: // skip whitespace (except for \n as it might be a close) if (tok_start >= m_in.size()) { @@ -2611,7 +1182,7 @@ class Lexer { } const char ch = m_in[pos]; // be very permissive in lexer (we'll catch errors when conversion happens) - if (!std::isdigit(ch) && ch != '.' && ch != 'e' && ch != 'E' && ch != '+' && ch != '-') { + if (!(std::isdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' || (ch == '+' && (pos == 0 || m_in[pos-1] == 'e' || m_in[pos-1] == 'E')) || (ch == '-' && (pos == 0 || m_in[pos-1] == 'e' || m_in[pos-1] == 'E')))) { break; } pos += 1; @@ -2627,7 +1198,7 @@ class Lexer { } const char ch = m_in[pos++]; if (ch == '\\') { - escape = true; + escape = !escape; } else if (!escape && ch == m_in[tok_start]) { break; } else { @@ -2637,7 +1208,9 @@ class Lexer { return make_token(Token::Kind::String); } - Token make_token(Token::Kind kind) const { return Token(kind, string_view::slice(m_in, tok_start, pos)); } + Token make_token(Token::Kind kind) const { + return Token(kind, string_view::slice(m_in, tok_start, pos)); + } void skip_whitespaces_and_newlines() { if (pos < m_in.size()) { @@ -2667,8 +1240,8 @@ class Lexer { } } - static nonstd::string_view clear_final_line_if_whitespace(nonstd::string_view text) { - nonstd::string_view result = text; + static std::string_view clear_final_line_if_whitespace(std::string_view text) { + std::string_view result = text; while (!result.empty()) { const char ch = result.back(); if (ch == ' ' || ch == '\t') { @@ -2683,13 +1256,13 @@ class Lexer { } public: - explicit Lexer(const LexerConfig &config) : config(config), state(State::Text), minus_state(MinusState::Number) {} + explicit Lexer(const LexerConfig& config): config(config), state(State::Text), minus_state(MinusState::Number) {} SourceLocation current_position() const { return get_source_location(m_in, tok_start); } - void start(nonstd::string_view input) { + void start(std::string_view input) { m_in = input; tok_start = 0; pos = 0; @@ -2715,7 +1288,7 @@ class Lexer { case State::Text: { // fast-scan to first open character const size_t open_start = m_in.substr(pos).find_first_of(config.open_chars); - if (open_start == nonstd::string_view::npos) { + if (open_start == std::string_view::npos) { // didn't find open, return remaining text as text token pos = m_in.size(); return make_token(Token::Kind::Text); @@ -2723,7 +1296,7 @@ class Lexer { pos += open_start; // try to match one of the opening sequences, and get the close - nonstd::string_view open_str = m_in.substr(pos); + std::string_view open_str = m_in.substr(pos); bool must_lstrip = false; if (inja::string_view::starts_with(open_str, config.expression_open)) { if (inja::string_view::starts_with(open_str, config.expression_open_force_lstrip)) { @@ -2735,7 +1308,7 @@ class Lexer { } else if (inja::string_view::starts_with(open_str, config.statement_open)) { if (inja::string_view::starts_with(open_str, config.statement_open_no_lstrip)) { state = State::StatementStartNoLstrip; - } else if (inja::string_view::starts_with(open_str, config.statement_open_force_lstrip )) { + } else if (inja::string_view::starts_with(open_str, config.statement_open_force_lstrip)) { state = State::StatementStartForceLstrip; must_lstrip = true; } else { @@ -2757,7 +1330,7 @@ class Lexer { goto again; } - nonstd::string_view text = string_view::slice(m_in, tok_start, pos); + std::string_view text = string_view::slice(m_in, tok_start, pos); if (must_lstrip) { text = clear_final_line_if_whitespace(text); } @@ -2816,7 +1389,7 @@ class Lexer { case State::CommentBody: { // fast-scan to comment close const size_t end = m_in.substr(pos).find(config.comment_close); - if (end == nonstd::string_view::npos) { + if (end == std::string_view::npos) { pos = m_in.size(); return make_token(Token::Kind::Eof); } @@ -2837,7 +1410,7 @@ class Lexer { } } - const LexerConfig &get_config() const { + const LexerConfig& get_config() const { return config; } }; @@ -2855,39 +1428,34 @@ class Lexer { // #include "utils.hpp" - namespace inja { /*! * \brief Class for parsing an inja Template. */ class Parser { - const ParserConfig &config; + using Arguments = std::vector>; + using OperatorStack = std::stack>; + + const ParserConfig& config; Lexer lexer; - TemplateStorage &template_storage; - const FunctionStorage &function_storage; + TemplateStorage& template_storage; + const FunctionStorage& function_storage; Token tok, peek_tok; bool have_peek_tok {false}; - size_t current_paren_level {0}; - size_t current_bracket_level {0}; - size_t current_brace_level {0}; + std::string_view literal_start; - nonstd::string_view json_literal_start; + BlockNode* current_block {nullptr}; + ExpressionListNode* current_expression_list {nullptr}; - BlockNode *current_block {nullptr}; - ExpressionListNode *current_expression_list {nullptr}; - std::stack> function_stack; - std::vector> arguments; - - std::stack> operator_stack; std::stack if_statement_stack; std::stack for_statement_stack; std::stack block_statement_stack; - inline void throw_parser_error(const std::string &message) { + inline void throw_parser_error(const std::string& message) const { INJA_THROW(ParserError(message, lexer.current_position())); } @@ -2907,15 +1475,19 @@ class Parser { } } - inline void add_json_literal(const char* content_ptr) { - nonstd::string_view json_text(json_literal_start.data(), tok.text.data() - json_literal_start.data() + tok.text.size()); - arguments.emplace_back(std::make_shared(json::parse(json_text), json_text.data() - content_ptr)); + inline void add_literal(Arguments &arguments, const char* content_ptr) { + std::string_view data_text(literal_start.data(), tok.text.data() - literal_start.data() + tok.text.size()); + arguments.emplace_back(std::make_shared(data_text, data_text.data() - content_ptr)); } - inline void add_operator() { + inline void add_operator(Arguments &arguments, OperatorStack &operator_stack) { auto function = operator_stack.top(); operator_stack.pop(); + if (static_cast(arguments.size()) < function->number_args) { + throw_parser_error("too few arguments"); + } + for (int i = 0; i < function->number_args; ++i) { function->arguments.insert(function->arguments.begin(), arguments.back()); arguments.pop_back(); @@ -2923,7 +1495,7 @@ class Parser { arguments.emplace_back(function); } - void add_to_template_storage(nonstd::string_view path, std::string& template_name) { + void add_to_template_storage(std::string_view path, std::string& template_name) { if (template_storage.find(template_name) != template_storage.end()) { return; } @@ -2949,7 +1521,6 @@ class Parser { template_storage.emplace(template_name, include_template); parse_into_template(template_storage[template_name], template_name); return; - } else if (!config.include_callback) { INJA_THROW(FileError("failed accessing file at '" + template_name + "'")); } @@ -2963,37 +1534,56 @@ class Parser { } } - bool parse_expression(Template &tmpl, Token::Kind closing) { - while (tok.kind != closing && tok.kind != Token::Kind::Eof) { + std::string parse_filename() const { + if (tok.kind != Token::Kind::String) { + throw_parser_error("expected string, got '" + tok.describe() + "'"); + } + + if (tok.text.length() < 2) { + throw_parser_error("expected filename, got '" + static_cast(tok.text) + "'"); + } + + // Remove first and last character "" + return std::string {tok.text.substr(1, tok.text.length() - 2)}; + } + + bool parse_expression(Template& tmpl, Token::Kind closing) { + current_expression_list->root = parse_expression(tmpl); + return tok.kind == closing; + } + + std::shared_ptr parse_expression(Template& tmpl) { + size_t current_bracket_level {0}; + size_t current_brace_level {0}; + Arguments arguments; + OperatorStack operator_stack; + + while (tok.kind != Token::Kind::Eof) { // Literals switch (tok.kind) { case Token::Kind::String: { if (current_brace_level == 0 && current_bracket_level == 0) { - json_literal_start = tok.text; - add_json_literal(tmpl.content.c_str()); + literal_start = tok.text; + add_literal(arguments, tmpl.content.c_str()); } - } break; case Token::Kind::Number: { if (current_brace_level == 0 && current_bracket_level == 0) { - json_literal_start = tok.text; - add_json_literal(tmpl.content.c_str()); + literal_start = tok.text; + add_literal(arguments, tmpl.content.c_str()); } - } break; case Token::Kind::LeftBracket: { if (current_brace_level == 0 && current_bracket_level == 0) { - json_literal_start = tok.text; + literal_start = tok.text; } current_bracket_level += 1; - } break; case Token::Kind::LeftBrace: { if (current_brace_level == 0 && current_bracket_level == 0) { - json_literal_start = tok.text; + literal_start = tok.text; } current_brace_level += 1; - } break; case Token::Kind::RightBracket: { if (current_bracket_level == 0) { @@ -3002,9 +1592,8 @@ class Parser { current_bracket_level -= 1; if (current_brace_level == 0 && current_bracket_level == 0) { - add_json_literal(tmpl.content.c_str()); + add_literal(arguments, tmpl.content.c_str()); } - } break; case Token::Kind::RightBrace: { if (current_brace_level == 0) { @@ -3013,35 +1602,57 @@ class Parser { current_brace_level -= 1; if (current_brace_level == 0 && current_bracket_level == 0) { - add_json_literal(tmpl.content.c_str()); + add_literal(arguments, tmpl.content.c_str()); } - } break; case Token::Kind::Id: { get_peek_token(); - // Json Literal - if (tok.text == static_cast("true") || tok.text == static_cast("false") || tok.text == static_cast("null")) { + // Data Literal + if (tok.text == static_cast("true") || tok.text == static_cast("false") || + tok.text == static_cast("null")) { if (current_brace_level == 0 && current_bracket_level == 0) { - json_literal_start = tok.text; - add_json_literal(tmpl.content.c_str()); + literal_start = tok.text; + add_literal(arguments, tmpl.content.c_str()); } - // Operator + // Operator } else if (tok.text == "and" || tok.text == "or" || tok.text == "in" || tok.text == "not") { goto parse_operator; - // Functions + // Functions } else if (peek_tok.kind == Token::Kind::LeftParen) { - operator_stack.emplace(std::make_shared(static_cast(tok.text), tok.text.data() - tmpl.content.c_str())); - function_stack.emplace(operator_stack.top().get(), current_paren_level); + auto func = std::make_shared(tok.text, tok.text.data() - tmpl.content.c_str()); + get_next_token(); + do { + get_next_token(); + auto expr = parse_expression(tmpl); + if (!expr) { + break; + } + func->number_args += 1; + func->arguments.emplace_back(expr); + } while (tok.kind == Token::Kind::Comma); + if (tok.kind != Token::Kind::RightParen) { + throw_parser_error("expected right parenthesis, got '" + tok.describe() + "'"); + } + + auto function_data = function_storage.find_function(func->name, func->number_args); + if (function_data.operation == FunctionStorage::Operation::None) { + throw_parser_error("unknown function " + func->name); + } + func->operation = function_data.operation; + if (function_data.operation == FunctionStorage::Operation::Callback) { + func->callback = function_data.callback; + } + arguments.emplace_back(func); - // Variables + // Variables } else { - arguments.emplace_back(std::make_shared(static_cast(tok.text), tok.text.data() - tmpl.content.c_str())); + arguments.emplace_back(std::make_shared(static_cast(tok.text), tok.text.data() - tmpl.content.c_str())); } - // Operators + // Operators } break; case Token::Kind::Equal: case Token::Kind::NotEqual: @@ -3057,7 +1668,7 @@ class Parser { case Token::Kind::Percent: case Token::Kind::Dot: { - parse_operator: + parse_operator: FunctionStorage::Operation operation; switch (tok.kind) { case Token::Kind::Id: { @@ -3118,93 +1729,58 @@ class Parser { } auto function_node = std::make_shared(operation, tok.text.data() - tmpl.content.c_str()); - while (!operator_stack.empty() && ((operator_stack.top()->precedence > function_node->precedence) || (operator_stack.top()->precedence == function_node->precedence && function_node->associativity == FunctionNode::Associativity::Left)) && (operator_stack.top()->operation != FunctionStorage::Operation::ParenLeft)) { - add_operator(); + while (!operator_stack.empty() && + ((operator_stack.top()->precedence > function_node->precedence) || + (operator_stack.top()->precedence == function_node->precedence && function_node->associativity == FunctionNode::Associativity::Left))) { + add_operator(arguments, operator_stack); } operator_stack.emplace(function_node); - } break; case Token::Kind::Comma: { if (current_brace_level == 0 && current_bracket_level == 0) { - if (function_stack.empty()) { - throw_parser_error("unexpected ','"); - } - - function_stack.top().first->number_args += 1; + goto break_loop; } - } break; case Token::Kind::Colon: { if (current_brace_level == 0 && current_bracket_level == 0) { throw_parser_error("unexpected ':'"); } - } break; case Token::Kind::LeftParen: { - current_paren_level += 1; - operator_stack.emplace(std::make_shared(FunctionStorage::Operation::ParenLeft, tok.text.data() - tmpl.content.c_str())); - - get_peek_token(); - if (peek_tok.kind == Token::Kind::RightParen) { - if (!function_stack.empty() && function_stack.top().second == current_paren_level - 1) { - function_stack.top().first->number_args = 0; - } - } - - } break; - case Token::Kind::RightParen: { - current_paren_level -= 1; - while (!operator_stack.empty() && operator_stack.top()->operation != FunctionStorage::Operation::ParenLeft) { - add_operator(); - } - - if (!operator_stack.empty() && operator_stack.top()->operation == FunctionStorage::Operation::ParenLeft) { - operator_stack.pop(); + get_next_token(); + auto expr = parse_expression(tmpl); + if (tok.kind != Token::Kind::RightParen) { + throw_parser_error("expected right parenthesis, got '" + tok.describe() + "'"); } - - if (!function_stack.empty() && function_stack.top().second == current_paren_level) { - auto func = function_stack.top().first; - auto function_data = function_storage.find_function(func->name, func->number_args); - if (function_data.operation == FunctionStorage::Operation::None) { - throw_parser_error("unknown function " + func->name); - } - func->operation = function_data.operation; - if (function_data.operation == FunctionStorage::Operation::Callback) { - func->callback = function_data.callback; - } - - if (operator_stack.empty()) { - throw_parser_error("internal error at function " + func->name); - } - - add_operator(); - function_stack.pop(); + if (!expr) { + throw_parser_error("empty expression in parentheses"); } - } + arguments.emplace_back(expr); + } break; default: - break; + goto break_loop; } get_next_token(); } + break_loop: while (!operator_stack.empty()) { - add_operator(); + add_operator(arguments, operator_stack); } + std::shared_ptr expr; if (arguments.size() == 1) { - current_expression_list->root = arguments[0]; + expr = arguments[0]; arguments = {}; - } else if (arguments.size() > 1) { throw_parser_error("malformed expression"); } - - return true; + return expr; } - bool parse_statement(Template &tmpl, Token::Kind closing, nonstd::string_view path) { + bool parse_statement(Template& tmpl, Token::Kind closing, std::string_view path) { if (tok.kind != Token::Kind::Id) { return false; } @@ -3221,12 +1797,11 @@ class Parser { if (!parse_expression(tmpl, closing)) { return false; } - } else if (tok.text == static_cast("else")) { if (if_statement_stack.empty()) { throw_parser_error("else without matching if"); } - auto &if_statement_data = if_statement_stack.top(); + auto& if_statement_data = if_statement_stack.top(); get_next_token(); if_statement_data->has_false_statement = true; @@ -3246,7 +1821,6 @@ class Parser { return false; } } - } else if (tok.text == static_cast("endif")) { if (if_statement_stack.empty()) { throw_parser_error("endif without matching if"); @@ -3257,12 +1831,11 @@ class Parser { if_statement_stack.pop(); } - auto &if_statement_data = if_statement_stack.top(); + auto& if_statement_data = if_statement_stack.top(); get_next_token(); current_block = if_statement_data->parent; if_statement_stack.pop(); - } else if (tok.text == static_cast("block")) { get_next_token(); @@ -3282,18 +1855,16 @@ class Parser { } get_next_token(); - } else if (tok.text == static_cast("endblock")) { if (block_statement_stack.empty()) { throw_parser_error("endblock without matching block"); } - auto &block_statement_data = block_statement_stack.top(); + auto& block_statement_data = block_statement_stack.top(); get_next_token(); current_block = block_statement_data->parent; block_statement_stack.pop(); - } else if (tok.text == static_cast("for")) { get_next_token(); @@ -3317,11 +1888,13 @@ class Parser { value_token = tok; get_next_token(); - for_statement_node = std::make_shared(static_cast(key_token.text), static_cast(value_token.text), current_block, tok.text.data() - tmpl.content.c_str()); + for_statement_node = std::make_shared(static_cast(key_token.text), static_cast(value_token.text), + current_block, tok.text.data() - tmpl.content.c_str()); - // Array type + // Array type } else { - for_statement_node = std::make_shared(static_cast(value_token.text), current_block, tok.text.data() - tmpl.content.c_str()); + for_statement_node = + std::make_shared(static_cast(value_token.text), current_block, tok.text.data() - tmpl.content.c_str()); } current_block->nodes.emplace_back(for_statement_node); @@ -3337,46 +1910,34 @@ class Parser { if (!parse_expression(tmpl, closing)) { return false; } - } else if (tok.text == static_cast("endfor")) { if (for_statement_stack.empty()) { throw_parser_error("endfor without matching for"); } - auto &for_statement_data = for_statement_stack.top(); + auto& for_statement_data = for_statement_stack.top(); get_next_token(); current_block = for_statement_data->parent; for_statement_stack.pop(); - } else if (tok.text == static_cast("include")) { get_next_token(); - if (tok.kind != Token::Kind::String) { - throw_parser_error("expected string, got '" + tok.describe() + "'"); - } - - std::string template_name = json::parse(tok.text).get_ref(); + std::string template_name = parse_filename(); add_to_template_storage(path, template_name); current_block->nodes.emplace_back(std::make_shared(template_name, tok.text.data() - tmpl.content.c_str())); get_next_token(); - } else if (tok.text == static_cast("extends")) { get_next_token(); - if (tok.kind != Token::Kind::String) { - throw_parser_error("expected string, got '" + tok.describe() + "'"); - } - - std::string template_name = json::parse(tok.text).get_ref(); + std::string template_name = parse_filename(); add_to_template_storage(path, template_name); current_block->nodes.emplace_back(std::make_shared(template_name, tok.text.data() - tmpl.content.c_str())); get_next_token(); - } else if (tok.text == static_cast("set")) { get_next_token(); @@ -3399,14 +1960,13 @@ class Parser { if (!parse_expression(tmpl, closing)) { return false; } - } else { return false; } return true; } - void parse_into(Template &tmpl, nonstd::string_view path) { + void parse_into(Template& tmpl, std::string_view path) { lexer.start(tmpl.content); current_block = &tmpl.root; @@ -3420,7 +1980,8 @@ class Parser { if (!for_statement_stack.empty()) { throw_parser_error("unmatched for"); } - } return; + } + return; case Token::Kind::Text: { current_block->nodes.emplace_back(std::make_shared(tok.text.data() - tmpl.content.c_str(), tok.text.size())); } break; @@ -3450,10 +2011,6 @@ class Parser { current_expression_list = expression_list_node.get(); if (!parse_expression(tmpl, Token::Kind::ExpressionClose)) { - throw_parser_error("expected expression, got '" + tok.describe() + "'"); - } - - if (tok.kind != Token::Kind::ExpressionClose) { throw_parser_error("expected expression close, got '" + tok.describe() + "'"); } } break; @@ -3470,31 +2027,26 @@ class Parser { } } - public: - explicit Parser(const ParserConfig &parser_config, const LexerConfig &lexer_config, - TemplateStorage &template_storage, const FunctionStorage &function_storage) - : config(parser_config), lexer(lexer_config), template_storage(template_storage), function_storage(function_storage) { } + explicit Parser(const ParserConfig& parser_config, const LexerConfig& lexer_config, TemplateStorage& template_storage, + const FunctionStorage& function_storage) + : config(parser_config), lexer(lexer_config), template_storage(template_storage), function_storage(function_storage) {} - Template parse(nonstd::string_view input, nonstd::string_view path) { + Template parse(std::string_view input, std::string_view path) { auto result = Template(static_cast(input)); parse_into(result, path); return result; } - Template parse(nonstd::string_view input) { - return parse(input, "./"); - } - - void parse_into_template(Template& tmpl, nonstd::string_view filename) { - nonstd::string_view path = filename.substr(0, filename.find_last_of("/\\") + 1); + void parse_into_template(Template& tmpl, std::string_view filename) { + std::string_view path = filename.substr(0, filename.find_last_of("/\\") + 1); // StringRef path = sys::path::parent_path(filename); auto sub_parser = Parser(config, lexer.get_config(), template_storage, function_storage); sub_parser.parse_into(tmpl, path); } - std::string load_file(const std::string& filename) { + static std::string load_file(const std::string& filename) { std::ifstream file; file.open(filename); if (file.fail()) { @@ -3535,31 +2087,31 @@ namespace inja { /*! * \brief Class for rendering a Template with data. */ -class Renderer : public NodeVisitor { +class Renderer : public NodeVisitor { using Op = FunctionStorage::Operation; const RenderConfig config; - const TemplateStorage &template_storage; - const FunctionStorage &function_storage; + const TemplateStorage& template_storage; + const FunctionStorage& function_storage; - const Template *current_template; + const Template* current_template; size_t current_level {0}; std::vector template_stack; std::vector block_statement_stack; - const json *json_input; - std::ostream *output_stream; + const json* data_input; + std::ostream* output_stream; - json json_additional_data; - json* current_loop_data = &json_additional_data["loop"]; + json additional_data; + json* current_loop_data = &additional_data["loop"]; - std::vector> json_tmp_stack; - std::stack json_eval_stack; - std::stack not_found_stack; + std::vector> data_tmp_stack; + std::stack data_eval_stack; + std::stack not_found_stack; bool break_rendering {false}; - bool truthy(const json* data) const { + static bool truthy(const json* data) { if (data->is_boolean()) { return data->get(); } else if (data->is_number()) { @@ -3570,9 +2122,11 @@ class Renderer : public NodeVisitor { return !data->empty(); } - void print_json(const std::shared_ptr value) { + void print_data(const std::shared_ptr value) { if (value->is_string()) { *output_stream << value->get_ref(); + } else if (value->is_number_unsigned()) { + *output_stream << value->get(); } else if (value->is_number_integer()) { *output_stream << value->get(); } else if (value->is_null()) { @@ -3588,14 +2142,14 @@ class Renderer : public NodeVisitor { expression_list.root->accept(*this); - if (json_eval_stack.empty()) { + if (data_eval_stack.empty()) { throw_renderer_error("empty expression", expression_list); - } else if (json_eval_stack.size() != 1) { + } else if (data_eval_stack.size() != 1) { throw_renderer_error("malformed expression", expression_list); } - const auto result = json_eval_stack.top(); - json_eval_stack.pop(); + const auto result = data_eval_stack.top(); + data_eval_stack.pop(); if (!result) { if (not_found_stack.empty()) { @@ -3610,13 +2164,18 @@ class Renderer : public NodeVisitor { return std::make_shared(*result); } - void throw_renderer_error(const std::string &message, const AstNode& node) { + void throw_renderer_error(const std::string& message, const AstNode& node) { SourceLocation loc = get_source_location(current_template->content, node.pos); INJA_THROW(RenderError(message, loc)); } - template - std::array get_arguments(const FunctionNode& node) { + void make_result(const json&& result) { + auto result_ptr = std::make_shared(result); + data_tmp_stack.push_back(result_ptr); + data_eval_stack.push(result_ptr.get()); + } + + template std::array get_arguments(const FunctionNode& node) { if (node.arguments.size() < N_start + N) { throw_renderer_error("function needs " + std::to_string(N_start + N) + " variables, but has only found " + std::to_string(node.arguments.size()), node); } @@ -3625,49 +2184,48 @@ class Renderer : public NodeVisitor { node.arguments[i]->accept(*this); } - if (json_eval_stack.size() < N) { - throw_renderer_error("function needs " + std::to_string(N) + " variables, but has only found " + std::to_string(json_eval_stack.size()), node); + if (data_eval_stack.size() < N) { + throw_renderer_error("function needs " + std::to_string(N) + " variables, but has only found " + std::to_string(data_eval_stack.size()), node); } std::array result; for (size_t i = 0; i < N; i += 1) { - result[N - i - 1] = json_eval_stack.top(); - json_eval_stack.pop(); + result[N - i - 1] = data_eval_stack.top(); + data_eval_stack.pop(); if (!result[N - i - 1]) { - const auto json_node = not_found_stack.top(); + const auto data_node = not_found_stack.top(); not_found_stack.pop(); if (throw_not_found) { - throw_renderer_error("variable '" + static_cast(json_node->name) + "' not found", *json_node); + throw_renderer_error("variable '" + static_cast(data_node->name) + "' not found", *data_node); } } } return result; } - template - Arguments get_argument_vector(const FunctionNode& node) { + template Arguments get_argument_vector(const FunctionNode& node) { const size_t N = node.arguments.size(); - for (auto a: node.arguments) { + for (auto a : node.arguments) { a->accept(*this); } - if (json_eval_stack.size() < N) { - throw_renderer_error("function needs " + std::to_string(N) + " variables, but has only found " + std::to_string(json_eval_stack.size()), node); + if (data_eval_stack.size() < N) { + throw_renderer_error("function needs " + std::to_string(N) + " variables, but has only found " + std::to_string(data_eval_stack.size()), node); } Arguments result {N}; for (size_t i = 0; i < N; i += 1) { - result[N - i - 1] = json_eval_stack.top(); - json_eval_stack.pop(); + result[N - i - 1] = data_eval_stack.top(); + data_eval_stack.pop(); if (!result[N - i - 1]) { - const auto json_node = not_found_stack.top(); + const auto data_node = not_found_stack.top(); not_found_stack.pop(); if (throw_not_found) { - throw_renderer_error("variable '" + static_cast(json_node->name) + "' not found", *json_node); + throw_renderer_error("variable '" + static_cast(data_node->name) + "' not found", *data_node); } } } @@ -3688,160 +2246,118 @@ class Renderer : public NodeVisitor { output_stream->write(current_template->content.c_str() + node.pos, node.length); } - void visit(const ExpressionNode&) { } + void visit(const ExpressionNode&) {} void visit(const LiteralNode& node) { - json_eval_stack.push(&node.value); + data_eval_stack.push(&node.value); } - void visit(const JsonNode& node) { - if (json_additional_data.contains(node.ptr)) { - json_eval_stack.push(&(json_additional_data[node.ptr])); - - } else if (json_input->contains(node.ptr)) { - json_eval_stack.push(&(*json_input)[node.ptr]); - + void visit(const DataNode& node) { + if (additional_data.contains(node.ptr)) { + data_eval_stack.push(&(additional_data[node.ptr])); + } else if (data_input->contains(node.ptr)) { + data_eval_stack.push(&(*data_input)[node.ptr]); } else { // Try to evaluate as a no-argument callback const auto function_data = function_storage.find_function(node.name, 0); if (function_data.operation == FunctionStorage::Operation::Callback) { Arguments empty_args {}; const auto value = std::make_shared(function_data.callback(empty_args)); - json_tmp_stack.push_back(value); - json_eval_stack.push(value.get()); - + data_tmp_stack.push_back(value); + data_eval_stack.push(value.get()); } else { - json_eval_stack.push(nullptr); + data_eval_stack.push(nullptr); not_found_stack.emplace(&node); } } } void visit(const FunctionNode& node) { - std::shared_ptr result_ptr; - switch (node.operation) { case Op::Not: { const auto args = get_arguments<1>(node); - result_ptr = std::make_shared(!truthy(args[0])); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(!truthy(args[0])); } break; case Op::And: { - result_ptr = std::make_shared(truthy(get_arguments<1, 0>(node)[0]) && truthy(get_arguments<1, 1>(node)[0])); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(truthy(get_arguments<1, 0>(node)[0]) && truthy(get_arguments<1, 1>(node)[0])); } break; case Op::Or: { - result_ptr = std::make_shared(truthy(get_arguments<1, 0>(node)[0]) || truthy(get_arguments<1, 1>(node)[0])); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(truthy(get_arguments<1, 0>(node)[0]) || truthy(get_arguments<1, 1>(node)[0])); } break; case Op::In: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(std::find(args[1]->begin(), args[1]->end(), *args[0]) != args[1]->end()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(std::find(args[1]->begin(), args[1]->end(), *args[0]) != args[1]->end()); } break; case Op::Equal: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(*args[0] == *args[1]); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(*args[0] == *args[1]); } break; case Op::NotEqual: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(*args[0] != *args[1]); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(*args[0] != *args[1]); } break; case Op::Greater: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(*args[0] > *args[1]); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(*args[0] > *args[1]); } break; case Op::GreaterEqual: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(*args[0] >= *args[1]); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(*args[0] >= *args[1]); } break; case Op::Less: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(*args[0] < *args[1]); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(*args[0] < *args[1]); } break; case Op::LessEqual: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(*args[0] <= *args[1]); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(*args[0] <= *args[1]); } break; case Op::Add: { const auto args = get_arguments<2>(node); if (args[0]->is_string() && args[1]->is_string()) { - result_ptr = std::make_shared(args[0]->get_ref() + args[1]->get_ref()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get_ref() + args[1]->get_ref()); } else if (args[0]->is_number_integer() && args[1]->is_number_integer()) { - result_ptr = std::make_shared(args[0]->get() + args[1]->get()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get() + args[1]->get()); } else { - result_ptr = std::make_shared(args[0]->get() + args[1]->get()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get() + args[1]->get()); } - json_eval_stack.push(result_ptr.get()); } break; case Op::Subtract: { const auto args = get_arguments<2>(node); if (args[0]->is_number_integer() && args[1]->is_number_integer()) { - result_ptr = std::make_shared(args[0]->get() - args[1]->get()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get() - args[1]->get()); } else { - result_ptr = std::make_shared(args[0]->get() - args[1]->get()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get() - args[1]->get()); } - json_eval_stack.push(result_ptr.get()); } break; case Op::Multiplication: { const auto args = get_arguments<2>(node); if (args[0]->is_number_integer() && args[1]->is_number_integer()) { - result_ptr = std::make_shared(args[0]->get() * args[1]->get()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get() * args[1]->get()); } else { - result_ptr = std::make_shared(args[0]->get() * args[1]->get()); - json_tmp_stack.push_back(result_ptr); + make_result(args[0]->get() * args[1]->get()); } - json_eval_stack.push(result_ptr.get()); } break; case Op::Division: { const auto args = get_arguments<2>(node); - if (args[1]->get() == 0) { + if (args[1]->get() == 0) { throw_renderer_error("division by zero", node); } - result_ptr = std::make_shared(args[0]->get() / args[1]->get()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(args[0]->get() / args[1]->get()); } break; case Op::Power: { const auto args = get_arguments<2>(node); - if (args[0]->is_number_integer() && args[1]->get() >= 0) { - int result = static_cast(std::pow(args[0]->get(), args[1]->get())); - result_ptr = std::make_shared(std::move(result)); - json_tmp_stack.push_back(result_ptr); + if (args[0]->is_number_integer() && args[1]->get() >= 0) { + const auto result = static_cast(std::pow(args[0]->get(), args[1]->get())); + make_result(result); } else { - double result = std::pow(args[0]->get(), args[1]->get()); - result_ptr = std::make_shared(std::move(result)); - json_tmp_stack.push_back(result_ptr); + const auto result = std::pow(args[0]->get(), args[1]->get()); + make_result(result); } - json_eval_stack.push(result_ptr.get()); } break; case Op::Modulo: { const auto args = get_arguments<2>(node); - result_ptr = std::make_shared(args[0]->get() % args[1]->get()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(args[0]->get() % args[1]->get()); } break; case Op::AtId: { const auto container = get_arguments<1, 0, false>(node)[0]; @@ -3851,168 +2367,128 @@ class Renderer : public NodeVisitor { } const auto id_node = not_found_stack.top(); not_found_stack.pop(); - json_eval_stack.pop(); - json_eval_stack.push(&container->at(id_node->name)); + data_eval_stack.pop(); + data_eval_stack.push(&container->at(id_node->name)); } break; case Op::At: { const auto args = get_arguments<2>(node); if (args[0]->is_object()) { - json_eval_stack.push(&args[0]->at(args[1]->get())); + data_eval_stack.push(&args[0]->at(args[1]->get())); } else { - json_eval_stack.push(&args[0]->at(args[1]->get())); + data_eval_stack.push(&args[0]->at(args[1]->get())); } } break; case Op::Default: { const auto test_arg = get_arguments<1, 0, false>(node)[0]; - json_eval_stack.push(test_arg ? test_arg : get_arguments<1, 1>(node)[0]); + data_eval_stack.push(test_arg ? test_arg : get_arguments<1, 1>(node)[0]); } break; case Op::DivisibleBy: { const auto args = get_arguments<2>(node); - const int divisor = args[1]->get(); - result_ptr = std::make_shared((divisor != 0) && (args[0]->get() % divisor == 0)); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + const auto divisor = args[1]->get(); + make_result((divisor != 0) && (args[0]->get() % divisor == 0)); } break; case Op::Even: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->get() % 2 == 0); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->get() % 2 == 0); } break; case Op::Exists: { - auto &&name = get_arguments<1>(node)[0]->get_ref(); - result_ptr = std::make_shared(json_input->contains(json::json_pointer(JsonNode::convert_dot_to_json_ptr(name)))); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + auto&& name = get_arguments<1>(node)[0]->get_ref(); + make_result(data_input->contains(json::json_pointer(DataNode::convert_dot_to_ptr(name)))); } break; case Op::ExistsInObject: { const auto args = get_arguments<2>(node); - auto &&name = args[1]->get_ref(); - result_ptr = std::make_shared(args[0]->find(name) != args[0]->end()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + auto&& name = args[1]->get_ref(); + make_result(args[0]->find(name) != args[0]->end()); } break; case Op::First: { const auto result = &get_arguments<1>(node)[0]->front(); - json_eval_stack.push(result); + data_eval_stack.push(result); } break; case Op::Float: { - result_ptr = std::make_shared(std::stod(get_arguments<1>(node)[0]->get_ref())); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(std::stod(get_arguments<1>(node)[0]->get_ref())); } break; case Op::Int: { - result_ptr = std::make_shared(std::stoi(get_arguments<1>(node)[0]->get_ref())); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(std::stoi(get_arguments<1>(node)[0]->get_ref())); } break; case Op::Last: { const auto result = &get_arguments<1>(node)[0]->back(); - json_eval_stack.push(result); + data_eval_stack.push(result); } break; case Op::Length: { const auto val = get_arguments<1>(node)[0]; if (val->is_string()) { - result_ptr = std::make_shared(val->get_ref().length()); + make_result(val->get_ref().length()); } else { - result_ptr = std::make_shared(val->size()); + make_result(val->size()); } - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); } break; case Op::Lower: { - std::string result = get_arguments<1>(node)[0]->get(); - std::transform(result.begin(), result.end(), result.begin(), ::tolower); - result_ptr = std::make_shared(std::move(result)); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + auto result = get_arguments<1>(node)[0]->get(); + std::transform(result.begin(), result.end(), result.begin(), [](char c) { return static_cast(::tolower(c)); }); + make_result(std::move(result)); } break; case Op::Max: { const auto args = get_arguments<1>(node); const auto result = std::max_element(args[0]->begin(), args[0]->end()); - json_eval_stack.push(&(*result)); + data_eval_stack.push(&(*result)); } break; case Op::Min: { const auto args = get_arguments<1>(node); const auto result = std::min_element(args[0]->begin(), args[0]->end()); - json_eval_stack.push(&(*result)); + data_eval_stack.push(&(*result)); } break; case Op::Odd: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->get() % 2 != 0); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->get() % 2 != 0); } break; case Op::Range: { - std::vector result(get_arguments<1>(node)[0]->get()); + std::vector result(get_arguments<1>(node)[0]->get()); std::iota(result.begin(), result.end(), 0); - result_ptr = std::make_shared(std::move(result)); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(std::move(result)); } break; case Op::Round: { const auto args = get_arguments<2>(node); - const int precision = args[1]->get(); - const double result = std::round(args[0]->get() * std::pow(10.0, precision)) / std::pow(10.0, precision); - if(0==precision){ - result_ptr = std::make_shared(int(result)); - }else{ - result_ptr = std::make_shared(std::move(result)); + const auto precision = args[1]->get(); + const double result = std::round(args[0]->get() * std::pow(10.0, precision)) / std::pow(10.0, precision); + if (precision == 0) { + make_result(int(result)); + } else { + make_result(result); } - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); } break; case Op::Sort: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->get>()); + auto result_ptr = std::make_shared(get_arguments<1>(node)[0]->get>()); std::sort(result_ptr->begin(), result_ptr->end()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + data_tmp_stack.push_back(result_ptr); + data_eval_stack.push(result_ptr.get()); } break; case Op::Upper: { - std::string result = get_arguments<1>(node)[0]->get(); - std::transform(result.begin(), result.end(), result.begin(), ::toupper); - result_ptr = std::make_shared(std::move(result)); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + auto result = get_arguments<1>(node)[0]->get(); + std::transform(result.begin(), result.end(), result.begin(), [](char c) { return static_cast(::toupper(c)); }); + make_result(std::move(result)); } break; case Op::IsBoolean: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_boolean()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_boolean()); } break; case Op::IsNumber: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_number()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_number()); } break; case Op::IsInteger: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_number_integer()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_number_integer()); } break; case Op::IsFloat: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_number_float()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_number_float()); } break; case Op::IsObject: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_object()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_object()); } break; case Op::IsArray: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_array()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_array()); } break; case Op::IsString: { - result_ptr = std::make_shared(get_arguments<1>(node)[0]->is_string()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(get_arguments<1>(node)[0]->is_string()); } break; case Op::Callback: { auto args = get_argument_vector(node); - result_ptr = std::make_shared(node.callback(args)); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(node.callback(args)); } break; case Op::Super: { const auto args = get_argument_vector(node); @@ -4029,8 +2505,8 @@ class Renderer : public NodeVisitor { } const auto current_block_statement = block_statement_stack.back(); - const Template *new_template = template_stack.at(level); - const Template *old_template = current_template; + const Template* new_template = template_stack.at(level); + const Template* old_template = current_template; const auto block_it = new_template->block_storage.find(current_block_statement->name); if (block_it != new_template->block_storage.end()) { current_template = new_template; @@ -4041,13 +2517,11 @@ class Renderer : public NodeVisitor { } else { throw_renderer_error("could not find block with name '" + current_block_statement->name + "'", node); } - result_ptr = std::make_shared(nullptr); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(nullptr); } break; case Op::Join: { const auto args = get_arguments<2>(node); - const auto separator = args[1]->get(); + const auto separator = args[1]->get(); std::ostringstream os; std::string sep; for (const auto& value : *args[0]) { @@ -4055,28 +2529,24 @@ class Renderer : public NodeVisitor { if (value.is_string()) { os << value.get(); // otherwise the value is surrounded with "" } else { - os << value; + os << value.dump(); } sep = separator; } - result_ptr = std::make_shared(os.str()); - json_tmp_stack.push_back(result_ptr); - json_eval_stack.push(result_ptr.get()); + make_result(os.str()); } break; - case Op::ParenLeft: - case Op::ParenRight: case Op::None: break; } } void visit(const ExpressionListNode& node) { - print_json(eval_expression_list(node)); + print_data(eval_expression_list(node)); } - void visit(const StatementNode&) { } + void visit(const StatementNode&) {} - void visit(const ForStatementNode&) { } + void visit(const ForStatementNode&) {} void visit(const ForArrayStatementNode& node) { const auto result = eval_expression_list(node.condition); @@ -4093,7 +2563,7 @@ class Renderer : public NodeVisitor { (*current_loop_data)["is_first"] = true; (*current_loop_data)["is_last"] = (result->size() <= 1); for (auto it = result->begin(); it != result->end(); ++it) { - json_additional_data[static_cast(node.value)] = *it; + additional_data[static_cast(node.value)] = *it; (*current_loop_data)["index"] = index; (*current_loop_data)["index1"] = index + 1; @@ -4108,12 +2578,12 @@ class Renderer : public NodeVisitor { ++index; } - json_additional_data[static_cast(node.value)].clear(); + additional_data[static_cast(node.value)].clear(); if (!(*current_loop_data)["parent"].empty()) { const auto tmp = (*current_loop_data)["parent"]; *current_loop_data = std::move(tmp); } else { - current_loop_data = &json_additional_data["loop"]; + current_loop_data = &additional_data["loop"]; } } @@ -4131,8 +2601,8 @@ class Renderer : public NodeVisitor { (*current_loop_data)["is_first"] = true; (*current_loop_data)["is_last"] = (result->size() <= 1); for (auto it = result->begin(); it != result->end(); ++it) { - json_additional_data[static_cast(node.key)] = it.key(); - json_additional_data[static_cast(node.value)] = it.value(); + additional_data[static_cast(node.key)] = it.key(); + additional_data[static_cast(node.value)] = it.value(); (*current_loop_data)["index"] = index; (*current_loop_data)["index1"] = index + 1; @@ -4147,12 +2617,12 @@ class Renderer : public NodeVisitor { ++index; } - json_additional_data[static_cast(node.key)].clear(); - json_additional_data[static_cast(node.value)].clear(); + additional_data[static_cast(node.key)].clear(); + additional_data[static_cast(node.value)].clear(); if (!(*current_loop_data)["parent"].empty()) { *current_loop_data = std::move((*current_loop_data)["parent"]); } else { - current_loop_data = &json_additional_data["loop"]; + current_loop_data = &additional_data["loop"]; } } @@ -4169,7 +2639,7 @@ class Renderer : public NodeVisitor { auto sub_renderer = Renderer(config, template_storage, function_storage); const auto included_template_it = template_storage.find(node.file); if (included_template_it != template_storage.end()) { - sub_renderer.render_to(*output_stream, included_template_it->second, *json_input, &json_additional_data); + sub_renderer.render_to(*output_stream, included_template_it->second, *data_input, &additional_data); } else if (config.throw_at_missing_includes) { throw_renderer_error("include '" + node.file + "' not found", node); } @@ -4178,8 +2648,8 @@ class Renderer : public NodeVisitor { void visit(const ExtendsStatementNode& node) { const auto included_template_it = template_storage.find(node.file); if (included_template_it != template_storage.end()) { - const Template *parent_template = &included_template_it->second; - render_to(*output_stream, *parent_template, *json_input, &json_additional_data); + const Template* parent_template = &included_template_it->second; + render_to(*output_stream, *parent_template, *data_input, &additional_data); break_rendering = true; } else if (config.throw_at_missing_includes) { throw_renderer_error("extends '" + node.file + "' not found", node); @@ -4194,7 +2664,7 @@ class Renderer : public NodeVisitor { if (block_it != current_template->block_storage.end()) { block_statement_stack.emplace_back(&node); block_it->second->block.accept(*this); - block_statement_stack.pop_back(); + block_statement_stack.pop_back(); } current_level = old_level; current_template = template_stack.back(); @@ -4204,26 +2674,26 @@ class Renderer : public NodeVisitor { std::string ptr = node.key; replace_substring(ptr, ".", "/"); ptr = "/" + ptr; - json_additional_data[json::json_pointer(ptr)] = *eval_expression_list(node.expression); + additional_data[json::json_pointer(ptr)] = *eval_expression_list(node.expression); } public: - Renderer(const RenderConfig& config, const TemplateStorage &template_storage, const FunctionStorage &function_storage) - : config(config), template_storage(template_storage), function_storage(function_storage) { } + Renderer(const RenderConfig& config, const TemplateStorage& template_storage, const FunctionStorage& function_storage) + : config(config), template_storage(template_storage), function_storage(function_storage) {} - void render_to(std::ostream &os, const Template &tmpl, const json &data, json *loop_data = nullptr) { + void render_to(std::ostream& os, const Template& tmpl, const json& data, json* loop_data = nullptr) { output_stream = &os; current_template = &tmpl; - json_input = &data; + data_input = &data; if (loop_data) { - json_additional_data = *loop_data; - current_loop_data = &json_additional_data["loop"]; + additional_data = *loop_data; + current_loop_data = &additional_data["loop"]; } template_stack.emplace_back(current_template); current_template->root.accept(*this); - json_tmp_stack.clear(); + data_tmp_stack.clear(); } }; @@ -4231,8 +2701,6 @@ class Renderer : public NodeVisitor { #endif // INCLUDE_INJA_RENDERER_HPP_ -// #include "string_view.hpp" - // #include "template.hpp" // #include "utils.hpp" @@ -4244,9 +2712,6 @@ namespace inja { * \brief Class for changing the configuration. */ class Environment { - std::string input_path; - std::string output_path; - LexerConfig lexer_config; ParserConfig parser_config; RenderConfig render_config; @@ -4254,16 +2719,19 @@ class Environment { FunctionStorage function_storage; TemplateStorage template_storage; +protected: + std::string input_path; + std::string output_path; + public: - Environment() : Environment("") {} + Environment(): Environment("") {} - explicit Environment(const std::string &global_path) : input_path(global_path), output_path(global_path) {} + explicit Environment(const std::string& global_path): input_path(global_path), output_path(global_path) {} - Environment(const std::string &input_path, const std::string &output_path) - : input_path(input_path), output_path(output_path) {} + Environment(const std::string& input_path, const std::string& output_path): input_path(input_path), output_path(output_path) {} /// Sets the opener and closer for template statements - void set_statement(const std::string &open, const std::string &close) { + void set_statement(const std::string& open, const std::string& close) { lexer_config.statement_open = open; lexer_config.statement_open_no_lstrip = open + "+"; lexer_config.statement_open_force_lstrip = open + "-"; @@ -4273,13 +2741,13 @@ class Environment { } /// Sets the opener for template line statements - void set_line_statement(const std::string &open) { + void set_line_statement(const std::string& open) { lexer_config.line_statement = open; lexer_config.update_open_chars(); } /// Sets the opener and closer for template expressions - void set_expression(const std::string &open, const std::string &close) { + void set_expression(const std::string& open, const std::string& close) { lexer_config.expression_open = open; lexer_config.expression_open_force_lstrip = open + "-"; lexer_config.expression_close = close; @@ -4288,7 +2756,7 @@ class Environment { } /// Sets the opener and closer for template comments - void set_comment(const std::string &open, const std::string &close) { + void set_comment(const std::string& open, const std::string& close) { lexer_config.comment_open = open; lexer_config.comment_open_force_lstrip = open + "-"; lexer_config.comment_close = close; @@ -4316,116 +2784,119 @@ class Environment { render_config.throw_at_missing_includes = will_throw; } - Template parse(nonstd::string_view input) { + Template parse(std::string_view input) { Parser parser(parser_config, lexer_config, template_storage, function_storage); - return parser.parse(input); + return parser.parse(input, input_path); } - Template parse_template(const std::string &filename) { + Template parse_template(const std::string& filename) { Parser parser(parser_config, lexer_config, template_storage, function_storage); - auto result = Template(parser.load_file(input_path + static_cast(filename))); + auto result = Template(Parser::load_file(input_path + static_cast(filename))); parser.parse_into_template(result, input_path + static_cast(filename)); return result; } - Template parse_file(const std::string &filename) { + Template parse_file(const std::string& filename) { return parse_template(filename); } - std::string render(nonstd::string_view input, const json &data) { return render(parse(input), data); } + std::string render(std::string_view input, const json& data) { + return render(parse(input), data); + } - std::string render(const Template &tmpl, const json &data) { + std::string render(const Template& tmpl, const json& data) { std::stringstream os; render_to(os, tmpl, data); return os.str(); } - std::string render_file(const std::string &filename, const json &data) { + std::string render_file(const std::string& filename, const json& data) { return render(parse_template(filename), data); } - std::string render_file_with_json_file(const std::string &filename, const std::string &filename_data) { + std::string render_file_with_json_file(const std::string& filename, const std::string& filename_data) { const json data = load_json(filename_data); return render_file(filename, data); } - void write(const std::string &filename, const json &data, const std::string &filename_out) { + void write(const std::string& filename, const json& data, const std::string& filename_out) { std::ofstream file(output_path + filename_out); file << render_file(filename, data); file.close(); } - void write(const Template &temp, const json &data, const std::string &filename_out) { + void write(const Template& temp, const json& data, const std::string& filename_out) { std::ofstream file(output_path + filename_out); file << render(temp, data); file.close(); } - void write_with_json_file(const std::string &filename, const std::string &filename_data, - const std::string &filename_out) { + void write_with_json_file(const std::string& filename, const std::string& filename_data, const std::string& filename_out) { const json data = load_json(filename_data); write(filename, data, filename_out); } - void write_with_json_file(const Template &temp, const std::string &filename_data, const std::string &filename_out) { + void write_with_json_file(const Template& temp, const std::string& filename_data, const std::string& filename_out) { const json data = load_json(filename_data); write(temp, data, filename_out); } - std::ostream &render_to(std::ostream &os, const Template &tmpl, const json &data) { + std::ostream& render_to(std::ostream& os, const Template& tmpl, const json& data) { Renderer(render_config, template_storage, function_storage).render_to(os, tmpl, data); return os; } - std::string load_file(const std::string &filename) { + std::string load_file(const std::string& filename) { Parser parser(parser_config, lexer_config, template_storage, function_storage); - return parser.load_file(input_path + filename); + return Parser::load_file(input_path + filename); } - json load_json(const std::string &filename) { + json load_json(const std::string& filename) { std::ifstream file; file.open(input_path + filename); if (file.fail()) { INJA_THROW(FileError("failed accessing file at '" + input_path + filename + "'")); } - json j; - file >> j; - return j; + + return json::parse(std::istreambuf_iterator(file), std::istreambuf_iterator()); } /*! @brief Adds a variadic callback */ - void add_callback(const std::string &name, const CallbackFunction &callback) { + void add_callback(const std::string& name, const CallbackFunction& callback) { add_callback(name, -1, callback); } /*! @brief Adds a variadic void callback */ - void add_void_callback(const std::string &name, const VoidCallbackFunction &callback) { + void add_void_callback(const std::string& name, const VoidCallbackFunction& callback) { add_void_callback(name, -1, callback); } /*! @brief Adds a callback with given number or arguments */ - void add_callback(const std::string &name, int num_args, const CallbackFunction &callback) { + void add_callback(const std::string& name, int num_args, const CallbackFunction& callback) { function_storage.add_callback(name, num_args, callback); } /*! @brief Adds a void callback with given number or arguments */ - void add_void_callback(const std::string &name, int num_args, const VoidCallbackFunction &callback) { - function_storage.add_callback(name, num_args, [callback](Arguments& args) { callback(args); return json(); }); + void add_void_callback(const std::string& name, int num_args, const VoidCallbackFunction& callback) { + function_storage.add_callback(name, num_args, [callback](Arguments& args) { + callback(args); + return json(); + }); } /** Includes a template with a given name into the environment. * Then, a template can be rendered in another template using the * include "" syntax. */ - void include_template(const std::string &name, const Template &tmpl) { + void include_template(const std::string& name, const Template& tmpl) { template_storage[name] = tmpl; } @@ -4440,14 +2911,14 @@ class Environment { /*! @brief render with default settings to a string */ -inline std::string render(nonstd::string_view input, const json &data) { +inline std::string render(std::string_view input, const json& data) { return Environment().render(input, data); } /*! @brief render with default settings to the given output stream */ -inline void render_to(std::ostream &os, nonstd::string_view input, const json &data) { +inline void render_to(std::ostream& os, std::string_view input, const json& data) { Environment env; env.render_to(os, env.parse(input), data); } @@ -4462,9 +2933,7 @@ inline void render_to(std::ostream &os, nonstd::string_view input, const json &d // #include "renderer.hpp" -// #include "string_view.hpp" - // #include "template.hpp" -#endif // INCLUDE_INJA_INJA_HPP_ \ No newline at end of file +#endif // INCLUDE_INJA_INJA_HPP_ diff --git a/include/jpcre2.hpp b/include/jpcre2.hpp index 073627562..5adaa9024 100644 --- a/include/jpcre2.hpp +++ b/include/jpcre2.hpp @@ -76,8 +76,14 @@ #ifndef JPCRE2_USE_FUNCTION_POINTER_CALLBACK #include // std::function #endif +#endif +#if __cplusplus >= 201703L || _MSVC_LANG >= 201703L + #define JPCRE2_USE_MINIMUM_CXX_17 1 + #include #else - #define JPCRE2_USE_MINIMUM_CXX_11 0 + #ifdef JPCRE2_UNSET_CAPTURES_NULL + #error JPCRE2_UNSET_CAPTURES_NULL requires C++17 + #endif #endif #define JPCRE2_UNUSED(x) ((void)(x)) @@ -194,7 +200,7 @@ static inline void _jvassert(bool cond, char const * name, const char* f, size_t static inline std::string _tostdstring(unsigned x){ char buf[128]; - int written = std::sprintf(buf, "%u", x); + int written = std::snprintf(buf, 128, "%u", x); return (written > 0) ? std::string(buf, buf + written) : std::string(); } @@ -1197,7 +1203,7 @@ template<> inline std::basic_string MSG::INVALID_MODIFIER(){ return template<> inline std::basic_string MSG::INVALID_MODIFIER(){ return L"Invalid modifier: "; } template<> inline std::basic_string MSG::INSUFFICIENT_OVECTOR(){ return "ovector wasn't big enough"; } template<> inline std::basic_string MSG::INSUFFICIENT_OVECTOR(){ return L"ovector wasn't big enough"; } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template<> inline std::basic_string MSG::INVALID_MODIFIER(){ return u"Invalid modifier: "; } template<> inline std::basic_string MSG::INVALID_MODIFIER(){ return U"Invalid modifier: "; } template<> inline std::basic_string MSG::INSUFFICIENT_OVECTOR(){ return u"ovector wasn't big enough"; } @@ -1230,7 +1236,7 @@ template<> inline std::basic_string MSG::INSUFFICIENT_OVECTO ///```cpp ///typedef jpcre2::select jp; ///``` -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map=std::map> #else template @@ -1252,7 +1258,7 @@ struct select{ ///char32_t | std::u32string (>=C++11) typedef typename std::basic_string String; - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 ///Map for Named substrings. typedef class Map MapNas; ///Substring name to Substring number map. @@ -1268,7 +1274,11 @@ struct select{ typedef MapNtN MapNtn; ///Vector for Numbered substrings (Sub container). + #ifdef JPCRE2_UNSET_CAPTURES_NULL + typedef typename std::vector> NumSub; + #else typedef typename std::vector NumSub; + #endif ///Vector of matches with named substrings. typedef typename std::vector VecNas; ///Vector of substring name to substring number map. @@ -1449,7 +1459,7 @@ struct select{ onlyCopy(rm); } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 void deepMove(RegexMatch& rm){ m_subject = std::move_if_noexcept(rm.m_subject); onlyCopy(rm); @@ -1498,7 +1508,7 @@ struct select{ return *this; } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 ///@overload ///... ///Move constructor. @@ -1579,7 +1589,7 @@ struct select{ /// Returns the last error message ///@return Last error message virtual String getErrorMessage() const { - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 return select::getErrorMessage(error_number, error_offset); #else return select::getErrorMessage(error_number, error_offset); @@ -2044,14 +2054,18 @@ struct select{ ///@param ntn jp::MapNtN map. ///@return total match (group 0) of current match. static String fill(NumSub const &num, MapNas const &nas, MapNtn const &ntn){ + #ifdef JPCRE2_UNSET_CAPTURES_NULL + return *num[0]; + #else return num[0]; + #endif } private: //prevent object instantiation. callback(); callback(callback const &); - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 callback(callback&&); #endif ~callback(); @@ -2219,7 +2233,7 @@ struct select{ onlyCopy(me); } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 void deepMove(MatchEvaluator& me){ vec_num = std::move_if_noexcept(me.vec_num); vec_nas = std::move_if_noexcept(me.vec_nas); @@ -2391,7 +2405,7 @@ struct select{ return *this; } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 ///@overload /// ... @@ -2957,7 +2971,7 @@ struct select{ onlyCopy(rr); } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 void deepMove(RegexReplace& rr){ r_subject = std::move_if_noexcept(rr.r_subject); onlyCopy(rr); @@ -3005,7 +3019,7 @@ struct select{ return *this; } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 ///@overload ///... @@ -3080,7 +3094,7 @@ struct select{ /// Returns the last error message ///@return Last error message String getErrorMessage() const { - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 return select::getErrorMessage(error_number, error_offset); #else return select::getErrorMessage(error_number, error_offset); @@ -3619,7 +3633,7 @@ struct select{ : freeRegexMemory(); } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 void deepMove(Regex& r) { pat_str = std::move_if_noexcept(r.pat_str); @@ -3740,7 +3754,7 @@ struct select{ } - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 /// @overload @@ -3895,6 +3909,15 @@ struct select{ return pat_str_ptr; } + ///Get number of captures from compiled code. + ///@return New line option value or 0. + Uint getNumCaptures() { + if(!code) return 0; + Uint numCaptures = 0; + int ret = Pcre2Func::pattern_info(code, PCRE2_INFO_CAPTURECOUNT, &numCaptures); + if(ret < 0) error_number = ret; + return numCaptures; + } /// Calculate modifier string from PCRE2 and JPCRE2 options and return it. /// @@ -3944,7 +3967,7 @@ struct select{ /// Returns the last error message ///@return Last error message String getErrorMessage() const { - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 return select::getErrorMessage(error_number, error_offset); #else return select::getErrorMessage(error_number, error_offset); @@ -4388,7 +4411,7 @@ struct select{ //prevent object instantiation of select class select(); select(select const &); - #if JPCRE2_USE_MINIMUM_CXX_11 + #ifdef JPCRE2_USE_MINIMUM_CXX_11 select(select&&); #endif ~select(); @@ -4417,7 +4440,7 @@ inline void jpcre2::ModifierTable::parseModifierTable(std::string& tabjs, VecOpt } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> void jpcre2::select::Regex::compile() { #else @@ -4458,7 +4481,7 @@ void jpcre2::select::Regex::compile() { } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> typename jpcre2::select::String jpcre2::select::MatchEvaluator::replace(bool do_match, Uint replace_opts, SIZE_T * counter) { #else @@ -4488,7 +4511,7 @@ typename jpcre2::select::String jpcre2::select::MatchEvaluator:: SIZE_T last = vec_eoff.size(); last = (last>0)?last-1:0; JPCRE2_ASSERT(vec_eoff[last] <= RegexMatch::getSubject().size(), "ValueError: subject string is not of the required size, may be it's changed!!!\ - If you are using esisting match data, try a new match."); + If you are using existing match data, try a new match."); //loop through the matches for(SIZE_T i=0;i::String jpcre2::select::MatchEvaluator:: //second part ///the matched part is the subject //~ Pcre2Sptr subject = (Pcre2Sptr) RegexMatch::getSubjectPointer()->c_str(); - //substr(vec_soff[i], vec_eoff[i] - vec_soff[i]).c_str();//->substr(vec_soff[i], vec_eoff[i]-vec_soff[i]); + //substr(vec_soff[i], vec_eoff[i] - vec_soff[i]).c_str(); Pcre2Sptr subject = r_subject_ptr + vec_soff[i]; PCRE2_SIZE subject_length = vec_eoff[i] - vec_soff[i]; @@ -4586,7 +4609,7 @@ typename jpcre2::select::String jpcre2::select::MatchEvaluator:: } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> typename jpcre2::select::String jpcre2::select::MatchEvaluator::nreplace(bool do_match, Uint jo, SIZE_T* counter){ #else @@ -4605,7 +4628,7 @@ typename jpcre2::select::String jpcre2::select::MatchEvaluator:: SIZE_T last = vec_eoff.size(); last = (last>0)?last-1:0; JPCRE2_ASSERT(vec_eoff[last] <= RegexMatch::getSubject().size(), "ValueError: subject string is not of the required size, may be it's changed!!!\ - If you are using esisting match data, try a new match."); + If you are using existing match data, try a new match."); //loop through the matches for(SIZE_T i=0;i::String jpcre2::select::MatchEvaluator:: } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> typename jpcre2::select::String jpcre2::select::RegexReplace::replace() { #else @@ -4713,7 +4736,7 @@ typename jpcre2::select::String jpcre2::select::RegexReplace::re } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> bool jpcre2::select::RegexMatch::getNumberedSubstrings(int rc, Pcre2Sptr subject, PCRE2_SIZE* ovector, uint32_t ovector_count) { #else @@ -4724,16 +4747,22 @@ bool jpcre2::select::RegexMatch::getNumberedSubstrings(int rc, Pcre2Sptr uint32_t rcu = rc; num_sub.reserve(rcu); //we know exactly how many elements it will have. uint32_t i; - for (i = 0u; i < rcu; i++) - num_sub.push_back(String((Char*)(subject + ovector[2*i]), ovector[2*i+1] - ovector[2*i])); - for (uint32_t j = i; j < ovector_count; j++) - num_sub.push_back(String()); + for (i = 0u; i < ovector_count; i++) { + if (ovector[2*i] != PCRE2_UNSET) + num_sub.push_back(String((Char*)(subject + ovector[2*i]), ovector[2*i+1] - ovector[2*i])); + else + #ifdef JPCRE2_UNSET_CAPTURES_NULL + num_sub.push_back(std::nullopt); + #else + num_sub.push_back(String()); + #endif + } vec_num->push_back(num_sub); //this function shouldn't be called if this vector is null return true; } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> bool jpcre2::select::RegexMatch::getNamedSubstrings(int namecount, int name_entry_size, Pcre2Sptr name_table, @@ -4771,7 +4800,7 @@ bool jpcre2::select::RegexMatch::getNamedSubstrings(int namecount, int n } -#if JPCRE2_USE_MINIMUM_CXX_11 +#ifdef JPCRE2_USE_MINIMUM_CXX_11 template class Map> jpcre2::SIZE_T jpcre2::select::RegexMatch::match() { #else @@ -5113,6 +5142,11 @@ jpcre2::SIZE_T jpcre2::select::RegexMatch::match() { ///Using the standard `NDEBUG` macro will have the same effect, ///but it is recommended that you use `JPCRE2_NDEBUG` to strip out debug codes specifically for this library. + +///@def JPCRE2_UNSET_CAPTURES_NULL +///Define to change the type of NumSub so that captures are recorded +///with std::optional. It is undefined by default. This feature requires C++17. + #endif diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp index 8959265da..4d1a37ad7 100644 --- a/include/nlohmann/json.hpp +++ b/include/nlohmann/json.hpp @@ -1,39 +1,23 @@ -/* - __ _____ _____ _____ - __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 3.10.2 -|_____|_____|_____|_|___| https://github.com/nlohmann/json - -Licensed under the MIT License . -SPDX-License-Identifier: MIT -Copyright (c) 2013-2019 Niels Lohmann . - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ #ifndef INCLUDE_NLOHMANN_JSON_HPP_ #define INCLUDE_NLOHMANN_JSON_HPP_ -#define NLOHMANN_JSON_VERSION_MAJOR 3 -#define NLOHMANN_JSON_VERSION_MINOR 10 -#define NLOHMANN_JSON_VERSION_PATCH 2 - #include // all_of, find, for_each #include // nullptr_t, ptrdiff_t, size_t #include // hash, less @@ -49,12 +33,129 @@ SOFTWARE. #include // vector // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + -#include #include +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 2 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 2 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + #include // transform @@ -70,14 +171,31 @@ SOFTWARE. #include // valarray // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + +#include // nullptr_t #include // exception #include // runtime_error #include // to_string #include // vector // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + #include // array @@ -85,102 +203,130 @@ SOFTWARE. #include // uint8_t #include // string -namespace nlohmann -{ +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { -/////////////////////////// -// JSON type enumeration // -/////////////////////////// -/*! -@brief the JSON type enumeration +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. -@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ -@since version 1.0.0 -*/ -enum class value_t : std::uint8_t +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch { - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - binary, ///< binary array (ordered collection of bytes) - discarded ///< discarded by the parser callback function + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; }; -/*! -@brief comparison operator for JSON types - -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string < binary -- furthermore, each type is not smaller than itself -- discarded values are not comparable -- binary is represented as a b"" string in python and directly comparable to a - string; however, making a binary array directly comparable with a string would - be surprising behavior in a JSON file. +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; -@since version 1.0.0 -*/ -inline bool operator<(const value_t lhs, const value_t rhs) noexcept +template class Op, class... Args> +struct detector>, Op, Args...> { - static constexpr std::array order = {{ - 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, - 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, - 6 /* binary */ - } - }; + using value_t = std::true_type; + using type = Op; +}; - const auto l_index = static_cast(lhs); - const auto r_index = static_cast(rhs); - return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; -} -} // namespace detail -} // namespace nlohmann +template class Op, class... Args> +using is_detected = typename detector::value_t; -// #include +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; +template class Op, class... Args> +using detected_t = typename detector::type; -#include -// #include +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END -#include // pair // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson +// SPDX-License-Identifier: MIT + /* Hedley - https://nemequ.github.io/hedley * Created by Evan Nemerson - * - * To the extent possible under law, the author(s) have dedicated all - * copyright and related and neighboring rights to this software to - * the public domain worldwide. This software is distributed without - * any warranty. - * - * For details, see . - * SPDX-License-Identifier: CC0-1.0 */ #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) @@ -2215,9 +2361,12 @@ JSON_HEDLEY_DIAGNOSTIC_POP #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ -// This file contains all internal macro definitions +// This file contains all internal macro definitions (except those affecting ABI) // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them +// #include + + // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) @@ -2248,6 +2397,104 @@ JSON_HEDLEY_DIAGNOSTIC_POP #define JSON_HAS_CPP_11 #endif +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + // disable documentation warnings on clang #if defined(__clang__) #pragma clang diagnostic push @@ -2255,7 +2502,7 @@ JSON_HEDLEY_DIAGNOSTIC_POP #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #endif -// allow to disable exceptions +// allow disabling exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try @@ -2289,7 +2536,7 @@ JSON_HEDLEY_DIAGNOSTIC_POP #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif -// allow to override assert +// allow overriding assert #if !defined(JSON_ASSERT) #include // assert #define JSON_ASSERT(x) assert(x) @@ -2485,6 +2732,7 @@ JSON_HEDLEY_DIAGNOSTIC_POP #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1); /*! @brief macro @@ -2495,6 +2743,10 @@ JSON_HEDLEY_DIAGNOSTIC_POP friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { Type nlohmann_json_default_obj; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + /*! @brief macro @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE @@ -2504,6 +2756,49 @@ JSON_HEDLEY_DIAGNOSTIC_POP inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { Type nlohmann_json_default_obj; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + #ifndef JSON_USE_IMPLICIT_CONVERSIONS #define JSON_USE_IMPLICIT_CONVERSIONS 1 #endif @@ -2514,35 +2809,155 @@ JSON_HEDLEY_DIAGNOSTIC_POP #define JSON_EXPLICIT explicit #endif -#ifndef JSON_DIAGNOSTICS - #define JSON_DIAGNOSTICS 0 +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 #endif +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif -namespace nlohmann -{ +NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { -/*! -@brief replace all occurrences of a substring by another string - -@param[in,out] s the string to manipulate; changed so that all - occurrences of @a f are replaced with @a t -@param[in] f the substring to replace with @a t -@param[in] t the string to replace @a f +/////////////////////////// +// JSON type enumeration // +/////////////////////////// -@pre The search string @a f must not be empty. **This precondition is -enforced with an assertion.** +/*! +@brief the JSON type enumeration -@since version 2.0.0 -*/ -inline void replace_substring(std::string& s, const std::string& f, - const std::string& t) -{ +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ JSON_ASSERT(!f.empty()); for (auto pos = s.find(f); // find first occurrence of f - pos != std::string::npos; // make sure f was found + pos != StringType::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} @@ -2555,10 +2970,11 @@ inline void replace_substring(std::string& s, const std::string& f, * * Note the order of escaping "~" to "~0" and "/" to "~1" is important. */ -inline std::string escape(std::string s) +template +inline StringType escape(StringType s) { - replace_substring(s, "~", "~0"); - replace_substring(s, "/", "~1"); + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); return s; } @@ -2569,24 +2985,36 @@ inline std::string escape(std::string s) * * Note the order of escaping "~1" to "/" and "~0" to "~" is important. */ -static void unescape(std::string& s) +template +static void unescape(StringType& s) { - replace_substring(s, "~1", "/"); - replace_substring(s, "~0", "~"); + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); } -} // namespace detail -} // namespace nlohmann +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + #include // size_t -namespace nlohmann -{ +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { + /// struct to capture the start position of the current token struct position_t { @@ -2604,497 +3032,85 @@ struct position_t } }; -} // namespace detail -} // namespace nlohmann +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END // #include +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT -namespace nlohmann -{ -namespace detail -{ -//////////////// -// exceptions // -//////////////// - -/*! -@brief general exception of the @ref basic_json class -This class is an extension of `std::exception` objects with a member @a id for -exception ids. It is used as the base class for all exceptions thrown by the -@ref basic_json class. This class can hence be used as "wildcard" to catch -exceptions. -Subclasses: -- @ref parse_error for exceptions indicating a parse error -- @ref invalid_iterator for exceptions indicating errors with iterators -- @ref type_error for exceptions indicating executing a member function with - a wrong type -- @ref out_of_range for exceptions indicating access out of the defined range -- @ref other_error for exceptions indicating other library errors +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for -@internal -@note To have nothrow-copy-constructible exceptions, we internally use - `std::runtime_error` which can cope with arbitrary-length error messages. - Intermediate strings are built with static functions and then passed to - the actual constructor. -@endinternal +// #include -@liveexample{The following code shows how arbitrary library exceptions can be -caught.,exception} -@since version 3.0.0 -*/ -class exception : public std::exception +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail { - public: - /// returns the explanatory string - const char* what() const noexcept override - { - return m.what(); - } - - /// the id of the exception - const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - - protected: - JSON_HEDLEY_NON_NULL(3) - exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} - static std::string name(const std::string& ename, int id_) - { - return "[json.exception." + ename + "." + std::to_string(id_) + "] "; - } +template +using uncvref_t = typename std::remove_cv::type>::type; - template - static std::string diagnostics(const BasicJsonType& leaf_element) - { -#if JSON_DIAGNOSTICS - std::vector tokens; - for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) - { - switch (current->m_parent->type()) - { - case value_t::array: - { - for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) - { - if (¤t->m_parent->m_value.array->operator[](i) == current) - { - tokens.emplace_back(std::to_string(i)); - break; - } - } - break; - } +#ifdef JSON_HAS_CPP_14 - case value_t::object: - { - for (const auto& element : *current->m_parent->m_value.object) - { - if (&element.second == current) - { - tokens.emplace_back(element.first.c_str()); - break; - } - } - break; - } +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; - case value_t::null: // LCOV_EXCL_LINE - case value_t::string: // LCOV_EXCL_LINE - case value_t::boolean: // LCOV_EXCL_LINE - case value_t::number_integer: // LCOV_EXCL_LINE - case value_t::number_unsigned: // LCOV_EXCL_LINE - case value_t::number_float: // LCOV_EXCL_LINE - case value_t::binary: // LCOV_EXCL_LINE - case value_t::discarded: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - break; // LCOV_EXCL_LINE - } - } +#else - if (tokens.empty()) - { - return ""; - } +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; - return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, - [](const std::string & a, const std::string & b) - { - return a + "/" + detail::escape(b); - }) + ") "; -#else - static_cast(leaf_element); - return ""; -#endif - } +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. - private: - /// an exception object as storage for error messages - std::runtime_error m; -}; +//// START OF CODE FROM GOOGLE ABSEIL -/*! -@brief exception indicating a parse error - -This exception is thrown by the library when a parse error occurs. Parse errors -can occur during the deserialization of JSON text, CBOR, MessagePack, as well -as when using JSON Patch. - -Member @a byte holds the byte index of the last read character in the input -file. - -Exceptions have ids 1xx. - -name / id | example message | description ------------------------------- | --------------- | ------------------------- -json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. -json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. -json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. -json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. -json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. -json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. -json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. -json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. -json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. -json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. -json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. -json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. -json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). -json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed. - -@note For an input with n bytes, 1 is the index of the first character and n+1 - is the index of the terminating null byte or the end of file. This also - holds true when reading a byte vector (CBOR or MessagePack). - -@liveexample{The following code shows how a `parse_error` exception can be -caught.,parse_error} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref out_of_range for exceptions indicating access out of the defined range -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class parse_error : public exception +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence { - public: - /*! - @brief create a parse error exception - @param[in] id_ the id of the exception - @param[in] pos the position where the error occurred (or with - chars_read_total=0 if the position cannot be - determined) - @param[in] what_arg the explanatory string - @return parse_error object - */ - template - static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - position_string(pos) + ": " + exception::diagnostics(context) + what_arg; - return parse_error(id_, pos.chars_read_total, w.c_str()); - } - - template - static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) + using value_type = T; + static constexpr std::size_t size() noexcept { - std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + - ": " + exception::diagnostics(context) + what_arg; - return parse_error(id_, byte_, w.c_str()); + return sizeof...(Ints); } - - /*! - @brief byte index of the parse error - - The byte index of the last read character in the input file. - - @note For an input with n bytes, 1 is the index of the first character and - n+1 is the index of the terminating null byte or the end of file. - This also holds true when reading a byte vector (CBOR or MessagePack). - */ - const std::size_t byte; - - private: - parse_error(int id_, std::size_t byte_, const char* what_arg) - : exception(id_, what_arg), byte(byte_) {} - - static std::string position_string(const position_t& pos) - { - return " at line " + std::to_string(pos.lines_read + 1) + - ", column " + std::to_string(pos.chars_read_current_line); - } -}; - -/*! -@brief exception indicating errors with iterators - -This exception is thrown if iterators passed to a library function do not match -the expected semantics. - -Exceptions have ids 2xx. - -name / id | example message | description ------------------------------------ | --------------- | ------------------------- -json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. -json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. -json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. -json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. -json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. -json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. -json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. -json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. -json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. -json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. -json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. -json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. -json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. -json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). - -@liveexample{The following code shows how an `invalid_iterator` exception can be -caught.,invalid_iterator} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref out_of_range for exceptions indicating access out of the defined range -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class invalid_iterator : public exception -{ - public: - template - static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; - return invalid_iterator(id_, w.c_str()); - } - - private: - JSON_HEDLEY_NON_NULL(3) - invalid_iterator(int id_, const char* what_arg) - : exception(id_, what_arg) {} -}; - -/*! -@brief exception indicating executing a member function with a wrong type - -This exception is thrown in case of a type error; that is, a library function is -executed on a JSON value whose type does not match the expected semantics. - -Exceptions have ids 3xx. - -name / id | example message | description ------------------------------ | --------------- | ------------------------- -json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. -json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. -json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. -json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. -json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. -json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. -json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. -json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. -json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. -json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. -json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. -json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. -json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. -json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. -json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. -json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | -json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | - -@liveexample{The following code shows how a `type_error` exception can be -caught.,type_error} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref out_of_range for exceptions indicating access out of the defined range -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class type_error : public exception -{ - public: - template - static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; - return type_error(id_, w.c_str()); - } - - private: - JSON_HEDLEY_NON_NULL(3) - type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/*! -@brief exception indicating access out of the defined range - -This exception is thrown in case a library function is called on an input -parameter that exceeds the expected range, for instance in case of array -indices or nonexisting object keys. - -Exceptions have ids 4xx. - -name / id | example message | description -------------------------------- | --------------- | ------------------------- -json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. -json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. -json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. -json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. -json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. -json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. -json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) | -json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | -json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | - -@liveexample{The following code shows how an `out_of_range` exception can be -caught.,out_of_range} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class out_of_range : public exception -{ - public: - template - static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; - return out_of_range(id_, w.c_str()); - } - - private: - JSON_HEDLEY_NON_NULL(3) - out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/*! -@brief exception indicating other library errors - -This exception is thrown in case of errors that cannot be classified with the -other exception types. - -Exceptions have ids 5xx. - -name / id | example message | description ------------------------------- | --------------- | ------------------------- -json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref out_of_range for exceptions indicating access out of the defined range - -@liveexample{The following code shows how an `other_error` exception can be -caught.,other_error} - -@since version 3.0.0 -*/ -class other_error : public exception -{ - public: - template - static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; - return other_error(id_, w.c_str()); - } - - private: - JSON_HEDLEY_NON_NULL(3) - other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // size_t -#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type -#include // index_sequence, make_index_sequence, index_sequence_for - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -template -using uncvref_t = typename std::remove_cv::type>::type; - -#ifdef JSON_HAS_CPP_14 - -// the following utilities are natively available in C++14 -using std::enable_if_t; -using std::index_sequence; -using std::make_index_sequence; -using std::index_sequence_for; - -#else - -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; - -// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h -// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. - -//// START OF CODE FROM GOOGLE ABSEIL - -// integer_sequence -// -// Class template representing a compile-time integer sequence. An instantiation -// of `integer_sequence` has a sequence of integers encoded in its -// type through its template arguments (which is a common need when -// working with C++11 variadic templates). `absl::integer_sequence` is designed -// to be a drop-in replacement for C++14's `std::integer_sequence`. -// -// Example: -// -// template< class T, T... Ints > -// void user_function(integer_sequence); -// -// int main() -// { -// // user_function's `T` will be deduced to `int` and `Ints...` -// // will be deduced to `0, 1, 2, 3, 4`. -// user_function(make_integer_sequence()); -// } -template -struct integer_sequence -{ - using value_type = T; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } -}; +}; // index_sequence // @@ -3178,28 +3194,32 @@ template<> struct priority_tag<0> {}; template struct static_const { - static constexpr T value{}; + static JSON_INLINE_VARIABLE constexpr T value{}; }; -template -constexpr T static_const::value; - -} // namespace detail -} // namespace nlohmann - -// #include - +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif -namespace nlohmann -{ -namespace detail +template +inline constexpr std::array make_array(Args&& ... args) { -// dispatching helper struct -template struct identity_tag {}; + return std::array {{static_cast(std::forward(args))...}}; +} + } // namespace detail -} // namespace nlohmann +NLOHMANN_JSON_NAMESPACE_END // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + #include // numeric_limits @@ -3208,32 +3228,29 @@ template struct identity_tag {}; #include // tuple // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT -#include // random_access_iterator_tag -// #include +#include // random_access_iterator_tag +// #include -namespace nlohmann -{ -namespace detail -{ -template struct make_void -{ - using type = void; -}; -template using void_t = typename make_void::type; -} // namespace detail -} // namespace nlohmann +// #include // #include -namespace nlohmann -{ +NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { + template struct iterator_types {}; @@ -3272,160 +3289,135 @@ struct iterator_traits::value>> using pointer = T*; using reference = T&; }; -} // namespace detail -} // namespace nlohmann + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END // #include -// #include +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT -// #include -#include +// #include -// #include +NLOHMANN_JSON_NAMESPACE_BEGIN -// https://en.cppreference.com/w/cpp/experimental/is_detected -namespace nlohmann -{ -namespace detail -{ -struct nonesuch -{ - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; -}; +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); -template class Op, - class... Args> -struct detector -{ - using value_t = std::false_type; - using type = Default; -}; +NLOHMANN_JSON_NAMESPACE_END -template class Op, class... Args> -struct detector>, Op, Args...> -{ - using value_t = std::true_type; - using type = Op; -}; +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT -template class Op, class... Args> -using is_detected = typename detector::value_t; -template class Op, class... Args> -struct is_detected_lazy : is_detected { }; -template class Op, class... Args> -using detected_t = typename detector::type; +// #include -template class Op, class... Args> -using detected_or = detector; -template class Op, class... Args> -using detected_or_t = typename detected_or::type; +NLOHMANN_JSON_NAMESPACE_BEGIN -template class Op, class... Args> -using is_detected_exact = std::is_same>; +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); -template class Op, class... Args> -using is_detected_convertible = - std::is_convertible, To>; -} // namespace detail -} // namespace nlohmann +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include // #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ -#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ -#include // int64_t, uint64_t -#include // map -#include // allocator -#include // string -#include // vector + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -/*! -@brief default JSONSerializer template argument + // #include -This serializer ignores the template arguments and uses ADL -([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) -for serialization. -*/ -template -struct adl_serializer; - -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer, - class BinaryType = std::vector> -class basic_json; -/*! -@brief JSON Pointer - -A JSON pointer defines a string syntax for identifying a specific value -within a JSON document. It can be used with functions `at` and -`operator[]`. Furthermore, JSON pointers are the base for JSON patches. - -@sa [RFC 6901](https://tools.ietf.org/html/rfc6901) - -@since version 2.0.0 -*/ -template -class json_pointer; + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN -/*! -@brief default JSON class + /*! + @brief default JSONSerializer template argument -This type is the default specialization of the @ref basic_json class which -uses the standard template types. + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; -@since version 1.0.0 -*/ -using json = basic_json<>; + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> + class basic_json; -template -struct ordered_map; + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; -/*! -@brief ordered JSON class + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; -This type preserves the insertion order of object keys. + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; -@since version 3.9.0 -*/ -using ordered_json = basic_json; + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; -} // namespace nlohmann + NLOHMANN_JSON_NAMESPACE_END #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ -namespace nlohmann -{ +NLOHMANN_JSON_NAMESPACE_BEGIN /*! @brief detail namespace with internal helper functions @@ -3436,6 +3428,7 @@ implementations of some @ref basic_json methods, and meta-programming helpers. */ namespace detail { + ///////////// // helpers // ///////////// @@ -3454,6 +3447,16 @@ template struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json : std::true_type {}; +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + ////////////////////// // json_ref helpers // ////////////////////// @@ -3492,9 +3495,6 @@ using reference_t = typename T::reference; template using iterator_category_t = typename T::iterator_category; -template -using iterator_t = typename T::iterator; - template using to_json_function = decltype(T::to_json(std::declval()...)); @@ -3558,6 +3558,24 @@ struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> T>::value; }; +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; /////////////////// // is_ functions // @@ -3565,10 +3583,10 @@ struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> // https://en.cppreference.com/w/cpp/types/conjunction template struct conjunction : std::true_type { }; -template struct conjunction : B1 { }; -template -struct conjunction -: std::conditional, B1>::type {}; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; // https://en.cppreference.com/w/cpp/types/negation template struct negation : std::integral_constant < bool, !B::value > { }; @@ -3630,6 +3648,31 @@ struct is_iterator_traits> is_detected::value; }; +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + // The following implementation of is_complete_type is taken from // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ // and is written by Xiang Fan who agreed to using it in this library. @@ -3697,60 +3740,46 @@ struct is_constructible_object_type : is_constructible_object_type_impl {}; -template -struct is_compatible_string_type_impl : std::false_type {}; - template -struct is_compatible_string_type_impl < - BasicJsonType, CompatibleStringType, - enable_if_t::value >> +struct is_compatible_string_type { static constexpr auto value = is_constructible::value; }; template -struct is_compatible_string_type - : is_compatible_string_type_impl {}; - -template -struct is_constructible_string_type_impl : std::false_type {}; - -template -struct is_constructible_string_type_impl < - BasicJsonType, ConstructibleStringType, - enable_if_t::value >> +struct is_constructible_string_type { + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + static constexpr auto value = - is_constructible::value; + conjunction < + is_constructible, + is_detected_exact>::value; }; -template -struct is_constructible_string_type - : is_constructible_string_type_impl {}; - template struct is_compatible_array_type_impl : std::false_type {}; template struct is_compatible_array_type_impl < BasicJsonType, CompatibleArrayType, - enable_if_t < is_detected::value&& + enable_if_t < is_detected::value&& -// This is needed because json_reverse_iterator has a ::iterator type... -// Therefore it is detected as a CompatibleArrayType. -// The real fix would be to have an Iterable concept. - !is_iterator_traits < - iterator_traits>::value >> + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> { static constexpr bool value = is_constructible::value; + range_value_t>::value; }; template @@ -3772,130 +3801,800 @@ struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& is_default_constructible::value&& (std::is_move_assignable::value || std::is_copy_assignable::value)&& -is_detected::value&& is_detected::value&& -is_complete_type < -detected_t>::value >> +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> { + using value_type = range_value_t; + static constexpr bool value = - // This is needed because json_reverse_iterator has a ::iterator type, - // furthermore, std::back_insert_iterator (and other iterators) have a - // base class `iterator`... Therefore it is detected as a - // ConstructibleArrayType. The real fix would be to have an Iterable - // concept. - !is_iterator_traits>::value && - - (std::is_same::value || - has_from_json::value || - has_non_default_from_json < - BasicJsonType, typename ConstructibleArrayType::value_type >::value); + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template