instructions.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package tengo
  2. import (
  3. "fmt"
  4. "github.com/d5/tengo/v2/parser"
  5. )
  6. // MakeInstruction returns a bytecode for an opcode and the operands.
  7. func MakeInstruction(opcode parser.Opcode, operands ...int) []byte {
  8. numOperands := parser.OpcodeOperands[opcode]
  9. totalLen := 1
  10. for _, w := range numOperands {
  11. totalLen += w
  12. }
  13. instruction := make([]byte, totalLen)
  14. instruction[0] = opcode
  15. offset := 1
  16. for i, o := range operands {
  17. width := numOperands[i]
  18. switch width {
  19. case 1:
  20. instruction[offset] = byte(o)
  21. case 2:
  22. n := uint16(o)
  23. instruction[offset] = byte(n >> 8)
  24. instruction[offset+1] = byte(n)
  25. }
  26. offset += width
  27. }
  28. return instruction
  29. }
  30. // FormatInstructions returns string representation of bytecode instructions.
  31. func FormatInstructions(b []byte, posOffset int) []string {
  32. var out []string
  33. i := 0
  34. for i < len(b) {
  35. numOperands := parser.OpcodeOperands[b[i]]
  36. operands, read := parser.ReadOperands(numOperands, b[i+1:])
  37. switch len(numOperands) {
  38. case 0:
  39. out = append(out, fmt.Sprintf("%04d %-7s",
  40. posOffset+i, parser.OpcodeNames[b[i]]))
  41. case 1:
  42. out = append(out, fmt.Sprintf("%04d %-7s %-5d",
  43. posOffset+i, parser.OpcodeNames[b[i]], operands[0]))
  44. case 2:
  45. out = append(out, fmt.Sprintf("%04d %-7s %-5d %-5d",
  46. posOffset+i, parser.OpcodeNames[b[i]],
  47. operands[0], operands[1]))
  48. }
  49. i += 1 + read
  50. }
  51. return out
  52. }