Files
llgo/cl/compile_test.go
2024-04-20 22:05:45 +08:00

87 lines
2.2 KiB
Go

/*
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cl
import (
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"os"
"testing"
llssa "github.com/goplus/llgo/ssa"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/ssautil"
)
func testCompile(t *testing.T, src, expected string) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "foo.go", src, parser.ParseComments)
if err != nil {
t.Fatal("ParseFile failed:", err)
}
files := []*ast.File{f}
pkg := types.NewPackage("foo", "foo")
foo, _, err := ssautil.BuildPackage(
&types.Config{Importer: importer.Default()}, fset, pkg, files, ssa.SanityCheckFunctions)
if err != nil {
t.Fatal("BuildPackage failed:", err)
}
foo.WriteTo(os.Stderr)
for _, m := range foo.Members {
if f, ok := m.(*ssa.Function); ok {
f.WriteTo(os.Stderr)
}
}
prog := llssa.NewProgram(nil)
ret, err := NewPackage(prog, foo, nil)
if err != nil {
t.Fatal("cl.NewPackage failed:", err)
}
if v := ret.String(); v != expected {
t.Fatalf("\n==> got:\n%s\n==> expected:\n%s\n", v, expected)
}
}
func TestVar(t *testing.T) {
testCompile(t, `package foo
var a int
`, `; ModuleID = 'foo'
source_filename = "foo"
@"init$guard" = external global ptr
@a = external global ptr
define void @init() {
_llgo_0:
%0 = load i1, ptr @"init$guard", align 1
%1 = load i1, ptr @"init$guard", align 1
br i1 %1, label %_llgo_2, label %_llgo_1
_llgo_1: ; preds = %_llgo_0
store i1 true, ptr @"init$guard", align 1
br label %_llgo_2
_llgo_2: ; preds = %_llgo_1, %_llgo_0
ret void
}
`)
}