halfway there on the next::method issue
[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 = newHV();
36     }
37     else {
38         /* XXX return cached entry for stashname if available */
39     }
40
41     /* not in cache, make a new one */
42
43     retval = (AV*)sv_2mortal((SV*)newAV());
44     av_push(retval, newSVpvn(stashname, stashname_len)); /* us first */
45
46     gvp = (GV**)hv_fetch(stash, "ISA", 3, FALSE);
47     isa = (gvp && (gv = *gvp) && gv != (GV*)&PL_sv_undef) ? GvAV(gv) : NULL;
48
49     if(isa && AvFILLp(isa) >= 0) {
50         SV** seqs_ptr;
51         I32 seqs_items;
52         HV* tails = (HV*)sv_2mortal((SV*)newHV());
53         AV* seqs = (AV*)sv_2mortal((SV*)newAV());
54         I32 items = AvFILLp(isa) + 1;
55         SV** isa_ptr = AvARRAY(isa);
56         while(items--) {
57             AV* isa_lin;
58             SV* isa_item = *isa_ptr++;
59             HV* isa_item_stash = gv_stashsv(isa_item, 0);
60             if(!isa_item_stash) {
61                 isa_lin = newAV();
62                 av_push(isa_lin, newSVsv(isa_item));
63             }
64             else {
65                 isa_lin = (AV*)sv_2mortal((SV*)__mro_linear_isa_c3(isa_item_stash, cache, level + 1)); /* recursion */
66             }
67             av_push(seqs, (SV*)av_make(AvFILLp(isa_lin)+1, AvARRAY(isa_lin)));
68         }
69         av_push(seqs, (SV*)av_make(AvFILLp(isa)+1, AvARRAY(isa)));
70
71         seqs_ptr = AvARRAY(seqs);
72         seqs_items = AvFILLp(seqs) + 1;
73         while(seqs_items--) {
74             AV* seq = (AV*)*seqs_ptr++;
75             I32 seq_items = AvFILLp(seq);
76             if(seq_items > 0) {
77                 SV** seq_ptr = AvARRAY(seq) + 1;
78                 while(seq_items--) {
79                     SV* seqitem = *seq_ptr++;
80                     HE* he = hv_fetch_ent(tails, seqitem, 0, 0);
81                     if(!he) {
82                         hv_store_ent(tails, seqitem, newSViv(1), 0);
83                     }
84                     else {
85                         SV* val = HeVAL(he);
86                         sv_inc(val);
87                     }
88                 }
89             }
90         }
91
92         while(1) {
93             SV* seqhead = NULL;
94             SV* cand = NULL;
95             SV* winner = NULL;
96             SV* val;
97             HE* tail_entry;
98             AV* seq;
99             SV** avptr = AvARRAY(seqs);
100             items = AvFILLp(seqs)+1;
101             while(items--) {
102                 SV** svp;
103                 seq = (AV*)*avptr++;
104                 if(AvFILLp(seq) < 0) continue;
105                 svp = av_fetch(seq, 0, 0);
106                 seqhead = *svp;
107                 if(!winner) {
108                     cand = seqhead;
109                     if((tail_entry = hv_fetch_ent(tails, cand, 0, 0))
110                        && (val = HeVAL(tail_entry))
111                        && (SvIVx(val) > 0))
112                            continue;
113                     winner = newSVsv(cand);
114                     av_push(retval, winner);
115                 }
116                 if(!sv_cmp(seqhead, winner)) {
117
118                     /* this is basically shift(@seq) in void context */
119                     SvREFCNT_dec(*AvARRAY(seq));
120                     *AvARRAY(seq) = &PL_sv_undef;
121                     AvARRAY(seq) = AvARRAY(seq) + 1;
122                     AvMAX(seq)--;
123                     AvFILLp(seq)--;
124
125                     if(AvFILLp(seq) < 0) continue;
126                     svp = av_fetch(seq, 0, 0);
127                     seqhead = *svp;
128                     tail_entry = hv_fetch_ent(tails, seqhead, 0, 0);
129                     val = HeVAL(tail_entry);
130                     sv_dec(val);
131                 }
132             }
133             if(!cand) break;
134             if(!winner)
135                 Perl_croak(aTHX_ "Inconsistent hierarchy during C3 merge of class '%s': "
136                     "merging failed on parent '%s'", stashname, SvPV_nolen(cand));
137         }
138     }
139
140     SvREADONLY_on(retval);
141     SvREFCNT_inc(retval); /* for cache storage */
142     SvREFCNT_inc(retval); /* for return to caller */
143     /* XXX store in cache storage */
144     return retval;
145 }
146
147 STATIC I32
148 __dopoptosub_at(const PERL_CONTEXT *cxstk, I32 startingblock) {
149     I32 i;
150     for (i = startingblock; i >= 0; i--) {
151         if(CxTYPE((PERL_CONTEXT*)(&cxstk[i])) == CXt_SUB) return i;
152     }
153     return i;
154 }
155
156 STATIC SV*
157 __nextcan(pTHX_ SV* self, I32 throw_nomethod)
158 {
159     register I32 cxix;
160     register const PERL_CONTEXT *ccstack = cxstack;
161     const PERL_SI *top_si = PL_curstackinfo;
162     HV* selfstash;
163     GV* cvgv;
164     SV *stashname;
165     const char *fq_subname;
166     const char *subname;
167     STRLEN fq_subname_len;
168     STRLEN stashname_len;
169     STRLEN subname_len;
170     SV* sv;
171     GV** gvp;
172     AV* linear_av;
173     SV** linear_svp;
174     SV* linear_sv;
175     HV* cstash;
176     GV* candidate = NULL;
177     CV* cand_cv = NULL;
178     const char *hvname;
179     I32 items;
180     struct mro_meta* selfmeta;
181     HV* nmcache;
182     HE* cache_entry;
183
184     if(sv_isobject(self))
185         selfstash = SvSTASH(SvRV(self));
186     else
187         selfstash = gv_stashsv(self, 0);
188
189     assert(selfstash);
190
191     hvname = HvNAME(selfstash);
192     if (!hvname)
193         croak("Can't use anonymous symbol table for method lookup");
194
195     cxix = __dopoptosub_at(cxstack, cxstack_ix);
196
197     /* This block finds the contextually-enclosing fully-qualified subname,
198        much like looking at (caller($i))[3] until you find a real sub that
199        isn't ANON, etc */
200     for (;;) {
201         /* we may be in a higher stacklevel, so dig down deeper */
202         while (cxix < 0) {
203             if(top_si->si_type == PERLSI_MAIN)
204                 croak("next::method/next::can/maybe::next::method must be used in method context");
205             top_si = top_si->si_prev;
206             ccstack = top_si->si_cxstack;
207             cxix = __dopoptosub_at(ccstack, top_si->si_cxix);
208         }
209
210         if(CxTYPE((PERL_CONTEXT*)(&ccstack[cxix])) != CXt_SUB
211           || (PL_DBsub && GvCV(PL_DBsub) && ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub))) {
212             cxix = __dopoptosub_at(ccstack, cxix - 1);
213             continue;
214         }
215
216         {
217             const I32 dbcxix = __dopoptosub_at(ccstack, cxix - 1);
218             if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub)) {
219                 if(CxTYPE((PERL_CONTEXT*)(&ccstack[dbcxix])) != CXt_SUB) {
220                     cxix = dbcxix;
221                     continue;
222                 }
223             }
224         }
225
226         cvgv = CvGV(ccstack[cxix].blk_sub.cv);
227
228         if(!isGV(cvgv)) {
229             cxix = __dopoptosub_at(ccstack, cxix - 1);
230             continue;
231         }
232
233         /* we found a real sub here */
234         sv = sv_2mortal(newSV(0));
235
236         gv_efullname3(sv, cvgv, NULL);
237
238         fq_subname = SvPVX(sv);
239         fq_subname_len = SvCUR(sv);
240
241         subname = strrchr(fq_subname, ':');
242         if(!subname)
243             croak("next::method/next::can/maybe::next::method cannot find enclosing method");
244
245         subname++;
246         subname_len = fq_subname_len - (subname - fq_subname);
247         if(subname_len == 8 && strEQ(subname, "__ANON__")) {
248             cxix = __dopoptosub_at(ccstack, cxix - 1);
249             continue;
250         }
251         break;
252     }
253
254     /* If we made it to here, we found our context */
255
256     /* 
257     XXX check %next::METHOD_CACHE 
258
259     selfmeta = HvMROMETA(selfstash);
260     if(!(nmcache = selfmeta->mro_nextmethod)) {
261         nmcache = selfmeta->mro_nextmethod = newHV();
262     }
263
264     if((cache_entry = hv_fetch_ent(nmcache, sv, 0, 0))) {
265         SV* val = HeVAL(cache_entry);
266         if(val == &PL_sv_undef) {
267             if(throw_nomethod)
268                 croak("No next::method '%s' found for %s", subname, hvname);
269             return &PL_sv_undef;
270         }
271         return SvREFCNT_inc(val);
272     }
273     */
274
275     /* beyond here is just for cache misses, so perf isn't as critical */
276
277     stashname_len = subname - fq_subname - 2;
278     stashname = sv_2mortal(newSVpvn(fq_subname, stashname_len));
279
280     linear_av = __mro_linear_isa_c3(selfstash, NULL, 0); /* has ourselves at the top of the list */
281     sv_2mortal((SV*)linear_av);
282
283     linear_svp = AvARRAY(linear_av);
284     items = AvFILLp(linear_av) + 1;
285
286     while (items--) {
287         linear_sv = *linear_svp++;
288         assert(linear_sv);
289         if(sv_eq(linear_sv, stashname))
290             break;
291     }
292
293     if(items > 0) {
294         SV* sub_sv = sv_2mortal(newSVpv(subname, subname_len));
295         HV* cc3_mro = get_hv("Class::C3::MRO", 0);
296         SV* methods = sv_2mortal(newSVpv("methods", 7));
297
298         while (items--) {
299             linear_sv = *linear_svp++;
300             assert(linear_sv);
301
302             if(cc3_mro) {
303                 HE* he_cc3_mro_class = hv_fetch_ent(cc3_mro, linear_sv, 0, 0);
304                 if(he_cc3_mro_class) {
305                     HV* cc3_mro_class = (HV*)HeVAL(he_cc3_mro_class);
306                     HE* he_cc3_mro_class_methods = hv_fetch_ent(cc3_mro_class, methods, 0, 0);
307                     if(he_cc3_mro_class_methods) {
308                         HV* cc3_mro_class_methods = (HV*)HeVAL(he_cc3_mro_class_methods);
309                         if(hv_exists_ent(cc3_mro_class_methods, sub_sv, 0))
310                             continue;
311                     }
312                 }
313             }
314
315             cstash = gv_stashsv(linear_sv, FALSE);
316
317             if (!cstash) {
318                 if (ckWARN(WARN_MISC))
319                     Perl_warner(aTHX_ packWARN(WARN_MISC), "Can't locate package %"SVf" for @%s::ISA",
320                         (void*)linear_sv, hvname);
321                 continue;
322             }
323
324             assert(cstash);
325
326             gvp = (GV**)hv_fetch(cstash, subname, subname_len, 0);
327             if (!gvp) continue;
328
329             candidate = *gvp;
330             assert(candidate);
331
332             if (SvTYPE(candidate) != SVt_PVGV)
333                 gv_init(candidate, cstash, subname, subname_len, TRUE);
334             if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
335                 SvREFCNT_inc((SV*)cand_cv);
336                 /* XXX store result in cache */
337                 /* hv_store_ent(nmcache, newSVsv(sv), (SV*)cand_cv, 0); */
338                 return (SV*)cand_cv;
339             }
340         }
341     }
342
343     /* XXX store undef in cache */
344     /* hv_store_ent(nmcache, newSVsv(sv), &PL_sv_undef, 0); */
345     if(throw_nomethod)
346         croak("No next::method '%s' found for %s", subname, hvname);
347     return &PL_sv_undef;
348 }
349
350 XS(XS_Class_C3_XS_calculateMRO);
351 XS(XS_Class_C3_XS_calculateMRO)
352 {
353 #ifdef dVAR
354     dVAR; dXSARGS;
355 #else
356     dXSARGS;
357 #endif
358
359     SV* classname;
360     HV* class_stash;
361     HV* cache = NULL;
362     AV* res;
363     I32 res_items;
364     I32 ret_items;
365     SV** res_ptr;
366
367     if(items < 1 || items > 2)
368         croak("Usage: calculateMRO(classname[, cache])");
369
370     classname = ST(0);
371     if(items == 2) cache = (HV*)ST(1);
372
373     class_stash = gv_stashsv(classname, 0);
374     if(!class_stash) croak("No such class: '%s'!", SvPV_nolen(classname));
375
376     res = (AV*)sv_2mortal((SV*)__mro_linear_isa_c3(class_stash, cache, 0));
377
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__);