semexprs.nim 114 KB

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