summaryrefslogtreecommitdiff
path: root/libadhocutil/nvpParse.h
blob: fe943dc189e07d8246c921a8cb3fa987394b8b2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#ifndef ADHOCUTIL_REFLECTION_H
#define ADHOCUTIL_REFLECTION_H

#include <boost/lexical_cast.hpp>
#include <functional>
#include <istream>
#include <map>
#include <memory>
#include <string>
#ifndef yyFlexLexer
#	define yyFlexLexer nvpBaseFlexLexer
#	include <FlexLexer.h>
#endif
#include "c++11Helpers.h"
#include "visibility.h"

namespace AdHoc {

	/// Name=Value parser.
	/**
	 * Parses an input stream of the format Name=Value;Name2=Value2;... into a predefined object
	 * structure.
	 */
	class NvpParse : public yyFlexLexer {
	public:
		/// @cond
		/// Thrown in the event of the input referring to a member that doesn't exist.
		class ValueNotFound : public std::runtime_error {
		public:
			explicit ValueNotFound(const std::string &);
		};

		using AssignFunc = std::function<void(const std::string &)>;
		using AssignMap = std::map<std::string, AssignFunc>;

		template<typename T> class TargetBase {
		public:
			TargetBase() = default;
			virtual ~TargetBase() = default;
			virtual AssignFunc assign(T *) const = 0;
			SPECIAL_MEMBERS_DEFAULT(TargetBase);
		};

		template<typename T, typename V> class Target : public TargetBase<T> {
		public:
			explicit Target(V T::*t) : target(t) { }

			AssignFunc
			assign(T * t) const override
			{
				return [t, this](const std::string & value) {
					t->*target = boost::lexical_cast<V>(value);
				};
			}

		private:
			V T::*target;
		};
		/// @endcond

#define NvpTarget(T) std::map<std::string, std::shared_ptr<::AdHoc::NvpParse::TargetBase<T>>>
#define NvpValue(c, m) \
	{ \
#		m, std::make_shared < ::AdHoc::NvpParse::Target < c, decltype(c::m)>>(&c::m) \
	}

		/** Parse an input stream into the given object.
		 * @param in The input stream.
		 * @param tm The Target Map for the object.
		 * @param t The target instance to populate.
		 */
		template<typename T>
		static void
		parse(std::istream & in, const NvpTarget(T) & tm, T & t)
		{
			NvpParse::AssignMap am;
			for (const auto & v : tm) {
				am[v.first] = v.second->assign(&t);
			}
			return parse(in, am);
		}

		/** Don't use this function directly, instead use:
		 * @code {.cpp} void parse(std::istream & in, const NvpTarget(T) & tm, T & t) @endcode
		 */
		DLL_PUBLIC static void parse(std::istream & in, const AssignMap & m);

	private:
		NvpParse(std::istream & in, const AssignMap &);

		int yylex() override;
		void LexerError(const char * msg) override;

		void process(const std::string & value) const;
		std::string name;
		const AssignMap values;
	};

}

#endif