Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import os
  3. import sys
  4.  
  5. instruction_set = [ 'live', 'ld', 'st', 'add', 'sub',
  6. 'and', 'or', 'xor', 'zjmp', 'ldi', 'sti',
  7. 'fork', 'lld', 'lldi', 'lfork', 'aff']
  8.  
  9. class CorewarException(BaseException):
  10. msg = None
  11. def __init__(self, msg):
  12. self.msg = msg
  13.  
  14. def asm(args):
  15. args = args.replace(',', ' ').replace(' ', ' ').split(' ')
  16. if not args[0] in instruction_set:
  17. raise CorewarException('Unknown instruction \'%s\'' % args[0])
  18. out = ['%02x' % (instruction_set.index(args[0]) + 1)]
  19. enc = ''
  20. for i,arg in enumerate(args[1:]):
  21. if arg[0] == 'r':
  22. try:
  23. register = int(arg[1:])
  24. if register < 1:
  25. raise ValueError()
  26. except ValueError:
  27. raise CorewarException('Invalid register number (argument %d)' % (i + 1))
  28. out.append('%02x' % register)
  29. enc += '01'
  30. elif arg[0] == '%':
  31. try:
  32. direct = int(arg[1:])
  33. except ValueError:
  34. raise CorewarException('Invalid direct value (argument %d)' % (i + 1))
  35. if not -0x80000000 <= direct <= 0x7fffffff:
  36. raise CorewarException('Direct value exceeds 32-bit limits (argument %d)' % (i + 1))
  37. direct &= 0xffffffff
  38. for k in reversed(range(4)):
  39. out.append('%02x' % ((direct >> (k*8)) & 0xff))
  40. enc += '10'
  41. else:
  42. try:
  43. indirect = int(arg)
  44. except ValueError:
  45. raise CorewarException('Invalid indirect value (argument %d)' % (i + 1))
  46. if not -0x8000 <= indirect <= 0x7fff:
  47. raise CorewarException('Indirect value exceeds 16-bit limits (argument %d)' % (i + 1))
  48. indirect &= 0xffff
  49. for k in reversed(range(2)):
  50. out.append('%02x' % ((indirect >> (k*8)) & 0xff))
  51. enc += '11'
  52. enc += '0' * max(0, 8 - len(enc))
  53. if not args[0] in ['live', 'fork', 'lfork', 'zjmp']:
  54. out.insert(1, '%02x' % int(enc, 2))
  55. return (' '.join(out))
  56.  
  57. def smartinput(prompt=''):
  58. if os.isatty(0):
  59. print(prompt, end='', flush='True')
  60. for line in sys.stdin:
  61. if line:
  62. return line.replace('\n', '')
  63. return None
  64.  
  65. def main(args):
  66. if len(args) < 2:
  67. while True:
  68. line = smartinput('> ')
  69. if line is None:
  70. if os.isatty(0):
  71. print()
  72. return 0
  73. if line:
  74. try:
  75. print(asm(line))
  76. except CorewarException as ex:
  77. print(ex.msg, file=sys.stderr)
  78. else:
  79. try:
  80. print(asm(' '.join(args[1:])))
  81. except CorewarException as ex:
  82. print(ex.msg, file=sys.stderr)
  83. return 1
  84. return 0
  85.  
  86. if __name__ == '__main__':
  87. exit(main(sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement