1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! macros to make working with cases where there is generic code but not generic types
//! such as dispatching an API method on an `RtObject` or `Type`, creating method wrappers
//! (e.g. x = 1; func = x.__hash__ since `__hash__` should be an object representing
//! `PyInteger::op_hash` for the instance ), shorthand for default implementations, etc.
//!


/// Creates default "not implemented" impls for the Objects.
///
/// As an example suppose there is a new type `PyDatabaseConnector` that
/// should not implement the context manager traits `::api::method::Enter`
/// and `::api::method::Exit`. Since `PyDatabaseConnector` must implement all traits
/// of `::api::PyAPI` but the default implementations already return a `Result::Err`
/// (specifically, `Err(Error::system_not_implemented(...)).` There are many
/// impl blocks that are empty.
///
/// # Examples
///
/// This macro allows for these cases to be short-hand with the following:
///
/// ```rust
/// use ::api::method;
///
/// method_not_implemented!(PyDatabaseConnector, Enter Exit);
/// ```
macro_rules! method_not_implemented {
  ($Type:ty, $($ApiTrait:ident)+) => {
    $(
        impl method::$ApiTrait for $Type {}
    )+
  };
}

/// Expands a `&builtins::types::Type` into its variant specific inner type
/// and dispatches a named `PyAPI` op-prefixed method based on the number of arguments
/// matched by the pattern.
///
macro_rules! foreach_type {
    ($sel:expr, $rt:expr, $function:ident, $receiver:ident) => (
        unary_op_foreach!($sel, $rt, $function, $receiver)
    );
    ($sel:expr, $rt:expr, $function:ident, $receiver:ident, $rhs:ident) => (
        binary_op_foreach!($sel, $rt, $function, $receiver, $rhs)
    );
    ($sel:expr, $rt:expr, $function:ident, $receiver:ident, $arg0:ident, $arg1:ident) => (
        ternary_op_foreach!($sel, $rt, $function, $receiver, $arg0, $arg1)
    );
    ($sel:expr, $rt:expr, $function:ident, $receiver:ident, $arg0:ident, $arg1:ident, $arg2:ident) => (
        _4ary_op_foreach!($sel, $rt, $function, $receiver, $arg0, $arg1, $arg2)
    );
}

/// A more flexible sibling of the `foreach_type!` and `native_foreach_type!` macros
/// which will allow execution an arbitrary block of code on
/// the inner value of any variant of `Type`. The `$inner:ident` is
/// identifier used to reference the match expanded value within the given code block.
///
/// # Examples
///
/// ```rust
///  let object: RtObject = rt.int(1);  // or something that produces an RtObject
///
///  expr_foreach_type!(object.as_ref(), value, {
///     write!(f, "{:?}", value)
/// })
/// ```
macro_rules! expr_foreach_type {
    ($obj:expr, $inner:ident, $e:block) => (
       match $obj {
            &Type::Bool(ref $inner) => $e,
            &Type::None(ref $inner) => $e,
            &Type::Int(ref $inner) => $e,
            &Type::Float(ref $inner) => $e,
            &Type::Iter(ref $inner) => $e,
            &Type::Dict(ref $inner) => $e,
            &Type::Str(ref $inner) => $e,
            &Type::Bytes(ref $inner) => $e,
            &Type::Tuple(ref $inner) =>$e,
            &Type::List(ref $inner) =>$e,
            &Type::Function(ref $inner) => $e,
            &Type::Object(ref $inner) => $e,
            &Type::Type(ref $inner) => $e,
            &Type::Module(ref $inner) => $e,
            &Type::Code(ref $inner) => $e,
            &Type::Frame(ref $inner) => $e,
            &Type::Set(ref $inner) => $e,
            &Type::FrozenSet(ref $inner) => $e,

            _ => unreachable!()
        }
    );
}


/// Type variant expansion and dispatch for unary `PyAPI` methods. This is called
/// by `foreach_type!` based on the macro pattern patching. When in doubt, use
/// `foreach_type!`.
///
macro_rules! unary_op_foreach{
    ($obj:expr, $rt:expr, $op:ident, $lhs:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($rt),
            &Type::None(ref $lhs) => $lhs.$op($rt),
            &Type::Int(ref $lhs) => $lhs.$op($rt),
            &Type::Float(ref $lhs) => $lhs.$op($rt),
            &Type::Iter(ref $lhs) => $lhs.$op($rt),
            &Type::Dict(ref $lhs) => $lhs.$op($rt),
            &Type::Str(ref $lhs) => $lhs.$op($rt),
            &Type::Bytes(ref $lhs) => $lhs.$op($rt),
            &Type::Tuple(ref $lhs) => $lhs.$op($rt),
            &Type::List(ref $lhs) => $lhs.$op($rt),
            &Type::Function(ref $lhs) => $lhs.$op($rt),
            &Type::Object(ref $lhs) => $lhs.$op($rt),
            &Type::Type(ref $lhs) => $lhs.$op($rt),
            &Type::Module(ref $lhs) => $lhs.$op($rt),
            &Type::Code(ref $lhs) => $lhs.$op($rt),
            &Type::Frame(ref $lhs) => $lhs.$op($rt),
            &Type::Set(ref $lhs) => $lhs.$op($rt),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($rt),

            _ => unreachable!()
        }
    };
}


