OILS / opy / compiler2 / misc.py View on Github | oilshell.org

47 lines, 28 significant
1import os
2import struct
3
4# mangle() is used by both symbols and pycodegen.
5
6MANGLE_LEN = 256 # magic constant from compile.c
7
8def mangle(name, klass):
9 if klass is None: # nothing to mangle
10 return name
11 if not name.startswith('__'): # not a private var
12 return name
13
14 if len(name) + 2 >= MANGLE_LEN:
15 return name
16 if name.endswith('__'):
17 return name
18 try:
19 i = 0
20 while klass[i] == '_':
21 i = i + 1
22 except IndexError:
23 return name
24 klass = klass[i:]
25
26 tlen = len(klass) + len(name)
27 if tlen > MANGLE_LEN:
28 klass = klass[:MANGLE_LEN-tlen]
29
30 return "_%s%s" % (klass, name)
31
32
33PY27_MAGIC = b'\x03\xf3\r\n' # removed host dep imp.get_magic()
34
35def getPycHeader(filename):
36 # compile.c uses marshal to write a long directly, with
37 # calling the interface that would also generate a 1-byte code
38 # to indicate the type of the value. simplest way to get the
39 # same effect is to call marshal and then skip the code.
40 mtime = os.path.getmtime(filename)
41 mtime = struct.pack('<i', int(mtime))
42
43 # Update for Python 3:
44 # https://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html
45 # https://gist.github.com/anonymous/35c08092a6eb70cdd723
46
47 return PY27_MAGIC + mtime