Fix BUILDARGS logic
[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         SV* meta;
124         GV* gv;
125
126         gv = stash_fetchs(stash, "BUILD", FALSE);
127         if(gv && GvCVu(gv)){
128             av_push(buildall, newRV_inc((SV*)GvCV(gv)));
129         }
130
131         gv = stash_fetchs(stash, "DEMOLISH", FALSE);
132         if(gv && GvCVu(gv)){
133             av_push(demolishall, newRV_inc((SV*)GvCV(gv)));
134         }
135
136         /* ATTRIBUTES */
137         meta = get_metaclass(klass);
138         if(!SvOK(meta)){
139             continue; /* skip non-Mouse classes */
140         }
141
142         mouse_class_push_attribute_list(aTHX_ meta, attrall, seen);
143     }
144
145     FREETMPS;
146     LEAVE;
147
148     sv_setuv(MOUSE_xc_gen(xc), mro_get_pkg_gen(stash));
149 }
150
151 AV*
152 mouse_get_xc(pTHX_ SV* const metaclass) {
153     AV* xc;
154     SV* gen;
155     HV* stash;
156     MAGIC* mg;
157
158     if(!IsObject(metaclass)){
159         croak("Not a Mouse metaclass");
160     }
161
162     mg = mouse_mg_find(aTHX_ SvRV(metaclass), &mouse_xc_vtbl, 0x00);
163     if(!mg){
164         SV* const package = get_slot(metaclass, mouse_package);
165         STRLEN len;
166         const char* const pv = SvPV_const(package, len);
167
168         stash = gv_stashpvn(pv, len, TRUE);
169         xc    = newAV();
170
171         mg = sv_magicext(SvRV(metaclass), (SV*)xc, PERL_MAGIC_ext, &mouse_xc_vtbl, pv, len);
172         SvREFCNT_dec(xc); /* refcnt++ in sv_magicext */
173
174         av_extend(xc, MOUSE_XC_last - 1);
175
176         av_store(xc, MOUSE_XC_GEN, newSViv(0));
177         av_store(xc, MOUSE_XC_STASH, (SV*)stash);
178
179         SvREFCNT_inc_simple_void_NN(stash);
180     }
181     else{
182         xc    = (AV*)MOUSE_mg_obj(mg);
183
184         assert(xc);
185         assert(SvTYPE(xc) == SVt_PVAV);
186     }
187
188     gen   = MOUSE_xc_gen(xc);
189     stash = MOUSE_xc_stash(xc);
190
191     if(SvUV(gen) != mro_get_pkg_gen(stash)){
192         mouse_class_update_xc(aTHX_ metaclass, stash, xc);
193     }
194
195     return xc;
196 }
197
198 HV*
199 mouse_build_args(pTHX_ SV* metaclass, SV* const klass, I32 const start, I32 const items, I32 const ax) {
200     HV* args;
201     if((items - start) == 1){
202         SV* const args_ref = ST(start);
203         if(!IsHashRef(args_ref)){
204             if(!metaclass){ metaclass = get_metaclass(klass); }
205             mouse_throw_error(metaclass, NULL, "Single parameters to new() must be a HASH ref");
206         }
207         args = newHVhv((HV*)SvRV(args_ref));
208         sv_2mortal((SV*)args);
209     }
210     else{
211         I32 i;
212
213         args = newHV_mortal();
214
215         if( ((items - start) % 2) != 0 ){
216             if(!metaclass){ metaclass = get_metaclass(klass); }
217             mouse_throw_error(metaclass, NULL, "Odd number of parameters to new()");
218         }
219
220         for(i = start; i < items; i += 2){
221             (void)hv_store_ent(args, ST(i), newSVsv(ST(i+1)), 0U);
222         }
223
224     }
225     return args;
226 }
227
228 void
229 mouse_class_initialize_object(pTHX_ SV* const meta, SV* const object, HV* const args, bool const ignore_triggers) {
230     AV* const xc    = mouse_get_xc(aTHX_ meta);
231     AV* const attrs = MOUSE_xc_attrall(xc);
232     I32 len         = AvFILLp(attrs) + 1;
233     I32 i;
234     AV* triggers_queue = NULL;
235
236     ENTER;
237     SAVETMPS;
238
239     if(!ignore_triggers){
240         triggers_queue = newAV_mortal();
241     }
242
243     for(i = 0; i < len; i++){
244         SV* const attr = AvARRAY(attrs)[i];
245         AV* const xa   = mouse_get_xa(aTHX_ AvARRAY(attrs)[i]);
246
247         SV* const slot     = MOUSE_xa_slot(xa);
248         U16 const flags    = (U16)MOUSE_xa_flags(xa);
249         SV* const init_arg = MOUSE_xa_init_arg(xa);
250         HE* he;
251
252         if(SvOK(init_arg) && ( he = hv_fetch_ent(args, init_arg, FALSE, 0U) ) ){
253             SV* value = HeVAL(he);
254             if(flags & MOUSEf_ATTR_HAS_TC){
255                 value = mouse_xa_apply_type_constraint(aTHX_ xa, value, flags);
256             }
257             set_slot(object, slot, value);
258             if(SvROK(value) && flags & MOUSEf_ATTR_IS_WEAK_REF){
259                 weaken_slot(object, slot);
260             }
261             if(flags & MOUSEf_ATTR_HAS_TRIGGER && triggers_queue){
262                 AV* const pair = newAV();
263                 av_push(pair, newSVsv( mcall0s(attr, "trigger") ));
264                 av_push(pair, newSVsv(value));
265
266                 av_push(triggers_queue, (SV*)pair);
267             }
268         }
269         else { /* no init arg */
270             if(flags & (MOUSEf_ATTR_HAS_DEFAULT | MOUSEf_ATTR_HAS_BUILDER)){
271                 if(!(flags & MOUSEf_ATTR_IS_LAZY)){
272                     mouse_xa_set_default(aTHX_ xa, object);
273                 }
274             }
275             else if(flags & MOUSEf_ATTR_IS_REQUIRED) {
276                 mouse_throw_error(attr, NULL, "Attribute (%"SVf") is required", slot);
277             }
278         }
279     } /* for each attributes */
280
281     if(triggers_queue){
282         len = AvFILLp(triggers_queue) + 1;
283         for(i = 0; i < len; i++){
284             AV* const pair    = (AV*)AvARRAY(triggers_queue)[i];
285             SV* const trigger = AvARRAY(pair)[0];
286             SV* const value   = AvARRAY(pair)[1];
287
288             mcall1(object, trigger, value);
289         }
290     }
291
292     if(MOUSE_xc_flags(xc) & MOUSEf_XC_IS_ANON){
293         set_slot(object, newSVpvs_flags("__ANON__", SVs_TEMP), meta);
294     }
295
296     FREETMPS;
297     LEAVE;
298 }
299
300 MODULE = Mouse  PACKAGE = Mouse
301
302 PROTOTYPES: DISABLE
303
304 BOOT:
305     mouse_package   = newSVpvs_share("package");
306     mouse_namespace = newSVpvs_share("namespace");
307     mouse_methods   = newSVpvs_share("methods");
308     mouse_name      = newSVpvs_share("name");
309
310     mouse_get_attribute      = newSVpvs_share("get_attribute");
311     mouse_get_attribute_list = newSVpvs_share("get_attribute_list");
312
313     MOUSE_CALL_BOOT(Mouse__Util);
314     MOUSE_CALL_BOOT(Mouse__Util__TypeConstraints);
315     MOUSE_CALL_BOOT(Mouse__Meta__Method__Accessor__XS);
316     MOUSE_CALL_BOOT(Mouse__Meta__Attribute);
317
318
319 MODULE = Mouse  PACKAGE = Mouse::Meta::Module
320
321 BOOT:
322     INSTALL_SIMPLE_READER_WITH_KEY(Module, name, package);
323     INSTALL_SIMPLE_READER_WITH_KEY(Module, _method_map, methods);
324     INSTALL_SIMPLE_READER_WITH_KEY(Module, _attribute_map, attributes);
325
326 HV*
327 namespace(SV* self)
328 CODE:
329 {
330     SV* const package = get_slot(self, mouse_package);
331     if(!(package && SvOK(package))){
332         croak("No package name defined");
333     }
334     RETVAL = gv_stashsv(package, GV_ADDMULTI);
335 }
336 OUTPUT:
337     RETVAL
338
339 # ignore extra arguments for extensibility
340 void
341 add_method(SV* self, SV* name, SV* code, ...)
342 CODE:
343 {
344     SV* const package = get_slot(self, mouse_package); /* $self->{package} */
345     SV* const methods = get_slot(self, mouse_methods); /* $self->{methods} */
346     GV* gv;
347     SV* code_ref;
348
349     if(!(package && SvOK(package))){
350         croak("No package name defined");
351     }
352
353     SvGETMAGIC(name);
354     SvGETMAGIC(code);
355
356     if(!SvOK(name)){
357         mouse_throw_error(self, NULL, "You must define a method name");
358     }
359     if(!SvROK(code)){
360         mouse_throw_error(self, NULL, "You must define a CODE reference");
361     }
362
363     code_ref = code;
364     if(SvTYPE(SvRV(code_ref)) != SVt_PVCV){
365         SV*  sv = code_ref;  /* used in tryAMAGICunDEREF */
366         SV** sp = &sv;       /* used in tryAMAGICunDEREF */
367         tryAMAGICunDEREF(to_cv); /* try \&{$code} */
368         if(SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV){
369             mouse_throw_error(self, NULL, "Not a CODE reference");
370         }
371         code_ref = sv;
372     }
373
374     /*  *{$package . '::' . $name} -> *gv */
375     gv = gv_fetchpv(form("%"SVf"::%"SVf, package, name), GV_ADDMULTI, SVt_PVCV);
376     if(GvCVu(gv)){ /* delete *slot{gv} to work around "redefine" warning */
377         SvREFCNT_dec(GvCV(gv));
378         GvCV(gv) = NULL;
379     }
380     sv_setsv_mg((SV*)gv, code_ref); /* *gv = $code_ref */
381
382     set_slot(methods, name, code); /* $self->{methods}{$name} = $code */
383
384     /* TODO: name the CODE ref if it's anonymous */
385     //code_entity = (CV*)SvRV(code_ref);
386     //if(CvANON(code_entity)
387     //    && CvGV(code_entity) /* a cv under construction has no gv */ ){
388
389     //    CvGV(code_entity) = gv;
390     //    CvANON_off(code_entity);
391     //}
392 }
393
394 MODULE = Mouse  PACKAGE = Mouse::Meta::Class
395
396 BOOT:
397     INSTALL_SIMPLE_READER(Class, roles);
398     INSTALL_SIMPLE_PREDICATE_WITH_KEY(Class, is_anon_class, anon_serial_id);
399
400 void
401 linearized_isa(SV* self)
402 PPCODE:
403 {
404     SV* const stash_ref = mcall0(self, mouse_namespace); /* $self->namespace */
405     AV* linearized_isa;
406     I32 len;
407     I32 i;
408     if(!(SvROK(stash_ref) && SvTYPE(SvRV(stash_ref)) == SVt_PVHV)){
409         croak("namespace() didn't return a HASH reference");
410     }
411     linearized_isa = mro_get_linear_isa((HV*)SvRV(stash_ref));
412     len = AvFILLp(linearized_isa) + 1;
413     EXTEND(SP, len);
414     for(i = 0; i < len; i++){
415         PUSHs(AvARRAY(linearized_isa)[i]);
416     }
417 }
418
419 void
420 get_all_attributes(SV* self)
421 PPCODE:
422 {
423     AV* const xc        = mouse_get_xc(aTHX_ self);
424     AV* const all_attrs =  MOUSE_xc_attrall(xc);
425     I32 const len       = AvFILLp(all_attrs) + 1;
426     I32 i;
427
428     EXTEND(SP, len);
429     for(i = 0; i < len; i++){
430         PUSHs( MOUSE_av_at(all_attrs, i) );
431     }
432 }
433
434 SV*
435 new_object_(SV* meta, ...)
436 CODE:
437 {
438     HV* const args = mouse_build_args(aTHX_ meta, NULL, 1, items, ax);
439     AV* const xc   = mouse_get_xc(aTHX_ meta);
440
441     RETVAL = mouse_instance_create(aTHX_ MOUSE_xc_stash(xc));
442     mouse_class_initialize_object(aTHX_ meta, RETVAL, args, FALSE);
443 }
444
445
446 void
447 _initialize_object(SV* meta, SV* object, HV* args, bool ignore_triggers = FALSE)
448 CODE:
449 {
450     mouse_class_initialize_object(aTHX_ meta, object, args, ignore_triggers);
451 }
452
453 MODULE = Mouse  PACKAGE = Mouse::Meta::Role
454
455 BOOT:
456     INSTALL_SIMPLE_READER_WITH_KEY(Role, get_roles, roles);
457     INSTALL_SIMPLE_PREDICATE_WITH_KEY(Role, is_anon_role, anon_serial_id);
458
459 MODULE = Mouse  PACKAGE = Mouse::Object
460
461 HV*
462 BUILDARGS(SV* klass, ...)
463 CODE:
464 {
465     RETVAL = mouse_build_args(aTHX_ NULL, klass, 1, items, ax);
466 }
467 OUTPUT:
468     RETVAL