source: git/Singular/pyobject.cc @ 29fc843

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