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

Golang parser.ParseExpr函数代码示例

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

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



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

示例1: ParseStmt

// A convenience function for parsing a Stmt by wrapping it in a func literal
func ParseStmt(stmt string) (ast.Stmt, error) {
	// parser.ParseExpr has some quirks, for example it won't parse unused map literals as
	// ExprStmts. Unused map literals are technically illegal, but it would be
	// nice to check them at a later stage. Therefore, we want to parse expressions
	// as expressions, and stmts and stmts. We try both.
	// However, there is a bug in parser.ParseExpr that it does not detect excess input.
	// Therefore, the _ of _ = 1 will be parsed as an expression. To avoid this, attempt
	// to parse the input as a statement first, and fall back to an expression
	expr := "func(){" + stmt + ";}"
	if e, err := parser.ParseExpr(expr); err != nil {
		if e, err := parser.ParseExpr(stmt); err == nil {
			return &ast.ExprStmt{X: e}, nil
		}
		errs := err.(scanner.ErrorList)
		for i := range errs {
			errs[i].Pos.Offset -= 7
			errs[i].Pos.Column -= 7
		}
		return nil, errs
	} else {
		node := e.(*ast.FuncLit).Body.List[0]
		if stmt, ok := node.(Stmt); !ok {
			return nil, fmt.Errorf("%T not supported", node)
		} else {
			return stmt, nil
		}
	}
}
开发者ID:philipmulcahy,项目名称:godebug,代码行数:29,代码来源:eval.go


示例2: Inline

// Inline replaces each instance of identifier k with v.Ident in ast.File f,
// for k, v := range m.
// For all inlines that were triggeres it also adds imports from v.Imports to f.
// In addition, it removes top level type declarations of the form
// type k ...
// for all k in m.
//
// Every k in m should be a valid identifier.
// Every v.Ident should be a valid expression.
func Inline(fset *token.FileSet, f *ast.File, m map[string]Target) error {
	// Build the inline map.
	im := map[string]reflect.Value{}
	for k, v := range m {
		expr, err := parser.ParseExpr(k)
		if err != nil {
			return fmt.Errorf("failed to parse `%s`: %s", k, err)
		}
		if _, ok := expr.(*ast.Ident); !ok {
			return fmt.Errorf("expected identifier, got %s which is %T", k, expr)
		}
		expr, err = parser.ParseExpr(v.Ident)
		if err != nil {
			return fmt.Errorf("failed to parse `%s`: %s", v.Ident, err)
		}
		s := v.Ident
		if _, ok := expr.(*ast.StarExpr); ok {
			s = fmt.Sprintf("(%s)", s)
		}
		im[k] = reflect.ValueOf(ast.Ident{Name: s})
	}
	// Filter `type XXX ...` declarations out if we are inlining XXX.
	cmap := ast.NewCommentMap(fset, f, f.Comments)
	to := 0
	for _, d := range f.Decls {
		skip := false
		if t, ok := d.(*ast.GenDecl); ok {
			for _, s := range t.Specs {
				ts, ok := s.(*ast.TypeSpec)
				if !ok {
					continue
				}
				if _, ok = im[ts.Name.String()]; ok {
					skip = true
				}
			}
		}
		if !skip {
			f.Decls[to] = d
			to++
		}
	}
	if to != len(f.Decls) {
		f.Decls = f.Decls[:to]
		// Remove comments for the declarations that were filtered out.
		f.Comments = cmap.Filter(f).Comments()
	}
	// Add imports for the inlines that were triggered.
	for k := range inline(im, f) {
		for _, imp := range m[k].Imports {
			astutil.AddImport(fset, f, imp)
		}
	}
	return nil
}
开发者ID:charl,项目名称:go-inline,代码行数:64,代码来源:goinline.go


示例3: compareTwoTrees

