source: git/modules/openmathserver/objects.py @ 3781a2

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