caching for calcMRO
[gitmo/Class-C3-XS.git] / lib / Class / C3 / XS.xs
1
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5
6 /* Most of this code is backported from the bleadperl patch's
7    mro.c, and then modified to work with Class::C3's
8    internals.
9 */
10
11 AV*
12 __mro_linear_isa_c3(pTHX_ HV* stash, HV* cache, I32 level)
13 {
14     AV* retval;
15     GV** gvp;
16     GV* gv;
17     AV* isa;
18     const char* stashname;
19     STRLEN stashname_len;
20
21     assert(stash);
22     assert(HvAUX(stash));
23
24     stashname = HvNAME(stash);
25     stashname_len = strlen(stashname);
26     if (!stashname)
27       Perl_croak(aTHX_
28                  "Can't linearize anonymous symbol table");
29
30     if (level > 100)
31         Perl_croak(aTHX_ "Recursive inheritance detected in package '%s'",
32               stashname);
33
34     if(!cache) {
35         cache = (HV*)sv_2mortal((SV*)newHV());
36     }
37     else {
38         sv_dump(cache);
39         SV** cache_entry = hv_fetch(cache, stashname, stashname_len, 0);
40         if(cache_entry)
41             return (AV*)SvREFCNT_inc(*cache_entry);
42     }
43
44     /* not in cache, make a new one */
45
46     retval = (AV*)sv_2mortal((SV*)newAV());
47     av_push(retval, newSVpvn(stashname, stashname_len)); /* us first */
48
49     gvp = (GV**)hv_fetch(stash, "ISA", 3, FALSE);
50     isa = (gvp && (gv = *gvp) && gv != (GV*)&PL_sv_undef) ? GvAV(gv) : NULL;
51
52     if(isa && AvFILLp(isa) >= 0) {
53         SV** seqs_ptr;
54         I32 seqs_items;
55         HV* tails = (HV*)sv_2mortal((SV*)newHV());
56         AV* seqs = (AV*)sv_2mortal((SV*)newAV());
57         I32 items = AvFILLp(isa) + 1;
58         SV** isa_ptr = AvARRAY(isa);
59         while(items--) {
60             AV* isa_lin;
61             SV* isa_item = *isa_ptr++;
62             HV* isa_item_stash = gv_stashsv(isa_item, 0);
63             if(!isa_item_stash) {
64                 isa_lin = newAV();
65                 av_push(isa_lin, newSVsv(isa_item));
66             }
67             else {
68                 isa_lin = (AV*)sv_2mortal((SV*)__mro_linear_isa_c3(isa_item_stash, cache, level + 1)); /* recursion */
69             }
70             av_push(seqs, (SV*)av_make(AvFILLp(isa_lin)+1, AvARRAY(isa_lin)));
71         }
72         av_push(seqs, (SV*)av_make(AvFILLp(isa)+1, AvARRAY(isa)));
73
74         seqs_ptr = AvARRAY(seqs);
75         seqs_items = AvFILLp(seqs) + 1;
76         while(seqs_items--) {
77             AV* seq = (AV*)*seqs_ptr++;
78             I32 seq_items = AvFILLp(seq);
79             if(seq_items > 0) {
80                 SV** seq_ptr = AvARRAY(seq) + 1;
81                 while(seq_items--) {
82                     SV* seqitem = *seq_ptr++;
83                     HE* he = hv_fetch_ent(tails, seqitem, 0, 0);
84                     if(!he) {
85                         hv_store_ent(tails, seqitem, newSViv(1), 0);
86                     }
87                     else {
88                         SV* val = HeVAL(he);
89                         sv_inc(val);
90                     }
91                 }
92             }
93         }
94
95         while(1) {
96             SV* seqhead = NULL;
97             SV* cand = NULL;
98             SV* winner = NULL;
99             SV* val;
100             HE* tail_entry;
101             AV* seq;
102             SV** avptr = AvARRAY(seqs);
103             items = AvFILLp(seqs)+1;
104             while(items--) {
105                 SV** svp;
106                 seq = (AV*)*avptr++;
107                 if(AvFILLp(seq) < 0) continue;
108                 svp = av_fetch(seq, 0, 0);
109                 seqhead = *svp;
110                 if(!winner) {
111                     cand = seqhead;
112                     if((tail_entry = hv_fetch_ent(tails, cand, 0, 0))
113                        && (val = HeVAL(tail_entry))
114                        && (SvIVx(val) > 0))
115                            continue;
116                     winner = newSVsv(cand);
117                     av_push(retval, winner);
118                 }
119                 if(!sv_cmp(seqhead, winner)) {
120
121                     /* this is basically shift(@seq) in void context */
122                     SvREFCNT_dec(*AvARRAY(seq));
123                     *AvARRAY(seq) = &PL_sv_undef;
124                     AvARRAY(seq) = AvARRAY(seq) + 1;
125                     AvMAX(seq)--;
126                     AvFILLp(seq)--;
127
128                     if(AvFILLp(seq) < 0) continue;
129                     svp = av_fetch(seq, 0, 0);
130                     seqhead = *svp;
131                     tail_entry = hv_fetch_ent(tails, seqhead, 0, 0);
132                     val = HeVAL(tail_entry);
133                     sv_dec(val);
134                 }
135             }
136             if(!cand) break;
137             if(!winner)
138                 Perl_croak(aTHX_ "Inconsistent hierarchy during C3 merge of class '%s': "
139                     "merging failed on parent '%s'", stashname, SvPV_nolen(cand));
140         }
141     }
142
143     SvREADONLY_on(retval);
144     SvREFCNT_inc(retval); /* for cache storage */
145     SvREFCNT_inc(retval); /* for return */
146     hv_store(cache, stashname, stashname_len, (SV*)retval, 0);
147     return retval;
148 }
149
150 STATIC I32
151 __dopoptosub_at(const PERL_CONTEXT *cxstk, I32 startingblock) {
152     I32 i;
153     for (i = startingblock; i >= 0; i--) {
154         if(CxTYPE((PERL_CONTEXT*)(&cxstk[i])) == CXt_SUB) return i;
155     }
156     return i;
157 }
158
159 STATIC SV*
160 __nextcan(pTHX_ SV* self, I32 throw_nomethod)
161 {
162     register I32 cxix;
163     register const PERL_CONTEXT *ccstack = cxstack;
164     const PERL_SI *top_si = PL_curstackinfo;
165     HV* selfstash;
166     GV* cvgv;
167     SV *stashname;
168     const char *fq_subname;
169     const char *subname;
170     STRLEN fq_subname_len;
171     STRLEN stashname_len;
172     STRLEN subname_len;
173     SV* sv;
174     GV** gvp;
175     AV* linear_av;
176     SV** linear_svp;
177     SV* linear_sv;
178     HV* cstash;
179     GV* candidate = NULL;
180     CV* cand_cv = NULL;
181     const char *hvname;
182     I32 items;
183     struct mro_meta* selfmeta;
184     HV* nmcache;
185     HE* cache_entry;
186
187     if(sv_isobject(self))
188         selfstash = SvSTASH(SvRV(self));
189     else
190         selfstash = gv_stashsv(self, 0);
191
192     assert(selfstash);
193
194     hvname = HvNAME(selfstash);
195     if (!hvname)
196         croak("Can't use anonymous symbol table for method lookup");
197
198     cxix = __dopoptosub_at(cxstack, cxstack_ix);
199
200     /* This block finds the contextually-enclosing fully-qualified subname,
201        much like looking at (caller($i))[3] until you find a real sub that
202        isn't ANON, etc */
203     for (;;) {
204         /* we may be in a higher stacklevel, so dig down deeper */
205         while (cxix < 0) {
206             if(top_si->si_type == PERLSI_MAIN)
207                 croak("next::method/next::can/maybe::next::method must be used in method context");
208             top_si = top_si->si_prev;
209             ccstack = top_si->si_cxstack;
210             cxix = __dopoptosub_at(ccstack, top_si->si_cxix);
211         }
212
213         if(CxTYPE((PERL_CONTEXT*)(&ccstack[cxix])) != CXt_SUB
214           || (PL_DBsub && GvCV(PL_DBsub) && ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub))) {
215             cxix = __dopoptosub_at(ccstack, cxix - 1);
216             continue;
217         }
218
219         {
220             const I32 dbcxix = __dopoptosub_at(ccstack, cxix - 1);
221             if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub)) {
222                 if(CxTYPE((PERL_CONTEXT*)(&ccstack[dbcxix])) != CXt_SUB) {
223                     cxix = dbcxix;
224                     continue;
225                 }
226             }
227         }
228
229         cvgv = CvGV(ccstack[cxix].blk_sub.cv);
230
231         if(!isGV(cvgv)) {
232             cxix = __dopoptosub_at(ccstack, cxix - 1);
233             continue;
234         }
235
236         /* we found a real sub here */
237         sv = sv_2mortal(newSV(0));
238
239         gv_efullname3(sv, cvgv, NULL);
240
241         fq_subname = SvPVX(sv);
242         fq_subname_len = SvCUR(sv);
243
244         subname = strrchr(fq_subname, ':');
245         if(!subname)
246             croak("next::method/next::can/maybe::next::method cannot find enclosing method");
247
248         subname++;
249         subname_len = fq_subname_len - (subname - fq_subname);
250         if(subname_len == 8 && strEQ(subname, "__ANON__")) {
251             cxix = __dopoptosub_at(ccstack, cxix - 1);
252             continue;
253         }
254         break;
255     }
256
257     /* If we made it to here, we found our context */
258
259     /* 
260     XXX check %next::METHOD_CACHE 
261
262     selfmeta = HvMROMETA(selfstash);
263     if(!(nmcache = selfmeta->mro_nextmethod)) {
264         nmcache = selfmeta->mro_nextmethod = newHV();
265     }
266
267     if((cache_entry = hv_fetch_ent(nmcache, sv, 0, 0))) {
268         SV* val = HeVAL(cache_entry);
269         if(val == &PL_sv_undef) {
270             if(throw_nomethod)
271                 croak("No next::method '%s' found for %s", subname, hvname);
272             return &PL_sv_undef;
273         }
274         return SvREFCNT_inc(val);
275     }
276     */
277
278     /* beyond here is just for cache misses, so perf isn't as critical */
279
280     stashname_len = subname - fq_subname - 2;
281     stashname = sv_2mortal(newSVpvn(fq_subname, stashname_len));
282
283     linear_av = (AV*)sv_2mortal((SV*)__mro_linear_isa_c3(selfstash, NULL, 0));
284
285     linear_svp = AvARRAY(linear_av);
286     items = AvFILLp(linear_av) + 1;
287
288     while (items--) {
289         linear_sv = *linear_svp++;
290         assert(linear_sv);
291         if(sv_eq(linear_sv, stashname))
292             break;
293     }
294
295     if(items > 0) {
296         SV* sub_sv = sv_2mortal(newSVpv(subname, subname_len));
297         HV* cc3_mro = get_hv("Class::C3::MRO", 0);
298
299         while (items--) {
300             linear_sv = *linear_svp++;
301             assert(linear_sv);
302
303             if(cc3_mro) {
304                 HE* he_cc3_mro_class = hv_fetch_ent(cc3_mro, linear_sv, 0, 0);
305                 if(he_cc3_mro_class) {
306                     HV* cc3_mro_class = (HV*)SvRV(HeVAL(he_cc3_mro_class));
307                     SV** svp_cc3_mro_class_methods = hv_fetch(cc3_mro_class, "methods", 7, 0);
308                     if(svp_cc3_mro_class_methods) {
309                         HV* cc3_mro_class_methods = (HV*)SvRV(*svp_cc3_mro_class_methods);
310                         if(hv_exists_ent(cc3_mro_class_methods, sub_sv, 0))
311                             continue;
312                     }
313                 }
314             }
315
316             cstash = gv_stashsv(linear_sv, FALSE);
317
318             if (!cstash) {
319                 if (ckWARN(WARN_MISC))
320                     Perl_warner(aTHX_ packWARN(WARN_MISC), "Can't locate package %"SVf" for @%s::ISA",
321                         (void*)linear_sv, hvname);
322                 continue;
323             }
324
325             assert(cstash);
326
327             gvp = (GV**)hv_fetch(cstash, subname, subname_len, 0);
328             if (!gvp) continue;
329
330             candidate = *gvp;
331             assert(candidate);
332
333             if (SvTYPE(candidate) != SVt_PVGV)
334                 gv_init(candidate, cstash, subname, subname_len, TRUE);
335             if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
336                 SvREFCNT_inc((SV*)cand_cv);
337                 /* XXX store result in cache */
338                 /* hv_store_ent(nmcache, newSVsv(sv), (SV*)cand_cv, 0); */
339                 return (SV*)cand_cv;
340             }
341         }
342     }
343
344     /* XXX store undef in cache */
345     /* hv_store_ent(nmcache, newSVsv(sv), &PL_sv_undef, 0); */
346     if(throw_nomethod)
347         croak("No next::method '%s' found for %s", subname, hvname);
348     return &PL_sv_undef;
349 }
350
351 XS(XS_Class_C3_XS_calculateMRO);
352 XS(XS_Class_C3_XS_calculateMRO)
353 {
354 #ifdef dVAR
355     dVAR; dXSARGS;
356 #else
357     dXSARGS;
358 #endif
359
360     SV* classname;
361     HV* class_stash;
362     HV* cache = NULL;
363     AV* res;
364     I32 res_items;
365     I32 ret_items;
366     SV** res_ptr;
367
368     if(items < 1 || items > 2)
369         croak("Usage: calculateMRO(classname[, cache])");
370
371     classname = ST(0);
372     if(items == 2) cache = (HV*)SvRV(ST(1));
373
374     class_stash = gv_stashsv(classname, 0);
375     if(!class_stash) croak("No such class: '%s'!", SvPV_nolen(classname));
376
377     res = (AV*)sv_2mortal((SV*)__mro_linear_isa_c3(class_stash, cache, 0));
378
379     res_items = ret_items = AvFILLp(res) + 1;
380     res_ptr = AvARRAY(res);
381
382     SP -= items;
383
384     while(res_items--) {
385         SV* res_item = *res_ptr++;
386         XPUSHs(res_item);
387     }
388
389     PUTBACK;
390
391     return;
392 }
393
394 XS(XS_next_can);
395 XS(XS_next_can)
396 {
397 #ifdef dVAR
398     dVAR; dXSARGS;
399 #else
400     dXSARGS;
401 #endif
402
403     SV* self = ST(0);
404     SV* methcv = __nextcan(self, 0);
405
406     PERL_UNUSED_VAR(items);
407
408     if(methcv == &PL_sv_undef) {
409         ST(0) = &PL_sv_undef;
410     }
411     else {
412         ST(0) = sv_2mortal(newRV_inc(methcv));
413     }
414
415     XSRETURN(1);
416 }
417
418 XS(XS_next_method);
419 XS(XS_next_method)
420 {
421     dMARK;
422     dAX;
423     SV* self = ST(0);
424     SV* methcv = __nextcan(self, 1);
425
426     PL_markstack_ptr++;
427     call_sv(methcv, GIMME_V);
428 }
429
430 XS(XS_maybe_next_method);
431 XS(XS_maybe_next_method)
432 {
433     dMARK;
434     dAX;
435     SV* self = ST(0);
436     SV* methcv = __nextcan(self, 0);
437
438     if(methcv == &PL_sv_undef) {
439         ST(0) = &PL_sv_undef;
440         XSRETURN(1);
441     }
442
443     PL_markstack_ptr++;
444     call_sv(methcv, GIMME_V);
445 }
446
447 MODULE = Class::C3::XS  PACKAGE = Class::C3::XS
448
449 BOOT:
450     newXS("Class::C3::XS::calculateMRO", XS_Class_C3_XS_calculateMRO, __FILE__);
451     newXS("next::can", XS_next_can, __FILE__);
452     newXS("next::method", XS_next_method, __FILE__);
453     newXS("maybe::next::method", XS_maybe_next_method, __FILE__);