semexprs.nim 104 KB

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