File: assignstmt.go

package info (click to toggle)
mumax3 3.10-9
  • links: PTS, VCS
  • area: contrib
  • in suites: trixie
  • size: 7,596 kB
  • sloc: makefile: 181; ansic: 155; sh: 77
file content (80 lines) | stat: -rw-r--r-- 2,041 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package script

import (
	"go/ast"
	"go/token"
	"reflect"
)

// compiles a (single) assign statement lhs = rhs
func (w *World) compileAssignStmt(a *ast.AssignStmt) Expr {
	if len(a.Lhs) != 1 || len(a.Rhs) != 1 {
		panic(err(a.Pos(), "multiple assignment not allowed"))
	}
	lhs, rhs := a.Lhs[0], a.Rhs[0]
	r := w.compileExpr(rhs)

	switch a.Tok {
	default:
		panic(err(a.Pos(), a.Tok, "not allowed"))
	case token.ASSIGN: // =
		return w.compileAssign(a, lhs, r)
	case token.DEFINE: // :=
		return w.compileDefine(a, lhs, r)
	case token.ADD_ASSIGN: // +=
		return w.compileAddAssign(a, lhs, r)
	case token.SUB_ASSIGN: // -=
		return w.compileSubAssign(a, lhs, r)
	}
}

// compile a = b
func (w *World) compileAssign(a *ast.AssignStmt, lhs ast.Expr, r Expr) Expr {
	l := w.compileLvalue(lhs)
	return &assignStmt{lhs: l, rhs: typeConv(a.Pos(), r, inputType(l))}
}

// compile a := b
func (w *World) compileDefine(a *ast.AssignStmt, lhs ast.Expr, r Expr) Expr {
	ident, ok := lhs.(*ast.Ident)
	if !ok {
		panic(err(a.Pos(), "non-name on left side of :="))
	}
	addr := reflect.New(r.Type())
	ok = w.safeDeclare(ident.Name, &reflectLvalue{addr.Elem()})
	if !ok {
		panic(err(a.Pos(), "already defined: "+ident.Name))
	}
	return w.compileAssign(a, lhs, r)
}

type assignStmt struct {
	lhs LValue
	rhs Expr
	void
}

func (a *assignStmt) Eval() interface{} {
	a.lhs.SetValue(a.rhs.Eval())
	return nil
}

func (a *assignStmt) Child() []Expr {
	return []Expr{a.lhs, a.rhs}
}

func (w *World) compileAddAssign(a *ast.AssignStmt, lhs ast.Expr, r Expr) Expr {
	l := w.compileLvalue(lhs)
	x := typeConv(a.Pos(), l, float64_t)
	y := typeConv(a.Pos(), r, float64_t)
	sum := &add{binaryExpr{x, y}}
	return &assignStmt{lhs: l, rhs: typeConv(a.Pos(), sum, inputType(l))}
}

func (w *World) compileSubAssign(a *ast.AssignStmt, lhs ast.Expr, r Expr) Expr {
	l := w.compileLvalue(lhs)
	x := typeConv(a.Pos(), l, float64_t)
	y := typeConv(a.Pos(), r, float64_t)
	sub := &sub{binaryExpr{x, y}}
	return &assignStmt{lhs: l, rhs: typeConv(a.Pos(), sub, inputType(l))}
}