import -ko -b 1.1.3 XEmacs XEmacs-21_2 r21-2-35
[chise/xemacs-chise.git.1] / src / elhash.c
1 /* Implementation of the hash table lisp object type.
2    Copyright (C) 1992, 1993, 1994 Free Software Foundation, Inc.
3    Copyright (C) 1995, 1996 Ben Wing.
4    Copyright (C) 1997 Free Software Foundation, Inc.
5
6 This file is part of XEmacs.
7
8 XEmacs is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 XEmacs is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCNTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with XEmacs; see the file COPYING.  If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 /* Synched up with: Not in FSF. */
24
25 #include <config.h>
26 #include "lisp.h"
27 #include "bytecode.h"
28 #include "elhash.h"
29
30 Lisp_Object Qhash_tablep;
31 static Lisp_Object Qhashtable, Qhash_table;
32 static Lisp_Object Qweakness, Qvalue, Qkey_value;
33 static Lisp_Object Vall_weak_hash_tables;
34 static Lisp_Object Qrehash_size, Qrehash_threshold;
35 static Lisp_Object Q_size, Q_test, Q_weakness, Q_rehash_size, Q_rehash_threshold;
36
37 /* obsolete as of 19990901 in xemacs-21.2 */
38 static Lisp_Object Qweak, Qkey_weak, Qvalue_weak, Qkey_value_weak;
39 static Lisp_Object Qnon_weak, Q_type;
40
41 typedef struct hentry
42 {
43   Lisp_Object key;
44   Lisp_Object value;
45 } hentry;
46
47 struct Lisp_Hash_Table
48 {
49   struct lcrecord_header header;
50   size_t size;
51   size_t count;
52   size_t rehash_count;
53   double rehash_size;
54   double rehash_threshold;
55   size_t golden_ratio;
56   hash_table_hash_function_t hash_function;
57   hash_table_test_function_t test_function;
58   hentry *hentries;
59   enum hash_table_weakness weakness;
60   Lisp_Object next_weak;     /* Used to chain together all of the weak
61                                 hash tables.  Don't mark through this. */
62 };
63
64 #define HENTRY_CLEAR_P(hentry) ((*(EMACS_UINT*)(&((hentry)->key))) == 0)
65 #define CLEAR_HENTRY(hentry)   \
66   ((*(EMACS_UINT*)(&((hentry)->key)))   = 0, \
67    (*(EMACS_UINT*)(&((hentry)->value))) = 0)
68
69 #define HASH_TABLE_DEFAULT_SIZE 16
70 #define HASH_TABLE_DEFAULT_REHASH_SIZE 1.3
71 #define HASH_TABLE_MIN_SIZE 10
72
73 #define HASH_CODE(key, ht)                                              \
74 ((((ht)->hash_function ? (ht)->hash_function (key) : LISP_HASH (key))   \
75   * (ht)->golden_ratio)                                                 \
76  % (ht)->size)
77
78 #define KEYS_EQUAL_P(key1, key2, testfun) \
79   (EQ (key1, key2) || ((testfun) && (testfun) (key1, key2)))
80
81 #define LINEAR_PROBING_LOOP(probe, entries, size)               \
82   for (;                                                        \
83        !HENTRY_CLEAR_P (probe) ||                               \
84          (probe == entries + size ?                             \
85           (probe = entries, !HENTRY_CLEAR_P (probe)) : 0);      \
86        probe++)
87
88 #ifndef ERROR_CHECK_HASH_TABLE
89 # ifdef ERROR_CHECK_TYPECHECK
90 #  define ERROR_CHECK_HASH_TABLE 1
91 # else
92 #  define ERROR_CHECK_HASH_TABLE 0
93 # endif
94 #endif
95
96 #if ERROR_CHECK_HASH_TABLE
97 static void
98 check_hash_table_invariants (Lisp_Hash_Table *ht)
99 {
100   assert (ht->count < ht->size);
101   assert (ht->count <= ht->rehash_count);
102   assert (ht->rehash_count < ht->size);
103   assert ((double) ht->count * ht->rehash_threshold - 1 <= (double) ht->rehash_count);
104   assert (HENTRY_CLEAR_P (ht->hentries + ht->size));
105 }
106 #else
107 #define check_hash_table_invariants(ht)
108 #endif
109
110 /* We use linear probing instead of double hashing, despite its lack
111    of blessing by Knuth and company, because, as a result of the
112    increasing discrepancy between CPU speeds and memory speeds, cache
113    behavior is becoming increasingly important, e.g:
114
115    For a trivial loop, the penalty for non-sequential access of an array is:
116     - a factor of 3-4 on Pentium Pro 200 Mhz
117     - a factor of 10  on Ultrasparc  300 Mhz */
118
119 /* Return a suitable size for a hash table, with at least SIZE slots. */
120 static size_t
121 hash_table_size (size_t requested_size)
122 {
123   /* Return some prime near, but greater than or equal to, SIZE.
124      Decades from the time of writing, someone will have a system large
125      enough that the list below will be too short... */
126   static const size_t primes [] =
127   {
128     19, 29, 41, 59, 79, 107, 149, 197, 263, 347, 457, 599, 787, 1031,
129     1361, 1777, 2333, 3037, 3967, 5167, 6719, 8737, 11369, 14783,
130     19219, 24989, 32491, 42257, 54941, 71429, 92861, 120721, 156941,
131     204047, 265271, 344857, 448321, 582821, 757693, 985003, 1280519,
132     1664681, 2164111, 2813353, 3657361, 4754591, 6180989, 8035301,
133     10445899, 13579681, 17653589, 22949669, 29834603, 38784989,
134     50420551, 65546729, 85210757, 110774011, 144006217, 187208107,
135     243370577, 316381771, 411296309, 534685237, 695090819, 903618083,
136     1174703521, 1527114613, 1985248999, 2580823717UL, 3355070839UL
137   };
138   /* We've heard of binary search. */
139   int low, high;
140   for (low = 0, high = countof (primes) - 1; high - low > 1;)
141     {
142       /* Loop Invariant: size < primes [high] */
143       int mid = (low + high) / 2;
144       if (primes [mid] < requested_size)
145         low = mid;
146       else
147         high = mid;
148     }
149   return primes [high];
150 }
151
152 \f
153 #if 0 /* I don't think these are needed any more.
154          If using the general lisp_object_equal_*() functions
155          causes efficiency problems, these can be resurrected. --ben */
156 /* equality and hash functions for Lisp strings */
157 int
158 lisp_string_equal (Lisp_Object str1, Lisp_Object str2)
159 {
160   /* This is wrong anyway.  You can't use strcmp() on Lisp strings,
161      because they can contain zero characters.  */
162   return !strcmp ((char *) XSTRING_DATA (str1), (char *) XSTRING_DATA (str2));
163 }
164
165 static hashcode_t
166 lisp_string_hash (Lisp_Object obj)
167 {
168   return hash_string (XSTRING_DATA (str), XSTRING_LENGTH (str));
169 }
170
171 #endif /* 0 */
172
173 static int
174 lisp_object_eql_equal (Lisp_Object obj1, Lisp_Object obj2)
175 {
176   return EQ (obj1, obj2) || (FLOATP (obj1) && internal_equal (obj1, obj2, 0));
177 }
178
179 static hashcode_t
180 lisp_object_eql_hash (Lisp_Object obj)
181 {
182   return FLOATP (obj) ? internal_hash (obj, 0) : LISP_HASH (obj);
183 }
184
185 static int
186 lisp_object_equal_equal (Lisp_Object obj1, Lisp_Object obj2)
187 {
188   return internal_equal (obj1, obj2, 0);
189 }
190
191 static hashcode_t
192 lisp_object_equal_hash (Lisp_Object obj)
193 {
194   return internal_hash (obj, 0);
195 }
196
197 \f
198 static Lisp_Object
199 mark_hash_table (Lisp_Object obj)
200 {
201   Lisp_Hash_Table *ht = XHASH_TABLE (obj);
202
203   /* If the hash table is weak, we don't want to mark the keys and
204      values (we scan over them after everything else has been marked,
205      and mark or remove them as necessary).  */
206   if (ht->weakness == HASH_TABLE_NON_WEAK)
207     {
208       hentry *e, *sentinel;
209
210       for (e = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
211         if (!HENTRY_CLEAR_P (e))
212           {
213             mark_object (e->key);
214             mark_object (e->value);
215           }
216     }
217   return Qnil;
218 }
219 \f
220 /* Equality of hash tables.  Two hash tables are equal when they are of
221    the same weakness and test function, they have the same number of
222    elements, and for each key in the hash table, the values are `equal'.
223
224    This is similar to Common Lisp `equalp' of hash tables, with the
225    difference that CL requires the keys to be compared with the test
226    function, which we don't do.  Doing that would require consing, and
227    consing is a bad idea in `equal'.  Anyway, our method should provide
228    the same result -- if the keys are not equal according to the test
229    function, then Fgethash() in hash_table_equal_mapper() will fail.  */
230 static int
231 hash_table_equal (Lisp_Object hash_table1, Lisp_Object hash_table2, int depth)
232 {
233   Lisp_Hash_Table *ht1 = XHASH_TABLE (hash_table1);
234   Lisp_Hash_Table *ht2 = XHASH_TABLE (hash_table2);
235   hentry *e, *sentinel;
236
237   if ((ht1->test_function != ht2->test_function) ||
238       (ht1->weakness      != ht2->weakness)      ||
239       (ht1->count         != ht2->count))
240     return 0;
241
242   depth++;
243
244   for (e = ht1->hentries, sentinel = e + ht1->size; e < sentinel; e++)
245     if (!HENTRY_CLEAR_P (e))
246       /* Look up the key in the other hash table, and compare the values. */
247       {
248         Lisp_Object value_in_other = Fgethash (e->key, hash_table2, Qunbound);
249         if (UNBOUNDP (value_in_other) ||
250             !internal_equal (e->value, value_in_other, depth))
251           return 0;             /* Give up */
252       }
253
254   return 1;
255 }
256
257 /* This is not a great hash function, but it _is_ correct and fast.
258    Examining all entries is too expensive, and examining a random
259    subset does not yield a correct hash function. */
260 static hashcode_t
261 hash_table_hash (Lisp_Object hash_table, int depth)
262 {
263   return XHASH_TABLE (hash_table)->count;
264 }
265
266 \f
267 /* Printing hash tables.
268
269    This is non-trivial, because we use a readable structure-style
270    syntax for hash tables.  This means that a typical hash table will be
271    readably printed in the form of:
272
273    #s(hash-table size 2 data (key1 value1 key2 value2))
274
275    The supported hash table structure keywords and their values are:
276    `test'             (eql (or nil), eq or equal)
277    `size'             (a natnum or nil)
278    `rehash-size'      (a float)
279    `rehash-threshold' (a float)
280    `weakness'         (nil, t, key or value)
281    `data'             (a list)
282
283    If `print-readably' is nil, then a simpler syntax is used, for example
284
285    #<hash-table size 2/13 data (key1 value1 key2 value2) 0x874d>
286
287    The data is truncated to four pairs, and the rest is shown with
288    `...'.  This printer does not cons.  */
289
290
291 /* Print the data of the hash table.  This maps through a Lisp
292    hash table and prints key/value pairs using PRINTCHARFUN.  */
293 static void
294 print_hash_table_data (Lisp_Hash_Table *ht, Lisp_Object printcharfun)
295 {
296   int count = 0;
297   hentry *e, *sentinel;
298
299   write_c_string (" data (", printcharfun);
300
301   for (e = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
302     if (!HENTRY_CLEAR_P (e))
303       {
304         if (count > 0)
305           write_c_string (" ", printcharfun);
306         if (!print_readably && count > 3)
307           {
308             write_c_string ("...", printcharfun);
309             break;
310           }
311         print_internal (e->key, printcharfun, 1);
312         write_c_string (" ", printcharfun);
313         print_internal (e->value, printcharfun, 1);
314         count++;
315       }
316
317   write_c_string (")", printcharfun);
318 }
319
320 static void
321 print_hash_table (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
322 {
323   Lisp_Hash_Table *ht = XHASH_TABLE (obj);
324   char buf[128];
325
326   write_c_string (print_readably ? "#s(hash-table" : "#<hash-table",
327                   printcharfun);
328
329   /* These checks have a kludgy look to them, but they are safe.
330      Due to nature of hashing, you cannot use arbitrary
331      test functions anyway.  */
332   if (!ht->test_function)
333     write_c_string (" test eq", printcharfun);
334   else if (ht->test_function == lisp_object_equal_equal)
335     write_c_string (" test equal", printcharfun);
336   else if (ht->test_function == lisp_object_eql_equal)
337     DO_NOTHING;
338   else
339     abort ();
340
341   if (ht->count || !print_readably)
342     {
343       if (print_readably)
344         sprintf (buf, " size %lu", (unsigned long) ht->count);
345       else
346         sprintf (buf, " size %lu/%lu",
347                  (unsigned long) ht->count,
348                  (unsigned long) ht->size);
349       write_c_string (buf, printcharfun);
350     }
351
352   if (ht->weakness != HASH_TABLE_NON_WEAK)
353     {
354       sprintf (buf, " weakness %s",
355                (ht->weakness == HASH_TABLE_WEAK       ? "t"     :
356                 ht->weakness == HASH_TABLE_KEY_WEAK   ? "key"   :
357                 ht->weakness == HASH_TABLE_VALUE_WEAK ? "value" :
358                 ht->weakness == HASH_TABLE_KEY_VALUE_WEAK ? "key-value" :
359                 "you-d-better-not-see-this"));
360       write_c_string (buf, printcharfun);
361     }
362
363   if (ht->count)
364     print_hash_table_data (ht, printcharfun);
365
366   if (print_readably)
367     write_c_string (")", printcharfun);
368   else
369     {
370       sprintf (buf, " 0x%x>", ht->header.uid);
371       write_c_string (buf, printcharfun);
372     }
373 }
374
375 static void
376 finalize_hash_table (void *header, int for_disksave)
377 {
378   if (!for_disksave)
379     {
380       Lisp_Hash_Table *ht = (Lisp_Hash_Table *) header;
381
382       xfree (ht->hentries);
383       ht->hentries = 0;
384     }
385 }
386
387 static const struct lrecord_description hentry_description_1[] = {
388   { XD_LISP_OBJECT, offsetof (hentry, key) },
389   { XD_LISP_OBJECT, offsetof (hentry, value) },
390   { XD_END }
391 };
392
393 static const struct struct_description hentry_description = {
394   sizeof (hentry),
395   hentry_description_1
396 };
397
398 const struct lrecord_description hash_table_description[] = {
399   { XD_SIZE_T,     offsetof (Lisp_Hash_Table, size) },
400   { XD_STRUCT_PTR, offsetof (Lisp_Hash_Table, hentries), XD_INDIRECT(0, 1), &hentry_description },
401   { XD_LO_LINK,    offsetof (Lisp_Hash_Table, next_weak) },
402   { XD_END }
403 };
404
405 DEFINE_LRECORD_IMPLEMENTATION ("hash-table", hash_table,
406                                mark_hash_table, print_hash_table,
407                                finalize_hash_table,
408                                hash_table_equal, hash_table_hash,
409                                hash_table_description,
410                                Lisp_Hash_Table);
411
412 static Lisp_Hash_Table *
413 xhash_table (Lisp_Object hash_table)
414 {
415   if (!gc_in_progress)
416     CHECK_HASH_TABLE (hash_table);
417   check_hash_table_invariants (XHASH_TABLE (hash_table));
418   return XHASH_TABLE (hash_table);
419 }
420
421 \f
422 /************************************************************************/
423 /*                       Creation of Hash Tables                        */
424 /************************************************************************/
425
426 /* Creation of hash tables, without error-checking. */
427 static void
428 compute_hash_table_derived_values (Lisp_Hash_Table *ht)
429 {
430   ht->rehash_count = (size_t)
431     ((double) ht->size * ht->rehash_threshold);
432   ht->golden_ratio = (size_t)
433     ((double) ht->size * (.6180339887 / (double) sizeof (Lisp_Object)));
434 }
435
436 Lisp_Object
437 make_general_lisp_hash_table (enum hash_table_test test,
438                               size_t size,
439                               double rehash_size,
440                               double rehash_threshold,
441                               enum hash_table_weakness weakness)
442 {
443   Lisp_Object hash_table;
444   Lisp_Hash_Table *ht = alloc_lcrecord_type (Lisp_Hash_Table, &lrecord_hash_table);
445
446   switch (test)
447     {
448     case HASH_TABLE_EQ:
449       ht->test_function = 0;
450       ht->hash_function = 0;
451       break;
452
453     case HASH_TABLE_EQL:
454       ht->test_function = lisp_object_eql_equal;
455       ht->hash_function = lisp_object_eql_hash;
456       break;
457
458     case HASH_TABLE_EQUAL:
459       ht->test_function = lisp_object_equal_equal;
460       ht->hash_function = lisp_object_equal_hash;
461       break;
462
463     default:
464       abort ();
465     }
466
467   ht->weakness = weakness;
468
469   ht->rehash_size =
470     rehash_size > 1.0 ? rehash_size : HASH_TABLE_DEFAULT_REHASH_SIZE;
471
472   ht->rehash_threshold =
473     rehash_threshold > 0.0 ? rehash_threshold :
474     size > 4096 && !ht->test_function ? 0.7 : 0.6;
475
476   if (size < HASH_TABLE_MIN_SIZE)
477     size = HASH_TABLE_MIN_SIZE;
478   ht->size = hash_table_size ((size_t) (((double) size / ht->rehash_threshold)
479                                         + 1.0));
480   ht->count = 0;
481
482   compute_hash_table_derived_values (ht);
483
484   /* We leave room for one never-occupied sentinel hentry at the end.  */
485   ht->hentries = xnew_array (hentry, ht->size + 1);
486
487   {
488     hentry *e, *sentinel;
489     for (e = ht->hentries, sentinel = e + ht->size; e <= sentinel; e++)
490       CLEAR_HENTRY (e);
491   }
492
493   XSETHASH_TABLE (hash_table, ht);
494
495   if (weakness == HASH_TABLE_NON_WEAK)
496     ht->next_weak = Qunbound;
497   else
498     ht->next_weak = Vall_weak_hash_tables, Vall_weak_hash_tables = hash_table;
499
500   return hash_table;
501 }
502
503 Lisp_Object
504 make_lisp_hash_table (size_t size,
505                       enum hash_table_weakness weakness,
506                       enum hash_table_test test)
507 {
508   return make_general_lisp_hash_table (test, size, -1.0, -1.0, weakness);
509 }
510
511 /* Pretty reading of hash tables.
512
513    Here we use the existing structures mechanism (which is,
514    unfortunately, pretty cumbersome) for validating and instantiating
515    the hash tables.  The idea is that the side-effect of reading a
516    #s(hash-table PLIST) object is creation of a hash table with desired
517    properties, and that the hash table is returned.  */
518
519 /* Validation functions: each keyword provides its own validation
520    function.  The errors should maybe be continuable, but it is
521    unclear how this would cope with ERRB.  */
522 static int
523 hash_table_size_validate (Lisp_Object keyword, Lisp_Object value,
524                          Error_behavior errb)
525 {
526   if (NATNUMP (value))
527     return 1;
528
529   maybe_signal_error (Qwrong_type_argument, list2 (Qnatnump, value),
530                       Qhash_table, errb);
531   return 0;
532 }
533
534 static size_t
535 decode_hash_table_size (Lisp_Object obj)
536 {
537   return NILP (obj) ? HASH_TABLE_DEFAULT_SIZE : XINT (obj);
538 }
539
540 static int
541 hash_table_weakness_validate (Lisp_Object keyword, Lisp_Object value,
542                               Error_behavior errb)
543 {
544   if (EQ (value, Qnil))         return 1;
545   if (EQ (value, Qt))           return 1;
546   if (EQ (value, Qkey))         return 1;
547   if (EQ (value, Qkey_value))           return 1;
548   if (EQ (value, Qvalue))       return 1;
549
550   /* Following values are obsolete as of 19990901 in xemacs-21.2 */
551   if (EQ (value, Qnon_weak))    return 1;
552   if (EQ (value, Qweak))        return 1;
553   if (EQ (value, Qkey_weak))    return 1;
554   if (EQ (value, Qkey_value_weak))      return 1;
555   if (EQ (value, Qvalue_weak))  return 1;
556
557   maybe_signal_simple_error ("Invalid hash table weakness",
558                              value, Qhash_table, errb);
559   return 0;
560 }
561
562 static enum hash_table_weakness
563 decode_hash_table_weakness (Lisp_Object obj)
564 {
565   if (EQ (obj, Qnil))        return HASH_TABLE_NON_WEAK;
566   if (EQ (obj, Qt))          return HASH_TABLE_WEAK;
567   if (EQ (obj, Qkey))        return HASH_TABLE_KEY_WEAK;
568   if (EQ (obj, Qkey_value))        return HASH_TABLE_KEY_VALUE_WEAK;
569   if (EQ (obj, Qvalue))      return HASH_TABLE_VALUE_WEAK;
570
571   /* Following values are obsolete as of 19990901 in xemacs-21.2 */
572   if (EQ (obj, Qnon_weak))   return HASH_TABLE_NON_WEAK;
573   if (EQ (obj, Qweak))       return HASH_TABLE_WEAK;
574   if (EQ (obj, Qkey_weak))   return HASH_TABLE_KEY_WEAK;
575   if (EQ (obj, Qkey_value_weak))   return HASH_TABLE_KEY_VALUE_WEAK;
576   if (EQ (obj, Qvalue_weak)) return HASH_TABLE_VALUE_WEAK;
577
578   signal_simple_error ("Invalid hash table weakness", obj);
579   return HASH_TABLE_NON_WEAK; /* not reached */
580 }
581
582 static int
583 hash_table_test_validate (Lisp_Object keyword, Lisp_Object value,
584                          Error_behavior errb)
585 {
586   if (EQ (value, Qnil))   return 1;
587   if (EQ (value, Qeq))    return 1;
588   if (EQ (value, Qequal)) return 1;
589   if (EQ (value, Qeql))   return 1;
590
591   maybe_signal_simple_error ("Invalid hash table test",
592                              value, Qhash_table, errb);
593   return 0;
594 }
595
596 static enum hash_table_test
597 decode_hash_table_test (Lisp_Object obj)
598 {
599   if (EQ (obj, Qnil))   return HASH_TABLE_EQL;
600   if (EQ (obj, Qeq))    return HASH_TABLE_EQ;
601   if (EQ (obj, Qequal)) return HASH_TABLE_EQUAL;
602   if (EQ (obj, Qeql))   return HASH_TABLE_EQL;
603
604   signal_simple_error ("Invalid hash table test", obj);
605   return HASH_TABLE_EQ; /* not reached */
606 }
607
608 static int
609 hash_table_rehash_size_validate (Lisp_Object keyword, Lisp_Object value,
610                                  Error_behavior errb)
611 {
612   if (!FLOATP (value))
613     {
614       maybe_signal_error (Qwrong_type_argument, list2 (Qfloatp, value),
615                           Qhash_table, errb);
616       return 0;
617     }
618
619   {
620     double rehash_size = XFLOAT_DATA (value);
621     if (rehash_size <= 1.0)
622       {
623         maybe_signal_simple_error
624           ("Hash table rehash size must be greater than 1.0",
625            value, Qhash_table, errb);
626         return 0;
627       }
628   }
629
630   return 1;
631 }
632
633 static double
634 decode_hash_table_rehash_size (Lisp_Object rehash_size)
635 {
636   return NILP (rehash_size) ? -1.0 : XFLOAT_DATA (rehash_size);
637 }
638
639 static int
640 hash_table_rehash_threshold_validate (Lisp_Object keyword, Lisp_Object value,
641                                      Error_behavior errb)
642 {
643   if (!FLOATP (value))
644     {
645       maybe_signal_error (Qwrong_type_argument, list2 (Qfloatp, value),
646                           Qhash_table, errb);
647       return 0;
648     }
649
650   {
651     double rehash_threshold = XFLOAT_DATA (value);
652     if (rehash_threshold <= 0.0 || rehash_threshold >= 1.0)
653       {
654         maybe_signal_simple_error
655           ("Hash table rehash threshold must be between 0.0 and 1.0",
656            value, Qhash_table, errb);
657         return 0;
658       }
659   }
660
661   return 1;
662 }
663
664 static double
665 decode_hash_table_rehash_threshold (Lisp_Object rehash_threshold)
666 {
667   return NILP (rehash_threshold) ? -1.0 : XFLOAT_DATA (rehash_threshold);
668 }
669
670 static int
671 hash_table_data_validate (Lisp_Object keyword, Lisp_Object value,
672                          Error_behavior errb)
673 {
674   int len;
675
676   GET_EXTERNAL_LIST_LENGTH (value, len);
677
678   if (len & 1)
679     {
680       maybe_signal_simple_error
681         ("Hash table data must have alternating key/value pairs",
682          value, Qhash_table, errb);
683       return 0;
684     }
685   return 1;
686 }
687
688 /* The actual instantiation of a hash table.  This does practically no
689    error checking, because it relies on the fact that the paranoid
690    functions above have error-checked everything to the last details.
691    If this assumption is wrong, we will get a crash immediately (with
692    error-checking compiled in), and we'll know if there is a bug in
693    the structure mechanism.  So there.  */
694 static Lisp_Object
695 hash_table_instantiate (Lisp_Object plist)
696 {
697   Lisp_Object hash_table;
698   Lisp_Object test             = Qnil;
699   Lisp_Object size             = Qnil;
700   Lisp_Object rehash_size      = Qnil;
701   Lisp_Object rehash_threshold = Qnil;
702   Lisp_Object weakness         = Qnil;
703   Lisp_Object data             = Qnil;
704
705   while (!NILP (plist))
706     {
707       Lisp_Object key, value;
708       key   = XCAR (plist); plist = XCDR (plist);
709       value = XCAR (plist); plist = XCDR (plist);
710
711       if      (EQ (key, Qtest))             test             = value;
712       else if (EQ (key, Qsize))             size             = value;
713       else if (EQ (key, Qrehash_size))      rehash_size      = value;
714       else if (EQ (key, Qrehash_threshold)) rehash_threshold = value;
715       else if (EQ (key, Qweakness))         weakness         = value;
716       else if (EQ (key, Qdata))             data             = value;
717       else if (EQ (key, Qtype))/*obsolete*/ weakness         = value;
718       else
719         abort ();
720     }
721
722   /* Create the hash table.  */
723   hash_table = make_general_lisp_hash_table
724     (decode_hash_table_test (test),
725      decode_hash_table_size (size),
726      decode_hash_table_rehash_size (rehash_size),
727      decode_hash_table_rehash_threshold (rehash_threshold),
728      decode_hash_table_weakness (weakness));
729
730   /* I'm not sure whether this can GC, but better safe than sorry.  */
731   {
732     struct gcpro gcpro1;
733     GCPRO1 (hash_table);
734
735     /* And fill it with data.  */
736     while (!NILP (data))
737       {
738         Lisp_Object key, value;
739         key   = XCAR (data); data = XCDR (data);
740         value = XCAR (data); data = XCDR (data);
741         Fputhash (key, value, hash_table);
742       }
743     UNGCPRO;
744   }
745
746   return hash_table;
747 }
748
749 static void
750 structure_type_create_hash_table_structure_name (Lisp_Object structure_name)
751 {
752   struct structure_type *st;
753
754   st = define_structure_type (structure_name, 0, hash_table_instantiate);
755   define_structure_type_keyword (st, Qtest, hash_table_test_validate);
756   define_structure_type_keyword (st, Qsize, hash_table_size_validate);
757   define_structure_type_keyword (st, Qrehash_size, hash_table_rehash_size_validate);
758   define_structure_type_keyword (st, Qrehash_threshold, hash_table_rehash_threshold_validate);
759   define_structure_type_keyword (st, Qweakness, hash_table_weakness_validate);
760   define_structure_type_keyword (st, Qdata, hash_table_data_validate);
761
762   /* obsolete as of 19990901 in xemacs-21.2 */
763   define_structure_type_keyword (st, Qtype, hash_table_weakness_validate);
764 }
765
766 /* Create a built-in Lisp structure type named `hash-table'.
767    We make #s(hashtable ...) equivalent to #s(hash-table ...),
768    for backward compatibility.
769    This is called from emacs.c.  */
770 void
771 structure_type_create_hash_table (void)
772 {
773   structure_type_create_hash_table_structure_name (Qhash_table);
774   structure_type_create_hash_table_structure_name (Qhashtable); /* compat */
775 }
776
777 \f
778 /************************************************************************/
779 /*              Definition of Lisp-visible methods                      */
780 /************************************************************************/
781
782 DEFUN ("hash-table-p", Fhash_table_p, 1, 1, 0, /*
783 Return t if OBJECT is a hash table, else nil.
784 */
785        (object))
786 {
787   return HASH_TABLEP (object) ? Qt : Qnil;
788 }
789
790 DEFUN ("make-hash-table", Fmake_hash_table, 0, MANY, 0, /*
791 Return a new empty hash table object.
792 Use Common Lisp style keywords to specify hash table properties.
793  (make-hash-table &key test size rehash-size rehash-threshold weakness)
794
795 Keyword :test can be `eq', `eql' (default) or `equal'.
796 Comparison between keys is done using this function.
797 If speed is important, consider using `eq'.
798 When storing strings in the hash table, you will likely need to use `equal'.
799
800 Keyword :size specifies the number of keys likely to be inserted.
801 This number of entries can be inserted without enlarging the hash table.
802
803 Keyword :rehash-size must be a float greater than 1.0, and specifies
804 the factor by which to increase the size of the hash table when enlarging.
805
806 Keyword :rehash-threshold must be a float between 0.0 and 1.0,
807 and specifies the load factor of the hash table which triggers enlarging.
808
809 Non-standard keyword :weakness can be `nil' (default), `t', `key', `value'
810 or `key-value'.
811
812 A weak hash table is one whose pointers do not count as GC referents:
813 for any key-value pair in the hash table, if the only remaining pointer
814 to either the key or the value is in a weak hash table, then the pair
815 will be removed from the hash table, and the key and value collected.
816 A non-weak hash table (or any other pointer) would prevent the object
817 from being collected.
818
819 A key-weak hash table is similar to a fully-weak hash table except that
820 a key-value pair will be removed only if the key remains unmarked
821 outside of weak hash tables.  The pair will remain in the hash table if
822 the key is pointed to by something other than a weak hash table, even
823 if the value is not.
824
825 A value-weak hash table is similar to a fully-weak hash table except
826 that a key-value pair will be removed only if the value remains
827 unmarked outside of weak hash tables.  The pair will remain in the
828 hash table if the value is pointed to by something other than a weak
829 hash table, even if the key is not.
830
831 A key-value-weak hash table is similar to a fully-weak hash table except
832 that a key-value pair will be removed only if the value and the key remain
833 unmarked outside of weak hash tables.  The pair will remain in the
834 hash table if the value or key are pointed to by something other than a weak
835 hash table, even if the other is not.
836 */
837        (int nargs, Lisp_Object *args))
838 {
839   int i = 0;
840   Lisp_Object test             = Qnil;
841   Lisp_Object size             = Qnil;
842   Lisp_Object rehash_size      = Qnil;
843   Lisp_Object rehash_threshold = Qnil;
844   Lisp_Object weakness         = Qnil;
845
846   while (i + 1 < nargs)
847     {
848       Lisp_Object keyword = args[i++];
849       Lisp_Object value   = args[i++];
850
851       if      (EQ (keyword, Q_test))             test             = value;
852       else if (EQ (keyword, Q_size))             size             = value;
853       else if (EQ (keyword, Q_rehash_size))      rehash_size      = value;
854       else if (EQ (keyword, Q_rehash_threshold)) rehash_threshold = value;
855       else if (EQ (keyword, Q_weakness))         weakness         = value;
856       else if (EQ (keyword, Q_type))/*obsolete*/ weakness         = value;
857       else signal_simple_error ("Invalid hash table property keyword", keyword);
858     }
859
860   if (i < nargs)
861     signal_simple_error ("Hash table property requires a value", args[i]);
862
863 #define VALIDATE_VAR(var) \
864 if (!NILP (var)) hash_table_##var##_validate (Q##var, var, ERROR_ME);
865
866   VALIDATE_VAR (test);
867   VALIDATE_VAR (size);
868   VALIDATE_VAR (rehash_size);
869   VALIDATE_VAR (rehash_threshold);
870   VALIDATE_VAR (weakness);
871
872   return make_general_lisp_hash_table
873     (decode_hash_table_test (test),
874      decode_hash_table_size (size),
875      decode_hash_table_rehash_size (rehash_size),
876      decode_hash_table_rehash_threshold (rehash_threshold),
877      decode_hash_table_weakness (weakness));
878 }
879
880 DEFUN ("copy-hash-table", Fcopy_hash_table, 1, 1, 0, /*
881 Return a new hash table containing the same keys and values as HASH-TABLE.
882 The keys and values will not themselves be copied.
883 */
884        (hash_table))
885 {
886   const Lisp_Hash_Table *ht_old = xhash_table (hash_table);
887   Lisp_Hash_Table *ht = alloc_lcrecord_type (Lisp_Hash_Table, &lrecord_hash_table);
888
889   copy_lcrecord (ht, ht_old);
890
891   ht->hentries = xnew_array (hentry, ht_old->size + 1);
892   memcpy (ht->hentries, ht_old->hentries, (ht_old->size + 1) * sizeof (hentry));
893
894   XSETHASH_TABLE (hash_table, ht);
895
896   if (! EQ (ht->next_weak, Qunbound))
897     {
898       ht->next_weak = Vall_weak_hash_tables;
899       Vall_weak_hash_tables = hash_table;
900     }
901
902   return hash_table;
903 }
904
905 static void
906 resize_hash_table (Lisp_Hash_Table *ht, size_t new_size)
907 {
908   hentry *old_entries, *new_entries, *sentinel, *e;
909   size_t old_size;
910
911   old_size = ht->size;
912   ht->size = new_size;
913
914   old_entries = ht->hentries;
915
916   ht->hentries = xnew_array_and_zero (hentry, new_size + 1);
917   new_entries = ht->hentries;
918
919   compute_hash_table_derived_values (ht);
920
921   for (e = old_entries, sentinel = e + old_size; e < sentinel; e++)
922     if (!HENTRY_CLEAR_P (e))
923       {
924         hentry *probe = new_entries + HASH_CODE (e->key, ht);
925         LINEAR_PROBING_LOOP (probe, new_entries, new_size)
926           ;
927         *probe = *e;
928       }
929
930   if (!DUMPEDP (old_entries))
931     xfree (old_entries);
932 }
933
934 /* After a hash table has been saved to disk and later restored by the
935    portable dumper, it contains the same objects, but their addresses
936    and thus their HASH_CODEs have changed. */
937 void
938 pdump_reorganize_hash_table (Lisp_Object hash_table)
939 {
940   const Lisp_Hash_Table *ht = xhash_table (hash_table);
941   hentry *new_entries = xnew_array_and_zero (hentry, ht->size + 1);
942   hentry *e, *sentinel;
943
944   for (e = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
945     if (!HENTRY_CLEAR_P (e))
946       {
947         hentry *probe = new_entries + HASH_CODE (e->key, ht);
948         LINEAR_PROBING_LOOP (probe, new_entries, ht->size)
949           ;
950         *probe = *e;
951       }
952
953   memcpy (ht->hentries, new_entries, ht->size * sizeof (hentry));
954
955   xfree (new_entries);
956 }
957
958 static void
959 enlarge_hash_table (Lisp_Hash_Table *ht)
960 {
961   size_t new_size =
962     hash_table_size ((size_t) ((double) ht->size * ht->rehash_size));
963   resize_hash_table (ht, new_size);
964 }
965
966 static hentry *
967 find_hentry (Lisp_Object key, const Lisp_Hash_Table *ht)
968 {
969   hash_table_test_function_t test_function = ht->test_function;
970   hentry *entries = ht->hentries;
971   hentry *probe = entries + HASH_CODE (key, ht);
972
973   LINEAR_PROBING_LOOP (probe, entries, ht->size)
974     if (KEYS_EQUAL_P (probe->key, key, test_function))
975       break;
976
977   return probe;
978 }
979
980 DEFUN ("gethash", Fgethash, 2, 3, 0, /*
981 Find hash value for KEY in HASH-TABLE.
982 If there is no corresponding value, return DEFAULT (which defaults to nil).
983 */
984        (key, hash_table, default_))
985 {
986   const Lisp_Hash_Table *ht = xhash_table (hash_table);
987   hentry *e = find_hentry (key, ht);
988
989   return HENTRY_CLEAR_P (e) ? default_ : e->value;
990 }
991
992 DEFUN ("puthash", Fputhash, 3, 3, 0, /*
993 Hash KEY to VALUE in HASH-TABLE.
994 */
995        (key, value, hash_table))
996 {
997   Lisp_Hash_Table *ht = xhash_table (hash_table);
998   hentry *e = find_hentry (key, ht);
999
1000   if (!HENTRY_CLEAR_P (e))
1001     return e->value = value;
1002
1003   e->key   = key;
1004   e->value = value;
1005
1006   if (++ht->count >= ht->rehash_count)
1007     enlarge_hash_table (ht);
1008
1009   return value;
1010 }
1011
1012 /* Remove hentry pointed at by PROBE.
1013    Subsequent entries are removed and reinserted.
1014    We don't use tombstones - too wasteful.  */
1015 static void
1016 remhash_1 (Lisp_Hash_Table *ht, hentry *entries, hentry *probe)
1017 {
1018   size_t size = ht->size;
1019   CLEAR_HENTRY (probe);
1020   probe++;
1021   ht->count--;
1022
1023   LINEAR_PROBING_LOOP (probe, entries, size)
1024     {
1025       Lisp_Object key = probe->key;
1026       hentry *probe2 = entries + HASH_CODE (key, ht);
1027       LINEAR_PROBING_LOOP (probe2, entries, size)
1028         if (EQ (probe2->key, key))
1029           /* hentry at probe doesn't need to move. */
1030           goto continue_outer_loop;
1031       /* Move hentry from probe to new home at probe2. */
1032       *probe2 = *probe;
1033       CLEAR_HENTRY (probe);
1034     continue_outer_loop: continue;
1035     }
1036 }
1037
1038 DEFUN ("remhash", Fremhash, 2, 2, 0, /*
1039 Remove the entry for KEY from HASH-TABLE.
1040 Do nothing if there is no entry for KEY in HASH-TABLE.
1041 */
1042        (key, hash_table))
1043 {
1044   Lisp_Hash_Table *ht = xhash_table (hash_table);
1045   hentry *e = find_hentry (key, ht);
1046
1047   if (HENTRY_CLEAR_P (e))
1048     return Qnil;
1049
1050   remhash_1 (ht, ht->hentries, e);
1051   return Qt;
1052 }
1053
1054 DEFUN ("clrhash", Fclrhash, 1, 1, 0, /*
1055 Remove all entries from HASH-TABLE, leaving it empty.
1056 */
1057        (hash_table))
1058 {
1059   Lisp_Hash_Table *ht = xhash_table (hash_table);
1060   hentry *e, *sentinel;
1061
1062   for (e = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
1063     CLEAR_HENTRY (e);
1064   ht->count = 0;
1065
1066   return hash_table;
1067 }
1068
1069 /************************************************************************/
1070 /*                          Accessor Functions                          */
1071 /************************************************************************/
1072
1073 DEFUN ("hash-table-count", Fhash_table_count, 1, 1, 0, /*
1074 Return the number of entries in HASH-TABLE.
1075 */
1076        (hash_table))
1077 {
1078   return make_int (xhash_table (hash_table)->count);
1079 }
1080
1081 DEFUN ("hash-table-test", Fhash_table_test, 1, 1, 0, /*
1082 Return the test function of HASH-TABLE.
1083 This can be one of `eq', `eql' or `equal'.
1084 */
1085        (hash_table))
1086 {
1087   hash_table_test_function_t fun = xhash_table (hash_table)->test_function;
1088
1089   return (fun == lisp_object_eql_equal   ? Qeql   :
1090           fun == lisp_object_equal_equal ? Qequal :
1091           Qeq);
1092 }
1093
1094 DEFUN ("hash-table-size", Fhash_table_size, 1, 1, 0, /*
1095 Return the size of HASH-TABLE.
1096 This is the current number of slots in HASH-TABLE, whether occupied or not.
1097 */
1098        (hash_table))
1099 {
1100   return make_int (xhash_table (hash_table)->size);
1101 }
1102
1103 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size, 1, 1, 0, /*
1104 Return the current rehash size of HASH-TABLE.
1105 This is a float greater than 1.0; the factor by which HASH-TABLE
1106 is enlarged when the rehash threshold is exceeded.
1107 */
1108        (hash_table))
1109 {
1110   return make_float (xhash_table (hash_table)->rehash_size);
1111 }
1112
1113 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold, 1, 1, 0, /*
1114 Return the current rehash threshold of HASH-TABLE.
1115 This is a float between 0.0 and 1.0; the maximum `load factor' of HASH-TABLE,
1116 beyond which the HASH-TABLE is enlarged by rehashing.
1117 */
1118        (hash_table))
1119 {
1120   return make_float (xhash_table (hash_table)->rehash_threshold);
1121 }
1122
1123 DEFUN ("hash-table-weakness", Fhash_table_weakness, 1, 1, 0, /*
1124 Return the weakness of HASH-TABLE.
1125 This can be one of `nil', `t', `key' or `value'.
1126 */
1127        (hash_table))
1128 {
1129   switch (xhash_table (hash_table)->weakness)
1130     {
1131     case HASH_TABLE_WEAK:       return Qt;
1132     case HASH_TABLE_KEY_WEAK:   return Qkey;
1133     case HASH_TABLE_KEY_VALUE_WEAK:     return Qkey_value;
1134     case HASH_TABLE_VALUE_WEAK: return Qvalue;
1135     default:                    return Qnil;
1136     }
1137 }
1138
1139 /* obsolete as of 19990901 in xemacs-21.2 */
1140 DEFUN ("hash-table-type", Fhash_table_type, 1, 1, 0, /*
1141 Return the type of HASH-TABLE.
1142 This can be one of `non-weak', `weak', `key-weak' or `value-weak'.
1143 */
1144        (hash_table))
1145 {
1146   switch (xhash_table (hash_table)->weakness)
1147     {
1148     case HASH_TABLE_WEAK:       return Qweak;
1149     case HASH_TABLE_KEY_WEAK:   return Qkey_weak;
1150     case HASH_TABLE_KEY_VALUE_WEAK:     return Qkey_value_weak;
1151     case HASH_TABLE_VALUE_WEAK: return Qvalue_weak;
1152     default:                    return Qnon_weak;
1153     }
1154 }
1155
1156 /************************************************************************/
1157 /*                          Mapping Functions                           */
1158 /************************************************************************/
1159 DEFUN ("maphash", Fmaphash, 2, 2, 0, /*
1160 Map FUNCTION over entries in HASH-TABLE, calling it with two args,
1161 each key and value in HASH-TABLE.
1162
1163 FUNCTION may not modify HASH-TABLE, with the one exception that FUNCTION
1164 may remhash or puthash the entry currently being processed by FUNCTION.
1165 */
1166        (function, hash_table))
1167 {
1168   const Lisp_Hash_Table *ht = xhash_table (hash_table);
1169   const hentry *e, *sentinel;
1170
1171   for (e = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
1172     if (!HENTRY_CLEAR_P (e))
1173       {
1174         Lisp_Object args[3], key;
1175       again:
1176         key = e->key;
1177         args[0] = function;
1178         args[1] = key;
1179         args[2] = e->value;
1180         Ffuncall (countof (args), args);
1181         /* Has FUNCTION done a remhash? */
1182         if (!EQ (key, e->key) && !HENTRY_CLEAR_P (e))
1183           goto again;
1184       }
1185
1186   return Qnil;
1187 }
1188
1189 /* Map *C* function FUNCTION over the elements of a lisp hash table. */
1190 void
1191 elisp_maphash (maphash_function_t function,
1192                Lisp_Object hash_table, void *extra_arg)
1193 {
1194   const Lisp_Hash_Table *ht = XHASH_TABLE (hash_table);
1195   const hentry *e, *sentinel;
1196
1197   for (e = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
1198     if (!HENTRY_CLEAR_P (e))
1199       {
1200         Lisp_Object key;
1201       again:
1202         key = e->key;
1203         if (function (key, e->value, extra_arg))
1204           return;
1205         /* Has FUNCTION done a remhash? */
1206         if (!EQ (key, e->key) && !HENTRY_CLEAR_P (e))
1207           goto again;
1208       }
1209 }
1210
1211 /* Remove all elements of a lisp hash table satisfying *C* predicate PREDICATE. */
1212 void
1213 elisp_map_remhash (maphash_function_t predicate,
1214                    Lisp_Object hash_table, void *extra_arg)
1215 {
1216   Lisp_Hash_Table *ht = XHASH_TABLE (hash_table);
1217   hentry *e, *entries, *sentinel;
1218
1219   for (e = entries = ht->hentries, sentinel = e + ht->size; e < sentinel; e++)
1220     if (!HENTRY_CLEAR_P (e))
1221       {
1222       again:
1223         if (predicate (e->key, e->value, extra_arg))
1224           {
1225             remhash_1 (ht, entries, e);
1226             if (!HENTRY_CLEAR_P (e))
1227               goto again;
1228           }
1229       }
1230 }
1231
1232 \f
1233 /************************************************************************/
1234 /*                 garbage collecting weak hash tables                  */
1235 /************************************************************************/
1236 #define MARK_OBJ(obj) do {              \
1237   Lisp_Object mo_obj = (obj);           \
1238   if (!marked_p (mo_obj))               \
1239     {                                   \
1240       mark_object (mo_obj);             \
1241       did_mark = 1;                     \
1242     }                                   \
1243 } while (0)
1244
1245
1246 /* Complete the marking for semi-weak hash tables. */
1247 int
1248 finish_marking_weak_hash_tables (void)
1249 {
1250   Lisp_Object hash_table;
1251   int did_mark = 0;
1252
1253   for (hash_table = Vall_weak_hash_tables;
1254        !NILP (hash_table);
1255        hash_table = XHASH_TABLE (hash_table)->next_weak)
1256     {
1257       const Lisp_Hash_Table *ht = XHASH_TABLE (hash_table);
1258       const hentry *e = ht->hentries;
1259       const hentry *sentinel = e + ht->size;
1260
1261       if (! marked_p (hash_table))
1262         /* The hash table is probably garbage.  Ignore it. */
1263         continue;
1264
1265       /* Now, scan over all the pairs.  For all pairs that are
1266          half-marked, we may need to mark the other half if we're
1267          keeping this pair. */
1268       switch (ht->weakness)
1269         {
1270         case HASH_TABLE_KEY_WEAK:
1271           for (; e < sentinel; e++)
1272             if (!HENTRY_CLEAR_P (e))
1273               if (marked_p (e->key))
1274                 MARK_OBJ (e->value);
1275           break;
1276
1277         case HASH_TABLE_VALUE_WEAK:
1278           for (; e < sentinel; e++)
1279             if (!HENTRY_CLEAR_P (e))
1280               if (marked_p (e->value))
1281                 MARK_OBJ (e->key);
1282           break;
1283
1284         case HASH_TABLE_KEY_VALUE_WEAK:
1285           for (; e < sentinel; e++)
1286             if (!HENTRY_CLEAR_P (e))
1287               {
1288                 if (marked_p (e->value))
1289                   MARK_OBJ (e->key);
1290                 else if (marked_p (e->key))
1291                   MARK_OBJ (e->value);
1292               }
1293           break;
1294
1295         case HASH_TABLE_KEY_CAR_WEAK:
1296           for (; e < sentinel; e++)
1297             if (!HENTRY_CLEAR_P (e))
1298               if (!CONSP (e->key) || marked_p (XCAR (e->key)))
1299                 {
1300                   MARK_OBJ (e->key);
1301                   MARK_OBJ (e->value);
1302                 }
1303           break;
1304
1305         case HASH_TABLE_VALUE_CAR_WEAK:
1306           for (; e < sentinel; e++)
1307             if (!HENTRY_CLEAR_P (e))
1308               if (!CONSP (e->value) || marked_p (XCAR (e->value)))
1309                 {
1310                   MARK_OBJ (e->key);
1311                   MARK_OBJ (e->value);
1312                 }
1313           break;
1314
1315         default:
1316           break;
1317         }
1318     }
1319
1320   return did_mark;
1321 }
1322
1323 void
1324 prune_weak_hash_tables (void)
1325 {
1326   Lisp_Object hash_table, prev = Qnil;
1327   for (hash_table = Vall_weak_hash_tables;
1328        !NILP (hash_table);
1329        hash_table = XHASH_TABLE (hash_table)->next_weak)
1330     {
1331       if (! marked_p (hash_table))
1332         {
1333           /* This hash table itself is garbage.  Remove it from the list. */
1334           if (NILP (prev))
1335             Vall_weak_hash_tables = XHASH_TABLE (hash_table)->next_weak;
1336           else
1337             XHASH_TABLE (prev)->next_weak = XHASH_TABLE (hash_table)->next_weak;
1338         }
1339       else
1340         {
1341           /* Now, scan over all the pairs.  Remove all of the pairs
1342              in which the key or value, or both, is unmarked
1343              (depending on the weakness of the hash table). */
1344           Lisp_Hash_Table *ht = XHASH_TABLE (hash_table);
1345           hentry *entries = ht->hentries;
1346           hentry *sentinel = entries + ht->size;
1347           hentry *e;
1348
1349           for (e = entries; e < sentinel; e++)
1350             if (!HENTRY_CLEAR_P (e))
1351               {
1352               again:
1353                 if (!marked_p (e->key) || !marked_p (e->value))
1354                   {
1355                     remhash_1 (ht, entries, e);
1356                     if (!HENTRY_CLEAR_P (e))
1357                       goto again;
1358                   }
1359               }
1360
1361           prev = hash_table;
1362         }
1363     }
1364 }
1365
1366 /* Return a hash value for an array of Lisp_Objects of size SIZE. */
1367
1368 hashcode_t
1369 internal_array_hash (Lisp_Object *arr, int size, int depth)
1370 {
1371   int i;
1372   hashcode_t hash = 0;
1373   depth++;
1374
1375   if (size <= 5)
1376     {
1377       for (i = 0; i < size; i++)
1378         hash = HASH2 (hash, internal_hash (arr[i], depth));
1379       return hash;
1380     }
1381
1382   /* just pick five elements scattered throughout the array.
1383      A slightly better approach would be to offset by some
1384      noise factor from the points chosen below. */
1385   for (i = 0; i < 5; i++)
1386     hash = HASH2 (hash, internal_hash (arr[i*size/5], depth));
1387
1388   return hash;
1389 }
1390
1391 /* Return a hash value for a Lisp_Object.  This is for use when hashing
1392    objects with the comparison being `equal' (for `eq', you can just
1393    use the Lisp_Object itself as the hash value).  You need to make a
1394    tradeoff between the speed of the hash function and how good the
1395    hashing is.  In particular, the hash function needs to be FAST,
1396    so you can't just traipse down the whole tree hashing everything
1397    together.  Most of the time, objects will differ in the first
1398    few elements you hash.  Thus, we only go to a short depth (5)
1399    and only hash at most 5 elements out of a vector.  Theoretically
1400    we could still take 5^5 time (a big big number) to compute a
1401    hash, but practically this won't ever happen. */
1402
1403 hashcode_t
1404 internal_hash (Lisp_Object obj, int depth)
1405 {
1406   if (depth > 5)
1407     return 0;
1408   if (CONSP (obj))
1409     {
1410       /* no point in worrying about tail recursion, since we're not
1411          going very deep */
1412       return HASH2 (internal_hash (XCAR (obj), depth + 1),
1413                     internal_hash (XCDR (obj), depth + 1));
1414     }
1415   if (STRINGP (obj))
1416     {
1417       return hash_string (XSTRING_DATA (obj), XSTRING_LENGTH (obj));
1418     }
1419   if (LRECORDP (obj))
1420     {
1421       const struct lrecord_implementation
1422         *imp = XRECORD_LHEADER_IMPLEMENTATION (obj);
1423       if (imp->hash)
1424         return imp->hash (obj, depth);
1425     }
1426
1427   return LISP_HASH (obj);
1428 }
1429
1430 DEFUN ("sxhash", Fsxhash, 1, 1, 0, /*
1431 Return a hash value for OBJECT.
1432 (equal obj1 obj2) implies (= (sxhash obj1) (sxhash obj2)).
1433 */
1434        (object))
1435 {
1436   return make_int (internal_hash (object, 0));
1437 }
1438
1439 #if 0
1440 xxDEFUN ("internal-hash-value", Finternal_hash_value, 1, 1, 0, /*
1441 Hash value of OBJECT.  For debugging.
1442 The value is returned as (HIGH . LOW).
1443 */
1444        (object))
1445 {
1446   /* This function is pretty 32bit-centric. */
1447   hashcode_t hash = internal_hash (object, 0);
1448   return Fcons (hash >> 16, hash & 0xffff);
1449 }
1450 #endif
1451
1452 \f
1453 /************************************************************************/
1454 /*                            initialization                            */
1455 /************************************************************************/
1456
1457 void
1458 syms_of_elhash (void)
1459 {
1460   INIT_LRECORD_IMPLEMENTATION (hash_table);
1461
1462   DEFSUBR (Fhash_table_p);
1463   DEFSUBR (Fmake_hash_table);
1464   DEFSUBR (Fcopy_hash_table);
1465   DEFSUBR (Fgethash);
1466   DEFSUBR (Fremhash);
1467   DEFSUBR (Fputhash);
1468   DEFSUBR (Fclrhash);
1469   DEFSUBR (Fmaphash);
1470   DEFSUBR (Fhash_table_count);
1471   DEFSUBR (Fhash_table_test);
1472   DEFSUBR (Fhash_table_size);
1473   DEFSUBR (Fhash_table_rehash_size);
1474   DEFSUBR (Fhash_table_rehash_threshold);
1475   DEFSUBR (Fhash_table_weakness);
1476   DEFSUBR (Fhash_table_type); /* obsolete */
1477   DEFSUBR (Fsxhash);
1478 #if 0
1479   DEFSUBR (Finternal_hash_value);
1480 #endif
1481
1482   defsymbol (&Qhash_tablep, "hash-table-p");
1483   defsymbol (&Qhash_table, "hash-table");
1484   defsymbol (&Qhashtable, "hashtable");
1485   defsymbol (&Qweakness, "weakness");
1486   defsymbol (&Qvalue, "value");
1487   defsymbol (&Qkey_value, "key-value");
1488   defsymbol (&Qrehash_size, "rehash-size");
1489   defsymbol (&Qrehash_threshold, "rehash-threshold");
1490
1491   defsymbol (&Qweak, "weak");             /* obsolete */
1492   defsymbol (&Qkey_weak, "key-weak");     /* obsolete */
1493   defsymbol (&Qkey_value_weak, "key-value-weak");     /* obsolete */
1494   defsymbol (&Qvalue_weak, "value-weak"); /* obsolete */
1495   defsymbol (&Qnon_weak, "non-weak");     /* obsolete */
1496
1497   defkeyword (&Q_test, ":test");
1498   defkeyword (&Q_size, ":size");
1499   defkeyword (&Q_rehash_size, ":rehash-size");
1500   defkeyword (&Q_rehash_threshold, ":rehash-threshold");
1501   defkeyword (&Q_weakness, ":weakness");
1502   defkeyword (&Q_type, ":type"); /* obsolete */
1503 }
1504
1505 void
1506 vars_of_elhash (void)
1507 {
1508   /* This must NOT be staticpro'd */
1509   Vall_weak_hash_tables = Qnil;
1510   pdump_wire_list (&Vall_weak_hash_tables);
1511 }