Tidy
[gitmo/Mouse.git] / xs-src / Mouse.xs
1 #define  NEED_newSVpvn_flags_GLOBAL
2 #include "mouse.h"
3
4 SV* mouse_package;
5 SV* mouse_namespace;
6 SV* mouse_methods;
7 SV* mouse_name;
8 SV* mouse_get_attribute;
9 SV* mouse_get_attribute_list;
10
11 #define MOUSE_xc_flags(a)       SvUVX(MOUSE_av_at((a), MOUSE_XC_FLAGS))
12 #define MOUSE_xc_gen(a)         MOUSE_av_at((a), MOUSE_XC_GEN)
13 #define MOUSE_xc_stash(a)       ( (HV*)MOUSE_av_at((a), MOUSE_XC_STASH) )
14 #define MOUSE_xc_attrall(a)     ( (AV*)MOUSE_av_at((a), MOUSE_XC_ATTRALL) )
15 #define MOUSE_xc_buildall(a)    ( (AV*)MOUSE_av_at((a), MOUSE_XC_BUILDALL) )
16 #define MOUSE_xc_demolishall(a) ( (AV*)MOUSE_av_at((a), MOUSE_XC_DEMOLISHALL) )
17
18 enum mouse_xc_flags_t {
19     MOUSEf_XC_IS_IMMUTABLE   = 0x0001,
20     MOUSEf_XC_IS_ANON        = 0x0002,
21     MOUSEf_XC_HAS_BUILDARGS  = 0x0004,
22
23     MOUSEf_XC_mask           = 0xFFFF /* not used */
24 };
25
26 /* Mouse XS Metaclass object */
27 enum mouse_xc_ix_t{
28     MOUSE_XC_FLAGS,
29
30     MOUSE_XC_GEN,          /* class generation */
31     MOUSE_XC_STASH,        /* symbol table hash */
32
33     MOUSE_XC_ATTRALL,      /* all the attributes */
34     MOUSE_XC_BUILDALL,     /* all the BUILD methods */
35     MOUSE_XC_DEMOLISHALL,  /* all the DEMOLISH methods */
36
37     MOUSE_XC_last
38 };
39
40 static MGVTBL mouse_xc_vtbl; /* for identity */
41
42 static void
43 mouse_class_push_attribute_list(pTHX_ SV* const metaclass, AV* const attrall, HV* const seen){
44     dSP;
45     I32 n;
46
47     /* $meta->get_attribute_list */
48     PUSHMARK(SP);
49     XPUSHs(metaclass);
50     PUTBACK;
51
52     n = call_sv(mouse_get_attribute_list, G_ARRAY | G_METHOD);
53     for(NOOP; n > 0; n--){
54         SV* name;
55
56         SPAGAIN;
57         name = POPs;
58         PUTBACK;
59
60         if(hv_exists_ent(seen, name, 0U)){
61             continue;
62         }
63         (void)hv_store_ent(seen, name, &PL_sv_undef, 0U);
64
65         av_push(attrall, newSVsv( mcall1(metaclass, mouse_get_attribute, name) ));
66     }
67 }
68
69 static int
70 mouse_class_has_custom_buildargs(pTHX_ HV* const stash) {
71     XS(XS_Mouse__Object_BUILDARGS); /* prototype */
72
73     GV* const buildargs = gv_fetchmeth_autoload(stash, "BUILDARGS", sizeof("BUILDARGS")-1, 0);
74
75     return buildargs && CvXSUB(GvCV(buildargs)) != XS_Mouse__Object_BUILDARGS;
76 }
77
78 static void
79 mouse_class_update_xc(pTHX_ SV* const metaclass PERL_UNUSED_DECL, HV* const stash, AV* const xc) {
80     AV* const linearized_isa = mro_get_linear_isa(stash);
81     I32 const len            = AvFILLp(linearized_isa);
82     I32 i;
83     U32 flags             = 0x00;
84     AV* const attrall     = newAV();
85     AV* const buildall    = newAV();
86     AV* const demolishall = newAV();
87     HV* const seen        = newHV(); /* for attributes */
88
89     ENTER;
90     SAVETMPS;
91
92     sv_2mortal((SV*)seen);
93
94      /* old data will be delete at the end of the perl scope */
95     av_delete(xc, MOUSE_XC_DEMOLISHALL, 0x00);
96     av_delete(xc, MOUSE_XC_BUILDALL,    0x00);
97     av_delete(xc, MOUSE_XC_ATTRALL,     0x00);
98
99     SvREFCNT_inc_simple_void_NN(linearized_isa);
100     sv_2mortal((SV*)linearized_isa);
101
102     /* update */
103
104     if(predicate_calls(metaclass, "is_immutable")){
105         flags |= MOUSEf_XC_IS_IMMUTABLE;
106     }
107
108     if(predicate_calls(metaclass, "is_anon_class")){
109         flags |= MOUSEf_XC_IS_ANON;
110     }
111
112     if(mouse_class_has_custom_buildargs(aTHX_ stash)){
113         flags |= MOUSEf_XC_HAS_BUILDARGS;
114     }
115
116     av_store(xc, MOUSE_XC_FLAGS,       newSVuv(flags));
117     av_store(xc, MOUSE_XC_ATTRALL,     (SV*)attrall);
118     av_store(xc, MOUSE_XC_BUILDALL,    (SV*)buildall);
119     av_store(xc, MOUSE_XC_DEMOLISHALL, (SV*)demolishall);
120
121     for(i = 0; i < len; i++){
122         SV* const klass = MOUSE_av_at(linearized_isa, i);
123         HV* const st    = gv_stashsv(klass, TRUE);
124         SV* meta;
125         GV* gv;
126
127         gv = stash_fetchs(st, "BUILD", FALSE);
128         if(gv && GvCVu(gv)){
129             av_unshift(buildall, 1);
130             av_store(buildall, 0, newRV_inc((SV*)GvCV(gv)));
131         }
132
133         gv = stash_fetchs(st, "DEMOLISH", FALSE);
134         if(gv && GvCVu(gv)){
135             av_push(demolishall, newRV_inc((SV*)GvCV(gv)));
136         }
137
138         /* ATTRIBUTES */
139         meta = get_metaclass(klass);
140         if(!SvOK(meta)){
141             continue; /* skip non-Mouse classes */
142         }
143
144         mouse_class_push_attribute_list(aTHX_ meta, attrall, seen);
145     }
146
147     FREETMPS;
148     LEAVE;
149
150     sv_setuv(MOUSE_xc_gen(xc), mro_get_pkg_gen(stash));
151 }
152
153 static AV*
154 mouse_get_xc(pTHX_ SV* const metaclass) {
155     AV* xc;
156     SV* gen;
157     HV* stash;
158     MAGIC* mg;
159
160     if(!IsObject(metaclass)){
161         croak("Not a Mouse metaclass");
162     }
163
164     mg = mouse_mg_find(aTHX_ SvRV(metaclass), &mouse_xc_vtbl, 0x00);
165     if(!mg){
166         SV* const package = get_slot(metaclass, mouse_package);
167         STRLEN len;
168         const char* const pv = SvPV_const(package, len);
169
170         stash = gv_stashpvn(pv, len, TRUE);
171         xc    = newAV();
172
173         mg = sv_magicext(SvRV(metaclass), (SV*)xc, PERL_MAGIC_ext, &mouse_xc_vtbl, pv, len);
174         SvREFCNT_dec(xc); /* refcnt++ in sv_magicext */
175
176         av_extend(xc, MOUSE_XC_last - 1);
177
178         av_store(xc, MOUSE_XC_GEN, newSVuv(0U));
179         av_store(xc, MOUSE_XC_STASH, (SV*)stash);
180
181         SvREFCNT_inc_simple_void_NN(stash);
182     }
183     else{
184         xc    = (AV*)MOUSE_mg_obj(mg);
185
186         assert(xc);
187         assert(SvTYPE(xc) == SVt_PVAV);
188     }
189
190     gen   = MOUSE_xc_gen(xc);
191
192     if(SvUVX(gen) != 0U && MOUSE_xc_flags(xc) & MOUSEf_XC_IS_IMMUTABLE){
193         return xc;
194     }
195
196     stash = MOUSE_xc_stash(xc);
197
198     if(SvUVX(gen) != mro_get_pkg_gen(stash)){
199         mouse_class_update_xc(aTHX_ metaclass, stash, xc);
200     }
201
202     return xc;
203 }
204
205 static HV*
206 mouse_buildargs(pTHX_ SV* metaclass, SV* const klass, I32 ax, I32 items) {
207     HV* args;
208
209     /* shift @_ */
210     ax++;
211     items--;
212
213     if(items == 1){
214         SV* const args_ref = ST(0);
215         if(!IsHashRef(args_ref)){
216             if(!metaclass){ metaclass = get_metaclass(klass); }
217             mouse_throw_error(metaclass, NULL, "Single parameters to new() must be a HASH ref");
218         }
219         args = newHVhv((HV*)SvRV(args_ref));
220         sv_2mortal((SV*)args);
221     }
222     else{
223         I32 i;
224
225         args = newHV_mortal();
226
227         if( (items % 2) != 0 ){
228             if(!metaclass){ metaclass = get_metaclass(klass); }
229             mouse_throw_error(metaclass, NULL, "Odd number of parameters to new()");
230         }
231
232         for(i = 0; i < items; i += 2){
233             (void)hv_store_ent(args, ST(i), newSVsv(ST(i+1)), 0U);
234         }
235
236     }
237     return args;
238 }
239
240 static void
241 mouse_class_initialize_object(pTHX_ SV* const meta, SV* const object, HV* const args, bool const ignore_triggers) {
242     AV* const xc    = mouse_get_xc(aTHX_ meta);
243     AV* const attrs = MOUSE_xc_attrall(xc);
244     I32 len         = AvFILLp(attrs) + 1;
245     I32 i;
246     AV* triggers_queue = NULL;
247
248     assert(meta || object);
249     assert(args);
250     assert(SvTYPE(args) == SVt_PVHV);
251
252     ENTER;
253     SAVETMPS;
254
255     if(!ignore_triggers){
256         triggers_queue = newAV_mortal();
257     }
258
259     for(i = 0; i < len; i++){
260         SV* const attr = AvARRAY(attrs)[i];
261         AV* const xa   = mouse_get_xa(aTHX_ AvARRAY(attrs)[i]);
262
263         SV* const slot     = MOUSE_xa_slot(xa);
264         U16 const flags    = (U16)MOUSE_xa_flags(xa);
265         SV* const init_arg = MOUSE_xa_init_arg(xa);
266         HE* he;
267
268         if(SvOK(init_arg) && ( he = hv_fetch_ent(args, init_arg, FALSE, 0U) ) ){
269             SV* value = HeVAL(he);
270             if(flags & MOUSEf_ATTR_HAS_TC){
271                 value = mouse_xa_apply_type_constraint(aTHX_ xa, value, flags);
272             }
273             set_slot(object, slot, value);
274             if(SvROK(value) && flags & MOUSEf_ATTR_IS_WEAK_REF){
275                 weaken_slot(object, slot);
276             }
277             if(flags & MOUSEf_ATTR_HAS_TRIGGER && triggers_queue){
278                 AV* const pair = newAV();
279                 av_push(pair, newSVsv( mcall0s(attr, "trigger") ));
280                 av_push(pair, newSVsv(value));
281
282                 av_push(triggers_queue, (SV*)pair);
283             }
284         }
285         else { /* no init arg */
286             if(flags & (MOUSEf_ATTR_HAS_DEFAULT | MOUSEf_ATTR_HAS_BUILDER)){
287                 if(!(flags & MOUSEf_ATTR_IS_LAZY)){
288                     mouse_xa_set_default(aTHX_ xa, object);
289                 }
290             }
291             else if(flags & MOUSEf_ATTR_IS_REQUIRED) {
292                 mouse_throw_error(attr, NULL, "Attribute (%"SVf") is required", slot);
293             }
294         }
295     } /* for each attributes */
296
297     if(triggers_queue){
298         len = AvFILLp(triggers_queue) + 1;
299         for(i = 0; i < len; i++){
300             AV* const pair    = (AV*)AvARRAY(triggers_queue)[i];
301             SV* const trigger = AvARRAY(pair)[0];
302             SV* const value   = AvARRAY(pair)[1];
303
304             mcall1(object, trigger, value);
305         }
306     }
307
308     if(MOUSE_xc_flags(xc) & MOUSEf_XC_IS_ANON){
309         set_slot(object, newSVpvs_flags("__ANON__", SVs_TEMP), meta);
310     }
311
312     FREETMPS;
313     LEAVE;
314 }
315
316 static SV*
317 mouse_initialize_metaclass(pTHX_ SV* const klass) {
318     SV* meta = get_metaclass(klass);
319
320     if(!SvOK(meta)){
321         dSP;
322         PUSHMARK(SP);
323
324         EXTEND(SP, 2);
325         mPUSHp("Mouse::Meta::Class", sizeof("Mouse::Meta::Class")-1);
326         PUSHs(klass);
327         PUTBACK;
328
329         call_method("initialize", G_SCALAR);
330         SPAGAIN;
331         meta = POPs;
332         PUTBACK;
333     }
334
335     return meta;
336 }
337
338 MODULE = Mouse  PACKAGE = Mouse
339
340 PROTOTYPES: DISABLE
341
342 BOOT:
343     mouse_package   = newSVpvs_share("package");
344     mouse_namespace = newSVpvs_share("namespace");
345     mouse_methods   = newSVpvs_share("methods");
346     mouse_name      = newSVpvs_share("name");
347
348     mouse_get_attribute      = newSVpvs_share("get_attribute");
349     mouse_get_attribute_list = newSVpvs_share("get_attribute_list");
350
351     MOUSE_CALL_BOOT(Mouse__Util);
352     MOUSE_CALL_BOOT(Mouse__Util__TypeConstraints);
353     MOUSE_CALL_BOOT(Mouse__Meta__Method__Accessor__XS);
354     MOUSE_CALL_BOOT(Mouse__Meta__Attribute);
355
356
357 MODULE = Mouse  PACKAGE = Mouse::Meta::Module
358
359 BOOT:
360     INSTALL_SIMPLE_READER_WITH_KEY(Module, name, package);
361     INSTALL_SIMPLE_READER_WITH_KEY(Module, _method_map, methods);
362     INSTALL_SIMPLE_READER_WITH_KEY(Module, _attribute_map, attributes);
363
364 HV*
365 namespace(SV* self)
366 CODE:
367 {
368     SV* const package = get_slot(self, mouse_package);
369     if(!(package && SvOK(package))){
370         croak("No package name defined");
371     }
372     RETVAL = gv_stashsv(package, GV_ADDMULTI);
373 }
374 OUTPUT:
375     RETVAL
376
377 # ignore extra arguments for extensibility
378 void
379 add_method(SV* self, SV* name, SV* code, ...)
380 CODE:
381 {
382     SV* const package = get_slot(self, mouse_package); /* $self->{package} */
383     SV* const methods = get_slot(self, mouse_methods); /* $self->{methods} */
384     GV* gv;
385     SV* code_ref;
386
387     if(!(package && SvOK(package))){
388         croak("No package name defined");
389     }
390
391     SvGETMAGIC(name);
392     SvGETMAGIC(code);
393
394     if(!SvOK(name)){
395         mouse_throw_error(self, NULL, "You must define a method name");
396     }
397     if(!SvROK(code)){
398         mouse_throw_error(self, NULL, "You must define a CODE reference");
399     }
400
401     code_ref = code;
402     if(SvTYPE(SvRV(code_ref)) != SVt_PVCV){
403         SV*  sv = code_ref;  /* used in tryAMAGICunDEREF */
404         SV** sp = &sv;       /* used in tryAMAGICunDEREF */
405         tryAMAGICunDEREF(to_cv); /* try \&{$code} */
406         if(SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV){
407             mouse_throw_error(self, NULL, "Not a CODE reference");
408         }
409         code_ref = sv;
410     }
411
412     /*  *{$package . '::' . $name} -> *gv */
413     gv = gv_fetchpv(form("%"SVf"::%"SVf, package, name), GV_ADDMULTI, SVt_PVCV);
414     if(GvCVu(gv)){ /* delete *slot{gv} to work around "redefine" warning */
415         SvREFCNT_dec(GvCV(gv));
416         GvCV(gv) = NULL;
417     }
418     sv_setsv_mg((SV*)gv, code_ref); /* *gv = $code_ref */
419
420     set_slot(methods, name, code); /* $self->{methods}{$name} = $code */
421
422     /* name the CODE ref if it's anonymous */
423     {
424         CV* const code_entity = (CV*)SvRV(code_ref);
425         if(CvANON(code_entity)
426             && CvGV(code_entity) /* a cv under construction has no gv */ ){
427
428             CvGV(code_entity) = gv;
429             CvANON_off(code_entity);
430         }
431     }
432 }
433
434 MODULE = Mouse  PACKAGE = Mouse::Meta::Class
435
436 BOOT:
437     INSTALL_SIMPLE_READER(Class, roles);
438     INSTALL_SIMPLE_PREDICATE_WITH_KEY(Class, is_anon_class, anon_serial_id);
439
440     INSTALL_SIMPLE_READER_WITH_DEFAULTS(Class, method_metaclass,     "Mouse::Meta::Method");
441     INSTALL_SIMPLE_READER_WITH_DEFAULTS(Class, attribute_metaclass,  "Mouse::Meta::Attribute");
442     INSTALL_SIMPLE_READER_WITH_DEFAULTS(Class, constructor_class,    "Mouse::Meta::Method::Constructor::XS");
443     INSTALL_SIMPLE_READER_WITH_DEFAULTS(Class, destructor_class,     "Mouse::Meta::Method::Destructor::XS");
444
445     newCONSTSUB(gv_stashpvs("Mouse::Meta::Method::Constructor::XS", TRUE), "_generate_constructor",
446         newRV_inc((SV*)get_cvs("Mouse::Object::new", TRUE)));
447     newCONSTSUB(gv_stashpvs("Mouse::Meta::Method::Destructor::XS", TRUE), "_generate_destructor",
448         newRV_inc((SV*)get_cvs("Mouse::Object::DESTROY", TRUE)));
449
450
451 void
452 linearized_isa(SV* self)
453 PPCODE:
454 {
455     SV* const stash_ref = mcall0(self, mouse_namespace); /* $self->namespace */
456     AV* linearized_isa;
457     I32 len;
458     I32 i;
459     if(!(SvROK(stash_ref) && SvTYPE(SvRV(stash_ref)) == SVt_PVHV)){
460         croak("namespace() didn't return a HASH reference");
461     }
462     linearized_isa = mro_get_linear_isa((HV*)SvRV(stash_ref));
463     len = AvFILLp(linearized_isa) + 1;
464     EXTEND(SP, len);
465     for(i = 0; i < len; i++){
466         PUSHs(AvARRAY(linearized_isa)[i]);
467     }
468 }
469
470 void
471 get_all_attributes(SV* self)
472 PPCODE:
473 {
474     AV* const xc        = mouse_get_xc(aTHX_ self);
475     AV* const all_attrs =  MOUSE_xc_attrall(xc);
476     I32 const len       = AvFILLp(all_attrs) + 1;
477     I32 i;
478
479     EXTEND(SP, len);
480     for(i = 0; i < len; i++){
481         PUSHs( MOUSE_av_at(all_attrs, i) );
482     }
483 }
484
485 SV*
486 new_object(SV* meta, ...)
487 CODE:
488 {
489     AV* const xc   = mouse_get_xc(aTHX_ meta);
490     HV* const args = mouse_buildargs(aTHX_ meta, NULL, ax, items);
491
492     RETVAL = mouse_instance_create(aTHX_ MOUSE_xc_stash(xc));
493     mouse_class_initialize_object(aTHX_ meta, RETVAL, args, FALSE);
494 }
495 OUTPUT:
496     RETVAL
497
498 void
499 _initialize_object(SV* meta, SV* object, HV* args, bool ignore_triggers = FALSE)
500 CODE:
501 {
502     mouse_class_initialize_object(aTHX_ meta, object, args, ignore_triggers);
503 }
504
505 MODULE = Mouse  PACKAGE = Mouse::Meta::Role
506
507 BOOT:
508     INSTALL_SIMPLE_READER_WITH_KEY(Role, get_roles, roles);
509     INSTALL_SIMPLE_PREDICATE_WITH_KEY(Role, is_anon_role, anon_serial_id);
510
511     INSTALL_SIMPLE_READER_WITH_DEFAULTS(Role, method_metaclass,  "Mouse::Meta::Role::Method");
512
513 MODULE = Mouse  PACKAGE = Mouse::Object
514
515 SV*
516 new(SV* klass, ...)
517 CODE:
518 {
519     SV* const meta = mouse_initialize_metaclass(aTHX_ klass);
520     AV* const xc   = mouse_get_xc(aTHX_ meta);
521     UV const flags = MOUSE_xc_flags(xc);
522     SV* args;
523     AV* buildall;
524     I32 len, i;
525
526     /* BUILDARGS */
527     if(flags & MOUSEf_XC_HAS_BUILDARGS){
528         SPAGAIN;
529
530         PUSHMARK(SP);
531         EXTEND(SP, items);
532         for(i = 0; i < items; i++){
533             PUSHs(ST(i));
534         }
535         //SP += items;
536         PUTBACK;
537         call_method("BUILDARGS", G_SCALAR);
538         SPAGAIN;
539         args = POPs;
540         PUTBACK;
541
542         if(!IsHashRef(args)){
543             croak("BUILDARGS did not return a HASH reference");
544         }
545     }
546     else{
547         args = newRV_inc((SV*)mouse_buildargs(aTHX_ meta, klass, ax, items));
548         sv_2mortal(args);
549     }
550
551     /* new_object */
552     RETVAL = mouse_instance_create(aTHX_ MOUSE_xc_stash(xc));
553     mouse_class_initialize_object(aTHX_ meta, RETVAL, (HV*)SvRV(args), FALSE);
554
555     /* BUILDALL */
556     buildall = MOUSE_xc_buildall(xc);
557     len      = AvFILLp(buildall) + 1;
558     for(i = 0; i < len; i++){
559         dSP;
560
561         PUSHMARK(SP);
562         EXTEND(SP, 2);
563         PUSHs(RETVAL);
564         PUSHs(args);
565         PUTBACK;
566
567         call_sv(AvARRAY(buildall)[i], G_VOID | G_DISCARD);
568     }
569 }
570 OUTPUT:
571     RETVAL
572
573 void
574 DESTROY(SV* object)
575 CODE:
576 {
577     SV* const meta = get_metaclass(object);
578     AV* demolishall;
579     I32 len, i;
580
581     if(!IsObject(object)){
582         croak("You must not call DESTROY as a class method");
583     }
584
585     if(SvOK(meta)){
586         AV* const xc = mouse_get_xc(aTHX_ meta);
587
588         demolishall = MOUSE_xc_demolishall(xc);
589     }
590     else {
591         AV* const linearized_isa = mro_get_linear_isa(SvSTASH(SvRV(object)));
592
593         len = AvFILLp(linearized_isa) + 1;
594
595         demolishall = newAV_mortal();
596         for(i = 0; i < len; i++){
597             SV* const klass = MOUSE_av_at(linearized_isa, i);
598             HV* const st    = gv_stashsv(klass, TRUE);
599             GV* const gv    = stash_fetchs(st, "DEMOLISH", FALSE);
600             if(gv && GvCVu(gv)){
601                 av_push(demolishall, newRV_inc((SV*)GvCV(gv)));
602             }
603         }
604     }
605
606     /* DEMOLISHALL */
607     len      = AvFILLp(demolishall) + 1;
608     if(len > 0){
609         GV* const statusvalue = gv_fetchpvs("?", 0, SVt_PV);
610         SAVESPTR(GvSV(statusvalue)); /* local $? */
611         SAVESPTR(ERRSV); /* local $@ */
612
613         GvSV(statusvalue) = sv_2mortal(newSViv(0));
614         ERRSV             = sv_2mortal(newSVpvs(""));
615         for(i = 0; i < len; i++){
616             dSP;
617
618             PUSHMARK(SP);
619             XPUSHs(object);
620             PUTBACK;
621
622             call_sv(AvARRAY(demolishall)[i], G_VOID | G_DISCARD | G_EVAL);
623             if(SvTRUE(ERRSV)){
624                 SV* const e = newSVsv(ERRSV);
625
626                 FREETMPS;
627                 LEAVE;
628
629                 sv_setsv(ERRSV, e);
630                 SvREFCNT_dec(e);
631                 croak(NULL); /* rethrow */
632             }
633         }
634     }
635 }
636
637 HV*
638 BUILDARGS(SV* klass, ...)
639 CODE:
640 {
641     RETVAL = mouse_buildargs(aTHX_ NULL, klass, ax, items);
642 }
643 OUTPUT:
644     RETVAL
645
646