repository_name
stringlengths 5
54
| func_path_in_repository
stringlengths 4
155
| func_name
stringlengths 1
118
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 1
value | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 21
188k
| func_documentation_string
stringlengths 4
26.3k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|
joho/godotenv | godotenv.go | Unmarshal | func Unmarshal(str string) (envMap map[string]string, err error) {
return Parse(strings.NewReader(str))
} | go | func Unmarshal(str string) (envMap map[string]string, err error) {
return Parse(strings.NewReader(str))
} | [
"func",
"Unmarshal",
"(",
"str",
"string",
")",
"(",
"envMap",
"map",
"[",
"string",
"]",
"string",
",",
"err",
"error",
")",
"{",
"return",
"Parse",
"(",
"strings",
".",
"NewReader",
"(",
"str",
")",
")",
"\n",
"}"
] | //Unmarshal reads an env file from a string, returning a map of keys and values. | [
"Unmarshal",
"reads",
"an",
"env",
"file",
"from",
"a",
"string",
"returning",
"a",
"map",
"of",
"keys",
"and",
"values",
"."
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L127-L129 |
joho/godotenv | godotenv.go | Exec | func Exec(filenames []string, cmd string, cmdArgs []string) error {
Load(filenames...)
command := exec.Command(cmd, cmdArgs...)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
return command.Run()
} | go | func Exec(filenames []string, cmd string, cmdArgs []string) error {
Load(filenames...)
command := exec.Command(cmd, cmdArgs...)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
return command.Run()
} | [
"func",
"Exec",
"(",
"filenames",
"[",
"]",
"string",
",",
"cmd",
"string",
",",
"cmdArgs",
"[",
"]",
"string",
")",
"error",
"{",
"Load",
"(",
"filenames",
"...",
")",
"\n\n",
"command",
":=",
"exec",
".",
"Command",
"(",
"cmd",
",",
"cmdArgs",
"...",
")",
"\n",
"command",
".",
"Stdin",
"=",
"os",
".",
"Stdin",
"\n",
"command",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"command",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"return",
"command",
".",
"Run",
"(",
")",
"\n",
"}"
] | // Exec loads env vars from the specified filenames (empty map falls back to default)
// then executes the cmd specified.
//
// Simply hooks up os.Stdin/err/out to the command and calls Run()
//
// If you want more fine grained control over your command it's recommended
// that you use `Load()` or `Read()` and the `os/exec` package yourself. | [
"Exec",
"loads",
"env",
"vars",
"from",
"the",
"specified",
"filenames",
"(",
"empty",
"map",
"falls",
"back",
"to",
"default",
")",
"then",
"executes",
"the",
"cmd",
"specified",
".",
"Simply",
"hooks",
"up",
"os",
".",
"Stdin",
"/",
"err",
"/",
"out",
"to",
"the",
"command",
"and",
"calls",
"Run",
"()",
"If",
"you",
"want",
"more",
"fine",
"grained",
"control",
"over",
"your",
"command",
"it",
"s",
"recommended",
"that",
"you",
"use",
"Load",
"()",
"or",
"Read",
"()",
"and",
"the",
"os",
"/",
"exec",
"package",
"yourself",
"."
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L138-L146 |
joho/godotenv | godotenv.go | Write | func Write(envMap map[string]string, filename string) error {
content, error := Marshal(envMap)
if error != nil {
return error
}
file, error := os.Create(filename)
if error != nil {
return error
}
_, err := file.WriteString(content)
return err
} | go | func Write(envMap map[string]string, filename string) error {
content, error := Marshal(envMap)
if error != nil {
return error
}
file, error := os.Create(filename)
if error != nil {
return error
}
_, err := file.WriteString(content)
return err
} | [
"func",
"Write",
"(",
"envMap",
"map",
"[",
"string",
"]",
"string",
",",
"filename",
"string",
")",
"error",
"{",
"content",
",",
"error",
":=",
"Marshal",
"(",
"envMap",
")",
"\n",
"if",
"error",
"!=",
"nil",
"{",
"return",
"error",
"\n",
"}",
"\n",
"file",
",",
"error",
":=",
"os",
".",
"Create",
"(",
"filename",
")",
"\n",
"if",
"error",
"!=",
"nil",
"{",
"return",
"error",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"file",
".",
"WriteString",
"(",
"content",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Write serializes the given environment and writes it to a file | [
"Write",
"serializes",
"the",
"given",
"environment",
"and",
"writes",
"it",
"to",
"a",
"file"
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L149-L160 |
joho/godotenv | godotenv.go | Marshal | func Marshal(envMap map[string]string) (string, error) {
lines := make([]string, 0, len(envMap))
for k, v := range envMap {
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
}
sort.Strings(lines)
return strings.Join(lines, "\n"), nil
} | go | func Marshal(envMap map[string]string) (string, error) {
lines := make([]string, 0, len(envMap))
for k, v := range envMap {
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
}
sort.Strings(lines)
return strings.Join(lines, "\n"), nil
} | [
"func",
"Marshal",
"(",
"envMap",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"lines",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"envMap",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"envMap",
"{",
"lines",
"=",
"append",
"(",
"lines",
",",
"fmt",
".",
"Sprintf",
"(",
"`%s=\"%s\"`",
",",
"k",
",",
"doubleQuoteEscape",
"(",
"v",
")",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"lines",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"lines",
",",
"\"",
"\\n",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // Marshal outputs the given environment as a dotenv-formatted environment file.
// Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped. | [
"Marshal",
"outputs",
"the",
"given",
"environment",
"as",
"a",
"dotenv",
"-",
"formatted",
"environment",
"file",
".",
"Each",
"line",
"is",
"in",
"the",
"format",
":",
"KEY",
"=",
"VALUE",
"where",
"VALUE",
"is",
"backslash",
"-",
"escaped",
"."
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L164-L171 |
sourcegraph/go-langserver | vfsutil/git.go | fetchOrWait | func (fs *GitRepoVFS) fetchOrWait(ctx context.Context) error {
fs.once.Do(func() {
fs.err = fs.fetch(ctx)
})
return fs.err
} | go | func (fs *GitRepoVFS) fetchOrWait(ctx context.Context) error {
fs.once.Do(func() {
fs.err = fs.fetch(ctx)
})
return fs.err
} | [
"func",
"(",
"fs",
"*",
"GitRepoVFS",
")",
"fetchOrWait",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"fs",
".",
"once",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"fs",
".",
"err",
"=",
"fs",
".",
"fetch",
"(",
"ctx",
")",
"\n",
"}",
")",
"\n",
"return",
"fs",
".",
"err",
"\n",
"}"
] | // fetchOrWait initiates the fetch if it has not yet
// started. Otherwise it waits for it to finish. | [
"fetchOrWait",
"initiates",
"the",
"fetch",
"if",
"it",
"has",
"not",
"yet",
"started",
".",
"Otherwise",
"it",
"waits",
"for",
"it",
"to",
"finish",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/git.go#L40-L45 |
sourcegraph/go-langserver | vfsutil/git.go | gitCheckArgSafety | func gitCheckArgSafety(rev string) error {
if strings.HasPrefix(rev, "-") {
return fmt.Errorf("invalid Git revision (can't start with '-'): %q", rev)
}
return nil
} | go | func gitCheckArgSafety(rev string) error {
if strings.HasPrefix(rev, "-") {
return fmt.Errorf("invalid Git revision (can't start with '-'): %q", rev)
}
return nil
} | [
"func",
"gitCheckArgSafety",
"(",
"rev",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"rev",
",",
"\"",
"\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rev",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // gitCheckArgSafety returns a non-nil error if rev is unsafe to
// use as a command-line argument (i.e., it begins with "-" and thus
// could be confused with a command-line flag). | [
"gitCheckArgSafety",
"returns",
"a",
"non",
"-",
"nil",
"error",
"if",
"rev",
"is",
"unsafe",
"to",
"use",
"as",
"a",
"command",
"-",
"line",
"argument",
"(",
"i",
".",
"e",
".",
"it",
"begins",
"with",
"-",
"and",
"thus",
"could",
"be",
"confused",
"with",
"a",
"command",
"-",
"line",
"flag",
")",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/git.go#L154-L159 |
sourcegraph/go-langserver | buildserver/pinned.go | Find | func (p pinnedPkgs) Find(pkg string) string {
if len(p) == 0 {
return ""
}
pkg = pkg + "/"
i := sort.Search(len(p), func(i int) bool { return p[i].Pkg > pkg })
if i > 0 && strings.HasPrefix(pkg, p[i-1].Pkg) {
return p[i-1].Rev
}
return ""
} | go | func (p pinnedPkgs) Find(pkg string) string {
if len(p) == 0 {
return ""
}
pkg = pkg + "/"
i := sort.Search(len(p), func(i int) bool { return p[i].Pkg > pkg })
if i > 0 && strings.HasPrefix(pkg, p[i-1].Pkg) {
return p[i-1].Rev
}
return ""
} | [
"func",
"(",
"p",
"pinnedPkgs",
")",
"Find",
"(",
"pkg",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"pkg",
"=",
"pkg",
"+",
"\"",
"\"",
"\n",
"i",
":=",
"sort",
".",
"Search",
"(",
"len",
"(",
"p",
")",
",",
"func",
"(",
"i",
"int",
")",
"bool",
"{",
"return",
"p",
"[",
"i",
"]",
".",
"Pkg",
">",
"pkg",
"}",
")",
"\n",
"if",
"i",
">",
"0",
"&&",
"strings",
".",
"HasPrefix",
"(",
"pkg",
",",
"p",
"[",
"i",
"-",
"1",
"]",
".",
"Pkg",
")",
"{",
"return",
"p",
"[",
"i",
"-",
"1",
"]",
".",
"Rev",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Find returns the revision a pkg is pinned at, or the empty string. | [
"Find",
"returns",
"the",
"revision",
"a",
"pkg",
"is",
"pinned",
"at",
"or",
"the",
"empty",
"string",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/pinned.go#L24-L34 |
sourcegraph/go-langserver | buildserver/pinned.go | loadGopkgLock | func loadGopkgLock(rawToml []byte) pinnedPkgs {
lock := struct {
Projects []struct {
Name string `toml:"name"`
Revision string `toml:"revision"`
// There are other fields, but we don't use them
} `toml:"projects"`
// There are other fields, but we don't use them
}{}
err := toml.Unmarshal(rawToml, &lock)
if err != nil {
return nil
}
pkgs := make(pinnedPkgs, 0, len(lock.Projects))
for _, p := range lock.Projects {
pkgs = append(pkgs, pinnedPkg{Pkg: p.Name + "/", Rev: p.Revision})
}
sort.Sort(pkgs)
return pkgs
} | go | func loadGopkgLock(rawToml []byte) pinnedPkgs {
lock := struct {
Projects []struct {
Name string `toml:"name"`
Revision string `toml:"revision"`
// There are other fields, but we don't use them
} `toml:"projects"`
// There are other fields, but we don't use them
}{}
err := toml.Unmarshal(rawToml, &lock)
if err != nil {
return nil
}
pkgs := make(pinnedPkgs, 0, len(lock.Projects))
for _, p := range lock.Projects {
pkgs = append(pkgs, pinnedPkg{Pkg: p.Name + "/", Rev: p.Revision})
}
sort.Sort(pkgs)
return pkgs
} | [
"func",
"loadGopkgLock",
"(",
"rawToml",
"[",
"]",
"byte",
")",
"pinnedPkgs",
"{",
"lock",
":=",
"struct",
"{",
"Projects",
"[",
"]",
"struct",
"{",
"Name",
"string",
"`toml:\"name\"`",
"\n",
"Revision",
"string",
"`toml:\"revision\"`",
"\n",
"// There are other fields, but we don't use them",
"}",
"`toml:\"projects\"`",
"\n",
"// There are other fields, but we don't use them",
"}",
"{",
"}",
"\n",
"err",
":=",
"toml",
".",
"Unmarshal",
"(",
"rawToml",
",",
"&",
"lock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"pkgs",
":=",
"make",
"(",
"pinnedPkgs",
",",
"0",
",",
"len",
"(",
"lock",
".",
"Projects",
")",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"lock",
".",
"Projects",
"{",
"pkgs",
"=",
"append",
"(",
"pkgs",
",",
"pinnedPkg",
"{",
"Pkg",
":",
"p",
".",
"Name",
"+",
"\"",
"\"",
",",
"Rev",
":",
"p",
".",
"Revision",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"pkgs",
")",
"\n",
"return",
"pkgs",
"\n",
"}"
] | // loadGopkgLock supports unmarshalling the lock file used by
// github.com/golang/dep. | [
"loadGopkgLock",
"supports",
"unmarshalling",
"the",
"lock",
"file",
"used",
"by",
"github",
".",
"com",
"/",
"golang",
"/",
"dep",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/pinned.go#L42-L62 |
sourcegraph/go-langserver | langserver/cancel.go | WithCancel | func (c *cancel) WithCancel(ctx context.Context, id jsonrpc2.ID) (context.Context, func()) {
ctx, cancel := context.WithCancel(ctx)
c.mu.Lock()
if c.m == nil {
c.m = make(map[jsonrpc2.ID]func())
}
c.m[id] = cancel
c.mu.Unlock()
return ctx, func() {
c.mu.Lock()
delete(c.m, id)
c.mu.Unlock()
cancel()
}
} | go | func (c *cancel) WithCancel(ctx context.Context, id jsonrpc2.ID) (context.Context, func()) {
ctx, cancel := context.WithCancel(ctx)
c.mu.Lock()
if c.m == nil {
c.m = make(map[jsonrpc2.ID]func())
}
c.m[id] = cancel
c.mu.Unlock()
return ctx, func() {
c.mu.Lock()
delete(c.m, id)
c.mu.Unlock()
cancel()
}
} | [
"func",
"(",
"c",
"*",
"cancel",
")",
"WithCancel",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"jsonrpc2",
".",
"ID",
")",
"(",
"context",
".",
"Context",
",",
"func",
"(",
")",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"m",
"==",
"nil",
"{",
"c",
".",
"m",
"=",
"make",
"(",
"map",
"[",
"jsonrpc2",
".",
"ID",
"]",
"func",
"(",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"m",
"[",
"id",
"]",
"=",
"cancel",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ctx",
",",
"func",
"(",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"c",
".",
"m",
",",
"id",
")",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"cancel",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // WithCancel is like context.WithCancel, except you can also cancel via
// calling c.Cancel with the same id. | [
"WithCancel",
"is",
"like",
"context",
".",
"WithCancel",
"except",
"you",
"can",
"also",
"cancel",
"via",
"calling",
"c",
".",
"Cancel",
"with",
"the",
"same",
"id",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/cancel.go#L18-L32 |
sourcegraph/go-langserver | langserver/cancel.go | Cancel | func (c *cancel) Cancel(id jsonrpc2.ID) {
var cancel func()
c.mu.Lock()
if c.m != nil {
cancel = c.m[id]
delete(c.m, id)
}
c.mu.Unlock()
if cancel != nil {
cancel()
}
} | go | func (c *cancel) Cancel(id jsonrpc2.ID) {
var cancel func()
c.mu.Lock()
if c.m != nil {
cancel = c.m[id]
delete(c.m, id)
}
c.mu.Unlock()
if cancel != nil {
cancel()
}
} | [
"func",
"(",
"c",
"*",
"cancel",
")",
"Cancel",
"(",
"id",
"jsonrpc2",
".",
"ID",
")",
"{",
"var",
"cancel",
"func",
"(",
")",
"\n",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"m",
"!=",
"nil",
"{",
"cancel",
"=",
"c",
".",
"m",
"[",
"id",
"]",
"\n",
"delete",
"(",
"c",
".",
"m",
",",
"id",
")",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"cancel",
"!=",
"nil",
"{",
"cancel",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Cancel will cancel the request with id. If the request has already been
// cancelled or not been tracked before, Cancel is a noop. | [
"Cancel",
"will",
"cancel",
"the",
"request",
"with",
"id",
".",
"If",
"the",
"request",
"has",
"already",
"been",
"cancelled",
"or",
"not",
"been",
"tracked",
"before",
"Cancel",
"is",
"a",
"noop",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/cancel.go#L36-L47 |
sourcegraph/go-langserver | buildserver/build_server.go | NewHandler | func NewHandler(defaultCfg langserver.Config) *BuildHandler {
if defaultCfg.MaxParallelism <= 0 {
panic(fmt.Sprintf("langserver.Config.MaxParallelism must be at least 1 (got %d)", defaultCfg.MaxParallelism))
}
shared := &langserver.HandlerShared{Shared: true}
h := &BuildHandler{
HandlerShared: shared,
lang: &langserver.LangHandler{
HandlerShared: shared,
DefaultConfig: defaultCfg,
},
}
shared.FindPackage = h.findPackageCached
return h
} | go | func NewHandler(defaultCfg langserver.Config) *BuildHandler {
if defaultCfg.MaxParallelism <= 0 {
panic(fmt.Sprintf("langserver.Config.MaxParallelism must be at least 1 (got %d)", defaultCfg.MaxParallelism))
}
shared := &langserver.HandlerShared{Shared: true}
h := &BuildHandler{
HandlerShared: shared,
lang: &langserver.LangHandler{
HandlerShared: shared,
DefaultConfig: defaultCfg,
},
}
shared.FindPackage = h.findPackageCached
return h
} | [
"func",
"NewHandler",
"(",
"defaultCfg",
"langserver",
".",
"Config",
")",
"*",
"BuildHandler",
"{",
"if",
"defaultCfg",
".",
"MaxParallelism",
"<=",
"0",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"defaultCfg",
".",
"MaxParallelism",
")",
")",
"\n",
"}",
"\n",
"shared",
":=",
"&",
"langserver",
".",
"HandlerShared",
"{",
"Shared",
":",
"true",
"}",
"\n",
"h",
":=",
"&",
"BuildHandler",
"{",
"HandlerShared",
":",
"shared",
",",
"lang",
":",
"&",
"langserver",
".",
"LangHandler",
"{",
"HandlerShared",
":",
"shared",
",",
"DefaultConfig",
":",
"defaultCfg",
",",
"}",
",",
"}",
"\n",
"shared",
".",
"FindPackage",
"=",
"h",
".",
"findPackageCached",
"\n",
"return",
"h",
"\n",
"}"
] | // NewHandler creates a new build server wrapping a (also newly
// created) Go language server. I.e., it creates a BuildHandler
// wrapping a LangHandler. The two handlers share a file system (in
// memory).
//
// The build server is responsible for things such as fetching
// dependencies, setting up the right file system structure and paths,
// and mapping local file system paths to logical URIs (e.g.,
// /goroot/src/fmt/print.go ->
// git://github.com/golang/go?go1.7.1#src/fmt/print.go). | [
"NewHandler",
"creates",
"a",
"new",
"build",
"server",
"wrapping",
"a",
"(",
"also",
"newly",
"created",
")",
"Go",
"language",
"server",
".",
"I",
".",
"e",
".",
"it",
"creates",
"a",
"BuildHandler",
"wrapping",
"a",
"LangHandler",
".",
"The",
"two",
"handlers",
"share",
"a",
"file",
"system",
"(",
"in",
"memory",
")",
".",
"The",
"build",
"server",
"is",
"responsible",
"for",
"things",
"such",
"as",
"fetching",
"dependencies",
"setting",
"up",
"the",
"right",
"file",
"system",
"structure",
"and",
"paths",
"and",
"mapping",
"local",
"file",
"system",
"paths",
"to",
"logical",
"URIs",
"(",
"e",
".",
"g",
".",
"/",
"goroot",
"/",
"src",
"/",
"fmt",
"/",
"print",
".",
"go",
"-",
">",
"git",
":",
"//",
"github",
".",
"com",
"/",
"golang",
"/",
"go?go1",
".",
"7",
".",
"1#src",
"/",
"fmt",
"/",
"print",
".",
"go",
")",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/build_server.go#L50-L64 |
sourcegraph/go-langserver | buildserver/build_server.go | reset | func (h *BuildHandler) reset(init *lspext.InitializeParams, conn *jsonrpc2.Conn, rootURI lsp.DocumentURI) error {
h.mu.Lock()
defer h.mu.Unlock()
h.findPkgMu.Lock()
defer h.findPkgMu.Unlock()
if err := h.HandlerCommon.Reset(rootURI); err != nil {
return err
}
if err := h.HandlerShared.Reset(false); err != nil {
return err
}
h.init = init
// 100 MiB cache, no age-based eviction
h.cachingClient = &http.Client{Transport: httpcache.NewTransport(lrucache.New(100*1024*1024, 0))}
h.depURLMutex = newKeyMutex()
h.gopathDeps = nil
h.pinnedDepsOnce = sync.Once{}
h.pinnedDeps = nil
h.findPkg = nil
return nil
} | go | func (h *BuildHandler) reset(init *lspext.InitializeParams, conn *jsonrpc2.Conn, rootURI lsp.DocumentURI) error {
h.mu.Lock()
defer h.mu.Unlock()
h.findPkgMu.Lock()
defer h.findPkgMu.Unlock()
if err := h.HandlerCommon.Reset(rootURI); err != nil {
return err
}
if err := h.HandlerShared.Reset(false); err != nil {
return err
}
h.init = init
// 100 MiB cache, no age-based eviction
h.cachingClient = &http.Client{Transport: httpcache.NewTransport(lrucache.New(100*1024*1024, 0))}
h.depURLMutex = newKeyMutex()
h.gopathDeps = nil
h.pinnedDepsOnce = sync.Once{}
h.pinnedDeps = nil
h.findPkg = nil
return nil
} | [
"func",
"(",
"h",
"*",
"BuildHandler",
")",
"reset",
"(",
"init",
"*",
"lspext",
".",
"InitializeParams",
",",
"conn",
"*",
"jsonrpc2",
".",
"Conn",
",",
"rootURI",
"lsp",
".",
"DocumentURI",
")",
"error",
"{",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"h",
".",
"findPkgMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"findPkgMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"HandlerCommon",
".",
"Reset",
"(",
"rootURI",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"h",
".",
"HandlerShared",
".",
"Reset",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"h",
".",
"init",
"=",
"init",
"\n",
"// 100 MiB cache, no age-based eviction",
"h",
".",
"cachingClient",
"=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"httpcache",
".",
"NewTransport",
"(",
"lrucache",
".",
"New",
"(",
"100",
"*",
"1024",
"*",
"1024",
",",
"0",
")",
")",
"}",
"\n",
"h",
".",
"depURLMutex",
"=",
"newKeyMutex",
"(",
")",
"\n",
"h",
".",
"gopathDeps",
"=",
"nil",
"\n",
"h",
".",
"pinnedDepsOnce",
"=",
"sync",
".",
"Once",
"{",
"}",
"\n",
"h",
".",
"pinnedDeps",
"=",
"nil",
"\n",
"h",
".",
"findPkg",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // reset clears all internal state in h. | [
"reset",
"clears",
"all",
"internal",
"state",
"in",
"h",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/build_server.go#L87-L107 |
sourcegraph/go-langserver | buildserver/build_server.go | callLangServer | func (h *BuildHandler) callLangServer(ctx context.Context, conn *jsonrpc2.Conn, method string, id jsonrpc2.ID, params, result interface{}) error {
req := jsonrpc2.Request{
ID: id,
Method: method,
}
if err := req.SetParams(params); err != nil {
return err
}
wrappedConn := &jsonrpc2ConnImpl{rewriteURI: h.rewriteURIFromLangServer, conn: conn}
result0, err := h.lang.Handle(ctx, wrappedConn, &req)
if err != nil {
return err
}
// Don't pass the interface{} value, to avoid the build and
// language servers from breaking the abstraction that they are in
// separate memory spaces.
b, err := json.Marshal(result0)
if err != nil {
return err
}
if result != nil {
if err := json.Unmarshal(b, result); err != nil {
return err
}
}
return nil
} | go | func (h *BuildHandler) callLangServer(ctx context.Context, conn *jsonrpc2.Conn, method string, id jsonrpc2.ID, params, result interface{}) error {
req := jsonrpc2.Request{
ID: id,
Method: method,
}
if err := req.SetParams(params); err != nil {
return err
}
wrappedConn := &jsonrpc2ConnImpl{rewriteURI: h.rewriteURIFromLangServer, conn: conn}
result0, err := h.lang.Handle(ctx, wrappedConn, &req)
if err != nil {
return err
}
// Don't pass the interface{} value, to avoid the build and
// language servers from breaking the abstraction that they are in
// separate memory spaces.
b, err := json.Marshal(result0)
if err != nil {
return err
}
if result != nil {
if err := json.Unmarshal(b, result); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"h",
"*",
"BuildHandler",
")",
"callLangServer",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"*",
"jsonrpc2",
".",
"Conn",
",",
"method",
"string",
",",
"id",
"jsonrpc2",
".",
"ID",
",",
"params",
",",
"result",
"interface",
"{",
"}",
")",
"error",
"{",
"req",
":=",
"jsonrpc2",
".",
"Request",
"{",
"ID",
":",
"id",
",",
"Method",
":",
"method",
",",
"}",
"\n",
"if",
"err",
":=",
"req",
".",
"SetParams",
"(",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"wrappedConn",
":=",
"&",
"jsonrpc2ConnImpl",
"{",
"rewriteURI",
":",
"h",
".",
"rewriteURIFromLangServer",
",",
"conn",
":",
"conn",
"}",
"\n\n",
"result0",
",",
"err",
":=",
"h",
".",
"lang",
".",
"Handle",
"(",
"ctx",
",",
"wrappedConn",
",",
"&",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Don't pass the interface{} value, to avoid the build and",
"// language servers from breaking the abstraction that they are in",
"// separate memory spaces.",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"result0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"result",
"!=",
"nil",
"{",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // callLangServer sends the (usually modified) request to the wrapped Go
// language server. Do not send notifications via this interface! Rather just
// directly pass on the jsonrpc2.Request via h.lang.Handle.
//
// Although bypasses the JSON-RPC wire protocol ( just sending it
// in-memory for simplicity/speed), it behaves in the same way as
// though the peer language server were remote. | [
"callLangServer",
"sends",
"the",
"(",
"usually",
"modified",
")",
"request",
"to",
"the",
"wrapped",
"Go",
"language",
"server",
".",
"Do",
"not",
"send",
"notifications",
"via",
"this",
"interface!",
"Rather",
"just",
"directly",
"pass",
"on",
"the",
"jsonrpc2",
".",
"Request",
"via",
"h",
".",
"lang",
".",
"Handle",
".",
"Although",
"bypasses",
"the",
"JSON",
"-",
"RPC",
"wire",
"protocol",
"(",
"just",
"sending",
"it",
"in",
"-",
"memory",
"for",
"simplicity",
"/",
"speed",
")",
"it",
"behaves",
"in",
"the",
"same",
"way",
"as",
"though",
"the",
"peer",
"language",
"server",
"were",
"remote",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/build_server.go#L549-L578 |
sourcegraph/go-langserver | buildserver/build_server.go | Close | func (h *BuildHandler) Close() error {
var result error
for _, closer := range h.closers {
err := closer.Close()
if err != nil {
result = multierror.Append(result, err)
}
}
return result
} | go | func (h *BuildHandler) Close() error {
var result error
for _, closer := range h.closers {
err := closer.Close()
if err != nil {
result = multierror.Append(result, err)
}
}
return result
} | [
"func",
"(",
"h",
"*",
"BuildHandler",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"result",
"error",
"\n",
"for",
"_",
",",
"closer",
":=",
"range",
"h",
".",
"closers",
"{",
"err",
":=",
"closer",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
"=",
"multierror",
".",
"Append",
"(",
"result",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // Close implements io.Closer | [
"Close",
"implements",
"io",
".",
"Closer"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/build_server.go#L581-L590 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/goodarch.go | goodOSArch | func goodOSArch(filename string) (ok bool) {
if dot := strings.Index(filename, "."); dot != -1 {
filename = filename[:dot]
}
l := strings.Split(filename, "_")
n := len(l)
if n == 0 {
return true
}
if good, known := goodOS[l[n-1]]; known {
return good
}
if good, known := goodArch[l[n-1]]; known {
if !good || n < 2 {
return false
}
good, known = goodOS[l[n-2]]
return good || !known
}
return true
} | go | func goodOSArch(filename string) (ok bool) {
if dot := strings.Index(filename, "."); dot != -1 {
filename = filename[:dot]
}
l := strings.Split(filename, "_")
n := len(l)
if n == 0 {
return true
}
if good, known := goodOS[l[n-1]]; known {
return good
}
if good, known := goodArch[l[n-1]]; known {
if !good || n < 2 {
return false
}
good, known = goodOS[l[n-2]]
return good || !known
}
return true
} | [
"func",
"goodOSArch",
"(",
"filename",
"string",
")",
"(",
"ok",
"bool",
")",
"{",
"if",
"dot",
":=",
"strings",
".",
"Index",
"(",
"filename",
",",
"\"",
"\"",
")",
";",
"dot",
"!=",
"-",
"1",
"{",
"filename",
"=",
"filename",
"[",
":",
"dot",
"]",
"\n",
"}",
"\n",
"l",
":=",
"strings",
".",
"Split",
"(",
"filename",
",",
"\"",
"\"",
")",
"\n",
"n",
":=",
"len",
"(",
"l",
")",
"\n",
"if",
"n",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"good",
",",
"known",
":=",
"goodOS",
"[",
"l",
"[",
"n",
"-",
"1",
"]",
"]",
";",
"known",
"{",
"return",
"good",
"\n",
"}",
"\n",
"if",
"good",
",",
"known",
":=",
"goodArch",
"[",
"l",
"[",
"n",
"-",
"1",
"]",
"]",
";",
"known",
"{",
"if",
"!",
"good",
"||",
"n",
"<",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"good",
",",
"known",
"=",
"goodOS",
"[",
"l",
"[",
"n",
"-",
"2",
"]",
"]",
"\n",
"return",
"good",
"||",
"!",
"known",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // goodOSArch returns false if the filename contains a $GOOS or $GOARCH
// suffix which does not match the current system.
// The recognized filename formats are:
//
// name_$(GOOS).*
// name_$(GOARCH).*
// name_$(GOOS)_$(GOARCH).*
// | [
"goodOSArch",
"returns",
"false",
"if",
"the",
"filename",
"contains",
"a",
"$GOOS",
"or",
"$GOARCH",
"suffix",
"which",
"does",
"not",
"match",
"the",
"current",
"system",
".",
"The",
"recognized",
"filename",
"formats",
"are",
":",
"name_$",
"(",
"GOOS",
")",
".",
"*",
"name_$",
"(",
"GOARCH",
")",
".",
"*",
"name_$",
"(",
"GOOS",
")",
"_$",
"(",
"GOARCH",
")",
".",
"*"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/goodarch.go#L23-L43 |
sourcegraph/go-langserver | langserver/symbol.go | String | func (q Query) String() string {
s := ""
switch q.Filter {
case FilterExported:
s = queryJoin(s, "is:exported")
case FilterDir:
s = queryJoin(s, fmt.Sprintf("%s:%s", q.Filter, q.Dir))
default:
// no filter.
}
if q.Kind != 0 {
for kwd, kind := range keywords {
if kind == q.Kind {
s = queryJoin(s, kwd)
}
}
}
for _, token := range q.Tokens {
s = queryJoin(s, token)
}
return s
} | go | func (q Query) String() string {
s := ""
switch q.Filter {
case FilterExported:
s = queryJoin(s, "is:exported")
case FilterDir:
s = queryJoin(s, fmt.Sprintf("%s:%s", q.Filter, q.Dir))
default:
// no filter.
}
if q.Kind != 0 {
for kwd, kind := range keywords {
if kind == q.Kind {
s = queryJoin(s, kwd)
}
}
}
for _, token := range q.Tokens {
s = queryJoin(s, token)
}
return s
} | [
"func",
"(",
"q",
"Query",
")",
"String",
"(",
")",
"string",
"{",
"s",
":=",
"\"",
"\"",
"\n",
"switch",
"q",
".",
"Filter",
"{",
"case",
"FilterExported",
":",
"s",
"=",
"queryJoin",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"case",
"FilterDir",
":",
"s",
"=",
"queryJoin",
"(",
"s",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"q",
".",
"Filter",
",",
"q",
".",
"Dir",
")",
")",
"\n",
"default",
":",
"// no filter.",
"}",
"\n",
"if",
"q",
".",
"Kind",
"!=",
"0",
"{",
"for",
"kwd",
",",
"kind",
":=",
"range",
"keywords",
"{",
"if",
"kind",
"==",
"q",
".",
"Kind",
"{",
"s",
"=",
"queryJoin",
"(",
"s",
",",
"kwd",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"token",
":=",
"range",
"q",
".",
"Tokens",
"{",
"s",
"=",
"queryJoin",
"(",
"s",
",",
"token",
")",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // String converts the query back into a logically equivalent, but not strictly
// byte-wise equal, query string. It is useful for converting a modified query
// structure back into a query string. | [
"String",
"converts",
"the",
"query",
"back",
"into",
"a",
"logically",
"equivalent",
"but",
"not",
"strictly",
"byte",
"-",
"wise",
"equal",
"query",
"string",
".",
"It",
"is",
"useful",
"for",
"converting",
"a",
"modified",
"query",
"structure",
"back",
"into",
"a",
"query",
"string",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L42-L63 |
sourcegraph/go-langserver | langserver/symbol.go | ParseQuery | func ParseQuery(q string) (qu Query) {
// All queries are case insensitive.
q = strings.ToLower(q)
// Split the query into space-delimited fields.
for _, field := range strings.Fields(q) {
// Check if the field is a filter like `is:exported`.
if strings.HasPrefix(field, "dir:") {
qu.Filter = FilterDir
qu.Dir = strings.TrimPrefix(field, "dir:")
continue
}
if field == "is:exported" {
qu.Filter = FilterExported
continue
}
// Each field is split into tokens, delimited by periods or slashes.
tokens := strings.FieldsFunc(field, func(c rune) bool {
return c == '.' || c == '/'
})
for _, tok := range tokens {
if kind, isKeyword := keywords[tok]; isKeyword {
qu.Kind = kind
continue
}
qu.Tokens = append(qu.Tokens, tok)
}
}
return qu
} | go | func ParseQuery(q string) (qu Query) {
// All queries are case insensitive.
q = strings.ToLower(q)
// Split the query into space-delimited fields.
for _, field := range strings.Fields(q) {
// Check if the field is a filter like `is:exported`.
if strings.HasPrefix(field, "dir:") {
qu.Filter = FilterDir
qu.Dir = strings.TrimPrefix(field, "dir:")
continue
}
if field == "is:exported" {
qu.Filter = FilterExported
continue
}
// Each field is split into tokens, delimited by periods or slashes.
tokens := strings.FieldsFunc(field, func(c rune) bool {
return c == '.' || c == '/'
})
for _, tok := range tokens {
if kind, isKeyword := keywords[tok]; isKeyword {
qu.Kind = kind
continue
}
qu.Tokens = append(qu.Tokens, tok)
}
}
return qu
} | [
"func",
"ParseQuery",
"(",
"q",
"string",
")",
"(",
"qu",
"Query",
")",
"{",
"// All queries are case insensitive.",
"q",
"=",
"strings",
".",
"ToLower",
"(",
"q",
")",
"\n\n",
"// Split the query into space-delimited fields.",
"for",
"_",
",",
"field",
":=",
"range",
"strings",
".",
"Fields",
"(",
"q",
")",
"{",
"// Check if the field is a filter like `is:exported`.",
"if",
"strings",
".",
"HasPrefix",
"(",
"field",
",",
"\"",
"\"",
")",
"{",
"qu",
".",
"Filter",
"=",
"FilterDir",
"\n",
"qu",
".",
"Dir",
"=",
"strings",
".",
"TrimPrefix",
"(",
"field",
",",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"field",
"==",
"\"",
"\"",
"{",
"qu",
".",
"Filter",
"=",
"FilterExported",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Each field is split into tokens, delimited by periods or slashes.",
"tokens",
":=",
"strings",
".",
"FieldsFunc",
"(",
"field",
",",
"func",
"(",
"c",
"rune",
")",
"bool",
"{",
"return",
"c",
"==",
"'.'",
"||",
"c",
"==",
"'/'",
"\n",
"}",
")",
"\n",
"for",
"_",
",",
"tok",
":=",
"range",
"tokens",
"{",
"if",
"kind",
",",
"isKeyword",
":=",
"keywords",
"[",
"tok",
"]",
";",
"isKeyword",
"{",
"qu",
".",
"Kind",
"=",
"kind",
"\n",
"continue",
"\n",
"}",
"\n",
"qu",
".",
"Tokens",
"=",
"append",
"(",
"qu",
".",
"Tokens",
",",
"tok",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"qu",
"\n",
"}"
] | // ParseQuery parses a user's raw query string and returns a
// structured representation of the query. | [
"ParseQuery",
"parses",
"a",
"user",
"s",
"raw",
"query",
"string",
"and",
"returns",
"a",
"structured",
"representation",
"of",
"the",
"query",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L73-L103 |
sourcegraph/go-langserver | langserver/symbol.go | Collect | func (s *resultSorter) Collect(si symbolPair) {
s.resultsMu.Lock()
score := score(s.Query, si)
if score > 0 {
sc := scoredSymbol{score, si}
s.results = append(s.results, sc)
}
s.resultsMu.Unlock()
} | go | func (s *resultSorter) Collect(si symbolPair) {
s.resultsMu.Lock()
score := score(s.Query, si)
if score > 0 {
sc := scoredSymbol{score, si}
s.results = append(s.results, sc)
}
s.resultsMu.Unlock()
} | [
"func",
"(",
"s",
"*",
"resultSorter",
")",
"Collect",
"(",
"si",
"symbolPair",
")",
"{",
"s",
".",
"resultsMu",
".",
"Lock",
"(",
")",
"\n",
"score",
":=",
"score",
"(",
"s",
".",
"Query",
",",
"si",
")",
"\n",
"if",
"score",
">",
"0",
"{",
"sc",
":=",
"scoredSymbol",
"{",
"score",
",",
"si",
"}",
"\n",
"s",
".",
"results",
"=",
"append",
"(",
"s",
".",
"results",
",",
"sc",
")",
"\n",
"}",
"\n",
"s",
".",
"resultsMu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Collect is a thread-safe method that will record the passed-in
// symbol in the list of results if its score > 0. | [
"Collect",
"is",
"a",
"thread",
"-",
"safe",
"method",
"that",
"will",
"record",
"the",
"passed",
"-",
"in",
"symbol",
"in",
"the",
"list",
"of",
"results",
"if",
"its",
"score",
">",
"0",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L167-L175 |
sourcegraph/go-langserver | langserver/symbol.go | Results | func (s *resultSorter) Results() []lsp.SymbolInformation {
res := make([]lsp.SymbolInformation, len(s.results))
for i, s := range s.results {
res[i] = s.SymbolInformation
}
return res
} | go | func (s *resultSorter) Results() []lsp.SymbolInformation {
res := make([]lsp.SymbolInformation, len(s.results))
for i, s := range s.results {
res[i] = s.SymbolInformation
}
return res
} | [
"func",
"(",
"s",
"*",
"resultSorter",
")",
"Results",
"(",
")",
"[",
"]",
"lsp",
".",
"SymbolInformation",
"{",
"res",
":=",
"make",
"(",
"[",
"]",
"lsp",
".",
"SymbolInformation",
",",
"len",
"(",
"s",
".",
"results",
")",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"s",
".",
"results",
"{",
"res",
"[",
"i",
"]",
"=",
"s",
".",
"SymbolInformation",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] | // Results returns the ranked list of SymbolInformation values. | [
"Results",
"returns",
"the",
"ranked",
"list",
"of",
"SymbolInformation",
"values",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L178-L184 |
sourcegraph/go-langserver | langserver/symbol.go | score | func score(q Query, s symbolPair) (scor int) {
if q.Kind != 0 {
if q.Kind != s.Kind {
return 0
}
}
if q.Symbol != nil && !s.desc.Contains(q.Symbol) {
return -1
}
name, container := strings.ToLower(s.Name), strings.ToLower(s.ContainerName)
if !util.IsURI(s.Location.URI) {
log.Printf("unexpectedly saw symbol defined at a non-file URI: %q", s.Location.URI)
return 0
}
filename := util.UriToPath(s.Location.URI)
isVendor := strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/")
if q.Filter == FilterExported && isVendor {
// is:exported excludes vendor symbols always.
return 0
}
if q.File != "" && filename != q.File {
// We're restricting results to a single file, and this isn't it.
return 0
}
if len(q.Tokens) == 0 { // early return if empty query
if isVendor {
return 1 // lower score for vendor symbols
} else {
return 2
}
}
for i, tok := range q.Tokens {
tok := strings.ToLower(tok)
if strings.HasPrefix(container, tok) {
scor += 2
}
if strings.HasPrefix(name, tok) {
scor += 3
}
if strings.Contains(filename, tok) && len(tok) >= 3 {
scor++
}
if strings.HasPrefix(path.Base(filename), tok) && len(tok) >= 3 {
scor += 2
}
if tok == name {
if i == len(q.Tokens)-1 {
scor += 50
} else {
scor += 5
}
}
if tok == container {
scor += 3
}
}
if scor > 0 && !(strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/")) {
// boost for non-vendor symbols
scor += 5
}
if scor > 0 && ast.IsExported(s.Name) {
// boost for exported symbols
scor++
}
return scor
} | go | func score(q Query, s symbolPair) (scor int) {
if q.Kind != 0 {
if q.Kind != s.Kind {
return 0
}
}
if q.Symbol != nil && !s.desc.Contains(q.Symbol) {
return -1
}
name, container := strings.ToLower(s.Name), strings.ToLower(s.ContainerName)
if !util.IsURI(s.Location.URI) {
log.Printf("unexpectedly saw symbol defined at a non-file URI: %q", s.Location.URI)
return 0
}
filename := util.UriToPath(s.Location.URI)
isVendor := strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/")
if q.Filter == FilterExported && isVendor {
// is:exported excludes vendor symbols always.
return 0
}
if q.File != "" && filename != q.File {
// We're restricting results to a single file, and this isn't it.
return 0
}
if len(q.Tokens) == 0 { // early return if empty query
if isVendor {
return 1 // lower score for vendor symbols
} else {
return 2
}
}
for i, tok := range q.Tokens {
tok := strings.ToLower(tok)
if strings.HasPrefix(container, tok) {
scor += 2
}
if strings.HasPrefix(name, tok) {
scor += 3
}
if strings.Contains(filename, tok) && len(tok) >= 3 {
scor++
}
if strings.HasPrefix(path.Base(filename), tok) && len(tok) >= 3 {
scor += 2
}
if tok == name {
if i == len(q.Tokens)-1 {
scor += 50
} else {
scor += 5
}
}
if tok == container {
scor += 3
}
}
if scor > 0 && !(strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/")) {
// boost for non-vendor symbols
scor += 5
}
if scor > 0 && ast.IsExported(s.Name) {
// boost for exported symbols
scor++
}
return scor
} | [
"func",
"score",
"(",
"q",
"Query",
",",
"s",
"symbolPair",
")",
"(",
"scor",
"int",
")",
"{",
"if",
"q",
".",
"Kind",
"!=",
"0",
"{",
"if",
"q",
".",
"Kind",
"!=",
"s",
".",
"Kind",
"{",
"return",
"0",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"q",
".",
"Symbol",
"!=",
"nil",
"&&",
"!",
"s",
".",
"desc",
".",
"Contains",
"(",
"q",
".",
"Symbol",
")",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"name",
",",
"container",
":=",
"strings",
".",
"ToLower",
"(",
"s",
".",
"Name",
")",
",",
"strings",
".",
"ToLower",
"(",
"s",
".",
"ContainerName",
")",
"\n",
"if",
"!",
"util",
".",
"IsURI",
"(",
"s",
".",
"Location",
".",
"URI",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"Location",
".",
"URI",
")",
"\n",
"return",
"0",
"\n",
"}",
"\n",
"filename",
":=",
"util",
".",
"UriToPath",
"(",
"s",
".",
"Location",
".",
"URI",
")",
"\n",
"isVendor",
":=",
"strings",
".",
"HasPrefix",
"(",
"filename",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"filename",
",",
"\"",
"\"",
")",
"\n",
"if",
"q",
".",
"Filter",
"==",
"FilterExported",
"&&",
"isVendor",
"{",
"// is:exported excludes vendor symbols always.",
"return",
"0",
"\n",
"}",
"\n",
"if",
"q",
".",
"File",
"!=",
"\"",
"\"",
"&&",
"filename",
"!=",
"q",
".",
"File",
"{",
"// We're restricting results to a single file, and this isn't it.",
"return",
"0",
"\n",
"}",
"\n",
"if",
"len",
"(",
"q",
".",
"Tokens",
")",
"==",
"0",
"{",
"// early return if empty query",
"if",
"isVendor",
"{",
"return",
"1",
"// lower score for vendor symbols",
"\n",
"}",
"else",
"{",
"return",
"2",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
",",
"tok",
":=",
"range",
"q",
".",
"Tokens",
"{",
"tok",
":=",
"strings",
".",
"ToLower",
"(",
"tok",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"container",
",",
"tok",
")",
"{",
"scor",
"+=",
"2",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"tok",
")",
"{",
"scor",
"+=",
"3",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"filename",
",",
"tok",
")",
"&&",
"len",
"(",
"tok",
")",
">=",
"3",
"{",
"scor",
"++",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"path",
".",
"Base",
"(",
"filename",
")",
",",
"tok",
")",
"&&",
"len",
"(",
"tok",
")",
">=",
"3",
"{",
"scor",
"+=",
"2",
"\n",
"}",
"\n",
"if",
"tok",
"==",
"name",
"{",
"if",
"i",
"==",
"len",
"(",
"q",
".",
"Tokens",
")",
"-",
"1",
"{",
"scor",
"+=",
"50",
"\n",
"}",
"else",
"{",
"scor",
"+=",
"5",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"tok",
"==",
"container",
"{",
"scor",
"+=",
"3",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"scor",
">",
"0",
"&&",
"!",
"(",
"strings",
".",
"HasPrefix",
"(",
"filename",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"filename",
",",
"\"",
"\"",
")",
")",
"{",
"// boost for non-vendor symbols",
"scor",
"+=",
"5",
"\n",
"}",
"\n",
"if",
"scor",
">",
"0",
"&&",
"ast",
".",
"IsExported",
"(",
"s",
".",
"Name",
")",
"{",
"// boost for exported symbols",
"scor",
"++",
"\n",
"}",
"\n",
"return",
"scor",
"\n",
"}"
] | // score returns 0 for results that aren't matches. Results that are matches are assigned
// a positive score, which should be used for ranking purposes. | [
"score",
"returns",
"0",
"for",
"results",
"that",
"aren",
"t",
"matches",
".",
"Results",
"that",
"are",
"matches",
"are",
"assigned",
"a",
"positive",
"score",
"which",
"should",
"be",
"used",
"for",
"ranking",
"purposes",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L188-L253 |
sourcegraph/go-langserver | langserver/symbol.go | toSym | func toSym(name string, bpkg *build.Package, container string, recv string, kind lsp.SymbolKind, fs *token.FileSet, pos token.Pos) symbolPair {
var id string
if container == "" {
id = fmt.Sprintf("%s/-/%s", path.Clean(bpkg.ImportPath), name)
} else {
id = fmt.Sprintf("%s/-/%s/%s", path.Clean(bpkg.ImportPath), container, name)
}
return symbolPair{
SymbolInformation: lsp.SymbolInformation{
Name: name,
Kind: kind,
Location: goRangeToLSPLocation(fs, pos, pos+token.Pos(len(name))),
ContainerName: container,
},
// NOTE: fields must be kept in sync with workspace_refs.go:defSymbolDescriptor
desc: symbolDescriptor{
Vendor: util.IsVendorDir(bpkg.Dir),
Package: path.Clean(bpkg.ImportPath),
PackageName: bpkg.Name,
Recv: recv,
Name: name,
ID: id,
},
}
} | go | func toSym(name string, bpkg *build.Package, container string, recv string, kind lsp.SymbolKind, fs *token.FileSet, pos token.Pos) symbolPair {
var id string
if container == "" {
id = fmt.Sprintf("%s/-/%s", path.Clean(bpkg.ImportPath), name)
} else {
id = fmt.Sprintf("%s/-/%s/%s", path.Clean(bpkg.ImportPath), container, name)
}
return symbolPair{
SymbolInformation: lsp.SymbolInformation{
Name: name,
Kind: kind,
Location: goRangeToLSPLocation(fs, pos, pos+token.Pos(len(name))),
ContainerName: container,
},
// NOTE: fields must be kept in sync with workspace_refs.go:defSymbolDescriptor
desc: symbolDescriptor{
Vendor: util.IsVendorDir(bpkg.Dir),
Package: path.Clean(bpkg.ImportPath),
PackageName: bpkg.Name,
Recv: recv,
Name: name,
ID: id,
},
}
} | [
"func",
"toSym",
"(",
"name",
"string",
",",
"bpkg",
"*",
"build",
".",
"Package",
",",
"container",
"string",
",",
"recv",
"string",
",",
"kind",
"lsp",
".",
"SymbolKind",
",",
"fs",
"*",
"token",
".",
"FileSet",
",",
"pos",
"token",
".",
"Pos",
")",
"symbolPair",
"{",
"var",
"id",
"string",
"\n",
"if",
"container",
"==",
"\"",
"\"",
"{",
"id",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
".",
"Clean",
"(",
"bpkg",
".",
"ImportPath",
")",
",",
"name",
")",
"\n",
"}",
"else",
"{",
"id",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
".",
"Clean",
"(",
"bpkg",
".",
"ImportPath",
")",
",",
"container",
",",
"name",
")",
"\n",
"}",
"\n\n",
"return",
"symbolPair",
"{",
"SymbolInformation",
":",
"lsp",
".",
"SymbolInformation",
"{",
"Name",
":",
"name",
",",
"Kind",
":",
"kind",
",",
"Location",
":",
"goRangeToLSPLocation",
"(",
"fs",
",",
"pos",
",",
"pos",
"+",
"token",
".",
"Pos",
"(",
"len",
"(",
"name",
")",
")",
")",
",",
"ContainerName",
":",
"container",
",",
"}",
",",
"// NOTE: fields must be kept in sync with workspace_refs.go:defSymbolDescriptor",
"desc",
":",
"symbolDescriptor",
"{",
"Vendor",
":",
"util",
".",
"IsVendorDir",
"(",
"bpkg",
".",
"Dir",
")",
",",
"Package",
":",
"path",
".",
"Clean",
"(",
"bpkg",
".",
"ImportPath",
")",
",",
"PackageName",
":",
"bpkg",
".",
"Name",
",",
"Recv",
":",
"recv",
",",
"Name",
":",
"name",
",",
"ID",
":",
"id",
",",
"}",
",",
"}",
"\n",
"}"
] | // toSym returns a SymbolInformation value derived from values we get
// from visiting the Go ast. | [
"toSym",
"returns",
"a",
"SymbolInformation",
"value",
"derived",
"from",
"values",
"we",
"get",
"from",
"visiting",
"the",
"Go",
"ast",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L257-L282 |
sourcegraph/go-langserver | langserver/symbol.go | handleTextDocumentSymbol | func (h *LangHandler) handleTextDocumentSymbol(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, params lsp.DocumentSymbolParams) ([]lsp.SymbolInformation, error) {
if !util.IsURI(params.TextDocument.URI) {
return nil, &jsonrpc2.Error{
Code: jsonrpc2.CodeInvalidParams,
Message: fmt.Sprintf("textDocument/documentSymbol not yet supported for out-of-workspace URI (%q)", params.TextDocument.URI),
}
}
path := util.UriToPath(params.TextDocument.URI)
fset := token.NewFileSet()
bctx := h.BuildContext(ctx)
src, err := buildutil.ParseFile(fset, bctx, nil, filepath.Dir(path), filepath.Base(path), 0)
if err != nil {
return nil, err
}
pkg := &ast.Package{
Name: src.Name.Name,
Files: map[string]*ast.File{},
}
pkg.Files[filepath.Base(path)] = src
symbols := astPkgToSymbols(fset, pkg, &build.Package{})
res := make([]lsp.SymbolInformation, len(symbols))
for i, s := range symbols {
res[i] = s.SymbolInformation
}
return res, nil
} | go | func (h *LangHandler) handleTextDocumentSymbol(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, params lsp.DocumentSymbolParams) ([]lsp.SymbolInformation, error) {
if !util.IsURI(params.TextDocument.URI) {
return nil, &jsonrpc2.Error{
Code: jsonrpc2.CodeInvalidParams,
Message: fmt.Sprintf("textDocument/documentSymbol not yet supported for out-of-workspace URI (%q)", params.TextDocument.URI),
}
}
path := util.UriToPath(params.TextDocument.URI)
fset := token.NewFileSet()
bctx := h.BuildContext(ctx)
src, err := buildutil.ParseFile(fset, bctx, nil, filepath.Dir(path), filepath.Base(path), 0)
if err != nil {
return nil, err
}
pkg := &ast.Package{
Name: src.Name.Name,
Files: map[string]*ast.File{},
}
pkg.Files[filepath.Base(path)] = src
symbols := astPkgToSymbols(fset, pkg, &build.Package{})
res := make([]lsp.SymbolInformation, len(symbols))
for i, s := range symbols {
res[i] = s.SymbolInformation
}
return res, nil
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"handleTextDocumentSymbol",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
",",
"params",
"lsp",
".",
"DocumentSymbolParams",
")",
"(",
"[",
"]",
"lsp",
".",
"SymbolInformation",
",",
"error",
")",
"{",
"if",
"!",
"util",
".",
"IsURI",
"(",
"params",
".",
"TextDocument",
".",
"URI",
")",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"params",
".",
"TextDocument",
".",
"URI",
")",
",",
"}",
"\n",
"}",
"\n",
"path",
":=",
"util",
".",
"UriToPath",
"(",
"params",
".",
"TextDocument",
".",
"URI",
")",
"\n\n",
"fset",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"\n",
"bctx",
":=",
"h",
".",
"BuildContext",
"(",
"ctx",
")",
"\n",
"src",
",",
"err",
":=",
"buildutil",
".",
"ParseFile",
"(",
"fset",
",",
"bctx",
",",
"nil",
",",
"filepath",
".",
"Dir",
"(",
"path",
")",
",",
"filepath",
".",
"Base",
"(",
"path",
")",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pkg",
":=",
"&",
"ast",
".",
"Package",
"{",
"Name",
":",
"src",
".",
"Name",
".",
"Name",
",",
"Files",
":",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"File",
"{",
"}",
",",
"}",
"\n",
"pkg",
".",
"Files",
"[",
"filepath",
".",
"Base",
"(",
"path",
")",
"]",
"=",
"src",
"\n\n",
"symbols",
":=",
"astPkgToSymbols",
"(",
"fset",
",",
"pkg",
",",
"&",
"build",
".",
"Package",
"{",
"}",
")",
"\n",
"res",
":=",
"make",
"(",
"[",
"]",
"lsp",
".",
"SymbolInformation",
",",
"len",
"(",
"symbols",
")",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"symbols",
"{",
"res",
"[",
"i",
"]",
"=",
"s",
".",
"SymbolInformation",
"\n",
"}",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // handleTextDocumentSymbol handles `textDocument/documentSymbol` requests for
// the Go language server. | [
"handleTextDocumentSymbol",
"handles",
"textDocument",
"/",
"documentSymbol",
"requests",
"for",
"the",
"Go",
"language",
"server",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L286-L313 |
sourcegraph/go-langserver | langserver/symbol.go | handleWorkspaceSymbol | func (h *LangHandler) handleWorkspaceSymbol(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, params lspext.WorkspaceSymbolParams) ([]lsp.SymbolInformation, error) {
q := ParseQuery(params.Query)
q.Symbol = params.Symbol
if q.Filter == FilterDir {
q.Dir = path.Join(h.init.RootImportPath, q.Dir)
}
if id, ok := q.Symbol["id"]; ok {
// id implicitly contains a dir hint. We can use that to
// reduce the number of files we have to parse.
q.Dir = strings.SplitN(id.(string), "/-/", 2)[0]
q.Filter = FilterDir
}
if params.Limit == 0 {
// If no limit is specified, default to a reasonable number
// for a user to look at. If they want more, they should
// refine the query.
params.Limit = 50
}
return h.handleSymbol(ctx, conn, req, q, params.Limit)
} | go | func (h *LangHandler) handleWorkspaceSymbol(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, params lspext.WorkspaceSymbolParams) ([]lsp.SymbolInformation, error) {
q := ParseQuery(params.Query)
q.Symbol = params.Symbol
if q.Filter == FilterDir {
q.Dir = path.Join(h.init.RootImportPath, q.Dir)
}
if id, ok := q.Symbol["id"]; ok {
// id implicitly contains a dir hint. We can use that to
// reduce the number of files we have to parse.
q.Dir = strings.SplitN(id.(string), "/-/", 2)[0]
q.Filter = FilterDir
}
if params.Limit == 0 {
// If no limit is specified, default to a reasonable number
// for a user to look at. If they want more, they should
// refine the query.
params.Limit = 50
}
return h.handleSymbol(ctx, conn, req, q, params.Limit)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"handleWorkspaceSymbol",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
",",
"params",
"lspext",
".",
"WorkspaceSymbolParams",
")",
"(",
"[",
"]",
"lsp",
".",
"SymbolInformation",
",",
"error",
")",
"{",
"q",
":=",
"ParseQuery",
"(",
"params",
".",
"Query",
")",
"\n",
"q",
".",
"Symbol",
"=",
"params",
".",
"Symbol",
"\n",
"if",
"q",
".",
"Filter",
"==",
"FilterDir",
"{",
"q",
".",
"Dir",
"=",
"path",
".",
"Join",
"(",
"h",
".",
"init",
".",
"RootImportPath",
",",
"q",
".",
"Dir",
")",
"\n",
"}",
"\n",
"if",
"id",
",",
"ok",
":=",
"q",
".",
"Symbol",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"// id implicitly contains a dir hint. We can use that to",
"// reduce the number of files we have to parse.",
"q",
".",
"Dir",
"=",
"strings",
".",
"SplitN",
"(",
"id",
".",
"(",
"string",
")",
",",
"\"",
"\"",
",",
"2",
")",
"[",
"0",
"]",
"\n",
"q",
".",
"Filter",
"=",
"FilterDir",
"\n",
"}",
"\n",
"if",
"params",
".",
"Limit",
"==",
"0",
"{",
"// If no limit is specified, default to a reasonable number",
"// for a user to look at. If they want more, they should",
"// refine the query.",
"params",
".",
"Limit",
"=",
"50",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleSymbol",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"q",
",",
"params",
".",
"Limit",
")",
"\n",
"}"
] | // handleSymbol handles `workspace/symbol` requests for the Go
// language server. | [
"handleSymbol",
"handles",
"workspace",
"/",
"symbol",
"requests",
"for",
"the",
"Go",
"language",
"server",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L317-L336 |
sourcegraph/go-langserver | langserver/symbol.go | collectFromPkg | func (h *LangHandler) collectFromPkg(ctx context.Context, bctx *build.Context, pkg string, rootPath string, results *resultSorter) {
symbols := h.symbolCache.Get(pkg, func() interface{} {
findPackage := h.getFindPackageFunc()
buildPkg, err := findPackage(ctx, bctx, pkg, rootPath, rootPath, 0)
if err != nil {
maybeLogImportError(pkg, err)
return nil
}
fs := token.NewFileSet()
astPkgs, err := parseDir(fs, bctx, buildPkg.Dir, nil, 0)
if err != nil {
log.Printf("failed to parse directory %s: %s", buildPkg.Dir, err)
return nil
}
astPkg := astPkgs[buildPkg.Name]
if astPkg == nil {
return nil
}
return astPkgToSymbols(fs, astPkg, buildPkg)
})
if symbols == nil {
return
}
for _, sym := range symbols.([]symbolPair) {
if results.Query.Filter == FilterExported && !isExported(&sym) {
continue
}
results.Collect(sym)
}
} | go | func (h *LangHandler) collectFromPkg(ctx context.Context, bctx *build.Context, pkg string, rootPath string, results *resultSorter) {
symbols := h.symbolCache.Get(pkg, func() interface{} {
findPackage := h.getFindPackageFunc()
buildPkg, err := findPackage(ctx, bctx, pkg, rootPath, rootPath, 0)
if err != nil {
maybeLogImportError(pkg, err)
return nil
}
fs := token.NewFileSet()
astPkgs, err := parseDir(fs, bctx, buildPkg.Dir, nil, 0)
if err != nil {
log.Printf("failed to parse directory %s: %s", buildPkg.Dir, err)
return nil
}
astPkg := astPkgs[buildPkg.Name]
if astPkg == nil {
return nil
}
return astPkgToSymbols(fs, astPkg, buildPkg)
})
if symbols == nil {
return
}
for _, sym := range symbols.([]symbolPair) {
if results.Query.Filter == FilterExported && !isExported(&sym) {
continue
}
results.Collect(sym)
}
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"collectFromPkg",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"pkg",
"string",
",",
"rootPath",
"string",
",",
"results",
"*",
"resultSorter",
")",
"{",
"symbols",
":=",
"h",
".",
"symbolCache",
".",
"Get",
"(",
"pkg",
",",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"findPackage",
":=",
"h",
".",
"getFindPackageFunc",
"(",
")",
"\n",
"buildPkg",
",",
"err",
":=",
"findPackage",
"(",
"ctx",
",",
"bctx",
",",
"pkg",
",",
"rootPath",
",",
"rootPath",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"maybeLogImportError",
"(",
"pkg",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"fs",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"\n",
"astPkgs",
",",
"err",
":=",
"parseDir",
"(",
"fs",
",",
"bctx",
",",
"buildPkg",
".",
"Dir",
",",
"nil",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"buildPkg",
".",
"Dir",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"astPkg",
":=",
"astPkgs",
"[",
"buildPkg",
".",
"Name",
"]",
"\n",
"if",
"astPkg",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"astPkgToSymbols",
"(",
"fs",
",",
"astPkg",
",",
"buildPkg",
")",
"\n",
"}",
")",
"\n\n",
"if",
"symbols",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"sym",
":=",
"range",
"symbols",
".",
"(",
"[",
"]",
"symbolPair",
")",
"{",
"if",
"results",
".",
"Query",
".",
"Filter",
"==",
"FilterExported",
"&&",
"!",
"isExported",
"(",
"&",
"sym",
")",
"{",
"continue",
"\n",
"}",
"\n",
"results",
".",
"Collect",
"(",
"sym",
")",
"\n",
"}",
"\n",
"}"
] | // collectFromPkg collects all the symbols from the specified package
// into the results. It uses LangHandler's package symbol cache to
// speed up repeated calls. | [
"collectFromPkg",
"collects",
"all",
"the",
"symbols",
"from",
"the",
"specified",
"package",
"into",
"the",
"results",
".",
"It",
"uses",
"LangHandler",
"s",
"package",
"symbol",
"cache",
"to",
"speed",
"up",
"repeated",
"calls",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L403-L436 |
sourcegraph/go-langserver | langserver/symbol.go | Visit | func (c *SymbolCollector) Visit(n ast.Node) (w ast.Visitor) {
switch t := n.(type) {
case *ast.TypeSpec:
if t.Name.Name != "_" {
switch term := t.Type.(type) {
case *ast.StructType:
c.addContainer(t.Name.Name, term.Fields, lsp.SKClass, t.Name.NamePos)
case *ast.InterfaceType:
c.addContainer(t.Name.Name, term.Methods, lsp.SKInterface, t.Name.NamePos)
default:
c.addSymbol(t.Name.Name, "", "", lsp.SKClass, t.Name.NamePos)
}
}
case *ast.GenDecl:
switch t.Tok {
case token.CONST:
names := specNames(t.Specs)
for _, name := range names {
c.addSymbol(name, "", "", lsp.SKConstant, declNamePos(t, name))
}
case token.VAR:
names := specNames(t.Specs)
for _, name := range names {
if name != "_" {
c.addSymbol(name, "", "", lsp.SKVariable, declNamePos(t, name))
}
}
}
case *ast.FuncDecl:
c.addFuncDecl(t)
}
return c
} | go | func (c *SymbolCollector) Visit(n ast.Node) (w ast.Visitor) {
switch t := n.(type) {
case *ast.TypeSpec:
if t.Name.Name != "_" {
switch term := t.Type.(type) {
case *ast.StructType:
c.addContainer(t.Name.Name, term.Fields, lsp.SKClass, t.Name.NamePos)
case *ast.InterfaceType:
c.addContainer(t.Name.Name, term.Methods, lsp.SKInterface, t.Name.NamePos)
default:
c.addSymbol(t.Name.Name, "", "", lsp.SKClass, t.Name.NamePos)
}
}
case *ast.GenDecl:
switch t.Tok {
case token.CONST:
names := specNames(t.Specs)
for _, name := range names {
c.addSymbol(name, "", "", lsp.SKConstant, declNamePos(t, name))
}
case token.VAR:
names := specNames(t.Specs)
for _, name := range names {
if name != "_" {
c.addSymbol(name, "", "", lsp.SKVariable, declNamePos(t, name))
}
}
}
case *ast.FuncDecl:
c.addFuncDecl(t)
}
return c
} | [
"func",
"(",
"c",
"*",
"SymbolCollector",
")",
"Visit",
"(",
"n",
"ast",
".",
"Node",
")",
"(",
"w",
"ast",
".",
"Visitor",
")",
"{",
"switch",
"t",
":=",
"n",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"TypeSpec",
":",
"if",
"t",
".",
"Name",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"switch",
"term",
":=",
"t",
".",
"Type",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"StructType",
":",
"c",
".",
"addContainer",
"(",
"t",
".",
"Name",
".",
"Name",
",",
"term",
".",
"Fields",
",",
"lsp",
".",
"SKClass",
",",
"t",
".",
"Name",
".",
"NamePos",
")",
"\n",
"case",
"*",
"ast",
".",
"InterfaceType",
":",
"c",
".",
"addContainer",
"(",
"t",
".",
"Name",
".",
"Name",
",",
"term",
".",
"Methods",
",",
"lsp",
".",
"SKInterface",
",",
"t",
".",
"Name",
".",
"NamePos",
")",
"\n",
"default",
":",
"c",
".",
"addSymbol",
"(",
"t",
".",
"Name",
".",
"Name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"lsp",
".",
"SKClass",
",",
"t",
".",
"Name",
".",
"NamePos",
")",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"*",
"ast",
".",
"GenDecl",
":",
"switch",
"t",
".",
"Tok",
"{",
"case",
"token",
".",
"CONST",
":",
"names",
":=",
"specNames",
"(",
"t",
".",
"Specs",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"c",
".",
"addSymbol",
"(",
"name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"lsp",
".",
"SKConstant",
",",
"declNamePos",
"(",
"t",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"case",
"token",
".",
"VAR",
":",
"names",
":=",
"specNames",
"(",
"t",
".",
"Specs",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"c",
".",
"addSymbol",
"(",
"name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"lsp",
".",
"SKVariable",
",",
"declNamePos",
"(",
"t",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"*",
"ast",
".",
"FuncDecl",
":",
"c",
".",
"addFuncDecl",
"(",
"t",
")",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // Visit visits AST nodes and collects symbol information | [
"Visit",
"visits",
"AST",
"nodes",
"and",
"collects",
"symbol",
"information"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L497-L529 |
sourcegraph/go-langserver | langserver/symbol.go | parseDir | func parseDir(fset *token.FileSet, bctx *build.Context, path string, filter func(os.FileInfo) bool, mode parser.Mode) (pkgs map[string]*ast.Package, first error) {
list, err := buildutil.ReadDir(bctx, path)
if err != nil {
return nil, err
}
pkgs = map[string]*ast.Package{}
for _, d := range list {
if strings.HasSuffix(d.Name(), ".go") && (filter == nil || filter(d)) {
filename := buildutil.JoinPath(bctx, path, d.Name())
if src, err := buildutil.ParseFile(fset, bctx, nil, buildutil.JoinPath(bctx, path, d.Name()), filename, mode); err == nil {
name := src.Name.Name
pkg, found := pkgs[name]
if !found {
pkg = &ast.Package{
Name: name,
Files: map[string]*ast.File{},
}
pkgs[name] = pkg
}
pkg.Files[filename] = src
} else if first == nil {
first = err
}
}
}
return
} | go | func parseDir(fset *token.FileSet, bctx *build.Context, path string, filter func(os.FileInfo) bool, mode parser.Mode) (pkgs map[string]*ast.Package, first error) {
list, err := buildutil.ReadDir(bctx, path)
if err != nil {
return nil, err
}
pkgs = map[string]*ast.Package{}
for _, d := range list {
if strings.HasSuffix(d.Name(), ".go") && (filter == nil || filter(d)) {
filename := buildutil.JoinPath(bctx, path, d.Name())
if src, err := buildutil.ParseFile(fset, bctx, nil, buildutil.JoinPath(bctx, path, d.Name()), filename, mode); err == nil {
name := src.Name.Name
pkg, found := pkgs[name]
if !found {
pkg = &ast.Package{
Name: name,
Files: map[string]*ast.File{},
}
pkgs[name] = pkg
}
pkg.Files[filename] = src
} else if first == nil {
first = err
}
}
}
return
} | [
"func",
"parseDir",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"path",
"string",
",",
"filter",
"func",
"(",
"os",
".",
"FileInfo",
")",
"bool",
",",
"mode",
"parser",
".",
"Mode",
")",
"(",
"pkgs",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"Package",
",",
"first",
"error",
")",
"{",
"list",
",",
"err",
":=",
"buildutil",
".",
"ReadDir",
"(",
"bctx",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pkgs",
"=",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"Package",
"{",
"}",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"list",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"d",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"&&",
"(",
"filter",
"==",
"nil",
"||",
"filter",
"(",
"d",
")",
")",
"{",
"filename",
":=",
"buildutil",
".",
"JoinPath",
"(",
"bctx",
",",
"path",
",",
"d",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"src",
",",
"err",
":=",
"buildutil",
".",
"ParseFile",
"(",
"fset",
",",
"bctx",
",",
"nil",
",",
"buildutil",
".",
"JoinPath",
"(",
"bctx",
",",
"path",
",",
"d",
".",
"Name",
"(",
")",
")",
",",
"filename",
",",
"mode",
")",
";",
"err",
"==",
"nil",
"{",
"name",
":=",
"src",
".",
"Name",
".",
"Name",
"\n",
"pkg",
",",
"found",
":=",
"pkgs",
"[",
"name",
"]",
"\n",
"if",
"!",
"found",
"{",
"pkg",
"=",
"&",
"ast",
".",
"Package",
"{",
"Name",
":",
"name",
",",
"Files",
":",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"File",
"{",
"}",
",",
"}",
"\n",
"pkgs",
"[",
"name",
"]",
"=",
"pkg",
"\n",
"}",
"\n",
"pkg",
".",
"Files",
"[",
"filename",
"]",
"=",
"src",
"\n",
"}",
"else",
"if",
"first",
"==",
"nil",
"{",
"first",
"=",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // parseDir mirrors parser.ParseDir, but uses the passed in build context's VFS. In other words,
// buildutil.parseFile : parser.ParseFile :: parseDir : parser.ParseDir | [
"parseDir",
"mirrors",
"parser",
".",
"ParseDir",
"but",
"uses",
"the",
"passed",
"in",
"build",
"context",
"s",
"VFS",
".",
"In",
"other",
"words",
"buildutil",
".",
"parseFile",
":",
"parser",
".",
"ParseFile",
"::",
"parseDir",
":",
"parser",
".",
"ParseDir"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L565-L593 |
sourcegraph/go-langserver | langserver/config.go | Apply | func (c Config) Apply(o *InitializationOptions) Config {
if o == nil {
return c
}
if o.FuncSnippetEnabled != nil {
c.FuncSnippetEnabled = *o.FuncSnippetEnabled
}
if o.GocodeCompletionEnabled != nil {
c.GocodeCompletionEnabled = *o.GocodeCompletionEnabled
}
if o.FormatTool != nil {
c.FormatTool = *o.FormatTool
}
if o.LintTool != nil {
c.LintTool = *o.LintTool
}
if o.GoimportsLocalPrefix != nil {
c.GoimportsLocalPrefix = *o.GoimportsLocalPrefix
}
if o.MaxParallelism != nil {
c.MaxParallelism = *o.MaxParallelism
}
if o.UseBinaryPkgCache != nil {
c.UseBinaryPkgCache = *o.UseBinaryPkgCache
}
if o.DiagnosticsEnabled != nil {
c.DiagnosticsEnabled = *o.DiagnosticsEnabled
}
return c
} | go | func (c Config) Apply(o *InitializationOptions) Config {
if o == nil {
return c
}
if o.FuncSnippetEnabled != nil {
c.FuncSnippetEnabled = *o.FuncSnippetEnabled
}
if o.GocodeCompletionEnabled != nil {
c.GocodeCompletionEnabled = *o.GocodeCompletionEnabled
}
if o.FormatTool != nil {
c.FormatTool = *o.FormatTool
}
if o.LintTool != nil {
c.LintTool = *o.LintTool
}
if o.GoimportsLocalPrefix != nil {
c.GoimportsLocalPrefix = *o.GoimportsLocalPrefix
}
if o.MaxParallelism != nil {
c.MaxParallelism = *o.MaxParallelism
}
if o.UseBinaryPkgCache != nil {
c.UseBinaryPkgCache = *o.UseBinaryPkgCache
}
if o.DiagnosticsEnabled != nil {
c.DiagnosticsEnabled = *o.DiagnosticsEnabled
}
return c
} | [
"func",
"(",
"c",
"Config",
")",
"Apply",
"(",
"o",
"*",
"InitializationOptions",
")",
"Config",
"{",
"if",
"o",
"==",
"nil",
"{",
"return",
"c",
"\n",
"}",
"\n",
"if",
"o",
".",
"FuncSnippetEnabled",
"!=",
"nil",
"{",
"c",
".",
"FuncSnippetEnabled",
"=",
"*",
"o",
".",
"FuncSnippetEnabled",
"\n",
"}",
"\n",
"if",
"o",
".",
"GocodeCompletionEnabled",
"!=",
"nil",
"{",
"c",
".",
"GocodeCompletionEnabled",
"=",
"*",
"o",
".",
"GocodeCompletionEnabled",
"\n",
"}",
"\n",
"if",
"o",
".",
"FormatTool",
"!=",
"nil",
"{",
"c",
".",
"FormatTool",
"=",
"*",
"o",
".",
"FormatTool",
"\n",
"}",
"\n",
"if",
"o",
".",
"LintTool",
"!=",
"nil",
"{",
"c",
".",
"LintTool",
"=",
"*",
"o",
".",
"LintTool",
"\n",
"}",
"\n",
"if",
"o",
".",
"GoimportsLocalPrefix",
"!=",
"nil",
"{",
"c",
".",
"GoimportsLocalPrefix",
"=",
"*",
"o",
".",
"GoimportsLocalPrefix",
"\n",
"}",
"\n",
"if",
"o",
".",
"MaxParallelism",
"!=",
"nil",
"{",
"c",
".",
"MaxParallelism",
"=",
"*",
"o",
".",
"MaxParallelism",
"\n",
"}",
"\n",
"if",
"o",
".",
"UseBinaryPkgCache",
"!=",
"nil",
"{",
"c",
".",
"UseBinaryPkgCache",
"=",
"*",
"o",
".",
"UseBinaryPkgCache",
"\n",
"}",
"\n",
"if",
"o",
".",
"DiagnosticsEnabled",
"!=",
"nil",
"{",
"c",
".",
"DiagnosticsEnabled",
"=",
"*",
"o",
".",
"DiagnosticsEnabled",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // Apply sets the corresponding field in c for each non-nil field in o. | [
"Apply",
"sets",
"the",
"corresponding",
"field",
"in",
"c",
"for",
"each",
"non",
"-",
"nil",
"field",
"in",
"o",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/config.go#L70-L99 |
sourcegraph/go-langserver | langserver/config.go | NewDefaultConfig | func NewDefaultConfig() Config {
// Default max parallelism to half the CPU cores, but at least always one.
maxparallelism := runtime.NumCPU() / 2
if maxparallelism <= 0 {
maxparallelism = 1
}
return Config{
FuncSnippetEnabled: true,
GocodeCompletionEnabled: false,
FormatTool: formatToolGoimports,
LintTool: lintToolNone,
DiagnosticsEnabled: false,
MaxParallelism: maxparallelism,
UseBinaryPkgCache: true,
}
} | go | func NewDefaultConfig() Config {
// Default max parallelism to half the CPU cores, but at least always one.
maxparallelism := runtime.NumCPU() / 2
if maxparallelism <= 0 {
maxparallelism = 1
}
return Config{
FuncSnippetEnabled: true,
GocodeCompletionEnabled: false,
FormatTool: formatToolGoimports,
LintTool: lintToolNone,
DiagnosticsEnabled: false,
MaxParallelism: maxparallelism,
UseBinaryPkgCache: true,
}
} | [
"func",
"NewDefaultConfig",
"(",
")",
"Config",
"{",
"// Default max parallelism to half the CPU cores, but at least always one.",
"maxparallelism",
":=",
"runtime",
".",
"NumCPU",
"(",
")",
"/",
"2",
"\n",
"if",
"maxparallelism",
"<=",
"0",
"{",
"maxparallelism",
"=",
"1",
"\n",
"}",
"\n\n",
"return",
"Config",
"{",
"FuncSnippetEnabled",
":",
"true",
",",
"GocodeCompletionEnabled",
":",
"false",
",",
"FormatTool",
":",
"formatToolGoimports",
",",
"LintTool",
":",
"lintToolNone",
",",
"DiagnosticsEnabled",
":",
"false",
",",
"MaxParallelism",
":",
"maxparallelism",
",",
"UseBinaryPkgCache",
":",
"true",
",",
"}",
"\n",
"}"
] | // NewDefaultConfig returns the default config. See the field comments for the
// defaults. | [
"NewDefaultConfig",
"returns",
"the",
"default",
"config",
".",
"See",
"the",
"field",
"comments",
"for",
"the",
"defaults",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/config.go#L103-L119 |
sourcegraph/go-langserver | gosrc/import_path.go | guessImportPath | func guessImportPath(importPath string) (*Directory, error) {
if !strings.Contains(importPath, ".git") {
// Assume GitHub-like where two path elements is the project
// root.
parts := strings.SplitN(importPath, "/", 4)
if len(parts) < 3 {
return nil, fmt.Errorf("invalid GitHub-like import path: %q", importPath)
}
repo := parts[0] + "/" + parts[1] + "/" + parts[2]
return &Directory{
ImportPath: importPath,
ProjectRoot: repo,
CloneURL: "http://" + repo,
VCS: "git",
}, nil
}
// TODO(slimsag): We assume that .git only shows up
// once in the import path. Not always true, but generally
// should be in 99% of cases.
split := strings.Split(importPath, ".git")
if len(split) != 2 {
return nil, fmt.Errorf("expected one .git in %q", importPath)
}
return &Directory{
ImportPath: importPath,
ProjectRoot: split[0] + ".git",
CloneURL: "http://" + split[0] + ".git",
VCS: "git",
}, nil
} | go | func guessImportPath(importPath string) (*Directory, error) {
if !strings.Contains(importPath, ".git") {
// Assume GitHub-like where two path elements is the project
// root.
parts := strings.SplitN(importPath, "/", 4)
if len(parts) < 3 {
return nil, fmt.Errorf("invalid GitHub-like import path: %q", importPath)
}
repo := parts[0] + "/" + parts[1] + "/" + parts[2]
return &Directory{
ImportPath: importPath,
ProjectRoot: repo,
CloneURL: "http://" + repo,
VCS: "git",
}, nil
}
// TODO(slimsag): We assume that .git only shows up
// once in the import path. Not always true, but generally
// should be in 99% of cases.
split := strings.Split(importPath, ".git")
if len(split) != 2 {
return nil, fmt.Errorf("expected one .git in %q", importPath)
}
return &Directory{
ImportPath: importPath,
ProjectRoot: split[0] + ".git",
CloneURL: "http://" + split[0] + ".git",
VCS: "git",
}, nil
} | [
"func",
"guessImportPath",
"(",
"importPath",
"string",
")",
"(",
"*",
"Directory",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"Contains",
"(",
"importPath",
",",
"\"",
"\"",
")",
"{",
"// Assume GitHub-like where two path elements is the project",
"// root.",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"importPath",
",",
"\"",
"\"",
",",
"4",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"3",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"importPath",
")",
"\n",
"}",
"\n",
"repo",
":=",
"parts",
"[",
"0",
"]",
"+",
"\"",
"\"",
"+",
"parts",
"[",
"1",
"]",
"+",
"\"",
"\"",
"+",
"parts",
"[",
"2",
"]",
"\n",
"return",
"&",
"Directory",
"{",
"ImportPath",
":",
"importPath",
",",
"ProjectRoot",
":",
"repo",
",",
"CloneURL",
":",
"\"",
"\"",
"+",
"repo",
",",
"VCS",
":",
"\"",
"\"",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// TODO(slimsag): We assume that .git only shows up",
"// once in the import path. Not always true, but generally",
"// should be in 99% of cases.",
"split",
":=",
"strings",
".",
"Split",
"(",
"importPath",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"split",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"importPath",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Directory",
"{",
"ImportPath",
":",
"importPath",
",",
"ProjectRoot",
":",
"split",
"[",
"0",
"]",
"+",
"\"",
"\"",
",",
"CloneURL",
":",
"\"",
"\"",
"+",
"split",
"[",
"0",
"]",
"+",
"\"",
"\"",
",",
"VCS",
":",
"\"",
"\"",
",",
"}",
",",
"nil",
"\n",
"}"
] | // guessImportPath is used by noGoGetDomains since we can't do the usual
// go get resolution. | [
"guessImportPath",
"is",
"used",
"by",
"noGoGetDomains",
"since",
"we",
"can",
"t",
"do",
"the",
"usual",
"go",
"get",
"resolution",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gosrc/import_path.go#L152-L183 |
sourcegraph/go-langserver | langserver/handler.go | NewHandler | func NewHandler(defaultCfg Config) jsonrpc2.Handler {
return lspHandler{jsonrpc2.HandlerWithError((&LangHandler{
DefaultConfig: defaultCfg,
HandlerShared: &HandlerShared{},
}).handle)}
} | go | func NewHandler(defaultCfg Config) jsonrpc2.Handler {
return lspHandler{jsonrpc2.HandlerWithError((&LangHandler{
DefaultConfig: defaultCfg,
HandlerShared: &HandlerShared{},
}).handle)}
} | [
"func",
"NewHandler",
"(",
"defaultCfg",
"Config",
")",
"jsonrpc2",
".",
"Handler",
"{",
"return",
"lspHandler",
"{",
"jsonrpc2",
".",
"HandlerWithError",
"(",
"(",
"&",
"LangHandler",
"{",
"DefaultConfig",
":",
"defaultCfg",
",",
"HandlerShared",
":",
"&",
"HandlerShared",
"{",
"}",
",",
"}",
")",
".",
"handle",
")",
"}",
"\n",
"}"
] | // NewHandler creates a Go language server handler. | [
"NewHandler",
"creates",
"a",
"Go",
"language",
"server",
"handler",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L26-L31 |
sourcegraph/go-langserver | langserver/handler.go | Handle | func (h lspHandler) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) {
if isFileSystemRequest(req.Method) {
h.Handler.Handle(ctx, conn, req)
return
}
go h.Handler.Handle(ctx, conn, req)
} | go | func (h lspHandler) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) {
if isFileSystemRequest(req.Method) {
h.Handler.Handle(ctx, conn, req)
return
}
go h.Handler.Handle(ctx, conn, req)
} | [
"func",
"(",
"h",
"lspHandler",
")",
"Handle",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"*",
"jsonrpc2",
".",
"Conn",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
")",
"{",
"if",
"isFileSystemRequest",
"(",
"req",
".",
"Method",
")",
"{",
"h",
".",
"Handler",
".",
"Handle",
"(",
"ctx",
",",
"conn",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n",
"go",
"h",
".",
"Handler",
".",
"Handle",
"(",
"ctx",
",",
"conn",
",",
"req",
")",
"\n",
"}"
] | // Handle implements jsonrpc2.Handler | [
"Handle",
"implements",
"jsonrpc2",
".",
"Handler"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L49-L55 |
sourcegraph/go-langserver | langserver/handler.go | reset | func (h *LangHandler) reset(init *InitializeParams) error {
for _, k := range init.Capabilities.TextDocument.Completion.CompletionItemKind.ValueSet {
if k == lsp.CIKConstant {
CIKConstantSupported = lsp.CIKConstant
break
}
}
if util.IsURI(lsp.DocumentURI(init.InitializeParams.RootPath)) {
log.Printf("Passing an initialize rootPath URI (%q) is deprecated. Use rootUri instead.", init.InitializeParams.RootPath)
}
h.mu.Lock()
defer h.mu.Unlock()
if err := h.HandlerCommon.Reset(init.Root()); err != nil {
return err
}
if !h.HandlerShared.Shared {
// Only reset the shared data if this lang server is running
// by itself.
if err := h.HandlerShared.Reset(!init.NoOSFileSystemAccess); err != nil {
return err
}
}
config := h.DefaultConfig.Apply(init.InitializationOptions)
h.config = &config
h.init = init
h.cancel = &cancel{}
h.resetCaches(false)
return nil
} | go | func (h *LangHandler) reset(init *InitializeParams) error {
for _, k := range init.Capabilities.TextDocument.Completion.CompletionItemKind.ValueSet {
if k == lsp.CIKConstant {
CIKConstantSupported = lsp.CIKConstant
break
}
}
if util.IsURI(lsp.DocumentURI(init.InitializeParams.RootPath)) {
log.Printf("Passing an initialize rootPath URI (%q) is deprecated. Use rootUri instead.", init.InitializeParams.RootPath)
}
h.mu.Lock()
defer h.mu.Unlock()
if err := h.HandlerCommon.Reset(init.Root()); err != nil {
return err
}
if !h.HandlerShared.Shared {
// Only reset the shared data if this lang server is running
// by itself.
if err := h.HandlerShared.Reset(!init.NoOSFileSystemAccess); err != nil {
return err
}
}
config := h.DefaultConfig.Apply(init.InitializationOptions)
h.config = &config
h.init = init
h.cancel = &cancel{}
h.resetCaches(false)
return nil
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"reset",
"(",
"init",
"*",
"InitializeParams",
")",
"error",
"{",
"for",
"_",
",",
"k",
":=",
"range",
"init",
".",
"Capabilities",
".",
"TextDocument",
".",
"Completion",
".",
"CompletionItemKind",
".",
"ValueSet",
"{",
"if",
"k",
"==",
"lsp",
".",
"CIKConstant",
"{",
"CIKConstantSupported",
"=",
"lsp",
".",
"CIKConstant",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"util",
".",
"IsURI",
"(",
"lsp",
".",
"DocumentURI",
"(",
"init",
".",
"InitializeParams",
".",
"RootPath",
")",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"init",
".",
"InitializeParams",
".",
"RootPath",
")",
"\n",
"}",
"\n\n",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"HandlerCommon",
".",
"Reset",
"(",
"init",
".",
"Root",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"h",
".",
"HandlerShared",
".",
"Shared",
"{",
"// Only reset the shared data if this lang server is running",
"// by itself.",
"if",
"err",
":=",
"h",
".",
"HandlerShared",
".",
"Reset",
"(",
"!",
"init",
".",
"NoOSFileSystemAccess",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"config",
":=",
"h",
".",
"DefaultConfig",
".",
"Apply",
"(",
"init",
".",
"InitializationOptions",
")",
"\n",
"h",
".",
"config",
"=",
"&",
"config",
"\n",
"h",
".",
"init",
"=",
"init",
"\n",
"h",
".",
"cancel",
"=",
"&",
"cancel",
"{",
"}",
"\n",
"h",
".",
"resetCaches",
"(",
"false",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // reset clears all internal state in h. | [
"reset",
"clears",
"all",
"internal",
"state",
"in",
"h",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L91-L121 |
sourcegraph/go-langserver | langserver/handler.go | handle | func (h *LangHandler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
return h.Handle(ctx, conn, req)
} | go | func (h *LangHandler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
return h.Handle(ctx, conn, req)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"handle",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"*",
"jsonrpc2",
".",
"Conn",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"h",
".",
"Handle",
"(",
"ctx",
",",
"conn",
",",
"req",
")",
"\n",
"}"
] | // handle implements jsonrpc2.Handler. | [
"handle",
"implements",
"jsonrpc2",
".",
"Handler",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L153-L155 |
sourcegraph/go-langserver | langserver/handler.go | Handle | func (h *LangHandler) Handle(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request) (result interface{}, err error) {
// Prevent any uncaught panics from taking the entire server down.
defer func() {
if perr := util.Panicf(recover(), "%v", req.Method); perr != nil {
err = perr
}
}()
var cancelManager *cancel
h.mu.Lock()
cancelManager = h.cancel
if req.Method != "initialize" && h.init == nil {
h.mu.Unlock()
return nil, errors.New("server must be initialized")
}
h.mu.Unlock()
if err := h.CheckReady(); err != nil {
if req.Method == "exit" {
err = nil
}
return nil, err
}
if conn, ok := conn.(*jsonrpc2.Conn); ok && conn != nil {
h.InitTracer(conn)
}
span, ctx, err := h.SpanForRequest(ctx, "lang", req, opentracing.Tags{"mode": "go"})
if err != nil {
return nil, err
}
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.LogEvent(fmt.Sprintf("error: %v", err))
}
span.Finish()
}()
// Notifications don't have an ID, so they can't be cancelled
if cancelManager != nil && !req.Notif {
var cancel func()
ctx, cancel = cancelManager.WithCancel(ctx, req.ID)
defer cancel()
}
switch req.Method {
case "initialize":
if h.init != nil {
return nil, errors.New("language server is already initialized")
}
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params InitializeParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
// HACK: RootPath is not a URI, but historically we treated it
// as such. Convert it to a file URI
if params.RootPath != "" && !util.IsURI(lsp.DocumentURI(params.RootPath)) {
params.RootPath = string(util.PathToURI(params.RootPath))
}
if err := h.reset(¶ms); err != nil {
return nil, err
}
// PERF: Kick off a workspace/symbol in the background to warm up the server
if yes, _ := strconv.ParseBool(envWarmupOnInitialize); yes {
go func() {
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(30*time.Second))
defer cancel()
_, _ = h.handleWorkspaceSymbol(ctx, conn, req, lspext.WorkspaceSymbolParams{
Query: "",
Limit: 100,
})
}()
}
// set the configured linter
if h.config.DiagnosticsEnabled && h.config.LintTool != lintToolNone {
switch h.config.LintTool {
case lintToolGolint:
h.linter = golint{}
}
if h.linter == nil {
log.Printf("warning: lint tool %s not supported", h.config.LintTool)
} else if err := h.linter.IsInstalled(ctx, h.BuildContext(ctx)); err != nil {
h.linter = nil
log.Printf("warning: lint tool (%s) initialize err: %s", h.config.LintTool, err)
} else {
// kick off a lint of the entire workspace
go func() {
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(30*time.Second))
defer cancel()
err := h.lintWorkspace(ctx, h.BuildContext(ctx), conn)
if err != nil {
log.Printf("warning: failed to lint workspace: %s", err)
}
}()
}
}
kind := lsp.TDSKIncremental
var completionOp *lsp.CompletionOptions
if h.config.GocodeCompletionEnabled {
completionOp = &lsp.CompletionOptions{TriggerCharacters: []string{"."}}
}
return lsp.InitializeResult{
Capabilities: lsp.ServerCapabilities{
TextDocumentSync: &lsp.TextDocumentSyncOptionsOrKind{
Kind: &kind,
},
CompletionProvider: completionOp,
DefinitionProvider: true,
TypeDefinitionProvider: true,
DocumentFormattingProvider: true,
DocumentSymbolProvider: true,
HoverProvider: true,
ReferencesProvider: true,
RenameProvider: true,
WorkspaceSymbolProvider: true,
ImplementationProvider: true,
XWorkspaceReferencesProvider: true,
XDefinitionProvider: true,
XWorkspaceSymbolByProperties: true,
SignatureHelpProvider: &lsp.SignatureHelpOptions{TriggerCharacters: []string{"(", ","}},
},
}, nil
case "initialized":
// A notification that the client is ready to receive requests. Ignore
return nil, nil
case "shutdown":
h.ShutDown()
return nil, nil
case "exit":
if c, ok := conn.(*jsonrpc2.Conn); ok {
c.Close()
}
return nil, nil
case "$/cancelRequest":
// notification, don't send back results/errors
if req.Params == nil {
return nil, nil
}
var params lsp.CancelParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, nil
}
if cancelManager == nil {
return nil, nil
}
cancelManager.Cancel(jsonrpc2.ID{
Num: params.ID.Num,
Str: params.ID.Str,
IsString: params.ID.IsString,
})
return nil, nil
case "textDocument/hover":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleHover(ctx, conn, req, params)
case "textDocument/definition":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleDefinition(ctx, conn, req, params)
case "textDocument/typeDefinition":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTypeDefinition(ctx, conn, req, params)
case "textDocument/xdefinition":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleXDefinition(ctx, conn, req, params)
case "textDocument/completion":
if !h.config.GocodeCompletionEnabled {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound,
Message: fmt.Sprintf("completion is disabled. Enable with flag `-gocodecompletion`")}
}
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.CompletionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentCompletion(ctx, conn, req, params)
case "textDocument/references":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.ReferenceParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentReferences(ctx, conn, req, params)
case "textDocument/implementation":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentImplementation(ctx, conn, req, params)
case "textDocument/documentSymbol":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DocumentSymbolParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentSymbol(ctx, conn, req, params)
case "textDocument/signatureHelp":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentSignatureHelp(ctx, conn, req, params)
case "textDocument/formatting":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DocumentFormattingParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentFormatting(ctx, conn, req, params)
case "workspace/symbol":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lspext.WorkspaceSymbolParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleWorkspaceSymbol(ctx, conn, req, params)
case "workspace/xreferences":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lspext.WorkspaceReferencesParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleWorkspaceReferences(ctx, conn, req, params)
case "textDocument/rename":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.RenameParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleRename(ctx, conn, req, params)
default:
if isFileSystemRequest(req.Method) {
uri, fileChanged, err := h.handleFileSystemRequest(ctx, req)
if fileChanged {
// a file changed, so we must re-typecheck and re-enumerate symbols
h.resetCaches(true)
}
if uri != "" {
// a user is viewing this path, hint to add it to the cache
// (unless we're primarily using binary package cache .a
// files).
if !h.config.UseBinaryPkgCache || (h.config.DiagnosticsEnabled && req.Method == "textDocument/didSave") {
go h.typecheck(ctx, conn, uri, lsp.Position{})
}
if h.config.DiagnosticsEnabled && h.linter != nil && req.Method == "textDocument/didSave" {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := h.lintPackage(ctx, h.BuildContext(ctx), conn, uri)
if err != nil {
log.Printf("warning: failed to lint package: %s", err)
}
}()
}
}
return nil, err
}
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound, Message: fmt.Sprintf("method not supported: %s", req.Method)}
}
} | go | func (h *LangHandler) Handle(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request) (result interface{}, err error) {
// Prevent any uncaught panics from taking the entire server down.
defer func() {
if perr := util.Panicf(recover(), "%v", req.Method); perr != nil {
err = perr
}
}()
var cancelManager *cancel
h.mu.Lock()
cancelManager = h.cancel
if req.Method != "initialize" && h.init == nil {
h.mu.Unlock()
return nil, errors.New("server must be initialized")
}
h.mu.Unlock()
if err := h.CheckReady(); err != nil {
if req.Method == "exit" {
err = nil
}
return nil, err
}
if conn, ok := conn.(*jsonrpc2.Conn); ok && conn != nil {
h.InitTracer(conn)
}
span, ctx, err := h.SpanForRequest(ctx, "lang", req, opentracing.Tags{"mode": "go"})
if err != nil {
return nil, err
}
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.LogEvent(fmt.Sprintf("error: %v", err))
}
span.Finish()
}()
// Notifications don't have an ID, so they can't be cancelled
if cancelManager != nil && !req.Notif {
var cancel func()
ctx, cancel = cancelManager.WithCancel(ctx, req.ID)
defer cancel()
}
switch req.Method {
case "initialize":
if h.init != nil {
return nil, errors.New("language server is already initialized")
}
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params InitializeParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
// HACK: RootPath is not a URI, but historically we treated it
// as such. Convert it to a file URI
if params.RootPath != "" && !util.IsURI(lsp.DocumentURI(params.RootPath)) {
params.RootPath = string(util.PathToURI(params.RootPath))
}
if err := h.reset(¶ms); err != nil {
return nil, err
}
// PERF: Kick off a workspace/symbol in the background to warm up the server
if yes, _ := strconv.ParseBool(envWarmupOnInitialize); yes {
go func() {
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(30*time.Second))
defer cancel()
_, _ = h.handleWorkspaceSymbol(ctx, conn, req, lspext.WorkspaceSymbolParams{
Query: "",
Limit: 100,
})
}()
}
// set the configured linter
if h.config.DiagnosticsEnabled && h.config.LintTool != lintToolNone {
switch h.config.LintTool {
case lintToolGolint:
h.linter = golint{}
}
if h.linter == nil {
log.Printf("warning: lint tool %s not supported", h.config.LintTool)
} else if err := h.linter.IsInstalled(ctx, h.BuildContext(ctx)); err != nil {
h.linter = nil
log.Printf("warning: lint tool (%s) initialize err: %s", h.config.LintTool, err)
} else {
// kick off a lint of the entire workspace
go func() {
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(30*time.Second))
defer cancel()
err := h.lintWorkspace(ctx, h.BuildContext(ctx), conn)
if err != nil {
log.Printf("warning: failed to lint workspace: %s", err)
}
}()
}
}
kind := lsp.TDSKIncremental
var completionOp *lsp.CompletionOptions
if h.config.GocodeCompletionEnabled {
completionOp = &lsp.CompletionOptions{TriggerCharacters: []string{"."}}
}
return lsp.InitializeResult{
Capabilities: lsp.ServerCapabilities{
TextDocumentSync: &lsp.TextDocumentSyncOptionsOrKind{
Kind: &kind,
},
CompletionProvider: completionOp,
DefinitionProvider: true,
TypeDefinitionProvider: true,
DocumentFormattingProvider: true,
DocumentSymbolProvider: true,
HoverProvider: true,
ReferencesProvider: true,
RenameProvider: true,
WorkspaceSymbolProvider: true,
ImplementationProvider: true,
XWorkspaceReferencesProvider: true,
XDefinitionProvider: true,
XWorkspaceSymbolByProperties: true,
SignatureHelpProvider: &lsp.SignatureHelpOptions{TriggerCharacters: []string{"(", ","}},
},
}, nil
case "initialized":
// A notification that the client is ready to receive requests. Ignore
return nil, nil
case "shutdown":
h.ShutDown()
return nil, nil
case "exit":
if c, ok := conn.(*jsonrpc2.Conn); ok {
c.Close()
}
return nil, nil
case "$/cancelRequest":
// notification, don't send back results/errors
if req.Params == nil {
return nil, nil
}
var params lsp.CancelParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, nil
}
if cancelManager == nil {
return nil, nil
}
cancelManager.Cancel(jsonrpc2.ID{
Num: params.ID.Num,
Str: params.ID.Str,
IsString: params.ID.IsString,
})
return nil, nil
case "textDocument/hover":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleHover(ctx, conn, req, params)
case "textDocument/definition":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleDefinition(ctx, conn, req, params)
case "textDocument/typeDefinition":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTypeDefinition(ctx, conn, req, params)
case "textDocument/xdefinition":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleXDefinition(ctx, conn, req, params)
case "textDocument/completion":
if !h.config.GocodeCompletionEnabled {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound,
Message: fmt.Sprintf("completion is disabled. Enable with flag `-gocodecompletion`")}
}
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.CompletionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentCompletion(ctx, conn, req, params)
case "textDocument/references":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.ReferenceParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentReferences(ctx, conn, req, params)
case "textDocument/implementation":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentImplementation(ctx, conn, req, params)
case "textDocument/documentSymbol":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DocumentSymbolParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentSymbol(ctx, conn, req, params)
case "textDocument/signatureHelp":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.TextDocumentPositionParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentSignatureHelp(ctx, conn, req, params)
case "textDocument/formatting":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DocumentFormattingParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleTextDocumentFormatting(ctx, conn, req, params)
case "workspace/symbol":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lspext.WorkspaceSymbolParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleWorkspaceSymbol(ctx, conn, req, params)
case "workspace/xreferences":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lspext.WorkspaceReferencesParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleWorkspaceReferences(ctx, conn, req, params)
case "textDocument/rename":
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.RenameParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
return h.handleRename(ctx, conn, req, params)
default:
if isFileSystemRequest(req.Method) {
uri, fileChanged, err := h.handleFileSystemRequest(ctx, req)
if fileChanged {
// a file changed, so we must re-typecheck and re-enumerate symbols
h.resetCaches(true)
}
if uri != "" {
// a user is viewing this path, hint to add it to the cache
// (unless we're primarily using binary package cache .a
// files).
if !h.config.UseBinaryPkgCache || (h.config.DiagnosticsEnabled && req.Method == "textDocument/didSave") {
go h.typecheck(ctx, conn, uri, lsp.Position{})
}
if h.config.DiagnosticsEnabled && h.linter != nil && req.Method == "textDocument/didSave" {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := h.lintPackage(ctx, h.BuildContext(ctx), conn, uri)
if err != nil {
log.Printf("warning: failed to lint package: %s", err)
}
}()
}
}
return nil, err
}
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound, Message: fmt.Sprintf("method not supported: %s", req.Method)}
}
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"Handle",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"// Prevent any uncaught panics from taking the entire server down.",
"defer",
"func",
"(",
")",
"{",
"if",
"perr",
":=",
"util",
".",
"Panicf",
"(",
"recover",
"(",
")",
",",
"\"",
"\"",
",",
"req",
".",
"Method",
")",
";",
"perr",
"!=",
"nil",
"{",
"err",
"=",
"perr",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"cancelManager",
"*",
"cancel",
"\n",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"cancelManager",
"=",
"h",
".",
"cancel",
"\n",
"if",
"req",
".",
"Method",
"!=",
"\"",
"\"",
"&&",
"h",
".",
"init",
"==",
"nil",
"{",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"CheckReady",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"req",
".",
"Method",
"==",
"\"",
"\"",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"conn",
",",
"ok",
":=",
"conn",
".",
"(",
"*",
"jsonrpc2",
".",
"Conn",
")",
";",
"ok",
"&&",
"conn",
"!=",
"nil",
"{",
"h",
".",
"InitTracer",
"(",
"conn",
")",
"\n",
"}",
"\n",
"span",
",",
"ctx",
",",
"err",
":=",
"h",
".",
"SpanForRequest",
"(",
"ctx",
",",
"\"",
"\"",
",",
"req",
",",
"opentracing",
".",
"Tags",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"ext",
".",
"Error",
".",
"Set",
"(",
"span",
",",
"true",
")",
"\n",
"span",
".",
"LogEvent",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"span",
".",
"Finish",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// Notifications don't have an ID, so they can't be cancelled",
"if",
"cancelManager",
"!=",
"nil",
"&&",
"!",
"req",
".",
"Notif",
"{",
"var",
"cancel",
"func",
"(",
")",
"\n",
"ctx",
",",
"cancel",
"=",
"cancelManager",
".",
"WithCancel",
"(",
"ctx",
",",
"req",
".",
"ID",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"}",
"\n\n",
"switch",
"req",
".",
"Method",
"{",
"case",
"\"",
"\"",
":",
"if",
"h",
".",
"init",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"InitializeParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// HACK: RootPath is not a URI, but historically we treated it",
"// as such. Convert it to a file URI",
"if",
"params",
".",
"RootPath",
"!=",
"\"",
"\"",
"&&",
"!",
"util",
".",
"IsURI",
"(",
"lsp",
".",
"DocumentURI",
"(",
"params",
".",
"RootPath",
")",
")",
"{",
"params",
".",
"RootPath",
"=",
"string",
"(",
"util",
".",
"PathToURI",
"(",
"params",
".",
"RootPath",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"h",
".",
"reset",
"(",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// PERF: Kick off a workspace/symbol in the background to warm up the server",
"if",
"yes",
",",
"_",
":=",
"strconv",
".",
"ParseBool",
"(",
"envWarmupOnInitialize",
")",
";",
"yes",
"{",
"go",
"func",
"(",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithDeadline",
"(",
"ctx",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"30",
"*",
"time",
".",
"Second",
")",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"handleWorkspaceSymbol",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"lspext",
".",
"WorkspaceSymbolParams",
"{",
"Query",
":",
"\"",
"\"",
",",
"Limit",
":",
"100",
",",
"}",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"// set the configured linter",
"if",
"h",
".",
"config",
".",
"DiagnosticsEnabled",
"&&",
"h",
".",
"config",
".",
"LintTool",
"!=",
"lintToolNone",
"{",
"switch",
"h",
".",
"config",
".",
"LintTool",
"{",
"case",
"lintToolGolint",
":",
"h",
".",
"linter",
"=",
"golint",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"h",
".",
"linter",
"==",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"h",
".",
"config",
".",
"LintTool",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"h",
".",
"linter",
".",
"IsInstalled",
"(",
"ctx",
",",
"h",
".",
"BuildContext",
"(",
"ctx",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"linter",
"=",
"nil",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"h",
".",
"config",
".",
"LintTool",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"// kick off a lint of the entire workspace",
"go",
"func",
"(",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithDeadline",
"(",
"ctx",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"30",
"*",
"time",
".",
"Second",
")",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"err",
":=",
"h",
".",
"lintWorkspace",
"(",
"ctx",
",",
"h",
".",
"BuildContext",
"(",
"ctx",
")",
",",
"conn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"kind",
":=",
"lsp",
".",
"TDSKIncremental",
"\n",
"var",
"completionOp",
"*",
"lsp",
".",
"CompletionOptions",
"\n",
"if",
"h",
".",
"config",
".",
"GocodeCompletionEnabled",
"{",
"completionOp",
"=",
"&",
"lsp",
".",
"CompletionOptions",
"{",
"TriggerCharacters",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"}",
"\n",
"}",
"\n",
"return",
"lsp",
".",
"InitializeResult",
"{",
"Capabilities",
":",
"lsp",
".",
"ServerCapabilities",
"{",
"TextDocumentSync",
":",
"&",
"lsp",
".",
"TextDocumentSyncOptionsOrKind",
"{",
"Kind",
":",
"&",
"kind",
",",
"}",
",",
"CompletionProvider",
":",
"completionOp",
",",
"DefinitionProvider",
":",
"true",
",",
"TypeDefinitionProvider",
":",
"true",
",",
"DocumentFormattingProvider",
":",
"true",
",",
"DocumentSymbolProvider",
":",
"true",
",",
"HoverProvider",
":",
"true",
",",
"ReferencesProvider",
":",
"true",
",",
"RenameProvider",
":",
"true",
",",
"WorkspaceSymbolProvider",
":",
"true",
",",
"ImplementationProvider",
":",
"true",
",",
"XWorkspaceReferencesProvider",
":",
"true",
",",
"XDefinitionProvider",
":",
"true",
",",
"XWorkspaceSymbolByProperties",
":",
"true",
",",
"SignatureHelpProvider",
":",
"&",
"lsp",
".",
"SignatureHelpOptions",
"{",
"TriggerCharacters",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"}",
",",
"}",
",",
"}",
",",
"nil",
"\n\n",
"case",
"\"",
"\"",
":",
"// A notification that the client is ready to receive requests. Ignore",
"return",
"nil",
",",
"nil",
"\n\n",
"case",
"\"",
"\"",
":",
"h",
".",
"ShutDown",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"c",
",",
"ok",
":=",
"conn",
".",
"(",
"*",
"jsonrpc2",
".",
"Conn",
")",
";",
"ok",
"{",
"c",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n\n",
"case",
"\"",
"\"",
":",
"// notification, don't send back results/errors",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"CancelParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"cancelManager",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"cancelManager",
".",
"Cancel",
"(",
"jsonrpc2",
".",
"ID",
"{",
"Num",
":",
"params",
".",
"ID",
".",
"Num",
",",
"Str",
":",
"params",
".",
"ID",
".",
"Str",
",",
"IsString",
":",
"params",
".",
"ID",
".",
"IsString",
",",
"}",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"TextDocumentPositionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleHover",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"TextDocumentPositionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleDefinition",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"TextDocumentPositionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTypeDefinition",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"TextDocumentPositionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleXDefinition",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"!",
"h",
".",
"config",
".",
"GocodeCompletionEnabled",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeMethodNotFound",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
"}",
"\n",
"}",
"\n",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"CompletionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTextDocumentCompletion",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"ReferenceParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTextDocumentReferences",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"TextDocumentPositionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTextDocumentImplementation",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"DocumentSymbolParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTextDocumentSymbol",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"TextDocumentPositionParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTextDocumentSignatureHelp",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"DocumentFormattingParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleTextDocumentFormatting",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lspext",
".",
"WorkspaceSymbolParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleWorkspaceSymbol",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lspext",
".",
"WorkspaceReferencesParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleWorkspaceReferences",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"if",
"req",
".",
"Params",
"==",
"nil",
"{",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeInvalidParams",
"}",
"\n",
"}",
"\n",
"var",
"params",
"lsp",
".",
"RenameParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"h",
".",
"handleRename",
"(",
"ctx",
",",
"conn",
",",
"req",
",",
"params",
")",
"\n",
"default",
":",
"if",
"isFileSystemRequest",
"(",
"req",
".",
"Method",
")",
"{",
"uri",
",",
"fileChanged",
",",
"err",
":=",
"h",
".",
"handleFileSystemRequest",
"(",
"ctx",
",",
"req",
")",
"\n",
"if",
"fileChanged",
"{",
"// a file changed, so we must re-typecheck and re-enumerate symbols",
"h",
".",
"resetCaches",
"(",
"true",
")",
"\n",
"}",
"\n",
"if",
"uri",
"!=",
"\"",
"\"",
"{",
"// a user is viewing this path, hint to add it to the cache",
"// (unless we're primarily using binary package cache .a",
"// files).",
"if",
"!",
"h",
".",
"config",
".",
"UseBinaryPkgCache",
"||",
"(",
"h",
".",
"config",
".",
"DiagnosticsEnabled",
"&&",
"req",
".",
"Method",
"==",
"\"",
"\"",
")",
"{",
"go",
"h",
".",
"typecheck",
"(",
"ctx",
",",
"conn",
",",
"uri",
",",
"lsp",
".",
"Position",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"if",
"h",
".",
"config",
".",
"DiagnosticsEnabled",
"&&",
"h",
".",
"linter",
"!=",
"nil",
"&&",
"req",
".",
"Method",
"==",
"\"",
"\"",
"{",
"go",
"func",
"(",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"30",
"*",
"time",
".",
"Second",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"err",
":=",
"h",
".",
"lintPackage",
"(",
"ctx",
",",
"h",
".",
"BuildContext",
"(",
"ctx",
")",
",",
"conn",
",",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"&",
"jsonrpc2",
".",
"Error",
"{",
"Code",
":",
"jsonrpc2",
".",
"CodeMethodNotFound",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"req",
".",
"Method",
")",
"}",
"\n",
"}",
"\n",
"}"
] | // Handle creates a response for a JSONRPC2 LSP request. Note: LSP has strict
// ordering requirements, so this should not just be wrapped in an
// jsonrpc2.AsyncHandler. Ensure you have the same ordering as used in the
// NewHandler implementation. | [
"Handle",
"creates",
"a",
"response",
"for",
"a",
"JSONRPC2",
"LSP",
"request",
".",
"Note",
":",
"LSP",
"has",
"strict",
"ordering",
"requirements",
"so",
"this",
"should",
"not",
"just",
"be",
"wrapped",
"in",
"an",
"jsonrpc2",
".",
"AsyncHandler",
".",
"Ensure",
"you",
"have",
"the",
"same",
"ordering",
"as",
"used",
"in",
"the",
"NewHandler",
"implementation",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L161-L490 |
sourcegraph/go-langserver | pkg/tools/buildutil.go | ListPkgsUnderDir | func ListPkgsUnderDir(ctxt *build.Context, dir string) []string {
ch := make(chan string)
dir = path.Clean(dir)
var (
wg sync.WaitGroup
dirInGOPATH bool
)
for _, root := range ctxt.SrcDirs() {
root = path.Clean(root)
if util.PathHasPrefix(root, dir) {
// If we are a child of dir, we can just start at the
// root. A concrete example of this happening is when
// root=/goroot/src and dir=/goroot
dir = root
}
if !util.PathHasPrefix(dir, root) {
continue
}
wg.Add(1)
go func() {
allPackages(ctxt, root, dir, ch)
wg.Done()
}()
dirInGOPATH = true
}
if !dirInGOPATH {
root := path.Dir(dir)
wg.Add(1)
go func() {
allPackages(ctxt, root, dir, ch)
wg.Done()
}()
}
go func() {
wg.Wait()
close(ch)
}()
var pkgs []string
for p := range ch {
pkgs = append(pkgs, p)
}
sort.Strings(pkgs)
return pkgs
} | go | func ListPkgsUnderDir(ctxt *build.Context, dir string) []string {
ch := make(chan string)
dir = path.Clean(dir)
var (
wg sync.WaitGroup
dirInGOPATH bool
)
for _, root := range ctxt.SrcDirs() {
root = path.Clean(root)
if util.PathHasPrefix(root, dir) {
// If we are a child of dir, we can just start at the
// root. A concrete example of this happening is when
// root=/goroot/src and dir=/goroot
dir = root
}
if !util.PathHasPrefix(dir, root) {
continue
}
wg.Add(1)
go func() {
allPackages(ctxt, root, dir, ch)
wg.Done()
}()
dirInGOPATH = true
}
if !dirInGOPATH {
root := path.Dir(dir)
wg.Add(1)
go func() {
allPackages(ctxt, root, dir, ch)
wg.Done()
}()
}
go func() {
wg.Wait()
close(ch)
}()
var pkgs []string
for p := range ch {
pkgs = append(pkgs, p)
}
sort.Strings(pkgs)
return pkgs
} | [
"func",
"ListPkgsUnderDir",
"(",
"ctxt",
"*",
"build",
".",
"Context",
",",
"dir",
"string",
")",
"[",
"]",
"string",
"{",
"ch",
":=",
"make",
"(",
"chan",
"string",
")",
"\n",
"dir",
"=",
"path",
".",
"Clean",
"(",
"dir",
")",
"\n\n",
"var",
"(",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"dirInGOPATH",
"bool",
"\n",
")",
"\n\n",
"for",
"_",
",",
"root",
":=",
"range",
"ctxt",
".",
"SrcDirs",
"(",
")",
"{",
"root",
"=",
"path",
".",
"Clean",
"(",
"root",
")",
"\n\n",
"if",
"util",
".",
"PathHasPrefix",
"(",
"root",
",",
"dir",
")",
"{",
"// If we are a child of dir, we can just start at the",
"// root. A concrete example of this happening is when",
"// root=/goroot/src and dir=/goroot",
"dir",
"=",
"root",
"\n",
"}",
"\n\n",
"if",
"!",
"util",
".",
"PathHasPrefix",
"(",
"dir",
",",
"root",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"allPackages",
"(",
"ctxt",
",",
"root",
",",
"dir",
",",
"ch",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"dirInGOPATH",
"=",
"true",
"\n",
"}",
"\n\n",
"if",
"!",
"dirInGOPATH",
"{",
"root",
":=",
"path",
".",
"Dir",
"(",
"dir",
")",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"allPackages",
"(",
"ctxt",
",",
"root",
",",
"dir",
",",
"ch",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"pkgs",
"[",
"]",
"string",
"\n",
"for",
"p",
":=",
"range",
"ch",
"{",
"pkgs",
"=",
"append",
"(",
"pkgs",
",",
"p",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"pkgs",
")",
"\n",
"return",
"pkgs",
"\n",
"}"
] | // ListPkgsUnderDir is buildutil.ExpandPattern(ctxt, []string{dir +
// "/..."}). The implementation is modified from the upstream
// buildutil.ExpandPattern so we can be much faster. buildutil.ExpandPattern
// looks at all directories under GOPATH if there is a `...` pattern. This
// instead only explores the directories under dir. In future
// buildutil.ExpandPattern may be more performant (there are TODOs for it). | [
"ListPkgsUnderDir",
"is",
"buildutil",
".",
"ExpandPattern",
"(",
"ctxt",
"[]",
"string",
"{",
"dir",
"+",
"/",
"...",
"}",
")",
".",
"The",
"implementation",
"is",
"modified",
"from",
"the",
"upstream",
"buildutil",
".",
"ExpandPattern",
"so",
"we",
"can",
"be",
"much",
"faster",
".",
"buildutil",
".",
"ExpandPattern",
"looks",
"at",
"all",
"directories",
"under",
"GOPATH",
"if",
"there",
"is",
"a",
"...",
"pattern",
".",
"This",
"instead",
"only",
"explores",
"the",
"directories",
"under",
"dir",
".",
"In",
"future",
"buildutil",
".",
"ExpandPattern",
"may",
"be",
"more",
"performant",
"(",
"there",
"are",
"TODOs",
"for",
"it",
")",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/pkg/tools/buildutil.go#L20-L71 |
sourcegraph/go-langserver | pkg/tools/buildutil.go | allPackages | func allPackages(ctxt *build.Context, root, start string, ch chan<- string) {
var wg sync.WaitGroup
var walkDir func(dir string)
walkDir = func(dir string) {
// Avoid .foo, _foo, and testdata directory trees.
base := path.Base(dir)
if base == "" || base[0] == '.' || base[0] == '_' || base == "testdata" {
return
}
pkg := util.PathTrimPrefix(dir, root)
// Prune search if we encounter any of these import paths.
switch pkg {
case "builtin":
return
}
if pkg != "" {
ch <- pkg
}
ioLimit <- true
files, _ := buildutil.ReadDir(ctxt, dir)
<-ioLimit
for _, fi := range files {
fi := fi
if fi.IsDir() {
wg.Add(1)
go func() {
walkDir(buildutil.JoinPath(ctxt, dir, fi.Name()))
wg.Done()
}()
}
}
}
walkDir(start)
wg.Wait()
} | go | func allPackages(ctxt *build.Context, root, start string, ch chan<- string) {
var wg sync.WaitGroup
var walkDir func(dir string)
walkDir = func(dir string) {
// Avoid .foo, _foo, and testdata directory trees.
base := path.Base(dir)
if base == "" || base[0] == '.' || base[0] == '_' || base == "testdata" {
return
}
pkg := util.PathTrimPrefix(dir, root)
// Prune search if we encounter any of these import paths.
switch pkg {
case "builtin":
return
}
if pkg != "" {
ch <- pkg
}
ioLimit <- true
files, _ := buildutil.ReadDir(ctxt, dir)
<-ioLimit
for _, fi := range files {
fi := fi
if fi.IsDir() {
wg.Add(1)
go func() {
walkDir(buildutil.JoinPath(ctxt, dir, fi.Name()))
wg.Done()
}()
}
}
}
walkDir(start)
wg.Wait()
} | [
"func",
"allPackages",
"(",
"ctxt",
"*",
"build",
".",
"Context",
",",
"root",
",",
"start",
"string",
",",
"ch",
"chan",
"<-",
"string",
")",
"{",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n\n",
"var",
"walkDir",
"func",
"(",
"dir",
"string",
")",
"\n",
"walkDir",
"=",
"func",
"(",
"dir",
"string",
")",
"{",
"// Avoid .foo, _foo, and testdata directory trees.",
"base",
":=",
"path",
".",
"Base",
"(",
"dir",
")",
"\n",
"if",
"base",
"==",
"\"",
"\"",
"||",
"base",
"[",
"0",
"]",
"==",
"'.'",
"||",
"base",
"[",
"0",
"]",
"==",
"'_'",
"||",
"base",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"pkg",
":=",
"util",
".",
"PathTrimPrefix",
"(",
"dir",
",",
"root",
")",
"\n\n",
"// Prune search if we encounter any of these import paths.",
"switch",
"pkg",
"{",
"case",
"\"",
"\"",
":",
"return",
"\n",
"}",
"\n\n",
"if",
"pkg",
"!=",
"\"",
"\"",
"{",
"ch",
"<-",
"pkg",
"\n",
"}",
"\n\n",
"ioLimit",
"<-",
"true",
"\n",
"files",
",",
"_",
":=",
"buildutil",
".",
"ReadDir",
"(",
"ctxt",
",",
"dir",
")",
"\n",
"<-",
"ioLimit",
"\n",
"for",
"_",
",",
"fi",
":=",
"range",
"files",
"{",
"fi",
":=",
"fi",
"\n",
"if",
"fi",
".",
"IsDir",
"(",
")",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"walkDir",
"(",
"buildutil",
".",
"JoinPath",
"(",
"ctxt",
",",
"dir",
",",
"fi",
".",
"Name",
"(",
")",
")",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"walkDir",
"(",
"start",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // allPackages is from tools/go/buildutil. We don't use the exported method
// since it doesn't allow searching from a directory. We need from a specific
// directory for performance on large GOPATHs. | [
"allPackages",
"is",
"from",
"tools",
"/",
"go",
"/",
"buildutil",
".",
"We",
"don",
"t",
"use",
"the",
"exported",
"method",
"since",
"it",
"doesn",
"t",
"allow",
"searching",
"from",
"a",
"directory",
".",
"We",
"need",
"from",
"a",
"specific",
"directory",
"for",
"performance",
"on",
"large",
"GOPATHs",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/pkg/tools/buildutil.go#L80-L121 |
sourcegraph/go-langserver | buildserver/stdlib.go | addSysZversionFile | func addSysZversionFile(fs ctxvfs.FileSystem) ctxvfs.FileSystem {
return ctxvfs.SingleFileOverlay(fs,
"/src/runtime/internal/sys/zversion.go",
[]byte(fmt.Sprintf(`
package sys
const DefaultGoroot = %q
const TheVersion = %q
const Goexperiment=""
const StackGuardMultiplier=1`,
goroot, gosrc.RuntimeVersion)))
} | go | func addSysZversionFile(fs ctxvfs.FileSystem) ctxvfs.FileSystem {
return ctxvfs.SingleFileOverlay(fs,
"/src/runtime/internal/sys/zversion.go",
[]byte(fmt.Sprintf(`
package sys
const DefaultGoroot = %q
const TheVersion = %q
const Goexperiment=""
const StackGuardMultiplier=1`,
goroot, gosrc.RuntimeVersion)))
} | [
"func",
"addSysZversionFile",
"(",
"fs",
"ctxvfs",
".",
"FileSystem",
")",
"ctxvfs",
".",
"FileSystem",
"{",
"return",
"ctxvfs",
".",
"SingleFileOverlay",
"(",
"fs",
",",
"\"",
"\"",
",",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"`\npackage sys\n\nconst DefaultGoroot = %q\nconst TheVersion = %q\nconst Goexperiment=\"\"\nconst StackGuardMultiplier=1`",
",",
"goroot",
",",
"gosrc",
".",
"RuntimeVersion",
")",
")",
")",
"\n",
"}"
] | // addSysZversionFile adds the zversion.go file, which is generated
// during the Go release process and does not exist in the VCS repo
// archive zips. We need to create it here, or else we'll see
// typechecker errors like "StackGuardMultiplier not declared by
// package sys" when any packages import from the Go stdlib. | [
"addSysZversionFile",
"adds",
"the",
"zversion",
".",
"go",
"file",
"which",
"is",
"generated",
"during",
"the",
"Go",
"release",
"process",
"and",
"does",
"not",
"exist",
"in",
"the",
"VCS",
"repo",
"archive",
"zips",
".",
"We",
"need",
"to",
"create",
"it",
"here",
"or",
"else",
"we",
"ll",
"see",
"typechecker",
"errors",
"like",
"StackGuardMultiplier",
"not",
"declared",
"by",
"package",
"sys",
"when",
"any",
"packages",
"import",
"from",
"the",
"Go",
"stdlib",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/stdlib.go#L15-L26 |
sourcegraph/go-langserver | debugserver/debug.go | Start | func Start(extra ...Endpoint) {
if addr == "" {
return
}
pp := http.NewServeMux()
index := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`
<a href="vars">Vars</a><br>
<a href="debug/pprof/">PProf</a><br>
<a href="metrics">Metrics</a><br>
<a href="debug/requests">Requests</a><br>
<a href="debug/events">Events</a><br>
`))
for _, e := range extra {
fmt.Fprintf(w, `<a href="%s">%s</a><br>`, strings.TrimPrefix(e.Path, "/"), e.Name)
}
w.Write([]byte(`
<br>
<form method="post" action="gc" style="display: inline;"><input type="submit" value="GC"></form>
<form method="post" action="freeosmemory" style="display: inline;"><input type="submit" value="Free OS Memory"></form>
`))
})
pp.Handle("/", index)
pp.Handle("/debug", index)
pp.Handle("/vars", http.HandlerFunc(expvarHandler))
pp.Handle("/gc", http.HandlerFunc(gcHandler))
pp.Handle("/freeosmemory", http.HandlerFunc(freeOSMemoryHandler))
pp.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
pp.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
pp.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
pp.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
pp.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
pp.Handle("/debug/requests", http.HandlerFunc(trace.Traces))
pp.Handle("/debug/events", http.HandlerFunc(trace.Events))
pp.Handle("/metrics", promhttp.Handler())
for _, e := range extra {
pp.Handle(e.Path, e.Handler)
}
log.Println("warning: could not start debug HTTP server:", http.ListenAndServe(addr, pp))
} | go | func Start(extra ...Endpoint) {
if addr == "" {
return
}
pp := http.NewServeMux()
index := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`
<a href="vars">Vars</a><br>
<a href="debug/pprof/">PProf</a><br>
<a href="metrics">Metrics</a><br>
<a href="debug/requests">Requests</a><br>
<a href="debug/events">Events</a><br>
`))
for _, e := range extra {
fmt.Fprintf(w, `<a href="%s">%s</a><br>`, strings.TrimPrefix(e.Path, "/"), e.Name)
}
w.Write([]byte(`
<br>
<form method="post" action="gc" style="display: inline;"><input type="submit" value="GC"></form>
<form method="post" action="freeosmemory" style="display: inline;"><input type="submit" value="Free OS Memory"></form>
`))
})
pp.Handle("/", index)
pp.Handle("/debug", index)
pp.Handle("/vars", http.HandlerFunc(expvarHandler))
pp.Handle("/gc", http.HandlerFunc(gcHandler))
pp.Handle("/freeosmemory", http.HandlerFunc(freeOSMemoryHandler))
pp.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
pp.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
pp.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
pp.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
pp.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
pp.Handle("/debug/requests", http.HandlerFunc(trace.Traces))
pp.Handle("/debug/events", http.HandlerFunc(trace.Events))
pp.Handle("/metrics", promhttp.Handler())
for _, e := range extra {
pp.Handle(e.Path, e.Handler)
}
log.Println("warning: could not start debug HTTP server:", http.ListenAndServe(addr, pp))
} | [
"func",
"Start",
"(",
"extra",
"...",
"Endpoint",
")",
"{",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"pp",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n",
"index",
":=",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"`\n\t\t\t\t<a href=\"vars\">Vars</a><br>\n\t\t\t\t<a href=\"debug/pprof/\">PProf</a><br>\n\t\t\t\t<a href=\"metrics\">Metrics</a><br>\n\t\t\t\t<a href=\"debug/requests\">Requests</a><br>\n\t\t\t\t<a href=\"debug/events\">Events</a><br>\n\t\t\t`",
")",
")",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"extra",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"`<a href=\"%s\">%s</a><br>`",
",",
"strings",
".",
"TrimPrefix",
"(",
"e",
".",
"Path",
",",
"\"",
"\"",
")",
",",
"e",
".",
"Name",
")",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"`\n\t\t\t\t<br>\n\t\t\t\t<form method=\"post\" action=\"gc\" style=\"display: inline;\"><input type=\"submit\" value=\"GC\"></form>\n\t\t\t\t<form method=\"post\" action=\"freeosmemory\" style=\"display: inline;\"><input type=\"submit\" value=\"Free OS Memory\"></form>\n\t\t\t`",
")",
")",
"\n",
"}",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"index",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"index",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"expvarHandler",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"gcHandler",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"freeOSMemoryHandler",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Index",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Cmdline",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Profile",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Symbol",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"pprof",
".",
"Trace",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"trace",
".",
"Traces",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"http",
".",
"HandlerFunc",
"(",
"trace",
".",
"Events",
")",
")",
"\n",
"pp",
".",
"Handle",
"(",
"\"",
"\"",
",",
"promhttp",
".",
"Handler",
"(",
")",
")",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"extra",
"{",
"pp",
".",
"Handle",
"(",
"e",
".",
"Path",
",",
"e",
".",
"Handler",
")",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"http",
".",
"ListenAndServe",
"(",
"addr",
",",
"pp",
")",
")",
"\n",
"}"
] | // Start runs a debug server (pprof, prometheus, etc) if it is configured (via
// SRC_PROF_HTTP environment variable). It is blocking. | [
"Start",
"runs",
"a",
"debug",
"server",
"(",
"pprof",
"prometheus",
"etc",
")",
"if",
"it",
"is",
"configured",
"(",
"via",
"SRC_PROF_HTTP",
"environment",
"variable",
")",
".",
"It",
"is",
"blocking",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/debugserver/debug.go#L75-L115 |
sourcegraph/go-langserver | langserver/implementation.go | implements | func implements(fset *token.FileSet, lprog *loader.Program, pkgInfo *loader.PackageInfo, path []ast.Node, action action) ([]*lspext.ImplementationLocation, error) {
var method *types.Func
var T types.Type // selected type (receiver if method != nil)
switch action {
case actionExpr:
// method?
if id, ok := path[0].(*ast.Ident); ok {
if obj, ok := pkgInfo.ObjectOf(id).(*types.Func); ok {
recv := obj.Type().(*types.Signature).Recv()
if recv == nil {
return nil, errors.New("this function is not a method")
}
method = obj
T = recv.Type()
}
}
// If not a method, use the expression's type.
if T == nil {
T = pkgInfo.TypeOf(path[0].(ast.Expr))
}
case actionType:
T = pkgInfo.TypeOf(path[0].(ast.Expr))
}
if T == nil {
return nil, errors.New("not a type, method, or value")
}
// Find all named types, even local types (which can have
// methods due to promotion) and the built-in "error".
// We ignore aliases 'type M = N' to avoid duplicate
// reporting of the Named type N.
var allNamed []*types.Named
for _, info := range lprog.AllPackages {
for _, obj := range info.Defs {
if obj, ok := obj.(*types.TypeName); ok && !isAlias(obj) {
if named, ok := obj.Type().(*types.Named); ok {
allNamed = append(allNamed, named)
}
}
}
}
allNamed = append(allNamed, types.Universe.Lookup("error").Type().(*types.Named))
var msets typeutil.MethodSetCache
// Test each named type.
var to, from, fromPtr []types.Type
for _, U := range allNamed {
if isInterface(T) {
if msets.MethodSet(T).Len() == 0 {
continue // empty interface
}
if isInterface(U) {
if msets.MethodSet(U).Len() == 0 {
continue // empty interface
}
// T interface, U interface
if !types.Identical(T, U) {
if types.AssignableTo(U, T) {
to = append(to, U)
}
if types.AssignableTo(T, U) {
from = append(from, U)
}
}
} else {
// T interface, U concrete
if types.AssignableTo(U, T) {
to = append(to, U)
} else if pU := types.NewPointer(U); types.AssignableTo(pU, T) {
to = append(to, pU)
}
}
} else if isInterface(U) {
if msets.MethodSet(U).Len() == 0 {
continue // empty interface
}
// T concrete, U interface
if types.AssignableTo(T, U) {
from = append(from, U)
} else if pT := types.NewPointer(T); types.AssignableTo(pT, U) {
fromPtr = append(fromPtr, U)
}
}
}
// Sort types (arbitrarily) to ensure test determinism.
sort.Sort(typesByString(to))
sort.Sort(typesByString(from))
sort.Sort(typesByString(fromPtr))
seen := map[types.Object]struct{}{}
toLocation := func(t types.Type, method *types.Func) *lspext.ImplementationLocation {
var obj types.Object
if method == nil {
// t is a type
nt, ok := deref(t).(*types.Named)
if !ok {
return nil // t is non-named
}
obj = nt.Obj()
} else {
// t is a method
tm := types.NewMethodSet(t).Lookup(method.Pkg(), method.Name())
if tm == nil {
return nil // method not found
}
obj = tm.Obj()
if _, seen := seen[obj]; seen {
return nil // already saw this method, via other embedding path
}
seen[obj] = struct{}{}
}
pos := obj.Pos()
end := obj.Pos() + token.Pos(len(obj.Name()))
return &lspext.ImplementationLocation{
Location: goRangeToLSPLocation(fset, pos, end),
Method: method != nil,
}
}
locs := make([]*lspext.ImplementationLocation, 0, len(to)+len(from)+len(fromPtr))
for _, t := range to {
loc := toLocation(t, method)
if loc == nil {
continue
}
loc.Type = "to"
locs = append(locs, loc)
}
for _, t := range from {
loc := toLocation(t, method)
if loc == nil {
continue
}
loc.Type = "from"
locs = append(locs, loc)
}
for _, t := range fromPtr {
loc := toLocation(t, method)
if loc == nil {
continue
}
loc.Type = "from"
loc.Ptr = true
locs = append(locs, loc)
}
return locs, nil
} | go | func implements(fset *token.FileSet, lprog *loader.Program, pkgInfo *loader.PackageInfo, path []ast.Node, action action) ([]*lspext.ImplementationLocation, error) {
var method *types.Func
var T types.Type // selected type (receiver if method != nil)
switch action {
case actionExpr:
// method?
if id, ok := path[0].(*ast.Ident); ok {
if obj, ok := pkgInfo.ObjectOf(id).(*types.Func); ok {
recv := obj.Type().(*types.Signature).Recv()
if recv == nil {
return nil, errors.New("this function is not a method")
}
method = obj
T = recv.Type()
}
}
// If not a method, use the expression's type.
if T == nil {
T = pkgInfo.TypeOf(path[0].(ast.Expr))
}
case actionType:
T = pkgInfo.TypeOf(path[0].(ast.Expr))
}
if T == nil {
return nil, errors.New("not a type, method, or value")
}
// Find all named types, even local types (which can have
// methods due to promotion) and the built-in "error".
// We ignore aliases 'type M = N' to avoid duplicate
// reporting of the Named type N.
var allNamed []*types.Named
for _, info := range lprog.AllPackages {
for _, obj := range info.Defs {
if obj, ok := obj.(*types.TypeName); ok && !isAlias(obj) {
if named, ok := obj.Type().(*types.Named); ok {
allNamed = append(allNamed, named)
}
}
}
}
allNamed = append(allNamed, types.Universe.Lookup("error").Type().(*types.Named))
var msets typeutil.MethodSetCache
// Test each named type.
var to, from, fromPtr []types.Type
for _, U := range allNamed {
if isInterface(T) {
if msets.MethodSet(T).Len() == 0 {
continue // empty interface
}
if isInterface(U) {
if msets.MethodSet(U).Len() == 0 {
continue // empty interface
}
// T interface, U interface
if !types.Identical(T, U) {
if types.AssignableTo(U, T) {
to = append(to, U)
}
if types.AssignableTo(T, U) {
from = append(from, U)
}
}
} else {
// T interface, U concrete
if types.AssignableTo(U, T) {
to = append(to, U)
} else if pU := types.NewPointer(U); types.AssignableTo(pU, T) {
to = append(to, pU)
}
}
} else if isInterface(U) {
if msets.MethodSet(U).Len() == 0 {
continue // empty interface
}
// T concrete, U interface
if types.AssignableTo(T, U) {
from = append(from, U)
} else if pT := types.NewPointer(T); types.AssignableTo(pT, U) {
fromPtr = append(fromPtr, U)
}
}
}
// Sort types (arbitrarily) to ensure test determinism.
sort.Sort(typesByString(to))
sort.Sort(typesByString(from))
sort.Sort(typesByString(fromPtr))
seen := map[types.Object]struct{}{}
toLocation := func(t types.Type, method *types.Func) *lspext.ImplementationLocation {
var obj types.Object
if method == nil {
// t is a type
nt, ok := deref(t).(*types.Named)
if !ok {
return nil // t is non-named
}
obj = nt.Obj()
} else {
// t is a method
tm := types.NewMethodSet(t).Lookup(method.Pkg(), method.Name())
if tm == nil {
return nil // method not found
}
obj = tm.Obj()
if _, seen := seen[obj]; seen {
return nil // already saw this method, via other embedding path
}
seen[obj] = struct{}{}
}
pos := obj.Pos()
end := obj.Pos() + token.Pos(len(obj.Name()))
return &lspext.ImplementationLocation{
Location: goRangeToLSPLocation(fset, pos, end),
Method: method != nil,
}
}
locs := make([]*lspext.ImplementationLocation, 0, len(to)+len(from)+len(fromPtr))
for _, t := range to {
loc := toLocation(t, method)
if loc == nil {
continue
}
loc.Type = "to"
locs = append(locs, loc)
}
for _, t := range from {
loc := toLocation(t, method)
if loc == nil {
continue
}
loc.Type = "from"
locs = append(locs, loc)
}
for _, t := range fromPtr {
loc := toLocation(t, method)
if loc == nil {
continue
}
loc.Type = "from"
loc.Ptr = true
locs = append(locs, loc)
}
return locs, nil
} | [
"func",
"implements",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"lprog",
"*",
"loader",
".",
"Program",
",",
"pkgInfo",
"*",
"loader",
".",
"PackageInfo",
",",
"path",
"[",
"]",
"ast",
".",
"Node",
",",
"action",
"action",
")",
"(",
"[",
"]",
"*",
"lspext",
".",
"ImplementationLocation",
",",
"error",
")",
"{",
"var",
"method",
"*",
"types",
".",
"Func",
"\n",
"var",
"T",
"types",
".",
"Type",
"// selected type (receiver if method != nil)",
"\n\n",
"switch",
"action",
"{",
"case",
"actionExpr",
":",
"// method?",
"if",
"id",
",",
"ok",
":=",
"path",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"{",
"if",
"obj",
",",
"ok",
":=",
"pkgInfo",
".",
"ObjectOf",
"(",
"id",
")",
".",
"(",
"*",
"types",
".",
"Func",
")",
";",
"ok",
"{",
"recv",
":=",
"obj",
".",
"Type",
"(",
")",
".",
"(",
"*",
"types",
".",
"Signature",
")",
".",
"Recv",
"(",
")",
"\n",
"if",
"recv",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"method",
"=",
"obj",
"\n",
"T",
"=",
"recv",
".",
"Type",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If not a method, use the expression's type.",
"if",
"T",
"==",
"nil",
"{",
"T",
"=",
"pkgInfo",
".",
"TypeOf",
"(",
"path",
"[",
"0",
"]",
".",
"(",
"ast",
".",
"Expr",
")",
")",
"\n",
"}",
"\n\n",
"case",
"actionType",
":",
"T",
"=",
"pkgInfo",
".",
"TypeOf",
"(",
"path",
"[",
"0",
"]",
".",
"(",
"ast",
".",
"Expr",
")",
")",
"\n",
"}",
"\n",
"if",
"T",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Find all named types, even local types (which can have",
"// methods due to promotion) and the built-in \"error\".",
"// We ignore aliases 'type M = N' to avoid duplicate",
"// reporting of the Named type N.",
"var",
"allNamed",
"[",
"]",
"*",
"types",
".",
"Named",
"\n",
"for",
"_",
",",
"info",
":=",
"range",
"lprog",
".",
"AllPackages",
"{",
"for",
"_",
",",
"obj",
":=",
"range",
"info",
".",
"Defs",
"{",
"if",
"obj",
",",
"ok",
":=",
"obj",
".",
"(",
"*",
"types",
".",
"TypeName",
")",
";",
"ok",
"&&",
"!",
"isAlias",
"(",
"obj",
")",
"{",
"if",
"named",
",",
"ok",
":=",
"obj",
".",
"Type",
"(",
")",
".",
"(",
"*",
"types",
".",
"Named",
")",
";",
"ok",
"{",
"allNamed",
"=",
"append",
"(",
"allNamed",
",",
"named",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"allNamed",
"=",
"append",
"(",
"allNamed",
",",
"types",
".",
"Universe",
".",
"Lookup",
"(",
"\"",
"\"",
")",
".",
"Type",
"(",
")",
".",
"(",
"*",
"types",
".",
"Named",
")",
")",
"\n\n",
"var",
"msets",
"typeutil",
".",
"MethodSetCache",
"\n\n",
"// Test each named type.",
"var",
"to",
",",
"from",
",",
"fromPtr",
"[",
"]",
"types",
".",
"Type",
"\n",
"for",
"_",
",",
"U",
":=",
"range",
"allNamed",
"{",
"if",
"isInterface",
"(",
"T",
")",
"{",
"if",
"msets",
".",
"MethodSet",
"(",
"T",
")",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"continue",
"// empty interface",
"\n",
"}",
"\n",
"if",
"isInterface",
"(",
"U",
")",
"{",
"if",
"msets",
".",
"MethodSet",
"(",
"U",
")",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"continue",
"// empty interface",
"\n",
"}",
"\n\n",
"// T interface, U interface",
"if",
"!",
"types",
".",
"Identical",
"(",
"T",
",",
"U",
")",
"{",
"if",
"types",
".",
"AssignableTo",
"(",
"U",
",",
"T",
")",
"{",
"to",
"=",
"append",
"(",
"to",
",",
"U",
")",
"\n",
"}",
"\n",
"if",
"types",
".",
"AssignableTo",
"(",
"T",
",",
"U",
")",
"{",
"from",
"=",
"append",
"(",
"from",
",",
"U",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// T interface, U concrete",
"if",
"types",
".",
"AssignableTo",
"(",
"U",
",",
"T",
")",
"{",
"to",
"=",
"append",
"(",
"to",
",",
"U",
")",
"\n",
"}",
"else",
"if",
"pU",
":=",
"types",
".",
"NewPointer",
"(",
"U",
")",
";",
"types",
".",
"AssignableTo",
"(",
"pU",
",",
"T",
")",
"{",
"to",
"=",
"append",
"(",
"to",
",",
"pU",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"isInterface",
"(",
"U",
")",
"{",
"if",
"msets",
".",
"MethodSet",
"(",
"U",
")",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"continue",
"// empty interface",
"\n",
"}",
"\n\n",
"// T concrete, U interface",
"if",
"types",
".",
"AssignableTo",
"(",
"T",
",",
"U",
")",
"{",
"from",
"=",
"append",
"(",
"from",
",",
"U",
")",
"\n",
"}",
"else",
"if",
"pT",
":=",
"types",
".",
"NewPointer",
"(",
"T",
")",
";",
"types",
".",
"AssignableTo",
"(",
"pT",
",",
"U",
")",
"{",
"fromPtr",
"=",
"append",
"(",
"fromPtr",
",",
"U",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Sort types (arbitrarily) to ensure test determinism.",
"sort",
".",
"Sort",
"(",
"typesByString",
"(",
"to",
")",
")",
"\n",
"sort",
".",
"Sort",
"(",
"typesByString",
"(",
"from",
")",
")",
"\n",
"sort",
".",
"Sort",
"(",
"typesByString",
"(",
"fromPtr",
")",
")",
"\n\n",
"seen",
":=",
"map",
"[",
"types",
".",
"Object",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"toLocation",
":=",
"func",
"(",
"t",
"types",
".",
"Type",
",",
"method",
"*",
"types",
".",
"Func",
")",
"*",
"lspext",
".",
"ImplementationLocation",
"{",
"var",
"obj",
"types",
".",
"Object",
"\n",
"if",
"method",
"==",
"nil",
"{",
"// t is a type",
"nt",
",",
"ok",
":=",
"deref",
"(",
"t",
")",
".",
"(",
"*",
"types",
".",
"Named",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"// t is non-named",
"\n",
"}",
"\n",
"obj",
"=",
"nt",
".",
"Obj",
"(",
")",
"\n",
"}",
"else",
"{",
"// t is a method",
"tm",
":=",
"types",
".",
"NewMethodSet",
"(",
"t",
")",
".",
"Lookup",
"(",
"method",
".",
"Pkg",
"(",
")",
",",
"method",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"tm",
"==",
"nil",
"{",
"return",
"nil",
"// method not found",
"\n",
"}",
"\n",
"obj",
"=",
"tm",
".",
"Obj",
"(",
")",
"\n",
"if",
"_",
",",
"seen",
":=",
"seen",
"[",
"obj",
"]",
";",
"seen",
"{",
"return",
"nil",
"// already saw this method, via other embedding path",
"\n",
"}",
"\n",
"seen",
"[",
"obj",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n\n",
"pos",
":=",
"obj",
".",
"Pos",
"(",
")",
"\n",
"end",
":=",
"obj",
".",
"Pos",
"(",
")",
"+",
"token",
".",
"Pos",
"(",
"len",
"(",
"obj",
".",
"Name",
"(",
")",
")",
")",
"\n",
"return",
"&",
"lspext",
".",
"ImplementationLocation",
"{",
"Location",
":",
"goRangeToLSPLocation",
"(",
"fset",
",",
"pos",
",",
"end",
")",
",",
"Method",
":",
"method",
"!=",
"nil",
",",
"}",
"\n",
"}",
"\n\n",
"locs",
":=",
"make",
"(",
"[",
"]",
"*",
"lspext",
".",
"ImplementationLocation",
",",
"0",
",",
"len",
"(",
"to",
")",
"+",
"len",
"(",
"from",
")",
"+",
"len",
"(",
"fromPtr",
")",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"to",
"{",
"loc",
":=",
"toLocation",
"(",
"t",
",",
"method",
")",
"\n",
"if",
"loc",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"loc",
".",
"Type",
"=",
"\"",
"\"",
"\n",
"locs",
"=",
"append",
"(",
"locs",
",",
"loc",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"from",
"{",
"loc",
":=",
"toLocation",
"(",
"t",
",",
"method",
")",
"\n",
"if",
"loc",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"loc",
".",
"Type",
"=",
"\"",
"\"",
"\n",
"locs",
"=",
"append",
"(",
"locs",
",",
"loc",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"fromPtr",
"{",
"loc",
":=",
"toLocation",
"(",
"t",
",",
"method",
")",
"\n",
"if",
"loc",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"loc",
".",
"Type",
"=",
"\"",
"\"",
"\n",
"loc",
".",
"Ptr",
"=",
"true",
"\n",
"locs",
"=",
"append",
"(",
"locs",
",",
"loc",
")",
"\n",
"}",
"\n",
"return",
"locs",
",",
"nil",
"\n",
"}"
] | // Adapted from golang.org/x/tools/cmd/guru (Copyright (c) 2013 The Go Authors). All rights
// reserved. See NOTICE for full license. | [
"Adapted",
"from",
"golang",
".",
"org",
"/",
"x",
"/",
"tools",
"/",
"cmd",
"/",
"guru",
"(",
"Copyright",
"(",
"c",
")",
"2013",
"The",
"Go",
"Authors",
")",
".",
"All",
"rights",
"reserved",
".",
"See",
"NOTICE",
"for",
"full",
"license",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/implementation.go#L65-L219 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | DefaultImportPathToName | func DefaultImportPathToName(path, srcDir string) (string, error) {
if path == "C" {
return "C", nil
}
pkg, err := build.Default.Import(path, srcDir, 0)
return pkg.Name, err
} | go | func DefaultImportPathToName(path, srcDir string) (string, error) {
if path == "C" {
return "C", nil
}
pkg, err := build.Default.Import(path, srcDir, 0)
return pkg.Name, err
} | [
"func",
"DefaultImportPathToName",
"(",
"path",
",",
"srcDir",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"pkg",
",",
"err",
":=",
"build",
".",
"Default",
".",
"Import",
"(",
"path",
",",
"srcDir",
",",
"0",
")",
"\n",
"return",
"pkg",
".",
"Name",
",",
"err",
"\n",
"}"
] | // DefaultImportPathToName returns the package identifier
// for the given import path. | [
"DefaultImportPathToName",
"returns",
"the",
"package",
"identifier",
"for",
"the",
"given",
"import",
"path",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L123-L129 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | isGoFile | func isGoFile(d os.FileInfo) bool {
return strings.HasSuffix(d.Name(), ".go") &&
!strings.HasSuffix(d.Name(), "_test.go") &&
!strings.HasPrefix(d.Name(), ".") &&
goodOSArch(d.Name())
} | go | func isGoFile(d os.FileInfo) bool {
return strings.HasSuffix(d.Name(), ".go") &&
!strings.HasSuffix(d.Name(), "_test.go") &&
!strings.HasPrefix(d.Name(), ".") &&
goodOSArch(d.Name())
} | [
"func",
"isGoFile",
"(",
"d",
"os",
".",
"FileInfo",
")",
"bool",
"{",
"return",
"strings",
".",
"HasSuffix",
"(",
"d",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"&&",
"!",
"strings",
".",
"HasSuffix",
"(",
"d",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"d",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"&&",
"goodOSArch",
"(",
"d",
".",
"Name",
"(",
")",
")",
"\n",
"}"
] | // isGoFile returns true if we will consider the file as a
// possible candidate for parsing as part of a package.
// Including _test.go here isn't quite right, but what
// else can we do?
// | [
"isGoFile",
"returns",
"true",
"if",
"we",
"will",
"consider",
"the",
"file",
"as",
"a",
"possible",
"candidate",
"for",
"parsing",
"as",
"part",
"of",
"a",
"package",
".",
"Including",
"_test",
".",
"go",
"here",
"isn",
"t",
"quite",
"right",
"but",
"what",
"else",
"can",
"we",
"do?"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L136-L141 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | Member | func (t Type) Member(name string) *ast.Object {
debugp("member %v '%s' {", t, name)
if t.Pkg != "" && !ast.IsExported(name) {
return nil
}
c := make(chan *ast.Object)
go func() {
if !Panic {
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %v", err)
c <- nil
}
}()
}
doMembers(t, name, func(obj *ast.Object) {
if obj.Name == name {
c <- obj
runtime.Goexit()
}
})
c <- nil
}()
m := <-c
debugp("} -> %v", m)
return m
} | go | func (t Type) Member(name string) *ast.Object {
debugp("member %v '%s' {", t, name)
if t.Pkg != "" && !ast.IsExported(name) {
return nil
}
c := make(chan *ast.Object)
go func() {
if !Panic {
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %v", err)
c <- nil
}
}()
}
doMembers(t, name, func(obj *ast.Object) {
if obj.Name == name {
c <- obj
runtime.Goexit()
}
})
c <- nil
}()
m := <-c
debugp("} -> %v", m)
return m
} | [
"func",
"(",
"t",
"Type",
")",
"Member",
"(",
"name",
"string",
")",
"*",
"ast",
".",
"Object",
"{",
"debugp",
"(",
"\"",
"\"",
",",
"t",
",",
"name",
")",
"\n",
"if",
"t",
".",
"Pkg",
"!=",
"\"",
"\"",
"&&",
"!",
"ast",
".",
"IsExported",
"(",
"name",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"c",
":=",
"make",
"(",
"chan",
"*",
"ast",
".",
"Object",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"if",
"!",
"Panic",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"c",
"<-",
"nil",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"doMembers",
"(",
"t",
",",
"name",
",",
"func",
"(",
"obj",
"*",
"ast",
".",
"Object",
")",
"{",
"if",
"obj",
".",
"Name",
"==",
"name",
"{",
"c",
"<-",
"obj",
"\n",
"runtime",
".",
"Goexit",
"(",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"c",
"<-",
"nil",
"\n",
"}",
"(",
")",
"\n",
"m",
":=",
"<-",
"c",
"\n",
"debugp",
"(",
"\"",
"\"",
",",
"m",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // Member looks for a member with the given name inside
// the type. For packages, the member can be any exported
// top level declaration inside the package. | [
"Member",
"looks",
"for",
"a",
"member",
"with",
"the",
"given",
"name",
"inside",
"the",
"type",
".",
"For",
"packages",
"the",
"member",
"can",
"be",
"any",
"exported",
"top",
"level",
"declaration",
"inside",
"the",
"package",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L156-L182 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | Iter | func (t Type) Iter() <-chan *ast.Object {
// TODO avoid sending members with the same name twice.
c := make(chan *ast.Object)
go func() {
internal := t.Pkg == ""
doMembers(t, "", func(obj *ast.Object) {
if internal || ast.IsExported(obj.Name) {
c <- obj
}
})
close(c)
}()
return c
} | go | func (t Type) Iter() <-chan *ast.Object {
// TODO avoid sending members with the same name twice.
c := make(chan *ast.Object)
go func() {
internal := t.Pkg == ""
doMembers(t, "", func(obj *ast.Object) {
if internal || ast.IsExported(obj.Name) {
c <- obj
}
})
close(c)
}()
return c
} | [
"func",
"(",
"t",
"Type",
")",
"Iter",
"(",
")",
"<-",
"chan",
"*",
"ast",
".",
"Object",
"{",
"// TODO avoid sending members with the same name twice.",
"c",
":=",
"make",
"(",
"chan",
"*",
"ast",
".",
"Object",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"internal",
":=",
"t",
".",
"Pkg",
"==",
"\"",
"\"",
"\n",
"doMembers",
"(",
"t",
",",
"\"",
"\"",
",",
"func",
"(",
"obj",
"*",
"ast",
".",
"Object",
")",
"{",
"if",
"internal",
"||",
"ast",
".",
"IsExported",
"(",
"obj",
".",
"Name",
")",
"{",
"c",
"<-",
"obj",
"\n",
"}",
"\n",
"}",
")",
"\n",
"close",
"(",
"c",
")",
"\n",
"}",
"(",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // Iter returns a channel, sends on it
// all the members of the type, then closes it.
// Members at a shallower depth will be
// sent first.
// | [
"Iter",
"returns",
"a",
"channel",
"sends",
"on",
"it",
"all",
"the",
"members",
"of",
"the",
"type",
"then",
"closes",
"it",
".",
"Members",
"at",
"a",
"shallower",
"depth",
"will",
"be",
"sent",
"first",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L189-L202 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | ExprType | func ExprType(e ast.Expr, importer Importer, fs *token.FileSet) (obj *ast.Object, typ Type) {
ctxt := &exprTypeContext{
importer: importer,
fileSet: fs,
}
return ctxt.exprType(e, false, "")
} | go | func ExprType(e ast.Expr, importer Importer, fs *token.FileSet) (obj *ast.Object, typ Type) {
ctxt := &exprTypeContext{
importer: importer,
fileSet: fs,
}
return ctxt.exprType(e, false, "")
} | [
"func",
"ExprType",
"(",
"e",
"ast",
".",
"Expr",
",",
"importer",
"Importer",
",",
"fs",
"*",
"token",
".",
"FileSet",
")",
"(",
"obj",
"*",
"ast",
".",
"Object",
",",
"typ",
"Type",
")",
"{",
"ctxt",
":=",
"&",
"exprTypeContext",
"{",
"importer",
":",
"importer",
",",
"fileSet",
":",
"fs",
",",
"}",
"\n",
"return",
"ctxt",
".",
"exprType",
"(",
"e",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // ExprType returns the type for the given expression,
// and the object that represents it, if there is one.
// All variables, methods, top level functions, packages, struct and
// interface members, and types have objects.
// The returned object can be used with DeclPos to find out
// the source location of the definition of the object.
// | [
"ExprType",
"returns",
"the",
"type",
"for",
"the",
"given",
"expression",
"and",
"the",
"object",
"that",
"represents",
"it",
"if",
"there",
"is",
"one",
".",
"All",
"variables",
"methods",
"top",
"level",
"functions",
"packages",
"struct",
"and",
"interface",
"members",
"and",
"types",
"have",
"objects",
".",
"The",
"returned",
"object",
"can",
"be",
"used",
"with",
"DeclPos",
"to",
"find",
"out",
"the",
"source",
"location",
"of",
"the",
"definition",
"of",
"the",
"object",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L211-L217 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | litToString | func litToString(lit *ast.BasicLit) (v string) {
if lit.Kind != token.STRING {
panic("expected string")
}
v, err := strconv.Unquote(string(lit.Value))
if err != nil {
panic("cannot unquote")
}
return v
} | go | func litToString(lit *ast.BasicLit) (v string) {
if lit.Kind != token.STRING {
panic("expected string")
}
v, err := strconv.Unquote(string(lit.Value))
if err != nil {
panic("cannot unquote")
}
return v
} | [
"func",
"litToString",
"(",
"lit",
"*",
"ast",
".",
"BasicLit",
")",
"(",
"v",
"string",
")",
"{",
"if",
"lit",
".",
"Kind",
"!=",
"token",
".",
"STRING",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"v",
",",
"err",
":=",
"strconv",
".",
"Unquote",
"(",
"string",
"(",
"lit",
".",
"Value",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"v",
"\n",
"}"
] | // litToString converts from a string literal to a regular string. | [
"litToString",
"converts",
"from",
"a",
"string",
"literal",
"to",
"a",
"regular",
"string",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L520-L529 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | doMembers | func doMembers(typ Type, name string, fn func(*ast.Object)) {
switch t := typ.Node.(type) {
case nil:
return
case *ast.ImportSpec:
path := litToString(t.Path)
pos := typ.ctxt.fileSet.Position(typ.Node.Pos())
if pkg := typ.ctxt.importer(path, filepath.Dir(pos.Filename)); pkg != nil {
doScope(pkg.Scope, name, fn, path)
}
return
}
q := list.New()
q.PushBack(typ)
for e := q.Front(); e != nil; e = q.Front() {
doTypeMembers(e.Value.(Type), name, fn, q)
q.Remove(e)
}
} | go | func doMembers(typ Type, name string, fn func(*ast.Object)) {
switch t := typ.Node.(type) {
case nil:
return
case *ast.ImportSpec:
path := litToString(t.Path)
pos := typ.ctxt.fileSet.Position(typ.Node.Pos())
if pkg := typ.ctxt.importer(path, filepath.Dir(pos.Filename)); pkg != nil {
doScope(pkg.Scope, name, fn, path)
}
return
}
q := list.New()
q.PushBack(typ)
for e := q.Front(); e != nil; e = q.Front() {
doTypeMembers(e.Value.(Type), name, fn, q)
q.Remove(e)
}
} | [
"func",
"doMembers",
"(",
"typ",
"Type",
",",
"name",
"string",
",",
"fn",
"func",
"(",
"*",
"ast",
".",
"Object",
")",
")",
"{",
"switch",
"t",
":=",
"typ",
".",
"Node",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"\n\n",
"case",
"*",
"ast",
".",
"ImportSpec",
":",
"path",
":=",
"litToString",
"(",
"t",
".",
"Path",
")",
"\n",
"pos",
":=",
"typ",
".",
"ctxt",
".",
"fileSet",
".",
"Position",
"(",
"typ",
".",
"Node",
".",
"Pos",
"(",
")",
")",
"\n",
"if",
"pkg",
":=",
"typ",
".",
"ctxt",
".",
"importer",
"(",
"path",
",",
"filepath",
".",
"Dir",
"(",
"pos",
".",
"Filename",
")",
")",
";",
"pkg",
"!=",
"nil",
"{",
"doScope",
"(",
"pkg",
".",
"Scope",
",",
"name",
",",
"fn",
",",
"path",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"q",
":=",
"list",
".",
"New",
"(",
")",
"\n",
"q",
".",
"PushBack",
"(",
"typ",
")",
"\n",
"for",
"e",
":=",
"q",
".",
"Front",
"(",
")",
";",
"e",
"!=",
"nil",
";",
"e",
"=",
"q",
".",
"Front",
"(",
")",
"{",
"doTypeMembers",
"(",
"e",
".",
"Value",
".",
"(",
"Type",
")",
",",
"name",
",",
"fn",
",",
"q",
")",
"\n",
"q",
".",
"Remove",
"(",
"e",
")",
"\n",
"}",
"\n",
"}"
] | // doMembers iterates through a type's members, calling
// fn for each member. If name is non-empty, it looks
// directly for members with that name when possible.
// It uses the list q as a queue to perform breadth-first
// traversal, as per the Go specification. | [
"doMembers",
"iterates",
"through",
"a",
"type",
"s",
"members",
"calling",
"fn",
"for",
"each",
"member",
".",
"If",
"name",
"is",
"non",
"-",
"empty",
"it",
"looks",
"directly",
"for",
"members",
"with",
"that",
"name",
"when",
"possible",
".",
"It",
"uses",
"the",
"list",
"q",
"as",
"a",
"queue",
"to",
"perform",
"breadth",
"-",
"first",
"traversal",
"as",
"per",
"the",
"Go",
"specification",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L536-L556 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | doTypeMembers | func doTypeMembers(t Type, name string, fn func(*ast.Object), q *list.List) {
// strip off single indirection
// TODO: eliminate methods disallowed when indirected.
if u, ok := t.Node.(*ast.StarExpr); ok {
_, t = t.ctxt.exprType(u.X, false, t.Pkg)
}
if id, _ := t.Node.(*ast.Ident); id != nil && id.Obj != nil {
if scope, ok := id.Obj.Type.(*ast.Scope); ok {
doScope(scope, name, fn, t.Pkg)
}
}
u := t.Underlying(true)
switch n := u.Node.(type) {
case *ast.StructType:
t.ctxt.doStructMembers(n.Fields.List, t.Pkg, fn, q)
case *ast.InterfaceType:
t.ctxt.doInterfaceMembers(n.Methods.List, t.Pkg, fn)
}
} | go | func doTypeMembers(t Type, name string, fn func(*ast.Object), q *list.List) {
// strip off single indirection
// TODO: eliminate methods disallowed when indirected.
if u, ok := t.Node.(*ast.StarExpr); ok {
_, t = t.ctxt.exprType(u.X, false, t.Pkg)
}
if id, _ := t.Node.(*ast.Ident); id != nil && id.Obj != nil {
if scope, ok := id.Obj.Type.(*ast.Scope); ok {
doScope(scope, name, fn, t.Pkg)
}
}
u := t.Underlying(true)
switch n := u.Node.(type) {
case *ast.StructType:
t.ctxt.doStructMembers(n.Fields.List, t.Pkg, fn, q)
case *ast.InterfaceType:
t.ctxt.doInterfaceMembers(n.Methods.List, t.Pkg, fn)
}
} | [
"func",
"doTypeMembers",
"(",
"t",
"Type",
",",
"name",
"string",
",",
"fn",
"func",
"(",
"*",
"ast",
".",
"Object",
")",
",",
"q",
"*",
"list",
".",
"List",
")",
"{",
"// strip off single indirection",
"// TODO: eliminate methods disallowed when indirected.",
"if",
"u",
",",
"ok",
":=",
"t",
".",
"Node",
".",
"(",
"*",
"ast",
".",
"StarExpr",
")",
";",
"ok",
"{",
"_",
",",
"t",
"=",
"t",
".",
"ctxt",
".",
"exprType",
"(",
"u",
".",
"X",
",",
"false",
",",
"t",
".",
"Pkg",
")",
"\n",
"}",
"\n",
"if",
"id",
",",
"_",
":=",
"t",
".",
"Node",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"id",
"!=",
"nil",
"&&",
"id",
".",
"Obj",
"!=",
"nil",
"{",
"if",
"scope",
",",
"ok",
":=",
"id",
".",
"Obj",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"Scope",
")",
";",
"ok",
"{",
"doScope",
"(",
"scope",
",",
"name",
",",
"fn",
",",
"t",
".",
"Pkg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"u",
":=",
"t",
".",
"Underlying",
"(",
"true",
")",
"\n",
"switch",
"n",
":=",
"u",
".",
"Node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"StructType",
":",
"t",
".",
"ctxt",
".",
"doStructMembers",
"(",
"n",
".",
"Fields",
".",
"List",
",",
"t",
".",
"Pkg",
",",
"fn",
",",
"q",
")",
"\n\n",
"case",
"*",
"ast",
".",
"InterfaceType",
":",
"t",
".",
"ctxt",
".",
"doInterfaceMembers",
"(",
"n",
".",
"Methods",
".",
"List",
",",
"t",
".",
"Pkg",
",",
"fn",
")",
"\n",
"}",
"\n",
"}"
] | // doTypeMembers calls fn for each member of the given type,
// at one level only. Unnamed members are pushed onto the queue. | [
"doTypeMembers",
"calls",
"fn",
"for",
"each",
"member",
"of",
"the",
"given",
"type",
"at",
"one",
"level",
"only",
".",
"Unnamed",
"members",
"are",
"pushed",
"onto",
"the",
"queue",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L560-L579 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | unnamedFieldName | func unnamedFieldName(t ast.Node) *ast.Ident {
switch t := t.(type) {
case *ast.Ident:
return t
case *ast.SelectorExpr:
return t.Sel
case *ast.StarExpr:
return unnamedFieldName(t.X)
}
panic("no name found for unnamed field")
} | go | func unnamedFieldName(t ast.Node) *ast.Ident {
switch t := t.(type) {
case *ast.Ident:
return t
case *ast.SelectorExpr:
return t.Sel
case *ast.StarExpr:
return unnamedFieldName(t.X)
}
panic("no name found for unnamed field")
} | [
"func",
"unnamedFieldName",
"(",
"t",
"ast",
".",
"Node",
")",
"*",
"ast",
".",
"Ident",
"{",
"switch",
"t",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"Ident",
":",
"return",
"t",
"\n\n",
"case",
"*",
"ast",
".",
"SelectorExpr",
":",
"return",
"t",
".",
"Sel",
"\n\n",
"case",
"*",
"ast",
".",
"StarExpr",
":",
"return",
"unnamedFieldName",
"(",
"t",
".",
"X",
")",
"\n",
"}",
"\n\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // unnamedFieldName returns the field name for
// an unnamed field with its type given by ast node t.
// | [
"unnamedFieldName",
"returns",
"the",
"field",
"name",
"for",
"an",
"unnamed",
"field",
"with",
"its",
"type",
"given",
"by",
"ast",
"node",
"t",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L635-L648 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | doScope | func doScope(s *ast.Scope, name string, fn func(*ast.Object), pkg string) {
if s == nil {
return
}
if name != "" {
if obj := s.Lookup(name); obj != nil {
fn(obj)
}
return
}
for _, obj := range s.Objects {
if obj.Kind == ast.Bad || pkg != "" && !ast.IsExported(obj.Name) {
continue
}
fn(obj)
}
} | go | func doScope(s *ast.Scope, name string, fn func(*ast.Object), pkg string) {
if s == nil {
return
}
if name != "" {
if obj := s.Lookup(name); obj != nil {
fn(obj)
}
return
}
for _, obj := range s.Objects {
if obj.Kind == ast.Bad || pkg != "" && !ast.IsExported(obj.Name) {
continue
}
fn(obj)
}
} | [
"func",
"doScope",
"(",
"s",
"*",
"ast",
".",
"Scope",
",",
"name",
"string",
",",
"fn",
"func",
"(",
"*",
"ast",
".",
"Object",
")",
",",
"pkg",
"string",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"if",
"obj",
":=",
"s",
".",
"Lookup",
"(",
"name",
")",
";",
"obj",
"!=",
"nil",
"{",
"fn",
"(",
"obj",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"s",
".",
"Objects",
"{",
"if",
"obj",
".",
"Kind",
"==",
"ast",
".",
"Bad",
"||",
"pkg",
"!=",
"\"",
"\"",
"&&",
"!",
"ast",
".",
"IsExported",
"(",
"obj",
".",
"Name",
")",
"{",
"continue",
"\n",
"}",
"\n",
"fn",
"(",
"obj",
")",
"\n",
"}",
"\n",
"}"
] | // doScope iterates through all the functions in the given scope, at
// the top level only. | [
"doScope",
"iterates",
"through",
"all",
"the",
"functions",
"in",
"the",
"given",
"scope",
"at",
"the",
"top",
"level",
"only",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L652-L668 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | Underlying | func (typ Type) Underlying(all bool) Type {
for {
id, _ := typ.Node.(*ast.Ident)
if id == nil || id.Obj == nil {
break
}
_, typNode := splitDecl(id.Obj, id)
_, t := typ.ctxt.exprType(typNode, false, typ.Pkg)
if t.Kind != ast.Typ {
return badType
}
typ.Node = t.Node
typ.Pkg = t.Pkg
if !all {
break
}
}
return typ
} | go | func (typ Type) Underlying(all bool) Type {
for {
id, _ := typ.Node.(*ast.Ident)
if id == nil || id.Obj == nil {
break
}
_, typNode := splitDecl(id.Obj, id)
_, t := typ.ctxt.exprType(typNode, false, typ.Pkg)
if t.Kind != ast.Typ {
return badType
}
typ.Node = t.Node
typ.Pkg = t.Pkg
if !all {
break
}
}
return typ
} | [
"func",
"(",
"typ",
"Type",
")",
"Underlying",
"(",
"all",
"bool",
")",
"Type",
"{",
"for",
"{",
"id",
",",
"_",
":=",
"typ",
".",
"Node",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
"\n",
"if",
"id",
"==",
"nil",
"||",
"id",
".",
"Obj",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"_",
",",
"typNode",
":=",
"splitDecl",
"(",
"id",
".",
"Obj",
",",
"id",
")",
"\n",
"_",
",",
"t",
":=",
"typ",
".",
"ctxt",
".",
"exprType",
"(",
"typNode",
",",
"false",
",",
"typ",
".",
"Pkg",
")",
"\n",
"if",
"t",
".",
"Kind",
"!=",
"ast",
".",
"Typ",
"{",
"return",
"badType",
"\n",
"}",
"\n",
"typ",
".",
"Node",
"=",
"t",
".",
"Node",
"\n",
"typ",
".",
"Pkg",
"=",
"t",
".",
"Pkg",
"\n",
"if",
"!",
"all",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"typ",
"\n",
"}"
] | // If typ represents a named type, Underlying returns
// the type that it was defined as. If all is true,
// it repeats this process until the type is not
// a named type. | [
"If",
"typ",
"represents",
"a",
"named",
"type",
"Underlying",
"returns",
"the",
"type",
"that",
"it",
"was",
"defined",
"as",
".",
"If",
"all",
"is",
"true",
"it",
"repeats",
"this",
"process",
"until",
"the",
"type",
"is",
"not",
"a",
"named",
"type",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L674-L692 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | certify | func (ctxt *exprTypeContext) certify(typ ast.Node, kind ast.ObjKind, pkg string) Type {
_, t := ctxt.exprType(typ, false, pkg)
if t.Kind == ast.Typ {
return ctxt.newType(t.Node, kind, t.Pkg)
}
return badType
} | go | func (ctxt *exprTypeContext) certify(typ ast.Node, kind ast.ObjKind, pkg string) Type {
_, t := ctxt.exprType(typ, false, pkg)
if t.Kind == ast.Typ {
return ctxt.newType(t.Node, kind, t.Pkg)
}
return badType
} | [
"func",
"(",
"ctxt",
"*",
"exprTypeContext",
")",
"certify",
"(",
"typ",
"ast",
".",
"Node",
",",
"kind",
"ast",
".",
"ObjKind",
",",
"pkg",
"string",
")",
"Type",
"{",
"_",
",",
"t",
":=",
"ctxt",
".",
"exprType",
"(",
"typ",
",",
"false",
",",
"pkg",
")",
"\n",
"if",
"t",
".",
"Kind",
"==",
"ast",
".",
"Typ",
"{",
"return",
"ctxt",
".",
"newType",
"(",
"t",
".",
"Node",
",",
"kind",
",",
"t",
".",
"Pkg",
")",
"\n",
"}",
"\n",
"return",
"badType",
"\n",
"}"
] | // make sure that the type is really a type expression | [
"make",
"sure",
"that",
"the",
"type",
"is",
"really",
"a",
"type",
"expression"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L706-L712 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | exprName | func exprName(typ interface{}) *ast.Object {
switch t := noParens(typ).(type) {
case *ast.Ident:
return t.Obj
case *ast.Object:
return t
}
return nil
} | go | func exprName(typ interface{}) *ast.Object {
switch t := noParens(typ).(type) {
case *ast.Ident:
return t.Obj
case *ast.Object:
return t
}
return nil
} | [
"func",
"exprName",
"(",
"typ",
"interface",
"{",
"}",
")",
"*",
"ast",
".",
"Object",
"{",
"switch",
"t",
":=",
"noParens",
"(",
"typ",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"Ident",
":",
"return",
"t",
".",
"Obj",
"\n",
"case",
"*",
"ast",
".",
"Object",
":",
"return",
"t",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // If n represents a single identifier, exprName returns its object. | [
"If",
"n",
"represents",
"a",
"single",
"identifier",
"exprName",
"returns",
"its",
"object",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L715-L723 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | splitDecl | func splitDecl(obj *ast.Object, id *ast.Ident) (expr, typ ast.Node) {
switch decl := obj.Decl.(type) {
case nil:
return nil, nil
case *ast.ValueSpec:
return splitVarDecl(obj.Name, decl.Names, decl.Values, decl.Type)
case *ast.TypeSpec:
return nil, decl.Type
case *ast.FuncDecl:
if decl.Recv != nil {
return decl, decl.Type
}
return decl.Body, decl.Type
case *ast.Field:
return nil, decl.Type
case *ast.LabeledStmt:
return decl, nil
case *ast.ImportSpec:
return nil, decl
case *ast.AssignStmt:
return splitVarDecl(obj.Name, exprsToIdents(decl.Lhs), decl.Rhs, nil)
case *ast.GenDecl:
if decl.Tok == token.CONST {
return splitConstDecl(obj.Name, decl)
}
case *ast.TypeSwitchStmt:
expr := decl.Assign.(*ast.AssignStmt).Rhs[0].(*ast.TypeAssertExpr).X
for _, stmt := range decl.Body.List {
tcase := stmt.(*ast.CaseClause)
for _, stmt := range tcase.Body {
if containsNode(stmt, id) {
if len(tcase.List) == 1 {
return expr, tcase.List[0]
}
return expr, nil
}
}
}
return expr, nil
}
debugp("unknown decl type %T %v", obj.Decl, obj.Decl)
return nil, nil
} | go | func splitDecl(obj *ast.Object, id *ast.Ident) (expr, typ ast.Node) {
switch decl := obj.Decl.(type) {
case nil:
return nil, nil
case *ast.ValueSpec:
return splitVarDecl(obj.Name, decl.Names, decl.Values, decl.Type)
case *ast.TypeSpec:
return nil, decl.Type
case *ast.FuncDecl:
if decl.Recv != nil {
return decl, decl.Type
}
return decl.Body, decl.Type
case *ast.Field:
return nil, decl.Type
case *ast.LabeledStmt:
return decl, nil
case *ast.ImportSpec:
return nil, decl
case *ast.AssignStmt:
return splitVarDecl(obj.Name, exprsToIdents(decl.Lhs), decl.Rhs, nil)
case *ast.GenDecl:
if decl.Tok == token.CONST {
return splitConstDecl(obj.Name, decl)
}
case *ast.TypeSwitchStmt:
expr := decl.Assign.(*ast.AssignStmt).Rhs[0].(*ast.TypeAssertExpr).X
for _, stmt := range decl.Body.List {
tcase := stmt.(*ast.CaseClause)
for _, stmt := range tcase.Body {
if containsNode(stmt, id) {
if len(tcase.List) == 1 {
return expr, tcase.List[0]
}
return expr, nil
}
}
}
return expr, nil
}
debugp("unknown decl type %T %v", obj.Decl, obj.Decl)
return nil, nil
} | [
"func",
"splitDecl",
"(",
"obj",
"*",
"ast",
".",
"Object",
",",
"id",
"*",
"ast",
".",
"Ident",
")",
"(",
"expr",
",",
"typ",
"ast",
".",
"Node",
")",
"{",
"switch",
"decl",
":=",
"obj",
".",
"Decl",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"nil",
",",
"nil",
"\n",
"case",
"*",
"ast",
".",
"ValueSpec",
":",
"return",
"splitVarDecl",
"(",
"obj",
".",
"Name",
",",
"decl",
".",
"Names",
",",
"decl",
".",
"Values",
",",
"decl",
".",
"Type",
")",
"\n\n",
"case",
"*",
"ast",
".",
"TypeSpec",
":",
"return",
"nil",
",",
"decl",
".",
"Type",
"\n\n",
"case",
"*",
"ast",
".",
"FuncDecl",
":",
"if",
"decl",
".",
"Recv",
"!=",
"nil",
"{",
"return",
"decl",
",",
"decl",
".",
"Type",
"\n",
"}",
"\n",
"return",
"decl",
".",
"Body",
",",
"decl",
".",
"Type",
"\n\n",
"case",
"*",
"ast",
".",
"Field",
":",
"return",
"nil",
",",
"decl",
".",
"Type",
"\n\n",
"case",
"*",
"ast",
".",
"LabeledStmt",
":",
"return",
"decl",
",",
"nil",
"\n\n",
"case",
"*",
"ast",
".",
"ImportSpec",
":",
"return",
"nil",
",",
"decl",
"\n\n",
"case",
"*",
"ast",
".",
"AssignStmt",
":",
"return",
"splitVarDecl",
"(",
"obj",
".",
"Name",
",",
"exprsToIdents",
"(",
"decl",
".",
"Lhs",
")",
",",
"decl",
".",
"Rhs",
",",
"nil",
")",
"\n\n",
"case",
"*",
"ast",
".",
"GenDecl",
":",
"if",
"decl",
".",
"Tok",
"==",
"token",
".",
"CONST",
"{",
"return",
"splitConstDecl",
"(",
"obj",
".",
"Name",
",",
"decl",
")",
"\n",
"}",
"\n",
"case",
"*",
"ast",
".",
"TypeSwitchStmt",
":",
"expr",
":=",
"decl",
".",
"Assign",
".",
"(",
"*",
"ast",
".",
"AssignStmt",
")",
".",
"Rhs",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"TypeAssertExpr",
")",
".",
"X",
"\n",
"for",
"_",
",",
"stmt",
":=",
"range",
"decl",
".",
"Body",
".",
"List",
"{",
"tcase",
":=",
"stmt",
".",
"(",
"*",
"ast",
".",
"CaseClause",
")",
"\n",
"for",
"_",
",",
"stmt",
":=",
"range",
"tcase",
".",
"Body",
"{",
"if",
"containsNode",
"(",
"stmt",
",",
"id",
")",
"{",
"if",
"len",
"(",
"tcase",
".",
"List",
")",
"==",
"1",
"{",
"return",
"expr",
",",
"tcase",
".",
"List",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"expr",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"expr",
",",
"nil",
"\n",
"}",
"\n",
"debugp",
"(",
"\"",
"\"",
",",
"obj",
".",
"Decl",
",",
"obj",
".",
"Decl",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // splitDecl splits obj.Decl and returns the expression part and the type part.
// Either may be nil, but not both if the declaration is value.
//
// If id is non-nil, it gives the referring identifier. This is only used
// to determine which node in a type switch is being referred to.
// | [
"splitDecl",
"splits",
"obj",
".",
"Decl",
"and",
"returns",
"the",
"expression",
"part",
"and",
"the",
"type",
"part",
".",
"Either",
"may",
"be",
"nil",
"but",
"not",
"both",
"if",
"the",
"declaration",
"is",
"value",
".",
"If",
"id",
"is",
"non",
"-",
"nil",
"it",
"gives",
"the",
"referring",
"identifier",
".",
"This",
"is",
"only",
"used",
"to",
"determine",
"which",
"node",
"in",
"a",
"type",
"switch",
"is",
"being",
"referred",
"to",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L746-L795 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | splitVarDecl | func splitVarDecl(name string, names []*ast.Ident, values []ast.Expr, vtype ast.Expr) (expr, typ ast.Node) {
if len(names) == 1 && len(values) == 1 {
return values[0], vtype
}
p := 0
for i, aname := range names {
if aname != nil && aname.Name == name {
p = i
break
}
}
if len(values) > 1 {
return values[p], vtype
}
if len(values) == 0 {
return nil, vtype
}
return &exprIndex{p, values[0]}, vtype
} | go | func splitVarDecl(name string, names []*ast.Ident, values []ast.Expr, vtype ast.Expr) (expr, typ ast.Node) {
if len(names) == 1 && len(values) == 1 {
return values[0], vtype
}
p := 0
for i, aname := range names {
if aname != nil && aname.Name == name {
p = i
break
}
}
if len(values) > 1 {
return values[p], vtype
}
if len(values) == 0 {
return nil, vtype
}
return &exprIndex{p, values[0]}, vtype
} | [
"func",
"splitVarDecl",
"(",
"name",
"string",
",",
"names",
"[",
"]",
"*",
"ast",
".",
"Ident",
",",
"values",
"[",
"]",
"ast",
".",
"Expr",
",",
"vtype",
"ast",
".",
"Expr",
")",
"(",
"expr",
",",
"typ",
"ast",
".",
"Node",
")",
"{",
"if",
"len",
"(",
"names",
")",
"==",
"1",
"&&",
"len",
"(",
"values",
")",
"==",
"1",
"{",
"return",
"values",
"[",
"0",
"]",
",",
"vtype",
"\n",
"}",
"\n",
"p",
":=",
"0",
"\n",
"for",
"i",
",",
"aname",
":=",
"range",
"names",
"{",
"if",
"aname",
"!=",
"nil",
"&&",
"aname",
".",
"Name",
"==",
"name",
"{",
"p",
"=",
"i",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"values",
")",
">",
"1",
"{",
"return",
"values",
"[",
"p",
"]",
",",
"vtype",
"\n",
"}",
"\n",
"if",
"len",
"(",
"values",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"vtype",
"\n",
"}",
"\n",
"return",
"&",
"exprIndex",
"{",
"p",
",",
"values",
"[",
"0",
"]",
"}",
",",
"vtype",
"\n",
"}"
] | // splitVarDecl finds the declaration expression and type from a
// variable declaration (short form or long form). | [
"splitVarDecl",
"finds",
"the",
"declaration",
"expression",
"and",
"type",
"from",
"a",
"variable",
"declaration",
"(",
"short",
"form",
"or",
"long",
"form",
")",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L799-L817 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | splitConstDecl | func splitConstDecl(name string, decl *ast.GenDecl) (expr, typ ast.Node) {
var lastSpec *ast.ValueSpec // last spec with >0 values.
for _, spec := range decl.Specs {
vspec := spec.(*ast.ValueSpec)
if len(vspec.Values) > 0 {
lastSpec = vspec
}
for i, vname := range vspec.Names {
if vname.Name == name {
if i < len(lastSpec.Values) {
return lastSpec.Values[i], lastSpec.Type
}
return nil, lastSpec.Type
}
}
}
return nil, nil
} | go | func splitConstDecl(name string, decl *ast.GenDecl) (expr, typ ast.Node) {
var lastSpec *ast.ValueSpec // last spec with >0 values.
for _, spec := range decl.Specs {
vspec := spec.(*ast.ValueSpec)
if len(vspec.Values) > 0 {
lastSpec = vspec
}
for i, vname := range vspec.Names {
if vname.Name == name {
if i < len(lastSpec.Values) {
return lastSpec.Values[i], lastSpec.Type
}
return nil, lastSpec.Type
}
}
}
return nil, nil
} | [
"func",
"splitConstDecl",
"(",
"name",
"string",
",",
"decl",
"*",
"ast",
".",
"GenDecl",
")",
"(",
"expr",
",",
"typ",
"ast",
".",
"Node",
")",
"{",
"var",
"lastSpec",
"*",
"ast",
".",
"ValueSpec",
"// last spec with >0 values.",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"decl",
".",
"Specs",
"{",
"vspec",
":=",
"spec",
".",
"(",
"*",
"ast",
".",
"ValueSpec",
")",
"\n",
"if",
"len",
"(",
"vspec",
".",
"Values",
")",
">",
"0",
"{",
"lastSpec",
"=",
"vspec",
"\n",
"}",
"\n",
"for",
"i",
",",
"vname",
":=",
"range",
"vspec",
".",
"Names",
"{",
"if",
"vname",
".",
"Name",
"==",
"name",
"{",
"if",
"i",
"<",
"len",
"(",
"lastSpec",
".",
"Values",
")",
"{",
"return",
"lastSpec",
".",
"Values",
"[",
"i",
"]",
",",
"lastSpec",
".",
"Type",
"\n",
"}",
"\n",
"return",
"nil",
",",
"lastSpec",
".",
"Type",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Constant declarations can omit the type, so the declaration for
// a const may be the entire GenDecl - we find the relevant
// clause and infer the type and expression. | [
"Constant",
"declarations",
"can",
"omit",
"the",
"type",
"so",
"the",
"declaration",
"for",
"a",
"const",
"may",
"be",
"the",
"entire",
"GenDecl",
"-",
"we",
"find",
"the",
"relevant",
"clause",
"and",
"infer",
"the",
"type",
"and",
"expression",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L830-L847 |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | containsNode | func containsNode(node, x ast.Node) (found bool) {
ast.Walk(funcVisitor(func(n ast.Node) bool {
if !found {
found = n == x
}
return !found
}),
node)
return
} | go | func containsNode(node, x ast.Node) (found bool) {
ast.Walk(funcVisitor(func(n ast.Node) bool {
if !found {
found = n == x
}
return !found
}),
node)
return
} | [
"func",
"containsNode",
"(",
"node",
",",
"x",
"ast",
".",
"Node",
")",
"(",
"found",
"bool",
")",
"{",
"ast",
".",
"Walk",
"(",
"funcVisitor",
"(",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"if",
"!",
"found",
"{",
"found",
"=",
"n",
"==",
"x",
"\n",
"}",
"\n",
"return",
"!",
"found",
"\n",
"}",
")",
",",
"node",
")",
"\n",
"return",
"\n",
"}"
] | // constainsNode returns true if x is found somewhere
// inside node. | [
"constainsNode",
"returns",
"true",
"if",
"x",
"is",
"found",
"somewhere",
"inside",
"node",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L862-L871 |
sourcegraph/go-langserver | langserver/lint.go | lint | func (h *LangHandler) lint(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, args []string, files []string) error {
if h.linter == nil {
return nil
}
diags, err := h.linter.Lint(ctx, bctx, args...)
if err != nil {
return err
}
return h.publishDiagnostics(ctx, conn, diags, h.config.LintTool, files)
} | go | func (h *LangHandler) lint(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, args []string, files []string) error {
if h.linter == nil {
return nil
}
diags, err := h.linter.Lint(ctx, bctx, args...)
if err != nil {
return err
}
return h.publishDiagnostics(ctx, conn, diags, h.config.LintTool, files)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"lint",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"args",
"[",
"]",
"string",
",",
"files",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"h",
".",
"linter",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"diags",
",",
"err",
":=",
"h",
".",
"linter",
".",
"Lint",
"(",
"ctx",
",",
"bctx",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"h",
".",
"publishDiagnostics",
"(",
"ctx",
",",
"conn",
",",
"diags",
",",
"h",
".",
"config",
".",
"LintTool",
",",
"files",
")",
"\n",
"}"
] | // lint runs the configured lint command with the given arguments then published the
// results as diagnostics. | [
"lint",
"runs",
"the",
"configured",
"lint",
"command",
"with",
"the",
"given",
"arguments",
"then",
"published",
"the",
"results",
"as",
"diagnostics",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lint.go#L34-L45 |
sourcegraph/go-langserver | langserver/lint.go | lintPackage | func (h *LangHandler) lintPackage(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, uri lsp.DocumentURI) error {
filename := h.FilePath(uri)
pkg, err := ContainingPackage(h.BuildContext(ctx), filename, h.RootFSPath)
if err != nil {
return err
}
files := make([]string, 0, len(pkg.GoFiles))
for _, f := range pkg.GoFiles {
files = append(files, path.Join(pkg.Dir, f))
}
return h.lint(ctx, bctx, conn, []string{path.Dir(filename)}, files)
} | go | func (h *LangHandler) lintPackage(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, uri lsp.DocumentURI) error {
filename := h.FilePath(uri)
pkg, err := ContainingPackage(h.BuildContext(ctx), filename, h.RootFSPath)
if err != nil {
return err
}
files := make([]string, 0, len(pkg.GoFiles))
for _, f := range pkg.GoFiles {
files = append(files, path.Join(pkg.Dir, f))
}
return h.lint(ctx, bctx, conn, []string{path.Dir(filename)}, files)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"lintPackage",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"uri",
"lsp",
".",
"DocumentURI",
")",
"error",
"{",
"filename",
":=",
"h",
".",
"FilePath",
"(",
"uri",
")",
"\n",
"pkg",
",",
"err",
":=",
"ContainingPackage",
"(",
"h",
".",
"BuildContext",
"(",
"ctx",
")",
",",
"filename",
",",
"h",
".",
"RootFSPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"files",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"pkg",
".",
"GoFiles",
")",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"pkg",
".",
"GoFiles",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"path",
".",
"Join",
"(",
"pkg",
".",
"Dir",
",",
"f",
")",
")",
"\n",
"}",
"\n",
"return",
"h",
".",
"lint",
"(",
"ctx",
",",
"bctx",
",",
"conn",
",",
"[",
"]",
"string",
"{",
"path",
".",
"Dir",
"(",
"filename",
")",
"}",
",",
"files",
")",
"\n",
"}"
] | // lintPackage runs LangHandler.lint for the package containing the uri. | [
"lintPackage",
"runs",
"LangHandler",
".",
"lint",
"for",
"the",
"package",
"containing",
"the",
"uri",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lint.go#L48-L60 |
sourcegraph/go-langserver | langserver/lint.go | lintWorkspace | func (h *LangHandler) lintWorkspace(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2) error {
var files []string
pkgs := tools.ListPkgsUnderDir(bctx, h.RootFSPath)
find := h.getFindPackageFunc()
for _, pkg := range pkgs {
p, err := find(ctx, bctx, pkg, h.RootFSPath, h.RootFSPath, 0)
if err != nil {
if _, ok := err.(*build.NoGoError); ok {
continue
}
if _, ok := err.(*build.MultiplePackageError); ok {
continue
}
return err
}
for _, f := range p.GoFiles {
files = append(files, path.Join(p.Dir, f))
}
}
return h.lint(ctx, bctx, conn, []string{path.Join(h.RootFSPath, "/...")}, files)
} | go | func (h *LangHandler) lintWorkspace(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2) error {
var files []string
pkgs := tools.ListPkgsUnderDir(bctx, h.RootFSPath)
find := h.getFindPackageFunc()
for _, pkg := range pkgs {
p, err := find(ctx, bctx, pkg, h.RootFSPath, h.RootFSPath, 0)
if err != nil {
if _, ok := err.(*build.NoGoError); ok {
continue
}
if _, ok := err.(*build.MultiplePackageError); ok {
continue
}
return err
}
for _, f := range p.GoFiles {
files = append(files, path.Join(p.Dir, f))
}
}
return h.lint(ctx, bctx, conn, []string{path.Join(h.RootFSPath, "/...")}, files)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"lintWorkspace",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
")",
"error",
"{",
"var",
"files",
"[",
"]",
"string",
"\n",
"pkgs",
":=",
"tools",
".",
"ListPkgsUnderDir",
"(",
"bctx",
",",
"h",
".",
"RootFSPath",
")",
"\n",
"find",
":=",
"h",
".",
"getFindPackageFunc",
"(",
")",
"\n",
"for",
"_",
",",
"pkg",
":=",
"range",
"pkgs",
"{",
"p",
",",
"err",
":=",
"find",
"(",
"ctx",
",",
"bctx",
",",
"pkg",
",",
"h",
".",
"RootFSPath",
",",
"h",
".",
"RootFSPath",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"build",
".",
"NoGoError",
")",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"build",
".",
"MultiplePackageError",
")",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"p",
".",
"GoFiles",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"path",
".",
"Join",
"(",
"p",
".",
"Dir",
",",
"f",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"h",
".",
"lint",
"(",
"ctx",
",",
"bctx",
",",
"conn",
",",
"[",
"]",
"string",
"{",
"path",
".",
"Join",
"(",
"h",
".",
"RootFSPath",
",",
"\"",
"\"",
")",
"}",
",",
"files",
")",
"\n",
"}"
] | // lintWorkspace runs LangHandler.lint for the entire workspace | [
"lintWorkspace",
"runs",
"LangHandler",
".",
"lint",
"for",
"the",
"entire",
"workspace"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lint.go#L63-L84 |
sourcegraph/go-langserver | pkg/tools/importgraph.go | BuildReverseImportGraph | func BuildReverseImportGraph(ctxt *build.Context, findPackage FindPackageFunc, dir string) importgraph.Graph {
type importEdge struct {
from, to string
}
ch := make(chan importEdge)
go func() {
sema := make(chan int, 20) // I/O concurrency limiting semaphore
var wg sync.WaitGroup
for _, path := range ListPkgsUnderDir(ctxt, dir) {
wg.Add(1)
go func(path string) {
defer wg.Done()
sema <- 1
// Even in error cases, Import usually returns a package.
bp, _ := findPackage(ctxt, path, "", 0)
<-sema
memo := make(map[string]string)
absolutize := func(path string) string {
canon, ok := memo[path]
if !ok {
sema <- 1
bp2, _ := findPackage(ctxt, path, bp.Dir, build.FindOnly)
<-sema
if bp2 != nil {
canon = bp2.ImportPath
} else {
canon = path
}
memo[path] = canon
}
return canon
}
if bp != nil {
for _, imp := range bp.Imports {
ch <- importEdge{path, absolutize(imp)}
}
for _, imp := range bp.TestImports {
ch <- importEdge{path, absolutize(imp)}
}
for _, imp := range bp.XTestImports {
ch <- importEdge{path, absolutize(imp)}
}
}
}(path)
}
wg.Wait()
close(ch)
}()
reverse := make(importgraph.Graph)
for e := range ch {
if e.to == "C" {
continue // "C" is fake
}
addEdge(reverse, e.to, e.from)
}
return reverse
} | go | func BuildReverseImportGraph(ctxt *build.Context, findPackage FindPackageFunc, dir string) importgraph.Graph {
type importEdge struct {
from, to string
}
ch := make(chan importEdge)
go func() {
sema := make(chan int, 20) // I/O concurrency limiting semaphore
var wg sync.WaitGroup
for _, path := range ListPkgsUnderDir(ctxt, dir) {
wg.Add(1)
go func(path string) {
defer wg.Done()
sema <- 1
// Even in error cases, Import usually returns a package.
bp, _ := findPackage(ctxt, path, "", 0)
<-sema
memo := make(map[string]string)
absolutize := func(path string) string {
canon, ok := memo[path]
if !ok {
sema <- 1
bp2, _ := findPackage(ctxt, path, bp.Dir, build.FindOnly)
<-sema
if bp2 != nil {
canon = bp2.ImportPath
} else {
canon = path
}
memo[path] = canon
}
return canon
}
if bp != nil {
for _, imp := range bp.Imports {
ch <- importEdge{path, absolutize(imp)}
}
for _, imp := range bp.TestImports {
ch <- importEdge{path, absolutize(imp)}
}
for _, imp := range bp.XTestImports {
ch <- importEdge{path, absolutize(imp)}
}
}
}(path)
}
wg.Wait()
close(ch)
}()
reverse := make(importgraph.Graph)
for e := range ch {
if e.to == "C" {
continue // "C" is fake
}
addEdge(reverse, e.to, e.from)
}
return reverse
} | [
"func",
"BuildReverseImportGraph",
"(",
"ctxt",
"*",
"build",
".",
"Context",
",",
"findPackage",
"FindPackageFunc",
",",
"dir",
"string",
")",
"importgraph",
".",
"Graph",
"{",
"type",
"importEdge",
"struct",
"{",
"from",
",",
"to",
"string",
"\n",
"}",
"\n\n",
"ch",
":=",
"make",
"(",
"chan",
"importEdge",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"sema",
":=",
"make",
"(",
"chan",
"int",
",",
"20",
")",
"// I/O concurrency limiting semaphore",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"ListPkgsUnderDir",
"(",
"ctxt",
",",
"dir",
")",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"path",
"string",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"sema",
"<-",
"1",
"\n",
"// Even in error cases, Import usually returns a package.",
"bp",
",",
"_",
":=",
"findPackage",
"(",
"ctxt",
",",
"path",
",",
"\"",
"\"",
",",
"0",
")",
"\n",
"<-",
"sema",
"\n\n",
"memo",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"absolutize",
":=",
"func",
"(",
"path",
"string",
")",
"string",
"{",
"canon",
",",
"ok",
":=",
"memo",
"[",
"path",
"]",
"\n",
"if",
"!",
"ok",
"{",
"sema",
"<-",
"1",
"\n",
"bp2",
",",
"_",
":=",
"findPackage",
"(",
"ctxt",
",",
"path",
",",
"bp",
".",
"Dir",
",",
"build",
".",
"FindOnly",
")",
"\n",
"<-",
"sema",
"\n\n",
"if",
"bp2",
"!=",
"nil",
"{",
"canon",
"=",
"bp2",
".",
"ImportPath",
"\n",
"}",
"else",
"{",
"canon",
"=",
"path",
"\n",
"}",
"\n",
"memo",
"[",
"path",
"]",
"=",
"canon",
"\n",
"}",
"\n",
"return",
"canon",
"\n",
"}",
"\n\n",
"if",
"bp",
"!=",
"nil",
"{",
"for",
"_",
",",
"imp",
":=",
"range",
"bp",
".",
"Imports",
"{",
"ch",
"<-",
"importEdge",
"{",
"path",
",",
"absolutize",
"(",
"imp",
")",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"imp",
":=",
"range",
"bp",
".",
"TestImports",
"{",
"ch",
"<-",
"importEdge",
"{",
"path",
",",
"absolutize",
"(",
"imp",
")",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"imp",
":=",
"range",
"bp",
".",
"XTestImports",
"{",
"ch",
"<-",
"importEdge",
"{",
"path",
",",
"absolutize",
"(",
"imp",
")",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"(",
"path",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}",
"(",
")",
"\n\n",
"reverse",
":=",
"make",
"(",
"importgraph",
".",
"Graph",
")",
"\n\n",
"for",
"e",
":=",
"range",
"ch",
"{",
"if",
"e",
".",
"to",
"==",
"\"",
"\"",
"{",
"continue",
"// \"C\" is fake",
"\n",
"}",
"\n",
"addEdge",
"(",
"reverse",
",",
"e",
".",
"to",
",",
"e",
".",
"from",
")",
"\n",
"}",
"\n\n",
"return",
"reverse",
"\n",
"}"
] | // BuildReverseImportGraph is much like importgraph.Build, except:
// * it only returns the reverse graph
// * it does not return errors
// * it uses a custom FindPackageFunc
// * it only searches pkgs under dir (but graph can contain pkgs outside of dir)
// * it searches xtest pkgs as well
//
// The code is adapted from the original function. | [
"BuildReverseImportGraph",
"is",
"much",
"like",
"importgraph",
".",
"Build",
"except",
":",
"*",
"it",
"only",
"returns",
"the",
"reverse",
"graph",
"*",
"it",
"does",
"not",
"return",
"errors",
"*",
"it",
"uses",
"a",
"custom",
"FindPackageFunc",
"*",
"it",
"only",
"searches",
"pkgs",
"under",
"dir",
"(",
"but",
"graph",
"can",
"contain",
"pkgs",
"outside",
"of",
"dir",
")",
"*",
"it",
"searches",
"xtest",
"pkgs",
"as",
"well",
"The",
"code",
"is",
"adapted",
"from",
"the",
"original",
"function",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/pkg/tools/importgraph.go#L27-L93 |
sourcegraph/go-langserver | langserver/diagnostics.go | sync | func (p *diagnosticsCache) sync(update func(diagnostics) diagnostics, compare func(oldDiagnostics, newDiagnostics diagnostics) (publish diagnostics)) (publish diagnostics) {
p.mu.Lock()
defer p.mu.Unlock()
if p.cache == nil {
p.cache = diagnostics{}
}
newCache := update(p.cache)
publish = compare(p.cache, newCache)
p.cache = newCache
return publish
} | go | func (p *diagnosticsCache) sync(update func(diagnostics) diagnostics, compare func(oldDiagnostics, newDiagnostics diagnostics) (publish diagnostics)) (publish diagnostics) {
p.mu.Lock()
defer p.mu.Unlock()
if p.cache == nil {
p.cache = diagnostics{}
}
newCache := update(p.cache)
publish = compare(p.cache, newCache)
p.cache = newCache
return publish
} | [
"func",
"(",
"p",
"*",
"diagnosticsCache",
")",
"sync",
"(",
"update",
"func",
"(",
"diagnostics",
")",
"diagnostics",
",",
"compare",
"func",
"(",
"oldDiagnostics",
",",
"newDiagnostics",
"diagnostics",
")",
"(",
"publish",
"diagnostics",
")",
")",
"(",
"publish",
"diagnostics",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"p",
".",
"cache",
"==",
"nil",
"{",
"p",
".",
"cache",
"=",
"diagnostics",
"{",
"}",
"\n",
"}",
"\n\n",
"newCache",
":=",
"update",
"(",
"p",
".",
"cache",
")",
"\n",
"publish",
"=",
"compare",
"(",
"p",
".",
"cache",
",",
"newCache",
")",
"\n",
"p",
".",
"cache",
"=",
"newCache",
"\n",
"return",
"publish",
"\n",
"}"
] | // sync updates the diagnosticsCache and returns diagnostics need to be
// published.
//
// When a file no longer has any diagnostics the file will be removed from
// the cache. The removed file will be included in the returned diagnostics
// in order to clear the client.
//
// sync is thread safe and will only allow one go routine to modify the cache
// at a time. | [
"sync",
"updates",
"the",
"diagnosticsCache",
"and",
"returns",
"diagnostics",
"need",
"to",
"be",
"published",
".",
"When",
"a",
"file",
"no",
"longer",
"has",
"any",
"diagnostics",
"the",
"file",
"will",
"be",
"removed",
"from",
"the",
"cache",
".",
"The",
"removed",
"file",
"will",
"be",
"included",
"in",
"the",
"returned",
"diagnostics",
"in",
"order",
"to",
"clear",
"the",
"client",
".",
"sync",
"is",
"thread",
"safe",
"and",
"will",
"only",
"allow",
"one",
"go",
"routine",
"to",
"modify",
"the",
"cache",
"at",
"a",
"time",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/diagnostics.go#L42-L54 |
sourcegraph/go-langserver | langserver/diagnostics.go | publishDiagnostics | func (h *LangHandler) publishDiagnostics(ctx context.Context, conn jsonrpc2.JSONRPC2, diags diagnostics, source string, files []string) error {
if !h.config.DiagnosticsEnabled {
return nil
}
if diags == nil {
diags = diagnostics{}
}
publish := h.diagnosticsCache.sync(
func(cached diagnostics) diagnostics {
return updateCachedDiagnostics(cached, diags, source, files)
},
func(oldDiagnostics, newDiagnostics diagnostics) (publish diagnostics) {
return compareCachedDiagnostics(oldDiagnostics, newDiagnostics, files)
},
)
for filename, diags := range publish {
params := lsp.PublishDiagnosticsParams{
URI: util.PathToURI(filename),
Diagnostics: make([]lsp.Diagnostic, len(diags)),
}
for i, d := range diags {
params.Diagnostics[i] = *d
}
if err := conn.Notify(ctx, "textDocument/publishDiagnostics", params); err != nil {
return err
}
}
return nil
} | go | func (h *LangHandler) publishDiagnostics(ctx context.Context, conn jsonrpc2.JSONRPC2, diags diagnostics, source string, files []string) error {
if !h.config.DiagnosticsEnabled {
return nil
}
if diags == nil {
diags = diagnostics{}
}
publish := h.diagnosticsCache.sync(
func(cached diagnostics) diagnostics {
return updateCachedDiagnostics(cached, diags, source, files)
},
func(oldDiagnostics, newDiagnostics diagnostics) (publish diagnostics) {
return compareCachedDiagnostics(oldDiagnostics, newDiagnostics, files)
},
)
for filename, diags := range publish {
params := lsp.PublishDiagnosticsParams{
URI: util.PathToURI(filename),
Diagnostics: make([]lsp.Diagnostic, len(diags)),
}
for i, d := range diags {
params.Diagnostics[i] = *d
}
if err := conn.Notify(ctx, "textDocument/publishDiagnostics", params); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"publishDiagnostics",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"diags",
"diagnostics",
",",
"source",
"string",
",",
"files",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"!",
"h",
".",
"config",
".",
"DiagnosticsEnabled",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"diags",
"==",
"nil",
"{",
"diags",
"=",
"diagnostics",
"{",
"}",
"\n",
"}",
"\n\n",
"publish",
":=",
"h",
".",
"diagnosticsCache",
".",
"sync",
"(",
"func",
"(",
"cached",
"diagnostics",
")",
"diagnostics",
"{",
"return",
"updateCachedDiagnostics",
"(",
"cached",
",",
"diags",
",",
"source",
",",
"files",
")",
"\n",
"}",
",",
"func",
"(",
"oldDiagnostics",
",",
"newDiagnostics",
"diagnostics",
")",
"(",
"publish",
"diagnostics",
")",
"{",
"return",
"compareCachedDiagnostics",
"(",
"oldDiagnostics",
",",
"newDiagnostics",
",",
"files",
")",
"\n",
"}",
",",
")",
"\n\n",
"for",
"filename",
",",
"diags",
":=",
"range",
"publish",
"{",
"params",
":=",
"lsp",
".",
"PublishDiagnosticsParams",
"{",
"URI",
":",
"util",
".",
"PathToURI",
"(",
"filename",
")",
",",
"Diagnostics",
":",
"make",
"(",
"[",
"]",
"lsp",
".",
"Diagnostic",
",",
"len",
"(",
"diags",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"d",
":=",
"range",
"diags",
"{",
"params",
".",
"Diagnostics",
"[",
"i",
"]",
"=",
"*",
"d",
"\n",
"}",
"\n",
"if",
"err",
":=",
"conn",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // publishDiagnostics sends diagnostic information (such as compile
// errors) to the client. | [
"publishDiagnostics",
"sends",
"diagnostic",
"information",
"(",
"such",
"as",
"compile",
"errors",
")",
"to",
"the",
"client",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/diagnostics.go#L58-L89 |
sourcegraph/go-langserver | langserver/diagnostics.go | compareCachedDiagnostics | func compareCachedDiagnostics(oldDiagnostics, newDiagnostics diagnostics, files []string) (publish diagnostics) {
publish = diagnostics{}
for _, f := range files {
_, inOld := oldDiagnostics[f]
diags, inNew := newDiagnostics[f]
if inOld && !inNew {
publish[f] = nil
continue
}
if inNew {
publish[f] = diags
}
}
return publish
} | go | func compareCachedDiagnostics(oldDiagnostics, newDiagnostics diagnostics, files []string) (publish diagnostics) {
publish = diagnostics{}
for _, f := range files {
_, inOld := oldDiagnostics[f]
diags, inNew := newDiagnostics[f]
if inOld && !inNew {
publish[f] = nil
continue
}
if inNew {
publish[f] = diags
}
}
return publish
} | [
"func",
"compareCachedDiagnostics",
"(",
"oldDiagnostics",
",",
"newDiagnostics",
"diagnostics",
",",
"files",
"[",
"]",
"string",
")",
"(",
"publish",
"diagnostics",
")",
"{",
"publish",
"=",
"diagnostics",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"_",
",",
"inOld",
":=",
"oldDiagnostics",
"[",
"f",
"]",
"\n",
"diags",
",",
"inNew",
":=",
"newDiagnostics",
"[",
"f",
"]",
"\n\n",
"if",
"inOld",
"&&",
"!",
"inNew",
"{",
"publish",
"[",
"f",
"]",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"inNew",
"{",
"publish",
"[",
"f",
"]",
"=",
"diags",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"publish",
"\n",
"}"
] | // compareCachedDiagnostics compares new and old diagnostics to determine
// what needs to be published. | [
"compareCachedDiagnostics",
"compares",
"new",
"and",
"old",
"diagnostics",
"to",
"determine",
"what",
"needs",
"to",
"be",
"published",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/diagnostics.go#L121-L138 |
sourcegraph/go-langserver | gituri/uri.go | Parse | func Parse(uriStr string) (*URI, error) {
u, err := url.Parse(uriStr)
if err != nil {
return nil, err
}
if !u.IsAbs() {
return nil, &url.Error{Op: "gituri.Parse", URL: uriStr, Err: errors.New("sourcegraph URI must be absolute")}
}
return &URI{*u}, nil
} | go | func Parse(uriStr string) (*URI, error) {
u, err := url.Parse(uriStr)
if err != nil {
return nil, err
}
if !u.IsAbs() {
return nil, &url.Error{Op: "gituri.Parse", URL: uriStr, Err: errors.New("sourcegraph URI must be absolute")}
}
return &URI{*u}, nil
} | [
"func",
"Parse",
"(",
"uriStr",
"string",
")",
"(",
"*",
"URI",
",",
"error",
")",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"uriStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"u",
".",
"IsAbs",
"(",
")",
"{",
"return",
"nil",
",",
"&",
"url",
".",
"Error",
"{",
"Op",
":",
"\"",
"\"",
",",
"URL",
":",
"uriStr",
",",
"Err",
":",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"}",
"\n",
"}",
"\n",
"return",
"&",
"URI",
"{",
"*",
"u",
"}",
",",
"nil",
"\n",
"}"
] | // Parse parses uriStr to a URI. The uriStr should be an absolute URL. | [
"Parse",
"parses",
"uriStr",
"to",
"a",
"URI",
".",
"The",
"uriStr",
"should",
"be",
"an",
"absolute",
"URL",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gituri/uri.go#L35-L44 |
sourcegraph/go-langserver | gituri/uri.go | CloneURL | func (u *URI) CloneURL() *url.URL {
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
}
} | go | func (u *URI) CloneURL() *url.URL {
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
}
} | [
"func",
"(",
"u",
"*",
"URI",
")",
"CloneURL",
"(",
")",
"*",
"url",
".",
"URL",
"{",
"return",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"u",
".",
"Scheme",
",",
"Host",
":",
"u",
".",
"Host",
",",
"Path",
":",
"u",
".",
"Path",
",",
"}",
"\n",
"}"
] | // CloneURL returns the repository clone URL component of the URI. | [
"CloneURL",
"returns",
"the",
"repository",
"clone",
"URL",
"component",
"of",
"the",
"URI",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gituri/uri.go#L47-L53 |
sourcegraph/go-langserver | gituri/uri.go | ResolveFilePath | func (u *URI) ResolveFilePath(p string) string {
return cleanPath(path.Join(u.FilePath(), strings.TrimPrefix(p, "/")))
} | go | func (u *URI) ResolveFilePath(p string) string {
return cleanPath(path.Join(u.FilePath(), strings.TrimPrefix(p, "/")))
} | [
"func",
"(",
"u",
"*",
"URI",
")",
"ResolveFilePath",
"(",
"p",
"string",
")",
"string",
"{",
"return",
"cleanPath",
"(",
"path",
".",
"Join",
"(",
"u",
".",
"FilePath",
"(",
")",
",",
"strings",
".",
"TrimPrefix",
"(",
"p",
",",
"\"",
"\"",
")",
")",
")",
"\n",
"}"
] | // ResolveFilePath returns the cleaned file path component obtained by
// appending p to the URI's file path. It is called "resolve" not
// "join" because it strips p's leading slash (if any). | [
"ResolveFilePath",
"returns",
"the",
"cleaned",
"file",
"path",
"component",
"obtained",
"by",
"appending",
"p",
"to",
"the",
"URI",
"s",
"file",
"path",
".",
"It",
"is",
"called",
"resolve",
"not",
"join",
"because",
"it",
"strips",
"p",
"s",
"leading",
"slash",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gituri/uri.go#L70-L72 |
sourcegraph/go-langserver | gituri/uri.go | WithFilePath | func (u *URI) WithFilePath(p string) *URI {
copy := *u
copy.Fragment = cleanPath(p)
return ©
} | go | func (u *URI) WithFilePath(p string) *URI {
copy := *u
copy.Fragment = cleanPath(p)
return ©
} | [
"func",
"(",
"u",
"*",
"URI",
")",
"WithFilePath",
"(",
"p",
"string",
")",
"*",
"URI",
"{",
"copy",
":=",
"*",
"u",
"\n",
"copy",
".",
"Fragment",
"=",
"cleanPath",
"(",
"p",
")",
"\n",
"return",
"&",
"copy",
"\n",
"}"
] | // WithFilePath returns a copy of u with the file path p overwriting
// the existing file path (if any). | [
"WithFilePath",
"returns",
"a",
"copy",
"of",
"u",
"with",
"the",
"file",
"path",
"p",
"overwriting",
"the",
"existing",
"file",
"path",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gituri/uri.go#L76-L80 |
sourcegraph/go-langserver | langserver/format.go | ComputeTextEdits | func ComputeTextEdits(unformatted string, formatted string) []lsp.TextEdit {
// LSP wants a list of TextEdits. We use difflib to compute a
// non-naive TextEdit. Originally we returned an edit which deleted
// everything followed by inserting everything. This leads to a poor
// experience in vscode.
unformattedLines := strings.Split(unformatted, "\n")
formattedLines := strings.Split(formatted, "\n")
m := difflib.NewMatcher(unformattedLines, formattedLines)
var edits []lsp.TextEdit
for _, op := range m.GetOpCodes() {
switch op.Tag {
case 'r': // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
case 'd': // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
})
case 'i': // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I1,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
}
}
return edits
} | go | func ComputeTextEdits(unformatted string, formatted string) []lsp.TextEdit {
// LSP wants a list of TextEdits. We use difflib to compute a
// non-naive TextEdit. Originally we returned an edit which deleted
// everything followed by inserting everything. This leads to a poor
// experience in vscode.
unformattedLines := strings.Split(unformatted, "\n")
formattedLines := strings.Split(formatted, "\n")
m := difflib.NewMatcher(unformattedLines, formattedLines)
var edits []lsp.TextEdit
for _, op := range m.GetOpCodes() {
switch op.Tag {
case 'r': // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
case 'd': // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
})
case 'i': // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I1,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
}
}
return edits
} | [
"func",
"ComputeTextEdits",
"(",
"unformatted",
"string",
",",
"formatted",
"string",
")",
"[",
"]",
"lsp",
".",
"TextEdit",
"{",
"// LSP wants a list of TextEdits. We use difflib to compute a",
"// non-naive TextEdit. Originally we returned an edit which deleted",
"// everything followed by inserting everything. This leads to a poor",
"// experience in vscode.",
"unformattedLines",
":=",
"strings",
".",
"Split",
"(",
"unformatted",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"formattedLines",
":=",
"strings",
".",
"Split",
"(",
"formatted",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"m",
":=",
"difflib",
".",
"NewMatcher",
"(",
"unformattedLines",
",",
"formattedLines",
")",
"\n",
"var",
"edits",
"[",
"]",
"lsp",
".",
"TextEdit",
"\n",
"for",
"_",
",",
"op",
":=",
"range",
"m",
".",
"GetOpCodes",
"(",
")",
"{",
"switch",
"op",
".",
"Tag",
"{",
"case",
"'r'",
":",
"// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]",
"edits",
"=",
"append",
"(",
"edits",
",",
"lsp",
".",
"TextEdit",
"{",
"Range",
":",
"lsp",
".",
"Range",
"{",
"Start",
":",
"lsp",
".",
"Position",
"{",
"Line",
":",
"op",
".",
"I1",
",",
"}",
",",
"End",
":",
"lsp",
".",
"Position",
"{",
"Line",
":",
"op",
".",
"I2",
",",
"}",
",",
"}",
",",
"NewText",
":",
"strings",
".",
"Join",
"(",
"formattedLines",
"[",
"op",
".",
"J1",
":",
"op",
".",
"J2",
"]",
",",
"\"",
"\\n",
"\"",
")",
"+",
"\"",
"\\n",
"\"",
",",
"}",
")",
"\n",
"case",
"'d'",
":",
"// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.",
"edits",
"=",
"append",
"(",
"edits",
",",
"lsp",
".",
"TextEdit",
"{",
"Range",
":",
"lsp",
".",
"Range",
"{",
"Start",
":",
"lsp",
".",
"Position",
"{",
"Line",
":",
"op",
".",
"I1",
",",
"}",
",",
"End",
":",
"lsp",
".",
"Position",
"{",
"Line",
":",
"op",
".",
"I2",
",",
"}",
",",
"}",
",",
"}",
")",
"\n",
"case",
"'i'",
":",
"// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.",
"edits",
"=",
"append",
"(",
"edits",
",",
"lsp",
".",
"TextEdit",
"{",
"Range",
":",
"lsp",
".",
"Range",
"{",
"Start",
":",
"lsp",
".",
"Position",
"{",
"Line",
":",
"op",
".",
"I1",
",",
"}",
",",
"End",
":",
"lsp",
".",
"Position",
"{",
"Line",
":",
"op",
".",
"I1",
",",
"}",
",",
"}",
",",
"NewText",
":",
"strings",
".",
"Join",
"(",
"formattedLines",
"[",
"op",
".",
"J1",
":",
"op",
".",
"J2",
"]",
",",
"\"",
"\\n",
"\"",
")",
"+",
"\"",
"\\n",
"\"",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"edits",
"\n",
"}"
] | // ComputeTextEdits computes text edits that are required to
// change the `unformatted` to the `formatted` text. | [
"ComputeTextEdits",
"computes",
"text",
"edits",
"that",
"are",
"required",
"to",
"change",
"the",
"unformatted",
"to",
"the",
"formatted",
"text",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/format.go#L79-L129 |
sourcegraph/go-langserver | langserver/signature.go | callExpr | func callExpr(fset *token.FileSet, nodes []ast.Node) *ast.CallExpr {
for _, node := range nodes {
callExpr, ok := node.(*ast.CallExpr)
if ok {
return callExpr
}
}
return nil
} | go | func callExpr(fset *token.FileSet, nodes []ast.Node) *ast.CallExpr {
for _, node := range nodes {
callExpr, ok := node.(*ast.CallExpr)
if ok {
return callExpr
}
}
return nil
} | [
"func",
"callExpr",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"nodes",
"[",
"]",
"ast",
".",
"Node",
")",
"*",
"ast",
".",
"CallExpr",
"{",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"callExpr",
",",
"ok",
":=",
"node",
".",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"\n",
"if",
"ok",
"{",
"return",
"callExpr",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // callExpr climbs AST tree up until call expression | [
"callExpr",
"climbs",
"AST",
"tree",
"up",
"until",
"call",
"expression"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/signature.go#L77-L85 |
sourcegraph/go-langserver | langserver/signature.go | shortType | func shortType(t types.Type) string {
return types.TypeString(t, func(*types.Package) string {
return ""
})
} | go | func shortType(t types.Type) string {
return types.TypeString(t, func(*types.Package) string {
return ""
})
} | [
"func",
"shortType",
"(",
"t",
"types",
".",
"Type",
")",
"string",
"{",
"return",
"types",
".",
"TypeString",
"(",
"t",
",",
"func",
"(",
"*",
"types",
".",
"Package",
")",
"string",
"{",
"return",
"\"",
"\"",
"\n",
"}",
")",
"\n",
"}"
] | // shortTyoe returns shorthand type notation without specifying type's import path | [
"shortTyoe",
"returns",
"shorthand",
"type",
"notation",
"without",
"specifying",
"type",
"s",
"import",
"path"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/signature.go#L88-L92 |
sourcegraph/go-langserver | langserver/signature.go | shortParam | func shortParam(param *types.Var) string {
ret := param.Name()
if ret != "" {
ret += " "
}
return ret + shortType(param.Type())
} | go | func shortParam(param *types.Var) string {
ret := param.Name()
if ret != "" {
ret += " "
}
return ret + shortType(param.Type())
} | [
"func",
"shortParam",
"(",
"param",
"*",
"types",
".",
"Var",
")",
"string",
"{",
"ret",
":=",
"param",
".",
"Name",
"(",
")",
"\n",
"if",
"ret",
"!=",
"\"",
"\"",
"{",
"ret",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"ret",
"+",
"shortType",
"(",
"param",
".",
"Type",
"(",
")",
")",
"\n",
"}"
] | // shortParam returns shorthand parameter notation in form "name type" without specifying type's import path | [
"shortParam",
"returns",
"shorthand",
"parameter",
"notation",
"in",
"form",
"name",
"type",
"without",
"specifying",
"type",
"s",
"import",
"path"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/signature.go#L95-L101 |
sourcegraph/go-langserver | langserver/ast.go | goRangeToLSPLocation | func goRangeToLSPLocation(fset *token.FileSet, pos token.Pos, end token.Pos) lsp.Location {
return lsp.Location{
URI: util.PathToURI(fset.Position(pos).Filename),
Range: rangeForNode(fset, fakeNode{p: pos, e: end}),
}
} | go | func goRangeToLSPLocation(fset *token.FileSet, pos token.Pos, end token.Pos) lsp.Location {
return lsp.Location{
URI: util.PathToURI(fset.Position(pos).Filename),
Range: rangeForNode(fset, fakeNode{p: pos, e: end}),
}
} | [
"func",
"goRangeToLSPLocation",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"pos",
"token",
".",
"Pos",
",",
"end",
"token",
".",
"Pos",
")",
"lsp",
".",
"Location",
"{",
"return",
"lsp",
".",
"Location",
"{",
"URI",
":",
"util",
".",
"PathToURI",
"(",
"fset",
".",
"Position",
"(",
"pos",
")",
".",
"Filename",
")",
",",
"Range",
":",
"rangeForNode",
"(",
"fset",
",",
"fakeNode",
"{",
"p",
":",
"pos",
",",
"e",
":",
"end",
"}",
")",
",",
"}",
"\n\n",
"}"
] | // goRangeToLSPLocation converts a token.Pos range into a lsp.Location. end is
// exclusive. | [
"goRangeToLSPLocation",
"converts",
"a",
"token",
".",
"Pos",
"range",
"into",
"a",
"lsp",
".",
"Location",
".",
"end",
"is",
"exclusive",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/ast.go#L69-L75 |
sourcegraph/go-langserver | langserver/ast.go | findInterestingNode | func findInterestingNode(pkginfo *loader.PackageInfo, path []ast.Node) ([]ast.Node, action) {
// TODO(adonovan): integrate with go/types/stdlib_test.go and
// apply this to every AST node we can find to make sure it
// doesn't crash.
// TODO(adonovan): audit for ParenExpr safety, esp. since we
// traverse up and down.
// TODO(adonovan): if the users selects the "." in
// "fmt.Fprintf()", they'll get an ambiguous selection error;
// we won't even reach here. Can we do better?
// TODO(adonovan): describing a field within 'type T struct {...}'
// describes the (anonymous) struct type and concludes "no methods".
// We should ascend to the enclosing type decl, if any.
for len(path) > 0 {
switch n := path[0].(type) {
case *ast.GenDecl:
if len(n.Specs) == 1 {
// Descend to sole {Import,Type,Value}Spec child.
path = append([]ast.Node{n.Specs[0]}, path...)
continue
}
return path, actionUnknown // uninteresting
case *ast.FuncDecl:
// Descend to function name.
path = append([]ast.Node{n.Name}, path...)
continue
case *ast.ImportSpec:
return path, actionPackage
case *ast.ValueSpec:
if len(n.Names) == 1 {
// Descend to sole Ident child.
path = append([]ast.Node{n.Names[0]}, path...)
continue
}
return path, actionUnknown // uninteresting
case *ast.TypeSpec:
// Descend to type name.
path = append([]ast.Node{n.Name}, path...)
continue
case *ast.Comment, *ast.CommentGroup, *ast.File, *ast.KeyValueExpr, *ast.CommClause:
return path, actionUnknown // uninteresting
case ast.Stmt:
return path, actionStmt
case *ast.ArrayType,
*ast.StructType,
*ast.FuncType,
*ast.InterfaceType,
*ast.MapType,
*ast.ChanType:
return path, actionType
case *ast.Ellipsis:
// Continue to enclosing node.
// e.g. [...]T in ArrayType
// f(x...) in CallExpr
// f(x...T) in FuncType
case *ast.Field:
// TODO(adonovan): this needs more thought,
// since fields can be so many things.
if len(n.Names) == 1 {
// Descend to sole Ident child.
path = append([]ast.Node{n.Names[0]}, path...)
continue
}
// Zero names (e.g. anon field in struct)
// or multiple field or param names:
// continue to enclosing field list.
case *ast.FieldList:
// Continue to enclosing node:
// {Struct,Func,Interface}Type or FuncDecl.
case *ast.BasicLit:
if _, ok := path[1].(*ast.ImportSpec); ok {
return path[1:], actionPackage
}
return path, actionExpr
case *ast.SelectorExpr:
// TODO(adonovan): use Selections info directly.
if pkginfo.Uses[n.Sel] == nil {
// TODO(adonovan): is this reachable?
return path, actionUnknown
}
// Descend to .Sel child.
path = append([]ast.Node{n.Sel}, path...)
continue
case *ast.Ident:
switch pkginfo.ObjectOf(n).(type) {
case *types.PkgName:
return path, actionPackage
case *types.Const:
return path, actionExpr
case *types.Label:
return path, actionStmt
case *types.TypeName:
return path, actionType
case *types.Var:
// For x in 'struct {x T}', return struct type, for now.
if _, ok := path[1].(*ast.Field); ok {
_ = path[2].(*ast.FieldList) // assertion
if _, ok := path[3].(*ast.StructType); ok {
return path[3:], actionType
}
}
return path, actionExpr
case *types.Func:
return path, actionExpr
case *types.Builtin:
// For reference to built-in function, return enclosing call.
path = path[1:] // ascend to enclosing function call
continue
case *types.Nil:
return path, actionExpr
}
// No object.
switch path[1].(type) {
case *ast.SelectorExpr:
// Return enclosing selector expression.
return path[1:], actionExpr
case *ast.Field:
// TODO(adonovan): test this.
// e.g. all f in:
// struct { f, g int }
// interface { f() }
// func (f T) method(f, g int) (f, g bool)
//
// switch path[3].(type) {
// case *ast.FuncDecl:
// case *ast.StructType:
// case *ast.InterfaceType:
// }
//
// return path[1:], actionExpr
//
// Unclear what to do with these.
// Struct.Fields -- field
// Interface.Methods -- field
// FuncType.{Params.Results} -- actionExpr
// FuncDecl.Recv -- actionExpr
case *ast.File:
// 'package foo'
return path, actionPackage
case *ast.ImportSpec:
return path[1:], actionPackage
default:
// e.g. blank identifier
// or y in "switch y := x.(type)"
// or code in a _test.go file that's not part of the package.
return path, actionUnknown
}
case *ast.StarExpr:
if pkginfo.Types[n].IsType() {
return path, actionType
}
return path, actionExpr
case ast.Expr:
// All Expr but {BasicLit,Ident,StarExpr} are
// "true" expressions that evaluate to a value.
return path, actionExpr
}
// Ascend to parent.
path = path[1:]
}
return nil, actionUnknown // unreachable
} | go | func findInterestingNode(pkginfo *loader.PackageInfo, path []ast.Node) ([]ast.Node, action) {
// TODO(adonovan): integrate with go/types/stdlib_test.go and
// apply this to every AST node we can find to make sure it
// doesn't crash.
// TODO(adonovan): audit for ParenExpr safety, esp. since we
// traverse up and down.
// TODO(adonovan): if the users selects the "." in
// "fmt.Fprintf()", they'll get an ambiguous selection error;
// we won't even reach here. Can we do better?
// TODO(adonovan): describing a field within 'type T struct {...}'
// describes the (anonymous) struct type and concludes "no methods".
// We should ascend to the enclosing type decl, if any.
for len(path) > 0 {
switch n := path[0].(type) {
case *ast.GenDecl:
if len(n.Specs) == 1 {
// Descend to sole {Import,Type,Value}Spec child.
path = append([]ast.Node{n.Specs[0]}, path...)
continue
}
return path, actionUnknown // uninteresting
case *ast.FuncDecl:
// Descend to function name.
path = append([]ast.Node{n.Name}, path...)
continue
case *ast.ImportSpec:
return path, actionPackage
case *ast.ValueSpec:
if len(n.Names) == 1 {
// Descend to sole Ident child.
path = append([]ast.Node{n.Names[0]}, path...)
continue
}
return path, actionUnknown // uninteresting
case *ast.TypeSpec:
// Descend to type name.
path = append([]ast.Node{n.Name}, path...)
continue
case *ast.Comment, *ast.CommentGroup, *ast.File, *ast.KeyValueExpr, *ast.CommClause:
return path, actionUnknown // uninteresting
case ast.Stmt:
return path, actionStmt
case *ast.ArrayType,
*ast.StructType,
*ast.FuncType,
*ast.InterfaceType,
*ast.MapType,
*ast.ChanType:
return path, actionType
case *ast.Ellipsis:
// Continue to enclosing node.
// e.g. [...]T in ArrayType
// f(x...) in CallExpr
// f(x...T) in FuncType
case *ast.Field:
// TODO(adonovan): this needs more thought,
// since fields can be so many things.
if len(n.Names) == 1 {
// Descend to sole Ident child.
path = append([]ast.Node{n.Names[0]}, path...)
continue
}
// Zero names (e.g. anon field in struct)
// or multiple field or param names:
// continue to enclosing field list.
case *ast.FieldList:
// Continue to enclosing node:
// {Struct,Func,Interface}Type or FuncDecl.
case *ast.BasicLit:
if _, ok := path[1].(*ast.ImportSpec); ok {
return path[1:], actionPackage
}
return path, actionExpr
case *ast.SelectorExpr:
// TODO(adonovan): use Selections info directly.
if pkginfo.Uses[n.Sel] == nil {
// TODO(adonovan): is this reachable?
return path, actionUnknown
}
// Descend to .Sel child.
path = append([]ast.Node{n.Sel}, path...)
continue
case *ast.Ident:
switch pkginfo.ObjectOf(n).(type) {
case *types.PkgName:
return path, actionPackage
case *types.Const:
return path, actionExpr
case *types.Label:
return path, actionStmt
case *types.TypeName:
return path, actionType
case *types.Var:
// For x in 'struct {x T}', return struct type, for now.
if _, ok := path[1].(*ast.Field); ok {
_ = path[2].(*ast.FieldList) // assertion
if _, ok := path[3].(*ast.StructType); ok {
return path[3:], actionType
}
}
return path, actionExpr
case *types.Func:
return path, actionExpr
case *types.Builtin:
// For reference to built-in function, return enclosing call.
path = path[1:] // ascend to enclosing function call
continue
case *types.Nil:
return path, actionExpr
}
// No object.
switch path[1].(type) {
case *ast.SelectorExpr:
// Return enclosing selector expression.
return path[1:], actionExpr
case *ast.Field:
// TODO(adonovan): test this.
// e.g. all f in:
// struct { f, g int }
// interface { f() }
// func (f T) method(f, g int) (f, g bool)
//
// switch path[3].(type) {
// case *ast.FuncDecl:
// case *ast.StructType:
// case *ast.InterfaceType:
// }
//
// return path[1:], actionExpr
//
// Unclear what to do with these.
// Struct.Fields -- field
// Interface.Methods -- field
// FuncType.{Params.Results} -- actionExpr
// FuncDecl.Recv -- actionExpr
case *ast.File:
// 'package foo'
return path, actionPackage
case *ast.ImportSpec:
return path[1:], actionPackage
default:
// e.g. blank identifier
// or y in "switch y := x.(type)"
// or code in a _test.go file that's not part of the package.
return path, actionUnknown
}
case *ast.StarExpr:
if pkginfo.Types[n].IsType() {
return path, actionType
}
return path, actionExpr
case ast.Expr:
// All Expr but {BasicLit,Ident,StarExpr} are
// "true" expressions that evaluate to a value.
return path, actionExpr
}
// Ascend to parent.
path = path[1:]
}
return nil, actionUnknown // unreachable
} | [
"func",
"findInterestingNode",
"(",
"pkginfo",
"*",
"loader",
".",
"PackageInfo",
",",
"path",
"[",
"]",
"ast",
".",
"Node",
")",
"(",
"[",
"]",
"ast",
".",
"Node",
",",
"action",
")",
"{",
"// TODO(adonovan): integrate with go/types/stdlib_test.go and",
"// apply this to every AST node we can find to make sure it",
"// doesn't crash.",
"// TODO(adonovan): audit for ParenExpr safety, esp. since we",
"// traverse up and down.",
"// TODO(adonovan): if the users selects the \".\" in",
"// \"fmt.Fprintf()\", they'll get an ambiguous selection error;",
"// we won't even reach here. Can we do better?",
"// TODO(adonovan): describing a field within 'type T struct {...}'",
"// describes the (anonymous) struct type and concludes \"no methods\".",
"// We should ascend to the enclosing type decl, if any.",
"for",
"len",
"(",
"path",
")",
">",
"0",
"{",
"switch",
"n",
":=",
"path",
"[",
"0",
"]",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"GenDecl",
":",
"if",
"len",
"(",
"n",
".",
"Specs",
")",
"==",
"1",
"{",
"// Descend to sole {Import,Type,Value}Spec child.",
"path",
"=",
"append",
"(",
"[",
"]",
"ast",
".",
"Node",
"{",
"n",
".",
"Specs",
"[",
"0",
"]",
"}",
",",
"path",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"path",
",",
"actionUnknown",
"// uninteresting",
"\n\n",
"case",
"*",
"ast",
".",
"FuncDecl",
":",
"// Descend to function name.",
"path",
"=",
"append",
"(",
"[",
"]",
"ast",
".",
"Node",
"{",
"n",
".",
"Name",
"}",
",",
"path",
"...",
")",
"\n",
"continue",
"\n\n",
"case",
"*",
"ast",
".",
"ImportSpec",
":",
"return",
"path",
",",
"actionPackage",
"\n\n",
"case",
"*",
"ast",
".",
"ValueSpec",
":",
"if",
"len",
"(",
"n",
".",
"Names",
")",
"==",
"1",
"{",
"// Descend to sole Ident child.",
"path",
"=",
"append",
"(",
"[",
"]",
"ast",
".",
"Node",
"{",
"n",
".",
"Names",
"[",
"0",
"]",
"}",
",",
"path",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"path",
",",
"actionUnknown",
"// uninteresting",
"\n\n",
"case",
"*",
"ast",
".",
"TypeSpec",
":",
"// Descend to type name.",
"path",
"=",
"append",
"(",
"[",
"]",
"ast",
".",
"Node",
"{",
"n",
".",
"Name",
"}",
",",
"path",
"...",
")",
"\n",
"continue",
"\n\n",
"case",
"*",
"ast",
".",
"Comment",
",",
"*",
"ast",
".",
"CommentGroup",
",",
"*",
"ast",
".",
"File",
",",
"*",
"ast",
".",
"KeyValueExpr",
",",
"*",
"ast",
".",
"CommClause",
":",
"return",
"path",
",",
"actionUnknown",
"// uninteresting",
"\n\n",
"case",
"ast",
".",
"Stmt",
":",
"return",
"path",
",",
"actionStmt",
"\n\n",
"case",
"*",
"ast",
".",
"ArrayType",
",",
"*",
"ast",
".",
"StructType",
",",
"*",
"ast",
".",
"FuncType",
",",
"*",
"ast",
".",
"InterfaceType",
",",
"*",
"ast",
".",
"MapType",
",",
"*",
"ast",
".",
"ChanType",
":",
"return",
"path",
",",
"actionType",
"\n\n",
"case",
"*",
"ast",
".",
"Ellipsis",
":",
"// Continue to enclosing node.",
"// e.g. [...]T in ArrayType",
"// f(x...) in CallExpr",
"// f(x...T) in FuncType",
"case",
"*",
"ast",
".",
"Field",
":",
"// TODO(adonovan): this needs more thought,",
"// since fields can be so many things.",
"if",
"len",
"(",
"n",
".",
"Names",
")",
"==",
"1",
"{",
"// Descend to sole Ident child.",
"path",
"=",
"append",
"(",
"[",
"]",
"ast",
".",
"Node",
"{",
"n",
".",
"Names",
"[",
"0",
"]",
"}",
",",
"path",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// Zero names (e.g. anon field in struct)",
"// or multiple field or param names:",
"// continue to enclosing field list.",
"case",
"*",
"ast",
".",
"FieldList",
":",
"// Continue to enclosing node:",
"// {Struct,Func,Interface}Type or FuncDecl.",
"case",
"*",
"ast",
".",
"BasicLit",
":",
"if",
"_",
",",
"ok",
":=",
"path",
"[",
"1",
"]",
".",
"(",
"*",
"ast",
".",
"ImportSpec",
")",
";",
"ok",
"{",
"return",
"path",
"[",
"1",
":",
"]",
",",
"actionPackage",
"\n",
"}",
"\n",
"return",
"path",
",",
"actionExpr",
"\n\n",
"case",
"*",
"ast",
".",
"SelectorExpr",
":",
"// TODO(adonovan): use Selections info directly.",
"if",
"pkginfo",
".",
"Uses",
"[",
"n",
".",
"Sel",
"]",
"==",
"nil",
"{",
"// TODO(adonovan): is this reachable?",
"return",
"path",
",",
"actionUnknown",
"\n",
"}",
"\n",
"// Descend to .Sel child.",
"path",
"=",
"append",
"(",
"[",
"]",
"ast",
".",
"Node",
"{",
"n",
".",
"Sel",
"}",
",",
"path",
"...",
")",
"\n",
"continue",
"\n\n",
"case",
"*",
"ast",
".",
"Ident",
":",
"switch",
"pkginfo",
".",
"ObjectOf",
"(",
"n",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"types",
".",
"PkgName",
":",
"return",
"path",
",",
"actionPackage",
"\n\n",
"case",
"*",
"types",
".",
"Const",
":",
"return",
"path",
",",
"actionExpr",
"\n\n",
"case",
"*",
"types",
".",
"Label",
":",
"return",
"path",
",",
"actionStmt",
"\n\n",
"case",
"*",
"types",
".",
"TypeName",
":",
"return",
"path",
",",
"actionType",
"\n\n",
"case",
"*",
"types",
".",
"Var",
":",
"// For x in 'struct {x T}', return struct type, for now.",
"if",
"_",
",",
"ok",
":=",
"path",
"[",
"1",
"]",
".",
"(",
"*",
"ast",
".",
"Field",
")",
";",
"ok",
"{",
"_",
"=",
"path",
"[",
"2",
"]",
".",
"(",
"*",
"ast",
".",
"FieldList",
")",
"// assertion",
"\n",
"if",
"_",
",",
"ok",
":=",
"path",
"[",
"3",
"]",
".",
"(",
"*",
"ast",
".",
"StructType",
")",
";",
"ok",
"{",
"return",
"path",
"[",
"3",
":",
"]",
",",
"actionType",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"path",
",",
"actionExpr",
"\n\n",
"case",
"*",
"types",
".",
"Func",
":",
"return",
"path",
",",
"actionExpr",
"\n\n",
"case",
"*",
"types",
".",
"Builtin",
":",
"// For reference to built-in function, return enclosing call.",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"// ascend to enclosing function call",
"\n",
"continue",
"\n\n",
"case",
"*",
"types",
".",
"Nil",
":",
"return",
"path",
",",
"actionExpr",
"\n",
"}",
"\n\n",
"// No object.",
"switch",
"path",
"[",
"1",
"]",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"SelectorExpr",
":",
"// Return enclosing selector expression.",
"return",
"path",
"[",
"1",
":",
"]",
",",
"actionExpr",
"\n\n",
"case",
"*",
"ast",
".",
"Field",
":",
"// TODO(adonovan): test this.",
"// e.g. all f in:",
"// struct { f, g int }",
"// interface { f() }",
"// func (f T) method(f, g int) (f, g bool)",
"//",
"// switch path[3].(type) {",
"// case *ast.FuncDecl:",
"// case *ast.StructType:",
"// case *ast.InterfaceType:",
"// }",
"//",
"// return path[1:], actionExpr",
"//",
"// Unclear what to do with these.",
"// Struct.Fields -- field",
"// Interface.Methods -- field",
"// FuncType.{Params.Results} -- actionExpr",
"// FuncDecl.Recv -- actionExpr",
"case",
"*",
"ast",
".",
"File",
":",
"// 'package foo'",
"return",
"path",
",",
"actionPackage",
"\n\n",
"case",
"*",
"ast",
".",
"ImportSpec",
":",
"return",
"path",
"[",
"1",
":",
"]",
",",
"actionPackage",
"\n\n",
"default",
":",
"// e.g. blank identifier",
"// or y in \"switch y := x.(type)\"",
"// or code in a _test.go file that's not part of the package.",
"return",
"path",
",",
"actionUnknown",
"\n",
"}",
"\n\n",
"case",
"*",
"ast",
".",
"StarExpr",
":",
"if",
"pkginfo",
".",
"Types",
"[",
"n",
"]",
".",
"IsType",
"(",
")",
"{",
"return",
"path",
",",
"actionType",
"\n",
"}",
"\n",
"return",
"path",
",",
"actionExpr",
"\n\n",
"case",
"ast",
".",
"Expr",
":",
"// All Expr but {BasicLit,Ident,StarExpr} are",
"// \"true\" expressions that evaluate to a value.",
"return",
"path",
",",
"actionExpr",
"\n",
"}",
"\n\n",
"// Ascend to parent.",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"actionUnknown",
"// unreachable",
"\n",
"}"
] | // findInterestingNode classifies the syntax node denoted by path as one of:
// - an expression, part of an expression or a reference to a constant
// or variable;
// - a type, part of a type, or a reference to a named type;
// - a statement, part of a statement, or a label referring to a statement;
// - part of a package declaration or import spec.
// - none of the above.
// and returns the most "interesting" associated node, which may be
// the same node, an ancestor or a descendent.
//
// Adapted from golang.org/x/tools/cmd/guru (Copyright (c) 2013 The Go Authors). All rights
// reserved. See NOTICE for full license. | [
"findInterestingNode",
"classifies",
"the",
"syntax",
"node",
"denoted",
"by",
"path",
"as",
"one",
"of",
":",
"-",
"an",
"expression",
"part",
"of",
"an",
"expression",
"or",
"a",
"reference",
"to",
"a",
"constant",
"or",
"variable",
";",
"-",
"a",
"type",
"part",
"of",
"a",
"type",
"or",
"a",
"reference",
"to",
"a",
"named",
"type",
";",
"-",
"a",
"statement",
"part",
"of",
"a",
"statement",
"or",
"a",
"label",
"referring",
"to",
"a",
"statement",
";",
"-",
"part",
"of",
"a",
"package",
"declaration",
"or",
"import",
"spec",
".",
"-",
"none",
"of",
"the",
"above",
".",
"and",
"returns",
"the",
"most",
"interesting",
"associated",
"node",
"which",
"may",
"be",
"the",
"same",
"node",
"an",
"ancestor",
"or",
"a",
"descendent",
".",
"Adapted",
"from",
"golang",
".",
"org",
"/",
"x",
"/",
"tools",
"/",
"cmd",
"/",
"guru",
"(",
"Copyright",
"(",
"c",
")",
"2013",
"The",
"Go",
"Authors",
")",
".",
"All",
"rights",
"reserved",
".",
"See",
"NOTICE",
"for",
"full",
"license",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/ast.go#L99-L292 |
sourcegraph/go-langserver | langserver/lsp.go | Contains | func (a *symbolDescriptor) Contains(b lspext.SymbolDescriptor) bool {
for k, v := range b {
switch k {
case "package":
if s, ok := v.(string); !ok || s != a.Package {
return false
}
case "packageName":
if s, ok := v.(string); !ok || s != a.PackageName {
return false
}
case "recv":
if s, ok := v.(string); !ok || s != a.Recv {
return false
}
case "name":
if s, ok := v.(string); !ok || s != a.Name {
return false
}
case "id":
if s, ok := v.(string); !ok || s != a.ID {
return false
}
case "vendor":
if s, ok := v.(bool); !ok || s != a.Vendor {
return false
}
default:
return false
}
}
return true
} | go | func (a *symbolDescriptor) Contains(b lspext.SymbolDescriptor) bool {
for k, v := range b {
switch k {
case "package":
if s, ok := v.(string); !ok || s != a.Package {
return false
}
case "packageName":
if s, ok := v.(string); !ok || s != a.PackageName {
return false
}
case "recv":
if s, ok := v.(string); !ok || s != a.Recv {
return false
}
case "name":
if s, ok := v.(string); !ok || s != a.Name {
return false
}
case "id":
if s, ok := v.(string); !ok || s != a.ID {
return false
}
case "vendor":
if s, ok := v.(bool); !ok || s != a.Vendor {
return false
}
default:
return false
}
}
return true
} | [
"func",
"(",
"a",
"*",
"symbolDescriptor",
")",
"Contains",
"(",
"b",
"lspext",
".",
"SymbolDescriptor",
")",
"bool",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"b",
"{",
"switch",
"k",
"{",
"case",
"\"",
"\"",
":",
"if",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"!",
"ok",
"||",
"s",
"!=",
"a",
".",
"Package",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"!",
"ok",
"||",
"s",
"!=",
"a",
".",
"PackageName",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"!",
"ok",
"||",
"s",
"!=",
"a",
".",
"Recv",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"!",
"ok",
"||",
"s",
"!=",
"a",
".",
"Name",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"!",
"ok",
"||",
"s",
"!=",
"a",
".",
"ID",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"bool",
")",
";",
"!",
"ok",
"||",
"s",
"!=",
"a",
".",
"Vendor",
"{",
"return",
"false",
"\n",
"}",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Contains ensures that b is a subset of our symbolDescriptor | [
"Contains",
"ensures",
"that",
"b",
"is",
"a",
"subset",
"of",
"our",
"symbolDescriptor"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lsp.go#L24-L56 |
sourcegraph/go-langserver | langserver/references.go | reverseImportGraph | func (h *LangHandler) reverseImportGraph(ctx context.Context, conn jsonrpc2.JSONRPC2) <-chan importgraph.Graph {
// Ensure our buffer is big enough to prevent deadlock
c := make(chan importgraph.Graph, 2)
go func() {
// This should always be related to the go import path for
// this repo. For sourcegraph.com this means we share the
// import graph across commits. We want this behaviour since
// we assume that they don't change drastically across
// commits.
cacheKey := "importgraph:" + string(h.init.Root())
h.mu.Lock()
tryCache := h.importGraph == nil
once := h.importGraphOnce
h.mu.Unlock()
if tryCache {
g := make(importgraph.Graph)
if hit := h.cacheGet(ctx, conn, cacheKey, g); hit {
// \o/
c <- g
}
}
parentCtx := ctx
once.Do(func() {
// Note: We use a background context since this
// operation should not be cancelled due to an
// individual request.
span := startSpanFollowsFromContext(parentCtx, "BuildReverseImportGraph")
ctx := opentracing.ContextWithSpan(context.Background(), span)
defer span.Finish()
bctx := h.BuildContext(ctx)
findPackageWithCtx := h.getFindPackageFunc()
findPackage := func(bctx *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {
return findPackageWithCtx(ctx, bctx, importPath, fromDir, h.RootFSPath, mode)
}
g := tools.BuildReverseImportGraph(bctx, findPackage, h.FilePath(h.init.Root()))
h.mu.Lock()
h.importGraph = g
h.mu.Unlock()
// Update cache in background
go h.cacheSet(ctx, conn, cacheKey, g)
})
h.mu.Lock()
// TODO(keegancsmith) h.importGraph may have been reset after once
importGraph := h.importGraph
h.mu.Unlock()
c <- importGraph
close(c)
}()
return c
} | go | func (h *LangHandler) reverseImportGraph(ctx context.Context, conn jsonrpc2.JSONRPC2) <-chan importgraph.Graph {
// Ensure our buffer is big enough to prevent deadlock
c := make(chan importgraph.Graph, 2)
go func() {
// This should always be related to the go import path for
// this repo. For sourcegraph.com this means we share the
// import graph across commits. We want this behaviour since
// we assume that they don't change drastically across
// commits.
cacheKey := "importgraph:" + string(h.init.Root())
h.mu.Lock()
tryCache := h.importGraph == nil
once := h.importGraphOnce
h.mu.Unlock()
if tryCache {
g := make(importgraph.Graph)
if hit := h.cacheGet(ctx, conn, cacheKey, g); hit {
// \o/
c <- g
}
}
parentCtx := ctx
once.Do(func() {
// Note: We use a background context since this
// operation should not be cancelled due to an
// individual request.
span := startSpanFollowsFromContext(parentCtx, "BuildReverseImportGraph")
ctx := opentracing.ContextWithSpan(context.Background(), span)
defer span.Finish()
bctx := h.BuildContext(ctx)
findPackageWithCtx := h.getFindPackageFunc()
findPackage := func(bctx *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {
return findPackageWithCtx(ctx, bctx, importPath, fromDir, h.RootFSPath, mode)
}
g := tools.BuildReverseImportGraph(bctx, findPackage, h.FilePath(h.init.Root()))
h.mu.Lock()
h.importGraph = g
h.mu.Unlock()
// Update cache in background
go h.cacheSet(ctx, conn, cacheKey, g)
})
h.mu.Lock()
// TODO(keegancsmith) h.importGraph may have been reset after once
importGraph := h.importGraph
h.mu.Unlock()
c <- importGraph
close(c)
}()
return c
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"reverseImportGraph",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
")",
"<-",
"chan",
"importgraph",
".",
"Graph",
"{",
"// Ensure our buffer is big enough to prevent deadlock",
"c",
":=",
"make",
"(",
"chan",
"importgraph",
".",
"Graph",
",",
"2",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"// This should always be related to the go import path for",
"// this repo. For sourcegraph.com this means we share the",
"// import graph across commits. We want this behaviour since",
"// we assume that they don't change drastically across",
"// commits.",
"cacheKey",
":=",
"\"",
"\"",
"+",
"string",
"(",
"h",
".",
"init",
".",
"Root",
"(",
")",
")",
"\n\n",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"tryCache",
":=",
"h",
".",
"importGraph",
"==",
"nil",
"\n",
"once",
":=",
"h",
".",
"importGraphOnce",
"\n",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"tryCache",
"{",
"g",
":=",
"make",
"(",
"importgraph",
".",
"Graph",
")",
"\n",
"if",
"hit",
":=",
"h",
".",
"cacheGet",
"(",
"ctx",
",",
"conn",
",",
"cacheKey",
",",
"g",
")",
";",
"hit",
"{",
"// \\o/",
"c",
"<-",
"g",
"\n",
"}",
"\n",
"}",
"\n\n",
"parentCtx",
":=",
"ctx",
"\n",
"once",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"// Note: We use a background context since this",
"// operation should not be cancelled due to an",
"// individual request.",
"span",
":=",
"startSpanFollowsFromContext",
"(",
"parentCtx",
",",
"\"",
"\"",
")",
"\n",
"ctx",
":=",
"opentracing",
".",
"ContextWithSpan",
"(",
"context",
".",
"Background",
"(",
")",
",",
"span",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"bctx",
":=",
"h",
".",
"BuildContext",
"(",
"ctx",
")",
"\n",
"findPackageWithCtx",
":=",
"h",
".",
"getFindPackageFunc",
"(",
")",
"\n",
"findPackage",
":=",
"func",
"(",
"bctx",
"*",
"build",
".",
"Context",
",",
"importPath",
",",
"fromDir",
"string",
",",
"mode",
"build",
".",
"ImportMode",
")",
"(",
"*",
"build",
".",
"Package",
",",
"error",
")",
"{",
"return",
"findPackageWithCtx",
"(",
"ctx",
",",
"bctx",
",",
"importPath",
",",
"fromDir",
",",
"h",
".",
"RootFSPath",
",",
"mode",
")",
"\n",
"}",
"\n",
"g",
":=",
"tools",
".",
"BuildReverseImportGraph",
"(",
"bctx",
",",
"findPackage",
",",
"h",
".",
"FilePath",
"(",
"h",
".",
"init",
".",
"Root",
"(",
")",
")",
")",
"\n",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"h",
".",
"importGraph",
"=",
"g",
"\n",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Update cache in background",
"go",
"h",
".",
"cacheSet",
"(",
"ctx",
",",
"conn",
",",
"cacheKey",
",",
"g",
")",
"\n",
"}",
")",
"\n",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// TODO(keegancsmith) h.importGraph may have been reset after once",
"importGraph",
":=",
"h",
".",
"importGraph",
"\n",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"c",
"<-",
"importGraph",
"\n\n",
"close",
"(",
"c",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"c",
"\n",
"}"
] | // reverseImportGraph returns the reversed import graph for the workspace
// under the RootPath. Computing the reverse import graph is IO intensive, as
// such we may send down more than one import graph. The later a graph is
// sent, the more accurate it is. The channel will be closed, and the last
// graph sent is accurate. The reader does not have to read all the values. | [
"reverseImportGraph",
"returns",
"the",
"reversed",
"import",
"graph",
"for",
"the",
"workspace",
"under",
"the",
"RootPath",
".",
"Computing",
"the",
"reverse",
"import",
"graph",
"is",
"IO",
"intensive",
"as",
"such",
"we",
"may",
"send",
"down",
"more",
"than",
"one",
"import",
"graph",
".",
"The",
"later",
"a",
"graph",
"is",
"sent",
"the",
"more",
"accurate",
"it",
"is",
".",
"The",
"channel",
"will",
"be",
"closed",
"and",
"the",
"last",
"graph",
"sent",
"is",
"accurate",
".",
"The",
"reader",
"does",
"not",
"have",
"to",
"read",
"all",
"the",
"values",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L215-L271 |
sourcegraph/go-langserver | langserver/references.go | refStreamAndCollect | func refStreamAndCollect(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, fset *token.FileSet, refs <-chan *ast.Ident, limit int, stop func()) []lsp.Location {
if limit == 0 {
// If we don't have a limit, just set it to a value we should never exceed
limit = math.MaxInt32
}
id := lsp.ID{
Num: req.ID.Num,
Str: req.ID.Str,
IsString: req.ID.IsString,
}
initial := json.RawMessage(`[{"op":"replace","path":"","value":[]}]`)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
Patch: &initial,
})
var (
locs []lsp.Location
pos int
)
send := func() {
if pos >= len(locs) {
return
}
patch := make([]referenceAddOp, 0, len(locs)-pos)
for _, l := range locs[pos:] {
patch = append(patch, referenceAddOp{
OP: "add",
Path: "/-",
Value: l,
})
}
pos = len(locs)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
// We use referencePatch so the build server can rewrite URIs
Patch: referencePatch(patch),
})
}
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case n, ok := <-refs:
if !ok {
// send a final update
send()
return locs
}
if len(locs) >= limit {
stop()
continue
}
locs = append(locs, goRangeToLSPLocation(fset, n.Pos(), n.End()))
case <-tick.C:
send()
}
}
} | go | func refStreamAndCollect(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, fset *token.FileSet, refs <-chan *ast.Ident, limit int, stop func()) []lsp.Location {
if limit == 0 {
// If we don't have a limit, just set it to a value we should never exceed
limit = math.MaxInt32
}
id := lsp.ID{
Num: req.ID.Num,
Str: req.ID.Str,
IsString: req.ID.IsString,
}
initial := json.RawMessage(`[{"op":"replace","path":"","value":[]}]`)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
Patch: &initial,
})
var (
locs []lsp.Location
pos int
)
send := func() {
if pos >= len(locs) {
return
}
patch := make([]referenceAddOp, 0, len(locs)-pos)
for _, l := range locs[pos:] {
patch = append(patch, referenceAddOp{
OP: "add",
Path: "/-",
Value: l,
})
}
pos = len(locs)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
// We use referencePatch so the build server can rewrite URIs
Patch: referencePatch(patch),
})
}
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case n, ok := <-refs:
if !ok {
// send a final update
send()
return locs
}
if len(locs) >= limit {
stop()
continue
}
locs = append(locs, goRangeToLSPLocation(fset, n.Pos(), n.End()))
case <-tick.C:
send()
}
}
} | [
"func",
"refStreamAndCollect",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"refs",
"<-",
"chan",
"*",
"ast",
".",
"Ident",
",",
"limit",
"int",
",",
"stop",
"func",
"(",
")",
")",
"[",
"]",
"lsp",
".",
"Location",
"{",
"if",
"limit",
"==",
"0",
"{",
"// If we don't have a limit, just set it to a value we should never exceed",
"limit",
"=",
"math",
".",
"MaxInt32",
"\n",
"}",
"\n\n",
"id",
":=",
"lsp",
".",
"ID",
"{",
"Num",
":",
"req",
".",
"ID",
".",
"Num",
",",
"Str",
":",
"req",
".",
"ID",
".",
"Str",
",",
"IsString",
":",
"req",
".",
"ID",
".",
"IsString",
",",
"}",
"\n",
"initial",
":=",
"json",
".",
"RawMessage",
"(",
"`[{\"op\":\"replace\",\"path\":\"\",\"value\":[]}]`",
")",
"\n",
"_",
"=",
"conn",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"&",
"lspext",
".",
"PartialResultParams",
"{",
"ID",
":",
"id",
",",
"Patch",
":",
"&",
"initial",
",",
"}",
")",
"\n\n",
"var",
"(",
"locs",
"[",
"]",
"lsp",
".",
"Location",
"\n",
"pos",
"int",
"\n",
")",
"\n",
"send",
":=",
"func",
"(",
")",
"{",
"if",
"pos",
">=",
"len",
"(",
"locs",
")",
"{",
"return",
"\n",
"}",
"\n",
"patch",
":=",
"make",
"(",
"[",
"]",
"referenceAddOp",
",",
"0",
",",
"len",
"(",
"locs",
")",
"-",
"pos",
")",
"\n",
"for",
"_",
",",
"l",
":=",
"range",
"locs",
"[",
"pos",
":",
"]",
"{",
"patch",
"=",
"append",
"(",
"patch",
",",
"referenceAddOp",
"{",
"OP",
":",
"\"",
"\"",
",",
"Path",
":",
"\"",
"\"",
",",
"Value",
":",
"l",
",",
"}",
")",
"\n",
"}",
"\n",
"pos",
"=",
"len",
"(",
"locs",
")",
"\n",
"_",
"=",
"conn",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"&",
"lspext",
".",
"PartialResultParams",
"{",
"ID",
":",
"id",
",",
"// We use referencePatch so the build server can rewrite URIs",
"Patch",
":",
"referencePatch",
"(",
"patch",
")",
",",
"}",
")",
"\n",
"}",
"\n\n",
"tick",
":=",
"time",
".",
"NewTicker",
"(",
"100",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"defer",
"tick",
".",
"Stop",
"(",
")",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"n",
",",
"ok",
":=",
"<-",
"refs",
":",
"if",
"!",
"ok",
"{",
"// send a final update",
"send",
"(",
")",
"\n",
"return",
"locs",
"\n",
"}",
"\n",
"if",
"len",
"(",
"locs",
")",
">=",
"limit",
"{",
"stop",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"locs",
"=",
"append",
"(",
"locs",
",",
"goRangeToLSPLocation",
"(",
"fset",
",",
"n",
".",
"Pos",
"(",
")",
",",
"n",
".",
"End",
"(",
")",
")",
")",
"\n",
"case",
"<-",
"tick",
".",
"C",
":",
"send",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // refStreamAndCollect returns all refs read in from chan until it is
// closed. While it is reading, it will also occasionally stream out updates of
// the refs received so far. | [
"refStreamAndCollect",
"returns",
"all",
"refs",
"read",
"in",
"from",
"chan",
"until",
"it",
"is",
"closed",
".",
"While",
"it",
"is",
"reading",
"it",
"will",
"also",
"occasionally",
"stream",
"out",
"updates",
"of",
"the",
"refs",
"received",
"so",
"far",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L276-L337 |
sourcegraph/go-langserver | langserver/references.go | findReferences | func findReferences(ctx context.Context, lconf loader.Config, pkgInWorkspace func(string) bool, obj types.Object, refs chan<- *ast.Ident) error {
// Bail out early if the context is canceled
if ctx.Err() != nil {
return ctx.Err()
}
allowErrors(&lconf)
defpkg := strings.TrimSuffix(obj.Pkg().Path(), "_test")
objposn := lconf.Fset.Position(obj.Pos())
// The remainder of this function is somewhat tricky because it
// operates on the concurrent stream of packages observed by the
// loader's AfterTypeCheck hook.
var (
wg sync.WaitGroup
mu sync.Mutex
qobj types.Object
afterTypeCheckErr error
)
collectPkg := pkgInWorkspace
if _, ok := lconf.ImportPkgs[defpkg]; !ok {
// We have to typecheck defpkg, so just avoid references being collected.
collectPkg = func(path string) bool {
path = strings.TrimSuffix(path, "_test")
return pkgInWorkspace(path) && path != defpkg
}
lconf.ImportWithTests(defpkg)
}
// Only typecheck pkgs which we can collect refs in, or the pkg our
// object is defined in.
lconf.TypeCheckFuncBodies = func(path string) bool {
if ctx.Err() != nil {
return false
}
path = strings.TrimSuffix(path, "_test")
_, imported := lconf.ImportPkgs[path]
return imported && (pkgInWorkspace(path) || path == defpkg)
}
// For efficiency, we scan each package for references
// just after it has been type-checked. The loader calls
// AfterTypeCheck (concurrently), providing us with a stream of
// packages.
lconf.AfterTypeCheck = func(info *loader.PackageInfo, files []*ast.File) {
// AfterTypeCheck may be called twice for the same package due
// to augmentation.
defer clearInfoFields(info) // save memory
wg.Add(1)
defer wg.Done()
pkg := strings.TrimSuffix(info.Pkg.Path(), "_test")
// Only inspect packages that depend on the declaring package
// (and thus were type-checked).
if !lconf.TypeCheckFuncBodies(pkg) {
return
}
// Record the query object and its package when we see
// it. We can't reuse obj from the initial typecheck
// because each go/loader Load invocation creates new
// objects, and we need to test for equality later when we
// look up refs.
mu.Lock()
if qobj == nil && pkg == defpkg {
// Find the object by its position (slightly ugly).
qobj = findObject(lconf.Fset, &info.Info, objposn)
if qobj == nil {
// It really ought to be there; we found it once
// already.
afterTypeCheckErr = fmt.Errorf("object at %s not found in package %s", objposn, defpkg)
}
}
queryObj := qobj
mu.Unlock()
// Look for references to the query object. Only collect
// those that are in this workspace.
if queryObj != nil && collectPkg(pkg) {
for id, obj := range info.Uses {
if sameObj(queryObj, obj) {
refs <- id
}
}
}
}
// We don't use workgroup on this goroutine, since we want to return
// early on context cancellation.
done := make(chan struct{})
go func() {
// Prevent any uncaught panics from taking the entire server down.
defer func() {
close(done)
_ = util.Panicf(recover(), "findReferences")
}()
lconf.Load() // ignore error
}()
select {
case <-done:
case <-ctx.Done():
}
// This should only wait in the case of the context being done. In
// that case we are waiting for the currently running AfterTypeCheck
// functions to finish.
wg.Wait()
if qobj == nil {
if ctx.Err() != nil {
return ctx.Err()
}
if afterTypeCheckErr != nil {
// Only triggered by 1 specific error above (where we assign
// afterTypeCheckErr), not any general loader error.
return afterTypeCheckErr
}
return errors.New("query object not found during reloading")
}
return nil
} | go | func findReferences(ctx context.Context, lconf loader.Config, pkgInWorkspace func(string) bool, obj types.Object, refs chan<- *ast.Ident) error {
// Bail out early if the context is canceled
if ctx.Err() != nil {
return ctx.Err()
}
allowErrors(&lconf)
defpkg := strings.TrimSuffix(obj.Pkg().Path(), "_test")
objposn := lconf.Fset.Position(obj.Pos())
// The remainder of this function is somewhat tricky because it
// operates on the concurrent stream of packages observed by the
// loader's AfterTypeCheck hook.
var (
wg sync.WaitGroup
mu sync.Mutex
qobj types.Object
afterTypeCheckErr error
)
collectPkg := pkgInWorkspace
if _, ok := lconf.ImportPkgs[defpkg]; !ok {
// We have to typecheck defpkg, so just avoid references being collected.
collectPkg = func(path string) bool {
path = strings.TrimSuffix(path, "_test")
return pkgInWorkspace(path) && path != defpkg
}
lconf.ImportWithTests(defpkg)
}
// Only typecheck pkgs which we can collect refs in, or the pkg our
// object is defined in.
lconf.TypeCheckFuncBodies = func(path string) bool {
if ctx.Err() != nil {
return false
}
path = strings.TrimSuffix(path, "_test")
_, imported := lconf.ImportPkgs[path]
return imported && (pkgInWorkspace(path) || path == defpkg)
}
// For efficiency, we scan each package for references
// just after it has been type-checked. The loader calls
// AfterTypeCheck (concurrently), providing us with a stream of
// packages.
lconf.AfterTypeCheck = func(info *loader.PackageInfo, files []*ast.File) {
// AfterTypeCheck may be called twice for the same package due
// to augmentation.
defer clearInfoFields(info) // save memory
wg.Add(1)
defer wg.Done()
pkg := strings.TrimSuffix(info.Pkg.Path(), "_test")
// Only inspect packages that depend on the declaring package
// (and thus were type-checked).
if !lconf.TypeCheckFuncBodies(pkg) {
return
}
// Record the query object and its package when we see
// it. We can't reuse obj from the initial typecheck
// because each go/loader Load invocation creates new
// objects, and we need to test for equality later when we
// look up refs.
mu.Lock()
if qobj == nil && pkg == defpkg {
// Find the object by its position (slightly ugly).
qobj = findObject(lconf.Fset, &info.Info, objposn)
if qobj == nil {
// It really ought to be there; we found it once
// already.
afterTypeCheckErr = fmt.Errorf("object at %s not found in package %s", objposn, defpkg)
}
}
queryObj := qobj
mu.Unlock()
// Look for references to the query object. Only collect
// those that are in this workspace.
if queryObj != nil && collectPkg(pkg) {
for id, obj := range info.Uses {
if sameObj(queryObj, obj) {
refs <- id
}
}
}
}
// We don't use workgroup on this goroutine, since we want to return
// early on context cancellation.
done := make(chan struct{})
go func() {
// Prevent any uncaught panics from taking the entire server down.
defer func() {
close(done)
_ = util.Panicf(recover(), "findReferences")
}()
lconf.Load() // ignore error
}()
select {
case <-done:
case <-ctx.Done():
}
// This should only wait in the case of the context being done. In
// that case we are waiting for the currently running AfterTypeCheck
// functions to finish.
wg.Wait()
if qobj == nil {
if ctx.Err() != nil {
return ctx.Err()
}
if afterTypeCheckErr != nil {
// Only triggered by 1 specific error above (where we assign
// afterTypeCheckErr), not any general loader error.
return afterTypeCheckErr
}
return errors.New("query object not found during reloading")
}
return nil
} | [
"func",
"findReferences",
"(",
"ctx",
"context",
".",
"Context",
",",
"lconf",
"loader",
".",
"Config",
",",
"pkgInWorkspace",
"func",
"(",
"string",
")",
"bool",
",",
"obj",
"types",
".",
"Object",
",",
"refs",
"chan",
"<-",
"*",
"ast",
".",
"Ident",
")",
"error",
"{",
"// Bail out early if the context is canceled",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"allowErrors",
"(",
"&",
"lconf",
")",
"\n\n",
"defpkg",
":=",
"strings",
".",
"TrimSuffix",
"(",
"obj",
".",
"Pkg",
"(",
")",
".",
"Path",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"objposn",
":=",
"lconf",
".",
"Fset",
".",
"Position",
"(",
"obj",
".",
"Pos",
"(",
")",
")",
"\n\n",
"// The remainder of this function is somewhat tricky because it",
"// operates on the concurrent stream of packages observed by the",
"// loader's AfterTypeCheck hook.",
"var",
"(",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"mu",
"sync",
".",
"Mutex",
"\n",
"qobj",
"types",
".",
"Object",
"\n",
"afterTypeCheckErr",
"error",
"\n",
")",
"\n\n",
"collectPkg",
":=",
"pkgInWorkspace",
"\n",
"if",
"_",
",",
"ok",
":=",
"lconf",
".",
"ImportPkgs",
"[",
"defpkg",
"]",
";",
"!",
"ok",
"{",
"// We have to typecheck defpkg, so just avoid references being collected.",
"collectPkg",
"=",
"func",
"(",
"path",
"string",
")",
"bool",
"{",
"path",
"=",
"strings",
".",
"TrimSuffix",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"return",
"pkgInWorkspace",
"(",
"path",
")",
"&&",
"path",
"!=",
"defpkg",
"\n",
"}",
"\n",
"lconf",
".",
"ImportWithTests",
"(",
"defpkg",
")",
"\n",
"}",
"\n\n",
"// Only typecheck pkgs which we can collect refs in, or the pkg our",
"// object is defined in.",
"lconf",
".",
"TypeCheckFuncBodies",
"=",
"func",
"(",
"path",
"string",
")",
"bool",
"{",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"path",
"=",
"strings",
".",
"TrimSuffix",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"_",
",",
"imported",
":=",
"lconf",
".",
"ImportPkgs",
"[",
"path",
"]",
"\n",
"return",
"imported",
"&&",
"(",
"pkgInWorkspace",
"(",
"path",
")",
"||",
"path",
"==",
"defpkg",
")",
"\n",
"}",
"\n\n",
"// For efficiency, we scan each package for references",
"// just after it has been type-checked. The loader calls",
"// AfterTypeCheck (concurrently), providing us with a stream of",
"// packages.",
"lconf",
".",
"AfterTypeCheck",
"=",
"func",
"(",
"info",
"*",
"loader",
".",
"PackageInfo",
",",
"files",
"[",
"]",
"*",
"ast",
".",
"File",
")",
"{",
"// AfterTypeCheck may be called twice for the same package due",
"// to augmentation.",
"defer",
"clearInfoFields",
"(",
"info",
")",
"// save memory",
"\n\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"pkg",
":=",
"strings",
".",
"TrimSuffix",
"(",
"info",
".",
"Pkg",
".",
"Path",
"(",
")",
",",
"\"",
"\"",
")",
"\n\n",
"// Only inspect packages that depend on the declaring package",
"// (and thus were type-checked).",
"if",
"!",
"lconf",
".",
"TypeCheckFuncBodies",
"(",
"pkg",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// Record the query object and its package when we see",
"// it. We can't reuse obj from the initial typecheck",
"// because each go/loader Load invocation creates new",
"// objects, and we need to test for equality later when we",
"// look up refs.",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"qobj",
"==",
"nil",
"&&",
"pkg",
"==",
"defpkg",
"{",
"// Find the object by its position (slightly ugly).",
"qobj",
"=",
"findObject",
"(",
"lconf",
".",
"Fset",
",",
"&",
"info",
".",
"Info",
",",
"objposn",
")",
"\n",
"if",
"qobj",
"==",
"nil",
"{",
"// It really ought to be there; we found it once",
"// already.",
"afterTypeCheckErr",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"objposn",
",",
"defpkg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"queryObj",
":=",
"qobj",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Look for references to the query object. Only collect",
"// those that are in this workspace.",
"if",
"queryObj",
"!=",
"nil",
"&&",
"collectPkg",
"(",
"pkg",
")",
"{",
"for",
"id",
",",
"obj",
":=",
"range",
"info",
".",
"Uses",
"{",
"if",
"sameObj",
"(",
"queryObj",
",",
"obj",
")",
"{",
"refs",
"<-",
"id",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// We don't use workgroup on this goroutine, since we want to return",
"// early on context cancellation.",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"// Prevent any uncaught panics from taking the entire server down.",
"defer",
"func",
"(",
")",
"{",
"close",
"(",
"done",
")",
"\n",
"_",
"=",
"util",
".",
"Panicf",
"(",
"recover",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"(",
")",
"\n\n",
"lconf",
".",
"Load",
"(",
")",
"// ignore error",
"\n",
"}",
"(",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"done",
":",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"}",
"\n\n",
"// This should only wait in the case of the context being done. In",
"// that case we are waiting for the currently running AfterTypeCheck",
"// functions to finish.",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"if",
"qobj",
"==",
"nil",
"{",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"afterTypeCheckErr",
"!=",
"nil",
"{",
"// Only triggered by 1 specific error above (where we assign",
"// afterTypeCheckErr), not any general loader error.",
"return",
"afterTypeCheckErr",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // findReferences will find all references to obj. It will only return
// references from packages in lconf.ImportPkgs. | [
"findReferences",
"will",
"find",
"all",
"references",
"to",
"obj",
".",
"It",
"will",
"only",
"return",
"references",
"from",
"packages",
"in",
"lconf",
".",
"ImportPkgs",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L341-L471 |
sourcegraph/go-langserver | langserver/references.go | findReferencesPkgLevel | func (h *LangHandler) findReferencesPkgLevel(ctx context.Context, bctx *build.Context, fset *token.FileSet, users map[string]bool, pkgInWorkspace func(string) bool, obj types.Object, refs chan<- *ast.Ident) error {
// findReferencesPkgLevel uses go/ast and friends instead of go/types.
// This affords a considerable performance benefit.
// It comes at the cost of some code complexity.
//
// Here's a high level summary.
//
// The goal is to find references to the query object p.Q.
// There are several possible scenarios, each handled differently.
//
// 1. We are looking in a package other than p, and p is not dot-imported.
// This is the simplest case. Q must be referred to as n.Q,
// where n is the name under which p is imported.
// We look at all imports of p to gather all names under which it is imported.
// (In the typical case, it is imported only once, under its default name.)
// Then we look at all selector expressions and report any matches.
//
// 2. We are looking in a package other than p, and p is dot-imported.
// In this case, Q will be referred to just as Q.
// Furthermore, go/ast's object resolution will not be able to resolve
// Q to any other object, unlike any local (file- or function- or block-scoped) object.
// So we look at all matching identifiers and report all unresolvable ones.
//
// 3. We are looking in package p.
// (Care must be taken to separate p and p_test (an xtest package),
// and make sure that they are treated as separate packages.)
// In this case, we give go/ast the entire package for object resolution,
// instead of going file by file.
// We then iterate over all identifiers that resolve to the query object.
// (The query object itself has already been reported, so we don't re-report it.)
//
// We always skip all files that don't contain the string Q, as they cannot be
// relevant to finding references to Q.
//
// We parse all files leniently. In the presence of parsing errors, results are best-effort.
defpkg := strings.TrimSuffix(obj.Pkg().Path(), "_test") // package x_test actually has package name x
defpkg = imports.VendorlessPath(defpkg)
defname := obj.Pkg().Name() // name of the defining package of the query object, used for resolving imports that use import path only (common case)
isxtest := strings.HasSuffix(defname, "_test") // indicates whether the query object is defined in an xtest package
name := obj.Name()
namebytes := []byte(name) // byte slice version of query object name, for early filtering
objpos := fset.Position(obj.Pos()) // position of query object, used to prevent re-emitting original decl
find := h.getFindPackageFunc()
var reterr error
sema := make(chan struct{}, 20) // counting semaphore to limit I/O concurrency
var wg sync.WaitGroup
for u := range users {
// Bail out early if the context is canceled
if err := ctx.Err(); err != nil {
reterr = err
// Don't "return err" here;
// doing so would allow the caller to close the refs channel,
// which might cause a panic if there are existing searches in flight.
// Instead, just decline to start any new goroutines.
break
}
u := u // redeclare u to avoid range races
uIsXTest := strings.HasSuffix(u, "!test") // indicates whether this package is the special defpkg xtest package
u = strings.TrimSuffix(u, "!test")
// pkgInWorkspace is cheap and usually false; check it before firing up a goroutine.
if !pkgInWorkspace(u) {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
// Resolve package.
// TODO: is fromDir == "" correct?
sema <- struct{}{} // acquire token
pkg, err := find(ctx, bctx, u, "", h.RootFSPath, build.IgnoreVendor)
<-sema // release token
if err != nil {
return
}
// If we're not in the query package,
// the object is in another package regardless,
// so we want to process all files.
// If we are in the query package,
// we want to only process the files that are
// part of that query package;
// that set depends on whether the query package itself is an xtest.
inQueryPkg := u == defpkg && isxtest == uIsXTest
var files []string
if !inQueryPkg || !isxtest {
files = append(files, pkg.GoFiles...)
files = append(files, pkg.TestGoFiles...)
files = append(files, pkg.CgoFiles...) // use raw cgo files, as we're only parsing
}
if !inQueryPkg || isxtest {
files = append(files, pkg.XTestGoFiles...)
}
if len(files) == 0 {
return
}
var deffiles map[string]*ast.File // set of files that are part of this package, for inQueryPkg only
if inQueryPkg {
deffiles = make(map[string]*ast.File)
}
buf := new(bytes.Buffer) // reusable buffer for reading files
for _, file := range files {
if !buildutil.IsAbsPath(bctx, file) {
file = buildutil.JoinPath(bctx, pkg.Dir, file)
}
buf.Reset()
sema <- struct{}{} // acquire token
src, err := readFile(bctx, file, buf)
<-sema // release token
if err != nil {
continue
}
// Fast path: If the object's name isn't present anywhere in the source, ignore the file.
if !bytes.Contains(src, namebytes) {
continue
}
if inQueryPkg {
// If we're in the query package, we defer final processing until we have
// parsed all of the candidate files in the package.
// Best effort; allow errors and use what we can from what remains.
f, _ := parser.ParseFile(fset, file, src, parser.AllErrors)
if f != nil {
deffiles[file] = f
}
continue
}
// We aren't in the query package. Go file by file.
// Parse out only the imports, to check whether the defining package
// was imported, and if so, under what names.
// Best effort; allow errors and use what we can from what remains.
f, _ := parser.ParseFile(fset, file, src, parser.ImportsOnly|parser.AllErrors)
if f == nil {
continue
}
// pkgnames is the set of names by which defpkg is imported in this file.
// (Multiple imports in the same file are legal but vanishingly rare.)
pkgnames := make([]string, 0, 1)
var isdotimport bool
for _, imp := range f.Imports {
path, err := strconv.Unquote(imp.Path.Value)
if err != nil || path != defpkg {
continue
}
switch {
case imp.Name == nil:
pkgnames = append(pkgnames, defname)
case imp.Name.Name == ".":
isdotimport = true
default:
pkgnames = append(pkgnames, imp.Name.Name)
}
}
if len(pkgnames) == 0 && !isdotimport {
// Defining package not imported, bail.
continue
}
// Re-parse the entire file.
// Parse errors are ok; we'll do the best we can with a partial AST, if we have one.
f, _ = parser.ParseFile(fset, file, src, parser.AllErrors)
if f == nil {
continue
}
// Walk the AST looking for references.
ast.Inspect(f, func(n ast.Node) bool {
// Check selector expressions.
// If the selector matches the target name,
// and the expression is one of the names
// that the defining package was imported under,
// then we have a match.
if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == name {
if id, ok := sel.X.(*ast.Ident); ok {
for _, n := range pkgnames {
if n == id.Name {
refs <- sel.Sel
// Don't recurse further, to avoid duplicate entries
// from the dot import check below.
return false
}
}
}
}
// Dot imports are special.
// Objects imported from the defining package are placed in the package scope.
// go/ast does not resolve them to an object.
// At all other scopes (file, local), go/ast can do the resolution.
// So we're looking for object-free idents with the right name.
// The only other way to get something with the right name at the package scope
// is to *be* the defining package. We handle that case separately (inQueryPkg).
if isdotimport {
if id, ok := n.(*ast.Ident); ok && id.Obj == nil && id.Name == name {
refs <- id
return false
}
}
return true
})
}
// If we're in the query package, we've now collected all the files in the package.
// (Or at least the ones that might contain references to the object.)
if inQueryPkg {
// Bundle the files together into a package.
// This does package-level object resolution.
pkg, _ := ast.NewPackage(fset, deffiles, nil, nil)
// Look up the query object; we know that it is defined in the package scope.
pkgobj := pkg.Scope.Objects[name]
if pkgobj == nil {
panic("missing defpkg object for " + defpkg + "." + name)
}
// Find all references to the query object.
ast.Inspect(pkg, func(n ast.Node) bool {
if id, ok := n.(*ast.Ident); ok {
// Check both that this is a reference to the query object
// and that it is not the query object itself;
// the query object itself was already emitted.
if id.Obj == pkgobj && objpos != fset.Position(id.Pos()) {
refs <- id
return false
}
}
return true
})
deffiles = nil // allow GC
}
}()
}
wg.Wait()
return reterr
} | go | func (h *LangHandler) findReferencesPkgLevel(ctx context.Context, bctx *build.Context, fset *token.FileSet, users map[string]bool, pkgInWorkspace func(string) bool, obj types.Object, refs chan<- *ast.Ident) error {
// findReferencesPkgLevel uses go/ast and friends instead of go/types.
// This affords a considerable performance benefit.
// It comes at the cost of some code complexity.
//
// Here's a high level summary.
//
// The goal is to find references to the query object p.Q.
// There are several possible scenarios, each handled differently.
//
// 1. We are looking in a package other than p, and p is not dot-imported.
// This is the simplest case. Q must be referred to as n.Q,
// where n is the name under which p is imported.
// We look at all imports of p to gather all names under which it is imported.
// (In the typical case, it is imported only once, under its default name.)
// Then we look at all selector expressions and report any matches.
//
// 2. We are looking in a package other than p, and p is dot-imported.
// In this case, Q will be referred to just as Q.
// Furthermore, go/ast's object resolution will not be able to resolve
// Q to any other object, unlike any local (file- or function- or block-scoped) object.
// So we look at all matching identifiers and report all unresolvable ones.
//
// 3. We are looking in package p.
// (Care must be taken to separate p and p_test (an xtest package),
// and make sure that they are treated as separate packages.)
// In this case, we give go/ast the entire package for object resolution,
// instead of going file by file.
// We then iterate over all identifiers that resolve to the query object.
// (The query object itself has already been reported, so we don't re-report it.)
//
// We always skip all files that don't contain the string Q, as they cannot be
// relevant to finding references to Q.
//
// We parse all files leniently. In the presence of parsing errors, results are best-effort.
defpkg := strings.TrimSuffix(obj.Pkg().Path(), "_test") // package x_test actually has package name x
defpkg = imports.VendorlessPath(defpkg)
defname := obj.Pkg().Name() // name of the defining package of the query object, used for resolving imports that use import path only (common case)
isxtest := strings.HasSuffix(defname, "_test") // indicates whether the query object is defined in an xtest package
name := obj.Name()
namebytes := []byte(name) // byte slice version of query object name, for early filtering
objpos := fset.Position(obj.Pos()) // position of query object, used to prevent re-emitting original decl
find := h.getFindPackageFunc()
var reterr error
sema := make(chan struct{}, 20) // counting semaphore to limit I/O concurrency
var wg sync.WaitGroup
for u := range users {
// Bail out early if the context is canceled
if err := ctx.Err(); err != nil {
reterr = err
// Don't "return err" here;
// doing so would allow the caller to close the refs channel,
// which might cause a panic if there are existing searches in flight.
// Instead, just decline to start any new goroutines.
break
}
u := u // redeclare u to avoid range races
uIsXTest := strings.HasSuffix(u, "!test") // indicates whether this package is the special defpkg xtest package
u = strings.TrimSuffix(u, "!test")
// pkgInWorkspace is cheap and usually false; check it before firing up a goroutine.
if !pkgInWorkspace(u) {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
// Resolve package.
// TODO: is fromDir == "" correct?
sema <- struct{}{} // acquire token
pkg, err := find(ctx, bctx, u, "", h.RootFSPath, build.IgnoreVendor)
<-sema // release token
if err != nil {
return
}
// If we're not in the query package,
// the object is in another package regardless,
// so we want to process all files.
// If we are in the query package,
// we want to only process the files that are
// part of that query package;
// that set depends on whether the query package itself is an xtest.
inQueryPkg := u == defpkg && isxtest == uIsXTest
var files []string
if !inQueryPkg || !isxtest {
files = append(files, pkg.GoFiles...)
files = append(files, pkg.TestGoFiles...)
files = append(files, pkg.CgoFiles...) // use raw cgo files, as we're only parsing
}
if !inQueryPkg || isxtest {
files = append(files, pkg.XTestGoFiles...)
}
if len(files) == 0 {
return
}
var deffiles map[string]*ast.File // set of files that are part of this package, for inQueryPkg only
if inQueryPkg {
deffiles = make(map[string]*ast.File)
}
buf := new(bytes.Buffer) // reusable buffer for reading files
for _, file := range files {
if !buildutil.IsAbsPath(bctx, file) {
file = buildutil.JoinPath(bctx, pkg.Dir, file)
}
buf.Reset()
sema <- struct{}{} // acquire token
src, err := readFile(bctx, file, buf)
<-sema // release token
if err != nil {
continue
}
// Fast path: If the object's name isn't present anywhere in the source, ignore the file.
if !bytes.Contains(src, namebytes) {
continue
}
if inQueryPkg {
// If we're in the query package, we defer final processing until we have
// parsed all of the candidate files in the package.
// Best effort; allow errors and use what we can from what remains.
f, _ := parser.ParseFile(fset, file, src, parser.AllErrors)
if f != nil {
deffiles[file] = f
}
continue
}
// We aren't in the query package. Go file by file.
// Parse out only the imports, to check whether the defining package
// was imported, and if so, under what names.
// Best effort; allow errors and use what we can from what remains.
f, _ := parser.ParseFile(fset, file, src, parser.ImportsOnly|parser.AllErrors)
if f == nil {
continue
}
// pkgnames is the set of names by which defpkg is imported in this file.
// (Multiple imports in the same file are legal but vanishingly rare.)
pkgnames := make([]string, 0, 1)
var isdotimport bool
for _, imp := range f.Imports {
path, err := strconv.Unquote(imp.Path.Value)
if err != nil || path != defpkg {
continue
}
switch {
case imp.Name == nil:
pkgnames = append(pkgnames, defname)
case imp.Name.Name == ".":
isdotimport = true
default:
pkgnames = append(pkgnames, imp.Name.Name)
}
}
if len(pkgnames) == 0 && !isdotimport {
// Defining package not imported, bail.
continue
}
// Re-parse the entire file.
// Parse errors are ok; we'll do the best we can with a partial AST, if we have one.
f, _ = parser.ParseFile(fset, file, src, parser.AllErrors)
if f == nil {
continue
}
// Walk the AST looking for references.
ast.Inspect(f, func(n ast.Node) bool {
// Check selector expressions.
// If the selector matches the target name,
// and the expression is one of the names
// that the defining package was imported under,
// then we have a match.
if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == name {
if id, ok := sel.X.(*ast.Ident); ok {
for _, n := range pkgnames {
if n == id.Name {
refs <- sel.Sel
// Don't recurse further, to avoid duplicate entries
// from the dot import check below.
return false
}
}
}
}
// Dot imports are special.
// Objects imported from the defining package are placed in the package scope.
// go/ast does not resolve them to an object.
// At all other scopes (file, local), go/ast can do the resolution.
// So we're looking for object-free idents with the right name.
// The only other way to get something with the right name at the package scope
// is to *be* the defining package. We handle that case separately (inQueryPkg).
if isdotimport {
if id, ok := n.(*ast.Ident); ok && id.Obj == nil && id.Name == name {
refs <- id
return false
}
}
return true
})
}
// If we're in the query package, we've now collected all the files in the package.
// (Or at least the ones that might contain references to the object.)
if inQueryPkg {
// Bundle the files together into a package.
// This does package-level object resolution.
pkg, _ := ast.NewPackage(fset, deffiles, nil, nil)
// Look up the query object; we know that it is defined in the package scope.
pkgobj := pkg.Scope.Objects[name]
if pkgobj == nil {
panic("missing defpkg object for " + defpkg + "." + name)
}
// Find all references to the query object.
ast.Inspect(pkg, func(n ast.Node) bool {
if id, ok := n.(*ast.Ident); ok {
// Check both that this is a reference to the query object
// and that it is not the query object itself;
// the query object itself was already emitted.
if id.Obj == pkgobj && objpos != fset.Position(id.Pos()) {
refs <- id
return false
}
}
return true
})
deffiles = nil // allow GC
}
}()
}
wg.Wait()
return reterr
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"findReferencesPkgLevel",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"users",
"map",
"[",
"string",
"]",
"bool",
",",
"pkgInWorkspace",
"func",
"(",
"string",
")",
"bool",
",",
"obj",
"types",
".",
"Object",
",",
"refs",
"chan",
"<-",
"*",
"ast",
".",
"Ident",
")",
"error",
"{",
"// findReferencesPkgLevel uses go/ast and friends instead of go/types.",
"// This affords a considerable performance benefit.",
"// It comes at the cost of some code complexity.",
"//",
"// Here's a high level summary.",
"//",
"// The goal is to find references to the query object p.Q.",
"// There are several possible scenarios, each handled differently.",
"//",
"// 1. We are looking in a package other than p, and p is not dot-imported.",
"// This is the simplest case. Q must be referred to as n.Q,",
"// where n is the name under which p is imported.",
"// We look at all imports of p to gather all names under which it is imported.",
"// (In the typical case, it is imported only once, under its default name.)",
"// Then we look at all selector expressions and report any matches.",
"//",
"// 2. We are looking in a package other than p, and p is dot-imported.",
"// In this case, Q will be referred to just as Q.",
"// Furthermore, go/ast's object resolution will not be able to resolve",
"// Q to any other object, unlike any local (file- or function- or block-scoped) object.",
"// So we look at all matching identifiers and report all unresolvable ones.",
"//",
"// 3. We are looking in package p.",
"// (Care must be taken to separate p and p_test (an xtest package),",
"// and make sure that they are treated as separate packages.)",
"// In this case, we give go/ast the entire package for object resolution,",
"// instead of going file by file.",
"// We then iterate over all identifiers that resolve to the query object.",
"// (The query object itself has already been reported, so we don't re-report it.)",
"//",
"// We always skip all files that don't contain the string Q, as they cannot be",
"// relevant to finding references to Q.",
"//",
"// We parse all files leniently. In the presence of parsing errors, results are best-effort.",
"defpkg",
":=",
"strings",
".",
"TrimSuffix",
"(",
"obj",
".",
"Pkg",
"(",
")",
".",
"Path",
"(",
")",
",",
"\"",
"\"",
")",
"// package x_test actually has package name x",
"\n",
"defpkg",
"=",
"imports",
".",
"VendorlessPath",
"(",
"defpkg",
")",
"\n\n",
"defname",
":=",
"obj",
".",
"Pkg",
"(",
")",
".",
"Name",
"(",
")",
"// name of the defining package of the query object, used for resolving imports that use import path only (common case)",
"\n",
"isxtest",
":=",
"strings",
".",
"HasSuffix",
"(",
"defname",
",",
"\"",
"\"",
")",
"// indicates whether the query object is defined in an xtest package",
"\n\n",
"name",
":=",
"obj",
".",
"Name",
"(",
")",
"\n",
"namebytes",
":=",
"[",
"]",
"byte",
"(",
"name",
")",
"// byte slice version of query object name, for early filtering",
"\n",
"objpos",
":=",
"fset",
".",
"Position",
"(",
"obj",
".",
"Pos",
"(",
")",
")",
"// position of query object, used to prevent re-emitting original decl",
"\n\n",
"find",
":=",
"h",
".",
"getFindPackageFunc",
"(",
")",
"\n\n",
"var",
"reterr",
"error",
"\n",
"sema",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"20",
")",
"// counting semaphore to limit I/O concurrency",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"u",
":=",
"range",
"users",
"{",
"// Bail out early if the context is canceled",
"if",
"err",
":=",
"ctx",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"reterr",
"=",
"err",
"\n",
"// Don't \"return err\" here;",
"// doing so would allow the caller to close the refs channel,",
"// which might cause a panic if there are existing searches in flight.",
"// Instead, just decline to start any new goroutines.",
"break",
"\n",
"}",
"\n\n",
"u",
":=",
"u",
"// redeclare u to avoid range races",
"\n",
"uIsXTest",
":=",
"strings",
".",
"HasSuffix",
"(",
"u",
",",
"\"",
"\"",
")",
"// indicates whether this package is the special defpkg xtest package",
"\n",
"u",
"=",
"strings",
".",
"TrimSuffix",
"(",
"u",
",",
"\"",
"\"",
")",
"\n\n",
"// pkgInWorkspace is cheap and usually false; check it before firing up a goroutine.",
"if",
"!",
"pkgInWorkspace",
"(",
"u",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"// Resolve package.",
"// TODO: is fromDir == \"\" correct?",
"sema",
"<-",
"struct",
"{",
"}",
"{",
"}",
"// acquire token",
"\n",
"pkg",
",",
"err",
":=",
"find",
"(",
"ctx",
",",
"bctx",
",",
"u",
",",
"\"",
"\"",
",",
"h",
".",
"RootFSPath",
",",
"build",
".",
"IgnoreVendor",
")",
"\n",
"<-",
"sema",
"// release token",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// If we're not in the query package,",
"// the object is in another package regardless,",
"// so we want to process all files.",
"// If we are in the query package,",
"// we want to only process the files that are",
"// part of that query package;",
"// that set depends on whether the query package itself is an xtest.",
"inQueryPkg",
":=",
"u",
"==",
"defpkg",
"&&",
"isxtest",
"==",
"uIsXTest",
"\n",
"var",
"files",
"[",
"]",
"string",
"\n",
"if",
"!",
"inQueryPkg",
"||",
"!",
"isxtest",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"pkg",
".",
"GoFiles",
"...",
")",
"\n",
"files",
"=",
"append",
"(",
"files",
",",
"pkg",
".",
"TestGoFiles",
"...",
")",
"\n",
"files",
"=",
"append",
"(",
"files",
",",
"pkg",
".",
"CgoFiles",
"...",
")",
"// use raw cgo files, as we're only parsing",
"\n",
"}",
"\n",
"if",
"!",
"inQueryPkg",
"||",
"isxtest",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"pkg",
".",
"XTestGoFiles",
"...",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"files",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"deffiles",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"File",
"// set of files that are part of this package, for inQueryPkg only",
"\n",
"if",
"inQueryPkg",
"{",
"deffiles",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"File",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"// reusable buffer for reading files",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"if",
"!",
"buildutil",
".",
"IsAbsPath",
"(",
"bctx",
",",
"file",
")",
"{",
"file",
"=",
"buildutil",
".",
"JoinPath",
"(",
"bctx",
",",
"pkg",
".",
"Dir",
",",
"file",
")",
"\n",
"}",
"\n",
"buf",
".",
"Reset",
"(",
")",
"\n",
"sema",
"<-",
"struct",
"{",
"}",
"{",
"}",
"// acquire token",
"\n",
"src",
",",
"err",
":=",
"readFile",
"(",
"bctx",
",",
"file",
",",
"buf",
")",
"\n",
"<-",
"sema",
"// release token",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Fast path: If the object's name isn't present anywhere in the source, ignore the file.",
"if",
"!",
"bytes",
".",
"Contains",
"(",
"src",
",",
"namebytes",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"inQueryPkg",
"{",
"// If we're in the query package, we defer final processing until we have",
"// parsed all of the candidate files in the package.",
"// Best effort; allow errors and use what we can from what remains.",
"f",
",",
"_",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"file",
",",
"src",
",",
"parser",
".",
"AllErrors",
")",
"\n",
"if",
"f",
"!=",
"nil",
"{",
"deffiles",
"[",
"file",
"]",
"=",
"f",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// We aren't in the query package. Go file by file.",
"// Parse out only the imports, to check whether the defining package",
"// was imported, and if so, under what names.",
"// Best effort; allow errors and use what we can from what remains.",
"f",
",",
"_",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"file",
",",
"src",
",",
"parser",
".",
"ImportsOnly",
"|",
"parser",
".",
"AllErrors",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// pkgnames is the set of names by which defpkg is imported in this file.",
"// (Multiple imports in the same file are legal but vanishingly rare.)",
"pkgnames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"1",
")",
"\n",
"var",
"isdotimport",
"bool",
"\n",
"for",
"_",
",",
"imp",
":=",
"range",
"f",
".",
"Imports",
"{",
"path",
",",
"err",
":=",
"strconv",
".",
"Unquote",
"(",
"imp",
".",
"Path",
".",
"Value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"path",
"!=",
"defpkg",
"{",
"continue",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"imp",
".",
"Name",
"==",
"nil",
":",
"pkgnames",
"=",
"append",
"(",
"pkgnames",
",",
"defname",
")",
"\n",
"case",
"imp",
".",
"Name",
".",
"Name",
"==",
"\"",
"\"",
":",
"isdotimport",
"=",
"true",
"\n",
"default",
":",
"pkgnames",
"=",
"append",
"(",
"pkgnames",
",",
"imp",
".",
"Name",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pkgnames",
")",
"==",
"0",
"&&",
"!",
"isdotimport",
"{",
"// Defining package not imported, bail.",
"continue",
"\n",
"}",
"\n\n",
"// Re-parse the entire file.",
"// Parse errors are ok; we'll do the best we can with a partial AST, if we have one.",
"f",
",",
"_",
"=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"file",
",",
"src",
",",
"parser",
".",
"AllErrors",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Walk the AST looking for references.",
"ast",
".",
"Inspect",
"(",
"f",
",",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"// Check selector expressions.",
"// If the selector matches the target name,",
"// and the expression is one of the names",
"// that the defining package was imported under,",
"// then we have a match.",
"if",
"sel",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
";",
"ok",
"&&",
"sel",
".",
"Sel",
".",
"Name",
"==",
"name",
"{",
"if",
"id",
",",
"ok",
":=",
"sel",
".",
"X",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"pkgnames",
"{",
"if",
"n",
"==",
"id",
".",
"Name",
"{",
"refs",
"<-",
"sel",
".",
"Sel",
"\n",
"// Don't recurse further, to avoid duplicate entries",
"// from the dot import check below.",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Dot imports are special.",
"// Objects imported from the defining package are placed in the package scope.",
"// go/ast does not resolve them to an object.",
"// At all other scopes (file, local), go/ast can do the resolution.",
"// So we're looking for object-free idents with the right name.",
"// The only other way to get something with the right name at the package scope",
"// is to *be* the defining package. We handle that case separately (inQueryPkg).",
"if",
"isdotimport",
"{",
"if",
"id",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"&&",
"id",
".",
"Obj",
"==",
"nil",
"&&",
"id",
".",
"Name",
"==",
"name",
"{",
"refs",
"<-",
"id",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"// If we're in the query package, we've now collected all the files in the package.",
"// (Or at least the ones that might contain references to the object.)",
"if",
"inQueryPkg",
"{",
"// Bundle the files together into a package.",
"// This does package-level object resolution.",
"pkg",
",",
"_",
":=",
"ast",
".",
"NewPackage",
"(",
"fset",
",",
"deffiles",
",",
"nil",
",",
"nil",
")",
"\n",
"// Look up the query object; we know that it is defined in the package scope.",
"pkgobj",
":=",
"pkg",
".",
"Scope",
".",
"Objects",
"[",
"name",
"]",
"\n",
"if",
"pkgobj",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"defpkg",
"+",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}",
"\n",
"// Find all references to the query object.",
"ast",
".",
"Inspect",
"(",
"pkg",
",",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"if",
"id",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"{",
"// Check both that this is a reference to the query object",
"// and that it is not the query object itself;",
"// the query object itself was already emitted.",
"if",
"id",
".",
"Obj",
"==",
"pkgobj",
"&&",
"objpos",
"!=",
"fset",
".",
"Position",
"(",
"id",
".",
"Pos",
"(",
")",
")",
"{",
"refs",
"<-",
"id",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"deffiles",
"=",
"nil",
"// allow GC",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"return",
"reterr",
"\n",
"}"
] | // findReferencesPkgLevel finds all references to obj.
// It only returns references from packages in users.
// It is the analogue of globalReferrersPkgLevel
// from golang.org/x/tools/cmd/guru/referrers.go. | [
"findReferencesPkgLevel",
"finds",
"all",
"references",
"to",
"obj",
".",
"It",
"only",
"returns",
"references",
"from",
"packages",
"in",
"users",
".",
"It",
"is",
"the",
"analogue",
"of",
"globalReferrersPkgLevel",
"from",
"golang",
".",
"org",
"/",
"x",
"/",
"tools",
"/",
"cmd",
"/",
"guru",
"/",
"referrers",
".",
"go",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L477-L726 |
sourcegraph/go-langserver | langserver/references.go | classify | func classify(obj types.Object) (global, pkglevel bool) {
if obj.Exported() {
if obj.Parent() == nil {
// selectable object (field or method)
return true, false
}
if obj.Parent() == obj.Pkg().Scope() {
// lexical object (package-level var/const/func/type)
return true, true
}
}
// object with unexported named or defined in local scope
return false, false
} | go | func classify(obj types.Object) (global, pkglevel bool) {
if obj.Exported() {
if obj.Parent() == nil {
// selectable object (field or method)
return true, false
}
if obj.Parent() == obj.Pkg().Scope() {
// lexical object (package-level var/const/func/type)
return true, true
}
}
// object with unexported named or defined in local scope
return false, false
} | [
"func",
"classify",
"(",
"obj",
"types",
".",
"Object",
")",
"(",
"global",
",",
"pkglevel",
"bool",
")",
"{",
"if",
"obj",
".",
"Exported",
"(",
")",
"{",
"if",
"obj",
".",
"Parent",
"(",
")",
"==",
"nil",
"{",
"// selectable object (field or method)",
"return",
"true",
",",
"false",
"\n",
"}",
"\n",
"if",
"obj",
".",
"Parent",
"(",
")",
"==",
"obj",
".",
"Pkg",
"(",
")",
".",
"Scope",
"(",
")",
"{",
"// lexical object (package-level var/const/func/type)",
"return",
"true",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"// object with unexported named or defined in local scope",
"return",
"false",
",",
"false",
"\n",
"}"
] | // classify classifies objects by how far
// we have to look to find references to them. | [
"classify",
"classifies",
"objects",
"by",
"how",
"far",
"we",
"have",
"to",
"look",
"to",
"find",
"references",
"to",
"them",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L730-L743 |
sourcegraph/go-langserver | langserver/references.go | allowErrors | func allowErrors(lconf *loader.Config) {
ctxt := *lconf.Build // copy
ctxt.CgoEnabled = false
lconf.Build = &ctxt
lconf.AllowErrors = true
// AllErrors makes the parser always return an AST instead of
// bailing out after 10 errors and returning an empty ast.File.
lconf.ParserMode = parser.AllErrors
lconf.TypeChecker.Error = func(err error) {}
} | go | func allowErrors(lconf *loader.Config) {
ctxt := *lconf.Build // copy
ctxt.CgoEnabled = false
lconf.Build = &ctxt
lconf.AllowErrors = true
// AllErrors makes the parser always return an AST instead of
// bailing out after 10 errors and returning an empty ast.File.
lconf.ParserMode = parser.AllErrors
lconf.TypeChecker.Error = func(err error) {}
} | [
"func",
"allowErrors",
"(",
"lconf",
"*",
"loader",
".",
"Config",
")",
"{",
"ctxt",
":=",
"*",
"lconf",
".",
"Build",
"// copy",
"\n",
"ctxt",
".",
"CgoEnabled",
"=",
"false",
"\n",
"lconf",
".",
"Build",
"=",
"&",
"ctxt",
"\n",
"lconf",
".",
"AllowErrors",
"=",
"true",
"\n",
"// AllErrors makes the parser always return an AST instead of",
"// bailing out after 10 errors and returning an empty ast.File.",
"lconf",
".",
"ParserMode",
"=",
"parser",
".",
"AllErrors",
"\n",
"lconf",
".",
"TypeChecker",
".",
"Error",
"=",
"func",
"(",
"err",
"error",
")",
"{",
"}",
"\n",
"}"
] | // allowErrors causes type errors to be silently ignored.
// (Not suitable if SSA construction follows.)
//
// NOTICE: Adapted from golang.org/x/tools. | [
"allowErrors",
"causes",
"type",
"errors",
"to",
"be",
"silently",
"ignored",
".",
"(",
"Not",
"suitable",
"if",
"SSA",
"construction",
"follows",
".",
")",
"NOTICE",
":",
"Adapted",
"from",
"golang",
".",
"org",
"/",
"x",
"/",
"tools",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L749-L758 |
sourcegraph/go-langserver | langserver/references.go | findObject | func findObject(fset *token.FileSet, info *types.Info, objposn token.Position) types.Object {
good := func(obj types.Object) bool {
if obj == nil {
return false
}
posn := fset.Position(obj.Pos())
return posn.Filename == objposn.Filename && posn.Offset == objposn.Offset
}
for _, obj := range info.Defs {
if good(obj) {
return obj
}
}
for _, obj := range info.Implicits {
if good(obj) {
return obj
}
}
return nil
} | go | func findObject(fset *token.FileSet, info *types.Info, objposn token.Position) types.Object {
good := func(obj types.Object) bool {
if obj == nil {
return false
}
posn := fset.Position(obj.Pos())
return posn.Filename == objposn.Filename && posn.Offset == objposn.Offset
}
for _, obj := range info.Defs {
if good(obj) {
return obj
}
}
for _, obj := range info.Implicits {
if good(obj) {
return obj
}
}
return nil
} | [
"func",
"findObject",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"info",
"*",
"types",
".",
"Info",
",",
"objposn",
"token",
".",
"Position",
")",
"types",
".",
"Object",
"{",
"good",
":=",
"func",
"(",
"obj",
"types",
".",
"Object",
")",
"bool",
"{",
"if",
"obj",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"posn",
":=",
"fset",
".",
"Position",
"(",
"obj",
".",
"Pos",
"(",
")",
")",
"\n",
"return",
"posn",
".",
"Filename",
"==",
"objposn",
".",
"Filename",
"&&",
"posn",
".",
"Offset",
"==",
"objposn",
".",
"Offset",
"\n",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"info",
".",
"Defs",
"{",
"if",
"good",
"(",
"obj",
")",
"{",
"return",
"obj",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"info",
".",
"Implicits",
"{",
"if",
"good",
"(",
"obj",
")",
"{",
"return",
"obj",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // findObject returns the object defined at the specified position. | [
"findObject",
"returns",
"the",
"object",
"defined",
"at",
"the",
"specified",
"position",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L761-L780 |
sourcegraph/go-langserver | langserver/references.go | sameObj | func sameObj(x, y types.Object) bool {
if x == y {
return true
}
if x, ok := x.(*types.PkgName); ok {
if y, ok := y.(*types.PkgName); ok {
return x.Imported() == y.Imported()
}
}
return false
} | go | func sameObj(x, y types.Object) bool {
if x == y {
return true
}
if x, ok := x.(*types.PkgName); ok {
if y, ok := y.(*types.PkgName); ok {
return x.Imported() == y.Imported()
}
}
return false
} | [
"func",
"sameObj",
"(",
"x",
",",
"y",
"types",
".",
"Object",
")",
"bool",
"{",
"if",
"x",
"==",
"y",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"x",
",",
"ok",
":=",
"x",
".",
"(",
"*",
"types",
".",
"PkgName",
")",
";",
"ok",
"{",
"if",
"y",
",",
"ok",
":=",
"y",
".",
"(",
"*",
"types",
".",
"PkgName",
")",
";",
"ok",
"{",
"return",
"x",
".",
"Imported",
"(",
")",
"==",
"y",
".",
"Imported",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // same reports whether x and y are identical, or both are PkgNames
// that import the same Package. | [
"same",
"reports",
"whether",
"x",
"and",
"y",
"are",
"identical",
"or",
"both",
"are",
"PkgNames",
"that",
"import",
"the",
"same",
"Package",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L794-L804 |
sourcegraph/go-langserver | langserver/references.go | readFile | func readFile(ctxt *build.Context, filename string, buf *bytes.Buffer) ([]byte, error) {
rc, err := buildutil.OpenFile(ctxt, filename)
if err != nil {
return nil, err
}
defer rc.Close()
if buf == nil {
buf = new(bytes.Buffer)
}
if _, err := io.Copy(buf, rc); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func readFile(ctxt *build.Context, filename string, buf *bytes.Buffer) ([]byte, error) {
rc, err := buildutil.OpenFile(ctxt, filename)
if err != nil {
return nil, err
}
defer rc.Close()
if buf == nil {
buf = new(bytes.Buffer)
}
if _, err := io.Copy(buf, rc); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"readFile",
"(",
"ctxt",
"*",
"build",
".",
"Context",
",",
"filename",
"string",
",",
"buf",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"rc",
",",
"err",
":=",
"buildutil",
".",
"OpenFile",
"(",
"ctxt",
",",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n",
"if",
"buf",
"==",
"nil",
"{",
"buf",
"=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"buf",
",",
"rc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // readFile is like ioutil.ReadFile, but
// it goes through the virtualized build.Context.
// If non-nil, buf must have been reset. | [
"readFile",
"is",
"like",
"ioutil",
".",
"ReadFile",
"but",
"it",
"goes",
"through",
"the",
"virtualized",
"build",
".",
"Context",
".",
"If",
"non",
"-",
"nil",
"buf",
"must",
"have",
"been",
"reset",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L809-L822 |
sourcegraph/go-langserver | langserver/handler_common.go | ShutDown | func (h *HandlerCommon) ShutDown() {
h.mu.Lock()
if h.shutdown {
log.Printf("Warning: server received a shutdown request after it was already shut down.")
}
h.shutdown = true
h.mu.Unlock()
} | go | func (h *HandlerCommon) ShutDown() {
h.mu.Lock()
if h.shutdown {
log.Printf("Warning: server received a shutdown request after it was already shut down.")
}
h.shutdown = true
h.mu.Unlock()
} | [
"func",
"(",
"h",
"*",
"HandlerCommon",
")",
"ShutDown",
"(",
")",
"{",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"h",
".",
"shutdown",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"h",
".",
"shutdown",
"=",
"true",
"\n",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // ShutDown marks this server as being shut down and causes all future calls to checkReady to return an error. | [
"ShutDown",
"marks",
"this",
"server",
"as",
"being",
"shut",
"down",
"and",
"causes",
"all",
"future",
"calls",
"to",
"checkReady",
"to",
"return",
"an",
"error",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler_common.go#L40-L47 |
sourcegraph/go-langserver | langserver/handler_common.go | CheckReady | func (h *HandlerCommon) CheckReady() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.shutdown {
return errors.New("server is shutting down")
}
return nil
} | go | func (h *HandlerCommon) CheckReady() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.shutdown {
return errors.New("server is shutting down")
}
return nil
} | [
"func",
"(",
"h",
"*",
"HandlerCommon",
")",
"CheckReady",
"(",
")",
"error",
"{",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"h",
".",
"shutdown",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CheckReady returns an error if the handler has been shut
// down. | [
"CheckReady",
"returns",
"an",
"error",
"if",
"the",
"handler",
"has",
"been",
"shut",
"down",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler_common.go#L51-L58 |
sourcegraph/go-langserver | vfsutil/archive.go | fetchOrWait | func (fs *ArchiveFS) fetchOrWait(ctx context.Context) error {
fs.once.Do(func() {
// If we have already closed, do not open new resources. If we
// haven't closed, prevent closing while fetching by holding
// the lock.
fs.closedMu.Lock()
defer fs.closedMu.Unlock()
if fs.closed {
fs.err = errors.New("closed")
return
}
fs.ar, fs.err = fs.fetch(ctx)
if fs.err == nil {
fs.fs = zipfs.New(&zip.ReadCloser{Reader: *fs.ar.Reader}, "")
if fs.ar.StripTopLevelDir {
entries, err := fs.fs.ReadDir("/")
if err == nil && len(entries) == 1 && entries[0].IsDir() {
fs.ar.prefix = entries[0].Name()
}
}
if fs.ar.prefix != "" {
ns := vfs.NameSpace{}
ns.Bind("/", fs.fs, "/"+fs.ar.prefix, vfs.BindReplace)
fs.fs = ns
}
}
})
return fs.err
} | go | func (fs *ArchiveFS) fetchOrWait(ctx context.Context) error {
fs.once.Do(func() {
// If we have already closed, do not open new resources. If we
// haven't closed, prevent closing while fetching by holding
// the lock.
fs.closedMu.Lock()
defer fs.closedMu.Unlock()
if fs.closed {
fs.err = errors.New("closed")
return
}
fs.ar, fs.err = fs.fetch(ctx)
if fs.err == nil {
fs.fs = zipfs.New(&zip.ReadCloser{Reader: *fs.ar.Reader}, "")
if fs.ar.StripTopLevelDir {
entries, err := fs.fs.ReadDir("/")
if err == nil && len(entries) == 1 && entries[0].IsDir() {
fs.ar.prefix = entries[0].Name()
}
}
if fs.ar.prefix != "" {
ns := vfs.NameSpace{}
ns.Bind("/", fs.fs, "/"+fs.ar.prefix, vfs.BindReplace)
fs.fs = ns
}
}
})
return fs.err
} | [
"func",
"(",
"fs",
"*",
"ArchiveFS",
")",
"fetchOrWait",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"fs",
".",
"once",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"// If we have already closed, do not open new resources. If we",
"// haven't closed, prevent closing while fetching by holding",
"// the lock.",
"fs",
".",
"closedMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fs",
".",
"closedMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"fs",
".",
"closed",
"{",
"fs",
".",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"fs",
".",
"ar",
",",
"fs",
".",
"err",
"=",
"fs",
".",
"fetch",
"(",
"ctx",
")",
"\n",
"if",
"fs",
".",
"err",
"==",
"nil",
"{",
"fs",
".",
"fs",
"=",
"zipfs",
".",
"New",
"(",
"&",
"zip",
".",
"ReadCloser",
"{",
"Reader",
":",
"*",
"fs",
".",
"ar",
".",
"Reader",
"}",
",",
"\"",
"\"",
")",
"\n",
"if",
"fs",
".",
"ar",
".",
"StripTopLevelDir",
"{",
"entries",
",",
"err",
":=",
"fs",
".",
"fs",
".",
"ReadDir",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"entries",
")",
"==",
"1",
"&&",
"entries",
"[",
"0",
"]",
".",
"IsDir",
"(",
")",
"{",
"fs",
".",
"ar",
".",
"prefix",
"=",
"entries",
"[",
"0",
"]",
".",
"Name",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"fs",
".",
"ar",
".",
"prefix",
"!=",
"\"",
"\"",
"{",
"ns",
":=",
"vfs",
".",
"NameSpace",
"{",
"}",
"\n",
"ns",
".",
"Bind",
"(",
"\"",
"\"",
",",
"fs",
".",
"fs",
",",
"\"",
"\"",
"+",
"fs",
".",
"ar",
".",
"prefix",
",",
"vfs",
".",
"BindReplace",
")",
"\n",
"fs",
".",
"fs",
"=",
"ns",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"fs",
".",
"err",
"\n",
"}"
] | // fetchOrWait initiates the fetch if it has not yet
// started. Otherwise it waits for it to finish. | [
"fetchOrWait",
"initiates",
"the",
"fetch",
"if",
"it",
"has",
"not",
"yet",
"started",
".",
"Otherwise",
"it",
"waits",
"for",
"it",
"to",
"finish",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/archive.go#L54-L84 |
sourcegraph/go-langserver | langserver/fs.go | handleFileSystemRequest | func (h *HandlerShared) handleFileSystemRequest(ctx context.Context, req *jsonrpc2.Request) (lsp.DocumentURI, bool, error) {
span := opentracing.SpanFromContext(ctx)
h.Mu.Lock()
overlay := h.overlay
h.Mu.Unlock()
do := func(uri lsp.DocumentURI, op func() error) (lsp.DocumentURI, bool, error) {
span.SetTag("uri", uri)
before, beforeErr := h.readFile(ctx, uri)
if beforeErr != nil && !os.IsNotExist(beforeErr) {
// There is no op that could succeed in this case. (Most
// commonly occurs when uri refers to a dir, not a file.)
return uri, false, beforeErr
}
err := op()
after, afterErr := h.readFile(ctx, uri)
if os.IsNotExist(beforeErr) && os.IsNotExist(afterErr) {
// File did not exist before or after so nothing has changed.
return uri, false, err
} else if afterErr != nil || beforeErr != nil {
// If an error prevented us from reading the file
// before or after then we assume the file changed to
// be conservative.
return uri, true, err
}
return uri, !bytes.Equal(before, after), err
}
switch req.Method {
case "textDocument/didOpen":
var params lsp.DidOpenTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
return do(params.TextDocument.URI, func() error {
overlay.didOpen(¶ms)
return nil
})
case "textDocument/didChange":
var params lsp.DidChangeTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
return do(params.TextDocument.URI, func() error {
return overlay.didChange(¶ms)
})
case "textDocument/didClose":
var params lsp.DidCloseTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
return do(params.TextDocument.URI, func() error {
overlay.didClose(¶ms)
return nil
})
case "textDocument/didSave":
var params lsp.DidSaveTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
// no-op
return params.TextDocument.URI, false, nil
default:
panic("unexpected file system request method: " + req.Method)
}
} | go | func (h *HandlerShared) handleFileSystemRequest(ctx context.Context, req *jsonrpc2.Request) (lsp.DocumentURI, bool, error) {
span := opentracing.SpanFromContext(ctx)
h.Mu.Lock()
overlay := h.overlay
h.Mu.Unlock()
do := func(uri lsp.DocumentURI, op func() error) (lsp.DocumentURI, bool, error) {
span.SetTag("uri", uri)
before, beforeErr := h.readFile(ctx, uri)
if beforeErr != nil && !os.IsNotExist(beforeErr) {
// There is no op that could succeed in this case. (Most
// commonly occurs when uri refers to a dir, not a file.)
return uri, false, beforeErr
}
err := op()
after, afterErr := h.readFile(ctx, uri)
if os.IsNotExist(beforeErr) && os.IsNotExist(afterErr) {
// File did not exist before or after so nothing has changed.
return uri, false, err
} else if afterErr != nil || beforeErr != nil {
// If an error prevented us from reading the file
// before or after then we assume the file changed to
// be conservative.
return uri, true, err
}
return uri, !bytes.Equal(before, after), err
}
switch req.Method {
case "textDocument/didOpen":
var params lsp.DidOpenTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
return do(params.TextDocument.URI, func() error {
overlay.didOpen(¶ms)
return nil
})
case "textDocument/didChange":
var params lsp.DidChangeTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
return do(params.TextDocument.URI, func() error {
return overlay.didChange(¶ms)
})
case "textDocument/didClose":
var params lsp.DidCloseTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
return do(params.TextDocument.URI, func() error {
overlay.didClose(¶ms)
return nil
})
case "textDocument/didSave":
var params lsp.DidSaveTextDocumentParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return "", false, err
}
// no-op
return params.TextDocument.URI, false, nil
default:
panic("unexpected file system request method: " + req.Method)
}
} | [
"func",
"(",
"h",
"*",
"HandlerShared",
")",
"handleFileSystemRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
")",
"(",
"lsp",
".",
"DocumentURI",
",",
"bool",
",",
"error",
")",
"{",
"span",
":=",
"opentracing",
".",
"SpanFromContext",
"(",
"ctx",
")",
"\n",
"h",
".",
"Mu",
".",
"Lock",
"(",
")",
"\n",
"overlay",
":=",
"h",
".",
"overlay",
"\n",
"h",
".",
"Mu",
".",
"Unlock",
"(",
")",
"\n\n",
"do",
":=",
"func",
"(",
"uri",
"lsp",
".",
"DocumentURI",
",",
"op",
"func",
"(",
")",
"error",
")",
"(",
"lsp",
".",
"DocumentURI",
",",
"bool",
",",
"error",
")",
"{",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"uri",
")",
"\n",
"before",
",",
"beforeErr",
":=",
"h",
".",
"readFile",
"(",
"ctx",
",",
"uri",
")",
"\n",
"if",
"beforeErr",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"beforeErr",
")",
"{",
"// There is no op that could succeed in this case. (Most",
"// commonly occurs when uri refers to a dir, not a file.)",
"return",
"uri",
",",
"false",
",",
"beforeErr",
"\n",
"}",
"\n",
"err",
":=",
"op",
"(",
")",
"\n",
"after",
",",
"afterErr",
":=",
"h",
".",
"readFile",
"(",
"ctx",
",",
"uri",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"beforeErr",
")",
"&&",
"os",
".",
"IsNotExist",
"(",
"afterErr",
")",
"{",
"// File did not exist before or after so nothing has changed.",
"return",
"uri",
",",
"false",
",",
"err",
"\n",
"}",
"else",
"if",
"afterErr",
"!=",
"nil",
"||",
"beforeErr",
"!=",
"nil",
"{",
"// If an error prevented us from reading the file",
"// before or after then we assume the file changed to",
"// be conservative.",
"return",
"uri",
",",
"true",
",",
"err",
"\n",
"}",
"\n",
"return",
"uri",
",",
"!",
"bytes",
".",
"Equal",
"(",
"before",
",",
"after",
")",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"req",
".",
"Method",
"{",
"case",
"\"",
"\"",
":",
"var",
"params",
"lsp",
".",
"DidOpenTextDocumentParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"do",
"(",
"params",
".",
"TextDocument",
".",
"URI",
",",
"func",
"(",
")",
"error",
"{",
"overlay",
".",
"didOpen",
"(",
"&",
"params",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"var",
"params",
"lsp",
".",
"DidChangeTextDocumentParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"do",
"(",
"params",
".",
"TextDocument",
".",
"URI",
",",
"func",
"(",
")",
"error",
"{",
"return",
"overlay",
".",
"didChange",
"(",
"&",
"params",
")",
"\n",
"}",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"var",
"params",
"lsp",
".",
"DidCloseTextDocumentParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"do",
"(",
"params",
".",
"TextDocument",
".",
"URI",
",",
"func",
"(",
")",
"error",
"{",
"overlay",
".",
"didClose",
"(",
"&",
"params",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"var",
"params",
"lsp",
".",
"DidSaveTextDocumentParams",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
".",
"Params",
",",
"&",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"// no-op",
"return",
"params",
".",
"TextDocument",
".",
"URI",
",",
"false",
",",
"nil",
"\n\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
"+",
"req",
".",
"Method",
")",
"\n",
"}",
"\n",
"}"
] | // handleFileSystemRequest handles textDocument/did* requests. The URI the
// request is for is returned. true is returned if a file was modified. | [
"handleFileSystemRequest",
"handles",
"textDocument",
"/",
"did",
"*",
"requests",
".",
"The",
"URI",
"the",
"request",
"is",
"for",
"is",
"returned",
".",
"true",
"is",
"returned",
"if",
"a",
"file",
"was",
"modified",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L34-L103 |
sourcegraph/go-langserver | langserver/fs.go | FS | func (h *overlay) FS() ctxvfs.FileSystem {
return ctxvfs.Sync(&h.mu, ctxvfs.Map(h.m))
} | go | func (h *overlay) FS() ctxvfs.FileSystem {
return ctxvfs.Sync(&h.mu, ctxvfs.Map(h.m))
} | [
"func",
"(",
"h",
"*",
"overlay",
")",
"FS",
"(",
")",
"ctxvfs",
".",
"FileSystem",
"{",
"return",
"ctxvfs",
".",
"Sync",
"(",
"&",
"h",
".",
"mu",
",",
"ctxvfs",
".",
"Map",
"(",
"h",
".",
"m",
")",
")",
"\n",
"}"
] | // FS returns a vfs for the overlay. | [
"FS",
"returns",
"a",
"vfs",
"for",
"the",
"overlay",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L117-L119 |
sourcegraph/go-langserver | langserver/fs.go | applyContentChanges | func applyContentChanges(uri lsp.DocumentURI, contents []byte, changes []lsp.TextDocumentContentChangeEvent) ([]byte, error) {
for _, change := range changes {
if change.Range == nil && change.RangeLength == 0 {
contents = []byte(change.Text) // new full content
continue
}
start, ok, why := offsetForPosition(contents, change.Range.Start)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
var end int
if change.RangeLength != 0 {
end = start + int(change.RangeLength)
} else {
// RangeLength not specified, work it out from Range.End
end, ok, why = offsetForPosition(contents, change.Range.End)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
}
if start < 0 || end > len(contents) || end < start {
return nil, fmt.Errorf("received textDocument/didChange for out of range position %q on %q", change.Range, uri)
}
// Try avoid doing too many allocations, so use bytes.Buffer
b := &bytes.Buffer{}
b.Grow(start + len(change.Text) + len(contents) - end)
b.Write(contents[:start])
b.WriteString(change.Text)
b.Write(contents[end:])
contents = b.Bytes()
}
return contents, nil
} | go | func applyContentChanges(uri lsp.DocumentURI, contents []byte, changes []lsp.TextDocumentContentChangeEvent) ([]byte, error) {
for _, change := range changes {
if change.Range == nil && change.RangeLength == 0 {
contents = []byte(change.Text) // new full content
continue
}
start, ok, why := offsetForPosition(contents, change.Range.Start)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
var end int
if change.RangeLength != 0 {
end = start + int(change.RangeLength)
} else {
// RangeLength not specified, work it out from Range.End
end, ok, why = offsetForPosition(contents, change.Range.End)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
}
if start < 0 || end > len(contents) || end < start {
return nil, fmt.Errorf("received textDocument/didChange for out of range position %q on %q", change.Range, uri)
}
// Try avoid doing too many allocations, so use bytes.Buffer
b := &bytes.Buffer{}
b.Grow(start + len(change.Text) + len(contents) - end)
b.Write(contents[:start])
b.WriteString(change.Text)
b.Write(contents[end:])
contents = b.Bytes()
}
return contents, nil
} | [
"func",
"applyContentChanges",
"(",
"uri",
"lsp",
".",
"DocumentURI",
",",
"contents",
"[",
"]",
"byte",
",",
"changes",
"[",
"]",
"lsp",
".",
"TextDocumentContentChangeEvent",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"for",
"_",
",",
"change",
":=",
"range",
"changes",
"{",
"if",
"change",
".",
"Range",
"==",
"nil",
"&&",
"change",
".",
"RangeLength",
"==",
"0",
"{",
"contents",
"=",
"[",
"]",
"byte",
"(",
"change",
".",
"Text",
")",
"// new full content",
"\n",
"continue",
"\n",
"}",
"\n",
"start",
",",
"ok",
",",
"why",
":=",
"offsetForPosition",
"(",
"contents",
",",
"change",
".",
"Range",
".",
"Start",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"change",
".",
"Range",
".",
"Start",
",",
"uri",
",",
"why",
")",
"\n",
"}",
"\n",
"var",
"end",
"int",
"\n",
"if",
"change",
".",
"RangeLength",
"!=",
"0",
"{",
"end",
"=",
"start",
"+",
"int",
"(",
"change",
".",
"RangeLength",
")",
"\n",
"}",
"else",
"{",
"// RangeLength not specified, work it out from Range.End",
"end",
",",
"ok",
",",
"why",
"=",
"offsetForPosition",
"(",
"contents",
",",
"change",
".",
"Range",
".",
"End",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"change",
".",
"Range",
".",
"Start",
",",
"uri",
",",
"why",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"start",
"<",
"0",
"||",
"end",
">",
"len",
"(",
"contents",
")",
"||",
"end",
"<",
"start",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"change",
".",
"Range",
",",
"uri",
")",
"\n",
"}",
"\n",
"// Try avoid doing too many allocations, so use bytes.Buffer",
"b",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"b",
".",
"Grow",
"(",
"start",
"+",
"len",
"(",
"change",
".",
"Text",
")",
"+",
"len",
"(",
"contents",
")",
"-",
"end",
")",
"\n",
"b",
".",
"Write",
"(",
"contents",
"[",
":",
"start",
"]",
")",
"\n",
"b",
".",
"WriteString",
"(",
"change",
".",
"Text",
")",
"\n",
"b",
".",
"Write",
"(",
"contents",
"[",
"end",
":",
"]",
")",
"\n",
"contents",
"=",
"b",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"return",
"contents",
",",
"nil",
"\n",
"}"
] | // applyContentChanges updates `contents` based on `changes` | [
"applyContentChanges",
"updates",
"contents",
"based",
"on",
"changes"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L141-L173 |
sourcegraph/go-langserver | langserver/fs.go | NewAtomicFS | func NewAtomicFS() *AtomicFS {
fs := &AtomicFS{}
fs.v.Store(make(ctxvfs.NameSpace))
return fs
} | go | func NewAtomicFS() *AtomicFS {
fs := &AtomicFS{}
fs.v.Store(make(ctxvfs.NameSpace))
return fs
} | [
"func",
"NewAtomicFS",
"(",
")",
"*",
"AtomicFS",
"{",
"fs",
":=",
"&",
"AtomicFS",
"{",
"}",
"\n",
"fs",
".",
"v",
".",
"Store",
"(",
"make",
"(",
"ctxvfs",
".",
"NameSpace",
")",
")",
"\n",
"return",
"fs",
"\n",
"}"
] | // NewAtomicFS returns an AtomicFS with an empty wrapped ctxvfs.NameSpace | [
"NewAtomicFS",
"returns",
"an",
"AtomicFS",
"with",
"an",
"empty",
"wrapped",
"ctxvfs",
".",
"NameSpace"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L242-L246 |
sourcegraph/go-langserver | langserver/fs.go | Bind | func (a *AtomicFS) Bind(old string, newfs ctxvfs.FileSystem, new string, mode ctxvfs.BindMode) {
// We do copy-on-write
a.mu.Lock()
defer a.mu.Unlock()
fs1 := a.v.Load().(ctxvfs.NameSpace)
fs2 := make(ctxvfs.NameSpace)
for k, v := range fs1 {
fs2[k] = v
}
fs2.Bind(old, newfs, new, mode)
a.v.Store(fs2)
} | go | func (a *AtomicFS) Bind(old string, newfs ctxvfs.FileSystem, new string, mode ctxvfs.BindMode) {
// We do copy-on-write
a.mu.Lock()
defer a.mu.Unlock()
fs1 := a.v.Load().(ctxvfs.NameSpace)
fs2 := make(ctxvfs.NameSpace)
for k, v := range fs1 {
fs2[k] = v
}
fs2.Bind(old, newfs, new, mode)
a.v.Store(fs2)
} | [
"func",
"(",
"a",
"*",
"AtomicFS",
")",
"Bind",
"(",
"old",
"string",
",",
"newfs",
"ctxvfs",
".",
"FileSystem",
",",
"new",
"string",
",",
"mode",
"ctxvfs",
".",
"BindMode",
")",
"{",
"// We do copy-on-write",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"fs1",
":=",
"a",
".",
"v",
".",
"Load",
"(",
")",
".",
"(",
"ctxvfs",
".",
"NameSpace",
")",
"\n",
"fs2",
":=",
"make",
"(",
"ctxvfs",
".",
"NameSpace",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"fs1",
"{",
"fs2",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"fs2",
".",
"Bind",
"(",
"old",
",",
"newfs",
",",
"new",
",",
"mode",
")",
"\n",
"a",
".",
"v",
".",
"Store",
"(",
"fs2",
")",
"\n",
"}"
] | // Bind wraps ctxvfs.NameSpace.Bind | [
"Bind",
"wraps",
"ctxvfs",
".",
"NameSpace",
".",
"Bind"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L249-L261 |
sourcegraph/go-langserver | langserver/fs.go | Open | func (a *AtomicFS) Open(ctx context.Context, path string) (ctxvfs.ReadSeekCloser, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Open(ctx, path)
} | go | func (a *AtomicFS) Open(ctx context.Context, path string) (ctxvfs.ReadSeekCloser, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Open(ctx, path)
} | [
"func",
"(",
"a",
"*",
"AtomicFS",
")",
"Open",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"ctxvfs",
".",
"ReadSeekCloser",
",",
"error",
")",
"{",
"fs",
":=",
"a",
".",
"v",
".",
"Load",
"(",
")",
".",
"(",
"ctxvfs",
".",
"NameSpace",
")",
"\n",
"return",
"fs",
".",
"Open",
"(",
"ctx",
",",
"path",
")",
"\n",
"}"
] | // Open wraps ctxvfs.NameSpace.Open | [
"Open",
"wraps",
"ctxvfs",
".",
"NameSpace",
".",
"Open"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L268-L271 |
sourcegraph/go-langserver | langserver/fs.go | Stat | func (a *AtomicFS) Stat(ctx context.Context, path string) (os.FileInfo, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Stat(ctx, path)
} | go | func (a *AtomicFS) Stat(ctx context.Context, path string) (os.FileInfo, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Stat(ctx, path)
} | [
"func",
"(",
"a",
"*",
"AtomicFS",
")",
"Stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"fs",
":=",
"a",
".",
"v",
".",
"Load",
"(",
")",
".",
"(",
"ctxvfs",
".",
"NameSpace",
")",
"\n",
"return",
"fs",
".",
"Stat",
"(",
"ctx",
",",
"path",
")",
"\n",
"}"
] | // Stat wraps ctxvfs.NameSpace.Stat | [
"Stat",
"wraps",
"ctxvfs",
".",
"NameSpace",
".",
"Stat"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L274-L277 |
sourcegraph/go-langserver | langserver/xcache.go | cacheGet | func (h *LangHandler) cacheGet(ctx context.Context, conn jsonrpc2.JSONRPC2, key string, v interface{}) bool {
if !h.init.Capabilities.XCacheProvider {
return false
}
var r json.RawMessage
err := conn.Call(ctx, "xcache/get", lspext.CacheGetParams{Key: key}, &r)
if err != nil {
return false
}
b := []byte(r)
if bytes.Equal(b, []byte("null")) {
return false
}
err = json.Unmarshal(b, &v)
return err == nil
} | go | func (h *LangHandler) cacheGet(ctx context.Context, conn jsonrpc2.JSONRPC2, key string, v interface{}) bool {
if !h.init.Capabilities.XCacheProvider {
return false
}
var r json.RawMessage
err := conn.Call(ctx, "xcache/get", lspext.CacheGetParams{Key: key}, &r)
if err != nil {
return false
}
b := []byte(r)
if bytes.Equal(b, []byte("null")) {
return false
}
err = json.Unmarshal(b, &v)
return err == nil
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"cacheGet",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"key",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"if",
"!",
"h",
".",
"init",
".",
"Capabilities",
".",
"XCacheProvider",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"var",
"r",
"json",
".",
"RawMessage",
"\n",
"err",
":=",
"conn",
".",
"Call",
"(",
"ctx",
",",
"\"",
"\"",
",",
"lspext",
".",
"CacheGetParams",
"{",
"Key",
":",
"key",
"}",
",",
"&",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"b",
":=",
"[",
"]",
"byte",
"(",
"r",
")",
"\n",
"if",
"bytes",
".",
"Equal",
"(",
"b",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"v",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] | // cacheGet will do a xcache/get request for key, and unmarshal the result
// into v on a cache hit. If it is a cache miss, false is returned. If the
// client is not a XCacheProvider, cacheGet will always return false. | [
"cacheGet",
"will",
"do",
"a",
"xcache",
"/",
"get",
"request",
"for",
"key",
"and",
"unmarshal",
"the",
"result",
"into",
"v",
"on",
"a",
"cache",
"hit",
".",
"If",
"it",
"is",
"a",
"cache",
"miss",
"false",
"is",
"returned",
".",
"If",
"the",
"client",
"is",
"not",
"a",
"XCacheProvider",
"cacheGet",
"will",
"always",
"return",
"false",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/xcache.go#L15-L31 |
sourcegraph/go-langserver | langserver/xcache.go | cacheSet | func (h *LangHandler) cacheSet(ctx context.Context, conn jsonrpc2.JSONRPC2, key string, v interface{}) {
if !h.init.Capabilities.XCacheProvider {
return
}
b, _ := json.Marshal(v)
m := json.RawMessage(b)
_ = conn.Notify(ctx, "xcache/set", lspext.CacheSetParams{Key: key, Value: &m})
} | go | func (h *LangHandler) cacheSet(ctx context.Context, conn jsonrpc2.JSONRPC2, key string, v interface{}) {
if !h.init.Capabilities.XCacheProvider {
return
}
b, _ := json.Marshal(v)
m := json.RawMessage(b)
_ = conn.Notify(ctx, "xcache/set", lspext.CacheSetParams{Key: key, Value: &m})
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"cacheSet",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"key",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"if",
"!",
"h",
".",
"init",
".",
"Capabilities",
".",
"XCacheProvider",
"{",
"return",
"\n",
"}",
"\n\n",
"b",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"v",
")",
"\n",
"m",
":=",
"json",
".",
"RawMessage",
"(",
"b",
")",
"\n",
"_",
"=",
"conn",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"lspext",
".",
"CacheSetParams",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"&",
"m",
"}",
")",
"\n",
"}"
] | // cacheSet will do a xcache/set request for key and a marshalled value. If
// the client is not a XCacheProvider, cacheSet will do nothing. | [
"cacheSet",
"will",
"do",
"a",
"xcache",
"/",
"set",
"request",
"for",
"key",
"and",
"a",
"marshalled",
"value",
".",
"If",
"the",
"client",
"is",
"not",
"a",
"XCacheProvider",
"cacheSet",
"will",
"do",
"nothing",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/xcache.go#L35-L43 |
sourcegraph/go-langserver | langserver/cache.go | newLRU | func newLRU(env string, defaultSize int) *lru.Cache {
size := defaultSize
if i, err := strconv.Atoi(os.Getenv(env)); err == nil && i > 0 {
size = i
}
c, err := lru.New(size)
if err != nil {
// This should never happen since our size is always > 0
panic(err)
}
return c
} | go | func newLRU(env string, defaultSize int) *lru.Cache {
size := defaultSize
if i, err := strconv.Atoi(os.Getenv(env)); err == nil && i > 0 {
size = i
}
c, err := lru.New(size)
if err != nil {
// This should never happen since our size is always > 0
panic(err)
}
return c
} | [
"func",
"newLRU",
"(",
"env",
"string",
",",
"defaultSize",
"int",
")",
"*",
"lru",
".",
"Cache",
"{",
"size",
":=",
"defaultSize",
"\n",
"if",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"os",
".",
"Getenv",
"(",
"env",
")",
")",
";",
"err",
"==",
"nil",
"&&",
"i",
">",
"0",
"{",
"size",
"=",
"i",
"\n",
"}",
"\n",
"c",
",",
"err",
":=",
"lru",
".",
"New",
"(",
"size",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// This should never happen since our size is always > 0",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // newLRU returns an LRU based cache. | [
"newLRU",
"returns",
"an",
"LRU",
"based",
"cache",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/cache.go#L142-L153 |
sourcegraph/go-langserver | buildserver/util.go | add | func (e *errorList) add(err error) {
e.mu.Lock()
e.errors = append(e.errors, err)
e.mu.Unlock()
} | go | func (e *errorList) add(err error) {
e.mu.Lock()
e.errors = append(e.errors, err)
e.mu.Unlock()
} | [
"func",
"(",
"e",
"*",
"errorList",
")",
"add",
"(",
"err",
"error",
")",
"{",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
".",
"errors",
"=",
"append",
"(",
"e",
".",
"errors",
",",
"err",
")",
"\n",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // add adds err to the list of errors. It is safe to call it from
// concurrent goroutines. | [
"add",
"adds",
"err",
"to",
"the",
"list",
"of",
"errors",
".",
"It",
"is",
"safe",
"to",
"call",
"it",
"from",
"concurrent",
"goroutines",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/util.go#L15-L19 |
sourcegraph/go-langserver | buildserver/util.go | error | func (e *errorList) error() error {
switch len(e.errors) {
case 0:
return nil
case 1:
return e.errors[0]
default:
return fmt.Errorf("%s [and %d more errors]", e.errors[0], len(e.errors)-1)
}
} | go | func (e *errorList) error() error {
switch len(e.errors) {
case 0:
return nil
case 1:
return e.errors[0]
default:
return fmt.Errorf("%s [and %d more errors]", e.errors[0], len(e.errors)-1)
}
} | [
"func",
"(",
"e",
"*",
"errorList",
")",
"error",
"(",
")",
"error",
"{",
"switch",
"len",
"(",
"e",
".",
"errors",
")",
"{",
"case",
"0",
":",
"return",
"nil",
"\n",
"case",
"1",
":",
"return",
"e",
".",
"errors",
"[",
"0",
"]",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"e",
".",
"errors",
"[",
"0",
"]",
",",
"len",
"(",
"e",
".",
"errors",
")",
"-",
"1",
")",
"\n",
"}",
"\n",
"}"
] | // errors returns the list of errors as a single error. It is NOT safe
// to call from concurrent goroutines. | [
"errors",
"returns",
"the",
"list",
"of",
"errors",
"as",
"a",
"single",
"error",
".",
"It",
"is",
"NOT",
"safe",
"to",
"call",
"from",
"concurrent",
"goroutines",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/util.go#L23-L32 |
sourcegraph/go-langserver | langserver/handler_shared.go | getFindPackageFunc | func (h *HandlerShared) getFindPackageFunc() FindPackageFunc {
if h.FindPackage != nil {
return h.FindPackage
}
return defaultFindPackageFunc
} | go | func (h *HandlerShared) getFindPackageFunc() FindPackageFunc {
if h.FindPackage != nil {
return h.FindPackage
}
return defaultFindPackageFunc
} | [
"func",
"(",
"h",
"*",
"HandlerShared",
")",
"getFindPackageFunc",
"(",
")",
"FindPackageFunc",
"{",
"if",
"h",
".",
"FindPackage",
"!=",
"nil",
"{",
"return",
"h",
".",
"FindPackage",
"\n",
"}",
"\n",
"return",
"defaultFindPackageFunc",
"\n",
"}"
] | // getFindPackageFunc is a helper which returns h.FindPackage if non-nil, otherwise defaultFindPackageFunc | [
"getFindPackageFunc",
"is",
"a",
"helper",
"which",
"returns",
"h",
".",
"FindPackage",
"if",
"non",
"-",
"nil",
"otherwise",
"defaultFindPackageFunc"
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler_shared.go#L93-L98 |
sourcegraph/go-langserver | vfsutil/cache.go | Evict | func (f *cachedFile) Evict() {
// Best-effort. Ignore error
_ = os.Remove(f.path)
cachedFileEvict.Inc()
} | go | func (f *cachedFile) Evict() {
// Best-effort. Ignore error
_ = os.Remove(f.path)
cachedFileEvict.Inc()
} | [
"func",
"(",
"f",
"*",
"cachedFile",
")",
"Evict",
"(",
")",
"{",
"// Best-effort. Ignore error",
"_",
"=",
"os",
".",
"Remove",
"(",
"f",
".",
"path",
")",
"\n",
"cachedFileEvict",
".",
"Inc",
"(",
")",
"\n",
"}"
] | // Evict will remove the file from the cache. It does not close File. It also
// does not protect against other open readers or concurrent fetches. | [
"Evict",
"will",
"remove",
"the",
"file",
"from",
"the",
"cache",
".",
"It",
"does",
"not",
"close",
"File",
".",
"It",
"also",
"does",
"not",
"protect",
"against",
"other",
"open",
"readers",
"or",
"concurrent",
"fetches",
"."
] | train | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/cache.go#L38-L42 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.