0.01_06, better memory mgmt?
[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         croak("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                 croak("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             croak("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                 croak("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         croak("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) croak("No such class: '%s'!", SvPV_nolen(classname));
370
371     res = __mro_linear_isa_c3(aTHX_ class_stash, cache, 0);
372
373     res_items = ret_items = AvFILLp(res) + 1;
374     res_ptr = AvARRAY(res);
375
376     SP -= items;
377
378     while(res_items--) {
379         SV* res_item = *res_ptr++;
380         XPUSHs(sv_2mortal(newSVsv(res_item)));
381     }
382     SvREFCNT_dec(res);
383
384     PUTBACK;
385
386     return;
387 }
388
389 XS(XS_next_can);
390 XS(XS_next_can)
391 {
392 #ifdef dVAR
393     dVAR; dXSARGS;
394 #else
395     dXSARGS;
396 #endif
397
398     SV* self = ST(0);
399     SV* methcv = __nextcan(aTHX_ self, 0);
400
401     PERL_UNUSED_VAR(items);
402
403     if(methcv == &PL_sv_undef) {
404         ST(0) = &PL_sv_undef;
405     }
406     else {
407         ST(0) = sv_2mortal(newRV_inc(methcv));
408     }
409
410     XSRETURN(1);
411 }
412
413 XS(XS_next_method);
414 XS(XS_next_method)
415 {
416     dMARK;
417     dAX;
418     SV* self = ST(0);
419     SV* methcv = __nextcan(aTHX_ self, 1);
420
421     PL_markstack_ptr++;
422     call_sv(methcv, GIMME_V);
423 }
424
425 XS(XS_maybe_next_method);
426 XS(XS_maybe_next_method)
427 {
428     dMARK;
429     dAX;
430     SV* self = ST(0);
431     SV* methcv = __nextcan(aTHX_ self, 0);
432
433     if(methcv == &PL_sv_undef) {
434         ST(0) = &PL_sv_undef;
435         XSRETURN(1);
436     }
437
438     PL_markstack_ptr++;
439     call_sv(methcv, GIMME_V);
440 }
441
442 MODULE = Class::C3::XS  PACKAGE = Class::C3::XS
443
444 BOOT:
445     newXS("Class::C3::XS::calculateMRO", XS_Class_C3_XS_calculateMRO, __FILE__);
446     newXS("next::can", XS_next_can, __FILE__);
447     newXS("next::method", XS_next_method, __FILE__);
448     newXS("maybe::next::method", XS_maybe_next_method, __FILE__);