Lichen

Annotated encoders.py

543:b7334adb7dec
2017-02-04 Paul Boddie Handle situations where a global accidentally refers to a built-in module.
paul@0 1
#!/usr/bin/env python
paul@0 2
paul@0 3
"""
paul@0 4
Encoder functions, producing representations of program objects.
paul@0 5
paul@498 6
Copyright (C) 2016, 2017 Paul Boddie <paul@boddie.org.uk>
paul@0 7
paul@0 8
This program is free software; you can redistribute it and/or modify it under
paul@0 9
the terms of the GNU General Public License as published by the Free Software
paul@0 10
Foundation; either version 3 of the License, or (at your option) any later
paul@0 11
version.
paul@0 12
paul@0 13
This program is distributed in the hope that it will be useful, but WITHOUT
paul@0 14
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
paul@0 15
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
paul@0 16
details.
paul@0 17
paul@0 18
You should have received a copy of the GNU General Public License along with
paul@0 19
this program.  If not, see <http://www.gnu.org/licenses/>.
paul@0 20
"""
paul@0 21
paul@498 22
from common import first, InstructionSequence
paul@56 23
paul@0 24
# Output encoding and decoding for the summary files.
paul@0 25
paul@0 26
def encode_attrnames(attrnames):
paul@0 27
paul@0 28
    "Encode the 'attrnames' representing usage."
paul@0 29
paul@0 30
    return ", ".join(attrnames) or "{}"
paul@0 31
paul@0 32
def encode_constrained(constrained):
paul@0 33
paul@0 34
    "Encode the 'constrained' status for program summaries."
paul@0 35
paul@0 36
    return constrained and "constrained" or "deduced"
paul@0 37
paul@0 38
def encode_usage(usage):
paul@0 39
paul@0 40
    "Encode attribute details from 'usage'."
paul@0 41
paul@0 42
    all_attrnames = []
paul@0 43
    for t in usage:
paul@107 44
        attrname, invocation, assignment = t
paul@107 45
        all_attrnames.append("%s%s" % (attrname, invocation and "!" or assignment and "=" or ""))
paul@0 46
    return ", ".join(all_attrnames) or "{}"
paul@0 47
paul@88 48
def decode_usage(s):
paul@88 49
paul@88 50
    "Decode attribute details from 's'."
paul@88 51
paul@88 52
    all_attrnames = set()
paul@88 53
    for attrname_str in s.split(", "):
paul@107 54
        all_attrnames.add((attrname_str.rstrip("!="), attrname_str.endswith("!"), attrname_str.endswith("=")))
paul@88 55
paul@88 56
    all_attrnames = list(all_attrnames)
paul@88 57
    all_attrnames.sort()
paul@88 58
    return tuple(all_attrnames)
paul@88 59
paul@0 60
def encode_access_location(t):
paul@0 61
paul@0 62
    "Encode the access location 't'."
paul@0 63
paul@0 64
    path, name, attrname, version = t
paul@0 65
    return "%s %s %s:%d" % (path, name or "{}", attrname, version)
paul@0 66
paul@0 67
def encode_location(t):
paul@0 68
paul@0 69
    "Encode the general location 't' in a concise form."
paul@0 70
paul@0 71
    path, name, attrname, version = t
paul@0 72
    if name is not None and version is not None:
paul@0 73
        return "%s %s:%d" % (path, name, version)
paul@0 74
    elif name is not None:
paul@0 75
        return "%s %s" % (path, name)
paul@0 76
    else:
paul@0 77
        return "%s :%s" % (path, attrname)
paul@0 78
paul@0 79
def encode_modifiers(modifiers):
paul@0 80
paul@0 81
    "Encode assignment details from 'modifiers'."
paul@0 82
paul@0 83
    all_modifiers = []
paul@0 84
    for t in modifiers:
paul@0 85
        all_modifiers.append(encode_modifier_term(t))
paul@0 86
    return "".join(all_modifiers)
paul@0 87
paul@0 88
def encode_modifier_term(t):
paul@0 89
paul@0 90
    "Encode modifier 't' representing assignment status."
paul@0 91
paul@117 92
    assignment, invocation = t
paul@117 93
    return assignment and "=" or invocation and "!" or "_"
paul@0 94
paul@0 95
def decode_modifier_term(s):
paul@0 96
paul@0 97
    "Decode modifier term 's' representing assignment status."
