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

Golang parser.Mode函数代码示例

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

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



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

示例1: initParserMode

func initParserMode() {
	parserMode = parser.Mode(0)
	parserMode |= parser.ParseComments
	if *allErrors {
		parserMode |= parser.AllErrors
	}
}
开发者ID:kelsieflynn,项目名称:goimports,代码行数:7,代码来源:goimports.go


示例2: GrokDir

func GrokDir(dir string) {
	pkgs, err := parser.ParseDir(fset, dir, FilterDotGo, parser.Mode(0))
	if err != nil {
		panic(Sprintf("ERROR <%q> IN DIR <%s>", err, dir))
	}

	// Find the subdir that follows /pkg/
	subdir := AfterFirstDelim(dir, "/pkg/", "")
	if len(subdir) == 0 {
		panic("dir does not contain /pkg/ plus a tail: " + dir)
	}

	// Trim trailing /, if any.
	if subdir[len(subdir)-1] == '/' {
		subdir = subdir[:len(subdir)-1]
	}

	for pk, pv := range pkgs {
		// For dirpkg, remove final piece of subdir
		// and replace with stated package name.
		// Often these are the same, but not always.
		updir := BeforeFinalDelim(subdir, "/", "")
		dirpkg := Cond(updir == "", pk, updir+"/"+pk)

		Printf("#dirpkg %#v\n", dirpkg)
		Printf("#pv %#v\n", pv)

		for _, fv := range pv.Files {
			for i, dcl := range fv.Decls {
				doDecl(dcl, i, dirpkg)
			}
		}
	}
}
开发者ID:strickyak,项目名称:pyrrhus,代码行数:34,代码来源:grok.go


示例3: goInitParserMode

func goInitParserMode() {
	goParserMode = parser.Mode(0)
	if *comments {
		goParserMode |= parser.ParseComments
	}
	goParserMode |= parser.AllErrors
}
开发者ID:shaunstanislaus,项目名称:igo,代码行数:7,代码来源:from_go.go


示例4: TestBump

func TestBump(t *testing.T) {
	fset := token.NewFileSet()
	pkgs, err := parser.ParseDir(fset, "testdata/test1", nil, parser.Mode(0))
	if err != nil {
		t.Fatal(err)
	}

	conf := Config{
		MinorDelta: 1,
	}

	for _, pkg := range pkgs {
		for _, f := range pkg.Files {
			vers, err := conf.ProcessNode(fset, f)
			if err != nil {
				t.Errorf("got error: %s", err)
			}
			if _, ok := vers["version"]; !ok {
				t.Errorf("should detect `version`")
			}
			if _, ok := vers["VERSION"]; !ok {
				t.Errorf("should detect `VERSION`")
			}
			if vers["version"] != "1.1.0" {
				t.Errorf("expected %v: got %v", "1.1.0", vers["version"])
			}
			if vers["VERSION"] != "2.1.0" {
				t.Errorf("expected %v: got %v", "2.1.0", vers["VERSION"])
			}
		}
	}
}
开发者ID:motemen,项目名称:gobump,代码行数:32,代码来源:gobump_test.go


示例5: fastQueryPos

