github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/equity/compiler/optimize.go (about)

     1  package compiler
     2  
     3  import "strings"
     4  
     5  var optimizations = []struct {
     6  	before, after string
     7  }{
     8  	{"0 ROLL", ""},
     9  	{"0 PICK", "DUP"},
    10  	{"1 ROLL", "SWAP"},
    11  	{"1 PICK", "OVER"},
    12  	{"2 ROLL", "ROT"},
    13  	{"TRUE VERIFY", ""},
    14  	{"SWAP SWAP", ""},
    15  	{"OVER OVER", "2DUP"},
    16  	{"SWAP OVER", "TUCK"},
    17  	{"DROP DROP", "2DROP"},
    18  	{"SWAP DROP", "NIP"},
    19  	{"5 ROLL 5 ROLL", "2ROT"},
    20  	{"3 PICK 3 PICK", "2OVER"},
    21  	{"3 ROLL 3 ROLL", "2SWAP"},
    22  	{"2 PICK 2 PICK 2 PICK", "3DUP"},
    23  	{"1 ADD", "1ADD"},
    24  	{"1 SUB", "1SUB"},
    25  	{"EQUAL VERIFY", "EQUALVERIFY"},
    26  	{"SWAP TXSIGHASH ROT", "TXSIGHASH SWAP"},
    27  	{"SWAP EQUAL", "EQUAL"},
    28  	{"SWAP EQUALVERIFY", "EQUALVERIFY"},
    29  	{"SWAP ADD", "ADD"},
    30  	{"SWAP BOOLAND", "BOOLAND"},
    31  	{"SWAP BOOLOR", "BOOLOR"},
    32  	{"SWAP MIN", "MIN"},
    33  	{"SWAP MAX", "MAX"},
    34  	{"DUP 2 PICK EQUAL", "2DUP EQUAL"},
    35  	{"DUP 2 PICK EQUALVERIFY", "2DUP EQUALVERIFY"},
    36  	{"DUP 2 PICK ADD", "2DUP ADD"},
    37  	{"DUP 2 PICK BOOLAND", "2DUP BOOLAND"},
    38  	{"DUP 2 PICK BOOLOR", "2DUP BOOLOR"},
    39  	{"DUP 2 PICK MIN", "2DUP MIN"},
    40  	{"DUP 2 PICK MAX", "2DUP MAX"},
    41  }
    42  
    43  func optimize(opcodes string) string {
    44  	opcodes = " " + opcodes + " "
    45  	looping := true
    46  	for looping {
    47  		looping = false
    48  		for _, o := range optimizations {
    49  			before := " " + o.before + " "
    50  			var after string
    51  			if o.after == "" {
    52  				after = " "
    53  			} else {
    54  				after = " " + o.after + " "
    55  			}
    56  			newOpcodes := strings.Replace(opcodes, before, after, -1)
    57  			if newOpcodes != opcodes {
    58  				looping = true
    59  				opcodes = newOpcodes
    60  			}
    61  		}
    62  	}
    63  	return strings.TrimSpace(opcodes)
    64  }