9986e1f08b704a100b7ecd3280926c52bfff61c2
[gitmo/Moose.git] / Moose.xs
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4
5 #define NEED_newRV_noinc
6 #define NEED_newSVpvn_share
7 #define NEED_sv_2pv_flags
8 #include "ppport.h"
9
10 #ifndef XSPROTO
11 #define XSPROTO(name) void name(pTHX_ CV* cv)
12 #endif
13
14 #ifndef gv_stashpvs
15 #define gv_stashpvs(x, y) Perl_gv_stashpvn(aTHX_ STR_WITH_LEN(x), y)
16 #endif
17
18 /* FIXME
19  * delegations and attribute helpers:
20  *
21  * typedef struct {
22  *      ATTR *attr;
23  *      pv *method;
24  * } delegation;
25  *
26  * typedef struct {
27  *      ATTR *attr;
28  *      I32 *type; // hash, array, whatever + vtable for operation
29  * } attributehelper;
30  */
31
32
33
34
35
36
37
38 /* These two functions attach magic with no behavior to an SV.
39  *
40  * The stashed value is reference counted, and is destroyed when it's parent
41  * object is destroyed.
42  *
43  * This is used to keep a reference the the meta attribute from a generated
44  * method, and to cache the C struct based wrapper attached to the meta
45  * instance.
46  */
47
48 STATIC MGVTBL null_mg_vtbl = {
49     NULL, /* get */
50     NULL, /* set */
51     NULL, /* len */
52     NULL, /* clear */
53     NULL, /* free */
54 #if MGf_COPY
55     NULL, /* copy */
56 #endif /* MGf_COPY */
57 #if MGf_DUP
58     NULL, /* dup */
59 #endif /* MGf_DUP */
60 #if MGf_LOCAL
61     NULL, /* local */
62 #endif /* MGf_LOCAL */
63 };
64
65 STATIC MAGIC *stash_in_mg (pTHX_ SV *sv, SV *obj) {
66     MAGIC *mg = sv_magicext(sv, obj, PERL_MAGIC_ext, &null_mg_vtbl, NULL, 0 );
67     mg->mg_flags |= MGf_REFCOUNTED;
68
69     return mg;
70 }
71
72 STATIC SV *get_stashed_in_mg(pTHX_ SV *sv) {
73     MAGIC *mg;
74
75     if (SvTYPE(sv) >= SVt_PVMG) {
76         for (mg = SvMAGIC(sv); mg; mg = mg->mg_moremagic) {
77             if ((mg->mg_type == PERL_MAGIC_ext) && (mg->mg_virtual == &null_mg_vtbl))
78                 break;
79         }
80         if (mg)
81             return mg->mg_obj;
82     }
83
84     return NULL;
85 }
86
87
88
89
90
91
92
93
94
95 /* The folloing data structures deal with type constraints */
96
97 /* this is an enum of the various kinds of constraint checking an attribute can
98  * have.
99  *
100  * tc_cv is the fallback behavior (simply applying the
101  * ->_compiled_type_constraint to the value, but other more optimal checks are
102  *  implemented too. */
103
104 typedef enum {
105     tc_none = 0, /* no type checking */
106     tc_type, /* a builtin type to be checked by check_sv_type */
107     tc_stash, /* a stash for a class, implements TypeConstraint::Class by comparing SvSTASH and then invoking C<isa> if necessary */
108     tc_cv, /* applies a code reference to the value and checks for truth */
109     tc_fptr, /* apply a C function pointer */
110     tc_enum, /* TODO check that the value is in an allowed set of values (strings) */
111 } tc_kind;
112
113 /* this is a enum of builtin type check. They are handled in a switch statement
114  * in check_sv_type */
115 typedef enum {
116     Any, /* or item, or bool */
117     Undef,
118     Defined,
119     Str, /* or value */
120     Num,
121     Int,
122     GlobRef, /* SVt_PVGV */
123     ArrayRef, /* SVt_PVAV */
124     HashRef, /* SVt_PVHV */
125     CodeRef, /* SVt_PVCV */
126     Ref,
127     ScalarRef,
128     FileHandle, /* TODO */
129     RegexpRef,
130     Object,
131     Role, /* TODO */
132     ClassName,
133 } TC;
134
135 /* auxillary pointer/int union used for constraint checking */
136 typedef union {
137     TC type; /* the builtin type number for tc_type */
138     SV *sv; /* the cv for tc_cv, or the stash for tc_stash */
139     OP *op; /* TODO not used */
140     bool (*fptr)(pTHX_ SV *type_constraint, SV *sv); /* the function pointer for tc_fptr  FIXME aux data? */
141 } TC_CHECK;
142
143
144
145
146
147
148 /* The folloing data structures deal with type default value generation */
149
150 /* This is an enum for the various types of default value behaviors an
151  * attribute can have */
152
153 typedef enum {
154     default_none = 0, /* no default value */
155     default_normal, /* code reference or scalar */
156     default_builder, /* builder method */
157     default_type, /* TODO enumerated type optimization (will call newHV, newAV etc to avoid calling a code ref for these simple cases) */
158 } default_kind;
159
160 typedef union {
161     SV *sv; /* The default value, or a code ref to generate one. If builder then this sv is applied as a method (stringified) */
162     U32 type; /* TODO for default_type, should probably be one of SVt_PVAV/SVt_PVHV */
163 } DEFAULT;
164
165
166
167
168
169
170 /* the ATTR struct contains all the meta data for a Moose::Meta::Attribute for
171  * a given meta instance
172  *
173  * flags determines the various behaviors
174  *
175  * This supports only one slot per attribute in the current implementation, but
176  * slot_sv could contain an array
177  *
178  * A list of XSUBs that rely on this attr struct are cross indexed in the cvs
179  * array, so that when the meta instance is destroyed the XSANY field will be
180  * cleared. This is done in delete_mi
181  * */
182
183 typedef struct {
184     /* pointer to the MI this attribute is a part of the meta instance struct */
185     struct mi *mi;
186
187     U32 flags; /* slot type, TC behavior, coerce, weaken, (no default | default, builder + lazy), auto_deref */
188
189     /* slot access fields */
190     SV *slot_sv; /* value of the slot (currently always slot name) */
191     U32 slot_u32; /* for optimized access (precomputed hash, possibly something else) */
192
193     SV *init_arg_sv;
194     U32 init_arg_u32;
195
196     DEFAULT def; /* cv, value or other, depending on flags */
197
198     TC_CHECK tc_check; /* see TC_CHECK*/
199     SV *type_constraint; /* Moose::Meta::TypeConstraint object */
200
201     CV *initializer; /* TODO */
202     CV *trigger; /* TODO */
203
204     SV *meta_attr; /* the Moose::Meta::Attribute */
205     AV *cvs; /* an array of CVs which use this attr, see delete_mi */
206 } ATTR;
207
208 /* the flags integer is mapped as follows
209  * instance     misc  reading  writing
210  * 00000000 00000000 00000000 00000000
211  *                                     writing
212  *                             ^       trigger
213  *                              ^      weak
214  *                               ^     tc.sv is refcounted
215  *                                 ^^^ tc_kind
216  *                                ^    coerce
217  *
218  *                                     reading
219  *                        ^^^          default_kind
220  *                       ^             lazy
221  *                      ^              def.sv is refcounted
222  *
223  *                                     misc
224  *                 ^                   attr is required TODO
225  *
226  *                                     flags having to do with the instance layout (TODO, only hash supported for now)
227  * ^^^^^^^                             if 0 then nothing special (just hash)? FIXME TBD
228  */
229
230 #define ATTR_INSTANCE_MASK 0xff000000
231 #define ATTR_READING_MASK  0x0000ff00
232 #define ATTR_WRITING_MASK  0x000000ff
233
234 #define ATTR_MASK_TYPE 0x7
235
236 #define ATTR_MASK_DEFAULT 0x700
237 #define ATTR_SHIFT_DEFAULT 8
238
239 #define ATTR_LAZY 0x800
240 #define ATTR_DEFREFCNT 0x1000
241
242 #define ATTR_COERCE 0x8
243 #define ATTR_TCREFCNT 0x10
244 #define ATTR_WEAK 0x20
245 #define ATTR_TRIGGER 0x40
246
247 #define ATTR_ISWEAK(attr) ( attr->flags & ATTR_WEAK )
248 #define ATTR_ISLAZY(attr) ( attr->flags & ATTR_LAZY )
249 #define ATTR_ISCOERCE(attr) ( attr->flags & ATTR_COERCE )
250
251 #define ATTR_TYPE(f) ( attr->flags & 0x7 )
252 #define ATTR_DEFAULT(f) ( ( attr->flags & ATTR_MASK_DEFAULT ) >> ATTR_SHIFT_DEFAULT )
253
254 #define ATTR_DUMB_READER(attr) !ATTR_IS_LAZY(attr)
255 #define ATTR_DUMB_WRITER(attr) ( ( attr->flags & ATTR_WRITING_MASK ) == 0 )
256 #define ATTR_DUMB_INSTANCE(attr) ( ( attr->flags & ATTR_INSTANCE_MASK ) == 0 )
257
258
259
260 /* This unused (TODO) vtable will implement the meta instance protocol in terms
261  * of function pointers to allow the XS accessors to be used with custom meta
262  * instances in the future.
263  *
264  * We'll need to define a default instance of this vtable that uses call_sv,
265  * too. */
266
267 /* FIXME define a vtable that does call_sv for fallback meta instance protocol */
268 typedef struct {
269     SV * (*get)(pTHX_ SV *self, ATTR *attr);
270     void (*set)(pTHX_ SV *self, ATTR *attr, SV *value);
271     bool * (*has)(pTHX_ SV *self, ATTR *attr);
272     SV * (*delete)(pTHX_ SV *self, ATTR *attr);
273 } instance_vtbl;
274
275 /* TODO this table describes the instance layout of the object. Not yet
276  * implemented */
277 typedef enum {
278     hash = 0,
279
280     /* these are not yet implemented */
281     array,
282     fptr,
283     cv,
284     judy,
285 } instance_types;
286
287
288 /* this struct models the meta instance *and* meta attributes simultaneously.
289  * It is a cache of the meta attribute behaviors for a given class or subclass
290  * and can be parametrized on that level
291  *
292  *
293  * An object pointing to this structure is kept in a refcounted magic inside
294  * the meta instance it corresponds to. On C<invalidate_meta_instance> the meta
295  * instance is destroyed, causing the proxy object to be destroyed, deleting
296  * this structure, clearing the XSANY of all dependent attribute methods.
297  *
298  * The next invocation of an attribute method will eventually call get_attr,
299  * which will call C<get_meta_instance> on the metaclass (recreating it in the
300  * Class::MOP level), and cache a new MI struct inside it. Subsequent
301  * invocations of get_attr will then search the MI for an ATTR matching the
302  * meta_attribute of the attribute method */
303 typedef struct mi {
304     HV *stash;
305
306     /* slot access method */
307     instance_types type; /* TODO only hashes supported currently */
308     instance_vtbl *vtbl; /* TODO */
309
310     /* attr descriptors */
311     I32 num_attrs;
312     ATTR *attrs;
313 } MI;
314
315
316
317
318
319
320
321
322 /* these functions implement type constraint checking */
323
324 /* checks that the SV is a scalar ref */
325 STATIC bool check_is_scalar_ref(SV *sv) {
326     if( SvROK(sv) ) {
327         switch (SvTYPE(SvRV(sv))) {
328             case SVt_IV:
329             case SVt_NV:
330             case SVt_PV:
331             case SVt_NULL:
332                 return 1;
333                 break;
334             default:
335                 return 0;
336         }
337     }
338     return 0;
339 }
340
341 /* checks that the SV is a ref to a certain SvTYPE, where type is in the table
342  * above */
343 STATIC bool check_reftype(TC type, SV *sv) {
344     int svt;
345
346     if ( !SvROK(sv) )
347         return 0;
348
349     switch (type) {
350         case GlobRef:
351             svt = SVt_PVGV;
352             break;
353         case ArrayRef:
354             svt = SVt_PVAV;
355             break;
356         case HashRef:
357             svt = SVt_PVHV;
358             break;
359         case CodeRef:
360             svt = SVt_PVCV;
361             break;
362         default:
363             croak("not a reftype %d\n", type);
364     }
365
366     return SvTYPE(SvRV(sv)) == svt;
367 }
368
369 /* checks whether an SV is of a certain class
370  * SvSTASH is first compared by pointer for efficiency */
371 STATIC bool check_sv_class(pTHX_ HV *stash, SV *sv) {
372     dSP;
373     bool ret;
374     SV *rv;
375
376     if (!sv)
377         return 0;
378     SvGETMAGIC(sv);
379     if (!SvROK(sv))
380         return 0;
381     rv = (SV*)SvRV(sv);
382     if (!SvOBJECT(rv))
383         return 0;
384     if (SvSTASH(rv) == stash)
385         return 1;
386
387     ENTER;
388     SAVETMPS;
389     PUSHMARK(SP);
390     XPUSHs(sv);
391     XPUSHs(sv_2mortal(newSVpv(HvNAME_get(stash), 0)));
392     PUTBACK;
393
394     call_method("isa", G_SCALAR);
395
396     SPAGAIN;
397     ret = SvTRUE(TOPs);
398
399     FREETMPS;
400     LEAVE;
401
402     return ret;
403 }
404
405 /* checks whether SV of of a known simple type. Most of the non parametrized
406  * Moose core types are implemented here */
407 STATIC bool check_sv_type (TC type, SV *sv) {
408     if (!sv)
409         return 0;
410
411     switch (type) {
412         case Any:
413             return 1;
414             break;
415         case Undef:
416             return !SvOK(sv);
417             break;
418         case Defined:
419             return SvOK(sv);
420             break;
421         case Str:
422             return (SvOK(sv) && !SvROK(sv));
423         case Num:
424 #if (PERL_VERSION < 8) || (PERL_VERSION == 8 && PERL_SUBVERSION <5)
425             if (!SvPOK(sv) && !SvPOKp(sv))
426                 return SvFLAGS(sv) & (SVf_NOK|SVp_NOK|SVf_IOK|SVp_IOK);
427             else
428 #endif
429                 return looks_like_number(sv);
430             break;
431         case Int:
432             if ( SvIOK(sv) ) {
433                 return 1;
434             } else if ( SvPOK(sv) ) {
435                 /* FIXME i really don't like this */
436                 int i;
437                 STRLEN len;
438                 char *pv = SvPV(sv, len);
439                 char *end = pv + len;
440                 char *tail = end;
441
442                 errno = 0;
443                 i = strtol(pv, &tail, 0);
444
445                 if ( errno ) return 0;
446
447                 while ( tail != end ) {
448                     if ( !isspace(*tail++) ) return 0;
449                 }
450
451                 return 1;
452             }
453             return 0;
454             break;
455         case Ref:
456             return SvROK(sv);
457             break;
458         case ScalarRef:
459             return check_is_scalar_ref(sv);
460             break;
461         case ArrayRef:
462         case HashRef:
463         case CodeRef:
464         case GlobRef:
465             return check_reftype(type, sv);
466             break;
467         case RegexpRef:
468             return ( sv_isobject(sv) && ( strEQ("Regexp", HvNAME_get(SvSTASH(SvRV(sv)))) ) );
469             break;
470         case Object:
471             return ( sv_isobject(sv) && ( strNE("Regexp", HvNAME_get(SvSTASH(SvRV(sv)))) ) );
472             break;
473         case ClassName:
474             if ( SvOK(sv) && !SvROK(sv) ) {
475                 STRLEN len;
476                 char *pv;
477                 pv = SvPV(sv, len);
478                 return ( gv_stashpvn(pv, len, 0) != NULL );
479             }
480             return 0;
481             break;
482         case FileHandle:
483             croak("todo");
484             break;
485         default:
486             croak("todo");
487     }
488
489     return 0;
490 }
491
492 /* invoke a CV on an SV and return SvTRUE of the result */
493 STATIC bool check_sv_cv (pTHX_ SV *cv, SV *sv) {
494     bool ret;
495     dSP;
496
497     ENTER;
498     SAVETMPS;
499     PUSHMARK(SP);
500     XPUSHs(sv);
501     PUTBACK;
502
503     call_sv(cv, G_SCALAR);
504
505     SPAGAIN;
506     ret = SvTRUE(POPs);
507
508     PUTBACK;
509     FREETMPS;
510     LEAVE;
511
512     return ret;
513 }
514
515 /* checks the type constraint for an SV based on the type constraint kind */
516 STATIC bool check_type_constraint(pTHX_ tc_kind kind, TC_CHECK tc_check, SV *type_constraint, SV *sv) {
517     switch (kind) {
518         case tc_none:
519             return 1;
520             break;
521         case tc_type:
522             return check_sv_type(tc_check.type, sv);
523             break;
524         case tc_stash:
525             return check_sv_class(aTHX_ (HV *)tc_check.sv, sv);
526             break;
527         case tc_fptr:
528             return tc_check.fptr(aTHX_ type_constraint, sv);
529             break;
530         case tc_cv:
531             return check_sv_cv(aTHX_ tc_check.sv, sv);
532             break;
533         case tc_enum:
534             croak("todo\n");
535             break;
536     }
537
538     croak("todo");
539     return 0;
540 }
541
542
543 /* end of type constraint checking functions */
544
545
546
547
548
549
550
551
552
553 /* Initialize the ATTR structure using positional arguments from Perl space. */
554
555 STATIC void init_attr (MI *mi, ATTR *attr, AV *desc) {
556     U32 flags = 0;
557     U32 slot_hash, init_arg_hash;
558     STRLEN slot_len, init_arg_len;
559     char *slot_pv, *init_arg_pv;
560     I32 ix = av_len(desc);
561     SV **params = AvARRAY(desc);
562     SV *tc;
563     SV *slot_sv;
564     SV *init_arg_sv;
565
566     attr->mi = mi;
567
568     if ( ix != 13 )
569         croak("wrong number of args (%d != 14)", ix + 1);
570
571     for ( ; ix >= 0; ix-- ) {
572         if ( !params[ix] || params[ix] == &PL_sv_undef )
573             croak("bad params");
574     }
575
576
577
578     /* handle attribute slot array */
579
580     if ( !SvROK(params[1]) || SvTYPE(SvRV(params[1])) != SVt_PVAV )
581         croak("slots is not an array");
582
583     if ( av_len((AV *)SvRV(params[1])) != 0 )
584         croak("Only unary slots are supported at the moment");
585
586     /* calculate a hash from the slot */
587     /* FIXME arrays etc should also be supported */
588     slot_sv = *av_fetch((AV *)SvRV(params[1]), 0, 0);
589     slot_pv = SvPV(slot_sv, slot_len);
590     PERL_HASH(slot_hash, slot_pv, slot_len);
591
592
593     init_arg_sv = params[13];
594     init_arg_pv = SvPV(init_arg_sv, init_arg_len);
595     PERL_HASH(init_arg_hash, init_arg_pv, init_arg_len);
596
597
598     /* FIXME better organize these, positionals suck */
599     if ( SvTRUE(params[2]) )
600         flags |= ATTR_WEAK;
601
602     if ( SvTRUE(params[3]) )
603         flags |= ATTR_COERCE;
604
605     if ( SvTRUE(params[4]) )
606         flags |= ATTR_LAZY;
607
608
609
610     /* type constraint data */
611
612     tc = params[5];
613
614     if ( SvOK(tc) ) {
615         int tc_kind = SvIV(params[6]);
616         SV *data = params[7];
617
618         switch (tc_kind) {
619             case tc_type:
620                 attr->tc_check.type = SvIV(data);
621                 break;
622             case tc_stash:
623                 flags |= ATTR_TCREFCNT;
624                 attr->tc_check.sv = (SV *)gv_stashsv(data, 0);
625                 break;
626             case tc_cv:
627                 flags |= ATTR_TCREFCNT;
628                 attr->tc_check.sv = SvRV(data);
629                 if ( SvTYPE(attr->tc_check.sv) != SVt_PVCV )
630                     croak("compiled type constraint is not a coderef");
631                 break;
632             default:
633                 croak("todo");
634         }
635
636         flags |= tc_kind;
637     }
638
639     
640
641     /* default/builder data */
642
643     if ( SvTRUE(params[10]) ) { /* has default */
644         SV *sv = params[11];
645
646         if ( SvROK(sv) ) {
647             attr->def.sv = SvRV(sv);
648             if ( SvTYPE(attr->def.sv) != SVt_PVCV )
649                 croak("compiled type constraint is not a coderef");
650         } else {
651             attr->def.sv = newSVsv(sv);
652             sv_2mortal(attr->def.sv); /* in case of error soon, we refcnt inc it later after we're done checking params */
653         }
654
655         flags |= ( ATTR_DEFREFCNT | ( default_normal << ATTR_SHIFT_DEFAULT ) );
656     } else if ( SvOK(params[12]) ) { /* builder */
657         attr->def.sv = newSVsv(params[12]);
658         flags |= ( ATTR_DEFREFCNT | ( default_builder << ATTR_SHIFT_DEFAULT ) );
659     }
660
661
662
663     attr->trigger = SvROK(params[6]) ? (CV *)SvRV(params[6]) : NULL;
664     if ( attr->trigger && SvTYPE(attr->trigger) != SVt_PVCV )
665         croak("trigger is not a coderef");
666
667     attr->initializer = SvROK(params[7]) ? (CV *)SvRV(params[7]) : NULL;
668     if ( attr->initializer && SvTYPE(attr->initializer) != SVt_PVCV )
669         croak("initializer is not a coderef");
670
671
672
673     /* now that we're done preparing/checking args and shit, so we finalize the
674      * attr, increasing refcounts for any referenced data, and creating the CV
675      * array */
676
677     attr->flags = flags;
678
679     /* copy the outer ref SV */
680     attr->meta_attr       = newSVsv(params[0]);
681     attr->type_constraint = newSVsv(tc);
682
683     /* increase the refcount for auxillary structures */
684     SvREFCNT_inc(attr->trigger);
685     SvREFCNT_inc(attr->initializer);
686     if ( flags & ATTR_TCREFCNT )  SvREFCNT_inc(attr->tc_check.sv);
687     if ( flags & ATTR_DEFREFCNT ) SvREFCNT_inc(attr->def.sv);
688
689     attr->slot_sv = newSVpvn_share(slot_pv, slot_len, slot_hash);
690     attr->slot_u32 = slot_hash;
691
692     attr->init_arg_sv = newSVpvn_share(init_arg_pv, init_arg_len, init_arg_hash);
693     attr->init_arg_u32 = init_arg_hash;
694
695     /* cross refs to CVs which use this struct */
696     attr->cvs = newAV();
697 }
698
699 STATIC SV *new_mi (pTHX_ HV *stash, AV *attrs) {
700     HV *mi_stash = gv_stashpvs("Moose::XS::Meta::Instance",0);
701     SV *sv_ptr = newSViv(0);
702     SV *obj = sv_2mortal(sv_bless(newRV_noinc(sv_ptr), mi_stash));
703     MI *mi;
704     const I32 num_attrs = av_len(attrs) + 1;
705
706     Newxz(mi, 1, MI);
707
708     /* set the pointer now, if we have any initialization errors it'll get
709      * cleaned up because obj is mortal */
710     sv_setiv(sv_ptr, PTR2IV(mi));
711
712     Newxz(mi->attrs, num_attrs, ATTR);
713
714     SvREFCNT_inc_simple(stash);
715     mi->stash = stash;
716
717     mi->type = 0; /* nothing else implemented yet */
718
719     /* initialize attributes */
720     for ( ; mi->num_attrs < num_attrs; mi->num_attrs++ ) {
721         SV **desc = av_fetch(attrs, mi->num_attrs, 0);
722
723         if ( !desc || !*desc || !SvROK(*desc) || !(SvTYPE(SvRV(*desc)) == SVt_PVAV) ) {
724             croak("Attribute descriptor has to be a hash reference");
725         }
726
727         init_attr(mi, &mi->attrs[mi->num_attrs], (AV *)SvRV(*desc));
728     }
729
730     return obj;
731 }
732
733 STATIC void delete_attr (pTHX_ ATTR *attr) {
734     I32 i;
735     SV **cvs = AvARRAY(attr->cvs);
736
737     /* remove the pointers to this ATTR struct from all the the dependent CVs */
738     for ( i = av_len(attr->cvs); i >= 0; i-- ) {
739         CV *cv = (CV *)cvs[i];
740         XSANY.any_i32 = 0;
741     }
742
743     SvREFCNT_dec(attr->cvs);
744     SvREFCNT_dec(attr->slot_sv);
745     SvREFCNT_dec(attr->type_constraint);
746     if ( attr->flags & ATTR_TCREFCNT )  SvREFCNT_dec(attr->tc_check.sv);
747     if ( attr->flags & ATTR_DEFREFCNT ) SvREFCNT_dec(attr->def.sv);
748     SvREFCNT_dec(attr->initializer);
749     SvREFCNT_dec(attr->trigger);
750     SvREFCNT_dec(attr->meta_attr);
751 }
752
753 STATIC void delete_mi (pTHX_ MI *mi) {
754     SvREFCNT_dec(mi->stash);
755
756     while ( mi->num_attrs--) {
757         ATTR *attr = &mi->attrs[mi->num_attrs];
758         delete_attr(aTHX_ attr);
759     }
760
761     if ( mi->attrs ) Safefree(mi->attrs);
762     Safefree(mi);
763 }
764
765
766
767
768 /* these functions call Perl-space for MOP methods, helpers etc */
769
770
771 /* wow, so much code for the equivalent of
772  * $attr->associated_class->get_meta_instance */
773 STATIC SV *attr_to_meta_instance(pTHX_ SV *meta_attr) {
774     dSP;
775     I32 count;
776     SV *mi;
777
778     if ( !meta_attr )
779         croak("No attr found in magic!");
780
781     ENTER;
782     SAVETMPS;
783     PUSHMARK(SP);
784
785     XPUSHs(meta_attr);
786
787     PUTBACK;
788     count = call_pv("Moose::XS::attr_to_meta_instance", G_SCALAR);
789
790     if ( count != 1 )
791         croak("attr_to_meta_instance borked (%d args returned, expecting 1)", count);
792
793     SPAGAIN;
794     mi = POPs;
795
796     SvREFCNT_inc(mi);
797
798     PUTBACK;
799     FREETMPS;
800     LEAVE;
801
802     return sv_2mortal(mi);
803 }
804
805 /* gets a class and an array of attr parameters */
806 STATIC SV *perl_mi_to_c_mi(pTHX_ SV *perl_mi) {
807     dSP;
808     I32 count;
809     SV *mi;
810     SV *class;
811     SV *attrs;
812     HV *stash;
813
814     ENTER;
815     SAVETMPS;
816     PUSHMARK(SP);
817
818     XPUSHs(perl_mi);
819
820     PUTBACK;
821     count = call_pv("Moose::XS::meta_instance_to_attr_descs", G_ARRAY);
822
823     if ( count != 2 )
824         croak("meta_instance_to_attr_descs borked (%d args returned, expecting 2)", count);
825
826     SPAGAIN;
827     attrs = POPs;
828     class = POPs;
829
830     PUTBACK;
831
832     stash = gv_stashsv(class, 0);
833
834     mi = new_mi(aTHX_ stash, (AV *)SvRV(attrs));
835     SvREFCNT_inc(mi);
836
837     FREETMPS;
838     LEAVE;
839
840     return sv_2mortal(mi);
841 }
842
843
844
845 /* locate an ATTR for a MOP level attribute inside an MI */
846 STATIC ATTR *mi_find_attr(SV *mi_obj, SV *meta_attr) {
847     I32 ix;
848     MI *mi = INT2PTR(MI *, SvIV(SvRV(mi_obj)));
849
850     for ( ix = 0; ix < mi->num_attrs; ix++ ) {
851         if ( SvRV(mi->attrs[ix].meta_attr) == SvRV(meta_attr) ) {
852             return &mi->attrs[ix];
853         }
854     }
855
856     croak("Attr %x not found in meta instance of %s", SvRV(meta_attr) /* SvPV_force_nomg(sv_2mortal(newSVsv(meta_attr))) */, HvNAME_get(mi->stash) );
857     return NULL;
858 }
859
860 /* returns the ATTR for a CV:
861  *
862  * 1. get the Moose::Meta::Attribute using get_stashed_in_mg from the CV itself
863  * 2. get the meta instance by calling $attr->associated_class->get_meta_instance
864  * 3. get the MI by using get_stashed_in_mg from the meta instance, creating it if necessary
865  * 4. search for the appropriate ATTR in the MI using mi_find_attr
866  */
867 STATIC ATTR *get_attr(pTHX_ CV *cv) {
868     SV *meta_attr = get_stashed_in_mg(aTHX_ (SV *)cv);
869     SV *perl_mi = attr_to_meta_instance(aTHX_ meta_attr);
870     SV *mi_obj = get_stashed_in_mg(aTHX_ SvRV(perl_mi));
871
872     if (!mi_obj) {
873         mi_obj = perl_mi_to_c_mi(aTHX_ perl_mi);
874         stash_in_mg(aTHX_ SvRV(perl_mi), mi_obj);
875     }
876
877     return mi_find_attr(mi_obj, meta_attr);
878 }
879
880 /* Cache a pointer to the appropriate ATTR in the XSANY of the CV, using
881  * get_attr */
882 STATIC ATTR *define_attr (pTHX_ CV *cv) {
883     ATTR *attr = get_attr(aTHX_ cv);
884     assert(attr);
885
886     XSANY.any_i32 = PTR2IV(attr);
887
888     SvREFCNT_inc(cv);
889     av_push( attr->cvs, (SV *)cv );
890
891     return attr;
892 }
893
894
895
896
897
898
899
900 STATIC void weaken(pTHX_ SV *sv) {
901 #ifdef SvWEAKREF
902         sv_rvweaken(sv); /* FIXME i think this might warn when weakening an already weak ref */
903 #else
904         croak("weak references are not implemented in this release of perl");
905 #endif
906 }
907
908
909
910
911
912
913 /* meta instance protocol */
914
915 STATIC SV *get_slot_value(pTHX_ SV *self, ATTR *attr) {
916     HE *he;
917
918     assert(self);
919     assert(SvROK(self));
920     assert(SvTYPE(SvRV(self)) == SVt_PVHV);
921
922     assert( ATTR_DUMB_INSTANCE(attr) );
923
924     if ((he = hv_fetch_ent((HV *)SvRV(self), attr->slot_sv, 0, attr->slot_u32)))
925         return HeVAL(he);
926     else
927         return NULL;
928 }
929
930 STATIC void set_slot_value(pTHX_ SV *self, ATTR *attr, SV *value) {
931     HE *he;
932     SV *copy;
933
934     assert(self);
935     assert(SvROK(self));
936     assert(SvTYPE(SvRV(self)) == SVt_PVHV);
937
938     assert( ATTR_DUMB_INSTANCE(attr) );
939
940     copy = newSVsv(value);
941
942     he = hv_store_ent((HV*)SvRV(self), attr->slot_sv, copy, attr->slot_u32);
943
944     if (he != NULL) {
945         if ( ATTR_ISWEAK(attr) )
946             weaken(aTHX_ HeVAL(he));
947     } else {
948         SvREFCNT_dec(copy);
949         croak("Hash store failed.");
950     }
951 }
952
953 STATIC bool has_slot_value(pTHX_ SV *self, ATTR *attr) {
954     assert(self);
955     assert(SvROK(self));
956     assert(SvTYPE(SvRV(self)) == SVt_PVHV);
957
958     assert( ATTR_DUMB_INSTANCE(attr) );
959
960     return hv_exists_ent((HV *)SvRV(self), attr->slot_sv, attr->slot_u32);
961 }
962
963 STATIC SV *deinitialize_slot(pTHX_ SV *self, ATTR *attr) {
964     assert(self);
965     assert(SvROK(self));
966     assert(SvTYPE(SvRV(self)) == SVt_PVHV);
967
968     assert( ATTR_DUMB_INSTANCE(attr) );
969
970     return hv_delete_ent((HV *)SvRV(self), attr->slot_sv, 0, attr->slot_u32);
971 }
972
973 STATIC SV *create_instance(pTHX_ MI *mi) {
974     return sv_bless(sv_2mortal(newRV_noinc((SV *)newHV())), mi->stash);
975 }
976
977
978
979
980 /* Shared functionality for readers/writers/accessors, this roughly corresponds
981  * to the methods of Moose::Meta::Attribute on the instance
982  * (get_value/set_value, default value handling, etc) */
983
984 STATIC void attr_set_value(pTHX_ SV *self, ATTR *attr, SV *value);
985
986 STATIC SV *call_builder (pTHX_ SV *self, ATTR *attr) {
987     SV *sv;
988     dSP;
989
990     ENTER;
991     SAVETMPS;
992     PUSHMARK(SP);
993
994     XPUSHs(self);
995
996     /* we invoke the builder as a stringified method. This will not work for
997      * $obj->$coderef etc, for that we need to use 'default' */
998     PUTBACK;
999     call_method(SvPV_nolen(attr->def.sv), G_SCALAR);
1000     SPAGAIN;
1001
1002     /* the value is a mortal with a refcount of 1, so we need to keep it around */
1003     sv = POPs;
1004     SvREFCNT_inc(sv);
1005
1006     PUTBACK;
1007     FREETMPS;
1008     LEAVE;
1009
1010     return sv_2mortal(sv);
1011 }
1012
1013
1014 /* Returns an SV for the default value. Should be copied by the caller because
1015  * it's either an alias for a simple value, or a mortal from cv/builder */
1016 STATIC SV *get_default(pTHX_ SV *self, ATTR *attr) {
1017     switch ( ATTR_DEFAULT(attr) ) {
1018         case default_none:
1019             return NULL;
1020             break;
1021         case default_builder:
1022             return call_builder(aTHX_ self, attr);
1023             break;
1024         case default_normal:
1025             if ( SvROK(attr->def.sv) ) {
1026                 printf("CV default\n");
1027                 croak("todo");
1028             } else {
1029                 printf("simple value\n");
1030                 return attr->def.sv; /* will be copied by set for lazy, and by reader for both cases */
1031             }
1032             break;
1033         case default_type:
1034             croak("todo");
1035             break;
1036     }
1037
1038     return NULL;
1039 }
1040
1041 /* $attr->get_value($self), will vivify lazy values if needed
1042  * returns an alias to the sv that is copied in the reader/writer/accessor code
1043  * */
1044 STATIC SV *attr_get_value(pTHX_ SV *self, ATTR *attr) {
1045     SV *value = get_slot_value(aTHX_ self, attr);
1046
1047     if ( value ) {
1048         return value;
1049     } else if ( ATTR_ISLAZY(attr) ) {
1050         value = get_default(aTHX_ self, attr);
1051         attr_set_value(aTHX_ self, attr, value);
1052         return value;
1053     }
1054
1055     return NULL;
1056 }
1057
1058 /* $attr->set_value($self) */
1059 STATIC void attr_set_value(pTHX_ SV *self, ATTR *attr, SV *value) {
1060     if ( ATTR_TYPE(attr) ) {
1061         if ( !check_type_constraint(aTHX_ ATTR_TYPE(attr), attr->tc_check, attr->type_constraint, value) )
1062             croak("Bad param");
1063     }
1064
1065     set_slot_value(aTHX_ self, attr, value);
1066 }
1067
1068
1069
1070
1071
1072
1073
1074 /* Perl-space level functionality
1075  *
1076  * These subs are installed by new_sub's various aliases as the bodies of the
1077  * new XSUBs
1078  * */
1079
1080
1081
1082 /* This macro is used in the XS subs to set up the 'attr' variable.
1083  *
1084  * if XSANY is NULL then define_attr is called on the CV, to set the pointer
1085  * to the ATTR struct.
1086  * */
1087 #define dATTR ATTR *attr = (XSANY.any_i32 ? INT2PTR(ATTR *, (XSANY.any_i32)) : define_attr(aTHX_ cv))
1088
1089
1090 STATIC XS(reader);
1091 STATIC XS(reader)
1092 {
1093 #ifdef dVAR
1094     dVAR;
1095 #endif
1096     dXSARGS;
1097     dATTR;
1098     SV *value;
1099
1100     if (items != 1)
1101         Perl_croak(aTHX_ "Usage: %s(%s)", GvNAME(CvGV(cv)), "self");
1102
1103     SP -= items;
1104
1105     value = attr_get_value(aTHX_ ST(0), attr);
1106
1107     if (value) {
1108         ST(0) = sv_mortalcopy(value); /* mortalcopy because $_ .= "blah" for $foo->bar */
1109         XSRETURN(1);
1110     } else {
1111         XSRETURN_UNDEF;
1112     }
1113 }
1114
1115 STATIC XS(writer);
1116 STATIC XS(writer)
1117 {
1118 #ifdef dVAR
1119     dVAR;
1120 #endif
1121     dXSARGS;
1122     dATTR;
1123
1124     if (items != 2)
1125         Perl_croak(aTHX_ "Usage: %s(%s, %s)", GvNAME(CvGV(cv)), "self", "value");
1126
1127     SP -= items;
1128
1129     attr_set_value(aTHX_ ST(0), attr, ST(1));
1130
1131     ST(0) = ST(1); /* return value */
1132     XSRETURN(1);
1133 }
1134
1135 STATIC XS(accessor);
1136 STATIC XS(accessor)
1137 {
1138 #ifdef dVAR
1139     dVAR;
1140 #endif
1141     dXSARGS;
1142     dATTR;
1143
1144     if (items < 1)
1145         Perl_croak(aTHX_ "Usage: %s(%s, [ %s ])", GvNAME(CvGV(cv)), "self", "value");
1146
1147     SP -= items;
1148
1149     if (items > 1) {
1150         attr_set_value(aTHX_ ST(0), attr, ST(1));
1151         ST(0) = ST(1); /* return value */
1152     } else {
1153         SV *value = attr_get_value(aTHX_ ST(0), attr);
1154         if ( value ) {
1155             ST(0) = value;
1156         } else {
1157             XSRETURN_UNDEF;
1158         }
1159     }
1160
1161     XSRETURN(1);
1162 }
1163
1164 STATIC XS(predicate);
1165 STATIC XS(predicate)
1166 {
1167 #ifdef dVAR
1168     dVAR;
1169 #endif
1170     dXSARGS;
1171     dATTR;
1172
1173     if (items != 1)
1174         Perl_croak(aTHX_ "Usage: %s(%s)", GvNAME(CvGV(cv)), "self");
1175
1176     SP -= items;
1177
1178     if ( has_slot_value(aTHX_ ST(0), attr) )
1179         XSRETURN_YES;
1180     else
1181         XSRETURN_NO;
1182 }
1183
1184 enum xs_body {
1185     xs_body_reader = 0,
1186     xs_body_writer,
1187     xs_body_accessor,
1188     xs_body_predicate,
1189     max_xs_body
1190 };
1191
1192 STATIC XSPROTO ((*xs_bodies[])) = {
1193     reader,
1194     writer,
1195     accessor,
1196     predicate,
1197 };
1198
1199 MODULE = Moose PACKAGE = Moose::XS
1200 PROTOTYPES: ENABLE
1201
1202 CV *
1203 new_sub(attr, name)
1204     INPUT:
1205         SV *attr;
1206         SV *name;
1207     PROTOTYPE: $;$
1208     ALIAS:
1209         new_reader    = xs_body_reader
1210         new_writer    = xs_body_writer
1211         new_accessor  = xs_body_accessor
1212         new_predicate = xs_body_predicate
1213     PREINIT:
1214         CV * cv;
1215     CODE:
1216         if ( ix >= max_xs_body )
1217             croak("Unknown Moose::XS body type");
1218
1219         if ( !sv_isobject(attr) )
1220             croak("'attr' must be a Moose::Meta::Attribute");
1221
1222         cv = newXS(SvOK(name) ? SvPV_nolen(name) : NULL, xs_bodies[ix], __FILE__);
1223
1224         if (cv == NULL)
1225             croak("Oi vey!");
1226
1227         /* associate CV with meta attr */
1228         stash_in_mg(aTHX_ (SV *)cv, attr);
1229
1230         /* this will be set on first call */
1231         XSANY.any_i32 = 0;
1232
1233         RETVAL = cv;
1234     OUTPUT:
1235         RETVAL
1236
1237
1238 MODULE = Moose  PACKAGE = Moose::XS::Meta::Instance
1239 PROTOTYPES: DISABLE
1240
1241 void
1242 DESTROY(self)
1243     INPUT:
1244         SV *self;
1245     PREINIT:
1246         MI *mi = INT2PTR(MI *, SvIV(SvRV(self)));
1247     CODE:
1248         if ( mi )
1249             delete_mi(aTHX_ mi);
1250
1251
1252 MODULE = Moose  PACKAGE = Moose::XS::TypeConstraints
1253 PROTOTYPES: ENABLE
1254
1255 bool
1256 _check_type(sv)
1257     INPUT:
1258         SV* sv
1259     ALIAS:
1260         Any = Any
1261         Item = Any
1262         Bool = Any
1263         Undef = Undef
1264         Defined = Defined
1265         Str = Str
1266         Value = Str
1267         Num = Num
1268         Int = Int
1269         GlobRef = GlobRef
1270         ArrayRef = ArrayRef
1271         HashRef = HashRef
1272         CodeRef = CodeRef
1273         Ref = Ref
1274         ScalarRef = ScalarRef
1275         FileHandle = FileHandle
1276         RegexpRef = RegexpRef
1277         Object = Object
1278         Role = Role
1279         ClassName = ClassName
1280     CODE:
1281         RETVAL = check_sv_type(ix, sv);
1282     OUTPUT:
1283         RETVAL
1284
1285 bool
1286 ObjectOfType(sv, class)
1287     INPUT:
1288         SV* sv
1289         SV* class
1290     PREINIT:
1291         HV *stash = gv_stashsv(class, 0);
1292     CODE:
1293         RETVAL = check_sv_class(aTHX_ stash, sv);
1294     OUTPUT:
1295         RETVAL