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