Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/fontTools/ttLib/tables/ttProgram.py: 18%

311 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:33 +0000

1"""ttLib.tables.ttProgram.py -- Assembler/disassembler for TrueType bytecode programs.""" 

2from __future__ import annotations 

3 

4from fontTools.misc.textTools import num2binary, binary2num, readHex, strjoin 

5import array 

6from io import StringIO 

7from typing import List 

8import re 

9import logging 

10 

11 

12log = logging.getLogger(__name__) 

13 

14# fmt: off 

15 

16# first, the list of instructions that eat bytes or words from the instruction stream 

17 

18streamInstructions = [ 

19# 

20# opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes 

21# 

22 (0x40, 'NPUSHB', 0, 'PushNBytes', 0, -1), # n, b1, b2,...bn b1,b2...bn 

23 (0x41, 'NPUSHW', 0, 'PushNWords', 0, -1), # n, w1, w2,...w w1,w2...wn 

24 (0xb0, 'PUSHB', 3, 'PushBytes', 0, -1), # b0, b1,..bn b0, b1, ...,bn 

25 (0xb8, 'PUSHW', 3, 'PushWords', 0, -1), # w0,w1,..wn w0 ,w1, ...wn 

26] 

27 

28 

29# next, the list of "normal" instructions 

30 

31instructions = [ 

32# 

33# opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes 

34# 

35 (0x7f, 'AA', 0, 'AdjustAngle', 1, 0), # p - 

36 (0x64, 'ABS', 0, 'Absolute', 1, 1), # n |n| 

37 (0x60, 'ADD', 0, 'Add', 2, 1), # n2, n1 (n1 + n2) 

38 (0x27, 'ALIGNPTS', 0, 'AlignPts', 2, 0), # p2, p1 - 

39 (0x3c, 'ALIGNRP', 0, 'AlignRelativePt', -1, 0), # p1, p2, ... , ploopvalue - 

40 (0x5a, 'AND', 0, 'LogicalAnd', 2, 1), # e2, e1 b 

41 (0x2b, 'CALL', 0, 'CallFunction', 1, 0), # f - 

42 (0x67, 'CEILING', 0, 'Ceiling', 1, 1), # n ceil(n) 

43 (0x25, 'CINDEX', 0, 'CopyXToTopStack', 1, 1), # k ek 

44 (0x22, 'CLEAR', 0, 'ClearStack', -1, 0), # all items on the stack - 

45 (0x4f, 'DEBUG', 0, 'DebugCall', 1, 0), # n - 

46 (0x73, 'DELTAC1', 0, 'DeltaExceptionC1', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - 

47 (0x74, 'DELTAC2', 0, 'DeltaExceptionC2', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - 

48 (0x75, 'DELTAC3', 0, 'DeltaExceptionC3', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - 

49 (0x5d, 'DELTAP1', 0, 'DeltaExceptionP1', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - 

50 (0x71, 'DELTAP2', 0, 'DeltaExceptionP2', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - 

51 (0x72, 'DELTAP3', 0, 'DeltaExceptionP3', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - 

52 (0x24, 'DEPTH', 0, 'GetDepthStack', 0, 1), # - n 

53 (0x62, 'DIV', 0, 'Divide', 2, 1), # n2, n1 (n1 * 64)/ n2 

54 (0x20, 'DUP', 0, 'DuplicateTopStack', 1, 2), # e e, e 

55 (0x59, 'EIF', 0, 'EndIf', 0, 0), # - - 

56 (0x1b, 'ELSE', 0, 'Else', 0, 0), # - - 

57 (0x2d, 'ENDF', 0, 'EndFunctionDefinition', 0, 0), # - - 

58 (0x54, 'EQ', 0, 'Equal', 2, 1), # e2, e1 b 

59 (0x57, 'EVEN', 0, 'Even', 1, 1), # e b 

60 (0x2c, 'FDEF', 0, 'FunctionDefinition', 1, 0), # f - 

61 (0x4e, 'FLIPOFF', 0, 'SetAutoFlipOff', 0, 0), # - - 

62 (0x4d, 'FLIPON', 0, 'SetAutoFlipOn', 0, 0), # - - 

63 (0x80, 'FLIPPT', 0, 'FlipPoint', -1, 0), # p1, p2, ..., ploopvalue - 

64 (0x82, 'FLIPRGOFF', 0, 'FlipRangeOff', 2, 0), # h, l - 

65 (0x81, 'FLIPRGON', 0, 'FlipRangeOn', 2, 0), # h, l - 

66 (0x66, 'FLOOR', 0, 'Floor', 1, 1), # n floor(n) 

67 (0x46, 'GC', 1, 'GetCoordOnPVector', 1, 1), # p c 

68 (0x88, 'GETINFO', 0, 'GetInfo', 1, 1), # selector result 

69 (0x91, 'GETVARIATION', 0, 'GetVariation', 0, -1), # - a1,..,an 

70 (0x0d, 'GFV', 0, 'GetFVector', 0, 2), # - px, py 

71 (0x0c, 'GPV', 0, 'GetPVector', 0, 2), # - px, py 

72 (0x52, 'GT', 0, 'GreaterThan', 2, 1), # e2, e1 b 

73 (0x53, 'GTEQ', 0, 'GreaterThanOrEqual', 2, 1), # e2, e1 b 

74 (0x89, 'IDEF', 0, 'InstructionDefinition', 1, 0), # f - 

75 (0x58, 'IF', 0, 'If', 1, 0), # e - 

76 (0x8e, 'INSTCTRL', 0, 'SetInstrExecControl', 2, 0), # s, v - 

77 (0x39, 'IP', 0, 'InterpolatePts', -1, 0), # p1, p2, ... , ploopvalue - 

78 (0x0f, 'ISECT', 0, 'MovePtToIntersect', 5, 0), # a1, a0, b1, b0, p - 

79 (0x30, 'IUP', 1, 'InterpolateUntPts', 0, 0), # - - 

80 (0x1c, 'JMPR', 0, 'Jump', 1, 0), # offset - 

81 (0x79, 'JROF', 0, 'JumpRelativeOnFalse', 2, 0), # e, offset - 

82 (0x78, 'JROT', 0, 'JumpRelativeOnTrue', 2, 0), # e, offset - 

83 (0x2a, 'LOOPCALL', 0, 'LoopAndCallFunction', 2, 0), # f, count - 

84 (0x50, 'LT', 0, 'LessThan', 2, 1), # e2, e1 b 

85 (0x51, 'LTEQ', 0, 'LessThenOrEqual', 2, 1), # e2, e1 b 

86 (0x8b, 'MAX', 0, 'Maximum', 2, 1), # e2, e1 max(e1, e2) 

87 (0x49, 'MD', 1, 'MeasureDistance', 2, 1), # p2,p1 d 

88 (0x2e, 'MDAP', 1, 'MoveDirectAbsPt', 1, 0), # p - 

89 (0xc0, 'MDRP', 5, 'MoveDirectRelPt', 1, 0), # p - 

90 (0x3e, 'MIAP', 1, 'MoveIndirectAbsPt', 2, 0), # n, p - 

91 (0x8c, 'MIN', 0, 'Minimum', 2, 1), # e2, e1 min(e1, e2) 

92 (0x26, 'MINDEX', 0, 'MoveXToTopStack', 1, 1), # k ek 

93 (0xe0, 'MIRP', 5, 'MoveIndirectRelPt', 2, 0), # n, p - 

94 (0x4b, 'MPPEM', 0, 'MeasurePixelPerEm', 0, 1), # - ppem 

95 (0x4c, 'MPS', 0, 'MeasurePointSize', 0, 1), # - pointSize 

96 (0x3a, 'MSIRP', 1, 'MoveStackIndirRelPt', 2, 0), # d, p - 

97 (0x63, 'MUL', 0, 'Multiply', 2, 1), # n2, n1 (n1 * n2)/64 

98 (0x65, 'NEG', 0, 'Negate', 1, 1), # n -n 

99 (0x55, 'NEQ', 0, 'NotEqual', 2, 1), # e2, e1 b 

100 (0x5c, 'NOT', 0, 'LogicalNot', 1, 1), # e ( not e ) 

101 (0x6c, 'NROUND', 2, 'NoRound', 1, 1), # n1 n2 

102 (0x56, 'ODD', 0, 'Odd', 1, 1), # e b 

103 (0x5b, 'OR', 0, 'LogicalOr', 2, 1), # e2, e1 b 

104 (0x21, 'POP', 0, 'PopTopStack', 1, 0), # e - 

105 (0x45, 'RCVT', 0, 'ReadCVT', 1, 1), # location value 

106 (0x7d, 'RDTG', 0, 'RoundDownToGrid', 0, 0), # - - 

107 (0x7a, 'ROFF', 0, 'RoundOff', 0, 0), # - - 

108 (0x8a, 'ROLL', 0, 'RollTopThreeStack', 3, 3), # a,b,c b,a,c 

109 (0x68, 'ROUND', 2, 'Round', 1, 1), # n1 n2 

110 (0x43, 'RS', 0, 'ReadStore', 1, 1), # n v 

111 (0x3d, 'RTDG', 0, 'RoundToDoubleGrid', 0, 0), # - - 

112 (0x18, 'RTG', 0, 'RoundToGrid', 0, 0), # - - 

113 (0x19, 'RTHG', 0, 'RoundToHalfGrid', 0, 0), # - - 

114 (0x7c, 'RUTG', 0, 'RoundUpToGrid', 0, 0), # - - 

115 (0x77, 'S45ROUND', 0, 'SuperRound45Degrees', 1, 0), # n - 

116 (0x7e, 'SANGW', 0, 'SetAngleWeight', 1, 0), # weight - 

117 (0x85, 'SCANCTRL', 0, 'ScanConversionControl', 1, 0), # n - 

118 (0x8d, 'SCANTYPE', 0, 'ScanType', 1, 0), # n - 

119 (0x48, 'SCFS', 0, 'SetCoordFromStackFP', 2, 0), # c, p - 

120 (0x1d, 'SCVTCI', 0, 'SetCVTCutIn', 1, 0), # n - 

121 (0x5e, 'SDB', 0, 'SetDeltaBaseInGState', 1, 0), # n - 

122 (0x86, 'SDPVTL', 1, 'SetDualPVectorToLine', 2, 0), # p2, p1 - 

123 (0x5f, 'SDS', 0, 'SetDeltaShiftInGState', 1, 0), # n - 

124 (0x0b, 'SFVFS', 0, 'SetFVectorFromStack', 2, 0), # y, x - 

125 (0x04, 'SFVTCA', 1, 'SetFVectorToAxis', 0, 0), # - - 

126 (0x08, 'SFVTL', 1, 'SetFVectorToLine', 2, 0), # p2, p1 - 

127 (0x0e, 'SFVTPV', 0, 'SetFVectorToPVector', 0, 0), # - - 

128 (0x34, 'SHC', 1, 'ShiftContourByLastPt', 1, 0), # c - 

129 (0x32, 'SHP', 1, 'ShiftPointByLastPoint', -1, 0), # p1, p2, ..., ploopvalue - 

130 (0x38, 'SHPIX', 0, 'ShiftZoneByPixel', -1, 0), # d, p1, p2, ..., ploopvalue - 

131 (0x36, 'SHZ', 1, 'ShiftZoneByLastPoint', 1, 0), # e - 

132 (0x17, 'SLOOP', 0, 'SetLoopVariable', 1, 0), # n - 

133 (0x1a, 'SMD', 0, 'SetMinimumDistance', 1, 0), # distance - 

134 (0x0a, 'SPVFS', 0, 'SetPVectorFromStack', 2, 0), # y, x - 

135 (0x02, 'SPVTCA', 1, 'SetPVectorToAxis', 0, 0), # - - 

136 (0x06, 'SPVTL', 1, 'SetPVectorToLine', 2, 0), # p2, p1 - 

137 (0x76, 'SROUND', 0, 'SuperRound', 1, 0), # n - 

138 (0x10, 'SRP0', 0, 'SetRefPoint0', 1, 0), # p - 

139 (0x11, 'SRP1', 0, 'SetRefPoint1', 1, 0), # p - 

140 (0x12, 'SRP2', 0, 'SetRefPoint2', 1, 0), # p - 

141 (0x1f, 'SSW', 0, 'SetSingleWidth', 1, 0), # n - 

142 (0x1e, 'SSWCI', 0, 'SetSingleWidthCutIn', 1, 0), # n - 

143 (0x61, 'SUB', 0, 'Subtract', 2, 1), # n2, n1 (n1 - n2) 

144 (0x00, 'SVTCA', 1, 'SetFPVectorToAxis', 0, 0), # - - 

145 (0x23, 'SWAP', 0, 'SwapTopStack', 2, 2), # e2, e1 e1, e2 

146 (0x13, 'SZP0', 0, 'SetZonePointer0', 1, 0), # n - 

147 (0x14, 'SZP1', 0, 'SetZonePointer1', 1, 0), # n - 

148 (0x15, 'SZP2', 0, 'SetZonePointer2', 1, 0), # n - 

149 (0x16, 'SZPS', 0, 'SetZonePointerS', 1, 0), # n - 

150 (0x29, 'UTP', 0, 'UnTouchPt', 1, 0), # p - 

151 (0x70, 'WCVTF', 0, 'WriteCVTInFUnits', 2, 0), # n, l - 

152 (0x44, 'WCVTP', 0, 'WriteCVTInPixels', 2, 0), # v, l - 

153 (0x42, 'WS', 0, 'WriteStore', 2, 0), # v, l - 

154] 

155 

156# fmt: on 

157 

158 

159def bitRepr(value, bits): 

160 s = "" 

161 for i in range(bits): 

162 s = "01"[value & 0x1] + s 

163 value = value >> 1 

164 return s 

165 

166 

167_mnemonicPat = re.compile(r"[A-Z][A-Z0-9]*$") 

168 

169 

170def _makeDict(instructionList): 

171 opcodeDict = {} 

172 mnemonicDict = {} 

173 for op, mnemonic, argBits, name, pops, pushes in instructionList: 

174 assert _mnemonicPat.match(mnemonic) 

175 mnemonicDict[mnemonic] = op, argBits, name 

176 if argBits: 

177 argoffset = op 

178 for i in range(1 << argBits): 

179 opcodeDict[op + i] = mnemonic, argBits, argoffset, name 

180 else: 

181 opcodeDict[op] = mnemonic, 0, 0, name 

182 return opcodeDict, mnemonicDict 

183 

184 

185streamOpcodeDict, streamMnemonicDict = _makeDict(streamInstructions) 

186opcodeDict, mnemonicDict = _makeDict(instructions) 

187 

188 

189class tt_instructions_error(Exception): 

190 def __init__(self, error): 

191 self.error = error 

192 

193 def __str__(self): 

194 return "TT instructions error: %s" % repr(self.error) 

195 

196 

197_comment = r"/\*.*?\*/" 

198_instruction = r"([A-Z][A-Z0-9]*)\s*\[(.*?)\]" 

199_number = r"-?[0-9]+" 

200_token = "(%s)|(%s)|(%s)" % (_instruction, _number, _comment) 

201 

202_tokenRE = re.compile(_token) 

203_whiteRE = re.compile(r"\s*") 

204 

205_pushCountPat = re.compile(r"[A-Z][A-Z0-9]*\s*\[.*?\]\s*/\* ([0-9]+).*?\*/") 

206 

207_indentRE = re.compile(r"^FDEF|IF|ELSE\[ \]\t.+") 

208_unindentRE = re.compile(r"^ELSE|ENDF|EIF\[ \]\t.+") 

209 

210 

211def _skipWhite(data, pos): 

212 m = _whiteRE.match(data, pos) 

213 newPos = m.regs[0][1] 

214 assert newPos >= pos 

215 return newPos 

216 

217 

218class Program(object): 

219 def __init__(self) -> None: 

220 pass 

221 

222 def fromBytecode(self, bytecode: bytes) -> None: 

223 self.bytecode = array.array("B", bytecode) 

224 if hasattr(self, "assembly"): 

225 del self.assembly 

226 

227 def fromAssembly(self, assembly: List[str] | str) -> None: 

228 if isinstance(assembly, list): 

229 self.assembly = assembly 

230 elif isinstance(assembly, str): 

231 self.assembly = assembly.splitlines() 

232 else: 

233 raise TypeError(f"expected str or List[str], got {type(assembly).__name__}") 

234 if hasattr(self, "bytecode"): 

235 del self.bytecode 

236 

237 def getBytecode(self) -> bytes: 

238 if not hasattr(self, "bytecode"): 

239 self._assemble() 

240 return self.bytecode.tobytes() 

241 

242 def getAssembly(self, preserve=True) -> List[str]: 

243 if not hasattr(self, "assembly"): 

244 self._disassemble(preserve=preserve) 

245 return self.assembly 

246 

247 def toXML(self, writer, ttFont) -> None: 

248 if ( 

249 not hasattr(ttFont, "disassembleInstructions") 

250 or ttFont.disassembleInstructions 

251 ): 

252 try: 

253 assembly = self.getAssembly() 

254 except: 

255 import traceback 

256 

257 tmp = StringIO() 

258 traceback.print_exc(file=tmp) 

259 msg = "An exception occurred during the decompilation of glyph program:\n\n" 

260 msg += tmp.getvalue() 

261 log.error(msg) 

262 writer.begintag("bytecode") 

263 writer.newline() 

264 writer.comment(msg.strip()) 

265 writer.newline() 

266 writer.dumphex(self.getBytecode()) 

267 writer.endtag("bytecode") 

268 writer.newline() 

269 else: 

270 if not assembly: 

271 return 

272 writer.begintag("assembly") 

273 writer.newline() 

274 i = 0 

275 indent = 0 

276 nInstr = len(assembly) 

277 while i < nInstr: 

278 instr = assembly[i] 

279 if _unindentRE.match(instr): 

280 indent -= 1 

281 writer.write(writer.indentwhite * indent) 

282 writer.write(instr) 

283 writer.newline() 

284 m = _pushCountPat.match(instr) 

285 i = i + 1 

286 if m: 

287 nValues = int(m.group(1)) 

288 line: List[str] = [] 

289 j = 0 

290 for j in range(nValues): 

291 if j and not (j % 25): 

292 writer.write(writer.indentwhite * indent) 

293 writer.write(" ".join(line)) 

294 writer.newline() 

295 line = [] 

296 line.append(assembly[i + j]) 

297 writer.write(writer.indentwhite * indent) 

298 writer.write(" ".join(line)) 

299 writer.newline() 

300 i = i + j + 1 

301 if _indentRE.match(instr): 

302 indent += 1 

303 writer.endtag("assembly") 

304 writer.newline() 

305 else: 

306 bytecode = self.getBytecode() 

307 if not bytecode: 

308 return 

309 writer.begintag("bytecode") 

310 writer.newline() 

311 writer.dumphex(bytecode) 

312 writer.endtag("bytecode") 

313 writer.newline() 

314 

315 def fromXML(self, name, attrs, content, ttFont) -> None: 

316 if name == "assembly": 

317 self.fromAssembly(strjoin(content)) 

318 self._assemble() 

319 del self.assembly 

320 else: 

321 assert name == "bytecode" 

322 self.fromBytecode(readHex(content)) 

323 

324 def _assemble(self) -> None: 

325 assembly = " ".join(getattr(self, "assembly", [])) 

326 bytecode: List[int] = [] 

327 push = bytecode.append 

328 lenAssembly = len(assembly) 

329 pos = _skipWhite(assembly, 0) 

330 while pos < lenAssembly: 

331 m = _tokenRE.match(assembly, pos) 

332 if m is None: 

333 raise tt_instructions_error( 

334 "Syntax error in TT program (%s)" % assembly[pos - 5 : pos + 15] 

335 ) 

336 dummy, mnemonic, arg, number, comment = m.groups() 

337 pos = m.regs[0][1] 

338 if comment: 

339 pos = _skipWhite(assembly, pos) 

340 continue 

341 

342 arg = arg.strip() 

343 if mnemonic.startswith("INSTR"): 

344 # Unknown instruction 

345 op = int(mnemonic[5:]) 

346 push(op) 

347 elif mnemonic not in ("PUSH", "NPUSHB", "NPUSHW", "PUSHB", "PUSHW"): 

348 op, argBits, name = mnemonicDict[mnemonic] 

349 if len(arg) != argBits: 

350 raise tt_instructions_error( 

351 "Incorrect number of argument bits (%s[%s])" % (mnemonic, arg) 

352 ) 

353 if arg: 

354 arg = binary2num(arg) 

355 push(op + arg) 

356 else: 

357 push(op) 

358 else: 

359 args = [] 

360 pos = _skipWhite(assembly, pos) 

361 while pos < lenAssembly: 

362 m = _tokenRE.match(assembly, pos) 

363 if m is None: 

364 raise tt_instructions_error( 

365 "Syntax error in TT program (%s)" % assembly[pos : pos + 15] 

366 ) 

367 dummy, _mnemonic, arg, number, comment = m.groups() 

368 if number is None and comment is None: 

369 break 

370 pos = m.regs[0][1] 

371 pos = _skipWhite(assembly, pos) 

372 if comment is not None: 

373 continue 

374 args.append(int(number)) 

375 nArgs = len(args) 

376 if mnemonic == "PUSH": 

377 # Automatically choose the most compact representation 

378 nWords = 0 

379 while nArgs: 

380 while ( 

381 nWords < nArgs 

382 and nWords < 255 

383 and not (0 <= args[nWords] <= 255) 

384 ): 

385 nWords += 1 

386 nBytes = 0 

387 while ( 

388 nWords + nBytes < nArgs 

389 and nBytes < 255 

390 and 0 <= args[nWords + nBytes] <= 255 

391 ): 

392 nBytes += 1 

393 if ( 

394 nBytes < 2 

395 and nWords + nBytes < 255 

396 and nWords + nBytes != nArgs 

397 ): 

398 # Will write bytes as words 

399 nWords += nBytes 

400 continue 

401 

402 # Write words 

403 if nWords: 

404 if nWords <= 8: 

405 op, argBits, name = streamMnemonicDict["PUSHW"] 

406 op = op + nWords - 1 

407 push(op) 

408 else: 

409 op, argBits, name = streamMnemonicDict["NPUSHW"] 

410 push(op) 

411 push(nWords) 

412 for value in args[:nWords]: 

413 assert -32768 <= value < 32768, ( 

414 "PUSH value out of range %d" % value 

415 ) 

416 push((value >> 8) & 0xFF) 

417 push(value & 0xFF) 

418 

419 # Write bytes 

420 if nBytes: 

421 pass 

422 if nBytes <= 8: 

423 op, argBits, name = streamMnemonicDict["PUSHB"] 

424 op = op + nBytes - 1 

425 push(op) 

426 else: 

427 op, argBits, name = streamMnemonicDict["NPUSHB"] 

428 push(op) 

429 push(nBytes) 

430 for value in args[nWords : nWords + nBytes]: 

431 push(value) 

432 

433 nTotal = nWords + nBytes 

434 args = args[nTotal:] 

435 nArgs -= nTotal 

436 nWords = 0 

437 else: 

438 # Write exactly what we've been asked to 

439 words = mnemonic[-1] == "W" 

440 op, argBits, name = streamMnemonicDict[mnemonic] 

441 if mnemonic[0] != "N": 

442 assert nArgs <= 8, nArgs 

443 op = op + nArgs - 1 

444 push(op) 

445 else: 

446 assert nArgs < 256 

447 push(op) 

448 push(nArgs) 

449 if words: 

450 for value in args: 

451 assert -32768 <= value < 32768, ( 

452 "PUSHW value out of range %d" % value 

453 ) 

454 push((value >> 8) & 0xFF) 

455 push(value & 0xFF) 

456 else: 

457 for value in args: 

458 assert 0 <= value < 256, ( 

459 "PUSHB value out of range %d" % value 

460 ) 

461 push(value) 

462 

463 pos = _skipWhite(assembly, pos) 

464 

465 if bytecode: 

466 assert max(bytecode) < 256 and min(bytecode) >= 0 

467 self.bytecode = array.array("B", bytecode) 

468 

469 def _disassemble(self, preserve=False) -> None: 

470 assembly = [] 

471 i = 0 

472 bytecode = getattr(self, "bytecode", []) 

473 numBytecode = len(bytecode) 

474 while i < numBytecode: 

475 op = bytecode[i] 

476 try: 

477 mnemonic, argBits, argoffset, name = opcodeDict[op] 

478 except KeyError: 

479 if op in streamOpcodeDict: 

480 values = [] 

481 

482 # Merge consecutive PUSH operations 

483 while bytecode[i] in streamOpcodeDict: 

484 op = bytecode[i] 

485 mnemonic, argBits, argoffset, name = streamOpcodeDict[op] 

486 words = mnemonic[-1] == "W" 

487 if argBits: 

488 nValues = op - argoffset + 1 

489 else: 

490 i = i + 1 

491 nValues = bytecode[i] 

492 i = i + 1 

493 assert nValues > 0 

494 if not words: 

495 for j in range(nValues): 

496 value = bytecode[i] 

497 values.append(repr(value)) 

498 i = i + 1 

499 else: 

500 for j in range(nValues): 

501 # cast to signed int16 

502 value = (bytecode[i] << 8) | bytecode[i + 1] 

503 if value >= 0x8000: 

504 value = value - 0x10000 

505 values.append(repr(value)) 

506 i = i + 2 

507 if preserve: 

508 break 

509 

510 if not preserve: 

511 mnemonic = "PUSH" 

512 nValues = len(values) 

513 if nValues == 1: 

514 assembly.append("%s[ ] /* 1 value pushed */" % mnemonic) 

515 else: 

516 assembly.append( 

517 "%s[ ] /* %s values pushed */" % (mnemonic, nValues) 

518 ) 

519 assembly.extend(values) 

520 else: 

521 assembly.append("INSTR%d[ ]" % op) 

522 i = i + 1 

523 else: 

524 if argBits: 

525 assembly.append( 

526 mnemonic 

527 + "[%s] /* %s */" % (num2binary(op - argoffset, argBits), name) 

528 ) 

529 else: 

530 assembly.append(mnemonic + "[ ] /* %s */" % name) 

531 i = i + 1 

532 self.assembly = assembly 

533 

534 def __bool__(self) -> bool: 

535 """ 

536 >>> p = Program() 

537 >>> bool(p) 

538 False 

539 >>> bc = array.array("B", [0]) 

540 >>> p.fromBytecode(bc) 

541 >>> bool(p) 

542 True 

543 >>> p.bytecode.pop() 

544 0 

545 >>> bool(p) 

546 False 

547 

548 >>> p = Program() 

549 >>> asm = ['SVTCA[0]'] 

550 >>> p.fromAssembly(asm) 

551 >>> bool(p) 

552 True 

553 >>> p.assembly.pop() 

554 'SVTCA[0]' 

555 >>> bool(p) 

556 False 

557 """ 

558 return (hasattr(self, "assembly") and len(self.assembly) > 0) or ( 

559 hasattr(self, "bytecode") and len(self.bytecode) > 0 

560 ) 

561 

562 __nonzero__ = __bool__ 

563 

564 def __eq__(self, other) -> bool: 

565 if type(self) != type(other): 

566 return NotImplemented 

567 return self.__dict__ == other.__dict__ 

568 

569 def __ne__(self, other) -> bool: 

570 result = self.__eq__(other) 

571 return result if result is NotImplemented else not result 

572 

573 

574def _test(): 

575 """ 

576 >>> _test() 

577 True 

578 """ 

579 

580 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/-""" 

581 

582 p = Program() 

583 p.fromBytecode(bc) 

584 asm = p.getAssembly(preserve=True) 

585 p.fromAssembly(asm) 

586 print(bc == p.getBytecode()) 

587 

588 

589if __name__ == "__main__": 

590 import sys 

591 import doctest 

592 

593 sys.exit(doctest.testmod().failed)