| 44 | } |
| 45 | |
| 46 | func (p *Parser) parseOperation() (Node, error) { |
| 47 | op := &Operation{ |
| 48 | LeftNode: nil, |
| 49 | Gate: "", |
| 50 | RightNode: nil, |
| 51 | } |
| 52 | tok, lit := p.scanIgnoreWhitespace() |
| 53 | for tok != EOF { |
| 54 | switch { |
| 55 | // If we hit an open bracket then we parse the operation contained in the brackets. |
| 56 | case tok == OPEN_BRACKET: |
| 57 | node, err := p.parseOperation() |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | // Assign the operation to left node if we haven't already. |
| 62 | if op.LeftNode == nil { |
| 63 | op.LeftNode = node |
| 64 | break |
| 65 | } |
| 66 | if op.Gate == "" { |
| 67 | return nil, errors.New("shouldn't find operation before Gate if left node already exists") |
| 68 | } |
| 69 | // Assign to right otherwise. |
| 70 | if op.RightNode == nil { |
| 71 | op.RightNode = node |
| 72 | tempOp := &Operation{ |
| 73 | LeftNode: op, |
| 74 | Gate: "", |
| 75 | RightNode: nil, |
| 76 | } |
| 77 | op = tempOp |
| 78 | break |
| 79 | } |
| 80 | case tok == STRING: |
| 81 | if (op.LeftNode != nil && op.Gate == "") || (op.LeftNode != nil && op.RightNode != nil) { |
| 82 | return nil, errors.New("didn't expect an expression here") |
| 83 | } |
| 84 | p.unscan(TokenInfo{ |
| 85 | Token: tok, |
| 86 | Literal: lit, |
| 87 | }) |
| 88 | expr, err := p.parseExpression() |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | if op.LeftNode == nil { |
| 93 | op.LeftNode = expr |
| 94 | break |
| 95 | } |
| 96 | if op.RightNode == nil { |
| 97 | op.RightNode = expr |
| 98 | tempOp := &Operation{ |
| 99 | LeftNode: op, |
| 100 | Gate: "", |
| 101 | RightNode: nil, |
| 102 | } |
| 103 | op = tempOp |