param.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // Copyright (c) 2019 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package dig
  21. import (
  22. "errors"
  23. "fmt"
  24. "reflect"
  25. "go.uber.org/dig/internal/dot"
  26. )
  27. // The param interface represents a dependency for a constructor.
  28. //
  29. // The following implementations exist:
  30. // paramList All arguments of the constructor.
  31. // paramSingle An explicitly requested type.
  32. // paramObject dig.In struct where each field in the struct can be another
  33. // param.
  34. // paramGroupedSlice
  35. // A slice consuming a value group. This will receive all
  36. // values produced with a `group:".."` tag with the same name
  37. // as a slice.
  38. type param interface {
  39. fmt.Stringer
  40. // Builds this dependency and any of its dependencies from the provided
  41. // Container.
  42. //
  43. // This MAY panic if the param does not produce a single value.
  44. Build(containerStore) (reflect.Value, error)
  45. // DotParam returns a slice of dot.Param(s).
  46. DotParam() []*dot.Param
  47. }
  48. var (
  49. _ param = paramSingle{}
  50. _ param = paramObject{}
  51. _ param = paramList{}
  52. _ param = paramGroupedSlice{}
  53. )
  54. // newParam builds a param from the given type. If the provided type is a
  55. // dig.In struct, an paramObject will be returned.
  56. func newParam(t reflect.Type) (param, error) {
  57. switch {
  58. case IsOut(t) || (t.Kind() == reflect.Ptr && IsOut(t.Elem())) || embedsType(t, _outPtrType):
  59. return nil, errf("cannot depend on result objects", "%v embeds a dig.Out", t)
  60. case IsIn(t):
  61. return newParamObject(t)
  62. case embedsType(t, _inPtrType):
  63. return nil, errf(
  64. "cannot build a parameter object by embedding *dig.In, embed dig.In instead",
  65. "%v embeds *dig.In", t)
  66. case t.Kind() == reflect.Ptr && IsIn(t.Elem()):
  67. return nil, errf(
  68. "cannot depend on a pointer to a parameter object, use a value instead",
  69. "%v is a pointer to a struct that embeds dig.In", t)
  70. default:
  71. return paramSingle{Type: t}, nil
  72. }
  73. }
  74. // paramVisitor visits every param in a param tree, allowing tracking state at
  75. // each level.
  76. type paramVisitor interface {
  77. // Visit is called on the param being visited.
  78. //
  79. // If Visit returns a non-nil paramVisitor, that paramVisitor visits all
  80. // the child params of this param.
  81. Visit(param) paramVisitor
  82. // We can implement AnnotateWithField and AnnotateWithPosition like
  83. // resultVisitor if we need to track that information in the future.
  84. }
  85. // paramVisitorFunc is a paramVisitor that visits param in a tree with the
  86. // return value deciding whether the descendants of this param should be
  87. // recursed into.
  88. type paramVisitorFunc func(param) (recurse bool)
  89. func (f paramVisitorFunc) Visit(p param) paramVisitor {
  90. if f(p) {
  91. return f
  92. }
  93. return nil
  94. }
  95. // walkParam walks the param tree for the given param with the provided
  96. // visitor.
  97. //
  98. // paramVisitor.Visit will be called on the provided param and if a non-nil
  99. // paramVisitor is received, this param's descendants will be walked with that
  100. // visitor.
  101. //
  102. // This is very similar to how go/ast.Walk works.
  103. func walkParam(p param, v paramVisitor) {
  104. v = v.Visit(p)
  105. if v == nil {
  106. return
  107. }
  108. switch par := p.(type) {
  109. case paramSingle, paramGroupedSlice:
  110. // No sub-results
  111. case paramObject:
  112. for _, f := range par.Fields {
  113. walkParam(f.Param, v)
  114. }
  115. case paramList:
  116. for _, p := range par.Params {
  117. walkParam(p, v)
  118. }
  119. default:
  120. panic(fmt.Sprintf(
  121. "It looks like you have found a bug in dig. "+
  122. "Please file an issue at https://github.com/uber-go/dig/issues/ "+
  123. "and provide the following message: "+
  124. "received unknown param type %T", p))
  125. }
  126. }
  127. // paramList holds all arguments of the constructor as params.
  128. //
  129. // NOTE: Build() MUST NOT be called on paramList. Instead, BuildList
  130. // must be called.
  131. type paramList struct {
  132. ctype reflect.Type // type of the constructor
  133. Params []param
  134. }
  135. func (pl paramList) DotParam() []*dot.Param {
  136. var types []*dot.Param
  137. for _, param := range pl.Params {
  138. types = append(types, param.DotParam()...)
  139. }
  140. return types
  141. }
  142. // newParamList builds a paramList from the provided constructor type.
  143. //
  144. // Variadic arguments of a constructor are ignored and not included as
  145. // dependencies.
  146. func newParamList(ctype reflect.Type) (paramList, error) {
  147. numArgs := ctype.NumIn()
  148. if ctype.IsVariadic() {
  149. // NOTE: If the function is variadic, we skip the last argument
  150. // because we're not filling variadic arguments yet. See #120.
  151. numArgs--
  152. }
  153. pl := paramList{
  154. ctype: ctype,
  155. Params: make([]param, 0, numArgs),
  156. }
  157. for i := 0; i < numArgs; i++ {
  158. p, err := newParam(ctype.In(i))
  159. if err != nil {
  160. return pl, errf("bad argument %d", i+1, err)
  161. }
  162. pl.Params = append(pl.Params, p)
  163. }
  164. return pl, nil
  165. }
  166. func (pl paramList) Build(containerStore) (reflect.Value, error) {
  167. panic("It looks like you have found a bug in dig. " +
  168. "Please file an issue at https://github.com/uber-go/dig/issues/ " +
  169. "and provide the following message: " +
  170. "paramList.Build() must never be called")
  171. }
  172. // BuildList returns an ordered list of values which may be passed directly
  173. // to the underlying constructor.
  174. func (pl paramList) BuildList(c containerStore) ([]reflect.Value, error) {
  175. args := make([]reflect.Value, len(pl.Params))
  176. for i, p := range pl.Params {
  177. var err error
  178. args[i], err = p.Build(c)
  179. if err != nil {
  180. return nil, err
  181. }
  182. }
  183. return args, nil
  184. }
  185. // paramSingle is an explicitly requested type, optionally with a name.
  186. //
  187. // This object must be present in the graph as-is unless it's specified as
  188. // optional.
  189. type paramSingle struct {
  190. Name string
  191. Optional bool
  192. Type reflect.Type
  193. }
  194. func (ps paramSingle) DotParam() []*dot.Param {
  195. return []*dot.Param{
  196. {
  197. Node: &dot.Node{
  198. Type: ps.Type,
  199. Name: ps.Name,
  200. },
  201. Optional: ps.Optional,
  202. },
  203. }
  204. }
  205. func (ps paramSingle) Build(c containerStore) (reflect.Value, error) {
  206. if v, ok := c.getValue(ps.Name, ps.Type); ok {
  207. return v, nil
  208. }
  209. providers := c.getValueProviders(ps.Name, ps.Type)
  210. if len(providers) == 0 {
  211. if ps.Optional {
  212. return reflect.Zero(ps.Type), nil
  213. }
  214. return _noValue, newErrMissingTypes(c, key{name: ps.Name, t: ps.Type})
  215. }
  216. for _, n := range providers {
  217. err := n.Call(c)
  218. if err == nil {
  219. continue
  220. }
  221. // If we're missing dependencies but the parameter itself is optional,
  222. // we can just move on.
  223. if _, ok := err.(errMissingDependencies); ok && ps.Optional {
  224. return reflect.Zero(ps.Type), nil
  225. }
  226. return _noValue, errParamSingleFailed{
  227. CtorID: n.ID(),
  228. Key: key{t: ps.Type, name: ps.Name},
  229. Reason: err,
  230. }
  231. }
  232. // If we get here, it's impossible for the value to be absent from the
  233. // container.
  234. v, _ := c.getValue(ps.Name, ps.Type)
  235. return v, nil
  236. }
  237. // paramObject is a dig.In struct where each field is another param.
  238. //
  239. // This object is not expected in the graph as-is.
  240. type paramObject struct {
  241. Type reflect.Type
  242. Fields []paramObjectField
  243. }
  244. func (po paramObject) DotParam() []*dot.Param {
  245. var types []*dot.Param
  246. for _, field := range po.Fields {
  247. types = append(types, field.DotParam()...)
  248. }
  249. return types
  250. }
  251. // newParamObject builds an paramObject from the provided type. The type MUST
  252. // be a dig.In struct.
  253. func newParamObject(t reflect.Type) (paramObject, error) {
  254. po := paramObject{Type: t}
  255. for i := 0; i < t.NumField(); i++ {
  256. f := t.Field(i)
  257. if f.Type == _inType {
  258. // Skip over the dig.In embed.
  259. continue
  260. }
  261. pof, err := newParamObjectField(i, f)
  262. if err != nil {
  263. return po, errf("bad field %q of %v", f.Name, t, err)
  264. }
  265. po.Fields = append(po.Fields, pof)
  266. }
  267. return po, nil
  268. }
  269. func (po paramObject) Build(c containerStore) (reflect.Value, error) {
  270. dest := reflect.New(po.Type).Elem()
  271. for _, f := range po.Fields {
  272. v, err := f.Build(c)
  273. if err != nil {
  274. return dest, err
  275. }
  276. dest.Field(f.FieldIndex).Set(v)
  277. }
  278. return dest, nil
  279. }
  280. // paramObjectField is a single field of a dig.In struct.
  281. type paramObjectField struct {
  282. // Name of the field in the struct.
  283. FieldName string
  284. // Index of this field in the target struct.
  285. //
  286. // We need to track this separately because not all fields of the
  287. // struct map to params.
  288. FieldIndex int
  289. // The dependency requested by this field.
  290. Param param
  291. }
  292. func (pof paramObjectField) DotParam() []*dot.Param {
  293. return pof.Param.DotParam()
  294. }
  295. func newParamObjectField(idx int, f reflect.StructField) (paramObjectField, error) {
  296. pof := paramObjectField{
  297. FieldName: f.Name,
  298. FieldIndex: idx,
  299. }
  300. var p param
  301. switch {
  302. case f.PkgPath != "":
  303. return pof, errf(
  304. "unexported fields not allowed in dig.In, did you mean to export %q (%v)?",
  305. f.Name, f.Type)
  306. case f.Tag.Get(_groupTag) != "":
  307. var err error
  308. p, err = newParamGroupedSlice(f)
  309. if err != nil {
  310. return pof, err
  311. }
  312. default:
  313. var err error
  314. p, err = newParam(f.Type)
  315. if err != nil {
  316. return pof, err
  317. }
  318. }
  319. if ps, ok := p.(paramSingle); ok {
  320. ps.Name = f.Tag.Get(_nameTag)
  321. var err error
  322. ps.Optional, err = isFieldOptional(f)
  323. if err != nil {
  324. return pof, err
  325. }
  326. p = ps
  327. }
  328. pof.Param = p
  329. return pof, nil
  330. }
  331. func (pof paramObjectField) Build(c containerStore) (reflect.Value, error) {
  332. v, err := pof.Param.Build(c)
  333. if err != nil {
  334. return v, err
  335. }
  336. return v, nil
  337. }
  338. // paramGroupedSlice is a param which produces a slice of values with the same
  339. // group name.
  340. type paramGroupedSlice struct {
  341. // Name of the group as specified in the `group:".."` tag.
  342. Group string
  343. // Type of the slice.
  344. Type reflect.Type
  345. }
  346. func (pt paramGroupedSlice) DotParam() []*dot.Param {
  347. return []*dot.Param{
  348. {
  349. Node: &dot.Node{
  350. Type: pt.Type,
  351. Group: pt.Group,
  352. },
  353. },
  354. }
  355. }
  356. // newParamGroupedSlice builds a paramGroupedSlice from the provided type with
  357. // the given name.
  358. //
  359. // The type MUST be a slice type.
  360. func newParamGroupedSlice(f reflect.StructField) (paramGroupedSlice, error) {
  361. g, err := parseGroupString(f.Tag.Get(_groupTag))
  362. if err != nil {
  363. return paramGroupedSlice{}, err
  364. }
  365. pg := paramGroupedSlice{Group: g.Name, Type: f.Type}
  366. name := f.Tag.Get(_nameTag)
  367. optional, _ := isFieldOptional(f)
  368. switch {
  369. case f.Type.Kind() != reflect.Slice:
  370. return pg, errf("value groups may be consumed as slices only",
  371. "field %q (%v) is not a slice", f.Name, f.Type)
  372. case g.Flatten:
  373. return pg, errf("cannot use flatten in parameter value groups",
  374. "field %q (%v) specifies flatten", f.Name, f.Type)
  375. case name != "":
  376. return pg, errf(
  377. "cannot use named values with value groups",
  378. "name:%q requested with group:%q", name, pg.Group)
  379. case optional:
  380. return pg, errors.New("value groups cannot be optional")
  381. }
  382. return pg, nil
  383. }
  384. func (pt paramGroupedSlice) Build(c containerStore) (reflect.Value, error) {
  385. for _, n := range c.getGroupProviders(pt.Group, pt.Type.Elem()) {
  386. if err := n.Call(c); err != nil {
  387. return _noValue, errParamGroupFailed{
  388. CtorID: n.ID(),
  389. Key: key{group: pt.Group, t: pt.Type.Elem()},
  390. Reason: err,
  391. }
  392. }
  393. }
  394. items := c.getValueGroup(pt.Group, pt.Type.Elem())
  395. result := reflect.MakeSlice(pt.Type, len(items), len(items))
  396. for i, v := range items {
  397. result.Index(i).Set(v)
  398. }
  399. return result, nil
  400. }