func compareTwoTrees(src string) {
	v1 := &channelPusher{}
	v1.fileSet = token.NewFileSet()
	v1.queue = make(chan *ast.Node)

	v2 := &channelPusher{}
	v2.fileSet = token.NewFileSet()
	v2.queue = make(chan *ast.Node)

	tree1, err := parser.ParseExpr(src)
	if err != nil {
		panic(err)
	}

	src2 := "x + 2*y"
	tree2, err := parser.ParseExpr(src2)
	if err != nil {
		panic(err)
	}
	done := make(chan struct{})
	defer close(done)

	go func() {
		ast.Walk(v1, tree1)
		close(v1.queue)
		done <- struct{}{}
	}()
	go func() {
		ast.Walk(v2, tree2)
		close(v2.queue)
		done <- struct{}{}
	}()

	var n1, n2 *ast.Node
	quit := false
	for !quit {
		select {
		case n1 = <-v1.queue:
		case n2 = <-v2.queue:
		case <-done:
			quit = true
		}
		if n1 != nil && n2 != nil {
			if !equalNodes(n1, n2) {
				println("!equalNodes")
				break
			}
			println("equalNodes")
			n1 = nil
			n2 = nil
		}
	}
}
开发者ID:rtfb,项目名称:sketchbook,代码行数:53,代码来源:parz.go


示例4: parseExpr

// parseExpr returns an ast expression from the source s
// stolen from http://golang.org/src/cmd/fix/fix.go
func parseExpr(s string) ast.Expr {
	exp, err := parser.ParseExpr(s)
	if err != nil {
		log.Println("Cannot parse expression %s :%s", s, err.Error())
	}
	return exp
}
开发者ID:skyportsystems,项目名称:goweave,代码行数:9,代码来源:ast.go


示例5: Compile

// compiles source consisting of a number of statements. E.g.:
// 	src = "a = 1; b = sin(x)"
// 	code, err := world.Compile(src)
// 	code.Eval()
func (w *World) Compile(src string) (code *BlockStmt, e error) {
	// parse
	exprSrc := "func(){\n" + src + "\n}" // wrap in func to turn into expression
	tree, err := parser.ParseExpr(exprSrc)
	if err != nil {
		return nil, fmt.Errorf("script line %v: ", err)
	}

	// catch compile errors and decode line number
	if !Debug {
		defer func() {
			err := recover()
			if err == nil {
				return
			}
			if compErr, ok := err.(*compileErr); ok {
				code = nil
				e = fmt.Errorf("script %v: %v", pos2line(compErr.pos, exprSrc), compErr.msg)
			} else {
				panic(err)
			}
		}()
	}

	// compile
	stmts := tree.(*ast.FuncLit).Body.List // strip func again
	if Debug {
		ast.Print(nil, stmts)
	}
	block := new(BlockStmt)
	for _, s := range stmts {
		block.append(w.compile(s), s)
	}
	return block, nil
}
开发者ID:callistoaz,项目名称:3,代码行数:39,代码来源:compile.go


示例6: CompileExpr

// Compiles an expression, which can then be evaluated. E.g.:
// 	expr, err := world.CompileExpr("1+1")
// 	expr.Eval()   // returns 2
func (w *World) CompileExpr(src string) (code Expr, e error) {
	// parse
	tree, err := parser.ParseExpr(src)
	if err != nil {
		return nil, fmt.Errorf(`parse "%s": %v`, src, err)
	}
	if Debug {
		ast.Print(nil, tree)
	}

	// catch compile errors
	if !Debug {
		defer func() {
			err := recover()
			if err == nil {
				return
			}
			if er, ok := err.(*compileErr); ok {
				code = nil
				e = fmt.Errorf(`parse "%s": %v`, src, er)
			} else {
				panic(err)
			}
		}()
	}
	return w.compile(tree), nil
}
开发者ID:callistoaz,项目名称:3,代码行数:30,代码来源:compile.go


示例7: asExpr

func asExpr(s string) ast.Expr {
	expr, err := parser.ParseExpr(s)
	if err != nil {
		panic(err)
	}
	return expr
}
开发者ID:tav,项目名称:bolt,代码行数:7,代码来源:bolt.go


