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