当前位置: 首页>>代码示例>>Golang>>正文


Golang parser.Mode函数代码示例

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


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


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