示例8: parseTemplateAndArgs

// Parse the arguments string Template(A, B, C)
func parseTemplateAndArgs(s string) (name string, args []string) {
	expr, err := parser.ParseExpr(s)
	if err != nil {
		fatalf("Failed to parse %q: %v", s, err)
	}
	debugf("expr = %#v\n", expr)
	callExpr, ok := expr.(*ast.CallExpr)
	if !ok {
		fatalf("Failed to parse %q: expecting Identifier(...)", s)
	}
	debugf("fun = %#v", callExpr.Fun)
	fn, ok := callExpr.Fun.(*ast.Ident)
	if !ok {
		fatalf("Failed to parse %q: expecting Identifier(...)", s)
	}
	name = fn.Name
	for i, arg := range callExpr.Args {
		var buf bytes.Buffer
		debugf("arg[%d] = %#v", i, arg)
		format.Node(&buf, token.NewFileSet(), arg)
		s := buf.String()
		debugf("parsed = %q", s)
		args = append(args, s)
	}
	return
}
开发者ID:tjyang,项目名称:gotemplate,代码行数:27,代码来源:template.go


示例9: expr

func expr(s string) ast.Expr {
	x, err := parser.ParseExpr(s)
	if err != nil {
		panic("parsing " + s + ": " + err.Error())
	}
	return x
}
开发者ID:krasin,项目名称:go-deflate,代码行数:7,代码来源:fix.go


示例10: Eval

// Eval evaluates a string
func (s *Scope) Eval(str string) (interface{}, error) {
	expr, err := parser.ParseExpr("func(){" + str + "}()")
	if err != nil {
		return nil, err
	}
	return s.Interpret(expr.(*ast.CallExpr).Fun.(*ast.FuncLit).Body)
}
开发者ID:xtaci,项目名称:goeval,代码行数:8,代码来源:eval.go


示例11: parseImport

// This parses an import statement, such as "./foo/bar(int,baz.T(foo.T))",
// returning a list of types and a list of imports that are needed
// (e.g. baz and foo in the above example).
func parseImport(s string) (types []string) {
	// First, I want to cut off any preliminary directories, so the
	// import should look like a function call.
	n := strings.Index(s, "(")
	if n < 1 {
		return
	}
	start := 0
	for i := n - 1; i >= 0; i-- {
		if s[i] == '/' {
			start = i + 1
			break
		}
	}
	s = s[start:]
	// Now we just need to parse the apparent function call...
	x, _ := parser.ParseExpr(s)
	callexpr, ok := x.(*ast.CallExpr)
	if !ok {
		return
	} // FIXME: need error handling?
	for _, texpr := range callexpr.Args {
		types = append(types, pretty(texpr))
	}
	return types
}
开发者ID:johnmcconnell,项目名称:gotgo,代码行数:29,代码来源:gotimports.go


示例12: WhatisCommand

func WhatisCommand(args []string) {
	line := repl.CmdLine[len(args[0]):len(repl.CmdLine)]
	ctx := &eval.Ctx{line}
	if expr, err := parser.ParseExpr(line); err != nil {
		if pair := eval.FormatErrorPos(line, err.Error()); len(pair) == 2 {
			repl.Msg(pair[0])
			repl.Msg(pair[1])
		}
		repl.Errmsg("parse error: %s\n", err)
	} else {
		cexpr, errs := eval.CheckExpr(ctx, expr, repl.Env)
		if len(errs) != 0 {
			for _, cerr := range errs {
				repl.Msg("%v", cerr)
			}
		} else {
			repl.Section(cexpr.String())
			if cexpr.IsConst() {
				repl.Msg("constant:\t%s", cexpr.Const())
			}
			knownTypes := cexpr.KnownType()
			if len(knownTypes) == 1 {
				repl.Msg("type:\t%s", knownTypes[0])
			} else {
				for i, v := range knownTypes {
					repl.Msg("type[%d]:\t%s", i, v)
				}
			}
		}
	}
}
开发者ID:raff,项目名称:go-fish,代码行数:31,代码来源:whatis.go