paul@0 98
paul@117 99
    return (s == "=", s == "!")
paul@0 100
paul@56 101
paul@56 102
paul@56 103
# Test generation functions.
paul@56 104
paul@56 105
def get_kinds(all_types):
paul@56 106
paul@56 107
    """ 
paul@56 108
    Return object kind details for 'all_types', being a collection of
paul@56 109
    references for program types.
paul@56 110
    """
paul@56 111
paul@56 112
    return map(lambda ref: ref.get_kind(), all_types)
paul@56 113
paul@237 114
def test_label_for_kind(kind):
paul@56 115
paul@237 116
    "Return the label used for 'kind' in test details."
paul@56 117
paul@237 118
    return kind == "<instance>" and "instance" or "type"
paul@56 119
paul@237 120
def test_label_for_type(ref):
paul@56 121
paul@237 122
    "Return the label used for 'ref' in test details."
paul@56 123
paul@237 124
    return test_label_for_kind(ref.get_kind())
paul@56 125
paul@56 126
paul@56 127
paul@94 128
# Instruction representation encoding.
paul@94 129
paul@94 130
def encode_instruction(instruction):
paul@94 131
paul@94 132
    """
paul@94 133
    Encode the 'instruction' - a sequence starting with an operation and
paul@94 134
    followed by arguments, each of which may be an instruction sequence or a
paul@94 135
    plain value - to produce a function call string representation.
paul@94 136
    """
paul@94 137
paul@94 138
    op = instruction[0]
paul@94 139
    args = instruction[1:]
paul@94 140
paul@94 141
    if args:
paul@94 142
        a = []
paul@113 143
        for arg in args:
paul@113 144
            if isinstance(arg, tuple):
paul@113 145
                a.append(encode_instruction(arg))
paul@94 146
            else:
paul@113 147
                a.append(arg or "{}")
paul@94 148
        argstr = "(%s)" % ", ".join(a)
paul@94 149
        return "%s%s" % (op, argstr)
paul@94 150
    else:
paul@94 151
        return op
paul@94 152
paul@94 153
paul@94 154
paul@0 155
# Output program encoding.
paul@0 156
paul@153 157
attribute_loading_ops = (
paul@153 158
    "__load_via_class", "__load_via_object", "__get_class_and_load",
paul@153 159
    )
paul@153 160
paul@153 161
attribute_ops = attribute_loading_ops + (
paul@113 162
    "__store_via_object",
paul@113 163
    )
paul@113 164
paul@153 165
checked_loading_ops = (
paul@113 166
    "__check_and_load_via_class", "__check_and_load_via_object", "__check_and_load_via_any",
paul@153 167
    )
paul@153 168
paul@153 169
checked_ops = checked_loading_ops + (
paul@113 170
    "__check_and_store_via_class", "__check_and_store_via_object", "__check_and_store_via_any",
paul@113 171
    )
paul@113 172
paul@113 173
typename_ops = (
paul@144 174
    "__test_common_instance", "__test_common_object", "__test_common_type",
paul@113 175
    )
paul@113 176
paul@385 177
type_ops = (
paul@385 178
    "__test_specific_instance", "__test_specific_object", "__test_specific_type",
paul@385 179
    )
paul@385 180
paul@141 181
static_ops = (
paul@141 182
    "__load_static",
paul@141 183
    )
paul@141 184
paul@153 185
reference_acting_ops = attribute_ops + checked_ops + typename_ops
paul@153 186
attribute_producing_ops = attribute_loading_ops + checked_loading_ops
paul@153 187
paul@113 188
def encode_access_instruction(instruction, subs):
paul@113 189
paul@113 190
    """
paul@113 191
    Encode the 'instruction' - a sequence starting with an operation and
paul@113 192
    followed by arguments, each of which may be an instruction sequence or a
paul@113 193
    plain value - to produce a function call string representation.
paul@113 194
paul@113 195
    The 'subs' parameter defines a mapping of substitutions for special values
paul@113 196
    used in instructions.
paul@482 197
paul@482 198
    Return both the encoded instruction and a collection of substituted names.
paul@113 199
    """
paul@113 200
paul@113 201
    op = instruction[0]
paul@113 202
    args = instruction[1:]
paul@482 203
    substituted = set()
