sq_xml-2.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /**
  2. LuaXML License
  3. LuaXml is licensed under the terms of the MIT license reproduced below,
  4. the same as Lua itself. This means that LuaXml is free software and can be
  5. used for both academic and commercial purposes at absolutely no cost.
  6. Copyright (C) 2007-2010 Gerald Franz, www.viremo.de
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. Ported to Squirrel/SquiLu by Domingo Alvarez Duarte 22/01/2012
  23. */
  24. #include "squirrel.h"
  25. #include "sqstdblobimpl.h"
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <ctype.h>
  29. #include <stdlib.h>
  30. SQ_OPT_STRING_STRLEN();
  31. static const SQChar ESC=27;
  32. static const SQChar OPN=28;
  33. static const SQChar CLS=29;
  34. //--- auxliary functions -------------------------------------------
  35. static const SQChar* char2code(USQChar ch, SQChar buf[8]) {
  36. USQChar i=0;
  37. buf[i++]=_SC('&');
  38. buf[i++]=_SC('#');
  39. if(ch>99) buf[i++]=ch/100+48;
  40. if(ch>9) buf[i++]=(ch%100)/10+48;
  41. buf[i++]=ch%10+48;
  42. buf[i++]=_SC(';');
  43. buf[i]=0;
  44. return buf;
  45. }
  46. static size_t find(const SQChar* s, const SQChar* pattern, size_t start) {
  47. const SQChar* found =scstrstr(s+start, pattern);
  48. return found ? found-s : scstrlen(s);
  49. }
  50. //--- internal tokenizer -------------------------------------------
  51. typedef struct Tokenizer_s {
  52. /// stores string to be tokenized
  53. const SQChar* s;
  54. /// stores size of string to be tokenized
  55. size_t s_size;
  56. /// stores current read position
  57. size_t i;
  58. /// stores current read context
  59. int tagMode;
  60. /// stores next token, if already determined
  61. const SQChar* m_next;
  62. /// size of next token
  63. size_t m_next_size;
  64. /// pointer to current token
  65. SQChar* m_token;
  66. /// size of current token
  67. size_t m_token_size;
  68. /// capacity of current token
  69. size_t m_token_capacity;
  70. } Tokenizer;
  71. Tokenizer* Tokenizer_new(const SQChar* str, size_t str_size) {
  72. Tokenizer *tok = (Tokenizer*)sq_malloc(sizeof(Tokenizer));
  73. memset(tok, 0, sizeof(Tokenizer));
  74. tok->s_size = str_size;
  75. tok->s = str;
  76. return tok;
  77. }
  78. void Tokenizer_delete(Tokenizer* tok) {
  79. sq_free(tok->m_token);
  80. sq_free(tok);
  81. }
  82. //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); }
  83. static const SQChar* Tokenizer_set(Tokenizer* tok, const SQChar* s, size_t size) {
  84. if(!size||!s) return 0;
  85. free(tok->m_token);
  86. tok->m_token = (SQChar*)sq_malloc(size+1);
  87. scstrncpy(tok->m_token,s, size);
  88. tok->m_token[size] = 0;
  89. tok->m_token_size = tok->m_token_capacity = size;
  90. //Tokenizer_print(tok);
  91. return tok->m_token;
  92. }
  93. static void Tokenizer_append(Tokenizer* tok, SQChar ch) {
  94. if(tok->m_token_size+1>=tok->m_token_capacity) {
  95. tok->m_token_capacity = (tok->m_token_capacity==0) ? 16 : tok->m_token_capacity*2;
  96. tok->m_token = (SQChar*)sq_realloc(tok->m_token, tok->m_token_capacity);
  97. }
  98. tok->m_token[tok->m_token_size]=ch;
  99. tok->m_token[++tok->m_token_size]=0;
  100. }
  101. const SQChar* Tokenizer_next(Tokenizer* tok) {
  102. const SQChar* ESC_str = _SC("\033");
  103. const SQChar* OPEN_str = _SC("\034");
  104. const SQChar* CLOSE_str = _SC("\035");
  105. if(tok->m_token) {
  106. sq_free(tok->m_token);
  107. tok->m_token = 0;
  108. tok->m_token_size=tok->m_token_capacity = 0;
  109. }
  110. int quotMode=0;
  111. int tokenComplete = 0;
  112. while(tok->m_next_size || (tok->i < tok->s_size)) {
  113. if(tok->m_next_size) {
  114. Tokenizer_set(tok, tok->m_next, tok->m_next_size);
  115. tok->m_next=0;
  116. tok->m_next_size=0;
  117. return tok->m_token;
  118. }
  119. switch(tok->s[tok->i]) {
  120. case _SC('"'):
  121. case _SC('\''):
  122. if(tok->tagMode) {
  123. if(!quotMode) quotMode=tok->s[tok->i];
  124. else if(quotMode==tok->s[tok->i]) quotMode=0;
  125. }
  126. Tokenizer_append(tok, tok->s[tok->i]);
  127. break;
  128. case _SC('<'):
  129. if(!quotMode&&(tok->i+4<tok->s_size)&&(scstrncmp(tok->s+tok->i,_SC("<!--"),4)==0)) // strip comments
  130. tok->i=find(tok->s, _SC("-->"), tok->i+4)+2;
  131. else if(!quotMode&&(tok->i+9<tok->s_size)&&(scstrncmp(tok->s+tok->i,_SC("<![CDATA["),9)==0)) { // interpret CDATA
  132. size_t b=tok->i+9;
  133. tok->i=find(tok->s, _SC("]]>"),b)+3;
  134. if(!tok->m_token_size) return Tokenizer_set(tok, tok->s+b, tok->i-b-3);
  135. tokenComplete = 1;
  136. tok->m_next = tok->s+b;
  137. tok->m_next_size = tok->i-b-3;
  138. --tok->i;
  139. }
  140. else if(!quotMode&&(tok->i+1<tok->s_size)&&((tok->s[tok->i+1]==_SC('?'))||(tok->s[tok->i+1]==_SC('!')))) // strip meta information
  141. tok->i=find(tok->s, _SC(">"), tok->i+2);
  142. else if(!quotMode&&!tok->tagMode) {
  143. if((tok->i+1<tok->s_size)&&(tok->s[tok->i+1]==_SC('/'))) {
  144. tok->m_next=ESC_str;
  145. tok->m_next_size = 1;
  146. tok->i=find(tok->s, _SC(">"), tok->i+2);
  147. }
  148. else {
  149. tok->m_next = OPEN_str;
  150. tok->m_next_size = 1;
  151. tok->tagMode=1;
  152. }
  153. tokenComplete = 1;
  154. }
  155. else Tokenizer_append(tok, tok->s[tok->i]);
  156. break;
  157. case _SC('/'):
  158. if(tok->tagMode&&!quotMode) {
  159. tokenComplete = 1;
  160. if((tok->i+1 < tok->s_size) && (tok->s[tok->i+1]==_SC('>'))) {
  161. tok->tagMode=0;
  162. tok->m_next=ESC_str;
  163. tok->m_next_size = 1;
  164. ++tok->i;
  165. }
  166. else Tokenizer_append(tok, tok->s[tok->i]);
  167. }
  168. else Tokenizer_append(tok, tok->s[tok->i]);
  169. break;
  170. case _SC('>'):
  171. if(!quotMode&&tok->tagMode) {
  172. tok->tagMode=0;
  173. tokenComplete = 1;
  174. tok->m_next = CLOSE_str;
  175. tok->m_next_size = 1;
  176. }
  177. else Tokenizer_append(tok, tok->s[tok->i]);
  178. break;
  179. case _SC(' '):
  180. case _SC('\r'):
  181. case _SC('\n'):
  182. case _SC('\t'):
  183. if(tok->tagMode&&!quotMode) {
  184. if(tok->m_token_size) tokenComplete=1;
  185. }
  186. else if(tok->m_token_size) Tokenizer_append(tok, tok->s[tok->i]);
  187. break;
  188. default: Tokenizer_append(tok, tok->s[tok->i]);
  189. }
  190. ++tok->i;
  191. if((tok->i>=tok->s_size)||(tokenComplete&&tok->m_token_size)) {
  192. tokenComplete=0;
  193. while(tok->m_token_size&&isspace(tok->m_token[tok->m_token_size-1])) // trim whitespace
  194. tok->m_token[--tok->m_token_size]=0;
  195. if(tok->m_token_size) break;
  196. }
  197. }
  198. //Tokenizer_print(tok);
  199. return tok->m_token;
  200. }
  201. //--- local variables ----------------------------------------------
  202. /// stores number of special character codes
  203. static size_t sv_code_size=0;
  204. /// stores currently allocated capacity for special character codes
  205. static size_t sv_code_capacity=16;
  206. /// stores code table for special characters
  207. static SQChar** sv_code=0;
  208. static const SQChar *sq_str_replace (HSQUIRRELVM v, const SQChar *s, const SQChar *p, const SQChar *r) {
  209. const SQChar *wild;
  210. size_t l = scstrlen(p);
  211. SQBlob b(0, BLOB_BUFSIZE);
  212. while ((wild = scstrstr(s, p)) != NULL) {
  213. b.Write(s, wild - s); /* push prefix */
  214. b.WriteZstr(r); /* push replacement in place of pattern */
  215. s = wild + l; /* continue after `p' */
  216. }
  217. b.WriteZstr(s); /* push last suffix */
  218. sq_pushstring(v, (const SQChar*)b.GetBuf(), b.Len());
  219. return sq_tostring(v, -1);
  220. }
  221. //--- public methods -----------------------------------------------
  222. static void Xml_pushDecode(HSQUIRRELVM v, const char* s, size_t s_size) {
  223. SQ_FUNC_VARS_NO_TOP(v);
  224. size_t start=0, pos;
  225. if(!s_size) s_size=strlen(s);
  226. SQBlob b(0, BLOB_BUFSIZE);
  227. const char* found = scstrstr(s, _SC("&#"));
  228. if(!found) pos = s_size;
  229. else pos = found-s;
  230. while(found&&(pos+5<s_size)&&(*(found+5)==_SC(';'))&&scisdigit(*(found+2))&&scisdigit(*(found+3))&&scisdigit(*(found+4)) ) {
  231. if(pos>start) b.Write(s+start, pos-start);
  232. b.WriteChar(100*(s[pos+2]-48)+10*(s[pos+3]-48)+(s[pos+4]-48));
  233. start=pos+6;
  234. found = scstrstr(found+6, _SC("&#"));
  235. if(!found) pos = s_size;
  236. else pos = found-s;
  237. }
  238. if(pos>start) b.Write(s+start, pos-start);
  239. sq_pushstring(v, (const SQChar*)b.GetBuf(), b.Len());
  240. size_t i;
  241. for(i=sv_code_size-1; i<sv_code_size; i-=2) {
  242. SQ_GET_STRING(v, -1, str);
  243. sq_str_replace(v, str, sv_code[i], sv_code[i-1]);
  244. sq_remove(v,-2);
  245. }
  246. }
  247. int Xml_eval(HSQUIRRELVM v) {
  248. SQ_FUNC_VARS_NO_TOP(v);
  249. SQChar* str = 0;
  250. size_t str_size=0;
  251. if(sq_gettype(v,2) == OT_USERPOINTER) sq_getuserpointer(v, 2, &str);
  252. else {
  253. SQ_GET_STRING(v, 2, sTmp);
  254. str = (SQChar*)sq_malloc(sTmp_size+(sizeof(SQChar)));
  255. memcpy(str, sTmp, sTmp_size);
  256. str[sTmp_size]=0;
  257. str_size = sTmp_size;
  258. }
  259. Tokenizer* tok = Tokenizer_new(str, str_size ? str_size : scstrlen(str));
  260. sq_settop(v,0);
  261. const SQChar* token=0;
  262. int firstStatement = 1;
  263. while((token=Tokenizer_next(tok))!=0) if(token[0]==OPN) { // new tag found
  264. if(sq_gettop(v)) {
  265. int newIndex=sq_size(v,-1)+1;
  266. sq_pushinteger(v,newIndex);
  267. sq_newtable(v);
  268. sq_set(v, -3);
  269. sq_pushinteger(v,newIndex);
  270. sq_get(v,-2);
  271. }
  272. else {
  273. if (firstStatement) {
  274. sq_newtable(v);
  275. firstStatement = 0;
  276. }
  277. else return lua_gettop(L);
  278. }
  279. // set metatable:
  280. sq_newtable(v);
  281. sq_pushliteral(v, _SC("__index"));
  282. sq_getglobal(v, "xml");
  283. lua_settable(v, -3);
  284. sq_pushliteral(v, _SC("__tostring")); // set __tostring metamethod
  285. lua_getglobal(L, "xml");
  286. lua_pushliteral(L,"str");
  287. lua_gettable(v, -2);
  288. sq_remove(v, -2);
  289. sq_set(v, -3);
  290. lua_setmetatable(L, -2);
  291. // parse tag and content:
  292. sq_pushinteger(v,0); // use index 0 for storing the tag
  293. sq_pushstring(v, Tokenizer_next(tok), -1);
  294. sq_set(v, -3);
  295. while(((token = Tokenizer_next(tok))!=0)&&(token[0]!=CLS)&&(token[0]!=ESC)) { // parse tag header
  296. size_t sepPos=find(token, "=", 0);
  297. if(token[sepPos]) { // regular attribute
  298. const SQChar* aVal =token+sepPos+2;
  299. sq_pushstring(v, token, sepPos);
  300. size_t lenVal = strlen(aVal)-1;
  301. if(!lenVal) Xml_pushDecode(v, _SC(""), 0);
  302. else Xml_pushDecode(v, aVal, lenVal);
  303. sq_set(v, -3);
  304. }
  305. }
  306. if(!token||(token[0]==ESC)) {
  307. if(sq_gettop(v)>1) sq_settop(v,-2); // this tag has no content, only attributes
  308. else break;
  309. }
  310. }
  311. else if(token[0]==ESC) { // previous tag is over
  312. if(sq_gettop(v)>1) sq_settop(v,-2); // pop current table
  313. else break;
  314. }
  315. else { // read elements
  316. sq_pushinteger(v,sq_size(v,-1)+1);
  317. Xml_pushDecode(v, token, 0);
  318. sq_rawset(v, -3);
  319. }
  320. Tokenizer_delete(tok);
  321. sq_free(str);
  322. return sq_gettop(v);
  323. }
  324. int Xml_load (HSQUIRRELVM v) {
  325. SQ_FUNC_VARS_NO_TOP(v);
  326. SQ_GET_STRING(v, 2, filename);
  327. FILE * file=fopen(filename,"r");
  328. if(!file) return sq_throwerror(v, _SC("SQXml ERROR: \"%s\" file error or file not found!"),filename);
  329. fseek (file , 0 , SEEK_END);
  330. size_t sz = ftell (file);
  331. rewind (file);
  332. char* buffer = (char*)sq_malloc(sz+1);
  333. sz = fread (buffer,1,sz,file);
  334. fclose(file);
  335. buffer[sz]=0;
  336. sq_pushuserpointer(v,buffer);
  337. sq_replace(v,2);
  338. return Xml_eval(v);
  339. };
  340. int Xml_registerCode(HSQUIRRELVM v) {
  341. SQ_FUNC_VARS_NO_TOP(v);
  342. SQ_GET_STRING(v, 2, decoded);
  343. SQ_GET_STRING(v, 3, encoded);
  344. size_t i;
  345. for(i=0; i<sv_code_size; i+=2)
  346. if(scstrcmp(sv_code[i],decoded)==0)
  347. return sq_throwerror(v,_SC"SQXml ERROR: code already exists."));
  348. if(sv_code_size+2>sv_code_capacity) {
  349. size_t old_capacity = sv_code_capacity;
  350. sv_code_capacity*=2;
  351. sv_code = (SQChar**)sq_realloc(sv_code, old_capacity*sizeof(SQChar*), sv_code_capacity*sizeof(SQChar*));
  352. }
  353. sv_code[sv_code_size]=(SQChar*)sq_malloc((scstrlen(decoded)+1)*sizeof(SQChar*));
  354. strcpy(sv_code[sv_code_size++], decoded);
  355. sv_code[sv_code_size]=(SQChar*)sq_malloc((scstrlen(decoded)+1)*sizeof(SQChar*));
  356. strcpy(sv_code[sv_code_size++],encoded);
  357. return 0;
  358. }
  359. int Xml_encode(HSQUIRRELVM v) {
  360. SQ_FUNC_VARS(v);
  361. SQ_GET_STRING(v, 2, s);
  362. size_t i;
  363. for(i=0; i<sv_code_size; i+=2) {
  364. sq_str_replace(v, s, sv_code[i], sv_code[i+1]);
  365. sq_remove(v,-2);
  366. }
  367. SQChar buf[8];
  368. SQ_GET_STRING(v, 2, s);
  369. size_t start, pos;
  370. SQBlob b(0, BLOB_BUFSIZE);
  371. for(start=pos=0; s[pos]!=0; ++pos) if(s[pos]<0) {
  372. if(pos>start) b.Write(s+start, pos-start);
  373. b.WriteZstr(char2code(uchar(s[pos]),buf));
  374. start=pos+1;
  375. }
  376. if(pos>start) b.Write(s+start, pos-start);
  377. sq_pushstring(v, (const SQChar*)b.GetBuf(), b.Len());
  378. return 1;
  379. }
  380. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name),base64_##name,nparams,tycheck}
  381. static SQRegFunction xml_methods[] =
  382. {
  383. _DECL_FUNC(load,2,_SC(".s")),
  384. _DECL_FUNC(eval,2,_SC(".s")),
  385. _DECL_FUNC(encode,2,_SC(".s")),
  386. _DECL_FUNC(registerCode,2,_SC(".s")),
  387. {0,0}
  388. };
  389. #ifdef __cplusplus
  390. extern "C" {
  391. #endif
  392. SQRESULT sqext_register_sqxml(HSQUIRRELVM v)
  393. {
  394. sq_pushstring(v,_SC("SQXml"),-1);
  395. sq_newclass(v,SQFalse);
  396. sq_insert_reg_funcs(v, xml_methods);
  397. sq_newslot(v,-3,SQTrue);
  398. // register default codes:
  399. if(!sv_code) {
  400. sv_code=(SQChar**)sq_malloc(sv_code_capacity*sizeof(SQChar*));
  401. sv_code[sv_code_size++]=_SC("&");
  402. sv_code[sv_code_size++]=_SC("&amp;");
  403. sv_code[sv_code_size++]=_SC("<");
  404. sv_code[sv_code_size++]=_SC("&lt;");
  405. sv_code[sv_code_size++]=_SC(">");
  406. sv_code[sv_code_size++]=_SC("&gt;");
  407. sv_code[sv_code_size++]=_SC("\"");
  408. sv_code[sv_code_size++]=_SC("&quot;");
  409. sv_code[sv_code_size++]=_SC("'");
  410. sv_code[sv_code_size++]=_SC("&apos;");
  411. }
  412. return 1;
  413. }
  414. #ifdef __cplusplus
  415. }
  416. #endif