source: git/modules/openmathserver/objects.py @ 559396

spielwiese
Last change on this file since 559396 was 559396, checked in by Michael Brickenstein <bricken@…>, 18 years ago
*bricken: refactored git-svn-id: file:///usr/local/Singular/svn/trunk@8378 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 9.7 KB
Line 
1from omexceptions import *
2from exceptions import *
3from copy import copy
4import base64
5#TODO: OMOBJ, OME, OMATTR
6#from cd import *
7class XMLAttribute(object):
8    def __init__(self, name, value):
9        self.name=name
10        self.value=value
11    def encode(self, context):
12        return "".join([self.name,"=\"",self.value,"\""])
13class OMObjectBase(object):
14    """ at the moment only a base class"""
15    def __init__(self):
16        self.attributes={}
17    def __getChildren(self):
18        try:
19            return self.getChildren()
20        except AttributeError:
21            try:
22                return self.__children
23            except AttributeError:
24                return []
25    def __delChildren(self):
26        try:
27            self.delChildren()
28            return
29        except AttributeError:
30            try:
31                del self.__children
32            except AttributeError:
33                pass
34    def __setChildren(self,children):
35        try:
36            self.setChildren(children)
37        except AttributeError:
38                raise UnsupportedOperationError
39    def __getBody(self):
40        try:
41            return self.getBody()
42        except AttributeError:
43            try:
44                return self.__body
45            except AttributeError:
46                return None
47    def __delBody(self):
48        try:
49            self.delBody()
50            return
51        except AttributeError:
52            try:
53                del self.__body
54            except AttributeError:
55                pass
56    def __setBody(self,body):
57        try:
58            self.setBody(body)
59        except AttributeError:
60                raise UnsupportedOperationError
61    def __getXMLAttributes(self):
62        try:
63            return self.getXMLAttributes()
64        except AttributeError:
65            try:
66                return self.__XMLAttributes
67            except AttributeError:
68                #do return None, cause if modifiying a new list, changes will not be saved
69                return []
70    def __delXMLAttributes(self):
71        try:
72            self.delXMLAttributes()
73            return
74        except AttributeError:
75            try:
76                del self.__XMLAttributes
77            except AttributeError:
78                pass
79    def __setXMLAttributes(self,XMLAttributes):
80        try:
81            self.setBody(XMLAttributes)
82        except AttributeError:
83            raise UnsupportedOperationError
84    children=property(__getChildren, __setChildren,__delChildren,\
85                      """ children in an OMtree""")
86    body=property(__getBody,__setBody,__delBody,\
87        "xml body,FIXME: at the moment only char data")
88    XMLAttributes=property(__getXMLAttributes,__setXMLAttributes,__delXMLAttributes,\
89        "xml attributes")
90    def XMLEncode(self, context):
91       
92        attr=self.XMLAttributes
93        if attr:
94            attrstr=" "+" ".join([a.encode(context) for a in attr])
95        else:
96            attrstr=""
97        opening="".join(["<", self.XMLtag, attrstr,">"])
98        children=self.children
99        if children:
100            body="".join([context.XMLEncodeObject(c) for c in children])
101        else:
102            body=self.body
103            if not body:
104                body=""
105            assert body!=None
106            body=context.XMLEncodeBody(body)
107            assert body!=None
108        closing="".join(["</"+self.XMLtag+">"])
109        return "".join([opening,body,closing])
110class OMObject(OMObjectBase):
111    def __init__(self, children):
112        super(OMObject,self).__init__()
113        self.children=children
114    def getChildren(self):
115        return self.__children
116    def setChildren(self,children):
117        self.__children=children
118    XMLtag="OMOBJ"
119    def evaluate(self, context):
120        return OMObject([context.evaluate(c) for c in self.children])
121class OMVar(OMObjectBase):
122    def __init__(self,name):
123        super(OMVar,self).__init__()
124        self.name=name
125    def evaluate(self,context):
126        try:
127            return context[self.name]
128        except OutOfScopeError:
129            return self
130    def __str__(self):
131        return "OMV(" + self.name +")"
132    XMLtag="OMV"
133    def getXMLAttributes(self):
134        return [XMLAttribute("name", self.name)]
135       
136class OMApply(OMObjectBase):
137    def __init__(self, func, args):
138        super(OMApply,self).__init__()
139        self.func=func
140        self.args=args
141    def evaluate(self,context):
142        efunc=context.evaluate(self.func)
143        eargs=[context.evaluate(a) for a in self.args]
144        if callable(efunc):
145            try:
146                return context.apply(efunc, eargs)
147            except EvaluationFailedError, NotImplementedError:
148                return OMApply(efunc, eargs)
149                #return self
150        else:
151            return OMApply(efunc, eargs)
152    XMLtag="OMA"
153    def getChildren(self):
154        return [self.func]+self.args
155    def setChildren(self):
156        raise UnsupportedOperationError
157       
158class OMSymbol(OMObjectBase):
159    def __init__(self,name,cd=None):
160        super(OMSymbol,self).__init__()
161        self.cd=cd
162        self.name=name
163    def __eq__(self, other):
164        try:
165            return bool(other.name==self.name and self.cd==other.cd)
166        except:
167            return False
168    def __str__(self):
169        return "OMS("+self.name+", "+self.cd.name + ")"
170    def __hash__(self):#
171        return hash((self.name,self.cd.__hash__()))
172    def evaluate(self,context):
173        return context.evaluateSymbol(self)
174    XMLtag="OMS"
175    def getXMLAttributes(self):
176        return [XMLAttribute("name", self.name),\
177                 XMLAttribute("cdbase",self.cd.base),\
178                 XMLAttribute("cd",self.cd.name)]
179    def setXMLAttributes(self):
180        raise UnsupportedOperationError
181class SimpleValue(OMObjectBase):
182    def __init__(self,value):
183        super(SimpleValue,self).__init__()
184        if (isinstance(value, str)):
185            value=self.parse(value)
186        self.value=value
187    def evaluate(self, context):
188        return self
189    def getValue(self):
190        return self.value
191    def __str__(self):
192        return "OM("+repr(self.value)+")"
193
194class OMint(SimpleValue):
195    def __init__(self,value):
196        if not isinstance(value,int):
197            value=self.parse(value)
198        super(OMint,self).__init__(value)
199    def parse(self,value):
200        """FIXME: Not fully standard compliant,
201        -> hex encodings"""
202        return int(value,10)
203    def __str__(self):
204        return "OMint("+repr(self.value)+")"
205    def getBody(self):
206        return str(self.value)
207    def setBody(self, value):
208        raise UnsupportedOperationError
209    XMLtag="OMI"
210class OMfloat(SimpleValue):
211    def __init__(self,value):
212        super(OMfloat,self).__init__(value)
213    def parse(self, value):
214        """FIXME: Not fully standard compliant,
215        -> hex encodings"""
216        return float(value)
217    def __str__(self):
218        return "OMfloat("+repr(self.value)+")"
219    XMLtag="OMF"
220    def getXMLAttributes(self):
221        return [XMLAttribute("dec",str(self.value))]
222class OMString(SimpleValue):
223    def __init__(self,value):
224        super(OMString,self).__init__(value)
225    def __str__(self):
226        return "OMSTR("+repr(self.value)+")"
227    XMLtag="OMSTR"
228    def getBody(self):
229        return self.value
230class OMByteArray(SimpleValue):
231    def __init__(self,value):
232        super(OMByteArray,self).__init__(value)
233    def __str__(self):
234        return "OMByteArray("+repr(self.value)+")"
235    def parse(self, value):
236        return value
237    XMLtag="OMB"
238    def getBody(self):
239        return base64.encodestring(self.value)
240class OMRef(OMObjectBase):
241    def __init__(self, ref):
242        self.ref=ref
243    def evaluate(self, context):
244        return context.evaluate(self.ref)
245    def XMLEncode(self, context):
246        "FIXME: maybe it should also be able to encode as reference"
247        return context.XMLEncodeObject(self.ref)
248class OMAttributePair(OMObjectBase):
249    def __init__(self,key, value):
250        super(OMAttributePair,self).__init__()
251        self.key=key
252        self.value=value
253    def getChildren(self):
254        return [self.key, self.value]
255    XMLtag = "OMATP"
256    def evaluate(self, context):
257        return OMAttributePair(context.evaluate(self.key),\
258            context.evaluate(self.value))
259class OMAttribution(OMObjectBase):
260    def __init__(self, *args):
261        super(OMAttribution,self).__init__()
262        self.attr=list(args[:-1])
263        self.value=args[-1]
264    def getChildren(self):
265        #print type(self.attr)
266        #print type(self.value)
267        return self.attr+[self.value]
268    def evaluate(self, context):
269        value=copy(self.value)
270        value.attributes=copy(value.attributes)
271        for a in self.attr:
272            ae=context.evaluate(a)
273            value.attributes[ae.key]=ae.value
274        return value
275    XMLtag="OMATTR"
276if __name__=='__main__':
277    from context import *
278
279    from binding import *
280
281    context=Context()
282
283    context.push({})
284
285    context["x"]=OMint(1)
286
287    x=OMVar("x")
288
289    y=OMVar("y")
290
291    print context.evaluate(x)
292    print context.evaluate(y)
293    firstArg=OMBinding(lambdasym,[OMVar("x"), OMVar("y")], OMVar("x"))
294    #print context.evaluate(firstArg)
295    application=OMApply(firstArg, [x,y])
296    print context.evaluate(application)
297    application=OMApply(firstArg,[y,x])
298    print context.evaluate(application)
299    import arith1
300    context.addCDImplementation(arith1.implementation)
301    #print type(context.lookupImplementation(arith1.plussym))
302    #application=OMApply(arith1.plussym,[x])
303    #application=OMApply(arith1.plussym,[x,x])
304    application=OMApply(OMSymbol("plus",arith1.content),[x,x])
305   
306    print context.evaluate(application)
307    application=OMApply(OMSymbol("plus",arith1.content),[x,x,x])
308   
309    print context.evaluate(application)
310    i=OMint(22482489)
311    print i.body
312    print i.XMLEncode(context)
313    #i.body="dshj"
314   
Note: See TracBrowser for help on using the repository browser.