Make it easier to add new prehashed hash keys.
[gitmo/Class-MOP.git] / MOP.xs
1 /* There's a lot of cases of doubled parens in here like this:
2
3   while ( (he = ...) ) {
4
5 This shuts up warnings from gcc -Wall
6 */
7
8 #include "EXTERN.h"
9 #include "perl.h"
10 #include "XSUB.h"
11
12 #define NEED_newRV_noinc
13 #define NEED_sv_2pv_flags
14 #define NEED_sv_2pv_nolen
15 #include "ppport.h"
16
17 #define DECLARE_KEY(name) SV *key_##name; U32 hash_##name;
18
19 #define PREHASH_KEY(name, value) do { \
20     key_##name = newSVpvs(value); \
21     PERL_HASH(hash_##name, value, sizeof(value) - 1); \
22 } while (0)
23
24 DECLARE_KEY(name);
25 DECLARE_KEY(package);
26 DECLARE_KEY(package_name);
27 DECLARE_KEY(body);
28 DECLARE_KEY(package_cache_flag);
29 DECLARE_KEY(methods);
30 DECLARE_KEY(VERSION);
31 DECLARE_KEY(ISA);
32
33 SV *method_metaclass;
34 SV *associated_metaclass;
35 SV *wrap;
36
37
38 #define check_package_cache_flag(stash) mop_check_package_cache_flag(aTHX_ stash)
39 #if PERL_VERSION >= 10
40
41 static UV
42 mop_check_package_cache_flag(pTHX_ HV* stash) {
43     assert(SvTYPE(stash) == SVt_PVHV);
44
45     /* here we're trying to implement a c version of mro::get_pkg_gen($stash),
46      * however the perl core doesn't make it easy for us. It doesn't provide an
47      * api that just does what we want.
48      *
49      * However, we know that the information we want is, inside the core,
50      * available using HvMROMETA(stash)->pkg_gen. Unfortunately, although the
51      * HvMROMETA macro is public, it is implemented using Perl_mro_meta_init,
52      * which is not public and only available inside the core, as the mro
53      * interface as well as the structure returned by mro_meta_init isn't
54      * considered to be stable yet.
55      *
56      * Perl_mro_meta_init isn't declared static, so we could just define it
57      * ourselfs if perls headers don't do that for us, except that won't work
58      * on platforms where symbols need to be explicitly exported when linking
59      * shared libraries.
60      *
61      * So our, hopefully temporary, solution is to be even more evil and
62      * basically reimplement HvMROMETA in a very fragile way that'll blow up
63      * when the relevant parts of the mro implementation in core change.
64      *
65      * :-(
66      *
67      */
68
69     return HvAUX(stash)->xhv_mro_meta
70          ? HvAUX(stash)->xhv_mro_meta->pkg_gen
71          : 0;
72 }
73
74 #else /* pre 5.10.0 */
75
76 static UV
77 mop_check_package_cache_flag(pTHX_ HV *stash) {
78     PERL_UNUSED_ARG(stash);
79     assert(SvTYPE(stash) == SVt_PVHV);
80
81     return PL_sub_generation;
82 }
83 #endif
84
85 #define call0(s, m)  mop_call0(aTHX_ s, m)
86 static SV *
87 mop_call0(pTHX_ SV *const self, SV *const method) {
88     dSP;
89     SV *ret;
90
91     PUSHMARK(SP);
92     XPUSHs(self);
93     PUTBACK;
94
95     call_sv(method, G_SCALAR | G_METHOD);
96
97     SPAGAIN;
98     ret = POPs;
99     PUTBACK;
100
101     return ret;
102 }
103
104 static int
105 get_code_info (SV *coderef, char **pkg, char **name)
106 {
107     if (!SvOK(coderef) || !SvROK(coderef) || SvTYPE(SvRV(coderef)) != SVt_PVCV) {
108         return 0;
109     }
110
111     coderef = SvRV(coderef);
112     /* I think this only gets triggered with a mangled coderef, but if
113        we hit it without the guard, we segfault. The slightly odd return
114        value strikes me as an improvement (mst)
115     */
116 #ifdef isGV_with_GP
117     if ( isGV_with_GP(CvGV(coderef)) ) {
118 #endif
119         *pkg     = HvNAME( GvSTASH(CvGV(coderef)) );
120         *name    = GvNAME( CvGV(coderef) );
121 #ifdef isGV_with_GP
122     } else {
123         *pkg     = "__UNKNOWN__";
124         *name    = "__ANON__";
125     }
126 #endif
127
128     return 1;
129 }
130
131 typedef enum {
132     TYPE_FILTER_NONE,
133     TYPE_FILTER_CODE,
134     TYPE_FILTER_ARRAY,
135     TYPE_FILTER_IO,
136     TYPE_FILTER_HASH,
137     TYPE_FILTER_SCALAR,
138 } type_filter_t;
139
140 static HV *
141 get_all_package_symbols(HV *stash, type_filter_t filter)
142 {
143     HE *he;
144     HV *ret = newHV();
145
146     (void)hv_iterinit(stash);
147
148     if (filter == TYPE_FILTER_NONE) {
149         while ( (he = hv_iternext(stash)) ) {
150             STRLEN keylen;
151             char *key = HePV(he, keylen);
152             if (!hv_store(ret, key, keylen, SvREFCNT_inc(HeVAL(he)), 0)) {
153                 croak("failed to store glob ref");
154             }
155         }
156
157         return ret;
158     }
159
160     while ( (he = hv_iternext(stash)) ) {
161         SV *const gv = HeVAL(he);
162         SV *sv = NULL;
163         char *key;
164         STRLEN keylen;
165         char *package;
166         SV *fq;
167
168         switch( SvTYPE(gv) ) {
169 #ifndef SVt_RV
170             case SVt_RV:
171 #endif
172             case SVt_PV:
173             case SVt_IV:
174                 /* expand the gv into a real typeglob if it
175                  * contains stub functions and we were asked to
176                  * return CODE symbols */
177                 if (filter == TYPE_FILTER_CODE) {
178                     if (SvROK(gv)) {
179                         /* we don't really care about the length,
180                            but that's the API */
181                         key = HePV(he, keylen);
182                         package = HvNAME(stash);
183                         fq = newSVpvf("%s::%s", package, key);
184                         sv = (SV *)get_cv(SvPV_nolen(fq), 0);
185                         break;
186                     }
187
188                     key = HePV(he, keylen);
189                     gv_init((GV *)gv, stash, key, keylen, GV_ADDMULTI);
190                 }
191                 /* fall through */
192             case SVt_PVGV:
193                 switch (filter) {
194                     case TYPE_FILTER_CODE:   sv = (SV *)GvCVu(gv); break;
195                     case TYPE_FILTER_ARRAY:  sv = (SV *)GvAV(gv);  break;
196                     case TYPE_FILTER_IO:     sv = (SV *)GvIO(gv);  break;
197                     case TYPE_FILTER_HASH:   sv = (SV *)GvHV(gv);  break;
198                     case TYPE_FILTER_SCALAR: sv = (SV *)GvSV(gv);  break;
199                     default:
200                         croak("Unknown type");
201                 }
202                 break;
203             default:
204                 continue;
205         }
206
207         if (sv) {
208             char *key = HePV(he, keylen);
209             if (!hv_store(ret, key, keylen, newRV_inc(sv), 0)) {
210                 croak("failed to store symbol ref");
211             }
212         }
213     }
214
215     return ret;
216 }
217
218
219 static void
220 mop_update_method_map(pTHX_ SV *const self, SV *const class_name, HV *const stash, HV *const map) {
221     const char *const class_name_pv = HvNAME(stash); /* must be HvNAME(stash), not SvPV_nolen_const(class_name) */
222     SV   *method_metaclass_name;
223     char *method_name;
224     I32   method_name_len;
225     SV   *coderef;
226     HV   *symbols;
227     dSP;
228
229     symbols = get_all_package_symbols(stash, TYPE_FILTER_CODE);
230
231     (void)hv_iterinit(symbols);
232     while ( (coderef = hv_iternextsv(symbols, &method_name, &method_name_len)) ) {
233         CV *cv = (CV *)SvRV(coderef);
234         char *cvpkg_name;
235         char *cv_name;
236         SV *method_slot;
237         SV *method_object;
238
239         if (!get_code_info(coderef, &cvpkg_name, &cv_name)) {
240             continue;
241         }
242
243         /* this checks to see that the subroutine is actually from our package  */
244         if ( !(strEQ(cvpkg_name, "constant") && strEQ(cv_name, "__ANON__")) ) {
245             if ( strNE(cvpkg_name, class_name_pv) ) {
246                 continue;
247             }
248         }
249
250         method_slot = *hv_fetch(map, method_name, method_name_len, TRUE);
251         if ( SvOK(method_slot) ) {
252             SV *const body = call0(method_slot, key_body); /* $method_object->body() */
253             if ( SvROK(body) && ((CV *) SvRV(body)) == cv ) {
254                 continue;
255             }
256         }
257
258         method_metaclass_name = call0(self, method_metaclass); /* $self->method_metaclass() */
259
260         /*
261             $method_object = $method_metaclass->wrap(
262                 $cv,
263                 associated_metaclass => $self,
264                 package_name         => $class_name,
265                 name                 => $method_name
266             );
267         */
268         ENTER;
269         SAVETMPS;
270
271         PUSHMARK(SP);
272         EXTEND(SP, 8);
273         PUSHs(method_metaclass_name); /* invocant */
274         mPUSHs(newRV_inc((SV *)cv));
275         PUSHs(associated_metaclass);
276         PUSHs(self);
277         PUSHs(key_package_name);
278         PUSHs(class_name);
279         PUSHs(key_name);
280         mPUSHs(newSVpv(method_name, method_name_len));
281         PUTBACK;
282
283         call_sv(wrap, G_SCALAR | G_METHOD);
284         SPAGAIN;
285         method_object = POPs;
286         PUTBACK;
287         /* $map->{$method_name} = $method_object */
288         sv_setsv(method_slot, method_object);
289
290         FREETMPS;
291         LEAVE;
292     }
293 }
294
295 /*
296 get_code_info:
297   Pass in a coderef, returns:
298   [ $pkg_name, $coderef_name ] ie:
299   [ 'Foo::Bar', 'new' ]
300 */
301
302 MODULE = Class::MOP   PACKAGE = Class::MOP
303
304 BOOT:
305     PREHASH_KEY(name, "name");
306     PREHASH_KEY(body, "body");
307     PREHASH_KEY(package, "package");
308     PREHASH_KEY(package_name, "package_name");
309     PREHASH_KEY(package_cache_flag, "_package_cache_flag");
310     PREHASH_KEY(methods, "methods");
311     PREHASH_KEY(VERSION, "VERSION");
312     PREHASH_KEY(ISA, "ISA");
313
314     method_metaclass     = newSVpvs("method_metaclass");
315     wrap                 = newSVpvs("wrap");
316     associated_metaclass = newSVpvs("associated_metaclass");
317
318
319 PROTOTYPES: ENABLE
320
321
322 void
323 get_code_info(coderef)
324     SV *coderef
325     PREINIT:
326         char *pkg  = NULL;
327         char *name = NULL;
328     PPCODE:
329         if (get_code_info(coderef, &pkg, &name)) {
330             EXTEND(SP, 2);
331             PUSHs(newSVpv(pkg, 0));
332             PUSHs(newSVpv(name, 0));
333         }
334
335 PROTOTYPES: DISABLE
336
337 void
338 is_class_loaded(klass=&PL_sv_undef)
339     SV *klass
340     PREINIT:
341         HV *stash;
342         char *key;
343         I32 keylen;
344         GV *gv;
345     PPCODE:
346         if (!SvPOK(klass) || !SvCUR(klass)) {
347             XSRETURN_NO;
348         }
349
350         stash = gv_stashsv(klass, 0);
351         if (!stash) {
352             XSRETURN_NO;
353         }
354
355         if (hv_exists_ent (stash, key_VERSION, hash_VERSION)) {
356             HE *version = hv_fetch_ent(stash, key_VERSION, 0, hash_VERSION);
357             if (version && HeVAL(version) && GvSV(HeVAL(version))) {
358                 XSRETURN_YES;
359             }
360         }
361
362         if (hv_exists_ent (stash, key_ISA, hash_ISA)) {
363             HE *isa = hv_fetch_ent(stash, key_ISA, 0, hash_ISA);
364             if (isa && HeVAL(isa) && GvAV(HeVAL(isa))) {
365                 XSRETURN_YES;
366             }
367         }
368
369         (void)hv_iterinit(stash);
370         while ((gv = (GV *)hv_iternextsv(stash, &key, &keylen))) {
371             if (keylen <= 0) {
372                 continue;
373             }
374
375             if (key[keylen - 1] == ':' && key[keylen - 2] == ':') {
376                 continue;
377             }
378
379             if (!isGV(gv) || GvCV(gv) || GvSV(gv) || GvAV(gv) || GvHV(gv) || GvIO(gv) || GvFORM(gv)) {
380                 XSRETURN_YES;
381             }
382         }
383
384         XSRETURN_NO;
385
386 MODULE = Class::MOP   PACKAGE = Class::MOP::Package
387
388 PROTOTYPES: ENABLE
389
390 void
391 get_all_package_symbols(self, filter=TYPE_FILTER_NONE)
392     SV *self
393     type_filter_t filter
394     PROTOTYPE: $;$
395     PREINIT:
396         HV *stash = NULL;
397         HV *symbols = NULL;
398         register HE *he;
399     PPCODE:
400         if ( ! SvROK(self) ) {
401             die("Cannot call get_all_package_symbols as a class method");
402         }
403
404         if (GIMME_V == G_VOID) {
405             XSRETURN_EMPTY;
406         }
407
408
409         PUTBACK;
410
411         if ( (he = hv_fetch_ent((HV *)SvRV(self), key_package, 0, hash_package)) ) {
412             stash = gv_stashsv(HeVAL(he), 0);
413         }
414
415
416         if (!stash) {
417             switch (GIMME_V) {
418                 case G_SCALAR: XSRETURN_UNDEF; break;
419                 case G_ARRAY:  XSRETURN_EMPTY; break;
420             }
421         }
422
423         symbols = get_all_package_symbols(stash, filter);
424
425         switch (GIMME_V) {
426             case G_SCALAR:
427                 PUSHs(sv_2mortal(newRV_inc((SV *)symbols)));
428                 break;
429             case G_ARRAY:
430                 warn("Class::MOP::Package::get_all_package_symbols in list context is deprecated. use scalar context instead.");
431
432                 EXTEND(SP, HvKEYS(symbols) * 2);
433
434                 while ((he = hv_iternext(symbols))) {
435                     PUSHs(hv_iterkeysv(he));
436                     PUSHs(sv_2mortal(SvREFCNT_inc(HeVAL(he))));
437                 }
438
439                 break;
440             default:
441                 break;
442         }
443
444         SvREFCNT_dec((SV *)symbols);
445
446 void
447 name(self)
448     SV *self
449     PREINIT:
450         register HE *he;
451     PPCODE:
452         if ( ! SvROK(self) ) {
453             die("Cannot call name as a class method");
454         }
455
456         if ( (he = hv_fetch_ent((HV *)SvRV(self), key_package, 0, hash_package)) )
457             XPUSHs(HeVAL(he));
458         else
459             ST(0) = &PL_sv_undef;
460
461 MODULE = Class::MOP   PACKAGE = Class::MOP::Attribute
462
463 void
464 name(self)
465     SV *self
466     PREINIT:
467         register HE *he;
468     PPCODE:
469         if ( ! SvROK(self) ) {
470             die("Cannot call name as a class method");
471         }
472
473         if ( (he = hv_fetch_ent((HV *)SvRV(self), key_name, 0, hash_name)) )
474             XPUSHs(HeVAL(he));
475         else
476             ST(0) = &PL_sv_undef;
477
478 MODULE = Class::MOP   PACKAGE = Class::MOP::Method
479
480 void
481 name(self)
482     SV *self
483     PREINIT:
484         register HE *he;
485     PPCODE:
486         if ( ! SvROK(self) ) {
487             die("Cannot call name as a class method");
488         }
489
490         if ( (he = hv_fetch_ent((HV *)SvRV(self), key_name, 0, hash_name)) )
491             XPUSHs(HeVAL(he));
492         else
493             ST(0) = &PL_sv_undef;
494
495 void
496 package_name(self)
497     SV *self
498     PREINIT:
499         register HE *he;
500     PPCODE:
501         if ( ! SvROK(self) ) {
502             die("Cannot call package_name as a class method");
503         }
504
505         if ( (he = hv_fetch_ent((HV *)SvRV(self), key_package_name, 0, hash_package_name)) )
506             XPUSHs(HeVAL(he));
507         else
508             ST(0) = &PL_sv_undef;
509
510 void
511 body(self)
512     SV *self
513     PREINIT:
514         register HE *he;
515     PPCODE:
516         if ( ! SvROK(self) ) {
517             die("Cannot call body as a class method");
518         }
519
520         if ( (he = hv_fetch_ent((HV *)SvRV(self), key_body, 0, hash_body)) )
521             XPUSHs(HeVAL(he));
522         else
523             ST(0) = &PL_sv_undef;
524
525
526 MODULE = Class::MOP    PACKAGE = Class::MOP::Class
527
528 void
529 get_method_map(self)
530     SV *self
531     PREINIT:
532         HV *const obj        = (HV *)SvRV(self);
533         SV *const class_name = HeVAL( hv_fetch_ent(obj, key_package, 0, hash_package) );
534         HV *const stash      = gv_stashsv(class_name, 0);
535         UV  const current    = check_package_cache_flag(stash);
536         SV *const cache_flag = HeVAL( hv_fetch_ent(obj, key_package_cache_flag, TRUE, hash_package_cache_flag));
537         SV *const map_ref    = HeVAL( hv_fetch_ent(obj, key_methods, TRUE, hash_methods));
538     PPCODE:
539         /* in  $self->{methods} does not yet exist (or got deleted) */
540         if ( !SvROK(map_ref) || SvTYPE(SvRV(map_ref)) != SVt_PVHV ) {
541             SV *new_map_ref = newRV_noinc((SV *)newHV());
542             sv_2mortal(new_map_ref);
543             sv_setsv(map_ref, new_map_ref);
544         }
545
546         if ( !SvOK(cache_flag) || SvUV(cache_flag) != current ) {
547             mop_update_method_map(aTHX_ self, class_name, stash, (HV *)SvRV(map_ref));
548             sv_setuv(cache_flag, check_package_cache_flag(stash)); /* update_cache_flag() */
549         }
550
551         XPUSHs(map_ref);