semexprs.nim 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 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 for expressions
  10. # included from sem.nim
  11. const
  12. errExprXHasNoType = "expression '$1' has no type (or is ambiguous)"
  13. errXExpectsTypeOrValue = "'$1' expects a type or value"
  14. errVarForOutParamNeededX = "for a 'var' type a variable needs to be passed; but '$1' is immutable"
  15. errXStackEscape = "address of '$1' may not escape its stack frame"
  16. errExprHasNoAddress = "expression has no address; maybe use 'unsafeAddr'"
  17. errCannotInterpretNodeX = "cannot evaluate '$1'"
  18. errNamedExprExpected = "named expression expected"
  19. errNamedExprNotAllowed = "named expression not allowed here"
  20. errFieldInitTwice = "field initialized twice: '$1'"
  21. errUndeclaredFieldX = "undeclared field: '$1'"
  22. proc semTemplateExpr(c: PContext, n: PNode, s: PSym,
  23. flags: TExprFlags = {}): PNode =
  24. markUsed(c.config, n.info, s, c.graph.usageSym)
  25. onUse(n.info, s)
  26. pushInfoContext(c.config, n.info, s.detailedInfo)
  27. result = evalTemplate(n, s, getCurrOwner(c), c.config, efFromHlo in flags)
  28. if efNoSemCheck notin flags: result = semAfterMacroCall(c, n, result, s, flags)
  29. popInfoContext(c.config)
  30. # XXX: A more elaborate line info rewrite might be needed
  31. result.info = n.info
  32. proc semFieldAccess(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  33. proc semOperand(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  34. # same as 'semExprWithType' but doesn't check for proc vars
  35. result = semExpr(c, n, flags + {efOperand})
  36. #if result.kind == nkEmpty and result.typ.isNil:
  37. # do not produce another redundant error message:
  38. #raiseRecoverableError("")
  39. # result = errorNode(c, n)
  40. if result.typ != nil:
  41. # XXX tyGenericInst here?
  42. if result.typ.kind == tyProc and tfUnresolved in result.typ.flags:
  43. localError(c.config, n.info, errProcHasNoConcreteType % n.renderTree)
  44. if result.typ.kind in {tyVar, tyLent}: result = newDeref(result)
  45. elif {efWantStmt, efAllowStmt} * flags != {}:
  46. result.typ = newTypeS(tyVoid, c)
  47. else:
  48. localError(c.config, n.info, errExprXHasNoType %
  49. renderTree(result, {renderNoComments}))
  50. result.typ = errorType(c)
  51. proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  52. result = semExpr(c, n, flags+{efWantValue})
  53. if result.isNil or result.kind == nkEmpty:
  54. # do not produce another redundant error message:
  55. #raiseRecoverableError("")
  56. result = errorNode(c, n)
  57. if result.typ == nil or result.typ == c.enforceVoidContext:
  58. localError(c.config, n.info, errExprXHasNoType %
  59. renderTree(result, {renderNoComments}))
  60. result.typ = errorType(c)
  61. else:
  62. if result.typ.kind in {tyVar, tyLent}: result = newDeref(result)
  63. proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  64. result = semExpr(c, n, flags)
  65. if result.kind == nkEmpty:
  66. # do not produce another redundant error message:
  67. result = errorNode(c, n)
  68. if result.typ == nil:
  69. localError(c.config, n.info, errExprXHasNoType %
  70. renderTree(result, {renderNoComments}))
  71. result.typ = errorType(c)
  72. proc semSymGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode =
  73. result = symChoice(c, n, s, scClosed)
  74. proc inlineConst(c: PContext, n: PNode, s: PSym): PNode {.inline.} =
  75. result = copyTree(s.ast)
  76. if result.isNil:
  77. localError(c.config, n.info, "constant of type '" & typeToString(s.typ) & "' has no value")
  78. result = newSymNode(s)
  79. else:
  80. result.typ = s.typ
  81. result.info = n.info
  82. type
  83. TConvStatus = enum
  84. convOK,
  85. convNotNeedeed,
  86. convNotLegal
  87. proc checkConversionBetweenObjects(castDest, src: PType; pointers: int): TConvStatus =
  88. let diff = inheritanceDiff(castDest, src)
  89. return if diff == high(int) or (pointers > 1 and diff != 0):
  90. convNotLegal
  91. else:
  92. convOK
  93. const
  94. IntegralTypes = {tyBool, tyEnum, tyChar, tyInt..tyUInt64}
  95. proc checkConvertible(c: PContext, castDest, src: PType): TConvStatus =
  96. result = convOK
  97. if sameType(castDest, src) and castDest.sym == src.sym:
  98. # don't annoy conversions that may be needed on another processor:
  99. if castDest.kind notin IntegralTypes+{tyRange}:
  100. result = convNotNeedeed
  101. return
  102. # Save for later
  103. var d = skipTypes(castDest, abstractVar)
  104. var s = src
  105. if s.kind in tyUserTypeClasses and s.isResolvedUserTypeClass:
  106. s = s.lastSon
  107. s = skipTypes(s, abstractVar-{tyTypeDesc})
  108. var pointers = 0
  109. while (d != nil) and (d.kind in {tyPtr, tyRef}) and (d.kind == s.kind):
  110. d = d.lastSon
  111. s = s.lastSon
  112. inc pointers
  113. if d == nil:
  114. result = convNotLegal
  115. elif d.kind == tyObject and s.kind == tyObject:
  116. result = checkConversionBetweenObjects(d, s, pointers)
  117. elif (skipTypes(castDest, abstractVarRange).kind in IntegralTypes) and
  118. (skipTypes(src, abstractVarRange-{tyTypeDesc}).kind in IntegralTypes):
  119. # accept conversion between integral types
  120. discard
  121. else:
  122. # we use d, s here to speed up that operation a bit:
  123. case cmpTypes(c, d, s)
  124. of isNone, isGeneric:
  125. if not compareTypes(castDest.skipTypes(abstractVar), src, dcEqIgnoreDistinct):
  126. result = convNotLegal
  127. else:
  128. discard
  129. proc isCastable(conf: ConfigRef; dst, src: PType): bool =
  130. ## Checks whether the source type can be cast to the destination type.
  131. ## Casting is very unrestrictive; casts are allowed as long as
  132. ## castDest.size >= src.size, and typeAllowed(dst, skParam)
  133. #const
  134. # castableTypeKinds = {tyInt, tyPtr, tyRef, tyCstring, tyString,
  135. # tySequence, tyPointer, tyNil, tyOpenArray,
  136. # tyProc, tySet, tyEnum, tyBool, tyChar}
  137. let src = src.skipTypes(tyUserTypeClasses)
  138. if skipTypes(dst, abstractInst-{tyOpenArray}).kind == tyOpenArray:
  139. return false
  140. if skipTypes(src, abstractInst-{tyTypeDesc}).kind == tyTypeDesc:
  141. return false
  142. var dstSize, srcSize: BiggestInt
  143. dstSize = computeSize(conf, dst)
  144. srcSize = computeSize(conf, src)
  145. if dstSize == -3 or srcSize == -3: # szUnknownSize
  146. # The Nim compiler can't detect if it's legal or not.
  147. # Just assume the programmer knows what he is doing.
  148. return true
  149. if dstSize < 0:
  150. result = false
  151. elif srcSize < 0:
  152. result = false
  153. elif typeAllowed(dst, skParam) != nil:
  154. result = false
  155. elif dst.kind == tyProc and dst.callConv == ccClosure:
  156. result = src.kind == tyProc and src.callConv == ccClosure
  157. else:
  158. result = (dstSize >= srcSize) or
  159. (skipTypes(dst, abstractInst).kind in IntegralTypes) or
  160. (skipTypes(src, abstractInst-{tyTypeDesc}).kind in IntegralTypes)
  161. if result and src.kind == tyNil:
  162. result = dst.size <= conf.target.ptrSize
  163. proc isSymChoice(n: PNode): bool {.inline.} =
  164. result = n.kind in nkSymChoices
  165. proc maybeLiftType(t: var PType, c: PContext, info: TLineInfo) =
  166. # XXX: liftParamType started to perform addDecl
  167. # we could do that instead in semTypeNode by snooping for added
  168. # gnrc. params, then it won't be necessary to open a new scope here
  169. openScope(c)
  170. var lifted = liftParamType(c, skType, newNodeI(nkArgList, info),
  171. t, ":anon", info)
  172. closeScope(c)
  173. if lifted != nil: t = lifted
  174. proc semConv(c: PContext, n: PNode): PNode =
  175. if sonsLen(n) != 2:
  176. localError(c.config, n.info, "a type conversion takes exactly one argument")
  177. return n
  178. result = newNodeI(nkConv, n.info)
  179. var targetType = semTypeNode(c, n.sons[0], nil)
  180. if targetType.kind == tyTypeDesc:
  181. internalAssert c.config, targetType.len > 0
  182. if targetType.base.kind == tyNone:
  183. return semTypeOf(c, n)
  184. else:
  185. targetType = targetType.base
  186. elif targetType.kind == tyStatic:
  187. var evaluated = semStaticExpr(c, n[1])
  188. if evaluated.kind == nkType or evaluated.typ.kind == tyTypeDesc:
  189. result = n
  190. result.typ = c.makeTypeDesc semStaticType(c, evaluated, nil)
  191. return
  192. elif targetType.base.kind == tyNone:
  193. return evaluated
  194. else:
  195. targetType = targetType.base
  196. maybeLiftType(targetType, c, n[0].info)
  197. if targetType.kind in {tySink, tyLent}:
  198. let baseType = semTypeNode(c, n.sons[1], nil).skipTypes({tyTypeDesc})
  199. let t = newTypeS(targetType.kind, c)
  200. t.rawAddSonNoPropagationOfTypeFlags baseType
  201. result = newNodeI(nkType, n.info)
  202. result.typ = makeTypeDesc(c, t)
  203. return
  204. result.addSon copyTree(n.sons[0])
  205. # special case to make MyObject(x = 3) produce a nicer error message:
  206. if n[1].kind == nkExprEqExpr and
  207. targetType.skipTypes(abstractPtrs).kind == tyObject:
  208. localError(c.config, n.info, "object contruction uses ':', not '='")
  209. var op = semExprWithType(c, n.sons[1])
  210. if targetType.isMetaType:
  211. let final = inferWithMetatype(c, targetType, op, true)
  212. result.addSon final
  213. result.typ = final.typ
  214. return
  215. result.typ = targetType
  216. # XXX op is overwritten later on, this is likely added too early
  217. # here or needs to be overwritten too then.
  218. addSon(result, op)
  219. if not isSymChoice(op):
  220. let status = checkConvertible(c, result.typ, op.typ)
  221. case status
  222. of convOK:
  223. # handle SomeProcType(SomeGenericProc)
  224. if op.kind == nkSym and op.sym.isGenericRoutine:
  225. result.sons[1] = fitNode(c, result.typ, result.sons[1], result.info)
  226. elif op.kind in {nkPar, nkTupleConstr} and targetType.kind == tyTuple:
  227. op = fitNode(c, targetType, op, result.info)
  228. of convNotNeedeed:
  229. message(c.config, n.info, hintConvFromXtoItselfNotNeeded, result.typ.typeToString)
  230. of convNotLegal:
  231. result = fitNode(c, result.typ, result.sons[1], result.info)
  232. if result == nil:
  233. localError(c.config, n.info, "illegal conversion from '$1' to '$2'" %
  234. [op.typ.typeToString, result.typ.typeToString])
  235. else:
  236. for i in countup(0, sonsLen(op) - 1):
  237. let it = op.sons[i]
  238. let status = checkConvertible(c, result.typ, it.typ)
  239. if status in {convOK, convNotNeedeed}:
  240. markUsed(c.config, n.info, it.sym, c.graph.usageSym)
  241. onUse(n.info, it.sym)
  242. markIndirect(c, it.sym)
  243. return it
  244. errorUseQualifier(c, n.info, op.sons[0].sym)
  245. proc semCast(c: PContext, n: PNode): PNode =
  246. ## Semantically analyze a casting ("cast[type](param)")
  247. checkSonsLen(n, 2, c.config)
  248. let targetType = semTypeNode(c, n.sons[0], nil)
  249. let castedExpr = semExprWithType(c, n.sons[1])
  250. if tfHasMeta in targetType.flags:
  251. localError(c.config, n.sons[0].info, "cannot cast to a non concrete type: '$1'" % $targetType)
  252. if not isCastable(c.config, targetType, castedExpr.typ):
  253. let tar = $targetType
  254. let alt = typeToString(targetType, preferDesc)
  255. let msg = if tar != alt: tar & "=" & alt else: tar
  256. localError(c.config, n.info, "expression cannot be cast to " & msg)
  257. result = newNodeI(nkCast, n.info)
  258. result.typ = targetType
  259. addSon(result, copyTree(n.sons[0]))
  260. addSon(result, castedExpr)
  261. proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode =
  262. const
  263. opToStr: array[mLow..mHigh, string] = ["low", "high"]
  264. if sonsLen(n) != 2:
  265. localError(c.config, n.info, errXExpectsTypeOrValue % opToStr[m])
  266. else:
  267. n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType})
  268. var typ = skipTypes(n.sons[1].typ, abstractVarRange + {tyTypeDesc, tyUserTypeClassInst})
  269. case typ.kind
  270. of tySequence, tyString, tyCString, tyOpenArray, tyVarargs:
  271. n.typ = getSysType(c.graph, n.info, tyInt)
  272. of tyArray:
  273. n.typ = typ.sons[0] # indextype
  274. of tyInt..tyInt64, tyChar, tyBool, tyEnum, tyUInt8, tyUInt16, tyUInt32:
  275. # do not skip the range!
  276. n.typ = n.sons[1].typ.skipTypes(abstractVar)
  277. of tyGenericParam:
  278. # prepare this for resolving in semtypinst:
  279. # we must use copyTree here in order to avoid creating a cycle
  280. # that could easily turn into an infinite recursion in semtypinst
  281. n.typ = makeTypeFromExpr(c, n.copyTree)
  282. else:
  283. localError(c.config, n.info, "invalid argument for: " & opToStr[m])
  284. result = n
  285. proc fixupStaticType(c: PContext, n: PNode) =
  286. # This proc can be applied to evaluated expressions to assign
  287. # them a static type.
  288. #
  289. # XXX: with implicit static, this should not be necessary,
  290. # because the output type of operations such as `semConstExpr`
  291. # should be a static type (as well as the type of any other
  292. # expression that can be implicitly evaluated). For now, we
  293. # apply this measure only in code that is enlightened to work
  294. # with static types.
  295. if n.typ.kind != tyStatic:
  296. n.typ = newTypeWithSons(getCurrOwner(c), tyStatic, @[n.typ])
  297. n.typ.n = n # XXX: cycles like the one here look dangerous.
  298. # Consider using `n.copyTree`
  299. proc isOpImpl(c: PContext, n: PNode, flags: TExprFlags): PNode =
  300. internalAssert c.config,
  301. n.sonsLen == 3 and
  302. n[1].typ != nil and
  303. n[2].kind in {nkStrLit..nkTripleStrLit, nkType}
  304. var
  305. res = false
  306. t1 = n[1].typ
  307. t2 = n[2].typ
  308. if t1.kind == tyTypeDesc and t2.kind != tyTypeDesc:
  309. t1 = t1.base
  310. if n[2].kind in {nkStrLit..nkTripleStrLit}:
  311. case n[2].strVal.normalize
  312. of "closure":
  313. let t = skipTypes(t1, abstractRange)
  314. res = t.kind == tyProc and
  315. t.callConv == ccClosure and
  316. tfIterator notin t.flags
  317. of "iterator":
  318. let t = skipTypes(t1, abstractRange)
  319. res = t.kind == tyProc and
  320. t.callConv == ccClosure and
  321. tfIterator in t.flags
  322. else:
  323. res = false
  324. else:
  325. maybeLiftType(t2, c, n.info)
  326. var m: TCandidate
  327. initCandidate(c, m, t2)
  328. if efExplain in flags:
  329. m.diagnostics = @[]
  330. m.diagnosticsEnabled = true
  331. res = typeRel(m, t2, t1) >= isSubtype # isNone
  332. result = newIntNode(nkIntLit, ord(res))
  333. result.typ = n.typ
  334. proc semIs(c: PContext, n: PNode, flags: TExprFlags): PNode =
  335. if sonsLen(n) != 3:
  336. localError(c.config, n.info, "'is' operator takes 2 arguments")
  337. let boolType = getSysType(c.graph, n.info, tyBool)
  338. result = n
  339. n.typ = boolType
  340. var liftLhs = true
  341. n.sons[1] = semExprWithType(c, n[1], {efDetermineType, efWantIterator})
  342. if n[2].kind notin {nkStrLit..nkTripleStrLit}:
  343. let t2 = semTypeNode(c, n[2], nil)
  344. n.sons[2] = newNodeIT(nkType, n[2].info, t2)
  345. if t2.kind == tyStatic:
  346. let evaluated = tryConstExpr(c, n[1])
  347. if evaluated != nil:
  348. c.fixupStaticType(evaluated)
  349. n[1] = evaluated
  350. else:
  351. result = newIntNode(nkIntLit, 0)
  352. result.typ = boolType
  353. return
  354. elif t2.kind == tyTypeDesc and
  355. (t2.base.kind == tyNone or tfExplicit in t2.flags):
  356. # When the right-hand side is an explicit type, we must
  357. # not allow regular values to be matched against the type:
  358. liftLhs = false
  359. else:
  360. n.sons[2] = semExpr(c, n[2])
  361. var lhsType = n[1].typ
  362. if lhsType.kind != tyTypeDesc:
  363. if liftLhs:
  364. n[1] = makeTypeSymNode(c, lhsType, n[1].info)
  365. lhsType = n[1].typ
  366. else:
  367. internalAssert c.config, lhsType.base.kind != tyNone
  368. if c.inGenericContext > 0 and lhsType.base.containsGenericType:
  369. # BUGFIX: don't evaluate this too early: ``T is void``
  370. return
  371. result = isOpImpl(c, n, flags)
  372. proc semOpAux(c: PContext, n: PNode) =
  373. const flags = {efDetermineType}
  374. for i in countup(1, n.sonsLen-1):
  375. var a = n.sons[i]
  376. if a.kind == nkExprEqExpr and sonsLen(a) == 2:
  377. let info = a.sons[0].info
  378. a.sons[0] = newIdentNode(considerQuotedIdent(c, a.sons[0], a), info)
  379. a.sons[1] = semExprWithType(c, a.sons[1], flags)
  380. a.typ = a.sons[1].typ
  381. else:
  382. n.sons[i] = semExprWithType(c, a, flags)
  383. proc overloadedCallOpr(c: PContext, n: PNode): PNode =
  384. # quick check if there is *any* () operator overloaded:
  385. var par = getIdent(c.cache, "()")
  386. if searchInScopes(c, par) == nil:
  387. result = nil
  388. else:
  389. result = newNodeI(nkCall, n.info)
  390. addSon(result, newIdentNode(par, n.info))
  391. for i in countup(0, sonsLen(n) - 1): addSon(result, n.sons[i])
  392. result = semExpr(c, result)
  393. proc changeType(c: PContext; n: PNode, newType: PType, check: bool) =
  394. case n.kind
  395. of nkCurly, nkBracket:
  396. for i in countup(0, sonsLen(n) - 1):
  397. changeType(c, n.sons[i], elemType(newType), check)
  398. of nkPar, nkTupleConstr:
  399. let tup = newType.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct})
  400. if tup.kind != tyTuple:
  401. if tup.kind == tyObject: return
  402. globalError(c.config, n.info, "no tuple type for constructor")
  403. elif sonsLen(n) > 0 and n.sons[0].kind == nkExprColonExpr:
  404. # named tuple?
  405. for i in countup(0, sonsLen(n) - 1):
  406. var m = n.sons[i].sons[0]
  407. if m.kind != nkSym:
  408. globalError(c.config, m.info, "invalid tuple constructor")
  409. return
  410. if tup.n != nil:
  411. var f = getSymFromList(tup.n, m.sym.name)
  412. if f == nil:
  413. globalError(c.config, m.info, "unknown identifier: " & m.sym.name.s)
  414. return
  415. changeType(c, n.sons[i].sons[1], f.typ, check)
  416. else:
  417. changeType(c, n.sons[i].sons[1], tup.sons[i], check)
  418. else:
  419. for i in countup(0, sonsLen(n) - 1):
  420. changeType(c, n.sons[i], tup.sons[i], check)
  421. when false:
  422. var m = n.sons[i]
  423. var a = newNodeIT(nkExprColonExpr, m.info, newType.sons[i])
  424. addSon(a, newSymNode(newType.n.sons[i].sym))
  425. addSon(a, m)
  426. changeType(m, tup.sons[i], check)
  427. of nkCharLit..nkUInt64Lit:
  428. if check and n.kind != nkUInt64Lit:
  429. let value = n.intVal
  430. if value < firstOrd(c.config, newType) or value > lastOrd(c.config, newType):
  431. localError(c.config, n.info, "cannot convert " & $value &
  432. " to " & typeToString(newType))
  433. else: discard
  434. n.typ = newType
  435. proc arrayConstrType(c: PContext, n: PNode): PType =
  436. var typ = newTypeS(tyArray, c)
  437. rawAddSon(typ, nil) # index type
  438. if sonsLen(n) == 0:
  439. rawAddSon(typ, newTypeS(tyEmpty, c)) # needs an empty basetype!
  440. else:
  441. var t = skipTypes(n.sons[0].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  442. addSonSkipIntLit(typ, t)
  443. typ.sons[0] = makeRangeType(c, 0, sonsLen(n) - 1, n.info)
  444. result = typ
  445. proc semArrayConstr(c: PContext, n: PNode, flags: TExprFlags): PNode =
  446. result = newNodeI(nkBracket, n.info)
  447. result.typ = newTypeS(tyArray, c)
  448. rawAddSon(result.typ, nil) # index type
  449. if sonsLen(n) == 0:
  450. rawAddSon(result.typ, newTypeS(tyEmpty, c)) # needs an empty basetype!
  451. else:
  452. var x = n.sons[0]
  453. var lastIndex: BiggestInt = 0
  454. var indexType = getSysType(c.graph, n.info, tyInt)
  455. if x.kind == nkExprColonExpr and sonsLen(x) == 2:
  456. var idx = semConstExpr(c, x.sons[0])
  457. lastIndex = getOrdValue(idx)
  458. indexType = idx.typ
  459. x = x.sons[1]
  460. let yy = semExprWithType(c, x)
  461. var typ = yy.typ
  462. addSon(result, yy)
  463. #var typ = skipTypes(result.sons[0].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal})
  464. for i in countup(1, sonsLen(n) - 1):
  465. x = n.sons[i]
  466. if x.kind == nkExprColonExpr and sonsLen(x) == 2:
  467. var idx = semConstExpr(c, x.sons[0])
  468. idx = fitNode(c, indexType, idx, x.info)
  469. if lastIndex+1 != getOrdValue(idx):
  470. localError(c.config, x.info, "invalid order in array constructor")
  471. x = x.sons[1]
  472. let xx = semExprWithType(c, x, flags*{efAllowDestructor})
  473. result.add xx
  474. typ = commonType(typ, xx.typ)
  475. #n.sons[i] = semExprWithType(c, x, flags*{efAllowDestructor})
  476. #addSon(result, fitNode(c, typ, n.sons[i]))
  477. inc(lastIndex)
  478. addSonSkipIntLit(result.typ, typ)
  479. for i in 0 ..< result.len:
  480. result.sons[i] = fitNode(c, typ, result.sons[i], result.sons[i].info)
  481. result.typ.sons[0] = makeRangeType(c, 0, sonsLen(result) - 1, n.info)
  482. proc fixAbstractType(c: PContext, n: PNode) =
  483. for i in 1 ..< n.len:
  484. let it = n.sons[i]
  485. # do not get rid of nkHiddenSubConv for OpenArrays, the codegen needs it:
  486. if it.kind == nkHiddenSubConv and
  487. skipTypes(it.typ, abstractVar).kind notin {tyOpenArray, tyVarargs}:
  488. if skipTypes(it.sons[1].typ, abstractVar).kind in
  489. {tyNil, tyTuple, tySet} or it[1].isArrayConstr:
  490. var s = skipTypes(it.typ, abstractVar)
  491. if s.kind != tyExpr:
  492. changeType(c, it.sons[1], s, check=true)
  493. n.sons[i] = it.sons[1]
  494. proc isAssignable(c: PContext, n: PNode; isUnsafeAddr=false): TAssignableResult =
  495. result = parampatterns.isAssignable(c.p.owner, n, isUnsafeAddr)
  496. proc isUnresolvedSym(s: PSym): bool =
  497. return s.kind == skGenericParam or
  498. tfInferrableStatic in s.typ.flags or
  499. (s.kind == skParam and s.typ.isMetaType) or
  500. (s.kind == skType and
  501. s.typ.flags * {tfGenericTypeParam, tfImplicitTypeParam} != {})
  502. proc hasUnresolvedArgs(c: PContext, n: PNode): bool =
  503. # Checks whether an expression depends on generic parameters that
  504. # don't have bound values yet. E.g. this could happen in situations
  505. # such as:
  506. # type Slot[T] = array[T.size, byte]
  507. # proc foo[T](x: default(T))
  508. #
  509. # Both static parameter and type parameters can be unresolved.
  510. case n.kind
  511. of nkSym:
  512. return isUnresolvedSym(n.sym)
  513. of nkIdent, nkAccQuoted:
  514. let ident = considerQuotedIdent(c, n)
  515. let sym = searchInScopes(c, ident)
  516. if sym != nil:
  517. return isUnresolvedSym(sym)
  518. else:
  519. return false
  520. else:
  521. for i in 0..<n.safeLen:
  522. if hasUnresolvedArgs(c, n.sons[i]): return true
  523. return false
  524. proc newHiddenAddrTaken(c: PContext, n: PNode): PNode =
  525. if n.kind == nkHiddenDeref and not (c.config.cmd == cmdCompileToCpp or
  526. sfCompileToCpp in c.module.flags):
  527. checkSonsLen(n, 1, c.config)
  528. result = n.sons[0]
  529. else:
  530. result = newNodeIT(nkHiddenAddr, n.info, makeVarType(c, n.typ))
  531. addSon(result, n)
  532. if isAssignable(c, n) notin {arLValue, arLocalLValue}:
  533. localError(c.config, n.info, errVarForOutParamNeededX % renderNotLValue(n))
  534. proc analyseIfAddressTaken(c: PContext, n: PNode): PNode =
  535. result = n
  536. case n.kind
  537. of nkSym:
  538. # n.sym.typ can be nil in 'check' mode ...
  539. if n.sym.typ != nil and
  540. skipTypes(n.sym.typ, abstractInst-{tyTypeDesc}).kind notin {tyVar, tyLent}:
  541. incl(n.sym.flags, sfAddrTaken)
  542. result = newHiddenAddrTaken(c, n)
  543. of nkDotExpr:
  544. checkSonsLen(n, 2, c.config)
  545. if n.sons[1].kind != nkSym:
  546. internalError(c.config, n.info, "analyseIfAddressTaken")
  547. return
  548. if skipTypes(n.sons[1].sym.typ, abstractInst-{tyTypeDesc}).kind notin {tyVar, tyLent}:
  549. incl(n.sons[1].sym.flags, sfAddrTaken)
  550. result = newHiddenAddrTaken(c, n)
  551. of nkBracketExpr:
  552. checkMinSonsLen(n, 1, c.config)
  553. if skipTypes(n.sons[0].typ, abstractInst-{tyTypeDesc}).kind notin {tyVar, tyLent}:
  554. if n.sons[0].kind == nkSym: incl(n.sons[0].sym.flags, sfAddrTaken)
  555. result = newHiddenAddrTaken(c, n)
  556. else:
  557. result = newHiddenAddrTaken(c, n)
  558. proc analyseIfAddressTakenInCall(c: PContext, n: PNode) =
  559. checkMinSonsLen(n, 1, c.config)
  560. const
  561. FakeVarParams = {mNew, mNewFinalize, mInc, ast.mDec, mIncl, mExcl,
  562. mSetLengthStr, mSetLengthSeq, mAppendStrCh, mAppendStrStr, mSwap,
  563. mAppendSeqElem, mNewSeq, mReset, mShallowCopy, mDeepCopy, mMove,
  564. mWasMoved}
  565. # get the real type of the callee
  566. # it may be a proc var with a generic alias type, so we skip over them
  567. var t = n.sons[0].typ.skipTypes({tyGenericInst, tyAlias, tySink})
  568. if n.sons[0].kind == nkSym and n.sons[0].sym.magic in FakeVarParams:
  569. # BUGFIX: check for L-Value still needs to be done for the arguments!
  570. # note sometimes this is eval'ed twice so we check for nkHiddenAddr here:
  571. for i in countup(1, sonsLen(n) - 1):
  572. if i < sonsLen(t) and t.sons[i] != nil and
  573. skipTypes(t.sons[i], abstractInst-{tyTypeDesc}).kind == tyVar:
  574. let it = n[i]
  575. if isAssignable(c, it) notin {arLValue, arLocalLValue}:
  576. if it.kind != nkHiddenAddr:
  577. localError(c.config, it.info, errVarForOutParamNeededX % $it)
  578. # bug #5113: disallow newSeq(result) where result is a 'var T':
  579. if n[0].sym.magic in {mNew, mNewFinalize, mNewSeq}:
  580. var arg = n[1] #.skipAddr
  581. if arg.kind == nkHiddenDeref: arg = arg[0]
  582. if arg.kind == nkSym and arg.sym.kind == skResult and
  583. arg.typ.skipTypes(abstractInst).kind in {tyVar, tyLent}:
  584. localError(c.config, n.info, errXStackEscape % renderTree(n[1], {renderNoComments}))
  585. return
  586. for i in countup(1, sonsLen(n) - 1):
  587. let n = if n.kind == nkHiddenDeref: n[0] else: n
  588. if n.sons[i].kind == nkHiddenCallConv:
  589. # we need to recurse explicitly here as converters can create nested
  590. # calls and then they wouldn't be analysed otherwise
  591. analyseIfAddressTakenInCall(c, n.sons[i])
  592. if i < sonsLen(t) and
  593. skipTypes(t.sons[i], abstractInst-{tyTypeDesc}).kind == tyVar:
  594. if n.sons[i].kind != nkHiddenAddr:
  595. n.sons[i] = analyseIfAddressTaken(c, n.sons[i])
  596. include semmagic
  597. proc evalAtCompileTime(c: PContext, n: PNode): PNode =
  598. result = n
  599. if n.kind notin nkCallKinds or n.sons[0].kind != nkSym: return
  600. var callee = n.sons[0].sym
  601. # workaround for bug #537 (overly aggressive inlining leading to
  602. # wrong NimNode semantics):
  603. if n.typ != nil and tfTriggersCompileTime in n.typ.flags: return
  604. # constant folding that is necessary for correctness of semantic pass:
  605. if callee.magic != mNone and callee.magic in ctfeWhitelist and n.typ != nil:
  606. var call = newNodeIT(nkCall, n.info, n.typ)
  607. call.add(n.sons[0])
  608. var allConst = true
  609. for i in 1 ..< n.len:
  610. var a = getConstExpr(c.module, n.sons[i], c.graph)
  611. if a == nil:
  612. allConst = false
  613. a = n.sons[i]
  614. if a.kind == nkHiddenStdConv: a = a.sons[1]
  615. call.add(a)
  616. if allConst:
  617. result = semfold.getConstExpr(c.module, call, c.graph)
  618. if result.isNil: result = n
  619. else: return result
  620. block maybeLabelAsStatic:
  621. # XXX: temporary work-around needed for tlateboundstatic.
  622. # This is certainly not correct, but it will get the job
  623. # done until we have a more robust infrastructure for
  624. # implicit statics.
  625. if n.len > 1:
  626. for i in 1 ..< n.len:
  627. # see bug #2113, it's possible that n[i].typ for errornous code:
  628. if n[i].typ.isNil or n[i].typ.kind != tyStatic or
  629. tfUnresolved notin n[i].typ.flags:
  630. break maybeLabelAsStatic
  631. n.typ = newTypeWithSons(c, tyStatic, @[n.typ])
  632. n.typ.flags.incl tfUnresolved
  633. # optimization pass: not necessary for correctness of the semantic pass
  634. if {sfNoSideEffect, sfCompileTime} * callee.flags != {} and
  635. {sfForward, sfImportc} * callee.flags == {} and n.typ != nil:
  636. if sfCompileTime notin callee.flags and
  637. optImplicitStatic notin c.config.options: return
  638. if callee.magic notin ctfeWhitelist: return
  639. if callee.kind notin {skProc, skFunc, skConverter} or callee.isGenericRoutine:
  640. return
  641. if n.typ != nil and typeAllowed(n.typ, skConst) != nil: return
  642. var call = newNodeIT(nkCall, n.info, n.typ)
  643. call.add(n.sons[0])
  644. for i in 1 ..< n.len:
  645. let a = getConstExpr(c.module, n.sons[i], c.graph)
  646. if a == nil: return n
  647. call.add(a)
  648. #echo "NOW evaluating at compile time: ", call.renderTree
  649. if sfCompileTime in callee.flags:
  650. result = evalStaticExpr(c.module, c.graph, call, c.p.owner)
  651. if result.isNil:
  652. localError(c.config, n.info, errCannotInterpretNodeX % renderTree(call))
  653. else: result = fixupTypeAfterEval(c, result, n)
  654. else:
  655. result = evalConstExpr(c.module, c.graph, call)
  656. if result.isNil: result = n
  657. else: result = fixupTypeAfterEval(c, result, n)
  658. #if result != n:
  659. # echo "SUCCESS evaluated at compile time: ", call.renderTree
  660. proc semStaticExpr(c: PContext, n: PNode): PNode =
  661. let a = semExpr(c, n)
  662. if a.findUnresolvedStatic != nil: return a
  663. result = evalStaticExpr(c.module, c.graph, a, c.p.owner)
  664. if result.isNil:
  665. localError(c.config, n.info, errCannotInterpretNodeX % renderTree(n))
  666. result = c.graph.emptyNode
  667. else:
  668. result = fixupTypeAfterEval(c, result, a)
  669. proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode,
  670. flags: TExprFlags): PNode =
  671. if flags*{efInTypeof, efWantIterator} != {}:
  672. # consider: 'for x in pReturningArray()' --> we don't want the restriction
  673. # to 'skIterator' anymore; skIterator is preferred in sigmatch already
  674. # for typeof support.
  675. # for ``type(countup(1,3))``, see ``tests/ttoseq``.
  676. result = semOverloadedCall(c, n, nOrig,
  677. {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate, skIterator}, flags)
  678. else:
  679. result = semOverloadedCall(c, n, nOrig,
  680. {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate}, flags)
  681. if result != nil:
  682. if result.sons[0].kind != nkSym:
  683. internalError(c.config, "semOverloadedCallAnalyseEffects")
  684. return
  685. let callee = result.sons[0].sym
  686. case callee.kind
  687. of skMacro, skTemplate: discard
  688. else:
  689. if callee.kind == skIterator and callee.id == c.p.owner.id:
  690. localError(c.config, n.info, errRecursiveDependencyX % callee.name.s)
  691. # error correction, prevents endless for loop elimination in transf.
  692. # See bug #2051:
  693. result.sons[0] = newSymNode(errorSym(c, n))
  694. proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode
  695. proc resolveIndirectCall(c: PContext; n, nOrig: PNode;
  696. t: PType): TCandidate =
  697. initCandidate(c, result, t)
  698. matches(c, n, nOrig, result)
  699. if result.state != csMatch:
  700. # try to deref the first argument:
  701. if implicitDeref in c.features and canDeref(n):
  702. n.sons[1] = n.sons[1].tryDeref
  703. initCandidate(c, result, t)
  704. matches(c, n, nOrig, result)
  705. proc bracketedMacro(n: PNode): PSym =
  706. if n.len >= 1 and n[0].kind == nkSym:
  707. result = n[0].sym
  708. if result.kind notin {skMacro, skTemplate}:
  709. result = nil
  710. proc setGenericParams(c: PContext, n: PNode) =
  711. for i in 1 ..< n.len:
  712. n[i].typ = semTypeNode(c, n[i], nil)
  713. proc afterCallActions(c: PContext; n, orig: PNode, flags: TExprFlags): PNode =
  714. result = n
  715. let callee = result.sons[0].sym
  716. case callee.kind
  717. of skMacro: result = semMacroExpr(c, result, orig, callee, flags)
  718. of skTemplate: result = semTemplateExpr(c, result, callee, flags)
  719. else:
  720. semFinishOperands(c, result)
  721. activate(c, result)
  722. fixAbstractType(c, result)
  723. analyseIfAddressTakenInCall(c, result)
  724. if callee.magic != mNone:
  725. result = magicsAfterOverloadResolution(c, result, flags)
  726. if result.typ != nil and
  727. not (result.typ.kind == tySequence and result.typ.sons[0].kind == tyEmpty):
  728. liftTypeBoundOps(c, result.typ, n.info)
  729. #result = patchResolvedTypeBoundOp(c, result)
  730. if c.matchedConcept == nil:
  731. result = evalAtCompileTime(c, result)
  732. proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode =
  733. result = nil
  734. checkMinSonsLen(n, 1, c.config)
  735. var prc = n.sons[0]
  736. if n.sons[0].kind == nkDotExpr:
  737. checkSonsLen(n.sons[0], 2, c.config)
  738. let n0 = semFieldAccess(c, n.sons[0])
  739. if n0.kind == nkDotCall:
  740. # it is a static call!
  741. result = n0
  742. result.kind = nkCall
  743. result.flags.incl nfExplicitCall
  744. for i in countup(1, sonsLen(n) - 1): addSon(result, n.sons[i])
  745. return semExpr(c, result, flags)
  746. else:
  747. n.sons[0] = n0
  748. else:
  749. n.sons[0] = semExpr(c, n.sons[0], {efInCall})
  750. let t = n.sons[0].typ
  751. if t != nil and t.kind in {tyVar, tyLent}:
  752. n.sons[0] = newDeref(n.sons[0])
  753. elif n.sons[0].kind == nkBracketExpr:
  754. let s = bracketedMacro(n.sons[0])
  755. if s != nil:
  756. setGenericParams(c, n[0])
  757. return semDirectOp(c, n, flags)
  758. let nOrig = n.copyTree
  759. semOpAux(c, n)
  760. var t: PType = nil
  761. if n.sons[0].typ != nil:
  762. t = skipTypes(n.sons[0].typ, abstractInst-{tyTypeDesc})
  763. if t != nil and t.kind == tyProc:
  764. # This is a proc variable, apply normal overload resolution
  765. let m = resolveIndirectCall(c, n, nOrig, t)
  766. if m.state != csMatch:
  767. if c.config.m.errorOutputs == {}:
  768. # speed up error generation:
  769. globalError(c.config, n.info, "type mismatch")
  770. return c.graph.emptyNode
  771. else:
  772. var hasErrorType = false
  773. var msg = "type mismatch: got <"
  774. for i in countup(1, sonsLen(n) - 1):
  775. if i > 1: add(msg, ", ")
  776. let nt = n.sons[i].typ
  777. add(msg, typeToString(nt))
  778. if nt.kind == tyError:
  779. hasErrorType = true
  780. break
  781. if not hasErrorType:
  782. add(msg, ">\nbut expected one of: \n" &
  783. typeToString(n.sons[0].typ))
  784. localError(c.config, n.info, msg)
  785. return errorNode(c, n)
  786. result = nil
  787. else:
  788. result = m.call
  789. instGenericConvertersSons(c, result, m)
  790. elif t != nil and t.kind == tyTypeDesc:
  791. if n.len == 1: return semObjConstr(c, n, flags)
  792. return semConv(c, n)
  793. else:
  794. result = overloadedCallOpr(c, n)
  795. # Now that nkSym does not imply an iteration over the proc/iterator space,
  796. # the old ``prc`` (which is likely an nkIdent) has to be restored:
  797. if result == nil:
  798. # XXX: hmm, what kind of symbols will end up here?
  799. # do we really need to try the overload resolution?
  800. n.sons[0] = prc
  801. nOrig.sons[0] = prc
  802. n.flags.incl nfExprCall
  803. result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags)
  804. if result == nil: return errorNode(c, n)
  805. elif result.kind notin nkCallKinds:
  806. # the semExpr() in overloadedCallOpr can even break this condition!
  807. # See bug #904 of how to trigger it:
  808. return result
  809. #result = afterCallActions(c, result, nOrig, flags)
  810. if result.sons[0].kind == nkSym:
  811. result = afterCallActions(c, result, nOrig, flags)
  812. else:
  813. fixAbstractType(c, result)
  814. analyseIfAddressTakenInCall(c, result)
  815. proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode =
  816. # this seems to be a hotspot in the compiler!
  817. let nOrig = n.copyTree
  818. #semLazyOpAux(c, n)
  819. result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags)
  820. if result != nil: result = afterCallActions(c, result, nOrig, flags)
  821. else: result = errorNode(c, n)
  822. proc buildEchoStmt(c: PContext, n: PNode): PNode =
  823. # we MUST not check 'n' for semantics again here! But for now we give up:
  824. result = newNodeI(nkCall, n.info)
  825. var e = strTableGet(c.graph.systemModule.tab, getIdent(c.cache, "echo"))
  826. if e != nil:
  827. add(result, newSymNode(e))
  828. else:
  829. localError(c.config, n.info, "system needs: echo")
  830. add(result, errorNode(c, n))
  831. add(result, n)
  832. result = semExpr(c, result)
  833. proc semExprNoType(c: PContext, n: PNode): PNode =
  834. let isPush = hintExtendedContext in c.config.notes
  835. if isPush: pushInfoContext(c.config, n.info)
  836. result = semExpr(c, n, {efWantStmt})
  837. discardCheck(c, result, {})
  838. if isPush: popInfoContext(c.config)
  839. proc isTypeExpr(n: PNode): bool =
  840. case n.kind
  841. of nkType, nkTypeOfExpr: result = true
  842. of nkSym: result = n.sym.kind == skType
  843. else: result = false
  844. proc createSetType(c: PContext; baseType: PType): PType =
  845. assert baseType != nil
  846. result = newTypeS(tySet, c)
  847. rawAddSon(result, baseType)
  848. proc lookupInRecordAndBuildCheck(c: PContext, n, r: PNode, field: PIdent,
  849. check: var PNode): PSym =
  850. # transform in a node that contains the runtime check for the
  851. # field, if it is in a case-part...
  852. result = nil
  853. case r.kind
  854. of nkRecList:
  855. for i in countup(0, sonsLen(r) - 1):
  856. result = lookupInRecordAndBuildCheck(c, n, r.sons[i], field, check)
  857. if result != nil: return
  858. of nkRecCase:
  859. checkMinSonsLen(r, 2, c.config)
  860. if (r.sons[0].kind != nkSym): illFormedAst(r, c.config)
  861. result = lookupInRecordAndBuildCheck(c, n, r.sons[0], field, check)
  862. if result != nil: return
  863. let setType = createSetType(c, r.sons[0].typ)
  864. var s = newNodeIT(nkCurly, r.info, setType)
  865. for i in countup(1, sonsLen(r) - 1):
  866. var it = r.sons[i]
  867. case it.kind
  868. of nkOfBranch:
  869. result = lookupInRecordAndBuildCheck(c, n, lastSon(it), field, check)
  870. if result == nil:
  871. for j in 0..sonsLen(it)-2: addSon(s, copyTree(it.sons[j]))
  872. else:
  873. if check == nil:
  874. check = newNodeI(nkCheckedFieldExpr, n.info)
  875. addSon(check, c.graph.emptyNode) # make space for access node
  876. s = newNodeIT(nkCurly, n.info, setType)
  877. for j in countup(0, sonsLen(it) - 2): addSon(s, copyTree(it.sons[j]))
  878. var inExpr = newNodeIT(nkCall, n.info, getSysType(c.graph, n.info, tyBool))
  879. addSon(inExpr, newSymNode(c.graph.opContains, n.info))
  880. addSon(inExpr, s)
  881. addSon(inExpr, copyTree(r.sons[0]))
  882. addSon(check, inExpr)
  883. #addSon(check, semExpr(c, inExpr))
  884. return
  885. of nkElse:
  886. result = lookupInRecordAndBuildCheck(c, n, lastSon(it), field, check)
  887. if result != nil:
  888. if check == nil:
  889. check = newNodeI(nkCheckedFieldExpr, n.info)
  890. addSon(check, c.graph.emptyNode) # make space for access node
  891. var inExpr = newNodeIT(nkCall, n.info, getSysType(c.graph, n.info, tyBool))
  892. addSon(inExpr, newSymNode(c.graph.opContains, n.info))
  893. addSon(inExpr, s)
  894. addSon(inExpr, copyTree(r.sons[0]))
  895. var notExpr = newNodeIT(nkCall, n.info, getSysType(c.graph, n.info, tyBool))
  896. addSon(notExpr, newSymNode(c.graph.opNot, n.info))
  897. addSon(notExpr, inExpr)
  898. addSon(check, notExpr)
  899. return
  900. else: illFormedAst(it, c.config)
  901. of nkSym:
  902. if r.sym.name.id == field.id: result = r.sym
  903. else: illFormedAst(n, c.config)
  904. const
  905. tyTypeParamsHolders = {tyGenericInst, tyCompositeTypeClass}
  906. tyDotOpTransparent = {tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink}
  907. proc readTypeParameter(c: PContext, typ: PType,
  908. paramName: PIdent, info: TLineInfo): PNode =
  909. # Note: This function will return emptyNode when attempting to read
  910. # a static type parameter that is not yet resolved (e.g. this may
  911. # happen in proc signatures such as `proc(x: T): array[T.sizeParam, U]`
  912. if typ.kind in {tyUserTypeClass, tyUserTypeClassInst}:
  913. for statement in typ.n:
  914. case statement.kind
  915. of nkTypeSection:
  916. for def in statement:
  917. if def[0].sym.name.id == paramName.id:
  918. # XXX: Instead of lifting the section type to a typedesc
  919. # here, we could try doing it earlier in semTypeSection.
  920. # This seems semantically correct and then we'll be able
  921. # to return the section symbol directly here
  922. let foundType = makeTypeDesc(c, def[2].typ)
  923. return newSymNode(copySym(def[0].sym).linkTo(foundType), info)
  924. of nkConstSection:
  925. for def in statement:
  926. if def[0].sym.name.id == paramName.id:
  927. return def[2]
  928. else:
  929. discard
  930. if typ.kind != tyUserTypeClass:
  931. let ty = if typ.kind == tyCompositeTypeClass: typ.sons[1].skipGenericAlias
  932. else: typ.skipGenericAlias
  933. let tbody = ty.sons[0]
  934. for s in countup(0, tbody.len-2):
  935. let tParam = tbody.sons[s]
  936. if tParam.sym.name.id == paramName.id:
  937. let rawTyp = ty.sons[s + 1]
  938. if rawTyp.kind == tyStatic:
  939. if rawTyp.n != nil:
  940. return rawTyp.n
  941. else:
  942. return c.graph.emptyNode
  943. else:
  944. let foundTyp = makeTypeDesc(c, rawTyp)
  945. return newSymNode(copySym(tParam.sym).linkTo(foundTyp), info)
  946. return nil
  947. proc semSym(c: PContext, n: PNode, sym: PSym, flags: TExprFlags): PNode =
  948. let s = getGenSym(c, sym)
  949. case s.kind
  950. of skConst:
  951. markUsed(c.config, n.info, s, c.graph.usageSym)
  952. onUse(n.info, s)
  953. case skipTypes(s.typ, abstractInst-{tyTypeDesc}).kind
  954. of tyNil, tyChar, tyInt..tyInt64, tyFloat..tyFloat128,
  955. tyTuple, tySet, tyUInt..tyUInt64:
  956. if s.magic == mNone: result = inlineConst(c, n, s)
  957. else: result = newSymNode(s, n.info)
  958. of tyArray, tySequence:
  959. # Consider::
  960. # const x = []
  961. # proc p(a: openarray[int])
  962. # proc q(a: openarray[char])
  963. # p(x)
  964. # q(x)
  965. #
  966. # It is clear that ``[]`` means two totally different things. Thus, we
  967. # copy `x`'s AST into each context, so that the type fixup phase can
  968. # deal with two different ``[]``.
  969. if s.ast.len == 0: result = inlineConst(c, n, s)
  970. else: result = newSymNode(s, n.info)
  971. else:
  972. result = newSymNode(s, n.info)
  973. of skMacro:
  974. if efNoEvaluateGeneric in flags and s.ast[genericParamsPos].len > 0 or
  975. (n.kind notin nkCallKinds and s.requiredParams > 0):
  976. markUsed(c.config, n.info, s, c.graph.usageSym)
  977. onUse(n.info, s)
  978. result = symChoice(c, n, s, scClosed)
  979. else:
  980. result = semMacroExpr(c, n, n, s, flags)
  981. of skTemplate:
  982. if efNoEvaluateGeneric in flags and s.ast[genericParamsPos].len > 0 or
  983. (n.kind notin nkCallKinds and s.requiredParams > 0) or
  984. sfCustomPragma in sym.flags:
  985. markUsed(c.config, n.info, s, c.graph.usageSym)
  986. onUse(n.info, s)
  987. result = symChoice(c, n, s, scClosed)
  988. else:
  989. result = semTemplateExpr(c, n, s, flags)
  990. of skParam:
  991. markUsed(c.config, n.info, s, c.graph.usageSym)
  992. onUse(n.info, s)
  993. if s.typ != nil and s.typ.kind == tyStatic and s.typ.n != nil:
  994. # XXX see the hack in sigmatch.nim ...
  995. return s.typ.n
  996. elif sfGenSym in s.flags:
  997. # the owner should have been set by now by addParamOrResult
  998. internalAssert c.config, s.owner != nil
  999. if c.p.wasForwarded:
  1000. # gensym'ed parameters that nevertheless have been forward declared
  1001. # need a special fixup:
  1002. let realParam = c.p.owner.typ.n[s.position+1]
  1003. internalAssert c.config, realParam.kind == nkSym and realParam.sym.kind == skParam
  1004. return newSymNode(c.p.owner.typ.n[s.position+1].sym, n.info)
  1005. elif c.p.owner.kind == skMacro:
  1006. # gensym'ed macro parameters need a similar hack (see bug #1944):
  1007. var u = searchInScopes(c, s.name)
  1008. internalAssert c.config, u != nil and u.kind == skParam and u.owner == s.owner
  1009. return newSymNode(u, n.info)
  1010. result = newSymNode(s, n.info)
  1011. of skVar, skLet, skResult, skForVar:
  1012. if s.magic == mNimvm:
  1013. localError(c.config, n.info, "illegal context for 'nimvm' magic")
  1014. markUsed(c.config, n.info, s, c.graph.usageSym)
  1015. onUse(n.info, s)
  1016. result = newSymNode(s, n.info)
  1017. # We cannot check for access to outer vars for example because it's still
  1018. # not sure the symbol really ends up being used:
  1019. # var len = 0 # but won't be called
  1020. # genericThatUsesLen(x) # marked as taking a closure?
  1021. of skGenericParam:
  1022. onUse(n.info, s)
  1023. if s.typ.kind == tyStatic:
  1024. result = newSymNode(s, n.info)
  1025. result.typ = s.typ
  1026. elif s.ast != nil:
  1027. result = semExpr(c, s.ast)
  1028. else:
  1029. n.typ = s.typ
  1030. return n
  1031. of skType:
  1032. markUsed(c.config, n.info, s, c.graph.usageSym)
  1033. onUse(n.info, s)
  1034. if s.typ.kind == tyStatic and s.typ.base.kind != tyNone and s.typ.n != nil:
  1035. return s.typ.n
  1036. result = newSymNode(s, n.info)
  1037. result.typ = makeTypeDesc(c, s.typ)
  1038. of skField:
  1039. var p = c.p
  1040. while p != nil and p.selfSym == nil:
  1041. p = p.next
  1042. if p != nil and p.selfSym != nil:
  1043. var ty = skipTypes(p.selfSym.typ, {tyGenericInst, tyVar, tyLent, tyPtr, tyRef,
  1044. tyAlias, tySink})
  1045. while tfBorrowDot in ty.flags: ty = ty.skipTypes({tyDistinct})
  1046. var check: PNode = nil
  1047. if ty.kind == tyObject:
  1048. while true:
  1049. check = nil
  1050. let f = lookupInRecordAndBuildCheck(c, n, ty.n, s.name, check)
  1051. if f != nil and fieldVisible(c, f):
  1052. # is the access to a public field or in the same module or in a friend?
  1053. doAssert f == s
  1054. markUsed(c.config, n.info, f, c.graph.usageSym)
  1055. onUse(n.info, f)
  1056. result = newNodeIT(nkDotExpr, n.info, f.typ)
  1057. result.add makeDeref(newSymNode(p.selfSym))
  1058. result.add newSymNode(f) # we now have the correct field
  1059. if check != nil:
  1060. check.sons[0] = result
  1061. check.typ = result.typ
  1062. result = check
  1063. return result
  1064. if ty.sons[0] == nil: break
  1065. ty = skipTypes(ty.sons[0], skipPtrs)
  1066. # old code, not sure if it's live code:
  1067. markUsed(c.config, n.info, s, c.graph.usageSym)
  1068. onUse(n.info, s)
  1069. result = newSymNode(s, n.info)
  1070. else:
  1071. markUsed(c.config, n.info, s, c.graph.usageSym)
  1072. onUse(n.info, s)
  1073. result = newSymNode(s, n.info)
  1074. proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1075. ## returns nil if it's not a built-in field access
  1076. checkSonsLen(n, 2, c.config)
  1077. # tests/bind/tbindoverload.nim wants an early exit here, but seems to
  1078. # work without now. template/tsymchoicefield doesn't like an early exit
  1079. # here at all!
  1080. #if isSymChoice(n.sons[1]): return
  1081. when defined(nimsuggest):
  1082. if c.config.cmd == cmdIdeTools:
  1083. suggestExpr(c, n)
  1084. if exactEquals(c.config.m.trackPos, n[1].info): suggestExprNoCheck(c, n)
  1085. var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared, checkModule})
  1086. if s != nil:
  1087. if s.kind in OverloadableSyms:
  1088. result = symChoice(c, n, s, scClosed)
  1089. if result.kind == nkSym: result = semSym(c, n, s, flags)
  1090. else:
  1091. markUsed(c.config, n.sons[1].info, s, c.graph.usageSym)
  1092. result = semSym(c, n, s, flags)
  1093. onUse(n.sons[1].info, s)
  1094. return
  1095. n.sons[0] = semExprWithType(c, n.sons[0], flags+{efDetermineType})
  1096. #restoreOldStyleType(n.sons[0])
  1097. var i = considerQuotedIdent(c, n.sons[1], n)
  1098. var ty = n.sons[0].typ
  1099. var f: PSym = nil
  1100. result = nil
  1101. template tryReadingGenericParam(t: PType) =
  1102. case t.kind
  1103. of tyTypeParamsHolders:
  1104. result = readTypeParameter(c, t, i, n.info)
  1105. if result == c.graph.emptyNode:
  1106. result = n
  1107. n.typ = makeTypeFromExpr(c, n.copyTree)
  1108. return
  1109. of tyUserTypeClasses:
  1110. if t.isResolvedUserTypeClass:
  1111. return readTypeParameter(c, t, i, n.info)
  1112. else:
  1113. n.typ = makeTypeFromExpr(c, copyTree(n))
  1114. return n
  1115. of tyGenericParam, tyAnything:
  1116. n.typ = makeTypeFromExpr(c, copyTree(n))
  1117. return n
  1118. else:
  1119. discard
  1120. var argIsType = false
  1121. if ty.kind == tyTypeDesc:
  1122. if ty.base.kind == tyNone:
  1123. # This is a still unresolved typedesc parameter.
  1124. # If this is a regular proc, then all bets are off and we must return
  1125. # tyFromExpr, but when this happen in a macro this is not a built-in
  1126. # field access and we leave the compiler to compile a normal call:
  1127. if getCurrOwner(c).kind != skMacro:
  1128. n.typ = makeTypeFromExpr(c, n.copyTree)
  1129. return n
  1130. else:
  1131. return nil
  1132. else:
  1133. ty = ty.base
  1134. argIsType = true
  1135. else:
  1136. argIsType = isTypeExpr(n.sons[0])
  1137. if argIsType:
  1138. ty = ty.skipTypes(tyDotOpTransparent)
  1139. case ty.kind
  1140. of tyEnum:
  1141. # look up if the identifier belongs to the enum:
  1142. while ty != nil:
  1143. f = getSymFromList(ty.n, i)
  1144. if f != nil: break
  1145. ty = ty.sons[0] # enum inheritance
  1146. if f != nil:
  1147. result = newSymNode(f)
  1148. result.info = n.info
  1149. result.typ = ty
  1150. markUsed(c.config, n.info, f, c.graph.usageSym)
  1151. onUse(n.info, f)
  1152. return
  1153. of tyObject, tyTuple:
  1154. if ty.n != nil and ty.n.kind == nkRecList:
  1155. let field = lookupInRecord(ty.n, i)
  1156. if field != nil:
  1157. n.typ = makeTypeDesc(c, field.typ)
  1158. return n
  1159. else:
  1160. tryReadingGenericParam(ty)
  1161. return
  1162. # XXX: This is probably not relevant any more
  1163. # reset to prevent 'nil' bug: see "tests/reject/tenumitems.nim":
  1164. ty = n.sons[0].typ
  1165. return nil
  1166. if ty.kind in tyUserTypeClasses and ty.isResolvedUserTypeClass:
  1167. ty = ty.lastSon
  1168. ty = skipTypes(ty, {tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink})
  1169. while tfBorrowDot in ty.flags: ty = ty.skipTypes({tyDistinct})
  1170. var check: PNode = nil
  1171. if ty.kind == tyObject:
  1172. while true:
  1173. check = nil
  1174. f = lookupInRecordAndBuildCheck(c, n, ty.n, i, check)
  1175. if f != nil: break
  1176. if ty.sons[0] == nil: break
  1177. ty = skipTypes(ty.sons[0], skipPtrs)
  1178. if f != nil:
  1179. if fieldVisible(c, f):
  1180. # is the access to a public field or in the same module or in a friend?
  1181. markUsed(c.config, n.sons[1].info, f, c.graph.usageSym)
  1182. onUse(n.sons[1].info, f)
  1183. n.sons[0] = makeDeref(n.sons[0])
  1184. n.sons[1] = newSymNode(f) # we now have the correct field
  1185. n.typ = f.typ
  1186. if check == nil:
  1187. result = n
  1188. else:
  1189. check.sons[0] = n
  1190. check.typ = n.typ
  1191. result = check
  1192. elif ty.kind == tyTuple and ty.n != nil:
  1193. f = getSymFromList(ty.n, i)
  1194. if f != nil:
  1195. markUsed(c.config, n.sons[1].info, f, c.graph.usageSym)
  1196. onUse(n.sons[1].info, f)
  1197. n.sons[0] = makeDeref(n.sons[0])
  1198. n.sons[1] = newSymNode(f)
  1199. n.typ = f.typ
  1200. result = n
  1201. # we didn't find any field, let's look for a generic param
  1202. if result == nil:
  1203. let t = n.sons[0].typ.skipTypes(tyDotOpTransparent)
  1204. tryReadingGenericParam(t)
  1205. proc dotTransformation(c: PContext, n: PNode): PNode =
  1206. if isSymChoice(n.sons[1]):
  1207. result = newNodeI(nkDotCall, n.info)
  1208. addSon(result, n.sons[1])
  1209. addSon(result, copyTree(n[0]))
  1210. else:
  1211. var i = considerQuotedIdent(c, n.sons[1], n)
  1212. result = newNodeI(nkDotCall, n.info)
  1213. result.flags.incl nfDotField
  1214. addSon(result, newIdentNode(i, n[1].info))
  1215. addSon(result, copyTree(n[0]))
  1216. proc semFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1217. # this is difficult, because the '.' is used in many different contexts
  1218. # in Nim. We first allow types in the semantic checking.
  1219. result = builtinFieldAccess(c, n, flags)
  1220. if result == nil:
  1221. result = dotTransformation(c, n)
  1222. proc buildOverloadedSubscripts(n: PNode, ident: PIdent): PNode =
  1223. result = newNodeI(nkCall, n.info)
  1224. result.add(newIdentNode(ident, n.info))
  1225. for i in 0 .. n.len-1: result.add(n[i])
  1226. proc semDeref(c: PContext, n: PNode): PNode =
  1227. checkSonsLen(n, 1, c.config)
  1228. n.sons[0] = semExprWithType(c, n.sons[0])
  1229. result = n
  1230. var t = skipTypes(n.sons[0].typ, {tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  1231. case t.kind
  1232. of tyRef, tyPtr: n.typ = t.lastSon
  1233. else: result = nil
  1234. #GlobalError(n.sons[0].info, errCircumNeedsPointer)
  1235. proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1236. ## returns nil if not a built-in subscript operator; also called for the
  1237. ## checking of assignments
  1238. if sonsLen(n) == 1:
  1239. let x = semDeref(c, n)
  1240. if x == nil: return nil
  1241. result = newNodeIT(nkDerefExpr, x.info, x.typ)
  1242. result.add(x[0])
  1243. return
  1244. checkMinSonsLen(n, 2, c.config)
  1245. # make sure we don't evaluate generic macros/templates
  1246. n.sons[0] = semExprWithType(c, n.sons[0],
  1247. {efNoEvaluateGeneric})
  1248. var arr = skipTypes(n.sons[0].typ, {tyGenericInst, tyUserTypeClassInst,
  1249. tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink})
  1250. if arr.kind == tyStatic:
  1251. if arr.base.kind == tyNone:
  1252. result = n
  1253. result.typ = semStaticType(c, n[1], nil)
  1254. return
  1255. elif arr.n != nil:
  1256. return semSubscript(c, arr.n, flags)
  1257. else:
  1258. arr = arr.base
  1259. case arr.kind
  1260. of tyArray, tyOpenArray, tyVarargs, tySequence, tyString, tyCString,
  1261. tyUncheckedArray:
  1262. if n.len != 2: return nil
  1263. n.sons[0] = makeDeref(n.sons[0])
  1264. for i in countup(1, sonsLen(n) - 1):
  1265. n.sons[i] = semExprWithType(c, n.sons[i],
  1266. flags*{efInTypeof, efDetermineType})
  1267. # Arrays index type is dictated by the range's type
  1268. if arr.kind == tyArray:
  1269. var indexType = arr.sons[0]
  1270. var arg = indexTypesMatch(c, indexType, n.sons[1].typ, n.sons[1])
  1271. if arg != nil:
  1272. n.sons[1] = arg
  1273. result = n
  1274. result.typ = elemType(arr)
  1275. # Other types have a bit more of leeway
  1276. elif n.sons[1].typ.skipTypes(abstractRange-{tyDistinct}).kind in
  1277. {tyInt..tyInt64, tyUInt..tyUInt64}:
  1278. result = n
  1279. result.typ = elemType(arr)
  1280. of tyTypeDesc:
  1281. # The result so far is a tyTypeDesc bound
  1282. # a tyGenericBody. The line below will substitute
  1283. # it with the instantiated type.
  1284. result = n
  1285. result.typ = makeTypeDesc(c, semTypeNode(c, n, nil))
  1286. #result = symNodeFromType(c, semTypeNode(c, n, nil), n.info)
  1287. of tyTuple:
  1288. if n.len != 2: return nil
  1289. n.sons[0] = makeDeref(n.sons[0])
  1290. # [] operator for tuples requires constant expression:
  1291. n.sons[1] = semConstExpr(c, n.sons[1])
  1292. if skipTypes(n.sons[1].typ, {tyGenericInst, tyRange, tyOrdinal, tyAlias, tySink}).kind in
  1293. {tyInt..tyInt64}:
  1294. let idx = getOrdValue(n.sons[1])
  1295. if idx >= 0 and idx < len(arr): n.typ = arr.sons[int(idx)]
  1296. else: localError(c.config, n.info, "invalid index value for tuple subscript")
  1297. result = n
  1298. else:
  1299. result = nil
  1300. else:
  1301. let s = if n.sons[0].kind == nkSym: n.sons[0].sym
  1302. elif n[0].kind in nkSymChoices: n.sons[0][0].sym
  1303. else: nil
  1304. if s != nil:
  1305. case s.kind
  1306. of skProc, skFunc, skMethod, skConverter, skIterator:
  1307. # type parameters: partial generic specialization
  1308. n.sons[0] = semSymGenericInstantiation(c, n.sons[0], s)
  1309. result = explicitGenericInstantiation(c, n, s)
  1310. of skMacro, skTemplate:
  1311. if efInCall in flags:
  1312. # We are processing macroOrTmpl[] in macroOrTmpl[](...) call.
  1313. # Return as is, so it can be transformed into complete macro or
  1314. # template call in semIndirectOp caller.
  1315. result = n
  1316. else:
  1317. # We are processing macroOrTmpl[] not in call. Transform it to the
  1318. # macro or template call with generic arguments here.
  1319. n.kind = nkCall
  1320. case s.kind
  1321. of skMacro: result = semMacroExpr(c, n, n, s, flags)
  1322. of skTemplate: result = semTemplateExpr(c, n, s, flags)
  1323. else: discard
  1324. of skType:
  1325. result = symNodeFromType(c, semTypeNode(c, n, nil), n.info)
  1326. else:
  1327. discard
  1328. proc semArrayAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1329. result = semSubscript(c, n, flags)
  1330. if result == nil:
  1331. # overloaded [] operator:
  1332. result = semExpr(c, buildOverloadedSubscripts(n, getIdent(c.cache, "[]")))
  1333. proc propertyWriteAccess(c: PContext, n, nOrig, a: PNode): PNode =
  1334. var id = considerQuotedIdent(c, a[1], a)
  1335. var setterId = newIdentNode(getIdent(c.cache, id.s & '='), n.info)
  1336. # a[0] is already checked for semantics, that does ``builtinFieldAccess``
  1337. # this is ugly. XXX Semantic checking should use the ``nfSem`` flag for
  1338. # nodes?
  1339. let aOrig = nOrig[0]
  1340. result = newNode(nkCall, n.info, sons = @[setterId, a[0],
  1341. semExprWithType(c, n[1])])
  1342. result.flags.incl nfDotSetter
  1343. let orig = newNode(nkCall, n.info, sons = @[setterId, aOrig[0], nOrig[1]])
  1344. result = semOverloadedCallAnalyseEffects(c, result, orig, {})
  1345. if result != nil:
  1346. result = afterCallActions(c, result, nOrig, {})
  1347. #fixAbstractType(c, result)
  1348. #analyseIfAddressTakenInCall(c, result)
  1349. proc takeImplicitAddr(c: PContext, n: PNode; isLent: bool): PNode =
  1350. # See RFC #7373, calls returning 'var T' are assumed to
  1351. # return a view into the first argument (if there is one):
  1352. let root = exprRoot(n)
  1353. if root != nil and root.owner == c.p.owner:
  1354. if root.kind in {skLet, skVar, skTemp} and sfGlobal notin root.flags:
  1355. localError(c.config, n.info, "'$1' escapes its stack frame; context: '$2'; see $3/var_t_return.html" % [
  1356. root.name.s, renderTree(n, {renderNoComments}), explanationsBaseUrl])
  1357. elif root.kind == skParam and root.position != 0:
  1358. localError(c.config, n.info, "'$1' is not the first parameter; context: '$2'; see $3/var_t_return.html" % [
  1359. root.name.s, renderTree(n, {renderNoComments}), explanationsBaseUrl])
  1360. case n.kind
  1361. of nkHiddenAddr, nkAddr: return n
  1362. of nkHiddenDeref, nkDerefExpr: return n.sons[0]
  1363. of nkBracketExpr:
  1364. if len(n) == 1: return n.sons[0]
  1365. else: discard
  1366. let valid = isAssignable(c, n)
  1367. if valid != arLValue:
  1368. if valid == arLocalLValue:
  1369. localError(c.config, n.info, errXStackEscape % renderTree(n, {renderNoComments}))
  1370. elif not isLent:
  1371. localError(c.config, n.info, errExprHasNoAddress)
  1372. result = newNodeIT(nkHiddenAddr, n.info, makePtrType(c, n.typ))
  1373. result.add(n)
  1374. proc asgnToResultVar(c: PContext, n, le, ri: PNode) {.inline.} =
  1375. if le.kind == nkHiddenDeref:
  1376. var x = le.sons[0]
  1377. if x.typ.kind in {tyVar, tyLent} and x.kind == nkSym and x.sym.kind == skResult:
  1378. n.sons[0] = x # 'result[]' --> 'result'
  1379. n.sons[1] = takeImplicitAddr(c, ri, x.typ.kind == tyLent)
  1380. x.typ.flags.incl tfVarIsPtr
  1381. #echo x.info, " setting it for this type ", typeToString(x.typ), " ", n.info
  1382. template resultTypeIsInferrable(typ: PType): untyped =
  1383. typ.isMetaType and typ.kind != tyTypeDesc
  1384. proc goodLineInfo(arg: PNode): TLineinfo =
  1385. if arg.kind == nkStmtListExpr and arg.len > 0:
  1386. goodLineInfo(arg[^1])
  1387. else:
  1388. arg.info
  1389. proc semAsgn(c: PContext, n: PNode; mode=asgnNormal): PNode =
  1390. checkSonsLen(n, 2, c.config)
  1391. var a = n.sons[0]
  1392. case a.kind
  1393. of nkDotExpr:
  1394. # r.f = x
  1395. # --> `f=` (r, x)
  1396. let nOrig = n.copyTree
  1397. a = builtinFieldAccess(c, a, {efLValue})
  1398. if a == nil:
  1399. a = propertyWriteAccess(c, n, nOrig, n[0])
  1400. if a != nil: return a
  1401. # we try without the '='; proc that return 'var' or macros are still
  1402. # possible:
  1403. a = dotTransformation(c, n[0])
  1404. if a.kind == nkDotCall:
  1405. a.kind = nkCall
  1406. a = semExprWithType(c, a, {efLValue})
  1407. of nkBracketExpr:
  1408. # a[i] = x
  1409. # --> `[]=`(a, i, x)
  1410. a = semSubscript(c, a, {efLValue})
  1411. if a == nil:
  1412. result = buildOverloadedSubscripts(n.sons[0], getIdent(c.cache, "[]="))
  1413. add(result, n[1])
  1414. if mode == noOverloadedSubscript:
  1415. bracketNotFoundError(c, result)
  1416. return n
  1417. else:
  1418. result = semExprNoType(c, result)
  1419. return result
  1420. of nkCurlyExpr:
  1421. # a{i} = x --> `{}=`(a, i, x)
  1422. result = buildOverloadedSubscripts(n.sons[0], getIdent(c.cache, "{}="))
  1423. add(result, n[1])
  1424. return semExprNoType(c, result)
  1425. of nkPar, nkTupleConstr:
  1426. if a.len >= 2:
  1427. # unfortunately we need to rewrite ``(x, y) = foo()`` already here so
  1428. # that overloading of the assignment operator still works. Usually we
  1429. # prefer to do these rewritings in transf.nim:
  1430. return semStmt(c, lowerTupleUnpackingForAsgn(c.graph, n, c.p.owner), {})
  1431. else:
  1432. a = semExprWithType(c, a, {efLValue})
  1433. else:
  1434. a = semExprWithType(c, a, {efLValue})
  1435. n.sons[0] = a
  1436. # a = b # both are vars, means: a[] = b[]
  1437. # a = b # b no 'var T' means: a = addr(b)
  1438. var le = a.typ
  1439. if le == nil:
  1440. localError(c.config, a.info, "expression has no type")
  1441. elif (skipTypes(le, {tyGenericInst, tyAlias, tySink}).kind != tyVar and
  1442. isAssignable(c, a) == arNone) or
  1443. skipTypes(le, abstractVar).kind in {tyOpenArray, tyVarargs}:
  1444. # Direct assignment to a discriminant is allowed!
  1445. localError(c.config, a.info, errXCannotBeAssignedTo %
  1446. renderTree(a, {renderNoComments}))
  1447. else:
  1448. let
  1449. lhs = n.sons[0]
  1450. lhsIsResult = lhs.kind == nkSym and lhs.sym.kind == skResult
  1451. var
  1452. rhs = semExprWithType(c, n.sons[1],
  1453. if lhsIsResult: {efAllowDestructor} else: {})
  1454. if lhsIsResult:
  1455. n.typ = c.enforceVoidContext
  1456. if c.p.owner.kind != skMacro and resultTypeIsInferrable(lhs.sym.typ):
  1457. var rhsTyp = rhs.typ
  1458. if rhsTyp.kind in tyUserTypeClasses and rhsTyp.isResolvedUserTypeClass:
  1459. rhsTyp = rhsTyp.lastSon
  1460. if cmpTypes(c, lhs.typ, rhsTyp) in {isGeneric, isEqual}:
  1461. internalAssert c.config, c.p.resultSym != nil
  1462. # Make sure the type is valid for the result variable
  1463. typeAllowedCheck(c.config, n.info, rhsTyp, skResult)
  1464. lhs.typ = rhsTyp
  1465. c.p.resultSym.typ = rhsTyp
  1466. c.p.owner.typ.sons[0] = rhsTyp
  1467. else:
  1468. typeMismatch(c.config, n.info, lhs.typ, rhsTyp)
  1469. n.sons[1] = fitNode(c, le, rhs, goodLineInfo(n[1]))
  1470. liftTypeBoundOps(c, lhs.typ, lhs.info)
  1471. #liftTypeBoundOps(c, n.sons[0].typ, n.sons[0].info)
  1472. fixAbstractType(c, n)
  1473. asgnToResultVar(c, n, n.sons[0], n.sons[1])
  1474. result = n
  1475. proc semReturn(c: PContext, n: PNode): PNode =
  1476. result = n
  1477. checkSonsLen(n, 1, c.config)
  1478. if c.p.owner.kind in {skConverter, skMethod, skProc, skFunc, skMacro} or (
  1479. c.p.owner.kind == skIterator and c.p.owner.typ.callConv == ccClosure):
  1480. if n.sons[0].kind != nkEmpty:
  1481. # transform ``return expr`` to ``result = expr; return``
  1482. if c.p.resultSym != nil:
  1483. var a = newNodeI(nkAsgn, n.sons[0].info)
  1484. addSon(a, newSymNode(c.p.resultSym))
  1485. addSon(a, n.sons[0])
  1486. n.sons[0] = semAsgn(c, a)
  1487. # optimize away ``result = result``:
  1488. if n[0][1].kind == nkSym and n[0][1].sym == c.p.resultSym:
  1489. n.sons[0] = c.graph.emptyNode
  1490. else:
  1491. localError(c.config, n.info, errNoReturnTypeDeclared)
  1492. else:
  1493. localError(c.config, n.info, "'return' not allowed here")
  1494. proc semProcBody(c: PContext, n: PNode): PNode =
  1495. openScope(c)
  1496. result = semExpr(c, n)
  1497. if c.p.resultSym != nil and not isEmptyType(result.typ):
  1498. if result.kind == nkNilLit:
  1499. # or ImplicitlyDiscardable(result):
  1500. # new semantic: 'result = x' triggers the void context
  1501. result.typ = nil
  1502. elif result.kind == nkStmtListExpr and result.typ.kind == tyNil:
  1503. # to keep backwards compatibility bodies like:
  1504. # nil
  1505. # # comment
  1506. # are not expressions:
  1507. fixNilType(c, result)
  1508. else:
  1509. var a = newNodeI(nkAsgn, n.info, 2)
  1510. a.sons[0] = newSymNode(c.p.resultSym)
  1511. a.sons[1] = result
  1512. result = semAsgn(c, a)
  1513. else:
  1514. discardCheck(c, result, {})
  1515. if c.p.owner.kind notin {skMacro, skTemplate} and
  1516. c.p.resultSym != nil and c.p.resultSym.typ.isMetaType:
  1517. if isEmptyType(result.typ):
  1518. # we inferred a 'void' return type:
  1519. c.p.resultSym.typ = errorType(c)
  1520. c.p.owner.typ.sons[0] = nil
  1521. else:
  1522. localError(c.config, c.p.resultSym.info, errCannotInferReturnType)
  1523. closeScope(c)
  1524. proc semYieldVarResult(c: PContext, n: PNode, restype: PType) =
  1525. var t = skipTypes(restype, {tyGenericInst, tyAlias, tySink})
  1526. case t.kind
  1527. of tyVar, tyLent:
  1528. if t.kind == tyVar: t.flags.incl tfVarIsPtr # bugfix for #4048, #4910, #6892
  1529. if n.sons[0].kind in {nkHiddenStdConv, nkHiddenSubConv}:
  1530. n.sons[0] = n.sons[0].sons[1]
  1531. n.sons[0] = takeImplicitAddr(c, n.sons[0], t.kind == tyLent)
  1532. of tyTuple:
  1533. for i in 0..<t.sonsLen:
  1534. var e = skipTypes(t.sons[i], {tyGenericInst, tyAlias, tySink})
  1535. if e.kind in {tyVar, tyLent}:
  1536. if e.kind == tyVar: e.flags.incl tfVarIsPtr # bugfix for #4048, #4910, #6892
  1537. if n.sons[0].kind in {nkPar, nkTupleConstr}:
  1538. n.sons[0].sons[i] = takeImplicitAddr(c, n.sons[0].sons[i], e.kind == tyLent)
  1539. elif n.sons[0].kind in {nkHiddenStdConv, nkHiddenSubConv} and
  1540. n.sons[0].sons[1].kind in {nkPar, nkTupleConstr}:
  1541. var a = n.sons[0].sons[1]
  1542. a.sons[i] = takeImplicitAddr(c, a.sons[i], false)
  1543. else:
  1544. localError(c.config, n.sons[0].info, errXExpected, "tuple constructor")
  1545. else: discard
  1546. proc semYield(c: PContext, n: PNode): PNode =
  1547. result = n
  1548. checkSonsLen(n, 1, c.config)
  1549. if c.p.owner == nil or c.p.owner.kind != skIterator:
  1550. localError(c.config, n.info, errYieldNotAllowedHere)
  1551. elif n.sons[0].kind != nkEmpty:
  1552. n.sons[0] = semExprWithType(c, n.sons[0]) # check for type compatibility:
  1553. var iterType = c.p.owner.typ
  1554. let restype = iterType.sons[0]
  1555. if restype != nil:
  1556. if restype.kind != tyExpr:
  1557. n.sons[0] = fitNode(c, restype, n.sons[0], n.info)
  1558. if n.sons[0].typ == nil: internalError(c.config, n.info, "semYield")
  1559. if resultTypeIsInferrable(restype):
  1560. let inferred = n.sons[0].typ
  1561. iterType.sons[0] = inferred
  1562. semYieldVarResult(c, n, restype)
  1563. else:
  1564. localError(c.config, n.info, errCannotReturnExpr)
  1565. elif c.p.owner.typ.sons[0] != nil:
  1566. localError(c.config, n.info, errGenerated, "yield statement must yield a value")
  1567. proc lookUpForDefined(c: PContext, i: PIdent, onlyCurrentScope: bool): PSym =
  1568. if onlyCurrentScope:
  1569. result = localSearchInScope(c, i)
  1570. else:
  1571. result = searchInScopes(c, i) # no need for stub loading
  1572. proc lookUpForDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PSym =
  1573. case n.kind
  1574. of nkIdent:
  1575. result = lookUpForDefined(c, n.ident, onlyCurrentScope)
  1576. of nkDotExpr:
  1577. result = nil
  1578. if onlyCurrentScope: return
  1579. checkSonsLen(n, 2, c.config)
  1580. var m = lookUpForDefined(c, n.sons[0], onlyCurrentScope)
  1581. if m != nil and m.kind == skModule:
  1582. let ident = considerQuotedIdent(c, n[1], n)
  1583. if m == c.module:
  1584. result = strTableGet(c.topLevelScope.symbols, ident)
  1585. else:
  1586. result = strTableGet(m.tab, ident)
  1587. of nkAccQuoted:
  1588. result = lookUpForDefined(c, considerQuotedIdent(c, n), onlyCurrentScope)
  1589. of nkSym:
  1590. result = n.sym
  1591. of nkOpenSymChoice, nkClosedSymChoice:
  1592. result = n.sons[0].sym
  1593. else:
  1594. localError(c.config, n.info, "identifier expected, but got: " & renderTree(n))
  1595. result = nil
  1596. proc semDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PNode =
  1597. checkSonsLen(n, 2, c.config)
  1598. # we replace this node by a 'true' or 'false' node:
  1599. result = newIntNode(nkIntLit, 0)
  1600. if not onlyCurrentScope and considerQuotedIdent(c, n[0], n).s == "defined":
  1601. let d = considerQuotedIdent(c, n[1], n)
  1602. result.intVal = ord isDefined(c.config, d.s)
  1603. elif lookUpForDefined(c, n.sons[1], onlyCurrentScope) != nil:
  1604. result.intVal = 1
  1605. result.info = n.info
  1606. result.typ = getSysType(c.graph, n.info, tyBool)
  1607. proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym =
  1608. ## The argument to the proc should be nkCall(...) or similar
  1609. ## Returns the macro/template symbol
  1610. if isCallExpr(n):
  1611. var expandedSym = qualifiedLookUp(c, n[0], {checkUndeclared})
  1612. if expandedSym == nil:
  1613. errorUndeclaredIdentifier(c, n.info, n[0].renderTree)
  1614. return errorSym(c, n[0])
  1615. if expandedSym.kind notin {skMacro, skTemplate}:
  1616. localError(c.config, n.info, "'$1' is not a macro or template" % expandedSym.name.s)
  1617. return errorSym(c, n[0])
  1618. result = expandedSym
  1619. else:
  1620. localError(c.config, n.info, "'$1' is not a macro or template" % n.renderTree)
  1621. result = errorSym(c, n)
  1622. proc expectString(c: PContext, n: PNode): string =
  1623. var n = semConstExpr(c, n)
  1624. if n.kind in nkStrKinds:
  1625. return n.strVal
  1626. else:
  1627. localError(c.config, n.info, errStringLiteralExpected)
  1628. proc newAnonSym(c: PContext; kind: TSymKind, info: TLineInfo): PSym =
  1629. result = newSym(kind, c.cache.idAnon, getCurrOwner(c), info)
  1630. result.flags = {sfGenSym}
  1631. proc semExpandToAst(c: PContext, n: PNode): PNode =
  1632. let macroCall = n[1]
  1633. when false:
  1634. let expandedSym = expectMacroOrTemplateCall(c, macroCall)
  1635. if expandedSym.kind == skError: return n
  1636. macroCall.sons[0] = newSymNode(expandedSym, macroCall.info)
  1637. markUsed(c.config, n.info, expandedSym, c.graph.usageSym)
  1638. onUse(n.info, expandedSym)
  1639. if isCallExpr(macroCall):
  1640. for i in countup(1, macroCall.len-1):
  1641. #if macroCall.sons[0].typ.sons[i].kind != tyExpr:
  1642. macroCall.sons[i] = semExprWithType(c, macroCall[i], {})
  1643. # performing overloading resolution here produces too serious regressions:
  1644. let headSymbol = macroCall[0]
  1645. var cands = 0
  1646. var cand: PSym = nil
  1647. var o: TOverloadIter
  1648. var symx = initOverloadIter(o, c, headSymbol)
  1649. while symx != nil:
  1650. if symx.kind in {skTemplate, skMacro} and symx.typ.len == macroCall.len:
  1651. cand = symx
  1652. inc cands
  1653. symx = nextOverloadIter(o, c, headSymbol)
  1654. if cands == 0:
  1655. localError(c.config, n.info, "expected a template that takes " & $(macroCall.len-1) & " arguments")
  1656. elif cands >= 2:
  1657. localError(c.config, n.info, "ambiguous symbol in 'getAst' context: " & $macroCall)
  1658. else:
  1659. let info = macroCall.sons[0].info
  1660. macroCall.sons[0] = newSymNode(cand, info)
  1661. markUsed(c.config, info, cand, c.graph.usageSym)
  1662. onUse(info, cand)
  1663. # we just perform overloading resolution here:
  1664. #n.sons[1] = semOverloadedCall(c, macroCall, macroCall, {skTemplate, skMacro})
  1665. else:
  1666. localError(c.config, n.info, "getAst takes a call, but got " & n.renderTree)
  1667. # Preserve the magic symbol in order to be handled in evals.nim
  1668. internalAssert c.config, n.sons[0].sym.magic == mExpandToAst
  1669. #n.typ = getSysSym("NimNode").typ # expandedSym.getReturnType
  1670. if n.kind == nkStmtList and n.len == 1: result = n[0]
  1671. else: result = n
  1672. result.typ = sysTypeFromName(c.graph, n.info, "NimNode")
  1673. proc semExpandToAst(c: PContext, n: PNode, magicSym: PSym,
  1674. flags: TExprFlags = {}): PNode =
  1675. if sonsLen(n) == 2:
  1676. n.sons[0] = newSymNode(magicSym, n.info)
  1677. result = semExpandToAst(c, n)
  1678. else:
  1679. result = semDirectOp(c, n, flags)
  1680. proc processQuotations(c: PContext; n: var PNode, op: string,
  1681. quotes: var seq[PNode],
  1682. ids: var seq[PNode]) =
  1683. template returnQuote(q) =
  1684. quotes.add q
  1685. n = newIdentNode(getIdent(c.cache, $quotes.len), n.info)
  1686. ids.add n
  1687. return
  1688. if n.kind == nkPrefix:
  1689. checkSonsLen(n, 2, c.config)
  1690. if n[0].kind == nkIdent:
  1691. var examinedOp = n[0].ident.s
  1692. if examinedOp == op:
  1693. returnQuote n[1]
  1694. elif examinedOp.startsWith(op):
  1695. n.sons[0] = newIdentNode(getIdent(c.cache, examinedOp.substr(op.len)), n.info)
  1696. elif n.kind == nkAccQuoted and op == "``":
  1697. returnQuote n[0]
  1698. elif n.kind == nkIdent:
  1699. if n.ident.s == "result":
  1700. n = ids[0]
  1701. for i in 0 ..< n.safeLen:
  1702. processQuotations(c, n.sons[i], op, quotes, ids)
  1703. proc semQuoteAst(c: PContext, n: PNode): PNode =
  1704. internalAssert c.config, n.len == 2 or n.len == 3
  1705. # We transform the do block into a template with a param for
  1706. # each interpolation. We'll pass this template to getAst.
  1707. var
  1708. quotedBlock = n[^1]
  1709. op = if n.len == 3: expectString(c, n[1]) else: "``"
  1710. quotes = newSeq[PNode](2)
  1711. # the quotes will be added to a nkCall statement
  1712. # leave some room for the callee symbol and the result symbol
  1713. ids = newSeq[PNode](1)
  1714. # this will store the generated param names
  1715. # leave some room for the result symbol
  1716. if quotedBlock.kind != nkStmtList:
  1717. localError(c.config, n.info, errXExpected, "block")
  1718. # This adds a default first field to pass the result symbol
  1719. ids[0] = newAnonSym(c, skParam, n.info).newSymNode
  1720. processQuotations(c, quotedBlock, op, quotes, ids)
  1721. var dummyTemplate = newProcNode(
  1722. nkTemplateDef, quotedBlock.info, body = quotedBlock,
  1723. params = c.graph.emptyNode,
  1724. name = newAnonSym(c, skTemplate, n.info).newSymNode,
  1725. pattern = c.graph.emptyNode, genericParams = c.graph.emptyNode,
  1726. pragmas = c.graph.emptyNode, exceptions = c.graph.emptyNode)
  1727. if ids.len > 0:
  1728. dummyTemplate.sons[paramsPos] = newNodeI(nkFormalParams, n.info)
  1729. dummyTemplate[paramsPos].add getSysSym(c.graph, n.info, "typed").newSymNode # return type
  1730. ids.add getSysSym(c.graph, n.info, "untyped").newSymNode # params type
  1731. ids.add c.graph.emptyNode # no default value
  1732. dummyTemplate[paramsPos].add newNode(nkIdentDefs, n.info, ids)
  1733. var tmpl = semTemplateDef(c, dummyTemplate)
  1734. quotes[0] = tmpl[namePos]
  1735. # This adds a call to newIdentNode("result") as the first argument to the template call
  1736. quotes[1] = newNode(nkCall, n.info, @[newIdentNode(getIdent(c.cache, "newIdentNode"), n.info), newStrNode(nkStrLit, "result")])
  1737. result = newNode(nkCall, n.info, @[
  1738. createMagic(c.graph, "getAst", mExpandToAst).newSymNode,
  1739. newNode(nkCall, n.info, quotes)])
  1740. result = semExpandToAst(c, result)
  1741. proc tryExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  1742. # watch out, hacks ahead:
  1743. let oldErrorCount = c.config.errorCounter
  1744. let oldErrorMax = c.config.errorMax
  1745. let oldCompilesId = c.compilesContextId
  1746. inc c.compilesContextIdGenerator
  1747. c.compilesContextId = c.compilesContextIdGenerator
  1748. # do not halt after first error:
  1749. c.config.errorMax = high(int)
  1750. # open a scope for temporary symbol inclusions:
  1751. let oldScope = c.currentScope
  1752. openScope(c)
  1753. let oldOwnerLen = len(c.graph.owners)
  1754. let oldGenerics = c.generics
  1755. let oldErrorOutputs = c.config.m.errorOutputs
  1756. if efExplain notin flags: c.config.m.errorOutputs = {}
  1757. let oldContextLen = msgs.getInfoContextLen(c.config)
  1758. let oldInGenericContext = c.inGenericContext
  1759. let oldInUnrolledContext = c.inUnrolledContext
  1760. let oldInGenericInst = c.inGenericInst
  1761. let oldInStaticContext = c.inStaticContext
  1762. let oldProcCon = c.p
  1763. c.generics = @[]
  1764. var err: string
  1765. try:
  1766. result = semExpr(c, n, flags)
  1767. if c.config.errorCounter != oldErrorCount: result = nil
  1768. except ERecoverableError:
  1769. discard
  1770. # undo symbol table changes (as far as it's possible):
  1771. c.compilesContextId = oldCompilesId
  1772. c.generics = oldGenerics
  1773. c.inGenericContext = oldInGenericContext
  1774. c.inUnrolledContext = oldInUnrolledContext
  1775. c.inGenericInst = oldInGenericInst
  1776. c.inStaticContext = oldInStaticContext
  1777. c.p = oldProcCon
  1778. msgs.setInfoContextLen(c.config, oldContextLen)
  1779. setLen(c.graph.owners, oldOwnerLen)
  1780. c.currentScope = oldScope
  1781. c.config.m.errorOutputs = oldErrorOutputs
  1782. c.config.errorCounter = oldErrorCount
  1783. c.config.errorMax = oldErrorMax
  1784. proc semCompiles(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1785. # we replace this node by a 'true' or 'false' node:
  1786. if sonsLen(n) != 2: return semDirectOp(c, n, flags)
  1787. result = newIntNode(nkIntLit, ord(tryExpr(c, n[1], flags) != nil))
  1788. result.info = n.info
  1789. result.typ = getSysType(c.graph, n.info, tyBool)
  1790. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1791. if sonsLen(n) == 3:
  1792. # XXX ugh this is really a hack: shallowCopy() can be overloaded only
  1793. # with procs that take not 2 parameters:
  1794. result = newNodeI(nkFastAsgn, n.info)
  1795. result.add(n[1])
  1796. result.add(n[2])
  1797. result = semAsgn(c, result)
  1798. else:
  1799. result = semDirectOp(c, n, flags)
  1800. proc createFlowVar(c: PContext; t: PType; info: TLineInfo): PType =
  1801. result = newType(tyGenericInvocation, c.module)
  1802. addSonSkipIntLit(result, magicsys.getCompilerProc(c.graph, "FlowVar").typ)
  1803. addSonSkipIntLit(result, t)
  1804. result = instGenericContainer(c, info, result, allowMetaTypes = false)
  1805. proc instantiateCreateFlowVarCall(c: PContext; t: PType;
  1806. info: TLineInfo): PSym =
  1807. let sym = magicsys.getCompilerProc(c.graph, "nimCreateFlowVar")
  1808. if sym == nil:
  1809. localError(c.config, info, "system needs: nimCreateFlowVar")
  1810. var bindings: TIdTable
  1811. initIdTable(bindings)
  1812. bindings.idTablePut(sym.ast[genericParamsPos].sons[0].typ, t)
  1813. result = c.semGenerateInstance(c, sym, bindings, info)
  1814. # since it's an instantiation, we unmark it as a compilerproc. Otherwise
  1815. # codegen would fail:
  1816. if sfCompilerProc in result.flags:
  1817. result.flags = result.flags - {sfCompilerProc, sfExportC, sfImportC}
  1818. result.loc.r = nil
  1819. proc setMs(n: PNode, s: PSym): PNode =
  1820. result = n
  1821. n.sons[0] = newSymNode(s)
  1822. n.sons[0].info = n.info
  1823. proc semSizeof(c: PContext, n: PNode): PNode =
  1824. if sonsLen(n) != 2:
  1825. localError(c.config, n.info, errXExpectsTypeOrValue % "sizeof")
  1826. else:
  1827. n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType})
  1828. #restoreOldStyleType(n.sons[1])
  1829. n.typ = getSysType(c.graph, n.info, tyInt)
  1830. let size = getSize(c.config, n[1].typ)
  1831. if size >= 0:
  1832. result = newIntNode(nkIntLit, size)
  1833. result.info = n.info
  1834. result.typ = n.typ
  1835. else:
  1836. result = n
  1837. proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode =
  1838. # this is a hotspot in the compiler!
  1839. result = n
  1840. case s.magic # magics that need special treatment
  1841. of mAddr:
  1842. checkSonsLen(n, 2, c.config)
  1843. result = semAddr(c, n.sons[1], s.name.s == "unsafeAddr")
  1844. of mTypeOf:
  1845. result = semTypeOf(c, n)
  1846. #of mArrGet: result = semArrGet(c, n, flags)
  1847. #of mArrPut: result = semArrPut(c, n, flags)
  1848. #of mAsgn: result = semAsgnOpr(c, n)
  1849. of mDefined: result = semDefined(c, setMs(n, s), false)
  1850. of mDefinedInScope: result = semDefined(c, setMs(n, s), true)
  1851. of mCompiles: result = semCompiles(c, setMs(n, s), flags)
  1852. #of mLow: result = semLowHigh(c, setMs(n, s), mLow)
  1853. #of mHigh: result = semLowHigh(c, setMs(n, s), mHigh)
  1854. of mIs: result = semIs(c, setMs(n, s), flags)
  1855. #of mOf: result = semOf(c, setMs(n, s))
  1856. of mShallowCopy: result = semShallowCopy(c, n, flags)
  1857. of mExpandToAst: result = semExpandToAst(c, n, s, flags)
  1858. of mQuoteAst: result = semQuoteAst(c, n)
  1859. of mAstToStr:
  1860. checkSonsLen(n, 2, c.config)
  1861. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph)
  1862. result.typ = getSysType(c.graph, n.info, tyString)
  1863. of mParallel:
  1864. if parallel notin c.features:
  1865. localError(c.config, n.info, "use the {.experimental.} pragma to enable 'parallel'")
  1866. result = setMs(n, s)
  1867. var x = n.lastSon
  1868. if x.kind == nkDo: x = x.sons[bodyPos]
  1869. inc c.inParallelStmt
  1870. result.sons[1] = semStmt(c, x, {})
  1871. dec c.inParallelStmt
  1872. of mSpawn:
  1873. result = setMs(n, s)
  1874. for i in 1 ..< n.len:
  1875. result.sons[i] = semExpr(c, n.sons[i])
  1876. let typ = result[^1].typ
  1877. if not typ.isEmptyType:
  1878. if spawnResult(typ, c.inParallelStmt > 0) == srFlowVar:
  1879. result.typ = createFlowVar(c, typ, n.info)
  1880. else:
  1881. result.typ = typ
  1882. result.add instantiateCreateFlowVarCall(c, typ, n.info).newSymNode
  1883. else:
  1884. result.add c.graph.emptyNode
  1885. of mProcCall:
  1886. result = setMs(n, s)
  1887. result.sons[1] = semExpr(c, n.sons[1])
  1888. result.typ = n[1].typ
  1889. of mPlugin:
  1890. # semDirectOp with conditional 'afterCallActions':
  1891. let nOrig = n.copyTree
  1892. #semLazyOpAux(c, n)
  1893. result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags)
  1894. if result == nil:
  1895. result = errorNode(c, n)
  1896. else:
  1897. let callee = result.sons[0].sym
  1898. if callee.magic == mNone:
  1899. semFinishOperands(c, result)
  1900. activate(c, result)
  1901. fixAbstractType(c, result)
  1902. analyseIfAddressTakenInCall(c, result)
  1903. if callee.magic != mNone:
  1904. result = magicsAfterOverloadResolution(c, result, flags)
  1905. of mRunnableExamples:
  1906. if c.config.cmd == cmdDoc and n.len >= 2 and n.lastSon.kind == nkStmtList:
  1907. when false:
  1908. # some of this dead code was moved to `prepareExamples`
  1909. if sfMainModule in c.module.flags:
  1910. let inp = toFullPath(c.config, c.module.info)
  1911. if c.runnableExamples == nil:
  1912. c.runnableExamples = newTree(nkStmtList,
  1913. newTree(nkImportStmt, newStrNode(nkStrLit, expandFilename(inp))))
  1914. let imports = newTree(nkStmtList)
  1915. var savedLastSon = copyTree n.lastSon
  1916. extractImports(savedLastSon, imports)
  1917. for imp in imports: c.runnableExamples.add imp
  1918. c.runnableExamples.add newTree(nkBlockStmt, c.graph.emptyNode, copyTree savedLastSon)
  1919. result = setMs(n, s)
  1920. else:
  1921. result = c.graph.emptyNode
  1922. of mSizeOf: result = semSizeof(c, setMs(n, s))
  1923. of mOmpParFor:
  1924. checkMinSonsLen(n, 3, c.config)
  1925. result = semDirectOp(c, n, flags)
  1926. else:
  1927. result = semDirectOp(c, n, flags)
  1928. proc semWhen(c: PContext, n: PNode, semCheck = true): PNode =
  1929. # If semCheck is set to false, ``when`` will return the verbatim AST of
  1930. # the correct branch. Otherwise the AST will be passed through semStmt.
  1931. result = nil
  1932. template setResult(e: untyped) =
  1933. if semCheck: result = semExpr(c, e) # do not open a new scope!
  1934. else: result = e
  1935. # Check if the node is "when nimvm"
  1936. # when nimvm:
  1937. # ...
  1938. # else:
  1939. # ...
  1940. var whenNimvm = false
  1941. var typ = commonTypeBegin
  1942. if n.sons.len == 2 and n.sons[0].kind == nkElifBranch and
  1943. n.sons[1].kind == nkElse:
  1944. let exprNode = n.sons[0].sons[0]
  1945. if exprNode.kind == nkIdent:
  1946. whenNimvm = lookUp(c, exprNode).magic == mNimvm
  1947. elif exprNode.kind == nkSym:
  1948. whenNimvm = exprNode.sym.magic == mNimvm
  1949. if whenNimvm: n.flags.incl nfLL
  1950. for i in countup(0, sonsLen(n) - 1):
  1951. var it = n.sons[i]
  1952. case it.kind
  1953. of nkElifBranch, nkElifExpr:
  1954. checkSonsLen(it, 2, c.config)
  1955. if whenNimvm:
  1956. if semCheck:
  1957. it.sons[1] = semExpr(c, it.sons[1])
  1958. typ = commonType(typ, it.sons[1].typ)
  1959. result = n # when nimvm is not elimited until codegen
  1960. else:
  1961. let e = forceBool(c, semConstExpr(c, it.sons[0]))
  1962. if e.kind != nkIntLit:
  1963. # can happen for cascading errors, assume false
  1964. # InternalError(n.info, "semWhen")
  1965. discard
  1966. elif e.intVal != 0 and result == nil:
  1967. setResult(it.sons[1])
  1968. of nkElse, nkElseExpr:
  1969. checkSonsLen(it, 1, c.config)
  1970. if result == nil or whenNimvm:
  1971. if semCheck:
  1972. it.sons[0] = semExpr(c, it.sons[0])
  1973. typ = commonType(typ, it.sons[0].typ)
  1974. if result == nil:
  1975. result = it.sons[0]
  1976. else: illFormedAst(n, c.config)
  1977. if result == nil:
  1978. result = newNodeI(nkEmpty, n.info)
  1979. if whenNimvm: result.typ = typ
  1980. # The ``when`` statement implements the mechanism for platform dependent
  1981. # code. Thus we try to ensure here consistent ID allocation after the
  1982. # ``when`` statement.
  1983. idSynchronizationPoint(200)
  1984. proc semSetConstr(c: PContext, n: PNode): PNode =
  1985. result = newNodeI(nkCurly, n.info)
  1986. result.typ = newTypeS(tySet, c)
  1987. if sonsLen(n) == 0:
  1988. rawAddSon(result.typ, newTypeS(tyEmpty, c))
  1989. else:
  1990. # only semantic checking for all elements, later type checking:
  1991. var typ: PType = nil
  1992. for i in countup(0, sonsLen(n) - 1):
  1993. if isRange(n.sons[i]):
  1994. checkSonsLen(n.sons[i], 3, c.config)
  1995. n.sons[i].sons[1] = semExprWithType(c, n.sons[i].sons[1])
  1996. n.sons[i].sons[2] = semExprWithType(c, n.sons[i].sons[2])
  1997. if typ == nil:
  1998. typ = skipTypes(n.sons[i].sons[1].typ,
  1999. {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  2000. n.sons[i].typ = n.sons[i].sons[2].typ # range node needs type too
  2001. elif n.sons[i].kind == nkRange:
  2002. # already semchecked
  2003. if typ == nil:
  2004. typ = skipTypes(n.sons[i].sons[0].typ,
  2005. {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  2006. else:
  2007. n.sons[i] = semExprWithType(c, n.sons[i])
  2008. if typ == nil:
  2009. typ = skipTypes(n.sons[i].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  2010. if not isOrdinalType(typ, allowEnumWithHoles=true):
  2011. localError(c.config, n.info, errOrdinalTypeExpected)
  2012. typ = makeRangeType(c, 0, MaxSetElements-1, n.info)
  2013. elif lengthOrd(c.config, typ) > MaxSetElements:
  2014. typ = makeRangeType(c, 0, MaxSetElements-1, n.info)
  2015. addSonSkipIntLit(result.typ, typ)
  2016. for i in countup(0, sonsLen(n) - 1):
  2017. var m: PNode
  2018. let info = n.sons[i].info
  2019. if isRange(n.sons[i]):
  2020. m = newNodeI(nkRange, info)
  2021. addSon(m, fitNode(c, typ, n.sons[i].sons[1], info))
  2022. addSon(m, fitNode(c, typ, n.sons[i].sons[2], info))
  2023. elif n.sons[i].kind == nkRange: m = n.sons[i] # already semchecked
  2024. else:
  2025. m = fitNode(c, typ, n.sons[i], info)
  2026. addSon(result, m)
  2027. proc semTableConstr(c: PContext, n: PNode): PNode =
  2028. # we simply transform ``{key: value, key2, key3: value}`` to
  2029. # ``[(key, value), (key2, value2), (key3, value2)]``
  2030. result = newNodeI(nkBracket, n.info)
  2031. var lastKey = 0
  2032. for i in 0..n.len-1:
  2033. var x = n.sons[i]
  2034. if x.kind == nkExprColonExpr and sonsLen(x) == 2:
  2035. for j in countup(lastKey, i-1):
  2036. var pair = newNodeI(nkTupleConstr, x.info)
  2037. pair.add(n.sons[j])
  2038. pair.add(x[1])
  2039. result.add(pair)
  2040. var pair = newNodeI(nkTupleConstr, x.info)
  2041. pair.add(x[0])
  2042. pair.add(x[1])
  2043. result.add(pair)
  2044. lastKey = i+1
  2045. if lastKey != n.len: illFormedAst(n, c.config)
  2046. result = semExpr(c, result)
  2047. type
  2048. TParKind = enum
  2049. paNone, paSingle, paTupleFields, paTuplePositions
  2050. proc checkPar(c: PContext; n: PNode): TParKind =
  2051. var length = sonsLen(n)
  2052. if length == 0:
  2053. result = paTuplePositions # ()
  2054. elif length == 1:
  2055. if n.sons[0].kind == nkExprColonExpr: result = paTupleFields
  2056. elif n.kind == nkTupleConstr: result = paTuplePositions
  2057. else: result = paSingle # (expr)
  2058. else:
  2059. if n.sons[0].kind == nkExprColonExpr: result = paTupleFields
  2060. else: result = paTuplePositions
  2061. for i in countup(0, length - 1):
  2062. if result == paTupleFields:
  2063. if (n.sons[i].kind != nkExprColonExpr) or
  2064. not (n.sons[i].sons[0].kind in {nkSym, nkIdent}):
  2065. localError(c.config, n.sons[i].info, errNamedExprExpected)
  2066. return paNone
  2067. else:
  2068. if n.sons[i].kind == nkExprColonExpr:
  2069. localError(c.config, n.sons[i].info, errNamedExprNotAllowed)
  2070. return paNone
  2071. proc semTupleFieldsConstr(c: PContext, n: PNode, flags: TExprFlags): PNode =
  2072. result = newNodeI(nkTupleConstr, n.info)
  2073. var typ = newTypeS(tyTuple, c)
  2074. typ.n = newNodeI(nkRecList, n.info) # nkIdentDefs
  2075. var ids = initIntSet()
  2076. for i in countup(0, sonsLen(n) - 1):
  2077. if n[i].kind != nkExprColonExpr or n[i][0].kind notin {nkSym, nkIdent}:
  2078. illFormedAst(n.sons[i], c.config)
  2079. var id: PIdent
  2080. if n.sons[i].sons[0].kind == nkIdent: id = n.sons[i].sons[0].ident
  2081. else: id = n.sons[i].sons[0].sym.name
  2082. if containsOrIncl(ids, id.id):
  2083. localError(c.config, n.sons[i].info, errFieldInitTwice % id.s)
  2084. n.sons[i].sons[1] = semExprWithType(c, n.sons[i].sons[1],
  2085. flags*{efAllowDestructor})
  2086. var f = newSymS(skField, n.sons[i].sons[0], c)
  2087. f.typ = skipIntLit(n.sons[i].sons[1].typ)
  2088. f.position = i
  2089. rawAddSon(typ, f.typ)
  2090. addSon(typ.n, newSymNode(f))
  2091. n.sons[i].sons[0] = newSymNode(f)
  2092. addSon(result, n.sons[i])
  2093. result.typ = typ
  2094. proc semTuplePositionsConstr(c: PContext, n: PNode, flags: TExprFlags): PNode =
  2095. result = n # we don't modify n, but compute the type:
  2096. result.kind = nkTupleConstr
  2097. var typ = newTypeS(tyTuple, c) # leave typ.n nil!
  2098. for i in countup(0, sonsLen(n) - 1):
  2099. n.sons[i] = semExprWithType(c, n.sons[i], flags*{efAllowDestructor})
  2100. addSonSkipIntLit(typ, n.sons[i].typ)
  2101. result.typ = typ
  2102. proc isTupleType(n: PNode): bool =
  2103. if n.len == 0:
  2104. return false # don't interpret () as type
  2105. for i in countup(0, n.len - 1):
  2106. if n[i].typ == nil or n[i].typ.kind != tyTypeDesc:
  2107. return false
  2108. return true
  2109. include semobjconstr
  2110. proc semBlock(c: PContext, n: PNode; flags: TExprFlags): PNode =
  2111. result = n
  2112. inc(c.p.nestedBlockCounter)
  2113. checkSonsLen(n, 2, c.config)
  2114. openScope(c) # BUGFIX: label is in the scope of block!
  2115. if n.sons[0].kind != nkEmpty:
  2116. var labl = newSymG(skLabel, n.sons[0], c)
  2117. if sfGenSym notin labl.flags:
  2118. addDecl(c, labl)
  2119. elif labl.owner == nil:
  2120. labl.owner = c.p.owner
  2121. n.sons[0] = newSymNode(labl, n.sons[0].info)
  2122. suggestSym(c.config, n.sons[0].info, labl, c.graph.usageSym)
  2123. styleCheckDef(c.config, labl)
  2124. onDef(n[0].info, labl)
  2125. n.sons[1] = semExpr(c, n.sons[1], flags)
  2126. n.typ = n.sons[1].typ
  2127. if isEmptyType(n.typ): n.kind = nkBlockStmt
  2128. else: n.kind = nkBlockExpr
  2129. closeScope(c)
  2130. dec(c.p.nestedBlockCounter)
  2131. proc semExportExcept(c: PContext, n: PNode): PNode =
  2132. let moduleName = semExpr(c, n[0])
  2133. if moduleName.kind != nkSym or moduleName.sym.kind != skModule:
  2134. localError(c.config, n.info, "The export/except syntax expects a module name")
  2135. return n
  2136. let exceptSet = readExceptSet(c, n)
  2137. let exported = moduleName.sym
  2138. result = newNodeI(nkExportStmt, n.info)
  2139. strTableAdd(c.module.tab, exported)
  2140. var i: TTabIter
  2141. var s = initTabIter(i, exported.tab)
  2142. while s != nil:
  2143. if s.kind in ExportableSymKinds+{skModule} and
  2144. s.name.id notin exceptSet:
  2145. strTableAdd(c.module.tab, s)
  2146. result.add newSymNode(s, n.info)
  2147. s = nextIter(i, exported.tab)
  2148. proc semExport(c: PContext, n: PNode): PNode =
  2149. result = newNodeI(nkExportStmt, n.info)
  2150. for i in 0..<n.len:
  2151. let a = n.sons[i]
  2152. var o: TOverloadIter
  2153. var s = initOverloadIter(o, c, a)
  2154. if s == nil:
  2155. localError(c.config, a.info, errGenerated, "cannot export: " & renderTree(a))
  2156. elif s.kind == skModule:
  2157. # forward everything from that module:
  2158. strTableAdd(c.module.tab, s)
  2159. var ti: TTabIter
  2160. var it = initTabIter(ti, s.tab)
  2161. while it != nil:
  2162. if it.kind in ExportableSymKinds+{skModule}:
  2163. strTableAdd(c.module.tab, it)
  2164. result.add newSymNode(it, a.info)
  2165. it = nextIter(ti, s.tab)
  2166. else:
  2167. while s != nil:
  2168. if s.kind in ExportableSymKinds+{skModule}:
  2169. result.add(newSymNode(s, a.info))
  2170. strTableAdd(c.module.tab, s)
  2171. s = nextOverloadIter(o, c, a)
  2172. proc shouldBeBracketExpr(n: PNode): bool =
  2173. assert n.kind in nkCallKinds
  2174. let a = n.sons[0]
  2175. if a.kind in nkCallKinds:
  2176. let b = a[0]
  2177. if b.kind in nkSymChoices:
  2178. for i in 0..<b.len:
  2179. if b[i].kind == nkSym and b[i].sym.magic == mArrGet:
  2180. let be = newNodeI(nkBracketExpr, n.info)
  2181. for i in 1..<a.len: be.add(a[i])
  2182. n.sons[0] = be
  2183. return true
  2184. proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  2185. result = n
  2186. if c.config.cmd == cmdIdeTools: suggestExpr(c, n)
  2187. if nfSem in n.flags: return
  2188. case n.kind
  2189. of nkIdent, nkAccQuoted:
  2190. let checks = if efNoEvaluateGeneric in flags:
  2191. {checkUndeclared, checkPureEnumFields}
  2192. elif efInCall in flags:
  2193. {checkUndeclared, checkModule, checkPureEnumFields}
  2194. else:
  2195. {checkUndeclared, checkModule, checkAmbiguity, checkPureEnumFields}
  2196. var s = qualifiedLookUp(c, n, checks)
  2197. if c.matchedConcept == nil: semCaptureSym(s, c.p.owner)
  2198. if s.kind in {skProc, skFunc, skMethod, skConverter, skIterator}:
  2199. #performProcvarCheck(c, n, s)
  2200. result = symChoice(c, n, s, scClosed)
  2201. if result.kind == nkSym:
  2202. markIndirect(c, result.sym)
  2203. # if isGenericRoutine(result.sym):
  2204. # localError(c.config, n.info, errInstantiateXExplicitly, s.name.s)
  2205. else:
  2206. result = semSym(c, n, s, flags)
  2207. of nkSym:
  2208. # because of the changed symbol binding, this does not mean that we
  2209. # don't have to check the symbol for semantics here again!
  2210. result = semSym(c, n, n.sym, flags)
  2211. of nkEmpty, nkNone, nkCommentStmt, nkType:
  2212. discard
  2213. of nkNilLit:
  2214. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyNil)
  2215. of nkIntLit:
  2216. if result.typ == nil: setIntLitType(c.graph, result)
  2217. of nkInt8Lit:
  2218. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyInt8)
  2219. of nkInt16Lit:
  2220. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyInt16)
  2221. of nkInt32Lit:
  2222. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyInt32)
  2223. of nkInt64Lit:
  2224. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyInt64)
  2225. of nkUIntLit:
  2226. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyUInt)
  2227. of nkUInt8Lit:
  2228. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyUInt8)
  2229. of nkUInt16Lit:
  2230. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyUInt16)
  2231. of nkUInt32Lit:
  2232. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyUInt32)
  2233. of nkUInt64Lit:
  2234. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyUInt64)
  2235. #of nkFloatLit:
  2236. # if result.typ == nil: result.typ = getFloatLitType(result)
  2237. of nkFloat32Lit:
  2238. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyFloat32)
  2239. of nkFloat64Lit, nkFloatLit:
  2240. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyFloat64)
  2241. of nkFloat128Lit:
  2242. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyFloat128)
  2243. of nkStrLit..nkTripleStrLit:
  2244. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyString)
  2245. of nkCharLit:
  2246. if result.typ == nil: result.typ = getSysType(c.graph, n.info, tyChar)
  2247. of nkDotExpr:
  2248. result = semFieldAccess(c, n, flags)
  2249. if result.kind == nkDotCall:
  2250. result.kind = nkCall
  2251. result = semExpr(c, result, flags)
  2252. of nkBind:
  2253. message(c.config, n.info, warnDeprecated, "bind")
  2254. result = semExpr(c, n.sons[0], flags)
  2255. of nkTypeOfExpr, nkTupleTy, nkTupleClassTy, nkRefTy..nkEnumTy, nkStaticTy:
  2256. if c.matchedConcept != nil and n.len == 1:
  2257. let modifier = n.modifierTypeKindOfNode
  2258. if modifier != tyNone:
  2259. var baseType = semExpr(c, n[0]).typ.skipTypes({tyTypeDesc})
  2260. result.typ = c.makeTypeDesc(c.newTypeWithSons(modifier, @[baseType]))
  2261. return
  2262. var typ = semTypeNode(c, n, nil).skipTypes({tyTypeDesc})
  2263. result.typ = makeTypeDesc(c, typ)
  2264. of nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit:
  2265. # check if it is an expression macro:
  2266. checkMinSonsLen(n, 1, c.config)
  2267. #when defined(nimsuggest):
  2268. # if gIdeCmd == ideCon and c.config.m.trackPos == n.info: suggestExprNoCheck(c, n)
  2269. let mode = if nfDotField in n.flags: {} else: {checkUndeclared}
  2270. var s = qualifiedLookUp(c, n.sons[0], mode)
  2271. if s != nil:
  2272. #if c.config.cmd == cmdPretty and n.sons[0].kind == nkDotExpr:
  2273. # pretty.checkUse(n.sons[0].sons[1].info, s)
  2274. case s.kind
  2275. of skMacro:
  2276. if sfImmediate notin s.flags:
  2277. result = semDirectOp(c, n, flags)
  2278. else:
  2279. result = semMacroExpr(c, n, n, s, flags)
  2280. of skTemplate:
  2281. if sfImmediate notin s.flags:
  2282. result = semDirectOp(c, n, flags)
  2283. else:
  2284. result = semTemplateExpr(c, n, s, flags)
  2285. of skType:
  2286. # XXX think about this more (``set`` procs)
  2287. if n.len == 2:
  2288. result = semConv(c, n)
  2289. elif contains(c.ambiguousSymbols, s.id) and n.len == 1:
  2290. errorUseQualifier(c, n.info, s)
  2291. elif n.len == 1:
  2292. result = semObjConstr(c, n, flags)
  2293. elif s.magic == mNone: result = semDirectOp(c, n, flags)
  2294. else: result = semMagic(c, n, s, flags)
  2295. of skProc, skFunc, skMethod, skConverter, skIterator:
  2296. if s.magic == mNone: result = semDirectOp(c, n, flags)
  2297. else: result = semMagic(c, n, s, flags)
  2298. else:
  2299. #liMessage(n.info, warnUser, renderTree(n));
  2300. result = semIndirectOp(c, n, flags)
  2301. elif (n[0].kind == nkBracketExpr or shouldBeBracketExpr(n)) and
  2302. isSymChoice(n[0][0]):
  2303. # indirectOp can deal with explicit instantiations; the fixes
  2304. # the 'newSeq[T](x)' bug
  2305. setGenericParams(c, n.sons[0])
  2306. result = semDirectOp(c, n, flags)
  2307. elif isSymChoice(n.sons[0]) or nfDotField in n.flags:
  2308. result = semDirectOp(c, n, flags)
  2309. else:
  2310. result = semIndirectOp(c, n, flags)
  2311. of nkWhen:
  2312. if efWantStmt in flags:
  2313. result = semWhen(c, n, true)
  2314. else:
  2315. result = semWhen(c, n, false)
  2316. if result == n:
  2317. # This is a "when nimvm" stmt.
  2318. result = semWhen(c, n, true)
  2319. else:
  2320. result = semExpr(c, result, flags)
  2321. of nkBracketExpr:
  2322. checkMinSonsLen(n, 1, c.config)
  2323. result = semArrayAccess(c, n, flags)
  2324. of nkCurlyExpr:
  2325. result = semExpr(c, buildOverloadedSubscripts(n, getIdent(c.cache, "{}")), flags)
  2326. of nkPragmaExpr:
  2327. var
  2328. expr = n[0]
  2329. pragma = n[1]
  2330. pragmaName = considerQuotedIdent(c, pragma[0])
  2331. flags = flags
  2332. case whichKeyword(pragmaName)
  2333. of wExplain:
  2334. flags.incl efExplain
  2335. else:
  2336. # what other pragmas are allowed for expressions? `likely`, `unlikely`
  2337. invalidPragma(c, n)
  2338. result = semExpr(c, n[0], flags)
  2339. of nkPar, nkTupleConstr:
  2340. case checkPar(c, n)
  2341. of paNone: result = errorNode(c, n)
  2342. of paTuplePositions:
  2343. var tupexp = semTuplePositionsConstr(c, n, flags)
  2344. if isTupleType(tupexp):
  2345. # reinterpret as type
  2346. var typ = semTypeNode(c, n, nil).skipTypes({tyTypeDesc})
  2347. result.typ = makeTypeDesc(c, typ)
  2348. else:
  2349. result = tupexp
  2350. of paTupleFields: result = semTupleFieldsConstr(c, n, flags)
  2351. of paSingle: result = semExpr(c, n.sons[0], flags)
  2352. of nkCurly: result = semSetConstr(c, n)
  2353. of nkBracket: result = semArrayConstr(c, n, flags)
  2354. of nkObjConstr: result = semObjConstr(c, n, flags)
  2355. of nkLambdaKinds: result = semLambda(c, n, flags)
  2356. of nkDerefExpr: result = semDeref(c, n)
  2357. of nkAddr:
  2358. result = n
  2359. checkSonsLen(n, 1, c.config)
  2360. result = semAddr(c, n.sons[0])
  2361. of nkHiddenAddr, nkHiddenDeref:
  2362. checkSonsLen(n, 1, c.config)
  2363. n.sons[0] = semExpr(c, n.sons[0], flags)
  2364. of nkCast: result = semCast(c, n)
  2365. of nkIfExpr, nkIfStmt: result = semIf(c, n, flags)
  2366. of nkHiddenStdConv, nkHiddenSubConv, nkConv, nkHiddenCallConv:
  2367. checkSonsLen(n, 2, c.config)
  2368. considerGenSyms(c, n)
  2369. of nkStringToCString, nkCStringToString, nkObjDownConv, nkObjUpConv:
  2370. checkSonsLen(n, 1, c.config)
  2371. considerGenSyms(c, n)
  2372. of nkChckRangeF, nkChckRange64, nkChckRange:
  2373. checkSonsLen(n, 3, c.config)
  2374. considerGenSyms(c, n)
  2375. of nkCheckedFieldExpr:
  2376. checkMinSonsLen(n, 2, c.config)
  2377. considerGenSyms(c, n)
  2378. of nkTableConstr:
  2379. result = semTableConstr(c, n)
  2380. of nkClosedSymChoice, nkOpenSymChoice:
  2381. # handling of sym choices is context dependent
  2382. # the node is left intact for now
  2383. discard
  2384. of nkStaticExpr: result = semStaticExpr(c, n[0])
  2385. of nkAsgn: result = semAsgn(c, n)
  2386. of nkBlockStmt, nkBlockExpr: result = semBlock(c, n, flags)
  2387. of nkStmtList, nkStmtListExpr: result = semStmtList(c, n, flags)
  2388. of nkRaiseStmt: result = semRaise(c, n)
  2389. of nkVarSection: result = semVarOrLet(c, n, skVar)
  2390. of nkLetSection: result = semVarOrLet(c, n, skLet)
  2391. of nkConstSection: result = semConst(c, n)
  2392. of nkTypeSection: result = semTypeSection(c, n)
  2393. of nkDiscardStmt: result = semDiscard(c, n)
  2394. of nkWhileStmt: result = semWhile(c, n, flags)
  2395. of nkTryStmt: result = semTry(c, n, flags)
  2396. of nkBreakStmt, nkContinueStmt: result = semBreakOrContinue(c, n)
  2397. of nkForStmt, nkParForStmt: result = semFor(c, n, flags)
  2398. of nkCaseStmt: result = semCase(c, n, flags)
  2399. of nkReturnStmt: result = semReturn(c, n)
  2400. of nkUsingStmt: result = semUsing(c, n)
  2401. of nkAsmStmt: result = semAsm(c, n)
  2402. of nkYieldStmt: result = semYield(c, n)
  2403. of nkPragma: pragma(c, c.p.owner, n, stmtPragmas)
  2404. of nkIteratorDef: result = semIterator(c, n)
  2405. of nkProcDef: result = semProc(c, n)
  2406. of nkFuncDef: result = semFunc(c, n)
  2407. of nkMethodDef: result = semMethod(c, n)
  2408. of nkConverterDef: result = semConverterDef(c, n)
  2409. of nkMacroDef: result = semMacroDef(c, n)
  2410. of nkTemplateDef: result = semTemplateDef(c, n)
  2411. of nkImportStmt:
  2412. # this particular way allows 'import' in a 'compiles' context so that
  2413. # template canImport(x): bool =
  2414. # compiles:
  2415. # import x
  2416. #
  2417. # works:
  2418. if c.currentScope.depthLevel > 2 + c.compilesContextId:
  2419. localError(c.config, n.info, errXOnlyAtModuleScope % "import")
  2420. result = evalImport(c, n)
  2421. of nkImportExceptStmt:
  2422. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "import")
  2423. result = evalImportExcept(c, n)
  2424. of nkFromStmt:
  2425. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "from")
  2426. result = evalFrom(c, n)
  2427. of nkIncludeStmt:
  2428. #if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "include")
  2429. result = evalInclude(c, n)
  2430. of nkExportStmt:
  2431. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "export")
  2432. result = semExport(c, n)
  2433. of nkExportExceptStmt:
  2434. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "export")
  2435. result = semExportExcept(c, n)
  2436. of nkPragmaBlock:
  2437. result = semPragmaBlock(c, n)
  2438. of nkStaticStmt:
  2439. result = semStaticStmt(c, n)
  2440. of nkDefer:
  2441. n.sons[0] = semExpr(c, n.sons[0])
  2442. if not n.sons[0].typ.isEmptyType and not implicitlyDiscardable(n.sons[0]):
  2443. localError(c.config, n.info, "'defer' takes a 'void' expression")
  2444. #localError(c.config, n.info, errGenerated, "'defer' not allowed in this context")
  2445. of nkGotoState, nkState:
  2446. if n.len != 1 and n.len != 2: illFormedAst(n, c.config)
  2447. for i in 0 ..< n.len:
  2448. n.sons[i] = semExpr(c, n.sons[i])
  2449. of nkComesFrom: discard "ignore the comes from information for now"
  2450. else:
  2451. localError(c.config, n.info, "invalid expression: " &
  2452. renderTree(n, {renderNoComments}))
  2453. if result != nil: incl(result.flags, nfSem)