1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
#ifndef JINJA2CPP_SRC_RENDERER_H
#define JINJA2CPP_SRC_RENDERER_H
#include "out_stream.h"
#include "lexertk.h"
#include "expression_evaluator.h"
#include "render_context.h"
#include "ast_visitor.h"
#include <jinja2cpp/value.h>
#include <jinja2cpp/utils/i_comparable.h>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
namespace jinja2
{
class IRendererBase : public virtual IComparable
{
public:
virtual ~IRendererBase() = default;
virtual void Render(OutStream& os, RenderContext& values) = 0;
};
class VisitableRendererBase : public IRendererBase, public VisitableStatement
{
};
using RendererPtr = std::shared_ptr<IRendererBase>;
inline bool operator==(const RendererPtr& lhs, const RendererPtr& rhs)
{
if (lhs && rhs && !lhs->IsEqual(*rhs))
return false;
if ((lhs && !rhs) || (!lhs && rhs))
return false;
return true;
}
inline bool operator!=(const RendererPtr& lhs, const RendererPtr& rhs)
{
return !(lhs == rhs);
}
class ComposedRenderer : public VisitableRendererBase
{
public:
VISITABLE_STATEMENT();
void AddRenderer(RendererPtr r)
{
m_renderers.push_back(std::move(r));
}
void Render(OutStream& os, RenderContext& values) override
{
for (auto& r : m_renderers)
r->Render(os, values);
}
bool IsEqual(const IComparable& other) const override
{
auto* val = dynamic_cast<const ComposedRenderer*>(&other);
if (!val)
return false;
return m_renderers == val->m_renderers;
}
private:
std::vector<RendererPtr> m_renderers;
};
class RawTextRenderer : public VisitableRendererBase
{
public:
VISITABLE_STATEMENT();
RawTextRenderer(const void* ptr, size_t len)
: m_ptr(ptr)
, m_length(len)
{
}
void Render(OutStream& os, RenderContext&) override
{
os.WriteBuffer(m_ptr, m_length);
}
bool IsEqual(const IComparable& other) const override
{
auto* val = dynamic_cast<const RawTextRenderer*>(&other);
if (!val)
return false;
if (m_ptr != val->m_ptr)
return false;
return m_length == val->m_length;
}
private:
const void* m_ptr{};
size_t m_length{};
};
class ExpressionRenderer : public VisitableRendererBase
{
public:
VISITABLE_STATEMENT();
explicit ExpressionRenderer(ExpressionEvaluatorPtr<> expr)
: m_expression(std::move(expr))
{
}
void Render(OutStream& os, RenderContext& values) override
{
m_expression->Render(os, values);
}
bool IsEqual(const IComparable& other) const override
{
auto* val = dynamic_cast<const ExpressionRenderer*>(&other);
if (!val)
return false;
return m_expression == val->m_expression;
}
private:
ExpressionEvaluatorPtr<> m_expression;
};
} // namespace jinja2
#endif // JINJA2CPP_SRC_RENDERER_H
|