How to use TestTransform method of compiler Package

Best K6 code snippet using compiler.TestTransform

transform_test.go

Source:transform_test.go Github

copy

Full Screen

1package transform_test2// This file defines some helper functions for testing transforms.3import (4 "flag"5 "go/token"6 "go/types"7 "io/ioutil"8 "os"9 "path/filepath"10 "strings"11 "testing"12 "github.com/tinygo-org/tinygo/compileopts"13 "github.com/tinygo-org/tinygo/compiler"14 "github.com/tinygo-org/tinygo/loader"15 "tinygo.org/x/go-llvm"16)17var update = flag.Bool("update", false, "update transform package tests")18var defaultTestConfig = &compileopts.Config{19 Target: &compileopts.TargetSpec{},20 Options: &compileopts.Options{Opt: "2"},21}22// testTransform runs a transformation pass on an input file (pathPrefix+".ll")23// and checks whether it matches the expected output (pathPrefix+".out.ll"). The24// output is compared with a fuzzy match that ignores some irrelevant lines such25// as empty lines.26func testTransform(t *testing.T, pathPrefix string, transform func(mod llvm.Module)) {27 // Read the input IR.28 ctx := llvm.NewContext()29 defer ctx.Dispose()30 buf, err := llvm.NewMemoryBufferFromFile(pathPrefix + ".ll")31 os.Stat(pathPrefix + ".ll") // make sure this file is tracked by `go test` caching32 if err != nil {33 t.Fatalf("could not read file %s: %v", pathPrefix+".ll", err)34 }35 mod, err := ctx.ParseIR(buf)36 if err != nil {37 t.Fatalf("could not load module:\n%v", err)38 }39 defer mod.Dispose()40 // Perform the transform.41 transform(mod)42 // Check for any incorrect IR.43 err = llvm.VerifyModule(mod, llvm.PrintMessageAction)44 if err != nil {45 t.Fatal("IR verification failed")46 }47 // Get the output from the test and filter some irrelevant lines.48 actual := mod.String()49 actual = actual[strings.Index(actual, "\ntarget datalayout = ")+1:]50 if *update {51 err := ioutil.WriteFile(pathPrefix+".out.ll", []byte(actual), 0666)52 if err != nil {53 t.Error("failed to write out new output:", err)54 }55 } else {56 // Read the expected output IR.57 out, err := ioutil.ReadFile(pathPrefix + ".out.ll")58 if err != nil {59 t.Fatalf("could not read output file %s: %v", pathPrefix+".out.ll", err)60 }61 // See whether the transform output matches with the expected output IR.62 expected := string(out)63 if !fuzzyEqualIR(expected, actual) {64 t.Logf("output does not match expected output:\n%s", actual)65 t.Fail()66 }67 }68}69// fuzzyEqualIR returns true if the two LLVM IR strings passed in are roughly70// equal. That means, only relevant lines are compared (excluding comments71// etc.).72func fuzzyEqualIR(s1, s2 string) bool {73 lines1 := filterIrrelevantIRLines(strings.Split(s1, "\n"))74 lines2 := filterIrrelevantIRLines(strings.Split(s2, "\n"))75 if len(lines1) != len(lines2) {76 return false77 }78 for i, line1 := range lines1 {79 line2 := lines2[i]80 if line1 != line2 {81 return false82 }83 }84 return true85}86// filterIrrelevantIRLines removes lines from the input slice of strings that87// are not relevant in comparing IR. For example, empty lines and comments are88// stripped out.89func filterIrrelevantIRLines(lines []string) []string {90 var out []string91 for _, line := range lines {92 line = strings.Split(line, ";")[0] // strip out comments/info93 line = strings.TrimRight(line, "\r ") // drop '\r' on Windows and remove trailing spaces from comments94 if line == "" {95 continue96 }97 if strings.HasPrefix(line, "source_filename = ") {98 continue99 }100 out = append(out, line)101 }102 return out103}104// compileGoFileForTesting compiles the given Go file to run tests against.105// Only the given Go file is compiled (no dependencies) and no optimizations are106// run.107// If there are any errors, they are reported via the *testing.T instance.108func compileGoFileForTesting(t *testing.T, filename string) llvm.Module {109 target, err := compileopts.LoadTarget(&compileopts.Options{GOOS: "linux", GOARCH: "386"})110 if err != nil {111 t.Fatal("failed to load target:", err)112 }113 config := &compileopts.Config{114 Options: &compileopts.Options{},115 Target: target,116 }117 compilerConfig := &compiler.Config{118 Triple: config.Triple(),119 GOOS: config.GOOS(),120 GOARCH: config.GOARCH(),121 CodeModel: config.CodeModel(),122 RelocationModel: config.RelocationModel(),123 Scheduler: config.Scheduler(),124 AutomaticStackSize: config.AutomaticStackSize(),125 Debug: true,126 }127 machine, err := compiler.NewTargetMachine(compilerConfig)128 if err != nil {129 t.Fatal("failed to create target machine:", err)130 }131 defer machine.Dispose()132 // Load entire program AST into memory.133 lprogram, err := loader.Load(config, filename, config.ClangHeaders, types.Config{134 Sizes: compiler.Sizes(machine),135 })136 if err != nil {137 t.Fatal("failed to create target machine:", err)138 }139 err = lprogram.Parse()140 if err != nil {141 t.Fatal("could not parse", err)142 }143 // Compile AST to IR.144 program := lprogram.LoadSSA()145 pkg := lprogram.MainPkg()146 mod, errs := compiler.CompilePackage(filename, pkg, program.Package(pkg.Pkg), machine, compilerConfig, false)147 if errs != nil {148 for _, err := range errs {149 t.Error(err)150 }151 t.FailNow()152 }153 return mod154}155// getPosition returns the position information for the given value, as far as156// it is available.157func getPosition(val llvm.Value) token.Position {158 if !val.IsAInstruction().IsNil() {159 loc := val.InstructionDebugLoc()160 if loc.IsNil() {161 return token.Position{}162 }163 file := loc.LocationScope().ScopeFile()164 return token.Position{165 Filename: filepath.Join(file.FileDirectory(), file.FileFilename()),166 Line: int(loc.LocationLine()),167 Column: int(loc.LocationColumn()),168 }169 } else if !val.IsAFunction().IsNil() {170 loc := val.Subprogram()171 if loc.IsNil() {172 return token.Position{}173 }174 file := loc.ScopeFile()175 return token.Position{176 Filename: filepath.Join(file.FileDirectory(), file.FileFilename()),177 Line: int(loc.SubprogramLine()),178 }179 } else {180 return token.Position{}181 }182}...

