repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
google/go-github
github/github-accessors.go
GetRemoteName
func (s *SourceImportAuthor) GetRemoteName() string { if s == nil || s.RemoteName == nil { return "" } return *s.RemoteName }
go
func (s *SourceImportAuthor) GetRemoteName() string { if s == nil || s.RemoteName == nil { return "" } return *s.RemoteName }
[ "func", "(", "s", "*", "SourceImportAuthor", ")", "GetRemoteName", "(", ")", "string", "{", "if", "s", "==", "nil", "||", "s", ".", "RemoteName", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "s", ".", "RemoteName", "\n", "}" ]
// GetRemoteName returns the RemoteName field if it's non-nil, zero value otherwise.
[ "GetRemoteName", "returns", "the", "RemoteName", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L10680-L10685
train
google/go-github
github/github-accessors.go
GetIgnored
func (s *Subscription) GetIgnored() bool { if s == nil || s.Ignored == nil { return false } return *s.Ignored }
go
func (s *Subscription) GetIgnored() bool { if s == nil || s.Ignored == nil { return false } return *s.Ignored }
[ "func", "(", "s", "*", "Subscription", ")", "GetIgnored", "(", ")", "bool", "{", "if", "s", "==", "nil", "||", "s", ".", "Ignored", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "s", ".", "Ignored", "\n", "}" ]
// GetIgnored returns the Ignored field if it's non-nil, zero value otherwise.
[ "GetIgnored", "returns", "the", "Ignored", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L10856-L10861
train
google/go-github
github/github-accessors.go
GetSubscribed
func (s *Subscription) GetSubscribed() bool { if s == nil || s.Subscribed == nil { return false } return *s.Subscribed }
go
func (s *Subscription) GetSubscribed() bool { if s == nil || s.Subscribed == nil { return false } return *s.Subscribed }
[ "func", "(", "s", "*", "Subscription", ")", "GetSubscribed", "(", ")", "bool", "{", "if", "s", "==", "nil", "||", "s", ".", "Subscribed", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "s", ".", "Subscribed", "\n", "}" ]
// GetSubscribed returns the Subscribed field if it's non-nil, zero value otherwise.
[ "GetSubscribed", "returns", "the", "Subscribed", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L10880-L10885
train
google/go-github
github/github-accessors.go
GetThreadURL
func (s *Subscription) GetThreadURL() string { if s == nil || s.ThreadURL == nil { return "" } return *s.ThreadURL }
go
func (s *Subscription) GetThreadURL() string { if s == nil || s.ThreadURL == nil { return "" } return *s.ThreadURL }
[ "func", "(", "s", "*", "Subscription", ")", "GetThreadURL", "(", ")", "string", "{", "if", "s", "==", "nil", "||", "s", ".", "ThreadURL", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "s", ".", "ThreadURL", "\n", "}" ]
// GetThreadURL returns the ThreadURL field if it's non-nil, zero value otherwise.
[ "GetThreadURL", "returns", "the", "ThreadURL", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L10888-L10893
train
google/go-github
github/github-accessors.go
GetTag
func (t *Tag) GetTag() string { if t == nil || t.Tag == nil { return "" } return *t.Tag }
go
func (t *Tag) GetTag() string { if t == nil || t.Tag == nil { return "" } return *t.Tag }
[ "func", "(", "t", "*", "Tag", ")", "GetTag", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "Tag", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "Tag", "\n", "}" ]
// GetTag returns the Tag field if it's non-nil, zero value otherwise.
[ "GetTag", "returns", "the", "Tag", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L10936-L10941
train
google/go-github
github/github-accessors.go
GetMembersCount
func (t *Team) GetMembersCount() int { if t == nil || t.MembersCount == nil { return 0 } return *t.MembersCount }
go
func (t *Team) GetMembersCount() int { if t == nil || t.MembersCount == nil { return 0 } return *t.MembersCount }
[ "func", "(", "t", "*", "Team", ")", "GetMembersCount", "(", ")", "int", "{", "if", "t", "==", "nil", "||", "t", ".", "MembersCount", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "*", "t", ".", "MembersCount", "\n", "}" ]
// GetMembersCount returns the MembersCount field if it's non-nil, zero value otherwise.
[ "GetMembersCount", "returns", "the", "MembersCount", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L10992-L10997
train
google/go-github
github/github-accessors.go
GetReposCount
func (t *Team) GetReposCount() int { if t == nil || t.ReposCount == nil { return 0 } return *t.ReposCount }
go
func (t *Team) GetReposCount() int { if t == nil || t.ReposCount == nil { return 0 } return *t.ReposCount }
[ "func", "(", "t", "*", "Team", ")", "GetReposCount", "(", ")", "int", "{", "if", "t", "==", "nil", "||", "t", ".", "ReposCount", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "*", "t", ".", "ReposCount", "\n", "}" ]
// GetReposCount returns the ReposCount field if it's non-nil, zero value otherwise.
[ "GetReposCount", "returns", "the", "ReposCount", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11056-L11061
train
google/go-github
github/github-accessors.go
GetCommentsCount
func (t *TeamDiscussion) GetCommentsCount() int { if t == nil || t.CommentsCount == nil { return 0 } return *t.CommentsCount }
go
func (t *TeamDiscussion) GetCommentsCount() int { if t == nil || t.CommentsCount == nil { return 0 } return *t.CommentsCount }
[ "func", "(", "t", "*", "TeamDiscussion", ")", "GetCommentsCount", "(", ")", "int", "{", "if", "t", "==", "nil", "||", "t", ".", "CommentsCount", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "*", "t", ".", "CommentsCount", "\n", "}" ]
// GetCommentsCount returns the CommentsCount field if it's non-nil, zero value otherwise.
[ "GetCommentsCount", "returns", "the", "CommentsCount", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11160-L11165
train
google/go-github
github/github-accessors.go
GetPinned
func (t *TeamDiscussion) GetPinned() bool { if t == nil || t.Pinned == nil { return false } return *t.Pinned }
go
func (t *TeamDiscussion) GetPinned() bool { if t == nil || t.Pinned == nil { return false } return *t.Pinned }
[ "func", "(", "t", "*", "TeamDiscussion", ")", "GetPinned", "(", ")", "bool", "{", "if", "t", "==", "nil", "||", "t", ".", "Pinned", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "t", ".", "Pinned", "\n", "}" ]
// GetPinned returns the Pinned field if it's non-nil, zero value otherwise.
[ "GetPinned", "returns", "the", "Pinned", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11216-L11221
train
google/go-github
github/github-accessors.go
GetTeamURL
func (t *TeamDiscussion) GetTeamURL() string { if t == nil || t.TeamURL == nil { return "" } return *t.TeamURL }
go
func (t *TeamDiscussion) GetTeamURL() string { if t == nil || t.TeamURL == nil { return "" } return *t.TeamURL }
[ "func", "(", "t", "*", "TeamDiscussion", ")", "GetTeamURL", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "TeamURL", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "TeamURL", "\n", "}" ]
// GetTeamURL returns the TeamURL field if it's non-nil, zero value otherwise.
[ "GetTeamURL", "returns", "the", "TeamURL", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11240-L11245
train
google/go-github
github/github-accessors.go
GetFragment
func (t *TextMatch) GetFragment() string { if t == nil || t.Fragment == nil { return "" } return *t.Fragment }
go
func (t *TextMatch) GetFragment() string { if t == nil || t.Fragment == nil { return "" } return *t.Fragment }
[ "func", "(", "t", "*", "TextMatch", ")", "GetFragment", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "Fragment", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "Fragment", "\n", "}" ]
// GetFragment returns the Fragment field if it's non-nil, zero value otherwise.
[ "GetFragment", "returns", "the", "Fragment", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11416-L11421
train
google/go-github
github/github-accessors.go
GetObjectType
func (t *TextMatch) GetObjectType() string { if t == nil || t.ObjectType == nil { return "" } return *t.ObjectType }
go
func (t *TextMatch) GetObjectType() string { if t == nil || t.ObjectType == nil { return "" } return *t.ObjectType }
[ "func", "(", "t", "*", "TextMatch", ")", "GetObjectType", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "ObjectType", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "ObjectType", "\n", "}" ]
// GetObjectType returns the ObjectType field if it's non-nil, zero value otherwise.
[ "GetObjectType", "returns", "the", "ObjectType", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11424-L11429
train
google/go-github
github/github-accessors.go
GetObjectURL
func (t *TextMatch) GetObjectURL() string { if t == nil || t.ObjectURL == nil { return "" } return *t.ObjectURL }
go
func (t *TextMatch) GetObjectURL() string { if t == nil || t.ObjectURL == nil { return "" } return *t.ObjectURL }
[ "func", "(", "t", "*", "TextMatch", ")", "GetObjectURL", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "ObjectURL", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "ObjectURL", "\n", "}" ]
// GetObjectURL returns the ObjectURL field if it's non-nil, zero value otherwise.
[ "GetObjectURL", "returns", "the", "ObjectURL", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11432-L11437
train
google/go-github
github/github-accessors.go
GetProperty
func (t *TextMatch) GetProperty() string { if t == nil || t.Property == nil { return "" } return *t.Property }
go
func (t *TextMatch) GetProperty() string { if t == nil || t.Property == nil { return "" } return *t.Property }
[ "func", "(", "t", "*", "TextMatch", ")", "GetProperty", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "Property", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "Property", "\n", "}" ]
// GetProperty returns the Property field if it's non-nil, zero value otherwise.
[ "GetProperty", "returns", "the", "Property", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11440-L11445
train
google/go-github
github/github-accessors.go
GetReferrer
func (t *TrafficReferrer) GetReferrer() string { if t == nil || t.Referrer == nil { return "" } return *t.Referrer }
go
func (t *TrafficReferrer) GetReferrer() string { if t == nil || t.Referrer == nil { return "" } return *t.Referrer }
[ "func", "(", "t", "*", "TrafficReferrer", ")", "GetReferrer", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "Referrer", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "Referrer", "\n", "}" ]
// GetReferrer returns the Referrer field if it's non-nil, zero value otherwise.
[ "GetReferrer", "returns", "the", "Referrer", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11632-L11637
train
google/go-github
github/github-accessors.go
GetTruncated
func (t *Tree) GetTruncated() bool { if t == nil || t.Truncated == nil { return false } return *t.Truncated }
go
func (t *Tree) GetTruncated() bool { if t == nil || t.Truncated == nil { return false } return *t.Truncated }
[ "func", "(", "t", "*", "Tree", ")", "GetTruncated", "(", ")", "bool", "{", "if", "t", "==", "nil", "||", "t", ".", "Truncated", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "t", ".", "Truncated", "\n", "}" ]
// GetTruncated returns the Truncated field if it's non-nil, zero value otherwise.
[ "GetTruncated", "returns", "the", "Truncated", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11672-L11677
train
google/go-github
github/github-accessors.go
GetMode
func (t *TreeEntry) GetMode() string { if t == nil || t.Mode == nil { return "" } return *t.Mode }
go
func (t *TreeEntry) GetMode() string { if t == nil || t.Mode == nil { return "" } return *t.Mode }
[ "func", "(", "t", "*", "TreeEntry", ")", "GetMode", "(", ")", "string", "{", "if", "t", "==", "nil", "||", "t", ".", "Mode", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "t", ".", "Mode", "\n", "}" ]
// GetMode returns the Mode field if it's non-nil, zero value otherwise.
[ "GetMode", "returns", "the", "Mode", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11688-L11693
train
google/go-github
github/github-accessors.go
GetBio
func (u *User) GetBio() string { if u == nil || u.Bio == nil { return "" } return *u.Bio }
go
func (u *User) GetBio() string { if u == nil || u.Bio == nil { return "" } return *u.Bio }
[ "func", "(", "u", "*", "User", ")", "GetBio", "(", ")", "string", "{", "if", "u", "==", "nil", "||", "u", ".", "Bio", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "u", ".", "Bio", "\n", "}" ]
// GetBio returns the Bio field if it's non-nil, zero value otherwise.
[ "GetBio", "returns", "the", "Bio", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11808-L11813
train
google/go-github
github/github-accessors.go
GetHireable
func (u *User) GetHireable() bool { if u == nil || u.Hireable == nil { return false } return *u.Hireable }
go
func (u *User) GetHireable() bool { if u == nil || u.Hireable == nil { return false } return *u.Hireable }
[ "func", "(", "u", "*", "User", ")", "GetHireable", "(", ")", "bool", "{", "if", "u", "==", "nil", "||", "u", ".", "Hireable", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "u", ".", "Hireable", "\n", "}" ]
// GetHireable returns the Hireable field if it's non-nil, zero value otherwise.
[ "GetHireable", "returns", "the", "Hireable", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L11920-L11925
train
google/go-github
github/github-accessors.go
GetSuspendedAt
func (u *User) GetSuspendedAt() Timestamp { if u == nil || u.SuspendedAt == nil { return Timestamp{} } return *u.SuspendedAt }
go
func (u *User) GetSuspendedAt() Timestamp { if u == nil || u.SuspendedAt == nil { return Timestamp{} } return *u.SuspendedAt }
[ "func", "(", "u", "*", "User", ")", "GetSuspendedAt", "(", ")", "Timestamp", "{", "if", "u", "==", "nil", "||", "u", ".", "SuspendedAt", "==", "nil", "{", "return", "Timestamp", "{", "}", "\n", "}", "\n", "return", "*", "u", ".", "SuspendedAt", "\n", "}" ]
// GetSuspendedAt returns the SuspendedAt field if it's non-nil, zero value otherwise.
[ "GetSuspendedAt", "returns", "the", "SuspendedAt", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12072-L12077
train
google/go-github
github/github-accessors.go
GetTwoFactorAuthentication
func (u *User) GetTwoFactorAuthentication() bool { if u == nil || u.TwoFactorAuthentication == nil { return false } return *u.TwoFactorAuthentication }
go
func (u *User) GetTwoFactorAuthentication() bool { if u == nil || u.TwoFactorAuthentication == nil { return false } return *u.TwoFactorAuthentication }
[ "func", "(", "u", "*", "User", ")", "GetTwoFactorAuthentication", "(", ")", "bool", "{", "if", "u", "==", "nil", "||", "u", ".", "TwoFactorAuthentication", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "u", ".", "TwoFactorAuthentication", "\n", "}" ]
// GetTwoFactorAuthentication returns the TwoFactorAuthentication field if it's non-nil, zero value otherwise.
[ "GetTwoFactorAuthentication", "returns", "the", "TwoFactorAuthentication", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12088-L12093
train
google/go-github
github/github-accessors.go
GetOcticon
func (u *UserContext) GetOcticon() string { if u == nil || u.Octicon == nil { return "" } return *u.Octicon }
go
func (u *UserContext) GetOcticon() string { if u == nil || u.Octicon == nil { return "" } return *u.Octicon }
[ "func", "(", "u", "*", "UserContext", ")", "GetOcticon", "(", ")", "string", "{", "if", "u", "==", "nil", "||", "u", ".", "Octicon", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "u", ".", "Octicon", "\n", "}" ]
// GetOcticon returns the Octicon field if it's non-nil, zero value otherwise.
[ "GetOcticon", "returns", "the", "Octicon", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12128-L12133
train
google/go-github
github/github-accessors.go
GetPrimary
func (u *UserEmail) GetPrimary() bool { if u == nil || u.Primary == nil { return false } return *u.Primary }
go
func (u *UserEmail) GetPrimary() bool { if u == nil || u.Primary == nil { return false } return *u.Primary }
[ "func", "(", "u", "*", "UserEmail", ")", "GetPrimary", "(", ")", "bool", "{", "if", "u", "==", "nil", "||", "u", ".", "Primary", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "*", "u", ".", "Primary", "\n", "}" ]
// GetPrimary returns the Primary field if it's non-nil, zero value otherwise.
[ "GetPrimary", "returns", "the", "Primary", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12144-L12149
train
google/go-github
github/github-accessors.go
GetAdminUsers
func (u *UserStats) GetAdminUsers() int { if u == nil || u.AdminUsers == nil { return 0 } return *u.AdminUsers }
go
func (u *UserStats) GetAdminUsers() int { if u == nil || u.AdminUsers == nil { return 0 } return *u.AdminUsers }
[ "func", "(", "u", "*", "UserStats", ")", "GetAdminUsers", "(", ")", "int", "{", "if", "u", "==", "nil", "||", "u", ".", "AdminUsers", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "*", "u", ".", "AdminUsers", "\n", "}" ]
// GetAdminUsers returns the AdminUsers field if it's non-nil, zero value otherwise.
[ "GetAdminUsers", "returns", "the", "AdminUsers", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12376-L12381
train
google/go-github
github/github-accessors.go
GetSuspendedUsers
func (u *UserStats) GetSuspendedUsers() int { if u == nil || u.SuspendedUsers == nil { return 0 } return *u.SuspendedUsers }
go
func (u *UserStats) GetSuspendedUsers() int { if u == nil || u.SuspendedUsers == nil { return 0 } return *u.SuspendedUsers }
[ "func", "(", "u", "*", "UserStats", ")", "GetSuspendedUsers", "(", ")", "int", "{", "if", "u", "==", "nil", "||", "u", ".", "SuspendedUsers", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "*", "u", ".", "SuspendedUsers", "\n", "}" ]
// GetSuspendedUsers returns the SuspendedUsers field if it's non-nil, zero value otherwise.
[ "GetSuspendedUsers", "returns", "the", "SuspendedUsers", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12384-L12389
train
google/go-github
github/github-accessors.go
GetTotalUsers
func (u *UserStats) GetTotalUsers() int { if u == nil || u.TotalUsers == nil { return 0 } return *u.TotalUsers }
go
func (u *UserStats) GetTotalUsers() int { if u == nil || u.TotalUsers == nil { return 0 } return *u.TotalUsers }
[ "func", "(", "u", "*", "UserStats", ")", "GetTotalUsers", "(", ")", "int", "{", "if", "u", "==", "nil", "||", "u", ".", "TotalUsers", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "*", "u", ".", "TotalUsers", "\n", "}" ]
// GetTotalUsers returns the TotalUsers field if it's non-nil, zero value otherwise.
[ "GetTotalUsers", "returns", "the", "TotalUsers", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12392-L12397
train
google/go-github
github/github-accessors.go
GetUsername
func (w *WebHookAuthor) GetUsername() string { if w == nil || w.Username == nil { return "" } return *w.Username }
go
func (w *WebHookAuthor) GetUsername() string { if w == nil || w.Username == nil { return "" } return *w.Username }
[ "func", "(", "w", "*", "WebHookAuthor", ")", "GetUsername", "(", ")", "string", "{", "if", "w", "==", "nil", "||", "w", ".", "Username", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "*", "w", ".", "Username", "\n", "}" ]
// GetUsername returns the Username field if it's non-nil, zero value otherwise.
[ "GetUsername", "returns", "the", "Username", "field", "if", "it", "s", "non", "-", "nil", "zero", "value", "otherwise", "." ]
1fef44b9b427e6c43f92b2f20918e496c275393f
https://github.com/google/go-github/blob/1fef44b9b427e6c43f92b2f20918e496c275393f/github/github-accessors.go#L12456-L12461
train
graphql-go/graphql
schema.go
AddImplementation
func (gq *Schema) AddImplementation() error { // Keep track of all implementations by interface name. if gq.implementations == nil { gq.implementations = map[string][]*Object{} } for _, ttype := range gq.typeMap { if ttype, ok := ttype.(*Object); ok { for _, iface := range ttype.Interfaces() { impls, ok := gq.implementations[iface.Name()] if impls == nil || !ok { impls = []*Object{} } impls = append(impls, ttype) gq.implementations[iface.Name()] = impls } } } // Enforce correct interface implementations for _, ttype := range gq.typeMap { if ttype, ok := ttype.(*Object); ok { for _, iface := range ttype.Interfaces() { err := assertObjectImplementsInterface(gq, ttype, iface) if err != nil { return err } } } } return nil }
go
func (gq *Schema) AddImplementation() error { // Keep track of all implementations by interface name. if gq.implementations == nil { gq.implementations = map[string][]*Object{} } for _, ttype := range gq.typeMap { if ttype, ok := ttype.(*Object); ok { for _, iface := range ttype.Interfaces() { impls, ok := gq.implementations[iface.Name()] if impls == nil || !ok { impls = []*Object{} } impls = append(impls, ttype) gq.implementations[iface.Name()] = impls } } } // Enforce correct interface implementations for _, ttype := range gq.typeMap { if ttype, ok := ttype.(*Object); ok { for _, iface := range ttype.Interfaces() { err := assertObjectImplementsInterface(gq, ttype, iface) if err != nil { return err } } } } return nil }
[ "func", "(", "gq", "*", "Schema", ")", "AddImplementation", "(", ")", "error", "{", "// Keep track of all implementations by interface name.", "if", "gq", ".", "implementations", "==", "nil", "{", "gq", ".", "implementations", "=", "map", "[", "string", "]", "[", "]", "*", "Object", "{", "}", "\n", "}", "\n", "for", "_", ",", "ttype", ":=", "range", "gq", ".", "typeMap", "{", "if", "ttype", ",", "ok", ":=", "ttype", ".", "(", "*", "Object", ")", ";", "ok", "{", "for", "_", ",", "iface", ":=", "range", "ttype", ".", "Interfaces", "(", ")", "{", "impls", ",", "ok", ":=", "gq", ".", "implementations", "[", "iface", ".", "Name", "(", ")", "]", "\n", "if", "impls", "==", "nil", "||", "!", "ok", "{", "impls", "=", "[", "]", "*", "Object", "{", "}", "\n", "}", "\n", "impls", "=", "append", "(", "impls", ",", "ttype", ")", "\n", "gq", ".", "implementations", "[", "iface", ".", "Name", "(", ")", "]", "=", "impls", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Enforce correct interface implementations", "for", "_", ",", "ttype", ":=", "range", "gq", ".", "typeMap", "{", "if", "ttype", ",", "ok", ":=", "ttype", ".", "(", "*", "Object", ")", ";", "ok", "{", "for", "_", ",", "iface", ":=", "range", "ttype", ".", "Interfaces", "(", ")", "{", "err", ":=", "assertObjectImplementsInterface", "(", "gq", ",", "ttype", ",", "iface", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
//Added Check implementation of interfaces at runtime.. //Add Implementations at Runtime..
[ "Added", "Check", "implementation", "of", "interfaces", "at", "runtime", "..", "Add", "Implementations", "at", "Runtime", ".." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/schema.go#L154-L186
train
graphql-go/graphql
schema.go
AppendType
func (gq *Schema) AppendType(objectType Type) error { if objectType.Error() != nil { return objectType.Error() } var err error gq.typeMap, err = typeMapReducer(gq, gq.typeMap, objectType) if err != nil { return err } //Now Add interface implementation.. return gq.AddImplementation() }
go
func (gq *Schema) AppendType(objectType Type) error { if objectType.Error() != nil { return objectType.Error() } var err error gq.typeMap, err = typeMapReducer(gq, gq.typeMap, objectType) if err != nil { return err } //Now Add interface implementation.. return gq.AddImplementation() }
[ "func", "(", "gq", "*", "Schema", ")", "AppendType", "(", "objectType", "Type", ")", "error", "{", "if", "objectType", ".", "Error", "(", ")", "!=", "nil", "{", "return", "objectType", ".", "Error", "(", ")", "\n", "}", "\n", "var", "err", "error", "\n", "gq", ".", "typeMap", ",", "err", "=", "typeMapReducer", "(", "gq", ",", "gq", ".", "typeMap", ",", "objectType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "//Now Add interface implementation..", "return", "gq", ".", "AddImplementation", "(", ")", "\n", "}" ]
//Edited. To check add Types at RunTime.. //Append Runtime schema to typeMap
[ "Edited", ".", "To", "check", "add", "Types", "at", "RunTime", "..", "Append", "Runtime", "schema", "to", "typeMap" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/schema.go#L190-L201
train
graphql-go/graphql
schema.go
AddExtensions
func (gq *Schema) AddExtensions(e ...Extension) { gq.extensions = append(gq.extensions, e...) }
go
func (gq *Schema) AddExtensions(e ...Extension) { gq.extensions = append(gq.extensions, e...) }
[ "func", "(", "gq", "*", "Schema", ")", "AddExtensions", "(", "e", "...", "Extension", ")", "{", "gq", ".", "extensions", "=", "append", "(", "gq", ".", "extensions", ",", "e", "...", ")", "\n", "}" ]
// AddExtensions can be used to add additional extensions to the schema
[ "AddExtensions", "can", "be", "used", "to", "add", "additional", "extensions", "to", "the", "schema" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/schema.go#L270-L272
train
graphql-go/graphql
definition.go
IsInputType
func IsInputType(ttype Type) bool { switch GetNamed(ttype).(type) { case *Scalar, *Enum, *InputObject: return true default: return false } }
go
func IsInputType(ttype Type) bool { switch GetNamed(ttype).(type) { case *Scalar, *Enum, *InputObject: return true default: return false } }
[ "func", "IsInputType", "(", "ttype", "Type", ")", "bool", "{", "switch", "GetNamed", "(", "ttype", ")", ".", "(", "type", ")", "{", "case", "*", "Scalar", ",", "*", "Enum", ",", "*", "InputObject", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsInputType determines if given type is a GraphQLInputType
[ "IsInputType", "determines", "if", "given", "type", "is", "a", "GraphQLInputType" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L45-L52
train
graphql-go/graphql
definition.go
IsOutputType
func IsOutputType(ttype Type) bool { switch GetNamed(ttype).(type) { case *Scalar, *Object, *Interface, *Union, *Enum: return true default: return false } }
go
func IsOutputType(ttype Type) bool { switch GetNamed(ttype).(type) { case *Scalar, *Object, *Interface, *Union, *Enum: return true default: return false } }
[ "func", "IsOutputType", "(", "ttype", "Type", ")", "bool", "{", "switch", "GetNamed", "(", "ttype", ")", ".", "(", "type", ")", "{", "case", "*", "Scalar", ",", "*", "Object", ",", "*", "Interface", ",", "*", "Union", ",", "*", "Enum", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsOutputType determines if given type is a GraphQLOutputType
[ "IsOutputType", "determines", "if", "given", "type", "is", "a", "GraphQLOutputType" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L55-L62
train
graphql-go/graphql
definition.go
IsLeafType
func IsLeafType(ttype Type) bool { switch GetNamed(ttype).(type) { case *Scalar, *Enum: return true default: return false } }
go
func IsLeafType(ttype Type) bool { switch GetNamed(ttype).(type) { case *Scalar, *Enum: return true default: return false } }
[ "func", "IsLeafType", "(", "ttype", "Type", ")", "bool", "{", "switch", "GetNamed", "(", "ttype", ")", ".", "(", "type", ")", "{", "case", "*", "Scalar", ",", "*", "Enum", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsLeafType determines if given type is a leaf value
[ "IsLeafType", "determines", "if", "given", "type", "is", "a", "leaf", "value" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L77-L84
train
graphql-go/graphql
definition.go
GetNullable
func GetNullable(ttype Type) Nullable { if ttype, ok := ttype.(*NonNull); ok { return ttype.OfType } return ttype }
go
func GetNullable(ttype Type) Nullable { if ttype, ok := ttype.(*NonNull); ok { return ttype.OfType } return ttype }
[ "func", "GetNullable", "(", "ttype", "Type", ")", "Nullable", "{", "if", "ttype", ",", "ok", ":=", "ttype", ".", "(", "*", "NonNull", ")", ";", "ok", "{", "return", "ttype", ".", "OfType", "\n", "}", "\n", "return", "ttype", "\n", "}" ]
// GetNullable returns the Nullable type of the given GraphQL type
[ "GetNullable", "returns", "the", "Nullable", "type", "of", "the", "given", "GraphQL", "type" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L154-L159
train
graphql-go/graphql
definition.go
GetNamed
func GetNamed(ttype Type) Named { unmodifiedType := ttype for { switch typ := unmodifiedType.(type) { case *List: unmodifiedType = typ.OfType case *NonNull: unmodifiedType = typ.OfType default: return unmodifiedType } } }
go
func GetNamed(ttype Type) Named { unmodifiedType := ttype for { switch typ := unmodifiedType.(type) { case *List: unmodifiedType = typ.OfType case *NonNull: unmodifiedType = typ.OfType default: return unmodifiedType } } }
[ "func", "GetNamed", "(", "ttype", "Type", ")", "Named", "{", "unmodifiedType", ":=", "ttype", "\n", "for", "{", "switch", "typ", ":=", "unmodifiedType", ".", "(", "type", ")", "{", "case", "*", "List", ":", "unmodifiedType", "=", "typ", ".", "OfType", "\n", "case", "*", "NonNull", ":", "unmodifiedType", "=", "typ", ".", "OfType", "\n", "default", ":", "return", "unmodifiedType", "\n", "}", "\n", "}", "\n", "}" ]
// GetNamed returns the Named type of the given GraphQL type
[ "GetNamed", "returns", "the", "Named", "type", "of", "the", "given", "GraphQL", "type" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L174-L186
train
graphql-go/graphql
definition.go
NewScalar
func NewScalar(config ScalarConfig) *Scalar { st := &Scalar{} err := invariant(config.Name != "", "Type must be named.") if err != nil { st.err = err return st } err = assertValidName(config.Name) if err != nil { st.err = err return st } st.PrivateName = config.Name st.PrivateDescription = config.Description err = invariantf( config.Serialize != nil, `%v must provide "serialize" function. If this custom Scalar is `+ `also used as an input type, ensure "parseValue" and "parseLiteral" `+ `functions are also provided.`, st, ) if err != nil { st.err = err return st } if config.ParseValue != nil || config.ParseLiteral != nil { err = invariantf( config.ParseValue != nil && config.ParseLiteral != nil, `%v must provide both "parseValue" and "parseLiteral" functions.`, st, ) if err != nil { st.err = err return st } } st.scalarConfig = config return st }
go
func NewScalar(config ScalarConfig) *Scalar { st := &Scalar{} err := invariant(config.Name != "", "Type must be named.") if err != nil { st.err = err return st } err = assertValidName(config.Name) if err != nil { st.err = err return st } st.PrivateName = config.Name st.PrivateDescription = config.Description err = invariantf( config.Serialize != nil, `%v must provide "serialize" function. If this custom Scalar is `+ `also used as an input type, ensure "parseValue" and "parseLiteral" `+ `functions are also provided.`, st, ) if err != nil { st.err = err return st } if config.ParseValue != nil || config.ParseLiteral != nil { err = invariantf( config.ParseValue != nil && config.ParseLiteral != nil, `%v must provide both "parseValue" and "parseLiteral" functions.`, st, ) if err != nil { st.err = err return st } } st.scalarConfig = config return st }
[ "func", "NewScalar", "(", "config", "ScalarConfig", ")", "*", "Scalar", "{", "st", ":=", "&", "Scalar", "{", "}", "\n", "err", ":=", "invariant", "(", "config", ".", "Name", "!=", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "st", ".", "err", "=", "err", "\n", "return", "st", "\n", "}", "\n\n", "err", "=", "assertValidName", "(", "config", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "st", ".", "err", "=", "err", "\n", "return", "st", "\n", "}", "\n\n", "st", ".", "PrivateName", "=", "config", ".", "Name", "\n", "st", ".", "PrivateDescription", "=", "config", ".", "Description", "\n\n", "err", "=", "invariantf", "(", "config", ".", "Serialize", "!=", "nil", ",", "`%v must provide \"serialize\" function. If this custom Scalar is `", "+", "`also used as an input type, ensure \"parseValue\" and \"parseLiteral\" `", "+", "`functions are also provided.`", ",", "st", ",", ")", "\n", "if", "err", "!=", "nil", "{", "st", ".", "err", "=", "err", "\n", "return", "st", "\n", "}", "\n", "if", "config", ".", "ParseValue", "!=", "nil", "||", "config", ".", "ParseLiteral", "!=", "nil", "{", "err", "=", "invariantf", "(", "config", ".", "ParseValue", "!=", "nil", "&&", "config", ".", "ParseLiteral", "!=", "nil", ",", "`%v must provide both \"parseValue\" and \"parseLiteral\" functions.`", ",", "st", ",", ")", "\n", "if", "err", "!=", "nil", "{", "st", ".", "err", "=", "err", "\n", "return", "st", "\n", "}", "\n", "}", "\n\n", "st", ".", "scalarConfig", "=", "config", "\n", "return", "st", "\n", "}" ]
// NewScalar creates a new GraphQLScalar
[ "NewScalar", "creates", "a", "new", "GraphQLScalar" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L230-L270
train
graphql-go/graphql
definition.go
WithKey
func (p *ResponsePath) WithKey(key interface{}) *ResponsePath { return &ResponsePath{ Prev: p, Key: key, } }
go
func (p *ResponsePath) WithKey(key interface{}) *ResponsePath { return &ResponsePath{ Prev: p, Key: key, } }
[ "func", "(", "p", "*", "ResponsePath", ")", "WithKey", "(", "key", "interface", "{", "}", ")", "*", "ResponsePath", "{", "return", "&", "ResponsePath", "{", "Prev", ":", "p", ",", "Key", ":", "key", ",", "}", "\n", "}" ]
// WithKey returns a new responsePath containing the new key.
[ "WithKey", "returns", "a", "new", "responsePath", "containing", "the", "new", "key", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L1306-L1311
train
graphql-go/graphql
definition.go
AsArray
func (p *ResponsePath) AsArray() []interface{} { if p == nil { return nil } return append(p.Prev.AsArray(), p.Key) }
go
func (p *ResponsePath) AsArray() []interface{} { if p == nil { return nil } return append(p.Prev.AsArray(), p.Key) }
[ "func", "(", "p", "*", "ResponsePath", ")", "AsArray", "(", ")", "[", "]", "interface", "{", "}", "{", "if", "p", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "append", "(", "p", ".", "Prev", ".", "AsArray", "(", ")", ",", "p", ".", "Key", ")", "\n", "}" ]
// AsArray returns an array of path keys.
[ "AsArray", "returns", "an", "array", "of", "path", "keys", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/definition.go#L1314-L1319
train
graphql-go/graphql
executor.go
getOperationRootType
func getOperationRootType(schema Schema, operation ast.Definition) (*Object, error) { if operation == nil { return nil, errors.New("Can only execute queries, mutations and subscription") } switch operation.GetOperation() { case ast.OperationTypeQuery: return schema.QueryType(), nil case ast.OperationTypeMutation: mutationType := schema.MutationType() if mutationType == nil || mutationType.PrivateName == "" { return nil, gqlerrors.NewError( "Schema is not configured for mutations", []ast.Node{operation}, "", nil, []int{}, nil, ) } return mutationType, nil case ast.OperationTypeSubscription: subscriptionType := schema.SubscriptionType() if subscriptionType == nil || subscriptionType.PrivateName == "" { return nil, gqlerrors.NewError( "Schema is not configured for subscriptions", []ast.Node{operation}, "", nil, []int{}, nil, ) } return subscriptionType, nil default: return nil, gqlerrors.NewError( "Can only execute queries, mutations and subscription", []ast.Node{operation}, "", nil, []int{}, nil, ) } }
go
func getOperationRootType(schema Schema, operation ast.Definition) (*Object, error) { if operation == nil { return nil, errors.New("Can only execute queries, mutations and subscription") } switch operation.GetOperation() { case ast.OperationTypeQuery: return schema.QueryType(), nil case ast.OperationTypeMutation: mutationType := schema.MutationType() if mutationType == nil || mutationType.PrivateName == "" { return nil, gqlerrors.NewError( "Schema is not configured for mutations", []ast.Node{operation}, "", nil, []int{}, nil, ) } return mutationType, nil case ast.OperationTypeSubscription: subscriptionType := schema.SubscriptionType() if subscriptionType == nil || subscriptionType.PrivateName == "" { return nil, gqlerrors.NewError( "Schema is not configured for subscriptions", []ast.Node{operation}, "", nil, []int{}, nil, ) } return subscriptionType, nil default: return nil, gqlerrors.NewError( "Can only execute queries, mutations and subscription", []ast.Node{operation}, "", nil, []int{}, nil, ) } }
[ "func", "getOperationRootType", "(", "schema", "Schema", ",", "operation", "ast", ".", "Definition", ")", "(", "*", "Object", ",", "error", ")", "{", "if", "operation", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "operation", ".", "GetOperation", "(", ")", "{", "case", "ast", ".", "OperationTypeQuery", ":", "return", "schema", ".", "QueryType", "(", ")", ",", "nil", "\n", "case", "ast", ".", "OperationTypeMutation", ":", "mutationType", ":=", "schema", ".", "MutationType", "(", ")", "\n", "if", "mutationType", "==", "nil", "||", "mutationType", ".", "PrivateName", "==", "\"", "\"", "{", "return", "nil", ",", "gqlerrors", ".", "NewError", "(", "\"", "\"", ",", "[", "]", "ast", ".", "Node", "{", "operation", "}", ",", "\"", "\"", ",", "nil", ",", "[", "]", "int", "{", "}", ",", "nil", ",", ")", "\n", "}", "\n", "return", "mutationType", ",", "nil", "\n", "case", "ast", ".", "OperationTypeSubscription", ":", "subscriptionType", ":=", "schema", ".", "SubscriptionType", "(", ")", "\n", "if", "subscriptionType", "==", "nil", "||", "subscriptionType", ".", "PrivateName", "==", "\"", "\"", "{", "return", "nil", ",", "gqlerrors", ".", "NewError", "(", "\"", "\"", ",", "[", "]", "ast", ".", "Node", "{", "operation", "}", ",", "\"", "\"", ",", "nil", ",", "[", "]", "int", "{", "}", ",", "nil", ",", ")", "\n", "}", "\n", "return", "subscriptionType", ",", "nil", "\n", "default", ":", "return", "nil", ",", "gqlerrors", ".", "NewError", "(", "\"", "\"", ",", "[", "]", "ast", ".", "Node", "{", "operation", "}", ",", "\"", "\"", ",", "nil", ",", "[", "]", "int", "{", "}", ",", "nil", ",", ")", "\n", "}", "\n", "}" ]
// Extracts the root type of the operation from the schema.
[ "Extracts", "the", "root", "type", "of", "the", "operation", "from", "the", "schema", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L193-L237
train
graphql-go/graphql
executor.go
executeFieldsSerially
func executeFieldsSerially(p executeFieldsParams) *Result { if p.Source == nil { p.Source = map[string]interface{}{} } if p.Fields == nil { p.Fields = map[string][]*ast.Field{} } finalResults := make(map[string]interface{}, len(p.Fields)) for responseName, fieldASTs := range p.Fields { fieldPath := p.Path.WithKey(responseName) resolved, state := resolveField(p.ExecutionContext, p.ParentType, p.Source, fieldASTs, fieldPath) if state.hasNoFieldDefs { continue } finalResults[responseName] = resolved } dethunkMapDepthFirst(finalResults) return &Result{ Data: finalResults, Errors: p.ExecutionContext.Errors, } }
go
func executeFieldsSerially(p executeFieldsParams) *Result { if p.Source == nil { p.Source = map[string]interface{}{} } if p.Fields == nil { p.Fields = map[string][]*ast.Field{} } finalResults := make(map[string]interface{}, len(p.Fields)) for responseName, fieldASTs := range p.Fields { fieldPath := p.Path.WithKey(responseName) resolved, state := resolveField(p.ExecutionContext, p.ParentType, p.Source, fieldASTs, fieldPath) if state.hasNoFieldDefs { continue } finalResults[responseName] = resolved } dethunkMapDepthFirst(finalResults) return &Result{ Data: finalResults, Errors: p.ExecutionContext.Errors, } }
[ "func", "executeFieldsSerially", "(", "p", "executeFieldsParams", ")", "*", "Result", "{", "if", "p", ".", "Source", "==", "nil", "{", "p", ".", "Source", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "}", "\n", "if", "p", ".", "Fields", "==", "nil", "{", "p", ".", "Fields", "=", "map", "[", "string", "]", "[", "]", "*", "ast", ".", "Field", "{", "}", "\n", "}", "\n\n", "finalResults", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "p", ".", "Fields", ")", ")", "\n", "for", "responseName", ",", "fieldASTs", ":=", "range", "p", ".", "Fields", "{", "fieldPath", ":=", "p", ".", "Path", ".", "WithKey", "(", "responseName", ")", "\n", "resolved", ",", "state", ":=", "resolveField", "(", "p", ".", "ExecutionContext", ",", "p", ".", "ParentType", ",", "p", ".", "Source", ",", "fieldASTs", ",", "fieldPath", ")", "\n", "if", "state", ".", "hasNoFieldDefs", "{", "continue", "\n", "}", "\n", "finalResults", "[", "responseName", "]", "=", "resolved", "\n", "}", "\n", "dethunkMapDepthFirst", "(", "finalResults", ")", "\n\n", "return", "&", "Result", "{", "Data", ":", "finalResults", ",", "Errors", ":", "p", ".", "ExecutionContext", ".", "Errors", ",", "}", "\n", "}" ]
// Implements the "Evaluating selection sets" section of the spec for "write" mode.
[ "Implements", "the", "Evaluating", "selection", "sets", "section", "of", "the", "spec", "for", "write", "mode", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L248-L271
train
graphql-go/graphql
executor.go
executeFields
func executeFields(p executeFieldsParams) *Result { finalResults := executeSubFields(p) dethunkMapWithBreadthFirstTraversal(finalResults) return &Result{ Data: finalResults, Errors: p.ExecutionContext.Errors, } }
go
func executeFields(p executeFieldsParams) *Result { finalResults := executeSubFields(p) dethunkMapWithBreadthFirstTraversal(finalResults) return &Result{ Data: finalResults, Errors: p.ExecutionContext.Errors, } }
[ "func", "executeFields", "(", "p", "executeFieldsParams", ")", "*", "Result", "{", "finalResults", ":=", "executeSubFields", "(", "p", ")", "\n\n", "dethunkMapWithBreadthFirstTraversal", "(", "finalResults", ")", "\n\n", "return", "&", "Result", "{", "Data", ":", "finalResults", ",", "Errors", ":", "p", ".", "ExecutionContext", ".", "Errors", ",", "}", "\n", "}" ]
// Implements the "Evaluating selection sets" section of the spec for "read" mode.
[ "Implements", "the", "Evaluating", "selection", "sets", "section", "of", "the", "spec", "for", "read", "mode", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L274-L283
train
graphql-go/graphql
executor.go
collectFields
func collectFields(p collectFieldsParams) (fields map[string][]*ast.Field) { // overlying SelectionSet & Fields to fields if p.SelectionSet == nil { return p.Fields } fields = p.Fields if fields == nil { fields = map[string][]*ast.Field{} } if p.VisitedFragmentNames == nil { p.VisitedFragmentNames = map[string]bool{} } for _, iSelection := range p.SelectionSet.Selections { switch selection := iSelection.(type) { case *ast.Field: if !shouldIncludeNode(p.ExeContext, selection.Directives) { continue } name := getFieldEntryKey(selection) if _, ok := fields[name]; !ok { fields[name] = []*ast.Field{} } fields[name] = append(fields[name], selection) case *ast.InlineFragment: if !shouldIncludeNode(p.ExeContext, selection.Directives) || !doesFragmentConditionMatch(p.ExeContext, selection, p.RuntimeType) { continue } innerParams := collectFieldsParams{ ExeContext: p.ExeContext, RuntimeType: p.RuntimeType, SelectionSet: selection.SelectionSet, Fields: fields, VisitedFragmentNames: p.VisitedFragmentNames, } collectFields(innerParams) case *ast.FragmentSpread: fragName := "" if selection.Name != nil { fragName = selection.Name.Value } if visited, ok := p.VisitedFragmentNames[fragName]; (ok && visited) || !shouldIncludeNode(p.ExeContext, selection.Directives) { continue } p.VisitedFragmentNames[fragName] = true fragment, hasFragment := p.ExeContext.Fragments[fragName] if !hasFragment { continue } if fragment, ok := fragment.(*ast.FragmentDefinition); ok { if !doesFragmentConditionMatch(p.ExeContext, fragment, p.RuntimeType) { continue } innerParams := collectFieldsParams{ ExeContext: p.ExeContext, RuntimeType: p.RuntimeType, SelectionSet: fragment.GetSelectionSet(), Fields: fields, VisitedFragmentNames: p.VisitedFragmentNames, } collectFields(innerParams) } } } return fields }
go
func collectFields(p collectFieldsParams) (fields map[string][]*ast.Field) { // overlying SelectionSet & Fields to fields if p.SelectionSet == nil { return p.Fields } fields = p.Fields if fields == nil { fields = map[string][]*ast.Field{} } if p.VisitedFragmentNames == nil { p.VisitedFragmentNames = map[string]bool{} } for _, iSelection := range p.SelectionSet.Selections { switch selection := iSelection.(type) { case *ast.Field: if !shouldIncludeNode(p.ExeContext, selection.Directives) { continue } name := getFieldEntryKey(selection) if _, ok := fields[name]; !ok { fields[name] = []*ast.Field{} } fields[name] = append(fields[name], selection) case *ast.InlineFragment: if !shouldIncludeNode(p.ExeContext, selection.Directives) || !doesFragmentConditionMatch(p.ExeContext, selection, p.RuntimeType) { continue } innerParams := collectFieldsParams{ ExeContext: p.ExeContext, RuntimeType: p.RuntimeType, SelectionSet: selection.SelectionSet, Fields: fields, VisitedFragmentNames: p.VisitedFragmentNames, } collectFields(innerParams) case *ast.FragmentSpread: fragName := "" if selection.Name != nil { fragName = selection.Name.Value } if visited, ok := p.VisitedFragmentNames[fragName]; (ok && visited) || !shouldIncludeNode(p.ExeContext, selection.Directives) { continue } p.VisitedFragmentNames[fragName] = true fragment, hasFragment := p.ExeContext.Fragments[fragName] if !hasFragment { continue } if fragment, ok := fragment.(*ast.FragmentDefinition); ok { if !doesFragmentConditionMatch(p.ExeContext, fragment, p.RuntimeType) { continue } innerParams := collectFieldsParams{ ExeContext: p.ExeContext, RuntimeType: p.RuntimeType, SelectionSet: fragment.GetSelectionSet(), Fields: fields, VisitedFragmentNames: p.VisitedFragmentNames, } collectFields(innerParams) } } } return fields }
[ "func", "collectFields", "(", "p", "collectFieldsParams", ")", "(", "fields", "map", "[", "string", "]", "[", "]", "*", "ast", ".", "Field", ")", "{", "// overlying SelectionSet & Fields to fields", "if", "p", ".", "SelectionSet", "==", "nil", "{", "return", "p", ".", "Fields", "\n", "}", "\n", "fields", "=", "p", ".", "Fields", "\n", "if", "fields", "==", "nil", "{", "fields", "=", "map", "[", "string", "]", "[", "]", "*", "ast", ".", "Field", "{", "}", "\n", "}", "\n", "if", "p", ".", "VisitedFragmentNames", "==", "nil", "{", "p", ".", "VisitedFragmentNames", "=", "map", "[", "string", "]", "bool", "{", "}", "\n", "}", "\n", "for", "_", ",", "iSelection", ":=", "range", "p", ".", "SelectionSet", ".", "Selections", "{", "switch", "selection", ":=", "iSelection", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "Field", ":", "if", "!", "shouldIncludeNode", "(", "p", ".", "ExeContext", ",", "selection", ".", "Directives", ")", "{", "continue", "\n", "}", "\n", "name", ":=", "getFieldEntryKey", "(", "selection", ")", "\n", "if", "_", ",", "ok", ":=", "fields", "[", "name", "]", ";", "!", "ok", "{", "fields", "[", "name", "]", "=", "[", "]", "*", "ast", ".", "Field", "{", "}", "\n", "}", "\n", "fields", "[", "name", "]", "=", "append", "(", "fields", "[", "name", "]", ",", "selection", ")", "\n", "case", "*", "ast", ".", "InlineFragment", ":", "if", "!", "shouldIncludeNode", "(", "p", ".", "ExeContext", ",", "selection", ".", "Directives", ")", "||", "!", "doesFragmentConditionMatch", "(", "p", ".", "ExeContext", ",", "selection", ",", "p", ".", "RuntimeType", ")", "{", "continue", "\n", "}", "\n", "innerParams", ":=", "collectFieldsParams", "{", "ExeContext", ":", "p", ".", "ExeContext", ",", "RuntimeType", ":", "p", ".", "RuntimeType", ",", "SelectionSet", ":", "selection", ".", "SelectionSet", ",", "Fields", ":", "fields", ",", "VisitedFragmentNames", ":", "p", ".", "VisitedFragmentNames", ",", "}", "\n", "collectFields", "(", "innerParams", ")", "\n", "case", "*", "ast", ".", "FragmentSpread", ":", "fragName", ":=", "\"", "\"", "\n", "if", "selection", ".", "Name", "!=", "nil", "{", "fragName", "=", "selection", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "visited", ",", "ok", ":=", "p", ".", "VisitedFragmentNames", "[", "fragName", "]", ";", "(", "ok", "&&", "visited", ")", "||", "!", "shouldIncludeNode", "(", "p", ".", "ExeContext", ",", "selection", ".", "Directives", ")", "{", "continue", "\n", "}", "\n", "p", ".", "VisitedFragmentNames", "[", "fragName", "]", "=", "true", "\n", "fragment", ",", "hasFragment", ":=", "p", ".", "ExeContext", ".", "Fragments", "[", "fragName", "]", "\n", "if", "!", "hasFragment", "{", "continue", "\n", "}", "\n\n", "if", "fragment", ",", "ok", ":=", "fragment", ".", "(", "*", "ast", ".", "FragmentDefinition", ")", ";", "ok", "{", "if", "!", "doesFragmentConditionMatch", "(", "p", ".", "ExeContext", ",", "fragment", ",", "p", ".", "RuntimeType", ")", "{", "continue", "\n", "}", "\n", "innerParams", ":=", "collectFieldsParams", "{", "ExeContext", ":", "p", ".", "ExeContext", ",", "RuntimeType", ":", "p", ".", "RuntimeType", ",", "SelectionSet", ":", "fragment", ".", "GetSelectionSet", "(", ")", ",", "Fields", ":", "fields", ",", "VisitedFragmentNames", ":", "p", ".", "VisitedFragmentNames", ",", "}", "\n", "collectFields", "(", "innerParams", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// Given a selectionSet, adds all of the fields in that selection to // the passed in map of fields, and returns it at the end. // CollectFields requires the "runtime type" of an object. For a field which // returns and Interface or Union type, the "runtime type" will be the actual // Object type returned by that field.
[ "Given", "a", "selectionSet", "adds", "all", "of", "the", "fields", "in", "that", "selection", "to", "the", "passed", "in", "map", "of", "fields", "and", "returns", "it", "at", "the", "end", ".", "CollectFields", "requires", "the", "runtime", "type", "of", "an", "object", ".", "For", "a", "field", "which", "returns", "and", "Interface", "or", "Union", "type", "the", "runtime", "type", "will", "be", "the", "actual", "Object", "type", "returned", "by", "that", "field", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L408-L476
train
graphql-go/graphql
executor.go
shouldIncludeNode
func shouldIncludeNode(eCtx *executionContext, directives []*ast.Directive) bool { var ( skipAST, includeAST *ast.Directive argValues map[string]interface{} ) for _, directive := range directives { if directive == nil || directive.Name == nil { continue } switch directive.Name.Value { case SkipDirective.Name: skipAST = directive case IncludeDirective.Name: includeAST = directive } } // precedence: skipAST > includeAST if skipAST != nil { argValues = getArgumentValues(SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues) if skipIf, ok := argValues["if"].(bool); ok && skipIf { return false // excluded selectionSet's fields } } if includeAST != nil { argValues = getArgumentValues(IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues) if includeIf, ok := argValues["if"].(bool); ok && !includeIf { return false // excluded selectionSet's fields } } return true }
go
func shouldIncludeNode(eCtx *executionContext, directives []*ast.Directive) bool { var ( skipAST, includeAST *ast.Directive argValues map[string]interface{} ) for _, directive := range directives { if directive == nil || directive.Name == nil { continue } switch directive.Name.Value { case SkipDirective.Name: skipAST = directive case IncludeDirective.Name: includeAST = directive } } // precedence: skipAST > includeAST if skipAST != nil { argValues = getArgumentValues(SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues) if skipIf, ok := argValues["if"].(bool); ok && skipIf { return false // excluded selectionSet's fields } } if includeAST != nil { argValues = getArgumentValues(IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues) if includeIf, ok := argValues["if"].(bool); ok && !includeIf { return false // excluded selectionSet's fields } } return true }
[ "func", "shouldIncludeNode", "(", "eCtx", "*", "executionContext", ",", "directives", "[", "]", "*", "ast", ".", "Directive", ")", "bool", "{", "var", "(", "skipAST", ",", "includeAST", "*", "ast", ".", "Directive", "\n", "argValues", "map", "[", "string", "]", "interface", "{", "}", "\n", ")", "\n", "for", "_", ",", "directive", ":=", "range", "directives", "{", "if", "directive", "==", "nil", "||", "directive", ".", "Name", "==", "nil", "{", "continue", "\n", "}", "\n", "switch", "directive", ".", "Name", ".", "Value", "{", "case", "SkipDirective", ".", "Name", ":", "skipAST", "=", "directive", "\n", "case", "IncludeDirective", ".", "Name", ":", "includeAST", "=", "directive", "\n", "}", "\n", "}", "\n", "// precedence: skipAST > includeAST", "if", "skipAST", "!=", "nil", "{", "argValues", "=", "getArgumentValues", "(", "SkipDirective", ".", "Args", ",", "skipAST", ".", "Arguments", ",", "eCtx", ".", "VariableValues", ")", "\n", "if", "skipIf", ",", "ok", ":=", "argValues", "[", "\"", "\"", "]", ".", "(", "bool", ")", ";", "ok", "&&", "skipIf", "{", "return", "false", "// excluded selectionSet's fields", "\n", "}", "\n", "}", "\n", "if", "includeAST", "!=", "nil", "{", "argValues", "=", "getArgumentValues", "(", "IncludeDirective", ".", "Args", ",", "includeAST", ".", "Arguments", ",", "eCtx", ".", "VariableValues", ")", "\n", "if", "includeIf", ",", "ok", ":=", "argValues", "[", "\"", "\"", "]", ".", "(", "bool", ")", ";", "ok", "&&", "!", "includeIf", "{", "return", "false", "// excluded selectionSet's fields", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Determines if a field should be included based on the @include and @skip // directives, where @skip has higher precedence than @include.
[ "Determines", "if", "a", "field", "should", "be", "included", "based", "on", "the" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L480-L510
train
graphql-go/graphql
executor.go
doesFragmentConditionMatch
func doesFragmentConditionMatch(eCtx *executionContext, fragment ast.Node, ttype *Object) bool { switch fragment := fragment.(type) { case *ast.FragmentDefinition: typeConditionAST := fragment.TypeCondition if typeConditionAST == nil { return true } conditionalType, err := typeFromAST(eCtx.Schema, typeConditionAST) if err != nil { return false } if conditionalType == ttype { return true } if conditionalType.Name() == ttype.Name() { return true } if conditionalType, ok := conditionalType.(*Interface); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } if conditionalType, ok := conditionalType.(*Union); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } case *ast.InlineFragment: typeConditionAST := fragment.TypeCondition if typeConditionAST == nil { return true } conditionalType, err := typeFromAST(eCtx.Schema, typeConditionAST) if err != nil { return false } if conditionalType == ttype { return true } if conditionalType.Name() == ttype.Name() { return true } if conditionalType, ok := conditionalType.(*Interface); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } if conditionalType, ok := conditionalType.(*Union); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } } return false }
go
func doesFragmentConditionMatch(eCtx *executionContext, fragment ast.Node, ttype *Object) bool { switch fragment := fragment.(type) { case *ast.FragmentDefinition: typeConditionAST := fragment.TypeCondition if typeConditionAST == nil { return true } conditionalType, err := typeFromAST(eCtx.Schema, typeConditionAST) if err != nil { return false } if conditionalType == ttype { return true } if conditionalType.Name() == ttype.Name() { return true } if conditionalType, ok := conditionalType.(*Interface); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } if conditionalType, ok := conditionalType.(*Union); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } case *ast.InlineFragment: typeConditionAST := fragment.TypeCondition if typeConditionAST == nil { return true } conditionalType, err := typeFromAST(eCtx.Schema, typeConditionAST) if err != nil { return false } if conditionalType == ttype { return true } if conditionalType.Name() == ttype.Name() { return true } if conditionalType, ok := conditionalType.(*Interface); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } if conditionalType, ok := conditionalType.(*Union); ok { return eCtx.Schema.IsPossibleType(conditionalType, ttype) } } return false }
[ "func", "doesFragmentConditionMatch", "(", "eCtx", "*", "executionContext", ",", "fragment", "ast", ".", "Node", ",", "ttype", "*", "Object", ")", "bool", "{", "switch", "fragment", ":=", "fragment", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "FragmentDefinition", ":", "typeConditionAST", ":=", "fragment", ".", "TypeCondition", "\n", "if", "typeConditionAST", "==", "nil", "{", "return", "true", "\n", "}", "\n", "conditionalType", ",", "err", ":=", "typeFromAST", "(", "eCtx", ".", "Schema", ",", "typeConditionAST", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "conditionalType", "==", "ttype", "{", "return", "true", "\n", "}", "\n", "if", "conditionalType", ".", "Name", "(", ")", "==", "ttype", ".", "Name", "(", ")", "{", "return", "true", "\n", "}", "\n", "if", "conditionalType", ",", "ok", ":=", "conditionalType", ".", "(", "*", "Interface", ")", ";", "ok", "{", "return", "eCtx", ".", "Schema", ".", "IsPossibleType", "(", "conditionalType", ",", "ttype", ")", "\n", "}", "\n", "if", "conditionalType", ",", "ok", ":=", "conditionalType", ".", "(", "*", "Union", ")", ";", "ok", "{", "return", "eCtx", ".", "Schema", ".", "IsPossibleType", "(", "conditionalType", ",", "ttype", ")", "\n", "}", "\n", "case", "*", "ast", ".", "InlineFragment", ":", "typeConditionAST", ":=", "fragment", ".", "TypeCondition", "\n", "if", "typeConditionAST", "==", "nil", "{", "return", "true", "\n", "}", "\n", "conditionalType", ",", "err", ":=", "typeFromAST", "(", "eCtx", ".", "Schema", ",", "typeConditionAST", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "conditionalType", "==", "ttype", "{", "return", "true", "\n", "}", "\n", "if", "conditionalType", ".", "Name", "(", ")", "==", "ttype", ".", "Name", "(", ")", "{", "return", "true", "\n", "}", "\n", "if", "conditionalType", ",", "ok", ":=", "conditionalType", ".", "(", "*", "Interface", ")", ";", "ok", "{", "return", "eCtx", ".", "Schema", ".", "IsPossibleType", "(", "conditionalType", ",", "ttype", ")", "\n", "}", "\n", "if", "conditionalType", ",", "ok", ":=", "conditionalType", ".", "(", "*", "Union", ")", ";", "ok", "{", "return", "eCtx", ".", "Schema", ".", "IsPossibleType", "(", "conditionalType", ",", "ttype", ")", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Determines if a fragment is applicable to the given type.
[ "Determines", "if", "a", "fragment", "is", "applicable", "to", "the", "given", "type", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L513-L561
train
graphql-go/graphql
executor.go
resolveField
func resolveField(eCtx *executionContext, parentType *Object, source interface{}, fieldASTs []*ast.Field, path *ResponsePath) (result interface{}, resultState resolveFieldResultState) { // catch panic from resolveFn var returnType Output defer func() (interface{}, resolveFieldResultState) { if r := recover(); r != nil { handleFieldError(r, FieldASTsToNodeASTs(fieldASTs), path, returnType, eCtx) return result, resultState } return result, resultState }() fieldAST := fieldASTs[0] fieldName := "" if fieldAST.Name != nil { fieldName = fieldAST.Name.Value } fieldDef := getFieldDef(eCtx.Schema, parentType, fieldName) if fieldDef == nil { resultState.hasNoFieldDefs = true return nil, resultState } returnType = fieldDef.Type resolveFn := fieldDef.Resolve if resolveFn == nil { resolveFn = DefaultResolveFn } // Build a map of arguments from the field.arguments AST, using the // variables scope to fulfill any variable references. // TODO: find a way to memoize, in case this field is within a List type. args := getArgumentValues(fieldDef.Args, fieldAST.Arguments, eCtx.VariableValues) info := ResolveInfo{ FieldName: fieldName, FieldASTs: fieldASTs, Path: path, ReturnType: returnType, ParentType: parentType, Schema: eCtx.Schema, Fragments: eCtx.Fragments, RootValue: eCtx.Root, Operation: eCtx.Operation, VariableValues: eCtx.VariableValues, } var resolveFnError error extErrs, resolveFieldFinishFn := handleExtensionsResolveFieldDidStart(eCtx.Schema.extensions, eCtx, &info) if len(extErrs) != 0 { eCtx.Errors = append(eCtx.Errors, extErrs...) } result, resolveFnError = resolveFn(ResolveParams{ Source: source, Args: args, Info: info, Context: eCtx.Context, }) if resolveFnError != nil { panic(resolveFnError) } extErrs = resolveFieldFinishFn(result, resolveFnError) if len(extErrs) != 0 { eCtx.Errors = append(eCtx.Errors, extErrs...) } completed := completeValueCatchingError(eCtx, returnType, fieldASTs, info, path, result) return completed, resultState }
go
func resolveField(eCtx *executionContext, parentType *Object, source interface{}, fieldASTs []*ast.Field, path *ResponsePath) (result interface{}, resultState resolveFieldResultState) { // catch panic from resolveFn var returnType Output defer func() (interface{}, resolveFieldResultState) { if r := recover(); r != nil { handleFieldError(r, FieldASTsToNodeASTs(fieldASTs), path, returnType, eCtx) return result, resultState } return result, resultState }() fieldAST := fieldASTs[0] fieldName := "" if fieldAST.Name != nil { fieldName = fieldAST.Name.Value } fieldDef := getFieldDef(eCtx.Schema, parentType, fieldName) if fieldDef == nil { resultState.hasNoFieldDefs = true return nil, resultState } returnType = fieldDef.Type resolveFn := fieldDef.Resolve if resolveFn == nil { resolveFn = DefaultResolveFn } // Build a map of arguments from the field.arguments AST, using the // variables scope to fulfill any variable references. // TODO: find a way to memoize, in case this field is within a List type. args := getArgumentValues(fieldDef.Args, fieldAST.Arguments, eCtx.VariableValues) info := ResolveInfo{ FieldName: fieldName, FieldASTs: fieldASTs, Path: path, ReturnType: returnType, ParentType: parentType, Schema: eCtx.Schema, Fragments: eCtx.Fragments, RootValue: eCtx.Root, Operation: eCtx.Operation, VariableValues: eCtx.VariableValues, } var resolveFnError error extErrs, resolveFieldFinishFn := handleExtensionsResolveFieldDidStart(eCtx.Schema.extensions, eCtx, &info) if len(extErrs) != 0 { eCtx.Errors = append(eCtx.Errors, extErrs...) } result, resolveFnError = resolveFn(ResolveParams{ Source: source, Args: args, Info: info, Context: eCtx.Context, }) if resolveFnError != nil { panic(resolveFnError) } extErrs = resolveFieldFinishFn(result, resolveFnError) if len(extErrs) != 0 { eCtx.Errors = append(eCtx.Errors, extErrs...) } completed := completeValueCatchingError(eCtx, returnType, fieldASTs, info, path, result) return completed, resultState }
[ "func", "resolveField", "(", "eCtx", "*", "executionContext", ",", "parentType", "*", "Object", ",", "source", "interface", "{", "}", ",", "fieldASTs", "[", "]", "*", "ast", ".", "Field", ",", "path", "*", "ResponsePath", ")", "(", "result", "interface", "{", "}", ",", "resultState", "resolveFieldResultState", ")", "{", "// catch panic from resolveFn", "var", "returnType", "Output", "\n", "defer", "func", "(", ")", "(", "interface", "{", "}", ",", "resolveFieldResultState", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "handleFieldError", "(", "r", ",", "FieldASTsToNodeASTs", "(", "fieldASTs", ")", ",", "path", ",", "returnType", ",", "eCtx", ")", "\n", "return", "result", ",", "resultState", "\n", "}", "\n", "return", "result", ",", "resultState", "\n", "}", "(", ")", "\n\n", "fieldAST", ":=", "fieldASTs", "[", "0", "]", "\n", "fieldName", ":=", "\"", "\"", "\n", "if", "fieldAST", ".", "Name", "!=", "nil", "{", "fieldName", "=", "fieldAST", ".", "Name", ".", "Value", "\n", "}", "\n\n", "fieldDef", ":=", "getFieldDef", "(", "eCtx", ".", "Schema", ",", "parentType", ",", "fieldName", ")", "\n", "if", "fieldDef", "==", "nil", "{", "resultState", ".", "hasNoFieldDefs", "=", "true", "\n", "return", "nil", ",", "resultState", "\n", "}", "\n", "returnType", "=", "fieldDef", ".", "Type", "\n", "resolveFn", ":=", "fieldDef", ".", "Resolve", "\n", "if", "resolveFn", "==", "nil", "{", "resolveFn", "=", "DefaultResolveFn", "\n", "}", "\n\n", "// Build a map of arguments from the field.arguments AST, using the", "// variables scope to fulfill any variable references.", "// TODO: find a way to memoize, in case this field is within a List type.", "args", ":=", "getArgumentValues", "(", "fieldDef", ".", "Args", ",", "fieldAST", ".", "Arguments", ",", "eCtx", ".", "VariableValues", ")", "\n\n", "info", ":=", "ResolveInfo", "{", "FieldName", ":", "fieldName", ",", "FieldASTs", ":", "fieldASTs", ",", "Path", ":", "path", ",", "ReturnType", ":", "returnType", ",", "ParentType", ":", "parentType", ",", "Schema", ":", "eCtx", ".", "Schema", ",", "Fragments", ":", "eCtx", ".", "Fragments", ",", "RootValue", ":", "eCtx", ".", "Root", ",", "Operation", ":", "eCtx", ".", "Operation", ",", "VariableValues", ":", "eCtx", ".", "VariableValues", ",", "}", "\n\n", "var", "resolveFnError", "error", "\n\n", "extErrs", ",", "resolveFieldFinishFn", ":=", "handleExtensionsResolveFieldDidStart", "(", "eCtx", ".", "Schema", ".", "extensions", ",", "eCtx", ",", "&", "info", ")", "\n", "if", "len", "(", "extErrs", ")", "!=", "0", "{", "eCtx", ".", "Errors", "=", "append", "(", "eCtx", ".", "Errors", ",", "extErrs", "...", ")", "\n", "}", "\n\n", "result", ",", "resolveFnError", "=", "resolveFn", "(", "ResolveParams", "{", "Source", ":", "source", ",", "Args", ":", "args", ",", "Info", ":", "info", ",", "Context", ":", "eCtx", ".", "Context", ",", "}", ")", "\n\n", "if", "resolveFnError", "!=", "nil", "{", "panic", "(", "resolveFnError", ")", "\n", "}", "\n\n", "extErrs", "=", "resolveFieldFinishFn", "(", "result", ",", "resolveFnError", ")", "\n", "if", "len", "(", "extErrs", ")", "!=", "0", "{", "eCtx", ".", "Errors", "=", "append", "(", "eCtx", ".", "Errors", ",", "extErrs", "...", ")", "\n", "}", "\n\n", "completed", ":=", "completeValueCatchingError", "(", "eCtx", ",", "returnType", ",", "fieldASTs", ",", "info", ",", "path", ",", "result", ")", "\n", "return", "completed", ",", "resultState", "\n", "}" ]
// Resolves the field on the given source object. In particular, this // figures out the value that the field returns by calling its resolve function, // then calls completeValue to complete promises, serialize scalars, or execute // the sub-selection-set for objects.
[ "Resolves", "the", "field", "on", "the", "given", "source", "object", ".", "In", "particular", "this", "figures", "out", "the", "value", "that", "the", "field", "returns", "by", "calling", "its", "resolve", "function", "then", "calls", "completeValue", "to", "complete", "promises", "serialize", "scalars", "or", "execute", "the", "sub", "-", "selection", "-", "set", "for", "objects", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L593-L664
train
graphql-go/graphql
executor.go
completeObjectValue
func completeObjectValue(eCtx *executionContext, returnType *Object, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} { // If there is an isTypeOf predicate function, call it with the // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if returnType.IsTypeOf != nil { p := IsTypeOfParams{ Value: result, Info: info, Context: eCtx.Context, } if !returnType.IsTypeOf(p) { panic(gqlerrors.NewFormattedError( fmt.Sprintf(`Expected value of type "%v" but got: %T.`, returnType, result), )) } } // Collect sub-fields to execute to complete this value. subFieldASTs := map[string][]*ast.Field{} visitedFragmentNames := map[string]bool{} for _, fieldAST := range fieldASTs { if fieldAST == nil { continue } selectionSet := fieldAST.SelectionSet if selectionSet != nil { innerParams := collectFieldsParams{ ExeContext: eCtx, RuntimeType: returnType, SelectionSet: selectionSet, Fields: subFieldASTs, VisitedFragmentNames: visitedFragmentNames, } subFieldASTs = collectFields(innerParams) } } executeFieldsParams := executeFieldsParams{ ExecutionContext: eCtx, ParentType: returnType, Source: result, Fields: subFieldASTs, Path: path, } return executeSubFields(executeFieldsParams) }
go
func completeObjectValue(eCtx *executionContext, returnType *Object, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} { // If there is an isTypeOf predicate function, call it with the // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if returnType.IsTypeOf != nil { p := IsTypeOfParams{ Value: result, Info: info, Context: eCtx.Context, } if !returnType.IsTypeOf(p) { panic(gqlerrors.NewFormattedError( fmt.Sprintf(`Expected value of type "%v" but got: %T.`, returnType, result), )) } } // Collect sub-fields to execute to complete this value. subFieldASTs := map[string][]*ast.Field{} visitedFragmentNames := map[string]bool{} for _, fieldAST := range fieldASTs { if fieldAST == nil { continue } selectionSet := fieldAST.SelectionSet if selectionSet != nil { innerParams := collectFieldsParams{ ExeContext: eCtx, RuntimeType: returnType, SelectionSet: selectionSet, Fields: subFieldASTs, VisitedFragmentNames: visitedFragmentNames, } subFieldASTs = collectFields(innerParams) } } executeFieldsParams := executeFieldsParams{ ExecutionContext: eCtx, ParentType: returnType, Source: result, Fields: subFieldASTs, Path: path, } return executeSubFields(executeFieldsParams) }
[ "func", "completeObjectValue", "(", "eCtx", "*", "executionContext", ",", "returnType", "*", "Object", ",", "fieldASTs", "[", "]", "*", "ast", ".", "Field", ",", "info", "ResolveInfo", ",", "path", "*", "ResponsePath", ",", "result", "interface", "{", "}", ")", "interface", "{", "}", "{", "// If there is an isTypeOf predicate function, call it with the", "// current result. If isTypeOf returns false, then raise an error rather", "// than continuing execution.", "if", "returnType", ".", "IsTypeOf", "!=", "nil", "{", "p", ":=", "IsTypeOfParams", "{", "Value", ":", "result", ",", "Info", ":", "info", ",", "Context", ":", "eCtx", ".", "Context", ",", "}", "\n", "if", "!", "returnType", ".", "IsTypeOf", "(", "p", ")", "{", "panic", "(", "gqlerrors", ".", "NewFormattedError", "(", "fmt", ".", "Sprintf", "(", "`Expected value of type \"%v\" but got: %T.`", ",", "returnType", ",", "result", ")", ",", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Collect sub-fields to execute to complete this value.", "subFieldASTs", ":=", "map", "[", "string", "]", "[", "]", "*", "ast", ".", "Field", "{", "}", "\n", "visitedFragmentNames", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "for", "_", ",", "fieldAST", ":=", "range", "fieldASTs", "{", "if", "fieldAST", "==", "nil", "{", "continue", "\n", "}", "\n", "selectionSet", ":=", "fieldAST", ".", "SelectionSet", "\n", "if", "selectionSet", "!=", "nil", "{", "innerParams", ":=", "collectFieldsParams", "{", "ExeContext", ":", "eCtx", ",", "RuntimeType", ":", "returnType", ",", "SelectionSet", ":", "selectionSet", ",", "Fields", ":", "subFieldASTs", ",", "VisitedFragmentNames", ":", "visitedFragmentNames", ",", "}", "\n", "subFieldASTs", "=", "collectFields", "(", "innerParams", ")", "\n", "}", "\n", "}", "\n", "executeFieldsParams", ":=", "executeFieldsParams", "{", "ExecutionContext", ":", "eCtx", ",", "ParentType", ":", "returnType", ",", "Source", ":", "result", ",", "Fields", ":", "subFieldASTs", ",", "Path", ":", "path", ",", "}", "\n", "return", "executeSubFields", "(", "executeFieldsParams", ")", "\n", "}" ]
// completeObjectValue complete an Object value by executing all sub-selections.
[ "completeObjectValue", "complete", "an", "Object", "value", "by", "executing", "all", "sub", "-", "selections", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L820-L865
train
graphql-go/graphql
executor.go
completeListValue
func completeListValue(eCtx *executionContext, returnType *List, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} { resultVal := reflect.ValueOf(result) if resultVal.Kind() == reflect.Ptr { resultVal = resultVal.Elem() } parentTypeName := "" if info.ParentType != nil { parentTypeName = info.ParentType.Name() } err := invariantf( resultVal.IsValid() && isIterable(result), "User Error: expected iterable, but did not find one "+ "for field %v.%v.", parentTypeName, info.FieldName) if err != nil { panic(gqlerrors.FormatError(err)) } itemType := returnType.OfType completedResults := make([]interface{}, 0, resultVal.Len()) for i := 0; i < resultVal.Len(); i++ { val := resultVal.Index(i).Interface() fieldPath := path.WithKey(i) completedItem := completeValueCatchingError(eCtx, itemType, fieldASTs, info, fieldPath, val) completedResults = append(completedResults, completedItem) } return completedResults }
go
func completeListValue(eCtx *executionContext, returnType *List, fieldASTs []*ast.Field, info ResolveInfo, path *ResponsePath, result interface{}) interface{} { resultVal := reflect.ValueOf(result) if resultVal.Kind() == reflect.Ptr { resultVal = resultVal.Elem() } parentTypeName := "" if info.ParentType != nil { parentTypeName = info.ParentType.Name() } err := invariantf( resultVal.IsValid() && isIterable(result), "User Error: expected iterable, but did not find one "+ "for field %v.%v.", parentTypeName, info.FieldName) if err != nil { panic(gqlerrors.FormatError(err)) } itemType := returnType.OfType completedResults := make([]interface{}, 0, resultVal.Len()) for i := 0; i < resultVal.Len(); i++ { val := resultVal.Index(i).Interface() fieldPath := path.WithKey(i) completedItem := completeValueCatchingError(eCtx, itemType, fieldASTs, info, fieldPath, val) completedResults = append(completedResults, completedItem) } return completedResults }
[ "func", "completeListValue", "(", "eCtx", "*", "executionContext", ",", "returnType", "*", "List", ",", "fieldASTs", "[", "]", "*", "ast", ".", "Field", ",", "info", "ResolveInfo", ",", "path", "*", "ResponsePath", ",", "result", "interface", "{", "}", ")", "interface", "{", "}", "{", "resultVal", ":=", "reflect", ".", "ValueOf", "(", "result", ")", "\n", "if", "resultVal", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "resultVal", "=", "resultVal", ".", "Elem", "(", ")", "\n", "}", "\n", "parentTypeName", ":=", "\"", "\"", "\n", "if", "info", ".", "ParentType", "!=", "nil", "{", "parentTypeName", "=", "info", ".", "ParentType", ".", "Name", "(", ")", "\n", "}", "\n", "err", ":=", "invariantf", "(", "resultVal", ".", "IsValid", "(", ")", "&&", "isIterable", "(", "result", ")", ",", "\"", "\"", "+", "\"", "\"", ",", "parentTypeName", ",", "info", ".", "FieldName", ")", "\n\n", "if", "err", "!=", "nil", "{", "panic", "(", "gqlerrors", ".", "FormatError", "(", "err", ")", ")", "\n", "}", "\n\n", "itemType", ":=", "returnType", ".", "OfType", "\n", "completedResults", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "resultVal", ".", "Len", "(", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "resultVal", ".", "Len", "(", ")", ";", "i", "++", "{", "val", ":=", "resultVal", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", "\n", "fieldPath", ":=", "path", ".", "WithKey", "(", "i", ")", "\n", "completedItem", ":=", "completeValueCatchingError", "(", "eCtx", ",", "itemType", ",", "fieldASTs", ",", "info", ",", "fieldPath", ",", "val", ")", "\n", "completedResults", "=", "append", "(", "completedResults", ",", "completedItem", ")", "\n", "}", "\n", "return", "completedResults", "\n", "}" ]
// completeListValue complete a list value by completing each item in the list with the inner type
[ "completeListValue", "complete", "a", "list", "value", "by", "completing", "each", "item", "in", "the", "list", "with", "the", "inner", "type" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L877-L904
train
graphql-go/graphql
executor.go
defaultResolveTypeFn
func defaultResolveTypeFn(p ResolveTypeParams, abstractType Abstract) *Object { possibleTypes := p.Info.Schema.PossibleTypes(abstractType) for _, possibleType := range possibleTypes { if possibleType.IsTypeOf == nil { continue } isTypeOfParams := IsTypeOfParams{ Value: p.Value, Info: p.Info, Context: p.Context, } if res := possibleType.IsTypeOf(isTypeOfParams); res { return possibleType } } return nil }
go
func defaultResolveTypeFn(p ResolveTypeParams, abstractType Abstract) *Object { possibleTypes := p.Info.Schema.PossibleTypes(abstractType) for _, possibleType := range possibleTypes { if possibleType.IsTypeOf == nil { continue } isTypeOfParams := IsTypeOfParams{ Value: p.Value, Info: p.Info, Context: p.Context, } if res := possibleType.IsTypeOf(isTypeOfParams); res { return possibleType } } return nil }
[ "func", "defaultResolveTypeFn", "(", "p", "ResolveTypeParams", ",", "abstractType", "Abstract", ")", "*", "Object", "{", "possibleTypes", ":=", "p", ".", "Info", ".", "Schema", ".", "PossibleTypes", "(", "abstractType", ")", "\n", "for", "_", ",", "possibleType", ":=", "range", "possibleTypes", "{", "if", "possibleType", ".", "IsTypeOf", "==", "nil", "{", "continue", "\n", "}", "\n", "isTypeOfParams", ":=", "IsTypeOfParams", "{", "Value", ":", "p", ".", "Value", ",", "Info", ":", "p", ".", "Info", ",", "Context", ":", "p", ".", "Context", ",", "}", "\n", "if", "res", ":=", "possibleType", ".", "IsTypeOf", "(", "isTypeOfParams", ")", ";", "res", "{", "return", "possibleType", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// defaultResolveTypeFn If a resolveType function is not given, then a default resolve behavior is // used which tests each possible type for the abstract type by calling // isTypeOf for the object being coerced, returning the first type that matches.
[ "defaultResolveTypeFn", "If", "a", "resolveType", "function", "is", "not", "given", "then", "a", "default", "resolve", "behavior", "is", "used", "which", "tests", "each", "possible", "type", "for", "the", "abstract", "type", "by", "calling", "isTypeOf", "for", "the", "object", "being", "coerced", "returning", "the", "first", "type", "that", "matches", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/executor.go#L909-L925
train
graphql-go/graphql
extensions.go
handleExtensionsInits
func handleExtensionsInits(p *Params) gqlerrors.FormattedErrors { errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { func() { // catch panic from an extension init fn defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.Init: %v", ext.Name(), r.(error)))) } }() // update context p.Context = ext.Init(p.Context, p) }() } return errs }
go
func handleExtensionsInits(p *Params) gqlerrors.FormattedErrors { errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { func() { // catch panic from an extension init fn defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.Init: %v", ext.Name(), r.(error)))) } }() // update context p.Context = ext.Init(p.Context, p) }() } return errs }
[ "func", "handleExtensionsInits", "(", "p", "*", "Params", ")", "gqlerrors", ".", "FormattedErrors", "{", "errs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "_", ",", "ext", ":=", "range", "p", ".", "Schema", ".", "extensions", "{", "func", "(", ")", "{", "// catch panic from an extension init fn", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ext", ".", "Name", "(", ")", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "// update context", "p", ".", "Context", "=", "ext", ".", "Init", "(", "p", ".", "Context", ",", "p", ")", "\n", "}", "(", ")", "\n", "}", "\n", "return", "errs", "\n", "}" ]
// handleExtensionsInits handles all the init functions for all the extensions in the schema
[ "handleExtensionsInits", "handles", "all", "the", "init", "functions", "for", "all", "the", "extensions", "in", "the", "schema" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/extensions.go#L60-L75
train
graphql-go/graphql
extensions.go
handleExtensionsParseDidStart
func handleExtensionsParseDidStart(p *Params) ([]gqlerrors.FormattedError, parseFinishFuncHandler) { fs := map[string]ParseFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ParseFinishFunc ) // catch panic from an extension's parseDidStart functions func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ParseDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ParseDidStart(p.Context) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(err error) []gqlerrors.FormattedError { errs := gqlerrors.FormattedErrors{} for name, fn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ParseFinishFunc: %v", name, r.(error)))) } }() fn(err) }() } return errs } }
go
func handleExtensionsParseDidStart(p *Params) ([]gqlerrors.FormattedError, parseFinishFuncHandler) { fs := map[string]ParseFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ParseFinishFunc ) // catch panic from an extension's parseDidStart functions func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ParseDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ParseDidStart(p.Context) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(err error) []gqlerrors.FormattedError { errs := gqlerrors.FormattedErrors{} for name, fn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ParseFinishFunc: %v", name, r.(error)))) } }() fn(err) }() } return errs } }
[ "func", "handleExtensionsParseDidStart", "(", "p", "*", "Params", ")", "(", "[", "]", "gqlerrors", ".", "FormattedError", ",", "parseFinishFuncHandler", ")", "{", "fs", ":=", "map", "[", "string", "]", "ParseFinishFunc", "{", "}", "\n", "errs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "_", ",", "ext", ":=", "range", "p", ".", "Schema", ".", "extensions", "{", "var", "(", "ctx", "context", ".", "Context", "\n", "finishFn", "ParseFinishFunc", "\n", ")", "\n", "// catch panic from an extension's parseDidStart functions", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ext", ".", "Name", "(", ")", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "ctx", ",", "finishFn", "=", "ext", ".", "ParseDidStart", "(", "p", ".", "Context", ")", "\n", "// update context", "p", ".", "Context", "=", "ctx", "\n", "fs", "[", "ext", ".", "Name", "(", ")", "]", "=", "finishFn", "\n", "}", "(", ")", "\n", "}", "\n", "return", "errs", ",", "func", "(", "err", "error", ")", "[", "]", "gqlerrors", ".", "FormattedError", "{", "errs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "name", ",", "fn", ":=", "range", "fs", "{", "func", "(", ")", "{", "// catch panic from a finishFn", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "fn", "(", "err", ")", "\n", "}", "(", ")", "\n", "}", "\n", "return", "errs", "\n", "}", "\n", "}" ]
// handleExtensionsParseDidStart runs the ParseDidStart functions for each extension
[ "handleExtensionsParseDidStart", "runs", "the", "ParseDidStart", "functions", "for", "each", "extension" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/extensions.go#L78-L114
train
graphql-go/graphql
extensions.go
handleExtensionsValidationDidStart
func handleExtensionsValidationDidStart(p *Params) ([]gqlerrors.FormattedError, validationFinishFuncHandler) { fs := map[string]ValidationFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ValidationFinishFunc ) // catch panic from an extension's validationDidStart function func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ValidationDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ValidationDidStart(p.Context) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(errs []gqlerrors.FormattedError) []gqlerrors.FormattedError { extErrs := gqlerrors.FormattedErrors{} for name, finishFn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { extErrs = append(extErrs, gqlerrors.FormatError(fmt.Errorf("%s.ValidationFinishFunc: %v", name, r.(error)))) } }() finishFn(errs) }() } return extErrs } }
go
func handleExtensionsValidationDidStart(p *Params) ([]gqlerrors.FormattedError, validationFinishFuncHandler) { fs := map[string]ValidationFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ValidationFinishFunc ) // catch panic from an extension's validationDidStart function func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ValidationDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ValidationDidStart(p.Context) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(errs []gqlerrors.FormattedError) []gqlerrors.FormattedError { extErrs := gqlerrors.FormattedErrors{} for name, finishFn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { extErrs = append(extErrs, gqlerrors.FormatError(fmt.Errorf("%s.ValidationFinishFunc: %v", name, r.(error)))) } }() finishFn(errs) }() } return extErrs } }
[ "func", "handleExtensionsValidationDidStart", "(", "p", "*", "Params", ")", "(", "[", "]", "gqlerrors", ".", "FormattedError", ",", "validationFinishFuncHandler", ")", "{", "fs", ":=", "map", "[", "string", "]", "ValidationFinishFunc", "{", "}", "\n", "errs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "_", ",", "ext", ":=", "range", "p", ".", "Schema", ".", "extensions", "{", "var", "(", "ctx", "context", ".", "Context", "\n", "finishFn", "ValidationFinishFunc", "\n", ")", "\n", "// catch panic from an extension's validationDidStart function", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ext", ".", "Name", "(", ")", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "ctx", ",", "finishFn", "=", "ext", ".", "ValidationDidStart", "(", "p", ".", "Context", ")", "\n", "// update context", "p", ".", "Context", "=", "ctx", "\n", "fs", "[", "ext", ".", "Name", "(", ")", "]", "=", "finishFn", "\n", "}", "(", ")", "\n", "}", "\n", "return", "errs", ",", "func", "(", "errs", "[", "]", "gqlerrors", ".", "FormattedError", ")", "[", "]", "gqlerrors", ".", "FormattedError", "{", "extErrs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "name", ",", "finishFn", ":=", "range", "fs", "{", "func", "(", ")", "{", "// catch panic from a finishFn", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "extErrs", "=", "append", "(", "extErrs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "finishFn", "(", "errs", ")", "\n", "}", "(", ")", "\n", "}", "\n", "return", "extErrs", "\n", "}", "\n", "}" ]
// handleExtensionsValidationDidStart notifies the extensions about the start of the validation process
[ "handleExtensionsValidationDidStart", "notifies", "the", "extensions", "about", "the", "start", "of", "the", "validation", "process" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/extensions.go#L117-L153
train
graphql-go/graphql
extensions.go
handleExtensionsExecutionDidStart
func handleExtensionsExecutionDidStart(p *ExecuteParams) ([]gqlerrors.FormattedError, executionFinishFuncHandler) { fs := map[string]ExecutionFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ExecutionFinishFunc ) // catch panic from an extension's executionDidStart function func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ExecutionDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ExecutionDidStart(p.Context) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(result *Result) []gqlerrors.FormattedError { extErrs := gqlerrors.FormattedErrors{} for name, finishFn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { extErrs = append(extErrs, gqlerrors.FormatError(fmt.Errorf("%s.ExecutionFinishFunc: %v", name, r.(error)))) } }() finishFn(result) }() } return extErrs } }
go
func handleExtensionsExecutionDidStart(p *ExecuteParams) ([]gqlerrors.FormattedError, executionFinishFuncHandler) { fs := map[string]ExecutionFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ExecutionFinishFunc ) // catch panic from an extension's executionDidStart function func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ExecutionDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ExecutionDidStart(p.Context) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(result *Result) []gqlerrors.FormattedError { extErrs := gqlerrors.FormattedErrors{} for name, finishFn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { extErrs = append(extErrs, gqlerrors.FormatError(fmt.Errorf("%s.ExecutionFinishFunc: %v", name, r.(error)))) } }() finishFn(result) }() } return extErrs } }
[ "func", "handleExtensionsExecutionDidStart", "(", "p", "*", "ExecuteParams", ")", "(", "[", "]", "gqlerrors", ".", "FormattedError", ",", "executionFinishFuncHandler", ")", "{", "fs", ":=", "map", "[", "string", "]", "ExecutionFinishFunc", "{", "}", "\n", "errs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "_", ",", "ext", ":=", "range", "p", ".", "Schema", ".", "extensions", "{", "var", "(", "ctx", "context", ".", "Context", "\n", "finishFn", "ExecutionFinishFunc", "\n", ")", "\n", "// catch panic from an extension's executionDidStart function", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ext", ".", "Name", "(", ")", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "ctx", ",", "finishFn", "=", "ext", ".", "ExecutionDidStart", "(", "p", ".", "Context", ")", "\n", "// update context", "p", ".", "Context", "=", "ctx", "\n", "fs", "[", "ext", ".", "Name", "(", ")", "]", "=", "finishFn", "\n", "}", "(", ")", "\n", "}", "\n", "return", "errs", ",", "func", "(", "result", "*", "Result", ")", "[", "]", "gqlerrors", ".", "FormattedError", "{", "extErrs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "name", ",", "finishFn", ":=", "range", "fs", "{", "func", "(", ")", "{", "// catch panic from a finishFn", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "extErrs", "=", "append", "(", "extErrs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "finishFn", "(", "result", ")", "\n", "}", "(", ")", "\n", "}", "\n", "return", "extErrs", "\n", "}", "\n", "}" ]
// handleExecutionDidStart handles the ExecutionDidStart functions
[ "handleExecutionDidStart", "handles", "the", "ExecutionDidStart", "functions" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/extensions.go#L156-L192
train
graphql-go/graphql
extensions.go
handleExtensionsResolveFieldDidStart
func handleExtensionsResolveFieldDidStart(exts []Extension, p *executionContext, i *ResolveInfo) ([]gqlerrors.FormattedError, resolveFieldFinishFuncHandler) { fs := map[string]ResolveFieldFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ResolveFieldFinishFunc ) // catch panic from an extension's resolveFieldDidStart function func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ResolveFieldDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ResolveFieldDidStart(p.Context, i) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(val interface{}, err error) []gqlerrors.FormattedError { extErrs := gqlerrors.FormattedErrors{} for name, finishFn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { extErrs = append(extErrs, gqlerrors.FormatError(fmt.Errorf("%s.ResolveFieldFinishFunc: %v", name, r.(error)))) } }() finishFn(val, err) }() } return extErrs } }
go
func handleExtensionsResolveFieldDidStart(exts []Extension, p *executionContext, i *ResolveInfo) ([]gqlerrors.FormattedError, resolveFieldFinishFuncHandler) { fs := map[string]ResolveFieldFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ResolveFieldFinishFunc ) // catch panic from an extension's resolveFieldDidStart function func() { defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ResolveFieldDidStart: %v", ext.Name(), r.(error)))) } }() ctx, finishFn = ext.ResolveFieldDidStart(p.Context, i) // update context p.Context = ctx fs[ext.Name()] = finishFn }() } return errs, func(val interface{}, err error) []gqlerrors.FormattedError { extErrs := gqlerrors.FormattedErrors{} for name, finishFn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { extErrs = append(extErrs, gqlerrors.FormatError(fmt.Errorf("%s.ResolveFieldFinishFunc: %v", name, r.(error)))) } }() finishFn(val, err) }() } return extErrs } }
[ "func", "handleExtensionsResolveFieldDidStart", "(", "exts", "[", "]", "Extension", ",", "p", "*", "executionContext", ",", "i", "*", "ResolveInfo", ")", "(", "[", "]", "gqlerrors", ".", "FormattedError", ",", "resolveFieldFinishFuncHandler", ")", "{", "fs", ":=", "map", "[", "string", "]", "ResolveFieldFinishFunc", "{", "}", "\n", "errs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "_", ",", "ext", ":=", "range", "p", ".", "Schema", ".", "extensions", "{", "var", "(", "ctx", "context", ".", "Context", "\n", "finishFn", "ResolveFieldFinishFunc", "\n", ")", "\n", "// catch panic from an extension's resolveFieldDidStart function", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ext", ".", "Name", "(", ")", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "ctx", ",", "finishFn", "=", "ext", ".", "ResolveFieldDidStart", "(", "p", ".", "Context", ",", "i", ")", "\n", "// update context", "p", ".", "Context", "=", "ctx", "\n", "fs", "[", "ext", ".", "Name", "(", ")", "]", "=", "finishFn", "\n", "}", "(", ")", "\n", "}", "\n", "return", "errs", ",", "func", "(", "val", "interface", "{", "}", ",", "err", "error", ")", "[", "]", "gqlerrors", ".", "FormattedError", "{", "extErrs", ":=", "gqlerrors", ".", "FormattedErrors", "{", "}", "\n", "for", "name", ",", "finishFn", ":=", "range", "fs", "{", "func", "(", ")", "{", "// catch panic from a finishFn", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "extErrs", "=", "append", "(", "extErrs", ",", "gqlerrors", ".", "FormatError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "r", ".", "(", "error", ")", ")", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "finishFn", "(", "val", ",", "err", ")", "\n", "}", "(", ")", "\n", "}", "\n", "return", "extErrs", "\n", "}", "\n", "}" ]
// handleResolveFieldDidStart handles the notification of the extensions about the start of a resolve function
[ "handleResolveFieldDidStart", "handles", "the", "notification", "of", "the", "extensions", "about", "the", "start", "of", "a", "resolve", "function" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/extensions.go#L195-L231
train
graphql-go/graphql
validator.go
VisitUsingRules
func VisitUsingRules(schema *Schema, typeInfo *TypeInfo, astDoc *ast.Document, rules []ValidationRuleFn) []gqlerrors.FormattedError { context := NewValidationContext(schema, astDoc, typeInfo) visitors := []*visitor.VisitorOptions{} for _, rule := range rules { instance := rule(context) visitors = append(visitors, instance.VisitorOpts) } // Visit the whole document with each instance of all provided rules. visitor.Visit(astDoc, visitor.VisitWithTypeInfo(typeInfo, visitor.VisitInParallel(visitors...)), nil) return context.Errors() }
go
func VisitUsingRules(schema *Schema, typeInfo *TypeInfo, astDoc *ast.Document, rules []ValidationRuleFn) []gqlerrors.FormattedError { context := NewValidationContext(schema, astDoc, typeInfo) visitors := []*visitor.VisitorOptions{} for _, rule := range rules { instance := rule(context) visitors = append(visitors, instance.VisitorOpts) } // Visit the whole document with each instance of all provided rules. visitor.Visit(astDoc, visitor.VisitWithTypeInfo(typeInfo, visitor.VisitInParallel(visitors...)), nil) return context.Errors() }
[ "func", "VisitUsingRules", "(", "schema", "*", "Schema", ",", "typeInfo", "*", "TypeInfo", ",", "astDoc", "*", "ast", ".", "Document", ",", "rules", "[", "]", "ValidationRuleFn", ")", "[", "]", "gqlerrors", ".", "FormattedError", "{", "context", ":=", "NewValidationContext", "(", "schema", ",", "astDoc", ",", "typeInfo", ")", "\n", "visitors", ":=", "[", "]", "*", "visitor", ".", "VisitorOptions", "{", "}", "\n\n", "for", "_", ",", "rule", ":=", "range", "rules", "{", "instance", ":=", "rule", "(", "context", ")", "\n", "visitors", "=", "append", "(", "visitors", ",", "instance", ".", "VisitorOpts", ")", "\n", "}", "\n\n", "// Visit the whole document with each instance of all provided rules.", "visitor", ".", "Visit", "(", "astDoc", ",", "visitor", ".", "VisitWithTypeInfo", "(", "typeInfo", ",", "visitor", ".", "VisitInParallel", "(", "visitors", "...", ")", ")", ",", "nil", ")", "\n", "return", "context", ".", "Errors", "(", ")", "\n", "}" ]
// VisitUsingRules This uses a specialized visitor which runs multiple visitors in parallel, // while maintaining the visitor skip and break API. // // @internal // Had to expose it to unit test experimental customizable validation feature, // but not meant for public consumption
[ "VisitUsingRules", "This", "uses", "a", "specialized", "visitor", "which", "runs", "multiple", "visitors", "in", "parallel", "while", "maintaining", "the", "visitor", "skip", "and", "break", "API", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/validator.go#L59-L72
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
findConflictsWithinSelectionSet
func (rule *overlappingFieldsCanBeMergedRule) findConflictsWithinSelectionSet(parentType Named, selectionSet *ast.SelectionSet) []conflict { conflicts := []conflict{} fieldsInfo := rule.getFieldsAndFragmentNames(parentType, selectionSet) // (A) Find find all conflicts "within" the fields of this selection set. // Note: this is the *only place* `collectConflictsWithin` is called. conflicts = rule.collectConflictsWithin(conflicts, fieldsInfo) // (B) Then collect conflicts between these fields and those represented by // each spread fragment name found. for i := 0; i < len(fieldsInfo.fragmentNames); i++ { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, false, fieldsInfo, fieldsInfo.fragmentNames[i]) // (C) Then compare this fragment with all other fragments found in this // selection set to collect conflicts between fragments spread together. // This compares each item in the list of fragment names to every other item // in that same list (except for itself). for k := i + 1; k < len(fieldsInfo.fragmentNames); k++ { conflicts = rule.collectConflictsBetweenFragments(conflicts, false, fieldsInfo.fragmentNames[i], fieldsInfo.fragmentNames[k]) } } return conflicts }
go
func (rule *overlappingFieldsCanBeMergedRule) findConflictsWithinSelectionSet(parentType Named, selectionSet *ast.SelectionSet) []conflict { conflicts := []conflict{} fieldsInfo := rule.getFieldsAndFragmentNames(parentType, selectionSet) // (A) Find find all conflicts "within" the fields of this selection set. // Note: this is the *only place* `collectConflictsWithin` is called. conflicts = rule.collectConflictsWithin(conflicts, fieldsInfo) // (B) Then collect conflicts between these fields and those represented by // each spread fragment name found. for i := 0; i < len(fieldsInfo.fragmentNames); i++ { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, false, fieldsInfo, fieldsInfo.fragmentNames[i]) // (C) Then compare this fragment with all other fragments found in this // selection set to collect conflicts between fragments spread together. // This compares each item in the list of fragment names to every other item // in that same list (except for itself). for k := i + 1; k < len(fieldsInfo.fragmentNames); k++ { conflicts = rule.collectConflictsBetweenFragments(conflicts, false, fieldsInfo.fragmentNames[i], fieldsInfo.fragmentNames[k]) } } return conflicts }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "findConflictsWithinSelectionSet", "(", "parentType", "Named", ",", "selectionSet", "*", "ast", ".", "SelectionSet", ")", "[", "]", "conflict", "{", "conflicts", ":=", "[", "]", "conflict", "{", "}", "\n\n", "fieldsInfo", ":=", "rule", ".", "getFieldsAndFragmentNames", "(", "parentType", ",", "selectionSet", ")", "\n\n", "// (A) Find find all conflicts \"within\" the fields of this selection set.", "// Note: this is the *only place* `collectConflictsWithin` is called.", "conflicts", "=", "rule", ".", "collectConflictsWithin", "(", "conflicts", ",", "fieldsInfo", ")", "\n\n", "// (B) Then collect conflicts between these fields and those represented by", "// each spread fragment name found.", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "fieldsInfo", ".", "fragmentNames", ")", ";", "i", "++", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFieldsAndFragment", "(", "conflicts", ",", "false", ",", "fieldsInfo", ",", "fieldsInfo", ".", "fragmentNames", "[", "i", "]", ")", "\n\n", "// (C) Then compare this fragment with all other fragments found in this", "// selection set to collect conflicts between fragments spread together.", "// This compares each item in the list of fragment names to every other item", "// in that same list (except for itself).", "for", "k", ":=", "i", "+", "1", ";", "k", "<", "len", "(", "fieldsInfo", ".", "fragmentNames", ")", ";", "k", "++", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFragments", "(", "conflicts", ",", "false", ",", "fieldsInfo", ".", "fragmentNames", "[", "i", "]", ",", "fieldsInfo", ".", "fragmentNames", "[", "k", "]", ")", "\n", "}", "\n", "}", "\n", "return", "conflicts", "\n", "}" ]
// Find all conflicts found "within" a selection set, including those found // via spreading in fragments. Called when visiting each SelectionSet in the // GraphQL Document.
[ "Find", "all", "conflicts", "found", "within", "a", "selection", "set", "including", "those", "found", "via", "spreading", "in", "fragments", ".", "Called", "when", "visiting", "each", "SelectionSet", "in", "the", "GraphQL", "Document", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L166-L190
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
collectConflictsBetweenFieldsAndFragment
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsBetweenFieldsAndFragment(conflicts []conflict, areMutuallyExclusive bool, fieldsInfo *fieldsAndFragmentNames, fragmentName string) []conflict { fragment := rule.context.Fragment(fragmentName) if fragment == nil { return conflicts } fieldsInfo2 := rule.getReferencedFieldsAndFragmentNames(fragment) // (D) First collect any conflicts between the provided collection of fields // and the collection of fields represented by the given fragment. conflicts = rule.collectConflictsBetween(conflicts, areMutuallyExclusive, fieldsInfo, fieldsInfo2) // (E) Then collect any conflicts between the provided collection of fields // and any fragment names found in the given fragment. for _, fragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, areMutuallyExclusive, fieldsInfo2, fragmentName2) } return conflicts }
go
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsBetweenFieldsAndFragment(conflicts []conflict, areMutuallyExclusive bool, fieldsInfo *fieldsAndFragmentNames, fragmentName string) []conflict { fragment := rule.context.Fragment(fragmentName) if fragment == nil { return conflicts } fieldsInfo2 := rule.getReferencedFieldsAndFragmentNames(fragment) // (D) First collect any conflicts between the provided collection of fields // and the collection of fields represented by the given fragment. conflicts = rule.collectConflictsBetween(conflicts, areMutuallyExclusive, fieldsInfo, fieldsInfo2) // (E) Then collect any conflicts between the provided collection of fields // and any fragment names found in the given fragment. for _, fragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, areMutuallyExclusive, fieldsInfo2, fragmentName2) } return conflicts }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "collectConflictsBetweenFieldsAndFragment", "(", "conflicts", "[", "]", "conflict", ",", "areMutuallyExclusive", "bool", ",", "fieldsInfo", "*", "fieldsAndFragmentNames", ",", "fragmentName", "string", ")", "[", "]", "conflict", "{", "fragment", ":=", "rule", ".", "context", ".", "Fragment", "(", "fragmentName", ")", "\n", "if", "fragment", "==", "nil", "{", "return", "conflicts", "\n", "}", "\n\n", "fieldsInfo2", ":=", "rule", ".", "getReferencedFieldsAndFragmentNames", "(", "fragment", ")", "\n\n", "// (D) First collect any conflicts between the provided collection of fields", "// and the collection of fields represented by the given fragment.", "conflicts", "=", "rule", ".", "collectConflictsBetween", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fieldsInfo", ",", "fieldsInfo2", ")", "\n\n", "// (E) Then collect any conflicts between the provided collection of fields", "// and any fragment names found in the given fragment.", "for", "_", ",", "fragmentName2", ":=", "range", "fieldsInfo2", ".", "fragmentNames", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFieldsAndFragment", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fieldsInfo2", ",", "fragmentName2", ")", "\n", "}", "\n\n", "return", "conflicts", "\n\n", "}" ]
// Collect all conflicts found between a set of fields and a fragment reference // including via spreading in any nested fragments.
[ "Collect", "all", "conflicts", "found", "between", "a", "set", "of", "fields", "and", "a", "fragment", "reference", "including", "via", "spreading", "in", "any", "nested", "fragments", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L194-L214
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
collectConflictsBetweenFragments
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsBetweenFragments(conflicts []conflict, areMutuallyExclusive bool, fragmentName1 string, fragmentName2 string) []conflict { fragment1 := rule.context.Fragment(fragmentName1) fragment2 := rule.context.Fragment(fragmentName2) if fragment1 == nil || fragment2 == nil { return conflicts } // No need to compare a fragment to itself. if fragment1 == fragment2 { return conflicts } // Memoize so two fragments are not compared for conflicts more than once. if rule.comparedSet.Has(fragmentName1, fragmentName2, areMutuallyExclusive) { return conflicts } rule.comparedSet.Add(fragmentName1, fragmentName2, areMutuallyExclusive) fieldsInfo1 := rule.getReferencedFieldsAndFragmentNames(fragment1) fieldsInfo2 := rule.getReferencedFieldsAndFragmentNames(fragment2) // (F) First, collect all conflicts between these two collections of fields // (not including any nested fragments). conflicts = rule.collectConflictsBetween(conflicts, areMutuallyExclusive, fieldsInfo1, fieldsInfo2) // (G) Then collect conflicts between the first fragment and any nested // fragments spread in the second fragment. for _, innerFragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFragments(conflicts, areMutuallyExclusive, fragmentName1, innerFragmentName2) } // (G) Then collect conflicts between the second fragment and any nested // fragments spread in the first fragment. for _, innerFragmentName1 := range fieldsInfo1.fragmentNames { conflicts = rule.collectConflictsBetweenFragments(conflicts, areMutuallyExclusive, innerFragmentName1, fragmentName2) } return conflicts }
go
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsBetweenFragments(conflicts []conflict, areMutuallyExclusive bool, fragmentName1 string, fragmentName2 string) []conflict { fragment1 := rule.context.Fragment(fragmentName1) fragment2 := rule.context.Fragment(fragmentName2) if fragment1 == nil || fragment2 == nil { return conflicts } // No need to compare a fragment to itself. if fragment1 == fragment2 { return conflicts } // Memoize so two fragments are not compared for conflicts more than once. if rule.comparedSet.Has(fragmentName1, fragmentName2, areMutuallyExclusive) { return conflicts } rule.comparedSet.Add(fragmentName1, fragmentName2, areMutuallyExclusive) fieldsInfo1 := rule.getReferencedFieldsAndFragmentNames(fragment1) fieldsInfo2 := rule.getReferencedFieldsAndFragmentNames(fragment2) // (F) First, collect all conflicts between these two collections of fields // (not including any nested fragments). conflicts = rule.collectConflictsBetween(conflicts, areMutuallyExclusive, fieldsInfo1, fieldsInfo2) // (G) Then collect conflicts between the first fragment and any nested // fragments spread in the second fragment. for _, innerFragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFragments(conflicts, areMutuallyExclusive, fragmentName1, innerFragmentName2) } // (G) Then collect conflicts between the second fragment and any nested // fragments spread in the first fragment. for _, innerFragmentName1 := range fieldsInfo1.fragmentNames { conflicts = rule.collectConflictsBetweenFragments(conflicts, areMutuallyExclusive, innerFragmentName1, fragmentName2) } return conflicts }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "collectConflictsBetweenFragments", "(", "conflicts", "[", "]", "conflict", ",", "areMutuallyExclusive", "bool", ",", "fragmentName1", "string", ",", "fragmentName2", "string", ")", "[", "]", "conflict", "{", "fragment1", ":=", "rule", ".", "context", ".", "Fragment", "(", "fragmentName1", ")", "\n", "fragment2", ":=", "rule", ".", "context", ".", "Fragment", "(", "fragmentName2", ")", "\n\n", "if", "fragment1", "==", "nil", "||", "fragment2", "==", "nil", "{", "return", "conflicts", "\n", "}", "\n\n", "// No need to compare a fragment to itself.", "if", "fragment1", "==", "fragment2", "{", "return", "conflicts", "\n", "}", "\n\n", "// Memoize so two fragments are not compared for conflicts more than once.", "if", "rule", ".", "comparedSet", ".", "Has", "(", "fragmentName1", ",", "fragmentName2", ",", "areMutuallyExclusive", ")", "{", "return", "conflicts", "\n", "}", "\n", "rule", ".", "comparedSet", ".", "Add", "(", "fragmentName1", ",", "fragmentName2", ",", "areMutuallyExclusive", ")", "\n\n", "fieldsInfo1", ":=", "rule", ".", "getReferencedFieldsAndFragmentNames", "(", "fragment1", ")", "\n", "fieldsInfo2", ":=", "rule", ".", "getReferencedFieldsAndFragmentNames", "(", "fragment2", ")", "\n\n", "// (F) First, collect all conflicts between these two collections of fields", "// (not including any nested fragments).", "conflicts", "=", "rule", ".", "collectConflictsBetween", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fieldsInfo1", ",", "fieldsInfo2", ")", "\n\n", "// (G) Then collect conflicts between the first fragment and any nested", "// fragments spread in the second fragment.", "for", "_", ",", "innerFragmentName2", ":=", "range", "fieldsInfo2", ".", "fragmentNames", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFragments", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fragmentName1", ",", "innerFragmentName2", ")", "\n", "}", "\n\n", "// (G) Then collect conflicts between the second fragment and any nested", "// fragments spread in the first fragment.", "for", "_", ",", "innerFragmentName1", ":=", "range", "fieldsInfo1", ".", "fragmentNames", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFragments", "(", "conflicts", ",", "areMutuallyExclusive", ",", "innerFragmentName1", ",", "fragmentName2", ")", "\n", "}", "\n\n", "return", "conflicts", "\n", "}" ]
// Collect all conflicts found between two fragments, including via spreading in // any nested fragments.
[ "Collect", "all", "conflicts", "found", "between", "two", "fragments", "including", "via", "spreading", "in", "any", "nested", "fragments", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L218-L257
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
findConflictsBetweenSubSelectionSets
func (rule *overlappingFieldsCanBeMergedRule) findConflictsBetweenSubSelectionSets(areMutuallyExclusive bool, parentType1 Named, selectionSet1 *ast.SelectionSet, parentType2 Named, selectionSet2 *ast.SelectionSet) []conflict { conflicts := []conflict{} fieldsInfo1 := rule.getFieldsAndFragmentNames(parentType1, selectionSet1) fieldsInfo2 := rule.getFieldsAndFragmentNames(parentType2, selectionSet2) // (H) First, collect all conflicts between these two collections of field. conflicts = rule.collectConflictsBetween(conflicts, areMutuallyExclusive, fieldsInfo1, fieldsInfo2) // (I) Then collect conflicts between the first collection of fields and // those referenced by each fragment name associated with the second. for _, fragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, areMutuallyExclusive, fieldsInfo1, fragmentName2) } // (I) Then collect conflicts between the second collection of fields and // those referenced by each fragment name associated with the first. for _, fragmentName1 := range fieldsInfo1.fragmentNames { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, areMutuallyExclusive, fieldsInfo2, fragmentName1) } // (J) Also collect conflicts between any fragment names by the first and // fragment names by the second. This compares each item in the first set of // names to each item in the second set of names. for _, fragmentName1 := range fieldsInfo1.fragmentNames { for _, fragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFragments(conflicts, areMutuallyExclusive, fragmentName1, fragmentName2) } } return conflicts }
go
func (rule *overlappingFieldsCanBeMergedRule) findConflictsBetweenSubSelectionSets(areMutuallyExclusive bool, parentType1 Named, selectionSet1 *ast.SelectionSet, parentType2 Named, selectionSet2 *ast.SelectionSet) []conflict { conflicts := []conflict{} fieldsInfo1 := rule.getFieldsAndFragmentNames(parentType1, selectionSet1) fieldsInfo2 := rule.getFieldsAndFragmentNames(parentType2, selectionSet2) // (H) First, collect all conflicts between these two collections of field. conflicts = rule.collectConflictsBetween(conflicts, areMutuallyExclusive, fieldsInfo1, fieldsInfo2) // (I) Then collect conflicts between the first collection of fields and // those referenced by each fragment name associated with the second. for _, fragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, areMutuallyExclusive, fieldsInfo1, fragmentName2) } // (I) Then collect conflicts between the second collection of fields and // those referenced by each fragment name associated with the first. for _, fragmentName1 := range fieldsInfo1.fragmentNames { conflicts = rule.collectConflictsBetweenFieldsAndFragment(conflicts, areMutuallyExclusive, fieldsInfo2, fragmentName1) } // (J) Also collect conflicts between any fragment names by the first and // fragment names by the second. This compares each item in the first set of // names to each item in the second set of names. for _, fragmentName1 := range fieldsInfo1.fragmentNames { for _, fragmentName2 := range fieldsInfo2.fragmentNames { conflicts = rule.collectConflictsBetweenFragments(conflicts, areMutuallyExclusive, fragmentName1, fragmentName2) } } return conflicts }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "findConflictsBetweenSubSelectionSets", "(", "areMutuallyExclusive", "bool", ",", "parentType1", "Named", ",", "selectionSet1", "*", "ast", ".", "SelectionSet", ",", "parentType2", "Named", ",", "selectionSet2", "*", "ast", ".", "SelectionSet", ")", "[", "]", "conflict", "{", "conflicts", ":=", "[", "]", "conflict", "{", "}", "\n\n", "fieldsInfo1", ":=", "rule", ".", "getFieldsAndFragmentNames", "(", "parentType1", ",", "selectionSet1", ")", "\n", "fieldsInfo2", ":=", "rule", ".", "getFieldsAndFragmentNames", "(", "parentType2", ",", "selectionSet2", ")", "\n\n", "// (H) First, collect all conflicts between these two collections of field.", "conflicts", "=", "rule", ".", "collectConflictsBetween", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fieldsInfo1", ",", "fieldsInfo2", ")", "\n\n", "// (I) Then collect conflicts between the first collection of fields and", "// those referenced by each fragment name associated with the second.", "for", "_", ",", "fragmentName2", ":=", "range", "fieldsInfo2", ".", "fragmentNames", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFieldsAndFragment", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fieldsInfo1", ",", "fragmentName2", ")", "\n", "}", "\n\n", "// (I) Then collect conflicts between the second collection of fields and", "// those referenced by each fragment name associated with the first.", "for", "_", ",", "fragmentName1", ":=", "range", "fieldsInfo1", ".", "fragmentNames", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFieldsAndFragment", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fieldsInfo2", ",", "fragmentName1", ")", "\n", "}", "\n\n", "// (J) Also collect conflicts between any fragment names by the first and", "// fragment names by the second. This compares each item in the first set of", "// names to each item in the second set of names.", "for", "_", ",", "fragmentName1", ":=", "range", "fieldsInfo1", ".", "fragmentNames", "{", "for", "_", ",", "fragmentName2", ":=", "range", "fieldsInfo2", ".", "fragmentNames", "{", "conflicts", "=", "rule", ".", "collectConflictsBetweenFragments", "(", "conflicts", ",", "areMutuallyExclusive", ",", "fragmentName1", ",", "fragmentName2", ")", "\n", "}", "\n", "}", "\n", "return", "conflicts", "\n", "}" ]
// Find all conflicts found between two selection sets, including those found // via spreading in fragments. Called when determining if conflicts exist // between the sub-fields of two overlapping fields.
[ "Find", "all", "conflicts", "found", "between", "two", "selection", "sets", "including", "those", "found", "via", "spreading", "in", "fragments", ".", "Called", "when", "determining", "if", "conflicts", "exist", "between", "the", "sub", "-", "fields", "of", "two", "overlapping", "fields", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L262-L292
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
collectConflictsWithin
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsWithin(conflicts []conflict, fieldsInfo *fieldsAndFragmentNames) []conflict { // A field map is a keyed collection, where each key represents a response // name and the value at that key is a list of all fields which provide that // response name. For every response name, if there are multiple fields, they // must be compared to find a potential conflict. for _, responseName := range fieldsInfo.fieldsOrder { fields, ok := fieldsInfo.fieldMap[responseName] if !ok { continue } // This compares every field in the list to every other field in this list // (except to itself). If the list only has one item, nothing needs to // be compared. if len(fields) <= 1 { continue } for i := 0; i < len(fields); i++ { for k := i + 1; k < len(fields); k++ { // within one collection is never mutually exclusive isMutuallyExclusive := false conflict := rule.findConflict(isMutuallyExclusive, responseName, fields[i], fields[k]) if conflict != nil { conflicts = append(conflicts, *conflict) } } } } return conflicts }
go
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsWithin(conflicts []conflict, fieldsInfo *fieldsAndFragmentNames) []conflict { // A field map is a keyed collection, where each key represents a response // name and the value at that key is a list of all fields which provide that // response name. For every response name, if there are multiple fields, they // must be compared to find a potential conflict. for _, responseName := range fieldsInfo.fieldsOrder { fields, ok := fieldsInfo.fieldMap[responseName] if !ok { continue } // This compares every field in the list to every other field in this list // (except to itself). If the list only has one item, nothing needs to // be compared. if len(fields) <= 1 { continue } for i := 0; i < len(fields); i++ { for k := i + 1; k < len(fields); k++ { // within one collection is never mutually exclusive isMutuallyExclusive := false conflict := rule.findConflict(isMutuallyExclusive, responseName, fields[i], fields[k]) if conflict != nil { conflicts = append(conflicts, *conflict) } } } } return conflicts }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "collectConflictsWithin", "(", "conflicts", "[", "]", "conflict", ",", "fieldsInfo", "*", "fieldsAndFragmentNames", ")", "[", "]", "conflict", "{", "// A field map is a keyed collection, where each key represents a response", "// name and the value at that key is a list of all fields which provide that", "// response name. For every response name, if there are multiple fields, they", "// must be compared to find a potential conflict.", "for", "_", ",", "responseName", ":=", "range", "fieldsInfo", ".", "fieldsOrder", "{", "fields", ",", "ok", ":=", "fieldsInfo", ".", "fieldMap", "[", "responseName", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "// This compares every field in the list to every other field in this list", "// (except to itself). If the list only has one item, nothing needs to", "// be compared.", "if", "len", "(", "fields", ")", "<=", "1", "{", "continue", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "fields", ")", ";", "i", "++", "{", "for", "k", ":=", "i", "+", "1", ";", "k", "<", "len", "(", "fields", ")", ";", "k", "++", "{", "// within one collection is never mutually exclusive", "isMutuallyExclusive", ":=", "false", "\n", "conflict", ":=", "rule", ".", "findConflict", "(", "isMutuallyExclusive", ",", "responseName", ",", "fields", "[", "i", "]", ",", "fields", "[", "k", "]", ")", "\n", "if", "conflict", "!=", "nil", "{", "conflicts", "=", "append", "(", "conflicts", ",", "*", "conflict", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "conflicts", "\n", "}" ]
// Collect all Conflicts "within" one collection of fields.
[ "Collect", "all", "Conflicts", "within", "one", "collection", "of", "fields", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L295-L323
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
collectConflictsBetween
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsBetween(conflicts []conflict, parentFieldsAreMutuallyExclusive bool, fieldsInfo1 *fieldsAndFragmentNames, fieldsInfo2 *fieldsAndFragmentNames) []conflict { // A field map is a keyed collection, where each key represents a response // name and the value at that key is a list of all fields which provide that // response name. For any response name which appears in both provided field // maps, each field from the first field map must be compared to every field // in the second field map to find potential conflicts. for _, responseName := range fieldsInfo1.fieldsOrder { fields1, ok1 := fieldsInfo1.fieldMap[responseName] fields2, ok2 := fieldsInfo2.fieldMap[responseName] if !ok1 || !ok2 { continue } for i := 0; i < len(fields1); i++ { for k := 0; k < len(fields2); k++ { conflict := rule.findConflict(parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[k]) if conflict != nil { conflicts = append(conflicts, *conflict) } } } } return conflicts }
go
func (rule *overlappingFieldsCanBeMergedRule) collectConflictsBetween(conflicts []conflict, parentFieldsAreMutuallyExclusive bool, fieldsInfo1 *fieldsAndFragmentNames, fieldsInfo2 *fieldsAndFragmentNames) []conflict { // A field map is a keyed collection, where each key represents a response // name and the value at that key is a list of all fields which provide that // response name. For any response name which appears in both provided field // maps, each field from the first field map must be compared to every field // in the second field map to find potential conflicts. for _, responseName := range fieldsInfo1.fieldsOrder { fields1, ok1 := fieldsInfo1.fieldMap[responseName] fields2, ok2 := fieldsInfo2.fieldMap[responseName] if !ok1 || !ok2 { continue } for i := 0; i < len(fields1); i++ { for k := 0; k < len(fields2); k++ { conflict := rule.findConflict(parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[k]) if conflict != nil { conflicts = append(conflicts, *conflict) } } } } return conflicts }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "collectConflictsBetween", "(", "conflicts", "[", "]", "conflict", ",", "parentFieldsAreMutuallyExclusive", "bool", ",", "fieldsInfo1", "*", "fieldsAndFragmentNames", ",", "fieldsInfo2", "*", "fieldsAndFragmentNames", ")", "[", "]", "conflict", "{", "// A field map is a keyed collection, where each key represents a response", "// name and the value at that key is a list of all fields which provide that", "// response name. For any response name which appears in both provided field", "// maps, each field from the first field map must be compared to every field", "// in the second field map to find potential conflicts.", "for", "_", ",", "responseName", ":=", "range", "fieldsInfo1", ".", "fieldsOrder", "{", "fields1", ",", "ok1", ":=", "fieldsInfo1", ".", "fieldMap", "[", "responseName", "]", "\n", "fields2", ",", "ok2", ":=", "fieldsInfo2", ".", "fieldMap", "[", "responseName", "]", "\n", "if", "!", "ok1", "||", "!", "ok2", "{", "continue", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "fields1", ")", ";", "i", "++", "{", "for", "k", ":=", "0", ";", "k", "<", "len", "(", "fields2", ")", ";", "k", "++", "{", "conflict", ":=", "rule", ".", "findConflict", "(", "parentFieldsAreMutuallyExclusive", ",", "responseName", ",", "fields1", "[", "i", "]", ",", "fields2", "[", "k", "]", ")", "\n", "if", "conflict", "!=", "nil", "{", "conflicts", "=", "append", "(", "conflicts", ",", "*", "conflict", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "conflicts", "\n", "}" ]
// Collect all Conflicts between two collections of fields. This is similar to, // but different from the `collectConflictsWithin` function above. This check // assumes that `collectConflictsWithin` has already been called on each // provided collection of fields. This is true because this validator traverses // each individual selection set.
[ "Collect", "all", "Conflicts", "between", "two", "collections", "of", "fields", ".", "This", "is", "similar", "to", "but", "different", "from", "the", "collectConflictsWithin", "function", "above", ".", "This", "check", "assumes", "that", "collectConflictsWithin", "has", "already", "been", "called", "on", "each", "provided", "collection", "of", "fields", ".", "This", "is", "true", "because", "this", "validator", "traverses", "each", "individual", "selection", "set", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L330-L354
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
findConflict
func (rule *overlappingFieldsCanBeMergedRule) findConflict(parentFieldsAreMutuallyExclusive bool, responseName string, field *fieldDefPair, field2 *fieldDefPair) *conflict { parentType1 := field.ParentType ast1 := field.Field def1 := field.FieldDef parentType2 := field2.ParentType ast2 := field2.Field def2 := field2.FieldDef // If it is known that two fields could not possibly apply at the same // time, due to the parent types, then it is safe to permit them to diverge // in aliased field or arguments used as they will not present any ambiguity // by differing. // It is known that two parent types could never overlap if they are // different Object types. Interface or Union types might overlap - if not // in the current state of the schema, then perhaps in some future version, // thus may not safely diverge. _, isParentType1Object := parentType1.(*Object) _, isParentType2Object := parentType2.(*Object) areMutuallyExclusive := parentFieldsAreMutuallyExclusive || parentType1 != parentType2 && isParentType1Object && isParentType2Object // The return type for each field. var type1 Type var type2 Type if def1 != nil { type1 = def1.Type } if def2 != nil { type2 = def2.Type } if !areMutuallyExclusive { // Two aliases must refer to the same field. name1 := "" name2 := "" if ast1.Name != nil { name1 = ast1.Name.Value } if ast2.Name != nil { name2 = ast2.Name.Value } if name1 != name2 { return &conflict{ Reason: conflictReason{ Name: responseName, Message: fmt.Sprintf(`%v and %v are different fields`, name1, name2), }, FieldsLeft: []ast.Node{ast1}, FieldsRight: []ast.Node{ast2}, } } // Two field calls must have the same arguments. if !sameArguments(ast1.Arguments, ast2.Arguments) { return &conflict{ Reason: conflictReason{ Name: responseName, Message: `they have differing arguments`, }, FieldsLeft: []ast.Node{ast1}, FieldsRight: []ast.Node{ast2}, } } } if type1 != nil && type2 != nil && doTypesConflict(type1, type2) { return &conflict{ Reason: conflictReason{ Name: responseName, Message: fmt.Sprintf(`they return conflicting types %v and %v`, type1, type2), }, FieldsLeft: []ast.Node{ast1}, FieldsRight: []ast.Node{ast2}, } } // Collect and compare sub-fields. Use the same "visited fragment names" list // for both collections so fields in a fragment reference are never // compared to themselves. selectionSet1 := ast1.SelectionSet selectionSet2 := ast2.SelectionSet if selectionSet1 != nil && selectionSet2 != nil { conflicts := rule.findConflictsBetweenSubSelectionSets(areMutuallyExclusive, GetNamed(type1), selectionSet1, GetNamed(type2), selectionSet2) return subfieldConflicts(conflicts, responseName, ast1, ast2) } return nil }
go
func (rule *overlappingFieldsCanBeMergedRule) findConflict(parentFieldsAreMutuallyExclusive bool, responseName string, field *fieldDefPair, field2 *fieldDefPair) *conflict { parentType1 := field.ParentType ast1 := field.Field def1 := field.FieldDef parentType2 := field2.ParentType ast2 := field2.Field def2 := field2.FieldDef // If it is known that two fields could not possibly apply at the same // time, due to the parent types, then it is safe to permit them to diverge // in aliased field or arguments used as they will not present any ambiguity // by differing. // It is known that two parent types could never overlap if they are // different Object types. Interface or Union types might overlap - if not // in the current state of the schema, then perhaps in some future version, // thus may not safely diverge. _, isParentType1Object := parentType1.(*Object) _, isParentType2Object := parentType2.(*Object) areMutuallyExclusive := parentFieldsAreMutuallyExclusive || parentType1 != parentType2 && isParentType1Object && isParentType2Object // The return type for each field. var type1 Type var type2 Type if def1 != nil { type1 = def1.Type } if def2 != nil { type2 = def2.Type } if !areMutuallyExclusive { // Two aliases must refer to the same field. name1 := "" name2 := "" if ast1.Name != nil { name1 = ast1.Name.Value } if ast2.Name != nil { name2 = ast2.Name.Value } if name1 != name2 { return &conflict{ Reason: conflictReason{ Name: responseName, Message: fmt.Sprintf(`%v and %v are different fields`, name1, name2), }, FieldsLeft: []ast.Node{ast1}, FieldsRight: []ast.Node{ast2}, } } // Two field calls must have the same arguments. if !sameArguments(ast1.Arguments, ast2.Arguments) { return &conflict{ Reason: conflictReason{ Name: responseName, Message: `they have differing arguments`, }, FieldsLeft: []ast.Node{ast1}, FieldsRight: []ast.Node{ast2}, } } } if type1 != nil && type2 != nil && doTypesConflict(type1, type2) { return &conflict{ Reason: conflictReason{ Name: responseName, Message: fmt.Sprintf(`they return conflicting types %v and %v`, type1, type2), }, FieldsLeft: []ast.Node{ast1}, FieldsRight: []ast.Node{ast2}, } } // Collect and compare sub-fields. Use the same "visited fragment names" list // for both collections so fields in a fragment reference are never // compared to themselves. selectionSet1 := ast1.SelectionSet selectionSet2 := ast2.SelectionSet if selectionSet1 != nil && selectionSet2 != nil { conflicts := rule.findConflictsBetweenSubSelectionSets(areMutuallyExclusive, GetNamed(type1), selectionSet1, GetNamed(type2), selectionSet2) return subfieldConflicts(conflicts, responseName, ast1, ast2) } return nil }
[ "func", "(", "rule", "*", "overlappingFieldsCanBeMergedRule", ")", "findConflict", "(", "parentFieldsAreMutuallyExclusive", "bool", ",", "responseName", "string", ",", "field", "*", "fieldDefPair", ",", "field2", "*", "fieldDefPair", ")", "*", "conflict", "{", "parentType1", ":=", "field", ".", "ParentType", "\n", "ast1", ":=", "field", ".", "Field", "\n", "def1", ":=", "field", ".", "FieldDef", "\n\n", "parentType2", ":=", "field2", ".", "ParentType", "\n", "ast2", ":=", "field2", ".", "Field", "\n", "def2", ":=", "field2", ".", "FieldDef", "\n\n", "// If it is known that two fields could not possibly apply at the same", "// time, due to the parent types, then it is safe to permit them to diverge", "// in aliased field or arguments used as they will not present any ambiguity", "// by differing.", "// It is known that two parent types could never overlap if they are", "// different Object types. Interface or Union types might overlap - if not", "// in the current state of the schema, then perhaps in some future version,", "// thus may not safely diverge.", "_", ",", "isParentType1Object", ":=", "parentType1", ".", "(", "*", "Object", ")", "\n", "_", ",", "isParentType2Object", ":=", "parentType2", ".", "(", "*", "Object", ")", "\n", "areMutuallyExclusive", ":=", "parentFieldsAreMutuallyExclusive", "||", "parentType1", "!=", "parentType2", "&&", "isParentType1Object", "&&", "isParentType2Object", "\n\n", "// The return type for each field.", "var", "type1", "Type", "\n", "var", "type2", "Type", "\n", "if", "def1", "!=", "nil", "{", "type1", "=", "def1", ".", "Type", "\n", "}", "\n", "if", "def2", "!=", "nil", "{", "type2", "=", "def2", ".", "Type", "\n", "}", "\n\n", "if", "!", "areMutuallyExclusive", "{", "// Two aliases must refer to the same field.", "name1", ":=", "\"", "\"", "\n", "name2", ":=", "\"", "\"", "\n\n", "if", "ast1", ".", "Name", "!=", "nil", "{", "name1", "=", "ast1", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "ast2", ".", "Name", "!=", "nil", "{", "name2", "=", "ast2", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "name1", "!=", "name2", "{", "return", "&", "conflict", "{", "Reason", ":", "conflictReason", "{", "Name", ":", "responseName", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "`%v and %v are different fields`", ",", "name1", ",", "name2", ")", ",", "}", ",", "FieldsLeft", ":", "[", "]", "ast", ".", "Node", "{", "ast1", "}", ",", "FieldsRight", ":", "[", "]", "ast", ".", "Node", "{", "ast2", "}", ",", "}", "\n", "}", "\n\n", "// Two field calls must have the same arguments.", "if", "!", "sameArguments", "(", "ast1", ".", "Arguments", ",", "ast2", ".", "Arguments", ")", "{", "return", "&", "conflict", "{", "Reason", ":", "conflictReason", "{", "Name", ":", "responseName", ",", "Message", ":", "`they have differing arguments`", ",", "}", ",", "FieldsLeft", ":", "[", "]", "ast", ".", "Node", "{", "ast1", "}", ",", "FieldsRight", ":", "[", "]", "ast", ".", "Node", "{", "ast2", "}", ",", "}", "\n", "}", "\n", "}", "\n\n", "if", "type1", "!=", "nil", "&&", "type2", "!=", "nil", "&&", "doTypesConflict", "(", "type1", ",", "type2", ")", "{", "return", "&", "conflict", "{", "Reason", ":", "conflictReason", "{", "Name", ":", "responseName", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "`they return conflicting types %v and %v`", ",", "type1", ",", "type2", ")", ",", "}", ",", "FieldsLeft", ":", "[", "]", "ast", ".", "Node", "{", "ast1", "}", ",", "FieldsRight", ":", "[", "]", "ast", ".", "Node", "{", "ast2", "}", ",", "}", "\n", "}", "\n\n", "// Collect and compare sub-fields. Use the same \"visited fragment names\" list", "// for both collections so fields in a fragment reference are never", "// compared to themselves.", "selectionSet1", ":=", "ast1", ".", "SelectionSet", "\n", "selectionSet2", ":=", "ast2", ".", "SelectionSet", "\n", "if", "selectionSet1", "!=", "nil", "&&", "selectionSet2", "!=", "nil", "{", "conflicts", ":=", "rule", ".", "findConflictsBetweenSubSelectionSets", "(", "areMutuallyExclusive", ",", "GetNamed", "(", "type1", ")", ",", "selectionSet1", ",", "GetNamed", "(", "type2", ")", ",", "selectionSet2", ")", "\n", "return", "subfieldConflicts", "(", "conflicts", ",", "responseName", ",", "ast1", ",", "ast2", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// findConflict Determines if there is a conflict between two particular fields.
[ "findConflict", "Determines", "if", "there", "is", "a", "conflict", "between", "two", "particular", "fields", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L357-L445
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
doTypesConflict
func doTypesConflict(type1 Output, type2 Output) bool { if type1, ok := type1.(*List); ok { if type2, ok := type2.(*List); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if type2, ok := type2.(*List); ok { if type1, ok := type1.(*List); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if type1, ok := type1.(*NonNull); ok { if type2, ok := type2.(*NonNull); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if type2, ok := type2.(*NonNull); ok { if type1, ok := type1.(*NonNull); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if IsLeafType(type1) || IsLeafType(type2) { return type1 != type2 } return false }
go
func doTypesConflict(type1 Output, type2 Output) bool { if type1, ok := type1.(*List); ok { if type2, ok := type2.(*List); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if type2, ok := type2.(*List); ok { if type1, ok := type1.(*List); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if type1, ok := type1.(*NonNull); ok { if type2, ok := type2.(*NonNull); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if type2, ok := type2.(*NonNull); ok { if type1, ok := type1.(*NonNull); ok { return doTypesConflict(type1.OfType, type2.OfType) } return true } if IsLeafType(type1) || IsLeafType(type2) { return type1 != type2 } return false }
[ "func", "doTypesConflict", "(", "type1", "Output", ",", "type2", "Output", ")", "bool", "{", "if", "type1", ",", "ok", ":=", "type1", ".", "(", "*", "List", ")", ";", "ok", "{", "if", "type2", ",", "ok", ":=", "type2", ".", "(", "*", "List", ")", ";", "ok", "{", "return", "doTypesConflict", "(", "type1", ".", "OfType", ",", "type2", ".", "OfType", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "type2", ",", "ok", ":=", "type2", ".", "(", "*", "List", ")", ";", "ok", "{", "if", "type1", ",", "ok", ":=", "type1", ".", "(", "*", "List", ")", ";", "ok", "{", "return", "doTypesConflict", "(", "type1", ".", "OfType", ",", "type2", ".", "OfType", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "type1", ",", "ok", ":=", "type1", ".", "(", "*", "NonNull", ")", ";", "ok", "{", "if", "type2", ",", "ok", ":=", "type2", ".", "(", "*", "NonNull", ")", ";", "ok", "{", "return", "doTypesConflict", "(", "type1", ".", "OfType", ",", "type2", ".", "OfType", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "type2", ",", "ok", ":=", "type2", ".", "(", "*", "NonNull", ")", ";", "ok", "{", "if", "type1", ",", "ok", ":=", "type1", ".", "(", "*", "NonNull", ")", ";", "ok", "{", "return", "doTypesConflict", "(", "type1", ".", "OfType", ",", "type2", ".", "OfType", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "IsLeafType", "(", "type1", ")", "||", "IsLeafType", "(", "type2", ")", "{", "return", "type1", "!=", "type2", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Two types conflict if both types could not apply to a value simultaneously. // Composite types are ignored as their individual field types will be compared // later recursively. However List and Non-Null types must match.
[ "Two", "types", "conflict", "if", "both", "types", "could", "not", "apply", "to", "a", "value", "simultaneously", ".", "Composite", "types", "are", "ignored", "as", "their", "individual", "field", "types", "will", "be", "compared", "later", "recursively", ".", "However", "List", "and", "Non", "-", "Null", "types", "must", "match", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L653-L682
train
graphql-go/graphql
rules_overlapping_fields_can_be_merged.go
subfieldConflicts
func subfieldConflicts(conflicts []conflict, responseName string, ast1 *ast.Field, ast2 *ast.Field) *conflict { if len(conflicts) > 0 { conflictReasons := []conflictReason{} conflictFieldsLeft := []ast.Node{ast1} conflictFieldsRight := []ast.Node{ast2} for _, c := range conflicts { conflictReasons = append(conflictReasons, c.Reason) conflictFieldsLeft = append(conflictFieldsLeft, c.FieldsLeft...) conflictFieldsRight = append(conflictFieldsRight, c.FieldsRight...) } return &conflict{ Reason: conflictReason{ Name: responseName, Message: conflictReasons, }, FieldsLeft: conflictFieldsLeft, FieldsRight: conflictFieldsRight, } } return nil }
go
func subfieldConflicts(conflicts []conflict, responseName string, ast1 *ast.Field, ast2 *ast.Field) *conflict { if len(conflicts) > 0 { conflictReasons := []conflictReason{} conflictFieldsLeft := []ast.Node{ast1} conflictFieldsRight := []ast.Node{ast2} for _, c := range conflicts { conflictReasons = append(conflictReasons, c.Reason) conflictFieldsLeft = append(conflictFieldsLeft, c.FieldsLeft...) conflictFieldsRight = append(conflictFieldsRight, c.FieldsRight...) } return &conflict{ Reason: conflictReason{ Name: responseName, Message: conflictReasons, }, FieldsLeft: conflictFieldsLeft, FieldsRight: conflictFieldsRight, } } return nil }
[ "func", "subfieldConflicts", "(", "conflicts", "[", "]", "conflict", ",", "responseName", "string", ",", "ast1", "*", "ast", ".", "Field", ",", "ast2", "*", "ast", ".", "Field", ")", "*", "conflict", "{", "if", "len", "(", "conflicts", ")", ">", "0", "{", "conflictReasons", ":=", "[", "]", "conflictReason", "{", "}", "\n", "conflictFieldsLeft", ":=", "[", "]", "ast", ".", "Node", "{", "ast1", "}", "\n", "conflictFieldsRight", ":=", "[", "]", "ast", ".", "Node", "{", "ast2", "}", "\n", "for", "_", ",", "c", ":=", "range", "conflicts", "{", "conflictReasons", "=", "append", "(", "conflictReasons", ",", "c", ".", "Reason", ")", "\n", "conflictFieldsLeft", "=", "append", "(", "conflictFieldsLeft", ",", "c", ".", "FieldsLeft", "...", ")", "\n", "conflictFieldsRight", "=", "append", "(", "conflictFieldsRight", ",", "c", ".", "FieldsRight", "...", ")", "\n", "}", "\n\n", "return", "&", "conflict", "{", "Reason", ":", "conflictReason", "{", "Name", ":", "responseName", ",", "Message", ":", "conflictReasons", ",", "}", ",", "FieldsLeft", ":", "conflictFieldsLeft", ",", "FieldsRight", ":", "conflictFieldsRight", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// subfieldConflicts Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict.
[ "subfieldConflicts", "Given", "a", "series", "of", "Conflicts", "which", "occurred", "between", "two", "sub", "-", "fields", "generate", "a", "single", "Conflict", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules_overlapping_fields_can_be_merged.go#L685-L706
train
graphql-go/graphql
type_info.go
DefaultTypeInfoFieldDef
func DefaultTypeInfoFieldDef(schema *Schema, parentType Type, fieldAST *ast.Field) *FieldDefinition { name := "" if fieldAST.Name != nil { name = fieldAST.Name.Value } if name == SchemaMetaFieldDef.Name && schema.QueryType() == parentType { return SchemaMetaFieldDef } if name == TypeMetaFieldDef.Name && schema.QueryType() == parentType { return TypeMetaFieldDef } if name == TypeNameMetaFieldDef.Name && parentType != nil { if t, ok := parentType.(*Object); ok && t != nil { return TypeNameMetaFieldDef } if t, ok := parentType.(*Interface); ok && t != nil { return TypeNameMetaFieldDef } if t, ok := parentType.(*Union); ok && t != nil { return TypeNameMetaFieldDef } } if parentType, ok := parentType.(*Object); ok && parentType != nil { field, _ := parentType.Fields()[name] return field } if parentType, ok := parentType.(*Interface); ok && parentType != nil { field, _ := parentType.Fields()[name] return field } return nil }
go
func DefaultTypeInfoFieldDef(schema *Schema, parentType Type, fieldAST *ast.Field) *FieldDefinition { name := "" if fieldAST.Name != nil { name = fieldAST.Name.Value } if name == SchemaMetaFieldDef.Name && schema.QueryType() == parentType { return SchemaMetaFieldDef } if name == TypeMetaFieldDef.Name && schema.QueryType() == parentType { return TypeMetaFieldDef } if name == TypeNameMetaFieldDef.Name && parentType != nil { if t, ok := parentType.(*Object); ok && t != nil { return TypeNameMetaFieldDef } if t, ok := parentType.(*Interface); ok && t != nil { return TypeNameMetaFieldDef } if t, ok := parentType.(*Union); ok && t != nil { return TypeNameMetaFieldDef } } if parentType, ok := parentType.(*Object); ok && parentType != nil { field, _ := parentType.Fields()[name] return field } if parentType, ok := parentType.(*Interface); ok && parentType != nil { field, _ := parentType.Fields()[name] return field } return nil }
[ "func", "DefaultTypeInfoFieldDef", "(", "schema", "*", "Schema", ",", "parentType", "Type", ",", "fieldAST", "*", "ast", ".", "Field", ")", "*", "FieldDefinition", "{", "name", ":=", "\"", "\"", "\n", "if", "fieldAST", ".", "Name", "!=", "nil", "{", "name", "=", "fieldAST", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "name", "==", "SchemaMetaFieldDef", ".", "Name", "&&", "schema", ".", "QueryType", "(", ")", "==", "parentType", "{", "return", "SchemaMetaFieldDef", "\n", "}", "\n", "if", "name", "==", "TypeMetaFieldDef", ".", "Name", "&&", "schema", ".", "QueryType", "(", ")", "==", "parentType", "{", "return", "TypeMetaFieldDef", "\n", "}", "\n", "if", "name", "==", "TypeNameMetaFieldDef", ".", "Name", "&&", "parentType", "!=", "nil", "{", "if", "t", ",", "ok", ":=", "parentType", ".", "(", "*", "Object", ")", ";", "ok", "&&", "t", "!=", "nil", "{", "return", "TypeNameMetaFieldDef", "\n", "}", "\n", "if", "t", ",", "ok", ":=", "parentType", ".", "(", "*", "Interface", ")", ";", "ok", "&&", "t", "!=", "nil", "{", "return", "TypeNameMetaFieldDef", "\n", "}", "\n", "if", "t", ",", "ok", ":=", "parentType", ".", "(", "*", "Union", ")", ";", "ok", "&&", "t", "!=", "nil", "{", "return", "TypeNameMetaFieldDef", "\n", "}", "\n", "}", "\n\n", "if", "parentType", ",", "ok", ":=", "parentType", ".", "(", "*", "Object", ")", ";", "ok", "&&", "parentType", "!=", "nil", "{", "field", ",", "_", ":=", "parentType", ".", "Fields", "(", ")", "[", "name", "]", "\n", "return", "field", "\n", "}", "\n", "if", "parentType", ",", "ok", ":=", "parentType", ".", "(", "*", "Interface", ")", ";", "ok", "&&", "parentType", "!=", "nil", "{", "field", ",", "_", ":=", "parentType", ".", "Fields", "(", ")", "[", "name", "]", "\n", "return", "field", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DefaultTypeInfoFieldDef Not exactly the same as the executor's definition of FieldDef, in this // statically evaluated environment we do not always have an Object type, // and need to handle Interface and Union types.
[ "DefaultTypeInfoFieldDef", "Not", "exactly", "the", "same", "as", "the", "executor", "s", "definition", "of", "FieldDef", "in", "this", "statically", "evaluated", "environment", "we", "do", "not", "always", "have", "an", "Object", "type", "and", "need", "to", "handle", "Interface", "and", "Union", "types", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/type_info.go#L236-L270
train
graphql-go/graphql
gqlerrors/located.go
NewLocatedError
func NewLocatedError(err interface{}, nodes []ast.Node) *Error { var origError error message := "An unknown error occurred." if err, ok := err.(error); ok { message = err.Error() origError = err } if err, ok := err.(string); ok { message = err origError = errors.New(err) } stack := message return NewError( message, nodes, stack, nil, []int{}, origError, ) }
go
func NewLocatedError(err interface{}, nodes []ast.Node) *Error { var origError error message := "An unknown error occurred." if err, ok := err.(error); ok { message = err.Error() origError = err } if err, ok := err.(string); ok { message = err origError = errors.New(err) } stack := message return NewError( message, nodes, stack, nil, []int{}, origError, ) }
[ "func", "NewLocatedError", "(", "err", "interface", "{", "}", ",", "nodes", "[", "]", "ast", ".", "Node", ")", "*", "Error", "{", "var", "origError", "error", "\n", "message", ":=", "\"", "\"", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "error", ")", ";", "ok", "{", "message", "=", "err", ".", "Error", "(", ")", "\n", "origError", "=", "err", "\n", "}", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "string", ")", ";", "ok", "{", "message", "=", "err", "\n", "origError", "=", "errors", ".", "New", "(", "err", ")", "\n", "}", "\n", "stack", ":=", "message", "\n", "return", "NewError", "(", "message", ",", "nodes", ",", "stack", ",", "nil", ",", "[", "]", "int", "{", "}", ",", "origError", ",", ")", "\n", "}" ]
// NewLocatedError creates a graphql.Error with location info // @deprecated 0.4.18 // Already exists in `graphql.NewLocatedError()`
[ "NewLocatedError", "creates", "a", "graphql", ".", "Error", "with", "location", "info" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/gqlerrors/located.go#L11-L31
train
graphql-go/graphql
examples/http/main.go
importJSONDataFromFile
func importJSONDataFromFile(fileName string, result interface{}) (isOK bool) { isOK = true content, err := ioutil.ReadFile(fileName) if err != nil { fmt.Print("Error:", err) isOK = false } err = json.Unmarshal(content, result) if err != nil { isOK = false fmt.Print("Error:", err) } return }
go
func importJSONDataFromFile(fileName string, result interface{}) (isOK bool) { isOK = true content, err := ioutil.ReadFile(fileName) if err != nil { fmt.Print("Error:", err) isOK = false } err = json.Unmarshal(content, result) if err != nil { isOK = false fmt.Print("Error:", err) } return }
[ "func", "importJSONDataFromFile", "(", "fileName", "string", ",", "result", "interface", "{", "}", ")", "(", "isOK", "bool", ")", "{", "isOK", "=", "true", "\n", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fileName", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "isOK", "=", "false", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "content", ",", "result", ")", "\n", "if", "err", "!=", "nil", "{", "isOK", "=", "false", "\n", "fmt", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
//Helper function to import json from file to map
[ "Helper", "function", "to", "import", "json", "from", "file", "to", "map" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/examples/http/main.go#L101-L114
train
graphql-go/graphql
language/parser/parser.go
parseName
func parseName(parser *Parser) (*ast.Name, error) { token, err := expect(parser, lexer.NAME) if err != nil { return nil, err } return ast.NewName(&ast.Name{ Value: token.Value, Loc: loc(parser, token.Start), }), nil }
go
func parseName(parser *Parser) (*ast.Name, error) { token, err := expect(parser, lexer.NAME) if err != nil { return nil, err } return ast.NewName(&ast.Name{ Value: token.Value, Loc: loc(parser, token.Start), }), nil }
[ "func", "parseName", "(", "parser", "*", "Parser", ")", "(", "*", "ast", ".", "Name", ",", "error", ")", "{", "token", ",", "err", ":=", "expect", "(", "parser", ",", "lexer", ".", "NAME", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ast", ".", "NewName", "(", "&", "ast", ".", "Name", "{", "Value", ":", "token", ".", "Value", ",", "Loc", ":", "loc", "(", "parser", ",", "token", ".", "Start", ")", ",", "}", ")", ",", "nil", "\n", "}" ]
// Converts a name lex token into a name parse node.
[ "Converts", "a", "name", "lex", "token", "into", "a", "name", "parse", "node", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L105-L114
train
graphql-go/graphql
language/parser/parser.go
advance
func advance(parser *Parser) error { parser.PrevEnd = parser.Token.End token, err := parser.LexToken(parser.PrevEnd) if err != nil { return err } parser.Token = token return nil }
go
func advance(parser *Parser) error { parser.PrevEnd = parser.Token.End token, err := parser.LexToken(parser.PrevEnd) if err != nil { return err } parser.Token = token return nil }
[ "func", "advance", "(", "parser", "*", "Parser", ")", "error", "{", "parser", ".", "PrevEnd", "=", "parser", ".", "Token", ".", "End", "\n", "token", ",", "err", ":=", "parser", ".", "LexToken", "(", "parser", ".", "PrevEnd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parser", ".", "Token", "=", "token", "\n", "return", "nil", "\n", "}" ]
// Moves the internal parser object to the next lexed token.
[ "Moves", "the", "internal", "parser", "object", "to", "the", "next", "lexed", "token", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1497-L1505
train
graphql-go/graphql
language/parser/parser.go
lookahead
func lookahead(parser *Parser) (lexer.Token, error) { return parser.LexToken(parser.Token.End) }
go
func lookahead(parser *Parser) (lexer.Token, error) { return parser.LexToken(parser.Token.End) }
[ "func", "lookahead", "(", "parser", "*", "Parser", ")", "(", "lexer", ".", "Token", ",", "error", ")", "{", "return", "parser", ".", "LexToken", "(", "parser", ".", "Token", ".", "End", ")", "\n", "}" ]
// lookahead retrieves the next token
[ "lookahead", "retrieves", "the", "next", "token" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1508-L1510
train
graphql-go/graphql
language/parser/parser.go
peek
func peek(parser *Parser, Kind lexer.TokenKind) bool { return parser.Token.Kind == Kind }
go
func peek(parser *Parser, Kind lexer.TokenKind) bool { return parser.Token.Kind == Kind }
[ "func", "peek", "(", "parser", "*", "Parser", ",", "Kind", "lexer", ".", "TokenKind", ")", "bool", "{", "return", "parser", ".", "Token", ".", "Kind", "==", "Kind", "\n", "}" ]
// Determines if the next token is of a given kind
[ "Determines", "if", "the", "next", "token", "is", "of", "a", "given", "kind" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1513-L1515
train
graphql-go/graphql
language/parser/parser.go
peekDescription
func peekDescription(parser *Parser) bool { return peek(parser, lexer.STRING) || peek(parser, lexer.BLOCK_STRING) }
go
func peekDescription(parser *Parser) bool { return peek(parser, lexer.STRING) || peek(parser, lexer.BLOCK_STRING) }
[ "func", "peekDescription", "(", "parser", "*", "Parser", ")", "bool", "{", "return", "peek", "(", "parser", ",", "lexer", ".", "STRING", ")", "||", "peek", "(", "parser", ",", "lexer", ".", "BLOCK_STRING", ")", "\n", "}" ]
// peekDescription determines if the next token is a string value
[ "peekDescription", "determines", "if", "the", "next", "token", "is", "a", "string", "value" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1518-L1520
train
graphql-go/graphql
language/parser/parser.go
skip
func skip(parser *Parser, Kind lexer.TokenKind) (bool, error) { if parser.Token.Kind == Kind { return true, advance(parser) } return false, nil }
go
func skip(parser *Parser, Kind lexer.TokenKind) (bool, error) { if parser.Token.Kind == Kind { return true, advance(parser) } return false, nil }
[ "func", "skip", "(", "parser", "*", "Parser", ",", "Kind", "lexer", ".", "TokenKind", ")", "(", "bool", ",", "error", ")", "{", "if", "parser", ".", "Token", ".", "Kind", "==", "Kind", "{", "return", "true", ",", "advance", "(", "parser", ")", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// If the next token is of the given kind, return true after advancing // the parser. Otherwise, do not change the parser state and return false.
[ "If", "the", "next", "token", "is", "of", "the", "given", "kind", "return", "true", "after", "advancing", "the", "parser", ".", "Otherwise", "do", "not", "change", "the", "parser", "state", "and", "return", "false", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1524-L1529
train
graphql-go/graphql
language/parser/parser.go
expect
func expect(parser *Parser, kind lexer.TokenKind) (lexer.Token, error) { token := parser.Token if token.Kind == kind { return token, advance(parser) } descp := fmt.Sprintf("Expected %s, found %s", kind, lexer.GetTokenDesc(token)) return token, gqlerrors.NewSyntaxError(parser.Source, token.Start, descp) }
go
func expect(parser *Parser, kind lexer.TokenKind) (lexer.Token, error) { token := parser.Token if token.Kind == kind { return token, advance(parser) } descp := fmt.Sprintf("Expected %s, found %s", kind, lexer.GetTokenDesc(token)) return token, gqlerrors.NewSyntaxError(parser.Source, token.Start, descp) }
[ "func", "expect", "(", "parser", "*", "Parser", ",", "kind", "lexer", ".", "TokenKind", ")", "(", "lexer", ".", "Token", ",", "error", ")", "{", "token", ":=", "parser", ".", "Token", "\n", "if", "token", ".", "Kind", "==", "kind", "{", "return", "token", ",", "advance", "(", "parser", ")", "\n", "}", "\n", "descp", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kind", ",", "lexer", ".", "GetTokenDesc", "(", "token", ")", ")", "\n", "return", "token", ",", "gqlerrors", ".", "NewSyntaxError", "(", "parser", ".", "Source", ",", "token", ".", "Start", ",", "descp", ")", "\n", "}" ]
// If the next token is of the given kind, return that token after advancing // the parser. Otherwise, do not change the parser state and return error.
[ "If", "the", "next", "token", "is", "of", "the", "given", "kind", "return", "that", "token", "after", "advancing", "the", "parser", ".", "Otherwise", "do", "not", "change", "the", "parser", "state", "and", "return", "error", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1533-L1540
train
graphql-go/graphql
language/parser/parser.go
expectKeyWord
func expectKeyWord(parser *Parser, value string) (lexer.Token, error) { token := parser.Token if token.Kind == lexer.NAME && token.Value == value { return token, advance(parser) } descp := fmt.Sprintf("Expected \"%s\", found %s", value, lexer.GetTokenDesc(token)) return token, gqlerrors.NewSyntaxError(parser.Source, token.Start, descp) }
go
func expectKeyWord(parser *Parser, value string) (lexer.Token, error) { token := parser.Token if token.Kind == lexer.NAME && token.Value == value { return token, advance(parser) } descp := fmt.Sprintf("Expected \"%s\", found %s", value, lexer.GetTokenDesc(token)) return token, gqlerrors.NewSyntaxError(parser.Source, token.Start, descp) }
[ "func", "expectKeyWord", "(", "parser", "*", "Parser", ",", "value", "string", ")", "(", "lexer", ".", "Token", ",", "error", ")", "{", "token", ":=", "parser", ".", "Token", "\n", "if", "token", ".", "Kind", "==", "lexer", ".", "NAME", "&&", "token", ".", "Value", "==", "value", "{", "return", "token", ",", "advance", "(", "parser", ")", "\n", "}", "\n", "descp", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "value", ",", "lexer", ".", "GetTokenDesc", "(", "token", ")", ")", "\n", "return", "token", ",", "gqlerrors", ".", "NewSyntaxError", "(", "parser", ".", "Source", ",", "token", ".", "Start", ",", "descp", ")", "\n", "}" ]
// If the next token is a keyword with the given value, return that token after // advancing the parser. Otherwise, do not change the parser state and return false.
[ "If", "the", "next", "token", "is", "a", "keyword", "with", "the", "given", "value", "return", "that", "token", "after", "advancing", "the", "parser", ".", "Otherwise", "do", "not", "change", "the", "parser", "state", "and", "return", "false", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1544-L1551
train
graphql-go/graphql
language/parser/parser.go
unexpected
func unexpected(parser *Parser, atToken lexer.Token) error { var token = atToken if (atToken == lexer.Token{}) { token = parser.Token } description := fmt.Sprintf("Unexpected %v", lexer.GetTokenDesc(token)) return gqlerrors.NewSyntaxError(parser.Source, token.Start, description) }
go
func unexpected(parser *Parser, atToken lexer.Token) error { var token = atToken if (atToken == lexer.Token{}) { token = parser.Token } description := fmt.Sprintf("Unexpected %v", lexer.GetTokenDesc(token)) return gqlerrors.NewSyntaxError(parser.Source, token.Start, description) }
[ "func", "unexpected", "(", "parser", "*", "Parser", ",", "atToken", "lexer", ".", "Token", ")", "error", "{", "var", "token", "=", "atToken", "\n", "if", "(", "atToken", "==", "lexer", ".", "Token", "{", "}", ")", "{", "token", "=", "parser", ".", "Token", "\n", "}", "\n", "description", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lexer", ".", "GetTokenDesc", "(", "token", ")", ")", "\n", "return", "gqlerrors", ".", "NewSyntaxError", "(", "parser", ".", "Source", ",", "token", ".", "Start", ",", "description", ")", "\n", "}" ]
// Helper function for creating an error when an unexpected lexed token // is encountered.
[ "Helper", "function", "for", "creating", "an", "error", "when", "an", "unexpected", "lexed", "token", "is", "encountered", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/parser/parser.go#L1555-L1562
train
graphql-go/graphql
rules.go
ArgumentsOfCorrectTypeRule
func ArgumentsOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Argument: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if argAST, ok := p.Node.(*ast.Argument); ok { if argDef := context.Argument(); argDef != nil { if isValid, messages := isValidLiteralValue(argDef.Type, argAST.Value); !isValid { var messagesStr, argNameValue string if argAST.Name != nil { argNameValue = argAST.Name.Value } if len(messages) > 0 { messagesStr = "\n" + strings.Join(messages, "\n") } reportError( context, fmt.Sprintf(`Argument "%v" has invalid value %v.%v`, argNameValue, printer.Print(argAST.Value), messagesStr), []ast.Node{argAST.Value}, ) } } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func ArgumentsOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Argument: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if argAST, ok := p.Node.(*ast.Argument); ok { if argDef := context.Argument(); argDef != nil { if isValid, messages := isValidLiteralValue(argDef.Type, argAST.Value); !isValid { var messagesStr, argNameValue string if argAST.Name != nil { argNameValue = argAST.Name.Value } if len(messages) > 0 { messagesStr = "\n" + strings.Join(messages, "\n") } reportError( context, fmt.Sprintf(`Argument "%v" has invalid value %v.%v`, argNameValue, printer.Print(argAST.Value), messagesStr), []ast.Node{argAST.Value}, ) } } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "ArgumentsOfCorrectTypeRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "Argument", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "argAST", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "Argument", ")", ";", "ok", "{", "if", "argDef", ":=", "context", ".", "Argument", "(", ")", ";", "argDef", "!=", "nil", "{", "if", "isValid", ",", "messages", ":=", "isValidLiteralValue", "(", "argDef", ".", "Type", ",", "argAST", ".", "Value", ")", ";", "!", "isValid", "{", "var", "messagesStr", ",", "argNameValue", "string", "\n", "if", "argAST", ".", "Name", "!=", "nil", "{", "argNameValue", "=", "argAST", ".", "Name", ".", "Value", "\n", "}", "\n\n", "if", "len", "(", "messages", ")", ">", "0", "{", "messagesStr", "=", "\"", "\\n", "\"", "+", "strings", ".", "Join", "(", "messages", ",", "\"", "\\n", "\"", ")", "\n", "}", "\n", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Argument \"%v\" has invalid value %v.%v`", ",", "argNameValue", ",", "printer", ".", "Print", "(", "argAST", ".", "Value", ")", ",", "messagesStr", ")", ",", "[", "]", "ast", ".", "Node", "{", "argAST", ".", "Value", "}", ",", ")", "\n", "}", "\n\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// ArgumentsOfCorrectTypeRule Argument values of correct type // // A GraphQL document is only valid if all field argument literal values are // of the type expected by their position.
[ "ArgumentsOfCorrectTypeRule", "Argument", "values", "of", "correct", "type", "A", "GraphQL", "document", "is", "only", "valid", "if", "all", "field", "argument", "literal", "values", "are", "of", "the", "type", "expected", "by", "their", "position", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L70-L104
train
graphql-go/graphql
rules.go
DefaultValuesOfCorrectTypeRule
func DefaultValuesOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if varDefAST, ok := p.Node.(*ast.VariableDefinition); ok { var ( name string defaultValue = varDefAST.DefaultValue messagesStr string ) if varDefAST.Variable != nil && varDefAST.Variable.Name != nil { name = varDefAST.Variable.Name.Value } ttype := context.InputType() // when input variable value must be nonNull, and set default value is unnecessary if ttype, ok := ttype.(*NonNull); ok && defaultValue != nil { reportError( context, fmt.Sprintf(`Variable "$%v" of type "%v" is required and will not use the default value. Perhaps you meant to use type "%v".`, name, ttype, ttype.OfType), []ast.Node{defaultValue}, ) } if isValid, messages := isValidLiteralValue(ttype, defaultValue); !isValid && defaultValue != nil { if len(messages) > 0 { messagesStr = "\n" + strings.Join(messages, "\n") } reportError( context, fmt.Sprintf(`Variable "$%v" has invalid default value: %v.%v`, name, printer.Print(defaultValue), messagesStr), []ast.Node{defaultValue}, ) } } return visitor.ActionSkip, nil }, }, kinds.SelectionSet: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func DefaultValuesOfCorrectTypeRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if varDefAST, ok := p.Node.(*ast.VariableDefinition); ok { var ( name string defaultValue = varDefAST.DefaultValue messagesStr string ) if varDefAST.Variable != nil && varDefAST.Variable.Name != nil { name = varDefAST.Variable.Name.Value } ttype := context.InputType() // when input variable value must be nonNull, and set default value is unnecessary if ttype, ok := ttype.(*NonNull); ok && defaultValue != nil { reportError( context, fmt.Sprintf(`Variable "$%v" of type "%v" is required and will not use the default value. Perhaps you meant to use type "%v".`, name, ttype, ttype.OfType), []ast.Node{defaultValue}, ) } if isValid, messages := isValidLiteralValue(ttype, defaultValue); !isValid && defaultValue != nil { if len(messages) > 0 { messagesStr = "\n" + strings.Join(messages, "\n") } reportError( context, fmt.Sprintf(`Variable "$%v" has invalid default value: %v.%v`, name, printer.Print(defaultValue), messagesStr), []ast.Node{defaultValue}, ) } } return visitor.ActionSkip, nil }, }, kinds.SelectionSet: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "DefaultValuesOfCorrectTypeRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "VariableDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "varDefAST", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "VariableDefinition", ")", ";", "ok", "{", "var", "(", "name", "string", "\n", "defaultValue", "=", "varDefAST", ".", "DefaultValue", "\n", "messagesStr", "string", "\n", ")", "\n", "if", "varDefAST", ".", "Variable", "!=", "nil", "&&", "varDefAST", ".", "Variable", ".", "Name", "!=", "nil", "{", "name", "=", "varDefAST", ".", "Variable", ".", "Name", ".", "Value", "\n", "}", "\n", "ttype", ":=", "context", ".", "InputType", "(", ")", "\n\n", "// when input variable value must be nonNull, and set default value is unnecessary", "if", "ttype", ",", "ok", ":=", "ttype", ".", "(", "*", "NonNull", ")", ";", "ok", "&&", "defaultValue", "!=", "nil", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Variable \"$%v\" of type \"%v\" is required and will not use the default value. Perhaps you meant to use type \"%v\".`", ",", "name", ",", "ttype", ",", "ttype", ".", "OfType", ")", ",", "[", "]", "ast", ".", "Node", "{", "defaultValue", "}", ",", ")", "\n", "}", "\n", "if", "isValid", ",", "messages", ":=", "isValidLiteralValue", "(", "ttype", ",", "defaultValue", ")", ";", "!", "isValid", "&&", "defaultValue", "!=", "nil", "{", "if", "len", "(", "messages", ")", ">", "0", "{", "messagesStr", "=", "\"", "\\n", "\"", "+", "strings", ".", "Join", "(", "messages", ",", "\"", "\\n", "\"", ")", "\n", "}", "\n", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Variable \"$%v\" has invalid default value: %v.%v`", ",", "name", ",", "printer", ".", "Print", "(", "defaultValue", ")", ",", "messagesStr", ")", ",", "[", "]", "ast", ".", "Node", "{", "defaultValue", "}", ",", ")", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "SelectionSet", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "FragmentDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// DefaultValuesOfCorrectTypeRule Variable default values of correct type // // A GraphQL document is only valid if all variable default values are of the // type expected by their definition.
[ "DefaultValuesOfCorrectTypeRule", "Variable", "default", "values", "of", "correct", "type", "A", "GraphQL", "document", "is", "only", "valid", "if", "all", "variable", "default", "values", "are", "of", "the", "type", "expected", "by", "their", "definition", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L110-L165
train
graphql-go/graphql
rules.go
getSuggestedTypeNames
func getSuggestedTypeNames(schema *Schema, ttype Output, fieldName string) []string { var ( suggestedObjectTypes = []string{} suggestedInterfaces = []*suggestedInterface{} // stores a map of interface name => index in suggestedInterfaces suggestedInterfaceMap = map[string]int{} // stores a maps of object name => true to remove duplicates from results suggestedObjectMap = map[string]bool{} ) possibleTypes := schema.PossibleTypes(ttype) for _, possibleType := range possibleTypes { if field, ok := possibleType.Fields()[fieldName]; !ok || field == nil { continue } // This object type defines this field. suggestedObjectTypes = append(suggestedObjectTypes, possibleType.Name()) suggestedObjectMap[possibleType.Name()] = true for _, possibleInterface := range possibleType.Interfaces() { if field, ok := possibleInterface.Fields()[fieldName]; !ok || field == nil { continue } // This interface type defines this field. // - find the index of the suggestedInterface and retrieving the interface // - increase count index, ok := suggestedInterfaceMap[possibleInterface.Name()] if !ok { suggestedInterfaces = append(suggestedInterfaces, &suggestedInterface{ name: possibleInterface.Name(), count: 0, }) index = len(suggestedInterfaces) - 1 suggestedInterfaceMap[possibleInterface.Name()] = index } if index < len(suggestedInterfaces) { s := suggestedInterfaces[index] if s.name == possibleInterface.Name() { s.count++ } } } } // sort results (by count usage for interfaces, alphabetical order for objects) sort.Sort(suggestedInterfaceSortedSlice(suggestedInterfaces)) sort.Sort(sort.StringSlice(suggestedObjectTypes)) // return concatenated slices of both interface and object type names // and removing duplicates // ordered by: interface (sorted) and object (sorted) results := []string{} for _, s := range suggestedInterfaces { if _, ok := suggestedObjectMap[s.name]; !ok { results = append(results, s.name) } } results = append(results, suggestedObjectTypes...) return results }
go
func getSuggestedTypeNames(schema *Schema, ttype Output, fieldName string) []string { var ( suggestedObjectTypes = []string{} suggestedInterfaces = []*suggestedInterface{} // stores a map of interface name => index in suggestedInterfaces suggestedInterfaceMap = map[string]int{} // stores a maps of object name => true to remove duplicates from results suggestedObjectMap = map[string]bool{} ) possibleTypes := schema.PossibleTypes(ttype) for _, possibleType := range possibleTypes { if field, ok := possibleType.Fields()[fieldName]; !ok || field == nil { continue } // This object type defines this field. suggestedObjectTypes = append(suggestedObjectTypes, possibleType.Name()) suggestedObjectMap[possibleType.Name()] = true for _, possibleInterface := range possibleType.Interfaces() { if field, ok := possibleInterface.Fields()[fieldName]; !ok || field == nil { continue } // This interface type defines this field. // - find the index of the suggestedInterface and retrieving the interface // - increase count index, ok := suggestedInterfaceMap[possibleInterface.Name()] if !ok { suggestedInterfaces = append(suggestedInterfaces, &suggestedInterface{ name: possibleInterface.Name(), count: 0, }) index = len(suggestedInterfaces) - 1 suggestedInterfaceMap[possibleInterface.Name()] = index } if index < len(suggestedInterfaces) { s := suggestedInterfaces[index] if s.name == possibleInterface.Name() { s.count++ } } } } // sort results (by count usage for interfaces, alphabetical order for objects) sort.Sort(suggestedInterfaceSortedSlice(suggestedInterfaces)) sort.Sort(sort.StringSlice(suggestedObjectTypes)) // return concatenated slices of both interface and object type names // and removing duplicates // ordered by: interface (sorted) and object (sorted) results := []string{} for _, s := range suggestedInterfaces { if _, ok := suggestedObjectMap[s.name]; !ok { results = append(results, s.name) } } results = append(results, suggestedObjectTypes...) return results }
[ "func", "getSuggestedTypeNames", "(", "schema", "*", "Schema", ",", "ttype", "Output", ",", "fieldName", "string", ")", "[", "]", "string", "{", "var", "(", "suggestedObjectTypes", "=", "[", "]", "string", "{", "}", "\n", "suggestedInterfaces", "=", "[", "]", "*", "suggestedInterface", "{", "}", "\n", "// stores a map of interface name => index in suggestedInterfaces", "suggestedInterfaceMap", "=", "map", "[", "string", "]", "int", "{", "}", "\n", "// stores a maps of object name => true to remove duplicates from results", "suggestedObjectMap", "=", "map", "[", "string", "]", "bool", "{", "}", "\n", ")", "\n", "possibleTypes", ":=", "schema", ".", "PossibleTypes", "(", "ttype", ")", "\n\n", "for", "_", ",", "possibleType", ":=", "range", "possibleTypes", "{", "if", "field", ",", "ok", ":=", "possibleType", ".", "Fields", "(", ")", "[", "fieldName", "]", ";", "!", "ok", "||", "field", "==", "nil", "{", "continue", "\n", "}", "\n", "// This object type defines this field.", "suggestedObjectTypes", "=", "append", "(", "suggestedObjectTypes", ",", "possibleType", ".", "Name", "(", ")", ")", "\n", "suggestedObjectMap", "[", "possibleType", ".", "Name", "(", ")", "]", "=", "true", "\n\n", "for", "_", ",", "possibleInterface", ":=", "range", "possibleType", ".", "Interfaces", "(", ")", "{", "if", "field", ",", "ok", ":=", "possibleInterface", ".", "Fields", "(", ")", "[", "fieldName", "]", ";", "!", "ok", "||", "field", "==", "nil", "{", "continue", "\n", "}", "\n\n", "// This interface type defines this field.", "// - find the index of the suggestedInterface and retrieving the interface", "// - increase count", "index", ",", "ok", ":=", "suggestedInterfaceMap", "[", "possibleInterface", ".", "Name", "(", ")", "]", "\n", "if", "!", "ok", "{", "suggestedInterfaces", "=", "append", "(", "suggestedInterfaces", ",", "&", "suggestedInterface", "{", "name", ":", "possibleInterface", ".", "Name", "(", ")", ",", "count", ":", "0", ",", "}", ")", "\n", "index", "=", "len", "(", "suggestedInterfaces", ")", "-", "1", "\n", "suggestedInterfaceMap", "[", "possibleInterface", ".", "Name", "(", ")", "]", "=", "index", "\n", "}", "\n", "if", "index", "<", "len", "(", "suggestedInterfaces", ")", "{", "s", ":=", "suggestedInterfaces", "[", "index", "]", "\n", "if", "s", ".", "name", "==", "possibleInterface", ".", "Name", "(", ")", "{", "s", ".", "count", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// sort results (by count usage for interfaces, alphabetical order for objects)", "sort", ".", "Sort", "(", "suggestedInterfaceSortedSlice", "(", "suggestedInterfaces", ")", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "StringSlice", "(", "suggestedObjectTypes", ")", ")", "\n\n", "// return concatenated slices of both interface and object type names", "// and removing duplicates", "// ordered by: interface (sorted) and object (sorted)", "results", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "s", ":=", "range", "suggestedInterfaces", "{", "if", "_", ",", "ok", ":=", "suggestedObjectMap", "[", "s", ".", "name", "]", ";", "!", "ok", "{", "results", "=", "append", "(", "results", ",", "s", ".", "name", ")", "\n\n", "}", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "suggestedObjectTypes", "...", ")", "\n", "return", "results", "\n", "}" ]
// getSuggestedTypeNames Go through all of the implementations of type, as well as the interfaces // that they implement. If any of those types include the provided field, // suggest them, sorted by how often the type is referenced, starting // with Interfaces.
[ "getSuggestedTypeNames", "Go", "through", "all", "of", "the", "implementations", "of", "type", "as", "well", "as", "the", "interfaces", "that", "they", "implement", ".", "If", "any", "of", "those", "types", "include", "the", "provided", "field", "suggest", "them", "sorted", "by", "how", "often", "the", "type", "is", "referenced", "starting", "with", "Interfaces", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L260-L322
train
graphql-go/graphql
rules.go
getSuggestedFieldNames
func getSuggestedFieldNames(schema *Schema, ttype Output, fieldName string) []string { fields := FieldDefinitionMap{} switch ttype := ttype.(type) { case *Object: fields = ttype.Fields() case *Interface: fields = ttype.Fields() default: return []string{} } possibleFieldNames := []string{} for possibleFieldName := range fields { possibleFieldNames = append(possibleFieldNames, possibleFieldName) } return suggestionList(fieldName, possibleFieldNames) }
go
func getSuggestedFieldNames(schema *Schema, ttype Output, fieldName string) []string { fields := FieldDefinitionMap{} switch ttype := ttype.(type) { case *Object: fields = ttype.Fields() case *Interface: fields = ttype.Fields() default: return []string{} } possibleFieldNames := []string{} for possibleFieldName := range fields { possibleFieldNames = append(possibleFieldNames, possibleFieldName) } return suggestionList(fieldName, possibleFieldNames) }
[ "func", "getSuggestedFieldNames", "(", "schema", "*", "Schema", ",", "ttype", "Output", ",", "fieldName", "string", ")", "[", "]", "string", "{", "fields", ":=", "FieldDefinitionMap", "{", "}", "\n", "switch", "ttype", ":=", "ttype", ".", "(", "type", ")", "{", "case", "*", "Object", ":", "fields", "=", "ttype", ".", "Fields", "(", ")", "\n", "case", "*", "Interface", ":", "fields", "=", "ttype", ".", "Fields", "(", ")", "\n", "default", ":", "return", "[", "]", "string", "{", "}", "\n", "}", "\n\n", "possibleFieldNames", ":=", "[", "]", "string", "{", "}", "\n", "for", "possibleFieldName", ":=", "range", "fields", "{", "possibleFieldNames", "=", "append", "(", "possibleFieldNames", ",", "possibleFieldName", ")", "\n", "}", "\n", "return", "suggestionList", "(", "fieldName", ",", "possibleFieldNames", ")", "\n", "}" ]
// getSuggestedFieldNames For the field name provided, determine if there are any similar field names // that may be the result of a typo.
[ "getSuggestedFieldNames", "For", "the", "field", "name", "provided", "determine", "if", "there", "are", "any", "similar", "field", "names", "that", "may", "be", "the", "result", "of", "a", "typo", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L326-L343
train
graphql-go/graphql
rules.go
KnownArgumentNamesRule
func KnownArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Argument: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { var action = visitor.ActionNoChange if node, ok := p.Node.(*ast.Argument); ok { var argumentOf ast.Node if len(p.Ancestors) > 0 { argumentOf = p.Ancestors[len(p.Ancestors)-1] } if argumentOf == nil { return action, nil } // verify node, if the node's name exists in Arguments{Field, Directive} var ( fieldArgDef *Argument fieldDef = context.FieldDef() directive = context.Directive() argNames []string parentTypeName string ) switch argumentOf.GetKind() { case kinds.Field: // get field definition if fieldDef == nil { return action, nil } for _, arg := range fieldDef.Args { if arg.Name() == node.Name.Value { fieldArgDef = arg break } argNames = append(argNames, arg.Name()) } if fieldArgDef == nil { parentType := context.ParentType() if parentType != nil { parentTypeName = parentType.Name() } reportError( context, unknownArgMessage( node.Name.Value, fieldDef.Name, parentTypeName, suggestionList(node.Name.Value, argNames), ), []ast.Node{node}, ) } case kinds.Directive: if directive = context.Directive(); directive == nil { return action, nil } for _, arg := range directive.Args { if arg.Name() == node.Name.Value { fieldArgDef = arg break } argNames = append(argNames, arg.Name()) } if fieldArgDef == nil { reportError( context, unknownDirectiveArgMessage( node.Name.Value, directive.Name, suggestionList(node.Name.Value, argNames), ), []ast.Node{node}, ) } } } return action, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func KnownArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Argument: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { var action = visitor.ActionNoChange if node, ok := p.Node.(*ast.Argument); ok { var argumentOf ast.Node if len(p.Ancestors) > 0 { argumentOf = p.Ancestors[len(p.Ancestors)-1] } if argumentOf == nil { return action, nil } // verify node, if the node's name exists in Arguments{Field, Directive} var ( fieldArgDef *Argument fieldDef = context.FieldDef() directive = context.Directive() argNames []string parentTypeName string ) switch argumentOf.GetKind() { case kinds.Field: // get field definition if fieldDef == nil { return action, nil } for _, arg := range fieldDef.Args { if arg.Name() == node.Name.Value { fieldArgDef = arg break } argNames = append(argNames, arg.Name()) } if fieldArgDef == nil { parentType := context.ParentType() if parentType != nil { parentTypeName = parentType.Name() } reportError( context, unknownArgMessage( node.Name.Value, fieldDef.Name, parentTypeName, suggestionList(node.Name.Value, argNames), ), []ast.Node{node}, ) } case kinds.Directive: if directive = context.Directive(); directive == nil { return action, nil } for _, arg := range directive.Args { if arg.Name() == node.Name.Value { fieldArgDef = arg break } argNames = append(argNames, arg.Name()) } if fieldArgDef == nil { reportError( context, unknownDirectiveArgMessage( node.Name.Value, directive.Name, suggestionList(node.Name.Value, argNames), ), []ast.Node{node}, ) } } } return action, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "KnownArgumentNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "Argument", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "var", "action", "=", "visitor", ".", "ActionNoChange", "\n", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "Argument", ")", ";", "ok", "{", "var", "argumentOf", "ast", ".", "Node", "\n", "if", "len", "(", "p", ".", "Ancestors", ")", ">", "0", "{", "argumentOf", "=", "p", ".", "Ancestors", "[", "len", "(", "p", ".", "Ancestors", ")", "-", "1", "]", "\n", "}", "\n", "if", "argumentOf", "==", "nil", "{", "return", "action", ",", "nil", "\n", "}", "\n", "// verify node, if the node's name exists in Arguments{Field, Directive}", "var", "(", "fieldArgDef", "*", "Argument", "\n", "fieldDef", "=", "context", ".", "FieldDef", "(", ")", "\n", "directive", "=", "context", ".", "Directive", "(", ")", "\n", "argNames", "[", "]", "string", "\n", "parentTypeName", "string", "\n", ")", "\n", "switch", "argumentOf", ".", "GetKind", "(", ")", "{", "case", "kinds", ".", "Field", ":", "// get field definition", "if", "fieldDef", "==", "nil", "{", "return", "action", ",", "nil", "\n", "}", "\n", "for", "_", ",", "arg", ":=", "range", "fieldDef", ".", "Args", "{", "if", "arg", ".", "Name", "(", ")", "==", "node", ".", "Name", ".", "Value", "{", "fieldArgDef", "=", "arg", "\n", "break", "\n", "}", "\n", "argNames", "=", "append", "(", "argNames", ",", "arg", ".", "Name", "(", ")", ")", "\n", "}", "\n", "if", "fieldArgDef", "==", "nil", "{", "parentType", ":=", "context", ".", "ParentType", "(", ")", "\n", "if", "parentType", "!=", "nil", "{", "parentTypeName", "=", "parentType", ".", "Name", "(", ")", "\n", "}", "\n", "reportError", "(", "context", ",", "unknownArgMessage", "(", "node", ".", "Name", ".", "Value", ",", "fieldDef", ".", "Name", ",", "parentTypeName", ",", "suggestionList", "(", "node", ".", "Name", ".", "Value", ",", "argNames", ")", ",", ")", ",", "[", "]", "ast", ".", "Node", "{", "node", "}", ",", ")", "\n", "}", "\n", "case", "kinds", ".", "Directive", ":", "if", "directive", "=", "context", ".", "Directive", "(", ")", ";", "directive", "==", "nil", "{", "return", "action", ",", "nil", "\n", "}", "\n", "for", "_", ",", "arg", ":=", "range", "directive", ".", "Args", "{", "if", "arg", ".", "Name", "(", ")", "==", "node", ".", "Name", ".", "Value", "{", "fieldArgDef", "=", "arg", "\n", "break", "\n", "}", "\n", "argNames", "=", "append", "(", "argNames", ",", "arg", ".", "Name", "(", ")", ")", "\n", "}", "\n", "if", "fieldArgDef", "==", "nil", "{", "reportError", "(", "context", ",", "unknownDirectiveArgMessage", "(", "node", ".", "Name", ".", "Value", ",", "directive", ".", "Name", ",", "suggestionList", "(", "node", ".", "Name", ".", "Value", ",", "argNames", ")", ",", ")", ",", "[", "]", "ast", ".", "Node", "{", "node", "}", ",", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "action", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// KnownArgumentNamesRule Known argument names // // A GraphQL field is only valid if all supplied arguments are defined by // that field.
[ "KnownArgumentNamesRule", "Known", "argument", "names", "A", "GraphQL", "field", "is", "only", "valid", "if", "all", "supplied", "arguments", "are", "defined", "by", "that", "field", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L438-L520
train
graphql-go/graphql
rules.go
KnownDirectivesRule
func KnownDirectivesRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Directive: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { var action = visitor.ActionNoChange var result interface{} if node, ok := p.Node.(*ast.Directive); ok { nodeName := "" if node.Name != nil { nodeName = node.Name.Value } var directiveDef *Directive for _, def := range context.Schema().Directives() { if def.Name == nodeName { directiveDef = def } } if directiveDef == nil { return reportError( context, fmt.Sprintf(`Unknown directive "%v".`, nodeName), []ast.Node{node}, ) } candidateLocation := getDirectiveLocationForASTPath(p.Ancestors) directiveHasLocation := false for _, loc := range directiveDef.Locations { if loc == candidateLocation { directiveHasLocation = true break } } if candidateLocation == "" { reportError( context, MisplaceDirectiveMessage(nodeName, node.GetKind()), []ast.Node{node}, ) } else if !directiveHasLocation { reportError( context, MisplaceDirectiveMessage(nodeName, candidateLocation), []ast.Node{node}, ) } } return action, result }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func KnownDirectivesRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Directive: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { var action = visitor.ActionNoChange var result interface{} if node, ok := p.Node.(*ast.Directive); ok { nodeName := "" if node.Name != nil { nodeName = node.Name.Value } var directiveDef *Directive for _, def := range context.Schema().Directives() { if def.Name == nodeName { directiveDef = def } } if directiveDef == nil { return reportError( context, fmt.Sprintf(`Unknown directive "%v".`, nodeName), []ast.Node{node}, ) } candidateLocation := getDirectiveLocationForASTPath(p.Ancestors) directiveHasLocation := false for _, loc := range directiveDef.Locations { if loc == candidateLocation { directiveHasLocation = true break } } if candidateLocation == "" { reportError( context, MisplaceDirectiveMessage(nodeName, node.GetKind()), []ast.Node{node}, ) } else if !directiveHasLocation { reportError( context, MisplaceDirectiveMessage(nodeName, candidateLocation), []ast.Node{node}, ) } } return action, result }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "KnownDirectivesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "Directive", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "var", "action", "=", "visitor", ".", "ActionNoChange", "\n", "var", "result", "interface", "{", "}", "\n", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "Directive", ")", ";", "ok", "{", "nodeName", ":=", "\"", "\"", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "nodeName", "=", "node", ".", "Name", ".", "Value", "\n", "}", "\n\n", "var", "directiveDef", "*", "Directive", "\n", "for", "_", ",", "def", ":=", "range", "context", ".", "Schema", "(", ")", ".", "Directives", "(", ")", "{", "if", "def", ".", "Name", "==", "nodeName", "{", "directiveDef", "=", "def", "\n", "}", "\n", "}", "\n", "if", "directiveDef", "==", "nil", "{", "return", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Unknown directive \"%v\".`", ",", "nodeName", ")", ",", "[", "]", "ast", ".", "Node", "{", "node", "}", ",", ")", "\n", "}", "\n\n", "candidateLocation", ":=", "getDirectiveLocationForASTPath", "(", "p", ".", "Ancestors", ")", "\n\n", "directiveHasLocation", ":=", "false", "\n", "for", "_", ",", "loc", ":=", "range", "directiveDef", ".", "Locations", "{", "if", "loc", "==", "candidateLocation", "{", "directiveHasLocation", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "candidateLocation", "==", "\"", "\"", "{", "reportError", "(", "context", ",", "MisplaceDirectiveMessage", "(", "nodeName", ",", "node", ".", "GetKind", "(", ")", ")", ",", "[", "]", "ast", ".", "Node", "{", "node", "}", ",", ")", "\n", "}", "else", "if", "!", "directiveHasLocation", "{", "reportError", "(", "context", ",", "MisplaceDirectiveMessage", "(", "nodeName", ",", "candidateLocation", ")", ",", "[", "]", "ast", ".", "Node", "{", "node", "}", ",", ")", "\n", "}", "\n\n", "}", "\n", "return", "action", ",", "result", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// KnownDirectivesRule Known directives // // A GraphQL document is only valid if all `@directives` are known by the // schema and legally positioned.
[ "KnownDirectivesRule", "Known", "directives", "A", "GraphQL", "document", "is", "only", "valid", "if", "all" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L530-L591
train
graphql-go/graphql
rules.go
KnownFragmentNamesRule
func KnownFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.FragmentSpread: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { var action = visitor.ActionNoChange var result interface{} if node, ok := p.Node.(*ast.FragmentSpread); ok { fragmentName := "" if node.Name != nil { fragmentName = node.Name.Value } fragment := context.Fragment(fragmentName) if fragment == nil { reportError( context, fmt.Sprintf(`Unknown fragment "%v".`, fragmentName), []ast.Node{node.Name}, ) } } return action, result }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func KnownFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance { visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.FragmentSpread: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { var action = visitor.ActionNoChange var result interface{} if node, ok := p.Node.(*ast.FragmentSpread); ok { fragmentName := "" if node.Name != nil { fragmentName = node.Name.Value } fragment := context.Fragment(fragmentName) if fragment == nil { reportError( context, fmt.Sprintf(`Unknown fragment "%v".`, fragmentName), []ast.Node{node.Name}, ) } } return action, result }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "KnownFragmentNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "FragmentSpread", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "var", "action", "=", "visitor", ".", "ActionNoChange", "\n", "var", "result", "interface", "{", "}", "\n", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "FragmentSpread", ")", ";", "ok", "{", "fragmentName", ":=", "\"", "\"", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "fragmentName", "=", "node", ".", "Name", ".", "Value", "\n", "}", "\n\n", "fragment", ":=", "context", ".", "Fragment", "(", "fragmentName", ")", "\n", "if", "fragment", "==", "nil", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Unknown fragment \"%v\".`", ",", "fragmentName", ")", ",", "[", "]", "ast", ".", "Node", "{", "node", ".", "Name", "}", ",", ")", "\n", "}", "\n", "}", "\n", "return", "action", ",", "result", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// KnownFragmentNamesRule Known fragment names // // A GraphQL document is only valid if all `...Fragment` fragment spreads refer // to fragments defined in the same document.
[ "KnownFragmentNamesRule", "Known", "fragment", "names", "A", "GraphQL", "document", "is", "only", "valid", "if", "all", "...", "Fragment", "fragment", "spreads", "refer", "to", "fragments", "defined", "in", "the", "same", "document", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L671-L702
train
graphql-go/graphql
rules.go
NoUndefinedVariablesRule
func NoUndefinedVariablesRule(context *ValidationContext) *ValidationRuleInstance { var variableNameDefined = map[string]bool{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { variableNameDefined = map[string]bool{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { if operation, ok := p.Node.(*ast.OperationDefinition); ok && operation != nil { usages := context.RecursiveVariableUsages(operation) for _, usage := range usages { if usage == nil { continue } if usage.Node == nil { continue } varName := "" if usage.Node.Name != nil { varName = usage.Node.Name.Value } opName := "" if operation.Name != nil { opName = operation.Name.Value } if res, ok := variableNameDefined[varName]; !ok || !res { reportError( context, UndefinedVarMessage(varName, opName), []ast.Node{usage.Node, operation}, ) } } } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.VariableDefinition); ok && node != nil { variableName := "" if node.Variable != nil && node.Variable.Name != nil { variableName = node.Variable.Name.Value } variableNameDefined[variableName] = true } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func NoUndefinedVariablesRule(context *ValidationContext) *ValidationRuleInstance { var variableNameDefined = map[string]bool{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { variableNameDefined = map[string]bool{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { if operation, ok := p.Node.(*ast.OperationDefinition); ok && operation != nil { usages := context.RecursiveVariableUsages(operation) for _, usage := range usages { if usage == nil { continue } if usage.Node == nil { continue } varName := "" if usage.Node.Name != nil { varName = usage.Node.Name.Value } opName := "" if operation.Name != nil { opName = operation.Name.Value } if res, ok := variableNameDefined[varName]; !ok || !res { reportError( context, UndefinedVarMessage(varName, opName), []ast.Node{usage.Node, operation}, ) } } } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.VariableDefinition); ok && node != nil { variableName := "" if node.Variable != nil && node.Variable.Name != nil { variableName = node.Variable.Name.Value } variableNameDefined[variableName] = true } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "NoUndefinedVariablesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "var", "variableNameDefined", "=", "map", "[", "string", "]", "bool", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Enter", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "variableNameDefined", "=", "map", "[", "string", "]", "bool", "{", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "Leave", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "operation", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "OperationDefinition", ")", ";", "ok", "&&", "operation", "!=", "nil", "{", "usages", ":=", "context", ".", "RecursiveVariableUsages", "(", "operation", ")", "\n\n", "for", "_", ",", "usage", ":=", "range", "usages", "{", "if", "usage", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "usage", ".", "Node", "==", "nil", "{", "continue", "\n", "}", "\n", "varName", ":=", "\"", "\"", "\n", "if", "usage", ".", "Node", ".", "Name", "!=", "nil", "{", "varName", "=", "usage", ".", "Node", ".", "Name", ".", "Value", "\n", "}", "\n", "opName", ":=", "\"", "\"", "\n", "if", "operation", ".", "Name", "!=", "nil", "{", "opName", "=", "operation", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "res", ",", "ok", ":=", "variableNameDefined", "[", "varName", "]", ";", "!", "ok", "||", "!", "res", "{", "reportError", "(", "context", ",", "UndefinedVarMessage", "(", "varName", ",", "opName", ")", ",", "[", "]", "ast", ".", "Node", "{", "usage", ".", "Node", ",", "operation", "}", ",", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "VariableDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "VariableDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "variableName", ":=", "\"", "\"", "\n", "if", "node", ".", "Variable", "!=", "nil", "&&", "node", ".", "Variable", ".", "Name", "!=", "nil", "{", "variableName", "=", "node", ".", "Variable", ".", "Name", ".", "Value", "\n", "}", "\n", "variableNameDefined", "[", "variableName", "]", "=", "true", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// NoUndefinedVariablesRule No undefined variables // // A GraphQL operation is only valid if all variables encountered, both directly // and via fragment spreads, are defined by that operation.
[ "NoUndefinedVariablesRule", "No", "undefined", "variables", "A", "GraphQL", "operation", "is", "only", "valid", "if", "all", "variables", "encountered", "both", "directly", "and", "via", "fragment", "spreads", "are", "defined", "by", "that", "operation", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L938-L996
train
graphql-go/graphql
rules.go
NoUnusedFragmentsRule
func NoUnusedFragmentsRule(context *ValidationContext) *ValidationRuleInstance { var fragmentDefs = []*ast.FragmentDefinition{} var operationDefs = []*ast.OperationDefinition{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.OperationDefinition); ok && node != nil { operationDefs = append(operationDefs, node) } return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.FragmentDefinition); ok && node != nil { fragmentDefs = append(fragmentDefs, node) } return visitor.ActionSkip, nil }, }, kinds.Document: { Leave: func(p visitor.VisitFuncParams) (string, interface{}) { fragmentNameUsed := map[string]bool{} for _, operation := range operationDefs { fragments := context.RecursivelyReferencedFragments(operation) for _, fragment := range fragments { fragName := "" if fragment.Name != nil { fragName = fragment.Name.Value } fragmentNameUsed[fragName] = true } } for _, def := range fragmentDefs { defName := "" if def.Name != nil { defName = def.Name.Value } isFragNameUsed, ok := fragmentNameUsed[defName] if !ok || isFragNameUsed != true { reportError( context, fmt.Sprintf(`Fragment "%v" is never used.`, defName), []ast.Node{def}, ) } } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func NoUnusedFragmentsRule(context *ValidationContext) *ValidationRuleInstance { var fragmentDefs = []*ast.FragmentDefinition{} var operationDefs = []*ast.OperationDefinition{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.OperationDefinition); ok && node != nil { operationDefs = append(operationDefs, node) } return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.FragmentDefinition); ok && node != nil { fragmentDefs = append(fragmentDefs, node) } return visitor.ActionSkip, nil }, }, kinds.Document: { Leave: func(p visitor.VisitFuncParams) (string, interface{}) { fragmentNameUsed := map[string]bool{} for _, operation := range operationDefs { fragments := context.RecursivelyReferencedFragments(operation) for _, fragment := range fragments { fragName := "" if fragment.Name != nil { fragName = fragment.Name.Value } fragmentNameUsed[fragName] = true } } for _, def := range fragmentDefs { defName := "" if def.Name != nil { defName = def.Name.Value } isFragNameUsed, ok := fragmentNameUsed[defName] if !ok || isFragNameUsed != true { reportError( context, fmt.Sprintf(`Fragment "%v" is never used.`, defName), []ast.Node{def}, ) } } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "NoUnusedFragmentsRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "var", "fragmentDefs", "=", "[", "]", "*", "ast", ".", "FragmentDefinition", "{", "}", "\n", "var", "operationDefs", "=", "[", "]", "*", "ast", ".", "OperationDefinition", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "OperationDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "operationDefs", "=", "append", "(", "operationDefs", ",", "node", ")", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "FragmentDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "FragmentDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "fragmentDefs", "=", "append", "(", "fragmentDefs", ",", "node", ")", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "Document", ":", "{", "Leave", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "fragmentNameUsed", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "for", "_", ",", "operation", ":=", "range", "operationDefs", "{", "fragments", ":=", "context", ".", "RecursivelyReferencedFragments", "(", "operation", ")", "\n", "for", "_", ",", "fragment", ":=", "range", "fragments", "{", "fragName", ":=", "\"", "\"", "\n", "if", "fragment", ".", "Name", "!=", "nil", "{", "fragName", "=", "fragment", ".", "Name", ".", "Value", "\n", "}", "\n", "fragmentNameUsed", "[", "fragName", "]", "=", "true", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "def", ":=", "range", "fragmentDefs", "{", "defName", ":=", "\"", "\"", "\n", "if", "def", ".", "Name", "!=", "nil", "{", "defName", "=", "def", ".", "Name", ".", "Value", "\n", "}", "\n\n", "isFragNameUsed", ",", "ok", ":=", "fragmentNameUsed", "[", "defName", "]", "\n", "if", "!", "ok", "||", "isFragNameUsed", "!=", "true", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Fragment \"%v\" is never used.`", ",", "defName", ")", ",", "[", "]", "ast", ".", "Node", "{", "def", "}", ",", ")", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// NoUnusedFragmentsRule No unused fragments // // A GraphQL document is only valid if all fragment definitions are spread // within operations, or spread within other fragments spread within operations.
[ "NoUnusedFragmentsRule", "No", "unused", "fragments", "A", "GraphQL", "document", "is", "only", "valid", "if", "all", "fragment", "definitions", "are", "spread", "within", "operations", "or", "spread", "within", "other", "fragments", "spread", "within", "operations", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1002-L1062
train
graphql-go/graphql
rules.go
NoUnusedVariablesRule
func NoUnusedVariablesRule(context *ValidationContext) *ValidationRuleInstance { var variableDefs = []*ast.VariableDefinition{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { variableDefs = []*ast.VariableDefinition{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { if operation, ok := p.Node.(*ast.OperationDefinition); ok && operation != nil { variableNameUsed := map[string]bool{} usages := context.RecursiveVariableUsages(operation) for _, usage := range usages { varName := "" if usage != nil && usage.Node != nil && usage.Node.Name != nil { varName = usage.Node.Name.Value } if varName != "" { variableNameUsed[varName] = true } } for _, variableDef := range variableDefs { variableName := "" if variableDef != nil && variableDef.Variable != nil && variableDef.Variable.Name != nil { variableName = variableDef.Variable.Name.Value } opName := "" if operation.Name != nil { opName = operation.Name.Value } if res, ok := variableNameUsed[variableName]; !ok || !res { reportError( context, UnusedVariableMessage(variableName, opName), []ast.Node{variableDef}, ) } } } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if def, ok := p.Node.(*ast.VariableDefinition); ok && def != nil { variableDefs = append(variableDefs, def) } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func NoUnusedVariablesRule(context *ValidationContext) *ValidationRuleInstance { var variableDefs = []*ast.VariableDefinition{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { variableDefs = []*ast.VariableDefinition{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { if operation, ok := p.Node.(*ast.OperationDefinition); ok && operation != nil { variableNameUsed := map[string]bool{} usages := context.RecursiveVariableUsages(operation) for _, usage := range usages { varName := "" if usage != nil && usage.Node != nil && usage.Node.Name != nil { varName = usage.Node.Name.Value } if varName != "" { variableNameUsed[varName] = true } } for _, variableDef := range variableDefs { variableName := "" if variableDef != nil && variableDef.Variable != nil && variableDef.Variable.Name != nil { variableName = variableDef.Variable.Name.Value } opName := "" if operation.Name != nil { opName = operation.Name.Value } if res, ok := variableNameUsed[variableName]; !ok || !res { reportError( context, UnusedVariableMessage(variableName, opName), []ast.Node{variableDef}, ) } } } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if def, ok := p.Node.(*ast.VariableDefinition); ok && def != nil { variableDefs = append(variableDefs, def) } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "NoUnusedVariablesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "var", "variableDefs", "=", "[", "]", "*", "ast", ".", "VariableDefinition", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Enter", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "variableDefs", "=", "[", "]", "*", "ast", ".", "VariableDefinition", "{", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "Leave", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "operation", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "OperationDefinition", ")", ";", "ok", "&&", "operation", "!=", "nil", "{", "variableNameUsed", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "usages", ":=", "context", ".", "RecursiveVariableUsages", "(", "operation", ")", "\n\n", "for", "_", ",", "usage", ":=", "range", "usages", "{", "varName", ":=", "\"", "\"", "\n", "if", "usage", "!=", "nil", "&&", "usage", ".", "Node", "!=", "nil", "&&", "usage", ".", "Node", ".", "Name", "!=", "nil", "{", "varName", "=", "usage", ".", "Node", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "varName", "!=", "\"", "\"", "{", "variableNameUsed", "[", "varName", "]", "=", "true", "\n", "}", "\n", "}", "\n", "for", "_", ",", "variableDef", ":=", "range", "variableDefs", "{", "variableName", ":=", "\"", "\"", "\n", "if", "variableDef", "!=", "nil", "&&", "variableDef", ".", "Variable", "!=", "nil", "&&", "variableDef", ".", "Variable", ".", "Name", "!=", "nil", "{", "variableName", "=", "variableDef", ".", "Variable", ".", "Name", ".", "Value", "\n", "}", "\n", "opName", ":=", "\"", "\"", "\n", "if", "operation", ".", "Name", "!=", "nil", "{", "opName", "=", "operation", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "res", ",", "ok", ":=", "variableNameUsed", "[", "variableName", "]", ";", "!", "ok", "||", "!", "res", "{", "reportError", "(", "context", ",", "UnusedVariableMessage", "(", "variableName", ",", "opName", ")", ",", "[", "]", "ast", ".", "Node", "{", "variableDef", "}", ",", ")", "\n", "}", "\n", "}", "\n\n", "}", "\n\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "VariableDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "def", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "VariableDefinition", ")", ";", "ok", "&&", "def", "!=", "nil", "{", "variableDefs", "=", "append", "(", "variableDefs", ",", "def", ")", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// NoUnusedVariablesRule No unused variables // // A GraphQL operation is only valid if all variables defined by an operation // are used, either directly or within a spread fragment.
[ "NoUnusedVariablesRule", "No", "unused", "variables", "A", "GraphQL", "operation", "is", "only", "valid", "if", "all", "variables", "defined", "by", "an", "operation", "are", "used", "either", "directly", "or", "within", "a", "spread", "fragment", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1075-L1136
train
graphql-go/graphql
rules.go
UniqueArgumentNamesRule
func UniqueArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance { knownArgNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Field: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { knownArgNames = map[string]*ast.Name{} return visitor.ActionNoChange, nil }, }, kinds.Directive: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { knownArgNames = map[string]*ast.Name{} return visitor.ActionNoChange, nil }, }, kinds.Argument: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.Argument); ok { argName := "" if node.Name != nil { argName = node.Name.Value } if nameAST, ok := knownArgNames[argName]; ok { reportError( context, fmt.Sprintf(`There can be only one argument named "%v".`, argName), []ast.Node{nameAST, node.Name}, ) } else { knownArgNames[argName] = node.Name } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func UniqueArgumentNamesRule(context *ValidationContext) *ValidationRuleInstance { knownArgNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.Field: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { knownArgNames = map[string]*ast.Name{} return visitor.ActionNoChange, nil }, }, kinds.Directive: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { knownArgNames = map[string]*ast.Name{} return visitor.ActionNoChange, nil }, }, kinds.Argument: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.Argument); ok { argName := "" if node.Name != nil { argName = node.Name.Value } if nameAST, ok := knownArgNames[argName]; ok { reportError( context, fmt.Sprintf(`There can be only one argument named "%v".`, argName), []ast.Node{nameAST, node.Name}, ) } else { knownArgNames[argName] = node.Name } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "UniqueArgumentNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "knownArgNames", ":=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "Field", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "knownArgNames", "=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "Directive", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "knownArgNames", "=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "Argument", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "Argument", ")", ";", "ok", "{", "argName", ":=", "\"", "\"", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "argName", "=", "node", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "nameAST", ",", "ok", ":=", "knownArgNames", "[", "argName", "]", ";", "ok", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`There can be only one argument named \"%v\".`", ",", "argName", ")", ",", "[", "]", "ast", ".", "Node", "{", "nameAST", ",", "node", ".", "Name", "}", ",", ")", "\n", "}", "else", "{", "knownArgNames", "[", "argName", "]", "=", "node", ".", "Name", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// UniqueArgumentNamesRule Unique argument names // // A GraphQL field or directive is only valid if all supplied arguments are // uniquely named.
[ "UniqueArgumentNamesRule", "Unique", "argument", "names", "A", "GraphQL", "field", "or", "directive", "is", "only", "valid", "if", "all", "supplied", "arguments", "are", "uniquely", "named", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1388-L1430
train
graphql-go/graphql
rules.go
UniqueFragmentNamesRule
func UniqueFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance { knownFragmentNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.FragmentDefinition); ok && node != nil { fragmentName := "" if node.Name != nil { fragmentName = node.Name.Value } if nameAST, ok := knownFragmentNames[fragmentName]; ok { reportError( context, fmt.Sprintf(`There can only be one fragment named "%v".`, fragmentName), []ast.Node{nameAST, node.Name}, ) } else { knownFragmentNames[fragmentName] = node.Name } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func UniqueFragmentNamesRule(context *ValidationContext) *ValidationRuleInstance { knownFragmentNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.FragmentDefinition); ok && node != nil { fragmentName := "" if node.Name != nil { fragmentName = node.Name.Value } if nameAST, ok := knownFragmentNames[fragmentName]; ok { reportError( context, fmt.Sprintf(`There can only be one fragment named "%v".`, fragmentName), []ast.Node{nameAST, node.Name}, ) } else { knownFragmentNames[fragmentName] = node.Name } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "UniqueFragmentNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "knownFragmentNames", ":=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "FragmentDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "FragmentDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "fragmentName", ":=", "\"", "\"", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "fragmentName", "=", "node", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "nameAST", ",", "ok", ":=", "knownFragmentNames", "[", "fragmentName", "]", ";", "ok", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`There can only be one fragment named \"%v\".`", ",", "fragmentName", ")", ",", "[", "]", "ast", ".", "Node", "{", "nameAST", ",", "node", ".", "Name", "}", ",", ")", "\n", "}", "else", "{", "knownFragmentNames", "[", "fragmentName", "]", "=", "node", ".", "Name", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// UniqueFragmentNamesRule Unique fragment names // // A GraphQL document is only valid if all defined fragments have unique names.
[ "UniqueFragmentNamesRule", "Unique", "fragment", "names", "A", "GraphQL", "document", "is", "only", "valid", "if", "all", "defined", "fragments", "have", "unique", "names", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1435-L1470
train
graphql-go/graphql
rules.go
UniqueInputFieldNamesRule
func UniqueInputFieldNamesRule(context *ValidationContext) *ValidationRuleInstance { knownNameStack := []map[string]*ast.Name{} knownNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.ObjectValue: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { knownNameStack = append(knownNameStack, knownNames) knownNames = map[string]*ast.Name{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { // pop knownNames, knownNameStack = knownNameStack[len(knownNameStack)-1], knownNameStack[:len(knownNameStack)-1] return visitor.ActionNoChange, nil }, }, kinds.ObjectField: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.ObjectField); ok { fieldName := "" if node.Name != nil { fieldName = node.Name.Value } if knownNameAST, ok := knownNames[fieldName]; ok { reportError( context, fmt.Sprintf(`There can be only one input field named "%v".`, fieldName), []ast.Node{knownNameAST, node.Name}, ) } else { knownNames[fieldName] = node.Name } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func UniqueInputFieldNamesRule(context *ValidationContext) *ValidationRuleInstance { knownNameStack := []map[string]*ast.Name{} knownNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.ObjectValue: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { knownNameStack = append(knownNameStack, knownNames) knownNames = map[string]*ast.Name{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { // pop knownNames, knownNameStack = knownNameStack[len(knownNameStack)-1], knownNameStack[:len(knownNameStack)-1] return visitor.ActionNoChange, nil }, }, kinds.ObjectField: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.ObjectField); ok { fieldName := "" if node.Name != nil { fieldName = node.Name.Value } if knownNameAST, ok := knownNames[fieldName]; ok { reportError( context, fmt.Sprintf(`There can be only one input field named "%v".`, fieldName), []ast.Node{knownNameAST, node.Name}, ) } else { knownNames[fieldName] = node.Name } } return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "UniqueInputFieldNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "knownNameStack", ":=", "[", "]", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n", "knownNames", ":=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "ObjectValue", ":", "{", "Enter", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "knownNameStack", "=", "append", "(", "knownNameStack", ",", "knownNames", ")", "\n", "knownNames", "=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "Leave", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "// pop", "knownNames", ",", "knownNameStack", "=", "knownNameStack", "[", "len", "(", "knownNameStack", ")", "-", "1", "]", ",", "knownNameStack", "[", ":", "len", "(", "knownNameStack", ")", "-", "1", "]", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "ObjectField", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "ObjectField", ")", ";", "ok", "{", "fieldName", ":=", "\"", "\"", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "fieldName", "=", "node", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "knownNameAST", ",", "ok", ":=", "knownNames", "[", "fieldName", "]", ";", "ok", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`There can be only one input field named \"%v\".`", ",", "fieldName", ")", ",", "[", "]", "ast", ".", "Node", "{", "knownNameAST", ",", "node", ".", "Name", "}", ",", ")", "\n", "}", "else", "{", "knownNames", "[", "fieldName", "]", "=", "node", ".", "Name", "\n", "}", "\n\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// UniqueInputFieldNamesRule Unique input field names // // A GraphQL input object value is only valid if all supplied fields are // uniquely named.
[ "UniqueInputFieldNamesRule", "Unique", "input", "field", "names", "A", "GraphQL", "input", "object", "value", "is", "only", "valid", "if", "all", "supplied", "fields", "are", "uniquely", "named", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1476-L1520
train
graphql-go/graphql
rules.go
UniqueOperationNamesRule
func UniqueOperationNamesRule(context *ValidationContext) *ValidationRuleInstance { knownOperationNames := make(map[string]ast.Node) visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.OperationDefinition); ok && node != nil { operationName := "" if node.Name != nil { operationName = node.Name.Value } var errNode ast.Node = node if node.Name != nil { errNode = node.Name } if nameAST, ok := knownOperationNames[operationName]; ok { reportError( context, fmt.Sprintf(`There can only be one operation named "%v".`, operationName), []ast.Node{nameAST, errNode}, ) } else { knownOperationNames[operationName] = errNode } } return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func UniqueOperationNamesRule(context *ValidationContext) *ValidationRuleInstance { knownOperationNames := make(map[string]ast.Node) visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.OperationDefinition); ok && node != nil { operationName := "" if node.Name != nil { operationName = node.Name.Value } var errNode ast.Node = node if node.Name != nil { errNode = node.Name } if nameAST, ok := knownOperationNames[operationName]; ok { reportError( context, fmt.Sprintf(`There can only be one operation named "%v".`, operationName), []ast.Node{nameAST, errNode}, ) } else { knownOperationNames[operationName] = errNode } } return visitor.ActionSkip, nil }, }, kinds.FragmentDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { return visitor.ActionSkip, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "UniqueOperationNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "knownOperationNames", ":=", "make", "(", "map", "[", "string", "]", "ast", ".", "Node", ")", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "OperationDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "operationName", ":=", "\"", "\"", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "operationName", "=", "node", ".", "Name", ".", "Value", "\n", "}", "\n", "var", "errNode", "ast", ".", "Node", "=", "node", "\n", "if", "node", ".", "Name", "!=", "nil", "{", "errNode", "=", "node", ".", "Name", "\n", "}", "\n", "if", "nameAST", ",", "ok", ":=", "knownOperationNames", "[", "operationName", "]", ";", "ok", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`There can only be one operation named \"%v\".`", ",", "operationName", ")", ",", "[", "]", "ast", ".", "Node", "{", "nameAST", ",", "errNode", "}", ",", ")", "\n", "}", "else", "{", "knownOperationNames", "[", "operationName", "]", "=", "errNode", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "FragmentDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "return", "visitor", ".", "ActionSkip", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// UniqueOperationNamesRule Unique operation names // // A GraphQL document is only valid if all defined operations have unique names.
[ "UniqueOperationNamesRule", "Unique", "operation", "names", "A", "GraphQL", "document", "is", "only", "valid", "if", "all", "defined", "operations", "have", "unique", "names", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1525-L1564
train
graphql-go/graphql
rules.go
UniqueVariableNamesRule
func UniqueVariableNamesRule(context *ValidationContext) *ValidationRuleInstance { knownVariableNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.OperationDefinition); ok && node != nil { knownVariableNames = map[string]*ast.Name{} } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.VariableDefinition); ok && node != nil { variableName := "" var variableNameAST *ast.Name if node.Variable != nil && node.Variable.Name != nil { variableNameAST = node.Variable.Name variableName = node.Variable.Name.Value } if nameAST, ok := knownVariableNames[variableName]; ok { reportError( context, fmt.Sprintf(`There can only be one variable named "%v".`, variableName), []ast.Node{nameAST, variableNameAST}, ) } else { knownVariableNames[variableName] = variableNameAST } } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func UniqueVariableNamesRule(context *ValidationContext) *ValidationRuleInstance { knownVariableNames := map[string]*ast.Name{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.OperationDefinition); ok && node != nil { knownVariableNames = map[string]*ast.Name{} } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(*ast.VariableDefinition); ok && node != nil { variableName := "" var variableNameAST *ast.Name if node.Variable != nil && node.Variable.Name != nil { variableNameAST = node.Variable.Name variableName = node.Variable.Name.Value } if nameAST, ok := knownVariableNames[variableName]; ok { reportError( context, fmt.Sprintf(`There can only be one variable named "%v".`, variableName), []ast.Node{nameAST, variableNameAST}, ) } else { knownVariableNames[variableName] = variableNameAST } } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "UniqueVariableNamesRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "knownVariableNames", ":=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "OperationDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "knownVariableNames", "=", "map", "[", "string", "]", "*", "ast", ".", "Name", "{", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "VariableDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "VariableDefinition", ")", ";", "ok", "&&", "node", "!=", "nil", "{", "variableName", ":=", "\"", "\"", "\n", "var", "variableNameAST", "*", "ast", ".", "Name", "\n", "if", "node", ".", "Variable", "!=", "nil", "&&", "node", ".", "Variable", ".", "Name", "!=", "nil", "{", "variableNameAST", "=", "node", ".", "Variable", ".", "Name", "\n", "variableName", "=", "node", ".", "Variable", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "nameAST", ",", "ok", ":=", "knownVariableNames", "[", "variableName", "]", ";", "ok", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`There can only be one variable named \"%v\".`", ",", "variableName", ")", ",", "[", "]", "ast", ".", "Node", "{", "nameAST", ",", "variableNameAST", "}", ",", ")", "\n", "}", "else", "{", "knownVariableNames", "[", "variableName", "]", "=", "variableNameAST", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// UniqueVariableNamesRule Unique variable names // // A GraphQL operation is only valid if all its variables are uniquely named.
[ "UniqueVariableNamesRule", "Unique", "variable", "names", "A", "GraphQL", "operation", "is", "only", "valid", "if", "all", "its", "variables", "are", "uniquely", "named", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1569-L1609
train
graphql-go/graphql
rules.go
effectiveType
func effectiveType(varType Type, varDef *ast.VariableDefinition) Type { if varDef.DefaultValue == nil { return varType } if _, ok := varType.(*NonNull); ok { return varType } return NewNonNull(varType) }
go
func effectiveType(varType Type, varDef *ast.VariableDefinition) Type { if varDef.DefaultValue == nil { return varType } if _, ok := varType.(*NonNull); ok { return varType } return NewNonNull(varType) }
[ "func", "effectiveType", "(", "varType", "Type", ",", "varDef", "*", "ast", ".", "VariableDefinition", ")", "Type", "{", "if", "varDef", ".", "DefaultValue", "==", "nil", "{", "return", "varType", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "varType", ".", "(", "*", "NonNull", ")", ";", "ok", "{", "return", "varType", "\n", "}", "\n", "return", "NewNonNull", "(", "varType", ")", "\n", "}" ]
// If a variable definition has a default value, it's effectively non-null.
[ "If", "a", "variable", "definition", "has", "a", "default", "value", "it", "s", "effectively", "non", "-", "null", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1649-L1657
train
graphql-go/graphql
rules.go
VariablesInAllowedPositionRule
func VariablesInAllowedPositionRule(context *ValidationContext) *ValidationRuleInstance { varDefMap := map[string]*ast.VariableDefinition{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { varDefMap = map[string]*ast.VariableDefinition{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { if operation, ok := p.Node.(*ast.OperationDefinition); ok { usages := context.RecursiveVariableUsages(operation) for _, usage := range usages { varName := "" if usage != nil && usage.Node != nil && usage.Node.Name != nil { varName = usage.Node.Name.Value } varDef, _ := varDefMap[varName] if varDef != nil && usage.Type != nil { varType, err := typeFromAST(*context.Schema(), varDef.Type) if err != nil { varType = nil } if varType != nil && !isTypeSubTypeOf(context.Schema(), effectiveType(varType, varDef), usage.Type) { reportError( context, fmt.Sprintf(`Variable "$%v" of type "%v" used in position `+ `expecting type "%v".`, varName, varType, usage.Type), []ast.Node{varDef, usage.Node}, ) } } } } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if varDefAST, ok := p.Node.(*ast.VariableDefinition); ok { defName := "" if varDefAST.Variable != nil && varDefAST.Variable.Name != nil { defName = varDefAST.Variable.Name.Value } if defName != "" { varDefMap[defName] = varDefAST } } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
go
func VariablesInAllowedPositionRule(context *ValidationContext) *ValidationRuleInstance { varDefMap := map[string]*ast.VariableDefinition{} visitorOpts := &visitor.VisitorOptions{ KindFuncMap: map[string]visitor.NamedVisitFuncs{ kinds.OperationDefinition: { Enter: func(p visitor.VisitFuncParams) (string, interface{}) { varDefMap = map[string]*ast.VariableDefinition{} return visitor.ActionNoChange, nil }, Leave: func(p visitor.VisitFuncParams) (string, interface{}) { if operation, ok := p.Node.(*ast.OperationDefinition); ok { usages := context.RecursiveVariableUsages(operation) for _, usage := range usages { varName := "" if usage != nil && usage.Node != nil && usage.Node.Name != nil { varName = usage.Node.Name.Value } varDef, _ := varDefMap[varName] if varDef != nil && usage.Type != nil { varType, err := typeFromAST(*context.Schema(), varDef.Type) if err != nil { varType = nil } if varType != nil && !isTypeSubTypeOf(context.Schema(), effectiveType(varType, varDef), usage.Type) { reportError( context, fmt.Sprintf(`Variable "$%v" of type "%v" used in position `+ `expecting type "%v".`, varName, varType, usage.Type), []ast.Node{varDef, usage.Node}, ) } } } } return visitor.ActionNoChange, nil }, }, kinds.VariableDefinition: { Kind: func(p visitor.VisitFuncParams) (string, interface{}) { if varDefAST, ok := p.Node.(*ast.VariableDefinition); ok { defName := "" if varDefAST.Variable != nil && varDefAST.Variable.Name != nil { defName = varDefAST.Variable.Name.Value } if defName != "" { varDefMap[defName] = varDefAST } } return visitor.ActionNoChange, nil }, }, }, } return &ValidationRuleInstance{ VisitorOpts: visitorOpts, } }
[ "func", "VariablesInAllowedPositionRule", "(", "context", "*", "ValidationContext", ")", "*", "ValidationRuleInstance", "{", "varDefMap", ":=", "map", "[", "string", "]", "*", "ast", ".", "VariableDefinition", "{", "}", "\n\n", "visitorOpts", ":=", "&", "visitor", ".", "VisitorOptions", "{", "KindFuncMap", ":", "map", "[", "string", "]", "visitor", ".", "NamedVisitFuncs", "{", "kinds", ".", "OperationDefinition", ":", "{", "Enter", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "varDefMap", "=", "map", "[", "string", "]", "*", "ast", ".", "VariableDefinition", "{", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "Leave", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "operation", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "OperationDefinition", ")", ";", "ok", "{", "usages", ":=", "context", ".", "RecursiveVariableUsages", "(", "operation", ")", "\n", "for", "_", ",", "usage", ":=", "range", "usages", "{", "varName", ":=", "\"", "\"", "\n", "if", "usage", "!=", "nil", "&&", "usage", ".", "Node", "!=", "nil", "&&", "usage", ".", "Node", ".", "Name", "!=", "nil", "{", "varName", "=", "usage", ".", "Node", ".", "Name", ".", "Value", "\n", "}", "\n", "varDef", ",", "_", ":=", "varDefMap", "[", "varName", "]", "\n", "if", "varDef", "!=", "nil", "&&", "usage", ".", "Type", "!=", "nil", "{", "varType", ",", "err", ":=", "typeFromAST", "(", "*", "context", ".", "Schema", "(", ")", ",", "varDef", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "varType", "=", "nil", "\n", "}", "\n", "if", "varType", "!=", "nil", "&&", "!", "isTypeSubTypeOf", "(", "context", ".", "Schema", "(", ")", ",", "effectiveType", "(", "varType", ",", "varDef", ")", ",", "usage", ".", "Type", ")", "{", "reportError", "(", "context", ",", "fmt", ".", "Sprintf", "(", "`Variable \"$%v\" of type \"%v\" used in position `", "+", "`expecting type \"%v\".`", ",", "varName", ",", "varType", ",", "usage", ".", "Type", ")", ",", "[", "]", "ast", ".", "Node", "{", "varDef", ",", "usage", ".", "Node", "}", ",", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "kinds", ".", "VariableDefinition", ":", "{", "Kind", ":", "func", "(", "p", "visitor", ".", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "varDefAST", ",", "ok", ":=", "p", ".", "Node", ".", "(", "*", "ast", ".", "VariableDefinition", ")", ";", "ok", "{", "defName", ":=", "\"", "\"", "\n", "if", "varDefAST", ".", "Variable", "!=", "nil", "&&", "varDefAST", ".", "Variable", ".", "Name", "!=", "nil", "{", "defName", "=", "varDefAST", ".", "Variable", ".", "Name", ".", "Value", "\n", "}", "\n", "if", "defName", "!=", "\"", "\"", "{", "varDefMap", "[", "defName", "]", "=", "varDefAST", "\n", "}", "\n", "}", "\n", "return", "visitor", ".", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", ",", "}", ",", "}", "\n", "return", "&", "ValidationRuleInstance", "{", "VisitorOpts", ":", "visitorOpts", ",", "}", "\n", "}" ]
// VariablesInAllowedPositionRule Variables passed to field arguments conform to type
[ "VariablesInAllowedPositionRule", "Variables", "passed", "to", "field", "arguments", "conform", "to", "type" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1660-L1720
train
graphql-go/graphql
rules.go
suggestionList
func suggestionList(input string, options []string) []string { dists := []float64{} filteredOpts := []string{} inputThreshold := float64(len(input) / 2) for _, opt := range options { dist := lexicalDistance(input, opt) threshold := math.Max(inputThreshold, float64(len(opt)/2)) threshold = math.Max(threshold, 1) if dist <= threshold { filteredOpts = append(filteredOpts, opt) dists = append(dists, dist) } } //sort results suggested := suggestionListResult{filteredOpts, dists} sort.Sort(suggested) return suggested.Options }
go
func suggestionList(input string, options []string) []string { dists := []float64{} filteredOpts := []string{} inputThreshold := float64(len(input) / 2) for _, opt := range options { dist := lexicalDistance(input, opt) threshold := math.Max(inputThreshold, float64(len(opt)/2)) threshold = math.Max(threshold, 1) if dist <= threshold { filteredOpts = append(filteredOpts, opt) dists = append(dists, dist) } } //sort results suggested := suggestionListResult{filteredOpts, dists} sort.Sort(suggested) return suggested.Options }
[ "func", "suggestionList", "(", "input", "string", ",", "options", "[", "]", "string", ")", "[", "]", "string", "{", "dists", ":=", "[", "]", "float64", "{", "}", "\n", "filteredOpts", ":=", "[", "]", "string", "{", "}", "\n", "inputThreshold", ":=", "float64", "(", "len", "(", "input", ")", "/", "2", ")", "\n\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "dist", ":=", "lexicalDistance", "(", "input", ",", "opt", ")", "\n", "threshold", ":=", "math", ".", "Max", "(", "inputThreshold", ",", "float64", "(", "len", "(", "opt", ")", "/", "2", ")", ")", "\n", "threshold", "=", "math", ".", "Max", "(", "threshold", ",", "1", ")", "\n", "if", "dist", "<=", "threshold", "{", "filteredOpts", "=", "append", "(", "filteredOpts", ",", "opt", ")", "\n", "dists", "=", "append", "(", "dists", ",", "dist", ")", "\n", "}", "\n", "}", "\n", "//sort results", "suggested", ":=", "suggestionListResult", "{", "filteredOpts", ",", "dists", "}", "\n", "sort", ".", "Sort", "(", "suggested", ")", "\n", "return", "suggested", ".", "Options", "\n", "}" ]
// suggestionList Given an invalid input string and a list of valid options, returns a filtered // list of valid options sorted based on their similarity with the input.
[ "suggestionList", "Given", "an", "invalid", "input", "string", "and", "a", "list", "of", "valid", "options", "returns", "a", "filtered", "list", "of", "valid", "options", "sorted", "based", "on", "their", "similarity", "with", "the", "input", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1830-L1848
train
graphql-go/graphql
rules.go
lexicalDistance
func lexicalDistance(a, b string) float64 { d := [][]float64{} aLen := len(a) bLen := len(b) for i := 0; i <= aLen; i++ { d = append(d, []float64{float64(i)}) } for k := 1; k <= bLen; k++ { d[0] = append(d[0], float64(k)) } for i := 1; i <= aLen; i++ { for k := 1; k <= bLen; k++ { cost := 1.0 if a[i-1] == b[k-1] { cost = 0.0 } minCostFloat := math.Min( d[i-1][k]+1.0, d[i][k-1]+1.0, ) minCostFloat = math.Min( minCostFloat, d[i-1][k-1]+cost, ) d[i] = append(d[i], minCostFloat) if i > 1 && k < 1 && a[i-1] == b[k-2] && a[i-2] == b[k-1] { d[i][k] = math.Min(d[i][k], d[i-2][k-2]+cost) } } } return d[aLen][bLen] }
go
func lexicalDistance(a, b string) float64 { d := [][]float64{} aLen := len(a) bLen := len(b) for i := 0; i <= aLen; i++ { d = append(d, []float64{float64(i)}) } for k := 1; k <= bLen; k++ { d[0] = append(d[0], float64(k)) } for i := 1; i <= aLen; i++ { for k := 1; k <= bLen; k++ { cost := 1.0 if a[i-1] == b[k-1] { cost = 0.0 } minCostFloat := math.Min( d[i-1][k]+1.0, d[i][k-1]+1.0, ) minCostFloat = math.Min( minCostFloat, d[i-1][k-1]+cost, ) d[i] = append(d[i], minCostFloat) if i > 1 && k < 1 && a[i-1] == b[k-2] && a[i-2] == b[k-1] { d[i][k] = math.Min(d[i][k], d[i-2][k-2]+cost) } } } return d[aLen][bLen] }
[ "func", "lexicalDistance", "(", "a", ",", "b", "string", ")", "float64", "{", "d", ":=", "[", "]", "[", "]", "float64", "{", "}", "\n", "aLen", ":=", "len", "(", "a", ")", "\n", "bLen", ":=", "len", "(", "b", ")", "\n", "for", "i", ":=", "0", ";", "i", "<=", "aLen", ";", "i", "++", "{", "d", "=", "append", "(", "d", ",", "[", "]", "float64", "{", "float64", "(", "i", ")", "}", ")", "\n", "}", "\n", "for", "k", ":=", "1", ";", "k", "<=", "bLen", ";", "k", "++", "{", "d", "[", "0", "]", "=", "append", "(", "d", "[", "0", "]", ",", "float64", "(", "k", ")", ")", "\n", "}", "\n\n", "for", "i", ":=", "1", ";", "i", "<=", "aLen", ";", "i", "++", "{", "for", "k", ":=", "1", ";", "k", "<=", "bLen", ";", "k", "++", "{", "cost", ":=", "1.0", "\n", "if", "a", "[", "i", "-", "1", "]", "==", "b", "[", "k", "-", "1", "]", "{", "cost", "=", "0.0", "\n", "}", "\n", "minCostFloat", ":=", "math", ".", "Min", "(", "d", "[", "i", "-", "1", "]", "[", "k", "]", "+", "1.0", ",", "d", "[", "i", "]", "[", "k", "-", "1", "]", "+", "1.0", ",", ")", "\n", "minCostFloat", "=", "math", ".", "Min", "(", "minCostFloat", ",", "d", "[", "i", "-", "1", "]", "[", "k", "-", "1", "]", "+", "cost", ",", ")", "\n", "d", "[", "i", "]", "=", "append", "(", "d", "[", "i", "]", ",", "minCostFloat", ")", "\n\n", "if", "i", ">", "1", "&&", "k", "<", "1", "&&", "a", "[", "i", "-", "1", "]", "==", "b", "[", "k", "-", "2", "]", "&&", "a", "[", "i", "-", "2", "]", "==", "b", "[", "k", "-", "1", "]", "{", "d", "[", "i", "]", "[", "k", "]", "=", "math", ".", "Min", "(", "d", "[", "i", "]", "[", "k", "]", ",", "d", "[", "i", "-", "2", "]", "[", "k", "-", "2", "]", "+", "cost", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "d", "[", "aLen", "]", "[", "bLen", "]", "\n", "}" ]
// lexicalDistance Computes the lexical distance between strings A and B. // The "distance" between two strings is given by counting the minimum number // of edits needed to transform string A into string B. An edit can be an // insertion, deletion, or substitution of a single character, or a swap of two // adjacent characters. // This distance can be useful for detecting typos in input or sorting
[ "lexicalDistance", "Computes", "the", "lexical", "distance", "between", "strings", "A", "and", "B", ".", "The", "distance", "between", "two", "strings", "is", "given", "by", "counting", "the", "minimum", "number", "of", "edits", "needed", "to", "transform", "string", "A", "into", "string", "B", ".", "An", "edit", "can", "be", "an", "insertion", "deletion", "or", "substitution", "of", "a", "single", "character", "or", "a", "swap", "of", "two", "adjacent", "characters", ".", "This", "distance", "can", "be", "useful", "for", "detecting", "typos", "in", "input", "or", "sorting" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/rules.go#L1856-L1892
train
graphql-go/graphql
util.go
BindArg
func BindArg(obj interface{}, tags ...string) FieldConfigArgument { v := reflect.Indirect(reflect.ValueOf(obj)) var config = make(FieldConfigArgument) for i := 0; i < v.NumField(); i++ { field := v.Type().Field(i) mytag := extractTag(field.Tag) if inArray(tags, mytag) { config[mytag] = &ArgumentConfig{ Type: getGraphType(field.Type), } } } return config }
go
func BindArg(obj interface{}, tags ...string) FieldConfigArgument { v := reflect.Indirect(reflect.ValueOf(obj)) var config = make(FieldConfigArgument) for i := 0; i < v.NumField(); i++ { field := v.Type().Field(i) mytag := extractTag(field.Tag) if inArray(tags, mytag) { config[mytag] = &ArgumentConfig{ Type: getGraphType(field.Type), } } } return config }
[ "func", "BindArg", "(", "obj", "interface", "{", "}", ",", "tags", "...", "string", ")", "FieldConfigArgument", "{", "v", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "obj", ")", ")", "\n", "var", "config", "=", "make", "(", "FieldConfigArgument", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "v", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "v", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", "\n\n", "mytag", ":=", "extractTag", "(", "field", ".", "Tag", ")", "\n", "if", "inArray", "(", "tags", ",", "mytag", ")", "{", "config", "[", "mytag", "]", "=", "&", "ArgumentConfig", "{", "Type", ":", "getGraphType", "(", "field", ".", "Type", ")", ",", "}", "\n", "}", "\n", "}", "\n", "return", "config", "\n", "}" ]
// lazy way of binding args
[ "lazy", "way", "of", "binding", "args" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/util.go#L148-L162
train
graphql-go/graphql
language/visitor/visitor.go
updateNodeField
func updateNodeField(src interface{}, targetName string, target interface{}) interface{} { var isPtr bool srcVal := reflect.ValueOf(src) // verify condition if srcVal.Kind() == reflect.Ptr { isPtr = true srcVal = srcVal.Elem() } targetVal := reflect.ValueOf(target) if srcVal.Kind() != reflect.Struct { return src } srcFieldValue := srcVal.FieldByName(targetName) if !srcFieldValue.IsValid() || srcFieldValue.Kind() != targetVal.Kind() { return src } if srcFieldValue.CanSet() { if srcFieldValue.Kind() == reflect.Slice { items := reflect.MakeSlice(srcFieldValue.Type(), targetVal.Len(), targetVal.Len()) for index := 0; index < items.Len(); index++ { tmp := targetVal.Index(index).Interface() items.Index(index).Set(reflect.ValueOf(tmp)) } srcFieldValue.Set(items) } else { srcFieldValue.Set(targetVal) } } if isPtr { return srcVal.Addr().Interface() } return srcVal.Interface() }
go
func updateNodeField(src interface{}, targetName string, target interface{}) interface{} { var isPtr bool srcVal := reflect.ValueOf(src) // verify condition if srcVal.Kind() == reflect.Ptr { isPtr = true srcVal = srcVal.Elem() } targetVal := reflect.ValueOf(target) if srcVal.Kind() != reflect.Struct { return src } srcFieldValue := srcVal.FieldByName(targetName) if !srcFieldValue.IsValid() || srcFieldValue.Kind() != targetVal.Kind() { return src } if srcFieldValue.CanSet() { if srcFieldValue.Kind() == reflect.Slice { items := reflect.MakeSlice(srcFieldValue.Type(), targetVal.Len(), targetVal.Len()) for index := 0; index < items.Len(); index++ { tmp := targetVal.Index(index).Interface() items.Index(index).Set(reflect.ValueOf(tmp)) } srcFieldValue.Set(items) } else { srcFieldValue.Set(targetVal) } } if isPtr { return srcVal.Addr().Interface() } return srcVal.Interface() }
[ "func", "updateNodeField", "(", "src", "interface", "{", "}", ",", "targetName", "string", ",", "target", "interface", "{", "}", ")", "interface", "{", "}", "{", "var", "isPtr", "bool", "\n", "srcVal", ":=", "reflect", ".", "ValueOf", "(", "src", ")", "\n", "// verify condition", "if", "srcVal", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "isPtr", "=", "true", "\n", "srcVal", "=", "srcVal", ".", "Elem", "(", ")", "\n", "}", "\n", "targetVal", ":=", "reflect", ".", "ValueOf", "(", "target", ")", "\n", "if", "srcVal", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "src", "\n", "}", "\n", "srcFieldValue", ":=", "srcVal", ".", "FieldByName", "(", "targetName", ")", "\n", "if", "!", "srcFieldValue", ".", "IsValid", "(", ")", "||", "srcFieldValue", ".", "Kind", "(", ")", "!=", "targetVal", ".", "Kind", "(", ")", "{", "return", "src", "\n", "}", "\n\n", "if", "srcFieldValue", ".", "CanSet", "(", ")", "{", "if", "srcFieldValue", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "{", "items", ":=", "reflect", ".", "MakeSlice", "(", "srcFieldValue", ".", "Type", "(", ")", ",", "targetVal", ".", "Len", "(", ")", ",", "targetVal", ".", "Len", "(", ")", ")", "\n", "for", "index", ":=", "0", ";", "index", "<", "items", ".", "Len", "(", ")", ";", "index", "++", "{", "tmp", ":=", "targetVal", ".", "Index", "(", "index", ")", ".", "Interface", "(", ")", "\n", "items", ".", "Index", "(", "index", ")", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "tmp", ")", ")", "\n", "}", "\n", "srcFieldValue", ".", "Set", "(", "items", ")", "\n", "}", "else", "{", "srcFieldValue", ".", "Set", "(", "targetVal", ")", "\n", "}", "\n", "}", "\n", "if", "isPtr", "{", "return", "srcVal", ".", "Addr", "(", ")", ".", "Interface", "(", ")", "\n", "}", "\n", "return", "srcVal", ".", "Interface", "(", ")", "\n", "}" ]
// currently only supports update struct field value
[ "currently", "only", "supports", "update", "struct", "field", "value" ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/visitor/visitor.go#L488-L521
train
graphql-go/graphql
language/visitor/visitor.go
VisitInParallel
func VisitInParallel(visitorOptsSlice ...*VisitorOptions) *VisitorOptions { skipping := map[int]interface{}{} return &VisitorOptions{ Enter: func(p VisitFuncParams) (string, interface{}) { for i, visitorOpts := range visitorOptsSlice { if _, ok := skipping[i]; !ok { node, ok := p.Node.(ast.Node) if !ok { continue } kind := node.GetKind() fn := GetVisitFn(visitorOpts, kind, false) if fn != nil { action, result := fn(p) if action == ActionSkip { skipping[i] = node } else if action == ActionBreak { skipping[i] = ActionBreak } else if action == ActionUpdate { return ActionUpdate, result } } } } return ActionNoChange, nil }, Leave: func(p VisitFuncParams) (string, interface{}) { for i, visitorOpts := range visitorOptsSlice { skippedNode, ok := skipping[i] if !ok { if node, ok := p.Node.(ast.Node); ok { kind := node.GetKind() fn := GetVisitFn(visitorOpts, kind, true) if fn != nil { action, result := fn(p) if action == ActionBreak { skipping[i] = ActionBreak } else if action == ActionUpdate { return ActionUpdate, result } } } } else if skippedNode == p.Node { delete(skipping, i) } } return ActionNoChange, nil }, } }
go
func VisitInParallel(visitorOptsSlice ...*VisitorOptions) *VisitorOptions { skipping := map[int]interface{}{} return &VisitorOptions{ Enter: func(p VisitFuncParams) (string, interface{}) { for i, visitorOpts := range visitorOptsSlice { if _, ok := skipping[i]; !ok { node, ok := p.Node.(ast.Node) if !ok { continue } kind := node.GetKind() fn := GetVisitFn(visitorOpts, kind, false) if fn != nil { action, result := fn(p) if action == ActionSkip { skipping[i] = node } else if action == ActionBreak { skipping[i] = ActionBreak } else if action == ActionUpdate { return ActionUpdate, result } } } } return ActionNoChange, nil }, Leave: func(p VisitFuncParams) (string, interface{}) { for i, visitorOpts := range visitorOptsSlice { skippedNode, ok := skipping[i] if !ok { if node, ok := p.Node.(ast.Node); ok { kind := node.GetKind() fn := GetVisitFn(visitorOpts, kind, true) if fn != nil { action, result := fn(p) if action == ActionBreak { skipping[i] = ActionBreak } else if action == ActionUpdate { return ActionUpdate, result } } } } else if skippedNode == p.Node { delete(skipping, i) } } return ActionNoChange, nil }, } }
[ "func", "VisitInParallel", "(", "visitorOptsSlice", "...", "*", "VisitorOptions", ")", "*", "VisitorOptions", "{", "skipping", ":=", "map", "[", "int", "]", "interface", "{", "}", "{", "}", "\n\n", "return", "&", "VisitorOptions", "{", "Enter", ":", "func", "(", "p", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "for", "i", ",", "visitorOpts", ":=", "range", "visitorOptsSlice", "{", "if", "_", ",", "ok", ":=", "skipping", "[", "i", "]", ";", "!", "ok", "{", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "ast", ".", "Node", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "kind", ":=", "node", ".", "GetKind", "(", ")", "\n", "fn", ":=", "GetVisitFn", "(", "visitorOpts", ",", "kind", ",", "false", ")", "\n", "if", "fn", "!=", "nil", "{", "action", ",", "result", ":=", "fn", "(", "p", ")", "\n", "if", "action", "==", "ActionSkip", "{", "skipping", "[", "i", "]", "=", "node", "\n", "}", "else", "if", "action", "==", "ActionBreak", "{", "skipping", "[", "i", "]", "=", "ActionBreak", "\n", "}", "else", "if", "action", "==", "ActionUpdate", "{", "return", "ActionUpdate", ",", "result", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ActionNoChange", ",", "nil", "\n", "}", ",", "Leave", ":", "func", "(", "p", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "for", "i", ",", "visitorOpts", ":=", "range", "visitorOptsSlice", "{", "skippedNode", ",", "ok", ":=", "skipping", "[", "i", "]", "\n", "if", "!", "ok", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "ast", ".", "Node", ")", ";", "ok", "{", "kind", ":=", "node", ".", "GetKind", "(", ")", "\n", "fn", ":=", "GetVisitFn", "(", "visitorOpts", ",", "kind", ",", "true", ")", "\n", "if", "fn", "!=", "nil", "{", "action", ",", "result", ":=", "fn", "(", "p", ")", "\n", "if", "action", "==", "ActionBreak", "{", "skipping", "[", "i", "]", "=", "ActionBreak", "\n", "}", "else", "if", "action", "==", "ActionUpdate", "{", "return", "ActionUpdate", ",", "result", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "if", "skippedNode", "==", "p", ".", "Node", "{", "delete", "(", "skipping", ",", "i", ")", "\n", "}", "\n", "}", "\n", "return", "ActionNoChange", ",", "nil", "\n", "}", ",", "}", "\n", "}" ]
// VisitInParallel Creates a new visitor instance which delegates to many visitors to run in // parallel. Each visitor will be visited for each node before moving on. // // If a prior visitor edits a node, no following visitors will see that node.
[ "VisitInParallel", "Creates", "a", "new", "visitor", "instance", "which", "delegates", "to", "many", "visitors", "to", "run", "in", "parallel", ".", "Each", "visitor", "will", "be", "visited", "for", "each", "node", "before", "moving", "on", ".", "If", "a", "prior", "visitor", "edits", "a", "node", "no", "following", "visitors", "will", "see", "that", "node", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/visitor/visitor.go#L605-L655
train
graphql-go/graphql
language/visitor/visitor.go
VisitWithTypeInfo
func VisitWithTypeInfo(ttypeInfo typeInfo.TypeInfoI, visitorOpts *VisitorOptions) *VisitorOptions { return &VisitorOptions{ Enter: func(p VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(ast.Node); ok { ttypeInfo.Enter(node) fn := GetVisitFn(visitorOpts, node.GetKind(), false) if fn != nil { action, result := fn(p) if action == ActionUpdate { ttypeInfo.Leave(node) if isNode(result) { if result, ok := result.(ast.Node); ok { ttypeInfo.Enter(result) } } } return action, result } } return ActionNoChange, nil }, Leave: func(p VisitFuncParams) (string, interface{}) { action := ActionNoChange var result interface{} if node, ok := p.Node.(ast.Node); ok { fn := GetVisitFn(visitorOpts, node.GetKind(), true) if fn != nil { action, result = fn(p) } ttypeInfo.Leave(node) } return action, result }, } }
go
func VisitWithTypeInfo(ttypeInfo typeInfo.TypeInfoI, visitorOpts *VisitorOptions) *VisitorOptions { return &VisitorOptions{ Enter: func(p VisitFuncParams) (string, interface{}) { if node, ok := p.Node.(ast.Node); ok { ttypeInfo.Enter(node) fn := GetVisitFn(visitorOpts, node.GetKind(), false) if fn != nil { action, result := fn(p) if action == ActionUpdate { ttypeInfo.Leave(node) if isNode(result) { if result, ok := result.(ast.Node); ok { ttypeInfo.Enter(result) } } } return action, result } } return ActionNoChange, nil }, Leave: func(p VisitFuncParams) (string, interface{}) { action := ActionNoChange var result interface{} if node, ok := p.Node.(ast.Node); ok { fn := GetVisitFn(visitorOpts, node.GetKind(), true) if fn != nil { action, result = fn(p) } ttypeInfo.Leave(node) } return action, result }, } }
[ "func", "VisitWithTypeInfo", "(", "ttypeInfo", "typeInfo", ".", "TypeInfoI", ",", "visitorOpts", "*", "VisitorOptions", ")", "*", "VisitorOptions", "{", "return", "&", "VisitorOptions", "{", "Enter", ":", "func", "(", "p", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "ast", ".", "Node", ")", ";", "ok", "{", "ttypeInfo", ".", "Enter", "(", "node", ")", "\n", "fn", ":=", "GetVisitFn", "(", "visitorOpts", ",", "node", ".", "GetKind", "(", ")", ",", "false", ")", "\n", "if", "fn", "!=", "nil", "{", "action", ",", "result", ":=", "fn", "(", "p", ")", "\n", "if", "action", "==", "ActionUpdate", "{", "ttypeInfo", ".", "Leave", "(", "node", ")", "\n", "if", "isNode", "(", "result", ")", "{", "if", "result", ",", "ok", ":=", "result", ".", "(", "ast", ".", "Node", ")", ";", "ok", "{", "ttypeInfo", ".", "Enter", "(", "result", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "action", ",", "result", "\n", "}", "\n", "}", "\n", "return", "ActionNoChange", ",", "nil", "\n", "}", ",", "Leave", ":", "func", "(", "p", "VisitFuncParams", ")", "(", "string", ",", "interface", "{", "}", ")", "{", "action", ":=", "ActionNoChange", "\n", "var", "result", "interface", "{", "}", "\n", "if", "node", ",", "ok", ":=", "p", ".", "Node", ".", "(", "ast", ".", "Node", ")", ";", "ok", "{", "fn", ":=", "GetVisitFn", "(", "visitorOpts", ",", "node", ".", "GetKind", "(", ")", ",", "true", ")", "\n", "if", "fn", "!=", "nil", "{", "action", ",", "result", "=", "fn", "(", "p", ")", "\n", "}", "\n", "ttypeInfo", ".", "Leave", "(", "node", ")", "\n", "}", "\n", "return", "action", ",", "result", "\n", "}", ",", "}", "\n", "}" ]
// VisitWithTypeInfo Creates a new visitor instance which maintains a provided TypeInfo instance // along with visiting visitor.
[ "VisitWithTypeInfo", "Creates", "a", "new", "visitor", "instance", "which", "maintains", "a", "provided", "TypeInfo", "instance", "along", "with", "visiting", "visitor", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/visitor/visitor.go#L659-L693
train
graphql-go/graphql
language/lexer/lexer.go
readDigits
func readDigits(s *source.Source, start int, firstCode rune, codeLength int) (int, error) { body := s.Body position := start code := firstCode if code >= '0' && code <= '9' { // 0 - 9 for { if code >= '0' && code <= '9' { // 0 - 9 position += codeLength code, codeLength = runeAt(body, position) continue } else { break } } return position, nil } var description string description = fmt.Sprintf("Invalid number, expected digit but got: %v.", printCharCode(code)) return position, gqlerrors.NewSyntaxError(s, position, description) }
go
func readDigits(s *source.Source, start int, firstCode rune, codeLength int) (int, error) { body := s.Body position := start code := firstCode if code >= '0' && code <= '9' { // 0 - 9 for { if code >= '0' && code <= '9' { // 0 - 9 position += codeLength code, codeLength = runeAt(body, position) continue } else { break } } return position, nil } var description string description = fmt.Sprintf("Invalid number, expected digit but got: %v.", printCharCode(code)) return position, gqlerrors.NewSyntaxError(s, position, description) }
[ "func", "readDigits", "(", "s", "*", "source", ".", "Source", ",", "start", "int", ",", "firstCode", "rune", ",", "codeLength", "int", ")", "(", "int", ",", "error", ")", "{", "body", ":=", "s", ".", "Body", "\n", "position", ":=", "start", "\n", "code", ":=", "firstCode", "\n", "if", "code", ">=", "'0'", "&&", "code", "<=", "'9'", "{", "// 0 - 9", "for", "{", "if", "code", ">=", "'0'", "&&", "code", "<=", "'9'", "{", "// 0 - 9", "position", "+=", "codeLength", "\n", "code", ",", "codeLength", "=", "runeAt", "(", "body", ",", "position", ")", "\n", "continue", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "return", "position", ",", "nil", "\n", "}", "\n", "var", "description", "string", "\n", "description", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "printCharCode", "(", "code", ")", ")", "\n", "return", "position", ",", "gqlerrors", ".", "NewSyntaxError", "(", "s", ",", "position", ",", "description", ")", "\n", "}" ]
// Returns the new position in the source after reading digits.
[ "Returns", "the", "new", "position", "in", "the", "source", "after", "reading", "digits", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/lexer/lexer.go#L197-L216
train
graphql-go/graphql
language/lexer/lexer.go
leadingWhitespaceLen
func leadingWhitespaceLen(in string) (n int) { for _, ch := range in { if ch == ' ' || ch == '\t' { n++ } else { break } } return }
go
func leadingWhitespaceLen(in string) (n int) { for _, ch := range in { if ch == ' ' || ch == '\t' { n++ } else { break } } return }
[ "func", "leadingWhitespaceLen", "(", "in", "string", ")", "(", "n", "int", ")", "{", "for", "_", ",", "ch", ":=", "range", "in", "{", "if", "ch", "==", "' '", "||", "ch", "==", "'\\t'", "{", "n", "++", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// leadingWhitespaceLen returns count of whitespace characters on given line.
[ "leadingWhitespaceLen", "returns", "count", "of", "whitespace", "characters", "on", "given", "line", "." ]
199d20bbfed70dae8c7d4619d4e0d339ce738b43
https://github.com/graphql-go/graphql/blob/199d20bbfed70dae8c7d4619d4e0d339ce738b43/language/lexer/lexer.go#L422-L431
train