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