semexprs.nim 107 KB

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