// fastQueryPos parses the position string and returns a queryPos.
// It parses only a single file and does not run the type checker.
func fastQueryPos(ctxt *build.Context, pos string) (*queryPos, error) {
	filename, startOffset, endOffset, err := parsePos(pos)
	if err != nil {
		return nil, err
	}

	// Parse the file, opening it the file via the build.Context
	// so that we observe the effects of the -modified flag.
	fset := token.NewFileSet()
	cwd, _ := os.Getwd()
	f, err := buildutil.ParseFile(fset, ctxt, nil, cwd, filename, parser.Mode(0))
	// ParseFile usually returns a partial file along with an error.
	// Only fail if there is no file.
	if f == nil {
		return nil, err
	}
	if !f.Pos().IsValid() {
		return nil, fmt.Errorf("%s is not a Go source file", filename)
	}

	start, end, err := fileOffsetToPos(fset.File(f.Pos()), startOffset, endOffset)
	if err != nil {
		return nil, err
	}

	path, exact := astutil.PathEnclosingInterval(f, start, end)
	if path == nil {
		return nil, fmt.Errorf("no syntax here")
	}

	return &queryPos{fset, start, end, path, exact, nil}, nil
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:34,代码来源:pos.go


示例6: initParserMode

func initParserMode() {
	parserMode = parser.Mode(0)
	if *comments {
		parserMode |= parser.ParseComments
	}
	if *allErrors {
		parserMode |= parser.SpuriousErrors
	}
}
开发者ID:krasin,项目名称:go-deflate,代码行数:9,代码来源:gofmt.go


示例7: importPackages

// importPackages includes packages defined on external file into main file
func (s *Session) importPackages(src []byte) error {
	astf, err := parser.ParseFile(s.Fset, "", src, parser.Mode(0))
	if err != nil {
		return err
	}

	for _, imt := range astf.Imports {
		debugf("import package: %s", imt.Path.Value)
		actionImport(s, imt.Path.Value)
	}

	return nil
}
开发者ID:jonfk,项目名称:gore,代码行数:14,代码来源:main.go


示例8: applyAroundAdvice

// applyAroundAdvice uses code from gofmt to wrap any after advice
// essentially this is the same stuff you could do w/the cmdline tool,
// gofmt
//
// FIXME - mv to CallExpr
//
// looks for call joinpoints && provides around advice capability
//
// this is currently a hack to support deferpanic's http lib
func (w *Weave) applyAroundAdvice(fname string) string {

	stuff := fileAsStr(fname)

	importsNeeded := []string{}

	for i := 0; i < len(w.aspects); i++ {
		aspect := w.aspects[i]
		if aspect.advize.around != "" {
			pk := aspect.pointkut
			around_advice := aspect.advize.around

			fset := token.NewFileSet()
			file, err := parser.ParseFile(fset, fname, stuff, parser.Mode(0))
			if err != nil {
				w.flog.Println("Failed to parse source: %s", err.Error())
			}

			// needs match groups
			// wildcards of d,s...etc.
			p := parseExpr(pk.def)
			val := parseExpr(around_advice)

			file = rewriteFile2(p, val, file)

			buf := new(bytes.Buffer)
			err = format.Node(buf, fset, file)
			if err != nil {
				w.flog.Println("Failed to format post-replace source: %v", err)
			}

			actual := buf.String()

			w.writeOut(fname, actual)

			stuff = actual

			for t := 0; t < len(aspect.importz); t++ {
				importsNeeded = append(importsNeeded, aspect.importz[t])
			}

		}
	}

	if len(importsNeeded) > 0 {
		// add any imports for this piece of advice
		stuff = w.writeMissingImports(fname, stuff, importsNeeded)
	}

	return stuff
}
开发者ID:skyportsystems,项目名称:goweave,代码行数:60,代码来源:transform.go


示例9: findPackageMember

// findPackageMember returns the type and position of the declaration of
// pkg.member by loading and parsing the files of that package.
// srcdir is the directory in which the import appears.
func findPackageMember(ctxt *build.Context, fset *token.FileSet, srcdir, pkg, member string) (token.Token, token.Pos, error) {
	bp, err := ctxt.Import(pkg, srcdir, 0)
	if err != nil {
		return 0, token.NoPos, err // no files for package
	}

	// TODO(adonovan): opt: parallelize.
	for _, fname := range bp.GoFiles {
		filename := filepath.Join(bp.Dir, fname)

		// Parse the file, opening it the file via the build.Context
		// so that we observe the effects of the -modified flag.
		f, _ := buildutil.ParseFile(fset, ctxt, nil, ".", filename, parser.Mode(0))
		if f == nil {
			continue
		}

		// Find a package-level decl called 'member'.
		for _, decl := range f.Decls {
			switch decl := decl.(type) {
			case *ast.GenDecl:
				for _, spec := range decl.Specs {
					switch spec := spec.(type) {
					case *ast.ValueSpec:
						// const or var
						for _, id := range spec.Names {
							if id.Name == member {
								return decl.Tok, id.Pos(), nil
							}
						}
					case *ast.TypeSpec:
						if spec.Name.Name == member {
							return token.TYPE, spec.Name.Pos(), nil
						}
					case *ast.AliasSpec:
						if spec.Name.Name == member {
							return decl.Tok, spec.Name.Pos(), nil
						}
					}
				}
			case *ast.FuncDecl:
				if decl.Recv == nil && decl.Name.Name == member {
					return token.FUNC, decl.Name.Pos(), nil
				}
			}
		}
	}

	return 0, token.NoPos, fmt.Errorf("couldn't find declaration of %s in %q", member, pkg)
}
开发者ID:syreclabs,项目名称:go-tools,代码行数:53,代码来源:definition18.go


示例10: applyGlobalAdvice

// applyGlobalAdvice applies any global scoped advice
// if advice has already been placed in this pkg than we skip
// no support for sub-pkgs yet
// FIXME
func (w *Weave) applyGlobalAdvice(fname string, stuff string) string {
	if w.appliedGlobal {
		return stuff
	}

	rout := stuff

	importsNeeded := []string{}

	for i := 0; i < len(w.aspects); i++ {
		aspect := w.aspects[i]
		if aspect.pointkut.def != "*" {
			continue
		}

		before_advice := aspect.advize.before
		after_advice := aspect.advize.after

		w.appliedGlobal = true

		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, fname, rout, parser.Mode(0))
		if err != nil {
			w.flog.Println("Failed to parse source: %s", err.Error())
		}

		// endOfImport returns the line after the import statement
		// used to add global advice
		// just a guess here - doubt this is ordered
		ilen := len(file.Imports)
		s := file.Imports[ilen-1].End()
		ei := fset.Position(s).Line + 1

		if before_advice != "" {
			rout = w.writeAtLine(fname, ei, before_advice)
		}

		if after_advice != "" {
			rout = w.writeAtLine(fname, ei, after_advice)
		}

	}

	if len(importsNeeded) > 0 {
		rout = w.writeMissingImports(fname, rout, importsNeeded)
	}

	return rout
}
开发者ID:skyportsystems,项目名称:goweave,代码行数:53,代码来源:transform.go


