source: git/Singular/pyobject.cc @ c0d292

spielwiese
Last change on this file since c0d292 was 1161a61, checked in by Alexander Dreyer <alexander.dreyer@…>, 12 years ago
fix: pyobject handles ternary operations acordingly
  • Property mode set to 100644
File size: 17.0 KB
Line 
1// -*- c++ -*-
2//*****************************************************************************
3/** @file pyobject.cc
4 *
5 * @author Alexander Dreyer
6 * @date 2010-12-15
7 *
8 * This file defines the @c blackbox operations for the pyobject type.
9 *
10 * @par Copyright:
11 *   (c) 2010 by The Singular Team, see LICENSE file
12**/
13//*****************************************************************************
14
15#include "config.h"
16#include <kernel/mod2.h>
17#include <misc/auxiliary.h>
18#include "newstruct.h"
19
20#include <omalloc/omalloc.h>
21
22#include <kernel/febase.h>
23
24#include "subexpr.h"
25#include "lists.h"
26#include "ipid.h"
27#include "blackbox.h"
28
29#include <Python.h>
30// #include <iterator>             // std::distance
31// #include <stdio.h>
32
33void sync_contexts();
34
35/** @class PythonInterpreter
36 * This class initializes and finalized the python interpreter.
37 *
38 * It also stores the Singular token number, which is assigned to this type on
39 * runtime.
40 **/
41class PythonInterpreter {
42public:
43  typedef int id_type;
44
45  ~PythonInterpreter()  { if(m_owns_python) Py_Finalize();  }
46
47  /// Initialize unique (singleton) python interpreter instance,
48  /// and set Singular type identifier
49  static void init(id_type num ) { instance().m_id = num; }
50
51  /// Get Singular type identitfier
52  static id_type id() { return instance().m_id; }
53
54private:
55  /// Singleton: Only init() is allowed to construct an instance
56  PythonInterpreter():
57    m_id(0), m_owns_python(false)  { start_python(); }
58
59  /// Static initialization -
60  /// safely takes care of destruction on program termination
61  static PythonInterpreter& instance() 
62  {
63    static PythonInterpreter init_interpreter;
64    return init_interpreter;
65  }
66
67  void start_python()
68  {
69    if (!Py_IsInitialized()) init_python();
70    set_python_defaults();
71  }
72 
73  void init_python()
74  {
75    Py_Initialize();
76    m_owns_python = true;
77  }
78
79  void set_python_defaults()
80  {
81    // Sone python modules needs argc, argv set for some reason
82    char* argv = "";
83    PySys_SetArgv(1, &argv);
84    PyRun_SimpleString("from sys import path, modules");
85    PyRun_SimpleString("_SINGULAR_IMPORTED = dict()");
86
87    char cmd[MAXPATHLEN + 20];
88    sprintf(cmd, "path.insert(0, '%s')", feGetResource('b'));
89    PyRun_SimpleString(cmd);
90    PyRun_SimpleString("del path");  // cleanup
91  }   
92
93  id_type m_id;
94  bool m_owns_python;
95};
96
97/** @class PythonObject
98 * This class defines an interface for calling PyObject from Singular.
99 *
100 * @note This class does not take care of the memory mangement, this is done in
101 * the blackbox routines.
102 **/
103class PythonObject
104{
105  typedef PythonObject self;
106
107public:
108  typedef PyObject* ptr_type;
109  struct sequence_tag{};
110  struct null_tag {};
111
112  PythonObject(): m_ptr(Py_None) { }
113  PythonObject(null_tag): m_ptr(NULL) { }
114  PythonObject(ptr_type ptr): m_ptr(ptr) {if (!ptr) handle_exception();}
115
116  ptr_type check_context(ptr_type ptr) const {
117    if(ptr) sync_contexts(); 
118    return ptr;
119  }
120  /// Unary operations
121  self operator()(int op) const
122  {
123    switch(op)
124    {
125    case '(':  return check_context(PyObject_CallObject(*this, NULL));
126    case ATTRIB_CMD: return PyObject_Dir(*this);
127    case PROC_CMD: return *this;
128    }
129
130    if (op == PythonInterpreter::id())
131      return *this;
132
133    return self(null_tag());
134  }
135
136  /// Binary and n-ary operations
137  self operator()(int op, const self& arg) const {
138
139    switch(op)
140    {
141      case '+':  return PyNumber_Add(*this, arg);
142      case '-':  return PyNumber_Subtract(*this, arg);
143      case '*':  return PyNumber_Multiply(*this, arg);
144      case '/':  return PyNumber_Divide(*this, arg);
145      case '^':  return PyNumber_Power(*this, arg, Py_None);
146      case '(':  return check_context(PyObject_CallObject(*this, arg));
147      case '[':  return operator[](arg);
148      case KILLATTR_CMD: return del_attr(arg);
149      case LIST_CMD:     return args2list(arg);
150      case '.': case COLONCOLON: case ATTRIB_CMD: return attr(arg);
151    }
152    return self(null_tag());
153  }
154
155  /// Ternary operations
156  self operator()(int op, const self& arg1, const self& arg2) const 
157  {
158    switch(op)
159    {
160      case ATTRIB_CMD: 
161        if(PyObject_SetAttr(*this, arg1, arg2) == -1) handle_exception();
162        return self();
163    }
164    return self(null_tag());
165  }
166
167  /// Get item
168  self operator[](const self& idx) const { return PyObject_GetItem(*this, idx); }
169  self operator[](long idx) const { return operator[](PyInt_FromLong(idx));  }
170
171  /// Get actual PyObject*
172  operator const ptr_type() const { return m_ptr; }
173
174  /// Get representative as C-style string
175  char* repr() const
176  {
177    return omStrDup(PyString_AsString(PyObject_Repr(*this)));
178  }
179
180  /// Extract C-style string
181  char* str() const { return omStrDup(PyString_AsString(*this)); }
182
183  Py_ssize_t size() const { return PyObject_Size(m_ptr); }
184
185  BOOLEAN assign_to(leftv result)
186  {
187    return (m_ptr? (m_ptr == Py_None? none_to(result): python_to(result)): TRUE);
188  }
189
190  void import_as(const char* name) const {
191    idhdl handle = enterid(omStrDup(name), 0, DEF_CMD, 
192                           &IDROOT, FALSE);
193
194    if (handle)
195    {
196      IDDATA(handle) = (char*)m_ptr;
197      Py_XINCREF(m_ptr); 
198      IDTYP(handle) =  PythonInterpreter::id();
199    }
200    else { Werror("Importing pyobject to Singular failed"); }
201  }
202
203  int compare(int op, const self& arg) const
204  { return PyObject_RichCompareBool(*this, arg, py_opid(op)); }
205
206
207  self attr(const self& arg) const { return PyObject_GetAttr(*this, arg); }
208
209  self del_attr(const self& arg) const 
210  {
211    if (!PyObject_HasAttr(*this, arg)) 
212      Werror("Cannot delete attribute %s.", arg.repr());
213    else
214      PyObject_DelAttr(*this, arg); 
215 
216    return self();
217  }
218
219protected:
220  self args2list(const self& args) const
221  {
222    self pylist(PyList_New(0));
223    PyList_Append(pylist, *this);
224    if(PyTuple_Check(args))  pylist.append_iter(PyObject_GetIter(args));
225    else PyList_Append(pylist, args);
226
227    return pylist;
228  }
229
230  void handle_exception() const {
231   
232    PyObject *pType, *pMessage, *pTraceback;
233    PyErr_Fetch(&pType, &pMessage, &pTraceback);
234   
235    Werror("pyobject error occured");
236    Werror(PyString_AsString(pMessage));
237   
238    Py_XDECREF(pType);
239    Py_XDECREF(pMessage);
240    Py_XDECREF(pTraceback);
241   
242    PyErr_Clear();
243  }
244
245  void append_iter(self iterator) {
246    ptr_type item;
247    while (item = PyIter_Next(iterator)) {
248      PyList_Append(*this, item);
249      Py_DECREF(item);
250    }
251  }
252
253  int py_opid(int op) const{
254    switch(op)
255    { 
256      case '<':  return Py_LT;
257      case '>':  return Py_GT;
258      case EQUAL_EQUAL:  return Py_EQ;
259      case NOTEQUAL:  return Py_NE;
260      case GE:  return Py_GE; 
261      case LE:  return Py_LE; 
262    }
263    return -1;
264  }
265
266private:
267  BOOLEAN none_to(leftv result) const
268  {
269    result->data = NULL;
270    result->rtyp = NONE;
271    return FALSE;
272  }
273
274  BOOLEAN python_to(leftv result) const
275  {
276    result->data = m_ptr;
277    Py_XINCREF(m_ptr);
278    result->rtyp = PythonInterpreter::id();
279    return !m_ptr;
280  }
281
282  /// The actual pointer
283  ptr_type m_ptr;
284};
285
286
287
288/** @class PythonCastStatic
289 * This template class does conversion of Singular objects to python objects on
290 * compile-time.
291 *
292 * @note The Singular objects are assumed to be equivalent to the template argument.
293 **/
294template <class CastType = PythonObject::ptr_type>
295class PythonCastStatic:
296  public PythonObject {
297public:
298
299  PythonCastStatic(void* value):
300    PythonObject(get(reinterpret_cast<CastType>(value))) {}
301
302  PythonCastStatic(leftv value):
303    PythonObject(get(reinterpret_cast<CastType>(value->Data()))) {}
304
305private:
306  ptr_type get(ptr_type value)       { return value; }
307  ptr_type get(long value)           { return PyInt_FromLong(value); }
308  ptr_type get(const char* value)    { return PyString_FromString(value); }
309  ptr_type get(char* value) { return get(const_cast<const char*>(value)); }
310  ptr_type get(lists value);         // inlined after PythonObjectDynamic
311};
312
313
314
315/** @class PythonCastDynamic
316 * This class does conversion of Singular objects to python objects on runtime.
317 *
318 **/
319class PythonCastDynamic:
320  public PythonObject {
321  typedef PythonCastDynamic self;
322
323public:
324  PythonCastDynamic(leftv value): PythonObject(get(value, value->Typ())) {}
325
326private:
327  PythonObject get(leftv value, int typeId)
328  {
329    if (typeId == PythonInterpreter::id()) return PythonCastStatic<>(value);
330   
331    switch (typeId)
332    {
333    case INT_CMD:    return PythonCastStatic<long>(value);
334    case STRING_CMD: return PythonCastStatic<const char*>(value);
335    case LIST_CMD:   return PythonCastStatic<lists>(value);
336    }
337
338    if (typeId > MAX_TOK)       // custom types
339    {
340      blackbox *bbx = getBlackboxStuff(typeId);
341      sleftv tmp;
342      if (! bbx->blackbox_Op1(PythonInterpreter::id(), &tmp, value) )
343        return PythonCastStatic<>(&tmp);
344    }
345    else
346      Werror("type '%s` incompatible with 'pyobject`", iiTwoOps(typeId));
347
348    return PythonObject();
349  }
350};
351
352template <class CastType>
353inline PythonObject::ptr_type
354PythonCastStatic<CastType>::get(lists value)
355{
356  ptr_type pylist(PyList_New(0));
357  for (size_t i = 0; i <= value->nr; ++i)
358    PyList_Append(pylist, PythonCastDynamic((value->m) + i));
359
360  return pylist;
361}
362
363/// Template specialization for getting handling sequence
364template <>
365class PythonCastStatic<PythonObject::sequence_tag>:
366public PythonObject
367{
368public:
369
370  PythonCastStatic(leftv value):
371    PythonObject(PyTuple_New(size(value)))  { append_to(value); }
372
373 
374private:
375  size_t size(leftv iter, size_t distance = 0) const 
376  {
377    if (iter) { do { ++distance; } while(iter = iter->next); }; 
378    return distance;
379  }
380 
381  void append_to(leftv iter) const
382  {
383    for(size_t idx = 0; iter != NULL; iter = iter->next)
384      PyTuple_SetItem(*this, idx++, PythonCastDynamic(iter));
385  }
386};
387
388
389PythonObject get_attrib_name(leftv arg)
390{
391  typedef PythonCastStatic<const char*> result_type;
392  if (arg->Typ() == STRING_CMD)
393    return result_type(arg);
394
395  return result_type((void*)arg->Name());
396}
397
398/// Evaluate string in python
399PythonObject python_eval(const char* arg) {
400
401  PyObject* globals = PyModule_GetDict(PyImport_Import(PyString_FromString("__main__")));
402  return PyRun_String(arg, Py_eval_input, globals, globals);
403}
404
405/// Evaluate string in python from Singular
406BOOLEAN python_eval(leftv result, leftv arg) {
407  if ( !arg || (arg->Typ() != STRING_CMD) ) {
408    Werror("expected python_eval('string')");
409    return TRUE;
410  }
411
412  return python_eval(reinterpret_cast<const char*>(arg->Data())).assign_to(result);
413}
414
415
416/// Execute string in python from Singular
417BOOLEAN python_run(leftv result, leftv arg)
418{
419  if ( !arg || (arg->Typ() != STRING_CMD) ) {
420    Werror("expected python_run('string')");
421    return TRUE;
422  }
423
424  PyRun_SimpleString(reinterpret_cast<const char*>(arg->Data()));
425  sync_contexts();
426  return PythonCastStatic<>(Py_None).assign_to(result);
427}
428
429PythonObject names_from_module(const char* module_name)
430{
431  char buffer[strlen(module_name) + 30];
432  sprintf (buffer, "SINGULAR_MODULE_NAME = '%s'", module_name);
433  PyRun_SimpleString(buffer);
434  PyRun_SimpleString("from sys import modules");
435  PyRun_SimpleString("exec('from ' + SINGULAR_MODULE_NAME + ' import *')");
436
437  return python_eval("[str for str in dir(modules[SINGULAR_MODULE_NAME]) if str[0] != '_']");
438}
439
440void from_module_import_all(const char* module_name)
441{
442  char buffer[strlen(module_name) + 20];
443  sprintf (buffer, "from %s import *", module_name);
444  PyRun_SimpleString(buffer);
445}
446
447/// import python module and export identifiers in Singular namespace
448BOOLEAN python_import(leftv result, leftv value) {
449
450  if ((value == NULL) || (value->Typ()!= STRING_CMD)) {
451    Werror("expected python_import('string')");
452    return TRUE;
453  }
454
455  from_module_import_all(reinterpret_cast<const char*>(value->Data()));
456  sync_contexts();
457
458  return PythonCastStatic<>(Py_None).assign_to(result);
459}
460
461/// blackbox support - initialization
462void* pyobject_Init(blackbox*)
463{
464  return Py_None;
465}
466
467/// blackbox support - convert to string representation
468char* pyobject_String(blackbox *b, void* ptr)
469{
470  return PythonCastStatic<>(ptr).repr();
471}
472
473/// blackbox support - copy element
474void* pyobject_Copy(blackbox*b, void* ptr)
475{ 
476    Py_XINCREF(ptr);
477    return ptr;
478}
479
480/// blackbox support - assign element
481BOOLEAN pyobject_Assign(leftv l, leftv r)
482{
483  Py_XDECREF(l->Data());
484  PyObject* result = PythonCastDynamic(r);
485  Py_XINCREF(result);
486
487  if (l->rtyp == IDHDL)
488    IDDATA((idhdl)l->data) = (char *)result;
489  else
490    l->data = (void *)result;
491 
492  return !result;
493}
494                                                                     
495
496/// blackbox support - unary operations
497BOOLEAN pyobject_Op1(int op, leftv res, leftv head)
498{
499  switch(op)
500  {
501    case INT_CMD:               // built-in return types first
502    {
503      long value = PyInt_AsLong(PythonCastStatic<>(head));
504      if( (value == -1) &&  PyErr_Occurred() ) {
505        Werror("'pyobject` cannot be converted to integer");
506        PyErr_Clear();
507        return TRUE;
508      }
509      res->data = (void*) value;
510      res->rtyp = INT_CMD;
511      return FALSE;
512    }
513    case TYPEOF_CMD:
514      res->data = (void*) omStrDup("pyobject");
515      res->rtyp = STRING_CMD; 
516      return FALSE; 
517  }
518
519  if (!PythonCastStatic<>(head)(op).assign_to(res))
520    return FALSE;
521
522  BOOLEAN newstruct_Op1(int, leftv, leftv); // forward declaration
523  return newstruct_Op1(op, res, head);
524}
525
526
527/// blackbox support - binary operations
528BOOLEAN pyobject_Op2(int op, leftv res, leftv arg1, leftv arg2)
529{
530  PythonCastStatic<> lhs(arg1);
531
532  switch(op)                    // built-in return types and special cases first
533  { 
534    case '<': case '>': case EQUAL_EQUAL: case NOTEQUAL: case GE: case LE:
535    {
536      res->data = (void *)lhs.compare(op, PythonCastDynamic(arg2));
537      res->rtyp = INT_CMD;
538      return FALSE;
539    }
540    case '.': case COLONCOLON: case ATTRIB_CMD:
541      return lhs.attr(get_attrib_name(arg2)).assign_to(res);
542  }
543
544  PythonCastDynamic rhs(arg2);
545  if (!lhs(op, rhs).assign_to(res))
546    return FALSE;
547
548  BOOLEAN newstruct_Op2(int, leftv, leftv, leftv); // forward declaration
549  return newstruct_Op2(op, res, arg1, arg2);
550
551}
552
553/// blackbox support - ternary operations
554BOOLEAN pyobject_Op3(int op, leftv res, leftv arg1, leftv arg2, leftv arg3)
555{
556  PythonCastStatic<> lhs(arg1);
557  PythonCastDynamic rhs1(arg2);
558  PythonCastDynamic rhs2(arg3);
559
560  if (!lhs(op, rhs1, rhs2).assign_to(res))
561    return blackboxDefaultOp3(op, res, arg1, arg2, arg3);
562}
563
564
565/// blackbox support - n-ary operations
566BOOLEAN pyobject_OpM(int op, leftv res, leftv args)
567{
568  typedef PythonCastStatic<PythonObject::sequence_tag> seq_type;
569
570  switch(op)                    // built-in return types first
571  {
572    case STRING_CMD:
573    {
574      blackbox* a = getBlackboxStuff(args->Typ());
575      res->data = (void *)a->blackbox_String(a, args->Data());
576      res->rtyp = STRING_CMD;
577      return FALSE;
578    }
579  }
580
581  typedef PythonCastStatic<PythonObject::sequence_tag> seq_type;
582  if (! PythonCastStatic<>(args)(op, seq_type(args->next)).assign_to(res))
583    return FALSE;
584
585  BOOLEAN newstruct_OpM(int, leftv, leftv); // forward declaration
586  return newstruct_OpM(op, res, args);
587}
588
589/// blackbox support - destruction
590void pyobject_destroy(blackbox *b, void* ptr)
591{
592  Py_XDECREF(ptr);
593}
594
595PyObject* get_current_definition(const char* name) {
596  idhdl handle =  ggetid(name);
597  if (!handle || (IDTYP(handle) != PythonInterpreter::id()))  return NULL;
598  PythonCastStatic<PyObject*> value(IDDATA(handle));
599  return value;
600}
601
602/// getting stuff from python to Singular namespace
603void sync_contexts()
604{
605  PyRun_SimpleString("_SINGULAR_NEW = modules['__main__'].__dict__.copy()");
606
607  PythonObject newElts = python_eval("[(_k, _e)   \
608    for (_k, _e) in _SINGULAR_NEW.iteritems() \
609    if _k not in _SINGULAR_IMPORTED or not _SINGULAR_IMPORTED[_k] is _e]");
610
611  long len = newElts.size();
612  for (long idx = 0; idx < len; ++idx)
613  {
614    char* name = newElts[idx][0].str();
615    if (name && (*name != '\0') && (*name != '_'))
616    {
617      Py_XDECREF(get_current_definition(name));
618      newElts[idx][1].import_as(name);
619    }
620
621  }
622
623  PythonObject deletedElts = 
624    python_eval("list(set(_SINGULAR_IMPORTED.iterkeys()) - \
625     set(_SINGULAR_NEW.iterkeys()))");
626  len = deletedElts.size();
627
628  for (long idx = 0; idx < len; ++idx)
629  {
630    char* name = deletedElts[idx].str();
631    if (name && (*name != '\0') && (*name != '_'))
632      killid(name, &IDROOT);
633  }
634
635  PyRun_SimpleString("_SINGULAR_IMPORTED =_SINGULAR_NEW");
636  PyRun_SimpleString("del  _SINGULAR_NEW");
637}
638
639
640// forward declaration
641int iiAddCproc(char *libname, char *procname, BOOLEAN pstatic,
642               BOOLEAN(*func)(leftv res, leftv v));
643
644#define ADD_C_PROC(name) iiAddCproc("", (char*)#name, FALSE, name);
645
646
647void pyobject_init() 
648{
649  blackbox *b = (blackbox*)omAlloc0(sizeof(blackbox));
650  b->blackbox_destroy = pyobject_destroy;
651  b->blackbox_String  = pyobject_String;
652  b->blackbox_Init    = pyobject_Init;
653  b->blackbox_Copy    = pyobject_Copy;
654  b->blackbox_Assign  = pyobject_Assign;
655  b->blackbox_Op1     = pyobject_Op1;
656  b->blackbox_Op2     = pyobject_Op2;
657  b->blackbox_Op3     = pyobject_Op3;
658  b->blackbox_OpM     = pyobject_OpM;
659  b->data             = omAlloc0(newstruct_desc_size());
660
661  PythonInterpreter::init(setBlackboxStuff(b,"pyobject"));
662
663  ADD_C_PROC(python_import);
664  ADD_C_PROC(python_eval);
665  ADD_C_PROC(python_run);
666}
667
668extern "C" { void mod_init() { pyobject_init(); } }
669
Note: See TracBrowser for help on using the repository browser.