How to use collectUnused method of compiler Package

Best Syzkaller code snippet using compiler.collectUnused

compiler_test.go

Source:compiler_test.go Github

copy

Full Screen

1// Copyright 2017 syzkaller project authors. All rights reserved.2// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.3package compiler4import (5 "bytes"6 "flag"7 "fmt"8 "io/ioutil"9 "path/filepath"10 "reflect"11 "sort"12 "testing"13 "github.com/google/syzkaller/pkg/ast"14 "github.com/google/syzkaller/pkg/serializer"15 "github.com/google/syzkaller/sys/targets"16)17var flagUpdate = flag.Bool("update", false, "reformat all.txt")18func TestCompileAll(t *testing.T) {19 for os, arches := range targets.List {20 os, arches := os, arches21 t.Run(os, func(t *testing.T) {22 t.Parallel()23 eh := func(pos ast.Pos, msg string) {24 t.Logf("%v: %v", pos, msg)25 }26 path := filepath.Join("..", "..", "sys", os)27 desc := ast.ParseGlob(filepath.Join(path, "*.txt"), eh)28 if desc == nil {29 t.Fatalf("parsing failed")30 }31 for arch, target := range arches {32 arch, target := arch, target33 t.Run(arch, func(t *testing.T) {34 t.Parallel()35 errors := new(bytes.Buffer)36 eh := func(pos ast.Pos, msg string) {37 fmt.Fprintf(errors, "%v: %v\n", pos, msg)38 }39 defer func() {40 t.Logf("\n%s", errors.Bytes())41 }()42 consts := DeserializeConstFile(filepath.Join(path, "*.const"), eh).Arch(arch)43 if consts == nil {44 t.Fatalf("reading consts failed")45 }46 prog := Compile(desc, consts, target, eh)47 if prog == nil {48 t.Fatalf("compilation failed")49 }50 })51 }52 })53 }54}55func TestData(t *testing.T) {56 t.Parallel()57 // Compile the canned descriptions in testdata and match expected errors.58 // Errors are produced in batches in different compilation phases.59 // If one phase produces errors, subsequent phases are not executed.60 // E.g. if we failed to parse descriptions, we won't run type checking at all.61 // Because of this we have one file per phase.62 for _, name := range []string{"errors.txt", "errors2.txt", "errors3.txt", "warnings.txt", "all.txt"} {63 for _, arch := range []string{targets.TestArch32Shmem, targets.TestArch64} {64 name, arch := name, arch65 t.Run(fmt.Sprintf("%v/%v", name, arch), func(t *testing.T) {66 t.Parallel()67 target := targets.List[targets.TestOS][arch]68 fileName := filepath.Join("testdata", name)69 em := ast.NewErrorMatcher(t, fileName)70 astDesc := ast.Parse(em.Data, name, em.ErrorHandler)71 if astDesc == nil {72 em.DumpErrors()73 t.Fatalf("parsing failed")74 }75 constInfo := ExtractConsts(astDesc, target, em.ErrorHandler)76 if name == "errors.txt" {77 em.Check()78 return79 }80 if constInfo == nil {81 em.DumpErrors()82 t.Fatalf("const extraction failed")83 }84 consts := map[string]uint64{85 "SYS_foo": 1,86 "C0": 0,87 "C1": 1,88 "C2": 2,89 "U8_MAX": 0xff,90 "U16_MAX": 0xffff,91 }92 FabricateSyscallConsts(target, constInfo, consts)93 delete(consts, "SYS_unsupported")94 desc := Compile(astDesc, consts, target, em.ErrorHandler)95 if name == "errors2.txt" || name == "errors3.txt" {96 em.Check()97 return98 }99 if desc == nil {100 em.DumpErrors()101 t.Fatalf("compilation failed")102 }103 if name == "warnings.txt" {104 em.Check()105 return106 }107 if formatted := ast.Format(astDesc); !bytes.Equal(em.Data, formatted) {108 if *flagUpdate {109 ioutil.WriteFile(fileName, formatted, 0644)110 }111 t.Fatalf("description is not formatted")112 }113 if len(desc.Unsupported) != 0 {114 t.Fatalf("something is unsupported:\n%+v", desc.Unsupported)115 }116 out := new(bytes.Buffer)117 fmt.Fprintf(out, "\n\nRESOURCES:\n")118 serializer.Write(out, desc.Resources)119 fmt.Fprintf(out, "\n\nSYSCALLS:\n")120 serializer.Write(out, desc.Syscalls)121 if false {122 t.Log(out.String()) // useful for debugging123 }124 })125 }126 }127}128func TestFuzz(t *testing.T) {129 t.Parallel()130 for _, data := range []string{131 `132type H b[A]133type b[L] {134 m b[u:L]135 l b[z:L]136 m b[V:L]137 m b[0:L]138 H b[o:L]139}140`,141 `142type p b[L]143type b[L]{144 e b[3:L]145 e b[2:L]146 e b[1[L]]147 k b[H]148 k b[Q]149}`,150 "d~^gB̉`i\u007f?\xb0.",151 "da[",152 "define\x98define(define\x98define\x98define\x98define\x98define)define\tdefin",153 "resource g[g]",154 `t[155l t156]`,157 `t()D[0]158type D[e]l`,159 "E",160 "#",161 `162type p b[L]163type b[L] {164 e b[L[L]]165}`,166 `167p() b[len]168type b[b] b169`,170 `171p() b[len[opt]]172type b[b] b173`,174 } {175 Fuzz([]byte(data)[:len(data):len(data)])176 }177}178func TestAlign(t *testing.T) {179 t.Parallel()180 const input = `181foo$0(a ptr[in, s0])182s0 {183 f0 int8184 f1 int16185}186foo$1(a ptr[in, s1])187s1 {188 f0 ptr[in, s2, opt]189}190s2 {191 f1 s1192 f2 array[s1, 2]193 f3 array[array[s1, 2], 2]194}195 `196 eh := func(pos ast.Pos, msg string) {197 t.Errorf("%v: %v", pos, msg)198 }199 desc := ast.Parse([]byte(input), "input", eh)200 if desc == nil {201 t.Fatal("failed to parse")202 }203 p := Compile(desc, map[string]uint64{"SYS_foo": 1}, targets.List[targets.TestOS][targets.TestArch64], eh)204 if p == nil {205 t.Fatal("failed to compile")206 }207}208func TestCollectUnusedError(t *testing.T) {209 t.Parallel()210 const input = `211 s0 {212 f0 fidl_string213 }214 `215 nopErrorHandler := func(pos ast.Pos, msg string) {}216 desc := ast.Parse([]byte(input), "input", nopErrorHandler)217 if desc == nil {218 t.Fatal("failed to parse")219 }220 _, err := CollectUnused(desc, targets.List[targets.TestOS][targets.TestArch64], nopErrorHandler)221 if err == nil {222 t.Fatal("CollectUnused should have failed but didn't")223 }224}225func TestCollectUnused(t *testing.T) {226 t.Parallel()227 inputs := []struct {228 text string229 names []string230 }{231 {232 text: `233 s0 {234 f0 string235 }236 `,237 names: []string{"s0"},238 },239 {240 text: `241 foo$0(a ptr[in, s0])242 s0 {243 f0 int8244 f1 int16245 }246 `,247 names: []string{},248 },249 {250 text: `251 s0 {252 f0 int8253 f1 int16254 }255 s1 {256 f2 int32257 }258 foo$0(a ptr[in, s0])259 `,260 names: []string{"s1"},261 },262 }263 for i, input := range inputs {264 desc := ast.Parse([]byte(input.text), "input", nil)265 if desc == nil {266 t.Fatalf("Test %d: failed to parse", i)267 }268 nodes, err := CollectUnused(desc, targets.List[targets.TestOS][targets.TestArch64], nil)269 if err != nil {270 t.Fatalf("Test %d: CollectUnused failed: %v", i, err)271 }272 if len(input.names) != len(nodes) {273 t.Errorf("Test %d: want %d nodes, got %d", i, len(input.names), len(nodes))274 }275 names := make([]string, len(nodes))276 for i := range nodes {277 _, _, names[i] = nodes[i].Info()278 }279 sort.Strings(names)280 sort.Strings(input.names)281 if !reflect.DeepEqual(names, input.names) {282 t.Errorf("Test %d: Unused nodes differ. Want %v, Got %v", i, input.names, names)283 }284 }285}...

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)4 if err != nil {5 log.Fatal(err)6 }7 ast.Print(fset, f)8 fmt.Println("Unused variables are: ")9 c := compiler{}10 c.collectUnused(f)11}12import (13type compiler struct {14}15func (c *compiler) collectUnused(f *ast.File) {16 for _, decl := range f.Decls {17 switch decl := decl.(type) {18 for _, spec := range decl.Specs {19 switch spec := spec.(type) {20 if len(spec.Names) > 1 {21 for _, name := range spec.Names {22 fmt.Println(name.Name)23 }24 } else {25 fmt.Println(spec.Names[0].Name)26 }27 fmt.Println(spec.Name.Name)28 }29 }30 fmt.Println(decl.Name.Name)31 }32 }33}34import (35type File struct {

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)4 if err != nil {5 log.Fatal(err)6 }7 fmt.Println("AST:")8 ast.Print(fset, f)9 fmt.Println("Unused variables:")10 for _, v := range collectUnused(f) {11 fmt.Printf("%s %s\n", v.Name, v.Type)12 }13}14func collectUnused(f *ast.File) []*ast.Field {15 ast.Inspect(f, func(n ast.Node) bool {16 switch x := n.(type) {17 if !ast.IsExported(x.Name.Name) {18 }19 ast.Inspect(x.Body, func(n ast.Node) bool {20 switch x := n.(type) {21 if x.Tok != token.ASSIGN {22 }23 for _, lhs := range x.Lhs {24 id, ok := lhs.(*ast.Ident)25 if !ok {26 }27 if !ast.IsExported(id.Name) {28 }29 if isUsed(id, x.Rhs) {30 }31 unused = append(unused, &ast.Field{32 Names: []*ast.Ident{id},33 })34 }35 }

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, 0)4 if err != nil {5 log.Fatal(err)6 }

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 src, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)4 if err != nil {5 log.Fatal(err)6 }7 for _, s := range src.Imports {8 fmt.Println(s.Path.Value)9 }10 for _, c := range src.Comments {11 fmt.Println(c.Text())12 }13 ast.Inspect(src, func(n ast.Node) bool {14 switch x := n.(type) {15 fmt.Println(x.Name.Name)16 for _, spec := range x.Specs {17 switch spec := spec.(type) {18 fmt.Println(spec.Name.Name)19 }20 }21 }22 })23 for _, decl := range src.Decls {24 ast.Inspect(decl, func(n ast.Node) bool {25 switch x := n.(type) {26 fmt.Println(x.Name)27 }28 })29 }30 ast.Inspect(src, func(n ast.Node) bool {31 switch x := n.(type) {32 fmt.Println(x.Value)33 }34 })35 for _, g := range src.Comments {36 fmt.Println(g.Text())37 }38 for _, g := range src.Comments {39 fmt.Println(g.Text())40 }

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 node, err := parser.ParseFile(fset, "2.go", nil, parser.ParseComments)5 if err != nil {6 log.Fatal(err)7 }8 config := types.Config{Importer: importer.Default()}9 info := &types.Info{10 Scopes: make(map[ast.Node]*types.Scope),11 }12 _, err = config.Check("cmd/compile/internal/gc", fset, []*ast.File{node}, info)13 if err != nil {14 log.Fatal(err)15 }16 for id, obj := range info.Uses {17 if obj.Exported() && !info.Defs[id].(*types.TypeName).IsAlias() {18 fmt.Printf("%s: %s\n", fset.Position(id.Pos()), id.Name)19 }20 }21}22import (23func main() {24 fset := token.NewFileSet()25 node, err := parser.ParseFile(fset, "2.go", nil, parser.ParseComments)26 if err != nil {27 log.Fatal(err)28 }29 config := types.Config{Importer: importer.Default()}30 info := &types.Info{31 Scopes: make(map[ast.Node]*types.Scope),32 }33 _, err = config.Check("cmd/compile/internal/gc", fset, []*ast.File{node}, info)34 if err != nil {35 log.Fatal(err)36 }37 for id, obj := range info.Uses {38 if obj.Exported()

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) != 2 {4 log.Fatal("usage: 2.go <go file>")5 }6 fset := token.NewFileSet()7 f, err := parser.ParseFile(fset, os.Args[1], nil, 0)8 if err != nil {9 log.Fatal(err)10 }11 comp := compiler{fset: fset, f: f}12 comp.collectUnused()13 fmt.Println("Unused variables:")14 for _, v := range comp.unused {15 fmt.Printf("\t%s\n", v)16 }17}18import (19func main() {20 if len(os.Args) != 2 {21 log.Fatal("usage: 3.go <go file>")22 }23 fset := token.NewFileSet()24 f, err := parser.ParseFile(fset, os.Args[1], nil, 0)25 if err != nil {26 log.Fatal(err)27 }28 comp := compiler{fset: fset, f: f}29 comp.collectUnused()30 fmt.Println("Unused variables:")31 for _, v := range comp.unused {32 fmt.Printf("\t%s\n", v)33 }34}35import (36func main() {37 if len(os.Args) != 2 {38 log.Fatal("usage: 4.go <go file>")39 }40 fset := token.NewFileSet()41 f, err := parser.ParseFile(fset, os.Args[1], nil, 0)42 if err != nil {43 log.Fatal(err)44 }45 comp := compiler{fset: fset, f: f}46 comp.collectUnused()47 fmt.Println("Unused variables:")48 for _, v := range comp.unused {49 fmt.Printf("\t%s\n", v)50 }51}

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1func main() {2 compiler := new(Compiler)3 compiler.collectUnused()4}5func main() {6 compiler := new(Compiler)7 compiler.collectUnused()8}9func main() {10 compiler := new(Compiler)11 compiler.collectUnused()12}13func main() {14 compiler := new(Compiler)15 compiler.collectUnused()16}17func main() {18 compiler := new(Compiler)19 compiler.collectUnused()20}21func main() {22 compiler := new(Compiler)23 compiler.collectUnused()24}25func main() {26 compiler := new(Compiler)27 compiler.collectUnused()28}29func main() {30 compiler := new(Compiler)31 compiler.collectUnused()32}33func main() {34 compiler := new(Compiler)35 compiler.collectUnused()36}37func main() {38 compiler := new(Compiler)

Full Screen

Full Screen

collectUnused

Using AI Code Generation

copy

Full Screen

1import (2type Compiler struct {3}4func (c *Compiler) collectUnused() []string {5 for k, v := range c.variables {6 if v == "unused" {7 unusedVars = append(unusedVars, k)8 }9 }10}11func (c *Compiler) removeUnused() {12 unusedVars := c.collectUnused()13 for _, v := range unusedVars {14 delete(c.variables, v)15 }16}17func (c *Compiler) collectUsed() []string {18 for k, v := range c.variables {19 if v == "used" {20 usedVars = append(usedVars, k)21 }22 }23}24func (c *Compiler) removeUsed() {25 usedVars := c.collectUsed()26 for _, v := range usedVars {27 delete(c.variables, v)28 }29}30func (c *Compiler) checkDeclaration(line string) {31 variableDeclaration := regexp.MustCompile(`^var\s+[a-z]+[a-z0-9_]*\s+`)32 if variableDeclaration.MatchString(line) {33 variableName := variableDeclaration.FindString(line)34 variableName = strings.TrimSpace(variableName)35 }36}37func (c *Compiler) checkAssignment(line string) {38 variableAssignment := regexp.MustCompile(`^[a-z]+[a-z0-9_]*\s*=`)39 if variableAssignment.MatchString(line) {40 variableName := variableAssignment.FindString(line)41 variableName = strings.TrimSpace(variableName)42 variableName = variableName[:len(variableName)-1]

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful