summaryrefslogtreecommitdiffstats
path: root/lib/kross/python/cxx/Extensions.h
blob: 48eb4e0914a1049a83c70167960c336f03cb4451 (plain)
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//---------------------------------------------------------------------------//
// Copyright 1998 The Regents of the University of California. 
// All rights reserved. See LEGAL.LLNL for full text and disclaimer.
//---------------------------------------------------------------------------//

#ifndef __CXX_Extensions__h
#define __CXX_Extensions__h


#ifdef _MSC_VER
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#endif


#include "Config.h"
#include "Objects.h"

extern "C"
	{
	extern PyObject py_object_initializer;
	}

#include <vector>
#include <map>

namespace Py
	{
	class ExtensionModuleBase;
	
	// Make an Exception Type for use in raising custom exceptions
	class ExtensionExceptionType : public Object
		{
	public:
		ExtensionExceptionType();
		virtual ~ExtensionExceptionType();

		// call init to create the type
		void init(  ExtensionModuleBase &module, const std::string& name );
		};

	
	class MethodTable 
		{
	public:
		MethodTable();
		virtual ~MethodTable();
		
		void add(const char* method_name, PyCFunction f, const char* doc="", int flag=1);
		PyMethodDef* table();
		
	protected:
		std::vector<PyMethodDef> t;	// accumulator of PyMethodDef's
		PyMethodDef *mt;		// Actual method table produced when full
		
		static PyMethodDef method (const char* method_name, PyCFunction f, int flags = 1, const char* doc="");
		
	private:
		//
		// prevent the compiler generating these unwanted functions
		//
		MethodTable(const MethodTable& m);	//unimplemented
		void operator=(const MethodTable& m);	//unimplemented
		
		}; // end class MethodTable
	
	extern "C"
		{
		typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args );
		typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict );
		}
	
	template<class T>
	class MethodDefExt : public PyMethodDef
		{
	public:
		typedef Object (T::*method_varargs_function_t)( const Tuple &args );
		typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
		
		MethodDefExt
		(
		const char *_name,
		method_varargs_function_t _function,
		method_varargs_call_handler_t _handler,
		const char *_doc
		)
			{
			ext_meth_def.ml_name = const_cast<char *>(_name);
			ext_meth_def.ml_meth = _handler;
			ext_meth_def.ml_flags = METH_VARARGS;
			ext_meth_def.ml_doc = const_cast<char *>(_doc);
			
			ext_varargs_function = _function;
			ext_keyword_function = NULL;
			}
		
		MethodDefExt
		(
		const char *_name,
		method_keyword_function_t _function,
		method_keyword_call_handler_t _handler,
		const char *_doc
		)
			{
			ext_meth_def.ml_name = const_cast<char *>(_name);
			ext_meth_def.ml_meth = method_varargs_call_handler_t( _handler );
			ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS;
			ext_meth_def.ml_doc = const_cast<char *>(_doc);
			
			ext_varargs_function = NULL;
			ext_keyword_function = _function;
			}
		
		~MethodDefExt()
			{}
		
		PyMethodDef ext_meth_def;
		method_varargs_function_t ext_varargs_function;	
		method_keyword_function_t ext_keyword_function;	
		};
	
	class ExtensionModuleBase
		{
	public:
		ExtensionModuleBase( const char *name );
		virtual ~ExtensionModuleBase();
		
		Module module(void) const;		// only valid after initialize() has been called
		Dict moduleDictionary(void) const;	// only valid after initialize() has been called
		
		virtual Object invoke_method_keyword( const std::string &_name, const Tuple &_args, const Dict &_keywords ) = 0;
		virtual Object invoke_method_varargs( const std::string &_name, const Tuple &_args ) = 0;
		
		const std::string &name() const;
		const std::string &fullName() const;
	
	protected:
		// Initialize the module
		void initialize( const char *module_doc );
		
		const std::string module_name;
		const std::string full_module_name;
		MethodTable method_table;
		
	private:
		
		//
		// prevent the compiler generating these unwanted functions
		//
		ExtensionModuleBase( const ExtensionModuleBase & );	//unimplemented
		void operator=( const ExtensionModuleBase & );		//unimplemented
		
		};
	
	extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords );
	extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args );
	extern "C" void do_not_dealloc( void * );
	
	
	template<typename T>
	class ExtensionModule : public ExtensionModuleBase
		{
	public:
		ExtensionModule( const char *name )
			: ExtensionModuleBase( name )
			{}
		virtual ~ExtensionModule()
			{}
		
	protected:
		typedef Object (T::*method_varargs_function_t)( const Tuple &args );
		typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
		typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
		
		static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
			{
			method_map_t &mm = methods();
			
			MethodDefExt<T> *method_definition = new MethodDefExt<T>
			(
			name,
			function,
			method_varargs_call_handler,
			doc
			);
			
			mm[std::string( name )] = method_definition;
			}
		
		static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
			{
			method_map_t &mm = methods();
			
			MethodDefExt<T> *method_definition = new MethodDefExt<T>
			(
			name,
			function,
			method_keyword_call_handler,
			doc
			);
			
			mm[std::string( name )] = method_definition;
			}

		void initialize( const char *module_doc="" )
			{
			ExtensionModuleBase::initialize( module_doc );
			Dict dict( moduleDictionary() );
			
			//
			// put each of the methods into the modules dictionary
			// so that we get called back at the function in T.
			//
			method_map_t &mm = methods();
			typename method_map_t::iterator i;
			
			for( i=mm.begin(); i != mm.end(); ++i )
				{
				MethodDefExt<T> *method_definition = (*i).second;
				
				static PyObject *self = PyCObject_FromVoidPtr( this, do_not_dealloc );
				
				Tuple args( 2 );
				args[0] = Object( self );
				args[1] = String( (*i).first );
				
				PyObject *func = PyCFunction_New
				(
				&method_definition->ext_meth_def,
				new_reference_to( args )
				);
				
				dict[ (*i).first ] = Object( func );
				}
			}
		
	protected:	// Tom Malcolmson reports that derived classes need access to these
		
		static method_map_t &methods(void)
			{
			static method_map_t *map_of_methods = NULL;
			if( map_of_methods == NULL )
			map_of_methods = new method_map_t;
			
			return *map_of_methods;
			}
		
		
		// this invoke function must be called from within a try catch block
		virtual Object invoke_method_keyword( const std::string &name, const Tuple &args, const Dict &keywords )
			{
			method_map_t &mm = methods();
			MethodDefExt<T> *meth_def = mm[ name ];
			if( meth_def == NULL )
				{
				std::string error_msg( "CXX - cannot invoke keyword method named " );
				error_msg += name;
				throw RuntimeError( error_msg );
				}
			
			// cast up to the derived class
			T *self = static_cast<T *>(this);
			
			return (self->*meth_def->ext_keyword_function)( args, keywords );
			}
		
		// this invoke function must be called from within a try catch block
		virtual Object invoke_method_varargs( const std::string &name, const Tuple &args )
			{
			method_map_t &mm = methods();
			MethodDefExt<T> *meth_def = mm[ name ];
			if( meth_def == NULL )
				{
				std::string error_msg( "CXX - cannot invoke varargs method named " );
				error_msg += name;
				throw RuntimeError( error_msg );
				}
			
			// cast up to the derived class
			T *self = static_cast<T *>(this);
			
			return (self->*meth_def->ext_varargs_function)( args );
			}
		
	private:
		//
		// prevent the compiler generating these unwanted functions
		//
		ExtensionModule( const ExtensionModule<T> & );	//unimplemented
		void operator=( const ExtensionModule<T> & );	//unimplemented
		};
	
	
	class PythonType
		{
	public:
		// if you define one sequence method you must define 
		// all of them except the assigns
		
		PythonType (size_t base_size, int itemsize, const char *default_name );
		virtual ~PythonType ();
		
		const char *getName () const;
		const char *getDoc () const;

		PyTypeObject* type_object () const;
		void name (const char* nam);
		void doc (const char* d);
		void dealloc(void (*f)(PyObject*));
		
		void supportPrint(void);
		void supportGetattr(void);
		void supportSetattr(void);
		void supportGetattro(void);
		void supportSetattro(void);
		void supportCompare(void);
		void supportRepr(void);
		void supportStr(void);
		void supportHash(void);
		void supportCall(void);
		
		void supportSequenceType(void);
		void supportMappingType(void);
		void supportNumberType(void);
		void supportBufferType(void);
		
	protected:
		PyTypeObject		*table;
		PySequenceMethods	*sequence_table;
		PyMappingMethods	*mapping_table;
		PyNumberMethods		*number_table;
		PyBufferProcs		*buffer_table;
		
		void init_sequence();
		void init_mapping();
		void init_number();
		void init_buffer();
		
	private:
		//
		// prevent the compiler generating these unwanted functions
		//
		PythonType (const PythonType& tb);	// unimplemented
		void operator=(const PythonType& t);	// unimplemented
		
		}; // end of PythonType
	
	
	
	// Class PythonExtension is what you inherit from to create
	// a new Python extension type. You give your class itself
	// as the template paramter.
	
	// There are two ways that extension objects can get destroyed.
	// 1. Their reference count goes to zero
	// 2. Someone does an explicit delete on a pointer.
	// In (1) the problem is to get the destructor called 
	//        We register a special deallocator in the Python type object
	//        (see behaviors()) to do this.
	// In (2) there is no problem, the dtor gets called.
	
	// PythonExtension does not use the usual Python heap allocator, 
	// instead using new/delete. We do the setting of the type object
	// and reference count, usually done by PyObject_New, in the 
	// base class ctor.
	
	// This special deallocator does a delete on the pointer.
	
	
	class PythonExtensionBase : public PyObject
		{
	public:
		PythonExtensionBase();
		virtual ~PythonExtensionBase();
		
	public:
		virtual int print( FILE *, int );
		virtual Object getattr( const char * ) = 0;
		virtual int setattr( const char *, const Object & );
		virtual Object getattro( const Object & );
		virtual int setattro( const Object &, const Object & );
		virtual int compare( const Object & );
		virtual Object repr();
		virtual Object str();
		virtual long hash();
		virtual Object call( const Object &, const Object & );
		
		// Sequence methods
		virtual int sequence_length();
		virtual Object sequence_concat( const Object & );
		virtual Object sequence_repeat( int );
		virtual Object sequence_item( int );
		virtual Object sequence_slice( int, int );
		virtual int sequence_ass_item( int, const Object & );
		virtual int sequence_ass_slice( int, int, const Object & );
		
		// Mapping
		virtual int mapping_length();
		virtual Object mapping_subscript( const Object & );
		virtual int mapping_ass_subscript( const Object &, const Object & );
		
		// Number
		virtual int number_nonzero();
		virtual Object number_negative();
		virtual Object number_positive();
		virtual Object number_absolute();
		virtual Object number_invert();
		virtual Object number_int();
		virtual Object number_float();
		virtual Object number_long();
		virtual Object number_oct();
		virtual Object number_hex();
		virtual Object number_add( const Object & );
		virtual Object number_subtract( const Object & );
		virtual Object number_multiply( const Object & );
		virtual Object number_divide( const Object & );
		virtual Object number_remainder( const Object & );
		virtual Object number_divmod( const Object & );
		virtual Object number_lshift( const Object & );
		virtual Object number_rshift( const Object & );
		virtual Object number_and( const Object & );
		virtual Object number_xor( const Object & );
		virtual Object number_or( const Object & );
		virtual Object number_power( const Object &, const Object & );
		
		// Buffer
		virtual int buffer_getreadbuffer( int, void** );
		virtual int buffer_getwritebuffer( int, void** );
		virtual int buffer_getsegcount( int* );
		
	private:
		void missing_method( void );
		static PyObject *method_call_handler( PyObject *self, PyObject *args );
		};
	
	template<typename T>
	class PythonExtension: public PythonExtensionBase 
		{
	public:
		static PyTypeObject* type_object() 
			{
			return behaviors().type_object();
			}
		
		static int check( PyObject *p )
			{
			// is p like me?
			return p->ob_type == type_object();
			}
		
		static int check( const Object& ob )
			{
			return check( ob.ptr());
			}
		
		
		//
		// every object needs getattr implemented
		// to support methods
		//
		virtual Object getattr( const char *name )
			{
			return getattr_methods( name );
			}
		
	protected:
		explicit PythonExtension()
			: PythonExtensionBase()
			{
			#ifdef PyObject_INIT
			(void)PyObject_INIT( this, type_object() );
			#else
			ob_refcnt = 1;
			ob_type = type_object();
			#endif
			
			// every object must support getattr
			behaviors().supportGetattr();
			}
		
		virtual ~PythonExtension()
			{} 
		
		static PythonType &behaviors()
			{
			static PythonType* p;
			if( p == NULL ) 
				{
#if defined( _CPPRTTI )
				const char *default_name = (typeid ( T )).name();
#else
				const char *default_name = "unknown";
#endif
				p = new PythonType( sizeof( T ), 0, default_name );
				p->dealloc( extension_object_deallocator );
				}
			
			return *p;
			}
		
		
		typedef Object (T::*method_varargs_function_t)( const Tuple &args );
		typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
		typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
		
		// support the default attributes, __name__, __doc__ and methods
		virtual Object getattr_default( const char *_name )
			{
			std::string name( _name );

			if( name == "__name__" && type_object()->tp_name != NULL )
				{
				return Py::String( type_object()->tp_name );
				}
			else if( name == "__doc__" && type_object()->tp_doc != NULL )
				{
				return Py::String( type_object()->tp_doc );
				}

// trying to fake out being a class for help()
//			else if( name == "__bases__"  )
//				{
//				return Py::Tuple(0);
//				}
//			else if( name == "__module__"  )
//				{
//				return Py::Nothing();
//				}
//			else if( name == "__dict__"  )
//				{
//				return Py::Dict();
//				}
			else
				{
				return getattr_methods( _name );
				}
			}

		// turn a name into function object
		virtual Object getattr_methods( const char *_name )
			{
			std::string name( _name );
			
			method_map_t &mm = methods();
			
			if( name == "__methods__" )
				{
				List methods;
				
				for( typename method_map_t::iterator i = mm.begin(); i != mm.end(); ++i )
					methods.append( String( (*i).first ) );
				
				return methods;
				}
			
			// see if name exists
			if( mm.find( name ) == mm.end() )
				throw AttributeError( "method '" + name + "' does not exist." );
			
			Tuple self( 2 );
			
			self[0] = Object( this );
			self[1] = String( name );
			
			MethodDefExt<T> *method_definition = mm[ name ];
			
			PyObject *func = PyCFunction_New( &method_definition->ext_meth_def, self.ptr() );
			
			return Object(func, true);
			}
		
		static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
			{
			method_map_t &mm = methods();
			
			MethodDefExt<T> *method_definition = new MethodDefExt<T>
			(
			name,
			function,
			method_varargs_call_handler,
			doc
			);
			
			mm[std::string( name )] = method_definition;
			}
		
		static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
			{
			method_map_t &mm = methods();
			
			MethodDefExt<T> *method_definition = new MethodDefExt<T>
			(
			name,
			function,
			method_keyword_call_handler,
			doc
			);
			
			mm[std::string( name )] = method_definition;
			}
		
	private:
		static method_map_t &methods(void)
			{
			static method_map_t *map_of_methods = NULL;
			if( map_of_methods == NULL )
			map_of_methods = new method_map_t;
			
			return *map_of_methods;
			}
		
		static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords )
			{
			try
				{
				Tuple self_and_name_tuple( _self_and_name_tuple );
				
				PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
				T *self = static_cast<T *>( self_in_cobject );
				
				String name( self_and_name_tuple[1] );
				
				method_map_t &mm = methods();
				MethodDefExt<T> *meth_def = mm[ name ];
				if( meth_def == NULL )
					return 0;
				
				Tuple args( _args );

				// _keywords may be NULL so be careful about the way the dict is created
				Dict keywords;
				if( _keywords != NULL )
					keywords = Dict( _keywords );
				
				Object result( (self->*meth_def->ext_keyword_function)( args, keywords ) );
				
				return new_reference_to( result.ptr() );
				}
			catch( Exception & )
				{
				return 0;
				}
			}
		
		static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args )
			{
			try
				{
				Tuple self_and_name_tuple( _self_and_name_tuple );
				
				PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
				T *self = static_cast<T *>( self_in_cobject );
				
				String name( self_and_name_tuple[1] );
				
				method_map_t &mm = methods();
				MethodDefExt<T> *meth_def = mm[ name ];
				if( meth_def == NULL )
					return 0;
				
				Tuple args( _args );
				
				Object result;
				
				// TMM: 7Jun'01 - Adding try & catch in case of STL debug-mode exceptions.
				#ifdef _STLP_DEBUG
				try
					{
					result = (self->*meth_def->ext_varargs_function)( args );
					}
				catch (std::__stl_debug_exception)
					{
					// throw cxx::RuntimeError( sErrMsg );
					throw cxx::RuntimeError( "Error message not set yet." );
					}
				#else
				result = (self->*meth_def->ext_varargs_function)( args );
				#endif // _STLP_DEBUG
				
				return new_reference_to( result.ptr() );
				}
			catch( Exception & )
				{
				return 0;
				}
			}
		
		static void extension_object_deallocator ( PyObject* t )
			{
			delete (T *)( t );
			}
		
		//
		// prevent the compiler generating these unwanted functions
		//
		explicit PythonExtension( const PythonExtension<T>& other );
		void operator=( const PythonExtension<T>& rhs );
		};
	
	//
	// ExtensionObject<T> is an Object that will accept only T's.
	//
	template<typename T>
	class ExtensionObject: public Object
		{
	public:
		
		explicit ExtensionObject ( PyObject *pyob )
			: Object( pyob )
			{
			validate();
			}
		
		ExtensionObject( const ExtensionObject<T>& other )
			: Object( *other )
			{
			validate();
			}
		
		ExtensionObject( const Object& other )
			: Object( *other )
			{
			validate();
			}
		
		ExtensionObject& operator= ( const Object& rhs )
			{
			return (*this = *rhs );
			}
		
		ExtensionObject& operator= ( PyObject* rhsp )
			{
			if( ptr() == rhsp )
			return *this;
			set( rhsp );
			return *this;
			}
		
		virtual bool accepts ( PyObject *pyob ) const
			{
			return ( pyob && T::check( pyob ));
			}       
		
		//
		//	Obtain a pointer to the PythonExtension object
		//
		T *extensionObject(void)
			{
			return static_cast<T *>( ptr() );
			}
		};
	
	} // Namespace Py
// End of CXX_Extensions.h
#endif