source: git/modules/openmathserver/objects.py @ 35ad2d

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