github.com/sean-/go@v0.0.0-20151219100004-97f854cd7bb6/src/go/importer/importer.go (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package importer provides access to export data importers.
     6  package importer
     7  
     8  import (
     9  	"go/internal/gccgoimporter"
    10  	"go/internal/gcimporter"
    11  	"go/types"
    12  	"io"
    13  	"runtime"
    14  )
    15  
    16  // A Lookup function returns a reader to access package data for
    17  // a given import path, or an error if no matching package is found.
    18  type Lookup func(path string) (io.ReadCloser, error)
    19  
    20  // For returns an Importer for the given compiler and lookup interface,
    21  // or nil. Supported compilers are "gc", and "gccgo". If lookup is nil,
    22  // the default package lookup mechanism for the given compiler is used.
    23  func For(compiler string, lookup Lookup) types.Importer {
    24  	switch compiler {
    25  	case "gc":
    26  		if lookup == nil {
    27  			return make(gcimports)
    28  		}
    29  		panic("gc importer for custom import path lookup not yet implemented")
    30  	case "gccgo":
    31  		if lookup == nil {
    32  			var inst gccgoimporter.GccgoInstallation
    33  			if err := inst.InitFromDriver("gccgo"); err != nil {
    34  				return nil
    35  			}
    36  			return &gccgoimports{
    37  				packages: make(map[string]*types.Package),
    38  				importer: inst.GetImporter(nil, nil),
    39  			}
    40  		}
    41  		panic("gccgo importer for custom import path lookup not yet implemented")
    42  	}
    43  	// compiler not supported
    44  	return nil
    45  }
    46  
    47  // Default returns an Importer for the compiler that built the running binary.
    48  func Default() types.Importer {
    49  	return For(runtime.Compiler, nil)
    50  }
    51  
    52  // gc support
    53  
    54  type gcimports map[string]*types.Package
    55  
    56  func (m gcimports) Import(path string) (*types.Package, error) {
    57  	return gcimporter.Import(m, path)
    58  }
    59  
    60  // gccgo support
    61  
    62  type gccgoimports struct {
    63  	packages map[string]*types.Package
    64  	importer gccgoimporter.Importer
    65  }
    66  
    67  func (m *gccgoimports) Import(path string) (*types.Package, error) {
    68  	return m.importer(m.packages, path)
    69  }