xref: /aosp_15_r20/external/fonttools/Lib/fontTools/ttLib/tables/ttProgram.py (revision e1fe3e4ad2793916b15cccdc4a7da52a7e1dd0e9)
1*e1fe3e4aSElliott Hughes"""ttLib.tables.ttProgram.py -- Assembler/disassembler for TrueType bytecode programs."""
2*e1fe3e4aSElliott Hughes
3*e1fe3e4aSElliott Hughesfrom __future__ import annotations
4*e1fe3e4aSElliott Hughes
5*e1fe3e4aSElliott Hughesfrom fontTools.misc.textTools import num2binary, binary2num, readHex, strjoin
6*e1fe3e4aSElliott Hughesimport array
7*e1fe3e4aSElliott Hughesfrom io import StringIO
8*e1fe3e4aSElliott Hughesfrom typing import List
9*e1fe3e4aSElliott Hughesimport re
10*e1fe3e4aSElliott Hughesimport logging
11*e1fe3e4aSElliott Hughes
12*e1fe3e4aSElliott Hughes
13*e1fe3e4aSElliott Hugheslog = logging.getLogger(__name__)
14*e1fe3e4aSElliott Hughes
15*e1fe3e4aSElliott Hughes# fmt: off
16*e1fe3e4aSElliott Hughes
17*e1fe3e4aSElliott Hughes# first, the list of instructions that eat bytes or words from the instruction stream
18*e1fe3e4aSElliott Hughes
19*e1fe3e4aSElliott HughesstreamInstructions = [
20*e1fe3e4aSElliott Hughes#
21*e1fe3e4aSElliott Hughes#   opcode  mnemonic   argBits    descriptive name         pops  pushes         eats from instruction stream          pushes
22*e1fe3e4aSElliott Hughes#
23*e1fe3e4aSElliott Hughes    (0x40,  'NPUSHB',        0,   'PushNBytes',              0, -1),    #                      n, b1, b2,...bn      b1,b2...bn
24*e1fe3e4aSElliott Hughes    (0x41,  'NPUSHW',        0,   'PushNWords',              0, -1),    #                       n, w1, w2,...w      w1,w2...wn
25*e1fe3e4aSElliott Hughes    (0xb0,  'PUSHB',         3,   'PushBytes',               0, -1),    #                          b0, b1,..bn  b0, b1, ...,bn
26*e1fe3e4aSElliott Hughes    (0xb8,  'PUSHW',         3,   'PushWords',               0, -1),    #                           w0,w1,..wn   w0 ,w1, ...wn
27*e1fe3e4aSElliott Hughes]
28*e1fe3e4aSElliott Hughes
29*e1fe3e4aSElliott Hughes
30*e1fe3e4aSElliott Hughes# next,    the list of "normal" instructions
31*e1fe3e4aSElliott Hughes
32*e1fe3e4aSElliott Hughesinstructions = [
33*e1fe3e4aSElliott Hughes#
34*e1fe3e4aSElliott Hughes#   opcode  mnemonic   argBits     descriptive name        pops  pushes         eats from instruction stream          pushes
35*e1fe3e4aSElliott Hughes#
36*e1fe3e4aSElliott Hughes    (0x7f,  'AA',            0,    'AdjustAngle',            1,  0),    #                                    p               -
37*e1fe3e4aSElliott Hughes    (0x64,  'ABS',           0,    'Absolute',               1,  1),    #                                    n             |n|
38*e1fe3e4aSElliott Hughes    (0x60,  'ADD',           0,    'Add',                    2,  1),    #                               n2, n1       (n1 + n2)
39*e1fe3e4aSElliott Hughes    (0x27,  'ALIGNPTS',      0,    'AlignPts',               2,  0),    #                               p2, p1               -
40*e1fe3e4aSElliott Hughes    (0x3c,  'ALIGNRP',       0,    'AlignRelativePt',       -1,  0),    #             p1, p2, ... , ploopvalue               -
41*e1fe3e4aSElliott Hughes    (0x5a,  'AND',           0,    'LogicalAnd',             2,  1),    #                               e2, e1               b
42*e1fe3e4aSElliott Hughes    (0x2b,  'CALL',          0,    'CallFunction',           1,  0),    #                                    f               -
43*e1fe3e4aSElliott Hughes    (0x67,  'CEILING',       0,    'Ceiling',                1,  1),    #                                    n         ceil(n)
44*e1fe3e4aSElliott Hughes    (0x25,  'CINDEX',        0,    'CopyXToTopStack',        1,  1),    #                                    k              ek
45*e1fe3e4aSElliott Hughes    (0x22,  'CLEAR',         0,    'ClearStack',            -1,  0),    #               all items on the stack               -
46*e1fe3e4aSElliott Hughes    (0x4f,  'DEBUG',         0,    'DebugCall',              1,  0),    #                                    n               -
47*e1fe3e4aSElliott Hughes    (0x73,  'DELTAC1',       0,    'DeltaExceptionC1',      -1,  0),    #    argn, cn, argn-1,cn-1, , arg1, c1               -
48*e1fe3e4aSElliott Hughes    (0x74,  'DELTAC2',       0,    'DeltaExceptionC2',      -1,  0),    #    argn, cn, argn-1,cn-1, , arg1, c1               -
49*e1fe3e4aSElliott Hughes    (0x75,  'DELTAC3',       0,    'DeltaExceptionC3',      -1,  0),    #    argn, cn, argn-1,cn-1, , arg1, c1               -
50*e1fe3e4aSElliott Hughes    (0x5d,  'DELTAP1',       0,    'DeltaExceptionP1',      -1,  0),    #   argn, pn, argn-1, pn-1, , arg1, p1               -
51*e1fe3e4aSElliott Hughes    (0x71,  'DELTAP2',       0,    'DeltaExceptionP2',      -1,  0),    #   argn, pn, argn-1, pn-1, , arg1, p1               -
52*e1fe3e4aSElliott Hughes    (0x72,  'DELTAP3',       0,    'DeltaExceptionP3',      -1,  0),    #   argn, pn, argn-1, pn-1, , arg1, p1               -
53*e1fe3e4aSElliott Hughes    (0x24,  'DEPTH',         0,    'GetDepthStack',          0,  1),    #                                    -               n
54*e1fe3e4aSElliott Hughes    (0x62,  'DIV',           0,    'Divide',                 2,  1),    #                               n2, n1   (n1 * 64)/ n2
55*e1fe3e4aSElliott Hughes    (0x20,  'DUP',           0,    'DuplicateTopStack',      1,  2),    #                                    e            e, e
56*e1fe3e4aSElliott Hughes    (0x59,  'EIF',           0,    'EndIf',                  0,  0),    #                                    -               -
57*e1fe3e4aSElliott Hughes    (0x1b,  'ELSE',          0,    'Else',                   0,  0),    #                                    -               -
58*e1fe3e4aSElliott Hughes    (0x2d,  'ENDF',          0,    'EndFunctionDefinition',  0,  0),    #                                    -               -
59*e1fe3e4aSElliott Hughes    (0x54,  'EQ',            0,    'Equal',                  2,  1),    #                               e2, e1               b
60*e1fe3e4aSElliott Hughes    (0x57,  'EVEN',          0,    'Even',                   1,  1),    #                                    e               b
61*e1fe3e4aSElliott Hughes    (0x2c,  'FDEF',          0,    'FunctionDefinition',     1,  0),    #                                    f               -
62*e1fe3e4aSElliott Hughes    (0x4e,  'FLIPOFF',       0,    'SetAutoFlipOff',         0,  0),    #                                    -               -
63*e1fe3e4aSElliott Hughes    (0x4d,  'FLIPON',        0,    'SetAutoFlipOn',          0,  0),    #                                    -               -
64*e1fe3e4aSElliott Hughes    (0x80,  'FLIPPT',        0,    'FlipPoint',             -1,  0),    #              p1, p2, ..., ploopvalue               -
65*e1fe3e4aSElliott Hughes    (0x82,  'FLIPRGOFF',     0,    'FlipRangeOff',           2,  0),    #                                 h, l               -
66*e1fe3e4aSElliott Hughes    (0x81,  'FLIPRGON',      0,    'FlipRangeOn',            2,  0),    #                                 h, l               -
67*e1fe3e4aSElliott Hughes    (0x66,  'FLOOR',         0,    'Floor',                  1,  1),    #                                    n        floor(n)
68*e1fe3e4aSElliott Hughes    (0x46,  'GC',            1,    'GetCoordOnPVector',      1,  1),    #                                    p               c
69*e1fe3e4aSElliott Hughes    (0x88,  'GETINFO',       0,    'GetInfo',                1,  1),    #                             selector          result
70*e1fe3e4aSElliott Hughes    (0x91,  'GETVARIATION',  0,    'GetVariation',           0, -1),    #                                    -        a1,..,an
71*e1fe3e4aSElliott Hughes    (0x0d,  'GFV',           0,    'GetFVector',             0,  2),    #                                    -          px, py
72*e1fe3e4aSElliott Hughes    (0x0c,  'GPV',           0,    'GetPVector',             0,  2),    #                                    -          px, py
73*e1fe3e4aSElliott Hughes    (0x52,  'GT',            0,    'GreaterThan',            2,  1),    #                               e2, e1               b
74*e1fe3e4aSElliott Hughes    (0x53,  'GTEQ',          0,    'GreaterThanOrEqual',     2,  1),    #                               e2, e1               b
75*e1fe3e4aSElliott Hughes    (0x89,  'IDEF',          0,    'InstructionDefinition',  1,  0),    #                                    f               -
76*e1fe3e4aSElliott Hughes    (0x58,  'IF',            0,    'If',                     1,  0),    #                                    e               -
77*e1fe3e4aSElliott Hughes    (0x8e,  'INSTCTRL',      0,    'SetInstrExecControl',    2,  0),    #                                 s, v               -
78*e1fe3e4aSElliott Hughes    (0x39,  'IP',            0,    'InterpolatePts',        -1,  0),    #             p1, p2, ... , ploopvalue               -
79*e1fe3e4aSElliott Hughes    (0x0f,  'ISECT',         0,    'MovePtToIntersect',      5,  0),    #                    a1, a0, b1, b0, p               -
80*e1fe3e4aSElliott Hughes    (0x30,  'IUP',           1,    'InterpolateUntPts',      0,  0),    #                                    -               -
81*e1fe3e4aSElliott Hughes    (0x1c,  'JMPR',          0,    'Jump',                   1,  0),    #                               offset               -
82*e1fe3e4aSElliott Hughes    (0x79,  'JROF',          0,    'JumpRelativeOnFalse',    2,  0),    #                            e, offset               -
83*e1fe3e4aSElliott Hughes    (0x78,  'JROT',          0,    'JumpRelativeOnTrue',     2,  0),    #                            e, offset               -
84*e1fe3e4aSElliott Hughes    (0x2a,  'LOOPCALL',      0,    'LoopAndCallFunction',    2,  0),    #                             f, count               -
85*e1fe3e4aSElliott Hughes    (0x50,  'LT',            0,    'LessThan',               2,  1),    #                               e2, e1               b
86*e1fe3e4aSElliott Hughes    (0x51,  'LTEQ',          0,    'LessThenOrEqual',        2,  1),    #                               e2, e1               b
87*e1fe3e4aSElliott Hughes    (0x8b,  'MAX',           0,    'Maximum',                2,  1),    #                               e2, e1     max(e1, e2)
88*e1fe3e4aSElliott Hughes    (0x49,  'MD',            1,    'MeasureDistance',        2,  1),    #                                p2,p1               d
89*e1fe3e4aSElliott Hughes    (0x2e,  'MDAP',          1,    'MoveDirectAbsPt',        1,  0),    #                                    p               -
90*e1fe3e4aSElliott Hughes    (0xc0,  'MDRP',          5,    'MoveDirectRelPt',        1,  0),    #                                    p               -
91*e1fe3e4aSElliott Hughes    (0x3e,  'MIAP',          1,    'MoveIndirectAbsPt',      2,  0),    #                                 n, p               -
92*e1fe3e4aSElliott Hughes    (0x8c,  'MIN',           0,    'Minimum',                2,  1),    #                               e2, e1     min(e1, e2)
93*e1fe3e4aSElliott Hughes    (0x26,  'MINDEX',        0,    'MoveXToTopStack',        1,  1),    #                                    k              ek
94*e1fe3e4aSElliott Hughes    (0xe0,  'MIRP',          5,    'MoveIndirectRelPt',      2,  0),    #                                 n, p               -
95*e1fe3e4aSElliott Hughes    (0x4b,  'MPPEM',         0,    'MeasurePixelPerEm',      0,  1),    #                                    -            ppem
96*e1fe3e4aSElliott Hughes    (0x4c,  'MPS',           0,    'MeasurePointSize',       0,  1),    #                                    -       pointSize
97*e1fe3e4aSElliott Hughes    (0x3a,  'MSIRP',         1,    'MoveStackIndirRelPt',    2,  0),    #                                 d, p               -
98*e1fe3e4aSElliott Hughes    (0x63,  'MUL',           0,    'Multiply',               2,  1),    #                               n2, n1    (n1 * n2)/64
99*e1fe3e4aSElliott Hughes    (0x65,  'NEG',           0,    'Negate',                 1,  1),    #                                    n              -n
100*e1fe3e4aSElliott Hughes    (0x55,  'NEQ',           0,    'NotEqual',               2,  1),    #                               e2, e1               b
101*e1fe3e4aSElliott Hughes    (0x5c,  'NOT',           0,    'LogicalNot',             1,  1),    #                                    e       ( not e )
102*e1fe3e4aSElliott Hughes    (0x6c,  'NROUND',        2,    'NoRound',                1,  1),    #                                   n1              n2
103*e1fe3e4aSElliott Hughes    (0x56,  'ODD',           0,    'Odd',                    1,  1),    #                                    e               b
104*e1fe3e4aSElliott Hughes    (0x5b,  'OR',            0,    'LogicalOr',              2,  1),    #                               e2, e1               b
105*e1fe3e4aSElliott Hughes    (0x21,  'POP',           0,    'PopTopStack',            1,  0),    #                                    e               -
106*e1fe3e4aSElliott Hughes    (0x45,  'RCVT',          0,    'ReadCVT',                1,  1),    #                             location           value
107*e1fe3e4aSElliott Hughes    (0x7d,  'RDTG',          0,    'RoundDownToGrid',        0,  0),    #                                    -               -
108*e1fe3e4aSElliott Hughes    (0x7a,  'ROFF',          0,    'RoundOff',               0,  0),    #                                    -               -
109*e1fe3e4aSElliott Hughes    (0x8a,  'ROLL',          0,    'RollTopThreeStack',      3,  3),    #                                a,b,c           b,a,c
110*e1fe3e4aSElliott Hughes    (0x68,  'ROUND',         2,    'Round',                  1,  1),    #                                   n1              n2
111*e1fe3e4aSElliott Hughes    (0x43,  'RS',            0,    'ReadStore',              1,  1),    #                                    n               v
112*e1fe3e4aSElliott Hughes    (0x3d,  'RTDG',          0,    'RoundToDoubleGrid',      0,  0),    #                                    -               -
113*e1fe3e4aSElliott Hughes    (0x18,  'RTG',           0,    'RoundToGrid',            0,  0),    #                                    -               -
114*e1fe3e4aSElliott Hughes    (0x19,  'RTHG',          0,    'RoundToHalfGrid',        0,  0),    #                                    -               -
115*e1fe3e4aSElliott Hughes    (0x7c,  'RUTG',          0,    'RoundUpToGrid',          0,  0),    #                                    -               -
116*e1fe3e4aSElliott Hughes    (0x77,  'S45ROUND',      0,    'SuperRound45Degrees',    1,  0),    #                                    n               -
117*e1fe3e4aSElliott Hughes    (0x7e,  'SANGW',         0,    'SetAngleWeight',         1,  0),    #                               weight               -
118*e1fe3e4aSElliott Hughes    (0x85,  'SCANCTRL',      0,    'ScanConversionControl',  1,  0),    #                                    n               -
119*e1fe3e4aSElliott Hughes    (0x8d,  'SCANTYPE',      0,    'ScanType',               1,  0),    #                                    n               -
120*e1fe3e4aSElliott Hughes    (0x48,  'SCFS',          0,    'SetCoordFromStackFP',    2,  0),    #                                 c, p               -
121*e1fe3e4aSElliott Hughes    (0x1d,  'SCVTCI',        0,    'SetCVTCutIn',            1,  0),    #                                    n               -
122*e1fe3e4aSElliott Hughes    (0x5e,  'SDB',           0,    'SetDeltaBaseInGState',   1,  0),    #                                    n               -
123*e1fe3e4aSElliott Hughes    (0x86,  'SDPVTL',        1,    'SetDualPVectorToLine',   2,  0),    #                               p2, p1               -
124*e1fe3e4aSElliott Hughes    (0x5f,  'SDS',           0,    'SetDeltaShiftInGState',  1,  0),    #                                    n               -
125*e1fe3e4aSElliott Hughes    (0x0b,  'SFVFS',         0,    'SetFVectorFromStack',    2,  0),    #                                 y, x               -
126*e1fe3e4aSElliott Hughes    (0x04,  'SFVTCA',        1,    'SetFVectorToAxis',       0,  0),    #                                    -               -
127*e1fe3e4aSElliott Hughes    (0x08,  'SFVTL',         1,    'SetFVectorToLine',       2,  0),    #                               p2, p1               -
128*e1fe3e4aSElliott Hughes    (0x0e,  'SFVTPV',        0,    'SetFVectorToPVector',    0,  0),    #                                    -               -
129*e1fe3e4aSElliott Hughes    (0x34,  'SHC',           1,    'ShiftContourByLastPt',   1,  0),    #                                    c               -
130*e1fe3e4aSElliott Hughes    (0x32,  'SHP',           1,    'ShiftPointByLastPoint', -1,  0),    #              p1, p2, ..., ploopvalue               -
131*e1fe3e4aSElliott Hughes    (0x38,  'SHPIX',         0,    'ShiftZoneByPixel',      -1,  0),    #           d, p1, p2, ..., ploopvalue               -
132*e1fe3e4aSElliott Hughes    (0x36,  'SHZ',           1,    'ShiftZoneByLastPoint',   1,  0),    #                                    e               -
133*e1fe3e4aSElliott Hughes    (0x17,  'SLOOP',         0,    'SetLoopVariable',        1,  0),    #                                    n               -
134*e1fe3e4aSElliott Hughes    (0x1a,  'SMD',           0,    'SetMinimumDistance',     1,  0),    #                             distance               -
135*e1fe3e4aSElliott Hughes    (0x0a,  'SPVFS',         0,    'SetPVectorFromStack',    2,  0),    #                                 y, x               -
136*e1fe3e4aSElliott Hughes    (0x02,  'SPVTCA',        1,    'SetPVectorToAxis',       0,  0),    #                                    -               -
137*e1fe3e4aSElliott Hughes    (0x06,  'SPVTL',         1,    'SetPVectorToLine',       2,  0),    #                               p2, p1               -
138*e1fe3e4aSElliott Hughes    (0x76,  'SROUND',        0,    'SuperRound',             1,  0),    #                                    n               -
139*e1fe3e4aSElliott Hughes    (0x10,  'SRP0',          0,    'SetRefPoint0',           1,  0),    #                                    p               -
140*e1fe3e4aSElliott Hughes    (0x11,  'SRP1',          0,    'SetRefPoint1',           1,  0),    #                                    p               -
141*e1fe3e4aSElliott Hughes    (0x12,  'SRP2',          0,    'SetRefPoint2',           1,  0),    #                                    p               -
142*e1fe3e4aSElliott Hughes    (0x1f,  'SSW',           0,    'SetSingleWidth',         1,  0),    #                                    n               -
143*e1fe3e4aSElliott Hughes    (0x1e,  'SSWCI',         0,    'SetSingleWidthCutIn',    1,  0),    #                                    n               -
144*e1fe3e4aSElliott Hughes    (0x61,  'SUB',           0,    'Subtract',               2,  1),    #                               n2, n1       (n1 - n2)
145*e1fe3e4aSElliott Hughes    (0x00,  'SVTCA',         1,    'SetFPVectorToAxis',      0,  0),    #                                    -               -
146*e1fe3e4aSElliott Hughes    (0x23,  'SWAP',          0,    'SwapTopStack',           2,  2),    #                               e2, e1          e1, e2
147*e1fe3e4aSElliott Hughes    (0x13,  'SZP0',          0,    'SetZonePointer0',        1,  0),    #                                    n               -
148*e1fe3e4aSElliott Hughes    (0x14,  'SZP1',          0,    'SetZonePointer1',        1,  0),    #                                    n               -
149*e1fe3e4aSElliott Hughes    (0x15,  'SZP2',          0,    'SetZonePointer2',        1,  0),    #                                    n               -
150*e1fe3e4aSElliott Hughes    (0x16,  'SZPS',          0,    'SetZonePointerS',        1,  0),    #                                    n               -
151*e1fe3e4aSElliott Hughes    (0x29,  'UTP',           0,    'UnTouchPt',              1,  0),    #                                    p               -
152*e1fe3e4aSElliott Hughes    (0x70,  'WCVTF',         0,    'WriteCVTInFUnits',       2,  0),    #                                 n, l               -
153*e1fe3e4aSElliott Hughes    (0x44,  'WCVTP',         0,    'WriteCVTInPixels',       2,  0),    #                                 v, l               -
154*e1fe3e4aSElliott Hughes    (0x42,  'WS',            0,    'WriteStore',             2,  0),    #                                 v, l               -
155*e1fe3e4aSElliott Hughes]
156*e1fe3e4aSElliott Hughes
157*e1fe3e4aSElliott Hughes# fmt: on
158*e1fe3e4aSElliott Hughes
159*e1fe3e4aSElliott Hughes
160*e1fe3e4aSElliott Hughesdef bitRepr(value, bits):
161*e1fe3e4aSElliott Hughes    s = ""
162*e1fe3e4aSElliott Hughes    for i in range(bits):
163*e1fe3e4aSElliott Hughes        s = "01"[value & 0x1] + s
164*e1fe3e4aSElliott Hughes        value = value >> 1
165*e1fe3e4aSElliott Hughes    return s
166*e1fe3e4aSElliott Hughes
167*e1fe3e4aSElliott Hughes
168*e1fe3e4aSElliott Hughes_mnemonicPat = re.compile(r"[A-Z][A-Z0-9]*$")
169*e1fe3e4aSElliott Hughes
170*e1fe3e4aSElliott Hughes
171*e1fe3e4aSElliott Hughesdef _makeDict(instructionList):
172*e1fe3e4aSElliott Hughes    opcodeDict = {}
173*e1fe3e4aSElliott Hughes    mnemonicDict = {}
174*e1fe3e4aSElliott Hughes    for op, mnemonic, argBits, name, pops, pushes in instructionList:
175*e1fe3e4aSElliott Hughes        assert _mnemonicPat.match(mnemonic)
176*e1fe3e4aSElliott Hughes        mnemonicDict[mnemonic] = op, argBits, name
177*e1fe3e4aSElliott Hughes        if argBits:
178*e1fe3e4aSElliott Hughes            argoffset = op
179*e1fe3e4aSElliott Hughes            for i in range(1 << argBits):
180*e1fe3e4aSElliott Hughes                opcodeDict[op + i] = mnemonic, argBits, argoffset, name
181*e1fe3e4aSElliott Hughes        else:
182*e1fe3e4aSElliott Hughes            opcodeDict[op] = mnemonic, 0, 0, name
183*e1fe3e4aSElliott Hughes    return opcodeDict, mnemonicDict
184*e1fe3e4aSElliott Hughes
185*e1fe3e4aSElliott Hughes
186*e1fe3e4aSElliott HughesstreamOpcodeDict, streamMnemonicDict = _makeDict(streamInstructions)
187*e1fe3e4aSElliott HughesopcodeDict, mnemonicDict = _makeDict(instructions)
188*e1fe3e4aSElliott Hughes
189*e1fe3e4aSElliott Hughes
190*e1fe3e4aSElliott Hughesclass tt_instructions_error(Exception):
191*e1fe3e4aSElliott Hughes    def __init__(self, error):
192*e1fe3e4aSElliott Hughes        self.error = error
193*e1fe3e4aSElliott Hughes
194*e1fe3e4aSElliott Hughes    def __str__(self):
195*e1fe3e4aSElliott Hughes        return "TT instructions error: %s" % repr(self.error)
196*e1fe3e4aSElliott Hughes
197*e1fe3e4aSElliott Hughes
198*e1fe3e4aSElliott Hughes_comment = r"/\*.*?\*/"
199*e1fe3e4aSElliott Hughes_instruction = r"([A-Z][A-Z0-9]*)\s*\[(.*?)\]"
200*e1fe3e4aSElliott Hughes_number = r"-?[0-9]+"
201*e1fe3e4aSElliott Hughes_token = "(%s)|(%s)|(%s)" % (_instruction, _number, _comment)
202*e1fe3e4aSElliott Hughes
203*e1fe3e4aSElliott Hughes_tokenRE = re.compile(_token)
204*e1fe3e4aSElliott Hughes_whiteRE = re.compile(r"\s*")
205*e1fe3e4aSElliott Hughes
206*e1fe3e4aSElliott Hughes_pushCountPat = re.compile(r"[A-Z][A-Z0-9]*\s*\[.*?\]\s*/\* ([0-9]+).*?\*/")
207*e1fe3e4aSElliott Hughes
208*e1fe3e4aSElliott Hughes_indentRE = re.compile(r"^FDEF|IF|ELSE\[ \]\t.+")
209*e1fe3e4aSElliott Hughes_unindentRE = re.compile(r"^ELSE|ENDF|EIF\[ \]\t.+")
210*e1fe3e4aSElliott Hughes
211*e1fe3e4aSElliott Hughes
212*e1fe3e4aSElliott Hughesdef _skipWhite(data, pos):
213*e1fe3e4aSElliott Hughes    m = _whiteRE.match(data, pos)
214*e1fe3e4aSElliott Hughes    newPos = m.regs[0][1]
215*e1fe3e4aSElliott Hughes    assert newPos >= pos
216*e1fe3e4aSElliott Hughes    return newPos
217*e1fe3e4aSElliott Hughes
218*e1fe3e4aSElliott Hughes
219*e1fe3e4aSElliott Hughesclass Program(object):
220*e1fe3e4aSElliott Hughes    def __init__(self) -> None:
221*e1fe3e4aSElliott Hughes        pass
222*e1fe3e4aSElliott Hughes
223*e1fe3e4aSElliott Hughes    def fromBytecode(self, bytecode: bytes) -> None:
224*e1fe3e4aSElliott Hughes        self.bytecode = array.array("B", bytecode)
225*e1fe3e4aSElliott Hughes        if hasattr(self, "assembly"):
226*e1fe3e4aSElliott Hughes            del self.assembly
227*e1fe3e4aSElliott Hughes
228*e1fe3e4aSElliott Hughes    def fromAssembly(self, assembly: List[str] | str) -> None:
229*e1fe3e4aSElliott Hughes        if isinstance(assembly, list):
230*e1fe3e4aSElliott Hughes            self.assembly = assembly
231*e1fe3e4aSElliott Hughes        elif isinstance(assembly, str):
232*e1fe3e4aSElliott Hughes            self.assembly = assembly.splitlines()
233*e1fe3e4aSElliott Hughes        else:
234*e1fe3e4aSElliott Hughes            raise TypeError(f"expected str or List[str], got {type(assembly).__name__}")
235*e1fe3e4aSElliott Hughes        if hasattr(self, "bytecode"):
236*e1fe3e4aSElliott Hughes            del self.bytecode
237*e1fe3e4aSElliott Hughes
238*e1fe3e4aSElliott Hughes    def getBytecode(self) -> bytes:
239*e1fe3e4aSElliott Hughes        if not hasattr(self, "bytecode"):
240*e1fe3e4aSElliott Hughes            self._assemble()
241*e1fe3e4aSElliott Hughes        return self.bytecode.tobytes()
242*e1fe3e4aSElliott Hughes
243*e1fe3e4aSElliott Hughes    def getAssembly(self, preserve=True) -> List[str]:
244*e1fe3e4aSElliott Hughes        if not hasattr(self, "assembly"):
245*e1fe3e4aSElliott Hughes            self._disassemble(preserve=preserve)
246*e1fe3e4aSElliott Hughes        return self.assembly
247*e1fe3e4aSElliott Hughes
248*e1fe3e4aSElliott Hughes    def toXML(self, writer, ttFont) -> None:
249*e1fe3e4aSElliott Hughes        if (
250*e1fe3e4aSElliott Hughes            not hasattr(ttFont, "disassembleInstructions")
251*e1fe3e4aSElliott Hughes            or ttFont.disassembleInstructions
252*e1fe3e4aSElliott Hughes        ):
253*e1fe3e4aSElliott Hughes            try:
254*e1fe3e4aSElliott Hughes                assembly = self.getAssembly()
255*e1fe3e4aSElliott Hughes            except:
256*e1fe3e4aSElliott Hughes                import traceback
257*e1fe3e4aSElliott Hughes
258*e1fe3e4aSElliott Hughes                tmp = StringIO()
259*e1fe3e4aSElliott Hughes                traceback.print_exc(file=tmp)
260*e1fe3e4aSElliott Hughes                msg = "An exception occurred during the decompilation of glyph program:\n\n"
261*e1fe3e4aSElliott Hughes                msg += tmp.getvalue()
262*e1fe3e4aSElliott Hughes                log.error(msg)
263*e1fe3e4aSElliott Hughes                writer.begintag("bytecode")
264*e1fe3e4aSElliott Hughes                writer.newline()
265*e1fe3e4aSElliott Hughes                writer.comment(msg.strip())
266*e1fe3e4aSElliott Hughes                writer.newline()
267*e1fe3e4aSElliott Hughes                writer.dumphex(self.getBytecode())
268*e1fe3e4aSElliott Hughes                writer.endtag("bytecode")
269*e1fe3e4aSElliott Hughes                writer.newline()
270*e1fe3e4aSElliott Hughes            else:
271*e1fe3e4aSElliott Hughes                if not assembly:
272*e1fe3e4aSElliott Hughes                    return
273*e1fe3e4aSElliott Hughes                writer.begintag("assembly")
274*e1fe3e4aSElliott Hughes                writer.newline()
275*e1fe3e4aSElliott Hughes                i = 0
276*e1fe3e4aSElliott Hughes                indent = 0
277*e1fe3e4aSElliott Hughes                nInstr = len(assembly)
278*e1fe3e4aSElliott Hughes                while i < nInstr:
279*e1fe3e4aSElliott Hughes                    instr = assembly[i]
280*e1fe3e4aSElliott Hughes                    if _unindentRE.match(instr):
281*e1fe3e4aSElliott Hughes                        indent -= 1
282*e1fe3e4aSElliott Hughes                    writer.write(writer.indentwhite * indent)
283*e1fe3e4aSElliott Hughes                    writer.write(instr)
284*e1fe3e4aSElliott Hughes                    writer.newline()
285*e1fe3e4aSElliott Hughes                    m = _pushCountPat.match(instr)
286*e1fe3e4aSElliott Hughes                    i = i + 1
287*e1fe3e4aSElliott Hughes                    if m:
288*e1fe3e4aSElliott Hughes                        nValues = int(m.group(1))
289*e1fe3e4aSElliott Hughes                        line: List[str] = []
290*e1fe3e4aSElliott Hughes                        j = 0
291*e1fe3e4aSElliott Hughes                        for j in range(nValues):
292*e1fe3e4aSElliott Hughes                            if j and not (j % 25):
293*e1fe3e4aSElliott Hughes                                writer.write(writer.indentwhite * indent)
294*e1fe3e4aSElliott Hughes                                writer.write(" ".join(line))
295*e1fe3e4aSElliott Hughes                                writer.newline()
296*e1fe3e4aSElliott Hughes                                line = []
297*e1fe3e4aSElliott Hughes                            line.append(assembly[i + j])
298*e1fe3e4aSElliott Hughes                        writer.write(writer.indentwhite * indent)
299*e1fe3e4aSElliott Hughes                        writer.write(" ".join(line))
300*e1fe3e4aSElliott Hughes                        writer.newline()
301*e1fe3e4aSElliott Hughes                        i = i + j + 1
302*e1fe3e4aSElliott Hughes                    if _indentRE.match(instr):
303*e1fe3e4aSElliott Hughes                        indent += 1
304*e1fe3e4aSElliott Hughes                writer.endtag("assembly")
305*e1fe3e4aSElliott Hughes                writer.newline()
306*e1fe3e4aSElliott Hughes        else:
307*e1fe3e4aSElliott Hughes            bytecode = self.getBytecode()
308*e1fe3e4aSElliott Hughes            if not bytecode:
309*e1fe3e4aSElliott Hughes                return
310*e1fe3e4aSElliott Hughes            writer.begintag("bytecode")
311*e1fe3e4aSElliott Hughes            writer.newline()
312*e1fe3e4aSElliott Hughes            writer.dumphex(bytecode)
313*e1fe3e4aSElliott Hughes            writer.endtag("bytecode")
314*e1fe3e4aSElliott Hughes            writer.newline()
315*e1fe3e4aSElliott Hughes
316*e1fe3e4aSElliott Hughes    def fromXML(self, name, attrs, content, ttFont) -> None:
317*e1fe3e4aSElliott Hughes        if name == "assembly":
318*e1fe3e4aSElliott Hughes            self.fromAssembly(strjoin(content))
319*e1fe3e4aSElliott Hughes            self._assemble()
320*e1fe3e4aSElliott Hughes            del self.assembly
321*e1fe3e4aSElliott Hughes        else:
322*e1fe3e4aSElliott Hughes            assert name == "bytecode"
323*e1fe3e4aSElliott Hughes            self.fromBytecode(readHex(content))
324*e1fe3e4aSElliott Hughes
325*e1fe3e4aSElliott Hughes    def _assemble(self) -> None:
326*e1fe3e4aSElliott Hughes        assembly = " ".join(getattr(self, "assembly", []))
327*e1fe3e4aSElliott Hughes        bytecode: List[int] = []
328*e1fe3e4aSElliott Hughes        push = bytecode.append
329*e1fe3e4aSElliott Hughes        lenAssembly = len(assembly)
330*e1fe3e4aSElliott Hughes        pos = _skipWhite(assembly, 0)
331*e1fe3e4aSElliott Hughes        while pos < lenAssembly:
332*e1fe3e4aSElliott Hughes            m = _tokenRE.match(assembly, pos)
333*e1fe3e4aSElliott Hughes            if m is None:
334*e1fe3e4aSElliott Hughes                raise tt_instructions_error(
335*e1fe3e4aSElliott Hughes                    "Syntax error in TT program (%s)" % assembly[pos - 5 : pos + 15]
336*e1fe3e4aSElliott Hughes                )
337*e1fe3e4aSElliott Hughes            dummy, mnemonic, arg, number, comment = m.groups()
338*e1fe3e4aSElliott Hughes            pos = m.regs[0][1]
339*e1fe3e4aSElliott Hughes            if comment:
340*e1fe3e4aSElliott Hughes                pos = _skipWhite(assembly, pos)
341*e1fe3e4aSElliott Hughes                continue
342*e1fe3e4aSElliott Hughes
343*e1fe3e4aSElliott Hughes            arg = arg.strip()
344*e1fe3e4aSElliott Hughes            if mnemonic.startswith("INSTR"):
345*e1fe3e4aSElliott Hughes                # Unknown instruction
346*e1fe3e4aSElliott Hughes                op = int(mnemonic[5:])
347*e1fe3e4aSElliott Hughes                push(op)
348*e1fe3e4aSElliott Hughes            elif mnemonic not in ("PUSH", "NPUSHB", "NPUSHW", "PUSHB", "PUSHW"):
349*e1fe3e4aSElliott Hughes                op, argBits, name = mnemonicDict[mnemonic]
350*e1fe3e4aSElliott Hughes                if len(arg) != argBits:
351*e1fe3e4aSElliott Hughes                    raise tt_instructions_error(
352*e1fe3e4aSElliott Hughes                        "Incorrect number of argument bits (%s[%s])" % (mnemonic, arg)
353*e1fe3e4aSElliott Hughes                    )
354*e1fe3e4aSElliott Hughes                if arg:
355*e1fe3e4aSElliott Hughes                    arg = binary2num(arg)
356*e1fe3e4aSElliott Hughes                    push(op + arg)
357*e1fe3e4aSElliott Hughes                else:
358*e1fe3e4aSElliott Hughes                    push(op)
359*e1fe3e4aSElliott Hughes            else:
360*e1fe3e4aSElliott Hughes                args = []
361*e1fe3e4aSElliott Hughes                pos = _skipWhite(assembly, pos)
362*e1fe3e4aSElliott Hughes                while pos < lenAssembly:
363*e1fe3e4aSElliott Hughes                    m = _tokenRE.match(assembly, pos)
364*e1fe3e4aSElliott Hughes                    if m is None:
365*e1fe3e4aSElliott Hughes                        raise tt_instructions_error(
366*e1fe3e4aSElliott Hughes                            "Syntax error in TT program (%s)" % assembly[pos : pos + 15]
367*e1fe3e4aSElliott Hughes                        )
368*e1fe3e4aSElliott Hughes                    dummy, _mnemonic, arg, number, comment = m.groups()
369*e1fe3e4aSElliott Hughes                    if number is None and comment is None:
370*e1fe3e4aSElliott Hughes                        break
371*e1fe3e4aSElliott Hughes                    pos = m.regs[0][1]
372*e1fe3e4aSElliott Hughes                    pos = _skipWhite(assembly, pos)
373*e1fe3e4aSElliott Hughes                    if comment is not None:
374*e1fe3e4aSElliott Hughes                        continue
375*e1fe3e4aSElliott Hughes                    args.append(int(number))
376*e1fe3e4aSElliott Hughes                nArgs = len(args)
377*e1fe3e4aSElliott Hughes                if mnemonic == "PUSH":
378*e1fe3e4aSElliott Hughes                    # Automatically choose the most compact representation
379*e1fe3e4aSElliott Hughes                    nWords = 0
380*e1fe3e4aSElliott Hughes                    while nArgs:
381*e1fe3e4aSElliott Hughes                        while (
382*e1fe3e4aSElliott Hughes                            nWords < nArgs
383*e1fe3e4aSElliott Hughes                            and nWords < 255
384*e1fe3e4aSElliott Hughes                            and not (0 <= args[nWords] <= 255)
385*e1fe3e4aSElliott Hughes                        ):
386*e1fe3e4aSElliott Hughes                            nWords += 1
387*e1fe3e4aSElliott Hughes                        nBytes = 0
388*e1fe3e4aSElliott Hughes                        while (
389*e1fe3e4aSElliott Hughes                            nWords + nBytes < nArgs
390*e1fe3e4aSElliott Hughes                            and nBytes < 255
391*e1fe3e4aSElliott Hughes                            and 0 <= args[nWords + nBytes] <= 255
392*e1fe3e4aSElliott Hughes                        ):
393*e1fe3e4aSElliott Hughes                            nBytes += 1
394*e1fe3e4aSElliott Hughes                        if (
395*e1fe3e4aSElliott Hughes                            nBytes < 2
396*e1fe3e4aSElliott Hughes                            and nWords + nBytes < 255
397*e1fe3e4aSElliott Hughes                            and nWords + nBytes != nArgs
398*e1fe3e4aSElliott Hughes                        ):
399*e1fe3e4aSElliott Hughes                            # Will write bytes as words
400*e1fe3e4aSElliott Hughes                            nWords += nBytes
401*e1fe3e4aSElliott Hughes                            continue
402*e1fe3e4aSElliott Hughes
403*e1fe3e4aSElliott Hughes                        # Write words
404*e1fe3e4aSElliott Hughes                        if nWords:
405*e1fe3e4aSElliott Hughes                            if nWords <= 8:
406*e1fe3e4aSElliott Hughes                                op, argBits, name = streamMnemonicDict["PUSHW"]
407*e1fe3e4aSElliott Hughes                                op = op + nWords - 1
408*e1fe3e4aSElliott Hughes                                push(op)
409*e1fe3e4aSElliott Hughes                            else:
410*e1fe3e4aSElliott Hughes                                op, argBits, name = streamMnemonicDict["NPUSHW"]
411*e1fe3e4aSElliott Hughes                                push(op)
412*e1fe3e4aSElliott Hughes                                push(nWords)
413*e1fe3e4aSElliott Hughes                            for value in args[:nWords]:
414*e1fe3e4aSElliott Hughes                                assert -32768 <= value < 32768, (
415*e1fe3e4aSElliott Hughes                                    "PUSH value out of range %d" % value
416*e1fe3e4aSElliott Hughes                                )
417*e1fe3e4aSElliott Hughes                                push((value >> 8) & 0xFF)
418*e1fe3e4aSElliott Hughes                                push(value & 0xFF)
419*e1fe3e4aSElliott Hughes
420*e1fe3e4aSElliott Hughes                        # Write bytes
421*e1fe3e4aSElliott Hughes                        if nBytes:
422*e1fe3e4aSElliott Hughes                            pass
423*e1fe3e4aSElliott Hughes                            if nBytes <= 8:
424*e1fe3e4aSElliott Hughes                                op, argBits, name = streamMnemonicDict["PUSHB"]
425*e1fe3e4aSElliott Hughes                                op = op + nBytes - 1
426*e1fe3e4aSElliott Hughes                                push(op)
427*e1fe3e4aSElliott Hughes                            else:
428*e1fe3e4aSElliott Hughes                                op, argBits, name = streamMnemonicDict["NPUSHB"]
429*e1fe3e4aSElliott Hughes                                push(op)
430*e1fe3e4aSElliott Hughes                                push(nBytes)
431*e1fe3e4aSElliott Hughes                            for value in args[nWords : nWords + nBytes]:
432*e1fe3e4aSElliott Hughes                                push(value)
433*e1fe3e4aSElliott Hughes
434*e1fe3e4aSElliott Hughes                        nTotal = nWords + nBytes
435*e1fe3e4aSElliott Hughes                        args = args[nTotal:]
436*e1fe3e4aSElliott Hughes                        nArgs -= nTotal
437*e1fe3e4aSElliott Hughes                        nWords = 0
438*e1fe3e4aSElliott Hughes                else:
439*e1fe3e4aSElliott Hughes                    # Write exactly what we've been asked to
440*e1fe3e4aSElliott Hughes                    words = mnemonic[-1] == "W"
441*e1fe3e4aSElliott Hughes                    op, argBits, name = streamMnemonicDict[mnemonic]
442*e1fe3e4aSElliott Hughes                    if mnemonic[0] != "N":
443*e1fe3e4aSElliott Hughes                        assert nArgs <= 8, nArgs
444*e1fe3e4aSElliott Hughes                        op = op + nArgs - 1
445*e1fe3e4aSElliott Hughes                        push(op)
446*e1fe3e4aSElliott Hughes                    else:
447*e1fe3e4aSElliott Hughes                        assert nArgs < 256
448*e1fe3e4aSElliott Hughes                        push(op)
449*e1fe3e4aSElliott Hughes                        push(nArgs)
450*e1fe3e4aSElliott Hughes                    if words:
451*e1fe3e4aSElliott Hughes                        for value in args:
452*e1fe3e4aSElliott Hughes                            assert -32768 <= value < 32768, (
453*e1fe3e4aSElliott Hughes                                "PUSHW value out of range %d" % value
454*e1fe3e4aSElliott Hughes                            )
455*e1fe3e4aSElliott Hughes                            push((value >> 8) & 0xFF)
456*e1fe3e4aSElliott Hughes                            push(value & 0xFF)
457*e1fe3e4aSElliott Hughes                    else:
458*e1fe3e4aSElliott Hughes                        for value in args:
459*e1fe3e4aSElliott Hughes                            assert 0 <= value < 256, (
460*e1fe3e4aSElliott Hughes                                "PUSHB value out of range %d" % value
461*e1fe3e4aSElliott Hughes                            )
462*e1fe3e4aSElliott Hughes                            push(value)
463*e1fe3e4aSElliott Hughes
464*e1fe3e4aSElliott Hughes            pos = _skipWhite(assembly, pos)
465*e1fe3e4aSElliott Hughes
466*e1fe3e4aSElliott Hughes        if bytecode:
467*e1fe3e4aSElliott Hughes            assert max(bytecode) < 256 and min(bytecode) >= 0
468*e1fe3e4aSElliott Hughes        self.bytecode = array.array("B", bytecode)
469*e1fe3e4aSElliott Hughes
470*e1fe3e4aSElliott Hughes    def _disassemble(self, preserve=False) -> None:
471*e1fe3e4aSElliott Hughes        assembly = []
472*e1fe3e4aSElliott Hughes        i = 0
473*e1fe3e4aSElliott Hughes        bytecode = getattr(self, "bytecode", [])
474*e1fe3e4aSElliott Hughes        numBytecode = len(bytecode)
475*e1fe3e4aSElliott Hughes        while i < numBytecode:
476*e1fe3e4aSElliott Hughes            op = bytecode[i]
477*e1fe3e4aSElliott Hughes            try:
478*e1fe3e4aSElliott Hughes                mnemonic, argBits, argoffset, name = opcodeDict[op]
479*e1fe3e4aSElliott Hughes            except KeyError:
480*e1fe3e4aSElliott Hughes                if op in streamOpcodeDict:
481*e1fe3e4aSElliott Hughes                    values = []
482*e1fe3e4aSElliott Hughes
483*e1fe3e4aSElliott Hughes                    # Merge consecutive PUSH operations
484*e1fe3e4aSElliott Hughes                    while bytecode[i] in streamOpcodeDict:
485*e1fe3e4aSElliott Hughes                        op = bytecode[i]
486*e1fe3e4aSElliott Hughes                        mnemonic, argBits, argoffset, name = streamOpcodeDict[op]
487*e1fe3e4aSElliott Hughes                        words = mnemonic[-1] == "W"
488*e1fe3e4aSElliott Hughes                        if argBits:
489*e1fe3e4aSElliott Hughes                            nValues = op - argoffset + 1
490*e1fe3e4aSElliott Hughes                        else:
491*e1fe3e4aSElliott Hughes                            i = i + 1
492*e1fe3e4aSElliott Hughes                            nValues = bytecode[i]
493*e1fe3e4aSElliott Hughes                        i = i + 1
494*e1fe3e4aSElliott Hughes                        assert nValues > 0
495*e1fe3e4aSElliott Hughes                        if not words:
496*e1fe3e4aSElliott Hughes                            for j in range(nValues):
497*e1fe3e4aSElliott Hughes                                value = bytecode[i]
498*e1fe3e4aSElliott Hughes                                values.append(repr(value))
499*e1fe3e4aSElliott Hughes                                i = i + 1
500*e1fe3e4aSElliott Hughes                        else:
501*e1fe3e4aSElliott Hughes                            for j in range(nValues):
502*e1fe3e4aSElliott Hughes                                # cast to signed int16
503*e1fe3e4aSElliott Hughes                                value = (bytecode[i] << 8) | bytecode[i + 1]
504*e1fe3e4aSElliott Hughes                                if value >= 0x8000:
505*e1fe3e4aSElliott Hughes                                    value = value - 0x10000
506*e1fe3e4aSElliott Hughes                                values.append(repr(value))
507*e1fe3e4aSElliott Hughes                                i = i + 2
508*e1fe3e4aSElliott Hughes                        if preserve:
509*e1fe3e4aSElliott Hughes                            break
510*e1fe3e4aSElliott Hughes
511*e1fe3e4aSElliott Hughes                    if not preserve:
512*e1fe3e4aSElliott Hughes                        mnemonic = "PUSH"
513*e1fe3e4aSElliott Hughes                    nValues = len(values)
514*e1fe3e4aSElliott Hughes                    if nValues == 1:
515*e1fe3e4aSElliott Hughes                        assembly.append("%s[ ]	/* 1 value pushed */" % mnemonic)
516*e1fe3e4aSElliott Hughes                    else:
517*e1fe3e4aSElliott Hughes                        assembly.append(
518*e1fe3e4aSElliott Hughes                            "%s[ ]	/* %s values pushed */" % (mnemonic, nValues)
519*e1fe3e4aSElliott Hughes                        )
520*e1fe3e4aSElliott Hughes                    assembly.extend(values)
521*e1fe3e4aSElliott Hughes                else:
522*e1fe3e4aSElliott Hughes                    assembly.append("INSTR%d[ ]" % op)
523*e1fe3e4aSElliott Hughes                    i = i + 1
524*e1fe3e4aSElliott Hughes            else:
525*e1fe3e4aSElliott Hughes                if argBits:
526*e1fe3e4aSElliott Hughes                    assembly.append(
527*e1fe3e4aSElliott Hughes                        mnemonic
528*e1fe3e4aSElliott Hughes                        + "[%s]	/* %s */" % (num2binary(op - argoffset, argBits), name)
529*e1fe3e4aSElliott Hughes                    )
530*e1fe3e4aSElliott Hughes                else:
531*e1fe3e4aSElliott Hughes                    assembly.append(mnemonic + "[ ]	/* %s */" % name)
532*e1fe3e4aSElliott Hughes                i = i + 1
533*e1fe3e4aSElliott Hughes        self.assembly = assembly
534*e1fe3e4aSElliott Hughes
535*e1fe3e4aSElliott Hughes    def __bool__(self) -> bool:
536*e1fe3e4aSElliott Hughes        """
537*e1fe3e4aSElliott Hughes        >>> p = Program()
538*e1fe3e4aSElliott Hughes        >>> bool(p)
539*e1fe3e4aSElliott Hughes        False
540*e1fe3e4aSElliott Hughes        >>> bc = array.array("B", [0])
541*e1fe3e4aSElliott Hughes        >>> p.fromBytecode(bc)
542*e1fe3e4aSElliott Hughes        >>> bool(p)
543*e1fe3e4aSElliott Hughes        True
544*e1fe3e4aSElliott Hughes        >>> p.bytecode.pop()
545*e1fe3e4aSElliott Hughes        0
546*e1fe3e4aSElliott Hughes        >>> bool(p)
547*e1fe3e4aSElliott Hughes        False
548*e1fe3e4aSElliott Hughes
549*e1fe3e4aSElliott Hughes        >>> p = Program()
550*e1fe3e4aSElliott Hughes        >>> asm = ['SVTCA[0]']
551*e1fe3e4aSElliott Hughes        >>> p.fromAssembly(asm)
552*e1fe3e4aSElliott Hughes        >>> bool(p)
553*e1fe3e4aSElliott Hughes        True
554*e1fe3e4aSElliott Hughes        >>> p.assembly.pop()
555*e1fe3e4aSElliott Hughes        'SVTCA[0]'
556*e1fe3e4aSElliott Hughes        >>> bool(p)
557*e1fe3e4aSElliott Hughes        False
558*e1fe3e4aSElliott Hughes        """
559*e1fe3e4aSElliott Hughes        return (hasattr(self, "assembly") and len(self.assembly) > 0) or (
560*e1fe3e4aSElliott Hughes            hasattr(self, "bytecode") and len(self.bytecode) > 0
561*e1fe3e4aSElliott Hughes        )
562*e1fe3e4aSElliott Hughes
563*e1fe3e4aSElliott Hughes    __nonzero__ = __bool__
564*e1fe3e4aSElliott Hughes
565*e1fe3e4aSElliott Hughes    def __eq__(self, other) -> bool:
566*e1fe3e4aSElliott Hughes        if type(self) != type(other):
567*e1fe3e4aSElliott Hughes            return NotImplemented
568*e1fe3e4aSElliott Hughes        return self.__dict__ == other.__dict__
569*e1fe3e4aSElliott Hughes
570*e1fe3e4aSElliott Hughes    def __ne__(self, other) -> bool:
571*e1fe3e4aSElliott Hughes        result = self.__eq__(other)
572*e1fe3e4aSElliott Hughes        return result if result is NotImplemented else not result
573*e1fe3e4aSElliott Hughes
574*e1fe3e4aSElliott Hughes
575*e1fe3e4aSElliott Hughesdef _test():
576*e1fe3e4aSElliott Hughes    """
577*e1fe3e4aSElliott Hughes    >>> _test()
578*e1fe3e4aSElliott Hughes    True
579*e1fe3e4aSElliott Hughes    """
580*e1fe3e4aSElliott Hughes
581*e1fe3e4aSElliott Hughes    bc = b"""@;:9876543210/.-,+*)(\'&%$#"! \037\036\035\034\033\032\031\030\027\026\025\024\023\022\021\020\017\016\015\014\013\012\011\010\007\006\005\004\003\002\001\000,\001\260\030CXEj\260\031C`\260F#D#\020 \260FN\360M/\260\000\022\033!#\0213Y-,\001\260\030CX\260\005+\260\000\023K\260\024PX\261\000@8Y\260\006+\033!#\0213Y-,\001\260\030CXN\260\003%\020\362!\260\000\022M\033 E\260\004%\260\004%#Jad\260(RX!#\020\326\033\260\003%\020\362!\260\000\022YY-,\260\032CX!!\033\260\002%\260\002%I\260\003%\260\003%Ja d\260\020PX!!!\033\260\003%\260\003%I\260\000PX\260\000PX\270\377\3428!\033\260\0208!Y\033\260\000RX\260\0368!\033\270\377\3608!YYYY-,\001\260\030CX\260\005+\260\000\023K\260\024PX\271\000\000\377\3008Y\260\006+\033!#\0213Y-,N\001\212\020\261F\031CD\260\000\024\261\000F\342\260\000\025\271\000\000\377\3608\000\260\000<\260(+\260\002%\020\260\000<-,\001\030\260\000/\260\001\024\362\260\001\023\260\001\025M\260\000\022-,\001\260\030CX\260\005+\260\000\023\271\000\000\377\3408\260\006+\033!#\0213Y-,\001\260\030CXEdj#Edi\260\031Cd``\260F#D#\020 \260F\360/\260\000\022\033!! \212 \212RX\0213\033!!YY-,\001\261\013\012C#Ce\012-,\000\261\012\013C#C\013-,\000\260F#p\261\001F>\001\260F#p\261\002FE:\261\002\000\010\015-,\260\022+\260\002%E\260\002%Ej\260@\213`\260\002%#D!!!-,\260\023+\260\002%E\260\002%Ej\270\377\300\214`\260\002%#D!!!-,\260\000\260\022+!!!-,\260\000\260\023+!!!-,\001\260\006C\260\007Ce\012-, i\260@a\260\000\213 \261,\300\212\214\270\020\000b`+\014d#da\\X\260\003aY-,\261\000\003%EhT\260\034KPZX\260\003%E\260\003%E`h \260\004%#D\260\004%#D\033\260\003% Eh \212#D\260\003%Eh`\260\003%#DY-,\260\003% Eh \212#D\260\003%Edhe`\260\004%\260\001`#D-,\260\011CX\207!\300\033\260\022CX\207E\260\021+\260G#D\260Gz\344\033\003\212E\030i \260G#D\212\212\207 \260\240QX\260\021+\260G#D\260Gz\344\033!\260Gz\344YYY\030-, \212E#Eh`D-,EjB-,\001\030/-,\001\260\030CX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260\031C`\260F#D!\212\020\260F\366!\033!!!!Y-,\001\260\030CX\260\002%E\260\002%Ed`j\260\003%Eja \260\004%Ej \212\213e\260\004%#D\214\260\003%#D!!\033 EjD EjDY-,\001 E\260\000U\260\030CZXEh#Ei\260@\213a \260\200bj \212#a \260\003%\213e\260\004%#D\214\260\003%#D!!\033!!\260\031+Y-,\001\212\212Ed#EdadB-,\260\004%\260\004%\260\031+\260\030CX\260\004%\260\004%\260\003%\260\033+\001\260\002%C\260@T\260\002%C\260\000TZX\260\003% E\260@aDY\260\002%C\260\000T\260\002%C\260@TZX\260\004% E\260@`DYY!!!!-,\001KRXC\260\002%E#aD\033!!Y-,\001KRXC\260\002%E#`D\033!!Y-,KRXED\033!!Y-,\001 \260\003%#I\260@`\260 c \260\000RX#\260\002%8#\260\002%e8\000\212c8\033!!!!!Y\001-,KPXED\033!!Y-,\001\260\005%\020# \212\365\000\260\001`#\355\354-,\001\260\005%\020# \212\365\000\260\001a#\355\354-,\001\260\006%\020\365\000\355\354-,F#F`\212\212F# F\212`\212a\270\377\200b# \020#\212\261KK\212pE` \260\000PX\260\001a\270\377\272\213\033\260F\214Y\260\020`h\001:-, E\260\003%FRX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-, E\260\003%FPX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-,\000\260\007C\260\006C\013-,\212\020\354-,\260\014CX!\033 F\260\000RX\270\377\3608\033\260\0208YY-, \260\000UX\270\020\000c\260\003%Ed\260\003%Eda\260\000SX\260\002\033\260@a\260\003Y%EiSXED\033!!Y\033!\260\002%E\260\002%Ead\260(QXED\033!!YY-,!!\014d#d\213\270@\000b-,!\260\200QX\014d#d\213\270 \000b\033\262\000@/+Y\260\002`-,!\260\300QX\014d#d\213\270\025Ub\033\262\000\200/+Y\260\002`-,\014d#d\213\270@\000b`#!-,KSX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260F#D!\212\020\260F\366!\033!\212\021#\022 9/Y-,\260\002%\260\002%Id\260\300TX\270\377\3708\260\0108\033!!Y-,\260\023CX\003\033\002Y-,\260\023CX\002\033\003Y-,\260\012+#\020 <\260\027+-,\260\002%\270\377\3608\260(+\212\020# \320#\260\020+\260\005CX\300\033<Y \020\021\260\000\022\001-,KS#KQZX8\033!!Y-,\001\260\002%\020\320#\311\001\260\001\023\260\000\024\020\260\001<\260\001\026-,\001\260\000\023\260\001\260\003%I\260\003\0278\260\001\023-,KS#KQZX E\212`D\033!!Y-, 9/-"""
582*e1fe3e4aSElliott Hughes
583*e1fe3e4aSElliott Hughes    p = Program()
584*e1fe3e4aSElliott Hughes    p.fromBytecode(bc)
585*e1fe3e4aSElliott Hughes    asm = p.getAssembly(preserve=True)
586*e1fe3e4aSElliott Hughes    p.fromAssembly(asm)
587*e1fe3e4aSElliott Hughes    print(bc == p.getBytecode())
588*e1fe3e4aSElliott Hughes
589*e1fe3e4aSElliott Hughes
590*e1fe3e4aSElliott Hughesif __name__ == "__main__":
591*e1fe3e4aSElliott Hughes    import sys
592*e1fe3e4aSElliott Hughes    import doctest
593*e1fe3e4aSElliott Hughes
594*e1fe3e4aSElliott Hughes    sys.exit(doctest.testmod().failed)
595