semexprs.nim 131 KB

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