semexprs.nim 98 KB

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