From 711889bc3fc8237dfb56c79befa11f984fb3e605 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Thu, 20 May 2021 16:43:22 +0200 Subject: cgo: implement prefix parsing This implements expressions such as "-5" and "-5 - 2", in other words, negative numbers. --- cgo/const.go | 12 ++++++++++++ cgo/const_test.go | 4 ++++ 2 files changed, 16 insertions(+) (limited to 'cgo') diff --git a/cgo/const.go b/cgo/const.go index 245bb899f..7501a62c8 100644 --- a/cgo/const.go +++ b/cgo/const.go @@ -39,6 +39,7 @@ func init() { token.STRING: parseBasicLit, token.CHAR: parseBasicLit, token.LPAREN: parseParenExpr, + token.SUB: parseUnaryExpr, } } @@ -131,6 +132,17 @@ func parseBinaryExpr(t *tokenizer, left ast.Expr) (ast.Expr, *scanner.Error) { return expression, err } +func parseUnaryExpr(t *tokenizer) (ast.Expr, *scanner.Error) { + expression := &ast.UnaryExpr{ + OpPos: t.curPos, + Op: t.curToken, + } + t.Next() + x, err := parseConstExpr(t, precedencePrefix) + expression.X = x + return expression, err +} + // unexpectedToken returns an error of the form "unexpected token FOO, expected // BAR". func unexpectedToken(t *tokenizer, expected token.Token) *scanner.Error { diff --git a/cgo/const_test.go b/cgo/const_test.go index c984ec6f6..a8fba70df 100644 --- a/cgo/const_test.go +++ b/cgo/const_test.go @@ -44,6 +44,10 @@ func TestParseConst(t *testing.T) { {`(1 - 2) * 3`, `(1 - 2) * 3`}, {`1 * 2 - 3`, `1*2 - 3`}, {`1 * (2 - 3)`, `1 * (2 - 3)`}, + // Unary operators. + {`-5`, `-5`}, + {`-5-2`, `-5 - 2`}, + {`5 - - 2`, `5 - -2`}, } { fset := token.NewFileSet() startPos := fset.AddFile("", -1, 1000).Pos(0) -- cgit v1.2.3