• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang constant.MakeInt64函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中go/constant.MakeInt64函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeInt64函数的具体用法?Golang MakeInt64怎么用?Golang MakeInt64使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了MakeInt64函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: capBuiltin

func capBuiltin(args []*Variable, nodeargs []ast.Expr) (*Variable, error) {
	if len(args) != 1 {
		return nil, fmt.Errorf("wrong number of arguments to cap: %d", len(args))
	}

	arg := args[0]
	invalidArgErr := fmt.Errorf("invalid argument %s (type %s) for cap", exprToString(nodeargs[0]), arg.TypeString())

	switch arg.Kind {
	case reflect.Ptr:
		arg = arg.maybeDereference()
		if arg.Kind != reflect.Array {
			return nil, invalidArgErr
		}
		fallthrough
	case reflect.Array:
		return newConstant(constant.MakeInt64(arg.Len), arg.mem), nil
	case reflect.Slice:
		return newConstant(constant.MakeInt64(arg.Cap), arg.mem), nil
	case reflect.Chan:
		arg.loadValue()
		if arg.Unreadable != nil {
			return nil, arg.Unreadable
		}
		if arg.Base == 0 {
			return newConstant(constant.MakeInt64(0), arg.mem), nil
		}
		return newConstant(arg.Children[1].Value, arg.mem), nil
	default:
		return nil, invalidArgErr
	}
}
开发者ID:mattn,项目名称:delve,代码行数:32,代码来源:eval.go


示例2: zeroConst

// zeroConst returns a new "zero" constant of the specified type,
// which must not be an array or struct type: the zero values of
// aggregates are well-defined but cannot be represented by Const.
//
func zeroConst(t types.Type) *Const {
	switch t := t.(type) {
	case *types.Basic:
		switch {
		case t.Info()&types.IsBoolean != 0:
			return NewConst(exact.MakeBool(false), t)
		case t.Info()&types.IsNumeric != 0:
			return NewConst(exact.MakeInt64(0), t)
		case t.Info()&types.IsString != 0:
			return NewConst(exact.MakeString(""), t)
		case t.Kind() == types.UnsafePointer:
			fallthrough
		case t.Kind() == types.UntypedNil:
			return nilConst(t)
		default:
			panic(fmt.Sprint("zeroConst for unexpected type:", t))
		}
	case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
		return nilConst(t)
	case *types.Named:
		return NewConst(zeroConst(t.Underlying()).Value, t)
	case *types.Array, *types.Struct, *types.Tuple:
		panic(fmt.Sprint("zeroConst applied to aggregate:", t))
	}
	panic(fmt.Sprint("zeroConst: unexpected ", t))
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:30,代码来源:const15.go


示例3: IncDecStmt

func IncDecStmt(stmt ast.Stmt, info *types.Info) ast.Stmt {
	if s, ok := stmt.(*ast.IncDecStmt); ok {
		t := info.TypeOf(s.X)
		if iExpr, isIExpr := s.X.(*ast.IndexExpr); isIExpr {
			switch u := info.TypeOf(iExpr.X).Underlying().(type) {
			case *types.Array:
				t = u.Elem()
			case *types.Slice:
				t = u.Elem()
			case *types.Map:
				t = u.Elem()
			}
		}

		tok := token.ADD_ASSIGN
		if s.Tok == token.DEC {
			tok = token.SUB_ASSIGN
		}

		one := &ast.BasicLit{Kind: token.INT}
		info.Types[one] = types.TypeAndValue{Type: t, Value: constant.MakeInt64(1)}

		return &ast.AssignStmt{
			Lhs: []ast.Expr{s.X},
			Tok: tok,
			Rhs: []ast.Expr{one},
		}
	}
	return stmt
}
开发者ID:snyderep,项目名称:pongish,代码行数:30,代码来源:incdecstmt.go


示例4: parseNumber

// number = int_lit [ "p" int_lit ] .
//
func (p *parser) parseNumber() (typ *types.Basic, val exact.Value) {
	// mantissa
	mant := exact.MakeFromLiteral(p.parseInt(), token.INT, 0)
	if mant == nil {
		panic("invalid mantissa")
	}

	if p.lit == "p" {
		// exponent (base 2)
		p.next()
		exp, err := strconv.ParseInt(p.parseInt(), 10, 0)
		if err != nil {
			p.error(err)
		}
		if exp < 0 {
			denom := exact.MakeInt64(1)
			denom = exact.Shift(denom, token.SHL, uint(-exp))
			typ = types.Typ[types.UntypedFloat]
			val = exact.BinaryOp(mant, token.QUO, denom)
			return
		}
		if exp > 0 {
			mant = exact.Shift(mant, token.SHL, uint(exp))
		}
		typ = types.Typ[types.UntypedFloat]
		val = mant
		return
	}

	typ = types.Typ[types.UntypedInt]
	val = mant
	return
}
开发者ID:vmware,项目名称:vic,代码行数:35,代码来源:gcimporter.go


示例5: zeroValue

func (c *funcContext) zeroValue(ty types.Type) ast.Expr {
	switch t := ty.Underlying().(type) {
	case *types.Basic:
		switch {
		case isBoolean(t):
			return c.newConst(ty, constant.MakeBool(false))
		case isNumeric(t):
			return c.newConst(ty, constant.MakeInt64(0))
		case isString(t):
			return c.newConst(ty, constant.MakeString(""))
		case t.Kind() == types.UnsafePointer:
			// fall through to "nil"
		case t.Kind() == types.UntypedNil:
			panic("Zero value for untyped nil.")
		default:
			panic(fmt.Sprintf("Unhandled basic type: %v\n", t))
		}
	case *types.Array, *types.Struct:
		return c.setType(&ast.CompositeLit{}, ty)
	case *types.Chan, *types.Interface, *types.Map, *types.Signature, *types.Slice, *types.Pointer:
		// fall through to "nil"
	default:
		panic(fmt.Sprintf("Unhandled type: %T\n", t))
	}
	id := c.newIdent("nil", ty)
	c.p.Uses[id] = nilObj
	return id
}
开发者ID:snyderep,项目名称:pongish,代码行数:28,代码来源:utils.go


示例6: float

func (p *importer) float() constant.Value {
	sign := p.int()
	if sign == 0 {
		return constant.MakeInt64(0)
	}

	exp := p.int()
	mant := []byte(p.string()) // big endian

	// remove leading 0's if any
	for len(mant) > 0 && mant[0] == 0 {
		mant = mant[1:]
	}

	// convert to little endian
	// TODO(gri) go/constant should have a more direct conversion function
	//           (e.g., once it supports a big.Float based implementation)
	for i, j := 0, len(mant)-1; i < j; i, j = i+1, j-1 {
		mant[i], mant[j] = mant[j], mant[i]
	}

	// adjust exponent (constant.MakeFromBytes creates an integer value,
	// but mant represents the mantissa bits such that 0.5 <= mant < 1.0)
	exp -= len(mant) << 3
	if len(mant) > 0 {
		for msd := mant[len(mant)-1]; msd&0x80 == 0; msd <<= 1 {
			exp++
		}
	}

	x := constant.MakeFromBytes(mant)
	switch {
	case exp < 0:
		d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp))
		x = constant.BinaryOp(x, token.QUO, d)
	case exp > 0:
		x = constant.Shift(x, token.SHL, uint(exp))
	}

	if sign < 0 {
		x = constant.UnaryOp(token.SUB, x, 0)
	}
	return x
}
开发者ID:CyCoreSystems,项目名称:coreos-kubernetes,代码行数:44,代码来源:bimport.go