示例11: reset

func (s *Session) reset() error {
	source, err := s.source(false)
	if err != nil {
		return err
	}

	file, err := parser.ParseFile(s.Fset, "gore_session.go", source, parser.Mode(0))
	if err != nil {
		return err
	}

	s.File = file
	s.mainBody = s.mainFunc().Body

	return nil
}
开发者ID:jonfk,项目名称:gore,代码行数:16,代码来源:main.go


示例12: TestDeadCode

func TestDeadCode(t *testing.T) {
	// We'll use dead code detection to verify the CFG.

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "dummy.go", src, parser.Mode(0))
	if err != nil {
		t.Fatal(err)
	}
	for _, decl := range f.Decls {
		if decl, ok := decl.(*ast.FuncDecl); ok {
			g := New(decl.Body, mayReturn)

			// Mark blocks reachable from entry.
			live := make(map[*Block]bool)
			var visit func(*Block)
			visit = func(b *Block) {
				if !live[b] {
					live[b] = true
					for _, succ := range b.Succs {
						visit(succ)
					}
				}
			}
			visit(g.Blocks[0])

			// Print statements in unreachable blocks
			// (in order determined by builder).
			var buf bytes.Buffer
			for _, b := range g.Blocks {
				if !live[b] {
					for _, n := range b.Nodes {
						fmt.Fprintf(&buf, "\t%s\n", formatNode(fset, n))
					}
				}
			}

			// Check that the result contains "dead" at least once but not "live".
			if !bytes.Contains(buf.Bytes(), []byte("dead")) ||
				bytes.Contains(buf.Bytes(), []byte("live")) {
				t.Errorf("unexpected dead statements in function %s:\n%s",
					decl.Name.Name,
					&buf)
				t.Logf("control flow graph:\n%s", g.Format(fset))
			}
		}
	}
}
开发者ID:Xiahl1990,项目名称:go,代码行数:47,代码来源:cfg_test.go


