semtypes.nim 93 KB

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