示例7: fraction

func (p *importer) fraction() constant.Value {
	sign := p.int()
	if sign == 0 {
		return constant.MakeInt64(0)
	}

	x := constant.BinaryOp(p.ufloat(), token.QUO, p.ufloat())
	if sign < 0 {
		x = constant.UnaryOp(token.SUB, x, 0)
	}
	return x
}
开发者ID:julesGoullee,项目名称:gopherjs,代码行数:12,代码来源:import.go


示例8: ufloat

func (p *importer) ufloat() constant.Value {
	exp := p.int()
	x := constant.MakeFromBytes(p.bytes())
	switch {
	case exp < 0:
		d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp))
		x = constant.BinaryOp(x, token.QUO, d)
	case exp > 0:
		x = constant.Shift(x, token.SHL, uint(exp))
	}
	return x
}
开发者ID:julesGoullee,项目名称:gopherjs,代码行数:12,代码来源:import.go


示例9: value

func (p *importer) value() constant.Value {
	switch kind := constant.Kind(p.int()); kind {
	case falseTag:
		return constant.MakeBool(false)
	case trueTag:
		return constant.MakeBool(true)
	case int64Tag:
		return constant.MakeInt64(p.int64())
	case floatTag:
		return p.float()
	case complexTag:
		re := p.float()
		im := p.float()
		return constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
	case stringTag:
		return constant.MakeString(p.string())
	default:
		panic(fmt.Sprintf("unexpected value kind %d", kind))
	}
}
开发者ID:jacobsa,项目名称:go,代码行数:20,代码来源:bimport.go


示例10: value

func (p *importer) value() constant.Value {
	switch tag := p.tagOrIndex(); tag {
	case falseTag:
		return constant.MakeBool(false)
	case trueTag:
		return constant.MakeBool(true)
	case int64Tag:
		return constant.MakeInt64(p.int64())
	case floatTag:
		return p.float()
	case complexTag:
		re := p.float()
		im := p.float()
		return constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
	case stringTag:
		return constant.MakeString(p.string())
	default:
		panic(fmt.Sprintf("unexpected value tag %d", tag))
	}
}
开发者ID:CyCoreSystems,项目名称:coreos-kubernetes,代码行数:20,代码来源:bimport.go


