You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

730 lines
26 KiB

  1. #!/usr/bin/python3.0
  2. # Copyright 2008, SoftPLC Corporation http://softplc.com
  3. # Dick Hollenbeck dick@softplc.com
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, you may find one here:
  16. # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  17. # or you may search the http://www.gnu.org website for the version 2 license,
  18. # or you may write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  20. # A python program to convert an SVF file to an XSVF file. There is an
  21. # option to include comments containing the source file line number from the origin
  22. # SVF file before each outputted XSVF statement.
  23. #
  24. # We deviate from the XSVF spec in that we introduce a new command called
  25. # XWAITSTATE which directly flows from the SVF RUNTEST command. Unfortunately
  26. # XRUNSTATE was ill conceived and is not used here. We also add support for the
  27. # three Lattice extensions to SVF: LCOUNT, LDELAY, and LSDR. The xsvf file
  28. # generated from this program is suitable for use with the xsvf player in
  29. # OpenOCD with my modifications to xsvf.c.
  30. #
  31. # This program is written for python 3.0, and it is not easy to change this
  32. # back to 2.x. You may find it easier to use python 3.x even if that means
  33. # building it.
  34. import re
  35. import sys
  36. import struct
  37. # There are both ---<Lexer>--- and ---<Parser>--- sections to this program
  38. if len( sys.argv ) < 3:
  39. print("usage %s <svf_filename> <xsvf_filename>" % sys.argv[0])
  40. exit(1)
  41. inputFilename = sys.argv[1]
  42. outputFilename = sys.argv[2]
  43. doCOMMENTs = True # Save XCOMMENTs in the output xsvf file
  44. #doCOMMENTs = False # Save XCOMMENTs in the output xsvf file
  45. # pick your file encoding
  46. file_encoding = 'ISO-8859-1'
  47. #file_encoding = 'utf-8'
  48. xrepeat = 0 # argument to XREPEAT, gives retry count for masked compares
  49. #-----< Lexer >---------------------------------------------------------------
  50. StateBin = (RESET,IDLE,
  51. DRSELECT,DRCAPTURE,DRSHIFT,DREXIT1,DRPAUSE,DREXIT2,DRUPDATE,
  52. IRSELECT,IRCAPTURE,IRSHIFT,IREXIT1,IRPAUSE,IREXIT2,IRUPDATE) = range(16)
  53. # Any integer index into this tuple will be equal to its corresponding StateBin value
  54. StateTxt = ("RESET","IDLE",
  55. "DRSELECT","DRCAPTURE","DRSHIFT","DREXIT1","DRPAUSE","DREXIT2","DRUPDATE",
  56. "IRSELECT","IRCAPTURE","IRSHIFT","IREXIT1","IRPAUSE","IREXIT2","IRUPDATE")
  57. (XCOMPLETE,XTDOMASK,XSIR,XSDR,XRUNTEST,hole0,hole1,XREPEAT,XSDRSIZE,XSDRTDO,
  58. XSETSDRMASKS,XSDRINC,XSDRB,XSDRC,XSDRE,XSDRTDOB,XSDRTDOC,
  59. XSDRTDOE,XSTATE,XENDIR,XENDDR,XSIR2,XCOMMENT,XWAIT,XWAITSTATE,
  60. LCOUNT,LDELAY,LSDR,XTRST) = range(29)
  61. #Note: LCOUNT, LDELAY, and LSDR are Lattice extensions to SVF and provide a way to loop back
  62. # and check a completion status, essentially waiting on a part until it signals that it is done.
  63. # For example below: loop 25 times, each time through the loop do a LDELAY (same as a true RUNTEST)
  64. # and exit loop when LSDR compares match.
  65. """
  66. LCOUNT 25;
  67. ! Step to DRPAUSE give 5 clocks and wait for 1.00e+000 SEC.
  68. LDELAY DRPAUSE 5 TCK 1.00E-003 SEC;
  69. ! Test for the completed status. Match means pass.
  70. ! Loop back to LDELAY line if not match and loop count less than 25.
  71. LSDR 1 TDI (0)
  72. TDO (1);
  73. """
  74. #XTRST is an opcode Xilinx seemed to have missed and it comes from the SVF TRST statement.
  75. LineNumber = 1
  76. def s_ident(scanner, token): return ("ident", token.upper(), LineNumber)
  77. def s_hex(scanner, token):
  78. global LineNumber
  79. LineNumber = LineNumber + token.count('\n')
  80. token = ''.join(token.split())
  81. return ("hex", token[1:-1], LineNumber)
  82. def s_int(scanner, token): return ("int", int(token), LineNumber)
  83. def s_float(scanner, token): return ("float", float(token), LineNumber)
  84. #def s_comment(scanner, token): return ("comment", token, LineNumber)
  85. def s_semicolon(scanner, token): return ("semi", token, LineNumber)
  86. def s_nl(scanner,token):
  87. global LineNumber
  88. LineNumber = LineNumber + 1
  89. #print( 'LineNumber=', LineNumber, file=sys.stderr )
  90. return None
  91. #2.00E-002
  92. scanner = re.Scanner([
  93. (r"[a-zA-Z]\w*", s_ident),
  94. # (r"[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?", s_float),
  95. (r"[-+]?[0-9]+(([.][0-9eE+-]*)|([eE]+[-+]?[0-9]+))", s_float),
  96. (r"\d+", s_int),
  97. (r"\(([0-9a-fA-F]|\s)*\)", s_hex),
  98. (r"(!|//).*$", None),
  99. (r";", s_semicolon),
  100. (r"\n",s_nl),
  101. (r"\s*", None),
  102. ],
  103. re.MULTILINE
  104. )
  105. # open the file using the given encoding
  106. file = open( sys.argv[1], encoding=file_encoding )
  107. # read all svf file input into string "input"
  108. input = file.read()
  109. file.close()
  110. # Lexer:
  111. # create a list of tuples containing (tokenType, tokenValue, LineNumber)
  112. tokens = scanner.scan( input )[0]
  113. input = None # allow gc to reclaim memory holding file
  114. #for tokenType, tokenValue, ln in tokens: print( "line %d: %s" % (ln, tokenType), tokenValue )
  115. #-----<parser>-----------------------------------------------------------------
  116. tokVal = tokType = tokLn = None
  117. tup = iter( tokens )
  118. def nextTok():
  119. """
  120. Function to read the next token from tup into tokType, tokVal, tokLn (linenumber)
  121. which are globals.
  122. """
  123. global tokType, tokVal, tokLn, tup
  124. tokType, tokVal, tokLn = tup.__next__()
  125. class ParseError(Exception):
  126. """A class to hold a parsing error message"""
  127. def __init__(self, linenumber, token, message):
  128. self.linenumber = linenumber
  129. self.token = token
  130. self.message = message
  131. def __str__(self):
  132. global inputFilename
  133. return "Error in file \'%s\' at line %d near token %s\n %s" % (
  134. inputFilename, self.linenumber, repr(self.token), self.message)
  135. class MASKSET(object):
  136. """
  137. Class MASKSET holds a set of bit vectors, all of which are related, will all
  138. have the same length, and are associated with one of the seven shiftOps:
  139. HIR, HDR, TIR, TDR, SIR, SDR, LSDR. One of these holds a mask, smask, tdi, tdo, and a
  140. size.
  141. """
  142. def __init__(self, name):
  143. self.empty()
  144. self.name = name
  145. def empty(self):
  146. self.mask = bytearray()
  147. self.smask = bytearray()
  148. self.tdi = bytearray()
  149. self.tdo = bytearray()
  150. self.size = 0
  151. def syncLengths( self, sawTDI, sawTDO, sawMASK, sawSMASK, newSize ):
  152. """
  153. Set all the lengths equal in the event some of the masks were
  154. not seen as part of the last change set.
  155. """
  156. if self.size == newSize:
  157. return
  158. if newSize == 0:
  159. self.empty()
  160. return
  161. # If an SIR was given without a MASK(), then use a mask of all zeros.
  162. # this is not consistent with the SVF spec, but it makes sense because
  163. # it would be odd to be testing an instruction register read out of a
  164. # tap without giving a mask for it. Also, lattice seems to agree and is
  165. # generating SVF files that comply with this philosophy.
  166. if self.name == 'SIR' and not sawMASK:
  167. self.mask = bytearray( newSize )
  168. if newSize != len(self.mask):
  169. self.mask = bytearray( newSize )
  170. if self.name == 'SDR': # leave mask for HIR,HDR,TIR,TDR,SIR zeros
  171. for i in range( newSize ):
  172. self.mask[i] = 1
  173. if newSize != len(self.tdo):
  174. self.tdo = bytearray( newSize )
  175. if newSize != len(self.tdi):
  176. self.tdi = bytearray( newSize )
  177. if newSize != len(self.smask):
  178. self.smask = bytearray( newSize )
  179. self.size = newSize
  180. #-----</MASKSET>-----
  181. def makeBitArray( hexString, bitCount ):
  182. """
  183. Converts a packed sequence of hex ascii characters into a bytearray where
  184. each element in the array holds exactly one bit. Only "bitCount" bits are
  185. scanned and these must be the least significant bits in the hex number. That
  186. is, it is legal to have some unused bits in the must significant hex nibble
  187. of the input "hexString". The string is scanned starting from the backend,
  188. then just before returning we reverse the array. This way the append()
  189. method can be used, which I assume is faster than an insert.
  190. """
  191. global tokLn
  192. a = bytearray()
  193. length = bitCount
  194. hexString = list(hexString)
  195. hexString.reverse()
  196. #print(hexString)
  197. for c in hexString:
  198. if length <= 0:
  199. break;
  200. c = int(c, 16)
  201. for mask in [1,2,4,8]:
  202. if length <= 0:
  203. break;
  204. length = length - 1
  205. a.append( (c & mask) != 0 )
  206. if length > 0:
  207. raise ParseError( tokLn, hexString, "Insufficient hex characters for given length of %d" % bitCount )
  208. a.reverse()
  209. #print(a)
  210. return a
  211. def makeXSVFbytes( bitarray ):
  212. """
  213. Make a bytearray which is contains the XSVF bits which will be written
  214. directly to disk. The number of bytes needed is calculated from the size
  215. of the argument bitarray.
  216. """
  217. bitCount = len(bitarray)
  218. byteCount = (bitCount+7)//8
  219. ba = bytearray( byteCount )
  220. firstBit = (bitCount % 8) - 1
  221. if firstBit == -1:
  222. firstBit = 7
  223. bitNdx = 0
  224. for byteNdx in range(byteCount):
  225. mask = 1<<firstBit
  226. byte = 0
  227. while mask:
  228. if bitarray[bitNdx]:
  229. byte |= mask;
  230. mask = mask >> 1
  231. bitNdx = bitNdx + 1
  232. ba[byteNdx] = byte
  233. firstBit = 7
  234. return ba
  235. def writeComment( outputFile, shiftOp_linenum, shiftOp ):
  236. """
  237. Write an XCOMMENT record to outputFile
  238. """
  239. comment = "%s @%d\0" % (shiftOp, shiftOp_linenum) # \0 is terminating nul
  240. ba = bytearray(1)
  241. ba[0] = XCOMMENT
  242. ba += comment.encode()
  243. outputFile.write( ba )
  244. def combineBitVectors( trailer, meat, header ):
  245. """
  246. Combine the 3 bit vectors comprizing a transmission. Since the least
  247. significant bits are sent first, the header is put onto the list last so
  248. they are sent first from that least significant position.
  249. """
  250. ret = bytearray()
  251. ret.extend( trailer )
  252. ret.extend( meat )
  253. ret.extend( header )
  254. return ret
  255. def writeRUNTEST( outputFile, run_state, end_state, run_count, min_time, tokenTxt ):
  256. """
  257. Write the output for the SVF RUNTEST command.
  258. run_count - the number of clocks
  259. min_time - the number of seconds
  260. tokenTxt - either RUNTEST or LDELAY
  261. """
  262. # convert from secs to usecs
  263. min_time = int( min_time * 1000000)
  264. # the SVF RUNTEST command does NOT map to the XSVF XRUNTEST command. Check the SVF spec, then
  265. # read the XSVF command. They are not the same. Use an XSVF XWAITSTATE to
  266. # implement the required behavior of the SVF RUNTEST command.
  267. if doCOMMENTs:
  268. writeComment( output, tokLn, tokenTxt )
  269. if tokenTxt == 'RUNTEST':
  270. obuf = bytearray(11)
  271. obuf[0] = XWAITSTATE
  272. obuf[1] = run_state
  273. obuf[2] = end_state
  274. struct.pack_into(">i", obuf, 3, run_count ) # big endian 4 byte int to obuf
  275. struct.pack_into(">i", obuf, 7, min_time ) # big endian 4 byte int to obuf
  276. outputFile.write( obuf )
  277. else: # == 'LDELAY'
  278. obuf = bytearray(10)
  279. obuf[0] = LDELAY
  280. obuf[1] = run_state
  281. # LDELAY has no end_state
  282. struct.pack_into(">i", obuf, 2, run_count ) # big endian 4 byte int to obuf
  283. struct.pack_into(">i", obuf, 6, min_time ) # big endian 4 byte int to obuf
  284. outputFile.write( obuf )
  285. output = open( outputFilename, mode='wb' )
  286. hir = MASKSET('HIR')
  287. hdr = MASKSET('HDR')
  288. tir = MASKSET('TIR')
  289. tdr = MASKSET('TDR')
  290. sir = MASKSET('SIR')
  291. sdr = MASKSET('SDR')
  292. expecting_eof = True
  293. # one of the commands that take the shiftParts after the length, the parse
  294. # template for all of these commands is identical
  295. shiftOps = ('SDR', 'SIR', 'LSDR', 'HDR', 'HIR', 'TDR', 'TIR')
  296. # the order must correspond to shiftOps, this holds the MASKSETS. 'LSDR' shares sdr with 'SDR'
  297. shiftSets = (sdr, sir, sdr, hdr, hir, tdr, tir )
  298. # what to expect as parameters to a shiftOp, i.e. after a SDR length or SIR length
  299. shiftParts = ('TDI', 'TDO', 'MASK', 'SMASK')
  300. # the set of legal states which can trail the RUNTEST command
  301. run_state_allowed = ('IRPAUSE', 'DRPAUSE', 'RESET', 'IDLE')
  302. enddr_state_allowed = ('DRPAUSE', 'IDLE')
  303. endir_state_allowed = ('IRPAUSE', 'IDLE')
  304. trst_mode_allowed = ('ON', 'OFF', 'Z', 'ABSENT')
  305. enddr_state = IDLE
  306. endir_state = IDLE
  307. frequency = 1.00e+006 # HZ;
  308. # change detection for xsdrsize and xtdomask
  309. xsdrsize = -1 # the last one sent, send only on change
  310. xtdomask = bytearray() # the last one sent, send only on change
  311. # we use a number of single byte writes for the XSVF command below
  312. cmdbuf = bytearray(1)
  313. # Save the XREPEAT setting into the file as first thing.
  314. obuf = bytearray(2)
  315. obuf[0] = XREPEAT
  316. obuf[1] = xrepeat
  317. output.write( obuf )
  318. try:
  319. while 1:
  320. expecting_eof = True
  321. nextTok()
  322. expecting_eof = False
  323. # print( tokType, tokVal, tokLn )
  324. if tokVal in shiftOps:
  325. shiftOp_linenum = tokLn
  326. shiftOp = tokVal
  327. set = shiftSets[shiftOps.index(shiftOp)]
  328. # set flags false, if we see one later, set that one true later
  329. sawTDI = sawTDO = sawMASK = sawSMASK = False
  330. nextTok()
  331. if tokType != 'int':
  332. raise ParseError( tokLn, tokVal, "Expecting 'int' giving %s length, got '%s'" % (shiftOp, tokType) )
  333. length = tokVal
  334. nextTok()
  335. while tokVal != ';':
  336. if tokVal not in shiftParts:
  337. raise ParseError( tokLn, tokVal, "Expecting TDI, TDO, MASK, SMASK, or ';'")
  338. shiftPart = tokVal
  339. nextTok()
  340. if tokType != 'hex':
  341. raise ParseError( tokLn, tokVal, "Expecting hex bits" )
  342. bits = makeBitArray( tokVal, length )
  343. if shiftPart == 'TDI':
  344. sawTDI = True
  345. set.tdi = bits
  346. elif shiftPart == 'TDO':
  347. sawTDO = True
  348. set.tdo = bits
  349. elif shiftPart == 'MASK':
  350. sawMASK = True
  351. set.mask = bits
  352. elif shiftPart == 'SMASK':
  353. sawSMASK = True
  354. set.smask = bits
  355. nextTok()
  356. set.syncLengths( sawTDI, sawTDO, sawMASK, sawSMASK, length )
  357. # process all the gathered parameters and generate outputs here
  358. if shiftOp == 'SIR':
  359. if doCOMMENTs:
  360. writeComment( output, shiftOp_linenum, 'SIR' )
  361. tdi = combineBitVectors( tir.tdi, sir.tdi, hir.tdi )
  362. if len(tdi) > 255:
  363. obuf = bytearray(3)
  364. obuf[0] = XSIR2
  365. struct.pack_into( ">h", obuf, 1, len(tdi) )
  366. else:
  367. obuf = bytearray(2)
  368. obuf[0] = XSIR
  369. obuf[1] = len(tdi)
  370. output.write( obuf )
  371. obuf = makeXSVFbytes( tdi )
  372. output.write( obuf )
  373. elif shiftOp == 'SDR':
  374. if doCOMMENTs:
  375. writeComment( output, shiftOp_linenum, shiftOp )
  376. if not sawTDO:
  377. # pass a zero filled bit vector for the sdr.mask
  378. mask = combineBitVectors( tdr.mask, bytearray(sdr.size), hdr.mask )
  379. tdi = combineBitVectors( tdr.tdi, sdr.tdi, hdr.tdi )
  380. if xsdrsize != len(tdi):
  381. xsdrsize = len(tdi)
  382. cmdbuf[0] = XSDRSIZE
  383. output.write( cmdbuf )
  384. obuf = bytearray(4)
  385. struct.pack_into( ">i", obuf, 0, xsdrsize ) # big endian 4 byte int to obuf
  386. output.write( obuf )
  387. if xtdomask != mask:
  388. xtdomask = mask
  389. cmdbuf[0] = XTDOMASK
  390. output.write( cmdbuf )
  391. obuf = makeXSVFbytes( mask )
  392. output.write( obuf )
  393. cmdbuf[0] = XSDR
  394. output.write( cmdbuf )
  395. obuf = makeXSVFbytes( tdi )
  396. output.write( obuf )
  397. else:
  398. mask = combineBitVectors( tdr.mask, sdr.mask, hdr.mask )
  399. tdi = combineBitVectors( tdr.tdi, sdr.tdi, hdr.tdi )
  400. tdo = combineBitVectors( tdr.tdo, sdr.tdo, hdr.tdo )
  401. if xsdrsize != len(tdi):
  402. xsdrsize = len(tdi)
  403. cmdbuf[0] = XSDRSIZE
  404. output.write( cmdbuf )
  405. obuf = bytearray(4)
  406. struct.pack_into(">i", obuf, 0, xsdrsize ) # big endian 4 byte int to obuf
  407. output.write( obuf )
  408. if xtdomask != mask:
  409. xtdomask = mask
  410. cmdbuf[0] = XTDOMASK
  411. output.write( cmdbuf )
  412. obuf = makeXSVFbytes( mask )
  413. output.write( obuf )
  414. cmdbuf[0] = XSDRTDO
  415. output.write( cmdbuf )
  416. obuf = makeXSVFbytes( tdi )
  417. output.write( obuf )
  418. obuf = makeXSVFbytes( tdo )
  419. output.write( obuf )
  420. #print( "len(tdo)=", len(tdo), "len(tdr.tdo)=", len(tdr.tdo), "len(sdr.tdo)=", len(sdr.tdo), "len(hdr.tdo)=", len(hdr.tdo) )
  421. elif shiftOp == 'LSDR':
  422. if doCOMMENTs:
  423. writeComment( output, shiftOp_linenum, shiftOp )
  424. mask = combineBitVectors( tdr.mask, sdr.mask, hdr.mask )
  425. tdi = combineBitVectors( tdr.tdi, sdr.tdi, hdr.tdi )
  426. tdo = combineBitVectors( tdr.tdo, sdr.tdo, hdr.tdo )
  427. if xsdrsize != len(tdi):
  428. xsdrsize = len(tdi)
  429. cmdbuf[0] = XSDRSIZE
  430. output.write( cmdbuf )
  431. obuf = bytearray(4)
  432. struct.pack_into(">i", obuf, 0, xsdrsize ) # big endian 4 byte int to obuf
  433. output.write( obuf )
  434. if xtdomask != mask:
  435. xtdomask = mask
  436. cmdbuf[0] = XTDOMASK
  437. output.write( cmdbuf )
  438. obuf = makeXSVFbytes( mask )
  439. output.write( obuf )
  440. cmdbuf[0] = LSDR
  441. output.write( cmdbuf )
  442. obuf = makeXSVFbytes( tdi )
  443. output.write( obuf )
  444. obuf = makeXSVFbytes( tdo )
  445. output.write( obuf )
  446. #print( "len(tdo)=", len(tdo), "len(tdr.tdo)=", len(tdr.tdo), "len(sdr.tdo)=", len(sdr.tdo), "len(hdr.tdo)=", len(hdr.tdo) )
  447. elif tokVal == 'RUNTEST' or tokVal == 'LDELAY':
  448. # e.g. from lattice tools:
  449. # "RUNTEST IDLE 5 TCK 1.00E-003 SEC;"
  450. saveTok = tokVal
  451. nextTok()
  452. min_time = 0
  453. run_count = 0
  454. max_time = 600 # ten minutes
  455. if tokVal in run_state_allowed:
  456. run_state = StateTxt.index(tokVal)
  457. end_state = run_state # bottom of page 17 of SVF spec
  458. nextTok()
  459. if tokType != 'int' and tokType != 'float':
  460. raise ParseError( tokLn, tokVal, "Expecting 'int' or 'float' after RUNTEST [run_state]")
  461. timeval = tokVal;
  462. nextTok()
  463. if tokVal != 'TCK' and tokVal != 'SEC' and tokVal != 'SCK':
  464. raise ParseError( tokLn, tokVal, "Expecting 'TCK' or 'SEC' or 'SCK' after RUNTEST [run_state] (run_count|min_time)")
  465. if tokVal == 'TCK' or tokVal == 'SCK':
  466. run_count = int( timeval )
  467. else:
  468. min_time = timeval
  469. nextTok()
  470. if tokType == 'int' or tokType == 'float':
  471. min_time = tokVal
  472. nextTok()
  473. if tokVal != 'SEC':
  474. raise ParseError( tokLn, tokVal, "Expecting 'SEC' after RUNTEST [run_state] run_count min_time")
  475. nextTok()
  476. if tokVal == 'MAXIMUM':
  477. nextTok()
  478. if tokType != 'int' and tokType != 'float':
  479. raise ParseError( tokLn, tokVal, "Expecting 'max_time' after RUNTEST [run_state] min_time SEC MAXIMUM")
  480. max_time = tokVal
  481. nextTok()
  482. if tokVal != 'SEC':
  483. raise ParseError( tokLn, tokVal, "Expecting 'max_time' after RUNTEST [run_state] min_time SEC MAXIMUM max_time")
  484. nextTok()
  485. if tokVal == 'ENDSTATE':
  486. nextTok()
  487. if tokVal not in run_state_allowed:
  488. raise ParseError( tokLn, tokVal, "Expecting 'run_state' after RUNTEST .... ENDSTATE")
  489. end_state = StateTxt.index(tokVal)
  490. nextTok()
  491. if tokVal != ';':
  492. raise ParseError( tokLn, tokVal, "Expecting ';' after RUNTEST ....")
  493. # print( "run_count=", run_count, "min_time=", min_time,
  494. # "max_time=", max_time, "run_state=", State[run_state], "end_state=", State[end_state] )
  495. writeRUNTEST( output, run_state, end_state, run_count, min_time, saveTok )
  496. elif tokVal == 'LCOUNT':
  497. nextTok()
  498. if tokType != 'int':
  499. raise ParseError( tokLn, tokVal, "Expecting integer 'count' after LCOUNT")
  500. loopCount = tokVal
  501. nextTok()
  502. if tokVal != ';':
  503. raise ParseError( tokLn, tokVal, "Expecting ';' after LCOUNT count")
  504. if doCOMMENTs:
  505. writeComment( output, tokLn, 'LCOUNT' )
  506. obuf = bytearray(5)
  507. obuf[0] = LCOUNT
  508. struct.pack_into(">i", obuf, 1, loopCount ) # big endian 4 byte int to obuf
  509. output.write( obuf )
  510. elif tokVal == 'ENDDR':
  511. nextTok()
  512. if tokVal not in enddr_state_allowed:
  513. raise ParseError( tokLn, tokVal, "Expecting 'stable_state' after ENDDR. (one of: DRPAUSE, IDLE)")
  514. enddr_state = StateTxt.index(tokVal)
  515. nextTok()
  516. if tokVal != ';':
  517. raise ParseError( tokLn, tokVal, "Expecting ';' after ENDDR stable_state")
  518. if doCOMMENTs:
  519. writeComment( output, tokLn, 'ENDDR' )
  520. obuf = bytearray(2)
  521. obuf[0] = XENDDR
  522. # Page 10 of the March 1999 SVF spec shows that RESET is also allowed here.
  523. # Yet the XSVF spec has no provision for that, and uses a non-standard, i.e.
  524. # boolean argument to XENDDR which only handles two of the 3 intended states.
  525. obuf[1] = 1 if enddr_state == DRPAUSE else 0
  526. output.write( obuf )
  527. elif tokVal == 'ENDIR':
  528. nextTok()
  529. if tokVal not in endir_state_allowed:
  530. raise ParseError( tokLn, tokVal, "Expecting 'stable_state' after ENDIR. (one of: IRPAUSE, IDLE)")
  531. endir_state = StateTxt.index(tokVal)
  532. nextTok()
  533. if tokVal != ';':
  534. raise ParseError( tokLn, tokVal, "Expecting ';' after ENDIR stable_state")
  535. if doCOMMENTs:
  536. writeComment( output, tokLn, 'ENDIR' )
  537. obuf = bytearray(2)
  538. obuf[0] = XENDIR
  539. # Page 10 of the March 1999 SVF spec shows that RESET is also allowed here.
  540. # Yet the XSVF spec has no provision for that, and uses a non-standard, i.e.
  541. # boolean argument to XENDDR which only handles two of the 3 intended states.
  542. obuf[1] = 1 if endir_state == IRPAUSE else 0
  543. output.write( obuf )
  544. elif tokVal == 'STATE':
  545. nextTok()
  546. ln = tokLn
  547. while tokVal != ';':
  548. if tokVal not in StateTxt:
  549. raise ParseError( tokLn, tokVal, "Expecting 'stable_state' after STATE")
  550. stable_state = StateTxt.index( tokVal )
  551. if doCOMMENTs and ln != -1:
  552. writeComment( output, ln, 'STATE' )
  553. ln = -1 # save comment only once
  554. obuf = bytearray(2)
  555. obuf[0] = XSTATE
  556. obuf[1] = stable_state
  557. output.write( obuf )
  558. nextTok()
  559. elif tokVal == 'FREQUENCY':
  560. nextTok()
  561. if tokVal != ';':
  562. if tokType != 'int' and tokType != 'float':
  563. raise ParseError( tokLn, tokVal, "Expecting 'cycles HZ' after FREQUENCY")
  564. frequency = tokVal
  565. nextTok()
  566. if tokVal != 'HZ':
  567. raise ParseError( tokLn, tokVal, "Expecting 'HZ' after FREQUENCY cycles")
  568. nextTok()
  569. if tokVal != ';':
  570. raise ParseError( tokLn, tokVal, "Expecting ';' after FREQUENCY cycles HZ")
  571. elif tokVal == 'TRST':
  572. nextTok()
  573. if tokVal not in trst_mode_allowed:
  574. raise ParseError( tokLn, tokVal, "Expecting 'ON|OFF|Z|ABSENT' after TRST")
  575. trst_mode = tokVal
  576. nextTok()
  577. if tokVal != ';':
  578. raise ParseError( tokLn, tokVal, "Expecting ';' after TRST trst_mode")
  579. if doCOMMENTs:
  580. writeComment( output, tokLn, 'TRST %s' % trst_mode )
  581. obuf = bytearray( 2 )
  582. obuf[0] = XTRST
  583. obuf[1] = trst_mode_allowed.index( trst_mode ) # use the index as the binary argument to XTRST opcode
  584. output.write( obuf )
  585. else:
  586. raise ParseError( tokLn, tokVal, "Unknown token '%s'" % tokVal)
  587. except StopIteration:
  588. if not expecting_eof:
  589. print( "Unexpected End of File at line ", tokLn )
  590. except ParseError as pe:
  591. print( "\n", pe )
  592. finally:
  593. # print( "closing file" )
  594. cmdbuf[0] = XCOMPLETE
  595. output.write( cmdbuf )
  596. output.close()