示例13: deduce_cursor_decl

// this function is called when the cursor is at the '.' and you need to get the
// declaration before that dot
func (c *auto_complete_context) deduce_cursor_decl(iter *token_iterator) *decl {
	expr, err := parser.ParseExpr(iter.extract_go_expr())
	if err != nil {
		return nil
	}
	return expr_to_decl(expr, c.current.scope)
}
开发者ID:agamem,项目名称:gocode,代码行数:9,代码来源:cursorcontext.go


示例14: main

func main() {
	// src is the input for which we want to inspect the AST.
	exprs := []string{
		"\"quoted\" string with backslash \\",
		"f(3.14)*2 + c",
		"-2  ", // trailing spaces to be devius
		" 5 == 6",
		"5\t< 6", // that's a tab in there
		"1+2",
		"(1+2)*3",
		"1 << n",
		"1 << 8",
		"y(",
	}

	for _, expr := range exprs {
		// Create the AST by parsing expr.
		f, err := parser.ParseExpr(expr)
		if err != nil {
			fmt.Printf("Error parsing %s: %s", expr, err.Error())
			continue
		}

		// Inspect the AST and print all identifiers and literals.
		if v := evalAction(f); v != nil {
			fmt.Printf("Eval: '%s' ok; value: %s\n", expr, v)
		} else {
			fmt.Printf("Eval '%s' no good\n", expr)
		}
		fmt.Println("--------------")
	}
}
开发者ID:rocky,项目名称:ssa-interp,代码行数:32,代码来源:expr.go


示例15: parse

func parse(x string) ast.Expr {
	expr, err := parser.ParseExpr(x)
	if err != nil {
		panic(err)
	}
	return expr
}
开发者ID:ronakbanka,项目名称:goken,代码行数:7,代码来源:visitor_test.go


示例16: Parse

func (p *predicateParser) Parse(in string) (interface{}, error) {
	expr, err := parser.ParseExpr(in)
	if err != nil {
		return nil, err
	}
	return p.parseNode(expr)
}
开发者ID:huhoo,项目名称:vulcand,代码行数:7,代码来源:parse.go


示例17: TestTypeExpr

func TestTypeExpr(t *testing.T) {
	for typeStr, expected := range TypeExprs {
		// Handle arrays and ... myself, since ParseExpr() does not.
		array := strings.HasPrefix(typeStr, "[]")
		if array {
			typeStr = typeStr[2:]
		}

		ellipsis := strings.HasPrefix(typeStr, "...")
		if ellipsis {
			typeStr = typeStr[3:]
		}

		expr, err := parser.ParseExpr(typeStr)
		if err != nil {
			t.Error("Failed to parse test expr:", typeStr)
			continue
		}

		if array {
			expr = &ast.ArrayType{expr.Pos(), nil, expr}
		}
		if ellipsis {
			expr = &ast.Ellipsis{expr.Pos(), expr}
		}

		actual := NewTypeExpr("pkg", expr)
		if !reflect.DeepEqual(expected, actual) {
			t.Error("Fail, expected", expected, ", was", actual)
		}
	}
}
开发者ID:ubik86,项目名称:revel,代码行数:32,代码来源:reflect_test.go


示例18: expectConst

