source: git/modules/openmathserver/objects.py @ 17c7ba

spielwiese
Last change on this file since 17c7ba was 17c7ba, checked in by Michael Brickenstein <bricken@…>, 19 years ago
*bricken: beautified git-svn-id: file:///usr/local/Singular/svn/trunk@8389 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 9.8 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,\
89        __setXMLAttributes,__delXMLAttributes,\
90        "xml attributes")
91    def XMLEncode(self, context):
92       
93        attr=self.XMLAttributes
94        if attr:
95            attrstr = " "+" ".join([a.encode(context) for a in attr])
96        else:
97            attrstr = ""
98        opening = "".join(["<", self.XMLtag, attrstr,">"])
99        children = self.children
100        if children:
101            body = "".join([context.XMLEncodeObject(c) for c in children])
102        else:
103            body = self.body
104            if not body:
105                body = ""
106            assert body != None
107            body = context.XMLEncodeBody(body)
108            assert body != None
109        closing = "".join(["</"+self.XMLtag+">"])
110        return "".join([opening,body,closing])
111class OMObject(OMObjectBase):
112    def __init__(self, children):
113        super(OMObject, self).__init__()
114        self.children = children
115    def getChildren(self):
116        return self.__children
117    def setChildren(self ,children):
118        self.__children=children
119    XMLtag = "OMOBJ"
120    def evaluate(self, context):
121        return OMObject([context.evaluate(c) for c in self.children])
122class OMVar(OMObjectBase):
123    def __init__(self,name):
124        super(OMVar, self).__init__()
125        self.name = name
126    def evaluate(self, context):
127        try:
128            return context[self.name]
129        except OutOfScopeError:
130            return self
131    def __str__(self):
132        return "OMV(" + self.name +")"
133    XMLtag = "OMV"
134    def getXMLAttributes(self):
135        return [XMLAttribute("name", self.name)]
136       
137class OMApply(OMObjectBase):
138    def __init__(self, func, args):
139        super(OMApply, self).__init__()
140        self.func = func
141        self.args = args
142    def evaluate(self, context):
143        efunc = context.evaluate(self.func)
144        eargs = [context.evaluate(a) for a in self.args]
145        if callable(efunc):
146            try:
147                return context.apply(efunc, eargs)
148            except EvaluationFailedError, NotImplementedError:
149                return OMApply(efunc, eargs)
150                #return self
151        else:
152            return OMApply(efunc, eargs)
153    XMLtag="OMA"
154    def getChildren(self):
155        return [self.func]+self.args
156    def setChildren(self):
157        raise UnsupportedOperationError
158       
159class OMSymbol(OMObjectBase):
160    def __init__(self,name,cd = None):
161        super(OMSymbol,self).__init__()
162        self.cd = cd
163        self.name = name
164    def __eq__(self, other):
165        try:
166            return bool(other.name == self.name and self.cd == other.cd)
167        except:
168            return False
169    def __str__(self):
170        return "OMS(" + self.name + ", " + self.cd.name + ")"
171    def __hash__(self):#
172        return hash((self.name,self.cd.__hash__()))
173    def evaluate(self,context):
174        return context.evaluateSymbol(self)
175    XMLtag="OMS"
176    def getXMLAttributes(self):
177        return [XMLAttribute("name", self.name),\
178                 XMLAttribute("cdbase", self.cd.base),\
179                 XMLAttribute("cd", self.cd.name)]
180    def setXMLAttributes(self):
181        raise UnsupportedOperationError
182class SimpleValue(OMObjectBase):
183    def __init__(self, value):
184        super(SimpleValue, self).__init__()
185        if (isinstance(value, str)):
186            value = self.parse(value)
187        self.value = value
188    def evaluate(self, context):
189        return self
190    def getValue(self):
191        return self.value
192    def __str__(self):
193        return "OM("+repr(self.value)+")"
194
195class OMint(SimpleValue):
196    def __init__(self,value):
197        if not isinstance(value,int):
198            value = self.parse(value)
199        super(OMint,self).__init__(value)
200    def parse(self,value):
201        """FIXME: Not fully standard compliant,
202        -> hex encodings"""
203        return int(value,10)
204    def __str__(self):
205        return "OMint("+repr(self.value)+")"
206    def getBody(self):
207        return str(self.value)
208    def setBody(self, value):
209        raise UnsupportedOperationError
210    XMLtag="OMI"
211class OMfloat(SimpleValue):
212    def __init__(self, value):
213        super(OMfloat, self).__init__(value)
214    def parse(self, value):
215        """FIXME: Not fully standard compliant,
216        -> hex encodings"""
217        return float(value)
218    def __str__(self):
219        return "OMfloat("+repr(self.value)+")"
220    XMLtag = "OMF"
221    def getXMLAttributes(self):
222        return [XMLAttribute("dec",str(self.value))]
223class OMString(SimpleValue):
224    def __init__(self,value):
225        super(OMString,self).__init__(value)
226    def __str__(self):
227        return "OMSTR("+repr(self.value)+")"
228    XMLtag = "OMSTR"
229    def getBody(self):
230        return self.value
231class OMByteArray(SimpleValue):
232    def __init__(self,value):
233        super(OMByteArray,self).__init__(value)
234    def __str__(self):
235        return "OMByteArray(" + repr(self.value) + ")"
236    def parse(self, value):
237        return value
238    XMLtag="OMB"
239    def getBody(self):
240        return base64.encodestring(self.value)
241class OMRef(OMObjectBase):
242    def __init__(self, ref):
243        self.ref=ref
244    def evaluate(self, context):
245        return context.evaluate(self.ref)
246    def XMLEncode(self, context):
247        "FIXME: maybe it should also be able to encode as reference"
248        return context.XMLEncodeObject(self.ref)
249class OMAttributePair(OMObjectBase):
250    def __init__(self, key, value):
251        super(OMAttributePair,self).__init__()
252        self.key = key
253        self.value = value
254    def getChildren(self):
255        return [self.key, self.value]
256    XMLtag = "OMATP"
257    def evaluate(self, context):
258        return OMAttributePair(context.evaluate(self.key),\
259            context.evaluate(self.value))
260class OMAttribution(OMObjectBase):
261    def __init__(self, *args):
262        super(OMAttribution,self).__init__()
263        self.attr = list(args[:-1])
264        self.value = args[-1]
265    def getChildren(self):
266        #print type(self.attr)
267        #print type(self.value)
268        return self.attr+[self.value]
269    def evaluate(self, context):
270        value = copy(self.value)
271        value.attributes = copy(value.attributes)
272        for a in self.attr:
273            ae=context.evaluate(a)
274            value.attributes[ae.key] = ae.value
275        return value
276    XMLtag = "OMATTR"
277if __name__ == '__main__':
278    from context import *
279
280    from binding import *
281
282    context = Context()
283
284    context.push({})
285
286    context["x"] = OMint(1)
287
288    x = OMVar("x")
289
290    y = OMVar("y")
291
292    print context.evaluate(x)
293    print context.evaluate(y)
294    firstArg=OMBinding(lambdasym,[OMVar("x"), OMVar("y")], OMVar("x"))
295    #print context.evaluate(firstArg)
296    application = OMApply(firstArg, [x,y])
297    print context.evaluate(application)
298    application = OMApply(firstArg, [y,x])
299    print context.evaluate(application)
300    import arith1
301    context.addCDImplementation(arith1.implementation)
302    #print type(context.lookupImplementation(arith1.plussym))
303    #application=OMApply(arith1.plussym,[x])
304    #application=OMApply(arith1.plussym,[x,x])
305    application = OMApply(OMSymbol("plus", arith1.content), [x, x])
306   
307    print context.evaluate(application)
308    application = OMApply(OMSymbol("plus", arith1.content), [x, x, x])
309   
310    print context.evaluate(application)
311    i =  OMint(22482489)
312    print i.body
313    print i.XMLEncode(context)
314    #i.body="dshj"
315   
Note: See TracBrowser for help on using the repository browser.