8e004cfbe68fd56adb0826938f060978c9f9cf38
[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 bleadperl'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         while (items--) {
295             linear_sv = *linear_svp++;
296             assert(linear_sv);
297             cstash = gv_stashsv(linear_sv, FALSE);
298
299             if (!cstash) {
300                 if (ckWARN(WARN_MISC))
301                     Perl_warner(aTHX_ packWARN(WARN_MISC), "Can't locate package %"SVf" for @%s::ISA",
302                         (void*)linear_sv, hvname);
303                 continue;
304             }
305
306             assert(cstash);
307
308 /* XXX we need to fetch from %Class::C3::MRO, not the real stash table */
309
310             gvp = (GV**)hv_fetch(cstash, subname, subname_len, 0);
311             if (!gvp) continue;
312
313             candidate = *gvp;
314             assert(candidate);
315
316             if (SvTYPE(candidate) != SVt_PVGV)
317                 gv_init(candidate, cstash, subname, subname_len, TRUE);
318             if (SvTYPE(candidate) == SVt_PVGV && (cand_cv = GvCV(candidate)) && !GvCVGEN(candidate)) {
319                 SvREFCNT_inc((SV*)cand_cv);
320                 /* XXX store result in cache */
321                 /* hv_store_ent(nmcache, newSVsv(sv), (SV*)cand_cv, 0); */
322                 return (SV*)cand_cv;
323             }
324         }
325     }
326
327     /* XXX store undef in cache */
328     /* hv_store_ent(nmcache, newSVsv(sv), &PL_sv_undef, 0); */
329     if(throw_nomethod)
330         croak("No next::method '%s' found for %s", subname, hvname);
331     return &PL_sv_undef;
332 }
333
334 XS(XS_Class_C3_XS_calculateMRO);
335 XS(XS_Class_C3_XS_calculateMRO)
336 {
337 #ifdef dVAR
338     dVAR; dXSARGS;
339 #else
340     dXSARGS;
341 #endif
342
343     SV* classname;
344     HV* class_stash;
345     HV* cache = NULL;
346     AV* res;
347     I32 res_items;
348     I32 ret_items;
349     SV** res_ptr;
350
351     if(items < 1 || items > 2)
352         croak("Usage: calculateMRO(classname[, cache])");
353
354     classname = ST(0);
355     if(items == 2) cache = (HV*)ST(1);
356
357     class_stash = gv_stashsv(classname, 0);
358     if(!class_stash) croak("No such class: '%s'!", SvPV_nolen(classname));
359
360     res = (AV*)sv_2mortal((SV*)__mro_linear_isa_c3(class_stash, cache, 0));
361
362
363     res_items = ret_items = AvFILLp(res) + 1;
364     res_ptr = AvARRAY(res);
365
366     SP -= items;
367
368     while(res_items--) {
369         SV* res_item = *res_ptr++;
370         XPUSHs(res_item);
371     }
372
373     PUTBACK;
374
375     return;
376 }
377
378 XS(XS_next_can);
379 XS(XS_next_can)
380 {
381 #ifdef dVAR
382     dVAR; dXSARGS;
383 #else
384     dXSARGS;
385 #endif
386
387     SV* self = ST(0);
388     SV* methcv = __nextcan(self, 0);
389
390     PERL_UNUSED_VAR(items);
391
392     if(methcv == &PL_sv_undef) {
393         ST(0) = &PL_sv_undef;
394     }
395     else {
396         ST(0) = sv_2mortal(newRV_inc(methcv));
397     }
398
399     XSRETURN(1);
400 }
401
402 XS(XS_next_method);
403 XS(XS_next_method)
404 {
405     dMARK;
406     dAX;
407     SV* self = ST(0);
408     SV* methcv = __nextcan(self, 1);
409
410     PL_markstack_ptr++;
411     call_sv(methcv, GIMME_V);
412 }
413
414 XS(XS_maybe_next_method);
415 XS(XS_maybe_next_method)
416 {
417     dMARK;
418     dAX;
419     SV* self = ST(0);
420     SV* methcv = __nextcan(self, 0);
421
422     if(methcv == &PL_sv_undef) {
423         ST(0) = &PL_sv_undef;
424         XSRETURN(1);
425     }
426
427     PL_markstack_ptr++;
428     call_sv(methcv, GIMME_V);
429 }
430
431 MODULE = Class::C3::XS  PACKAGE = Class::C3::XS
432
433 BOOT:
434     newXS("Class::C3::XS::calculateMRO", XS_Class_C3_XS_calculateMRO, __FILE__);
435     newXS("next::can", XS_next_can, __FILE__);
436     newXS("next::method", XS_next_method, __FILE__);
437     newXS("maybe::next::method", XS_maybe_next_method, __FILE__);