paul@113 204
paul@113 205
    if not args:
paul@113 206
        argstr = ""
paul@113 207
paul@113 208
    else:
paul@113 209
        # Encode the arguments.
paul@113 210
paul@113 211
        a = []
paul@153 212
        converting_op = op
paul@113 213
        for arg in args:
paul@482 214
            s, _substituted = encode_access_instruction_arg(arg, subs, converting_op)
paul@482 215
            substituted.update(_substituted)
paul@482 216
            a.append(s)
paul@153 217
            converting_op = None
paul@113 218
paul@113 219
        # Modify certain arguments.
paul@113 220
paul@113 221
        # Convert attribute name arguments to position symbols.
paul@113 222
paul@113 223
        if op in attribute_ops:
paul@113 224
            arg = a[1]
paul@113 225
            a[1] = encode_symbol("pos", arg)
paul@113 226
paul@113 227
        # Convert attribute name arguments to position and code symbols.
paul@113 228
paul@113 229
        elif op in checked_ops:
paul@113 230
            arg = a[1]
paul@113 231
            a[1] = encode_symbol("pos", arg)
paul@113 232
            a.insert(2, encode_symbol("code", arg))
paul@113 233
paul@113 234
        # Convert type name arguments to position and code symbols.
paul@113 235
paul@113 236
        elif op in typename_ops:
paul@339 237
            arg = encode_type_attribute(args[1])
paul@113 238
            a[1] = encode_symbol("pos", arg)
paul@113 239
            a.insert(2, encode_symbol("code", arg))
paul@113 240
paul@385 241
        # Obtain addresses of type arguments.
paul@385 242
paul@385 243
        elif op in type_ops:
paul@385 244
            a[1] = "&%s" % a[1]
paul@385 245
paul@141 246
        # Obtain addresses of static objects.
paul@141 247
paul@141 248
        elif op in static_ops:
paul@141 249
            a[0] = "&%s" % a[0]
paul@200 250
            a[1] = "&%s" % a[1]
paul@141 251
paul@491 252
        argstr = "(%s)" % ", ".join(map(str, a))
paul@113 253
paul@113 254
    # Substitute the first element of the instruction, which may not be an
paul@113 255
    # operation at all.
paul@113 256
paul@144 257
    if subs.has_key(op):
paul@482 258
        substituted.add(op)
paul@498 259
paul@498 260
        # Break accessor initialisation into initialisation and value-yielding
paul@498 261
        # parts:
paul@498 262
paul@498 263
        if op == "<set_accessor>" and isinstance(a[0], InstructionSequence):
paul@498 264
            ops = []
paul@498 265
            ops += a[0].get_init_instructions()
paul@498 266
            ops.append("%s(%s)" % (subs[op], a[0].get_value_instruction()))
paul@498 267
            return ", ".join(map(str, ops)), substituted
paul@498 268
paul@144 269
        op = subs[op]
paul@498 270
paul@144 271
    elif not args:
paul@144 272
        op = "&%s" % encode_path(op)
paul@144 273
paul@482 274
    return "%s%s" % (op, argstr), substituted
paul@113 275
paul@153 276
def encode_access_instruction_arg(arg, subs, op):
paul@113 277
paul@482 278
    """
paul@482 279
    Encode 'arg' using 'subs' to define substitutions, returning a tuple
paul@482 280
    containing the encoded form of 'arg' along with a collection of any
paul@482 281
    substituted values.
paul@482 282
    """
paul@113 283
paul@113 284
    if isinstance(arg, tuple):
paul@482 285
        encoded, substituted = encode_access_instruction(arg, subs)
paul@153 286
paul@153 287
        # Convert attribute results to references where required.
paul@153 288
paul@153 289
        if op and op in reference_acting_ops and arg[0] in attribute_producing_ops:
paul@482 290
            return "%s.value" % encoded, substituted
paul@153 291
        else:
paul@482 292
            return encoded, substituted
paul@113 293
paul@113 294
    # Special values only need replacing, not encoding.
paul@113 295
paul@113 296
    elif subs.has_key(arg):
paul@482 297
        return subs.get(arg), set([arg])
paul@113 298
paul@258 299
    # Convert static references to the appropriate type.
paul@258 300
paul@258 301
    elif op and op in reference_acting_ops and arg != "<accessor>":