示例11: defPredeclaredConsts

	res := NewVar(token.NoPos, nil, "", Typ[String])
	sig := &Signature{results: NewTuple(res)}
	err := NewFunc(token.NoPos, nil, "Error", sig)
	typ := &Named{underlying: NewInterface([]*Func{err}, nil).Complete()}
	sig.recv = NewVar(token.NoPos, nil, "", typ)
	def(NewTypeName(token.NoPos, nil, "error", typ))
}

var predeclaredConsts = [...]struct {
	name string
	kind BasicKind
	val  exact.Value
}{
	{"true", UntypedBool, exact.MakeBool(true)},
	{"false", UntypedBool, exact.MakeBool(false)},
	{"iota", UntypedInt, exact.MakeInt64(0)},
}

func defPredeclaredConsts() {
	for _, c := range predeclaredConsts {
		def(NewConst(token.NoPos, nil, c.name, Typ[c.kind], c.val))
	}
}

func defPredeclaredNil() {
	def(&Nil{object{name: "nil", typ: Typ[UntypedNil]}})
}

// A builtinId is the id of a builtin function.
type builtinId int
开发者ID:Ericean,项目名称:go,代码行数:30,代码来源:universe.go


示例12: collectObjects


//.........这里部分代码省略.........
									// TODO(gri) When we import a package, we create
									// a new local package object. We should do the
									// same for each dot-imported object. That way
									// they can have correct position information.
									// (We must not modify their existing position
									// information because the same package - found
									// via Config.Packages - may be dot-imported in
									// another package!)
									check.declare(fileScope, nil, obj, token.NoPos)
									check.recordImplicit(s, obj)
								}
							}
							// add position to set of dot-import positions for this file
							// (this is only needed for "imported but not used" errors)
							check.addUnusedDotImport(fileScope, imp, s.Pos())
						} else {
							// declare imported package object in file scope
							check.declare(fileScope, nil, obj, token.NoPos)
						}

					case *ast.ValueSpec:
						switch d.Tok {
						case token.CONST:
							// determine which initialization expressions to use
							switch {
							case s.Type != nil || len(s.Values) > 0:
								last = s
							case last == nil:
								last = new(ast.ValueSpec) // make sure last exists
							}

							// declare all constants
							for i, name := range s.Names {
								obj := NewConst(name.Pos(), pkg, name.Name, nil, exact.MakeInt64(int64(iota)))

								var init ast.Expr
								if i < len(last.Values) {
									init = last.Values[i]
								}

								d := &declInfo{file: fileScope, typ: last.Type, init: init}
								check.declarePkgObj(name, obj, d)
							}

							check.arityMatch(s, last)

						case token.VAR:
							lhs := make([]*Var, len(s.Names))
							// If there's exactly one rhs initializer, use
							// the same declInfo d1 for all lhs variables
							// so that each lhs variable depends on the same
							// rhs initializer (n:1 var declaration).
							var d1 *declInfo
							if len(s.Values) == 1 {
								// The lhs elements are only set up after the for loop below,
								// but that's ok because declareVar only collects the declInfo
								// for a later phase.
								d1 = &declInfo{file: fileScope, lhs: lhs, typ: s.Type, init: s.Values[0]}
							}

							// declare all variables
							for i, name := range s.Names {
								obj := NewVar(name.Pos(), pkg, name.Name, nil)
								lhs[i] = obj

								d := d1
开发者ID:Ericean,项目名称:go,代码行数:67,代码来源:resolver.go


示例13: translateStmt


//.........这里部分代码省略.........
				o := c.p.Defs[spec.(*ast.TypeSpec).Name].(*types.TypeName)
				c.p.typeNames = append(c.p.typeNames, o)
				c.p.objectNames[o] = c.newVariableWithLevel(o.Name(), true)
				c.p.dependencies[o] = true
			}
		case token.CONST:
			// skip, constants are inlined
		}

	case *ast.ExprStmt:
		expr := c.translateExpr(s.X)
		if expr != nil && expr.String() != "" {
			c.Printf("%s;", expr)
		}

	case *ast.LabeledStmt:
		label := c.p.Defs[s.Label].(*types.Label)
		if c.GotoLabel[label] {
			c.PrintCond(false, s.Label.Name+":", fmt.Sprintf("case %d:", c.labelCase(label)))
		}
		c.translateStmt(s.Stmt, label)

	case *ast.GoStmt:
		c.Printf("$go(%s, [%s]);", c.translateExpr(s.Call.Fun), strings.Join(c.translateArgs(c.p.TypeOf(s.Call.Fun).Underlying().(*types.Signature), s.Call.Args, s.Call.Ellipsis.IsValid(), true), ", "))

	case *ast.SendStmt:
		chanType := c.p.TypeOf(s.Chan).Underlying().(*types.Chan)
		call := &ast.CallExpr{
			Fun:  c.newIdent("$send", types.NewSignature(nil, types.NewTuple(types.NewVar(0, nil, "", chanType), types.NewVar(0, nil, "", chanType.Elem())), nil, false)),
			Args: []ast.Expr{s.Chan, c.newIdent(c.translateImplicitConversionWithCloning(s.Value, chanType.Elem()).String(), chanType.Elem())},
		}
		c.Blocking[call] = true
		c.translateStmt(&ast.ExprStmt{X: call}, label)

	case *ast.SelectStmt:
		selectionVar := c.newVariable("_selection")
		var channels []string
		var caseClauses []*ast.CaseClause
		flattened := false
		hasDefault := false
		for i, cc := range s.Body.List {
			clause := cc.(*ast.CommClause)
			switch comm := clause.Comm.(type) {
			case nil:
				channels = append(channels, "[]")
				hasDefault = true
			case *ast.ExprStmt:
				channels = append(channels, c.formatExpr("[%e]", astutil.RemoveParens(comm.X).(*ast.UnaryExpr).X).String())
			case *ast.AssignStmt:
				channels = append(channels, c.formatExpr("[%e]", astutil.RemoveParens(comm.Rhs[0]).(*ast.UnaryExpr).X).String())
			case *ast.SendStmt:
				chanType := c.p.TypeOf(comm.Chan).Underlying().(*types.Chan)
				channels = append(channels, c.formatExpr("[%e, %s]", comm.Chan, c.translateImplicitConversionWithCloning(comm.Value, chanType.Elem())).String())
			default:
				panic(fmt.Sprintf("unhandled: %T", comm))
			}

			indexLit := &ast.BasicLit{Kind: token.INT}
			c.p.Types[indexLit] = types.TypeAndValue{Type: types.Typ[types.Int], Value: constant.MakeInt64(int64(i))}

			var bodyPrefix []ast.Stmt
			if assign, ok := clause.Comm.(*ast.AssignStmt); ok {
				switch rhsType := c.p.TypeOf(assign.Rhs[0]).(type) {
				case *types.Tuple:
					bodyPrefix = []ast.Stmt{&ast.AssignStmt{Lhs: assign.Lhs, Rhs: []ast.Expr{c.newIdent(selectionVar+"[1]", rhsType)}, Tok: assign.Tok}}
				default:
					bodyPrefix = []ast.Stmt{&ast.AssignStmt{Lhs: assign.Lhs, Rhs: []ast.Expr{c.newIdent(selectionVar+"[1][0]", rhsType)}, Tok: assign.Tok}}
				}
			}

			caseClauses = append(caseClauses, &ast.CaseClause{
				List: []ast.Expr{indexLit},
				Body: append(bodyPrefix, clause.Body...),
			})

			flattened = flattened || c.Flattened[clause]
		}

		selectCall := c.setType(&ast.CallExpr{
			Fun:  c.newIdent("$select", types.NewSignature(nil, types.NewTuple(types.NewVar(0, nil, "", types.NewInterface(nil, nil))), types.NewTuple(types.NewVar(0, nil, "", types.Typ[types.Int])), false)),
			Args: []ast.Expr{c.newIdent(fmt.Sprintf("[%s]", strings.Join(channels, ", ")), types.NewInterface(nil, nil))},
		}, types.Typ[types.Int])
		c.Blocking[selectCall] = !hasDefault
		c.Printf("%s = %s;", selectionVar, c.translateExpr(selectCall))

		if len(caseClauses) != 0 {
			translateCond := func(cond ast.Expr) *expression {
				return c.formatExpr("%s[0] === %e", selectionVar, cond)
			}
			c.translateBranchingStmt(caseClauses, nil, true, translateCond, label, flattened)
		}

	case *ast.EmptyStmt:
		// skip

	default:
		panic(fmt.Sprintf("Unhandled statement: %T\n", s))

	}
}
开发者ID:pombredanne,项目名称:camlistore,代码行数:101,代码来源:statements.go


