semtypes.nim 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # this module does the semantic checking of type declarations
  10. # included from sem.nim
  11. const
  12. errStringOrIdentNodeExpected = "string or ident node expected"
  13. errStringLiteralExpected = "string literal expected"
  14. errIntLiteralExpected = "integer literal expected"
  15. errWrongNumberOfVariables = "wrong number of variables"
  16. errDuplicateAliasInEnumX = "duplicate value in enum '$1'"
  17. errOverflowInEnumX = "The enum '$1' exceeds its maximum value ($2)"
  18. errOrdinalTypeExpected = "ordinal type expected; given: $1"
  19. errSetTooBig = "set is too large; use `std/sets` for ordinal types with more than 2^16 elements"
  20. errBaseTypeMustBeOrdinal = "base type of a set must be an ordinal"
  21. errInheritanceOnlyWithNonFinalObjects = "inheritance only works with non-final objects"
  22. errXExpectsOneTypeParam = "'$1' expects one type parameter"
  23. errArrayExpectsTwoTypeParams = "array expects two type parameters"
  24. errInvalidVisibilityX = "invalid visibility: '$1'"
  25. errXCannotBeAssignedTo = "'$1' cannot be assigned to"
  26. errIteratorNotAllowed = "iterators can only be defined at the module's top level"
  27. errXNeedsReturnType = "$1 needs a return type"
  28. errNoReturnTypeDeclared = "no return type declared"
  29. errTIsNotAConcreteType = "'$1' is not a concrete type"
  30. errTypeExpected = "type expected"
  31. errXOnlyAtModuleScope = "'$1' is only allowed at top level"
  32. errDuplicateCaseLabel = "duplicate case label"
  33. errMacroBodyDependsOnGenericTypes = "the macro body cannot be compiled, " &
  34. "because the parameter '$1' has a generic type"
  35. errIllegalRecursionInTypeX = "illegal recursion in type '$1'"
  36. errNoGenericParamsAllowedForX = "no generic parameters allowed for $1"
  37. errInOutFlagNotExtern = "the '$1' modifier can be used only with imported types"
  38. proc newOrPrevType(kind: TTypeKind, prev: PType, c: PContext, son: sink PType): PType =
  39. if prev == nil or prev.kind == tyGenericBody:
  40. result = newTypeS(kind, c, son)
  41. else:
  42. result = prev
  43. result.setSon(son)
  44. if result.kind == tyForward: result.kind = kind
  45. #if kind == tyError: result.flags.incl tfCheckedForDestructor
  46. proc newOrPrevType(kind: TTypeKind, prev: PType, c: PContext): PType =
  47. if prev == nil or prev.kind == tyGenericBody:
  48. result = newTypeS(kind, c)
  49. else:
  50. result = prev
  51. if result.kind == tyForward: result.kind = kind
  52. proc newConstraint(c: PContext, k: TTypeKind): PType =
  53. result = newTypeS(tyBuiltInTypeClass, c)
  54. result.flags.incl tfCheckedForDestructor
  55. result.addSonSkipIntLit(newTypeS(k, c), c.idgen)
  56. proc semEnum(c: PContext, n: PNode, prev: PType): PType =
  57. if n.len == 0: return newConstraint(c, tyEnum)
  58. elif n.len == 1:
  59. # don't create an empty tyEnum; fixes #3052
  60. return errorType(c)
  61. var
  62. counter, x: BiggestInt = 0
  63. e: PSym = nil
  64. base: PType = nil
  65. identToReplace: ptr PNode = nil
  66. counterSet = initPackedSet[BiggestInt]()
  67. counter = 0
  68. base = nil
  69. result = newOrPrevType(tyEnum, prev, c)
  70. result.n = newNodeI(nkEnumTy, n.info)
  71. checkMinSonsLen(n, 1, c.config)
  72. if n[0].kind != nkEmpty:
  73. base = semTypeNode(c, n[0][0], nil)
  74. if base.kind != tyEnum:
  75. localError(c.config, n[0].info, "inheritance only works with an enum")
  76. counter = toInt64(lastOrd(c.config, base)) + 1
  77. rawAddSon(result, base)
  78. let isPure = result.sym != nil and sfPure in result.sym.flags
  79. var symbols: TStrTable = initStrTable()
  80. var hasNull = false
  81. for i in 1..<n.len:
  82. if n[i].kind == nkEmpty: continue
  83. var useAutoCounter = false
  84. case n[i].kind
  85. of nkEnumFieldDef:
  86. if n[i][0].kind == nkPragmaExpr:
  87. e = newSymS(skEnumField, n[i][0][0], c)
  88. identToReplace = addr n[i][0][0]
  89. pragma(c, e, n[i][0][1], enumFieldPragmas)
  90. else:
  91. e = newSymS(skEnumField, n[i][0], c)
  92. identToReplace = addr n[i][0]
  93. var v = semConstExpr(c, n[i][1])
  94. var strVal: PNode = nil
  95. case skipTypes(v.typ, abstractInst-{tyTypeDesc}).kind
  96. of tyTuple:
  97. if v.len == 2:
  98. strVal = v[1] # second tuple part is the string value
  99. if skipTypes(strVal.typ, abstractInst).kind in {tyString, tyCstring}:
  100. if not isOrdinalType(v[0].typ, allowEnumWithHoles=true):
  101. localError(c.config, v[0].info, errOrdinalTypeExpected % typeToString(v[0].typ, preferDesc))
  102. x = toInt64(getOrdValue(v[0])) # first tuple part is the ordinal
  103. n[i][1][0] = newIntTypeNode(x, getSysType(c.graph, unknownLineInfo, tyInt))
  104. else:
  105. localError(c.config, strVal.info, errStringLiteralExpected)
  106. else:
  107. localError(c.config, v.info, errWrongNumberOfVariables)
  108. of tyString, tyCstring:
  109. strVal = v
  110. x = counter
  111. useAutoCounter = true
  112. else:
  113. if isOrdinalType(v.typ, allowEnumWithHoles=true):
  114. x = toInt64(getOrdValue(v))
  115. n[i][1] = newIntTypeNode(x, getSysType(c.graph, unknownLineInfo, tyInt))
  116. else:
  117. localError(c.config, v.info, errOrdinalTypeExpected % typeToString(v.typ, preferDesc))
  118. if i != 1:
  119. if x != counter: incl(result.flags, tfEnumHasHoles)
  120. e.ast = strVal # might be nil
  121. counter = x
  122. of nkSym:
  123. e = n[i].sym
  124. useAutoCounter = true
  125. of nkIdent, nkAccQuoted:
  126. e = newSymS(skEnumField, n[i], c)
  127. identToReplace = addr n[i]
  128. useAutoCounter = true
  129. of nkPragmaExpr:
  130. e = newSymS(skEnumField, n[i][0], c)
  131. pragma(c, e, n[i][1], enumFieldPragmas)
  132. identToReplace = addr n[i][0]
  133. useAutoCounter = true
  134. else:
  135. illFormedAst(n[i], c.config)
  136. if useAutoCounter:
  137. while counter in counterSet and counter != high(typeof(counter)):
  138. inc counter
  139. counterSet.incl counter
  140. elif counterSet.containsOrIncl(counter):
  141. localError(c.config, n[i].info, errDuplicateAliasInEnumX % e.name.s)
  142. e.typ = result
  143. e.position = int(counter)
  144. let symNode = newSymNode(e)
  145. if identToReplace != nil and c.config.cmd notin cmdDocLike:
  146. # A hack to produce documentation for enum fields.
  147. identToReplace[] = symNode
  148. if e.position == 0: hasNull = true
  149. if result.sym != nil and sfExported in result.sym.flags:
  150. e.flags.incl {sfUsed, sfExported}
  151. result.n.add symNode
  152. styleCheckDef(c, e)
  153. onDef(e.info, e)
  154. suggestSym(c.graph, e.info, e, c.graph.usageSym)
  155. if sfGenSym notin e.flags:
  156. if not isPure:
  157. addInterfaceOverloadableSymAt(c, c.currentScope, e)
  158. else:
  159. declarePureEnumField(c, e)
  160. if (let conflict = strTableInclReportConflict(symbols, e); conflict != nil):
  161. wrongRedefinition(c, e.info, e.name.s, conflict.info)
  162. if counter == high(typeof(counter)):
  163. if i > 1 and result.n[i-2].sym.position == high(int):
  164. localError(c.config, n[i].info, errOverflowInEnumX % [e.name.s, $high(typeof(counter))])
  165. else:
  166. inc(counter)
  167. if isPure and sfExported in result.sym.flags:
  168. addPureEnum(c, LazySym(sym: result.sym))
  169. if tfNotNil in e.typ.flags and not hasNull:
  170. result.flags.incl tfRequiresInit
  171. setToStringProc(c.graph, result, genEnumToStrProc(result, n.info, c.graph, c.idgen))
  172. proc semSet(c: PContext, n: PNode, prev: PType): PType =
  173. result = newOrPrevType(tySet, prev, c)
  174. if n.len == 2 and n[1].kind != nkEmpty:
  175. var base = semTypeNode(c, n[1], nil)
  176. addSonSkipIntLit(result, base, c.idgen)
  177. if base.kind in {tyGenericInst, tyAlias, tySink}: base = skipModifier(base)
  178. if base.kind notin {tyGenericParam, tyGenericInvocation}:
  179. if base.kind == tyForward:
  180. c.skipTypes.add n
  181. elif not isOrdinalType(base, allowEnumWithHoles = true):
  182. localError(c.config, n.info, errOrdinalTypeExpected % typeToString(base, preferDesc))
  183. elif lengthOrd(c.config, base) > MaxSetElements:
  184. localError(c.config, n.info, errSetTooBig)
  185. else:
  186. localError(c.config, n.info, errXExpectsOneTypeParam % "set")
  187. addSonSkipIntLit(result, errorType(c), c.idgen)
  188. proc semContainerArg(c: PContext; n: PNode, kindStr: string; result: PType) =
  189. if n.len == 2:
  190. var base = semTypeNode(c, n[1], nil)
  191. if base.kind == tyVoid:
  192. localError(c.config, n.info, errTIsNotAConcreteType % typeToString(base))
  193. addSonSkipIntLit(result, base, c.idgen)
  194. else:
  195. localError(c.config, n.info, errXExpectsOneTypeParam % kindStr)
  196. addSonSkipIntLit(result, errorType(c), c.idgen)
  197. proc semContainer(c: PContext, n: PNode, kind: TTypeKind, kindStr: string,
  198. prev: PType): PType =
  199. result = newOrPrevType(kind, prev, c)
  200. semContainerArg(c, n, kindStr, result)
  201. proc semVarargs(c: PContext, n: PNode, prev: PType): PType =
  202. result = newOrPrevType(tyVarargs, prev, c)
  203. if n.len == 2 or n.len == 3:
  204. var base = semTypeNode(c, n[1], nil)
  205. addSonSkipIntLit(result, base, c.idgen)
  206. if n.len == 3:
  207. result.n = newIdentNode(considerQuotedIdent(c, n[2]), n[2].info)
  208. else:
  209. localError(c.config, n.info, errXExpectsOneTypeParam % "varargs")
  210. addSonSkipIntLit(result, errorType(c), c.idgen)
  211. proc semVarOutType(c: PContext, n: PNode, prev: PType; flags: TTypeFlags): PType =
  212. if n.len == 1:
  213. result = newOrPrevType(tyVar, prev, c)
  214. result.flags = flags
  215. var base = semTypeNode(c, n[0], nil)
  216. if base.kind == tyTypeDesc and not isSelf(base):
  217. base = base[0]
  218. if base.kind == tyVar:
  219. localError(c.config, n.info, "type 'var var' is not allowed")
  220. base = base[0]
  221. addSonSkipIntLit(result, base, c.idgen)
  222. else:
  223. result = newConstraint(c, tyVar)
  224. proc isRecursiveType(t: PType, cycleDetector: var IntSet): bool =
  225. if t == nil:
  226. return false
  227. if cycleDetector.containsOrIncl(t.id):
  228. return true
  229. case t.kind
  230. of tyAlias, tyGenericInst, tyDistinct:
  231. return isRecursiveType(t.skipModifier, cycleDetector)
  232. else:
  233. return false
  234. proc fitDefaultNode(c: PContext, n: PNode): PType =
  235. inc c.inStaticContext
  236. let expectedType = if n[^2].kind != nkEmpty: semTypeNode(c, n[^2], nil) else: nil
  237. n[^1] = semConstExpr(c, n[^1], expectedType = expectedType)
  238. let oldType = n[^1].typ
  239. n[^1].flags.incl nfSem
  240. if n[^2].kind != nkEmpty:
  241. if expectedType != nil and oldType != expectedType:
  242. n[^1] = fitNodeConsiderViewType(c, expectedType, n[^1], n[^1].info)
  243. changeType(c, n[^1], expectedType, true) # infer types for default fields value
  244. # bug #22926; be cautious that it uses `semConstExpr` to
  245. # evaulate the default fields; it's only natural to use
  246. # `changeType` to infer types for constant values
  247. # that's also the reason why we don't use `semExpr` to check
  248. # the type since two overlapping error messages might be produced
  249. result = n[^1].typ
  250. else:
  251. result = n[^1].typ
  252. # xxx any troubles related to defaults fields, consult `semConst` for a potential answer
  253. if n[^1].kind != nkNilLit:
  254. typeAllowedCheck(c, n.info, result, skConst, {taProcContextIsNotMacro, taIsDefaultField})
  255. dec c.inStaticContext
  256. proc isRecursiveType*(t: PType): bool =
  257. # handle simple recusive types before typeFinalPass
  258. var cycleDetector = initIntSet()
  259. isRecursiveType(t, cycleDetector)
  260. proc addSonSkipIntLitChecked(c: PContext; father, son: PType; it: PNode, id: IdGenerator) =
  261. let s = son.skipIntLit(id)
  262. father.add(s)
  263. if isRecursiveType(s):
  264. localError(c.config, it.info, "illegal recursion in type '" & typeToString(s) & "'")
  265. else:
  266. propagateToOwner(father, s)
  267. proc semDistinct(c: PContext, n: PNode, prev: PType): PType =
  268. if n.len == 0: return newConstraint(c, tyDistinct)
  269. result = newOrPrevType(tyDistinct, prev, c)
  270. addSonSkipIntLitChecked(c, result, semTypeNode(c, n[0], nil), n[0], c.idgen)
  271. if n.len > 1: result.n = n[1]
  272. proc semRangeAux(c: PContext, n: PNode, prev: PType): PType =
  273. assert isRange(n)
  274. checkSonsLen(n, 3, c.config)
  275. result = newOrPrevType(tyRange, prev, c)
  276. result.n = newNodeI(nkRange, n.info)
  277. # always create a 'valid' range type, but overwrite it later
  278. # because 'semExprWithType' can raise an exception. See bug #6895.
  279. addSonSkipIntLit(result, errorType(c), c.idgen)
  280. if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty):
  281. localError(c.config, n.info, "range is empty")
  282. var range: array[2, PNode]
  283. # XXX this is still a hard compilation in a generic context, this can
  284. # result in unresolved generic parameters being treated like real types
  285. range[0] = semExprWithType(c, n[1], {efDetermineType})
  286. range[1] = semExprWithType(c, n[2], {efDetermineType})
  287. var rangeT: array[2, PType] = default(array[2, PType])
  288. for i in 0..1:
  289. rangeT[i] = range[i].typ.skipTypes({tyStatic}).skipIntLit(c.idgen)
  290. let hasUnknownTypes = c.inGenericContext > 0 and
  291. (rangeT[0].kind == tyFromExpr or rangeT[1].kind == tyFromExpr)
  292. if not hasUnknownTypes:
  293. if not sameType(rangeT[0].skipTypes({tyRange}), rangeT[1].skipTypes({tyRange})):
  294. typeMismatch(c.config, n.info, rangeT[0], rangeT[1], n)
  295. elif not isOrdinalType(rangeT[0]) and rangeT[0].kind notin {tyFloat..tyFloat128} or
  296. rangeT[0].kind == tyBool:
  297. localError(c.config, n.info, "ordinal or float type expected, but got " & typeToString(rangeT[0]))
  298. elif enumHasHoles(rangeT[0]):
  299. localError(c.config, n.info, "enum '$1' has holes" % typeToString(rangeT[0]))
  300. for i in 0..1:
  301. if hasUnresolvedArgs(c, range[i]):
  302. result.n.add makeStaticExpr(c, range[i])
  303. result.flags.incl tfUnresolved
  304. else:
  305. result.n.add semConstExpr(c, range[i])
  306. if result.n[i].kind in {nkFloatLit..nkFloat64Lit} and result.n[i].floatVal.isNaN:
  307. localError(c.config, n.info, "NaN is not a valid range " & (if i == 0: "start" else: "end"))
  308. if weakLeValue(result.n[0], result.n[1]) == impNo:
  309. localError(c.config, n.info, "range is empty")
  310. result[0] = rangeT[0]
  311. proc semRange(c: PContext, n: PNode, prev: PType): PType =
  312. result = nil
  313. if n.len == 2:
  314. if isRange(n[1]):
  315. result = semRangeAux(c, n[1], prev)
  316. if not isDefined(c.config, "nimPreviewRangeDefault"):
  317. let n = result.n
  318. if n[0].kind in {nkCharLit..nkUInt64Lit} and n[0].intVal > 0:
  319. incl(result.flags, tfRequiresInit)
  320. elif n[1].kind in {nkCharLit..nkUInt64Lit} and n[1].intVal < 0:
  321. incl(result.flags, tfRequiresInit)
  322. elif n[0].kind in {nkFloatLit..nkFloat64Lit} and
  323. n[0].floatVal > 0.0:
  324. incl(result.flags, tfRequiresInit)
  325. elif n[1].kind in {nkFloatLit..nkFloat64Lit} and
  326. n[1].floatVal < 0.0:
  327. incl(result.flags, tfRequiresInit)
  328. else:
  329. if n[1].kind == nkInfix and considerQuotedIdent(c, n[1][0]).s == "..<":
  330. localError(c.config, n[0].info, "range types need to be constructed with '..', '..<' is not supported")
  331. else:
  332. localError(c.config, n[0].info, "expected range")
  333. result = newOrPrevType(tyError, prev, c)
  334. else:
  335. localError(c.config, n.info, errXExpectsOneTypeParam % "range")
  336. result = newOrPrevType(tyError, prev, c)
  337. proc semArrayIndexConst(c: PContext, e: PNode, info: TLineInfo): PType =
  338. let x = semConstExpr(c, e)
  339. if x.kind in {nkIntLit..nkUInt64Lit}:
  340. result = makeRangeType(c, 0, x.intVal-1, info,
  341. x.typ.skipTypes({tyTypeDesc}))
  342. else:
  343. result = x.typ.skipTypes({tyTypeDesc})
  344. proc semArrayIndex(c: PContext, n: PNode): PType =
  345. if isRange(n):
  346. result = semRangeAux(c, n, nil)
  347. elif n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.s == "..<":
  348. result = errorType(c)
  349. else:
  350. # XXX this is still a hard compilation in a generic context, this can
  351. # result in unresolved generic parameters being treated like real types
  352. let e = semExprWithType(c, n, {efDetermineType})
  353. if e.typ.kind == tyFromExpr:
  354. result = makeRangeWithStaticExpr(c, e.typ.n)
  355. elif e.kind in {nkIntLit..nkUInt64Lit}:
  356. if e.intVal < 0:
  357. localError(c.config, n.info,
  358. "Array length can't be negative, but was " & $e.intVal)
  359. result = makeRangeType(c, 0, e.intVal-1, n.info, e.typ)
  360. elif e.kind == nkSym and (e.typ.kind == tyStatic or e.typ.kind == tyTypeDesc):
  361. if e.typ.kind == tyStatic:
  362. if e.sym.ast != nil:
  363. return semArrayIndex(c, e.sym.ast)
  364. if e.typ.skipModifier.kind != tyGenericParam and not isOrdinalType(e.typ.skipModifier):
  365. let info = if n.safeLen > 1: n[1].info else: n.info
  366. localError(c.config, info, errOrdinalTypeExpected % typeToString(e.typ, preferDesc))
  367. result = makeRangeWithStaticExpr(c, e)
  368. if c.inGenericContext > 0: result.flags.incl tfUnresolved
  369. else:
  370. result = e.typ.skipTypes({tyTypeDesc})
  371. result.flags.incl tfImplicitStatic
  372. elif e.kind in (nkCallKinds + {nkBracketExpr}) and hasUnresolvedArgs(c, e):
  373. if not isOrdinalType(e.typ.skipTypes({tyStatic, tyAlias, tyGenericInst, tySink})):
  374. localError(c.config, n[1].info, errOrdinalTypeExpected % typeToString(e.typ, preferDesc))
  375. # This is an int returning call, depending on an
  376. # yet unknown generic param (see tuninstantiatedgenericcalls).
  377. # We are going to construct a range type that will be
  378. # properly filled-out in semtypinst (see how tyStaticExpr
  379. # is handled there).
  380. result = makeRangeWithStaticExpr(c, e)
  381. elif e.kind == nkIdent:
  382. result = e.typ.skipTypes({tyTypeDesc})
  383. else:
  384. result = semArrayIndexConst(c, e, n.info)
  385. #localError(c.config, n[1].info, errConstExprExpected)
  386. proc semArray(c: PContext, n: PNode, prev: PType): PType =
  387. var base: PType
  388. if n.len == 3:
  389. # 3 = length(array indx base)
  390. let indx = semArrayIndex(c, n[1])
  391. var indxB = indx
  392. if indxB.kind in {tyGenericInst, tyAlias, tySink}: indxB = skipModifier(indxB)
  393. if indxB.kind notin {tyGenericParam, tyStatic, tyFromExpr} and
  394. tfUnresolved notin indxB.flags:
  395. if not isOrdinalType(indxB):
  396. localError(c.config, n[1].info, errOrdinalTypeExpected % typeToString(indxB, preferDesc))
  397. elif enumHasHoles(indxB):
  398. localError(c.config, n[1].info, "enum '$1' has holes" %
  399. typeToString(indxB.skipTypes({tyRange})))
  400. elif indxB.kind != tyRange and
  401. lengthOrd(c.config, indxB) > high(uint16).int:
  402. # assume range type is intentional
  403. localError(c.config, n[1].info,
  404. "index type '$1' for array is too large" % typeToString(indxB))
  405. base = semTypeNode(c, n[2], nil)
  406. # ensure we only construct a tyArray when there was no error (bug #3048):
  407. # bug #6682: Do not propagate initialization requirements etc for the
  408. # index type:
  409. result = newOrPrevType(tyArray, prev, c, indx)
  410. addSonSkipIntLit(result, base, c.idgen)
  411. else:
  412. localError(c.config, n.info, errArrayExpectsTwoTypeParams)
  413. result = newOrPrevType(tyError, prev, c)
  414. proc semIterableType(c: PContext, n: PNode, prev: PType): PType =
  415. result = newOrPrevType(tyIterable, prev, c)
  416. if n.len == 2:
  417. let base = semTypeNode(c, n[1], nil)
  418. addSonSkipIntLit(result, base, c.idgen)
  419. else:
  420. localError(c.config, n.info, errXExpectsOneTypeParam % "iterable")
  421. result = newOrPrevType(tyError, prev, c)
  422. proc semOrdinal(c: PContext, n: PNode, prev: PType): PType =
  423. result = newOrPrevType(tyOrdinal, prev, c)
  424. if n.len == 2:
  425. var base = semTypeNode(c, n[1], nil)
  426. if base.kind != tyGenericParam:
  427. if not isOrdinalType(base):
  428. localError(c.config, n[1].info, errOrdinalTypeExpected % typeToString(base, preferDesc))
  429. addSonSkipIntLit(result, base, c.idgen)
  430. else:
  431. localError(c.config, n.info, errXExpectsOneTypeParam % "ordinal")
  432. result = newOrPrevType(tyError, prev, c)
  433. proc semAnonTuple(c: PContext, n: PNode, prev: PType): PType =
  434. if n.len == 0:
  435. localError(c.config, n.info, errTypeExpected)
  436. result = newOrPrevType(tyTuple, prev, c)
  437. for it in n:
  438. let t = semTypeNode(c, it, nil)
  439. addSonSkipIntLitChecked(c, result, t, it, c.idgen)
  440. proc firstRange(config: ConfigRef, t: PType): PNode =
  441. if t.skipModifier().kind in tyFloat..tyFloat64:
  442. result = newFloatNode(nkFloatLit, firstFloat(t))
  443. else:
  444. result = newIntNode(nkIntLit, firstOrd(config, t))
  445. result.typ = t
  446. proc semTuple(c: PContext, n: PNode, prev: PType): PType =
  447. var typ: PType
  448. result = newOrPrevType(tyTuple, prev, c)
  449. result.n = newNodeI(nkRecList, n.info)
  450. var check = initIntSet()
  451. var counter = 0
  452. for i in ord(n.kind == nkBracketExpr)..<n.len:
  453. var a = n[i]
  454. if (a.kind != nkIdentDefs): illFormedAst(a, c.config)
  455. checkMinSonsLen(a, 3, c.config)
  456. var hasDefaultField = a[^1].kind != nkEmpty
  457. if hasDefaultField:
  458. typ = fitDefaultNode(c, a)
  459. elif a[^2].kind != nkEmpty:
  460. typ = semTypeNode(c, a[^2], nil)
  461. if c.graph.config.isDefined("nimPreviewRangeDefault") and typ.skipTypes(abstractInst).kind == tyRange:
  462. a[^1] = firstRange(c.config, typ)
  463. hasDefaultField = true
  464. else:
  465. localError(c.config, a.info, errTypeExpected)
  466. typ = errorType(c)
  467. for j in 0..<a.len - 2:
  468. var field = newSymG(skField, a[j], c)
  469. field.typ = typ
  470. field.position = counter
  471. inc(counter)
  472. if containsOrIncl(check, field.name.id):
  473. localError(c.config, a[j].info, "attempt to redefine: '" & field.name.s & "'")
  474. else:
  475. let fSym = newSymNode(field)
  476. if hasDefaultField:
  477. fSym.sym.ast = a[^1]
  478. fSym.sym.ast.flags.incl nfSkipFieldChecking
  479. result.n.add fSym
  480. addSonSkipIntLit(result, typ, c.idgen)
  481. styleCheckDef(c, a[j].info, field)
  482. onDef(field.info, field)
  483. if result.n.len == 0: result.n = nil
  484. if isTupleRecursive(result):
  485. localError(c.config, n.info, errIllegalRecursionInTypeX % typeToString(result))
  486. proc semIdentVis(c: PContext, kind: TSymKind, n: PNode,
  487. allowed: TSymFlags): PSym =
  488. # identifier with visibility
  489. if n.kind == nkPostfix:
  490. if n.len == 2:
  491. # for gensym'ed identifiers the identifier may already have been
  492. # transformed to a symbol and we need to use that here:
  493. result = newSymG(kind, n[1], c)
  494. var v = considerQuotedIdent(c, n[0])
  495. if sfExported in allowed and v.id == ord(wStar):
  496. incl(result.flags, sfExported)
  497. else:
  498. if not (sfExported in allowed):
  499. localError(c.config, n[0].info, errXOnlyAtModuleScope % "export")
  500. else:
  501. localError(c.config, n[0].info, errInvalidVisibilityX % renderTree(n[0]))
  502. else:
  503. result = nil
  504. illFormedAst(n, c.config)
  505. else:
  506. result = newSymG(kind, n, c)
  507. proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
  508. allowed: TSymFlags, fromTopLevel = false): PSym =
  509. if n.kind == nkPragmaExpr:
  510. checkSonsLen(n, 2, c.config)
  511. result = semIdentVis(c, kind, n[0], allowed)
  512. case kind
  513. of skType:
  514. # process pragmas later, because result.typ has not been set yet
  515. discard
  516. of skField: pragma(c, result, n[1], fieldPragmas)
  517. of skVar: pragma(c, result, n[1], varPragmas)
  518. of skLet: pragma(c, result, n[1], letPragmas)
  519. of skConst: pragma(c, result, n[1], constPragmas)
  520. else: discard
  521. else:
  522. result = semIdentVis(c, kind, n, allowed)
  523. let invalidPragmasForPush = if fromTopLevel and sfWasGenSym notin result.flags:
  524. {}
  525. else:
  526. {wExportc, wExportCpp, wDynlib}
  527. case kind
  528. of skField: implicitPragmas(c, result, n.info, fieldPragmas)
  529. of skVar: implicitPragmas(c, result, n.info, varPragmas-invalidPragmasForPush)
  530. of skLet: implicitPragmas(c, result, n.info, letPragmas-invalidPragmasForPush)
  531. of skConst: implicitPragmas(c, result, n.info, constPragmas-invalidPragmasForPush)
  532. else: discard
  533. proc checkForOverlap(c: PContext, t: PNode, currentEx, branchIndex: int) =
  534. let ex = t[branchIndex][currentEx].skipConv
  535. for i in 1..branchIndex:
  536. for j in 0..<t[i].len - 1:
  537. if i == branchIndex and j == currentEx: break
  538. if overlap(t[i][j].skipConv, ex):
  539. localError(c.config, ex.info, errDuplicateCaseLabel)
  540. proc semBranchRange(c: PContext, n, a, b: PNode, covered: var Int128): PNode =
  541. checkMinSonsLen(n, 1, c.config)
  542. let ac = semConstExpr(c, a)
  543. let bc = semConstExpr(c, b)
  544. if ac.kind in {nkStrLit..nkTripleStrLit} or bc.kind in {nkStrLit..nkTripleStrLit}:
  545. localError(c.config, b.info, "range of string is invalid")
  546. let at = fitNode(c, n[0].typ, ac, ac.info).skipConvTakeType
  547. let bt = fitNode(c, n[0].typ, bc, bc.info).skipConvTakeType
  548. result = newNodeI(nkRange, a.info)
  549. result.add(at)
  550. result.add(bt)
  551. if emptyRange(ac, bc): localError(c.config, b.info, "range is empty")
  552. else: covered = covered + getOrdValue(bc) + 1 - getOrdValue(ac)
  553. proc semCaseBranchRange(c: PContext, t, b: PNode,
  554. covered: var Int128): PNode =
  555. checkSonsLen(b, 3, c.config)
  556. result = semBranchRange(c, t, b[1], b[2], covered)
  557. proc semCaseBranchSetElem(c: PContext, n, b: PNode,
  558. covered: var Int128): PNode =
  559. if isRange(b):
  560. checkSonsLen(b, 3, c.config)
  561. result = semBranchRange(c, n, b[1], b[2], covered)
  562. elif b.kind == nkRange:
  563. checkSonsLen(b, 2, c.config)
  564. result = semBranchRange(c, n, b[0], b[1], covered)
  565. else:
  566. result = fitNode(c, n[0].typ, b, b.info)
  567. inc(covered)
  568. proc semCaseBranch(c: PContext, n, branch: PNode, branchIndex: int,
  569. covered: var Int128) =
  570. let lastIndex = branch.len - 2
  571. for i in 0..lastIndex:
  572. var b = branch[i]
  573. if b.kind == nkRange:
  574. branch[i] = b
  575. elif isRange(b):
  576. branch[i] = semCaseBranchRange(c, n, b, covered)
  577. else:
  578. # constant sets and arrays are allowed:
  579. # set expected type to selector type for type inference
  580. # even if it can be a different type like a set or array
  581. var r = semConstExpr(c, b, expectedType = n[0].typ)
  582. if r.kind in {nkCurly, nkBracket} and r.len == 0 and branch.len == 2:
  583. # discarding ``{}`` and ``[]`` branches silently
  584. delSon(branch, 0)
  585. return
  586. elif r.kind notin {nkCurly, nkBracket} or r.len == 0:
  587. checkMinSonsLen(n, 1, c.config)
  588. var tmp = fitNode(c, n[0].typ, r, r.info)
  589. # the call to fitNode may introduce a call to a converter
  590. if tmp.kind == nkHiddenCallConv or
  591. (tmp.kind == nkHiddenStdConv and n[0].typ.kind == tyCstring):
  592. tmp = semConstExpr(c, tmp)
  593. branch[i] = skipConv(tmp)
  594. inc(covered)
  595. else:
  596. if r.kind == nkCurly:
  597. r = deduplicate(c.config, r)
  598. # first element is special and will overwrite: branch[i]:
  599. branch[i] = semCaseBranchSetElem(c, n, r[0], covered)
  600. # other elements have to be added to ``branch``
  601. for j in 1..<r.len:
  602. branch.add(semCaseBranchSetElem(c, n, r[j], covered))
  603. # caution! last son of branch must be the actions to execute:
  604. swap(branch[^2], branch[^1])
  605. checkForOverlap(c, n, i, branchIndex)
  606. # Elements added above needs to be checked for overlaps.
  607. for i in lastIndex.succ..<branch.len - 1:
  608. checkForOverlap(c, n, i, branchIndex)
  609. proc toCover(c: PContext, t: PType): Int128 =
  610. let t2 = skipTypes(t, abstractVarRange-{tyTypeDesc})
  611. if t2.kind == tyEnum and enumHasHoles(t2):
  612. result = toInt128(t2.n.len)
  613. else:
  614. # <----
  615. let t = skipTypes(t, abstractVar-{tyTypeDesc})
  616. # XXX: hack incoming. lengthOrd is incorrect for 64bit integer
  617. # types because it doesn't uset Int128 yet. This entire branching
  618. # should be removed as soon as lengthOrd uses int128.
  619. if t.kind in {tyInt64, tyUInt64}:
  620. result = toInt128(1) shl 64
  621. elif t.kind in {tyInt, tyUInt}:
  622. result = toInt128(1) shl (c.config.target.intSize * 8)
  623. else:
  624. result = lengthOrd(c.config, t)
  625. proc semRecordNodeAux(c: PContext, n: PNode, check: var IntSet, pos: var int,
  626. father: PNode, rectype: PType, hasCaseFields = false)
  627. proc getIntSetOfType(c: PContext, t: PType): IntSet =
  628. result = initIntSet()
  629. if t.enumHasHoles:
  630. let t = t.skipTypes(abstractRange)
  631. for field in t.n.sons:
  632. result.incl(field.sym.position)
  633. else:
  634. assert(lengthOrd(c.config, t) <= BiggestInt(MaxSetElements))
  635. for i in toInt64(firstOrd(c.config, t))..toInt64(lastOrd(c.config, t)):
  636. result.incl(i.int)
  637. iterator processBranchVals(b: PNode): int =
  638. assert b.kind in {nkOfBranch, nkElifBranch, nkElse}
  639. if b.kind == nkOfBranch:
  640. for i in 0..<b.len-1:
  641. if b[i].kind in {nkIntLit, nkCharLit}:
  642. yield b[i].intVal.int
  643. elif b[i].kind == nkRange:
  644. for i in b[i][0].intVal..b[i][1].intVal:
  645. yield i.int
  646. proc renderAsType(vals: IntSet, t: PType): string =
  647. result = "{"
  648. let t = t.skipTypes(abstractRange)
  649. var enumSymOffset = 0
  650. var i = 0
  651. for val in vals:
  652. if result.len > 1:
  653. result &= ", "
  654. case t.kind:
  655. of tyEnum, tyBool:
  656. while t.n[enumSymOffset].sym.position < val: inc(enumSymOffset)
  657. result &= t.n[enumSymOffset].sym.name.s
  658. of tyChar:
  659. result.addQuoted(char(val))
  660. else:
  661. if i == 64:
  662. result &= "omitted $1 values..." % $(vals.len - i)
  663. break
  664. else:
  665. result &= $val
  666. inc(i)
  667. result &= "}"
  668. proc formatMissingEnums(c: PContext, n: PNode): string =
  669. var coveredCases = initIntSet()
  670. for i in 1..<n.len:
  671. for val in processBranchVals(n[i]):
  672. coveredCases.incl val
  673. result = (c.getIntSetOfType(n[0].typ) - coveredCases).renderAsType(n[0].typ)
  674. proc semRecordCase(c: PContext, n: PNode, check: var IntSet, pos: var int,
  675. father: PNode, rectype: PType) =
  676. var a = copyNode(n)
  677. checkMinSonsLen(n, 2, c.config)
  678. semRecordNodeAux(c, n[0], check, pos, a, rectype, hasCaseFields = true)
  679. if a[0].kind != nkSym:
  680. internalError(c.config, "semRecordCase: discriminant is no symbol")
  681. return
  682. incl(a[0].sym.flags, sfDiscriminant)
  683. var covered = toInt128(0)
  684. var chckCovered = false
  685. var typ = skipTypes(a[0].typ, abstractVar-{tyTypeDesc})
  686. const shouldChckCovered = {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32, tyBool}
  687. case typ.kind
  688. of shouldChckCovered:
  689. chckCovered = true
  690. of tyFloat..tyFloat128, tyError:
  691. discard
  692. of tyRange:
  693. if skipTypes(typ.elementType, abstractInst).kind in shouldChckCovered:
  694. chckCovered = true
  695. of tyForward:
  696. errorUndeclaredIdentifier(c, n[0].info, typ.sym.name.s)
  697. elif not isOrdinalType(typ):
  698. localError(c.config, n[0].info, "selector must be of an ordinal type, float")
  699. if firstOrd(c.config, typ) != 0:
  700. localError(c.config, n.info, "low(" & $a[0].sym.name.s &
  701. ") must be 0 for discriminant")
  702. elif lengthOrd(c.config, typ) > 0x00007FFF:
  703. localError(c.config, n.info, "len($1) must be less than 32768" % a[0].sym.name.s)
  704. for i in 1..<n.len:
  705. var b = copyTree(n[i])
  706. a.add b
  707. case n[i].kind
  708. of nkOfBranch:
  709. checkMinSonsLen(b, 2, c.config)
  710. semCaseBranch(c, a, b, i, covered)
  711. of nkElse:
  712. checkSonsLen(b, 1, c.config)
  713. if chckCovered and covered == toCover(c, a[0].typ):
  714. message(c.config, b.info, warnUnreachableElse)
  715. chckCovered = false
  716. else: illFormedAst(n, c.config)
  717. delSon(b, b.len - 1)
  718. semRecordNodeAux(c, lastSon(n[i]), check, pos, b, rectype, hasCaseFields = true)
  719. if chckCovered and covered != toCover(c, a[0].typ):
  720. if a[0].typ.skipTypes(abstractRange).kind == tyEnum:
  721. localError(c.config, a.info, "not all cases are covered; missing: $1" %
  722. formatMissingEnums(c, a))
  723. else:
  724. localError(c.config, a.info, "not all cases are covered")
  725. father.add a
  726. proc semRecordNodeAux(c: PContext, n: PNode, check: var IntSet, pos: var int,
  727. father: PNode, rectype: PType, hasCaseFields: bool) =
  728. if n == nil: return
  729. case n.kind
  730. of nkRecWhen:
  731. var a = copyTree(n)
  732. var branch: PNode = nil # the branch to take
  733. for i in 0..<a.len:
  734. var it = a[i]
  735. if it == nil: illFormedAst(n, c.config)
  736. var idx = 1
  737. case it.kind
  738. of nkElifBranch:
  739. checkSonsLen(it, 2, c.config)
  740. if c.inGenericContext == 0:
  741. var e = semConstBoolExpr(c, it[0])
  742. if e.kind != nkIntLit: discard "don't report followup error"
  743. elif e.intVal != 0 and branch == nil: branch = it[1]
  744. else:
  745. # XXX this is still a hard compilation in a generic context, this can
  746. # result in unresolved generic parameters being treated like real types
  747. let e = semExprWithType(c, it[0], {efDetermineType})
  748. if e.typ.kind == tyFromExpr:
  749. it[0] = makeStaticExpr(c, e)
  750. else:
  751. it[0] = forceBool(c, e)
  752. of nkElse:
  753. checkSonsLen(it, 1, c.config)
  754. if branch == nil: branch = it[0]
  755. idx = 0
  756. else: illFormedAst(n, c.config)
  757. if c.inGenericContext > 0:
  758. # use a new check intset here for each branch:
  759. var newCheck: IntSet = check
  760. var newPos = pos
  761. var newf = newNodeI(nkRecList, n.info)
  762. semRecordNodeAux(c, it[idx], newCheck, newPos, newf, rectype, hasCaseFields)
  763. it[idx] = if newf.len == 1: newf[0] else: newf
  764. if c.inGenericContext > 0:
  765. father.add a
  766. elif branch != nil:
  767. semRecordNodeAux(c, branch, check, pos, father, rectype, hasCaseFields)
  768. elif father.kind in {nkElse, nkOfBranch}:
  769. father.add newNodeI(nkRecList, n.info)
  770. of nkRecCase:
  771. semRecordCase(c, n, check, pos, father, rectype)
  772. of nkNilLit:
  773. if father.kind != nkRecList: father.add newNodeI(nkRecList, n.info)
  774. of nkRecList:
  775. # attempt to keep the nesting at a sane level:
  776. var a = if father.kind == nkRecList: father else: copyNode(n)
  777. for i in 0..<n.len:
  778. semRecordNodeAux(c, n[i], check, pos, a, rectype, hasCaseFields)
  779. if a != father: father.add a
  780. of nkIdentDefs:
  781. checkMinSonsLen(n, 3, c.config)
  782. var a: PNode
  783. if father.kind != nkRecList and n.len >= 4: a = newNodeI(nkRecList, n.info)
  784. else: a = newNodeI(nkEmpty, n.info)
  785. var typ: PType
  786. var hasDefaultField = n[^1].kind != nkEmpty
  787. if hasDefaultField:
  788. typ = fitDefaultNode(c, n)
  789. propagateToOwner(rectype, typ)
  790. elif n[^2].kind == nkEmpty:
  791. localError(c.config, n.info, errTypeExpected)
  792. typ = errorType(c)
  793. else:
  794. typ = semTypeNode(c, n[^2], nil)
  795. if c.graph.config.isDefined("nimPreviewRangeDefault") and typ.skipTypes(abstractInst).kind == tyRange:
  796. n[^1] = firstRange(c.config, typ)
  797. hasDefaultField = true
  798. propagateToOwner(rectype, typ)
  799. var fieldOwner = if c.inGenericContext > 0: c.getCurrOwner
  800. else: rectype.sym
  801. for i in 0..<n.len-2:
  802. var f = semIdentWithPragma(c, skField, n[i], {sfExported})
  803. let info = if n[i].kind == nkPostfix:
  804. n[i][1].info
  805. else:
  806. n[i].info
  807. suggestSym(c.graph, info, f, c.graph.usageSym)
  808. f.typ = typ
  809. f.position = pos
  810. f.options = c.config.options
  811. if fieldOwner != nil and
  812. {sfImportc, sfExportc} * fieldOwner.flags != {} and
  813. not hasCaseFields and f.loc.snippet == "":
  814. f.loc.snippet = rope(f.name.s)
  815. f.flags.incl {sfImportc, sfExportc} * fieldOwner.flags
  816. inc(pos)
  817. if containsOrIncl(check, f.name.id):
  818. localError(c.config, info, "attempt to redefine: '" & f.name.s & "'")
  819. let fSym = newSymNode(f)
  820. if hasDefaultField:
  821. fSym.sym.ast = n[^1]
  822. fSym.sym.ast.flags.incl nfSkipFieldChecking
  823. if a.kind == nkEmpty: father.add fSym
  824. else: a.add fSym
  825. styleCheckDef(c, f)
  826. onDef(f.info, f)
  827. if a.kind != nkEmpty: father.add a
  828. of nkSym:
  829. # This branch only valid during generic object
  830. # inherited from generic/partial specialized parent second check.
  831. # There is no branch validity check here
  832. if containsOrIncl(check, n.sym.name.id):
  833. localError(c.config, n.info, "attempt to redefine: '" & n.sym.name.s & "'")
  834. father.add n
  835. of nkEmpty:
  836. if father.kind in {nkElse, nkOfBranch}:
  837. father.add n
  838. else: illFormedAst(n, c.config)
  839. proc addInheritedFieldsAux(c: PContext, check: var IntSet, pos: var int,
  840. n: PNode) =
  841. case n.kind
  842. of nkRecCase:
  843. if (n[0].kind != nkSym): internalError(c.config, n.info, "addInheritedFieldsAux")
  844. addInheritedFieldsAux(c, check, pos, n[0])
  845. for i in 1..<n.len:
  846. case n[i].kind
  847. of nkOfBranch, nkElse:
  848. addInheritedFieldsAux(c, check, pos, lastSon(n[i]))
  849. else: internalError(c.config, n.info, "addInheritedFieldsAux(record case branch)")
  850. of nkRecList, nkRecWhen, nkElifBranch, nkElse:
  851. for i in int(n.kind == nkElifBranch)..<n.len:
  852. addInheritedFieldsAux(c, check, pos, n[i])
  853. of nkSym:
  854. incl(check, n.sym.name.id)
  855. inc(pos)
  856. else: internalError(c.config, n.info, "addInheritedFieldsAux()")
  857. proc skipGenericInvocation(t: PType): PType {.inline.} =
  858. result = t
  859. if result.kind == tyGenericInvocation:
  860. result = result[0]
  861. while result.kind in {tyGenericInst, tyGenericBody, tyRef, tyPtr, tyAlias, tySink, tyOwned}:
  862. result = skipModifier(result)
  863. proc tryAddInheritedFields(c: PContext, check: var IntSet, pos: var int,
  864. obj: PType, n: PNode, isPartial = false, innerObj: PType = nil): bool =
  865. if ((not isPartial) and (obj.kind notin {tyObject, tyGenericParam} or tfFinal in obj.flags)) or
  866. (innerObj != nil and obj.sym.id == innerObj.sym.id):
  867. localError(c.config, n.info, "Cannot inherit from: '" & $obj & "'")
  868. result = false
  869. elif obj.kind == tyObject:
  870. result = true
  871. if (obj.len > 0) and (obj[0] != nil):
  872. result = result and tryAddInheritedFields(c, check, pos, obj[0].skipGenericInvocation, n, false, obj)
  873. addInheritedFieldsAux(c, check, pos, obj.n)
  874. else:
  875. result = true
  876. proc semObjectNode(c: PContext, n: PNode, prev: PType; flags: TTypeFlags): PType =
  877. result = nil
  878. if n.len == 0:
  879. return newConstraint(c, tyObject)
  880. var check = initIntSet()
  881. var pos = 0
  882. var base, realBase: PType = nil
  883. # n[0] contains the pragmas (if any). We process these later...
  884. checkSonsLen(n, 3, c.config)
  885. if n[1].kind != nkEmpty:
  886. realBase = semTypeNode(c, n[1][0], nil)
  887. base = skipTypesOrNil(realBase, skipPtrs)
  888. if base.isNil:
  889. localError(c.config, n.info, "cannot inherit from a type that is not an object type")
  890. else:
  891. var concreteBase = skipGenericInvocation(base)
  892. if concreteBase.kind in {tyObject, tyGenericParam,
  893. tyGenericInvocation} and tfFinal notin concreteBase.flags:
  894. # we only check fields duplication of object inherited from
  895. # concrete object. If inheriting from generic object or partial
  896. # specialized object, there will be second check after instantiation
  897. # located in semGeneric.
  898. if concreteBase.kind == tyObject:
  899. if concreteBase.sym != nil and concreteBase.sym.magic == mException and
  900. sfSystemModule notin c.module.flags:
  901. message(c.config, n.info, warnInheritFromException, "")
  902. if not tryAddInheritedFields(c, check, pos, concreteBase, n):
  903. return newType(tyError, c.idgen, result.owner)
  904. elif concreteBase.kind == tyForward:
  905. c.skipTypes.add n #we retry in the final pass
  906. else:
  907. if concreteBase.kind != tyError:
  908. localError(c.config, n[1].info, "inheritance only works with non-final objects; " &
  909. "for " & typeToString(realBase) & " to be inheritable it must be " &
  910. "'object of RootObj' instead of 'object'")
  911. base = nil
  912. realBase = nil
  913. if n.kind != nkObjectTy: internalError(c.config, n.info, "semObjectNode")
  914. result = newOrPrevType(tyObject, prev, c)
  915. rawAddSon(result, realBase)
  916. if realBase == nil and tfInheritable in flags:
  917. result.flags.incl tfInheritable
  918. if tfAcyclic in flags: result.flags.incl tfAcyclic
  919. if result.n.isNil:
  920. result.n = newNodeI(nkRecList, n.info)
  921. else:
  922. # partial object so add things to the check
  923. if not tryAddInheritedFields(c, check, pos, result, n, isPartial = true):
  924. return newType(tyError, c.idgen, result.owner)
  925. semRecordNodeAux(c, n[2], check, pos, result.n, result)
  926. if n[0].kind != nkEmpty:
  927. # dummy symbol for `pragma`:
  928. var s = newSymS(skType, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  929. s.typ = result
  930. pragma(c, s, n[0], typePragmas)
  931. if base == nil and tfInheritable notin result.flags:
  932. incl(result.flags, tfFinal)
  933. if c.inGenericContext == 0 and computeRequiresInit(c, result):
  934. result.flags.incl tfRequiresInit
  935. proc semAnyRef(c: PContext; n: PNode; kind: TTypeKind; prev: PType): PType =
  936. if n.len < 1:
  937. result = newConstraint(c, kind)
  938. else:
  939. let isCall = int ord(n.kind in nkCallKinds+{nkBracketExpr})
  940. let n = if n[0].kind == nkBracket: n[0] else: n
  941. checkMinSonsLen(n, 1, c.config)
  942. let body = n.lastSon
  943. var t = if prev != nil and prev.kind != tyGenericBody and body.kind == nkObjectTy:
  944. semObjectNode(c, body, nil, prev.flags)
  945. else:
  946. semTypeNode(c, body, nil)
  947. if t.kind == tyTypeDesc and tfUnresolved notin t.flags:
  948. t = t.base
  949. if t.kind == tyVoid:
  950. localError(c.config, n.info, "type '$1 void' is not allowed" % kind.toHumanStr)
  951. result = newOrPrevType(kind, prev, c)
  952. var isNilable = false
  953. var wrapperKind = tyNone
  954. # check every except the last is an object:
  955. for i in isCall..<n.len-1:
  956. let ni = n[i]
  957. # echo "semAnyRef ", "n: ", n, "i: ", i, "ni: ", ni
  958. if ni.kind == nkNilLit:
  959. isNilable = true
  960. else:
  961. let region = semTypeNode(c, ni, nil)
  962. if region.kind in {tyOwned, tySink}:
  963. wrapperKind = region.kind
  964. elif region.skipTypes({tyGenericInst, tyAlias, tySink}).kind notin {
  965. tyError, tyObject}:
  966. message c.config, n[i].info, errGenerated, "region needs to be an object type"
  967. addSonSkipIntLit(result, region, c.idgen)
  968. else:
  969. message(c.config, n.info, warnDeprecated, "region for pointer types is deprecated")
  970. addSonSkipIntLit(result, region, c.idgen)
  971. addSonSkipIntLit(result, t, c.idgen)
  972. if tfPartial in result.flags:
  973. if result.elementType.kind == tyObject: incl(result.elementType.flags, tfPartial)
  974. # if not isNilable: result.flags.incl tfNotNil
  975. case wrapperKind
  976. of tyOwned:
  977. if optOwnedRefs in c.config.globalOptions:
  978. let t = newTypeS(tyOwned, c, result)
  979. t.flags.incl tfHasOwned
  980. result = t
  981. of tySink:
  982. let t = newTypeS(tySink, c, result)
  983. result = t
  984. else: discard
  985. if result.kind == tyRef and c.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  986. result.flags.incl tfHasAsgn
  987. proc findEnforcedStaticType(t: PType): PType =
  988. # This handles types such as `static[T] and Foo`,
  989. # which are subset of `static[T]`, hence they could
  990. # be treated in the same way
  991. result = nil
  992. if t == nil: return nil
  993. if t.kind == tyStatic: return t
  994. if t.kind == tyAnd:
  995. for s in t.kids:
  996. let t = findEnforcedStaticType(s)
  997. if t != nil: return t
  998. proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind) =
  999. if kind == skMacro:
  1000. let staticType = findEnforcedStaticType(param.typ)
  1001. if staticType != nil:
  1002. var a = copySym(param, c.idgen)
  1003. a.typ = staticType.base
  1004. addDecl(c, a)
  1005. #elif param.typ != nil and param.typ.kind == tyTypeDesc:
  1006. # addDecl(c, param)
  1007. else:
  1008. # within a macro, every param has the type NimNode!
  1009. let nn = getSysSym(c.graph, param.info, "NimNode")
  1010. var a = copySym(param, c.idgen)
  1011. a.typ = nn.typ
  1012. addDecl(c, a)
  1013. else:
  1014. if sfGenSym in param.flags:
  1015. # bug #XXX, fix the gensym'ed parameters owner:
  1016. if param.owner == nil:
  1017. param.owner = getCurrOwner(c)
  1018. else: addDecl(c, param)
  1019. template shouldHaveMeta(t) =
  1020. internalAssert c.config, tfHasMeta in t.flags
  1021. # result.lastSon.flags.incl tfHasMeta
  1022. proc addImplicitGeneric(c: PContext; typeClass: PType, typId: PIdent;
  1023. info: TLineInfo; genericParams: PNode;
  1024. paramName: string): PType =
  1025. if genericParams == nil:
  1026. # This happens with anonymous proc types appearing in signatures
  1027. # XXX: we need to lift these earlier
  1028. return
  1029. let finalTypId = if typId != nil: typId
  1030. else: getIdent(c.cache, paramName & ":type")
  1031. # is this a bindOnce type class already present in the param list?
  1032. for i in 0..<genericParams.len:
  1033. if genericParams[i].sym.name.id == finalTypId.id:
  1034. return genericParams[i].typ
  1035. let owner = if typeClass.sym != nil: typeClass.sym
  1036. else: getCurrOwner(c)
  1037. var s = newSym(skType, finalTypId, c.idgen, owner, info)
  1038. if sfExplain in owner.flags: s.flags.incl sfExplain
  1039. if typId == nil: s.flags.incl(sfAnon)
  1040. s.linkTo(typeClass)
  1041. typeClass.flags.incl tfImplicitTypeParam
  1042. s.position = genericParams.len
  1043. genericParams.add newSymNode(s)
  1044. result = typeClass
  1045. addDecl(c, s)
  1046. proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode,
  1047. paramType: PType, paramName: string,
  1048. info: TLineInfo, anon = false): PType =
  1049. if paramType == nil: return # (e.g. proc return type)
  1050. template recurse(typ: PType, anonFlag = false): untyped =
  1051. liftParamType(c, procKind, genericParams, typ, paramName, info, anonFlag)
  1052. var paramTypId = if not anon and paramType.sym != nil: paramType.sym.name
  1053. else: nil
  1054. case paramType.kind
  1055. of tyAnything:
  1056. result = addImplicitGeneric(c, newTypeS(tyGenericParam, c), nil, info, genericParams, paramName)
  1057. of tyStatic:
  1058. if paramType.base.kind != tyNone and paramType.n != nil:
  1059. # this is a concrete static value
  1060. return
  1061. if tfUnresolved in paramType.flags: return # already lifted
  1062. let lifted = recurse(paramType.base)
  1063. let base = (if lifted != nil: lifted else: paramType.base)
  1064. if base.isMetaType and procKind == skMacro:
  1065. localError(c.config, info, errMacroBodyDependsOnGenericTypes % paramName)
  1066. result = addImplicitGeneric(c, newTypeS(tyStatic, c, base),
  1067. paramTypId, info, genericParams, paramName)
  1068. if result != nil: result.flags.incl({tfHasStatic, tfUnresolved})
  1069. of tyTypeDesc:
  1070. if tfUnresolved notin paramType.flags:
  1071. # naked typedescs are not bindOnce types
  1072. if paramType.base.kind == tyNone and paramTypId != nil and
  1073. (paramTypId.id == getIdent(c.cache, "typedesc").id or
  1074. paramTypId.id == getIdent(c.cache, "type").id):
  1075. # XXX Why doesn't this check for tyTypeDesc instead?
  1076. paramTypId = nil
  1077. let t = newTypeS(tyTypeDesc, c, paramType.base)
  1078. incl t.flags, tfCheckedForDestructor
  1079. result = addImplicitGeneric(c, t, paramTypId, info, genericParams, paramName)
  1080. else:
  1081. result = nil
  1082. of tyDistinct:
  1083. if paramType.len == 1:
  1084. # disable the bindOnce behavior for the type class
  1085. result = recurse(paramType.base, true)
  1086. else:
  1087. result = nil
  1088. of tyTuple:
  1089. result = nil
  1090. for i in 0..<paramType.len:
  1091. let t = recurse(paramType[i])
  1092. if t != nil:
  1093. paramType[i] = t
  1094. result = paramType
  1095. of tyAlias, tyOwned:
  1096. result = recurse(paramType.base)
  1097. of tySequence, tySet, tyArray, tyOpenArray,
  1098. tyVar, tyLent, tyPtr, tyRef, tyProc, tySink:
  1099. # XXX: this is a bit strange, but proc(s: seq)
  1100. # produces tySequence(tyGenericParam, tyNone).
  1101. # This also seems to be true when creating aliases
  1102. # like: type myseq = distinct seq.
  1103. # Maybe there is another better place to associate
  1104. # the seq type class with the seq identifier.
  1105. if paramType.kind == tySequence and paramType.elementType.kind == tyNone:
  1106. let typ = newTypeS(tyBuiltInTypeClass, c,
  1107. newTypeS(paramType.kind, c))
  1108. result = addImplicitGeneric(c, typ, paramTypId, info, genericParams, paramName)
  1109. else:
  1110. result = nil
  1111. for i in 0..<paramType.len:
  1112. if paramType[i] == paramType:
  1113. globalError(c.config, info, errIllegalRecursionInTypeX % typeToString(paramType))
  1114. var lifted = recurse(paramType[i])
  1115. if lifted != nil:
  1116. paramType[i] = lifted
  1117. result = paramType
  1118. of tyGenericBody:
  1119. result = newTypeS(tyGenericInvocation, c)
  1120. result.rawAddSon(paramType)
  1121. for i in 0..<paramType.len - 1:
  1122. if paramType[i].kind == tyStatic:
  1123. var staticCopy = paramType[i].exactReplica
  1124. staticCopy.flags.incl tfInferrableStatic
  1125. result.rawAddSon staticCopy
  1126. else:
  1127. result.rawAddSon newTypeS(tyAnything, c)
  1128. if paramType.typeBodyImpl.kind == tyUserTypeClass:
  1129. result.kind = tyUserTypeClassInst
  1130. result.rawAddSon paramType.typeBodyImpl
  1131. return addImplicitGeneric(c, result, paramTypId, info, genericParams, paramName)
  1132. let x = instGenericContainer(c, paramType.sym.info, result,
  1133. allowMetaTypes = true)
  1134. result = newTypeS(tyCompositeTypeClass, c)
  1135. result.rawAddSon paramType
  1136. result.rawAddSon x
  1137. result = addImplicitGeneric(c, result, paramTypId, info, genericParams, paramName)
  1138. of tyGenericInst:
  1139. result = nil
  1140. if paramType.skipModifier.kind == tyUserTypeClass:
  1141. var cp = copyType(paramType, c.idgen, getCurrOwner(c))
  1142. copyTypeProps(c.graph, c.idgen.module, cp, paramType)
  1143. cp.kind = tyUserTypeClassInst
  1144. return addImplicitGeneric(c, cp, paramTypId, info, genericParams, paramName)
  1145. for i in 1..<paramType.len-1:
  1146. var lifted = recurse(paramType[i])
  1147. if lifted != nil:
  1148. paramType[i] = lifted
  1149. result = paramType
  1150. result.last.shouldHaveMeta
  1151. let liftBody = recurse(paramType.skipModifier, true)
  1152. if liftBody != nil:
  1153. result = liftBody
  1154. result.flags.incl tfHasMeta
  1155. #result.shouldHaveMeta
  1156. of tyGenericInvocation:
  1157. result = nil
  1158. for i in 1..<paramType.len:
  1159. #if paramType[i].kind != tyTypeDesc:
  1160. let lifted = recurse(paramType[i])
  1161. if lifted != nil: paramType[i] = lifted
  1162. let body = paramType.base
  1163. if body.kind in {tyForward, tyError}:
  1164. # this may happen for proc type appearing in a type section
  1165. # before one of its param types
  1166. return
  1167. if body.last.kind == tyUserTypeClass:
  1168. let expanded = instGenericContainer(c, info, paramType,
  1169. allowMetaTypes = true)
  1170. result = recurse(expanded, true)
  1171. of tyUserTypeClasses, tyBuiltInTypeClass, tyCompositeTypeClass,
  1172. tyAnd, tyOr, tyNot, tyConcept:
  1173. result = addImplicitGeneric(c,
  1174. copyType(paramType, c.idgen, getCurrOwner(c)), paramTypId,
  1175. info, genericParams, paramName)
  1176. of tyGenericParam:
  1177. result = nil
  1178. markUsed(c, paramType.sym.info, paramType.sym)
  1179. onUse(paramType.sym.info, paramType.sym)
  1180. if tfWildcard in paramType.flags:
  1181. paramType.flags.excl tfWildcard
  1182. paramType.sym.transitionGenericParamToType()
  1183. else: result = nil
  1184. proc semParamType(c: PContext, n: PNode, constraint: var PNode): PType =
  1185. ## Semchecks the type of parameters.
  1186. if n.kind == nkCurlyExpr:
  1187. result = semTypeNode(c, n[0], nil)
  1188. constraint = semNodeKindConstraints(n, c.config, 1)
  1189. elif n.kind == nkCall and
  1190. n[0].kind in {nkIdent, nkSym, nkOpenSymChoice, nkClosedSymChoice, nkOpenSym} and
  1191. considerQuotedIdent(c, n[0]).s == "{}":
  1192. result = semTypeNode(c, n[1], nil)
  1193. constraint = semNodeKindConstraints(n, c.config, 2)
  1194. else:
  1195. result = semTypeNode(c, n, nil)
  1196. proc newProcType(c: PContext; info: TLineInfo; prev: PType = nil): PType =
  1197. result = newOrPrevType(tyProc, prev, c)
  1198. result.callConv = lastOptionEntry(c).defaultCC
  1199. result.n = newNodeI(nkFormalParams, info)
  1200. rawAddSon(result, nil) # return type
  1201. # result.n[0] used to be `nkType`, but now it's `nkEffectList` because
  1202. # the effects are now stored in there too ... this is a bit hacky, but as
  1203. # usual we desperately try to save memory:
  1204. result.n.add newNodeI(nkEffectList, info)
  1205. proc isMagic(sym: PSym): bool =
  1206. if sym.ast == nil: return false
  1207. let nPragmas = sym.ast[pragmasPos]
  1208. return hasPragma(nPragmas, wMagic)
  1209. proc semProcTypeNode(c: PContext, n, genericParams: PNode,
  1210. prev: PType, kind: TSymKind; isType=false): PType =
  1211. # for historical reasons (code grows) this is invoked for parameter
  1212. # lists too and then 'isType' is false.
  1213. checkMinSonsLen(n, 1, c.config)
  1214. result = newProcType(c, n.info, prev)
  1215. var check = initIntSet()
  1216. var counter = 0
  1217. template isCurrentlyGeneric: bool =
  1218. # genericParams might update as implicit generic params are added
  1219. genericParams != nil and genericParams.len > 0
  1220. for i in 1..<n.len:
  1221. var a = n[i]
  1222. if a.kind != nkIdentDefs:
  1223. # for some generic instantiations the passed ':env' parameter
  1224. # for closures has already been produced (see bug #898). We simply
  1225. # skip this parameter here. It'll then be re-generated in another LL
  1226. # pass over this instantiation:
  1227. if a.kind == nkSym and sfFromGeneric in a.sym.flags: continue
  1228. illFormedAst(a, c.config)
  1229. checkMinSonsLen(a, 3, c.config)
  1230. var
  1231. typ: PType = nil
  1232. def: PNode = nil
  1233. constraint: PNode = nil
  1234. hasType = a[^2].kind != nkEmpty
  1235. hasDefault = a[^1].kind != nkEmpty
  1236. if hasType:
  1237. let isGeneric = isCurrentlyGeneric()
  1238. inc c.inGenericContext, ord(isGeneric)
  1239. typ = semParamType(c, a[^2], constraint)
  1240. dec c.inGenericContext, ord(isGeneric)
  1241. # TODO: Disallow typed/untyped in procs in the compiler/stdlib
  1242. if kind in {skProc, skFunc} and (typ.kind == tyTyped or typ.kind == tyUntyped):
  1243. if not isMagic(getCurrOwner(c)):
  1244. localError(c.config, a[^2].info, "'" & typ.sym.name.s & "' is only allowed in templates and macros or magic procs")
  1245. if hasDefault:
  1246. def = a[^1]
  1247. if a.len > 3:
  1248. var msg = ""
  1249. for j in 0 ..< a.len - 2:
  1250. if msg.len != 0: msg.add(", ")
  1251. msg.add($a[j])
  1252. msg.add(" all have default value '")
  1253. msg.add(def.renderTree)
  1254. msg.add("', this may be unintentional, " &
  1255. "either use ';' (semicolon) or explicitly write each default value")
  1256. message(c.config, a.info, warnImplicitDefaultValue, msg)
  1257. block determineType:
  1258. var defTyp = typ
  1259. if isCurrentlyGeneric():
  1260. defTyp = nil
  1261. def = semGenericStmt(c, def)
  1262. if hasUnresolvedArgs(c, def):
  1263. def.typ = makeTypeFromExpr(c, def.copyTree)
  1264. break determineType
  1265. def = semExprWithType(c, def, {efDetermineType, efAllowSymChoice}, defTyp)
  1266. if def.referencesAnotherParam(getCurrOwner(c)):
  1267. def.flags.incl nfDefaultRefsParam
  1268. if typ == nil:
  1269. typ = def.typ
  1270. if isEmptyContainer(typ):
  1271. localError(c.config, a.info, "cannot infer the type of parameter '" & $a[0] & "'")
  1272. if typ.kind == tyTypeDesc:
  1273. # consider a proc such as:
  1274. # proc takesType(T = int)
  1275. # a naive analysis may conclude that the proc type is type[int]
  1276. # which will prevent other types from matching - clearly a very
  1277. # surprising behavior. We must instead fix the expected type of
  1278. # the proc to be the unbound typedesc type:
  1279. typ = newTypeS(tyTypeDesc, c, newTypeS(tyNone, c))
  1280. typ.flags.incl tfCheckedForDestructor
  1281. elif def.typ.kind != tyFromExpr:
  1282. # if def.typ != nil and def.typ.kind != tyNone:
  1283. # example code that triggers it:
  1284. # proc sort[T](cmp: proc(a, b: T): int = cmp)
  1285. if not containsGenericType(typ):
  1286. # check type compatibility between def.typ and typ:
  1287. def = fitNode(c, typ, def, def.info)
  1288. elif typ.kind == tyStatic:
  1289. def = semConstExpr(c, def)
  1290. def = fitNode(c, typ, def, def.info)
  1291. if not hasType and not hasDefault:
  1292. if isType: localError(c.config, a.info, "':' expected")
  1293. if kind in {skTemplate, skMacro}:
  1294. typ = newTypeS(tyUntyped, c)
  1295. elif skipTypes(typ, {tyGenericInst, tyAlias, tySink}).kind == tyVoid:
  1296. continue
  1297. for j in 0..<a.len-2:
  1298. var arg = newSymG(skParam, if a[j].kind == nkPragmaExpr: a[j][0] else: a[j], c)
  1299. if arg.name.id == ord(wUnderscore):
  1300. arg.flags.incl(sfGenSym)
  1301. elif containsOrIncl(check, arg.name.id):
  1302. localError(c.config, a[j].info, "attempt to redefine: '" & arg.name.s & "'")
  1303. if a[j].kind == nkPragmaExpr:
  1304. pragma(c, arg, a[j][1], paramPragmas)
  1305. if not hasType and not hasDefault and kind notin {skTemplate, skMacro}:
  1306. let param = strTableGet(c.signatures, arg.name)
  1307. if param != nil: typ = param.typ
  1308. else:
  1309. localError(c.config, a.info, "parameter '$1' requires a type" % arg.name.s)
  1310. typ = errorType(c)
  1311. var nameForLift = arg.name.s
  1312. if sfGenSym in arg.flags:
  1313. nameForLift.add("`gensym" & $arg.id)
  1314. let lifted = liftParamType(c, kind, genericParams, typ,
  1315. nameForLift, arg.info)
  1316. let finalType = if lifted != nil: lifted else: typ.skipIntLit(c.idgen)
  1317. arg.typ = finalType
  1318. arg.position = counter
  1319. if constraint != nil:
  1320. #only replace the constraint when it has been set as arg could contain codegenDecl
  1321. arg.constraint = constraint
  1322. inc(counter)
  1323. if def != nil and def.kind != nkEmpty:
  1324. arg.ast = copyTree(def)
  1325. result.n.add newSymNode(arg)
  1326. rawAddSon(result, finalType)
  1327. addParamOrResult(c, arg, kind)
  1328. styleCheckDef(c, a[j].info, arg)
  1329. onDef(a[j].info, arg)
  1330. a[j] = newSymNode(arg)
  1331. var r: PType = nil
  1332. if n[0].kind != nkEmpty:
  1333. let isGeneric = isCurrentlyGeneric()
  1334. inc c.inGenericContext, ord(isGeneric)
  1335. r = semTypeNode(c, n[0], nil)
  1336. dec c.inGenericContext, ord(isGeneric)
  1337. if r != nil and kind in {skMacro, skTemplate} and r.kind == tyTyped:
  1338. # XXX: To implement the proposed change in the warning, just
  1339. # delete this entire if block. The rest is (at least at time of
  1340. # writing this comment) already implemented.
  1341. let info = n[0].info
  1342. const msg = "`typed` will change its meaning in future versions of Nim. " &
  1343. "`void` or no return type declaration at all has the same " &
  1344. "meaning as the current meaning of `typed` as return type " &
  1345. "declaration."
  1346. message(c.config, info, warnDeprecated, msg)
  1347. r = nil
  1348. if r != nil:
  1349. # turn explicit 'void' return type into 'nil' because the rest of the
  1350. # compiler only checks for 'nil':
  1351. if skipTypes(r, {tyGenericInst, tyAlias, tySink}).kind != tyVoid:
  1352. if kind notin {skMacro, skTemplate} and r.kind in {tyTyped, tyUntyped}:
  1353. localError(c.config, n[0].info, "return type '" & typeToString(r) &
  1354. "' is only valid for macros and templates")
  1355. # 'auto' as a return type does not imply a generic:
  1356. elif r.kind == tyAnything:
  1357. r = copyType(r, c.idgen, r.owner)
  1358. r.flags.incl tfRetType
  1359. elif r.kind == tyStatic:
  1360. # type allowed should forbid this type
  1361. discard
  1362. else:
  1363. if r.sym == nil or sfAnon notin r.sym.flags:
  1364. let lifted = liftParamType(c, kind, genericParams, r, "result",
  1365. n[0].info)
  1366. if lifted != nil:
  1367. r = lifted
  1368. #if r.kind != tyGenericParam:
  1369. #echo "came here for ", typeToString(r)
  1370. r.flags.incl tfRetType
  1371. r = skipIntLit(r, c.idgen)
  1372. if kind == skIterator:
  1373. # see tchainediterators
  1374. # in cases like iterator foo(it: iterator): typeof(it)
  1375. # we don't need to change the return type to iter[T]
  1376. result.flags.incl tfIterator
  1377. # XXX Would be nice if we could get rid of this
  1378. result[0] = r
  1379. let oldFlags = result.flags
  1380. propagateToOwner(result, r)
  1381. if oldFlags != result.flags:
  1382. # XXX This rather hacky way keeps 'tflatmap' compiling:
  1383. if tfHasMeta notin oldFlags:
  1384. result.flags.excl tfHasMeta
  1385. result.n.typ = r
  1386. if isCurrentlyGeneric():
  1387. for n in genericParams:
  1388. if {sfUsed, sfAnon} * n.sym.flags == {}:
  1389. result.flags.incl tfUnresolved
  1390. if tfWildcard in n.sym.typ.flags:
  1391. n.sym.transitionGenericParamToType()
  1392. n.sym.typ.flags.excl tfWildcard
  1393. proc semStmtListType(c: PContext, n: PNode, prev: PType): PType =
  1394. checkMinSonsLen(n, 1, c.config)
  1395. for i in 0..<n.len - 1:
  1396. n[i] = semStmt(c, n[i], {})
  1397. if n.len > 0:
  1398. result = semTypeNode(c, n[^1], prev)
  1399. n.typ = result
  1400. n[^1].typ = result
  1401. else:
  1402. result = nil
  1403. proc semBlockType(c: PContext, n: PNode, prev: PType): PType =
  1404. inc(c.p.nestedBlockCounter)
  1405. let oldBreakInLoop = c.p.breakInLoop
  1406. c.p.breakInLoop = false
  1407. checkSonsLen(n, 2, c.config)
  1408. openScope(c)
  1409. if n[0].kind notin {nkEmpty, nkSym}:
  1410. addDecl(c, newSymS(skLabel, n[0], c))
  1411. result = semStmtListType(c, n[1], prev)
  1412. n[1].typ = result
  1413. n.typ = result
  1414. closeScope(c)
  1415. c.p.breakInLoop = oldBreakInLoop
  1416. dec(c.p.nestedBlockCounter)
  1417. proc semGenericParamInInvocation(c: PContext, n: PNode): PType =
  1418. result = semTypeNode(c, n, nil)
  1419. n.typ = makeTypeDesc(c, result)
  1420. proc trySemObjectTypeForInheritedGenericInst(c: PContext, n: PNode, t: PType): bool =
  1421. var
  1422. check = initIntSet()
  1423. pos = 0
  1424. let
  1425. realBase = t.baseClass
  1426. base = skipTypesOrNil(realBase, skipPtrs)
  1427. result = true
  1428. if base.isNil:
  1429. localError(c.config, n.info, errIllegalRecursionInTypeX % "object")
  1430. else:
  1431. let concreteBase = skipGenericInvocation(base)
  1432. if concreteBase.kind == tyObject and tfFinal notin concreteBase.flags:
  1433. if not tryAddInheritedFields(c, check, pos, concreteBase, n):
  1434. return false
  1435. else:
  1436. if concreteBase.kind != tyError:
  1437. localError(c.config, n.info, errInheritanceOnlyWithNonFinalObjects)
  1438. var newf = newNodeI(nkRecList, n.info)
  1439. semRecordNodeAux(c, t.n, check, pos, newf, t)
  1440. proc containsGenericInvocationWithForward(n: PNode): bool =
  1441. if n.kind == nkSym and n.sym.ast != nil and n.sym.ast.len > 1 and n.sym.ast[2].kind == nkObjectTy:
  1442. for p in n.sym.ast[2][^1]:
  1443. if p.kind == nkIdentDefs and p[1].typ != nil and p[1].typ.kind == tyGenericInvocation and
  1444. p[1][0].kind == nkSym and p[1][0].typ.kind == tyForward:
  1445. return true
  1446. return false
  1447. proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType =
  1448. if s.typ == nil:
  1449. localError(c.config, n.info, "cannot instantiate the '$1' $2" %
  1450. [s.name.s, s.kind.toHumanStr])
  1451. return newOrPrevType(tyError, prev, c)
  1452. var t = s.typ.skipTypes({tyAlias})
  1453. if t.kind == tyCompositeTypeClass and t.base.kind == tyGenericBody:
  1454. t = t.base
  1455. result = newOrPrevType(tyGenericInvocation, prev, c)
  1456. addSonSkipIntLit(result, t, c.idgen)
  1457. template addToResult(typ, skip) =
  1458. if typ.isNil:
  1459. internalAssert c.config, false
  1460. rawAddSon(result, typ)
  1461. else:
  1462. if skip:
  1463. addSonSkipIntLit(result, typ, c.idgen)
  1464. else:
  1465. rawAddSon(result, makeRangeWithStaticExpr(c, typ.n))
  1466. if t.kind == tyForward:
  1467. for i in 1..<n.len:
  1468. var elem = semGenericParamInInvocation(c, n[i])
  1469. addToResult(elem, true)
  1470. return
  1471. elif t.kind != tyGenericBody:
  1472. # we likely got code of the form TypeA[TypeB] where TypeA is
  1473. # not generic.
  1474. localError(c.config, n.info, errNoGenericParamsAllowedForX % s.name.s)
  1475. return newOrPrevType(tyError, prev, c)
  1476. else:
  1477. var m = newCandidate(c, t)
  1478. m.isNoCall = true
  1479. matches(c, n, copyTree(n), m)
  1480. if m.state != csMatch:
  1481. var err = "cannot instantiate "
  1482. err.addTypeHeader(c.config, t)
  1483. err.add "\ngot: <$1>\nbut expected: <$2>" % [describeArgs(c, n), describeArgs(c, t.n, 0)]
  1484. localError(c.config, n.info, errGenerated, err)
  1485. return newOrPrevType(tyError, prev, c)
  1486. var isConcrete = true
  1487. let rType = m.call[0].typ
  1488. let mIndex = if rType != nil: rType.len - 1 else: -1
  1489. for i in 1..<m.call.len:
  1490. var typ = m.call[i].typ
  1491. # is this a 'typedesc' *parameter*? If so, use the typedesc type,
  1492. # unstripped.
  1493. if m.call[i].kind == nkSym and m.call[i].sym.kind == skParam and
  1494. typ.kind == tyTypeDesc and containsGenericType(typ):
  1495. isConcrete = false
  1496. addToResult(typ, true)
  1497. else:
  1498. typ = typ.skipTypes({tyTypeDesc})
  1499. if containsGenericType(typ): isConcrete = false
  1500. var skip = true
  1501. if mIndex >= i - 1 and tfImplicitStatic in rType[i - 1].flags and isIntLit(typ):
  1502. skip = false
  1503. addToResult(typ, skip)
  1504. if isConcrete:
  1505. if s.ast == nil and s.typ.kind != tyCompositeTypeClass:
  1506. # XXX: What kind of error is this? is it still relevant?
  1507. localError(c.config, n.info, errCannotInstantiateX % s.name.s)
  1508. result = newOrPrevType(tyError, prev, c)
  1509. elif containsGenericInvocationWithForward(n[0]):
  1510. c.skipTypes.add n #fixes 1500
  1511. else:
  1512. result = instGenericContainer(c, n.info, result,
  1513. allowMetaTypes = false)
  1514. # special check for generic object with
  1515. # generic/partial specialized parent
  1516. let tx = result.skipTypes(abstractPtrs, 50)
  1517. if tx.isNil or isTupleRecursive(tx):
  1518. localError(c.config, n.info, "illegal recursion in type '$1'" % typeToString(result[0]))
  1519. return errorType(c)
  1520. if tx != result and tx.kind == tyObject:
  1521. if tx[0] != nil:
  1522. if not trySemObjectTypeForInheritedGenericInst(c, n, tx):
  1523. return newOrPrevType(tyError, prev, c)
  1524. var position = 0
  1525. recomputeFieldPositions(tx, tx.n, position)
  1526. proc maybeAliasType(c: PContext; typeExpr, prev: PType): PType =
  1527. if prev != nil and (prev.kind == tyGenericBody or
  1528. typeExpr.kind in {tyObject, tyEnum, tyDistinct, tyForward, tyGenericBody}):
  1529. result = newTypeS(tyAlias, c)
  1530. result.rawAddSon typeExpr
  1531. result.sym = prev.sym
  1532. if prev.kind != tyGenericBody:
  1533. assignType(prev, result)
  1534. else:
  1535. result = nil
  1536. proc fixupTypeOf(c: PContext, prev: PType, typExpr: PNode) =
  1537. if prev != nil:
  1538. let result = newTypeS(tyAlias, c)
  1539. result.rawAddSon typExpr.typ
  1540. result.sym = prev.sym
  1541. if prev.kind != tyGenericBody:
  1542. assignType(prev, result)
  1543. proc semTypeExpr(c: PContext, n: PNode; prev: PType): PType =
  1544. var n = semExprWithType(c, n, {efDetermineType})
  1545. if n.typ.kind == tyTypeDesc:
  1546. result = n.typ.base
  1547. # fix types constructed by macros/template:
  1548. if prev != nil and prev.kind != tyGenericBody and prev.sym != nil:
  1549. if result.sym.isNil:
  1550. # Behold! you're witnessing enormous power yielded
  1551. # by macros. Only macros can summon unnamed types
  1552. # and cast spell upon AST. Here we need to give
  1553. # it a name taken from left hand side's node
  1554. result.sym = prev.sym
  1555. result.sym.typ = result
  1556. else:
  1557. # Less powerful routine like template do not have
  1558. # the ability to produce unnamed types. But still
  1559. # it has wild power to push a type a bit too far.
  1560. # So we need to hold it back using alias and prevent
  1561. # unnecessary new type creation
  1562. let alias = maybeAliasType(c, result, prev)
  1563. if alias != nil: result = alias
  1564. elif n.typ.kind == tyFromExpr and c.inGenericContext > 0:
  1565. # sometimes not possible to distinguish type from value in generic body,
  1566. # for example `T.Foo`, so both are handled under `tyFromExpr`
  1567. result = n.typ
  1568. else:
  1569. localError(c.config, n.info, "expected type, but got: " & n.renderTree)
  1570. result = errorType(c)
  1571. proc freshType(c: PContext; res, prev: PType): PType {.inline.} =
  1572. if prev.isNil or prev.kind == tyGenericBody:
  1573. result = copyType(res, c.idgen, res.owner)
  1574. copyTypeProps(c.graph, c.idgen.module, result, res)
  1575. else:
  1576. result = res
  1577. template modifierTypeKindOfNode(n: PNode): TTypeKind =
  1578. case n.kind
  1579. of nkVarTy: tyVar
  1580. of nkRefTy: tyRef
  1581. of nkPtrTy: tyPtr
  1582. of nkStaticTy: tyStatic
  1583. of nkTypeOfExpr: tyTypeDesc
  1584. else: tyNone
  1585. proc semTypeClass(c: PContext, n: PNode, prev: PType): PType =
  1586. # if n.len == 0: return newConstraint(c, tyTypeClass)
  1587. if isNewStyleConcept(n):
  1588. result = newOrPrevType(tyConcept, prev, c)
  1589. result.flags.incl tfCheckedForDestructor
  1590. result.n = semConceptDeclaration(c, n)
  1591. return result
  1592. let
  1593. pragmas = n[1]
  1594. inherited = n[2]
  1595. var owner = getCurrOwner(c)
  1596. var candidateTypeSlot = newTypeS(tyAlias, c, c.errorType)
  1597. result = newOrPrevType(tyUserTypeClass, prev, c, son = candidateTypeSlot)
  1598. result.flags.incl tfCheckedForDestructor
  1599. result.n = n
  1600. if inherited.kind != nkEmpty:
  1601. for n in inherited.sons:
  1602. let typ = semTypeNode(c, n, nil)
  1603. result.add(typ)
  1604. openScope(c)
  1605. for param in n[0]:
  1606. var
  1607. dummyName: PNode
  1608. dummyType: PType
  1609. let modifier = param.modifierTypeKindOfNode
  1610. if modifier != tyNone:
  1611. dummyName = param[0]
  1612. dummyType = c.makeTypeWithModifier(modifier, candidateTypeSlot)
  1613. # if modifier == tyRef:
  1614. # dummyType.flags.incl tfNotNil
  1615. if modifier == tyTypeDesc:
  1616. dummyType.flags.incl tfConceptMatchedTypeSym
  1617. dummyType.flags.incl tfCheckedForDestructor
  1618. else:
  1619. dummyName = param
  1620. dummyType = candidateTypeSlot
  1621. # this can be true for 'nim check' on incomplete concepts,
  1622. # see bug #8230
  1623. if dummyName.kind == nkEmpty: continue
  1624. internalAssert c.config, dummyName.kind == nkIdent
  1625. var dummyParam = newSym(if modifier == tyTypeDesc: skType else: skVar,
  1626. dummyName.ident, c.idgen, owner, param.info)
  1627. dummyParam.typ = dummyType
  1628. incl dummyParam.flags, sfUsed
  1629. addDecl(c, dummyParam)
  1630. result.n[3] = semConceptBody(c, n[3])
  1631. closeScope(c)
  1632. proc applyTypeSectionPragmas(c: PContext; pragmas, operand: PNode): PNode =
  1633. result = nil
  1634. for p in pragmas:
  1635. let key = if p.kind in nkPragmaCallKinds and p.len >= 1: p[0] else: p
  1636. if p.kind == nkEmpty or whichPragma(p) != wInvalid:
  1637. discard "builtin pragma"
  1638. else:
  1639. trySuggestPragmas(c, key)
  1640. let ident =
  1641. if key.kind in nkIdentKinds:
  1642. considerQuotedIdent(c, key)
  1643. else:
  1644. nil
  1645. if ident != nil and strTableGet(c.userPragmas, ident) != nil:
  1646. discard "User-defined pragma"
  1647. else:
  1648. let sym = qualifiedLookUp(c, key, {})
  1649. # XXX: What to do here if amb is true?
  1650. if sym != nil and sfCustomPragma in sym.flags:
  1651. discard "Custom user pragma"
  1652. else:
  1653. # we transform ``(arg1, arg2: T) {.m, rest.}`` into ``m((arg1, arg2: T) {.rest.})`` and
  1654. # let the semantic checker deal with it:
  1655. var x = newNodeI(nkCall, key.info)
  1656. x.add(key)
  1657. if p.kind in nkPragmaCallKinds and p.len > 1:
  1658. # pass pragma arguments to the macro too:
  1659. for i in 1 ..< p.len:
  1660. x.add(p[i])
  1661. # Also pass the node the pragma has been applied to
  1662. x.add(operand.copyTreeWithoutNode(p))
  1663. # recursion assures that this works for multiple macro annotations too:
  1664. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  1665. if r != nil:
  1666. doAssert r[0].kind == nkSym
  1667. let m = r[0].sym
  1668. case m.kind
  1669. of skMacro: return semMacroExpr(c, r, r, m, {efNoSemCheck})
  1670. of skTemplate: return semTemplateExpr(c, r, m, {efNoSemCheck})
  1671. else: doAssert(false, "cannot happen")
  1672. proc semProcTypeWithScope(c: PContext, n: PNode,
  1673. prev: PType, kind: TSymKind): PType =
  1674. checkSonsLen(n, 2, c.config)
  1675. if n[1].kind != nkEmpty and n[1].len > 0:
  1676. let macroEval = applyTypeSectionPragmas(c, n[1], n)
  1677. if macroEval != nil:
  1678. return semTypeNode(c, macroEval, prev)
  1679. openScope(c)
  1680. result = semProcTypeNode(c, n[0], nil, prev, kind, isType=true)
  1681. # start with 'ccClosure', but of course pragmas can overwrite this:
  1682. result.callConv = ccClosure
  1683. # dummy symbol for `pragma`:
  1684. var s = newSymS(kind, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  1685. s.typ = result
  1686. if n[1].kind != nkEmpty and n[1].len > 0:
  1687. pragma(c, s, n[1], procTypePragmas)
  1688. when useEffectSystem: setEffectsForProcType(c.graph, result, n[1])
  1689. elif c.optionStack.len > 0:
  1690. # we construct a fake 'nkProcDef' for the 'mergePragmas' inside 'implicitPragmas'...
  1691. s.ast = newTree(nkProcDef, newNodeI(nkEmpty, n.info), newNodeI(nkEmpty, n.info),
  1692. newNodeI(nkEmpty, n.info), newNodeI(nkEmpty, n.info), newNodeI(nkEmpty, n.info))
  1693. implicitPragmas(c, s, n.info, {wTags, wRaises})
  1694. when useEffectSystem: setEffectsForProcType(c.graph, result, s.ast[pragmasPos])
  1695. closeScope(c)
  1696. proc symFromExpectedTypeNode(c: PContext, n: PNode): PSym =
  1697. if n.kind == nkType:
  1698. result = symFromType(c, n.typ, n.info)
  1699. else:
  1700. localError(c.config, n.info, errTypeExpected)
  1701. result = errorSym(c, n)
  1702. proc semStaticType(c: PContext, childNode: PNode, prev: PType): PType =
  1703. result = newOrPrevType(tyStatic, prev, c)
  1704. var base = semTypeNode(c, childNode, nil).skipTypes({tyTypeDesc, tyAlias})
  1705. result.rawAddSon(base)
  1706. result.flags.incl tfHasStatic
  1707. proc semTypeOf(c: PContext; n: PNode; prev: PType): PType =
  1708. openScope(c)
  1709. inc c.inTypeofContext
  1710. let t = semExprWithType(c, n, {efInTypeof})
  1711. dec c.inTypeofContext
  1712. closeScope(c)
  1713. fixupTypeOf(c, prev, t)
  1714. result = t.typ
  1715. proc semTypeOf2(c: PContext; n: PNode; prev: PType): PType =
  1716. openScope(c)
  1717. var m = BiggestInt 1 # typeOfIter
  1718. if n.len == 3:
  1719. let mode = semConstExpr(c, n[2])
  1720. if mode.kind != nkIntLit:
  1721. localError(c.config, n.info, "typeof: cannot evaluate 'mode' parameter at compile-time")
  1722. else:
  1723. m = mode.intVal
  1724. inc c.inTypeofContext
  1725. let t = semExprWithType(c, n[1], if m == 1: {efInTypeof} else: {})
  1726. dec c.inTypeofContext
  1727. closeScope(c)
  1728. fixupTypeOf(c, prev, t)
  1729. result = t.typ
  1730. proc semTypeIdent(c: PContext, n: PNode): PSym =
  1731. if n.kind == nkSym:
  1732. result = getGenSym(c, n.sym)
  1733. else:
  1734. result = pickSym(c, n, {skType, skGenericParam, skParam})
  1735. if result.isNil:
  1736. result = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared})
  1737. if result != nil:
  1738. markUsed(c, n.info, result)
  1739. onUse(n.info, result)
  1740. # alias syntax, see semSym for skTemplate, skMacro
  1741. if result.kind in {skTemplate, skMacro} and sfNoalias notin result.flags:
  1742. let t = semTypeExpr(c, n, nil)
  1743. result = symFromType(c, t, n.info)
  1744. if result.kind == skParam and result.typ.kind == tyTypeDesc:
  1745. # This is a typedesc param. is it already bound?
  1746. # it's not bound when it's used multiple times in the
  1747. # proc signature for example
  1748. if c.inGenericInst > 0:
  1749. let bound = result.typ.elementType.sym
  1750. if bound != nil: return bound
  1751. return result
  1752. if result.typ.sym == nil:
  1753. localError(c.config, n.info, errTypeExpected)
  1754. return errorSym(c, n)
  1755. result = result.typ.sym.copySym(c.idgen)
  1756. result.typ = exactReplica(result.typ)
  1757. result.typ.flags.incl tfUnresolved
  1758. if result.kind == skGenericParam:
  1759. if result.typ.kind == tyGenericParam and result.typ.len == 0 and
  1760. tfWildcard in result.typ.flags:
  1761. # collapse the wild-card param to a type
  1762. result.transitionGenericParamToType()
  1763. result.typ.flags.excl tfWildcard
  1764. return
  1765. else:
  1766. localError(c.config, n.info, errTypeExpected)
  1767. return errorSym(c, n)
  1768. if result.kind != skType and result.magic notin {mStatic, mType, mTypeOf}:
  1769. # this implements the wanted ``var v: V, x: V`` feature ...
  1770. var ov: TOverloadIter = default(TOverloadIter)
  1771. var amb = initOverloadIter(ov, c, n)
  1772. while amb != nil and amb.kind != skType:
  1773. amb = nextOverloadIter(ov, c, n)
  1774. if amb != nil: result = amb
  1775. else:
  1776. if result.kind != skError: localError(c.config, n.info, errTypeExpected)
  1777. return errorSym(c, n)
  1778. if result.typ.kind != tyGenericParam:
  1779. # XXX get rid of this hack!
  1780. var oldInfo = n.info
  1781. when defined(useNodeIds):
  1782. let oldId = n.id
  1783. reset(n[])
  1784. when defined(useNodeIds):
  1785. n.id = oldId
  1786. n.transitionNoneToSym()
  1787. n.sym = result
  1788. n.info = oldInfo
  1789. n.typ = result.typ
  1790. else:
  1791. localError(c.config, n.info, "identifier expected")
  1792. result = errorSym(c, n)
  1793. proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
  1794. result = nil
  1795. inc c.inTypeContext
  1796. if c.config.cmd == cmdIdeTools: suggestExpr(c, n)
  1797. case n.kind
  1798. of nkEmpty: result = n.typ
  1799. of nkTypeOfExpr:
  1800. # for ``typeof(countup(1,3))``, see ``tests/ttoseq``.
  1801. checkSonsLen(n, 1, c.config)
  1802. result = semTypeOf(c, n[0], prev)
  1803. if result.kind == tyTypeDesc: result.flags.incl tfExplicit
  1804. of nkPar:
  1805. if n.len == 1: result = semTypeNode(c, n[0], prev)
  1806. else:
  1807. result = semAnonTuple(c, n, prev)
  1808. of nkTupleConstr: result = semAnonTuple(c, n, prev)
  1809. of nkCallKinds:
  1810. let x = n[0]
  1811. let ident = x.getPIdent
  1812. if ident != nil and ident.s == "[]":
  1813. let b = newNodeI(nkBracketExpr, n.info)
  1814. for i in 1..<n.len: b.add(n[i])
  1815. result = semTypeNode(c, b, prev)
  1816. elif ident != nil and ident.id == ord(wDotDot):
  1817. result = semRangeAux(c, n, prev)
  1818. elif n[0].kind == nkNilLit and n.len == 2:
  1819. result = semTypeNode(c, n[1], prev)
  1820. if result.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).kind in NilableTypes+GenericTypes:
  1821. if tfNotNil in result.flags:
  1822. result = freshType(c, result, prev)
  1823. result.flags.excl(tfNotNil)
  1824. else:
  1825. localError(c.config, n.info, errGenerated, "invalid type")
  1826. elif n[0].kind notin nkIdentKinds:
  1827. result = semTypeExpr(c, n, prev)
  1828. else:
  1829. let op = considerQuotedIdent(c, n[0])
  1830. if op.id == ord(wAnd) or op.id == ord(wOr) or op.s == "|":
  1831. checkSonsLen(n, 3, c.config)
  1832. var
  1833. t1 = semTypeNode(c, n[1], nil)
  1834. t2 = semTypeNode(c, n[2], nil)
  1835. if t1 == nil:
  1836. localError(c.config, n[1].info, errTypeExpected)
  1837. result = newOrPrevType(tyError, prev, c)
  1838. elif t2 == nil:
  1839. localError(c.config, n[2].info, errTypeExpected)
  1840. result = newOrPrevType(tyError, prev, c)
  1841. else:
  1842. result = if op.id == ord(wAnd): makeAndType(c, t1, t2)
  1843. else: makeOrType(c, t1, t2)
  1844. elif op.id == ord(wNot):
  1845. case n.len
  1846. of 3:
  1847. result = semTypeNode(c, n[1], prev)
  1848. if result.kind == tyTypeDesc and tfUnresolved notin result.flags:
  1849. result = result.base
  1850. if n[2].kind != nkNilLit:
  1851. localError(c.config, n.info,
  1852. "Invalid syntax. When used with a type, 'not' can be followed only by 'nil'")
  1853. if notnil notin c.features and strictNotNil notin c.features:
  1854. localError(c.config, n.info,
  1855. "enable the 'not nil' annotation with {.experimental: \"notnil\".} or " &
  1856. " the `strict not nil` annotation with {.experimental: \"strictNotNil\".} " &
  1857. " the \"notnil\" one is going to be deprecated, so please use \"strictNotNil\"")
  1858. let resolvedType = result.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned})
  1859. case resolvedType.kind
  1860. of tyGenericParam, tyTypeDesc, tyFromExpr:
  1861. # XXX: This is a really inappropraite hack, but it solves
  1862. # https://github.com/nim-lang/Nim/issues/4907 for now.
  1863. #
  1864. # A proper solution is to introduce a new type kind such
  1865. # as `tyNotNil[tyRef[SomeGenericParam]]`. This will allow
  1866. # semtypinst to replace the generic param correctly in
  1867. # situations like the following:
  1868. #
  1869. # type Foo[T] = object
  1870. # bar: ref T not nil
  1871. # baz: ref T
  1872. #
  1873. # The root of the problem is that `T` here must have a specific
  1874. # ID that is bound to a concrete type during instantiation.
  1875. # The use of `freshType` below breaks this. Another hack would
  1876. # be to reuse the same ID for the not nil type, but this will
  1877. # fail if the `T` parameter is referenced multiple times as in
  1878. # the example above.
  1879. #
  1880. # I suggest revisiting this once the language decides on whether
  1881. # `not nil` should be the default. We can then map nilable refs
  1882. # to other types such as `Option[T]`.
  1883. result = makeTypeFromExpr(c, newTree(nkStmtListType, n.copyTree))
  1884. of NilableTypes + {tyGenericInvocation, tyForward}:
  1885. result = freshType(c, result, prev)
  1886. result.flags.incl(tfNotNil)
  1887. else:
  1888. localError(c.config, n.info, errGenerated, "invalid type")
  1889. of 2:
  1890. let negated = semTypeNode(c, n[1], prev)
  1891. result = makeNotType(c, negated)
  1892. else:
  1893. localError(c.config, n.info, errGenerated, "invalid type")
  1894. elif op.id == ord(wPtr):
  1895. result = semAnyRef(c, n, tyPtr, prev)
  1896. elif op.id == ord(wRef):
  1897. result = semAnyRef(c, n, tyRef, prev)
  1898. elif op.id == ord(wType):
  1899. checkSonsLen(n, 2, c.config)
  1900. result = semTypeOf(c, n[1], prev)
  1901. elif op.s == "typeof" and (
  1902. (n[0].kind == nkSym and n[0].sym.magic == mTypeOf) or
  1903. (n[0].kind == nkOpenSym and n[0][0].sym.magic == mTypeOf)):
  1904. result = semTypeOf2(c, n, prev)
  1905. elif op.s == "owned" and optOwnedRefs notin c.config.globalOptions and n.len == 2:
  1906. result = semTypeExpr(c, n[1], prev)
  1907. else:
  1908. result = semTypeExpr(c, n, prev)
  1909. of nkWhenStmt:
  1910. var whenResult = semWhen(c, n, false)
  1911. if whenResult.kind == nkStmtList: whenResult.transitionSonsKind(nkStmtListType)
  1912. result = semTypeNode(c, whenResult, prev)
  1913. of nkBracketExpr:
  1914. checkMinSonsLen(n, 2, c.config)
  1915. var head = n[0]
  1916. var s = if head.kind notin nkCallKinds: semTypeIdent(c, head)
  1917. else: symFromExpectedTypeNode(c, semExpr(c, head))
  1918. case s.magic
  1919. of mArray: result = semArray(c, n, prev)
  1920. of mOpenArray: result = semContainer(c, n, tyOpenArray, "openarray", prev)
  1921. of mUncheckedArray: result = semContainer(c, n, tyUncheckedArray, "UncheckedArray", prev)
  1922. of mRange: result = semRange(c, n, prev)
  1923. of mSet: result = semSet(c, n, prev)
  1924. of mOrdinal: result = semOrdinal(c, n, prev)
  1925. of mIterableType: result = semIterableType(c, n, prev)
  1926. of mSeq:
  1927. result = semContainer(c, n, tySequence, "seq", prev)
  1928. if optSeqDestructors in c.config.globalOptions:
  1929. incl result.flags, tfHasAsgn
  1930. of mVarargs: result = semVarargs(c, n, prev)
  1931. of mTypeDesc, mType, mTypeOf:
  1932. result = makeTypeDesc(c, semTypeNode(c, n[1], nil))
  1933. result.flags.incl tfExplicit
  1934. of mStatic:
  1935. result = semStaticType(c, n[1], prev)
  1936. of mExpr:
  1937. result = semTypeNode(c, n[0], nil)
  1938. if result != nil:
  1939. let old = result
  1940. result = copyType(result, c.idgen, getCurrOwner(c))
  1941. copyTypeProps(c.graph, c.idgen.module, result, old)
  1942. for i in 1..<n.len:
  1943. result.rawAddSon(semTypeNode(c, n[i], nil))
  1944. of mDistinct:
  1945. result = newOrPrevType(tyDistinct, prev, c)
  1946. addSonSkipIntLit(result, semTypeNode(c, n[1], nil), c.idgen)
  1947. of mVar:
  1948. result = newOrPrevType(tyVar, prev, c)
  1949. var base = semTypeNode(c, n[1], nil)
  1950. if base.kind in {tyVar, tyLent}:
  1951. localError(c.config, n.info, "type 'var var' is not allowed")
  1952. base = base[0]
  1953. addSonSkipIntLit(result, base, c.idgen)
  1954. of mRef: result = semAnyRef(c, n, tyRef, prev)
  1955. of mPtr: result = semAnyRef(c, n, tyPtr, prev)
  1956. of mTuple: result = semTuple(c, n, prev)
  1957. else: result = semGeneric(c, n, s, prev)
  1958. of nkDotExpr:
  1959. let typeExpr = semExpr(c, n)
  1960. if typeExpr.typ.isNil:
  1961. localError(c.config, n.info, "object constructor needs an object type;" &
  1962. " for named arguments use '=' instead of ':'")
  1963. result = errorType(c)
  1964. elif typeExpr.typ.kind == tyFromExpr:
  1965. result = typeExpr.typ
  1966. elif typeExpr.typ.kind != tyTypeDesc:
  1967. localError(c.config, n.info, errTypeExpected)
  1968. result = errorType(c)
  1969. else:
  1970. result = typeExpr.typ.base
  1971. if result.isMetaType and
  1972. result.kind != tyUserTypeClass:
  1973. # the dot expression may refer to a concept type in
  1974. # a different module. allow a normal alias then.
  1975. let preprocessed = semGenericStmt(c, n)
  1976. result = makeTypeFromExpr(c, preprocessed.copyTree)
  1977. else:
  1978. let alias = maybeAliasType(c, result, prev)
  1979. if alias != nil: result = alias
  1980. of nkIdent, nkAccQuoted:
  1981. var s = semTypeIdent(c, n)
  1982. if s.typ == nil:
  1983. if s.kind != skError: localError(c.config, n.info, errTypeExpected)
  1984. result = newOrPrevType(tyError, prev, c)
  1985. elif s.kind == skParam and s.typ.kind == tyTypeDesc:
  1986. internalAssert c.config, s.typ.base.kind != tyNone and prev == nil
  1987. result = s.typ.base
  1988. elif prev == nil:
  1989. result = s.typ
  1990. else:
  1991. let alias = maybeAliasType(c, s.typ, prev)
  1992. if alias != nil:
  1993. result = alias
  1994. elif prev.kind == tyGenericBody:
  1995. result = s.typ
  1996. else:
  1997. assignType(prev, s.typ)
  1998. # bugfix: keep the fresh id for aliases to integral types:
  1999. if s.typ.kind notin {tyBool, tyChar, tyInt..tyInt64, tyFloat..tyFloat128,
  2000. tyUInt..tyUInt64}:
  2001. prev.itemId = s.typ.itemId
  2002. result = prev
  2003. of nkSym:
  2004. let s = getGenSym(c, n.sym)
  2005. if s.typ != nil and (s.kind == skType or s.typ.kind == tyTypeDesc):
  2006. var t =
  2007. if s.kind == skType:
  2008. s.typ
  2009. else:
  2010. internalAssert c.config, s.typ.base.kind != tyNone and prev == nil
  2011. s.typ.base
  2012. let alias = maybeAliasType(c, t, prev)
  2013. if alias != nil:
  2014. result = alias
  2015. elif prev == nil or prev.kind == tyGenericBody:
  2016. result = t
  2017. else:
  2018. assignType(prev, t)
  2019. result = prev
  2020. markUsed(c, n.info, n.sym)
  2021. onUse(n.info, n.sym)
  2022. else:
  2023. if s.kind != skError:
  2024. if s.typ == nil:
  2025. localError(c.config, n.info, "type expected, but symbol '$1' has no type." % [s.name.s])
  2026. else:
  2027. localError(c.config, n.info, "type expected, but got symbol '$1' of kind '$2'" %
  2028. [s.name.s, s.kind.toHumanStr])
  2029. result = newOrPrevType(tyError, prev, c)
  2030. of nkObjectTy: result = semObjectNode(c, n, prev, {})
  2031. of nkTupleTy: result = semTuple(c, n, prev)
  2032. of nkTupleClassTy: result = newConstraint(c, tyTuple)
  2033. of nkTypeClassTy: result = semTypeClass(c, n, prev)
  2034. of nkRefTy: result = semAnyRef(c, n, tyRef, prev)
  2035. of nkPtrTy: result = semAnyRef(c, n, tyPtr, prev)
  2036. of nkVarTy: result = semVarOutType(c, n, prev, {})
  2037. of nkOutTy: result = semVarOutType(c, n, prev, {tfIsOutParam})
  2038. of nkDistinctTy: result = semDistinct(c, n, prev)
  2039. of nkStaticTy: result = semStaticType(c, n[0], prev)
  2040. of nkProcTy, nkIteratorTy:
  2041. if n.len == 0 or n[0].kind == nkEmpty:
  2042. # 0 length or empty param list with possible pragmas imply typeclass
  2043. result = newTypeS(tyBuiltInTypeClass, c)
  2044. let child = newTypeS(tyProc, c)
  2045. if n.kind == nkIteratorTy:
  2046. child.flags.incl tfIterator
  2047. if n.len > 0 and n[1].kind != nkEmpty and n[1].len > 0:
  2048. # typeclass with pragma
  2049. let symKind = if n.kind == nkIteratorTy: skIterator else: skProc
  2050. # dummy symbol for `pragma`:
  2051. var s = newSymS(symKind, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  2052. s.typ = child
  2053. # for now only call convention pragmas supported in proc typeclass
  2054. pragma(c, s, n[1], {FirstCallConv..LastCallConv})
  2055. result.addSonSkipIntLit(child, c.idgen)
  2056. else:
  2057. let symKind = if n.kind == nkIteratorTy: skIterator else: skProc
  2058. result = semProcTypeWithScope(c, n, prev, symKind)
  2059. if result == nil:
  2060. localError(c.config, n.info, "type expected, but got: " & renderTree(n))
  2061. result = newOrPrevType(tyError, prev, c)
  2062. if n.kind == nkIteratorTy and result.kind == tyProc:
  2063. result.flags.incl(tfIterator)
  2064. if result.callConv == ccClosure and c.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  2065. result.flags.incl tfHasAsgn
  2066. of nkEnumTy: result = semEnum(c, n, prev)
  2067. of nkType: result = n.typ
  2068. of nkStmtListType: result = semStmtListType(c, n, prev)
  2069. of nkBlockType: result = semBlockType(c, n, prev)
  2070. of nkOpenSym: result = semTypeNode(c, n[0], prev)
  2071. else:
  2072. result = semTypeExpr(c, n, prev)
  2073. when false:
  2074. localError(c.config, n.info, "type expected, but got: " & renderTree(n))
  2075. result = newOrPrevType(tyError, prev, c)
  2076. n.typ = result
  2077. dec c.inTypeContext
  2078. proc setMagicType(conf: ConfigRef; m: PSym, kind: TTypeKind, size: int) =
  2079. # source : https://en.wikipedia.org/wiki/Data_structure_alignment#x86
  2080. m.typ.kind = kind
  2081. m.typ.size = size
  2082. # this usually works for most basic types
  2083. # Assuming that since ARM, ARM64 don't support unaligned access
  2084. # data is aligned to type size
  2085. m.typ.align = size.int16
  2086. # FIXME: proper support for clongdouble should be added.
  2087. # long double size can be 8, 10, 12, 16 bytes depending on platform & compiler
  2088. if kind in {tyFloat64, tyFloat, tyInt, tyUInt, tyInt64, tyUInt64} and size == 8:
  2089. m.typ.align = int16(conf.floatInt64Align)
  2090. proc setMagicIntegral(conf: ConfigRef; m: PSym, kind: TTypeKind, size: int) =
  2091. setMagicType(conf, m, kind, size)
  2092. incl m.typ.flags, tfCheckedForDestructor
  2093. proc processMagicType(c: PContext, m: PSym) =
  2094. case m.magic
  2095. of mInt: setMagicIntegral(c.config, m, tyInt, c.config.target.intSize)
  2096. of mInt8: setMagicIntegral(c.config, m, tyInt8, 1)
  2097. of mInt16: setMagicIntegral(c.config, m, tyInt16, 2)
  2098. of mInt32: setMagicIntegral(c.config, m, tyInt32, 4)
  2099. of mInt64: setMagicIntegral(c.config, m, tyInt64, 8)
  2100. of mUInt: setMagicIntegral(c.config, m, tyUInt, c.config.target.intSize)
  2101. of mUInt8: setMagicIntegral(c.config, m, tyUInt8, 1)
  2102. of mUInt16: setMagicIntegral(c.config, m, tyUInt16, 2)
  2103. of mUInt32: setMagicIntegral(c.config, m, tyUInt32, 4)
  2104. of mUInt64: setMagicIntegral(c.config, m, tyUInt64, 8)
  2105. of mFloat: setMagicIntegral(c.config, m, tyFloat, c.config.target.floatSize)
  2106. of mFloat32: setMagicIntegral(c.config, m, tyFloat32, 4)
  2107. of mFloat64: setMagicIntegral(c.config, m, tyFloat64, 8)
  2108. of mFloat128: setMagicIntegral(c.config, m, tyFloat128, 16)
  2109. of mBool: setMagicIntegral(c.config, m, tyBool, 1)
  2110. of mChar: setMagicIntegral(c.config, m, tyChar, 1)
  2111. of mString:
  2112. setMagicType(c.config, m, tyString, szUncomputedSize)
  2113. rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
  2114. if optSeqDestructors in c.config.globalOptions:
  2115. incl m.typ.flags, tfHasAsgn
  2116. of mCstring:
  2117. setMagicIntegral(c.config, m, tyCstring, c.config.target.ptrSize)
  2118. rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
  2119. of mPointer: setMagicIntegral(c.config, m, tyPointer, c.config.target.ptrSize)
  2120. of mNil: setMagicType(c.config, m, tyNil, c.config.target.ptrSize)
  2121. of mExpr:
  2122. if m.name.s == "auto":
  2123. setMagicIntegral(c.config, m, tyAnything, 0)
  2124. else:
  2125. setMagicIntegral(c.config, m, tyUntyped, 0)
  2126. of mStmt:
  2127. setMagicIntegral(c.config, m, tyTyped, 0)
  2128. of mTypeDesc, mType:
  2129. setMagicIntegral(c.config, m, tyTypeDesc, 0)
  2130. rawAddSon(m.typ, newTypeS(tyNone, c))
  2131. of mStatic:
  2132. setMagicType(c.config, m, tyStatic, 0)
  2133. rawAddSon(m.typ, newTypeS(tyNone, c))
  2134. of mVoidType:
  2135. setMagicIntegral(c.config, m, tyVoid, 0)
  2136. of mArray:
  2137. setMagicType(c.config, m, tyArray, szUncomputedSize)
  2138. of mOpenArray:
  2139. setMagicType(c.config, m, tyOpenArray, szUncomputedSize)
  2140. of mVarargs:
  2141. setMagicType(c.config, m, tyVarargs, szUncomputedSize)
  2142. of mRange:
  2143. setMagicIntegral(c.config, m, tyRange, szUncomputedSize)
  2144. rawAddSon(m.typ, newTypeS(tyNone, c))
  2145. of mSet:
  2146. setMagicIntegral(c.config, m, tySet, szUncomputedSize)
  2147. of mUncheckedArray:
  2148. setMagicIntegral(c.config, m, tyUncheckedArray, szUncomputedSize)
  2149. of mSeq:
  2150. setMagicType(c.config, m, tySequence, szUncomputedSize)
  2151. if optSeqDestructors in c.config.globalOptions:
  2152. incl m.typ.flags, tfHasAsgn
  2153. if defined(nimsuggest) or c.config.cmd == cmdCheck: # bug #18985
  2154. discard
  2155. else:
  2156. assert c.graph.sysTypes[tySequence] == nil
  2157. c.graph.sysTypes[tySequence] = m.typ
  2158. of mOrdinal:
  2159. setMagicIntegral(c.config, m, tyOrdinal, szUncomputedSize)
  2160. rawAddSon(m.typ, newTypeS(tyNone, c))
  2161. of mIterableType:
  2162. setMagicIntegral(c.config, m, tyIterable, 0)
  2163. rawAddSon(m.typ, newTypeS(tyNone, c))
  2164. of mPNimrodNode:
  2165. incl m.typ.flags, tfTriggersCompileTime
  2166. incl m.typ.flags, tfCheckedForDestructor
  2167. of mException: discard
  2168. of mBuiltinType:
  2169. case m.name.s
  2170. of "lent": setMagicType(c.config, m, tyLent, c.config.target.ptrSize)
  2171. of "sink": setMagicType(c.config, m, tySink, szUncomputedSize)
  2172. of "owned":
  2173. setMagicType(c.config, m, tyOwned, c.config.target.ptrSize)
  2174. incl m.typ.flags, tfHasOwned
  2175. else: localError(c.config, m.info, errTypeExpected)
  2176. else: localError(c.config, m.info, errTypeExpected)
  2177. proc semGenericConstraints(c: PContext, x: PType): PType =
  2178. result = newTypeS(tyGenericParam, c, x)
  2179. proc semGenericParamList(c: PContext, n: PNode, father: PType = nil): PNode =
  2180. template addSym(result: PNode, s: PSym): untyped =
  2181. if father != nil: addSonSkipIntLit(father, s.typ, c.idgen)
  2182. if sfGenSym notin s.flags: addDecl(c, s)
  2183. result.add newSymNode(s)
  2184. result = copyNode(n)
  2185. if n.kind != nkGenericParams:
  2186. illFormedAst(n, c.config)
  2187. return
  2188. for i in 0..<n.len:
  2189. var a = n[i]
  2190. case a.kind
  2191. of nkSym: result.addSym(a.sym)
  2192. of nkIdentDefs:
  2193. var def = a[^1]
  2194. let constraint = a[^2]
  2195. var typ: PType = nil
  2196. if constraint.kind != nkEmpty:
  2197. typ = semTypeNode(c, constraint, nil)
  2198. if typ.kind != tyStatic or typ.len == 0:
  2199. if typ.kind == tyTypeDesc:
  2200. if typ.elementType.kind == tyNone:
  2201. typ = newTypeS(tyTypeDesc, c, newTypeS(tyNone, c))
  2202. incl typ.flags, tfCheckedForDestructor
  2203. else:
  2204. typ = semGenericConstraints(c, typ)
  2205. if def.kind != nkEmpty:
  2206. def = semConstExpr(c, def)
  2207. if typ == nil:
  2208. if def.typ.kind != tyTypeDesc:
  2209. typ = newTypeS(tyStatic, c, def.typ)
  2210. else:
  2211. # the following line fixes ``TV2*[T:SomeNumber=TR] = array[0..1, T]``
  2212. # from manyloc/named_argument_bug/triengine:
  2213. def.typ = def.typ.skipTypes({tyTypeDesc})
  2214. if not containsGenericType(def.typ):
  2215. def = fitNode(c, typ, def, def.info)
  2216. if typ == nil:
  2217. typ = newTypeS(tyGenericParam, c)
  2218. if father == nil: typ.flags.incl tfWildcard
  2219. typ.flags.incl tfGenericTypeParam
  2220. for j in 0..<a.len-2:
  2221. var finalType: PType
  2222. if j == 0:
  2223. finalType = typ
  2224. else:
  2225. finalType = copyType(typ, c.idgen, typ.owner)
  2226. copyTypeProps(c.graph, c.idgen.module, finalType, typ)
  2227. # it's important the we create an unique
  2228. # type for each generic param. the index
  2229. # of the parameter will be stored in the
  2230. # attached symbol.
  2231. var paramName = a[j]
  2232. var covarianceFlag = tfUnresolved
  2233. if paramName.safeLen == 2:
  2234. if not nimEnableCovariance or paramName[0].ident.s == "in":
  2235. if father == nil or sfImportc notin father.sym.flags:
  2236. localError(c.config, paramName.info, errInOutFlagNotExtern % $paramName[0])
  2237. covarianceFlag = if paramName[0].ident.s == "in": tfContravariant
  2238. else: tfCovariant
  2239. if father != nil: father.flags.incl tfCovariant
  2240. paramName = paramName[1]
  2241. var s = if finalType.kind == tyStatic or tfWildcard in typ.flags:
  2242. newSymG(skGenericParam, paramName, c).linkTo(finalType)
  2243. else:
  2244. newSymG(skType, paramName, c).linkTo(finalType)
  2245. if covarianceFlag != tfUnresolved: s.typ.flags.incl(covarianceFlag)
  2246. if def.kind != nkEmpty: s.ast = def
  2247. s.position = result.len
  2248. result.addSym(s)
  2249. else:
  2250. illFormedAst(n, c.config)