Debian Codegraph @

src/symbol.c

raw
1 /*
2 * symbol.c - symbol implementation
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/priv/atomicP.h"
38 #include "gauche/priv/builtin-syms.h"
39 #include "gauche/priv/moduleP.h"
40
41 /*-----------------------------------------------------------
42 * Symbols
43 */
44
45 static void symbol_print(ScmObj obj, ScmPort *port, ScmWriteContext *);
46 static int symbol_compare(ScmObj x, ScmObj y, int equalp);
47
48 SCM_DEFINE_BUILTIN_CLASS(Scm_SymbolClass, symbol_print, symbol_compare,
49 NULL, NULL, NULL);
50
51 static ScmClass *keyword_cpl[] = {
52 SCM_CLASS_STATIC_PTR(Scm_SymbolClass),
53 SCM_CLASS_STATIC_PTR(Scm_TopClass),
54 NULL
55 };
56
57 SCM_DEFINE_BUILTIN_CLASS(Scm_KeywordClass, symbol_print, symbol_compare,
58 NULL, NULL, keyword_cpl);
59
60 /* name -> symbol mapper */
61 static ScmInternalMutex obtable_mutex = SCM_INTERNAL_MUTEX_INITIALIZER;
62 static ScmHashTable *obtable = NULL;
63
64 #if GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION
65 /* Global keyword table. */
66 static struct {
67 ScmHashTable *table;
68 ScmInternalMutex mutex;
69 } keywords;
70
71 static int keyword_disjoint_p = FALSE;
72 #endif /*!GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION*/
73
74 /* internal constructor. NAME must be an immutable string. */
75 static ScmSymbol *make_sym(ScmClass *klass, ScmString *name, int interned)
76 {
77 if (interned) {
78 /* fast path */
79 SCM_INTERNAL_MUTEX_LOCK(obtable_mutex);
80 ScmObj e = Scm_HashTableRef(obtable, SCM_OBJ(name), SCM_FALSE);
81 SCM_INTERNAL_MUTEX_UNLOCK(obtable_mutex);
82 if (!SCM_FALSEP(e)) return SCM_SYMBOL(e);
83 }
84
85 ScmSymbol *sym = SCM_NEW(ScmSymbol);
86 SCM_SET_CLASS(sym, klass);
87 sym->name = name;
88 sym->flags = interned? SCM_SYMBOL_FLAG_INTERNED : 0;
89
90 if (!interned) {
91 return sym;
92 } else {
93 /* Using SCM_DICT_NO_OVERWRITE ensures that if another thread interns
94 the same name symbol between above HashTableRef and here, we'll
95 get the already interned symbol. */
96 SCM_INTERNAL_MUTEX_LOCK(obtable_mutex);
97 ScmObj r = Scm_HashTableSet(obtable, SCM_OBJ(name), SCM_OBJ(sym),
98 SCM_DICT_NO_OVERWRITE);
99 SCM_INTERNAL_MUTEX_UNLOCK(obtable_mutex);
100 return SCM_UNBOUNDP(r)? sym : SCM_SYMBOL(r);
101 }
102 }
103
104 /* Intern */
105 ScmObj Scm_MakeSymbol(ScmString *name, int interned)
106 {
107 ScmObj sname = Scm_CopyStringWithFlags(name, SCM_STRING_IMMUTABLE,
108 SCM_STRING_IMMUTABLE);
109 return SCM_OBJ(make_sym(SCM_CLASS_SYMBOL, SCM_STRING(sname), interned));
110 }
111
112 /* Keyword prefix. */
113 static SCM_DEFINE_STRING_CONST(keyword_prefix, ":", 1, 1);
114
115 /* In unified keyword, we include preceding ':' to the name. */
116 ScmObj Scm_MakeKeyword(ScmString *name)
117 {
118 #if GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION
119 if (keyword_disjoint_p) {
120 (void)SCM_INTERNAL_MUTEX_LOCK(keywords.mutex);
121 ScmObj r = Scm_HashTableRef(keywords.table, SCM_OBJ(name), SCM_FALSE);
122 (void)SCM_INTERNAL_MUTEX_UNLOCK(keywords.mutex);
123
124 if (SCM_KEYWORDP(r)) return r;
125
126 ScmKeyword *k = SCM_NEW(ScmKeyword);
127 SCM_SET_CLASS(k, SCM_CLASS_KEYWORD);
128 k->name = SCM_STRING(Scm_CopyString(name));
129 (void)SCM_INTERNAL_MUTEX_LOCK(keywords.mutex);
130 r = Scm_HashTableSet(keywords.table, SCM_OBJ(name), SCM_OBJ(k),
131 SCM_DICT_NO_OVERWRITE);
132 (void)SCM_INTERNAL_MUTEX_UNLOCK(keywords.mutex);
133 return SCM_UNBOUNDP(r)? SCM_OBJ(k) : r ;
134 }
135 #endif /*GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION*/
136 ScmObj sname = Scm_StringAppend2(&keyword_prefix, name);
137 ScmSymbol *s = make_sym(SCM_CLASS_KEYWORD, SCM_STRING(sname), TRUE);
138 Scm_DefineConst(Scm__GaucheKeywordModule(), s, SCM_OBJ(s));
139 return SCM_OBJ(s);
140 }
141
142 ScmObj Scm_KeywordToString(ScmKeyword *k)
143 {
144 #if GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION
145 if (keyword_disjoint_p) {
146 return SCM_OBJ(k->name);
147 } else {
148 return Scm_Substring(k->name, 1, -1, FALSE);
149 }
150 #else /*!GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION*/
151 return Scm_Substring(k->name, 1, -1, FALSE);
152 #endif /*!GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION*/
153 }
154
155 /* Default prefix string. */
156 static SCM_DEFINE_STRING_CONST(default_prefix, "G", 1, 1);
157
158 /* Returns uninterned symbol. PREFIX can be NULL */
159 ScmObj Scm_Gensym(ScmString *prefix)
160 {
161 char numbuf[50];
162 static ScmAtomicVar gensym_count = 0;
163 ScmAtomicWord mycount = Scm_AtomicLoad(&gensym_count);
164
165 while (!Scm_AtomicCompareExchange(&gensym_count, &mycount, mycount+1)) {
166 mycount = Scm_AtomicLoad(&gensym_count);
167 Scm_YieldCPU();
168 }
169
170 if (prefix == NULL) prefix = &default_prefix;
171 int nc = snprintf(numbuf, 49, "%"PRIdPTR, mycount);
172 numbuf[49] = '\0';
173 ScmObj name = Scm_StringAppendC(prefix, numbuf, nc, nc);
174 ScmSymbol *sym = make_sym(SCM_CLASS_SYMBOL, SCM_STRING(name), FALSE);
175 return SCM_OBJ(sym);
176 }
177
178 /* If symbol S has a prefix P, returns a symbol without the prefix.
179 Otherwise, returns #f. */
180 ScmObj Scm_SymbolSansPrefix(ScmSymbol *s, ScmSymbol *p)
181 {
182 const ScmStringBody *bp = SCM_STRING_BODY(SCM_SYMBOL_NAME(p));
183 const ScmStringBody *bs = SCM_STRING_BODY(SCM_SYMBOL_NAME(s));
184 int zp = SCM_STRING_BODY_SIZE(bp);
185 int zs = SCM_STRING_BODY_SIZE(bs);
186 const char *cp = SCM_STRING_BODY_START(bp);
187 const char *cs = SCM_STRING_BODY_START(bs);
188
189 if (zp > zs || memcmp(cp, cs, zp) != 0) return SCM_FALSE;
190 return Scm_Intern(SCM_STRING(Scm_MakeString(cs + zp, zs - zp, -1,
191 SCM_STRING_IMMUTABLE)));
192 }
193
194 /*
195 * Print
196 */
197
198 static int escape_required_p(const ScmStringBody *b, u_int flags, int casefold)
199 {
200 int siz = SCM_STRING_BODY_SIZE(b);
201 if (siz == 0) return !(flags & SCM_SYMBOL_WRITER_NOESCAPE_EMPTY);
202
203 const char *p = SCM_STRING_BODY_START(b);
204 const char *e = p + siz;
205 ScmChar ch;
206
207 if (flags & SCM_SYMBOL_WRITER_NOESCAPE_INITIAL) goto subsequent;
208
209 if (keyword_disjoint_p && *p == ':') return TRUE;
210
211 if (*p == '+' || *p == '-') {
212 p++;
213 if (p == e) return FALSE;
214 if (*p == '.') goto dot_subsequent;
215 /* detect special numeric constants */
216 if (siz == 2 && (*p == 'i' || *p == 'I')) return TRUE;
217 if (siz >= 6 && p[3] == '.' && p[4] == '0') {
218 if ((p[0] == 'n' || p[0] == 'N')
219 && (p[1] == 'a' || p[1] == 'A')
220 && (p[2] == 'n' || p[2] == 'N')) return TRUE;
221 if ((p[0] == 'i' || p[0] == 'I')
222 && (p[1] == 'n' || p[1] == 'N')
223 && (p[2] == 'f' || p[2] == 'F')) return TRUE;
224 }
225 SCM_CHAR_GET(p, ch);
226 if (!Scm_CharLexerCategoryP(ch, SCM_CHAR_SIGN_SUBSEQUENT)) return TRUE;
227 p += SCM_CHAR_NBYTES(ch);
228 goto subsequent;
229 }
230 if (*p == '.') {
231 dot_subsequent:
232 p++;
233 if (p == e) return TRUE;
234 SCM_CHAR_GET(p, ch);
235 if (ch != '.' && !Scm_CharLexerCategoryP(ch, SCM_CHAR_SIGN_SUBSEQUENT))
236 return TRUE;
237 p += SCM_CHAR_NBYTES(ch);
238 goto subsequent;
239 }
240 SCM_CHAR_GET(p, ch);
241 if (!Scm_CharLexerCategoryP(ch, SCM_CHAR_INITIAL)) return TRUE;
242 if (casefold && ch >= 'A' && ch <= 'Z') return TRUE;
243 p += SCM_CHAR_NBYTES(ch);
244
245 subsequent:
246 while (p < e) {
247 SCM_CHAR_GET(p, ch);
248 if (!Scm_CharLexerCategoryP(ch, SCM_CHAR_SUBSEQUENT)) return TRUE;
249 if (casefold && ch >= 'A' && ch <= 'Z') return TRUE;
250 p += SCM_CHAR_NBYTES(ch);
251 }
252 return FALSE;
253 }
254
255 /* internal function to write symbol name, with proper escaping */
256 void Scm_WriteSymbolName(ScmString *snam, ScmPort *port, ScmWriteContext *ctx,
257 u_int flags)
258 {
259 /* See if we have special characters, and use |-escape if necessary. */
260 /* TODO: For now, we regard chars over 0x80 is all "printable".
261 Need a more consistent mechanism. */
262 const ScmStringBody *b = SCM_STRING_BODY(snam);
263 const char *p = SCM_STRING_BODY_START(b);
264 int siz = SCM_STRING_BODY_SIZE(b);
265 int casefold = (Scm_WriteContextCase(ctx) == SCM_WRITE_CASE_FOLD);
266
267 if (siz == 0) { /* special case */
268 if (!(flags & SCM_SYMBOL_WRITER_NOESCAPE_EMPTY)) {
269 SCM_PUTZ("||", -1, port);
270 }
271 return;
272 }
273 if (escape_required_p(b, flags, casefold)) {
274 SCM_PUTC('|', port);
275 for (const char *q=p; q<p+siz; ) {
276 unsigned int ch;
277 SCM_CHAR_GET(q, ch);
278 q += SCM_CHAR_NBYTES(ch);
279 if (ch < 128) {
280 if (ch == '|' || ch == '\\') {
281 SCM_PUTC('\\', port);
282 SCM_PUTC(ch, port);
283 } else if (ch < 0x20 || ch == 0x7f) {
284 Scm_Printf(port, "\\x%02x;", ch);
285 } else {
286 SCM_PUTC(ch, port);
287 }
288 } else {
289 SCM_PUTC(ch, port);
290 }
291 }
292 SCM_PUTC('|', port);
293 } else {
294 SCM_PUTS(snam, port);
295 }
296 }
297
298 /* Symbol printer.
299 NB: Uninterned symbols are treated as sharable objects (can be written
300 with #n= syntax). It is handled by upper layer (write.c) so we don't
301 worry about it in this routine.
302 */
303 static void symbol_print(ScmObj obj, ScmPort *port, ScmWriteContext *ctx)
304 {
305 if (Scm_WriteContextMode(ctx) == SCM_WRITE_DISPLAY) {
306 SCM_PUTS(SCM_SYMBOL_NAME(obj), port);
307 } else {
308 #if GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION
309 if (SCM_KEYWORDP(obj) && keyword_disjoint_p) {
310 Scm_Putc(':', port);
311 /* We basically print keyword names in the same way as symbols
312 (i.e. using |-escape if necessary). However, as a convention,
313 two things are different from the default symbol writer.
314 (1) We don't check the noninitials; :1 is unambiguously a
315 keyword, so we don't need to print :|1|.
316 (2) A keyword with an empty name can be printed just as :,
317 instead of :||.
318 These conventions are useful if we pass the S-expression with
319 these keywords to other Scheme implementations that don't support
320 CL-style keywords; they would just read those ones as symbols.
321 */
322 Scm_WriteSymbolName(SCM_KEYWORD(obj)->name, port, ctx,
323 (SCM_SYMBOL_WRITER_NOESCAPE_INITIAL
324 |SCM_SYMBOL_WRITER_NOESCAPE_EMPTY));
325 return;
326 }
327 #endif /*GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION*/
328 if (!SCM_SYMBOL_INTERNED(obj)) SCM_PUTZ("#:", -1, port);
329 Scm_WriteSymbolName(SCM_SYMBOL_NAME(obj), port, ctx, 0);
330 }
331 }
332
333 /* Symbol comparison procedure.
334 Will be used via 'compare' procedure. Following srfi-114, we compare
335 by name, but takes extra care of intern/unintern distinction; if the
336 names are the same, interned symbol is less, and if both are
337 uninterned, we compare addresses.
338 */
339 static int symbol_compare(ScmObj x, ScmObj y, int equalp)
340 {
341 if (equalp) {
342 /* Symbol equality test is handled in Scm_Eq* and will never come
343 here, but just in case. */
344 return SCM_EQ(x, y)? 0:1;
345 } else if (SCM_EQ(x, y)) {
346 return 0;
347 } else {
348 int r = Scm_StringCmp(SCM_SYMBOL_NAME(x), SCM_SYMBOL_NAME(y));
349 if (r != 0) return r;
350 if (SCM_SYMBOL_INTERNED(x)) return -1; /* y must be uninterned */
351 if (SCM_SYMBOL_INTERNED(y)) return 1; /* x must be uninterned */
352 return (x < y)? -1 : 1; /* both are uninterned */
353 }
354 }
355
356 /*
357 * Keyword Utilities
358 * The names are historical; KEY doesn't need to be a keyword at all;
359 * anything that can be compared by eq? do.
360 */
361
362 ScmObj Scm_GetKeyword(ScmObj key, ScmObj list, ScmObj fallback)
363 {
364 ScmObj cp;
365 SCM_FOR_EACH(cp, list) {
366 if (!SCM_PAIRP(SCM_CDR(cp))) {
367 Scm_Error("incomplete key list: %S", list);
368 }
369 if (key == SCM_CAR(cp)) return SCM_CADR(cp);
370 cp = SCM_CDR(cp);
371 }
372 if (SCM_UNBOUNDP(fallback)) {
373 Scm_Error("value for key %S is not provided: %S", key, list);
374 }
375 return fallback;
376 }
377
378 ScmObj Scm_DeleteKeyword(ScmObj key, ScmObj list)
379 {
380 ScmObj cp;
381 SCM_FOR_EACH(cp, list) {
382 if (!SCM_PAIRP(SCM_CDR(cp))) {
383 Scm_Error("incomplete key list: %S", list);
384 }
385 if (key == SCM_CAR(cp)) {
386 /* found */
387 ScmObj h = SCM_NIL, t = SCM_NIL;
388 ScmObj tail = Scm_DeleteKeyword(key, SCM_CDR(SCM_CDR(cp)));
389 ScmObj cp2;
390 SCM_FOR_EACH(cp2, list) {
391 if (cp2 == cp) {
392 SCM_APPEND(h, t, tail);
393 return h;
394 } else {
395 SCM_APPEND1(h, t, SCM_CAR(cp2));
396 }
397 }
398 }
399 cp = SCM_CDR(cp);
400 }
401 return list;
402 }
403
404 ScmObj Scm_DeleteKeywordX(ScmObj key, ScmObj list)
405 {
406 ScmObj cp, prev = SCM_FALSE;
407 SCM_FOR_EACH(cp, list) {
408 if (!SCM_PAIRP(SCM_CDR(cp))) {
409 Scm_Error("incomplete key list: %S", list);
410 }
411 if (key == SCM_CAR(cp)) {
412 /* found */
413 if (SCM_FALSEP(prev)) {
414 /* we're at the head of list */
415 return Scm_DeleteKeywordX(key, SCM_CDR(SCM_CDR(cp)));
416 } else {
417 ScmObj tail = Scm_DeleteKeywordX(key, SCM_CDR(SCM_CDR(cp)));
418 Scm_SetCdr(prev, tail);
419 return list;
420 }
421 }
422 cp = SCM_CDR(cp);
423 prev = cp;
424 }
425 return list;
426 }
427
428 /* Scan kv-list to look for keywords in the array *KEYS. Saves the first
429 * found value in the corresponding *VALS. Returns a kv-list with all
430 * the keys deleted. For unfound keys, the corresponding VAL is set with
431 * FALLBACK.
432 * May throw an error if kv-list isn't even.
433 */
434 ScmObj Scm_ExtractKeywords(ScmObj kv_list,
435 const ScmObj *keys,
436 int numKeys,
437 ScmObj *vals,
438 ScmObj fallback)
439 {
440 ScmObj cp, h = SCM_NIL, t = SCM_NIL;
441 int i;
442 for (i=0; i<numKeys; i++) vals[i] = SCM_UNBOUND;
443 SCM_FOR_EACH(cp, kv_list) {
444 if (!SCM_PAIRP(SCM_CDR(cp))) {
445 Scm_Error("keyword list not even: %S", kv_list);
446 }
447 for (i=0; i<numKeys; i++) {
448 if (SCM_EQ(keys[i], SCM_CAR(cp))) {
449 if (SCM_UNBOUNDP(vals[i])) {
450 vals[i] = SCM_CADR(cp);
451 }
452 break;
453 }
454 }
455 if (i == numKeys) {
456 SCM_APPEND1(h, t, SCM_CAR(cp));
457 SCM_APPEND1(h, t, SCM_CADR(cp));
458 }
459 cp = SCM_CDR(cp);
460 }
461 if (!SCM_UNBOUNDP(fallback)) {
462 for (i=0; i<numKeys; i++) {
463 if (vals[i] == SCM_UNBOUND) {
464 vals[i] = fallback;
465 }
466 }
467 }
468 return h;
469 }
470
471 /*
472 * Initialization
473 */
474
475 #include "builtin-syms.c"
476
477 void Scm__InitSymbol(void)
478 {
479 SCM_INTERNAL_MUTEX_INIT(obtable_mutex);
480 obtable = SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_STRING, 4096));
481 init_builtin_syms();
482 #if GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION
483 (void)SCM_INTERNAL_MUTEX_INIT(keywords.mutex);
484 keywords.table = SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_STRING, 256));
485 /* Preset keyword class precedence list, depending on the value of
486 GAUCHE_KEYWORD_DISJOINT or GAUCHE_KEYWORD_IS_SYMBOL */
487 const char *disjoint = Scm_GetEnv("GAUCHE_KEYWORD_DISJOINT");
488 const char *issymbol = Scm_GetEnv("GAUCHE_KEYWORD_IS_SYMBOL");
489 if (disjoint != NULL) {
490 keyword_disjoint_p = TRUE;
491 } else if (issymbol != NULL) {
492 keyword_disjoint_p = FALSE;
493 } else {
494 keyword_disjoint_p = FALSE; /* This determines the default */
495 }
496 if (keyword_disjoint_p) {
497 Scm_KeywordClass.cpa = &(keyword_cpl[1]);
498 /* The class is initialized later in class.c */
499 }
500 #endif /*!GAUCHE_KEEP_DISJOINT_KEYWORD_OPTION*/
501 }