Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/TurtleArt/tatype.py
blob: 477e028a6980ec2fed1871647f999ec50d1328be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#Copyright (c) 2013 Marion Zepf

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.

""" type system for Primitives and their arguments """

import ast
from gettext import gettext as _

from taconstants import (Color, CONSTANTS)
from tautils import debug_output


class Type(object):
    """ A type in the type hierarchy. The `name` attribute is only for
    pretty-printing. The `value` attribute should be of a type that is fast
    to compare, like e.g., int. """
    def __init__(self, name, value):
        self.name = name
        self.value = value
    def __eq__(self, other):
        if other is None:
            return False
        if not isinstance(other, Type):
            raise TypeError("cannot compare Type to object of type " +
                            repr(type(other)))
        return self.value == other.value
    def __repr__(self):
        return repr(self.name)
    def __str__(self):
        return str(self.name)


class TypeDisjunction(tuple,Type):
    """ Disjunction of two or more Types (from the type hierarchy) """
    pass


TYPE_OBJECT = Type('object', 0)
TYPE_CHAR = Type('char', 1)
TYPE_COLOR = Type('color', 2)
TYPE_FLOAT = Type('float', 3)
TYPE_INT = Type('int', 4)
TYPE_NEGATIVE = Type('negative', 5)
TYPE_NUMBER = Type('number', 6)
TYPE_NUMERIC_STRING = Type('numeric string', 7)
TYPE_POSITIVE = Type('positive', 8)
TYPE_STRING = Type('string', 9)
TYPE_ZERO = Type('zero', 10)
# TODO add list types


def get_type(x):
    """ Return the most specific type in the type hierarchy that applies to x
    and a boolean indicating whether x is an AST. If the type cannot be
    determined, return TYPE_OBJECT as the type. """
    # non-AST types
    if isinstance(x, (float, int, long)):
        if x > 0:
            return (TYPE_POSITIVE, False)
        elif x == 0:
            return (TYPE_ZERO, False)
        else:
            return (TYPE_NEGATIVE, False)
    elif isinstance(x, basestring):
        if len(x) == 1:
            return (TYPE_CHAR, False)
        try:
            float(x)
        except ValueError:
            return (TYPE_STRING, False)
        else:
            return (TYPE_NUMERIC_STRING, False)
    elif isinstance(x, Color):
        return (TYPE_COLOR, False)
    elif hasattr(x, "return_type"):
        return (x.return_type, False)

    # AST types
    elif isinstance(x, ast.Num):
        return (get_type(x.n)[0], True)
    elif isinstance(x, ast.Str):
        return (get_type(x.s)[0], True)
    elif isinstance(x, ast.Name):
        try:
            # we need to have imported CONSTANTS for this to work
            value = eval(x.id)
        except NameError:
            return (TYPE_OBJECT, True)
        else:
            return (get_type(value)[0], True)
    elif isinstance(x, ast.Call):
        if isinstance(x.func, ast.Name):
            if x.func.id in ('float', 'int'):
                return (x.func.__name__, True)
            elif x.func.id in ('repr', 'str', 'unicode'):
                return (TYPE_STRING, True)

    return (TYPE_OBJECT, isinstance(x, ast.AST))


def is_instancemethod(method):
    # TODO how to access the type `instancemethod` directly?
    return type(method).__name__ == "instancemethod"

def is_bound_instancemethod(method):
    return is_instancemethod(method) and method.im_self is not None

def is_unbound_instancemethod(method):
    return is_instancemethod(method) and method.im_self is None

def is_staticmethod(method):
    # TODO how to access the type `staticmethod` directly?
    return type(method).__name__ == "staticmethod"


def identity(x):
    return x

TYPE_CONVERTERS = {
    # Type hierarchy: If there is a converter A -> B, then A is a subtype of B.
    # The converter from A to B is stored under TYPE_CONVERTERS[A][B].
    # The relation describing the type hierarchy must be transitive, i.e.
    # converting A -> C must yield the same result as converting A -> B -> C.
    # TYPE_OBJECT is the supertype of everything.
    TYPE_CHAR: {
        TYPE_POSITIVE: ord,  # ignore the zero byte, chr(0)
        TYPE_STRING: identity},
    TYPE_COLOR: {
        TYPE_FLOAT: float,
        TYPE_INT: int,
        TYPE_NUMBER: int,
        TYPE_STRING: Color.get_number_string},
    TYPE_FLOAT: {
        TYPE_INT: int,
        TYPE_NUMBER: identity,
        TYPE_STRING: str},
    TYPE_INT: {
        TYPE_FLOAT: float,
        TYPE_NUMBER: identity,
        TYPE_STRING: str},
    TYPE_NEGATIVE: {
        TYPE_FLOAT: float,
        TYPE_INT: int,
        TYPE_NUMBER: identity,
        TYPE_STRING: str},
    TYPE_NUMBER: {
        TYPE_STRING: str},
    TYPE_NUMERIC_STRING: {
        TYPE_FLOAT: float,
        TYPE_STRING: identity},
    TYPE_POSITIVE: {
        TYPE_FLOAT: float,
        TYPE_INT: int,
        TYPE_NUMBER: identity,
        TYPE_STRING: str},
    TYPE_ZERO: {
        TYPE_FLOAT: float,
        TYPE_INT: int,
        TYPE_NUMBER: identity,
        TYPE_STRING: str}
}