Full Screen

Full Screen

compiler_test.go

Source:compiler_test.go Github

copy

Full Screen

...7 compiler, err := New()8 assert.NoError(t, err)9 assert.NotNil(t, compiler)10}11func TestTransform(t *testing.T) {12 var script = `a => a + 100;`13 var result = `"use strict";14(function (a) {15 return a + 100;16});`17 compiler, _ := New()18 out, err := compiler.Transform(script)19 assert.NoError(t, err)20 assert.Equal(t, out, result)21}...

Full Screen

Full Screen

TestTransform

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 }6 fmt.Println("AST:")7 ast.Print(fset, f)8}9import (10func main() {11 f, err := parser.ParseFile(fset, "2.go", nil, 0)12 if err != nil {13 }14 fmt.Println("AST:")15 ast.Print(fset, f)16}17import (18func main() {19 f, err := parser.ParseFile(fset, "3.go", nil, 0)20 if err != nil {21 }22 fmt.Println("AST:")23 ast.Print(fset, f)24}25import (

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := ir.NewModule()4 f := m.NewFunc("add", types.I32, ir.NewParam("x", types.I32), ir.NewParam("y", types.I32))5 entry := f.NewBlock("entry")6 sum := entry.NewAdd(entry.Params[0], entry.Params[1])7 entry.NewRet(sum)8 fmt.Println(m)9 fmt.Println(m)10 m1 := ir.NewModule()11 f1 := m1.NewFunc("add", types.I32, ir.NewParam("x", types.I32), ir.NewParam("y", types.I32))12 entry1 := f1.NewBlock("entry")13 sum1 := entry1.NewAdd(entry1.Params[0], entry1.Params[1])14 entry1.NewRet(sum1)15 fmt.Println(m1)16 fmt.Println(m1)17 m2 := ir.NewModule()

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2func TestTransform() {3 cfg := &packages.Config{Mode: packages.LoadAllSyntax}4 pkgs, err := packages.Load(cfg, "github.com/rajdeepd/transformer/test")5 if err != nil {6 log.Fatal(err)7 }8 if packages.PrintErrors(pkgs) > 0 {9 os.Exit(1)10 }11 for _, pkg := range pkgs {12 files = append(files, pkg.Syntax...)13 }14 info := &types.Info{15 Defs: make(map[*ast.Ident]types.Object),16 }17 _, err = types.Check("pkg", fset, files, info)18 if err != nil {19 log.Fatal(err)20 }21 transform(fset, files, info)22 for _, file := range files {23 err = printer.Fprint(os.Stdout, fset, file)24 if err != nil {25 log.Fatal(err)26 }27 }28}29func transform(fset *token.FileSet, files []*ast.File, info *types.Info) {30 for _, file := range files {31 for _, decl := range file.Decls {32 if fn, _ = decl.(*ast.FuncDecl); fn != nil {33 if fn.Name.Name == "main" {34 }35 }36 }37 if fn != nil {38 }39 }40 ast.Inspect(fn.Body, func(node ast.Node) bool {41 if call, _ := node.(*ast.CallExpr); call != nil {42 if sel, _ := call.Fun.(*ast.SelectorExpr); sel != nil {43 if x, _ := sel.X.(*ast.Ident); x

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2type compiler struct {3}4func main() {5 fset := token.NewFileSet()6 c.files, err = parser.ParseDir(fset, "C:/Users/abhishek/Desktop/GoLang/GoLangTest/src/GoLangTest", nil, 0)7 if err != nil {8 log.Fatal(err)9 }10 for _, astfile := range c.files {11 }

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 vm := otto.New()4 vm.Run(`5 var compiler = require('./compiler');6 var code = "function test() { return 1; }";7 var result = compiler.TestTransform(code);8 console.log(result);9}10var compiler = (function () {11 var TestTransform = function (code) {12 return code;13 }14 return {15 }16})();17module.exports = compiler;

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Input string: ", s)4 fmt.Println("Output string: ", compiler.TestTransform(s))5}6import "fmt"7func main() {8 fmt.Println("Input string: ", s)9 fmt.Println("Output string: ", compiler.TestTransform(s))10}11import "fmt"12func main() {13 fmt.Println("Input string: ", s)14 fmt.Println("Output string: ", compiler.TestTransform(s))15}16import "fmt"17func main() {18 fmt.Println("Input string: ", s)19 fmt.Println("Output string: ", compiler.TestTransform(s))20}21import "fmt"22func main() {23 fmt.Println("Input string: ", s)24 fmt.Println("Output string: ", compiler.TestTransform(s))25}26import "fmt"27func main() {28 fmt.Println("Input string: ", s)29 fmt.Println("Output string: ", compiler.TestTransform(s))30}31import "fmt"32func main() {33 fmt.Println("Input string: ", s)34 fmt.Println("Output string: ", compiler.TestTransform(s))35}36import "fmt"37func main() {

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 c := compiler.NewCompiler()5 c.TestTransform()6}7import (8func main() {9 fmt.Println("Hello World")10 c := compiler.NewCompiler()11 c.TestTransform()12}13import (14func (c *Compiler) TestTransform() {15 fmt.Println("Hello World")16}

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("string s is", s)4 fmt.Println("string s memory address is", unsafe.Pointer(&s))5 fmt.Println("string s memory address is", unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data))6}

Full Screen

Full Screen

TestTransform

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := compiler.NewCompiler()4 fmt.Println(c.TestTransform("1 + 2"))5 fmt.Println(c.TestTransform("1 + 2 * 3"))6 fmt.Println(c.TestTransform("(1 + 2) * 3"))7 fmt.Println(c.TestTransform("1 * 2 + 3"))8 fmt.Println(c.TestTransform("1 * (2 + 3)"))9 fmt.Println(c.TestTransform("1 + 2 + 3"))10 fmt.Println(c.TestTransform("(1 + 2) + 3"))11 fmt.Println(c.TestTransform("1 + (2 + 3)"))12 fmt.Println(c.TestTransform("1 - 2 - 3"))13 fmt.Println(c.TestTransform("(1 - 2) - 3"))14 fmt.Println(c.TestTransform("1 - (2 - 3)"))15 fmt.Println(c.TestTransform("(1 + 2) * (3 + 4)"))16 fmt.Println(c.TestTransform("1 * (2 + 3) * 4"))17 fmt.Println(c.TestTransform("1 * (2 + 3 * 4)"))18 fmt.Println(c.TestTransform("1 * 2 + 3 * 4"))19 fmt.Println(c.TestTransform("1 + 2 * 3 + 4"))20 fmt.Println(c.TestTransform("1 * (2 + 3 * 4) + 5"))21 fmt.Println(c.TestTransform("1 * (2 + 3 * 4 + 5)"))22 fmt.Println(c.TestTransform("1 * (2 + 3 * 4 + 5) + 6"))23 fmt.Println(c.TestTransform("1 * (2 + 3 * 4 + 5) + 6 * 7

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful