semexprs.nim 120 KB

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