func expectConst(t *testing.T, expr string, env *Env, expected interface{}, expectedType reflect.Type) {
	ctx := &Ctx{expr}
	if e, err := parser.ParseExpr(expr); err != nil {
		t.Fatalf("Failed to parse expression '%s' (%v)", expr, err)
	} else if aexpr, errs := CheckExpr(ctx, e, env); errs != nil {
		t.Fatalf("Failed to check expression '%s' (%v)", expr, errs)
	} else if !aexpr.IsConst() {
		t.Fatalf("Expression '%s' did not yield a const node(%+v)", expr, aexpr)
	} else if expectedNumber, ok := expected.(*ConstNumber); ok {
		if actual, ok2 := aexpr.Const().Interface().(*ConstNumber); !ok2 {
			t.Fatalf("Expression '%s' yielded '%v', expected '%v'", expr, aexpr.Const(), expected)
		} else if !actual.Value.Equals(&expectedNumber.Value) {
			t.Fatalf("Expression '%s' yielded '%v', expected '%v'", expr, actual, expected)
		} else if len(aexpr.KnownType()) == 0 {
			t.Fatalf("Expression '%s' expected to have type '%v'", expr, expectedType)
		} else if actual := aexpr.KnownType()[0]; !typesEqual(expectedType, actual) {
			t.Fatalf("Expression '%s' has type '%v', expected '%v'", expr, actual, expectedType)
		}
	} else {
		if actual := aexpr.Const().Interface(); !reflect.DeepEqual(actual, expected) {
			t.Fatalf("Expression '%s' yielded '%+v', expected '%+v'", expr, actual, expected)
		} else if len(aexpr.KnownType()) == 0 {
			t.Fatalf("Expression '%s' expected to have type '%v'", expr, expectedType)
		} else if actual := aexpr.KnownType()[0]; !typesEqual(expectedType, actual) {
			t.Fatalf("Expression '%s' has type '%v', expected '%v'", expr, t, expectedType)
		}
	}
}
开发者ID:raff,项目名称:eval,代码行数:28,代码来源:helper_for_test.go


示例19: expectCheckError

func expectCheckError(t *testing.T, expr string, env *Env, errorString ...string) {
	ctx := &Ctx{expr}
	if e, err := parser.ParseExpr(expr); err != nil {
		t.Fatalf("Failed to parse expression '%s' (%v)", expr, err)
	} else if _, errs := CheckExpr(ctx, e, env); errs != nil {
		var i int
		out := "\n"
		ok := true
		for i = 0; i < len(errorString); i += 1 {
			if i >= len(errs) {
				out += fmt.Sprintf("%d. Expected `%v` missing\n", i, errorString[i])
				ok = false
			} else if errorString[i] == errs[i].Error() {
				out += fmt.Sprintf("%d. Expected `%v` == `%v`\n", i, errorString[i], errs[i])
			} else {
				out += fmt.Sprintf("%d. Expected `%v` != `%v`\n", i, errorString[i], errs[i])
				ok = false
			}
		}
		for ; i < len(errs); i += 1 {
			out += fmt.Sprintf("%d. Unexpected `%v`\n", i, errs[i])
			ok = false
		}
		if !ok {
			t.Fatalf("%sWrong check errors for expression '%s'", out, expr)
		}
	} else {
		for i, s := range errorString {
			t.Logf("%d. Expected `%v` missing\n", i, s)
		}
		t.Fatalf("Missing check errors for expression '%s'", expr)
	}
}
开发者ID:raff,项目名称:eval,代码行数:33,代码来源:helper_for_test.go


示例20: TestIsPkgAddressable

func TestIsPkgAddressable(t *testing.T) {
	env := MakeSimpleEnv()
	env.Pkgs["a"] = MakeSimpleEnv()
	env.Pkgs["a"].(*SimpleEnv).Vars["v"] = reflect.ValueOf(new(int))
	env.Pkgs["a"].(*SimpleEnv).Funcs["f"] = reflect.ValueOf(func() {})
	v, _ := parser.ParseExpr("a.v")
	vv, _ := CheckExpr(v, env)
	if !isAddressable(vv) {
		t.Fatalf("expected package var 'a.v' to be addressible")
	}

	f, _ := parser.ParseExpr("a.f")
	ff, _ := CheckExpr(f, env)
	if isAddressable(ff) {
		t.Fatalf("expected package func 'a.f' to be unaddressible")
	}
}
开发者ID:philipmulcahy,项目名称:godebug,代码行数:17,代码来源:util_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang parser.ParseFile函数代码示例发布时间:2022-05-28
下一篇:
Golang parser.ParseDir函数代码示例发布时间: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