示例13: importFile

// importFile adds external golang file to goRun target to use its function
func (s *Session) importFile(src []byte) error {
	// Don't need to same directory
	tmp, err := ioutil.TempFile(filepath.Dir(s.FilePath), "gore_extarnal_")
	if err != nil {
		return err
	}

	ext := tmp.Name() + ".go"

	f, err := parser.ParseFile(s.Fset, ext, src, parser.Mode(0))
	if err != nil {
		return err
	}

	// rewrite to package main
	f.Name.Name = "main"

	// remove func main()
	for i, decl := range f.Decls {
		if funcDecl, ok := decl.(*ast.FuncDecl); ok {
			if isNamedIdent(funcDecl.Name, "main") {
				f.Decls = append(f.Decls[0:i], f.Decls[i+1:]...)
				// main() removed from this file, we may have to
				// remove some unsed import's
				quickfix.QuickFix(s.Fset, []*ast.File{f})
				break
			}
		}
	}

	out, err := os.Create(ext)
	if err != nil {
		return err
	}
	defer out.Close()

	err = printer.Fprint(out, s.Fset, f)
	if err != nil {
		return err
	}

	debugf("import file: %s", ext)
	s.ExtraFilePaths = append(s.ExtraFilePaths, ext)
	s.ExtraFiles = append(s.ExtraFiles, f)

	return nil
}
开发者ID:jonfk,项目名称:gore,代码行数:48,代码来源:main.go


示例14: doDir

func doDir(name string) {
	notests := func(info os.FileInfo) bool {
		if !info.IsDir() && strings.HasSuffix(info.Name(), ".go") &&
			(!strings.HasSuffix(info.Name(), "_test.go") || *includeTests) {
			return true
		}
		return false
	}
	fs := token.NewFileSet()
	pkgs, err := parser.ParseDir(fs, name, notests, parser.Mode(0))
	if err != nil {
		errorf("%s", err)
		return
	}
	for _, pkg := range pkgs {
		doPackage(fs, pkg)
	}
}
开发者ID:robmurtha,项目名称:go-misc,代码行数:18,代码来源:deadcode.go


示例15: fixImports

// fixImports formats and adjusts imports for the current AST.
func (s *Session) fixImports() error {

	var buf bytes.Buffer
	err := printer.Fprint(&buf, s.Fset, s.File)
	if err != nil {
		return err
	}

	formatted, err := imports.Process("", buf.Bytes(), nil)
	if err != nil {
		return err
	}

	s.File, err = parser.ParseFile(s.Fset, "", formatted, parser.Mode(0))
	if err != nil {
		return err
	}
	s.mainBody = s.mainFunc().Body

	return nil
}
开发者ID:jonfk,项目名称:gore,代码行数:22,代码来源:main.go


示例16: NewSession

func NewSession() (*Session, error) {
	var err error

	s := &Session{
		Fset: token.NewFileSet(),
		Types: &types.Config{
			Packages: make(map[string]*types.Package),
		},
	}

	s.FilePath, err = tempFile()
	if err != nil {
		return nil, err
	}

	var initialSource string
	for _, pp := range printerPkgs {
		_, err := types.DefaultImport(s.Types.Packages, pp.path)
		if err == nil {
			initialSource = fmt.Sprintf(initialSourceTemplate, pp.path, pp.code)
			break
		}
		debugf("could not import %q: %s", pp.path, err)
	}

	if initialSource == "" {
		return nil, fmt.Errorf(`Could not load pretty printing package (even "fmt"; something is wrong)`)
	}

	s.File, err = parser.ParseFile(s.Fset, "gore_session.go", initialSource, parser.Mode(0))
	if err != nil {
		return nil, err
	}

	s.mainBody = s.mainFunc().Body

	return s, nil
}
开发者ID:jonfk,项目名称:gore,代码行数:38,代码来源:main.go


