forked from flit/cpptemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpptempl.cpp
1950 lines (1742 loc) · 58.4 KB
/
cpptempl.cpp
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2010-2014 Ryan Ginstrom
// Copyright (c) 2014 Martinho Fernandes
// Copyright (c) 2014-2016 Freescale Semiconductor, Inc.
//
// 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.
#ifdef _MSC_VER
#include "stdafx.h"
#endif
#include "cpptempl.h"
#include <cctype>
#include <sstream>
#include <algorithm>
#include <stack>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <cassert>
#include <cstdlib>
namespace cpptempl
{
namespace impl
{
// Types of tokens in control statements.
enum TokenType
{
INVALID_TOKEN,
KEY_PATH_TOKEN,
STRING_LITERAL_TOKEN,
INT_LITERAL_TOKEN,
TRUE_TOKEN,
FALSE_TOKEN,
FOR_TOKEN,
IN_TOKEN,
IF_TOKEN,
ELIF_TOKEN,
ELSE_TOKEN,
DEF_TOKEN,
SET_TOKEN,
ENDFOR_TOKEN,
ENDIF_TOKEN,
ENDDEF_TOKEN,
AND_TOKEN,
OR_TOKEN,
NOT_TOKEN,
EQ_TOKEN,
NEQ_TOKEN,
GE_TOKEN,
LE_TOKEN,
GT_TOKEN = '>',
LT_TOKEN = '<',
PLUS_TOKEN = '+',
MINUS_TOKEN = '-',
TIMES_TOKEN = '*',
DIVIDE_TOKEN = '/',
MOD_TOKEN = '%',
CONCAT_TOKEN = '&',
ASSIGN_TOKEN = '=',
OPEN_PAREN_TOKEN = '(',
CLOSE_PAREN_TOKEN = ')',
COMMA_TOKEN = ',',
END_TOKEN = 255
};
// Represents a token in a control statement.
class Token
{
TokenType m_type;
std::string m_value;
public:
Token(TokenType tokenType) : m_type(tokenType), m_value() {}
Token(TokenType tokenType, const std::string & value) : m_type(tokenType), m_value(value) {}
Token(const Token & other) : m_type(other.m_type), m_value(other.m_value) {}
Token(Token && other) : m_type(other.m_type), m_value(std::move(other.m_value)) {}
Token& operator=(const Token & other)=default;
Token& operator=(Token && other)
{
m_type = other.m_type;
m_value.assign(std::move(other.m_value));
return *this;
}
~Token()=default;
TokenType get_type() const { return m_type; }
const std::string & get_value() const { return m_value; }
};
typedef std::vector<Token> token_vector;
// Helper class for parsing tokens.
class TokenIterator
{
const token_vector & m_tokens;
size_t m_index;
static Token s_endToken;
public:
TokenIterator(const token_vector & seq) : m_tokens(seq), m_index(0) {}
TokenIterator(const TokenIterator & other) : m_tokens(other.m_tokens), m_index(other.m_index) {}
size_t size() const { return m_tokens.size(); }
bool empty() const { return size() == 0; }
bool is_valid() const { return m_index < size(); }
const Token * get() const;
const Token * next();
const Token * match(TokenType tokenType, const char * failure_msg=nullptr);
void reset() { m_index = 0; }
TokenIterator& operator ++ ();
const Token * operator -> () const { return get(); }
const Token & operator * () const { return *get(); }
};
class ExprParser
{
TokenIterator & m_tok;
data_map & m_data;
public:
ExprParser(TokenIterator & seq, data_map & data) : m_tok(seq), m_data(data) {}
data_ptr parse_expr();
data_ptr parse_oterm();
data_ptr parse_bterm();
data_ptr parse_bfactor();
data_ptr parse_gfactor();
data_ptr parse_afactor();
data_ptr parse_mfactor();
data_ptr parse_factor();
data_ptr get_var_value(const std::string & path, data_list & params);
};
typedef enum
{
NODE_TYPE_NONE,
NODE_TYPE_TEXT,
NODE_TYPE_VAR,
NODE_TYPE_IF,
NODE_TYPE_ELIF,
NODE_TYPE_ELSE,
NODE_TYPE_FOR,
NODE_TYPE_DEF,
NODE_TYPE_SET,
} NodeType;
// Template nodes
// base class for all node types
class Node
{
uint32_t m_line;
public:
Node(uint32_t line) : m_line(line) {}
virtual NodeType gettype() = 0 ;
virtual void gettext(std::ostream &stream, data_map &data) = 0 ;
virtual void set_children(node_vector &children);
virtual node_vector & get_children();
uint32_t get_line() { return m_line; }
void set_line(uint32_t line) { m_line = line; }
};
// node with children
class NodeParent : public Node
{
protected:
node_vector m_children ;
public:
NodeParent(uint32_t line) : Node(line) {}
void set_children(node_vector &children);
node_vector &get_children();
};
// normal text
class NodeText : public Node
{
std::string m_text ;
public:
NodeText(std::string text, uint32_t line=0) : Node(line), m_text(text){}
NodeType gettype();
void gettext(std::ostream &stream, data_map &data);
};
// variable
class NodeVar : public Node
{
token_vector m_expr;
public:
NodeVar(const token_vector & expr, uint32_t line=0) : Node(line), m_expr(expr) {}
NodeType gettype();
void gettext(std::ostream &stream, data_map &data);
};
// for block
class NodeFor : public NodeParent
{
std::string m_key ;
std::string m_val ;
bool m_is_top;
public:
NodeFor(const token_vector & tokens, bool is_top, uint32_t line=0);
NodeType gettype();
void gettext(std::ostream &stream, data_map &data);
};
// if block
class NodeIf : public NodeParent
{
token_vector m_expr ;
node_ptr m_else_if;
NodeType m_if_type;
public:
NodeIf(const token_vector & expr, uint32_t line=0);
NodeType gettype();
void set_else_if(node_ptr else_if);
void gettext(std::ostream &stream, data_map &data);
bool is_true(data_map &data);
bool is_else();
};
// def block
class NodeDef : public NodeParent
{
std::string m_name;
string_vector m_params;
public:
NodeDef(const token_vector & expr, uint32_t line=0);
NodeType gettype();
void gettext(std::ostream &stream, data_map &data);
};
// set variable
class NodeSet : public Node
{
token_vector m_expr;
public:
NodeSet(const token_vector & expr, uint32_t line=0) : Node(line), m_expr(expr) {}
NodeType gettype();
void gettext(std::ostream &stream, data_map &data);
};
// Lexer states for statement tokenizer.
enum lexer_state_t
{
INIT_STATE, //!< Initial state, skip whitespace, process single char tokens.
KEY_PATH_STATE, //!< Scan a key path.
STRING_LITERAL_STATE, //!< Scan a string literal.
INT_LITERAL_STATE, //!< Scan an integer literal.
COMMENT_STATE, //!< Single-line comment.
};
struct KeywordDef
{
TokenType tok;
const char * keyword;
};
class TemplateParser
{
std::string m_text;
node_vector & m_top_nodes;
uint32_t m_current_line;
std::stack<std::pair<node_ptr, TokenType>> m_node_stack;
node_ptr m_current_node;
node_vector * m_current_nodes;
bool m_eol_precedes;
bool m_last_was_eol;
TokenType m_until;
public:
TemplateParser(const std::string & text, node_vector & nodes);
node_vector & parse();
private:
void parse_var();
void parse_stmt();
void parse_comment();
void push_node(Node * new_node, TokenType until);
void check_omit_eol(size_t pos, bool force_omit);
};
std::string indent(int level);
inline bool is_key_path_char(char c);
TokenType get_keyword_token(const std::string & s);
void create_id_token(token_vector & tokens, const std::string & s);
int append_string_escape(std::string & str, std::function<char(unsigned)> peek);
token_vector tokenize_statement(const std::string & text);
inline size_t count_newlines(const std::string & text);
}
// This allows inclusion of the cpptempl::impl declarations into the unit test
// without also bringing in the implementation.
#if defined(CPPTEMPL_UNIT_TEST)
}
#else
//! Flag to track whether to remove the next newline that appears in the output.
//!
//! @bug This global breaks reentrancy.
static bool s_removeNewLine;
//////////////////////////////////////////////////////////////////////////
// Data classes
//////////////////////////////////////////////////////////////////////////
// These ctors are defined here to resolve definition ordering issues with clang.
data_ptr::data_ptr(DataBool* data) : ptr(data) {}
data_ptr::data_ptr(DataInt* data) : ptr(data) {}
data_ptr::data_ptr(DataValue* data) : ptr(data) {}
data_ptr::data_ptr(DataList* data) : ptr(data) {}
data_ptr::data_ptr(DataMap* data) : ptr(data) {}
data_ptr::data_ptr(DataTemplate* data) : ptr(data) {}
// data_map
data_ptr& data_map::operator [](const std::string& key) {
if (data.find(key) == data.end() && parent)
{
return (*parent)[key];
}
return data[key];
}
bool data_map::empty() {
return data.empty();
}
bool data_map::has(const std::string& key) {
bool local_has = data.find(key) != data.end();
return !local_has && parent ? parent->has(key) : local_has;
}
// data_ptr
template<>
void data_ptr::operator = (const bool& data) {
ptr.reset(new DataBool(data));
}
template<>
void data_ptr::operator = (const int& data) {
ptr.reset(new DataInt(data));
}
template<>
void data_ptr::operator = (const unsigned int& data) {
ptr.reset(new DataInt(data));
}
template<>
void data_ptr::operator = (const std::string& data) {
ptr.reset(new DataValue(data));
}
template<>
void data_ptr::operator = (const data_map& data) {
ptr.reset(new DataMap(data));
}
template<>
void data_ptr::operator = (const data_list& data) {
ptr.reset(new DataList(data));
}
data_ptr& data_ptr::operator = (std::string&& data) {
ptr.reset(new DataValue(std::move(data)));
return *this;
}
data_ptr& data_ptr::operator = (data_map&& data) {
ptr.reset(new DataMap(std::move(data)));
return *this;
}
data_ptr& data_ptr::operator = (data_list&& data) {
ptr.reset(new DataList(std::move(data)));
return *this;
}
void data_ptr::push_back(const data_ptr& data) {
if (!ptr) {
ptr.reset(new DataList(data_list()));
}
data_list& list = ptr->getlist();
list.push_back(data);
}
// base data
std::string Data::getvalue()
{
throw TemplateException("Data item is not a value") ;
}
data_list& Data::getlist()
{
throw TemplateException("Data item is not a list") ;
}
data_map& Data::getmap()
{
throw TemplateException("Data item is not a dictionary") ;
}
int Data::getint() const
{
return 0;
}
// data bool
std::string DataBool::getvalue()
{
return m_value ? "true" : "false" ;
}
bool DataBool::empty()
{
return !m_value;
}
void DataBool::dump(int indent)
{
std::cout << "(bool)" << getvalue() << std::endl;
}
int DataBool::getint() const
{
return static_cast<int>(m_value);
}
// data int
std::string DataInt::getvalue()
{
std::ostringstream stream;
stream << m_value;
return stream.str();
}
bool DataInt::empty()
{
return !m_value;
}
void DataInt::dump(int indent)
{
std::cout << "(int)" << m_value << std::endl;
}
int DataInt::getint() const
{
return m_value;
}
// data value
std::string DataValue::getvalue()
{
return m_value ;
}
bool DataValue::empty()
{
return m_value.empty();
}
int DataValue::getint() const
{
return static_cast<int>(std::strtol(m_value.c_str(), NULL, 0));
}
void DataValue::dump(int indent)
{
std::string text = boost::algorithm::replace_all_copy(getvalue(), "\n", "\\n");
std::cout << "\"" << text << "\"" << std::endl;
}
// data list
data_list& DataList::getlist()
{
return m_items ;
}
bool DataList::empty()
{
return m_items.empty();
}
void DataList::dump(int indent)
{
std::cout << "(list)" << std::endl;
int n=0;
for (auto it : m_items)
{
std::cout << impl::indent(indent) << n << ": ";
it->dump(indent+1);
++n;
};
}
// data map
data_map& DataMap::getmap()
{
return m_items ;
}
bool DataMap::empty()
{
return m_items.empty();
}
void DataMap::dump(int indent)
{
std::cout << "(map)" << std::endl;
for (auto it : m_items.data)
{
std::cout << impl::indent(indent) << it.first << ": ";
it.second->dump(indent+1);
};
}
// data template
DataTemplate::DataTemplate(const std::string & templateText)
{
// Parse the template
impl::TemplateParser(templateText, m_tree).parse();
}
std::string DataTemplate::getvalue()
{
return "";
}
bool DataTemplate::empty()
{
return false;
}
void DataTemplate::dump(int indent)
{
std::cout << "(template)\n";
}
std::string DataTemplate::eval(data_map & data, data_list * param_values)
{
std::ostringstream stream;
eval(stream, data, param_values);
return stream.str() ;
}
void DataTemplate::eval(std::ostream &stream, data_map & data, data_list * param_values)
{
data_map * use_data = &data;
// Build map of param names to provided param values. The params map's
// parent is set to the main data_map. This will cause params to
// override keys in the main map, without modifying the main map.
data_map params_map;
if (param_values)
{
// Check number of params.
if (param_values->size() > m_params.size())
{
throw TemplateException("too many parameter(s) provided to subtemplate");
}
for (size_t i=0; i < std::min(m_params.size(), param_values->size()); ++i)
{
const std::string & key = m_params[i];
data_ptr & value = (*param_values)[i];
params_map[key] = value;
}
params_map.set_parent(&data);
use_data = ¶ms_map;
}
// Recursively calls gettext on each node in the tree.
// gettext returns the appropriate text for that node.
for (auto node : m_tree)
{
node->gettext(stream, *use_data) ;
}
}
bool data_ptr::is_template() const
{
return (dynamic_cast<DataTemplate*>(ptr.get()) != nullptr);
}
TemplateException::TemplateException(size_t line, std::string reason)
: std::exception(),
m_line(0),
m_reason(reason)
{
set_line_if_missing(line);
}
void TemplateException::set_line_if_missing(size_t line)
{
if (!m_line)
{
m_line = line;
m_reason = std::string("Line ") + boost::lexical_cast<std::string>(line) + ": " + m_reason;
}
}
//////////////////////////////////////////////////////////////////////////
// parse_path
//////////////////////////////////////////////////////////////////////////
data_ptr& data_map::parse_path(const std::string & key, bool create)
{
if (key.empty())
{
throw key_error("empty map key");
}
// check for dotted notation, i.e [foo.bar]
size_t index = key.find(".") ;
if (index == std::string::npos)
{
if (!has(key))
{
if (!create)
{
printf("invalid map key: %s\n", key.c_str());
throw key_error("invalid map key");
}
data[key] = make_data("");
}
return operator[](key) ;
}
std::string sub_key = key.substr(0, index) ;
if (!has(sub_key))
{
printf("invalid map key: %s\n", sub_key.c_str());
throw key_error("invalid map key");
}
return operator[](sub_key)->getmap().parse_path(key.substr(index+1), create) ;
}
void dump_data(data_ptr data)
{
data->dump();
}
namespace impl
{
std::string indent(int level)
{
std::string result;
while (level--)
{
result += " ";
}
return result;
}
Token TokenIterator::s_endToken(END_TOKEN);
const Token * TokenIterator::get() const
{
if (is_valid())
{
return &m_tokens[m_index];
}
else
{
return &s_endToken;
}
}
const Token * TokenIterator::next()
{
if (m_index < size())
{
++m_index;
}
return get();
}
const Token * TokenIterator::match(TokenType tokenType, const char * failure_msg)
{
const Token * result = get();
if (result->get_type() != tokenType)
{
throw TemplateException(failure_msg ? failure_msg : "unexpected token");
}
next();
return result;
}
TokenIterator& TokenIterator::operator ++ ()
{
next();
return *this;
}
inline bool is_key_path_char(char c)
{
return (isalnum(c) || c == '.' || c == '_');
}
const KeywordDef k_keywords[] = {
{ TRUE_TOKEN, "true" },
{ FALSE_TOKEN, "false" },
{ FOR_TOKEN, "for" },
{ IN_TOKEN, "in" },
{ IF_TOKEN, "if" },
{ ELIF_TOKEN, "elif" },
{ ELSE_TOKEN, "else" },
{ DEF_TOKEN, "def" },
{ SET_TOKEN, "set" },
{ ENDFOR_TOKEN, "endfor" },
{ ENDIF_TOKEN, "endif" },
{ ENDDEF_TOKEN, "enddef" },
{ AND_TOKEN, "and" },
{ OR_TOKEN, "or" },
{ NOT_TOKEN, "not" },
{ INVALID_TOKEN }
};
TokenType get_keyword_token(const std::string & s)
{
const KeywordDef * k = k_keywords;
for (; k->tok != INVALID_TOKEN; ++k)
{
if (s == k->keyword)
{
return k->tok;
}
}
return INVALID_TOKEN;
}
void create_id_token(token_vector & tokens, const std::string & s)
{
TokenType t = get_keyword_token(s);
if (t == INVALID_TOKEN)
{
// Create key path token.
tokens.emplace_back(KEY_PATH_TOKEN, s);
}
else
{
tokens.emplace_back(t);
}
}
int append_string_escape(std::string & str, std::function<char(unsigned)> peek)
{
char esc = peek(1);
std::string hex;
int n=2;
switch (esc)
{
// standard C escape sequences
case 'a': esc = '\a'; break;
case 'b': esc = '\b'; break;
case 'f': esc = '\f'; break;
case 'n': esc = '\n'; break;
case 'r': esc = '\r'; break;
case 't': esc = '\t'; break;
case 'v': esc = '\v'; break;
case '0': esc = '\0'; break;
// handle hex escapes like \x2a
case 'x':
for (; std::isxdigit(peek(n)); ++n)
{
hex += peek(n);
}
esc = static_cast<char>(hex.empty() ? 0 : std::strtoul(hex.c_str(), nullptr, 16));
break;
}
str += esc;
return n-1;
}
token_vector tokenize_statement(const std::string & text)
{
token_vector tokens;
lexer_state_t state=INIT_STATE;
unsigned i=0;
uint32_t pos=0;
char str_open_quote=0;
std::string literal;
// closure to get the next char without advancing
auto peek = [&](unsigned n) { return i+n < text.size() ? text[i+n] : 0; };
for (; i < text.size(); ++i)
{
char c = text[i];
switch (state)
{
case INIT_STATE:
// Skip any whitespace
if (isspace(c))
{
continue;
}
else if (isdigit(c))
{
literal = c;
if (c == '0' && peek(1) == 'x')
{
literal += "x";
++i;
}
state = INT_LITERAL_STATE;
}
else if (is_key_path_char(c))
{
pos = i;
state = KEY_PATH_STATE;
}
else if (c == '(' || c == ')' || c == ',' || c == '+' || c == '*'
|| c == '/' || c == '%')
{
tokens.emplace_back(static_cast<TokenType>(c));
}
else if (c == '\"' || c == '\'')
{
str_open_quote = c;
literal.clear();
state = STRING_LITERAL_STATE;
}
else if (c == '=')
{
if (peek(1) == '=')
{
tokens.emplace_back(EQ_TOKEN);
++i;
}
else
{
tokens.emplace_back(ASSIGN_TOKEN);
}
}
else if (c == '>')
{
if (peek(1) == '=')
{
tokens.emplace_back(GE_TOKEN);
++i;
}
else
{
tokens.emplace_back(GT_TOKEN);
}
}
else if (c == '<')
{
if (peek(1) == '=')
{
tokens.emplace_back(LE_TOKEN);
++i;
}
else
{
tokens.emplace_back(LT_TOKEN);
}
}
else if (c == '!')
{
if (peek(1) == '=')
{
tokens.emplace_back(NEQ_TOKEN);
++i;
}
else
{
tokens.emplace_back(NOT_TOKEN);
}
}
else if (c == '&')
{
if (peek(1) == '&')
{
tokens.emplace_back(AND_TOKEN);
++i;
}
else
{
tokens.emplace_back(CONCAT_TOKEN);
}
}
else if (c == '|' && peek(1) == '|')
{
tokens.emplace_back(OR_TOKEN);
++i;
}
else if (c == '-')
{
if (peek(1) == '-')
{
state = COMMENT_STATE;
}
else
{
tokens.emplace_back(MINUS_TOKEN);
}
}
else
{
literal = "unexpected character '";
literal += c;
literal += "'";
throw TemplateException(literal);
}
break;
case KEY_PATH_STATE:
if (!is_key_path_char(c))
{
create_id_token(tokens, text.substr(pos, i-pos));
// Reprocess this char in the initial state.
state = INIT_STATE;
--i;
}
break;
case STRING_LITERAL_STATE:
if (c == str_open_quote)
{
// Create the string literal token and return to init state.
tokens.emplace_back(STRING_LITERAL_TOKEN, literal);
state = INIT_STATE;
}
else if (c == '\\')
{
i += append_string_escape(literal, peek);
}
else
{
literal += c;
}
break;
case INT_LITERAL_STATE:
if (isdigit(c))
{
literal += c;
}
else
{
tokens.emplace_back(INT_LITERAL_TOKEN, literal);
state = INIT_STATE;
--i;
}
break;
case COMMENT_STATE:
if (c == '\n')
{
state = INIT_STATE;
}
break;
}
}
// Handle a key path terminated by end of string.
if (state == KEY_PATH_STATE)
{
create_id_token(tokens, text.substr(pos, i-pos));
}
else if (state == STRING_LITERAL_STATE)
{
throw TemplateException("unterminated string literal");
}
else if (state == INT_LITERAL_STATE)
{
tokens.emplace_back(INT_LITERAL_TOKEN, literal);
}
return tokens;
}
//////////////////////////////////////////////////////////////////////////
// Expr parser
//////////////////////////////////////////////////////////////////////////
// Expression grammar
//
// expr ::= oterm [ "if" oterm "else" oterm ]
// oterm ::= bterm ( "or" bterm )*
// bterm ::= bfactor ( "and" bfactor )*
// bfactor ::= gfactor [ ( "==" | "!=" ) gfactor ]
// gfactor ::= afactor [ ( ">" | ">=" | "<" | "<=" ) afactor ]
// afactor ::= mfactor [ ( "&" | "+" | "-" ) afactor ]
// mfactor ::= factor [ ( "*" | "/" | "%" ) mfactor ]
// factor ::= "not" expr
// | "-" expr
// | "(" expr ")"
// | ( "true" | "false" )
// | KEY_PATH [ args ]
// | INT
// args ::= "(" [ expr ( "," expr )* ")"
data_ptr ExprParser::get_var_value(const std::string & path, data_list & params)
{
// Check if this is a pseudo function.