ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Utility.cxx
Go to the documentation of this file.
1 // @(#)root/pyroot:$Id$
2 // Author: Wim Lavrijsen, Apr 2004
3 
4 // Bindings
5 #include "PyROOT.h"
6 #include "PyStrings.h"
7 #include "Utility.h"
8 #include "ObjectProxy.h"
9 #include "MethodProxy.h"
10 #include "TFunctionHolder.h"
11 #include "TCustomPyTypes.h"
12 #include "TemplateProxy.h"
13 #include "RootWrapper.h"
14 #include "PyCallable.h"
15 
16 // ROOT
17 #include "TApplication.h"
18 #include "TROOT.h"
19 #include "TSystem.h"
20 #include "TObject.h"
21 #include "TClassEdit.h"
22 #include "TClassRef.h"
23 #include "TCollection.h"
24 #include "TDataType.h"
25 #include "TFunction.h"
26 #include "TFunctionTemplate.h"
27 #include "TMethod.h"
28 #include "TMethodArg.h"
29 #include "TError.h"
30 #include "TInterpreter.h"
31 
32 // Standard
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <algorithm>
37 #include <list>
38 #include <mutex>
39 #include <sstream>
40 #include <utility>
41 
42 
43 //- data _____________________________________________________________________
46 
47 typedef std::map< std::string, std::string > TC2POperatorMapping_t;
48 static TC2POperatorMapping_t gC2POperatorMapping;
49 
50 namespace {
51 
52  using namespace PyROOT::Utility;
53 
54  struct InitOperatorMapping_t {
55  public:
56  InitOperatorMapping_t() {
57  // Initialize the global map of operator names C++ -> python.
58 
59  // gC2POperatorMapping[ "[]" ] = "__setitem__"; // depends on return type
60  // gC2POperatorMapping[ "+" ] = "__add__"; // depends on # of args (see __pos__)
61  // gC2POperatorMapping[ "-" ] = "__sub__"; // id. (eq. __neg__)
62  // gC2POperatorMapping[ "*" ] = "__mul__"; // double meaning in C++
63 
64  gC2POperatorMapping[ "[]" ] = "__getitem__";
65  gC2POperatorMapping[ "()" ] = "__call__";
66  gC2POperatorMapping[ "/" ] = PYROOT__div__;
67  gC2POperatorMapping[ "%" ] = "__mod__";
68  gC2POperatorMapping[ "**" ] = "__pow__";
69  gC2POperatorMapping[ "<<" ] = "__lshift__";
70  gC2POperatorMapping[ ">>" ] = "__rshift__";
71  gC2POperatorMapping[ "&" ] = "__and__";
72  gC2POperatorMapping[ "|" ] = "__or__";
73  gC2POperatorMapping[ "^" ] = "__xor__";
74  gC2POperatorMapping[ "~" ] = "__inv__";
75  gC2POperatorMapping[ "+=" ] = "__iadd__";
76  gC2POperatorMapping[ "-=" ] = "__isub__";
77  gC2POperatorMapping[ "*=" ] = "__imul__";
78  gC2POperatorMapping[ "/=" ] = PYROOT__idiv__;
79  gC2POperatorMapping[ "%=" ] = "__imod__";
80  gC2POperatorMapping[ "**=" ] = "__ipow__";
81  gC2POperatorMapping[ "<<=" ] = "__ilshift__";
82  gC2POperatorMapping[ ">>=" ] = "__irshift__";
83  gC2POperatorMapping[ "&=" ] = "__iand__";
84  gC2POperatorMapping[ "|=" ] = "__ior__";
85  gC2POperatorMapping[ "^=" ] = "__ixor__";
86  gC2POperatorMapping[ "==" ] = "__eq__";
87  gC2POperatorMapping[ "!=" ] = "__ne__";
88  gC2POperatorMapping[ ">" ] = "__gt__";
89  gC2POperatorMapping[ "<" ] = "__lt__";
90  gC2POperatorMapping[ ">=" ] = "__ge__";
91  gC2POperatorMapping[ "<=" ] = "__le__";
92 
93  // the following type mappings are "exact"
94  gC2POperatorMapping[ "const char*" ] = "__str__";
95  gC2POperatorMapping[ "char*" ] = "__str__";
96  gC2POperatorMapping[ "const char *" ] = gC2POperatorMapping[ "const char*" ];
97  gC2POperatorMapping[ "char *" ] = gC2POperatorMapping[ "char*" ];
98  gC2POperatorMapping[ "int" ] = "__int__";
99  gC2POperatorMapping[ "long" ] = PYROOT__long__;
100  gC2POperatorMapping[ "double" ] = "__float__";
101 
102  // the following type mappings are "okay"; the assumption is that they
103  // are not mixed up with the ones above or between themselves (and if
104  // they are, that it is done consistently)
105  gC2POperatorMapping[ "short" ] = "__int__";
106  gC2POperatorMapping[ "unsigned short" ] = "__int__";
107  gC2POperatorMapping[ "unsigned int" ] = PYROOT__long__;
108  gC2POperatorMapping[ "unsigned long" ] = PYROOT__long__;
109  gC2POperatorMapping[ "long long" ] = PYROOT__long__;
110  gC2POperatorMapping[ "unsigned long long" ] = PYROOT__long__;
111  gC2POperatorMapping[ "float" ] = "__float__";
112 
113  gC2POperatorMapping[ "->" ] = "__follow__"; // not an actual python operator
114  gC2POperatorMapping[ "=" ] = "__assign__"; // id.
115 
116 #if PY_VERSION_HEX < 0x03000000
117  gC2POperatorMapping[ "bool" ] = "__nonzero__";
118 #else
119  gC2POperatorMapping[ "bool" ] = "__bool__";
120 #endif
121  }
122  } initOperatorMapping_;
123 
124  std::once_flag sOperatorTemplateFlag;
125  void InitOperatorTemplate() {
126  gROOT->ProcessLine(
127  "namespace _pyroot_internal { template<class C1, class C2>"
128  " bool is_equal(const C1& c1, const C2& c2){ return (bool)(c1 == c2); } }" );
129  gROOT->ProcessLine(
130  "namespace _pyroot_internal { template<class C1, class C2>"
131  " bool is_not_equal(const C1& c1, const C2& c2){ return (bool)(c1 != c2); } }" );
132  }
133 
134  inline void RemoveConst( std::string& cleanName ) {
135  std::string::size_type spos = std::string::npos;
136  while ( ( spos = cleanName.find( "const" ) ) != std::string::npos ) {
137  cleanName.swap( cleanName.erase( spos, 5 ) );
138  }
139  }
140 
141 } // unnamed namespace
142 
143 
144 //- public functions ---------------------------------------------------------
146 {
147 // Convert <pybject> to C++ unsigned long, with bounds checking, allow int -> ulong.
148  ULong_t ul = PyLong_AsUnsignedLong( pyobject );
149  if ( PyErr_Occurred() && PyInt_Check( pyobject ) ) {
150  PyErr_Clear();
151  Long_t i = PyInt_AS_LONG( pyobject );
152  if ( 0 <= i ) {
153  ul = (ULong_t)i;
154  } else {
155  PyErr_SetString( PyExc_ValueError,
156  "can\'t convert negative value to unsigned long" );
157  }
158  }
159 
160  return ul;
161 }
162 
163 ////////////////////////////////////////////////////////////////////////////////
164 /// Convert <pyobject> to C++ unsigned long long, with bounds checking.
165 
167 {
168  ULong64_t ull = PyLong_AsUnsignedLongLong( pyobject );
169  if ( PyErr_Occurred() && PyInt_Check( pyobject ) ) {
170  PyErr_Clear();
171  Long_t i = PyInt_AS_LONG( pyobject );
172  if ( 0 <= i ) {
173  ull = (ULong64_t)i;
174  } else {
175  PyErr_SetString( PyExc_ValueError,
176  "can\'t convert negative value to unsigned long long" );
177  }
178  }
179 
180  return ull;
181 }
182 
183 ////////////////////////////////////////////////////////////////////////////////
184 /// Add the given function to the class under name 'label'.
185 
187  PyObject* pyclass, const char* label, PyCFunction cfunc, int flags )
188 {
189 // use list for clean-up (.so's are unloaded only at interpreter shutdown)
190  static std::list< PyMethodDef > s_pymeths;
191 
192  s_pymeths.push_back( PyMethodDef() );
193  PyMethodDef* pdef = &s_pymeths.back();
194  pdef->ml_name = const_cast< char* >( label );
195  pdef->ml_meth = cfunc;
196  pdef->ml_flags = flags;
197  pdef->ml_doc = NULL;
198 
199  PyObject* func = PyCFunction_New( pdef, NULL );
200  PyObject* method = TCustomInstanceMethod_New( func, NULL, pyclass );
201  Bool_t isOk = PyObject_SetAttrString( pyclass, pdef->ml_name, method ) == 0;
202  Py_DECREF( method );
203  Py_DECREF( func );
204 
205  if ( PyErr_Occurred() )
206  return kFALSE;
207 
208  if ( ! isOk ) {
209  PyErr_Format( PyExc_TypeError, "could not add method %s", label );
210  return kFALSE;
211  }
212 
213  return kTRUE;
214 }
215 
216 ////////////////////////////////////////////////////////////////////////////////
217 /// Add the given function to the class under name 'label'.
218 
219 Bool_t PyROOT::Utility::AddToClass( PyObject* pyclass, const char* label, const char* func )
220 {
221  PyObject* pyfunc = PyObject_GetAttrString( pyclass, const_cast< char* >( func ) );
222  if ( ! pyfunc )
223  return kFALSE;
224 
225  Bool_t isOk = PyObject_SetAttrString( pyclass, const_cast< char* >( label ), pyfunc ) == 0;
226 
227  Py_DECREF( pyfunc );
228  return isOk;
229 }
230 
231 ////////////////////////////////////////////////////////////////////////////////
232 /// Add the given function to the class under name 'label'.
233 
234 Bool_t PyROOT::Utility::AddToClass( PyObject* pyclass, const char* label, PyCallable* pyfunc )
235 {
236  MethodProxy* method =
237  (MethodProxy*)PyObject_GetAttrString( pyclass, const_cast< char* >( label ) );
238 
239  if ( ! method || ! MethodProxy_Check( method ) ) {
240  // not adding to existing MethodProxy; add callable directly to the class
241  if ( PyErr_Occurred() )
242  PyErr_Clear();
243  Py_XDECREF( (PyObject*)method );
244  method = MethodProxy_New( label, pyfunc );
245  Bool_t isOk = PyObject_SetAttrString(
246  pyclass, const_cast< char* >( label ), (PyObject*)method ) == 0;
247  Py_DECREF( method );
248  return isOk;
249  }
250 
251  method->AddMethod( pyfunc );
252 
253  Py_DECREF( method );
254  return kTRUE;
255 }
256 
257 ////////////////////////////////////////////////////////////////////////////////
258 /// Helper to add base class methods to the derived class one (this covers the
259 /// 'using' cases, which the dictionary does not provide).
260 
261 Bool_t PyROOT::Utility::AddUsingToClass( PyObject* pyclass, const char* method )
262 {
263  MethodProxy* derivedMethod =
264  (MethodProxy*)PyObject_GetAttrString( pyclass, const_cast< char* >( method ) );
265  if ( ! MethodProxy_Check( derivedMethod ) ) {
266  Py_XDECREF( derivedMethod );
267  return kFALSE;
268  }
269 
270  PyObject* mro = PyObject_GetAttr( pyclass, PyStrings::gMRO );
271  if ( ! mro || ! PyTuple_Check( mro ) ) {
272  Py_XDECREF( mro );
273  Py_DECREF( derivedMethod );
274  return kFALSE;
275  }
276 
277  MethodProxy* baseMethod = 0;
278  for ( int i = 1; i < PyTuple_GET_SIZE( mro ); ++i ) {
279  baseMethod = (MethodProxy*)PyObject_GetAttrString(
280  PyTuple_GET_ITEM( mro, i ), const_cast< char* >( method ) );
281 
282  if ( ! baseMethod ) {
283  PyErr_Clear();
284  continue;
285  }
286 
287  if ( MethodProxy_Check( baseMethod ) )
288  break;
289 
290  Py_DECREF( baseMethod );
291  baseMethod = 0;
292  }
293 
294  Py_DECREF( mro );
295 
296  if ( ! MethodProxy_Check( baseMethod ) ) {
297  Py_XDECREF( baseMethod );
298  Py_DECREF( derivedMethod );
299  return kFALSE;
300  }
301 
302  derivedMethod->AddMethod( baseMethod );
303 
304  Py_DECREF( baseMethod );
305  Py_DECREF( derivedMethod );
306 
307  return kTRUE;
308 }
309 
310 ////////////////////////////////////////////////////////////////////////////////
311 /// Install the named operator (op) into the left object's class if such a function
312 /// exists as a global overload; a label must be given if the operator is not in
313 /// gC2POperatorMapping (i.e. if it is ambiguous at the member level).
314 
316  PyObject* left, PyObject* right, const char* op, const char* label, const char* alt )
317 {
318 // this should be a given, nevertheless ...
319  if ( ! ObjectProxy_Check( left ) )
320  return kFALSE;
321 
322 // retrieve the class names to match the signature of any found global functions
323  std::string rcname = ClassName( right );
324  std::string lcname = ClassName( left );
325  PyObject* pyclass = PyObject_GetAttr( left, PyStrings::gClass );
326 
327  Bool_t result = AddBinaryOperator( pyclass, lcname, rcname, op, label, alt );
328 
329  Py_DECREF( pyclass );
330  return result;
331 }
332 
333 ////////////////////////////////////////////////////////////////////////////////
334 /// Install binary operator op in pyclass, working on two instances of pyclass.
335 
337  PyObject* pyclass, const char* op, const char* label, const char* alt )
338 {
339  PyObject* pyname = PyObject_GetAttr( pyclass, PyStrings::gName );
340  std::string cname = Cppyy::ResolveName( PyROOT_PyUnicode_AsString( pyname ) );
341  Py_DECREF( pyname ); pyname = 0;
342 
343  return AddBinaryOperator( pyclass, cname, cname, op, label, alt );
344 }
345 
346 ////////////////////////////////////////////////////////////////////////////////
347 /// Helper to find a function with matching signature in 'funcs'.
348 
349 static inline Cppyy::TCppMethod_t FindAndAddOperator( const std::string& lcname, const std::string& rcname,
350  const char* op, TClass* klass = 0 ) {
351  std::string opname = "operator";
352  opname += op;
353  std::string proto = lcname + ", " + rcname;
354 
355 // case of global namespace
356  if ( ! klass )
357  return (Cppyy::TCppMethod_t)gROOT->GetGlobalFunctionWithPrototype( opname.c_str(), proto.c_str() );
358 
359 // case of specific namespace
360  return (Cppyy::TCppMethod_t)klass->GetMethodWithPrototype( opname.c_str(), proto.c_str() );
361 }
362 
363 Bool_t PyROOT::Utility::AddBinaryOperator( PyObject* pyclass, const std::string& lcname,
364  const std::string& rcname, const char* op, const char* label, const char* alt )
365 {
366 // Find a global function with a matching signature and install the result on pyclass;
367 // in addition, __gnu_cxx, std::__1, and _pyroot_internal are searched pro-actively (as
368 // there's AFAICS no way to unearth using information).
369 
370 // This function can be called too early when setting up some of the ROOT core classes,
371 // which in turn can trigger the creation of a (default) TApplication. Wait with looking
372 // for binary operators '!=' and '==' (which are set early in Pythonize.cxx) until fully
373 // initialized. Other operators are expected to have entered from user code.
374  if ( !gApplication && (strcmp( op, "==" ) == 0 || strcmp( op, "!=" ) == 0) )
375  return kFALSE;
376 
377 // For GNU on clang, search the internal __gnu_cxx namespace for binary operators (is
378 // typically the case for STL iterators operator==/!=.
379  static TClassRef gnucxx( "__gnu_cxx" );
380 
381 // Same for clang on Mac. TODO: find proper pre-processor magic to only use those specific
382 // namespaces that are actually around; although to be sure, this isn't expensive.
383  static TClassRef std__1( "std::__1" );
384 
385 // One more, mostly for Mac, but again not sure whether this is not a general issue. Some
386 // operators are declared as friends only in classes, so then they're not found in the
387 // global namespace. That's why there's this little helper.
388  std::call_once( sOperatorTemplateFlag, InitOperatorTemplate );
389  static TClassRef _pr_int( "_pyroot_internal" );
390 
391  PyCallable* pyfunc = 0;
392  if ( gnucxx.GetClass() ) {
393  Cppyy::TCppMethod_t func = FindAndAddOperator( lcname, rcname, op, gnucxx.GetClass() );
394  if ( func ) pyfunc = new TFunctionHolder( Cppyy::GetScope( "__gnu_cxx" ), func );
395  }
396 
397  if ( ! pyfunc && std__1.GetClass() ) {
398  Cppyy::TCppMethod_t func = FindAndAddOperator( lcname, rcname, op, std__1.GetClass() );
399  if ( func ) pyfunc = new TFunctionHolder( Cppyy::GetScope( "std::__1" ), func );
400  }
401 
402  if ( ! pyfunc ) {
403  std::string::size_type pos = lcname.substr(0, lcname.find('<')).rfind( "::" );
404  if ( pos != std::string::npos ) {
405  TClass* lcscope = TClass::GetClass( lcname.substr( 0, pos ).c_str() );
406  if ( lcscope ) {
407  Cppyy::TCppMethod_t func = FindAndAddOperator( lcname, rcname, op, lcscope );
408  if ( func ) pyfunc = new TFunctionHolder( Cppyy::GetScope( lcname.substr( 0, pos ) ), func );
409  }
410  }
411  }
412 
413  if ( ! pyfunc ) {
414  Cppyy::TCppMethod_t func = FindAndAddOperator( lcname, rcname, op );
415  if ( func ) pyfunc = new TFunctionHolder( Cppyy::gGlobalScope, func );
416  }
417 
418  if ( ! pyfunc && _pr_int.GetClass() &&
419  lcname.find( "iterator" ) != std::string::npos &&
420  rcname.find( "iterator" ) != std::string::npos ) {
421  // TODO: gets called too often; make sure it's purely lazy calls only; also try to
422  // find a better notion for which classes (other than iterators) this is supposed to
423  // work; right now it fails for cases where None is passed
424  std::stringstream fname;
425  if ( strncmp( op, "==", 2 ) == 0 ) { fname << "is_equal<"; }
426  else if ( strncmp( op, "!=", 2 ) == 0 ) { fname << "is_not_equal<"; }
427  else { fname << "not_implemented<"; }
428  fname << lcname << ", " << rcname << ">";
429  Cppyy::TCppMethod_t func = (Cppyy::TCppMethod_t)_pr_int->GetMethodAny( fname.str().c_str() );
430  if ( func ) pyfunc = new TFunctionHolder( Cppyy::GetScope( "_pyroot_internal" ), func );
431  }
432 
433 // last chance: there could be a non-instantiated templated method
434  TClass* lc = TClass::GetClass( lcname.c_str() );
435  if ( lc && strcmp(op, "==") != 0 && strcmp(op, "!=") != 0 ) {
436  std::string opname = "operator"; opname += op;
437  gInterpreter->LoadFunctionTemplates(lc);
438  gInterpreter->GetFunctionTemplate(lc->GetClassInfo(), opname.c_str());
439  TFunctionTemplate*f = lc->GetFunctionTemplate(opname.c_str());
441  (Cppyy::TCppMethod_t)lc->GetMethodWithPrototype( opname.c_str(), rcname.c_str() );
442  if ( func && f ) pyfunc = new TMethodHolder( Cppyy::GetScope( lcname ), func );
443  }
444 
445  if ( pyfunc ) { // found a matching overload; add to class
446  Bool_t ok = AddToClass( pyclass, label, pyfunc );
447  if ( ok && alt )
448  return AddToClass( pyclass, alt, label );
449  }
450 
451  return kFALSE;
452 }
453 
454 ////////////////////////////////////////////////////////////////////////////////
455 /// Helper to construct the "< type, type, ... >" part of a templated name (either
456 /// for a class as in MakeRootTemplateClass in RootModule.cxx) or for method lookup
457 /// (as in TemplatedMemberHook, below).
458 
460 {
461  if ( pyname )
463  else
464  pyname = PyROOT_PyUnicode_FromString( "" );
466 
467  Py_ssize_t nArgs = PyTuple_GET_SIZE( args );
468  for ( int i = argoff; i < nArgs; ++i ) {
469  // add type as string to name
470  PyObject* tn = PyTuple_GET_ITEM( args, i );
471  if ( PyROOT_PyUnicode_Check( tn ) )
472  PyROOT_PyUnicode_Append( &pyname, tn );
473  else if ( PyObject_HasAttr( tn, PyStrings::gName ) ) {
474  // this works for type objects
475  PyObject* tpName = PyObject_GetAttr( tn, PyStrings::gName );
476 
477  // special case for strings
478  if ( strcmp( PyROOT_PyUnicode_AsString( tpName ), "str" ) == 0 ) {
479  Py_DECREF( tpName );
480  tpName = PyROOT_PyUnicode_FromString( "std::string" );
481  }
482 
483  PyROOT_PyUnicode_AppendAndDel( &pyname, tpName );
484  } else {
485  // last ditch attempt, works for things like int values; since this is a
486  // source of errors otherwise, it is limited to specific types and not
487  // generally used (str(obj) can print anything ...)
488  PyObject* pystr = 0;
489  if ( PyInt_Check( tn ) || PyLong_Check( tn ) || PyFloat_Check( tn ) )
490  pystr = PyObject_Str( tn );
491 
492  if ( ! pystr ) {
493  Py_DECREF( pyname );
494  return 0;
495  }
496  PyROOT_PyUnicode_AppendAndDel( &pyname, pystr );
497  }
498 
499  // add a comma, as needed
500  if ( i != nArgs - 1 )
502  }
503 
504 // close template name; prevent '>>', which should be '> >'
505  if ( PyROOT_PyUnicode_AsString( pyname )[ PyROOT_PyUnicode_GetSize( pyname ) - 1 ] == '>' )
507  else
509 
510  return pyname;
511 }
512 
513 ////////////////////////////////////////////////////////////////////////////////
514 /// Initialize a proxy class for use by python, and add it to the ROOT module.
515 
516 Bool_t PyROOT::Utility::InitProxy( PyObject* module, PyTypeObject* pytype, const char* name )
517 {
518 // finalize proxy type
519  if ( PyType_Ready( pytype ) < 0 )
520  return kFALSE;
521 
522 // add proxy type to the given (ROOT) module
523  Py_INCREF( pytype ); // PyModule_AddObject steals reference
524  if ( PyModule_AddObject( module, (char*)name, (PyObject*)pytype ) < 0 ) {
525  Py_DECREF( pytype );
526  return kFALSE;
527  }
528 
529 // declare success
530  return kTRUE;
531 }
532 
533 ////////////////////////////////////////////////////////////////////////////////
534 /// Retrieve a linear buffer pointer from the given pyobject.
535 
536 int PyROOT::Utility::GetBuffer( PyObject* pyobject, char tc, int size, void*& buf, Bool_t check )
537 {
538 // special case: don't handle character strings here (yes, they're buffers, but not quite)
539  if ( PyBytes_Check( pyobject ) )
540  return 0;
541 
542 // attempt to retrieve pointer to buffer interface
543  PyBufferProcs* bufprocs = Py_TYPE(pyobject)->tp_as_buffer;
544 
545  PySequenceMethods* seqmeths = Py_TYPE(pyobject)->tp_as_sequence;
546  if ( seqmeths != 0 && bufprocs != 0
547 #if PY_VERSION_HEX < 0x03000000
548  && bufprocs->bf_getwritebuffer != 0
549  && (*(bufprocs->bf_getsegcount))( pyobject, 0 ) == 1
550 #else
551  && bufprocs->bf_getbuffer != 0
552 #endif
553  ) {
554 
555  // get the buffer
556 #if PY_VERSION_HEX < 0x03000000
557  Py_ssize_t buflen = (*(bufprocs->bf_getwritebuffer))( pyobject, 0, &buf );
558 #else
559  Py_buffer bufinfo;
560  (*(bufprocs->bf_getbuffer))( pyobject, &bufinfo, PyBUF_WRITABLE );
561  buf = (char*)bufinfo.buf;
562  Py_ssize_t buflen = bufinfo.len;
563 #endif
564 
565  if ( buf && check == kTRUE ) {
566  // determine buffer compatibility (use "buf" as a status flag)
567  PyObject* pytc = PyObject_GetAttr( pyobject, PyStrings::gTypeCode );
568  if ( pytc != 0 ) { // for array objects
569  if ( PyROOT_PyUnicode_AsString( pytc )[0] != tc )
570  buf = 0; // no match
571  Py_DECREF( pytc );
572  } else if ( seqmeths->sq_length &&
573  (int)(buflen / (*(seqmeths->sq_length))( pyobject )) == size ) {
574  // this is a gamble ... may or may not be ok, but that's for the user
575  PyErr_Clear();
576  } else if ( buflen == size ) {
577  // also a gamble, but at least 1 item will fit into the buffer, so very likely ok ...
578  PyErr_Clear();
579  } else {
580  buf = 0; // not compatible
581 
582  // clarify error message
583  PyObject* pytype = 0, *pyvalue = 0, *pytrace = 0;
584  PyErr_Fetch( &pytype, &pyvalue, &pytrace );
586  (char*)"%s and given element size (%ld) do not match needed (%d)",
587  PyROOT_PyUnicode_AsString( pyvalue ),
588  seqmeths->sq_length ? (Long_t)(buflen / (*(seqmeths->sq_length))( pyobject )) : (Long_t)buflen,
589  size );
590  Py_DECREF( pyvalue );
591  PyErr_Restore( pytype, pyvalue2, pytrace );
592  }
593  }
594 
595  return buflen;
596  }
597 
598  return 0;
599 }
600 
601 ////////////////////////////////////////////////////////////////////////////////
602 /// Map the given C++ operator name on the python equivalent.
603 
604 std::string PyROOT::Utility::MapOperatorName( const std::string& name, Bool_t bTakesParams )
605 {
606  if ( 8 < name.size() && name.substr( 0, 8 ) == "operator" ) {
607  std::string op = name.substr( 8, std::string::npos );
608 
609  // stripping ...
610  std::string::size_type start = 0, end = op.size();
611  while ( start < end && isspace( op[ start ] ) ) ++start;
612  while ( start < end && isspace( op[ end-1 ] ) ) --end;
613  op = TClassEdit::ResolveTypedef( op.substr( start, end - start ).c_str(), true );
614 
615  // map C++ operator to python equivalent, or made up name if no equivalent exists
616  TC2POperatorMapping_t::iterator pop = gC2POperatorMapping.find( op );
617  if ( pop != gC2POperatorMapping.end() ) {
618  return pop->second;
619 
620  } else if ( op == "*" ) {
621  // dereference v.s. multiplication of two instances
622  return bTakesParams ? "__mul__" : "__deref__";
623 
624  } else if ( op == "+" ) {
625  // unary positive v.s. addition of two instances
626  return bTakesParams ? "__add__" : "__pos__";
627 
628  } else if ( op == "-" ) {
629  // unary negative v.s. subtraction of two instances
630  return bTakesParams ? "__sub__" : "__neg__";
631 
632  } else if ( op == "++" ) {
633  // prefix v.s. postfix increment
634  return bTakesParams ? "__postinc__" : "__preinc__";
635 
636  } else if ( op == "--" ) {
637  // prefix v.s. postfix decrement
638  return bTakesParams ? "__postdec__" : "__predec__";
639  }
640 
641  }
642 
643 // might get here, as not all operator methods are handled (new, delete, etc.)
644  return name;
645 }
646 
647 ////////////////////////////////////////////////////////////////////////////////
648 /// Break down the compound of a fully qualified type name.
649 
650 const std::string PyROOT::Utility::Compound( const std::string& name )
651 {
652  std::string cleanName = name;
653  RemoveConst( cleanName );
654 
655  std::string compound = "";
656  for ( int ipos = (int)cleanName.size()-1; 0 <= ipos; --ipos ) {
657  char c = cleanName[ipos];
658  if ( isspace( c ) ) continue;
659  if ( isalnum( c ) || c == '_' || c == '>' ) break;
660 
661  compound = c + compound;
662  }
663 
664 // for arrays (TODO: deal with the actual size)
665  if ( compound == "]" )
666  return "[]";
667 
668  return compound;
669 }
670 
671 ////////////////////////////////////////////////////////////////////////////////
672 /// Extract size from an array type, if available.
673 
675 {
676  std::string cleanName = name;
677  RemoveConst( cleanName );
678 
679  if ( cleanName[cleanName.size()-1] == ']' ) {
680  std::string::size_type idx = cleanName.rfind( '[' );
681  if ( idx != std::string::npos ) {
682  const std::string asize = cleanName.substr( idx+1, cleanName.size()-2 );
683  return strtoul( asize.c_str(), NULL, 0 );
684  }
685  }
686 
687  return -1;
688 }
689 
690 ////////////////////////////////////////////////////////////////////////////////
691 /// Retrieve the class name from the given python object (which may be just an
692 /// instance of the class).
693 
694 const std::string PyROOT::Utility::ClassName( PyObject* pyobj )
695 {
696  std::string clname = "<unknown>";
697  PyObject* pyclass = PyObject_GetAttr( pyobj, PyStrings::gClass );
698  if ( pyclass != 0 ) {
699  PyObject* pyname = PyObject_GetAttr( pyclass, PyStrings::gName );
700 
701  if ( pyname != 0 ) {
702  clname = PyROOT_PyUnicode_AsString( pyname );
703  Py_DECREF( pyname );
704  } else
705  PyErr_Clear();
706 
707  Py_DECREF( pyclass );
708  } else
709  PyErr_Clear();
710 
711  return clname;
712 }
713 
714 ////////////////////////////////////////////////////////////////////////////////
715 /// Translate CINT error/warning into python equivalent.
716 
717 void PyROOT::Utility::ErrMsgCallback( char* /* msg */ )
718 {
719 // TODO (Cling): this function is probably not going to be used anymore and
720 // may need removing at some point for cleanup
721 
722 /* Commented out for Cling ---
723 
724 // ignore the "*** Interpreter error recovered ***" message
725  if ( strstr( msg, "error recovered" ) )
726  return;
727 
728 // ignore CINT-style FILE/LINE messages
729  if ( strstr( msg, "FILE:" ) )
730  return;
731 
732 // get file name and line number
733  char* errFile = (char*)G__stripfilename( G__get_ifile()->name );
734  int errLine = G__get_ifile()->line_number;
735 
736 // ignore ROOT-style FILE/LINE messages
737  char buf[256];
738  snprintf( buf, 256, "%s:%d:", errFile, errLine );
739  if ( strstr( msg, buf ) )
740  return;
741 
742 // strip newline, if any
743  int len = strlen( msg );
744  if ( msg[ len-1 ] == '\n' )
745  msg[ len-1 ] = '\0';
746 
747 // concatenate message if already in error processing mode (e.g. if multiple CINT errors)
748  if ( PyErr_Occurred() ) {
749  PyObject *etype, *value, *trace;
750  PyErr_Fetch( &etype, &value, &trace ); // clears current exception
751 
752  // need to be sure that error can be added; otherwise leave earlier error in place
753  if ( PyROOT_PyUnicode_Check( value ) ) {
754  if ( ! PyErr_GivenExceptionMatches( etype, PyExc_IndexError ) )
755  PyROOT_PyUnicode_AppendAndDel( &value, PyROOT_PyUnicode_FromString( (char*)"\n " ) );
756  PyROOT_PyUnicode_AppendAndDel( &value, PyROOT_PyUnicode_FromString( msg ) );
757  }
758 
759  PyErr_Restore( etype, value, trace );
760  return;
761  }
762 
763 // else, translate known errors and warnings, or simply accept the default
764  char* format = (char*)"(file \"%s\", line %d) %s";
765  char* p = 0;
766  if ( ( p = strstr( msg, "Syntax Error:" ) ) )
767  PyErr_Format( PyExc_SyntaxError, format, errFile, errLine, p+14 );
768  else if ( ( p = strstr( msg, "Error: Array" ) ) )
769  PyErr_Format( PyExc_IndexError, format, errFile, errLine, p+12 );
770  else if ( ( p = strstr( msg, "Error:" ) ) )
771  PyErr_Format( PyExc_RuntimeError, format, errFile, errLine, p+7 );
772  else if ( ( p = strstr( msg, "Exception:" ) ) )
773  PyErr_Format( PyExc_RuntimeError, format, errFile, errLine, p+11 );
774  else if ( ( p = strstr( msg, "Limitation:" ) ) )
775  PyErr_Format( PyExc_NotImplementedError, format, errFile, errLine, p+12 );
776  else if ( ( p = strstr( msg, "Internal Error: malloc" ) ) )
777  PyErr_Format( PyExc_MemoryError, format, errFile, errLine, p+23 );
778  else if ( ( p = strstr( msg, "Internal Error:" ) ) )
779  PyErr_Format( PyExc_SystemError, format, errFile, errLine, p+16 );
780  else if ( ( p = strstr( msg, "Warning:" ) ) )
781 // either printout or raise exception, depending on user settings
782  PyErr_WarnExplicit( NULL, p+9, errFile, errLine, (char*)"CINT", NULL );
783  else if ( ( p = strstr( msg, "Note:" ) ) )
784  fprintf( stdout, "Note: (file \"%s\", line %d) %s\n", errFile, errLine, p+6 );
785  else // unknown: printing it to screen is the safest action
786  fprintf( stdout, "Message: (file \"%s\", line %d) %s\n", errFile, errLine, msg );
787 
788  --- Commented out for Cling */
789 }
790 
791 ////////////////////////////////////////////////////////////////////////////////
792 /// Translate ROOT error/warning to python.
793 
794 void PyROOT::Utility::ErrMsgHandler( int level, Bool_t abort, const char* location, const char* msg )
795 {
796 // initialization from gEnv (the default handler will return w/o msg b/c level too low)
797  if ( gErrorIgnoreLevel == kUnset )
798  ::DefaultErrorHandler( kUnset - 1, kFALSE, "", "" );
799 
800  if ( level < gErrorIgnoreLevel )
801  return;
802 
803 // turn warnings into python warnings
804  if (level >= kError)
805  ::DefaultErrorHandler( level, abort, location, msg );
806  else if ( level >= kWarning ) {
807  // either printout or raise exception, depending on user settings
808  PyErr_WarnExplicit( NULL, (char*)msg, (char*)location, 0, (char*)"ROOT", NULL );
809  }
810  else
811  ::DefaultErrorHandler( level, abort, location, msg );
812 }
813 
814 
815 ////////////////////////////////////////////////////////////////////////////////
816 /// Compile a function on the fly and return a function pointer for use on C-APIs.
817 /// The callback should take a (void*)pyfunc and the (Long_t)user as well as the
818 /// rest of the declare signature. It should also live in namespace PyROOT
819 
821  const char* retType, const std::vector<std::string>& signature, const char* callback )
822 {
823  static Long_t s_fid = 0;
824 
825  if ( ! PyCallable_Check( pyfunc ) )
826  return 0;
827 
828 // keep alive (TODO: manage this intelligently)
829  Py_INCREF( pyfunc );
830 
831  Long_t fid = s_fid++;
832 
833 // basic function name part
834  std::ostringstream funcName;
835  funcName << "pyrootGenFun" << fid;
836 
837 // build-up a signature
838  std::ostringstream sigDecl, argsig;
839  std::vector<std::string>::size_type nargs = signature.size();
840  for ( std::vector<std::string>::size_type i = 0; i < nargs; ++i ) {
841  sigDecl << signature[i] << " a" << i;
842  argsig << ", a" << i;
843  if ( i != nargs-1 ) sigDecl << ", ";
844  }
845 
846 // create full definition
847  std::ostringstream declCode;
848  declCode << "namespace PyROOT { "
849  << retType << " " << callback << "(void*, Long_t, " << sigDecl.str() << "); }\n"
850  << retType << " " << funcName.str() << "(" << sigDecl.str()
851  << ") { void* v0 = (void*)" << (void*)pyfunc << "; "
852  << "return PyROOT::" << callback << "(v0, " << user << argsig.str() << "); }";
853 
854 // body compilation
855  gInterpreter->LoadText( declCode.str().c_str() );
856 
857 // func-ptr retrieval code
858  std::ostringstream fptrCode;
859  fptrCode << "void* pyrootPtrVar" << fid << " = (void*)" << funcName.str()
860  << "; pyrootPtrVar" << fid << ";";
861 
862 // retrieve function pointer
863  void* fptr = (void*)gInterpreter->ProcessLineSynch( fptrCode.str().c_str() );
864  if ( fptr == 0 )
865  PyErr_SetString( PyExc_SyntaxError, "could not generate C++ callback wrapper" );
866 
867  return fptr;
868 }
869 
870 ////////////////////////////////////////////////////////////////////////////////
871 /// Re-acquire the GIL before calling PyErr_Occurred() in case it has been
872 /// released; note that the p2.2 code assumes that there are no callbacks in
873 /// C++ to python (or at least none returning errors).
874 
876 {
877 #if PY_VERSION_HEX >= 0x02030000
878  PyGILState_STATE gstate = PyGILState_Ensure();
879  PyObject* e = PyErr_Occurred();
880  PyGILState_Release( gstate );
881 #else
882  if ( PyThreadState_GET() )
883  return PyErr_Occurred();
884  PyObject* e = 0;
885 #endif
886 
887  return e;
888 }
889 
890 ////////////////////////////////////////////////////////////////////////////////
891 
892 namespace {
893  static int (*sOldInputHook)() = NULL;
894  static PyThreadState* sInputHookEventThreadState = NULL;
895 
896  static int EventInputHook()
897  {
898  // This method is supposed to be called from CPython's command line and
899  // drives the GUI.
900  PyEval_RestoreThread( sInputHookEventThreadState );
902  PyEval_SaveThread();
903 
904  if ( sOldInputHook ) return sOldInputHook();
905  return 0;
906  }
907 
908 } // unnamed namespace
909 
911 {
912 // Install the method hook for sending events to the GUI
913  if ( PyOS_InputHook && PyOS_InputHook != &EventInputHook )
914  sOldInputHook = PyOS_InputHook;
915 
916  sInputHookEventThreadState = PyThreadState_Get();
917 
918  PyOS_InputHook = (int (*)())&EventInputHook;
919  Py_INCREF( Py_None );
920  return Py_None;
921 }
922 
924 {
925 // Remove event hook, if it was installed
926  PyOS_InputHook = sOldInputHook;
927  sInputHookEventThreadState = NULL;
928 
929  Py_INCREF( Py_None );
930  return Py_None;
931 }
Bool_t InitProxy(PyObject *module, PyTypeObject *pytype, const char *name)
Initialize a proxy class for use by python, and add it to the ROOT module.
Definition: Utility.cxx:516
Bool_t AddBinaryOperator(PyObject *left, PyObject *right, const char *op, const char *label, const char *alt_label=NULL)
Install the named operator (op) into the left object's class if such a function exists as a global ov...
Definition: Utility.cxx:315
#define PyROOT_PyUnicode_FromString
Definition: PyROOT.h:71
#define pyname
Definition: TMCParticle.cxx:19
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition: TSystem.cxx:420
R__EXTERN Int_t gErrorIgnoreLevel
Definition: TError.h:107
PyObject * TCustomInstanceMethod_New(PyObject *func, PyObject *self, PyObject *pyclass)
#define PYROOT__long__
Definition: PyROOT.h:89
return c
Dictionary for function template This class describes one single function template.
void DefaultErrorHandler(int level, Bool_t abort, const char *location, const char *msg)
The default error handler function.
Definition: TError.cxx:125
PyObject * RemoveGUIEventInputHook()
Definition: Utility.cxx:923
MethodProxy * MethodProxy_New(const std::string &name, std::vector< PyCallable * > &methods)
Definition: MethodProxy.h:75
#define gROOT
Definition: TROOT.h:344
R__EXTERN dict_lookup_func gDictLookupOrg
Definition: Utility.h:15
PyObject * BuildTemplateName(PyObject *pyname, PyObject *args, int argoff)
Helper to construct the "< type, type, ... >" part of a templated name (either for a class as in Make...
Definition: Utility.cxx:459
bool Bool_t
Definition: RtypesCore.h:59
const Bool_t kFALSE
Definition: Rtypes.h:92
#define gInterpreter
Definition: TInterpreter.h:502
R__EXTERN TApplication * gApplication
Definition: TApplication.h:171
R__EXTERN Bool_t gDictLookupActive
Definition: Utility.h:18
TFile * f
#define PyROOT_PyUnicode_FromFormat
Definition: PyROOT.h:70
#define PyROOT_PyUnicode_Append
Definition: PyROOT.h:73
std::string ResolveName(const std::string &cppitem_name)
Definition: Cppyy.cxx:140
std::string MapOperatorName(const std::string &name, Bool_t bTakesParames)
Map the given C++ operator name on the python equivalent.
Definition: Utility.cxx:604
#define PyROOT_PyUnicode_GetSize
Definition: PyROOT.h:69
#define PYROOT__idiv__
Definition: PyROOT.h:90
R__EXTERN PyObject * gMRO
Definition: PyStrings.h:32
std::string ResolveTypedef(const char *tname, bool resolveAll=false)
if(pyself &&pyself!=Py_None)
const std::string ClassName(PyObject *pyobj)
Retrieve the class name from the given python object (which may be just an instance of the class)...
Definition: Utility.cxx:694
#define PyROOT_PyUnicode_AsString
Definition: PyROOT.h:66
#define PyBytes_Check
Definition: PyROOT.h:52
PyObject * PyErr_Occurred_WithGIL()
Re-acquire the GIL before calling PyErr_Occurred() in case it has been released; note that the p2...
Definition: Utility.cxx:875
std::map< std::string, std::string > TC2POperatorMapping_t
Definition: Utility.cxx:47
static TC2POperatorMapping_t gC2POperatorMapping
Definition: Utility.cxx:48
ULong_t PyLongOrInt_AsULong(PyObject *pyobject)
Definition: Utility.cxx:145
void ErrMsgHandler(int level, Bool_t abort, const char *location, const char *msg)
Translate ROOT error/warning to python.
Definition: Utility.cxx:794
const Int_t kUnset
Definition: TError.h:37
ptrdiff_t TCppMethod_t
Definition: Cppyy.h:15
Bool_t ObjectProxy_Check(T *object)
Definition: ObjectProxy.h:91
R__EXTERN PyObject * gClass
Definition: PyStrings.h:18
TCppScope_t gGlobalScope
Definition: Cppyy.cxx:58
R__EXTERN TSystem * gSystem
Definition: TSystem.h:545
ClassInfo_t * GetClassInfo() const
Definition: TClass.h:390
ULong64_t PyLongOrInt_AsULong64(PyObject *pyobject)
Convert <pyobject> to C++ unsigned long long, with bounds checking.
Definition: Utility.cxx:166
The ROOT global object gROOT contains a list of all defined classes.
Definition: TClass.h:81
const Int_t kWarning
Definition: TError.h:40
#define PYROOT__div__
Definition: PyROOT.h:91
long Long_t
Definition: RtypesCore.h:50
#define PyROOT_PyUnicode_AppendAndDel
Definition: PyROOT.h:74
PyObject * InstallGUIEventInputHook()
Definition: Utility.cxx:910
TCppScope_t GetScope(const std::string &scope_name)
Definition: Cppyy.cxx:150
R__EXTERN PyObject * gName
Definition: PyStrings.h:33
void AddMethod(PyCallable *pc)
Fill in the data of a freshly created method proxy.
R__EXTERN PyObject * gTypeCode
Definition: PyStrings.h:35
unsigned long long ULong64_t
Definition: RtypesCore.h:70
unsigned long ULong_t
Definition: RtypesCore.h:51
double func(double *x, double *p)
Definition: stressTF1.cxx:213
Bool_t AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Add the given function to the class under name 'label'.
Definition: Utility.cxx:186
#define PyROOT_PyUnicode_Check
Definition: PyROOT.h:64
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition: TClass.cxx:2801
Bool_t AddUsingToClass(PyObject *pyclass, const char *method)
Helper to add base class methods to the derived class one (this covers the 'using' cases...
Definition: Utility.cxx:261
#define name(a, b)
Definition: linkTestLib0.cpp:5
TFunctionTemplate * GetFunctionTemplate(const char *name)
Definition: TClass.cxx:3339
TClass * GetClass() const
Definition: TClassRef.h:75
TClassRef is used to implement a permanent reference to a TClass object.
Definition: TClassRef.h:33
#define Py_TYPE(ob)
Definition: PyROOT.h:149
int Py_ssize_t
Definition: PyROOT.h:154
PyDictEntry *(* dict_lookup_func)(PyDictObject *, PyObject *, Long_t)
Definition: PyROOT.h:43
int GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, Bool_t check=kTRUE)
Retrieve a linear buffer pointer from the given pyobject.
Definition: Utility.cxx:536
const Int_t kError
Definition: TError.h:41
void * CreateWrapperMethod(PyObject *pyfunc, Long_t user, const char *retType, const std::vector< std::string > &signature, const char *callback)
Compile a function on the fly and return a function pointer for use on C-APIs.
Definition: Utility.cxx:820
Bool_t MethodProxy_Check(T *object)
Definition: MethodProxy.h:63
#define NULL
Definition: Rtypes.h:82
double result[121]
Py_ssize_t ArraySize(const std::string &name)
Extract size from an array type, if available.
Definition: Utility.cxx:674
void ErrMsgCallback(char *msg)
Translate CINT error/warning into python equivalent.
Definition: Utility.cxx:717
TMethod * GetMethodAny(const char *method)
Return pointer to method without looking at parameters.
Definition: TClass.cxx:4027
static Cppyy::TCppMethod_t FindAndAddOperator(const std::string &lcname, const std::string &rcname, const char *op, TClass *klass=0)
Helper to find a function with matching signature in 'funcs'.
Definition: Utility.cxx:349
const Bool_t kTRUE
Definition: Rtypes.h:91
TMethod * GetMethodWithPrototype(const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
Find the method with a given prototype.
Definition: TClass.cxx:4113
_object PyObject
Definition: TPyArg.h:22
const std::string Compound(const std::string &name)
Break down the compound of a fully qualified type name.
Definition: Utility.cxx:650