示例17: NewSession

// NewSession initiates a new REPL
func NewSession() (*Session, error) {

	s := &Session{
		Fset: token.NewFileSet(),
		Types: &types.Config{
			Importer: importer.Default(),
		},
	}

	var err error
	s.FilePath, err = tempFile()
	if err != nil {
		return nil, err
	}

	var initialSource string
	for _, pp := range printerPkgs {
		_, err := importer.Default().Import(pp.path)
		if err == nil {
			initialSource = fmt.Sprintf(initialSourceTemplate, pp.path, pp.code)
			break
		}
		debugf("could not import %q: %s", pp.path, err)
	}
	if initialSource == "" {
		return nil, fmt.Errorf("Could not load pretty printing package")
	}

	s.File, err = parser.ParseFile(s.Fset, "gophernotes_session.go", initialSource, parser.Mode(0))
	if err != nil {
		return nil, err
	}

	s.mainBody = s.mainFunc().Body

	return s, nil
}
开发者ID:gopherds,项目名称:gophernotes,代码行数:38,代码来源:repl.go


示例18: evalStmt

func (s *Session) evalStmt(in string) error {
	src := fmt.Sprintf("package P; func F() { %s }", in)
	f, err := parser.ParseFile(s.Fset, "stmt.go", src, parser.Mode(0))
	if err != nil {
		return err
	}

	enclosingFunc := f.Scope.Lookup("F").Decl.(*ast.FuncDecl)
	stmts := enclosingFunc.Body.List

	if len(stmts) > 0 {
		debugf("evalStmt :: %s", showNode(s.Fset, stmts))
		lastStmt := stmts[len(stmts)-1]
		// print last assigned/defined values
		if assign, ok := lastStmt.(*ast.AssignStmt); ok {
			vs := []ast.Expr{}
			for _, v := range assign.Lhs {
				if !isNamedIdent(v, "_") {
					vs = append(vs, v)
				}
			}
			if len(vs) > 0 {
				printLastValues := &ast.ExprStmt{
					X: &ast.CallExpr{
						Fun:  ast.NewIdent(printerName),
						Args: vs,
					},
				}
				stmts = append(stmts, printLastValues)
			}
		}
	}

	s.appendStatements(stmts...)

	return nil
}
开发者ID:billf,项目名称:gore,代码行数:37,代码来源:main.go


示例19: applySetJP

// applySetJP applies any advice for set joinpoints
func (w *Weave) applySetJP(fname string, stuff string) string {

	rout := stuff

	importsNeeded := []string{}

	for i := 0; i < len(w.aspects); i++ {

		aspect := w.aspects[i]
		if !aspect.pointkut.isSet() {
			continue
		}

		pk := aspect.pointkut.def

		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, fname, rout, parser.Mode(0))
		if err != nil {
			w.flog.Println("Failed to parse source: %s", err.Error())
		}

		linecnt := 0

		for _, decl := range file.Decls {
			fn, ok := decl.(*ast.FuncDecl)
			if !ok {
				continue
			}

			for x := 0; x < len(fn.Body.List); x++ {
				begin := 0
				after := 0

				as, ok2 := fn.Body.List[x].(*ast.SendStmt)
				if !ok2 {

					// look for assignment
					//*ast.AssignStmt
					as, ok3 := fn.Body.List[x].(*ast.AssignStmt)
					if !ok3 {
						continue
					}

					// no multiple-return support yet
					blah := as.Lhs[0].(*ast.Ident).Name

					if pk != blah {
						continue
					}

					begin = fset.Position(as.Pos()).Line - 1
					after = fset.Position(as.End()).Line + 1

				} else {
					// look for channel
					as3, ok3 := as.Chan.(*ast.Ident)
					if !ok3 {
						continue
					}

					if as3.Name != pk {
						continue
					}

					begin = fset.Position(as.Pos()).Line - 1
					after = fset.Position(as.End()).Line + 1

				}

				// figure out type

				//				begin := fset.Position(as.Pos()).Line - 1
				//				after := fset.Position(as.End()).Line + 1

				before_advice := aspect.advize.before
				after_advice := aspect.advize.after

				if before_advice != "" {
					rout = w.writeAtLine(fname, begin+linecnt, before_advice)
					linecnt += strings.Count(before_advice, "\n") + 1
				}

				if after_advice != "" {
					rout = w.writeAtLine(fname, after+linecnt-1, after_advice)

					linecnt += strings.Count(after_advice, "\n") + 1
				}

			}
		}

	}

	if len(importsNeeded) > 0 {
		// add any imports for this piece of advice
		rout = w.writeMissingImports(fname, rout, importsNeeded)
	}

	return rout