paul@482 302
        return "&%s" % encode_path(arg), set()
paul@258 303
paul@113 304
    # Other values may need encoding.
paul@113 305
paul@113 306
    else:
paul@482 307
        return encode_path(arg), set()
paul@113 308
paul@0 309
def encode_function_pointer(path):
paul@0 310
paul@0 311
    "Encode 'path' as a reference to an output program function."
paul@0 312
paul@0 313
    return "__fn_%s" % encode_path(path)
paul@0 314
paul@0 315
def encode_instantiator_pointer(path):
paul@0 316
paul@0 317
    "Encode 'path' as a reference to an output program instantiator."
paul@0 318
paul@0 319
    return "__new_%s" % encode_path(path)
paul@0 320
paul@491 321
def encode_instructions(instructions):
paul@491 322
paul@491 323
    "Encode 'instructions' as a sequence."
paul@491 324
paul@491 325
    if len(instructions) == 1:
paul@491 326
        return instructions[0]
paul@491 327
    else:
paul@491 328
        return "(\n%s\n)" % ",\n".join(instructions)
paul@491 329
paul@136 330
def encode_literal_constant(n):
paul@136 331
paul@136 332
    "Encode a name for the literal constant with the number 'n'."
paul@136 333
paul@136 334
    return "__const%d" % n
paul@136 335
paul@378 336
def encode_literal_constant_size(value):
paul@378 337
paul@378 338
    "Encode a size for the literal constant with the given 'value'."
paul@378 339
paul@378 340
    if isinstance(value, basestring):
paul@378 341
        return len(value)
paul@378 342
    else:
paul@378 343
        return 0
paul@378 344
paul@136 345
def encode_literal_constant_member(value):
paul@136 346
paul@136 347
    "Encode the member name for the 'value' in the final program."
paul@136 348
paul@136 349
    return "%svalue" % value.__class__.__name__
paul@136 350
paul@136 351
def encode_literal_constant_value(value):
paul@136 352
paul@136 353
    "Encode the given 'value' in the final program."
paul@136 354
paul@136 355
    if isinstance(value, (int, float)):
paul@136 356
        return str(value)
paul@136 357
    else:
paul@451 358
        l = []
paul@451 359
paul@451 360
        # Encode characters including non-ASCII ones.
paul@451 361
paul@451 362
        for c in str(value):
paul@451 363
            if c == '"': l.append('\\"')
paul@451 364
            elif c == '\n': l.append('\\n')
paul@451 365
            elif c == '\t': l.append('\\t')
paul@451 366
            elif c == '\r': l.append('\\r')
paul@512 367
            elif c == '\\': l.append('\\\\')
paul@451 368
            elif 0x20 <= ord(c) < 0x80: l.append(c)
paul@451 369
            else: l.append("\\x%02x" % ord(c))
paul@451 370
paul@451 371
        return '"%s"' % "".join(l)
paul@136 372
paul@283 373
def encode_literal_data_initialiser(style):
paul@283 374
paul@283 375
    """
paul@283 376
    Encode a reference to a function populating the data for a literal having
paul@283 377
    the given 'style' ("mapping" or "sequence").
paul@283 378
    """
paul@283 379
paul@283 380
    return "__newdata_%s" % style
paul@283 381
paul@159 382
def encode_literal_instantiator(path):
paul@159 383
paul@159 384
    """
paul@159 385
    Encode a reference to an instantiator for a literal having the given 'path'.
paul@159 386
    """
paul@159 387
paul@159 388
    return "__newliteral_%s" % encode_path(path)
paul@159 389
paul@136 390
def encode_literal_reference(n):
paul@136 391
paul@136 392
    "Encode a reference to a literal constant with the number 'n'."
paul@136 393
paul@136 394
    return "__constvalue%d" % n
paul@136 395
paul@512 396
paul@512 397
paul@340 398
# Track all encoded paths, detecting and avoiding conflicts.
paul@340 399
paul@340 400
all_encoded_paths = {}
paul@340 401
paul@0 402
def encode_path(path):
paul@0 403
paul@0 404
    "Encode 'path' as an output program object, translating special symbols."
paul@0 405
paul@0 406
    if path in reserved_words:
paul@0 407
        return "__%s" % path
paul@0 408
    else:
paul@340 409
        part_encoded = path.replace("#", "__").replace("$", "__")
