This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Macro for freeing meta->mro_linear_*
[perl5.git] / mro.c
1 /*    mro.c
2  *
3  *    Copyright (c) 2007 Brandon L Black
4  *    Copyright (c) 2007, 2008 Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * 'Which order shall we go in?' said Frodo.  'Eldest first, or quickest first?
13  *  You'll be last either way, Master Peregrin.'
14  *
15  *     [p.101 of _The Lord of the Rings_, I/iii: "A Conspiracy Unmasked"]
16  */
17
18 /*
19 =head1 MRO Functions
20
21 These functions are related to the method resolution order of perl classes
22
23 =cut
24 */
25
26 #include "EXTERN.h"
27 #define PERL_IN_MRO_C
28 #include "perl.h"
29
30 static const struct mro_alg dfs_alg =
31     {S_mro_get_linear_isa_dfs, "dfs", 3, 0, 0};
32
33 SV *
34 Perl_mro_get_private_data(pTHX_ struct mro_meta *const smeta,
35                           const struct mro_alg *const which)
36 {
37     SV **data;
38     PERL_ARGS_ASSERT_MRO_GET_PRIVATE_DATA;
39
40     data = (SV **)Perl_hv_common(aTHX_ smeta->mro_linear_all, NULL,
41                                  which->name, which->length, which->kflags,
42                                  HV_FETCH_JUST_SV, NULL, which->hash);
43     if (!data)
44         return NULL;
45
46     /* If we've been asked to look up the private data for the current MRO, then
47        cache it.  */
48     if (smeta->mro_which == which)
49         smeta->mro_linear_current = *data;
50
51     return *data;
52 }
53
54 SV *
55 Perl_mro_set_private_data(pTHX_ struct mro_meta *const smeta,
56                           const struct mro_alg *const which, SV *const data)
57 {
58     PERL_ARGS_ASSERT_MRO_SET_PRIVATE_DATA;
59
60     if (!smeta->mro_linear_all) {
61         if (smeta->mro_which == which) {
62             /* If all we need to store is the current MRO's data, then don't use
63                memory on a hash with 1 element - store it direct, and signal
64                this by leaving the would-be-hash NULL.  */
65             smeta->mro_linear_current = data;
66             return data;
67         } else {
68             HV *const hv = newHV();
69             /* Start with 2 buckets. It's unlikely we'll need more. */
70             HvMAX(hv) = 1;      
71             smeta->mro_linear_all = hv;
72
73             if (smeta->mro_linear_current) {
74                 /* If we were storing something directly, put it in the hash
75                    before we lose it. */
76                 Perl_mro_set_private_data(aTHX_ smeta, smeta->mro_which, 
77                                           smeta->mro_linear_current);
78             }
79         }
80     }
81
82     /* We get here if we're storing more than one linearisation for this stash,
83        or the linearisation we are storing is not that if its current MRO.  */
84
85     if (smeta->mro_which == which) {
86         /* If we've been asked to store the private data for the current MRO,
87            then cache it.  */
88         smeta->mro_linear_current = data;
89     }
90
91     if (!Perl_hv_common(aTHX_ smeta->mro_linear_all, NULL,
92                         which->name, which->length, which->kflags,
93                         HV_FETCH_ISSTORE, data, which->hash)) {
94         Perl_croak(aTHX_ "panic: hv_store() failed in set_mro_private_data() "
95                    "for '%.*s' %d", (int) which->length, which->name,
96                    which->kflags);
97     }
98
99     return data;
100 }
101
102 const struct mro_alg *
103 Perl_mro_get_from_name(pTHX_ SV *name) {
104     SV **data;
105
106     PERL_ARGS_ASSERT_MRO_GET_FROM_NAME;
107
108     data = (SV **)Perl_hv_common(aTHX_ PL_registered_mros, name, NULL, 0, 0,
109                                  HV_FETCH_JUST_SV, NULL, 0);
110     if (!data)
111         return NULL;
112     assert(SvTYPE(*data) == SVt_IV);
113     assert(SvIOK(*data));
114     return INT2PTR(const struct mro_alg *, SvUVX(*data));
115 }
116
117 void
118 Perl_mro_register(pTHX_ const struct mro_alg *mro) {
119     SV *wrapper = newSVuv(PTR2UV(mro));
120
121     PERL_ARGS_ASSERT_MRO_REGISTER;
122
123     
124     if (!Perl_hv_common(aTHX_ PL_registered_mros, NULL,
125                         mro->name, mro->length, mro->kflags,
126                         HV_FETCH_ISSTORE, wrapper, mro->hash)) {
127         SvREFCNT_dec(wrapper);
128         Perl_croak(aTHX_ "panic: hv_store() failed in mro_register() "
129                    "for '%.*s' %d", (int) mro->length, mro->name, mro->kflags);
130     }
131 }
132
133 struct mro_meta*
134 Perl_mro_meta_init(pTHX_ HV* stash)
135 {
136     struct mro_meta* newmeta;
137
138     PERL_ARGS_ASSERT_MRO_META_INIT;
139     assert(HvAUX(stash));
140     assert(!(HvAUX(stash)->xhv_mro_meta));
141     Newxz(newmeta, 1, struct mro_meta);
142     HvAUX(stash)->xhv_mro_meta = newmeta;
143     newmeta->cache_gen = 1;
144     newmeta->pkg_gen = 1;
145     newmeta->mro_which = &dfs_alg;
146
147     return newmeta;
148 }
149
150 #if defined(USE_ITHREADS)
151
152 /* for sv_dup on new threads */
153 struct mro_meta*
154 Perl_mro_meta_dup(pTHX_ struct mro_meta* smeta, CLONE_PARAMS* param)
155 {
156     struct mro_meta* newmeta;
157
158     PERL_ARGS_ASSERT_MRO_META_DUP;
159
160     Newx(newmeta, 1, struct mro_meta);
161     Copy(smeta, newmeta, 1, struct mro_meta);
162
163     if (newmeta->mro_linear_all) {
164         newmeta->mro_linear_all
165             = MUTABLE_HV(sv_dup_inc((const SV *)newmeta->mro_linear_all, param));
166         /* This is just acting as a shortcut pointer, and will be automatically
167            updated on the first get.  */
168         newmeta->mro_linear_current = NULL;
169     } else if (newmeta->mro_linear_current) {
170         /* Only the current MRO is stored, so this owns the data.  */
171         newmeta->mro_linear_current
172             = sv_dup_inc((const SV *)newmeta->mro_linear_current, param);
173     }
174
175     if (newmeta->mro_nextmethod)
176         newmeta->mro_nextmethod
177             = MUTABLE_HV(sv_dup_inc((const SV *)newmeta->mro_nextmethod, param));
178     if (newmeta->isa)
179         newmeta->isa
180             = MUTABLE_HV(sv_dup_inc((const SV *)newmeta->isa, param));
181
182     return newmeta;
183 }
184
185 #endif /* USE_ITHREADS */
186
187 /*
188 =for apidoc mro_get_linear_isa_dfs
189
190 Returns the Depth-First Search linearization of @ISA
191 the given stash.  The return value is a read-only AV*.
192 C<level> should be 0 (it is used internally in this
193 function's recursion).
194
195 You are responsible for C<SvREFCNT_inc()> on the
196 return value if you plan to store it anywhere
197 semi-permanently (otherwise it might be deleted
198 out from under you the next time the cache is
199 invalidated).
200
201 =cut
202 */
203 static AV*
204 S_mro_get_linear_isa_dfs(pTHX_ HV *stash, U32 level)
205 {
206     AV* retval;
207     GV** gvp;
208     GV* gv;
209     AV* av;
210     const HEK* stashhek;
211     struct mro_meta* meta;
212     SV *our_name;
213     HV *stored = NULL;
214
215     PERL_ARGS_ASSERT_MRO_GET_LINEAR_ISA_DFS;
216     assert(HvAUX(stash));
217
218     stashhek
219      = HvAUX(stash)->xhv_name && HvENAME_HEK_NN(stash)
220         ? HvENAME_HEK_NN(stash)
221         : HvNAME_HEK(stash);
222
223     if (!stashhek)
224       Perl_croak(aTHX_ "Can't linearize anonymous symbol table");
225
226     if (level > 100)
227         Perl_croak(aTHX_ "Recursive inheritance detected in package '%s'",
228                    HEK_KEY(stashhek));
229
230     meta = HvMROMETA(stash);
231
232     /* return cache if valid */
233     if((retval = MUTABLE_AV(MRO_GET_PRIVATE_DATA(meta, &dfs_alg)))) {
234         return retval;
235     }
236
237     /* not in cache, make a new one */
238
239     retval = MUTABLE_AV(sv_2mortal(MUTABLE_SV(newAV())));
240     /* We use this later in this function, but don't need a reference to it
241        beyond the end of this function, so reference count is fine.  */
242     our_name = newSVhek(stashhek);
243     av_push(retval, our_name); /* add ourselves at the top */
244
245     /* fetch our @ISA */
246     gvp = (GV**)hv_fetchs(stash, "ISA", FALSE);
247     av = (gvp && (gv = *gvp) && isGV_with_GP(gv)) ? GvAV(gv) : NULL;
248
249     /* "stored" is used to keep track of all of the classnames we have added to
250        the MRO so far, so we can do a quick exists check and avoid adding
251        duplicate classnames to the MRO as we go.
252        It's then retained to be re-used as a fast lookup for ->isa(), by adding
253        our own name and "UNIVERSAL" to it.  */
254
255     if(av && AvFILLp(av) >= 0) {
256
257         SV **svp = AvARRAY(av);
258         I32 items = AvFILLp(av) + 1;
259
260         /* foreach(@ISA) */
261         while (items--) {
262             SV* const sv = *svp++;
263             HV* const basestash = gv_stashsv(sv, 0);
264             SV *const *subrv_p;
265             I32 subrv_items;
266
267             if (!basestash) {
268                 /* if no stash exists for this @ISA member,
269                    simply add it to the MRO and move on */
270                 subrv_p = &sv;
271                 subrv_items = 1;
272             }
273             else {
274                 /* otherwise, recurse into ourselves for the MRO
275                    of this @ISA member, and append their MRO to ours.
276                    The recursive call could throw an exception, which
277                    has memory management implications here, hence the use of
278                    the mortal.  */
279                 const AV *const subrv
280                     = mro_get_linear_isa_dfs(basestash, level + 1);
281
282                 subrv_p = AvARRAY(subrv);
283                 subrv_items = AvFILLp(subrv) + 1;
284             }
285             if (stored) {
286                 while(subrv_items--) {
287                     SV *const subsv = *subrv_p++;
288                     /* LVALUE fetch will create a new undefined SV if necessary
289                      */
290                     HE *const he = hv_fetch_ent(stored, subsv, 1, 0);
291                     assert(he);
292                     if(HeVAL(he) != &PL_sv_undef) {
293                         /* It was newly created.  Steal it for our new SV, and
294                            replace it in the hash with the "real" thing.  */
295                         SV *const val = HeVAL(he);
296                         HEK *const key = HeKEY_hek(he);
297
298                         HeVAL(he) = &PL_sv_undef;
299                         /* Save copying by making a shared hash key scalar. We
300                            inline this here rather than calling
301                            Perl_newSVpvn_share because we already have the
302                            scalar, and we already have the hash key.  */
303                         assert(SvTYPE(val) == SVt_NULL);
304                         sv_upgrade(val, SVt_PV);
305                         SvPV_set(val, HEK_KEY(share_hek_hek(key)));
306                         SvCUR_set(val, HEK_LEN(key));
307                         SvREADONLY_on(val);
308                         SvFAKE_on(val);
309                         SvPOK_on(val);
310                         if (HEK_UTF8(key))
311                             SvUTF8_on(val);
312
313                         av_push(retval, val);
314                     }
315                 }
316             } else {
317                 /* We are the first (or only) parent. We can short cut the
318                    complexity above, because our @ISA is simply us prepended
319                    to our parent's @ISA, and our ->isa cache is simply our
320                    parent's, with our name added.  */
321                 /* newSVsv() is slow. This code is only faster if we can avoid
322                    it by ensuring that SVs in the arrays are shared hash key
323                    scalar SVs, because we can "copy" them very efficiently.
324                    Although to be fair, we can't *ensure* this, as a reference
325                    to the internal array is returned by mro::get_linear_isa(),
326                    so we'll have to be defensive just in case someone faffed
327                    with it.  */
328                 if (basestash) {
329                     SV **svp;
330                     stored = MUTABLE_HV(sv_2mortal((SV*)newHVhv(HvMROMETA(basestash)->isa)));
331                     av_extend(retval, subrv_items);
332                     AvFILLp(retval) = subrv_items;
333                     svp = AvARRAY(retval);
334                     while(subrv_items--) {
335                         SV *const val = *subrv_p++;
336                         *++svp = SvIsCOW_shared_hash(val)
337                             ? newSVhek(SvSHARED_HEK_FROM_PV(SvPVX(val)))
338                             : newSVsv(val);
339                     }
340                 } else {
341                     /* They have no stash.  So create ourselves an ->isa cache
342                        as if we'd copied it from what theirs should be.  */
343                     stored = MUTABLE_HV(sv_2mortal(MUTABLE_SV(newHV())));
344                     (void) hv_store(stored, "UNIVERSAL", 9, &PL_sv_undef, 0);
345                     av_push(retval,
346                             newSVhek(HeKEY_hek(hv_store_ent(stored, sv,
347                                                             &PL_sv_undef, 0))));
348                 }
349             }
350         }
351     } else {
352         /* We have no parents.  */
353         stored = MUTABLE_HV(sv_2mortal(MUTABLE_SV(newHV())));
354         (void) hv_store(stored, "UNIVERSAL", 9, &PL_sv_undef, 0);
355     }
356
357     (void) hv_store_ent(stored, our_name, &PL_sv_undef, 0);
358
359     SvREFCNT_inc_simple_void_NN(stored);
360     SvTEMP_off(stored);
361     SvREADONLY_on(stored);
362
363     meta->isa = stored;
364
365     /* now that we're past the exception dangers, grab our own reference to
366        the AV we're about to use for the result. The reference owned by the
367        mortals' stack will be released soon, so everything will balance.  */
368     SvREFCNT_inc_simple_void_NN(retval);
369     SvTEMP_off(retval);
370
371     /* we don't want anyone modifying the cache entry but us,
372        and we do so by replacing it completely */
373     SvREADONLY_on(retval);
374
375     return MUTABLE_AV(Perl_mro_set_private_data(aTHX_ meta, &dfs_alg,
376                                                 MUTABLE_SV(retval)));
377 }
378
379 /*
380 =for apidoc mro_get_linear_isa
381
382 Returns either C<mro_get_linear_isa_c3> or
383 C<mro_get_linear_isa_dfs> for the given stash,
384 dependant upon which MRO is in effect
385 for that stash.  The return value is a
386 read-only AV*.
387
388 You are responsible for C<SvREFCNT_inc()> on the
389 return value if you plan to store it anywhere
390 semi-permanently (otherwise it might be deleted
391 out from under you the next time the cache is
392 invalidated).
393
394 =cut
395 */
396 AV*
397 Perl_mro_get_linear_isa(pTHX_ HV *stash)
398 {
399     struct mro_meta* meta;
400     AV *isa;
401
402     PERL_ARGS_ASSERT_MRO_GET_LINEAR_ISA;
403     if(!SvOOK(stash))
404         Perl_croak(aTHX_ "Can't linearize anonymous symbol table");
405
406     meta = HvMROMETA(stash);
407     if (!meta->mro_which)
408         Perl_croak(aTHX_ "panic: invalid MRO!");
409     isa = meta->mro_which->resolve(aTHX_ stash, 0);
410
411     if (!meta->isa) {
412             HV *const isa_hash = newHV();
413             /* Linearisation didn't build it for us, so do it here.  */
414             SV *const *svp = AvARRAY(isa);
415             SV *const *const svp_end = svp + AvFILLp(isa) + 1;
416             const HEK *canon_name = HvENAME_HEK(stash);
417             if (!canon_name) canon_name = HvNAME_HEK(stash);
418
419             while (svp < svp_end) {
420                 (void) hv_store_ent(isa_hash, *svp++, &PL_sv_undef, 0);
421             }
422
423             (void) hv_common(isa_hash, NULL, HEK_KEY(canon_name),
424                              HEK_LEN(canon_name), HEK_FLAGS(canon_name),
425                              HV_FETCH_ISSTORE, &PL_sv_undef,
426                              HEK_HASH(canon_name));
427             (void) hv_store(isa_hash, "UNIVERSAL", 9, &PL_sv_undef, 0);
428
429             SvREADONLY_on(isa_hash);
430
431             meta->isa = isa_hash;
432     }
433
434     return isa;
435 }
436
437 /*
438 =for apidoc mro_isa_changed_in
439
440 Takes the necessary steps (cache invalidations, mostly)
441 when the @ISA of the given package has changed.  Invoked
442 by the C<setisa> magic, should not need to invoke directly.
443
444 =cut
445 */
446
447 /* Macro to avoid repeating the code three times. */
448 #define CLEAR_LINEAR(mEta)                                     \
449     if (mEta->mro_linear_all) {                                 \
450         SvREFCNT_dec(MUTABLE_SV(mEta->mro_linear_all));          \
451         mEta->mro_linear_all = NULL;                              \
452         /* This is just acting as a shortcut pointer.  */          \
453         mEta->mro_linear_current = NULL;                            \
454     } else if (mEta->mro_linear_current) {                           \
455         /* Only the current MRO is stored, so this owns the data.  */ \
456         SvREFCNT_dec(mEta->mro_linear_current);                        \
457         mEta->mro_linear_current = NULL;                                \
458     }
459
460 void
461 Perl_mro_isa_changed_in(pTHX_ HV* stash)
462 {
463     dVAR;
464     HV* isarev;
465     AV* linear_mro;
466     HE* iter;
467     SV** svp;
468     I32 items;
469     bool is_universal;
470     struct mro_meta * meta;
471     HV *isa = NULL;
472
473     const char * const stashname = HvENAME_get(stash);
474     const STRLEN stashname_len = HvENAMELEN_get(stash);
475
476     PERL_ARGS_ASSERT_MRO_ISA_CHANGED_IN;
477
478     if(!stashname)
479         Perl_croak(aTHX_ "Can't call mro_isa_changed_in() on anonymous symbol table");
480
481
482     /* wipe out the cached linearizations for this stash */
483     meta = HvMROMETA(stash);
484     CLEAR_LINEAR(meta);
485     if (meta->isa) {
486         /* Steal it for our own purposes. */
487         isa = (HV *)sv_2mortal((SV *)meta->isa);
488         meta->isa = NULL;
489     }
490
491     /* Inc the package generation, since our @ISA changed */
492     meta->pkg_gen++;
493
494     /* Wipe the global method cache if this package
495        is UNIVERSAL or one of its parents */
496
497     svp = hv_fetch(PL_isarev, stashname, stashname_len, 0);
498     isarev = svp ? MUTABLE_HV(*svp) : NULL;
499
500     if((stashname_len == 9 && strEQ(stashname, "UNIVERSAL"))
501         || (isarev && hv_exists(isarev, "UNIVERSAL", 9))) {
502         PL_sub_generation++;
503         is_universal = TRUE;
504     }
505     else { /* Wipe the local method cache otherwise */
506         meta->cache_gen++;
507         is_universal = FALSE;
508     }
509
510     /* wipe next::method cache too */
511     if(meta->mro_nextmethod) hv_clear(meta->mro_nextmethod);
512
513     /* Iterate the isarev (classes that are our children),
514        wiping out their linearization, method and isa caches
515        and upating PL_isarev. */
516     if(isarev) {
517         HV *isa_hashes = NULL;
518
519        /* We have to iterate through isarev twice to avoid a chicken and
520         * egg problem: if A inherits from B and both are in isarev, A might
521         * be processed before B and use B’s previous linearisation.
522         */
523
524        /* First iteration: Wipe everything, but stash away the isa hashes
525         * since we still need them for updating PL_isarev.
526         */
527
528         if(hv_iterinit(isarev)) {
529             /* Only create the hash if we need it; i.e., if isarev has
530                any elements. */
531             isa_hashes = (HV *)sv_2mortal((SV *)newHV());
532         }
533         while((iter = hv_iternext(isarev))) {
534             I32 len;
535             const char* const revkey = hv_iterkey(iter, &len);
536             HV* revstash = gv_stashpvn(revkey, len, 0);
537             struct mro_meta* revmeta;
538
539             if(!revstash) continue;
540             revmeta = HvMROMETA(revstash);
541             CLEAR_LINEAR(revmeta);
542             if(!is_universal)
543                 revmeta->cache_gen++;
544             if(revmeta->mro_nextmethod)
545                 hv_clear(revmeta->mro_nextmethod);
546
547             (void)
548               hv_store(
549                isa_hashes, (const char*)&revstash, sizeof(HV *),
550                revmeta->isa ? (SV *)revmeta->isa : &PL_sv_undef, 0
551               );
552             revmeta->isa = NULL;
553         }
554
555        /* Second pass: Update PL_isarev. We can just use isa_hashes to
556         * avoid another round of stash lookups. */
557
558        /* isarev might be deleted from PL_isarev during this loop, so hang
559         * on to it. */
560         SvREFCNT_inc_simple_void_NN(sv_2mortal((SV *)isarev));
561
562         if(isa_hashes) {
563             hv_iterinit(isa_hashes);
564             while((iter = hv_iternext(isa_hashes))) {
565                 HV* const revstash = *(HV **)HEK_KEY(HeKEY_hek(iter));
566                 HV * const isa = (HV *)HeVAL(iter);
567                 const HEK *namehek;
568
569                 /* We're starting at the 2nd element, skipping revstash */
570                 linear_mro = mro_get_linear_isa(revstash);
571                 svp = AvARRAY(linear_mro) + 1;
572                 items = AvFILLp(linear_mro);
573
574                 namehek = HvENAME_HEK(revstash);
575                 if (!namehek) namehek = HvNAME_HEK(revstash);
576
577                 while (items--) {
578                     SV* const sv = *svp++;
579                     HV* mroisarev;
580
581                     HE *he = hv_fetch_ent(PL_isarev, sv, TRUE, 0);
582
583                     /* That fetch should not fail.  But if it had to create
584                        a new SV for us, then will need to upgrade it to an
585                        HV (which sv_upgrade() can now do for us). */
586
587                     mroisarev = MUTABLE_HV(HeVAL(he));
588
589                     SvUPGRADE(MUTABLE_SV(mroisarev), SVt_PVHV);
590
591                     /* This hash only ever contains PL_sv_yes. Storing it
592                        over itself is almost as cheap as calling hv_exists,
593                        so on aggregate we expect to save time by not making
594                        two calls to the common HV code for the case where
595                        it doesn't exist.  */
596            
597                     (void)
598                       hv_store(
599                        mroisarev, HEK_KEY(namehek), HEK_LEN(namehek),
600                        &PL_sv_yes, 0
601                       );
602                 }
603
604                 if((SV *)isa != &PL_sv_undef)
605                     mro_clean_isarev(
606                      isa, HEK_KEY(namehek), HEK_LEN(namehek),
607                      HvMROMETA(revstash)->isa
608                     );
609             }
610         }
611     }
612
613     /* Now iterate our MRO (parents), adding ourselves and everything from
614        our isarev to their isarev.
615     */
616
617     /* We're starting at the 2nd element, skipping ourselves here */
618     linear_mro = mro_get_linear_isa(stash);
619     svp = AvARRAY(linear_mro) + 1;
620     items = AvFILLp(linear_mro);
621
622     while (items--) {
623         SV* const sv = *svp++;
624         HV* mroisarev;
625
626         HE *he = hv_fetch_ent(PL_isarev, sv, TRUE, 0);
627
628         /* That fetch should not fail.  But if it had to create a new SV for
629            us, then will need to upgrade it to an HV (which sv_upgrade() can
630            now do for us. */
631
632         mroisarev = MUTABLE_HV(HeVAL(he));
633
634         SvUPGRADE(MUTABLE_SV(mroisarev), SVt_PVHV);
635
636         /* This hash only ever contains PL_sv_yes. Storing it over itself is
637            almost as cheap as calling hv_exists, so on aggregate we expect to
638            save time by not making two calls to the common HV code for the
639            case where it doesn't exist.  */
640            
641         (void)hv_store(mroisarev, stashname, stashname_len, &PL_sv_yes, 0);
642     }
643
644     /* Delete our name from our former parents’ isarevs. */
645     if(isa && HvARRAY(isa))
646         mro_clean_isarev(isa, stashname, stashname_len, meta->isa);
647 }
648
649 /* Deletes name from all the isarev entries listed in isa */
650 STATIC void
651 S_mro_clean_isarev(pTHX_ HV * const isa, const char * const name,
652                          const STRLEN len, HV * const exceptions)
653 {
654     HE* iter;
655
656     PERL_ARGS_ASSERT_MRO_CLEAN_ISAREV;
657
658     /* Delete our name from our former parents’ isarevs. */
659     if(isa && HvARRAY(isa) && hv_iterinit(isa)) {
660         SV **svp;
661         while((iter = hv_iternext(isa))) {
662             I32 klen;
663             const char * const key = hv_iterkey(iter, &klen);
664             if(exceptions && hv_exists(exceptions, key, klen)) continue;
665             svp = hv_fetch(PL_isarev, key, klen, 0);
666             if(svp) {
667                 HV * const isarev = (HV *)*svp;
668                 (void)hv_delete(isarev, name, len, G_DISCARD);
669                 if(!HvARRAY(isarev) || !HvKEYS(isarev))
670                     (void)hv_delete(PL_isarev, key, klen, G_DISCARD);
671             }
672         }
673     }
674 }
675
676 /*
677 =for apidoc mro_package_moved
678
679 Call this function to signal to a stash that it has been assigned to
680 another spot in the stash hierarchy. C<stash> is the stash that has been
681 assigned. C<oldstash> is the stash it replaces, if any. C<gv> is the glob
682 that is actually being assigned to. C<newname> and C<newname_len> are the
683 full name of the GV. If these last two arguments are omitted, they can be
684 inferred from C<gv>. C<gv> can be omitted if C<newname> is given.
685
686 This can also be called with a null first argument to
687 indicate that C<oldstash> has been deleted.
688
689 This function invalidates isa caches on the old stash, on all subpackages
690 nested inside it, and on the subclasses of all those, including
691 non-existent packages that have corresponding entries in C<stash>.
692
693 It also sets the effective names (C<HvENAME>) on all the stashes as
694 appropriate.
695
696 =cut
697 */
698 void
699 Perl_mro_package_moved(pTHX_ HV * const stash, HV * const oldstash,
700                        const GV *gv, const char *newname,
701                        I32 newname_len)
702 {
703     HV *stashes;
704     HE* iter;
705
706     assert(stash || oldstash);
707     assert(gv || newname);
708
709     /* Determine the name of the location that stash was assigned to
710      * or from which oldstash was removed.
711      *
712      * We cannot reliably use the name in oldstash, because it may have
713      * been deleted from the location in the symbol table that its name
714      * suggests, as in this case:
715      *
716      *   $globref = \*foo::bar::;
717      *   Symbol::delete_package("foo");
718      *   *$globref = \%baz::;
719      *   *$globref = *frelp::;
720      *      # calls mro_package_moved(%frelp::, %baz::, *$globref, NULL, 0)
721      *
722      * If newname is not null, then we trust that the caller gave us the
723      * right name. Otherwise, we get it from the gv. But if the gv is not
724      * in the symbol table, then we just return.
725      */
726     if(!newname && gv) {
727         SV * const namesv = sv_newmortal();
728         STRLEN len;
729         gv_fullname4(namesv, gv, NULL, 0);
730         if(gv_fetchsv(namesv, GV_NOADD_NOINIT, SVt_PVGV) != gv) return;
731         newname = SvPV_const(namesv, len);
732         newname_len = len - 2; /* skip trailing :: */
733     }
734     if(newname_len < 0) newname_len = -newname_len;
735
736     /* Get a list of all the affected classes. */
737     /* We cannot simply pass them all to mro_isa_changed_in to avoid
738        the list, as that function assumes that only one package has
739        changed. It does not work with:
740
741           @foo::ISA = qw( B B::B );
742           *B:: = delete $::{"A::"};
743
744        as neither B nor B::B can be updated before the other, since they
745        will reset caches on foo, which will see either B or B::B with the
746        wrong name. The names must be set on *all* affected stashes before
747        we do anything else.
748      */
749     stashes = (HV *) sv_2mortal((SV *)newHV());
750     mro_gather_and_rename(
751      stashes, (HV *) sv_2mortal((SV *)newHV()),
752      stash, oldstash, newname, newname_len
753     );
754
755     /* Iterate through the stashes, wiping isa linearisations, but leaving
756        the isa hash (which mro_isa_changed_in needs for adjusting the
757        isarev hashes belonging to parent classes). */
758     hv_iterinit(stashes);
759     while((iter = hv_iternext(stashes))) {
760         HV * const stash = *(HV **)HEK_KEY(HeKEY_hek(iter));
761         if(HvENAME(stash)) {
762             struct mro_meta* meta;
763             meta = HvMROMETA(stash);
764             CLEAR_LINEAR(meta);
765         }
766     }
767
768     /* Once the caches have been wiped on all the classes, call
769        mro_isa_changed_in on each. */
770     hv_iterinit(stashes);
771     while((iter = hv_iternext(stashes))) {
772         HV * const stash = *(HV **)HEK_KEY(HeKEY_hek(iter));
773         if(HvENAME(stash)) {
774             /* We have to restore the original meta->isa (that
775                mro_gather_and_rename set aside for us) this way, in case
776                one class in this list is a superclass of a another class
777                that we have already encountered. In such a case, meta->isa
778                will have been overwritten without old entries being deleted 
779                from PL_isarev. */
780             struct mro_meta * const meta = HvMROMETA(stash);
781             if(meta->isa != (HV *)HeVAL(iter)){
782                 SvREFCNT_dec(meta->isa);
783                 meta->isa
784                  = HeVAL(iter) == &PL_sv_yes
785                     ? NULL
786                     : (HV *)HeVAL(iter);
787                 HeVAL(iter) = NULL; /* We donated our reference count. */
788             }
789             mro_isa_changed_in(stash);
790         }
791     }
792 }
793
794 void
795 S_mro_gather_and_rename(pTHX_ HV * const stashes, HV * const seen_stashes,
796                               HV *stash, HV *oldstash, const char *name,
797                               I32 namlen)
798 {
799     register XPVHV* xhv;
800     register HE *entry;
801     I32 riter = -1;
802     const bool stash_had_name = stash && HvENAME(stash);
803     HV *seen = NULL;
804     HV *isarev = NULL;
805     SV **svp;
806
807     PERL_ARGS_ASSERT_MRO_GATHER_AND_RENAME;
808
809     /* We use the seen_stashes hash to keep track of which packages have
810        been encountered so far. This must be separate from the main list of
811        stashes, as we need to distinguish between stashes being assigned
812        and stashes being replaced/deleted. (A nested stash can be on both
813        sides of an assignment. We cannot simply skip iterating through a
814        stash on the right if we have seen it on the left, as it will not
815        get its ename assigned to it.)
816
817        To avoid allocating extra SVs, instead of a bitfield we can make
818        bizarre use of immortals:
819
820         &PL_sv_undef:  seen on the left  (oldstash)
821         &PL_sv_no   :  seen on the right (stash)
822         &PL_sv_yes  :  seen on both sides
823
824      */
825
826     if(oldstash) {
827         /* Add to the big list. */
828         struct mro_meta * meta;
829         HE * const entry
830          = (HE *)
831              hv_common(
832               seen_stashes, NULL, (const char *)&oldstash, sizeof(HV *), 0,
833               HV_FETCH_LVALUE|HV_FETCH_EMPTY_HE, NULL, 0
834              );
835         if(HeVAL(entry) == &PL_sv_undef || HeVAL(entry) == &PL_sv_yes) {
836             oldstash = NULL;
837             goto check_stash;
838         }
839         HeVAL(entry)
840          = HeVAL(entry) == &PL_sv_no ? &PL_sv_yes : &PL_sv_undef;
841         meta = HvMROMETA(oldstash);
842         (void)
843           hv_store(
844            stashes, (const char *)&oldstash, sizeof(HV *),
845            meta->isa
846             ? SvREFCNT_inc_simple_NN((SV *)meta->isa)
847             : &PL_sv_yes,
848            0
849           );
850
851         /* Update the effective name. */
852         if(HvENAME_get(oldstash)) {
853           const HEK * const enamehek = HvENAME_HEK(oldstash);
854           if(PL_stashcache)
855             (void)
856              hv_delete(PL_stashcache, name, namlen, G_DISCARD);
857           hv_ename_delete(oldstash, name, namlen);
858
859          /* If the name deletion caused a name change, then we are not
860           * going to call mro_isa_changed_in with this name (and not at all
861           * if it has become anonymous) so we need to delete old isarev
862           * entries here, both those in the superclasses and this class’s
863           * own list of subclasses. We simply delete the latter from
864           * from PL_isarev, since we still need it. hv_delete mortifies it
865           * for us, so sv_2mortal is not necessary. */
866           if(HvENAME_HEK(oldstash) != enamehek) {
867             if(meta->isa && HvARRAY(meta->isa))
868                 mro_clean_isarev(meta->isa, name, namlen, NULL);
869             isarev = (HV *)hv_delete(PL_isarev, name, namlen, 0);
870           }
871         }
872     }
873    check_stash:
874     if(stash) {
875         hv_ename_add(stash, name, namlen);
876
877        /* Add it to the big list if it needs
878         * mro_isa_changed_in called on it. That happens if it was
879         * detached from the symbol table (so it had no HvENAME) before
880         * being assigned to the spot named by the â€˜name’ variable, because
881         * its cached isa linerisation is now stale (the effective name
882         * having changed), and subclasses will then use that cache when
883         * mro_package_moved calls mro_isa_changed_in. (See
884         * [perl #77358].)
885         *
886         * If it did have a name, then its previous name is still
887         * used in isa caches, and there is no need for
888         * mro_package_moved to call mro_isa_changed_in.
889         */
890
891         entry
892          = (HE *)
893              hv_common(
894               seen_stashes, NULL, (const char *)&stash, sizeof(HV *), 0,
895               HV_FETCH_LVALUE|HV_FETCH_EMPTY_HE, NULL, 0
896              );
897         if(HeVAL(entry) == &PL_sv_yes || HeVAL(entry) == &PL_sv_no)
898             stash = NULL;
899         else {
900             HeVAL(entry)
901              = HeVAL(entry) == &PL_sv_undef ? &PL_sv_yes : &PL_sv_no;
902             if(!stash_had_name)
903             {
904                 struct mro_meta * const meta = HvMROMETA(stash);
905                 (void)
906                   hv_store(
907                    stashes, (const char *)&stash, sizeof(HV *),
908                    meta->isa
909                     ? SvREFCNT_inc_simple_NN((SV *)meta->isa)
910                     : &PL_sv_yes,
911                    0
912                   );
913             }
914         }
915     }
916
917     if(!stash && !oldstash)
918         /* Both stashes have been encountered already. */
919         return;
920
921     /* Add all the subclasses to the big list. */
922     if(
923         isarev
924      || (
925            (svp = hv_fetch(PL_isarev, name, namlen, 0))
926         && (isarev = MUTABLE_HV(*svp))
927         )
928     ) {
929         HE *iter;
930         hv_iterinit(isarev);
931         while((iter = hv_iternext(isarev))) {
932             I32 len;
933             const char* const revkey = hv_iterkey(iter, &len);
934             HV* revstash = gv_stashpvn(revkey, len, 0);
935             struct mro_meta * meta;
936
937             if(!revstash) continue;
938             meta = HvMROMETA(revstash);
939             (void)
940               hv_store(
941                stashes, (const char *)&revstash, sizeof(HV *),
942                meta->isa
943                 ? SvREFCNT_inc_simple_NN((SV *)meta->isa)
944                 : &PL_sv_yes,
945                0
946               );
947         }
948     }
949
950     if(
951      (!stash || !HvARRAY(stash)) && (!oldstash || !HvARRAY(oldstash))
952     ) return;
953
954     /* This is partly based on code in hv_iternext_flags. We are not call-
955        ing that here, as we want to avoid resetting the hash iterator. */
956
957     /* Skip the entire loop if the hash is empty.   */
958     if(oldstash && HvUSEDKEYS(oldstash)) { 
959         xhv = (XPVHV*)SvANY(oldstash);
960         seen = (HV *) sv_2mortal((SV *)newHV());
961
962         /* Iterate through entries in the oldstash, adding them to the
963            list, meanwhile doing the equivalent of $seen{$key} = 1.
964          */
965
966         while (++riter <= (I32)xhv->xhv_max) {
967             entry = (HvARRAY(oldstash))[riter];
968
969             /* Iterate through the entries in this list */
970             for(; entry; entry = HeNEXT(entry)) {
971                 const char* key;
972                 I32 len;
973
974                 /* If this entry is not a glob, ignore it.
975                    Try the next.  */
976                 if (!isGV(HeVAL(entry))) continue;
977
978                 key = hv_iterkey(entry, &len);
979                 if(len > 1 && key[len-2] == ':' && key[len-1] == ':') {
980                     HV * const oldsubstash = GvHV(HeVAL(entry));
981                     SV ** const stashentry
982                      = stash ? hv_fetch(stash, key, len, 0) : NULL;
983                     HV *substash = NULL;
984
985                     /* Avoid main::main::main::... */
986                     if(oldsubstash == oldstash) continue;
987
988                     if(
989                         (
990                             stashentry && *stashentry
991                          && (substash = GvHV(*stashentry))
992                         )
993                      || (oldsubstash && HvENAME_get(oldsubstash))
994                     )
995                     {
996                         /* Add :: and the key (minus the trailing ::)
997                            to newname. */
998                         SV *namesv
999                          = newSVpvn_flags(name, namlen, SVs_TEMP);
1000                         {
1001                             const char *name;
1002                             STRLEN namlen;
1003                             sv_catpvs(namesv, "::");
1004                             sv_catpvn(namesv, key, len-2);
1005                             name = SvPV_const(namesv, namlen);
1006                             mro_gather_and_rename(
1007                              stashes, seen_stashes,
1008                              substash, oldsubstash, name, namlen
1009                             );
1010                         }
1011                     }
1012
1013                     (void)hv_store(seen, key, len, &PL_sv_yes, 0);
1014                 }
1015             }
1016         }
1017     }
1018
1019     /* Skip the entire loop if the hash is empty.   */
1020     if (stash && HvUSEDKEYS(stash)) {
1021         xhv = (XPVHV*)SvANY(stash);
1022         riter = -1;
1023
1024         /* Iterate through the new stash, skipping $seen{$key} items,
1025            calling mro_gather_and_rename(stashes,seen,entry,NULL, ...). */
1026         while (++riter <= (I32)xhv->xhv_max) {
1027             entry = (HvARRAY(stash))[riter];
1028
1029             /* Iterate through the entries in this list */
1030             for(; entry; entry = HeNEXT(entry)) {
1031                 const char* key;
1032                 I32 len;
1033
1034                 /* If this entry is not a glob, ignore it.
1035                    Try the next.  */
1036                 if (!isGV(HeVAL(entry))) continue;
1037
1038                 key = hv_iterkey(entry, &len);
1039                 if(len > 1 && key[len-2] == ':' && key[len-1] == ':') {
1040                     HV *substash;
1041
1042                     /* If this entry was seen when we iterated through the
1043                        oldstash, skip it. */
1044                     if(seen && hv_exists(seen, key, len)) continue;
1045
1046                     /* We get here only if this stash has no corresponding
1047                        entry in the stash being replaced. */
1048
1049                     substash = GvHV(HeVAL(entry));
1050                     if(substash) {
1051                         SV *namesv;
1052                         const char *subname;
1053                         STRLEN subnamlen;
1054
1055                         /* Avoid checking main::main::main::... */
1056                         if(substash == stash) continue;
1057
1058                         /* Add :: and the key (minus the trailing ::)
1059                            to newname. */
1060                         namesv
1061                          = newSVpvn_flags(name, namlen, SVs_TEMP);
1062                         sv_catpvs(namesv, "::");
1063                         sv_catpvn(namesv, key, len-2);
1064                         subname = SvPV_const(namesv, subnamlen);
1065                         mro_gather_and_rename(
1066                           stashes, seen_stashes,
1067                           substash, NULL, subname, subnamlen
1068                         );
1069                     }
1070                 }
1071             }
1072         }
1073     }
1074 }
1075
1076 /*
1077 =for apidoc mro_method_changed_in
1078
1079 Invalidates method caching on any child classes
1080 of the given stash, so that they might notice
1081 the changes in this one.
1082
1083 Ideally, all instances of C<PL_sub_generation++> in
1084 perl source outside of C<mro.c> should be
1085 replaced by calls to this.
1086
1087 Perl automatically handles most of the common
1088 ways a method might be redefined.  However, there
1089 are a few ways you could change a method in a stash
1090 without the cache code noticing, in which case you
1091 need to call this method afterwards:
1092
1093 1) Directly manipulating the stash HV entries from
1094 XS code.
1095
1096 2) Assigning a reference to a readonly scalar
1097 constant into a stash entry in order to create
1098 a constant subroutine (like constant.pm
1099 does).
1100
1101 This same method is available from pure perl
1102 via, C<mro::method_changed_in(classname)>.
1103
1104 =cut
1105 */
1106 void
1107 Perl_mro_method_changed_in(pTHX_ HV *stash)
1108 {
1109     const char * const stashname = HvENAME_get(stash);
1110     const STRLEN stashname_len = HvENAMELEN_get(stash);
1111
1112     SV ** const svp = hv_fetch(PL_isarev, stashname, stashname_len, 0);
1113     HV * const isarev = svp ? MUTABLE_HV(*svp) : NULL;
1114
1115     PERL_ARGS_ASSERT_MRO_METHOD_CHANGED_IN;
1116
1117     if(!stashname)
1118         Perl_croak(aTHX_ "Can't call mro_method_changed_in() on anonymous symbol table");
1119
1120     /* Inc the package generation, since a local method changed */
1121     HvMROMETA(stash)->pkg_gen++;
1122
1123     /* If stash is UNIVERSAL, or one of UNIVERSAL's parents,
1124        invalidate all method caches globally */
1125     if((stashname_len == 9 && strEQ(stashname, "UNIVERSAL"))
1126         || (isarev && hv_exists(isarev, "UNIVERSAL", 9))) {
1127         PL_sub_generation++;
1128         return;
1129     }
1130
1131     /* else, invalidate the method caches of all child classes,
1132        but not itself */
1133     if(isarev) {
1134         HE* iter;
1135
1136         hv_iterinit(isarev);
1137         while((iter = hv_iternext(isarev))) {
1138             I32 len;
1139             const char* const revkey = hv_iterkey(iter, &len);
1140             HV* const revstash = gv_stashpvn(revkey, len, 0);
1141             struct mro_meta* mrometa;
1142
1143             if(!revstash) continue;
1144             mrometa = HvMROMETA(revstash);
1145             mrometa->cache_gen++;
1146             if(mrometa->mro_nextmethod)
1147                 hv_clear(mrometa->mro_nextmethod);
1148         }
1149     }
1150 }
1151
1152 void
1153 Perl_mro_set_mro(pTHX_ struct mro_meta *const meta, SV *const name)
1154 {
1155     const struct mro_alg *const which = Perl_mro_get_from_name(aTHX_ name);
1156  
1157     PERL_ARGS_ASSERT_MRO_SET_MRO;
1158
1159     if (!which)
1160         Perl_croak(aTHX_ "Invalid mro name: '%"SVf"'", name);
1161
1162     if(meta->mro_which != which) {
1163         if (meta->mro_linear_current && !meta->mro_linear_all) {
1164             /* If we were storing something directly, put it in the hash before
1165                we lose it. */
1166             Perl_mro_set_private_data(aTHX_ meta, meta->mro_which, 
1167                                       MUTABLE_SV(meta->mro_linear_current));
1168         }
1169         meta->mro_which = which;
1170         /* Scrub our cached pointer to the private data.  */
1171         meta->mro_linear_current = NULL;
1172         /* Only affects local method cache, not
1173            even child classes */
1174         meta->cache_gen++;
1175         if(meta->mro_nextmethod)
1176             hv_clear(meta->mro_nextmethod);
1177     }
1178 }
1179
1180 #include "XSUB.h"
1181
1182 XS(XS_mro_method_changed_in);
1183
1184 void
1185 Perl_boot_core_mro(pTHX)
1186 {
1187     dVAR;
1188     static const char file[] = __FILE__;
1189
1190     Perl_mro_register(aTHX_ &dfs_alg);
1191
1192     newXSproto("mro::method_changed_in", XS_mro_method_changed_in, file, "$");
1193 }
1194
1195 XS(XS_mro_method_changed_in)
1196 {
1197     dVAR;
1198     dXSARGS;
1199     SV* classname;
1200     HV* class_stash;
1201
1202     if(items != 1)
1203         croak_xs_usage(cv, "classname");
1204     
1205     classname = ST(0);
1206
1207     class_stash = gv_stashsv(classname, 0);
1208     if(!class_stash) Perl_croak(aTHX_ "No such class: '%"SVf"'!", SVfARG(classname));
1209
1210     mro_method_changed_in(class_stash);
1211
1212     XSRETURN_EMPTY;
1213 }
1214
1215 /*
1216  * Local variables:
1217  * c-indentation-style: bsd
1218  * c-basic-offset: 4
1219  * indent-tabs-mode: t
1220  * End:
1221  *
1222  * ex: set ts=8 sts=4 sw=4 noet:
1223  */