示例14: main

func main() {
	i1 := 1
	i2 := 2
	f1 := 3.0
	i3 := 3
	p1 := &i1
	s1 := []string{"one", "two", "three", "four", "five"}
	s3 := make([]int, 0, 6)
	a1 := [5]string{"one", "two", "three", "four", "five"}
	c1 := cstruct{&bstruct{astruct{1, 2}}, []*astruct{&astruct{1, 2}, &astruct{2, 3}, &astruct{4, 5}}}
	s2 := []astruct{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}}
	p2 := &(c1.sa[2].B)
	as1 := astruct{1, 1}
	var p3 *int
	str1 := "01234567890"
	var fn1 functype = afunc
	var fn2 functype = nil
	var nilslice []int = nil
	var nilptr *int = nil
	ch1 := make(chan int, 2)
	var chnil chan int = nil
	m1 := map[string]astruct{
		"Malone":          astruct{2, 3},
		"Adenauer":        astruct{},
		"squadrons":       astruct{},
		"quintuplets":     astruct{},
		"parasite":        astruct{},
		"wristwatches":    astruct{},
		"flashgun":        astruct{},
		"equivocally":     astruct{},
		"sweetbrier":      astruct{},
		"idealism":        astruct{},
		"tangos":          astruct{},
		"alterable":       astruct{},
		"quaffing":        astruct{},
		"arsenic":         astruct{},
		"coincidentally":  astruct{},
		"hindrances":      astruct{},
		"zoning":          astruct{},
		"egging":          astruct{},
		"inserts":         astruct{},
		"adaptive":        astruct{},
		"orientations":    astruct{},
		"periling":        astruct{},
		"lip":             astruct{},
		"chant":           astruct{},
		"availing":        astruct{},
		"fern":            astruct{},
		"flummoxes":       astruct{},
		"meanders":        astruct{},
		"ravenously":      astruct{},
		"reminisce":       astruct{},
		"snorkel":         astruct{},
		"gutters":         astruct{},
		"jibbed":          astruct{},
		"tiara":           astruct{},
		"takers":          astruct{},
		"animates":        astruct{},
		"Zubenelgenubi":   astruct{},
		"bantering":       astruct{},
		"tumblers":        astruct{},
		"horticulturists": astruct{},
		"thallium":        astruct{},
	}
	var mnil map[string]astruct = nil
	m2 := map[int]*astruct{1: &astruct{10, 11}}
	m3 := map[astruct]int{{1, 1}: 42, {2, 2}: 43}
	up1 := unsafe.Pointer(&i1)
	i4 := 800
	i5 := -3
	i6 := -500
	var err1 error = c1.sa[0]
	var err2 error = c1.pb
	var errnil error = nil
	var iface1 interface{} = c1.sa[0]
	var iface2 interface{} = "test"
	var iface3 interface{} = map[string]constant.Value{}
	var iface4 interface{} = []constant.Value{constant.MakeInt64(4)}
	var ifacenil interface{} = nil
	arr1 := [4]int{0, 1, 2, 3}
	parr := &arr1
	cpx1 := complex(1, 2)
	const1 := constant.MakeInt64(3)
	recursive1 := dstruct{}
	recursive1.x = &recursive1
	var iface5 interface{} = &recursive1
	var iface2fn1 interface{} = afunc1
	var iface2fn2 interface{} = afunc2
	var mapinf maptype = map[string]interface{}{}
	mapinf["inf"] = mapinf
	var bencharr [64]benchstruct
	var benchparr [64]*benchstruct
	mainMenu := Menu{
		{Name: "home", Route: "/", Active: 1},
		{Name: "About", Route: "/about", Active: 1},
		{Name: "Login", Route: "/login", Active: 1},
	}

	for i := range benchparr {
		benchparr[i] = &benchstruct{}
//.........这里部分代码省略.........
开发者ID:mattn,项目名称:delve,代码行数:101,代码来源:testvariables3.go


示例15: builtin


//.........这里部分代码省略.........
			// fallthrough
		}

		// check general case by creating custom signature
		sig := makeSig(S, S, NewSlice(T)) // []T required for variadic signature
		sig.variadic = true
		check.arguments(x, call, sig, func(x *operand, i int) {
			// only evaluate arguments that have not been evaluated before
			if i < len(alist) {
				*x = alist[i]
				return
			}
			arg(x, i)
		}, nargs)
		// ok to continue even if check.arguments reported errors

		x.mode = value
		x.typ = S
		if check.Types != nil {
			check.recordBuiltinType(call.Fun, sig)
		}

	case _Cap, _Len:
		// cap(x)
		// len(x)
		mode := invalid
		var typ Type
		var val constant.Value
		switch typ = implicitArrayDeref(x.typ.Underlying()); t := typ.(type) {
		case *Basic:
			if isString(t) && id == _Len {
				if x.mode == constant_ {
					mode = constant_
					val = constant.MakeInt64(int64(len(constant.StringVal(x.val))))
				} else {
					mode = value
				}
			}

		case *Array:
			mode = value
			// spec: "The expressions len(s) and cap(s) are constants
			// if the type of s is an array or pointer to an array and
			// the expression s does not contain channel receives or
			// function calls; in this case s is not evaluated."
			if !check.hasCallOrRecv {
				mode = constant_
				val = constant.MakeInt64(t.len)
			}

		case *Slice, *Chan:
			mode = value

		case *Map:
			if id == _Len {
				mode = value
			}
		}

		if mode == invalid {
			check.invalidArg(x.pos(), "%s for %s", x, bin.name)
			return
		}

		x.mode = mode
		x.typ = Typ[Int]