def get_call_ast(func_name, args=None, keywords=None):
    """ Return an AST representing the call to a function with the name
    func_name, passing it the arguments args (given as a list) and the
    keyword arguments keywords (given as a dictionary). """
    if args is None:
        args = []
    if keywords is None:
        keywords = {}
    return ast.Call(func=ast.Name(id=func_name,
                                  ctx=ast.Load),
                    args=args,
                    keywords=keywords,
                    starargs=None,
                    kwargs=None)


class TATypeError(BaseException):
    """ TypeError with the types from the hierarchy, not with Python types """

    def __init__(self, bad_value, bad_type=None, req_type=None, message=''):
        """ bad_value -- the mis-typed value that caused the error
        bad_type -- the type of the bad_value
        req_type -- the type that the value was expected to have
        message -- short statement about the cause of the error. It is
            not shown to the user, but may appear in debugging output. """
        self.bad_value = bad_value
        self.bad_type = bad_type
        self.req_type = req_type
        self.message = message

    def __str__(self):
        msg = []
        if self.message:
            msg.append(self.message)
            msg.append(" (")
        msg.append("bad value: ")
        msg.append(repr(self.bad_value))
        if self.bad_type is not None:
            msg.append(", bad type: ")
            msg.append(repr(self.bad_type))
        if self.req_type is not None:
            msg.append(", req type: ")
            msg.append(repr(self.req_type))
        if self.message:
            msg.append(")")
        return "".join(msg)
    __repr__ = __str__


def get_converter(old_type, new_type):
    """ If there is a converter old_type -> new_type, return it. Else return
    None. If a chain of converters is necessary, return it as a tuple or
    list (starting with the innermost, first-to-apply converter). """
    # every type can be converted to TYPE_OBJECT
    if new_type == TYPE_OBJECT:
        return identity
    # every type can be converted to itself
    if old_type == new_type:
        return identity

    # is there a converter for this pair of types?
    converters_from_old = TYPE_CONVERTERS.get(old_type)
    if converters_from_old is None:
        return None
    converter = converters_from_old.get(new_type)
    if converter is not None:
        return converter
    else:
        # form the transitive closure of all types that old_type can be
        # converted to, and look for new_type there
        backtrace = converters_from_old.copy()
        new_backtrace = backtrace
        break_all = False
        while True:
            newest_backtrace = {}
            for t in new_backtrace:
                for new_t in TYPE_CONVERTERS.get(t, {}):
                    if new_t not in backtrace:
                        newest_backtrace[new_t] = t
                        backtrace[new_t] = t
                        if new_t == new_type:
                            break_all = True
                            break
                if break_all:
                    break
            if break_all or not newest_backtrace:
                break
            new_backtrace = newest_backtrace
        # use the backtrace to find the path from old_type to new_type
        if new_type in backtrace:
            converter_chain = []
            t = new_type
            while t in backtrace and isinstance(backtrace[t], Type):
                converter_chain.insert(0, TYPE_CONVERTERS[backtrace[t]][t])
                t = backtrace[t]
            return converter_chain
    return None


def convert(x, new_type, old_type=None, converter=None):
    """ Convert x to the new type if possible.
    old_type -- the type of x. If not given, it is computed. """
    if not isinstance(new_type, Type):
        raise ValueError('%s is not a type in the type hierarchy'
                         % (repr(new_type)))
    # every type can be converted to TYPE_OBJECT
    if new_type == TYPE_OBJECT:
        return x
    if not isinstance(old_type, Type):
        (old_type, is_an_ast) = get_type(x)
    else:
        is_an_ast = isinstance(x, ast.AST)
    # every type can be converted to itself
    if old_type == new_type:
        return x

    # if the converter is not given, try to find one
    if converter is None:
        converter = get_converter(old_type, new_type)
        if converter is None:
            # no converter available
            raise TATypeError(bad_value=x, bad_type=old_type,
                              req_type=new_type, message=("found no converter"
                                  " for this type combination"))

    def _apply_converter(converter, y):
        if is_an_ast:
            if converter == identity:
                return y
            elif is_instancemethod(converter):
                func = ast.Attribute(value=y,
                                     attr=converter.im_func.__name__,
                                     ctx=ast.Load)
                return ast.Call(func=func,
                                args=[],
                                keywords={},
                                starargs=None,
                                kwargs=None)
            else:
                func_name = converter.__name__
                return get_call_ast(func_name, [y])
        else:
            return converter(y)

    if isinstance(converter, (list, tuple)):
        # apply the converter chain recursively
        result = x
        for conv in converter:
            result = _apply_converter(conv, result)
        return result
    elif converter is not None:
        return _apply_converter(converter, x)