11 // We have some function naming conventions.
14 // scanX takes buf and position, returns new position (and maybe a value)
15 // peekX takes *parser, returns bool or string
16 // consumeX takes *parser and maybe a required literal, maybe returns value
17 // also updates the parser position
20 // parseX takes *parser, returns AST node, updates parser position
27 func (p *parser) errorf(format string, args ...interface{}) {
28 panic(parserErr{buf: p.buf, offset: p.pos, format: format, args: args})
31 // parse is the main entry point to the parser
32 func parse(buf []byte) (contracts []*Contract, err error) {
34 if val := recover(); val != nil {
35 if e, ok := val.(parserErr); ok {
42 p := &parser{buf: buf}
43 contracts = parseContracts(p)
49 func parseContracts(p *parser) []*Contract {
50 var result []*Contract
51 if pos := scanKeyword(p.buf, p.pos, "contract"); pos < 0 {
52 p.errorf("expected contract")
55 for peekKeyword(p) == "contract" {
56 contract := parseContract(p)
57 result = append(result, contract)
62 // contract name(p1, p2: t1, p3: t2) locks value { ... }
63 func parseContract(p *parser) *Contract {
64 consumeKeyword(p, "contract")
65 name := consumeIdentifier(p)
66 params := parseParams(p)
67 // locks amount of asset
68 consumeKeyword(p, "locks")
70 value.Amount = consumeIdentifier(p)
71 consumeKeyword(p, "of")
72 value.Asset = consumeIdentifier(p)
74 clauses := parseClauses(p)
76 return &Contract{Name: name, Params: params, Clauses: clauses, Value: value}
79 // (p1, p2: t1, p3: t2)
80 func parseParams(p *parser) []*Param {
84 for !peekTok(p, ")") {
90 pt := parseParamsType(p)
91 params = append(params, pt...)
97 func parseClauses(p *parser) []*Clause {
99 for !peekTok(p, "}") {
101 clauses = append(clauses, c)
106 func parseParamsType(p *parser) []*Param {
107 firstName := consumeIdentifier(p)
108 params := []*Param{&Param{Name: firstName}}
109 for peekTok(p, ",") {
111 name := consumeIdentifier(p)
112 params = append(params, &Param{Name: name})
115 typ := consumeIdentifier(p)
116 for _, parm := range params {
117 if tdesc, ok := types[typ]; ok {
120 p.errorf("unknown type %s", typ)
126 func parseClause(p *parser) *Clause {
128 consumeKeyword(p, "clause")
129 c.Name = consumeIdentifier(p)
130 c.Params = parseParams(p)
132 c.statements = parseStatements(p)
137 func parseStatements(p *parser) []statement {
138 var statements []statement
139 for !peekTok(p, "}") {
140 s := parseStatement(p)
141 statements = append(statements, s)
146 func parseStatement(p *parser) statement {
147 switch peekKeyword(p) {
149 return parseIfStmt(p)
151 return parseDefineStmt(p)
153 return parseAssignStmt(p)
155 return parseVerifyStmt(p)
157 return parseLockStmt(p)
159 return parseUnlockStmt(p)
161 panic(parseErr(p.buf, p.pos, "unknown keyword \"%s\"", peekKeyword(p)))
164 func parseIfStmt(p *parser) *ifStatement {
165 consumeKeyword(p, "if")
166 condition := parseExpr(p)
167 body := &IfStatmentBody{}
169 body.trueBody = parseStatements(p)
171 if peekKeyword(p) == "else" {
172 consumeKeyword(p, "else")
174 body.falseBody = parseStatements(p)
177 return &ifStatement{condition: condition, body: body}
180 func parseDefineStmt(p *parser) *defineStatement {
181 defineStat := &defineStatement{}
182 consumeKeyword(p, "define")
184 param.Name = consumeIdentifier(p)
186 variableType := consumeIdentifier(p)
187 if tdesc, ok := types[variableType]; ok {
190 p.errorf("unknown type %s", variableType)
192 defineStat.variable = param
195 defineStat.expr = parseExpr(p)
200 func parseAssignStmt(p *parser) *assignStatement {
201 consumeKeyword(p, "assign")
202 varName := consumeIdentifier(p)
205 return &assignStatement{variable: &Param{Name: varName}, expr: expr}
208 func parseVerifyStmt(p *parser) *verifyStatement {
209 consumeKeyword(p, "verify")
211 return &verifyStatement{expr: expr}
214 func parseLockStmt(p *parser) *lockStatement {
215 consumeKeyword(p, "lock")
216 lockedAmount := parseExpr(p)
217 consumeKeyword(p, "of")
218 lockedAsset := parseExpr(p)
219 consumeKeyword(p, "with")
220 program := parseExpr(p)
221 return &lockStatement{lockedAmount: lockedAmount, lockedAsset: lockedAsset, program: program}
224 func parseUnlockStmt(p *parser) *unlockStatement {
225 consumeKeyword(p, "unlock")
226 unlockedAmount := parseExpr(p)
227 consumeKeyword(p, "of")
228 unlockedAsset := parseExpr(p)
229 return &unlockStatement{unlockedAmount: unlockedAmount, unlockedAsset: unlockedAsset}
232 func parseExpr(p *parser) expression {
233 // Uses the precedence-climbing algorithm
234 // <https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method>
235 expr := parseUnaryExpr(p)
236 expr2, pos := parseExprCont(p, expr, 0)
238 p.errorf("expected expression")
244 func parseUnaryExpr(p *parser) expression {
245 op, pos := scanUnaryOp(p.buf, p.pos)
250 expr := parseUnaryExpr(p)
251 return &unaryExpr{op: op, expr: expr}
254 func parseExprCont(p *parser, lhs expression, minPrecedence int) (expression, int) {
256 op, pos := scanBinaryOp(p.buf, p.pos)
257 if pos < 0 || op.precedence < minPrecedence {
262 rhs := parseUnaryExpr(p)
265 op2, pos2 := scanBinaryOp(p.buf, p.pos)
266 if pos2 < 0 || op2.precedence <= op.precedence {
269 rhs, p.pos = parseExprCont(p, rhs, op2.precedence)
271 return nil, -1 // or is this an error?
274 lhs = &binaryExpr{left: lhs, right: rhs, op: op}
279 func parseExpr2(p *parser) expression {
280 if expr, pos := scanLiteralExpr(p.buf, p.pos); pos >= 0 {
287 func parseExpr3(p *parser) expression {
291 return &callExpr{fn: e, args: args}
296 func parseExpr4(p *parser) expression {
304 var elts []expression
307 for !peekTok(p, "]") {
314 elts = append(elts, e)
317 return listExpr(elts)
319 name := consumeIdentifier(p)
323 func parseArgs(p *parser) []expression {
324 var exprs []expression
327 for !peekTok(p, ")") {
334 exprs = append(exprs, e)
342 func peekKeyword(p *parser) string {
343 name, _ := scanIdentifier(p.buf, p.pos)
347 func peekTok(p *parser, token string) bool {
348 pos := scanTok(p.buf, p.pos, token)
354 var keywords = []string{
355 "contract", "clause", "verify", "locks", "of",
356 "lock", "with", "unlock", "if", "else",
357 "define", "assign", "true", "false",
360 func consumeKeyword(p *parser, keyword string) {
361 pos := scanKeyword(p.buf, p.pos, keyword)
363 p.errorf("expected keyword %s", keyword)
368 func consumeIdentifier(p *parser) string {
369 name, pos := scanIdentifier(p.buf, p.pos)
371 p.errorf("expected identifier")
377 func consumeTok(p *parser, token string) {
378 pos := scanTok(p.buf, p.pos, token)
380 p.errorf("expected %s token", token)
387 func scanUnaryOp(buf []byte, offset int) (*unaryOp, int) {
388 // Maximum munch. Make sure "-3" scans as ("-3"), not ("-", "3").
389 if _, pos := scanIntLiteral(buf, offset); pos >= 0 {
392 for _, op := range unaryOps {
393 newOffset := scanTok(buf, offset, op.op)
395 return &op, newOffset
401 func scanBinaryOp(buf []byte, offset int) (*binaryOp, int) {
402 offset = skipWsAndComments(buf, offset)
407 for i, op := range binaryOps {
408 offset2 := scanTok(buf, offset, op.op)
410 if found == nil || len(op.op) > len(found.op) {
411 found = &binaryOps[i]
416 return found, newOffset
419 // TODO(bobg): boolean literals?
420 func scanLiteralExpr(buf []byte, offset int) (expression, int) {
421 offset = skipWsAndComments(buf, offset)
422 intliteral, newOffset := scanIntLiteral(buf, offset)
424 return intliteral, newOffset
426 strliteral, newOffset := scanStrLiteral(buf, offset)
428 return strliteral, newOffset
430 bytesliteral, newOffset := scanBytesLiteral(buf, offset) // 0x6c249a...
432 return bytesliteral, newOffset
434 booleanLiteral, newOffset := scanBoolLiteral(buf, offset) // true or false
436 return booleanLiteral, newOffset
441 func scanIdentifier(buf []byte, offset int) (string, int) {
442 offset = skipWsAndComments(buf, offset)
444 for ; i < len(buf) && isIDChar(buf[i], i == offset); i++ {
449 return string(buf[offset:i]), i
452 func scanTok(buf []byte, offset int, s string) int {
453 offset = skipWsAndComments(buf, offset)
455 if bytes.HasPrefix(buf[offset:], prefix) {
456 return offset + len(prefix)
461 func scanKeyword(buf []byte, offset int, keyword string) int {
462 id, newOffset := scanIdentifier(buf, offset)
472 func scanIntLiteral(buf []byte, offset int) (integerLiteral, int) {
473 offset = skipWsAndComments(buf, offset)
475 if offset < len(buf) && buf[offset] == '-' {
479 for ; i < len(buf) && unicode.IsDigit(rune(buf[i])); i++ {
480 // the literal is BytesLiteral when it starts with 0x/0X
481 if buf[i] == '0' && i < len(buf)-1 && (buf[i+1] == 'x' || buf[i+1] == 'X') {
486 n, err := strconv.ParseInt(string(buf[start:i]), 10, 64)
490 return integerLiteral(n), i
495 func scanStrLiteral(buf []byte, offset int) (bytesLiteral, int) {
496 offset = skipWsAndComments(buf, offset)
497 if offset >= len(buf) || buf[offset] != '\'' {
498 return bytesLiteral{}, -1
500 var byteBuf bytesLiteral
501 for i := offset + 1; i < len(buf); i++ {
503 return byteBuf, i + 1
505 if buf[i] == '\\' && i < len(buf)-1 {
506 if c, ok := scanEscape(buf[i+1]); ok {
507 byteBuf = append(byteBuf, c)
512 byteBuf = append(byteBuf, buf[i])
514 panic(parseErr(buf, offset, "unterminated string literal"))
517 func scanBytesLiteral(buf []byte, offset int) (bytesLiteral, int) {
518 offset = skipWsAndComments(buf, offset)
519 if offset+4 >= len(buf) {
522 if buf[offset] != '0' || (buf[offset+1] != 'x' && buf[offset+1] != 'X') {
525 if !isHexDigit(buf[offset+2]) || !isHexDigit(buf[offset+3]) {
529 for ; i < len(buf); i += 2 {
531 panic(parseErr(buf, offset, "odd number of digits in hex literal"))
533 if !isHexDigit(buf[i]) {
536 if !isHexDigit(buf[i+1]) {
537 panic(parseErr(buf, offset, "odd number of digits in hex literal"))
540 decoded := make([]byte, hex.DecodedLen(i-(offset+2)))
541 _, err := hex.Decode(decoded, buf[offset+2:i])
543 return bytesLiteral{}, -1
545 return bytesLiteral(decoded), i
548 func scanBoolLiteral(buf []byte, offset int) (booleanLiteral, int) {
549 offset = skipWsAndComments(buf, offset)
550 if offset >= len(buf) {
554 newOffset := scanKeyword(buf, offset, "true")
556 if newOffset = scanKeyword(buf, offset, "false"); newOffset < 0 {
559 return false, newOffset
561 return true, newOffset
564 func skipWsAndComments(buf []byte, offset int) int {
566 for ; offset < len(buf); offset++ {
573 if c == '/' && offset < len(buf)-1 && buf[offset+1] == '/' {
575 offset++ // skip two chars instead of one
576 } else if !unicode.IsSpace(rune(c)) {
584 func isHexDigit(b byte) bool {
585 return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F')
588 func isIDChar(c byte, initial bool) bool {
589 if c >= 'a' && c <= 'z' {
592 if c >= 'A' && c <= 'Z' {
601 return unicode.IsDigit(rune(c))
604 type parserErr struct {
611 func parseErr(buf []byte, offset int, format string, args ...interface{}) error {
612 return parserErr{buf: buf, offset: offset, format: format, args: args}
615 func (p parserErr) Error() string {
616 // Lines start at 1, columns start at 0, like nature intended.
619 for i := 0; i < p.offset; i++ {
620 if p.buf[i] == '\n' {
627 args := []interface{}{line, col}
628 args = append(args, p.args...)
629 return fmt.Sprintf("line %d, col %d: "+p.format, args...)
632 func scanEscape(c byte) (byte, bool) {
635 case '\'', '"', '\\':