github.com/goplus/gox@v1.14.13-0.20240308130321-6ff7f61cfae8/cpackages/import.go (about)

     1  /*
     2   Copyright 2022 The GoPlus Authors (goplus.org)
     3   Licensed under the Apache License, Version 2.0 (the "License");
     4   you may not use this file except in compliance with the License.
     5   You may obtain a copy of the License at
     6       http://www.apache.org/licenses/LICENSE-2.0
     7   Unless required by applicable law or agreed to in writing, software
     8   distributed under the License is distributed on an "AS IS" BASIS,
     9   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10   See the License for the specific language governing permissions and
    11   limitations under the License.
    12  */
    13  
    14  package cpackages
    15  
    16  import (
    17  	"go/types"
    18  
    19  	"github.com/goplus/gox"
    20  )
    21  
    22  // ----------------------------------------------------------------------------
    23  
    24  type PkgRef struct {
    25  	pkg    gox.PkgRef
    26  	public map[string]string
    27  }
    28  
    29  func (p *PkgRef) Pkg() gox.PkgRef {
    30  	return p.pkg
    31  }
    32  
    33  func (p *PkgRef) Lookup(name string) types.Object {
    34  	if goName, ok := p.public[name]; ok {
    35  		if goName == "" {
    36  			goName = gox.CPubName(name)
    37  		}
    38  		return p.pkg.TryRef(goName)
    39  	}
    40  	return nil
    41  }
    42  
    43  func PubName(name string) string {
    44  	return gox.CPubName(name)
    45  }
    46  
    47  // ----------------------------------------------------------------------------
    48  
    49  type Config struct {
    50  	Pkg       *gox.Package
    51  	LookupPub func(pkgPath string) (pubfile string, err error)
    52  }
    53  
    54  type Importer struct {
    55  	loaded    map[string]PkgRef
    56  	lookupPub func(pkgPath string) (pubfile string, err error)
    57  	pkg       *gox.Package
    58  }
    59  
    60  func NewImporter(conf *Config) *Importer {
    61  	return &Importer{
    62  		loaded:    make(map[string]PkgRef),
    63  		lookupPub: conf.LookupPub,
    64  		pkg:       conf.Pkg,
    65  	}
    66  }
    67  
    68  func (p *Importer) Import(pkgPath string) (pkg PkgRef, err error) {
    69  	if ret, ok := p.loaded[pkgPath]; ok {
    70  		return ret, nil
    71  	}
    72  	pubfile, err := p.lookupPub(pkgPath)
    73  	if err != nil {
    74  		return
    75  	}
    76  	public, err := ReadPubFile(pubfile)
    77  	if err != nil {
    78  		return
    79  	}
    80  	pkgImp := p.pkg.Import(pkgPath)
    81  	pkg = PkgRef{pkg: pkgImp, public: public}
    82  	p.loaded[pkgPath] = pkg
    83  	return
    84  }
    85  
    86  // ----------------------------------------------------------------------------