Annotation of python/pyGiNaC/tools/wrap_typedefs.py, revision 1.3

1.1       pearu       1: #!/usr/bin/env python
                      2: 
                      3: import re
                      4: 
                      5: ok_types = [
                      6:     'int','unsigned int','long','unsigned long','double const','const std::string &',
                      7:     'bool','unsigned','double','const char *','const cln::cl_N &','void',
                      8:     'std::ostream &','std::string const &'
                      9:     ]
                     10: 
                     11: def fix_type(a):
                     12:     if a in ok_types:
                     13:         return a
                     14:     m = re.match(r'(?P<before>.*?)\b(?P<type>symbol|ex|numeric|expairseq|exprseq|basic|exvector|epvector|exlist|evalffunctype|matrix|lst|scalar_products|pseries|relational|expair|epplist)\b(?P<rest>.*)',a)
                     15:     if m:
                     16:         return m.group('before')+'GiNaC::'+m.group('type')+m.group('rest')
1.2       pearu      17:     if a == 'malloc_alloc':
                     18:         return a # ignore it
1.3     ! pearu      19:     m = re.match(r'(?P<before>.*?)\b(?P<type>series_funcp_\d+|derivative_funcp_\d+|evalf_funcp_\d+|eval_funcp_\d+|(eval|evalf|derivative|series)_funcp|)\b(?P<rest>.*)',a)
        !            20:     if m:
        !            21:         return m.group('before')+'GiNaC::'+m.group('type')+m.group('rest')
1.1       pearu      22:     print 'Not fixed:',a
                     23:     return a
                     24: 
                     25: def construct_vector_wrapper(name,ft,t):
                     26:     return '''\
                     27: // typedef #name# wrapper
                     28: struct #name#_wrapper: #ftype# {
                     29: \t#name#_wrapper(PyObject*, const #ftype#& v) : #ftype#(v) {}
                     30: \t#name#_wrapper(PyObject* self) : #ftype#() {}
1.2       pearu      31: \t#name#_wrapper(PyObject* self, const std::size_t n) : #ftype#(n) {}
1.1       pearu      32: \t#name#_wrapper(PyObject* self, const python::tuple seq) : #ftype#()
                     33: \t{
1.2       pearu      34: \t\tfor (std::size_t i = 0; i < seq.size(); i++)
1.1       pearu      35: \t\t\tthis->push_back(BOOST_PYTHON_CONVERSION::from_python(seq[i].get(), python::type< #type# >()));
                     36: \t}
                     37: };
                     38: void #name#_throw_index_error_if(const #ftype#& v, const std::size_t key)
                     39: {
                     40: \tif ((key >= v.size()) || (key < 0))
                     41: \t{
                     42: \t\tPyErr_SetObject(PyExc_IndexError, BOOST_PYTHON_CONVERSION::to_python(key));
                     43: \t\tthrow python::error_already_set();
                     44: \t}
                     45: }
                     46: #type# #name#_getitem (const #ftype#& v, const std::size_t key)
                     47: {
                     48: \t#name#_throw_index_error_if(v, key);
                     49: \treturn v[key];
                     50: }
                     51: void #name#_setitem(#ftype#& v, const std::size_t key, const #type# &d)
                     52: {
                     53: \t#ftype#::iterator viter = v.begin();
                     54: \t#name#_throw_index_error_if(v, key);
                     55: \tviter[key] = d;
                     56: }
                     57: void #name#_delitem(#ftype# & v, const std::size_t key)
                     58: {
                     59: \t#ftype#::iterator viter = v.begin();
                     60: \t#name#_throw_index_error_if(v, key);
                     61: \tv.erase(&viter[key]);
                     62: }
                     63: '''.replace('#name#',name).replace('#ftype#',ft).replace('#type#',t)
                     64: def construct_list_wrapper(name,ft,t):
                     65:     return '''\
                     66: // typedef #name# wrapper
                     67: struct #name#_wrapper: #ftype# {
                     68: \t#name#_wrapper(PyObject*, const #ftype#& v) : #ftype#(v) {}
                     69: \t#name#_wrapper(PyObject* self) : #ftype#() {}
1.2       pearu      70: \t#name#_wrapper(PyObject* self, const std::size_t n) : #ftype#(n) {}
1.1       pearu      71: \t#name#_wrapper(PyObject* self, const python::tuple seq) : #ftype#()
                     72: \t{
1.2       pearu      73: \t\tfor (std::size_t i = 0; i < seq.size(); i++)
1.1       pearu      74: \t\t\tthis->push_back(BOOST_PYTHON_CONVERSION::from_python(seq[i].get(),python::type< #type# >()));
                     75: \t}
                     76: };
                     77: void #name#_throw_index_error_if(const #ftype#& v, const std::size_t key)
                     78: {
                     79: \tif ((key >= v.size()) || (key < 0))
                     80: \t{
                     81: \t\tPyErr_SetObject(PyExc_IndexError, BOOST_PYTHON_CONVERSION::to_python(key));
                     82: \t\tthrow python::error_already_set();
                     83: \t}
                     84: }
                     85: #type# #name#_getitem (const #ftype#& v, const std::size_t key)
                     86: {
                     87: \t#ftype#::const_iterator viter = v.begin();
                     88: \t#name#_throw_index_error_if(v, key);
                     89: \tfor(unsigned int i = 0; i < key; i++,viter++);
                     90: \treturn *viter;
                     91: }
                     92: void #name#_setitem(#ftype#& v, const std::size_t key, const #type# &d)
                     93: {
                     94: \t#ftype#::iterator viter = v.begin();
                     95: \t#name#_throw_index_error_if(v, key);
                     96: \tfor(unsigned int i = 0; i < key; i++,viter++);
                     97: \tv.insert(viter,d);
                     98: \tviter = v.begin();
                     99: \tfor(unsigned int i = 0; i < key; i++,viter++);
                    100: \tviter++;
                    101: \tv.erase(viter);
                    102: }
                    103: void #name#_delitem(#ftype# & v, const std::size_t key)
                    104: {
                    105: \t#ftype#::iterator viter = v.begin();
                    106: \t#name#_throw_index_error_if(v, key);
                    107: \tfor(unsigned int i = 0; i < key; i++,viter++);
                    108: \tv.erase(viter);
                    109: }
                    110: '''.replace('#name#',name).replace('#ftype#',ft).replace('#type#',t)
                    111: 