//.........这里部分代码省略.........
开发者ID:AkihiroSuda,项目名称:goweave,代码行数:101,代码来源:set.go


示例20: parse

// parse parses src, which was read from filename,
// as a Go source file or statement list.
func parse(fset *token.FileSet, filename string, src []byte, opt *Options) (*ast.File, func(orig, src []byte) []byte, error) {
	parserMode := parser.Mode(0)
	if opt.Comments {
		parserMode |= parser.ParseComments
	}
	if opt.AllErrors {
		parserMode |= parser.AllErrors
	}

	// Try as whole source file.
	file, err := parser.ParseFile(fset, filename, src, parserMode)
	if err == nil {
		return file, nil, nil
	}
	// If the error is that the source file didn't begin with a
	// package line and we accept fragmented input, fall through to
	// try as a source fragment.  Stop and return on any other error.
	if !opt.Fragment || !strings.Contains(err.Error(), "expected 'package'") {
		return nil, nil, err
	}

	// If this is a declaration list, make it a source file
	// by inserting a package clause.
	// Insert using a ;, not a newline, so that the line numbers
	// in psrc match the ones in src.
	psrc := append([]byte("package main;"), src...)
	file, err = parser.ParseFile(fset, filename, psrc, parserMode)
	if err == nil {
		// If a main function exists, we will assume this is a main
		// package and leave the file.
		if containsMainFunc(file) {
			return file, nil, nil
		}

		adjust := func(orig, src []byte) []byte {
			// Remove the package clause.
			// Gofmt has turned the ; into a \n.
			src = src[len("package main\n"):]
			return matchSpace(orig, src)
		}
		return file, adjust, nil
	}
	// If the error is that the source file didn't begin with a
	// declaration, fall through to try as a statement list.
	// Stop and return on any other error.
	if !strings.Contains(err.Error(), "expected declaration") {
		return nil, nil, err
	}

	// If this is a statement list, make it a source file
	// by inserting a package clause and turning the list
	// into a function body.  This handles expressions too.
	// Insert using a ;, not a newline, so that the line numbers
	// in fsrc match the ones in src.
	fsrc := append(append([]byte("package p; func _() {"), src...), '}')
	file, err = parser.ParseFile(fset, filename, fsrc, parserMode)
	if err == nil {
		adjust := func(orig, src []byte) []byte {
			// Remove the wrapping.
			// Gofmt has turned the ; into a \n\n.
			src = src[len("package p\n\nfunc _() {"):]
			src = src[:len(src)-len("}\n")]
			// Gofmt has also indented the function body one level.
			// Remove that indent.
			src = bytes.Replace(src, []byte("\n\t"), []byte("\n"), -1)
			return matchSpace(orig, src)
		}
		return file, adjust, nil
	}

	// Failed, and out of options.
	return nil, nil, err
}
开发者ID:4honor,项目名称:obdi,代码行数:75,代码来源:imports.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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