-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLuaXML_lib.c
More file actions
1226 lines (1082 loc) · 39.4 KB
/
Copy pathLuaXML_lib.c
File metadata and controls
1226 lines (1082 loc) · 39.4 KB
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
/*
LuaXML License
LuaXML is licensed under the terms of the MIT license reproduced below,
the same as Lua itself. This means that LuaXML is free software and can be
used for both academic and commercial purposes at absolutely no cost.
Copyright (C) 2007-2013 Gerald Franz, eludi.net
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.
*/
/// @module LuaXML
#include "LuaXML_lib.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* compatibility with older Lua versions (<5.2) */
#if LUA_VERSION_NUM < 502
// Substitute lua_objlen() for lua_rawlen()
#define lua_rawlen(L, index) lua_objlen(L, index)
// Make use of luaL_register() to achieve same result as luaL_newlib()
#define luaL_newlib(L, funcs) do { \
lua_newtable(L); \
luaL_register(L, NULL, funcs); \
} while (0)
#endif
/* API changes for 5.2+ */
#if LUA_VERSION_NUM >= 502
// lua_compare() has replaced lua_equal()
#define lua_equal(L, index1, index2) lua_compare(L, index1, index2, LUA_OPEQ)
#endif
/* API changes for 5.3+ */
#if LUA_VERSION_NUM >= 503
// luaL_optinteger() has replaced luaL_optint()
#define luaL_optint(L, arg, d) luaL_optinteger(L, arg, d)
#endif
#define LUAXML_META "LuaXML" // name to be used for metatable
//--- auxliary functions -------------------------------------------
static size_t find(const char *s, const char *pattern, size_t start) {
const char *found = strstr(s + start, pattern);
return found ? (size_t)(found - s) : strlen(s);
}
// push (arbitrary Lua) value to be used as tag key, placing it on top of stack
static inline void push_TAG_key(lua_State *L) {
/* Note: Currently this is the number 0, which fits in nicely with using
* string keys for attribute-value pairs and also 'stays clear' of the
* array of sub-elements (starting at index 1).
* Theoretically, this could be any kind of Lua value; but when using a
* string key (e.g. "TAG"), extra care needs to be taken that it doesn't
* get confused with an attribute - which means that the str() function
* should be modified accordingly (to recognise and avoid the tag key).
*/
lua_pushinteger(L, 0);
}
// convert Lua table at given index to an XML "object", by setting its metatable
static void make_xml_object(lua_State *L, int index) {
if (index < 0) index += lua_gettop(L) + 1; // relative to absolute index
if (!lua_istable(L, index))
luaL_error(L, "%s() error: invalid type at %d - expected table, got %s",
__func__, index, luaL_typename(L, index));
luaL_getmetatable(L, LUAXML_META);
lua_setmetatable(L, index); // assign metatable
}
// push an indentation string for the given level to the Lua stack
static void push_indentStr(lua_State *L, int level) {
if (level <= 0) {
lua_pushliteral(L, "");
return;
}
luaL_Buffer b;
luaL_buffinit(L, &b);
//while (level-- > 0) luaL_addlstring(&b, " ", 2);
while (level-- > 0) luaL_addchar(&b, '\t'); // one TAB char per level
luaL_pushresult(&b);
}
// tests if a string consists entirely of whitespace
static bool is_whitespace(const char *s) {
if (!s) return false; // NULL pointer
if (*s == 0) return false; // empty string
while (*s)
if (!isspace(*s++)) return false;
return true;
}
// We consider a token "lead in", if it 1) is all whitespace and 2) starts with
// a newline. (This is typical for line breaks plus indentation on nested XML.)
static bool is_lead_token(const char *s) {
return is_whitespace(s) && (*s == '\n' || *s == '\r');
}
/*
* For the string at given stack index, substitute any occurrence (exact string
* match) of pattern "p" with the replacement string "r".
* When done, this function will replace the original string with the result.
*/
// TODO / Caveat:
// We return the luaL_gsub() pointer, but it's unclear (and untested) if that
// persists after the lua_replace(). Currently the result isn't used anywhere.
static const char *do_gsub(lua_State *L, int index, const char *p, const char *r)
{
if (index < 0) index += lua_gettop(L) + 1; // relative to absolute index
const char *result = luaL_gsub(L, lua_tostring(L, index), p, r);
lua_replace(L, index);
return result;
}
/*
* Lua C function to replace a gsub() match with the corresponding character.
* Xml_pushDecode() will use this as a replacement function argument to undo
* the XML encodings, passing one match (sequence of digits) at a time.
*
* Due to the pattern used, the matched string may also be 'x' followed by
* a sequence of hexadecimal characters ("xE4"), which is supported too.
*/
static int XMLencoding_replacement(lua_State *L) {
const char *matched = lua_tostring(L, 1);
if (matched) {
// support both decimal and hexadecimal conversion
char c = *matched == 'x' ? strtol(++matched, NULL, 16) : atoi(matched);
if (c) {
lua_pushlstring(L, &c, 1); // return character as Lua string
return 1;
} // c == 0 probably indicates conversion failure, return `nil`
}
return 0;
}
/* Lua C callback function for a `find()` match. Sets the upvalue (that will
* later be the result) and stops the iteration.
*
* A small problem here is that the callback handling by iterate() means this
* function cannot simply return the result on the Lua stack. Instead we need
* a "shared" upvalue that can be retrieved 'externally' later. Therefore a
* simple, 'flat' Lua value won't do (it can't be shared); so we'll use a table
* instead and assign the match to t[1].
*/
static int find_on_match(lua_State *L) {
// Upon entry the Lua stack will have `var` and `depth`
lua_settop(L, 1); // discard depth, leaving var on the stack
lua_rawseti(L, lua_upvalueindex(1), 1); // store to upvalue table
lua_pushboolean(L, false); // return false to stop iteration
return 1;
}
/// strip all leading / trailing whitespace
// @field WS_TRIM
/// remove "lead in" whitespace before tags
// @field WS_NORMALIZE
/// preserve all whitespace, even between tags
// @field WS_PRESERVE
enum whitespace_mode {
WHITESPACE_TRIM,
WHITESPACE_NORMALIZE,
WHITESPACE_PRESERVE
};
// control chars used by the Tokenizer to denote special meanings
#define ESC 27 /* end of scope, closing tag */
#define OPN 28 /* "open", start of tag */
#define CLS 29 /* closes opening tag, actual content follows */
//--- internal tokenizer -------------------------------------------
typedef struct Tokenizer_s {
/// stores string to be tokenized
const char *s;
/// stores size of string to be tokenized
size_t s_size;
/// stores current read position
size_t i;
/// stores current read context
int tagMode;
/// stores flag for "raw" byte sequence, *DON'T* decode any further
int cdata;
/// stores next token, if already determined
const char *m_next;
/// size of next token
size_t m_next_size;
/// pointer to current token
char *m_token;
/// size of current token
size_t m_token_size;
/// capacity of current token
size_t m_token_capacity;
/// whitespace handling
enum whitespace_mode mode;
} Tokenizer;
Tokenizer *Tokenizer_new(const char *str, size_t str_size,
enum whitespace_mode mode)
{
Tokenizer *tok = calloc(1, sizeof(Tokenizer));
tok->s_size = str_size;
tok->s = str;
tok->mode = mode;
return tok;
}
void Tokenizer_delete(Tokenizer *tok) {
free(tok->m_token);
free(tok);
}
#if LUAXML_DEBUG
void Tokenizer_print(Tokenizer *tok) {
printf(" @%u %s\n", tok->i,
!tok->m_token ? "(null)" :
(tok->m_token[0] == ESC) ? "(esc)" :
(tok->m_token[0] == OPN) ? "(open)" :
(tok->m_token[0] == CLS) ? "(close)" :
tok->m_token);
fflush(stdout);
}
#else
# define Tokenizer_print(tok) /* ignore */
#endif
static const char *Tokenizer_set(Tokenizer *tok, const char *s, size_t size) {
if (!size || !s) return NULL;
free(tok->m_token);
tok->m_token = malloc(size + 1);
strncpy(tok->m_token, s, size);
tok->m_token[size] = 0;
tok->m_token_size = tok->m_token_capacity = size;
Tokenizer_print(tok);
return tok->m_token;
}
static void Tokenizer_append(Tokenizer *tok, char ch) {
if (tok->m_token_size + 1 >= tok->m_token_capacity) {
tok->m_token_capacity = tok->m_token_capacity ? tok->m_token_capacity * 2 : 16;
tok->m_token = realloc(tok->m_token, tok->m_token_capacity);
}
tok->m_token[tok->m_token_size] = ch;
tok->m_token[++tok->m_token_size] = 0;
}
const char *Tokenizer_next(Tokenizer *tok) {
// NUL-terminated strings for the special tokens
static const char ESC_str[] = {ESC, 0};
static const char OPEN_str[] = {OPN, 0};
static const char CLOSE_str[] = {CLS, 0};
if (tok->m_token) {
free(tok->m_token);
tok->m_token = NULL;
tok->m_token_size = tok->m_token_capacity = 0;
}
char quotMode = 0;
int tokenComplete = 0;
while (tok->m_next_size || (tok->i < tok->s_size)) {
tok->cdata = 0;
if (tok->m_next_size) {
Tokenizer_set(tok, tok->m_next, tok->m_next_size);
tok->m_next = NULL;
tok->m_next_size = 0;
return tok->m_token;
}
switch (tok->s[tok->i]) {
case '"':
case '\'':
if (tok->tagMode) {
// toggle quotation mode
if (!quotMode)
quotMode = tok->s[tok->i];
else
if (quotMode == tok->s[tok->i]) quotMode = 0;
}
Tokenizer_append(tok, tok->s[tok->i]);
break;
case '<':
if (!quotMode && (tok->i + 4 < tok->s_size)
&& (strncmp(tok->s + tok->i, "<!--", 4) == 0))
tok->i = find(tok->s, "-->", tok->i + 4) + 2; // strip comments
else if (!quotMode && (tok->i + 9 < tok->s_size)
&& (strncmp(tok->s + tok->i, "<![CDATA[", 9) ==0)) {
if (tok->m_token_size > 0)
// finish current token first, after that reparse CDATA
tokenComplete = 1;
else {
// interpret CDATA
size_t b = tok->i + 9;
tok->i = find(tok->s, "]]>", b) + 3;
size_t cdata_len = tok->i - b - 3;
if (cdata_len > 0) {
tok->cdata = 1; // mark as "raw" byte sequence
return Tokenizer_set(tok, tok->s + b, cdata_len);
}
}
--tok->i;
}
else if (!quotMode && (tok->i + 1 < tok->s_size)
&& ((tok->s[tok->i + 1] == '?')
|| (tok->s[tok->i + 1] == '!')))
tok->i=find(tok->s, ">", tok->i + 2); // strip meta information
else if (!quotMode && !tok->tagMode) {
if ((tok->i + 1 < tok->s_size)
&& (tok->s[tok->i + 1] == '/')) {
// "</" sequence that starts a closing tag
tok->m_next = ESC_str;
tok->m_next_size = 1;
tok->i = find(tok->s, ">", tok->i + 2);
} else {
// regular '<' opening a new tag
tok->m_next = OPEN_str;
tok->m_next_size = 1;
tok->tagMode = 1;
}
tokenComplete = 1;
}
else Tokenizer_append(tok, tok->s[tok->i]);
break;
case '/':
if (tok->tagMode && !quotMode) {
tokenComplete = 1;
if ((tok->i + 1 < tok->s_size)
&& (tok->s[tok->i + 1] == '>')) {
// "/>" sequence = end of 'empty' tag
tok->tagMode = 0;
tok->m_next = ESC_str;
tok->m_next_size = 1;
++tok->i;
}
else Tokenizer_append(tok, tok->s[tok->i]);
}
else Tokenizer_append(tok, tok->s[tok->i]);
break;
case '>':
if (!quotMode && tok->tagMode) {
// this '>' closes the current tag
tok->tagMode = 0;
tokenComplete = 1;
tok->m_next = CLOSE_str;
tok->m_next_size = 1;
}
else Tokenizer_append(tok, tok->s[tok->i]);
break;
case ' ':
case '\r':
case '\n':
case '\t':
if (tok->tagMode && !quotMode) {
// within a tag, any unquoted whitespace ends the current token (= attribute)
if (tok->m_token_size) tokenComplete = 1;
}
else
if (tok->m_token_size || tok->mode != WHITESPACE_TRIM)
Tokenizer_append(tok, tok->s[tok->i]);
break;
default:
Tokenizer_append(tok, tok->s[tok->i]);
}
++tok->i;
if (tok->i >= tok->s_size || (tokenComplete && tok->m_token_size)) {
tokenComplete = 0;
if (tok->mode == WHITESPACE_TRIM) // trim whitespace
while (tok->m_token_size && isspace(tok->m_token[tok->m_token_size - 1]))
tok->m_token[--tok->m_token_size] = 0;
if (tok->m_token_size) break;
}
}
Tokenizer_print(tok);
return tok->m_token;
}
//--- local variables ----------------------------------------------
// 'private' table mapping between special chars and their XML substitutions
static int sv_code_ref; // (will receive a LUA reference)
//--- public methods -----------------------------------------------
/** sets or returns tag of a LuaXML object.
This method is just "syntactic sugar" (using a typical Lua term) that allows
the writing of clearer code. LuaXML stores the tag value of an XML statement
at table index 0, hence it can be simply accessed or altered by `var[0]`.
However, writing `var:tag()` for access or `var:tag("newTag")` for altering
may be more self explanatory (and future-proof in case LuaXML's tag handling
should ever change).
@function tag
@param var the variable whose tag should be accessed, a LuaXML object
@tparam ?string tag the new tag to be set
@return If you have passed a new tag, the function will return `var` (with
its tag changed); otherwise the result will be the current tag of `var`
(normally a string).
*/
int Xml_tag(lua_State *L) {
// the function will only operate on tables
if lua_istable(L, 1) {
lua_settop(L, 2);
push_TAG_key(L); // place tag key on top of stack (#3)
if (lua_type(L, 2) == LUA_TSTRING) {
lua_pushvalue(L, 2); // duplicate the value
lua_rawset(L, 1);
// we return the (modified) table
lua_settop(L, 1);
return 1;
} else {
// "tag" is empty or wrong type, retrieve the current tag
lua_rawget(L, 1);
return 1;
}
}
return 0;
}
/** creates a LuaXML "object", and optionally sets its tag.
The function either sets the metatable of an existing Lua table, or creates a
new (empty) "object". If you pass an optional` tag` string, it will be assigned
to the result.
(It's also possible to call this as `new(tag)`, which creates a new XML object
with the given tag and is equivalent to `new({}, tag)`.)
Note that it's not mandatory to use this function in order to treat a Lua table
as LuaXML object. Setting the metatable just allows the usage of a more
object-oriented syntax (e.g. `xmlvar:str()` instead of `xml.str(xmlvar)`).
XML objects created by `load` or `eval` automatically offer the
object-oriented syntax.
@function new
@param arg (optional) _(1)_ a table to be converted to a LuaXML object,
or _(2)_ the tag of the new LuaXML object
@tparam ?string tag a tag value that will be assigned to the object
@return LuaXML object, either newly created or the conversion of `arg`;
optionally tagged as requested
*/
int Xml_new(lua_State *L) {
if (!lua_istable(L, 1)) {
// create a new table and move it to the bottom of the stack (#1),
// possibly shifting other elements "one up"
lua_newtable(L);
lua_insert(L, 1);
}
// element at #1 now is a table, convert to "object"
make_xml_object(L, 1);
if (lua_type(L, 2) == LUA_TSTRING) {
lua_pushcfunction(L, Xml_tag);
lua_pushvalue(L, 1); // duplicate the object table
lua_pushvalue(L, 2); // duplicate the tag (string)
lua_call(L, 2, 0); // call the "tag" function, discarding any result
}
lua_settop(L, 1);
return 1;
}
/** appends a new subordinate LuaXML object to an existing one.
optionally sets tag
@function append
@param var the parent LuaXML object
@tparam ?string tag the tag of the appended LuaXML object
@return appended LuaXML object, or `nil` in case of errors
*/
int Xml_append(lua_State *L) {
if (lua_type(L, 1) == LUA_TTABLE) {
lua_settop(L, 2);
lua_pushcfunction(L, Xml_new);
lua_insert(L, 2);
lua_call(L, 1, 1); // new(tag)
lua_pushvalue(L, -1); // duplicate result
lua_rawseti(L, 1, lua_rawlen(L, 1) + 1); // append to parent (elements)
return 1;
}
return 0;
}
// Push XML-encoded string for the Lua value at given index.
// Will automatically use a tostring() conversion first, if necessary.
static void Xml_pushEncode(lua_State *L, int index) {
if (index < 0) index += lua_gettop(L) + 1; // relative to absolute index
if (lua_type(L, index) == LUA_TSTRING)
lua_pushvalue(L, index); // already a string, just duplicate it
else {
lua_getglobal(L, "tostring");
lua_pushvalue(L, index); // duplicate value
lua_call(L, 1, 1); // tostring()
}
// always do "&" first
// (avoids later affecting other substitutions, which may contain '&')
do_gsub(L, -1, "&", "&");
// encode other special entities
lua_rawgeti(L, LUA_REGISTRYINDEX, sv_code_ref);
lua_pushnil(L);
while (lua_next(L, -2)) {
// Lua stack has string to work on (-4), substitution table (-3),
// table key (-2 = special char) and value (-1 = replacement)
// (We want to replace the original char with the XML encoding.)
do_gsub(L, -4, lua_tostring(L, -2), lua_tostring(L, -1));
lua_pop(L, 1); // pop value, leaving key for the next iteration
}
lua_pop(L, 1); // pop substitution table to realign the stack
// transfer string one character at a time, encoding any chars with MSB set
char buf[8];
const unsigned char *s = (unsigned char *)lua_tostring(L, -1);
luaL_Buffer b;
luaL_buffinit(L, &b);
while (*s) {
if (*s < 128)
luaL_addchar(&b, *s); // copy character literally
else {
int len = snprintf(buf, sizeof(buf), "&#%d;", *s); // encode char
luaL_addlstring(&b, buf, len);
}
s++;
}
luaL_pushresult(&b);
lua_replace(L, -2); // (leaving the result on the stack)
}
/*
// Push a string, then do XML conversion on it - result remains on top of stack.
static void Xml_pushEncodeStr(lua_State *L, const char *s, int size) {
if (size == 0) {
lua_pushliteral(L, "");
return;
}
if (size < 0) size = strlen(s);
lua_pushlstring(L, s, size);
Xml_pushEncode(L, -1);
lua_replace(L, -2);
}
*/
// Push Lua representation of the given string, while decoding any special XML encodings
static void Xml_pushDecode(lua_State *L, const char *s, int size) {
if (size == 0) {
lua_pushliteral(L, "");
return;
}
if (size < 0) size = strlen(s);
// try a gsub() substition of decimal and hexadecimal character encodings
lua_pushlstring(L, s, size); // initial string
lua_pushliteral(L, "gsub");
lua_gettable(L, -2); // using string as object, retrieve the "gsub" function
lua_insert(L, -2); // swap with function, making string the arg #1
lua_pushliteral(L, "&#(x?%x+);"); // pattern for XML encodings (arg #2)
lua_pushcfunction(L, XMLencoding_replacement); // replacement func (arg #3)
lua_call(L, 3, 1); // three parameters, one result (the substituted string)
lua_rawgeti(L, LUA_REGISTRYINDEX, sv_code_ref);
lua_pushnil(L);
while (lua_next(L, -2)) {
// Lua stack has string to work on (-4), substitution table (-3),
// table key (-2 = special char) and value (-1 = replacement)
// (We want to replace the XML encoding with the original char.)
do_gsub(L, -4, lua_tostring(L, -1), lua_tostring(L, -2));
lua_pop(L, 1); // pop value, leaving key for the next iteration
}
lua_pop(L, 1); // pop substitution table, leaving result string on stack
do_gsub(L, -1, "&", "&"); // this should always be done last
}
/** parses an XML string into a Lua table.
The table will contain a representation of the XML tag, attributes (and their
values), and element content / subelements (either as strings or nested LuaXML
"objects").
Note: Parsing "wide" strings or Unicode (UCS-2, UCS-4, UTF-16) currently is
__not__ supported. If needed, convert such `xml` data to UTF-8 before passing it
to `eval()`. UTF-8 should be safe to use, and this function will also recognize
and ignore a UTF-8 BOM (byte order mark) at the start of `xml`.
@function eval
@tparam string|userdata xml
the XML to be converted. When passing a userdata type `xml` value, it must
point to a C-style (NUL-terminated) string.
@tparam ?number mode
whitespace handling mode, one of the `WS_*` constants - see [Fields](#Fields).
defaults to `WS_TRIM` (compatible to previous LuaXML versions)
@return a LuaXML object containing the XML data, or `nil` in case of errors
*/
int Xml_eval(lua_State *L) {
enum whitespace_mode mode = luaL_optint(L, 2, WHITESPACE_TRIM);
const char *str;
size_t str_size;
if (lua_isuserdata(L, 1)) {
str = lua_touserdata(L, 1);
str_size = strlen(str);
}
else str = luaL_checklstring(L, 1, &str_size);
if (str_size >= 3 && strncmp(str, "\xEF\xBB\xBF", 3) == 0) {
// ignore / skip over UTF-8 BOM (byte order mark)
str += 3;
str_size -= 3;
}
Tokenizer *tok = Tokenizer_new(str, str_size, mode);
lua_settop(L, 1);
const char *token;
int firstStatement = 1;
while ((token=Tokenizer_next(tok)))
if (*token == OPN) { // new tag found
if (lua_gettop(L) > 1) {
lua_newtable(L);
lua_pushvalue(L, -1); // duplicate table (keep one copy on stack)
lua_rawseti(L, -3, lua_rawlen(L, -3) + 1); // set parent subelement
} else {
if (firstStatement) {
lua_newtable(L);
firstStatement = 0;
}
else return 0;
}
make_xml_object(L, -1); // assign metatable
// parse tag and content:
push_TAG_key(L); // place tag key on top of stack
lua_pushstring(L, Tokenizer_next(tok));
lua_rawset(L, -3);
while ((token = Tokenizer_next(tok)) && (*token != CLS) && (*token != ESC)) {
// parse tag header
size_t sepPos = find(token, "=", 0);
if (token[sepPos]) { // regular attribute (key="value")
const char *aVal = token + sepPos + 2;
lua_pushlstring(L, token, sepPos);
Xml_pushDecode(L, aVal, strlen(aVal) - 1);
lua_rawset(L, -3);
}
}
if (!token || (*token == ESC)) {
// this tag has no content, only attributes
if (lua_gettop(L) > 2) lua_pop(L, 1); else break;
}
}
else if (*token == ESC) { // previous tag is over
if (lua_gettop(L) > 2) lua_pop(L, 1); // pop current table
else break;
}
else { // read elements
if (lua_gettop(L) > 1) {
// when normalizing, we ignore tokens considered "lead-in" type
if (mode != WHITESPACE_NORMALIZE || !is_lead_token(token)) {
if (tok->cdata) // "raw" mode, don't change token string!
lua_pushstring(L, token);
else
Xml_pushDecode(L, token, -1);
lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
}
}
else // element stack is empty, i.e. we encountered a token *before* any tag
if (!is_whitespace(token))
luaL_error(L, "Malformed XML: non-empty string '%s' before any tag (parser pos %d)",
token, (int)tok->i);
}
Tokenizer_delete(tok);
return lua_gettop(L) - 1;
}
/** loads XML data from a file and returns it as table.
Basically, this is just calling `eval` on the given file's content.
@function load
@tparam string filename the name and path of the file to be loaded
@tparam ?number mode whitespace handling mode, defaults to `WS_TRIM`
@return a Lua table representing the XML data, or `nil` in case of errors
*/
int Xml_load (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
FILE *file = fopen(filename, "r");
if (!file)
return luaL_error(L, "LuaXML ERROR: \"%s\" file error or file not found!", filename);
fseek(file, 0, SEEK_END);
size_t sz = ftell(file);
rewind(file);
char *buffer = malloc(sz + 1);
sz = fread(buffer, 1, sz, file);
fclose(file);
buffer[sz] = 0;
lua_pushlightuserdata(L, buffer);
lua_replace(L, 1);
int result = Xml_eval(L);
free(buffer);
return result;
};
/** registers a custom code for the conversion between non-standard characters
and XML character entities.
By default, only the most basic entities are known to LuaXML:
" < > '
On top (and independent) of that, the **ampersand** sign always gets encoded /
decoded separately: `&` ↔ `&amp;`. Character codes above 127 are
directly converted to an appropriate XML encoding, representing the character
number (e.g. `&#160;`). If other special encodings are needed, they can be
registered using this function.
Note: LuaXML now manages these encodings in a (private) standard Lua table.
This allows you to replace entries by calling `registerCode()` again, using the
same `decoded` and a different `encoded`. Encodings may even be removed later,
by explictly registering a `nil` value: `registerCode(decoded, nil)`.
@function registerCode
@tparam string decoded the character (sequence) to be used within Lua
@tparam string encoded the character entity to be used in XML
@see encode, decode
*/
int Xml_registerCode(lua_State *L) {
// We require the "decoded" string, but allow `nil` as argument #2.
// That way, users may remove entries from the table again.
luaL_checkstring(L, 1);
if (!lua_isnoneornil(L, 2)) luaL_checkstring(L, 2);
lua_settop(L, 2);
lua_rawgeti(L, LUA_REGISTRYINDEX, sv_code_ref); // get translation table
lua_insert(L, 1);
lua_rawset(L, 1); // assign key-value pair (k "decoded" -> v "encoded")
return 0;
}
/** converts a string to XML encoding.
This function transforms` str` by replacing any special characters with
suitable XML encodings.
@usage
print(xml.encode("<->")) -- "<->"
@function encode
@tparam string str string to be transformed
@treturn string the XML-encoded string
@see decode, registerCode
*/
int Xml_encode(lua_State *L) {
luaL_checkstring(L, 1); // make sure arg #1 is a string
Xml_pushEncode(L, 1); // and convert it
return 1;
}
/** converts a string from XML encoding.
This function transforms` str` by replacing any special XML encodings with
their "plain text" counterparts.
@usage
print((xml.decode("<->")) -- "<->"
@function decode
@tparam string str string to be transformed
@treturn string the decoded string
@see encode, registerCode
*/
int Xml_decode(lua_State *L) {
size_t size;
luaL_checklstring(L, 1, &size); // make sure arg #1 is a string
Xml_pushDecode(L, lua_tostring(L, 1), size); // and convert it
return 1;
}
/** converts any Lua value to an XML string.
@function str
@param value
the value to be converted, normally a table (LuaXML object). However this
function will 'encapsulate' other Lua values (of arbitrary type) in a way that
should make them valid XML.
<br>Note: Passing no `value` will cause the function to return `nil`.
@tparam ?number indent
indentation level for 'pretty' output. Mainly for internal use, defaults to 0.
@tparam ?string tag
the tag to be used in case `value` doesn't already have an 'implicit' tag.
Mainly for internal use.
@treturn string
an XML string, or `nil` in case of errors.
*/
int Xml_str(lua_State *L) {
// Note:
// Be very careful about mixing Lua stack usage and buffer access here.
// The stack *must* be (re)balanced before accessing "b", i.e. any output
// should only occur at the same Lua stack level as the previous one!
luaL_Buffer b;
lua_settop(L, 3);
int type = lua_type(L, 1); // type of "value"
if (type == LUA_TNIL) return 0;
if (type == LUA_TTABLE) {
push_TAG_key(L);
lua_rawget(L, 1); // retrieve tag entry from the table (may be `nil`)
// order of precedence: value[0], explicit tag string, Lua type name
const char *tag = lua_tostring(L, -1);
if (!tag) tag = lua_tostring(L, 3);
if (!tag) tag = lua_typename(L, type);
// Four elements already on stack: value, indent, tag, value[0]
// Use a string (#5) to manage (concatenate) simple attributes
lua_pushliteral(L, "");
// And a table (#6) to take care of (collect) 'extended' attributes
lua_newtable(L);
size_t table_attr = 0;
luaL_buffinit(L, &b);
push_indentStr(L, lua_tointeger(L, 2));
luaL_addvalue(&b);
luaL_addchar(&b, '<');
luaL_addstring(&b, tag);
// Iterate over string keys (= attributes)
lua_pushnil(L);
while (lua_next(L, 1)) {
// (k, v) pair on the stack
if (lua_type(L, -2) == LUA_TSTRING) {
// (the "_M" test here is to avoid recursion on module tables)
if (lua_istable(L, -1) && strcmp(lua_tostring(L, -2), "_M")) {
lua_pushcfunction(L, Xml_str);
lua_pushvalue(L, -2); // duplicate "v"
lua_pushinteger(L, lua_tointeger(L, 2) + 1); // indent + 1
lua_pushvalue(L, -4); // duplicate "k"
lua_call(L, 3, 1); // xml.str(v, indent + 1, k)
lua_rawseti(L, 6, ++table_attr); // append string to table
} else {
Xml_pushEncode(L, -1); // encode(tostring(v))
lua_pushfstring(L, "%s %s=\"%s\"", lua_tostring(L, 5),
lua_tostring(L, -3), lua_tostring(L, -1));
lua_replace(L, 5); // new attribute string
lua_pop(L, 1); // realign stack
}
}
lua_pop(L, 1); // pop <v>alue, leaving <k>ey for next iteration
}
// append "simple" attribute string to the output
if (lua_rawlen(L, 5) > 0) luaL_addstring(&b, lua_tostring(L, 5));
size_t count = lua_rawlen(L, 1); // number of "array" (sub)elements
if (count == 0 && table_attr == 0) {
// no sub-elements and no extended attr -> close tag and we're done
luaL_addlstring(&b, " />\n", 4);
luaL_pushresult(&b);
return 1;
}
luaL_addchar(&b, '>'); // close opening tag
if (count == 1 && table_attr == 0) {
// single subelement, no extended attributes
lua_rawgeti(L, 1, 1); // value[1]
if (!lua_istable(L, -1)) {
// output as single string, then close tag
Xml_pushEncode(L, -1); // encode(tostring(value[1]))
lua_replace(L, -2);
luaL_addvalue(&b); // add and pop
luaL_addlstring(&b, "</", 2);
luaL_addstring(&b, tag);
luaL_addlstring(&b, ">\n", 2);
luaL_pushresult(&b);
return 1;
}
lua_pop(L, 1); // discard (table) value, to realign stack
}
luaL_addchar(&b, '\n');
// Loop over all the sub-elements, placing each on a separate line
size_t k;
for (k = 1; k <= count; k++) {
#if LUA_VERSION_NUM < 503
lua_rawgeti(L, 1, k);
type = lua_type(L, -1);
#else
type = lua_rawgeti(L, 1, k); // (Lua 5.3 returns type directly)
#endif
if (type == LUA_TSTRING) {
push_indentStr(L, lua_tointeger(L, 2) + 1); // indentation
Xml_pushEncode(L, -2);
lua_remove(L, -3);
lua_pushliteral(L, "\n");
lua_concat(L, 3);
} else {
lua_pushcfunction(L, Xml_str);
lua_insert(L, -2); // place function before value
lua_pushinteger(L, lua_tointeger(L, 2) + 1); // indent + 1
lua_call(L, 2, 1); // xml.str(v, indent + 1)
}
luaL_addvalue(&b); // add (string) to output, pop from stack
}
// Finally we'll take care of the "extended" (table-type) attributes.
// The output is appended after the regular sub-elements, in order
// not to affect their numbering.
// Just process the corresponding table, concatenating all entries:
for (k = 1; k <= table_attr; k++) {
lua_rawgeti(L, 6, k);
luaL_addvalue(&b);
}
// closing tag
push_indentStr(L, lua_tointeger(L, 2));
luaL_addvalue(&b);
luaL_addlstring(&b, "</", 2);
luaL_addstring(&b, tag);
luaL_addlstring(&b, ">\n", 2);
luaL_pushresult(&b);
return 1;
}
// Getting here means a "flat" Lua value, format to XML as a single string
const char *tag = lua_tostring(L, 3);
if (!tag) tag = lua_typename(L, type); // use either tag or the type name
luaL_buffinit(L, &b);
push_indentStr(L, lua_tointeger(L, 2));
luaL_addvalue(&b);
luaL_addchar(&b, '<');
luaL_addstring(&b, tag);
luaL_addchar(&b, '>');
Xml_pushEncode(L, 1); // encode(tostring(value))
luaL_addvalue(&b);
luaL_addlstring(&b, "</", 2);
luaL_addstring(&b, tag);
luaL_addlstring(&b, ">\n", 2);
luaL_pushresult(&b);
return 1;
}
/** match XML entity against given (optional) criteria.
Passing `nil` for one of the` tag`, `key`, or `value` parameters means "don't
care" (i.e. match anything for that particular aspect). So for example
var:match(nil, "text", nil)
-- or shorter, but identical: var:match(nil, "text")
will look for an XML attribute (name) "text" to be present in `var`, but won't
consider its value or the tag of `var`.
Note: If you want to test for a specific attribute `value`, so also have to
supply a `key` - otherwise `value` will be ignored.
@usage
-- each of these will either return `x`, or `nil` in case of no match
x:match("foo") -- test for x:tag() == "foo"
x:match(nil, "bar") -- test if x has a "bar" attribute
x:match(nil, "foo", "bar") -- test if x has a "foo" attribute that equals "bar"
x:match("foobar", "foo", "bar") -- test for "foobar" tag, and attr "foo" == "bar"
@function match
@param var
the variable to test, normally a Lua table or LuaXML object. (If `var` is not
a table type, the test always fails.)