Lichen

encoders.py

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