Debian Codegraph @

terps/tads/tads3/vmstr.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/VMSTR.CPP,v 1.3 1999/05/17 02:52:28 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1998, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 vmstr.cpp - VM string metaclass implementation
15 Function
16
17 Notes
18
19 Modified
20 10/28/98 MJRoberts - Creation
21 */
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <limits.h>
27 #include <stdarg.h>
28
29 #include "t3std.h"
30 #include "vmmcreg.h"
31 #include "vmobj.h"
32 #include "vmstr.h"
33 #include "utf8.h"
34 #include "vmerr.h"
35 #include "vmerrnum.h"
36 #include "vmfile.h"
37 #include "vmstack.h"
38 #include "vmpool.h"
39 #include "vmmeta.h"
40 #include "vmrun.h"
41 #include "vmbif.h"
42 #include "vmpredef.h"
43 #include "vmlst.h"
44 #include "vmuni.h"
45 #include "vmcset.h"
46 #include "vmbytarr.h"
47 #include "vmstrbuf.h"
48 #include "charmap.h"
49 #include "vmnet.h"
50 #include "vmstrref.h"
51 #include "sha2.h"
52 #include "md5.h"
53 #include "vmpack.h"
54 #include "vmdatasrc.h"
55 #include "vmpat.h"
56 #include "vmregex.h"
57 #include "vmbiftad.h"
58 #include "vmfindrep.h"
59
60
61 /* ------------------------------------------------------------------------ */
62 /*
63 * statics
64 */
65
66 /* metaclass registration object */
67 static CVmMetaclassString metaclass_reg_obj;
68 CVmMetaclass *CVmObjString::metaclass_reg_ = &metaclass_reg_obj;
69
70 /* function table */
71 int (*CVmObjString::func_table_[])(VMG_ vm_val_t *retval,
72 const vm_val_t *self_val,
73 const char *str, uint *argc) =
74 {
75 &CVmObjString::getp_undef, /* 0 */
76 &CVmObjString::getp_len, /* 1 */
77 &CVmObjString::getp_substr, /* 2 */
78 &CVmObjString::getp_upper, /* 3 */
79 &CVmObjString::getp_lower, /* 4 */
80 &CVmObjString::getp_find, /* 5 */
81 &CVmObjString::getp_to_uni, /* 6 */
82 &CVmObjString::getp_htmlify, /* 7 */
83 &CVmObjString::getp_starts_with, /* 8 */
84 &CVmObjString::getp_ends_with, /* 9 */
85 &CVmObjString::getp_to_byte_array, /* 10 */
86 &CVmObjString::getp_replace, /* 11 */
87 &CVmObjString::getp_splice, /* 12 */
88 &CVmObjString::getp_split, /* 13 */
89 &CVmObjString::getp_specialsToHtml, /* 14 */
90 &CVmObjString::getp_specialsToText, /* 15 */
91 &CVmObjString::getp_urlEncode, /* 16 */
92 &CVmObjString::getp_urlDecode, /* 17 */
93 &CVmObjString::getp_sha256, /* 18 */
94 &CVmObjString::getp_md5, /* 19 */
95 &CVmObjString::getp_packBytes, /* 20 */
96 &CVmObjString::getp_unpackBytes, /* 21 */
97 &CVmObjString::getp_toTitleCase, /* 22 */
98 &CVmObjString::getp_toFoldedCase, /* 23 */
99 &CVmObjString::getp_compareTo, /* 24 */
100 &CVmObjString::getp_compareIgnoreCase, /* 25 */
101 &CVmObjString::getp_findLast, /* 26 */
102 &CVmObjString::getp_findAll, /* 27 */
103 &CVmObjString::getp_match /* 28 */
104 };
105
106 /* static property indices */
107 const int PROPIDX_packBytes = 20;
108
109 /* ------------------------------------------------------------------------ */
110 /*
111 * Static creation methods
112 */
113
114
115 /* create dynamically using stack arguments */
116 vm_obj_id_t CVmObjString::create_from_stack(VMG_ const uchar **, uint)
117 {
118 /* dynamic string construction is not currently supported */
119 err_throw(VMERR_BAD_DYNAMIC_NEW);
120
121 /* the compiler doesn't know we won't make it here */
122 AFTER_ERR_THROW(return VM_INVALID_OBJ;)
123 }
124
125 /* create a string with no initial contents */
126 vm_obj_id_t CVmObjString::create(VMG_ int in_root_set)
127 {
128 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
129 new (vmg_ id) CVmObjString();
130 return id;
131 }
132
133 /* create with a given buffer size */
134 vm_obj_id_t CVmObjString::create(VMG_ int in_root_set, size_t byte_size)
135 {
136 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
137 new (vmg_ id) CVmObjString(vmg_ byte_size);
138 return id;
139 }
140
141 /* create from a constant UTF-8 string */
142 vm_obj_id_t CVmObjString::create(VMG_ int in_root_set,
143 const char *str, size_t bytelen)
144 {
145 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
146 new (vmg_ id) CVmObjString(vmg_ str, bytelen);
147 return id;
148 }
149
150 /* create from a wide-character string */
151 vm_obj_id_t CVmObjString::create(VMG_ int in_root_set,
152 const wchar_t *str, size_t charlen)
153 {
154 /* get the utf8 byte length of the string */
155 size_t i, bytelen;
156 const wchar_t *src;
157 for (src = str, i = 0, bytelen = 0 ; i < charlen ; ++src, ++i)
158 bytelen += utf8_ptr::s_wchar_size(*src);
159
160 /* allocate space */
161 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
162 new (vmg_ id) CVmObjString(vmg_ bytelen);
163 CVmObjString *s = (CVmObjString *)vm_objp(vmg_ id);
164
165 /* build the string */
166 utf8_ptr dst(s->cons_get_buf());
167 for (src = str, i = 0 ; i < charlen ; ++src, ++i)
168 dst.setch(*src);
169
170 /* return the new string object ID */
171 return id;
172 }
173
174 /* create from the given character set */
175 vm_obj_id_t CVmObjString::create(VMG_ int in_root_set,
176 const char *src, size_t srclen,
177 CCharmapToUni *cmap)
178 {
179 /* figure the size needed for the conversion */
180 size_t ulen = cmap->map_str(0, 0, src, srclen);
181
182 /* create a string of the mapped length */
183 vm_obj_id_t ret = create(vmg_ in_root_set, ulen);
184 CVmObjString *retstr = (CVmObjString *)vm_objp(vmg_ ret);
185
186 /* map into the string buffer */
187 cmap->map_str(retstr->cons_get_buf(), ulen, src, srclen);
188
189 /* return the new string */
190 return ret;
191 }
192
193 /* create from a byte stream, interpreting the bytes as Latin-1 characters */
194 vm_obj_id_t CVmObjString::create_latin1(VMG_ int in_root_set,
195 CVmDataSource *src)
196 {
197 /* scan the memory stream to determine the string byte length */
198 long len = copy_latin1_to_string(0, 0, src);
199
200 /* make sure the length is within the acceptable range */
201 if (len > 65535)
202 err_throw(VMERR_STR_TOO_LONG);
203
204 /* allocate the string object */
205 vm_obj_id_t id = create(vmg_ FALSE, len);
206 CVmObjString *str = (CVmObjString *)vm_objp(vmg_ id);
207
208 /* copy the stream to the string */
209 copy_latin1_to_string(str->cons_get_buf(), len, src);
210
211 /* return the new object ID */
212 return id;
213 }
214
215 /* ------------------------------------------------------------------------ */
216 /*
217 * Copy a byte stream to a string, treating each byte of the source stream
218 * as a Latin-1 character.
219 *
220 * If the output buffer is null or is too short, we'll just count up the
221 * length without storing anything. Returns the total number of bytes
222 * needed to store the full source byte array.
223 */
224 size_t CVmObjString::copy_latin1_to_string(char *str, size_t len,
225 CVmDataSource *src)
226 {
227 /* we haven't copied any bytes out yet */
228 size_t tot = 0;
229
230 /* seek to the start of the source */
231 src->seek(0, OSFSK_SET);
232
233 /* keep going until we reach EOF */
234 for (;;)
235 {
236 /* read the next chunk of bytes from the source */
237 char buf[1024];
238 int cur = src->readc(buf, sizeof(buf));
239
240 /* if there's nothing left, we're done */
241 if (cur == 0)
242 return tot;
243
244 /* scan the buffer */
245 for (char *p = buf ; cur != 0 ; ++p, --cur)
246 {
247 /*
248 * if this character is from 0 to 127, store one byte;
249 * otherwise store it as two bytes in UTF-8 format
250 */
251 unsigned char c = *(unsigned char *)p;
252 if (c <= 127)
253 {
254 /* 0..127 -> single byte UTF-8 character */
255 tot += 1;
256 if (str != 0 && tot <= len)
257 *str++ = c;
258 }
259 else
260 {
261 /* 128.255 -> two-byte UTF-8 character */
262 tot += 2;
263 if (str != 0 && tot <= len)
264 {
265 *str++ = (char)(0xC0 | ((c >> 6) & 0x1F));
266 *str++ = (char)(0x80 | (c & 0x3F));
267 }
268 }
269 }
270 }
271 }
272
273
274 /* ------------------------------------------------------------------------ */
275 /*
276 * Constructors
277 */
278
279 /*
280 * create a string object with a given buffer size
281 */
282 CVmObjString::CVmObjString(VMG_ size_t len)
283 {
284 /*
285 * the length is limited to an unsigned 16-bit value (NB: it really is
286 * 65535 on ALL PLATFORMS - this is a portable limit imposed by the
287 * portable storage format, not a local platform limit)
288 */
289 if (len > 65535)
290 {
291 ext_ = 0;
292 err_throw(VMERR_STR_TOO_LONG);
293 }
294
295 /*
296 * allocate space for the buffer plus the length prefix in the
297 * variable heap
298 */
299 ext_ = (char *)G_mem->get_var_heap()->alloc_mem(len + VMB_LEN, this);
300
301 /* set the length */
302 vmb_put_len(ext_, len);
303 }
304
305 /*
306 * create a string object from a given UTF8 string constant
307 */
308 CVmObjString::CVmObjString(VMG_ const char *str, size_t len)
309 {
310 /* check for the length limit */
311 if (len > 65535)
312 {
313 ext_ = 0;
314 err_throw(VMERR_STR_TOO_LONG);
315 }
316
317 /*
318 * allocate space for the string plus the length prefix in the
319 * variable heap
320 */
321 ext_ = (char *)G_mem->get_var_heap()->alloc_mem(len + VMB_LEN, this);
322
323 /*
324 * store the length prefix in portable format (so that we can easily
325 * write our contents to a saved state file)
326 */
327 vmb_put_len(ext_, len);
328
329 /* copy the string's bytes */
330 memcpy(ext_ + VMB_LEN, str, len);
331 }
332
333
334 /* ------------------------------------------------------------------------ */
335 /*
336 * Ensure space for construction
337 */
338 char *CVmObjString::cons_ensure_space(VMG_ char *ptr, size_t len,
339 size_t margin)
340 {
341 /* figure the offset of the pointer into the current buffer */
342 int ofs = ptr - (ext_ + VMB_LEN);
343
344 /* calculate the needed size: this is the offset plus the added length */
345 size_t need = ofs + len;
346
347 /* if we already have enough space, we're done */
348 if (vmb_get_len(ext_) >= need)
349 return ptr;
350
351 /* expand to the needed size plus the margin */
352 size_t newlen = need + margin;
353 ext_ = (char *)G_mem->get_var_heap()->realloc_mem(
354 newlen + VMB_LEN, ext_, this);
355
356 /* set the new buffer size */
357 vmb_put_len(ext_, newlen);
358
359 /* return the pointer to the new buffer at the original offset */
360 return ext_ + VMB_LEN + ofs;
361 }
362
363 /*
364 * Append a string during construction
365 */
366 char *CVmObjString::cons_append(VMG_ char *ptr,
367 const char *addstr, size_t addlen,
368 size_t margin)
369 {
370 /* ensure we have space for the added string */
371 ptr = cons_ensure_space(vmg_ ptr, addlen, margin);
372
373 /* add the new string onto the end of the buffer */
374 memcpy(ptr, addstr, addlen);
375
376 /* return a pointer to the end of the added data */
377 return ptr + addlen;
378 }
379
380 /*
381 * Append a character during construction
382 */
383 char *CVmObjString::cons_append(VMG_ char *ptr, wchar_t ch, size_t margin)
384 {
385 /* encode the character as utf8 */
386 char buf[3];
387 size_t len = utf8_ptr::s_putch(buf, ch);
388
389 /* append the utf8 string for the character */
390 return cons_append(vmg_ ptr, buf, len, margin);
391 }
392
393 /*
394 * Shrink the buffer to the actual final size
395 */
396 void CVmObjString::cons_shrink_buffer(VMG_ char *ptr)
397 {
398 /* figure the offset of the pointer into the current buffer */
399 size_t siz = (size_t)(ptr - (ext_ + VMB_LEN));
400
401 /*
402 * If the savings are substantial enough, reallocate. If the size is
403 * unchanged, or it's within a reasonable margin of the target size, do
404 * nothing. Reallocation isn't free (we have to find memory and make a
405 * copy of the current buffer), so it's more efficient to waste a
406 * little memory if the savings are substantial.
407 */
408 if (vmb_get_len(ext_) - siz >= 256)
409 {
410 /* reallocate at the new size */
411 ext_ = (char *)G_mem->get_var_heap()->realloc_mem(
412 siz + VMB_LEN, ext_, this);
413 }
414
415 /* write the final length */
416 vmb_put_len(ext_, siz);
417 }
418
419
420
421 /* ------------------------------------------------------------------------ */
422 /*
423 * receive notification of deletion
424 */
425 void CVmObjString::notify_delete(VMG_ int in_root_set)
426 {
427 /* free our extension */
428 if (ext_ != 0 && !in_root_set)
429 G_mem->get_var_heap()->free_mem(ext_);
430 }
431
432 /* ------------------------------------------------------------------------ */
433 /*
434 * call a static property
435 */
436 int CVmObjString::call_stat_prop(VMG_ vm_val_t *result,
437 const uchar **pc_ptr, uint *argc,
438 vm_prop_id_t prop)
439 {
440 /* get the function table index */
441 int idx = G_meta_table->prop_to_vector_idx(
442 metaclass_reg_->get_reg_idx(), prop);
443
444 /* check for static methods */
445 switch (idx)
446 {
447 case PROPIDX_packBytes:
448 return static_getp_packBytes(vmg_ result, argc);
449
450 default:
451 /* inherit the default handling */
452 return CVmObject::call_stat_prop(vmg_ result, pc_ptr, argc, prop);
453 }
454 }
455
456 /* ------------------------------------------------------------------------ */
457 /*
458 * Set a property. Strings have no settable properties, so simply
459 * signal an error indicating that the set-prop call is invalid.
460 */
461 void CVmObjString::set_prop(VMG_ CVmUndo *, vm_obj_id_t,
462 vm_prop_id_t, const vm_val_t *)
463 {
464 err_throw(VMERR_INVALID_SETPROP);
465 }
466
467 /* ------------------------------------------------------------------------ */
468 /*
469 * Save the object to a file
470 */
471 void CVmObjString::save_to_file(VMG_ CVmFile *fp)
472 {
473 /* get our length */
474 size_t len = vmb_get_len(ext_);
475
476 /* write the length prefix and the string */
477 fp->write_bytes(ext_, len + VMB_LEN);
478 }
479
480 /*
481 * Restore the object from a file
482 */
483 void CVmObjString::restore_from_file(VMG_ vm_obj_id_t,
484 CVmFile *fp, CVmObjFixup *)
485 {
486 /* read the length prefix */
487 size_t len = fp->read_uint2();
488
489 /* free any existing extension */
490 if (ext_ != 0)
491 {
492 G_mem->get_var_heap()->free_mem(ext_);
493 ext_ = 0;
494 }
495
496 /*
497 * allocate our extension - make room for the length prefix plus the
498 * bytes of the string
499 */
500 ext_ = (char *)G_mem->get_var_heap()->alloc_mem(len + VMB_LEN, this);
501
502 /* store our length prefix */
503 vmb_put_len(ext_, len);
504
505 /* read the string */
506 fp->read_bytes(ext_ + VMB_LEN, len);
507 }
508
509 /* ------------------------------------------------------------------------ */
510 /*
511 * Cast to integer. We parse the string as a numeric value, using the same
512 * rules as toInteger().
513 */
514 long CVmObjString::cast_to_int(VMG0_) const
515 {
516 /*
517 * parse the string as an integer in decimal format; this is an
518 * explicit int cast, so don't allow BigNumber promotions
519 */
520 vm_val_t val;
521 parse_num_val(vmg_ &val, ext_ + VMB_LEN, vmb_get_len(ext_), 10, TRUE);
522
523 /* return the integer value */
524 return val.val.intval;
525 }
526
527 /*
528 * Cast to number.
529 */
530 void CVmObjString::cast_to_num(VMG_ vm_val_t *val, vm_obj_id_t self) const
531 {
532 /*
533 * Parse the string as a number in decimal format. We're allowed to
534 * return whatever numeric type is needed to represent the value, so
535 * allow BigNumber promotions if necessary.
536 */
537 parse_num_val(vmg_ val, ext_ + VMB_LEN, vmb_get_len(ext_), 10, FALSE);
538 }
539
540 /*
541 * Parse a string as an integer value
542 */
543 void CVmObjString::parse_num_val(VMG_ vm_val_t *retval,
544 const char *str, size_t len,
545 int radix, int int_only)
546 {
547 utf8_ptr p;
548 size_t rem;
549
550 /* skip leading spaces */
551 for (p.set((char *)str), rem = len ;
552 rem != 0 && t3_is_whitespace(p.getch()) ; p.inc(&rem)) ;
553
554 /* presume it's positive */
555 int is_neg = FALSE;
556
557 /* check for a leading + or - */
558 if (rem != 0)
559 {
560 if (p.getch() == '-')
561 {
562 /* note the sign and skip the character */
563 is_neg = TRUE;
564 p.inc(&rem);
565 }
566 else if (p.getch() == '+')
567 {
568 /* skip the character */
569 p.inc(&rem);
570 }
571 }
572
573 /* skip any additional spaces after the sign */
574 for ( ; rem != 0 && t3_is_whitespace(p.getch()) ; p.inc(&rem)) ;
575
576 /* clear the accumulator */
577 unsigned long acc = 0;
578
579 /* scan the digits */
580 for ( ; rem != 0 ; p.inc(&rem))
581 {
582 /* get the next digit */
583 wchar_t ch = p.getch();
584
585 /*
586 * If we're allowed to promote to BigNumber, and the radix is
587 * decimal, check for '.' and 'E' (for exponent) notation. These
588 * could indicate a floating point value.
589 */
590 if (radix == 10 && !int_only && (ch == '.' || ch == 'e' || ch == 'E'))
591 {
592 /* presume we're going to promote to BigNumber */
593 int promote = TRUE;
594
595 /*
596 * If it's an exponent, parse further to make sure it looks
597 * like a valid exponent: we can have an optional + or - sign,
598 * then need at least one digit.
599 */
600 if (ch == 'e' || ch == 'E')
601 {
602 /* set up a second pointer */
603 utf8_ptr p2(p);
604 size_t rem2 = rem;
605
606 /* skip the 'e' */
607 p2.inc(&rem);
608
609 /* if there's a sign, skip it */
610 if (rem2 != 0 && (p2.getch() == '+' || p2.getch() == '-'))
611 p2.inc(&rem2);
612
613 /* we need a digit at this point, or it's not an exponent */
614 promote = (rem2 != 0 && is_digit(p2.getch()));
615 }
616
617 /* if we're promoting after all, go do the promotion */
618 if (promote)
619 {
620 /* re-parse it as a BigNumber value */
621 retval->set_obj(CVmObjBigNum::create_radix(
622 vmg_ FALSE, str, len, radix));
623
624 /* return this value */
625 return;
626 }
627 }
628
629 /* get the integer value of the digit, treating A-Z as digits 10-35 */
630 int dig;
631 if (ch >= '0' && ch <= '9')
632 dig = (int)(ch - '0');
633 else if (ch >= 'a' && ch <= 'z')
634 dig = (int)(ch - 'a' + 10);
635 else if (ch >= 'A' && ch <= 'Z')
636 dig = (int)(ch - 'A' + 10);
637 else
638 break;
639
640 /* if it's outside the radix limit, it's not a digit after all */
641 if (dig >= radix)
642 break;
643
644 /*
645 * Make sure we're not going to overflow. If the base is 2, 8, or
646 * 16, and there wasn't a "-" sign, allow the value to go up to the
647 * unsigned 32-bit limit, 0xffffffff. Otherwise, limit it to
648 * 32-bit signed, -0x8000000 to +0x7ffffff.
649 */
650 unsigned long limit =
651 (!is_neg && (radix == 2 || radix == 8 || radix == 16))
652 ? 0xffffffff
653 : is_neg ? 0x80000000 : 0x7fffffff;
654
655 /* shift the accumulator by the radix, checking for overflow */
656 if (acc > limit/radix)
657 goto overflow;
658 acc *= radix;
659
660 /* add the digit, checking for overflow */
661 if (acc > limit - dig)
662 goto overflow;
663 acc += dig;
664 }
665
666 /* apply the sign, if appropriate, and set the return value */
667 retval->set_int(is_neg && acc <= 0x7FFFFFFF ? -(long)acc : (long)acc);
668 return;
669
670 overflow:
671 /*
672 * We overflowed the plain integer type. If we're allowed to promote
673 * to a BigNumber, re-parse the value as a BigNumber. If not, it's an
674 * error.
675 */
676 if (int_only)
677 {
678 /* we can't promote to BigNumber - throw an overflow error */
679 err_throw(VMERR_NUM_OVERFLOW);
680 }
681 else
682 {
683 /* re-parse it as a BigNumber value */
684 retval->set_obj(CVmObjBigNum::create_radix(
685 vmg_ FALSE, str, len, radix));
686 }
687 }
688
689 /* ------------------------------------------------------------------------ */
690 /*
691 * Add a value to this string
692 */
693 int CVmObjString::add_val(VMG_ vm_val_t *result,
694 vm_obj_id_t self, const vm_val_t *val)
695 {
696 /* set up a 'self' value holder */
697 vm_val_t selfval;
698 selfval.set_obj(self);
699
700 /*
701 * Use the generic string adder, using my extension as the constant
702 * string. We store our extension in the general string format
703 * required by the static adder.
704 */
705 add_to_str(vmg_ result, &selfval, val);
706
707 /* handled */
708 return TRUE;
709 }
710
711 /*
712 * Static string adder. This creates a new string object that results
713 * from appending the given value to the given string constant. This is
714 * defined statically so that this same code can be shared for adding to
715 * constant pool strings and adding to CVmObjString objects.
716 *
717 * 'strval' must point to a constant string. The first two bytes of the
718 * string are stored in portable UINT2 format and give the length in
719 * bytes of the string, not including the length prefix; immediately
720 * following the length prefix are the bytes of the string.
721 *
722 * Note that we *always* create a new object to hold the result, even if
723 * the new string is identical to the first, so that we consistently
724 * return a distinct reference from the original.
725 */
726 void CVmObjString::add_to_str(VMG_ vm_val_t *result,
727 const vm_val_t *self, const vm_val_t *val)
728 {
729 const char *strval1, *strval2;
730 char buf[128];
731 vm_obj_id_t obj;
732 size_t len1, len2;
733 CVmObjString *objptr;
734 vm_val_t new_obj2;
735
736 /*
737 * Get the string buffer pointers. The left value is already a string,
738 * or we wouldn't be here. The right value can be anything, though, so
739 * we need to apply an implicit string conversion if it's another type.
740 */
741 strval1 = self->get_as_string(vmg0_);
742 strval2 = cvt_to_str(vmg_ &new_obj2, buf, sizeof(buf), val, 10, 0);
743
744 /* get the lengths of the two strings */
745 len1 = vmb_get_len(strval1);
746 len2 = vmb_get_len(strval2);
747
748 /*
749 * If the right-hand value is zero length, or it's nil, simply return
750 * the left-hand value. If the left-hand value is zero length AND the
751 * right-hand value is already a string (constant or object), return
752 * the right-hand value unchanged. Otherwise, we actually need to
753 * build a whole new string with the concatenated texts.
754 */
755 if (len2 == 0 || val->typ == VM_NIL)
756 {
757 /* we're appending nothing to the string; just return 'self' */
758 *result = *self;
759 }
760 else if (len1 == 0 && val->get_as_string(vmg0_) != 0)
761 {
762 /*
763 * we're appending the right value to an empty string, AND the
764 * right value is already a string itself, so we can simply return
765 * the right value unchanged
766 */
767 *result = *val;
768 }
769 else
770 {
771 /*
772 * push the new string (if any) and self, to protect the two
773 * strings from garbage collection
774 */
775 G_stk->push(self);
776 G_stk->push(&new_obj2);
777
778 /* create a new string object to hold the result */
779 obj = create(vmg_ FALSE, len1 + len2);
780 objptr = (CVmObjString *)vm_objp(vmg_ obj);
781
782 /* copy the two strings into the new object's string buffer */
783 objptr->copy_into_str(0, strval1 + VMB_LEN, len1);
784 objptr->copy_into_str(len1, strval2 + VMB_LEN, len2);
785
786 /* we're done with the garbage collection protection */
787 G_stk->discard(2);
788
789 /* return the new object in the result */
790 result->set_obj(obj);
791 }
792 }
793
794
795 /* ------------------------------------------------------------------------ */
796 /*
797 * Allocate a string buffer large enough to hold a given value. We'll
798 * use the provided buffer if possible.
799 *
800 * If the provided buffer is null or is not large enough, we'll allocate
801 * a new string object with a large enough buffer to hold the value, and
802 * return the object's extension as the buffer. This object will never
803 * be referenced by anyone, so it will be deleted at the next garbage
804 * collection.
805 *
806 * The buffer size and requested size are in bytes.
807 */
808 char *CVmObjString::alloc_str_buf(VMG_ vm_val_t *new_obj,
809 char *buf, size_t buf_size,
810 size_t required_size)
811 {
812 /* if the provided buffer is large enough, use it */
813 if (buf != 0 && buf_size >= required_size)
814 {
815 /* there's no new object */
816 new_obj->set_nil();
817
818 /* return the buffer */
819 return buf;
820 }
821
822 /* allocate a new string object */
823 new_obj->set_obj(CVmObjString::create(vmg_ FALSE, required_size));
824
825 /* return the new object's full string buffer from the length prefix */
826 return ((CVmObjString *)vm_objp(vmg_ new_obj->val.obj))->ext_;
827 }
828
829
830 /* ------------------------------------------------------------------------ */
831 /*
832 * Try converting a value to a string via reflection services, imported
833 * from the bytecode program. Failing that, use a boilerplate format.
834 */
835 const char *CVmObjString::reflect_to_str(
836 VMG_ vm_val_t *new_str, char *result_buf, size_t result_buf_size,
837 const vm_val_t *val, const char *fmt, ...)
838 {
839 /* look for an exported reflectionServices object from the byteocde */
840 vm_val_t refl;
841 refl.set_obj(G_predef->reflection_services);
842 vm_prop_id_t valToSym = G_predef->reflection_valToSymbol;
843 if (refl.val.obj != VM_INVALID_OBJ && valToSym != VM_INVALID_PROP)
844 {
845 /* invoke reflectionServices.valToSymbol(val) */
846 G_stk->push(val);
847 G_interpreter->get_prop(vmg_ 0, &refl, valToSym, &refl, 1, 0);
848
849 /* if we got a string, return it */
850 const char *str = G_interpreter->get_r0()->get_as_string(vmg0_);
851 if (str != 0)
852 {
853 /* set the return value */
854 *new_str = *G_interpreter->get_r0();
855
856 /* return the string buffer */
857 return str;
858 }
859 }
860
861 /*
862 * No reflection services - fall back on the boilerplate format. Start
863 * by calculating the amount of space we need for the formatted string,
864 * adding a byte for the trailing null.
865 */
866 va_list args;
867 va_start(args, fmt);
868 size_t need = t3vsprintf(0, 0, fmt, args) + 1;
869 va_end(args);
870
871 /* allocate space, including room for the length prefix */
872 result_buf = alloc_str_buf(
873 vmg_ new_str, result_buf, result_buf_size, need + VMB_LEN);
874
875 /* do the formatting */
876 va_start(args, fmt);
877 t3vsprintf(result_buf + VMB_LEN, need, fmt, args);
878 va_end(args);
879
880 /* set the length prefix */
881 vmb_put_len(result_buf, need);
882
883 /* return the buffer */
884 return result_buf;
885 }
886
887
888 /* ------------------------------------------------------------------------ */
889 /*
890 * Convert a value to a string
891 */
892 const char *CVmObjString::cvt_to_str(VMG_ vm_val_t *new_str,
893 char *result_buf,
894 size_t result_buf_size,
895 const vm_val_t *val,
896 int radix, int flags)
897 {
898 /* presume we won't need to create a new string object */
899 new_str->set_nil();
900
901 /* check the type of the value */
902 switch(val->typ)
903 {
904 case VM_SSTRING:
905 /* it's a string constant - no conversion is necessary */
906 return G_const_pool->get_ptr(val->val.ofs);
907
908 case VM_OBJ:
909 /* it's an object - ask it for its string representation */
910 return vm_objp(vmg_ val->val.obj)->explicit_to_string(
911 vmg_ val->val.obj, new_str, radix, flags);
912
913 case VM_INT:
914 /*
915 * It's a number - convert it to a string. Use the provided result
916 * buffer if possible, but make sure we have room for the number.
917 * The unicode values we're storing are in the ascii range, so we
918 * only need one byte per character. The longest buffer we'd need,
919 * then, is 33 bytes, for a conversion to a bit string (i.e., base
920 * 2: 32 1s or 0s, plus a sign). The conversion also needs two
921 * bytes for the length prefix; add a few extra bytes as insurance
922 * against future algorithm changes that might need more padding.
923 */
924 result_buf = alloc_str_buf(vmg_ new_str,
925 result_buf, result_buf_size, 40);
926
927 /* generate the string */
928 return cvt_int_to_str(result_buf, 40, val->val.intval, radix, flags);
929
930 case VM_NIL:
931 /* nil - use the literal string "nil" */
932 return "\003\000nil";
933
934 case VM_TRUE:
935 /* true - use the literal string "true" */
936 return "\004\000true";
937
938 case VM_LIST:
939 return CVmObjList::list_to_string(vmg_ new_str, val, radix, flags);
940
941 case VM_PROP:
942 return reflect_to_str(vmg_ new_str, result_buf, result_buf_size, val,
943 "property#%d", (int)val->val.prop);
944
945 case VM_FUNCPTR:
946 return reflect_to_str(vmg_ new_str, result_buf, result_buf_size, val,
947 "function#%lx", (long)val->val.ofs);
948
949 case VM_ENUM:
950 return reflect_to_str(vmg_ new_str, result_buf, result_buf_size, val,
951 "enum#%ld", (long)val->val.enumval);
952
953 case VM_BIFPTR:
954 return reflect_to_str(vmg_ new_str, result_buf, result_buf_size, val,
955 "builtin#%d.%d",
956 (int)val->val.bifptr.set_idx,
957 (int)val->val.bifptr.func_idx);
958
959 default:
960 /* other types cannot be added to a string */
961 err_throw(VMERR_NO_STR_CONV);
962
963 /* we never really get here, but the compiler doesn't know that */
964 AFTER_ERR_THROW(return 0;)
965 }
966 }
967
968 /* ------------------------------------------------------------------------ */
969 /*
970 * Convert an integer to a string, storing the result in the given buffer
971 * in portable string format (with length prefix). We accept any radix
972 * from 2 to 36 (36 can be represented with "digits" 0-9A-Z).
973 *
974 * If the value is signed, a leading dash is included if the number is
975 * negative. Otherwise we treat the original value as unsigned, which on
976 * most hardware means we'll show the two's complement value.
977 *
978 * For efficiency, we store the number at the end of the buffer (this makes
979 * it easy to generate the number, since we need to generate numerals in
980 * reverse order). We return a pointer to the result, which may not start
981 * at the beginning of the buffer.
982 */
983 char *CVmObjString::cvt_int_to_str(char *buf, size_t buflen,
984 int32_t inval, int radix, int flags)
985 {
986 int neg;
987 uint32_t val;
988 char *p;
989 size_t len;
990
991 /* start at the end of the buffer */
992 p = buf + buflen;
993
994 /*
995 * if it's negative, and we're converting to a signed representation,
996 * use a leading minus sign plus the absolute value; otherwise, treat
997 * the value as unsigned
998 */
999 if (inval >= 0 || (flags & TOSTR_UNSIGNED) != 0)
1000 {
1001 /*
1002 * the value is non-negative, either because the signed
1003 * interpretation is non-negative or because we're using an
1004 * unsigned interpretation (in which case there's no such thing as
1005 * negative)
1006 */
1007 neg = FALSE;
1008
1009 /* use the value as-is */
1010 val = (uint32_t)inval;
1011 }
1012 else
1013 {
1014 /* it's signed and negative - note that we need a minus sign */
1015 neg = TRUE;
1016
1017 /* use the positive value for the conversion */
1018 val = (uint32_t)(-inval);
1019 }
1020
1021 /* store numerals in reverse order */
1022 do
1023 {
1024 char c;
1025
1026 /* if we have no more room, throw an error */
1027 if (p == buf)
1028 err_throw(VMERR_CONV_BUF_OVF);
1029
1030 /* move on to the next available character in the buffer */
1031 --p;
1032
1033 /* figure the character representation of this numeral */
1034 c = (char)(val % radix);
1035 if (c < 10)
1036 c += '0';
1037 else
1038 c += 'A' - 10;
1039
1040 /* store the numeral at the current location */
1041 *p = c;
1042
1043 /* divide the remaining number by the radix */
1044 val /= radix;
1045 } while (val != 0);
1046
1047 /* store the leading minus sign if necessary */
1048 if (neg)
1049 {
1050 /* if we don't have room, throw an error */
1051 if (p == buf)
1052 err_throw(VMERR_CONV_BUF_OVF);
1053
1054 /* move to the next byte */
1055 --p;
1056
1057 /* store the minus sign */
1058 *p = '-';
1059 }
1060
1061 /* calculate the length */
1062 len = buflen - (p - buf);
1063
1064 /* make sure we have room for the length prefix */
1065 if (p < buf + 2)
1066 err_throw(VMERR_CONV_BUF_OVF);
1067
1068 /* store the length prefix */
1069 p -= 2;
1070 vmb_put_len(p, len);
1071
1072 /* return the pointer to the start of the number */
1073 return p;
1074 }
1075
1076 /* ------------------------------------------------------------------------ */
1077 /*
1078 * Check a value for equality
1079 */
1080 int CVmObjString::equals(VMG_ vm_obj_id_t self,
1081 const vm_val_t *val, int /*depth*/) const
1082 {
1083 /* if the other value is a reference to myself, we certainly match */
1084 if (val->typ == VM_OBJ && val->val.obj == self)
1085 return TRUE;
1086
1087 /*
1088 * use the constant string comparison routine, using our underlying
1089 * string as the constant string data
1090 */
1091 return const_equals(vmg_ ext_, val);
1092 }
1093
1094 /*
1095 * Constant string equality test
1096 */
1097 int CVmObjString::const_equals(VMG_ const char *str, const vm_val_t *val)
1098 {
1099 const char *str2;
1100 size_t len;
1101
1102 /* if the other value is a string buffer, compare to its contents */
1103 if (val->typ == VM_OBJ
1104 && CVmObjStringBuffer::is_string_buffer_obj(vmg_ val->val.obj))
1105 return ((CVmObjStringBuffer *)vm_objp(vmg_ val->val.obj))
1106 ->equals_str(str);
1107
1108 /* get the other value as a string */
1109 str2 = val->get_as_string(vmg0_);
1110
1111 /* if the object doesn't have an underlying string, we don't match */
1112 if (str2 == 0)
1113 return FALSE;
1114
1115 /*
1116 * if their lengths match, and the bytes match exactly, we have a
1117 * match; otherwise, they're not equal
1118 */
1119 len = vmb_get_len(str);
1120 return (len == vmb_get_len(str2)
1121 && memcmp(str + VMB_LEN, str2 + VMB_LEN, len) == 0);
1122 }
1123
1124 /* ------------------------------------------------------------------------ */
1125 /*
1126 * Hash value
1127 */
1128 uint CVmObjString::calc_hash(VMG_ vm_obj_id_t self, int /*depth*/) const
1129 {
1130 return const_calc_hash(ext_);
1131 }
1132
1133 /*
1134 * Hash value calculation
1135 */
1136 uint CVmObjString::const_calc_hash(const char *str)
1137 {
1138 size_t len;
1139 uint hash;
1140 utf8_ptr p;
1141
1142 /* get and skip the length prefix */
1143 len = vmb_get_len(str);
1144 str += VMB_LEN;
1145
1146 /* scan the string and calculate the hash */
1147 for (p.set((char *)str), hash = 0 ; len != 0 ; p.inc(&len))
1148 hash += p.getch();
1149
1150 /* return the result */
1151 return hash;
1152 }
1153
1154
1155 /* ------------------------------------------------------------------------ */
1156 /*
1157 * Compare this string to another value
1158 */
1159 int CVmObjString::compare_to(VMG_ vm_obj_id_t /*self*/,
1160 const vm_val_t *val) const
1161 {
1162 /* use the static string magnitude comparison routine */
1163 return const_compare(vmg_ ext_, val);
1164 }
1165
1166 /*
1167 * Compare a constant string value to another value. Returns a positive
1168 * number if the constant string is lexically greater than the other
1169 * value, a negative number if the constant string is lexically less
1170 * than the other value, or zero if the constant string is lexically
1171 * identical to the other value.
1172 *
1173 * The other value must be a string constant or an object with an
1174 * underlying string value. We'll throw an error for any other type of
1175 * value.
1176 */
1177 int CVmObjString::const_compare(VMG_ const char *str1, const vm_val_t *val)
1178 {
1179 const char *str2;
1180 size_t len1, len2;
1181
1182 /* if the other value is a string buffer, compare to its contents */
1183 if (val->typ == VM_OBJ
1184 && CVmObjStringBuffer::is_string_buffer_obj(vmg_ val->val.obj))
1185 {
1186 /*
1187 * ask the string buffer to do the comparison, but reverse the
1188 * sense of the comparison, since from its perspective the
1189 * comparison is in the opposite order
1190 */
1191 return -((CVmObjStringBuffer *)vm_objp(vmg_ val->val.obj))
1192 ->compare_str(str1);
1193 }
1194
1195 /* get the other value as a string */
1196 str2 = val->get_as_string(vmg0_);
1197
1198 /* if it's not a string, we can't compare it */
1199 if (str2 == 0)
1200 err_throw(VMERR_INVALID_COMPARISON);
1201
1202 /* get the lengths of the two strings */
1203 len1 = vmb_get_len(str1);
1204 len2 = vmb_get_len(str2);
1205
1206 /* perform a lexical comparison and return the result */
1207 return utf8_ptr::s_compare_to(str1 + VMB_LEN, len1, str2 + VMB_LEN, len2);
1208 }
1209
1210 /* ------------------------------------------------------------------------ */
1211 /*
1212 * Find a substring within a string
1213 */
1214 const char *CVmObjString::find_substr(VMG_ const char *str, int32_t start_idx,
1215 const char *substr, size_t *idxp)
1216 {
1217 /* get the lengths */
1218 size_t rem = vmb_get_len(str);
1219 size_t sublen = vmb_get_len(substr);
1220
1221 /* set up utf8 pointer into the string */
1222 utf8_ptr p((char *)str + 2);
1223
1224 /* if the index is negative, it's from the end of the string */
1225 start_idx += (start_idx < 0 ? (int)p.len(rem) : -1);
1226
1227 /* skip to the starting index */
1228 for (int32_t i = start_idx ; i > 0 && rem >= sublen ; --i, p.inc(&rem)) ;
1229
1230 /* scan for the substring */
1231 for (size_t char_ofs = 0 ; rem != 0 && rem >= sublen ;
1232 ++char_ofs, p.inc(&rem))
1233 {
1234 /* check for a match */
1235 if (memcmp(p.getptr(), substr + VMB_LEN, sublen) == 0)
1236 {
1237 /* it's a match - set the return index if they are interested */
1238 if (idxp != 0)
1239 *idxp = char_ofs + start_idx;
1240
1241 /* return the current pointer */
1242 return p.getptr();
1243 }
1244 }
1245
1246 /* we didn't find it - so indicate by returning null */
1247 return 0;
1248 }
1249
1250 /*
1251 * Find a substring or pattern. 'basestr' is the entire string, and 'str'
1252 * is a pointer into the string giving the starting position for the
1253 * search; this can be the same as 'baseptr' to search from the very
1254 * beginning of the string, or to a character in the middle of the string.
1255 *
1256 * The returned 'match_idx' value is the character index relative to the
1257 * starting search position 'str'. If the match starts at the beginning of
1258 * 'str' then 'match_idx' is returned as 0. Note that this is relative to
1259 * the starting point 'str' rather than the overall string 'basestr'.
1260 */
1261 const char *CVmObjString::find_substr(
1262 VMG_ const vm_val_t *strval,
1263 const char *basestr, const char *str, size_t len,
1264 const char *substr, CVmObjPattern *pat, int *match_idx, int *match_len)
1265 {
1266 /* search for the string or pattern */
1267 if (substr != 0)
1268 {
1269 /* get the substring length and buffer pointer */
1270 size_t sublen = vmb_get_len(substr);
1271 substr += VMB_LEN;
1272
1273 /* search for the substring */
1274 utf8_ptr p((char *)str);
1275 for (int i = 0 ; len >= sublen ; p.inc(&len), ++i)
1276 {
1277 /* check for a match */
1278 if (memcmp(p.getptr(), substr, sublen) == 0)
1279 {
1280 /* got it - the match length is simply the substring length */
1281 *match_idx = i;
1282 *match_len = sublen;
1283 return p.getptr();
1284 }
1285 }
1286 }
1287 else if (pat != 0)
1288 {
1289 /* get the compiled pattern */
1290 re_compiled_pattern *cpat = pat->get_pattern(vmg0_);
1291
1292 /* save the last search source string */
1293 G_bif_tads_globals->last_rex_str->val = *strval;
1294 G_bif_tads_globals->rex_searcher->clear_group_regs();
1295
1296 /* search for the pattern */
1297 int idx = G_bif_tads_globals->rex_searcher->search_for_pattern(
1298 cpat, basestr, str, len, match_len);
1299
1300 /* if we found the match, return it */
1301 if (idx >= 0)
1302 {
1303 /* set the match index and length */
1304 *match_idx = utf8_ptr::s_len(str, idx);
1305 return str + idx;
1306 }
1307 }
1308
1309 /* no match */
1310 *match_idx = -1;
1311 *match_len = 0;
1312 return 0;
1313 }
1314
1315 /*
1316 * Find a substring, searching from the end of the string toward the
1317 * beginning. This works like find_substr(), but searchs backwards. The
1318 * match must end before the starting position 'str' - it can't overlap
1319 * this character. To search the entire string from the end, set 'str' to
1320 * the byte just after the last character of the string.
1321 *
1322 * As with find_substr(), we return with 'match_idx' set to the character
1323 * index of the start of the match relative to 'str'. This means that
1324 * 'match_idx' will be zero or negative on a successful match. (And the
1325 * only way it returns with zero is when the matched text is zero length,
1326 * because of the requirement that the match can't overlap the starting
1327 * character.)
1328 */
1329 const char *CVmObjString::find_last_substr(
1330 VMG_ const vm_val_t *strval,
1331 const char *basestr, const char *str, size_t len,
1332 const char *substr, CVmObjPattern *pat, int *match_idx, int *match_len)
1333 {
1334 /* search for the string or pattern */
1335 if (substr != 0)
1336 {
1337 /* get the substring length and buffer pointer */
1338 size_t sublen = vmb_get_len(substr);
1339 substr += VMB_LEN;
1340
1341 /* get the character length of the search string */
1342 size_t subclen = utf8_ptr::s_len(substr, sublen);
1343
1344 /* set up at the starting position */
1345 utf8_ptr p((char *)str);
1346
1347 /*
1348 * back up by the number of characters 'c' in the search string -
1349 * the match can't include the from_idx position, so we can't match
1350 * anything later in the string than 'c' characters before from_idx
1351 */
1352 size_t c;
1353 for (c = subclen ; c != 0 && p.getptr() != basestr ; --c, p.dec()) ;
1354
1355 /* if we couldn't back up far enough, there's no chance of a match */
1356 if (c > 0)
1357
1358 {
1359 *match_idx = -1;
1360 *match_len = 0;
1361 return 0;
1362 }
1363
1364 /* search backwards for the string */
1365 for (int i = -(int)subclen ; ; p.dec(), --i)
1366 {
1367 /* check for a match at the current position */
1368 if (memcmp(p.getptr(), substr, sublen) == 0)
1369 {
1370 /*
1371 * got it - the match index is the negative of the
1372 * character offset from the match position to the search
1373 * starting position, and the match length is simply
1374 * substring byte length
1375 */
1376 *match_idx = -(int)utf8_ptr::s_len(
1377 p.getptr(), str - p.getptr());
1378 *match_len = sublen;
1379 return p.getptr();
1380 }
1381
1382 /* if we're at the start of the base string, we're done */
1383 if (p.getptr() == basestr)
1384 break;
1385 }
1386 }
1387 else if (pat != 0)
1388 {
1389 /* get the compiled pattern */
1390 re_compiled_pattern *cpat = pat->get_pattern(vmg0_);
1391
1392 /* save the last search source string */
1393 G_bif_tads_globals->last_rex_str->val = *strval;
1394 G_bif_tads_globals->rex_searcher->clear_group_regs();
1395
1396 /* search for the pattern */
1397 int idx = G_bif_tads_globals->rex_searcher->search_back_for_pattern(
1398 cpat, basestr, str, len, match_len);
1399
1400 /* if we found the match, return it */
1401 if (idx >= 0)
1402 {
1403 /* set the match index and length */
1404 *match_idx = -(int)utf8_ptr::s_len(str - idx, idx);
1405 return str + idx;
1406 }
1407 }
1408
1409 /* no match */
1410 *match_idx = -1;
1411 *match_len = 0;
1412 return 0;
1413 }
1414
1415
1416 /* ------------------------------------------------------------------------ */
1417 /*
1418 * Evaluate a property
1419 */
1420 int CVmObjString::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
1421 vm_obj_id_t self, vm_obj_id_t *source_obj,
1422 uint *argc)
1423 {
1424 vm_val_t self_val;
1425
1426 /* use the constant evaluator */
1427 self_val.set_obj(self);
1428 if (const_get_prop(vmg_ retval, &self_val, ext_, prop, source_obj, argc))
1429 {
1430 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
1431 return TRUE;
1432 }
1433
1434 /* inherit default handling from the base object class */
1435 return CVmObject::get_prop(vmg_ prop, retval, self, source_obj, argc);
1436 }
1437
1438 /* ------------------------------------------------------------------------ */
1439 /*
1440 * Evaluate a property of a constant string value
1441 */
1442 int CVmObjString::const_get_prop(VMG_ vm_val_t *retval,
1443 const vm_val_t *self_val, const char *str,
1444 vm_prop_id_t prop, vm_obj_id_t *src_obj,
1445 uint *argc)
1446 {
1447 /* presume no source object */
1448 *src_obj = VM_INVALID_OBJ;
1449
1450 /* translate the property index to an index into our function table */
1451 uint func_idx = G_meta_table
1452 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
1453
1454 /* call the appropriate function */
1455 if ((*func_table_[func_idx])(vmg_ retval, self_val, str, argc))
1456 return TRUE;
1457
1458 /*
1459 * If this is a constant string (which is indicated by an invalid
1460 * 'self' object ID), try inheriting the default object
1461 * interpretation, passing the constant string placeholder object
1462 * for its type information.
1463 */
1464 if (self_val->typ != VM_OBJ)
1465 {
1466 /* try going to CVmObject directly */
1467 if (vm_objp(vmg_ G_predef->const_str_obj)
1468 ->CVmObject::get_prop(vmg_ prop, retval, G_predef->const_str_obj,
1469 src_obj, argc))
1470 return TRUE;
1471 }
1472
1473 /* not handled */
1474 return FALSE;
1475 }
1476
1477 /* ------------------------------------------------------------------------ */
1478 /*
1479 * property evaluator - get the length
1480 */
1481 int CVmObjString::getp_len(VMG_ vm_val_t *retval, const vm_val_t *self_val,
1482 const char *str, uint *argc)
1483 {
1484 /* check arguments */
1485 static CVmNativeCodeDesc desc(0);
1486 if (get_prop_check_argc(retval, argc, &desc))
1487 return TRUE;
1488
1489 /* set up a utf-8 pointer to the string's contents */
1490 utf8_ptr p;
1491 p.set((char *)str + VMB_LEN);
1492
1493 /* return the character length of the string */
1494 retval->set_int(p.len(vmb_get_len(str)));
1495
1496 /* handled */
1497 return TRUE;
1498 }
1499
1500 /* ------------------------------------------------------------------------ */
1501 /*
1502 * property evaluator - extract a substring
1503 */
1504 int CVmObjString::getp_substr(VMG_ vm_val_t *retval, const vm_val_t *self_val,
1505 const char *str, uint *in_argc)
1506 {
1507 long start;
1508 long len = 0;
1509 size_t rem;
1510 utf8_ptr p;
1511 utf8_ptr start_p;
1512 size_t start_rem;
1513 size_t new_len;
1514 vm_obj_id_t obj;
1515
1516 /* check arguments */
1517 uint argc = (in_argc == 0 ? 0 : *in_argc);
1518 static CVmNativeCodeDesc desc(1, 1);
1519 if (get_prop_check_argc(retval, in_argc, &desc))
1520 return TRUE;
1521
1522 /* pop the starting index */
1523 start = CVmBif::pop_long_val(vmg0_);
1524
1525 /* pop the length, if present */
1526 if (argc >= 2)
1527 len = CVmBif::pop_long_val(vmg0_);
1528
1529 /* push a self-reference to protect against GC */
1530 G_stk->push(self_val);
1531
1532 /* set up a utf8 pointer to traverse the string */
1533 p.set((char *)str + VMB_LEN);
1534
1535 /* get the byte length of the string */
1536 rem = vmb_get_len(str);
1537
1538 /*
1539 * Skip ahead to the starting index. If the index is positive, it's
1540 * an index from the start of the string; if it's negative, it's an
1541 * offset from the end of the string.
1542 */
1543 if (start > 0)
1544 {
1545 /*
1546 * it's an index from the start - skip ahead by start-1 characters
1547 * (since a start value of 1 tells us to start at the first
1548 * character)
1549 */
1550 for ( ; start > 1 && rem != 0 ; --start)
1551 p.inc(&rem);
1552 }
1553 else if (start < 0)
1554 {
1555 /*
1556 * It's an index from the end of the string: -1 tells us to start
1557 * at the last character, -2 at the second to last, and so on.
1558 * Move to the first byte past the end of the string, and work
1559 * backwards by the given number of characters.
1560 */
1561 for (p.set((char *)str + VMB_LEN + rem), rem = 0 ;
1562 start < 0 && p.getptr() != (char *)str + VMB_LEN ; ++start)
1563 {
1564 /* move back one character */
1565 p.dec(&rem);
1566 }
1567 }
1568
1569 /* this is the starting position */
1570 start_p = p;
1571 start_rem = rem;
1572
1573 /*
1574 * if a length was specified, calculate the number of bytes in the
1575 * given length; otherwise, use the entire remainder of the string
1576 */
1577 if (argc >= 2)
1578 {
1579 /* figure the positive or negative length */
1580 if (len >= 0)
1581 {
1582 /*
1583 * Positive length - this specifies the number of characters to
1584 * keep starting at the starting index. Skip ahead by the
1585 * desired length to figure the end pointer.
1586 */
1587 for ( ; len > 0 && rem != 0 ; --len)
1588 p.inc(&rem);
1589 }
1590 else
1591 {
1592 /*
1593 * Negative length - this specifies the number of characters to
1594 * remove from the end of the string. Move to the end of the
1595 * string, then skip back by |len| characters to find the end
1596 * pointer.
1597 */
1598 for (p.set(p.getptr() + rem), rem = 0 ;
1599 len < 0 && rem < start_rem ; ++len)
1600 p.dec(&rem);
1601 }
1602
1603 /* use the difference in lengths from the starting point to here */
1604 new_len = start_rem - rem;
1605 }
1606 else
1607 {
1608 /* use the entire remainder of the string */
1609 new_len = start_rem;
1610 }
1611
1612 /* create the new string */
1613 obj = CVmObjString::create(vmg_ FALSE, start_p.getptr(), new_len);
1614
1615 /* return the new object */
1616 retval->set_obj(obj);
1617
1618 /* discard the GC protection references */
1619 G_stk->discard();
1620
1621 /* handled */
1622 return TRUE;
1623 }
1624
1625 /* ------------------------------------------------------------------------ */
1626 /*
1627 * property evaluator - toUpper
1628 */
1629 int CVmObjString::getp_upper(VMG_ vm_val_t *retval, const vm_val_t *self_val,
1630 const char *str, uint *argc)
1631 {
1632 return gen_getp_case_conv(vmg_ retval, self_val, str, argc, &t3_to_upper);
1633 }
1634
1635 /*
1636 * property evaluator - toLower
1637 */
1638 int CVmObjString::getp_lower(VMG_ vm_val_t *retval, const vm_val_t *self_val,
1639 const char *str, uint *argc)
1640 {
1641 return gen_getp_case_conv(vmg_ retval, self_val, str, argc, &t3_to_lower);
1642 }
1643
1644 /*
1645 * property evaluator - toTitleCase
1646 */
1647 int CVmObjString::getp_toTitleCase(
1648 VMG_ vm_val_t *retval, const vm_val_t *self_val,
1649 const char *str, uint *argc)
1650 {
1651 return gen_getp_case_conv(vmg_ retval, self_val, str, argc, &t3_to_title);
1652 }
1653
1654 /*
1655 * property evaluator - toFoldedCase
1656 */
1657 int CVmObjString::getp_toFoldedCase(
1658 VMG_ vm_val_t *retval, const vm_val_t *self_val,
1659 const char *str, uint *argc)
1660 {
1661 return gen_getp_case_conv(vmg_ retval, self_val, str, argc, &t3_to_fold);
1662 }
1663
1664 /*
1665 * General case converter for toUpper, toLower, toTitleCase, toFoldedCase
1666 */
1667 int CVmObjString::gen_getp_case_conv(
1668 VMG_ vm_val_t *retval, const vm_val_t *self_val,
1669 const char *str, uint *argc, const wchar_t *(*conv)(wchar_t))
1670 {
1671 /* check arguments */
1672 static CVmNativeCodeDesc desc(0);
1673 if (get_prop_check_argc(retval, argc, &desc))
1674 return TRUE;
1675
1676 /* get my length */
1677 size_t srclen = vmb_get_len(str);
1678
1679 /* leave the string on the stack as GC protection */
1680 G_stk->push(self_val);
1681
1682 /*
1683 * Scan the string to determine how long the result will be. The
1684 * result won't necessarily be the same length as the original: some
1685 * case conversions are 1:N characters, and even when they're 1:1, a
1686 * two-byte character in the original could turn into a three-byte
1687 * character in the result, and vice versa.
1688 */
1689 size_t dstlen;
1690 utf8_ptr srcp, dstp;
1691 size_t rem;
1692 for (dstlen = 0, srcp.set((char *)str + VMB_LEN), rem = srclen ;
1693 rem != 0 ; srcp.inc(&rem))
1694 {
1695 /* get the mapping for this character */
1696 wchar_t ch = srcp.getch();
1697 const wchar_t *u = conv(ch);
1698
1699 /* add up the byte length of the mapping */
1700 dstlen += (u != 0
1701 ? utf8_ptr::s_wstr_size(u)
1702 : utf8_ptr::s_wchar_size(ch));
1703 }
1704
1705 /* allocate the result string */
1706 vm_obj_id_t result_obj = CVmObjString::create(vmg_ FALSE, dstlen);
1707
1708 /* get a pointer to the result buffer */
1709 dstp.set(((CVmObjString *)vm_objp(vmg_ result_obj))->cons_get_buf());
1710
1711 /* write the string */
1712 for (srcp.set((char *)str + VMB_LEN), rem = srclen ;
1713 rem != 0 ; srcp.inc(&rem))
1714 {
1715 /* get the mapping for this character */
1716 wchar_t ch = srcp.getch();
1717 const wchar_t *u = conv(ch);
1718
1719 /* put the character(s) */
1720 if (u != 0)
1721 dstlen -= dstp.setwcharsz(u, dstlen);
1722 else
1723 dstp.setch(ch, &dstlen);
1724 }
1725
1726 /* return the value */
1727 retval->set_obj(result_obj);
1728
1729 /* discard GC protection */
1730 G_stk->discard();
1731
1732 /* handled */
1733 return TRUE;
1734 }
1735
1736 /* ------------------------------------------------------------------------ */
1737 /*
1738 * Common handler for find() and findLast() methods. 'dir' specifies the
1739 * search direction: 1 for forward (left to right), -1 for reverse (right
1740 * to left).
1741 */
1742 template<int dir> inline int CVmObjString::find_common(
1743 VMG_ vm_val_t *retval,
1744 const vm_val_t *self_val, const char *str,
1745 uint *argc)
1746 {
1747 /* check arguments */
1748 uint orig_argc = (argc != 0 ? *argc : 0);
1749 static CVmNativeCodeDesc desc(1, 1);
1750 if (get_prop_check_argc(retval, argc, &desc))
1751 return TRUE;
1752
1753 /* get the string length and buffer pointer */
1754 size_t len = vmb_get_len(str);
1755 str += VMB_LEN;
1756
1757 /* remember where the base string strings */
1758 const char *basestr = str;
1759
1760 /* retrieve the string or regex pattern to find */
1761 vm_val_t *val2 = G_stk->get(0);
1762 const char *str2 = val2->get_as_string(vmg0_);
1763 CVmObjPattern *pat2 = 0;
1764 if (str2 != 0)
1765 {
1766 /* we have a simple string to find */
1767 }
1768 else if (val2->typ == VM_OBJ
1769 && CVmObjPattern::is_pattern_obj(vmg_ val2->val.obj))
1770 {
1771 /* it's a pattern */
1772 pat2 = (CVmObjPattern *)vm_objp(vmg_ val2->val.obj);
1773 }
1774 else
1775 {
1776 /* we need a string or a pattern; other values are invalid */
1777 err_throw(VMERR_BAD_TYPE_BIF);
1778 }
1779
1780 /* if there's a starting index, skip that many characters */
1781 int32_t start_idx = 0;
1782 if (orig_argc >= 2 && G_stk->get(1)->typ != VM_NIL)
1783 {
1784 /* get the starting index value */
1785 start_idx = G_stk->get(1)->num_to_int(vmg0_);
1786
1787 /* set up a UTF-8 pointer for traversing the string */
1788 utf8_ptr strp((char *)str);
1789
1790 /*
1791 * A positive index value is a 1-based index from the start of the
1792 * string. A negative index is from the end of the string, with -1
1793 * pointing to the last character. For reverse searches, 0 is the
1794 * position past the last character. In any case, adjust to a
1795 * zero-based index.
1796 */
1797 start_idx += (start_idx == 0 && dir < 0 ? (int)strp.len(len) :
1798 start_idx < 0 ? (int)strp.len(len) :
1799 -1);
1800
1801 /* if there's a substring, we can limit the skip */
1802 size_t min_len = (dir > 0 && str2 != 0 ? vmb_get_len(str2) : 0);
1803
1804 /* skip that many characters */
1805 int32_t i;
1806 for (i = 0 ; i < start_idx && len > min_len ; ++i, strp.inc(&len)) ;
1807
1808 /*
1809 * if the start index was past the end of the string (or past the
1810 * point where the remaining subject string is too short for the
1811 * target string), we definitely can't match
1812 */
1813 if (i < start_idx)
1814 {
1815 retval->set_nil();
1816 goto done;
1817 }
1818
1819 /* start the search here */
1820 str = strp.getptr();
1821 }
1822 else if (dir < 0)
1823 {
1824 /*
1825 * we're searching backwards, and there's no starting index, so the
1826 * starting point is the end of the string
1827 */
1828 str = str + len;
1829 start_idx = utf8_ptr::s_len(basestr, len);
1830 len = 0;
1831 }
1832
1833 /* find the substring */
1834 int match_idx, match_len;
1835 if (dir > 0
1836 ? find_substr(vmg_ self_val, basestr, str, len, str2, pat2,
1837 &match_idx, &match_len) != 0
1838 : find_last_substr(vmg_ self_val, basestr, str, len, str2, pat2,
1839 &match_idx, &match_len) != 0)
1840 {
1841 /* found it - adjust to a 1-based value for return */
1842 retval->set_int(start_idx + match_idx + 1);
1843 }
1844 else
1845 {
1846 /* didn't find it - return nil */
1847 retval->set_nil();
1848 }
1849
1850 done:
1851 /* discard arguments */
1852 G_stk->discard(orig_argc);
1853
1854 /* handled */
1855 return TRUE;
1856 }
1857
1858 /*
1859 * property evaluator - find
1860 */
1861 int CVmObjString::getp_find(VMG_ vm_val_t *retval,
1862 const vm_val_t *self_val, const char *str,
1863 uint *argc)
1864 {
1865 return find_common<1>(vmg_ retval, self_val, str, argc);
1866 }
1867
1868 /*
1869 * property evaluator - findLast
1870 */
1871 int CVmObjString::getp_findLast(VMG_ vm_val_t *retval,
1872 const vm_val_t *self_val, const char *str,
1873 uint *argc)
1874 {
1875 return find_common<-1>(vmg_ retval, self_val, str, argc);
1876 }
1877
1878
1879 /* ------------------------------------------------------------------------ */
1880 /*
1881 * property evaluator - findAll
1882 */
1883 int CVmObjString::getp_findAll(VMG_ vm_val_t *retval,
1884 const vm_val_t *self_val, const char *str,
1885 uint *argc)
1886 {
1887 /* check arguments */
1888 uint orig_argc = (argc != 0 ? *argc : 0);
1889 static CVmNativeCodeDesc desc(1, 1);
1890 if (get_prop_check_argc(retval, argc, &desc))
1891 return TRUE;
1892
1893 /* get the string length and buffer pointer */
1894 size_t len = vmb_get_len(str);
1895 str += VMB_LEN;
1896
1897 /* remember the base string */
1898 const char *basestr = str;
1899
1900 /* retrieve the string or regex pattern to find */
1901 vm_val_t *targ = G_stk->get(0);
1902 const char *targstr = 0;
1903 CVmObjPattern *targpat = 0;
1904 if ((targstr = targ->get_as_string(vmg0_)) != 0)
1905 {
1906 /* we have a simple string to find */
1907 }
1908 else if ((targpat = vm_val_cast(CVmObjPattern, targ)) != 0)
1909 {
1910 /* it's a pattern */
1911 }
1912 else
1913 {
1914 /* we need a string or a pattern; other values are invalid */
1915 err_throw(VMERR_BAD_TYPE_BIF);
1916 }
1917
1918 /* retrieve the filter callback function, if present */
1919 vm_val_t *func = 0;
1920 int func_argc_min = 0, func_argc_max = 0;
1921 vm_rcdesc rc;
1922 if (orig_argc >= 2 && (func = G_stk->get(1))->typ != VM_NIL)
1923 {
1924 /* make sure it's a function */
1925 if (!func->is_func_ptr(vmg0_))
1926 err_throw(VMERR_BAD_TYPE_BIF);
1927
1928 /* note how many arguments the function accepts */
1929 CVmFuncPtr fd(vmg_ func);
1930 func_argc_min = fd.get_min_argc();
1931 func_argc_max = fd.is_varargs() ? -1 : fd.get_max_argc();
1932 }
1933
1934 /*
1935 * create a tentative list for the results (we'll resize this as needed
1936 * as we add elements)
1937 */
1938 retval->set_obj(CVmObjList::create(vmg_ FALSE, 10));
1939 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
1940
1941 /* clear it initially and push it for gc protection */
1942 lst->cons_clear();
1943 G_stk->push(retval);
1944
1945 /* repeatedly search for the pattern */
1946 int cnt;
1947 for (cnt = 0 ; len != 0 ; ++cnt)
1948 {
1949 /* search for the next element */
1950 int match_cofs, match_len, match_bofs;
1951 const char *nxt = find_substr(
1952 vmg_ self_val, basestr, str, len, targstr, targpat,
1953 &match_cofs, &match_len);
1954
1955 /* if we didn't find a match, we're done */
1956 if (nxt == 0)
1957 break;
1958
1959 /* figure the byte offset of the match */
1960 match_bofs = nxt - str;
1961
1962 /* call the callback, or just return the match text directly */
1963 vm_val_t ele;
1964 if (func == 0)
1965 {
1966 /* no callback - just use the match text, as a new string */
1967 ele.set_obj(CVmObjString::create(vmg_ FALSE, nxt, match_len));
1968 }
1969 else
1970 {
1971 /* we have a callback - push arguments */
1972 int fargc = 0;
1973
1974 /*
1975 * Figure out how many groups are populated, and how many the
1976 * function expects. If the function takes varargs, it expects
1977 * all of the groups. If it takes fixed arguments, it expects
1978 * at most max_argc-2. In addition, the function expects a
1979 * minimum of min_argc-2 groups, and expects us to add nil
1980 * arguments for any unpopulated groups to fill out that
1981 * minimum.
1982 */
1983 int gc_actual = G_bif_tads_globals->rex_searcher->get_group_cnt();
1984 int gc_wanted = (func_argc_max == -1
1985 ? gc_actual : func_argc_max - 2);
1986 if (gc_wanted < func_argc_min - 2)
1987 gc_wanted = func_argc_min - 2;
1988
1989 /* push the groups, last to first */
1990 for (int i = gc_wanted ; i > 0 ; )
1991 {
1992 /* get the group, if it exists */
1993 const re_group_register *reg = 0;
1994 if (--i < gc_actual)
1995 {
1996 /* valid group - get the group information */
1997 reg = G_bif_tads_globals->rex_searcher->get_group_reg(i);
1998 }
1999
2000 /* if the group is populated, push its text, otherwise nil */
2001 if (reg != 0 && reg->start_ofs >= 0 && reg->end_ofs >= 0)
2002 {
2003 /* push the group text as a new string */
2004 G_stk->push()->set_obj(CVmObjString::create(
2005 vmg_ FALSE, basestr + reg->start_ofs,
2006 reg->end_ofs - reg->start_ofs));
2007 }
2008 else
2009 {
2010 /* unpopulated group - push nil */
2011 G_stk->push()->set_nil();
2012 }
2013
2014 /* count it */
2015 ++fargc;
2016 }
2017
2018 /* if the index value is desired, push it */
2019 if (func_argc_max == -1 || func_argc_max >= 2)
2020 {
2021 /* push the index of the match relative to basestr */
2022 G_stk->push()->set_int(
2023 utf8_ptr::s_len(basestr, nxt - basestr) + 1);
2024 ++fargc;
2025 }
2026
2027 /* if the match string value is desired, push it */
2028 if (func_argc_max == -1 || func_argc_max >= 1)
2029 {
2030 /* push the match text */
2031 G_stk->push()->set_obj(
2032 CVmObjString::create(vmg_ FALSE, nxt, match_len));
2033 ++fargc;
2034 }
2035
2036 /* call the callback */
2037 G_interpreter->call_func_ptr(vmg_ func, fargc, &rc, 0);
2038
2039 /* retrieve the return value */
2040 ele = *G_interpreter->get_r0();
2041 }
2042
2043 /* add it to the list */
2044 lst->cons_ensure_space(vmg_ cnt, 0);
2045 lst->cons_set_element(cnt, &ele);
2046
2047 /* skip the matched text */
2048 size_t skip = match_bofs + match_len;
2049 str += skip;
2050 len -= skip;
2051
2052 /*
2053 * if we matched zero characters, skip one character to prevent an
2054 * infinite loop
2055 */
2056 if (match_len == 0 && len != 0)
2057 str += utf8_ptr::s_bytelen(str, 1);
2058 }
2059
2060 /* finalize the list length */
2061 lst->cons_set_len(cnt);
2062
2063 /* discard arguments and gc protection */
2064 G_stk->discard(orig_argc + 1);
2065
2066 /* handled */
2067 return TRUE;
2068 }
2069
2070 /* ------------------------------------------------------------------------ */
2071 /*
2072 * property evaluator - match
2073 */
2074 int CVmObjString::getp_match(VMG_ vm_val_t *retval,
2075 const vm_val_t *self_val, const char *str,
2076 uint *argc)
2077 {
2078 /* check arguments */
2079 uint orig_argc = (argc != 0 ? *argc : 0);
2080 static CVmNativeCodeDesc desc(1, 1);
2081 if (get_prop_check_argc(retval, argc, &desc))
2082 return TRUE;
2083
2084 /* get the string length and buffer pointer */
2085 size_t len = vmb_get_len(str);
2086 str += VMB_LEN;
2087
2088 /* remember the base string */
2089 const char *basestr = str;
2090
2091 /* retrieve the string or regex pattern to match */
2092 vm_val_t *targ = G_stk->get(0);
2093 const char *targstr = 0;
2094 CVmObjPattern *targpat = 0;
2095 size_t targstrlen = 0;
2096 if ((targstr = targ->get_as_string(vmg0_)) != 0)
2097 {
2098 /* it's a literal string - get its length and text pointer */
2099 targstrlen = vmb_get_len(targstr);
2100 targstr += VMB_LEN;
2101 }
2102 else if ((targpat = vm_val_cast(CVmObjPattern, targ)) != 0)
2103 {
2104 /* it's a pattern */
2105 }
2106 else
2107 {
2108 /* we need a string or a pattern; other values are invalid */
2109 err_throw(VMERR_BAD_TYPE_BIF);
2110 }
2111
2112 /* retrieve the starting index, if present */
2113 int32_t start_idx = 0;
2114 if (orig_argc >= 2 && G_stk->get(1)->typ != VM_NIL)
2115 {
2116 /* get the starting index value */
2117 start_idx = G_stk->get(1)->num_to_int(vmg0_);
2118
2119 /* set up a UTF-8 pointer for traversing the string */
2120 utf8_ptr strp((char *)str);
2121
2122 /*
2123 * A positive index value is a 1-based index from the start of the
2124 * string. A negative index is from the end of the string, with -1
2125 * pointing to the last character.
2126 */
2127 start_idx += (start_idx < 0 ? (int)strp.len(len) : -1);
2128
2129 /* skip that many characters */
2130 int32_t i;
2131 for (i = 0 ; i < start_idx && len > targstrlen ; ++i, strp.inc(&len)) ;
2132
2133 /*
2134 * if the start index was past the end of the string (or past the
2135 * point where the remaining subject string is too short for the
2136 * target string), we definitely can't match
2137 */
2138 if (i < start_idx)
2139 {
2140 retval->set_nil();
2141 goto done;
2142 }
2143
2144 /* start the search here */
2145 str = strp.getptr();
2146 }
2147
2148 /* match the string or pattern */
2149 if (targstr != 0)
2150 {
2151 /* make sure it's long enough, then match the text literally */
2152 if (len >= targstrlen && memcmp(targstr, str, targstrlen) == 0)
2153 {
2154 /* matched - return the match length */
2155 retval->set_int(targstrlen);
2156 }
2157 else
2158 {
2159 /* no match */
2160 retval->set_nil();
2161 }
2162 }
2163 else
2164 {
2165 /* RexPattern - get the compiled pattern */
2166 re_compiled_pattern *cpat = targpat->get_pattern(vmg0_);
2167
2168 /* save the last search source string */
2169 G_bif_tads_globals->last_rex_str->val = *self_val;
2170 G_bif_tads_globals->rex_searcher->clear_group_regs();
2171
2172 /* match the pattern */
2173 int matchlen = G_bif_tads_globals->rex_searcher->match_pattern(
2174 cpat, basestr, str, len);
2175
2176 /* if it matched (len >= 0), return the length, otherwise nil */
2177 if (matchlen >= 0)
2178 retval->set_int(matchlen);
2179 else
2180 retval->set_nil();
2181 }
2182
2183 done:
2184 /* discard arguments */
2185 G_stk->discard(orig_argc);
2186
2187 /* handled */
2188 return TRUE;
2189 }
2190
2191 /* ------------------------------------------------------------------------ */
2192 /*
2193 * findReplace() method - replace one or all occurrences of a given
2194 * substring or regular expression pattern within the subject string (self)
2195 * with a given replacement string. This uses the common find/replace
2196 * handler defined in vmfindrep.h.
2197 */
2198 int CVmObjString::getp_replace(VMG_ vm_val_t *retval,
2199 const vm_val_t *self_val,
2200 const char *str, uint *argc)
2201 {
2202 /* check arguments */
2203 uint orig_argc = (argc != 0 ? *argc : 0);
2204 static CVmNativeCodeDesc desc(2, 3);
2205 if (get_prop_check_argc(retval, argc, &desc))
2206 return TRUE;
2207
2208 /* do the search-and-replace */
2209 vm_find_replace<VMFINDREPLACE_StringFindReplace>(
2210 vmg_ retval, orig_argc, self_val, str);
2211
2212 /* discard arguments */
2213 G_stk->discard(orig_argc);
2214
2215 /* handled */
2216 return TRUE;
2217 }
2218
2219 /* ------------------------------------------------------------------------ */
2220 /*
2221 * property evaluator - convert to unicode
2222 */
2223 int CVmObjString::getp_to_uni(VMG_ vm_val_t *retval,
2224 const vm_val_t *self_val,
2225 const char *str, uint *in_argc)
2226 {
2227 size_t bytelen;
2228 long idx = 1;
2229 utf8_ptr p;
2230
2231 /* check arguments */
2232 uint argc = (in_argc != 0 ? *in_argc : 0);
2233 static CVmNativeCodeDesc desc(0, 1);
2234 if (get_prop_check_argc(retval, in_argc, &desc))
2235 return TRUE;
2236
2237 /* retrieve the index argument if present */
2238 if (argc >= 1)
2239 idx = CVmBif::pop_long_val(vmg0_);
2240
2241 /* push a self-reference as GC protection */
2242 G_stk->push(self_val);
2243
2244 /* get and skip the string's length prefix */
2245 bytelen = vmb_get_len(str);
2246 str += VMB_LEN;
2247
2248 /* set up a utf8 pointer to the string */
2249 p.set((char *)str);
2250
2251 /* if the index is negative, it's an index from the end of the string */
2252 if (idx < 0)
2253 idx += p.len(bytelen) + 1;
2254
2255 /* check for an index argument */
2256 if (argc >= 1)
2257 {
2258 /* skip through the string until we get to the desired index */
2259 for ( ; idx > 1 && bytelen != 0 ; --idx, p.inc(&bytelen)) ;
2260
2261 /* check to see if we have a character available */
2262 if (idx == 1 && bytelen != 0)
2263 {
2264 /* the index is valid - return the character here */
2265 retval->set_int((long)p.getch());
2266 }
2267 else
2268 {
2269 /*
2270 * the index is past the end of the string or is less than 1
2271 * - return nil to indicate that there's no character here
2272 */
2273 retval->set_nil();
2274 }
2275 }
2276 else
2277 {
2278 size_t charlen;
2279 vm_obj_id_t lst_obj;
2280 CVmObjList *lst;
2281 size_t i;
2282
2283 /*
2284 * There's no index argument - they want a list of all of the
2285 * code points in the string. First, get the number of
2286 * characters in the string.
2287 */
2288 charlen = p.len(bytelen);
2289
2290 /* create a list to hold the results */
2291 lst_obj = CVmObjList::create(vmg_ FALSE, charlen);
2292 lst = (CVmObjList *)vm_objp(vmg_ lst_obj);
2293
2294 /* set the list's elements to the unicode characters values */
2295 for (i = 0 ; i < charlen ; ++i, p.inc())
2296 {
2297 wchar_t ch;
2298 vm_val_t ele_val;
2299
2300 /* get this character */
2301 ch = p.getch();
2302
2303 /* set this list element */
2304 ele_val.set_int((long)ch);
2305 lst->cons_set_element(i, &ele_val);
2306 }
2307
2308 /* return the list object */
2309 retval->set_obj(lst_obj);
2310 }
2311
2312 /* discard the GC protection */
2313 G_stk->discard();
2314
2315 /* handled */
2316 return TRUE;
2317 }
2318
2319 /* ------------------------------------------------------------------------ */
2320 /*
2321 * property evaluator - htmlify
2322 */
2323
2324 /*
2325 * htmlify flags
2326 */
2327
2328 /* preserve spaces */
2329 #define VMSTR_HTMLIFY_KEEP_SPACES 0x0001
2330
2331 /* preserve newlines */
2332 #define VMSTR_HTMLIFY_KEEP_NEWLINES 0x0002
2333
2334 /* preserve tabs */
2335 #define VMSTR_HTMLIFY_KEEP_TABS 0x0004
2336
2337 /*
2338 * htmlify implementation
2339 */
2340 int CVmObjString::getp_htmlify(VMG_ vm_val_t *retval,
2341 const vm_val_t *self_val,
2342 const char *str, uint *in_argc)
2343 {
2344 size_t bytelen;
2345 utf8_ptr p;
2346 utf8_ptr dstp;
2347 size_t rem;
2348 size_t extra;
2349 long flags;
2350 vm_obj_id_t result_obj;
2351 int prv_was_sp;
2352
2353 /* check arguments */
2354 uint argc = (in_argc != 0 ? *in_argc : 0);
2355 static CVmNativeCodeDesc desc(0, 1);
2356 if (get_prop_check_argc(retval, in_argc, &desc))
2357 return TRUE;
2358
2359 /* if they specified flags, pop them */
2360 if (argc >= 1)
2361 {
2362 /* retrieve the flags */
2363 flags = CVmBif::pop_long_val(vmg0_);
2364 }
2365 else
2366 {
2367 /* no flags */
2368 flags = 0;
2369 }
2370
2371 /* push a self-reference as GC protection */
2372 G_stk->push(self_val);
2373
2374 /* get and skip the string's length prefix */
2375 bytelen = vmb_get_len(str);
2376 str += VMB_LEN;
2377
2378 /*
2379 * scan the string to determine how much space we'll have to add to
2380 * generate the htmlified version
2381 */
2382 for (prv_was_sp = FALSE, extra = 0, p.set((char *)str), rem = bytelen ;
2383 rem != 0 ; p.inc(&rem))
2384 {
2385 int this_is_sp;
2386
2387 /* presume it's not a space */
2388 this_is_sp = FALSE;
2389
2390 /* check what we have */
2391 switch(p.getch())
2392 {
2393 case '&':
2394 /* we must replace '&' with '&amp;' - this adds four bytes */
2395 extra += 4;
2396 break;
2397
2398 case '<':
2399 /* we must replace '<' with '&lt;' - this adds three bytes */
2400 extra += 3;
2401 break;
2402
2403 case '>':
2404 /* replace '>' with '&gt;' */
2405 extra += 3;
2406 break;
2407
2408 case ' ':
2409 /*
2410 * If we're in preserve-spaces mode, and the previous space
2411 * was some kind of whitespace character, change this to
2412 * '&nbsp;' - this adds five bytes
2413 */
2414 if (prv_was_sp && (flags & VMSTR_HTMLIFY_KEEP_SPACES) != 0)
2415 extra += 5;
2416
2417 /* note that this was a whitespace character */
2418 this_is_sp = TRUE;
2419 break;
2420
2421 case '\t':
2422 /* if we're in preserve-tabs mode, change this to '<tab>' */
2423 if ((flags & VMSTR_HTMLIFY_KEEP_TABS) != 0)
2424 extra += 4;
2425
2426 /* note that this was a whitespace character */
2427 this_is_sp = TRUE;
2428 break;
2429
2430 case '\n':
2431 case 0x2028:
2432 /* if we're in preserve-newlines mode, change this to '<br>' */
2433 if ((flags & VMSTR_HTMLIFY_KEEP_NEWLINES) != 0)
2434 extra += 3;
2435
2436 /* note that this was a whitespace character */
2437 this_is_sp = TRUE;
2438 break;
2439 }
2440
2441 /* for next time, remember whether this is a space */
2442 prv_was_sp = this_is_sp;
2443 }
2444
2445 /* allocate space for the new string */
2446 result_obj = create(vmg_ FALSE, bytelen + extra);
2447
2448 /* get a pointer to the result buffer */
2449 dstp.set(((CVmObjString *)vm_objp(vmg_ result_obj))->cons_get_buf());
2450
2451 /* translate the string and write the result */
2452 for (prv_was_sp = FALSE, p.set((char *)str), rem = bytelen ;
2453 rem != 0 ; p.inc(&rem))
2454 {
2455 wchar_t ch;
2456 int this_is_sp;
2457
2458 /* get this character */
2459 ch = p.getch();
2460
2461 /* presume it's not a space */
2462 this_is_sp = FALSE;
2463
2464 /* check what we have */
2465 switch(ch)
2466 {
2467 case '&':
2468 /* replace '&' with '&amp;' */
2469 dstp.setch_str("&amp;");
2470 break;
2471
2472 case '<':
2473 /* we must replace '<' with '&lt;' - this adds three bytes */
2474 dstp.setch_str("&lt;");
2475 break;
2476
2477 case '>':
2478 dstp.setch_str("&gt;");
2479 break;
2480
2481 case ' ':
2482 /* note that this was a whitespace character */
2483 this_is_sp = TRUE;
2484
2485 /*
2486 * ignore it if not in preserve-spaces mode, or if the
2487 * previous character wasn't whitespace of some kind
2488 */
2489 if (!prv_was_sp || (flags & VMSTR_HTMLIFY_KEEP_SPACES) == 0)
2490 goto do_default;
2491
2492 /* add the nbsp */
2493 dstp.setch_str("&nbsp;");
2494 break;
2495
2496 case '\t':
2497 /* note that this was a whitespace character */
2498 this_is_sp = TRUE;
2499
2500 /* ignore if not in preserve-tabs mode */
2501 if ((flags & VMSTR_HTMLIFY_KEEP_TABS) == 0)
2502 goto do_default;
2503
2504 /* add the <tab> */
2505 dstp.setch_str("<tab>");
2506 break;
2507
2508 case '\n':
2509 case 0x2028:
2510 /* note that this was a whitespace character */
2511 this_is_sp = TRUE;
2512
2513 /* if we're not in preserve-newlines mode, ignore it */
2514 if ((flags & VMSTR_HTMLIFY_KEEP_NEWLINES) == 0)
2515 goto do_default;
2516
2517 /* add the <br> */
2518 dstp.setch_str("<br>");
2519 break;
2520
2521 default:
2522 do_default:
2523 /* copy this character unchanged */
2524 dstp.setch(ch);
2525 break;
2526 }
2527
2528 /* for next time, remember whether this is a space */
2529 prv_was_sp = this_is_sp;
2530 }
2531
2532 /* return the new string */
2533 retval->set_obj(result_obj);
2534
2535 /* discard the GC protection */
2536 G_stk->discard();
2537
2538 /* handled */
2539 return TRUE;
2540 }
2541
2542 /* ------------------------------------------------------------------------ */
2543 /*
2544 * property evaluator - startsWith
2545 */
2546 int CVmObjString::getp_starts_with(VMG_ vm_val_t *retval,
2547 const vm_val_t *self_val,
2548 const char *str, uint *argc)
2549 {
2550 const char *str2;
2551 size_t len;
2552 size_t len2;
2553
2554 /* check arguments */
2555 static CVmNativeCodeDesc desc(1);
2556 if (get_prop_check_argc(retval, argc, &desc))
2557 return TRUE;
2558
2559 /* retrieve the other string */
2560 str2 = CVmBif::pop_str_val(vmg0_);
2561
2562 /* get the lengths of the two strings */
2563 len = vmb_get_len(str);
2564 len2 = vmb_get_len(str2);
2565
2566 /* move to the contents of each string */
2567 str += VMB_LEN;
2568 str2 += VMB_LEN;
2569
2570 /*
2571 * if the other string is no longer than our string, and the other
2572 * string matches our string exactly for the other string's entire
2573 * length, we start with the other string
2574 */
2575 retval->set_logical(len2 <= len && memcmp(str, str2, len2) == 0);
2576
2577 /* handled */
2578 return TRUE;
2579 }
2580
2581 /*
2582 * property evaluator - endsWith
2583 */
2584 int CVmObjString::getp_ends_with(VMG_ vm_val_t *retval,
2585 const vm_val_t *self_val,
2586 const char *str, uint *argc)
2587 {
2588 const char *str2;
2589 size_t len;
2590 size_t len2;
2591
2592 /* check arguments */
2593 static CVmNativeCodeDesc desc(1);
2594 if (get_prop_check_argc(retval, argc, &desc))
2595 return TRUE;
2596
2597 /* retrieve the other string */
2598 str2 = CVmBif::pop_str_val(vmg0_);
2599
2600 /* get the lengths of the two strings */
2601 len = vmb_get_len(str);
2602 len2 = vmb_get_len(str2);
2603
2604 /* move to the contents of each string */
2605 str += VMB_LEN;
2606 str2 += VMB_LEN;
2607
2608 /*
2609 * If the other string is no longer than our string, and the other
2610 * string matches our string at the end exactly for the other string's
2611 * entire length, we start with the other string. Note we don't need
2612 * to worry about finding a valid character index in our string for
2613 * the ending offset, because all we care about is whether or not we
2614 * have an exact byte match between our suffix and the other string.
2615 */
2616 retval->set_logical(len2 <= len
2617 && memcmp(str + len - len2, str2, len2) == 0);
2618
2619 /* handled */
2620 return TRUE;
2621 }
2622
2623 /* ------------------------------------------------------------------------ */
2624 /*
2625 * property evaluator - mapToByteArray
2626 */
2627 int CVmObjString::getp_to_byte_array(VMG_ vm_val_t *retval,
2628 const vm_val_t *self_val,
2629 const char *str, uint *oargc)
2630 {
2631 /* check arguments */
2632 int argc = (oargc != 0 ? *oargc : 0);
2633 static CVmNativeCodeDesc desc(0, 1);
2634 if (get_prop_check_argc(retval, oargc, &desc))
2635 return TRUE;
2636
2637 /* note the mapper argument */
2638 const vm_val_t *cmap = (argc >= 1 ? G_stk->get(0) : 0);
2639
2640 /* save the string for gc protection */
2641 G_stk->push(self_val);
2642
2643 /* create the byte array */
2644 retval->set_obj(CVmObjByteArray::create_from_string(
2645 vmg_ self_val, str, cmap));
2646
2647 /* discard arguments and gc protection */
2648 G_stk->discard(argc + 1);
2649
2650 /* handled */
2651 return TRUE;
2652 }
2653
2654 /* ------------------------------------------------------------------------ */
2655 /*
2656 * property evaluator - splice
2657 */
2658 int CVmObjString::getp_splice(VMG_ vm_val_t *retval,
2659 const vm_val_t *self_val,
2660 const char *str, uint *argc)
2661 {
2662 char ins_buf[128];
2663
2664 /* check arguments */
2665 uint oargc = (argc != 0 ? *argc : 0);
2666 static CVmNativeCodeDesc desc(2, 1);
2667 if (get_prop_check_argc(retval, argc, &desc))
2668 return TRUE;
2669
2670 /* retrieve the starting index and deletion length */
2671 int start_idx = CVmBif::pop_int_val(vmg0_);
2672 int del_len = CVmBif::pop_int_val(vmg0_);
2673
2674 /* get and skip our length */
2675 size_t len = vmb_get_len(str);
2676 str += VMB_LEN;
2677 utf8_ptr p((char *)str);
2678 int charlen = p.len(len);
2679
2680 /* adjust the index to 0-based, and figure end-of-string offsets */
2681 start_idx += (start_idx < 0 ? charlen : -1);
2682
2683 /* make sure the starting index and deletion length are in bounds */
2684 start_idx = (start_idx < 0 ? 0 :
2685 start_idx > (int)charlen ? charlen :
2686 start_idx);
2687 del_len = (del_len < 0 ? 0 :
2688 del_len > (int)(charlen - start_idx) ? charlen - start_idx :
2689 del_len);
2690
2691 /* get the starting byte index */
2692 size_t start_byte_idx = p.bytelen(start_idx);
2693
2694 /* save 'self' as gc protection */
2695 G_stk->push(self_val);
2696
2697 /*
2698 * If there's an insertion string, get it as a string. Treat nil as an
2699 * empty insertion.
2700 */
2701 size_t ins_len = 0;
2702 const char *ins = 0;
2703 vm_val_t new_ins_str;
2704 new_ins_str.set_nil();
2705 if (oargc >= 3 && G_stk->get(1)->typ != VM_NIL)
2706 {
2707 /*
2708 * Leave the insertion string on the stack for gc protection, and
2709 * do an explicit conversion to string.
2710 */
2711 ins = cvt_to_str(vmg_ &new_ins_str, ins_buf, sizeof(ins_buf),
2712 G_stk->get(1), 10, 0);
2713 ins_len = vmb_get_len(ins);
2714 ins += VMB_LEN;
2715 }
2716
2717 /* push the new insertion string (if any) for gc protection */
2718 G_stk->push(&new_ins_str);
2719
2720 /* check to see if we're making any changes */
2721 if (del_len != 0 || ins_len != 0)
2722 {
2723 /* allocate a new string at the proper length */
2724 retval->set_obj(create(vmg_ FALSE, len + ins_len - del_len));
2725 CVmObjString *new_str = (CVmObjString *)vm_objp(vmg_ retval->val.obj);
2726 char *newp = new_str->cons_get_buf();
2727
2728 /* copy the part of our string up to the starting index */
2729 if (start_byte_idx > 0)
2730 {
2731 memcpy(newp, str, start_byte_idx);
2732 newp += start_byte_idx;
2733 }
2734
2735 /* if we have an insertion string, copy it */
2736 if (ins_len != 0)
2737 {
2738 memcpy(newp, ins, ins_len);
2739 newp += ins_len;
2740 }
2741
2742 /* skip past the deleted material in the original string */
2743 p.set((char *)str + start_byte_idx);
2744 for (len -= start_byte_idx ; del_len != 0 && len != 0 ; --del_len)
2745 p.inc(&len);
2746
2747 /* if we have any more of the spliced string, copy it */
2748 if (len != 0)
2749 memcpy(newp, p.getptr(), len);
2750 }
2751 else
2752 {
2753 /* we're making no changes - return the original string */
2754 *retval = *self_val;
2755 }
2756
2757 /*
2758 * discard the remaining arguments and the gc protection (original
2759 * argc, minus 2 arg pops, plus 2 gc protection pushes -> oargc)
2760 */
2761 G_stk->discard(oargc);
2762
2763 /* handled */
2764 return TRUE;
2765 }
2766
2767 /* ------------------------------------------------------------------------ */
2768 /*
2769 * property evaluator - split
2770 */
2771 int CVmObjString::getp_split(VMG_ vm_val_t *retval,
2772 const vm_val_t *self_val,
2773 const char *str, uint *argcp)
2774 {
2775 /* check arguments */
2776 static CVmNativeCodeDesc desc(0, 2);
2777 uint argc = (argcp != 0 ? *argcp : 0);
2778 if (get_prop_check_argc(retval, argcp, &desc))
2779 return TRUE;
2780
2781 /* get the string buffer and length */
2782 size_t len = vmb_get_len(str);
2783 str += VMB_LEN;
2784
2785 /* remember the start of the base string */
2786 const char *basestr = str;
2787
2788 /*
2789 * Get the delimiter or split size, leaving it on the stack for gc
2790 * protection. This can be a string, a RexPattern, or an integer.
2791 */
2792 const vm_val_t *delim = G_stk->get(0);
2793 const char *delim_str = 0;
2794 CVmObjPattern *delim_pat = 0;
2795 int split_len = 0;
2796 if (argc < 1 || delim->typ == VM_NIL)
2797 {
2798 /* there's no delimiter at all, so use the default split length 1 */
2799 split_len = 1;
2800 }
2801 else if (delim->typ == VM_INT)
2802 {
2803 /* it's a simple split length */
2804 split_len = delim->val.intval;
2805 if (split_len <= 0)
2806 err_throw(VMERR_BAD_VAL_BIF);
2807 }
2808 else if ((delim_str = delim->get_as_string(vmg0_)) == 0)
2809 {
2810 /* if it's not a length or string, it has to be a RexPattern object */
2811 if (delim->typ != VM_OBJ
2812 || !CVmObjPattern::is_pattern_obj(vmg_ delim->val.obj))
2813 err_throw(VMERR_BAD_TYPE_BIF);
2814
2815 /* get the pattern object, properly cast */
2816 delim_pat = (CVmObjPattern *)vm_objp(vmg_ delim->val.obj);
2817 }
2818
2819 /* get the split count limit, if there is one */
2820 int32_t limit = -1;
2821 if (argc >= 2 && G_stk->get(1)->typ != VM_NIL)
2822 {
2823 /* there's an explicit limit; fetch it and make sure it's at least 1 */
2824 if ((limit = G_stk->get(1)->num_to_int(vmg0_)) < 1)
2825 err_throw(VMERR_BAD_VAL_BIF);
2826 }
2827
2828 /* push 'self' for gc protection */
2829 G_stk->push(self_val);
2830
2831 /*
2832 * Set up a return list. If we have a limit, the list can't go over
2833 * that length, so just create the list at the limit. Otherwise, if we
2834 * have a split length, we can figure the required list length by
2835 * dividing the string length by the split length (rounding up).
2836 * Otherwise we have no idea how many list elements we'll need, so just
2837 * create the list at an arbitrary default length and expand later if
2838 * needed.
2839 */
2840 int init_list_len;
2841 if (limit > 0)
2842 {
2843 /* there's a limit, so we won't need more than this many elements */
2844 init_list_len = limit;
2845 }
2846 else if (split_len > 0)
2847 {
2848 /* split length -> divide the string length by the split length */
2849 init_list_len = (len + split_len - 1)/split_len;
2850
2851 /* set the length to at least one, unless it's an empty string */
2852 if (init_list_len < 1 && len != 0)
2853 init_list_len = 1;
2854 }
2855 else
2856 {
2857 /* no limit or length, so start with an arbitrary guess */
2858 init_list_len = 10;
2859 }
2860
2861 /* create the list */
2862 retval->set_obj(CVmObjList::create(vmg_ FALSE, init_list_len));
2863 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
2864
2865 /* clear the list to nils, since we're building it incrementally */
2866 lst->cons_clear();
2867
2868 /* push it for gc protection */
2869 G_stk->push(retval);
2870
2871 /* repeatedly search for the delimiter and split the string */
2872 int cnt;
2873 vm_val_t ele;
2874 for (cnt = 0 ; (limit < 0 || cnt + 1 < limit) && len != 0 ; ++cnt)
2875 {
2876 /* search for the next delimiter or next 'split_len' characters */
2877 int match_ofs, match_len;
2878 if (split_len > 0)
2879 {
2880 /* figure the number of bytes in split_len characters */
2881 match_ofs = utf8_ptr::s_bytelen(str, split_len);
2882
2883 /* if that uses the whole rest of the string, we're done */
2884 if (match_ofs >= (int)len)
2885 break;
2886
2887 /* there's no delimiter, so the delimiter match length is zero */
2888 match_len = 0;
2889 }
2890 else
2891 {
2892 /* search for the substring or pattern */
2893 const char *nxt = find_substr(
2894 vmg_ self_val, basestr, str, len, delim_str, delim_pat,
2895 &match_ofs, &match_len);
2896
2897 /* if we didn't find it, we're done */
2898 if (nxt == 0)
2899 break;
2900
2901 /* figure the byte offset to the match */
2902 match_ofs = nxt - str;
2903 }
2904
2905 /* add the substring from 'str' to 'p' to the list */
2906 lst->cons_ensure_space(vmg_ cnt, 0);
2907 ele.set_obj(CVmObjString::create(vmg_ FALSE, str, match_ofs));
2908 lst->cons_set_element(cnt, &ele);
2909
2910 /* skip to the position after the match */
2911 size_t skip = match_ofs + match_len;
2912 str += skip;
2913 len -= skip;
2914
2915 /*
2916 * if we matched zero characters, skip one character to prevent an
2917 * infinite loop
2918 */
2919 if (split_len == 0 && match_len == 0 && len != 0)
2920 str += utf8_ptr::s_bytelen(str, 1);
2921 }
2922
2923 /* add a final element for the remainder of the string */
2924 if (len != 0)
2925 {
2926 lst->cons_ensure_space(vmg_ cnt, 0);
2927 ele.set_obj(CVmObjString::create(vmg_ FALSE, str, len));
2928 lst->cons_set_element(cnt, &ele);
2929
2930 /* count it */
2931 ++cnt;
2932 }
2933
2934 /* set the final size of the list */
2935 lst->cons_set_len(cnt);
2936
2937 /* discard arguments plus gc protection */
2938 G_stk->discard(argc + 2);
2939
2940 /* handled */
2941 return TRUE;
2942 }
2943
2944
2945 /* ------------------------------------------------------------------------ */
2946 /*
2947 * Helper routines for specialsToHtml
2948 */
2949
2950 /* find the tag name within a tag */
2951 static void find_tag_name(StringRef *tag, const char *&name, size_t &len,
2952 int &is_end_tag)
2953 {
2954 const char *p;
2955
2956 /* skip leading spaces */
2957 for (p = tag->get() ; isspace(*p) ; ++p) ;
2958
2959 /* if it's an end tag, skip the '/' and any intervening spaces */
2960 if ((is_end_tag = (*p == '/')) != 0)
2961 for (++p ; isspace(*p) ; ++p) ;
2962
2963 /* scan the name - it's from here to the next space */
2964 for (name = p ; *p != '\0' && !isspace(*p) ; ++p) ;
2965
2966 /* note the length */
2967 len = p - name;
2968 }
2969
2970 /* parse the name from a tag */
2971 static void parse_tag_name(StringRef *tag, char *&name, int &is_end_tag)
2972 {
2973 /* get the tag name */
2974 size_t len;
2975 const char *namec;
2976 find_tag_name(tag, namec, len, is_end_tag);
2977
2978 /* allocate a copy of the tag name */
2979 name = lib_copy_str(namec, len);
2980 }
2981
2982 /* find an attribute value, given a pointer to the end of the attr name */
2983 static int find_attr_val(const char *name, size_t name_len,
2984 const char *&val, size_t &val_len)
2985 {
2986 const char *p;
2987
2988 /* go to the end of the attribute name */
2989 p = name + name_len;
2990
2991 /* if there's an '=', there's a value */
2992 if (*p == '=')
2993 {
2994 /* the attribute value starts after the '=' */
2995 val = ++p;
2996
2997 /* skip the token */
2998 for (char qu = 0 ; *p != 0 && (!isspace(*p) || qu != 0) ; ++p)
2999 {
3000 /* note if entering or leaving a quoted section */
3001 if (qu == 0 && (*p == '"' || *p == '\''))
3002 qu = *p;
3003 else if (*p == qu)
3004 qu = 0;
3005 }
3006
3007 /* note the length of the value */
3008 val_len = p - val;
3009
3010 /* there's an explicit value for this attribute */
3011 return TRUE;
3012 }
3013 else
3014 {
3015 /* the attribute name is its own implied value */
3016 val = name;
3017 val_len = name_len;
3018
3019 /* there's no explicit value */
3020 return FALSE;
3021 }
3022 }
3023
3024 /* get an attribute value in a tag */
3025 static char *parse_attr_val(StringRef *tag, const char *attr_name)
3026 {
3027 const char *p;
3028 size_t len;
3029 int is_end_tag;
3030 size_t attr_len = strlen(attr_name);
3031
3032 /* find and skip the tag name */
3033 find_tag_name(tag, p, len, is_end_tag);
3034 p += len;
3035
3036 /* keep going until we find the attribute or run out of text */
3037 for (;;)
3038 {
3039 /* skip leading spaces */
3040 for ( ; isspace(*p) ; ++p) ;
3041
3042 /* if we're at the end of the text, we're done */
3043 if (*p == '\0')
3044 break;
3045
3046 /* scan the attribute name */
3047 const char *an;
3048 size_t anlen;
3049 for (an = p ; *p != '\0' && *p != '=' && !isspace(*p) ; ++p) ;
3050 anlen = p - an;
3051
3052 /* get the attribute value */
3053 const char *av;
3054 size_t avlen;
3055 find_attr_val(an, anlen, av, avlen);
3056
3057 /* check for a match */
3058 if (anlen == attr_len && memicmp(attr_name, an, attr_len) == 0)
3059 {
3060 /* it's our attribute name - allocate a copy */
3061 char *retval = lib_copy_str(av, avlen);
3062
3063 /* remove quotes */
3064 char *dst, qu;
3065 for (p = dst = retval, qu = 0 ; *p != '\0' ; ++p)
3066 {
3067 /* check for entering/leaving a quoted section */
3068 if (qu == 0 && (*p == '"' || *p == '\''))
3069 {
3070 /* entering quotes - note the quote, don't copy it */
3071 qu = *p;
3072 }
3073 else if (qu == *p)
3074 {
3075 /* leaving quotes - don't copy the quote */
3076 qu = 0;
3077 }
3078 else
3079 {
3080 /* copy anything else as given */
3081 *dst++ = *p;
3082 }
3083 }
3084
3085 /* null-terminate the updated string and return it */
3086 *dst = '\0';
3087 return retval;
3088 }
3089
3090 /* skip the value and move on to the next attribute */
3091 p = av + avlen;
3092 }
3093
3094 /* didn't find the value */
3095 return 0;
3096 }
3097
3098 /*
3099 * property evaluator - specialsToHtml
3100 */
3101 int CVmObjString::getp_specialsToHtml(VMG_ vm_val_t *retval,
3102 const vm_val_t *self_val,
3103 const char *str, uint *argc)
3104 {
3105 return specialsTo(vmg_ retval, self_val, str, argc, TRUE);
3106 }
3107
3108 /*
3109 * property evaluator - specialsToText
3110 */
3111 int CVmObjString::getp_specialsToText(VMG_ vm_val_t *retval,
3112 const vm_val_t *self_val,
3113 const char *str, uint *argc)
3114 {
3115 return specialsTo(vmg_ retval, self_val, str, argc, FALSE);
3116 }
3117
3118 /*
3119 * common property evaluator for specialsToText and specialsToHtml
3120 */
3121 int CVmObjString::specialsTo(VMG_ vm_val_t *retval,
3122 const vm_val_t *self_val,
3123 const char *str, uint *argc,
3124 int html)
3125 {
3126 vm_rcdesc rc;
3127 vm_prop_id_t flags_prop = VM_INVALID_OBJ, tag_prop = VM_INVALID_OBJ;
3128
3129 /* check arguments */
3130 uint oargc = (argc != 0 ? *argc : 0);
3131 static CVmNativeCodeDesc desc(0, 1);
3132 if (get_prop_check_argc(retval, argc, &desc))
3133 return TRUE;
3134
3135 /* set up the default initial state */
3136 int in_line = FALSE;
3137 int caps = FALSE, nocaps = FALSE;
3138 int space = FALSE, qspace = FALSE;
3139 int in_tag = FALSE, in_entity = FALSE;
3140 int qlevel = 0;
3141 char attrq = 0;
3142 int col = 0;
3143 StringRef *tag = new StringRef(128);
3144
3145 /* get the string length and buffer pointer */
3146 size_t len = vmb_get_len(str);
3147 str += VMB_LEN;
3148
3149 /* set up a buffer for the output - anticipate a little expansion */
3150 StringRef *buf = new StringRef(len*5/4);
3151
3152 err_try
3153 {
3154 /* get the state object, if present */
3155 vm_val_t stateobj;
3156 stateobj.set_nil();
3157 if (oargc >= 1)
3158 {
3159 /* the argument is there - get the object or nil */
3160 if (G_stk->get(0)->typ == VM_OBJ)
3161 {
3162 /* get the state object */
3163 stateobj = *G_stk->get(0);
3164
3165 /* set up the recursive evaluation descriptor */
3166 rc.init(vmg_ "String.specialsToHtml", self_val, 13,
3167 G_stk->get(0), oargc);
3168
3169 /* get the 'flags_' and 'tag_' property IDs */
3170 flags_prop = G_predef->string_sth_flags;
3171 tag_prop = G_predef->string_sth_tag;
3172
3173 /* get the flags */
3174 int32_t flags = 0;
3175 if (flags_prop != VM_INVALID_OBJ)
3176 {
3177 /* get the property */
3178 G_interpreter->get_prop(vmg_ 0, &stateobj, flags_prop,
3179 &stateobj, 0, &rc);
3180
3181 /* if it's an integer, get its value */
3182 if (G_interpreter->get_r0()->typ == VM_INT)
3183 flags = G_interpreter->get_r0()->val.intval;
3184 }
3185
3186 /* decode the flags */
3187 in_line = (flags & 0x0001) != 0;
3188 caps = (flags & 0x0002) != 0;
3189 nocaps = (flags & 0x0004) != 0;
3190 in_tag = (flags & 0x0008) != 0;
3191 attrq = (flags & 0x0010 ? '"' : flags & 0x0020 ? '\'' : 0);
3192 space = (flags & 0x0040) != 0;
3193 qspace = (flags & 0x0080) != 0;
3194 qlevel = (flags & 0x0100) != 0;
3195 in_entity = (flags & 0x200) != 0;
3196 col = (flags & 0x3000) >> 12;
3197
3198 /* get the tag value */
3199 const char *tagp;
3200 if (tag_prop != VM_INVALID_OBJ)
3201 {
3202 /* get the property */
3203 G_interpreter->get_prop(vmg_ 0, &stateobj, tag_prop,
3204 &stateobj, 0, &rc);
3205
3206 /* get the string value, if any */
3207 tagp = G_interpreter->get_r0()->get_as_string(vmg0_);
3208
3209 /* copy the tag string, if we found it */
3210 if (tagp != 0)
3211 tag->append(tagp + VMB_LEN, vmb_get_len(tagp));
3212 }
3213 }
3214 else if (G_stk->get(0)->typ != VM_NIL)
3215 {
3216 /* anything other than an object or nil is an error */
3217 err_throw(VMERR_BAD_TYPE_BIF);
3218 }
3219 }
3220
3221 /* parse the string */
3222 utf8_ptr p;
3223 for (p.set((char *)str) ; len != 0 ; p.inc(&len))
3224 {
3225 /* get the next character */
3226 wchar_t ch = p.getch();
3227
3228 /* if we're in a tag, add this character to the tag */
3229 if (in_tag)
3230 {
3231 /* convert specials in the tag */
3232 switch (ch)
3233 {
3234 case '\n':
3235 case 0x0B:
3236 case 0x15:
3237 case '\t':
3238 /* convert newlines, quoted spaces, and tabs to spaces */
3239 tag->append(" ");
3240 break;
3241
3242 case 0x0E:
3243 case 0x0F:
3244 /* \^ and \v have no place in tags */
3245 break;
3246
3247 case '"':
3248 case '\'':
3249 /* note that we're entering or leaving quoted text */
3250 if (attrq == 0)
3251 attrq = (char)ch;
3252 else if (attrq == ch)
3253 attrq = 0;
3254
3255 /* append the character */
3256 tag->append_utf8(ch);
3257 break;
3258
3259 case '>':
3260 /* ignore it if we're in quoted text */
3261 if (attrq != 0)
3262 {
3263 tag->append_utf8(ch);
3264 }
3265 else
3266 {
3267 /* end the tag */
3268 in_tag = FALSE;
3269
3270 /* parse the tag name */
3271 char *tagname;
3272 int is_end_tag;
3273 parse_tag_name(tag, tagname, is_end_tag);
3274
3275 /* assume we'll copy it verbatim */
3276 int keep_tag = TRUE;
3277
3278 /* check to see if it's one of our special tags */
3279 if (stricmp(tagname, "q") == 0)
3280 {
3281 /*
3282 * <Q> or </Q> - translate to &ldquo..&rdquo or
3283 * &lsquo..&rsquo
3284 */
3285 static const char *qentity[] = {
3286 "&ldquo;", "&rdquo;",
3287 "&lsquo;", "&rsquo;"
3288 };
3289 static const char *qtxt[] = {
3290 "\"", "\"", "'", "'"
3291 };
3292
3293 /* if it's </Q>, pre-decrement the level */
3294 if (is_end_tag)
3295 qlevel = !qlevel;
3296
3297 /*
3298 * figure which type of quote to use: double
3299 * quotes at even levels, single quotes at odd
3300 * levels; left quotes for open tags, right
3301 * quotes for close tags
3302 */
3303 int idx = (qlevel ? 2 : 0)
3304 + (is_end_tag ? 1 : 0);
3305
3306 /* add the quote */
3307 buf->append(html ? qentity[idx] : qtxt[idx]);
3308 col++;
3309
3310 /* if it's <Q>, post-increment the level */
3311 if (!is_end_tag)
3312 qlevel = !qlevel;
3313
3314 /* we've translated the tag */
3315 keep_tag = FALSE;
3316 }
3317 else if (stricmp(tagname, "br") == 0)
3318 {
3319 /*
3320 * if there's a HEIGHT attribute, it's special;
3321 * otherwise it's just a regular <br>
3322 */
3323 char *htv = parse_attr_val(tag, "height");
3324 if (htv != 0)
3325 {
3326 /* get the numeric value */
3327 int ht = atoi(htv);
3328
3329 /*
3330 * if we're at the beginning of a line,
3331 * translate this to 'ht' <BR> tags; if
3332 * we're within a line, use 'ht+1' <BR>
3333 * tags
3334 */
3335 if (in_line)
3336 ht += 1;
3337
3338 /* write out the <BR> tags */
3339 while (ht-- > 0)
3340 buf->append(html ? "<br>" : "\n");
3341
3342 /* done with the height value */
3343 lib_free_str(htv);
3344
3345 /* we've translated the tag */
3346 keep_tag = FALSE;
3347 }
3348 else if (!html)
3349 {
3350 /* regular text mode - convert to \n */
3351 buf->append("\n");
3352 }
3353
3354 /* we're no longer in a line */
3355 in_line = FALSE;
3356 col = 0;
3357 }
3358 else if (stricmp(tagname, "p") == 0)
3359 {
3360 /* in text mode, add a newline or two */
3361 if (!html)
3362 {
3363 buf->append("\n");
3364 if (in_line)
3365 buf->append("\n");
3366 }
3367
3368 /* this counts as a line break */
3369 in_line = FALSE;
3370 col = 0;
3371 }
3372 else if (stricmp(tagname, "div") == 0
3373 || stricmp(tagname, "center") == 0
3374 || stricmp(tagname, "table") == 0
3375 || stricmp(tagname, "td") == 0
3376 || stricmp(tagname, "th") == 0
3377 || stricmp(tagname, "caption") == 0)
3378 {
3379 /* this counts as a line break */
3380 in_line = FALSE;
3381 col = 0;
3382
3383 /* in text mode, add a newline */
3384 if (!html)
3385 buf->append("\n");
3386 }
3387
3388 /*
3389 * if we're keeping the original tag, copy it to
3390 * the output
3391 */
3392 if (html && keep_tag)
3393 {
3394 buf->append("<");
3395 buf->append(tag->get(), tag->getlen());
3396 buf->append(">");
3397 }
3398
3399 /* done with the tag name */
3400 lib_free_str(tagname);
3401
3402 /* we're done with the tag - clear the buffer */
3403 tag->truncate(0);
3404 }
3405 break;
3406
3407 default:
3408 /* append anything else as-is */
3409 tag->append_utf8(ch);
3410 break;
3411 }
3412
3413 /* we're done processing this character */
3414 continue;
3415 }
3416
3417 /* continue gathering entity text if applicable */
3418 if (in_entity)
3419 {
3420 /*
3421 * If the entity is more than 10 character long, or this is
3422 * a semicolon, end the entity. Also stop if we're
3423 * processing a &# entity and this isn't a digit.
3424 */
3425 if (ch == ';'
3426 || tag->getlen() >= 10
3427 || (tag->get()[0] == '#' && !is_digit(ch)))
3428 {
3429 /* check what we have in the tag buffer */
3430 char *n = tag->get();
3431 if (n[0] == '#')
3432 {
3433 /* get the decimal unicode value */
3434 buf->append_utf8((wchar_t)atoi(n+1));
3435
3436 /*
3437 * if we stopped on something other than a ';', add
3438 * it as well
3439 */
3440 if (ch != ';')
3441 buf->append_utf8(ch);
3442 }
3443 else if (stricmp(n, "nbsp") == 0)
3444 buf->append_utf8(' ');
3445 else if (stricmp(n, "gt") == 0)
3446 buf->append_utf8('>');
3447 else if (stricmp(n, "lt") == 0)
3448 buf->append_utf8('<');
3449 else if (stricmp(n, "amp") == 0)
3450 buf->append_utf8('&');
3451 else if (stricmp(n, "ldquo") == 0
3452 || stricmp(n, "rdquo") == 0
3453 || stricmp(n, "quot") == 0)
3454 buf->append_utf8('\"');
3455 else if (stricmp(n, "lsquo") == 0
3456 || stricmp(n, "rsquo") == 0)
3457 buf->append_utf8('\'');
3458 else
3459 {
3460 /* unknown entity - copy it as-is */
3461 buf->append(n);
3462 }
3463
3464 /* we're no longer in an entity */
3465 in_entity = FALSE;
3466 tag->truncate(0);
3467 }
3468 else
3469 {
3470 /*
3471 * we're still working on gathering this entity -
3472 * simply buffer the character for now
3473 */
3474 tag->append_utf8(ch);
3475 }
3476
3477 /* we've handled this character */
3478 continue;
3479 }
3480
3481 /* if we have a pending space, write it out */
3482 if (space)
3483 {
3484 /*
3485 * We have a pending regular space. If the next character
3486 * is a quoted space, omit the regular space entirely, as
3487 * regular spaces combine with adjacent quoted spaces.
3488 * Otherwise, write it as a regular space.
3489 */
3490 if (ch != 0x15)
3491 {
3492 buf->append(" ");
3493 col++;
3494 }
3495
3496 /* we've now processed this pending space */
3497 space = FALSE;
3498 }
3499 else if (qspace)
3500 {
3501 /*
3502 * We have a pending quoted space.
3503 *
3504 * If the next character is a regular space, skip the space
3505 * and keep the pending quoted space flag set - the regular
3506 * space combines with the quoted space, so we can remove
3507 * it, but we don't yet know how to handle the quoted space
3508 * itself since we have to see the next non-space character
3509 * to determine that.
3510 *
3511 * If the next character is another quoted space, write the
3512 * pending quoted space as &nbsp;, since adjacent quoted
3513 * spaces don't combine.
3514 *
3515 * If the next character is anything else (not a space or
3516 * quoted space), write the pending quoted space as a
3517 * regular space, since the html renderer won't combine the
3518 * space with the following non-space character, and we do
3519 * want to allow a line break after a quoted space.
3520 */
3521 if (ch == ' ')
3522 continue;
3523 else if (html)
3524 {
3525 buf->append(ch == 0x15 ? "&nbsp;" : " ");
3526 col++;
3527 }
3528 else
3529 {
3530 buf->append(" ");
3531 col++;
3532 }
3533
3534 /* we've now processed this pending quoted space */
3535 qspace = FALSE;
3536 }
3537
3538 /* handle the character */
3539 switch (ch)
3540 {
3541 case '\n':
3542 /* add a <br> if we're within a line */
3543 if (in_line)
3544 buf->append(html ? "<br>" : "\n");
3545
3546 /* we're now at the start of a new line */
3547 in_line = FALSE;
3548 col = 0;
3549 caps = nocaps = FALSE;
3550 break;
3551
3552 case 0x0B:
3553 /*
3554 * '\b' - blank line: add two <BR>'s if we're within a
3555 * line, otherwise just add one
3556 */
3557 buf->append(html ? "<br>" : "\n");
3558 if (in_line)
3559 buf->append(html ? "<br>" : "\n");
3560
3561 /* we're now at the start of a new line */
3562 in_line = FALSE;
3563 col = 0;
3564 caps = nocaps = FALSE;
3565 break;
3566
3567 case 0x0F:
3568 /*
3569 * '\^' - this doesn't write anything to the output, but
3570 * simply sets a flag that tells us to capitalize the next
3571 * printing character
3572 */
3573 caps = TRUE;
3574 nocaps = FALSE;
3575 break;
3576
3577 case 0x0E:
3578 /*
3579 * '\v' - this doesn't write anything to the output, but
3580 * simply sets a flag that tells us to lower-case the next
3581 * printing character
3582 */
3583 caps = FALSE;
3584 nocaps = TRUE;
3585 break;
3586
3587 case 0x15:
3588 /*
3589 * '\ ' - quoted space: this is a non-combining space (it
3590 * can't be consolidated with adjacent spaces) that allows
3591 * line breaks. Don't write anything now, but set the
3592 * quoted space flag for the next character: if the next
3593 * character out is a regular or quoted space, we'll write
3594 * the quoted space as a non-breaking space; otherwise
3595 * we'll write the quoted space as a regular space, so that
3596 * we can break after it.
3597 */
3598 qspace = TRUE;
3599 break;
3600
3601 case ' ':
3602 /*
3603 * Regular space. Don't actually write anything yet, since
3604 * we'll have to turn this into a non-breaking space if the
3605 * next character turns out to be a quoted space. Just set
3606 * the space-pending flag for now.
3607 */
3608 space = TRUE;
3609 break;
3610
3611 case '\t':
3612 /*
3613 * Tab - append spaces to take us out to the next 4-column
3614 * tab stop. We want the renderer to obey the spaces
3615 * (rather than consolidating them), so use non-breaking
3616 * spaces (&nbsp;). However, we want to allow a line break
3617 * after the tab, so use an ordinary space for the last
3618 * one. The renderer won't combine an ordinary space with
3619 * an &nbsp, so it'll render the number of spaces we ask
3620 * for, but we'll be able to break the line after that
3621 * last, ordinary space.
3622 *
3623 * In regular text mode, just write out the tab character.
3624 */
3625 if (html)
3626 {
3627 col = ((col + 1) & 3) - 1;
3628 for ( ; col + 1 < 3 ; ++col)
3629 buf->append("&nbsp;");
3630 buf->append(" ");
3631 ++col;
3632 }
3633 else
3634 buf->append("\t");
3635 break;
3636
3637 case '<':
3638 /* start a tag */
3639 in_tag = TRUE;
3640 break;
3641
3642 case '&':
3643 /* if in text mode, gather the entity information */
3644 if (!html)
3645 in_entity = TRUE;
3646 else
3647 buf->append("&");
3648 break;
3649
3650 default:
3651 /* Ordinary character. Check for caps/nocaps conversions. */
3652 {
3653 const wchar_t *u = 0;
3654 if (caps)
3655 {
3656 u = t3_to_upper(ch);
3657 caps = FALSE;
3658 }
3659 else if (nocaps)
3660 {
3661 u = t3_to_lower(ch);
3662 nocaps = FALSE;
3663 }
3664
3665 /* we're now within a line */
3666 in_line = TRUE;
3667
3668 /* add this character or string to the output */
3669 if (u != 0)
3670 {
3671 for ( ; *u != 0 ; buf->append_utf8(*u++)) ;
3672 }
3673 else
3674 {
3675 buf->append_utf8(ch);
3676 }
3677
3678 /* advance the tab-stop column */
3679 col++;
3680 }
3681 break;
3682 }
3683 }
3684
3685 /*
3686 * If we have a state object, write the final state back to the
3687 * state object, so that the next call can pick up where we left
3688 * off.
3689 */
3690 if (stateobj.typ == VM_OBJ)
3691 {
3692 /* encode the flags */
3693 vm_val_t v;
3694 v.set_int((in_line ? 0x0001 : 0)
3695 | (caps ? 0x0002 : 0)
3696 | (nocaps ? 0x0004 : 0)
3697 | (in_tag ? 0x0008 : 0)
3698 | (attrq == '"' ? 0x0010 : attrq == '\'' ? 0x0020 : 0)
3699 | (space ? 0x0040 : 0)
3700 | (qspace ? 0x0080 : 0)
3701 | (qlevel ? 0x0100 : 0)
3702 | (in_entity ? 0x0200 : 0)
3703 | ((col & 3) << 12));
3704
3705 /* set the flags */
3706 if (flags_prop != VM_INVALID_OBJ)
3707 {
3708 G_interpreter->set_prop(
3709 vmg_ stateobj.val.obj, flags_prop, &v);
3710 }
3711
3712 /* set the tag */
3713 if (tag_prop != VM_INVALID_OBJ)
3714 {
3715 if (in_tag || in_entity)
3716 {
3717 /* we have a tag - set stateobj.tags_ to the string */
3718 G_interpreter->push_string(
3719 vmg_ tag->get(), tag->getlen());
3720 G_interpreter->set_prop(vmg_ stateobj.val.obj, tag_prop,
3721 G_stk->get(0));
3722
3723 /* done with the stacked string */
3724 G_stk->discard();
3725 }
3726 else
3727 {
3728 /* no tag - set stateobj.tags_ to nil */
3729 v.set_nil();
3730 G_interpreter->set_prop(
3731 vmg_ stateobj.val.obj, tag_prop, &v);
3732 }
3733 }
3734 }
3735
3736 /* return the result as a string value */
3737 G_interpreter->push_string(vmg_ buf->get(), buf->getlen());
3738 G_stk->pop(retval);
3739 }
3740 err_finally
3741 {
3742 /* release resources */
3743 tag->release_ref();
3744 buf->release_ref();
3745 }
3746 err_end;
3747
3748 /* discard arguments and gc protection items */
3749 G_stk->discard(oargc);
3750
3751 /* handled */
3752 return TRUE;
3753 }
3754
3755
3756 /* ------------------------------------------------------------------------ */
3757 /*
3758 * property evaluator - urlEncode()
3759 */
3760 int CVmObjString::getp_urlEncode(VMG_ vm_val_t *retval,
3761 const vm_val_t *self_val,
3762 const char *str, uint *argc)
3763 {
3764 /* check arguments */
3765 static CVmNativeCodeDesc desc(0);
3766 if (get_prop_check_argc(retval, argc, &desc))
3767 return TRUE;
3768
3769 /* save my own value for gc protection */
3770 G_stk->push(self_val);
3771
3772 /* get the length and buffer pointer */
3773 size_t len = vmb_get_len(str);
3774 str += VMB_LEN;
3775
3776 /* scan the string and determine the size of the expansion */
3777 size_t outlen;
3778 const char *p;
3779 size_t rem;
3780 for (outlen = 0, p = str, rem = len ; rem != 0 ; ++p, --rem)
3781 {
3782 /*
3783 * if this is a space, letter, digit, or '-' or '_', it requires
3784 * one byte in the output; otherwise it requires three bytes for
3785 * the "%xx" sequence
3786 */
3787 char c = *p;
3788 if (c == ' ' || c == '-' || c == '_'
3789 || (c >= 'a' && c <= 'z')
3790 || (c >= 'A' && c <= 'Z')
3791 || (c >= '0' && c <= '9'))
3792 outlen += 1;
3793 else
3794 outlen += 3;
3795 }
3796
3797 /* allocate the return string */
3798 retval->set_obj(create(vmg_ FALSE, outlen));
3799 char *dst =
3800 ((CVmObjString *)vm_objp(vmg_ retval->val.obj))->cons_get_buf();
3801
3802 /* build the return string */
3803 for (p = str, rem = len ; rem != 0 ; ++p, --rem)
3804 {
3805 /* translate this byte */
3806 char c = *p;
3807 if (c == ' ')
3808 {
3809 /* translate ' ' to '+' */
3810 *dst++ = '+';
3811 }
3812 else if (c == '-' || c == '_'
3813 || (c >= 'a' && c <= 'z')
3814 || (c >= 'A' && c <= 'Z')
3815 || (c >= '0' && c <= '9'))
3816 {
3817 /* letter, digit, '-', '_' - leave unchanged */
3818 *dst++ = c;
3819 }
3820 else
3821 {
3822 /* translate anything else to a %xx sequence */
3823 *dst++ = '%';
3824 byte_to_xdigits(dst, (unsigned char)c);
3825 dst += 2;
3826 }
3827 }
3828
3829 /* discard gc protection */
3830 G_stk->discard(1);
3831
3832 /* done */
3833 return TRUE;
3834 }
3835
3836 /* ------------------------------------------------------------------------ */
3837 /*
3838 * property evaluator - urlDecode()
3839 */
3840 int CVmObjString::getp_urlDecode(VMG_ vm_val_t *retval,
3841 const vm_val_t *self_val,
3842 const char *str, uint *argc)
3843 {
3844 /* check arguments */
3845 static CVmNativeCodeDesc desc(0);
3846 if (get_prop_check_argc(retval, argc, &desc))
3847 return TRUE;
3848
3849 /* save my own value for gc protection */
3850 G_stk->push(self_val);
3851
3852 /* get the length and buffer pointer */
3853 size_t len = vmb_get_len(str);
3854 str += VMB_LEN;
3855
3856 /* scan the string and determine the size of the result */
3857 size_t outlen;
3858 const char *p;
3859 size_t rem;
3860 for (outlen = 0, p = str, rem = len ; rem != 0 ; ++p, --rem, ++outlen)
3861 {
3862 /*
3863 * if this is a '%xx' sequence, it translates to a single byte;
3864 * otherwise just copy the byte as-is
3865 */
3866 if (*p == '%' && rem >= 3 && is_xdigit(*(p+1)) && is_xdigit(*(p+2)))
3867 {
3868 /*
3869 * it's a %xx sequence - skip the whole thing and count is as
3870 * just one byte of output
3871 */
3872 p += 2;
3873 rem -= 2;
3874 }
3875 }
3876
3877 /* allocate the return string */
3878 retval->set_obj(create(vmg_ FALSE, outlen));
3879 char *outbuf =
3880 ((CVmObjString *)vm_objp(vmg_ retval->val.obj))->cons_get_buf();
3881 char *dst = outbuf;
3882
3883 /* build the return string */
3884 for (p = str, rem = len ; rem != 0 ; ++p, --rem, ++dst)
3885 {
3886 /*
3887 * if it's a '+', translate to a space; otherwise, if this is a
3888 * '%xx' sequence, it translates to a single byte; otherwise just
3889 * copy the byte as-is
3890 */
3891 if (*p == '+')
3892 {
3893 *dst = ' ';
3894 }
3895 else if (*p == '%' && rem >= 3
3896 && is_xdigit(*(p+1)) && is_xdigit(*(p+2)))
3897 {
3898 /* it's a %xx sequence - translate to a byte */
3899 *dst = (value_of_xdigit(*(p+1)) << 4)
3900 | value_of_xdigit(*(p+2));
3901
3902 /* skip the %xx sequence in the input */
3903 p += 2;
3904 rem -= 2;
3905 }
3906 else
3907 {
3908 /* copy anything else as-is */
3909 *dst = *p;
3910 }
3911 }
3912
3913 /* validate the resulting UTF8 */
3914 CCharmapToUni::validate(outbuf, outlen);
3915
3916 /* discard gc protection */
3917 G_stk->discard(1);
3918
3919 /* done */
3920 return TRUE;
3921 }
3922
3923 /* ------------------------------------------------------------------------ */
3924 /*
3925 * property evaluator - sha256()
3926 */
3927 int CVmObjString::getp_sha256(VMG_ vm_val_t *retval,
3928 const vm_val_t *self_val,
3929 const char *str, uint *argc)
3930 {
3931 /* check arguments */
3932 static CVmNativeCodeDesc desc(0);
3933 if (get_prop_check_argc(retval, argc, &desc))
3934 return TRUE;
3935
3936 /* get the length and buffer pointer */
3937 size_t len = vmb_get_len(str);
3938 str += VMB_LEN;
3939
3940 /* calculate the hash */
3941 char hash[65];
3942 sha256_ez(hash, str, len);
3943
3944 /* allocate the return string */
3945 retval->set_obj(create(vmg_ FALSE, hash, 64));
3946
3947 /* done */
3948 return TRUE;
3949 }
3950
3951 /* ------------------------------------------------------------------------ */
3952 /*
3953 * property evaluator - digestMD5()
3954 */
3955 int CVmObjString::getp_md5(VMG_ vm_val_t *retval,
3956 const vm_val_t *self_val,
3957 const char *str, uint *argc)
3958 {
3959 /* check arguments */
3960 static CVmNativeCodeDesc desc(0);
3961 if (get_prop_check_argc(retval, argc, &desc))
3962 return TRUE;
3963
3964 /* get the length and buffer pointer */
3965 size_t len = vmb_get_len(str);
3966 str += VMB_LEN;
3967
3968 /* calculate the hash */
3969 char hash[33];
3970 md5_ez(hash, str, len);
3971
3972 /* allocate the return string */
3973 retval->set_obj(create(vmg_ FALSE, hash, 32));
3974
3975 /* done */
3976 return TRUE;
3977 }
3978
3979 /* ------------------------------------------------------------------------ */
3980 /*
3981 * property evaluator - packBytes()
3982 */
3983 int CVmObjString::static_getp_packBytes(VMG_ vm_val_t *retval, uint *pargc)
3984 {
3985 /* check arguments */
3986 uint argc = (pargc != 0 ? *pargc : 0);
3987 static CVmNativeCodeDesc desc(1, 0, TRUE);
3988 if (get_prop_check_argc(retval, pargc, &desc))
3989 return TRUE;
3990
3991 /* set up an in-memory data stream to receive the packed data */
3992 CVmMemorySource *dst = new CVmMemorySource(0L);
3993
3994 err_try
3995 {
3996 /* do the packing */
3997 CVmPack::pack(vmg_ 0, argc, dst);
3998
3999 /* create a string from the byte stream */
4000 retval->set_obj(create_latin1(vmg_ FALSE, dst));
4001 }
4002 err_finally
4003 {
4004 /* done with the in-memory data source */
4005 delete dst;
4006 }
4007 err_end;
4008
4009 /* discard arguments */
4010 G_stk->discard(argc);
4011
4012 /* done */
4013 return TRUE;
4014 }
4015
4016 /* ------------------------------------------------------------------------ */
4017 /*
4018 * UTF-8 String data source. This translates characters from the string to
4019 * bytes, treating the character code as the byte value. If we try to read
4020 * a character outside of the 0..255 range, we'll throw an error.
4021 */
4022 class CVmUTF8Source: public CVmDataSource
4023 {
4024 public:
4025 CVmUTF8Source(const char *str, size_t len)
4026 {
4027 /* remember the string and its byte length */
4028 this->str = str;
4029 this->bytelen = len;
4030
4031 /* calculate the character length */
4032 utf8_ptr p((char *)str);
4033 this->charlen = p.len(len);
4034
4035 /* start at the beginning of the string */
4036 this->charidx = 0;
4037 this->byteidx = 0;
4038 }
4039
4040 virtual CVmDataSource *clone(VMG_ const char * /*mode*/) { return 0; }
4041
4042 /* read bytes - returns 0 on success, non-zero on EOF or error */
4043 virtual int read(void *buf, size_t len)
4044 {
4045 /* do the read; if the request isn't filled exactly, return failure */
4046 return (size_t)readc(buf, len) != len;
4047 }
4048
4049 /* read bytes - returns the number of bytes read; 0 means EOF or error */
4050 virtual int readc(void *buf0, size_t len)
4051 {
4052 /* get the output buffer pointer as a character pointer */
4053 char *buf = (char *)buf0;
4054
4055 /*
4056 * limit the length to the remaining number of characters from the
4057 * current position
4058 */
4059 size_t rem = charlen - charidx;
4060 if (len > rem)
4061 len = rem;
4062
4063 /* do the copy */
4064 utf8_ptr p((char *)str + byteidx);
4065 for (size_t i = 0 ; i < len ; ++i, p.inc(), ++charidx)
4066 {
4067 /* get this character */
4068 wchar_t ch = p.getch();
4069
4070 /* if it's outside of the 0..255 range, it's an error */
4071 if (ch > 255)
4072 err_throw(VMERR_NUM_OVERFLOW);
4073
4074 /* store it */
4075 *buf++ = (char)ch;
4076 }
4077
4078 /* calculate the new byte index */
4079 byteidx = (size_t)(p.getptr() - str);
4080
4081 /* return the length we copied */
4082 return len;
4083 }
4084
4085 /* write bytes - we're read-only, so just return an error */
4086 virtual int write(const void *, size_t) { return 1; }
4087
4088 /*
4089 * Get the length of the file in bytes. We translate each character
4090 * from the string into into one byte in the stream, so our byte length
4091 * equals our character length.
4092 */
4093 virtual long get_size() { return charlen; }
4094
4095 /* get the current seek location */
4096 virtual long get_pos() { return charidx; }
4097
4098 /* set the current seek location - 'mode' is an OSFSK_xxx mode */
4099 virtual int seek(long ofs, int mode)
4100 {
4101 /* figure the absolute position based on the mode */
4102 switch (mode)
4103 {
4104 case OSFSK_SET:
4105 /* set - the offset is already absolute */
4106 break;
4107
4108 case OSFSK_CUR:
4109 /* relative to current index */
4110 ofs += charidx;
4111 break;
4112
4113 case OSFSK_END:
4114 /* relative to the end of file */
4115 ofs += charlen;
4116 break;
4117
4118 default:
4119 /* invalid mode - return an error */
4120 return 1;
4121 }
4122
4123 /* limit the position to the bounds of the string */
4124 if (ofs < 0)
4125 ofs = 0;
4126 else if (ofs > (long)charlen)
4127 ofs = (long)charlen;
4128
4129 /*
4130 * The caller is working with the stream: the byte index in the
4131 * stream equals the character index in the string.
4132 */
4133 charidx = (size_t)ofs;
4134
4135 /* calculate the byte index for the new character index */
4136 utf8_ptr p((char *)str);
4137 byteidx = p.bytelen(charidx);
4138
4139 /* success */
4140 return 0;
4141 }
4142
4143 /* flush - no effect, since we don't buffer anything */
4144 virtual int flush() { return 0; }
4145
4146 /* close - we have no system resources, so this is a no-op */
4147 virtual void close() { }
4148
4149 protected:
4150 /* the string */
4151 const char *str;
4152
4153 /* byte and character length of the string */
4154 size_t bytelen, charlen;
4155
4156 /* current byte and character seek position in the string */
4157 size_t byteidx, charidx;
4158 };
4159
4160 /*
4161 * property evaluator - unpackBytes()
4162 */
4163 int CVmObjString::getp_unpackBytes(VMG_ vm_val_t *retval,
4164 const vm_val_t *self_val,
4165 const char *str, uint *argc)
4166 {
4167 /* check arguments */
4168 static CVmNativeCodeDesc desc(1);
4169 if (get_prop_check_argc(retval, argc, &desc))
4170 return TRUE;
4171
4172 /* get the length and buffer pointer */
4173 size_t len = vmb_get_len(str);
4174 str += VMB_LEN;
4175
4176 /* get the format string (leave it on the stack for gc protection) */
4177 const char *fmt = G_stk->get(0)->get_as_string(vmg0_);
4178 if (fmt == 0)
4179 err_throw(VMERR_STRING_VAL_REQD);
4180
4181 /* get its buffer and length */
4182 size_t fmtlen = vmb_get_len(fmt);
4183 fmt += VMB_LEN;
4184
4185 /* unpack the string */
4186 CVmUTF8Source src(str, len);
4187 CVmPack::unpack(vmg_ retval, fmt, fmtlen, &src);
4188
4189 /* discard arguments */
4190 G_stk->discard(1);
4191
4192 /* done */
4193 return TRUE;
4194 }
4195
4196 /* ------------------------------------------------------------------------ */
4197 /*
4198 * property evaluator - compareTo()
4199 */
4200 int CVmObjString::getp_compareTo(VMG_ vm_val_t *retval,
4201 const vm_val_t *self_val,
4202 const char *str, uint *argc)
4203 {
4204 /* check arguments */
4205 static CVmNativeCodeDesc desc(1);
4206 if (get_prop_check_argc(retval, argc, &desc))
4207 return TRUE;
4208
4209 /* get the length and buffer pointer */
4210 size_t len = vmb_get_len(str);
4211 str += VMB_LEN;
4212
4213 /* get the other string (leave it on the stack for gc protection) */
4214 const char *other = G_stk->get(0)->get_as_string(vmg0_);
4215 if (other == 0)
4216 err_throw(VMERR_STRING_VAL_REQD);
4217
4218 /* get its buffer and length */
4219 size_t olen = vmb_get_len(other);
4220 other += VMB_LEN;
4221
4222 /* no result yet */
4223 retval->set_nil();
4224
4225 /* compare character by character */
4226 utf8_ptr a((char *)str);
4227 utf8_ptr b((char *)other);
4228 for ( ; len != 0 && olen != 0 ; a.inc(&len), b.inc(&olen))
4229 {
4230 int delta = (int)a.getch() - (int)b.getch();
4231 if (delta != 0)
4232 {
4233 retval->set_int(delta);
4234 break;
4235 }
4236 }
4237
4238 /* if we didn't find any differences, the shorter string sorts first */
4239 if (retval->typ == VM_NIL)
4240 retval->set_int(len - olen);
4241
4242 /* discard arguments */
4243 G_stk->discard(1);
4244
4245 /* done */
4246 return TRUE;
4247 }
4248
4249 /*
4250 * property evaluator - compareIgnoreCase()
4251 */
4252 int CVmObjString::getp_compareIgnoreCase(VMG_ vm_val_t *retval,
4253 const vm_val_t *self_val,
4254 const char *str, uint *argc)
4255 {
4256 /* check arguments */
4257 static CVmNativeCodeDesc desc(1);
4258 if (get_prop_check_argc(retval, argc, &desc))
4259 return TRUE;
4260
4261 /* get the length and buffer pointer */
4262 size_t len = vmb_get_len(str);
4263 str += VMB_LEN;
4264
4265 /* get the other string (leave it on the stack for gc protection) */
4266 const char *other = G_stk->get(0)->get_as_string(vmg0_);
4267 if (other == 0)
4268 err_throw(VMERR_STRING_VAL_REQD);
4269
4270 /* get its buffer and length */
4271 size_t olen = vmb_get_len(other);
4272 other += VMB_LEN;
4273
4274 /* compare the strings */
4275 retval->set_int(t3_compare_case_fold(str, len, other, olen, 0));
4276
4277 /* discard arguments */
4278 G_stk->discard(1);
4279
4280 /* done */
4281 return TRUE;
4282 }
4283
4284
4285 /* ------------------------------------------------------------------------ */
4286 /*
4287 * Constant-pool string object
4288 */
4289
4290 /*
4291 * create
4292 */
4293 vm_obj_id_t CVmObjStringConst::create(VMG_ const char *const_ptr)
4294 {
4295 /* create our new ID */
4296 vm_obj_id_t id = vm_new_id(vmg_ FALSE, FALSE, FALSE);
4297
4298 /* create our string object, pointing directly to the constant pool */
4299 new (vmg_ id) CVmObjStringConst(vmg_ const_ptr);
4300
4301 /* return the new ID */
4302 return id;
4303 }