sqstdstring.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /* see copyright notice in squirrel.h */
  2. #include <squirrel.h>
  3. #include <sqstdstring.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <ctype.h>
  8. #include <assert.h>
  9. #include <stdarg.h>
  10. #define MAX_FORMAT_LEN 20
  11. #define MAX_WFORMAT_LEN 3
  12. #define ADDITIONAL_FORMAT_SPACE (100*sizeof(SQChar))
  13. static SQUserPointer rex_typetag = NULL;
  14. static SQBool isfmtchr(SQChar ch)
  15. {
  16. switch(ch) {
  17. case '-': case '+': case ' ': case '#': case '0': return SQTrue;
  18. }
  19. return SQFalse;
  20. }
  21. static SQInteger validate_format(HSQUIRRELVM v, SQChar *fmt, const SQChar *src, SQInteger n,SQInteger &width)
  22. {
  23. SQChar *dummy;
  24. SQChar swidth[MAX_WFORMAT_LEN];
  25. SQInteger wc = 0;
  26. SQInteger start = n;
  27. fmt[0] = '%';
  28. while (isfmtchr(src[n])) n++;
  29. while (scisdigit(src[n])) {
  30. swidth[wc] = src[n];
  31. n++;
  32. wc++;
  33. if(wc>=MAX_WFORMAT_LEN)
  34. return sq_throwerror(v,_SC("width format too long"));
  35. }
  36. swidth[wc] = '\0';
  37. if(wc > 0) {
  38. width = scstrtol(swidth,&dummy,10);
  39. }
  40. else
  41. width = 0;
  42. if (src[n] == '.') {
  43. n++;
  44. wc = 0;
  45. while (scisdigit(src[n])) {
  46. swidth[wc] = src[n];
  47. n++;
  48. wc++;
  49. if(wc>=MAX_WFORMAT_LEN)
  50. return sq_throwerror(v,_SC("precision format too long"));
  51. }
  52. swidth[wc] = '\0';
  53. if(wc > 0) {
  54. width += scstrtol(swidth,&dummy,10);
  55. }
  56. }
  57. if (n-start > MAX_FORMAT_LEN )
  58. return sq_throwerror(v,_SC("format too long"));
  59. memcpy(&fmt[1],&src[start],((n-start)+1)*sizeof(SQChar));
  60. fmt[(n-start)+2] = '\0';
  61. return n;
  62. }
  63. SQRESULT sqstd_format(HSQUIRRELVM v,SQInteger nformatstringidx,SQInteger *outlen,SQChar **output)
  64. {
  65. const SQChar *format;
  66. SQChar *dest;
  67. SQChar fmt[MAX_FORMAT_LEN];
  68. const SQRESULT res = sq_getstring(v,nformatstringidx,&format);
  69. if (SQ_FAILED(res)) {
  70. return res; // propagate the error
  71. }
  72. SQInteger format_size = sq_getsize(v,nformatstringidx);
  73. SQInteger allocated = (format_size+2)*sizeof(SQChar);
  74. dest = sq_getscratchpad(v,allocated);
  75. SQInteger n = 0,i = 0, nparam = nformatstringidx+1, w = 0;
  76. //while(format[n] != '\0')
  77. while(n < format_size)
  78. {
  79. if(format[n] != '%') {
  80. assert(i < allocated);
  81. dest[i++] = format[n];
  82. n++;
  83. }
  84. else if(format[n+1] == '%') { //handles %%
  85. dest[i++] = '%';
  86. n += 2;
  87. }
  88. else {
  89. n++;
  90. if( nparam > sq_gettop(v) )
  91. return sq_throwerror(v,_SC("not enough parameters for the given format string"));
  92. n = validate_format(v,fmt,format,n,w);
  93. if(n < 0) return -1;
  94. SQInteger addlen = 0;
  95. SQInteger valtype = 0;
  96. const SQChar *ts = NULL;
  97. SQInteger ti = 0;
  98. SQFloat tf = 0;
  99. switch(format[n]) {
  100. case 's':
  101. if(SQ_FAILED(sq_getstring(v,nparam,&ts)))
  102. return sq_throwerror(v,_SC("string expected for the specified format"));
  103. addlen = (sq_getsize(v,nparam)*sizeof(SQChar))+((w+1)*sizeof(SQChar));
  104. valtype = 's';
  105. break;
  106. case 'i': case 'd': case 'o': case 'u': case 'x': case 'X':
  107. #ifdef _SQ64
  108. {
  109. size_t flen = scstrlen(fmt);
  110. SQInteger fpos = flen - 1;
  111. SQChar f = fmt[fpos];
  112. const SQChar *prec = (const SQChar *)_PRINT_INT_PREC;
  113. while(*prec != _SC('\0')) {
  114. fmt[fpos++] = *prec++;
  115. }
  116. fmt[fpos++] = f;
  117. fmt[fpos++] = _SC('\0');
  118. }
  119. #endif
  120. case 'c':
  121. if(SQ_FAILED(sq_getinteger(v,nparam,&ti)))
  122. return sq_throwerror(v,_SC("integer expected for the specified format"));
  123. addlen = (ADDITIONAL_FORMAT_SPACE)+((w+1)*sizeof(SQChar));
  124. valtype = 'i';
  125. break;
  126. case 'f': case 'g': case 'G': case 'e': case 'E':
  127. if(SQ_FAILED(sq_getfloat(v,nparam,&tf)))
  128. return sq_throwerror(v,_SC("float expected for the specified format"));
  129. addlen = (ADDITIONAL_FORMAT_SPACE)+((w+1)*sizeof(SQChar));
  130. valtype = 'f';
  131. break;
  132. default:
  133. return sq_throwerror(v,_SC("invalid format"));
  134. }
  135. n++;
  136. allocated += addlen + sizeof(SQChar);
  137. dest = sq_getscratchpad(v,allocated);
  138. switch(valtype) {
  139. case 's': i += scsprintf(&dest[i],allocated,fmt,ts); break;
  140. case 'i': i += scsprintf(&dest[i],allocated,fmt,ti); break;
  141. case 'f': i += scsprintf(&dest[i],allocated,fmt,tf); break;
  142. };
  143. nparam ++;
  144. }
  145. }
  146. *outlen = i;
  147. dest[i] = '\0';
  148. *output = dest;
  149. return SQ_OK;
  150. }
  151. void sqstd_pushstringf(HSQUIRRELVM v,const SQChar *s,...)
  152. {
  153. SQInteger n=256;
  154. va_list args;
  155. begin:
  156. va_start(args,s);
  157. SQChar *b=sq_getscratchpad(v,n);
  158. SQInteger r=scvsprintf(b,n,s,args);
  159. va_end(args);
  160. if (r>=n) {
  161. n=r+1;//required+null
  162. goto begin;
  163. } else if (r<0) {
  164. sq_pushnull(v);
  165. } else {
  166. sq_pushstring(v,b,r);
  167. }
  168. }
  169. static SQInteger _string_printf(HSQUIRRELVM v)
  170. {
  171. SQChar *dest = NULL;
  172. SQInteger length = 0;
  173. if(SQ_FAILED(sqstd_format(v,2,&length,&dest)))
  174. return -1;
  175. SQPRINTFUNCTION printfunc = sq_getprintfunc(v);
  176. if(printfunc) printfunc(v,_SC("%s"),dest);
  177. return 0;
  178. }
  179. static SQInteger _string_format(HSQUIRRELVM v)
  180. {
  181. SQChar *dest = NULL;
  182. SQInteger length = 0;
  183. if(SQ_FAILED(sqstd_format(v,2,&length,&dest)))
  184. return -1;
  185. sq_pushstring(v,dest,length);
  186. return 1;
  187. }
  188. static void __strip_l(const SQChar *str,const SQChar **start)
  189. {
  190. const SQChar *t = str;
  191. while(((*t) != '\0') && scisspace(*t)){ t++; }
  192. *start = t;
  193. }
  194. static void __strip_r(const SQChar *str,SQInteger len,const SQChar **end)
  195. {
  196. if(len == 0) {
  197. *end = str;
  198. return;
  199. }
  200. const SQChar *t = &str[len-1];
  201. while(t >= str && scisspace(*t)) { t--; }
  202. *end = t + 1;
  203. }
  204. static SQInteger _string_strip(HSQUIRRELVM v)
  205. {
  206. const SQChar *str,*start,*end;
  207. sq_getstring(v,2,&str);
  208. SQInteger len = sq_getsize(v,2);
  209. __strip_l(str,&start);
  210. __strip_r(str,len,&end);
  211. sq_pushstring(v,start,end - start);
  212. return 1;
  213. }
  214. static SQInteger _string_lstrip(HSQUIRRELVM v)
  215. {
  216. const SQChar *str,*start;
  217. sq_getstring(v,2,&str);
  218. __strip_l(str,&start);
  219. sq_pushstring(v,start,-1);
  220. return 1;
  221. }
  222. static SQInteger _string_rstrip(HSQUIRRELVM v)
  223. {
  224. const SQChar *str,*end;
  225. sq_getstring(v,2,&str);
  226. SQInteger len = sq_getsize(v,2);
  227. __strip_r(str,len,&end);
  228. sq_pushstring(v,str,end - str);
  229. return 1;
  230. }
  231. static SQInteger _string_split(HSQUIRRELVM v)
  232. {
  233. const SQChar *str,*seps;
  234. SQInteger sepsize;
  235. SQBool skipempty = SQFalse;
  236. sq_getstring(v,2,&str);
  237. sq_getstringandsize(v,3,&seps,&sepsize);
  238. if(sepsize == 0) return sq_throwerror(v,_SC("empty separators string"));
  239. if(sq_gettop(v)>3) {
  240. sq_getbool(v,4,&skipempty);
  241. }
  242. const SQChar *start = str;
  243. const SQChar *end = str;
  244. sq_newarray(v,0);
  245. while(*end != '\0')
  246. {
  247. SQChar cur = *end;
  248. for(SQInteger i = 0; i < sepsize; i++)
  249. {
  250. if(cur == seps[i])
  251. {
  252. if(!skipempty || (end != start)) {
  253. sq_pushstring(v,start,end-start);
  254. sq_arrayappend(v,-2);
  255. }
  256. start = end + 1;
  257. break;
  258. }
  259. }
  260. end++;
  261. }
  262. if(end != start)
  263. {
  264. sq_pushstring(v,start,end-start);
  265. sq_arrayappend(v,-2);
  266. }
  267. return 1;
  268. }
  269. static SQInteger _string_escape(HSQUIRRELVM v)
  270. {
  271. const SQChar *str;
  272. SQChar *dest,*resstr;
  273. SQInteger size;
  274. sq_getstring(v,2,&str);
  275. size = sq_getsize(v,2);
  276. if(size == 0) {
  277. sq_push(v,2);
  278. return 1;
  279. }
  280. #ifdef SQUNICODE
  281. #if WCHAR_SIZE == 2
  282. const SQChar *escpat = _SC("\\x%04x");
  283. const SQInteger maxescsize = 6;
  284. #else //WCHAR_SIZE == 4
  285. const SQChar *escpat = _SC("\\x%08x");
  286. const SQInteger maxescsize = 10;
  287. #endif
  288. #else
  289. const SQChar *escpat = _SC("\\x%02x");
  290. const SQInteger maxescsize = 4;
  291. #endif
  292. SQInteger destcharsize = (size * maxescsize); //assumes every char could be escaped
  293. resstr = dest = (SQChar *)sq_getscratchpad(v,destcharsize * sizeof(SQChar));
  294. SQChar c;
  295. SQChar escch;
  296. SQInteger escaped = 0;
  297. for(int n = 0; n < size; n++){
  298. c = *str++;
  299. escch = 0;
  300. if(scisprint(c) || c == 0) {
  301. switch(c) {
  302. case '\a': escch = 'a'; break;
  303. case '\b': escch = 'b'; break;
  304. case '\t': escch = 't'; break;
  305. case '\n': escch = 'n'; break;
  306. case '\v': escch = 'v'; break;
  307. case '\f': escch = 'f'; break;
  308. case '\r': escch = 'r'; break;
  309. case '\\': escch = '\\'; break;
  310. case '\"': escch = '\"'; break;
  311. case '\'': escch = '\''; break;
  312. case 0: escch = '0'; break;
  313. }
  314. if(escch) {
  315. *dest++ = '\\';
  316. *dest++ = escch;
  317. escaped++;
  318. }
  319. else {
  320. *dest++ = c;
  321. }
  322. }
  323. else {
  324. dest += scsprintf(dest, destcharsize, escpat, c);
  325. escaped++;
  326. }
  327. }
  328. if(escaped) {
  329. sq_pushstring(v,resstr,dest - resstr);
  330. }
  331. else {
  332. sq_push(v,2); //nothing escaped
  333. }
  334. return 1;
  335. }
  336. static SQInteger _string_startswith(HSQUIRRELVM v)
  337. {
  338. const SQChar *str,*cmp;
  339. sq_getstring(v,2,&str);
  340. sq_getstring(v,3,&cmp);
  341. SQInteger len = sq_getsize(v,2);
  342. SQInteger cmplen = sq_getsize(v,3);
  343. SQBool ret = SQFalse;
  344. if(cmplen <= len) {
  345. ret = memcmp(str,cmp,sq_rsl(cmplen)) == 0 ? SQTrue : SQFalse;
  346. }
  347. sq_pushbool(v,ret);
  348. return 1;
  349. }
  350. static SQInteger _string_endswith(HSQUIRRELVM v)
  351. {
  352. const SQChar *str,*cmp;
  353. sq_getstring(v,2,&str);
  354. sq_getstring(v,3,&cmp);
  355. SQInteger len = sq_getsize(v,2);
  356. SQInteger cmplen = sq_getsize(v,3);
  357. SQBool ret = SQFalse;
  358. if(cmplen <= len) {
  359. ret = memcmp(&str[len - cmplen],cmp,sq_rsl(cmplen)) == 0 ? SQTrue : SQFalse;
  360. }
  361. sq_pushbool(v,ret);
  362. return 1;
  363. }
  364. #define SETUP_REX(v) \
  365. SQRex *self = NULL; \
  366. if(SQ_FAILED(sq_getinstanceup(v,1,(SQUserPointer *)&self,rex_typetag,SQFalse))) { \
  367. return sq_throwerror(v,_SC("invalid type tag")); \
  368. }
  369. static SQInteger _rexobj_releasehook(SQUserPointer p, SQInteger SQ_UNUSED_ARG(size))
  370. {
  371. SQRex *self = ((SQRex *)p);
  372. sqstd_rex_free(self);
  373. return 1;
  374. }
  375. static SQInteger _regexp_match(HSQUIRRELVM v)
  376. {
  377. SETUP_REX(v);
  378. const SQChar *str;
  379. sq_getstring(v,2,&str);
  380. if(sqstd_rex_match(self,str) == SQTrue)
  381. {
  382. sq_pushbool(v,SQTrue);
  383. return 1;
  384. }
  385. sq_pushbool(v,SQFalse);
  386. return 1;
  387. }
  388. static void _addrexmatch(HSQUIRRELVM v,const SQChar *str,const SQChar *begin,const SQChar *end)
  389. {
  390. sq_newtable(v);
  391. sq_pushstring(v,_SC("begin"),-1);
  392. sq_pushinteger(v,begin - str);
  393. sq_rawset(v,-3);
  394. sq_pushstring(v,_SC("end"),-1);
  395. sq_pushinteger(v,end - str);
  396. sq_rawset(v,-3);
  397. }
  398. static SQInteger _regexp_search(HSQUIRRELVM v)
  399. {
  400. SETUP_REX(v);
  401. const SQChar *str,*begin,*end;
  402. SQInteger start = 0;
  403. sq_getstring(v,2,&str);
  404. if(sq_gettop(v) > 2) sq_getinteger(v,3,&start);
  405. if(sqstd_rex_search(self,str+start,&begin,&end) == SQTrue) {
  406. _addrexmatch(v,str,begin,end);
  407. return 1;
  408. }
  409. return 0;
  410. }
  411. static SQInteger _regexp_capture(HSQUIRRELVM v)
  412. {
  413. SETUP_REX(v);
  414. const SQChar *str,*begin,*end;
  415. SQInteger start = 0;
  416. sq_getstring(v,2,&str);
  417. if(sq_gettop(v) > 2) sq_getinteger(v,3,&start);
  418. if(sqstd_rex_search(self,str+start,&begin,&end) == SQTrue) {
  419. SQInteger n = sqstd_rex_getsubexpcount(self);
  420. SQRexMatch match;
  421. sq_newarray(v,0);
  422. for(SQInteger i = 0;i < n; i++) {
  423. sqstd_rex_getsubexp(self,i,&match);
  424. if(match.len > 0)
  425. _addrexmatch(v,str,match.begin,match.begin+match.len);
  426. else
  427. _addrexmatch(v,str,str,str); //empty match
  428. sq_arrayappend(v,-2);
  429. }
  430. return 1;
  431. }
  432. return 0;
  433. }
  434. static SQInteger _regexp_subexpcount(HSQUIRRELVM v)
  435. {
  436. SETUP_REX(v);
  437. sq_pushinteger(v,sqstd_rex_getsubexpcount(self));
  438. return 1;
  439. }
  440. static SQInteger _regexp_constructor(HSQUIRRELVM v)
  441. {
  442. SQRex *self = NULL;
  443. if (SQ_FAILED(sq_getinstanceup(v, 1, (SQUserPointer *)&self, rex_typetag, SQFalse))) {
  444. return sq_throwerror(v, _SC("invalid type tag"));
  445. }
  446. if (self != NULL) {
  447. return sq_throwerror(v, _SC("invalid regexp object"));
  448. }
  449. const SQChar *error,*pattern;
  450. sq_getstring(v,2,&pattern);
  451. SQRex *rex = sqstd_rex_compile(pattern,&error);
  452. if(!rex) return sq_throwerror(v,error);
  453. sq_setinstanceup(v,1,rex);
  454. sq_setreleasehook(v,1,_rexobj_releasehook);
  455. return 0;
  456. }
  457. static SQInteger _regexp__typeof(HSQUIRRELVM v)
  458. {
  459. sq_pushstring(v,_SC("regexp"),-1);
  460. return 1;
  461. }
  462. #define _DECL_REX_FUNC(name,nparamsmin,nparamsmax,pmask) {_SC(#name),_regexp_##name,nparamsmin,nparamsmax,pmask}
  463. static const SQRegFunction rexobj_funcs[]={
  464. _DECL_REX_FUNC(constructor,2,2,_SC(".s")),
  465. _DECL_REX_FUNC(search,2,0,_SC("xsn")),
  466. _DECL_REX_FUNC(match,2,2,_SC("xs")),
  467. _DECL_REX_FUNC(capture,2,0,_SC("xsn")),
  468. _DECL_REX_FUNC(subexpcount,1,1,_SC("x")),
  469. _DECL_REX_FUNC(_typeof,1,1,_SC("x")),
  470. {NULL,(SQFUNCTION)0,0,0,NULL}
  471. };
  472. #undef _DECL_REX_FUNC
  473. #define _DECL_FUNC(name,nparamsmin,nparamsmax,pmask) {_SC(#name),_string_##name,nparamsmin,nparamsmax,pmask}
  474. static const SQRegFunction stringlib_funcs[]={
  475. _DECL_FUNC(format,2,0,_SC(".s")),
  476. _DECL_FUNC(printf,2,0,_SC(".s")),
  477. _DECL_FUNC(strip,2,2,_SC(".s")),
  478. _DECL_FUNC(lstrip,2,2,_SC(".s")),
  479. _DECL_FUNC(rstrip,2,2,_SC(".s")),
  480. _DECL_FUNC(split,3,0,_SC(".ssb")),
  481. _DECL_FUNC(escape,2,2,_SC(".s")),
  482. _DECL_FUNC(startswith,3,3,_SC(".ss")),
  483. _DECL_FUNC(endswith,3,3,_SC(".ss")),
  484. {NULL,(SQFUNCTION)0,0,0,NULL}
  485. };
  486. #undef _DECL_FUNC
  487. SQInteger sqstd_register_stringlib(HSQUIRRELVM v)
  488. {
  489. sq_pushstring(v,_SC("regexp"),-1);
  490. sq_newclass(v,SQFalse);
  491. rex_typetag = (SQUserPointer)rexobj_funcs;
  492. sq_settypetag(v, -1, rex_typetag);
  493. SQInteger i = 0;
  494. while(rexobj_funcs[i].name != 0) {
  495. const SQRegFunction &f = rexobj_funcs[i];
  496. sq_pushstring(v,f.name,-1);
  497. sq_newclosure(v,f.f,0);
  498. sq_setparamscheck(v,f.nparamscheckmin,f.nparamscheckmax,f.typemask);
  499. sq_setnativeclosurename(v,-1,f.name);
  500. sq_newslot(v,-3,SQFalse);
  501. i++;
  502. }
  503. sq_newslot(v,-3,SQFalse);
  504. i = 0;
  505. while(stringlib_funcs[i].name!=0)
  506. {
  507. sq_pushstring(v,stringlib_funcs[i].name,-1);
  508. sq_newclosure(v,stringlib_funcs[i].f,0);
  509. sq_setparamscheck(v,stringlib_funcs[i].nparamscheckmin,stringlib_funcs[i].nparamscheckmax,stringlib_funcs[i].typemask);
  510. sq_setnativeclosurename(v,-1,stringlib_funcs[i].name);
  511. sq_newslot(v,-3,SQFalse);
  512. i++;
  513. }
  514. return 1;
  515. }