/// Type variant expansion and dispatch for binary `PyAPI` `op` prefixed methods.
/// This is called by `foreach_type!` based on the macro pattern patching.
/// When in doubt, use the `foreach_type!` macro.
///
macro_rules! binary_op_foreach{
    ($obj:expr, $rt:expr, $op:ident, $lhs:ident, $rhs:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::None(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Int(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Float(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Iter(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Dict(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Str(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Bytes(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Tuple(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::List(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Function(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Object(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Type(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Module(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Code(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Frame(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::Set(ref $lhs) => $lhs.$op($rt, $rhs),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($rt, $rhs),

            _ => unreachable!()
        }
    };
}


/// Type variant expansion and dispatch for ternary `PyAPI` `op` prefixed methods.
/// This is called by `foreach_type!` based on the macro pattern patching.
/// When in doubt, use the `foreach_type!` macro.
///
macro_rules! ternary_op_foreach{
    ($obj:expr, $rt:expr, $op:ident, $lhs:ident, $mid:ident, $rhs:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::None(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Int(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Float(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Iter(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Dict(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Str(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Bytes(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Tuple(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::List(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Function(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Object(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Type(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Module(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Code(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Frame(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::Set(ref $lhs) => $lhs.$op($rt, $mid, $rhs),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($rt, $mid, $rhs),

            _ => unreachable!()
        }
    };
}


/// Type variant expansion and dispatch for 4ary `PyAPI` `op` prefixed methods.
/// This is called by `foreach_type!` based on the macro pattern patching.
/// When in doubt, use the `foreach_type!` macro.
///
macro_rules! _4ary_op_foreach{
    ($obj:expr, $rt:expr, $op:ident, $lhs:ident, $arg0:ident, $arg1:ident, $arg2:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::None(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Int(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Float(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Iter(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Dict(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Str(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Bytes(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Tuple(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::List(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Function(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Object(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Type(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Module(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Code(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Frame(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::Set(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($rt, $arg0, $arg1, $arg2),

            _ => unreachable!()
        }
    };
}

/// Like `foreach_type!` but for `PyAPI` methods that are prefixed with `native_` indicating
/// they do not need a `&Runtime`.
macro_rules! native_foreach_type {
    ($sel:expr, $function:ident, $receiver:ident) => (
        native_unary_op_foreach!($sel, $function, $receiver)
    );
    ($sel:expr, $function:ident, $receiver:ident, $rhs:ident) => (
        native_binary_op_foreach!($sel, $function, $receiver, $rhs)
    );
    ($sel:expr, $function:ident, $receiver:ident, $arg0:ident, $arg1:ident) => (
        native_ternary_op_foreach!($sel, $function, $receiver, $arg0, $arg1)
    );
    ($sel:expr, $function:ident, $receiver:ident, $arg0:ident, $arg1:ident, $arg2:ident) => (
        native_4ary_op_foreach!($sel, $function, $receiver, $arg0, $arg1, $arg2)
    )
}


/// The `native` version of `unary_op_foreach!`
macro_rules! native_unary_op_foreach{
    ($obj:expr, $op:ident, $lhs:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op(),
            &Type::None(ref $lhs) => $lhs.$op(),
            &Type::Int(ref $lhs) => $lhs.$op(),
            &Type::Float(ref $lhs) => $lhs.$op(),
            &Type::Iter(ref $lhs) => $lhs.$op(),
            &Type::Dict(ref $lhs) => $lhs.$op(),
            &Type::Str(ref $lhs) => $lhs.$op(),
            &Type::Bytes(ref $lhs) => $lhs.$op(),
            &Type::Tuple(ref $lhs) => $lhs.$op(),
            &Type::List(ref $lhs) => $lhs.$op(),
            &Type::Function(ref $lhs) => $lhs.$op(),
            &Type::Object(ref $lhs) => $lhs.$op(),
            &Type::Type(ref $lhs) => $lhs.$op(),
            &Type::Module(ref $lhs) => $lhs.$op(),
            &Type::Code(ref $lhs) => $lhs.$op(),
            &Type::Frame(ref $lhs) => $lhs.$op(),
            &Type::Set(ref $lhs) => $lhs.$op(),
            &Type::FrozenSet(ref $lhs) => $lhs.$op(),

            _ => unreachable!()
        }
    };
}

/// The `native` version of `binary_op_foreach!`
macro_rules! native_binary_op_foreach{
    ($obj:expr, $op:ident, $lhs:ident, $rhs:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($rhs),
            &Type::None(ref $lhs) => $lhs.$op($rhs),
            &Type::Int(ref $lhs) => $lhs.$op($rhs),
            &Type::Float(ref $lhs) => $lhs.$op($rhs),
            &Type::Iter(ref $lhs) => $lhs.$op($rhs),
            &Type::Dict(ref $lhs) => $lhs.$op($rhs),
            &Type::Str(ref $lhs) => $lhs.$op($rhs),
            &Type::Bytes(ref $lhs) => $lhs.$op($rhs),
            &Type::Tuple(ref $lhs) => $lhs.$op($rhs),
            &Type::List(ref $lhs) => $lhs.$op($rhs),
            &Type::Function(ref $lhs) => $lhs.$op($rhs),
            &Type::Object(ref $lhs) => $lhs.$op($rhs),
            &Type::Type(ref $lhs) => $lhs.$op($rhs),
            &Type::Module(ref $lhs) => $lhs.$op($rhs),
            &Type::Code(ref $lhs) => $lhs.$op($rhs),
            &Type::Frame(ref $lhs) => $lhs.$op($rhs),
            &Type::Set(ref $lhs) => $lhs.$op($rhs),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($rhs),

            _ => unreachable!()
        }
    };
}

/// The `native` version of `ternary_op_foreach!`
macro_rules! native_ternary_op_foreach{
    ($obj:expr, $op:ident, $lhs:ident, $mid:ident, $rhs:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::None(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Int(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Float(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Iter(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Dict(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Str(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Bytes(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Tuple(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::List(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Function(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Object(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Type(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Module(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Code(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Frame(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::Set(ref $lhs) => $lhs.$op($mid, $rhs),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($mid, $rhs),

            _ => unreachable!()
        }
    };
}


/// The `native` version of `_4ary_op_foreach!`
macro_rules! native_4ary_op_foreach {
    ($obj:expr, $op:ident, $lhs:ident, $arg0:ident, $arg1:ident, $arg2:ident) => {
        match $obj {
            &Type::Bool(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::None(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Int(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Float(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Iter(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Dict(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Str(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Bytes(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Tuple(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::List(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Function(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Object(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Type(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Module(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Code(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Frame(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::Set(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),
            &Type::FrozenSet(ref $lhs) => $lhs.$op($arg0, $arg1, $arg2),

            _ => unreachable!()
        }
    };
}


/// Macro to create Object and native typed `PyAPI` trait definitions.
///
/// Each Function is generated with a default implementation that
/// will return a NotImplemented error.
///
/// Note that for arity of Functions may appear deceiving since the receiver (self)
/// is always the first argument and is the first argument by convention.
///
macro_rules! api_trait {
    (unary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident, $nativety:ty) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel) -> RtResult<$nativety> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (unary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel) -> RtResult<Type> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (binary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident, $nativety:ty) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime, &RtObject) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel, &Type) -> RtResult<$nativety> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (binary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime, &RtObject) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel, &Type) -> RtResult<Type> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (ternary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident, $nativety:ty) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime, &RtObject, &RtObject) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel, &Type, &Type) -> RtResult<$nativety> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (ternary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime, &RtObject, &RtObject) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel, &Type, &Type) -> RtResult<Type> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (4ary, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime, &RtObject, &RtObject, &RtObject) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            /// Native API Method $pyname
            fn $nfname(&$sel, &Type, &Type, &Type) -> RtResult<Type> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
    (variadic, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident) => {
        pub trait $tname {
            /// Runtime API Method $pyname
            fn $fname(&$sel, &Runtime, &Vec<RtObject>) -> ObjectResult {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }

            #[doc=stringify!(Native API Method $pyname)]
            fn $nfname(&$sel, &Vec<Type>) -> RtResult<Type> {
                Err(Error::system_not_implemented(stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) ))
            }
        }
    };
}


/// Create a test stub that panics with unimplemented. Originally used to give an idea of coverage
/// but has been refactored out of existence.
macro_rules! api_test_stub {
    ($args:ident, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident) => {
        //#[test]
        fn $pyname() {
            trace!("[stub] {} {} {} {} {}", stringify!($args), stringify!($pyname), &format!("file: {}, line: {}", file!(), line!()) , stringify!($tname), stringify!($fname), stringify!($nfname));
            unimplemented!()
        }
    };
    ($args:ident, $sel:ident, $pyname:ident, $tname:ident, $fname:ident, $nfname:ident, $($misc:ty),*) => {
        api_test_stub!($args, $sel, $pyname, $tname, $fname, $nfname);
    };
}



// Errors that should be in resource::strings but constant format strings are
// kind of an edge case I guess.
/// Generic formatting for a bad operand message. Given the python:
/// ```ignore
/// x = 1 + '3245'
/// ```
/// It will produce the string "unsupported operand type(s) for +: 'int' and 'str'.
macro_rules! strings_error_bad_operand {
    ($op:expr, $lhs:expr, $rhs:expr) => {
        format!("unsupported operand type(s) for {}: '{}' and '{}'", $op, $lhs, $rhs);
    }
}


/// Missing attribute error message formatter
macro_rules! strings_error_no_attribute {
    ($obj:expr, $attr:expr) => {
        format!("'{}' has no attribute '{:?}'", $obj, $attr);
    }
}

/// Attribute not string
macro_rules! string_error_bad_attr_type {
    ($expect:expr, $actual:expr) => {
        &format!("attribute type must be '{}' not '{}'", $expect, $actual)
    }
}

/// Generic index exception formatter
macro_rules! rsnek_exception_index {
    ($typ:expr) => {
        Error::index(&format!("{} {}", $typ, strings::ERROR_INDEX_OUT_OF_RANGE))
    }
}

/// Generate the code inline to wrap a native rust `PyAPI` unary method as a method-wrapper in a
/// generic way since the methods cause the function signatures to be type specific to the
/// implementation. For example, `PyInteger::op_add` has a signature of
/// `Fn(&PyInteger, &Runtime, &ObjectRef) -> ObjectResult`. There might be a way to
/// do this using Trait objects but the lifetimes/Sized-ness of the trait objects
/// always trips my implementations.
///
macro_rules! unary_method_wrapper (
    ($sel:ident, $tname:expr, $fname:ident, $rt:ident, $builtin:path, $func:ident) => ({
        let selfref = $sel.rc.upgrade()?;
        let callable: Box<rs::WrapperFn> = Box::new(move |rt, pos_args, starargs, kwargs| {
            let object = selfref.clone();
            check_args(0, &pos_args)?;
            check_args(0, &starargs)?;
            check_kwargs(0, &kwargs)?;

            match object.as_ref() {
                &$builtin(ref value) => {
                $func(value, rt)
                }
                _ => unreachable!()
            }
        });

        Ok($rt.function(rs::Func {
            name: format!("'{}' of {} object", $fname, $tname),
            signature: [].as_args(),
            module: strings::BUILTINS_MODULE.to_string(),
            callable: rs::FuncType::MethodWrapper($sel.rc.upgrade()?, callable)
        }))

    });
);


/// Generate the code inline to wrap a native rust `PyAPI` binary method as a method-wrapper in a
/// generic way since the methods cause the function signatures to be type specific to the
/// implementation. For example, `PyInteger::op_add` has a signature of
/// `Fn(&PyInteger, &Runtime, &ObjectRef) -> ObjectResult`. There might be a way to
/// do this using Trait objects but the lifetimes/Sized-ness of the trait objects
/// always trips my implementations.
///
macro_rules! binary_method_wrapper (
    ($sel:ident, $tname:expr, $fname:ident, $rt:ident, $builtin:path, $func:ident) => ({
        let selfref = $sel.rc.upgrade()?;
        let callable: Box<rs::WrapperFn> = Box::new(move |rt, pos_args, starargs, kwargs| {
            let object = selfref.clone();
            check_args(1, &pos_args)?;
            check_args(0, &starargs)?;
            check_kwargs(0, &kwargs)?;

            let arg = pos_args.op_getitem(&rt, &rt.int(0))?;

            match object.as_ref() {
                &$builtin(ref value) => {
                $func(value, rt, &arg)
                }
                _ => unreachable!()
            }
        });

        Ok($rt.function(rs::Func {
            name: format!("'{}' of {} object", $fname, $tname),
            signature: ["arg1"].as_args(),
            module: strings::BUILTINS_MODULE.to_string(),
            callable: rs::FuncType::MethodWrapper($sel.rc.upgrade()?, callable)
        }))

    });
);


/// Generate the code inline to wrap a native rust `PyAPI` ternary method as a method-wrapper in a
/// generic way since the methods cause the function signatures to be type specific to the
/// implementation. For example, `PyInteger::op_add` has a signature of
/// `Fn(&PyInteger, &Runtime, &ObjectRef) -> ObjectResult`. There might be a way to
/// do this using Trait objects but the lifetimes/Sized-ness of the trait objects
/// always trips my implementations.
///
macro_rules! ternary_method_wrapper (
    ($sel:ident, $tname:expr, $fname:ident, $rt:ident, $builtin:path, $func:ident) => ({
        let selfref = $sel.rc.upgrade()?;
        let callable: Box<rs::WrapperFn> = Box::new(move |rt, pos_args, starargs, kwargs| {
            let object = selfref.clone();
            check_args(2, &pos_args)?;
            check_args(0, &starargs)?;
            check_kwargs(0, &kwargs)?;

            let arg1 = pos_args.op_getitem(&rt, &rt.int(0))?;
            let arg2 = pos_args.op_getitem(&rt, &rt.int(1))?;
            match object.as_ref() {
                &$builtin(ref value) => {
                $func(value, rt, &arg1, &arg2)
                }
                _ => unreachable!()
            }
        });

        Ok($rt.function(rs::Func {
            name: format!("'{}' of {} object", $fname, $tname),
            signature: ["arg1", "arg2"].as_args(),
            module: strings::BUILTINS_MODULE.to_string(),
            callable: rs::FuncType::MethodWrapper($sel.rc.upgrade()?, callable)
        }))

    });
);