paul@349 410
paul@349 411
        if "." not in path:
paul@349 412
            return part_encoded
paul@349 413
paul@340 414
        encoded = part_encoded.replace(".", "_")
paul@340 415
paul@340 416
        # Test for a conflict with the encoding of a different path, re-encoding
paul@340 417
        # if necessary.
paul@340 418
paul@340 419
        previous = all_encoded_paths.get(encoded)
paul@340 420
        replacement = "_"
paul@340 421
paul@340 422
        while previous:
paul@340 423
            if path == previous:
paul@340 424
                return encoded
paul@340 425
            replacement += "_"
paul@340 426
            encoded = part_encoded.replace(".", replacement)
paul@340 427
            previous = all_encoded_paths.get(encoded)
paul@340 428
paul@340 429
        # Store any new or re-encoded path.
paul@340 430
paul@340 431
        all_encoded_paths[encoded] = path
paul@340 432
        return encoded
paul@0 433
paul@136 434
def encode_predefined_reference(path):
paul@136 435
paul@136 436
    "Encode a reference to a predefined constant value for 'path'."
paul@136 437
paul@136 438
    return "__predefined_%s" % encode_path(path)
paul@136 439
paul@150 440
def encode_size(kind, path=None):
paul@150 441
paul@150 442
    """
paul@150 443
    Encode a structure size reference for the given 'kind' of structure, with
paul@150 444
    'path' indicating a specific structure name.
paul@150 445
    """
paul@150 446
paul@150 447
    return "__%ssize%s" % (structure_size_prefixes.get(kind, kind), path and "_%s" % encode_path(path) or "")
paul@150 448
paul@0 449
def encode_symbol(symbol_type, path=None):
paul@0 450
paul@0 451
    "Encode a symbol with the given 'symbol_type' and optional 'path'."
paul@0 452
paul@0 453
    return "__%s%s" % (symbol_type, path and "_%s" % encode_path(path) or "")
paul@0 454
paul@150 455
def encode_tablename(kind, path):
paul@150 456
paul@150 457
    """
paul@150 458
    Encode a table reference for the given 'kind' of table structure, indicating
paul@150 459
    a 'path' for the specific object concerned.
paul@150 460
    """
paul@150 461
paul@150 462
    return "__%sTable_%s" % (table_name_prefixes[kind], encode_path(path))
paul@150 463
paul@131 464
def encode_type_attribute(path):
paul@131 465
paul@131 466
    "Encode the special type attribute for 'path'."
paul@131 467
paul@131 468
    return "#%s" % path
paul@131 469
paul@318 470
def decode_type_attribute(s):
paul@318 471
paul@318 472
    "Decode the special type attribute 's'."
paul@318 473
paul@318 474
    return s[1:]
paul@318 475
paul@318 476
def is_type_attribute(s):
paul@318 477
paul@318 478
    "Return whether 's' is a type attribute name."
paul@318 479
paul@318 480
    return s.startswith("#")
paul@318 481
paul@56 482
paul@56 483
paul@150 484
# A mapping from kinds to structure size reference prefixes.
paul@150 485
paul@150 486
structure_size_prefixes = {
paul@150 487
    "<class>" : "c",
paul@150 488
    "<module>" : "m",
paul@150 489
    "<instance>" : "i"
paul@150 490
    }
paul@150 491
paul@150 492
# A mapping from kinds to table name prefixes.
paul@150 493
paul@150 494
table_name_prefixes = {
paul@150 495
    "<class>" : "Class",
paul@150 496
    "<function>" : "Function",
paul@150 497
    "<module>" : "Module",
paul@150 498
    "<instance>" : "Instance"
paul@150 499
    }
paul@150 500
paul@150 501
paul@150 502
paul@0 503
# Output language reserved words.
paul@0 504
paul@0 505
reserved_words = [
paul@0 506
    "break", "char", "const", "continue",
paul@0 507
    "default", "double", "else",
paul@0 508
    "float", "for",
paul@0 509
    "if", "int", "long",
paul@0 510
    "NULL",
paul@0 511
    "return", "struct",
paul@0 512
    "typedef",
paul@0 513
    "void", "while",
paul@0 514
    ]
paul@0 515
paul@0 516
# vim: tabstop=4 expandtab shiftwidth=4