1.3     ! pearu     112: def construct_func_wrapper(name,ft,t):
        !           113:     return '''
        !           114: // typedef #name# wrapper
        !           115: struct #name#_wrapper: #ftype# {
        !           116: \t#name#_wrapper(PyObject* self) {cout << "#name#_wrapper_constructor" << endl ;}
        !           117: };
        !           118:     '''.replace('#name#',name).replace('#ftype#',ft).replace('#type#',t)
        !           119: 
1.1       pearu     120: fin = open('strip_ginac_rest.txt','r')
                    121: ftodo = open('todo_wtf.txt','w')
                    122: def todo(l):
                    123:     ftodo.write(l)
                    124: 
                    125: td_m = re.compile(r'typedef\s+(?P<type>.*?)\s+\b(?P<name>\w+)\b\s*;')
1.3     ! pearu     126: tdf_m = re.compile(r'typedef\s+(?P<type>.*?)\s*[(]\s*[*]\s*\b(?P<name>\w+)\b\s*[)]\s*[(]\s*(?P<args>.*?)\s*[)]\s*;')
        !           127: #typedef ex (*evalffunctype)(void);
1.1       pearu     128: 
                    129: defs = {'classes':[],'defs':[],'wrappers':[],'proto':['\t// prototypes of typedef ... wrappers']}
                    130: ignore = []
                    131: for l in fin.xreadlines():
                    132:     m = td_m.match(l.strip())
                    133:     if m:
                    134:         n,t = m.group('name'),m.group('type').strip()
                    135:         if (n,t) in ignore: continue
                    136:         ignore.append((n,t))
1.3     ! pearu     137:         if 0 and (t[:11]=='std::vector' or t[:9]=='std::list') and n in ['exvector','epvector','exlist']:
1.1       pearu     138:             if t[:11]=='std::vector':
                    139:                 args = [fix_type(a.strip()) for a in t[12:-1].split(',')]
                    140:                 ft = 'std::vector<'+', '.join(args)+'>'
1.2       pearu     141:                 ft = fix_type(n)
1.1       pearu     142:                 if n=='exvector' and len(args)==2:
                    143:                     continue
                    144:             elif t[:9]=='std::list':
                    145:                 args = [fix_type(a.strip()) for a in t[10:-1].split(',')]
                    146:                 ft = 'std::list<'+', '.join(args)+'>'
1.2       pearu     147:                 ft = fix_type(n)
1.1       pearu     148:                 if n=='exlist' and len(args)==2:
                    149:                     continue
                    150:             else:
                    151:                 assert 0,'unimpl.'
                    152:             r = '\tpython::class_builder<%s, %s_wrapper> %s_class(this_module, "%s");'%(ft,n,n,n)
                    153:             defs['classes'].append('\t// typedef %s'%(n))
                    154:             defs['classes'].append(r)
                    155:             defs['defs'].append('\t// typedef %s constructors'%(n))
                    156:             defs['defs'].append('\t%s_class.def(python::constructor<>());'%(n))
                    157:             defs['defs'].append('\t%s_class.def(python::constructor<const int>());'%(n))
                    158:             defs['defs'].append('\t%s_class.def(python::constructor<python::tuple>());'%(n))
1.2       pearu     159:             defs['defs'].append('\t// typedef %s methods'%(n))
1.1       pearu     160:             defs['defs'].append('\t%s_class.def(&%s::size, "__len__");'%(n,ft))
                    161:             assert len(args)==1
                    162:             if t[:11]=='std::vector':
                    163:                 defs['wrappers'].append(construct_vector_wrapper(n,ft,args[0]))
                    164:             elif t[:9]=='std::list':
                    165:                 defs['wrappers'].append(construct_list_wrapper(n,ft,args[0]))
                    166:             else:
                    167:                 assert 0,'unimpl.'
                    168:             defs['proto'].append('\tstruct %s_wrapper;'%n)
                    169:             defs['proto'].append('\t%s %s_getitem(const %s &, const std::size_t);'%(args[0],n,ft))
                    170:             defs['proto'].append('\tvoid %s_setitem(%s &, const std::size_t, const %s &);'%(n,ft,args[0]))
                    171:             defs['proto'].append('\tvoid %s_delitem(%s &, const std::size_t);'%(n,ft))
                    172:             defs['defs'].append('\t%s_class.def(%s_getitem, "__getitem__");'%(n,n))
                    173:             defs['defs'].append('\t%s_class.def(%s_setitem, "__setitem__");'%(n,n))
                    174:             defs['defs'].append('\t%s_class.def(%s_delitem, "__delitem__");'%(n,n))
1.2       pearu     175:             continue
                    176:         if n in ['epp','epplist','epplistvector','epviter','spmapkey','spmap',
                    177:                  'archive_node_id','archive_atom']:
                    178:             # no need to interface
1.1       pearu     179:             continue
                    180:         print 'Skipped typedef:',t,n
1.3     ! pearu     181:     m = tdf_m.match(l.strip())
        !           182:     if m:
        !           183:         rt = m.group('type')
        !           184:         n = m.group('name')
        !           185:         ft = fix_type(n)
        !           186:         args = [fix_type(a.strip()) for a in m.group('name').split(',')]
        !           187:         if n == 'evalffunctype':
        !           188:             print 'n=',n
        !           189:             print 'ft=',ft
        !           190:             print 'rt=',rt
        !           191:             print 'args=',args
        !           192:             defs['classes'].append('\t// typedef (*%s)()'%(n))
        !           193:             defs['classes'].append('\tpython::class_builder<%s, %s_wrapper> %s_class(this_module, "%s");'%(ft,n,n,n))
        !           194:             print defs['classes'][-1]
        !           195:             defs['defs'].append('\t// typedef %s constructors'%(n))
        !           196:             defs['defs'].append('\t%s_class.def(python::constructor<>());'%(n))
        !           197:             defs['proto'].append('\tstruct %s_wrapper;'%n)
        !           198:             defs['wrappers'].append(construct_func_wrapper(n,ft,args[0]))
1.1       pearu     199:     todo(l)
1.3     ! pearu     200:     
1.1       pearu     201: fin.close()
                    202: ftodo.close()
                    203: 
                    204: open('../src/typedef_class._cpp','w').write('\n'.join(defs['classes'])+'\n')
                    205: open('../src/typedef_method._cpp','w').write('\n'.join(defs['defs'])+'\n')
                    206: open('../src/typedef_wrapper._cpp','w').write('\n'.join(defs['wrappers'])+'\n')
                    207: open('../src/typedef_proto._cpp','w').write('\n'.join(defs['proto'])+'\n')

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>