From 711889bc3fc8237dfb56c79befa11f984fb3e605 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Thu, 20 May 2021 16:43:22 +0200 Subject: [PATCH] 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 ++++ testdata/cgo/main.go | 2 ++ testdata/cgo/out.txt | 1 + 4 files changed, 19 insertions(+) diff --git a/cgo/const.go b/cgo/const.go index 245bb899..7501a62c 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 c984ec6f..a8fba70d 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) diff --git a/testdata/cgo/main.go b/testdata/cgo/main.go index 55f9f4c4..36ef2905 100644 --- a/testdata/cgo/main.go +++ b/testdata/cgo/main.go @@ -6,6 +6,7 @@ int fortytwo(void); int mul(int, int); #include #cgo CFLAGS: -DSOME_CONSTANT=17 +#define someDefine -5 + 2 * 7 */ import "C" @@ -26,6 +27,7 @@ func main() { println("defined floats:", C.CONST_FLOAT, C.CONST_FLOAT2) println("defined string:", C.CONST_STRING) println("defined char:", C.CONST_CHAR) + println("defined expr:", C.someDefine) var ptr C.intPointer var n C.int = 15 ptr = C.intPointer(&n) diff --git a/testdata/cgo/out.txt b/testdata/cgo/out.txt index 2eb4f354..5f4b5f41 100644 --- a/testdata/cgo/out.txt +++ b/testdata/cgo/out.txt @@ -8,6 +8,7 @@ defined ints: 5 5 defined floats: +5.800000e+000 +5.800000e+000 defined string: defined string defined char: 99 +defined expr: 9 15: 15 25: 25 callback 1: 50