开发者ID:Greentor,项目名称:go,代码行数:67,代码来源:builtins.go


示例16: TestParsePrecedence

func TestParsePrecedence(t *testing.T) {
	// Precedence levels (highest first):
	//   0: - ~
	//   1: * / // %
	//   2: + -
	//   3: << >>
	//   4: &
	//   5: ^
	//   6: |
	//   7: = != > >= < <=
	//   8: NOT
	//   9: AND
	//  10: OR

	unary := func(op UnaryOperator, expr Expr) Expr {
		return &UnaryExpr{Operator: op, Expr: expr}
	}
	binary := func(op BinaryOperator, left, right Expr) Expr {
		return &BinaryExpr{Operator: op, Left: left, Right: right}
	}
	cmp := func(op ComparisonOperator, left, right Expr) Expr {
		return &ComparisonExpr{Operator: op, Left: left, Right: right}
	}
	not := func(expr Expr) Expr {
		return &NotExpr{Expr: expr}
	}
	and := func(left, right Expr) Expr {
		return &AndExpr{Left: left, Right: right}
	}
	or := func(left, right Expr) Expr {
		return &OrExpr{Left: left, Right: right}
	}

	one := &NumVal{Value: constant.MakeInt64(1), OrigString: "1"}
	two := &NumVal{Value: constant.MakeInt64(2), OrigString: "2"}
	three := &NumVal{Value: constant.MakeInt64(3), OrigString: "3"}

	testData := []struct {
		sql      string
		expected Expr
	}{
		// Unary plus and complement.
		{`~-1`, unary(UnaryComplement, unary(UnaryMinus, one))},
		{`-~1`, unary(UnaryMinus, unary(UnaryComplement, one))},

		// Mul, div, floordiv, mod combined with higher precedence.
		{`-1*2`, binary(Mult, unary(UnaryMinus, one), two)},
		{`1*-2`, binary(Mult, one, unary(UnaryMinus, two))},
		{`-1/2`, binary(Div, unary(UnaryMinus, one), two)},
		{`1/-2`, binary(Div, one, unary(UnaryMinus, two))},
		{`-1//2`, binary(FloorDiv, unary(UnaryMinus, one), two)},
		{`1//-2`, binary(FloorDiv, one, unary(UnaryMinus, two))},
		{`-1%2`, binary(Mod, unary(UnaryMinus, one), two)},
		{`1%-2`, binary(Mod, one, unary(UnaryMinus, two))},

		// Mul, div, floordiv, mod combined with self (left associative).
		{`1*2*3`, binary(Mult, binary(Mult, one, two), three)},
		{`1*2/3`, binary(Div, binary(Mult, one, two), three)},
		{`1/2*3`, binary(Mult, binary(Div, one, two), three)},
		{`1*2//3`, binary(FloorDiv, binary(Mult, one, two), three)},
		{`1//2*3`, binary(Mult, binary(FloorDiv, one, two), three)},
		{`1*2%3`, binary(Mod, binary(Mult, one, two), three)},
		{`1%2*3`, binary(Mult, binary(Mod, one, two), three)},
		{`1/2/3`, binary(Div, binary(Div, one, two), three)},
		{`1/2//3`, binary(FloorDiv, binary(Div, one, two), three)},
		{`1//2/3`, binary(Div, binary(FloorDiv, one, two), three)},
		{`1/2%3`, binary(Mod, binary(Div, one, two), three)},
		{`1%2/3`, binary(Div, binary(Mod, one, two), three)},
		{`1//2//3`, binary(FloorDiv, binary(FloorDiv, one, two), three)},
		{`1//2%3`, binary(Mod, binary(FloorDiv, one, two), three)},
		{`1%2//3`, binary(FloorDiv, binary(Mod, one, two), three)},
		{`1%2%3`, binary(Mod, binary(Mod, one, two), three)},

		// Binary plus and minus combined with higher precedence.
		{`1*2+3`, binary(Plus, binary(Mult, one, two), three)},
		{`1+2*3`, binary(Plus, one, binary(Mult, two, three))},
		{`1*2-3`, binary(Minus, binary(Mult, one, two), three)},
		{`1-2*3`, binary(Minus, one, binary(Mult, two, three))},

		// Binary plus and minus combined with self (left associative).
		{`1+2-3`, binary(Minus, binary(Plus, one, two), three)},
		{`1-2+3`, binary(Plus, binary(Minus, one, two), three)},

		// Left and right shift combined with higher precedence.
		{`1<<2+3`, binary(LShift, one, binary(Plus, two, three))},
		{`1+2<<3`, binary(LShift, binary(Plus, one, two), three)},
		{`1>>2+3`, binary(RShift, one, binary(Plus, two, three))},
		{`1+2>>3`, binary(RShift, binary(Plus, one, two), three)},

		// Left and right shift combined with self (left associative).
		{`1<<2<<3`, binary(LShift, binary(LShift, one, two), three)},
		{`1<<2>>3`, binary(RShift, binary(LShift, one, two), three)},
		{`1>>2<<3`, binary(LShift, binary(RShift, one, two), three)},
		{`1>>2>>3`, binary(RShift, binary(RShift, one, two), three)},

		// Bit-and combined with higher precedence.
		{`1&2<<3`, binary(Bitand, one, binary(LShift, two, three))},
		{`1<<2&3`, binary(Bitand, binary(LShift, one, two), three)},

		// Bit-and combined with self (left associative)
//.........这里部分代码省略.........
开发者ID:the872,项目名称:cockroach,代码行数:101,代码来源:parse_test.go


示例17: declStmt

func (check *Checker) declStmt(decl ast.Decl) {
	pkg := check.pkg

	switch d := decl.(type) {
	case *ast.BadDecl:
		// ignore

	case *ast.GenDecl:
		var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
		for iota, spec := range d.Specs {
			switch s := spec.(type) {
			case *ast.ValueSpec:
				switch d.Tok {
				case token.CONST:
					// determine which init exprs to use
					switch {
					case s.Type != nil || len(s.Values) > 0:
						last = s
					case last == nil:
						last = new(ast.ValueSpec) // make sure last exists
					}

					// declare all constants
					lhs := make([]*Const, len(s.Names))
					for i, name := range s.Names {
						obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota)))
						lhs[i] = obj

						var init ast.Expr
						if i < len(last.Values) {
							init = last.Values[i]
						}

						check.constDecl(obj, last.Type, init)
					}

					check.arityMatch(s, last)

					// spec: "The scope of a constant or variable identifier declared
					// inside a function begins at the end of the ConstSpec or VarSpec
					// (ShortVarDecl for short variable declarations) and ends at the
					// end of the innermost containing block."
					scopePos := s.End()
					for i, name := range s.Names {
						check.declare(check.scope, name, lhs[i], scopePos)
					}

				case token.VAR:
					lhs0 := make([]*Var, len(s.Names))
					for i, name := range s.Names {
						lhs0[i] = NewVar(name.Pos(), pkg, name.Name, nil)
					}

					// initialize all variables
					for i, obj := range lhs0 {
						var lhs []*Var
						var init ast.Expr
						switch len(s.Values) {
						case len(s.Names):
							// lhs and rhs match
							init = s.Values[i]
						case 1:
							// rhs is expected to be a multi-valued expression
							lhs = lhs0
							init = s.Values[0]
						default:
							if i < len(s.Values) {
								init = s.Values[i]
							}
						}
						check.varDecl(obj, lhs, s.Type, init)
						if len(s.Values) == 1 {
							// If we have a single lhs variable we are done either way.
							// If we have a single rhs expression, it must be a multi-
							// valued expression, in which case handling the first lhs
							// variable will cause all lhs variables to have a type
							// assigned, and we are done as well.
							if debug {
								for _, obj := range lhs0 {
									assert(obj.typ != nil)
								}
							}
							break
						}
					}

					check.arityMatch(s, nil)

					// declare all variables
					// (only at this point are the variable scopes (parents) set)
					scopePos := s.End() // see constant declarations
					for i, name := range s.Names {
						// see constant declarations
						check.declare(check.scope, name, lhs0[i], scopePos)
					}

				default:
					check.invalidAST(s.Pos(), "invalid token %s", d.Tok)
				}

//.........这里部分代码省略.........
开发者ID:RajibTheKing,项目名称:gcc,代码行数:101,代码来源:decl.go


示例18: TestValues

func TestValues(t *testing.T) {
	defer leaktest.AfterTest(t)()

	p := makePlanner()

	vInt := int64(5)
	vNum := 3.14159
	vStr := "two furs one cub"
	vBool := true

	unsupp := &parser.RangeCond{}

	intVal := func(v int64) *parser.NumVal {
		return &parser.NumVal{Value: constant.MakeInt64(v)}
	}
	floatVal := func(f float64) *parser.CastExpr {
		return &parser.CastExpr{
			Expr: &parser.NumVal{Value: constant.MakeFloat64(f)},
			Type: &parser.FloatColType{},
		}
	}
	asRow := func(datums ...parser.Datum) []parser.DTuple {
		return []parser.DTuple{datums}
	}

	makeValues := func(tuples ...*parser.Tuple) *parser.ValuesClause {
		return &parser.ValuesClause{Tuples: tuples}
	}
	makeTuple := func(exprs ...parser.Expr) *parser.Tuple {
		return &parser.Tuple{Exprs: exprs}
	}

	testCases := []struct {
		stmt *parser.ValuesClause
		rows []parser.DTuple
		ok   bool
	}{
		{
			makeValues(makeTuple(intVal(vInt))),
			asRow(parser.NewDInt(parser.DInt(vInt))),
			true,
		},
		{
			makeValues(makeTuple(intVal(vInt), intVal(vInt))),
			asRow(parser.NewDInt(parser.DInt(vInt)), parser.NewDInt(parser.DInt(vInt))),
			true,
		},
		{
			makeValues(makeTuple(floatVal(vNum))),
			asRow(parser.NewDFloat(parser.DFloat(vNum))),
			true,
		},
		{
			makeValues(makeTuple(parser.NewDString(vStr))),
			asRow(parser.NewDString(vStr)),
			true,
		},
		{
			makeValues(makeTuple(parser.NewDBytes(parser.DBytes(vStr)))),
			asRow(parser.NewDBytes(parser.DBytes(vStr))),
			true,
		},
		{
			makeValues(makeTuple(parser.MakeDBool(parser.DBool(vBool)))),
			asRow(parser.MakeDBool(parser.DBool(vBool))),
			true,
		},
		{
			makeValues(makeTuple(unsupp)),
			nil,
			false,
		},
	}

	for i, tc := range testCases {
		plan, err := func() (_ planNode, err error) {
			defer func() {
				if r := recover(); r != nil {
					err = errors.Errorf("%v", r)
				}
			}()
			return p.ValuesClause(tc.stmt, nil)
		}()
		if err == nil != tc.ok {
			t.Errorf("%d: error_expected=%t, but got error %v", i, tc.ok, err)
		}
		if plan != nil {
			if err := plan.expandPlan(); err != nil {
				t.Errorf("%d: unexpected error in expandPlan: %v", i, err)
				continue
			}
			if err := plan.Start(); err != nil {
				t.Errorf("%d: unexpected error in Start: %v", i, err)
				continue
			}
			var rows []parser.DTuple
			next, err := plan.Next()
			for ; next; next, err = plan.Next() {
				rows = append(rows, plan.Values())
			}
//.........这里部分代码省略.........
开发者ID:CubeLite,项目名称:cockroach,代码行数:101,代码来源:values_test.go


示例19: compare

func compare(a, b interface{}, tok token.Token) bool {
	vala := reflect.ValueOf(a)
	valb := reflect.ValueOf(b)

	ak := vala.Kind()
	bk := valb.Kind()
	switch {
	case ak >= reflect.Int && ak <= reflect.Int64:
		if bk >= reflect.Int && bk <= reflect.Int64 {
			return constant.Compare(constant.MakeInt64(vala.Int()), tok, constant.MakeInt64(valb.Int()))
		}

		if bk == reflect.Float32 || bk == reflect.Float64 {
			return constant.Compare(constant.MakeFloat64(float64(vala.Int())), tok, constant.MakeFloat64(valb.Float()))
		}

		if bk == reflect.String {
			bla, err := strconv.ParseFloat(valb.String(), 64)
			if err != nil {
				return false
			}

			return constant.Compare(constant.MakeFloat64(float64(vala.Int())), tok, constant.MakeFloat64(bla))
		}
	case ak == reflect.Float32 || ak == reflect.Float64:
		if bk == reflect.Float32 || bk == reflect.Float64 {
			return constant.Compare(constant.MakeFloat64(vala.Float()), tok, constant.MakeFloat64(valb.Float()))
		}

		if bk >= reflect.Int && bk <= reflect.Int64 {
			return constant.Compare(constant.MakeFloat64(vala.Float()), tok, constant.MakeFloat64(float64(valb.Int())))
		}

		if bk == reflect.String {
			bla, err := strconv.ParseFloat(valb.String(), 64)
			if err != nil {
				return false
			}

			return constant.Compare(constant.MakeFloat64(vala.Float()), tok, constant.MakeFloat64(bla))
		}
	case ak == reflect.String:
		if bk == reflect.String {
			return constant.Compare(constant.MakeString(vala.String()), tok, constant.MakeString(valb.String()))
		}
	}

	if reflect.TypeOf(a).String() == "time.Time" && reflect.TypeOf(b).String() == "time.Time" {
		var x, y int64
		x = 1
		if vala.MethodByName("Equal").Call([]reflect.Value{valb})[0].Bool() {
			y = 1
		} else if vala.MethodByName("Before").Call([]reflect.Value{valb})[0].Bool() {
			y = 2
		}
		return constant.Compare(constant.MakeInt64(x), tok, constant.MakeInt64(y))
	}

	if tok == token.EQL {
		return reflect.DeepEqual(a, b)
	}

	return false
}
开发者ID:asdine,项目名称:storm,代码行数:64,代码来源:compare.go


示例20: defPredeclaredConsts

	res := NewVar(token.NoPos, nil, "", Typ[String])
	sig := &Signature{results: NewTuple(res)}
	err := NewFunc(token.NoPos, nil, "Error", sig)
	typ := &Named{underlying: NewInterface([]*Func{err}, nil).Complete()}
	sig.recv = NewVar(token.NoPos, nil, "", typ)
	def(NewTypeName(token.NoPos, nil, "error", typ))
}

var predeclaredConsts = [...]struct {
	name string
	kind BasicKind
	val  constant.Value
}{
	{"true", UntypedBool, constant.MakeBool(true)},
	{"false", UntypedBool, constant.MakeBool(false)},
	{"iota", UntypedInt, constant.MakeInt64(0)},
}

func defPredeclaredConsts() {
	for _, c := range predeclaredConsts {
		def(NewConst(token.NoPos, nil, c.name, Typ[c.kind], c.val))
	}
}

func defPredeclaredNil() {
	def(&Nil{object{name: "nil", typ: Typ[UntypedNil]}})
}

// A builtinId is the id of a builtin function.
type builtinId int
开发者ID:RajibTheKing,项目名称:gcc,代码行数:30,代码来源:universe.go



注:本文中的go/constant.MakeInt64函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang constant.MakeString函数代码示例发布时间:2022-05-28
下一篇:
Golang constant.MakeImag函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap