source: git/Singular/pyobject.cc @ b2aa08

jengelh-datetimespielwiese
Last change on this file since b2aa08 was b2aa08, checked in by Alexander Dreyer <alexander.dreyer@…>, 11 years ago
fix: pyobject falls back to newstruct operations
  • 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: PyObject_SetAttr(*this, arg1, arg2); return self();
161    }
162    Werror("ternary operation %s not implemented for 'pyobject`", iiTwoOps(op));
163    return self(null_tag());
164  }
165
166  /// Get item
167  self operator[](const self& idx) const { return PyObject_GetItem(*this, idx); }
168  self operator[](long idx) const { return operator[](PyInt_FromLong(idx));  }
169
170  /// Get actual PyObject*
171  operator const ptr_type() const { return m_ptr; }
172
173  /// Get representative as C-style string
174  char* repr() const
175  {
176    return omStrDup(PyString_AsString(PyObject_Repr(*this)));
177  }
178
179  /// Extract C-style string
180  char* str() const { return omStrDup(PyString_AsString(*this)); }
181
182  Py_ssize_t size() const { return PyObject_Size(m_ptr); }
183
184  BOOLEAN assign_to(leftv result)
185  {
186    return (m_ptr? (m_ptr == Py_None? none_to(result): python_to(result)): TRUE);
187  }
188
189  void import_as(const char* name) const {
190    idhdl handle = enterid(omStrDup(name), 0, DEF_CMD, 
191                           &IDROOT, FALSE);
192
193    if (handle)
194    {
195      IDDATA(handle) = (char*)m_ptr;
196      Py_XINCREF(m_ptr); 
197      IDTYP(handle) =  PythonInterpreter::id();
198    }
199    else { Werror("Importing pyobject to Singular failed"); }
200  }
201
202  int compare(int op, const self& arg) const
203  { return PyObject_RichCompareBool(*this, arg, py_opid(op)); }
204
205
206  self attr(const self& arg) const { return PyObject_GetAttr(*this, arg); }
207
208  self del_attr(const self& arg) const 
209  {
210    if (!PyObject_HasAttr(*this, arg)) 
211      Werror("Cannot delete attribute %s.", arg.repr());
212    else
213      PyObject_DelAttr(*this, arg); 
214 
215    return self();
216  }
217
218protected:
219  self args2list(const self& args) const
220  {
221    self pylist(PyList_New(0));
222    PyList_Append(pylist, *this);
223    if(PyTuple_Check(args))  pylist.append_iter(PyObject_GetIter(args));
224    else PyList_Append(pylist, args);
225
226    return pylist;
227  }
228
229  void handle_exception() {
230   
231    PyObject *pType, *pMessage, *pTraceback;
232    PyErr_Fetch(&pType, &pMessage, &pTraceback);
233   
234    Werror("pyobject error occured");
235    Werror(PyString_AsString(pMessage));
236   
237    Py_XDECREF(pType);
238    Py_XDECREF(pMessage);
239    Py_XDECREF(pTraceback);
240   
241    PyErr_Clear();
242  }
243
244  void append_iter(self iterator) {
245    ptr_type item;
246    while (item = PyIter_Next(iterator)) {
247      PyList_Append(*this, item);
248      Py_DECREF(item);
249    }
250  }
251
252  int py_opid(int op) const{
253    switch(op)
254    { 
255      case '<':  return Py_LT;
256      case '>':  return Py_GT;
257      case EQUAL_EQUAL:  return Py_EQ;
258      case NOTEQUAL:  return Py_NE;
259      case GE:  return Py_GE; 
260      case LE:  return Py_LE; 
261    }
262    return -1;
263  }
264
265private:
266  BOOLEAN none_to(leftv result) const
267  {
268    result->data = NULL;
269    result->rtyp = NONE;
270    return FALSE;
271  }
272
273  BOOLEAN python_to(leftv result) const
274  {
275    result->data = m_ptr;
276    Py_XINCREF(m_ptr);
277    result->rtyp = PythonInterpreter::id();
278    return !m_ptr;
279  }
280
281  /// The actual pointer
282  ptr_type m_ptr;
283};
284
285
286
287/** @class PythonCastStatic
288 * This template class does conversion of Singular objects to python objects on
289 * compile-time.
290 *
291 * @note The Singular objects are assumed to be equivalent to the template argument.
292 **/
293template <class CastType = PythonObject::ptr_type>
294class PythonCastStatic:
295  public PythonObject {
296public:
297
298  PythonCastStatic(void* value):
299    PythonObject(get(reinterpret_cast<CastType>(value))) {}
300
301  PythonCastStatic(leftv value):
302    PythonObject(get(reinterpret_cast<CastType>(value->Data()))) {}
303
304private:
305  ptr_type get(ptr_type value)       { return value; }
306  ptr_type get(long value)           { return PyInt_FromLong(value); }
307  ptr_type get(const char* value)    { return PyString_FromString(value); }
308  ptr_type get(char* value) { return get(const_cast<const char*>(value)); }
309  ptr_type get(lists value);         // inlined after PythonObjectDynamic
310};
311
312
313
314/** @class PythonCastDynamic
315 * This class does conversion of Singular objects to python objects on runtime.
316 *
317 **/
318class PythonCastDynamic:
319  public PythonObject {
320  typedef PythonCastDynamic self;
321
322public:
323  PythonCastDynamic(leftv value): PythonObject(get(value, value->Typ())) {}
324
325private:
326  PythonObject get(leftv value, int typeId)
327  {
328    if (typeId == PythonInterpreter::id()) return PythonCastStatic<>(value);
329   
330    switch (typeId)
331    {
332    case INT_CMD:    return PythonCastStatic<long>(value);
333    case STRING_CMD: return PythonCastStatic<const char*>(value);
334    case LIST_CMD:   return PythonCastStatic<lists>(value);
335    }
336
337    if (typeId > MAX_TOK)       // custom types
338    {
339      blackbox *bbx = getBlackboxStuff(typeId);
340      sleftv tmp;
341      if (! bbx->blackbox_Op1(PythonInterpreter::id(), &tmp, value) )
342        return PythonCastStatic<>(&tmp);
343    }
344    else
345      Werror("type '%s` incompatible with 'pyobject`", iiTwoOps(typeId));
346
347    return PythonObject();
348  }
349};
350
351template <class CastType>
352inline PythonObject::ptr_type
353PythonCastStatic<CastType>::get(lists value)
354{
355  ptr_type pylist(PyList_New(0));
356  for (size_t i = 0; i <= value->nr; ++i)
357    PyList_Append(pylist, PythonCastDynamic((value->m) + i));
358
359  return pylist;
360}
361
362/// Template specialization for getting handling sequence
363template <>
364class PythonCastStatic<PythonObject::sequence_tag>:
365public PythonObject
366{
367public:
368
369  PythonCastStatic(leftv value):
370    PythonObject(PyTuple_New(size(value)))  { append_to(value); }
371
372 
373private:
374  size_t size(leftv iter, size_t distance = 0) const 
375  {
376    if (iter) { do { ++distance; } while(iter = iter->next); }; 
377    return distance;
378  }
379 
380  void append_to(leftv iter) const
381  {
382    for(size_t idx = 0; iter != NULL; iter = iter->next)
383      PyTuple_SetItem(*this, idx++, PythonCastDynamic(iter));
384  }
385};
386
387
388PythonObject get_attrib_name(leftv arg)
389{
390  typedef PythonCastStatic<const char*> result_type;
391  if (arg->Typ() == STRING_CMD)
392    return result_type(arg);
393
394  return result_type((void*)arg->Name());
395}
396
397/// Evaluate string in python
398PythonObject python_eval(const char* arg) {
399
400  PyObject* globals = PyModule_GetDict(PyImport_Import(PyString_FromString("__main__")));
401  return PyRun_String(arg, Py_eval_input, globals, globals);
402}
403
404/// Evaluate string in python from Singular
405BOOLEAN python_eval(leftv result, leftv arg) {
406  if ( !arg || (arg->Typ() != STRING_CMD) ) {
407    Werror("expected python_eval('string')");
408    return TRUE;
409  }
410
411  return python_eval(reinterpret_cast<const char*>(arg->Data())).assign_to(result);
412}
413
414
415/// Execute string in python from Singular
416BOOLEAN python_run(leftv result, leftv arg)
417{
418  if ( !arg || (arg->Typ() != STRING_CMD) ) {
419    Werror("expected python_run('string')");
420    return TRUE;
421  }
422
423  PyRun_SimpleString(reinterpret_cast<const char*>(arg->Data()));
424  sync_contexts();
425  return PythonCastStatic<>(Py_None).assign_to(result);
426}
427
428PythonObject names_from_module(const char* module_name)
429{
430  char buffer[strlen(module_name) + 30];
431  sprintf (buffer, "SINGULAR_MODULE_NAME = '%s'", module_name);
432  PyRun_SimpleString(buffer);
433  PyRun_SimpleString("from sys import modules");
434  PyRun_SimpleString("exec('from ' + SINGULAR_MODULE_NAME + ' import *')");
435
436  return python_eval("[str for str in dir(modules[SINGULAR_MODULE_NAME]) if str[0] != '_']");
437}
438
439void from_module_import_all(const char* module_name)
440{
441  char buffer[strlen(module_name) + 20];
442  sprintf (buffer, "from %s import *", module_name);
443  PyRun_SimpleString(buffer);
444}
445
446/// import python module and export identifiers in Singular namespace
447BOOLEAN python_import(leftv result, leftv value) {
448
449  if ((value == NULL) || (value->Typ()!= STRING_CMD)) {
450    Werror("expected python_import('string')");
451    return TRUE;
452  }
453
454  from_module_import_all(reinterpret_cast<const char*>(value->Data()));
455  sync_contexts();
456
457  return PythonCastStatic<>(Py_None).assign_to(result);
458}
459
460/// blackbox support - initialization
461void* pyobject_Init(blackbox*)
462{
463  return Py_None;
464}
465
466/// blackbox support - convert to string representation
467char* pyobject_String(blackbox *b, void* ptr)
468{
469  return PythonCastStatic<>(ptr).repr();
470}
471
472/// blackbox support - copy element
473void* pyobject_Copy(blackbox*b, void* ptr)
474{ 
475    Py_XINCREF(ptr);
476    return ptr;
477}
478
479/// blackbox support - assign element
480BOOLEAN pyobject_Assign(leftv l, leftv r)
481{
482  Py_XDECREF(l->Data());
483  PyObject* result = PythonCastDynamic(r);
484  Py_XINCREF(result);
485
486  if (l->rtyp == IDHDL)
487    IDDATA((idhdl)l->data) = (char *)result;
488  else
489    l->data = (void *)result;
490 
491  return !result;
492}
493                                                                     
494
495/// blackbox support - unary operations
496BOOLEAN pyobject_Op1(int op, leftv res, leftv head)
497{
498  switch(op)
499  {
500    case INT_CMD:               // built-in return types first
501    {
502      long value = PyInt_AsLong(PythonCastStatic<>(head));
503      if( (value == -1) &&  PyErr_Occurred() ) {
504        Werror("'pyobject` cannot be converted to integer");
505        PyErr_Clear();
506        return TRUE;
507      }
508      res->data = (void*) value;
509      res->rtyp = INT_CMD;
510      return FALSE;
511    }
512    case TYPEOF_CMD:
513      res->data = (void*) omStrDup("pyobject");
514      res->rtyp = STRING_CMD; 
515      return FALSE; 
516  }
517
518  if (!PythonCastStatic<>(head)(op).assign_to(res))
519    return FALSE;
520
521  BOOLEAN newstruct_Op1(int, leftv, leftv); // forward declaration
522  return newstruct_Op1(op, res, head);
523}
524
525
526/// blackbox support - binary operations
527BOOLEAN pyobject_Op2(int op, leftv res, leftv arg1, leftv arg2)
528{
529  PythonCastStatic<> lhs(arg1);
530
531  switch(op)                    // built-in return types and special cases first
532  { 
533    case '<': case '>': case EQUAL_EQUAL: case NOTEQUAL: case GE: case LE:
534    {
535      res->data = (void *)lhs.compare(op, PythonCastDynamic(arg2));
536      res->rtyp = INT_CMD;
537      return FALSE;
538    }
539    case '.': case COLONCOLON: case ATTRIB_CMD:
540      return lhs.attr(get_attrib_name(arg2)).assign_to(res);
541  }
542
543  PythonCastDynamic rhs(arg2);
544  if (!lhs(op, rhs).assign_to(res))
545    return FALSE;
546
547  BOOLEAN newstruct_Op2(int, leftv, leftv, leftv); // forward declaration
548  return newstruct_Op2(op, res, arg1, arg2);
549
550}
551
552/// blackbox support - ternary operations
553BOOLEAN pyobject_Op3(int op, leftv res, leftv arg1, leftv arg2, leftv arg3)
554{
555  PythonCastStatic<> lhs(arg1);
556  PythonCastDynamic rhs1(arg2);
557  PythonCastDynamic rhs2(arg3);
558
559  return lhs(op, rhs1, rhs2).assign_to(res);
560}
561
562
563/// blackbox support - n-ary operations
564BOOLEAN pyobject_OpM(int op, leftv res, leftv args)
565{
566  typedef PythonCastStatic<PythonObject::sequence_tag> seq_type;
567
568  switch(op)                    // built-in return types first
569  {
570    case STRING_CMD:
571    {
572      blackbox* a = getBlackboxStuff(args->Typ());
573      res->data = (void *)a->blackbox_String(a, args->Data());
574      res->rtyp = STRING_CMD;
575      return FALSE;
576    }
577  }
578
579  typedef PythonCastStatic<PythonObject::sequence_tag> seq_type;
580  if (! PythonCastStatic<>(args)(op, seq_type(args->next)).assign_to(res))
581    return FALSE;
582
583  BOOLEAN newstruct_OpM(int, leftv, leftv); // forward declaration
584  return newstruct_OpM(op, res, args);
585}
586
587/// blackbox support - destruction
588void pyobject_destroy(blackbox *b, void* ptr)
589{
590  Py_XDECREF(ptr);
591}
592
593PyObject* get_current_definition(const char* name) {
594  idhdl handle =  ggetid(name);
595  if (!handle || (IDTYP(handle) != PythonInterpreter::id()))  return NULL;
596  PythonCastStatic<PyObject*> value(IDDATA(handle));
597  return value;
598}
599
600/// getting stuff from python to Singular namespace
601void sync_contexts()
602{
603  PyRun_SimpleString("_SINGULAR_NEW = modules['__main__'].__dict__.copy()");
604
605  PythonObject newElts = python_eval("[(_k, _e)   \
606    for (_k, _e) in _SINGULAR_NEW.iteritems() \
607    if _k not in _SINGULAR_IMPORTED or not _SINGULAR_IMPORTED[_k] is _e]");
608
609  long len = newElts.size();
610  for (long idx = 0; idx < len; ++idx)
611  {
612    char* name = newElts[idx][0].str();
613    if (name && (*name != '\0') && (*name != '_'))
614    {
615      Py_XDECREF(get_current_definition(name));
616      newElts[idx][1].import_as(name);
617    }
618
619  }
620
621  PythonObject deletedElts = 
622    python_eval("list(set(_SINGULAR_IMPORTED.iterkeys()) - \
623     set(_SINGULAR_NEW.iterkeys()))");
624  len = deletedElts.size();
625
626  for (long idx = 0; idx < len; ++idx)
627  {
628    char* name = deletedElts[idx].str();
629    if (name && (*name != '\0') && (*name != '_'))
630      killid(name, &IDROOT);
631  }
632
633  PyRun_SimpleString("_SINGULAR_IMPORTED =_SINGULAR_NEW");
634  PyRun_SimpleString("del  _SINGULAR_NEW");
635}
636
637
638// forward declaration
639int iiAddCproc(char *libname, char *procname, BOOLEAN pstatic,
640               BOOLEAN(*func)(leftv res, leftv v));
641
642#define ADD_C_PROC(name) iiAddCproc("", (char*)#name, FALSE, name);
643
644
645void pyobject_init() 
646{
647  blackbox *b = (blackbox*)omAlloc0(sizeof(blackbox));
648  b->blackbox_destroy = pyobject_destroy;
649  b->blackbox_String  = pyobject_String;
650  b->blackbox_Init    = pyobject_Init;
651  b->blackbox_Copy    = pyobject_Copy;
652  b->blackbox_Assign  = pyobject_Assign;
653  b->blackbox_Op1     = pyobject_Op1;
654  b->blackbox_Op2     = pyobject_Op2;
655  b->blackbox_Op3     = pyobject_Op3;
656  b->blackbox_OpM     = pyobject_OpM;
657  b->data             = omAlloc0(newstruct_desc_size());
658
659  PythonInterpreter::init(setBlackboxStuff(b,"pyobject"));
660
661  ADD_C_PROC(python_import);
662  ADD_C_PROC(python_eval);
663  ADD_C_PROC(python_run);
664}
665
666extern "C" { void mod_init() { pyobject_init(); } }
667
Note: See TracBrowser for help on using the repository browser.