OSDN Git Service

add if-else statement (#7)
[bytom/equity.git] / compiler / compile.go
1 package compiler
2
3 import (
4         "encoding/json"
5         "fmt"
6         "io"
7         "io/ioutil"
8         "strings"
9
10         chainjson "github.com/bytom/encoding/json"
11         "github.com/bytom/errors"
12         "github.com/bytom/protocol/vm"
13         "github.com/bytom/protocol/vm/vmutil"
14 )
15
16 // ValueInfo describes how a blockchain value is used in a contract
17 // clause.
18 type ValueInfo struct {
19         // Name is the clause's name for this value.
20         Name string `json:"name"`
21
22         // Program is the program expression used to the lock the value, if
23         // the value is locked with "lock." If it's unlocked with "unlock"
24         // instead, this is empty.
25         Program string `json:"program,omitempty"`
26
27         // Asset is the expression describing the asset type the value must
28         // have, as it appears in a clause's "requires" section. If this is
29         // the contract value instead, this is empty.
30         Asset string `json:"asset,omitempty"`
31
32         // Amount is the expression describing the amount the value must
33         // have, as it appears in a clause's "requires" section. If this is
34         // the contract value instead, this is empty.
35         Amount string `json:"amount,omitempty"`
36 }
37
38 // ContractArg is an argument with which to instantiate a contract as
39 // a program. Exactly one of B, I, and S should be supplied.
40 type ContractArg struct {
41         B *bool               `json:"boolean,omitempty"`
42         I *int64              `json:"integer,omitempty"`
43         S *chainjson.HexBytes `json:"string,omitempty"`
44 }
45
46 // Compile parses a sequence of Equity contracts from the supplied reader
47 // and produces Contract objects containing the compiled bytecode and
48 // other analysis. If argMap is non-nil, it maps contract names to
49 // lists of arguments with which to instantiate them as programs, with
50 // the results placed in the contract's Program field. A contract
51 // named in argMap but not found in the input is silently ignored.
52 func Compile(r io.Reader) ([]*Contract, error) {
53         inp, err := ioutil.ReadAll(r)
54         if err != nil {
55                 return nil, errors.Wrap(err, "reading input")
56         }
57         contracts, err := parse(inp)
58         if err != nil {
59                 return nil, errors.Wrap(err, "parse error")
60         }
61
62         globalEnv := newEnviron(nil)
63         for _, k := range keywords {
64                 globalEnv.add(k, nilType, roleKeyword)
65         }
66         for _, b := range builtins {
67                 globalEnv.add(b.name, nilType, roleBuiltin)
68         }
69
70         // All contracts must be checked for recursiveness before any are
71         // compiled.
72         for _, contract := range contracts {
73                 contract.Recursive = checkRecursive(contract)
74         }
75
76         for _, contract := range contracts {
77                 err = globalEnv.addContract(contract)
78                 if err != nil {
79                         return nil, err
80                 }
81         }
82
83         for _, contract := range contracts {
84                 err = compileContract(contract, globalEnv)
85                 if err != nil {
86                         return nil, errors.Wrap(err, "compiling contract")
87                 }
88                 for _, clause := range contract.Clauses {
89                         for _, stmt := range clause.statements {
90                                 switch s := stmt.(type) {
91                                 case *lockStatement:
92                                         valueInfo := ValueInfo{
93                                                 Amount:  s.lockedAmount.String(),
94                                                 Asset:   s.lockedAsset.String(),
95                                                 Program: s.program.String(),
96                                         }
97
98                                         clause.Values = append(clause.Values, valueInfo)
99                                 case *unlockStatement:
100                                         valueInfo := ValueInfo{
101                                                 Amount: contract.Value.Amount,
102                                                 Asset:  contract.Value.Asset,
103                                         }
104                                         clause.Values = append(clause.Values, valueInfo)
105                                 }
106                         }
107                 }
108         }
109
110         return contracts, nil
111 }
112
113 func Instantiate(body []byte, params []*Param, recursive bool, args []ContractArg) ([]byte, error) {
114         if len(args) != len(params) {
115                 return nil, fmt.Errorf("got %d argument(s), want %d", len(args), len(params))
116         }
117
118         // typecheck args against param types
119         for i, param := range params {
120                 arg := args[i]
121                 switch param.Type {
122                 case amountType, intType:
123                         if arg.I == nil {
124                                 return nil, fmt.Errorf("type mismatch in arg %d (want integer)", i)
125                         }
126                 case assetType, hashType, progType, pubkeyType, sigType, strType:
127                         if arg.S == nil {
128                                 return nil, fmt.Errorf("type mismatch in arg %d (want string)", i)
129                         }
130                 case boolType:
131                         if arg.B == nil {
132                                 return nil, fmt.Errorf("type mismatch in arg %d (want boolean)", i)
133                         }
134                 }
135         }
136
137         b := vmutil.NewBuilder()
138
139         for i := len(args) - 1; i >= 0; i-- {
140                 a := args[i]
141                 switch {
142                 case a.B != nil:
143                         var n int64
144                         if *a.B {
145                                 n = 1
146                         }
147                         b.AddInt64(n)
148                 case a.I != nil:
149                         b.AddInt64(*a.I)
150                 case a.S != nil:
151                         b.AddData(*a.S)
152                 }
153         }
154
155         if recursive {
156                 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
157                 b.AddData(body)
158                 b.AddOp(vm.OP_DEPTH).AddOp(vm.OP_OVER)
159         } else {
160                 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
161                 b.AddOp(vm.OP_DEPTH)
162                 b.AddData(body)
163         }
164         b.AddInt64(0)
165         b.AddOp(vm.OP_CHECKPREDICATE)
166         return b.Build()
167 }
168
169 func compileContract(contract *Contract, globalEnv *environ) error {
170         var err error
171
172         if len(contract.Clauses) == 0 {
173                 return fmt.Errorf("empty contract")
174         }
175         env := newEnviron(globalEnv)
176         for _, p := range contract.Params {
177                 err = env.add(p.Name, p.Type, roleContractParam)
178                 if err != nil {
179                         return err
180                 }
181         }
182
183         // value is spilt with valueAmount and valueAsset
184         if err = env.add(contract.Value.Amount, amountType, roleContractValue); err != nil {
185                 return err
186         }
187         if err = env.add(contract.Value.Asset, assetType, roleContractValue); err != nil {
188                 return err
189         }
190
191         for _, c := range contract.Clauses {
192                 err = env.add(c.Name, nilType, roleClause)
193                 if err != nil {
194                         return err
195                 }
196         }
197
198         err = prohibitSigParams(contract)
199         if err != nil {
200                 return err
201         }
202         err = requireAllParamsUsedInClauses(contract.Params, contract.Clauses)
203         if err != nil {
204                 return err
205         }
206
207         var stk stack
208
209         if len(contract.Clauses) > 1 {
210                 stk = stk.add("<clause selector>")
211         }
212
213         for i := len(contract.Params) - 1; i >= 0; i-- {
214                 p := contract.Params[i]
215                 stk = stk.add(p.Name)
216         }
217
218         if contract.Recursive {
219                 stk = stk.add(contract.Name)
220         }
221
222         b := &builder{}
223         sequence := 0 // sequence is used to count the number of ifStatements
224
225         if len(contract.Clauses) == 1 {
226                 err = compileClause(b, stk, contract, env, contract.Clauses[0], &sequence)
227                 if err != nil {
228                         return err
229                 }
230         } else {
231                 if len(contract.Params) > 0 {
232                         // A clause selector is at the bottom of the stack. Roll it to the
233                         // top.
234                         n := len(contract.Params)
235                         if contract.Recursive {
236                                 n++
237                         }
238                         stk = b.addRoll(stk, n) // stack: [<clause params> <contract params> [<maybe contract body>] <clause selector>]
239                 }
240
241                 var stk2 stack
242
243                 // clauses 2..N-1
244                 for i := len(contract.Clauses) - 1; i >= 2; i-- {
245                         stk = b.addDup(stk)                                                   // stack: [... <clause selector> <clause selector>]
246                         stk = b.addInt64(stk, int64(i))                                       // stack: [... <clause selector> <clause selector> <i>]
247                         stk = b.addNumEqual(stk, fmt.Sprintf("(<clause selector> == %d)", i)) // stack: [... <clause selector> <i == clause selector>]
248                         stk = b.addJumpIf(stk, contract.Clauses[i].Name)                      // stack: [... <clause selector>]
249                         stk2 = stk                                                            // stack starts here for clauses 2 through N-1
250                 }
251
252                 // clause 1
253                 stk = b.addJumpIf(stk, contract.Clauses[1].Name) // consumes the clause selector
254
255                 // no jump needed for clause 0
256
257                 for i, clause := range contract.Clauses {
258                         if i > 1 {
259                                 // Clauses 0 and 1 have no clause selector on top of the
260                                 // stack. Clauses 2 and later do.
261                                 stk = stk2
262                         }
263
264                         b.addJumpTarget(stk, clause.Name)
265
266                         if i > 1 {
267                                 stk = b.addDrop(stk)
268                         }
269
270                         err = compileClause(b, stk, contract, env, clause, &sequence)
271                         if err != nil {
272                                 return errors.Wrapf(err, "compiling clause \"%s\"", clause.Name)
273                         }
274                         b.forgetPendingVerify()
275                         if i < len(contract.Clauses)-1 {
276                                 b.addJump(stk, "_end")
277                         }
278                 }
279                 b.addJumpTarget(stk, "_end")
280         }
281
282         opcodes := optimize(b.opcodes())
283         prog, err := vm.Assemble(opcodes)
284         if err != nil {
285                 return err
286         }
287
288         contract.Body = prog
289         contract.Opcodes = opcodes
290
291         contract.Steps = b.steps()
292
293         return nil
294 }
295
296 func compileClause(b *builder, contractStk stack, contract *Contract, env *environ, clause *Clause, sequence *int) error {
297         var err error
298
299         // copy env to leave outerEnv unchanged
300         env = newEnviron(env)
301         for _, p := range clause.Params {
302                 err = env.add(p.Name, p.Type, roleClauseParam)
303                 if err != nil {
304                         return err
305                 }
306         }
307         assignIndexes(clause)
308
309         var stk stack
310         for _, p := range clause.Params {
311                 // NOTE: the order of clause params is not reversed, unlike
312                 // contract params (and also unlike the arguments to Equity
313                 // function-calls).
314                 stk = stk.add(p.Name)
315         }
316         stk = stk.addFromStack(contractStk)
317
318         // a count of the number of times each variable is referenced
319         counts := make(map[string]int)
320         for _, s := range clause.statements {
321                 s.countVarRefs(counts)
322                 if stmt, ok := s.(*ifStatement); ok {
323                         for _, trueStmt := range stmt.body.trueBody {
324                                 trueStmt.countVarRefs(counts)
325                         }
326
327                         for _, falseStmt := range stmt.body.falseBody {
328                                 falseStmt.countVarRefs(counts)
329                         }
330                 }
331         }
332
333         for _, stat := range clause.statements {
334                 if stk, err = compileStatement(b, stk, contract, env, clause, counts, stat, sequence); err != nil {
335                         return err
336                 }
337         }
338
339         err = requireAllValuesDisposedOnce(contract, clause)
340         if err != nil {
341                 return err
342         }
343         err = typeCheckClause(contract, clause, env)
344         if err != nil {
345                 return err
346         }
347         err = requireAllParamsUsedInClause(clause.Params, clause)
348         if err != nil {
349                 return err
350         }
351
352         return nil
353 }
354
355 func compileStatement(b *builder, stk stack, contract *Contract, env *environ, clause *Clause, counts map[string]int, stat statement, sequence *int) (stack, error) {
356         var err error
357         switch stmt := stat.(type) {
358         case *ifStatement:
359                 // sequence add 1 when the statement is ifStatement
360                 *sequence++
361                 strSequence := fmt.Sprintf("%d", *sequence)
362
363                 // compile condition expression
364                 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.condition)
365                 if err != nil {
366                         return stk, errors.Wrapf(err, "in check condition of ifStatement in clause \"%s\"", clause.Name)
367                 }
368
369                 // jump to falseBody when condition is false, while the JUMPIF instruction will be run success when
370                 // the value of dataStack is true, therefore add this check
371                 conditionExpr := stk.str
372                 stk = b.addBoolean(stk, false)
373                 stk = b.addEqual(stk, fmt.Sprintf("(%s == false)", conditionExpr)) // stack: [... <condition_result == false>]
374
375                 // add label
376                 var label string
377                 if len(stmt.body.falseBody) != 0 {
378                         label = "else_" + strSequence
379                 } else {
380                         label = "endif_" + strSequence
381                 }
382                 stk = b.addJumpIf(stk, label)
383                 b.addJumpTarget(stk, "if_"+strSequence)
384
385                 // temporary store stack and counts for falseBody
386                 condStk := stk
387                 elseCounts := make(map[string]int)
388                 for k, v := range counts {
389                         elseCounts[k] = v
390                 }
391
392                 // compile trueBody statements
393                 if len(stmt.body.trueBody) != 0 {
394                         for _, st := range stmt.body.trueBody {
395                                 st.countVarRefs(counts)
396                         }
397
398                         for _, st := range stmt.body.trueBody {
399                                 if stk, err = compileStatement(b, stk, contract, env, clause, counts, st, sequence); err != nil {
400                                         return stk, err
401                                 }
402                         }
403                 }
404
405                 // compile falseBody statements
406                 if len(stmt.body.falseBody) != 0 {
407                         counts := make(map[string]int)
408                         for k, v := range elseCounts {
409                                 counts[k] = v
410                         }
411
412                         for _, st := range stmt.body.falseBody {
413                                 st.countVarRefs(counts)
414                         }
415
416                         stk = condStk
417                         b.addJump(stk, "endif_"+strSequence)
418                         b.addJumpTarget(stk, "else_"+strSequence)
419
420                         for _, st := range stmt.body.falseBody {
421                                 if stk, err = compileStatement(b, stk, contract, env, clause, counts, st, sequence); err != nil {
422                                         return stk, err
423                                 }
424                         }
425                 }
426                 b.addJumpTarget(stk, "endif_"+strSequence)
427
428         case *defineStatement:
429                 // variable
430                 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
431                 if err != nil {
432                         return stk, errors.Wrapf(err, "in define statement in clause \"%s\"", clause.Name)
433                 }
434
435                 // check variable type
436                 if stmt.expr.typ(env) != stmt.varName.Type {
437                         return stk, fmt.Errorf("expression in define statement in clause \"%s\" has type \"%s\", must be \"%s\"",
438                                 clause.Name, stmt.expr.typ(env), stmt.varName.Type)
439                 }
440
441                 // modify stack name
442                 stk.str = stmt.varName.Name
443
444                 // add environ for define variable
445                 if err = env.add(stmt.varName.Name, stmt.varName.Type, roleClauseVariable); err != nil {
446                         return stk, err
447                 }
448
449         case *verifyStatement:
450                 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
451                 if err != nil {
452                         return stk, errors.Wrapf(err, "in verify statement in clause \"%s\"", clause.Name)
453                 }
454                 stk = b.addVerify(stk)
455
456                 // special-case reporting of certain function calls
457                 if c, ok := stmt.expr.(*callExpr); ok && len(c.args) == 1 {
458                         if b := referencedBuiltin(c.fn); b != nil {
459                                 switch b.name {
460                                 case "below":
461                                         clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
462                                 case "above":
463                                         clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
464                                 }
465                         }
466                 }
467
468         case *lockStatement:
469                 // index
470                 stk = b.addInt64(stk, stmt.index)
471
472                 // TODO: permit more complex expressions for locked,
473                 // like "lock x+y with foo" (?)
474
475                 if stmt.lockedAmount.String() == contract.Value.Amount && stmt.lockedAsset.String() == contract.Value.Asset {
476                         stk = b.addAmount(stk, contract.Value.Amount)
477                         stk = b.addAsset(stk, contract.Value.Asset)
478                 } else {
479                         if strings.Contains(stmt.lockedAmount.String(), contract.Value.Amount) {
480                                 stk = b.addAmount(stk, contract.Value.Amount)
481                         }
482
483                         if strings.Contains(stmt.lockedAsset.String(), contract.Value.Asset) {
484                                 stk = b.addAsset(stk, contract.Value.Asset)
485                         }
486
487                         // amount
488                         stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAmount)
489                         if err != nil {
490                                 return stk, errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
491                         }
492
493                         // asset
494                         stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAsset)
495                         if err != nil {
496                                 return stk, errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
497                         }
498                 }
499
500                 // version
501                 stk = b.addInt64(stk, 1)
502
503                 // prog
504                 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.program)
505                 if err != nil {
506                         return stk, errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
507                 }
508
509                 stk = b.addCheckOutput(stk, fmt.Sprintf("checkOutput(%s, %s, %s)",
510                         stmt.lockedAmount.String(), stmt.lockedAsset.String(), stmt.program))
511                 stk = b.addVerify(stk)
512
513         case *unlockStatement:
514                 if len(clause.statements) == 1 {
515                         // This is the only statement in the clause, make sure TRUE is
516                         // on the stack.
517                         stk = b.addBoolean(stk, true)
518                 }
519         }
520
521         return stk, nil
522 }
523
524 func compileExpr(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, error) {
525         var err error
526
527         switch e := expr.(type) {
528         case *binaryExpr:
529                 // Do typechecking after compiling subexpressions (because other
530                 // compilation errors are more interesting than type mismatch
531                 // errors).
532
533                 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.left)
534                 if err != nil {
535                         return stk, errors.Wrapf(err, "in left operand of \"%s\" expression", e.op.op)
536                 }
537                 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.right)
538                 if err != nil {
539                         return stk, errors.Wrapf(err, "in right operand of \"%s\" expression", e.op.op)
540                 }
541
542                 lType := e.left.typ(env)
543                 if e.op.left != "" && !(lType == e.op.left || lType == amountType) {
544                         return stk, fmt.Errorf("in \"%s\", left operand has type \"%s\", must be \"%s\"", e, lType, e.op.left)
545                 }
546
547                 rType := e.right.typ(env)
548                 if e.op.right != "" && !(rType == e.op.right || rType == amountType) {
549                         return stk, fmt.Errorf("in \"%s\", right operand has type \"%s\", must be \"%s\"", e, rType, e.op.right)
550                 }
551
552                 switch e.op.op {
553                 case "==", "!=":
554                         if lType != rType {
555                                 // Maybe one is Hash and the other is (more-specific-Hash subtype).
556                                 // TODO(bobg): generalize this mechanism
557                                 if lType == hashType && isHashSubtype(rType) {
558                                         propagateType(contract, clause, env, rType, e.left)
559                                 } else if rType == hashType && isHashSubtype(lType) {
560                                         propagateType(contract, clause, env, lType, e.right)
561                                 } else {
562                                         return stk, fmt.Errorf("type mismatch in \"%s\": left operand has type \"%s\", right operand has type \"%s\"", e, lType, rType)
563                                 }
564                         }
565                         if lType == "Boolean" {
566                                 return stk, fmt.Errorf("in \"%s\": using \"%s\" on Boolean values not allowed", e, e.op.op)
567                         }
568                 }
569
570                 stk = b.addOps(stk.dropN(2), e.op.opcodes, e.String())
571
572         case *unaryExpr:
573                 // Do typechecking after compiling subexpression (because other
574                 // compilation errors are more interesting than type mismatch
575                 // errors).
576
577                 var err error
578                 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.expr)
579                 if err != nil {
580                         return stk, errors.Wrapf(err, "in \"%s\" expression", e.op.op)
581                 }
582
583                 if e.op.operand != "" && e.expr.typ(env) != e.op.operand {
584                         return stk, fmt.Errorf("in \"%s\", operand has type \"%s\", must be \"%s\"", e, e.expr.typ(env), e.op.operand)
585                 }
586                 b.addOps(stk.drop(), e.op.opcodes, e.String())
587
588         case *callExpr:
589                 bi := referencedBuiltin(e.fn)
590                 if bi == nil {
591                         if v, ok := e.fn.(varRef); ok {
592                                 if entry := env.lookup(string(v)); entry != nil && entry.t == contractType {
593                                         clause.Contracts = append(clause.Contracts, entry.c.Name)
594
595                                         partialName := fmt.Sprintf("%s(...)", v)
596                                         stk = b.addData(stk, nil)
597
598                                         if len(e.args) != len(entry.c.Params) {
599                                                 return stk, fmt.Errorf("contract \"%s\" expects %d argument(s), got %d", entry.c.Name, len(entry.c.Params), len(e.args))
600                                         }
601
602                                         for i := len(e.args) - 1; i >= 0; i-- {
603                                                 arg := e.args[i]
604                                                 if entry.c.Params[i].Type != "" && arg.typ(env) != entry.c.Params[i].Type {
605                                                         return stk, fmt.Errorf("argument %d to contract \"%s\" has type \"%s\", must be \"%s\"", i, entry.c.Name, arg.typ(env), entry.c.Params[i].Type)
606                                                 }
607                                                 stk, err = compileExpr(b, stk, contract, clause, env, counts, arg)
608                                                 if err != nil {
609                                                         return stk, err
610                                                 }
611                                                 stk = b.addCatPushdata(stk, partialName)
612                                         }
613
614                                         switch {
615                                         case entry.c == contract:
616                                                 // Recursive call - cannot use entry.c.Body
617                                                 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
618                                                 stk, err = compileRef(b, stk, counts, varRef(contract.Name))
619                                                 if err != nil {
620                                                         return stk, errors.Wrap(err, "compiling contract call")
621                                                 }
622                                                 stk = b.addCatPushdata(stk, partialName)
623                                                 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
624                                                 stk = b.addCat(stk, partialName)
625
626                                         case entry.c.Recursive:
627                                                 // Non-recursive call to a (different) recursive contract
628                                                 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
629                                                 if len(entry.c.Body) == 0 {
630                                                         // TODO(bobg): sort input contracts topologically to permit forward calling
631                                                         return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
632                                                 }
633                                                 stk = b.addData(stk, entry.c.Body)
634                                                 stk = b.addCatPushdata(stk, partialName)
635                                                 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
636                                                 stk = b.addCat(stk, partialName)
637
638                                         default:
639                                                 // Non-recursive call to non-recursive contract
640                                                 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
641                                                 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH)})
642                                                 stk = b.addCat(stk, partialName)
643                                                 if len(entry.c.Body) == 0 {
644                                                         // TODO(bobg): sort input contracts topologically to permit forward calling
645                                                         return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
646                                                 }
647                                                 stk = b.addData(stk, entry.c.Body)
648                                                 stk = b.addCatPushdata(stk, partialName)
649                                         }
650                                         stk = b.addData(stk, vm.Int64Bytes(0))
651                                         stk = b.addCatPushdata(stk, partialName)
652                                         stk = b.addData(stk, []byte{byte(vm.OP_CHECKPREDICATE)})
653                                         stk = b.addCat(stk, e.String())
654
655                                         return stk, nil
656                                 }
657                         }
658                         return stk, fmt.Errorf("unknown function \"%s\"", e.fn)
659                 }
660
661                 if len(e.args) != len(bi.args) {
662                         return stk, fmt.Errorf("wrong number of args for \"%s\": have %d, want %d", bi.name, len(e.args), len(bi.args))
663                 }
664
665                 // WARNING WARNING WOOP WOOP
666                 // special-case hack
667                 // WARNING WARNING WOOP WOOP
668                 if bi.name == "checkTxMultiSig" {
669                         if _, ok := e.args[0].(listExpr); !ok {
670                                 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 0", e.args[0])
671                         }
672                         if _, ok := e.args[1].(listExpr); !ok {
673                                 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 1", e.args[1])
674                         }
675
676                         var k1, k2 int
677
678                         stk, k1, err = compileArg(b, stk, contract, clause, env, counts, e.args[1])
679                         if err != nil {
680                                 return stk, err
681                         }
682
683                         // stack: [... sigM ... sig1 M]
684
685                         var altEntry string
686                         stk, altEntry = b.addToAltStack(stk) // stack: [... sigM ... sig1]
687                         stk = b.addTxSigHash(stk)            // stack: [... sigM ... sig1 txsighash]
688
689                         stk, k2, err = compileArg(b, stk, contract, clause, env, counts, e.args[0])
690                         if err != nil {
691                                 return stk, err
692                         }
693
694                         // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N]
695
696                         stk = b.addFromAltStack(stk, altEntry) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N M]
697                         stk = b.addSwap(stk)                   // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 M N]
698                         stk = b.addCheckMultisig(stk, k1+k2, e.String())
699
700                         return stk, nil
701                 }
702
703                 var k int
704
705                 for i := len(e.args) - 1; i >= 0; i-- {
706                         a := e.args[i]
707                         var k2 int
708                         var err error
709                         stk, k2, err = compileArg(b, stk, contract, clause, env, counts, a)
710                         if err != nil {
711                                 return stk, errors.Wrapf(err, "compiling argument %d in call expression", i)
712                         }
713                         k += k2
714                 }
715
716                 // Do typechecking after compiling subexpressions (because other
717                 // compilation errors are more interesting than type mismatch
718                 // errors).
719                 for i, actual := range e.args {
720                         if bi.args[i] != "" && actual.typ(env) != bi.args[i] {
721                                 return stk, fmt.Errorf("argument %d to \"%s\" has type \"%s\", must be \"%s\"", i, bi.name, actual.typ(env), bi.args[i])
722                         }
723                 }
724
725                 stk = b.addOps(stk.dropN(k), bi.opcodes, e.String())
726
727                 // special-case reporting
728                 switch bi.name {
729                 case "sha3", "sha256":
730                         clause.HashCalls = append(clause.HashCalls, HashCall{bi.name, e.args[0].String(), string(e.args[0].typ(env))})
731                 }
732
733         case varRef:
734                 return compileRef(b, stk, counts, e)
735
736         case integerLiteral:
737                 stk = b.addInt64(stk, int64(e))
738
739         case bytesLiteral:
740                 stk = b.addData(stk, []byte(e))
741
742         case booleanLiteral:
743                 stk = b.addBoolean(stk, bool(e))
744
745         case listExpr:
746                 // Lists are excluded here because they disobey the invariant of
747                 // this function: namely, that it increases the stack size by
748                 // exactly one. (A list pushes its items and its length on the
749                 // stack.) But they're OK as function-call arguments because the
750                 // function (presumably) consumes all the stack items added.
751                 return stk, fmt.Errorf("encountered list outside of function-call context")
752         }
753         return stk, nil
754 }
755
756 func compileArg(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, int, error) {
757         var n int
758         if list, ok := expr.(listExpr); ok {
759                 for i := 0; i < len(list); i++ {
760                         elt := list[len(list)-i-1]
761                         var err error
762                         stk, err = compileExpr(b, stk, contract, clause, env, counts, elt)
763                         if err != nil {
764                                 return stk, 0, err
765                         }
766                         n++
767                 }
768                 stk = b.addInt64(stk, int64(len(list)))
769                 n++
770                 return stk, n, nil
771         }
772         var err error
773         stk, err = compileExpr(b, stk, contract, clause, env, counts, expr)
774         return stk, 1, err
775 }
776
777 func compileRef(b *builder, stk stack, counts map[string]int, ref varRef) (stack, error) {
778         depth := stk.find(string(ref))
779         if depth < 0 {
780                 return stk, fmt.Errorf("undefined reference: \"%s\"", ref)
781         }
782
783         var isFinal bool
784         if count, ok := counts[string(ref)]; ok && count > 0 {
785                 count--
786                 counts[string(ref)] = count
787                 isFinal = count == 0
788         }
789
790         switch depth {
791         case 0:
792                 if !isFinal {
793                         stk = b.addDup(stk)
794                 }
795         case 1:
796                 if isFinal {
797                         stk = b.addSwap(stk)
798                 } else {
799                         stk = b.addOver(stk)
800                 }
801         default:
802                 if isFinal {
803                         stk = b.addRoll(stk, depth)
804                 } else {
805                         stk = b.addPick(stk, depth)
806                 }
807         }
808         return stk, nil
809 }
810
811 func (a *ContractArg) UnmarshalJSON(b []byte) error {
812         var m map[string]json.RawMessage
813         err := json.Unmarshal(b, &m)
814         if err != nil {
815                 return err
816         }
817         if r, ok := m["boolean"]; ok {
818                 var bval bool
819                 err = json.Unmarshal(r, &bval)
820                 if err != nil {
821                         return err
822                 }
823                 a.B = &bval
824                 return nil
825         }
826         if r, ok := m["integer"]; ok {
827                 var ival int64
828                 err = json.Unmarshal(r, &ival)
829                 if err != nil {
830                         return err
831                 }
832                 a.I = &ival
833                 return nil
834         }
835         r, ok := m["string"]
836         if !ok {
837                 return fmt.Errorf("contract arg must define one of boolean, integer, string")
838         }
839         var sval chainjson.HexBytes
840         err = json.Unmarshal(r, &sval)
841         if err != nil {
842                 return err
843         }
844         a.S = &sval
845         return nil
846 }