pragmas.nim 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements semantic checking for pragmas
  10. import
  11. os, condsyms, ast, astalgo, idents, semdata, msgs, renderer,
  12. wordrecg, ropes, options, strutils, extccomp, math, magicsys, trees,
  13. types, lookups, lineinfos, pathutils, linter
  14. const
  15. FirstCallConv* = wNimcall
  16. LastCallConv* = wNoconv
  17. const
  18. declPragmas = {wImportc, wImportObjC, wImportCpp, wImportJs, wExportc, wExportCpp,
  19. wExportNims, wExtern, wDeprecated, wNodecl, wError, wUsed, wAlign}
  20. ## common pragmas for declarations, to a good approximation
  21. procPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  22. wMagic, wNoSideEffect, wSideEffect, wNoreturn, wNosinks, wDynlib, wHeader,
  23. wCompilerProc, wNonReloadable, wCore, wProcVar, wVarargs, wCompileTime, wMerge,
  24. wBorrow, wImportCompilerProc, wThread,
  25. wAsmNoStackFrame, wDiscardable, wNoInit, wCodegenDecl,
  26. wGensym, wInject, wRaises, wTags, wLocks, wDelegator, wGcSafe,
  27. wConstructor, wLiftLocals, wStackTrace, wLineTrace, wNoDestroy,
  28. wRequires, wEnsures}
  29. converterPragmas* = procPragmas
  30. methodPragmas* = procPragmas+{wBase}-{wImportCpp}
  31. templatePragmas* = {wDeprecated, wError, wGensym, wInject, wDirty,
  32. wDelegator, wExportNims, wUsed, wPragma}
  33. macroPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  34. wMagic, wNoSideEffect, wCompilerProc, wNonReloadable, wCore,
  35. wDiscardable, wGensym, wInject, wDelegator}
  36. iteratorPragmas* = declPragmas + {FirstCallConv..LastCallConv, wNoSideEffect, wSideEffect,
  37. wMagic, wBorrow,
  38. wDiscardable, wGensym, wInject, wRaises,
  39. wTags, wLocks, wGcSafe, wRequires, wEnsures}
  40. exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNoSideEffect}
  41. stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangeChecks,
  42. wBoundChecks, wOverflowChecks, wNilChecks, wStaticBoundchecks,
  43. wStyleChecks, wAssertions,
  44. wWarnings, wHints,
  45. wLineDir, wStackTrace, wLineTrace, wOptimization, wHint, wWarning, wError,
  46. wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
  47. wPassl, wPassc, wLocalPassc,
  48. wDeadCodeElimUnused, # deprecated, always on
  49. wDeprecated,
  50. wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
  51. wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward, wReorder, wComputedGoto,
  52. wInjectStmt, wExperimental, wThis, wUsed, wInvariant, wAssume, wAssert}
  53. lambdaPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  54. wNoSideEffect, wSideEffect, wNoreturn, wNosinks, wDynlib, wHeader,
  55. wThread, wAsmNoStackFrame,
  56. wRaises, wLocks, wTags, wRequires, wEnsures,
  57. wGcSafe, wCodegenDecl} - {wExportNims, wError, wUsed} # why exclude these?
  58. typePragmas* = declPragmas + {wMagic, wAcyclic,
  59. wPure, wHeader, wCompilerProc, wCore, wFinal, wSize, wShallow,
  60. wIncompleteStruct, wCompleteStruct, wByCopy, wByRef,
  61. wInheritable, wGensym, wInject, wRequiresInit, wUnchecked, wUnion, wPacked,
  62. wBorrow, wGcSafe, wPartial, wExplain, wPackage}
  63. fieldPragmas* = declPragmas + {
  64. wGuard, wBitsize, wCursor, wRequiresInit, wNoalias} - {wExportNims, wNodecl} # why exclude these?
  65. varPragmas* = declPragmas + {wVolatile, wRegister, wThreadVar,
  66. wMagic, wHeader, wCompilerProc, wCore, wDynlib,
  67. wNoInit, wCompileTime, wGlobal,
  68. wGensym, wInject, wCodegenDecl, wGuard, wGoto, wCursor, wNoalias}
  69. constPragmas* = declPragmas + {wHeader, wMagic,
  70. wGensym, wInject,
  71. wIntDefine, wStrDefine, wBoolDefine, wCompilerProc, wCore}
  72. paramPragmas* = {wNoalias, wInject, wGensym}
  73. letPragmas* = varPragmas
  74. procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNoSideEffect,
  75. wThread, wRaises, wLocks, wTags, wGcSafe,
  76. wRequires, wEnsures}
  77. forVarPragmas* = {wInject, wGensym}
  78. allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
  79. enumFieldPragmas* = {wDeprecated}
  80. proc getPragmaVal*(procAst: PNode; name: TSpecialWord): PNode =
  81. let p = procAst[pragmasPos]
  82. if p.kind == nkEmpty: return nil
  83. for it in p:
  84. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent and
  85. it[0].ident.id == ord(name):
  86. return it[1]
  87. proc pragma*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  88. isStatement: bool = false)
  89. proc recordPragma(c: PContext; n: PNode; key, val: string; val2 = "") =
  90. var recorded = newNodeI(nkCommentStmt, n.info)
  91. recorded.add newStrNode(key, n.info)
  92. recorded.add newStrNode(val, n.info)
  93. if val2.len > 0: recorded.add newStrNode(val2, n.info)
  94. c.graph.recordStmt(c.graph, c.module, recorded)
  95. const
  96. errStringLiteralExpected = "string literal expected"
  97. errIntLiteralExpected = "integer literal expected"
  98. proc invalidPragma*(c: PContext; n: PNode) =
  99. localError(c.config, n.info, "invalid pragma: " & renderTree(n, {renderNoComments}))
  100. proc illegalCustomPragma*(c: PContext, n: PNode, s: PSym) =
  101. localError(c.config, n.info, "cannot attach a custom pragma to '" & s.name.s & "'")
  102. proc pragmaProposition(c: PContext, n: PNode) =
  103. if n.kind notin nkPragmaCallKinds or n.len != 2:
  104. localError(c.config, n.info, "proposition expected")
  105. else:
  106. n[1] = c.semExpr(c, n[1])
  107. proc pragmaEnsures(c: PContext, n: PNode) =
  108. if n.kind notin nkPragmaCallKinds or n.len != 2:
  109. localError(c.config, n.info, "proposition expected")
  110. else:
  111. openScope(c)
  112. let o = getCurrOwner(c)
  113. if o.kind in routineKinds and o.typ != nil and o.typ.sons[0] != nil:
  114. var s = newSym(skResult, getIdent(c.cache, "result"), o, n.info)
  115. s.typ = o.typ.sons[0]
  116. incl(s.flags, sfUsed)
  117. addDecl(c, s)
  118. n[1] = c.semExpr(c, n[1])
  119. closeScope(c)
  120. proc pragmaAsm*(c: PContext, n: PNode): char =
  121. result = '\0'
  122. if n != nil:
  123. for i in 0..<n.len:
  124. let it = n[i]
  125. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent:
  126. case whichKeyword(it[0].ident)
  127. of wSubsChar:
  128. if it[1].kind == nkCharLit: result = chr(int(it[1].intVal))
  129. else: invalidPragma(c, it)
  130. else: invalidPragma(c, it)
  131. else:
  132. invalidPragma(c, it)
  133. proc setExternName(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  134. # special cases to improve performance:
  135. if extname == "$1":
  136. s.loc.r = rope(s.name.s)
  137. elif '$' notin extname:
  138. s.loc.r = rope(extname)
  139. else:
  140. try:
  141. s.loc.r = rope(extname % s.name.s)
  142. except ValueError:
  143. localError(c.config, info, "invalid extern name: '" & extname & "'. (Forgot to escape '$'?)")
  144. when hasFFI:
  145. s.cname = $s.loc.r
  146. if c.config.cmd == cmdPretty and '$' notin extname:
  147. # note that '{.importc.}' is transformed into '{.importc: "$1".}'
  148. s.loc.flags.incl(lfFullExternalName)
  149. proc makeExternImport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  150. setExternName(c, s, extname, info)
  151. incl(s.flags, sfImportc)
  152. excl(s.flags, sfForward)
  153. proc makeExternExport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  154. setExternName(c, s, extname, info)
  155. incl(s.flags, sfExportc)
  156. proc processImportCompilerProc(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  157. setExternName(c, s, extname, info)
  158. incl(s.flags, sfImportc)
  159. excl(s.flags, sfForward)
  160. incl(s.loc.flags, lfImportCompilerProc)
  161. proc processImportCpp(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  162. setExternName(c, s, extname, info)
  163. incl(s.flags, sfImportc)
  164. incl(s.flags, sfInfixCall)
  165. excl(s.flags, sfForward)
  166. if c.config.backend == backendC:
  167. let m = s.getModule()
  168. incl(m.flags, sfCompileToCpp)
  169. incl c.config.globalOptions, optMixedMode
  170. proc processImportObjC(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  171. setExternName(c, s, extname, info)
  172. incl(s.flags, sfImportc)
  173. incl(s.flags, sfNamedParamCall)
  174. excl(s.flags, sfForward)
  175. let m = s.getModule()
  176. incl(m.flags, sfCompileToObjc)
  177. proc newEmptyStrNode(c: PContext; n: PNode): PNode {.noinline.} =
  178. result = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  179. result.strVal = ""
  180. proc getStrLitNode(c: PContext, n: PNode): PNode =
  181. if n.kind notin nkPragmaCallKinds or n.len != 2:
  182. localError(c.config, n.info, errStringLiteralExpected)
  183. # error correction:
  184. result = newEmptyStrNode(c, n)
  185. else:
  186. n[1] = c.semConstExpr(c, n[1])
  187. case n[1].kind
  188. of nkStrLit, nkRStrLit, nkTripleStrLit: result = n[1]
  189. else:
  190. localError(c.config, n.info, errStringLiteralExpected)
  191. # error correction:
  192. result = newEmptyStrNode(c, n)
  193. proc expectStrLit(c: PContext, n: PNode): string =
  194. result = getStrLitNode(c, n).strVal
  195. proc expectIntLit(c: PContext, n: PNode): int =
  196. if n.kind notin nkPragmaCallKinds or n.len != 2:
  197. localError(c.config, n.info, errIntLiteralExpected)
  198. else:
  199. n[1] = c.semConstExpr(c, n[1])
  200. case n[1].kind
  201. of nkIntLit..nkInt64Lit: result = int(n[1].intVal)
  202. else: localError(c.config, n.info, errIntLiteralExpected)
  203. proc getOptionalStr(c: PContext, n: PNode, defaultStr: string): string =
  204. if n.kind in nkPragmaCallKinds: result = expectStrLit(c, n)
  205. else: result = defaultStr
  206. proc processCodegenDecl(c: PContext, n: PNode, sym: PSym) =
  207. sym.constraint = getStrLitNode(c, n)
  208. proc processMagic(c: PContext, n: PNode, s: PSym) =
  209. #if sfSystemModule notin c.module.flags:
  210. # liMessage(n.info, errMagicOnlyInSystem)
  211. if n.kind notin nkPragmaCallKinds or n.len != 2:
  212. localError(c.config, n.info, errStringLiteralExpected)
  213. return
  214. var v: string
  215. if n[1].kind == nkIdent: v = n[1].ident.s
  216. else: v = expectStrLit(c, n)
  217. for m in TMagic:
  218. if substr($m, 1) == v:
  219. s.magic = m
  220. break
  221. if s.magic == mNone: message(c.config, n.info, warnUnknownMagic, v)
  222. proc wordToCallConv(sw: TSpecialWord): TCallingConvention =
  223. # this assumes that the order of special words and calling conventions is
  224. # the same
  225. TCallingConvention(ord(ccNimCall) + ord(sw) - ord(wNimcall))
  226. proc isTurnedOn(c: PContext, n: PNode): bool =
  227. if n.kind in nkPragmaCallKinds and n.len == 2:
  228. let x = c.semConstBoolExpr(c, n[1])
  229. n[1] = x
  230. if x.kind == nkIntLit: return x.intVal != 0
  231. localError(c.config, n.info, "'on' or 'off' expected")
  232. proc onOff(c: PContext, n: PNode, op: TOptions, resOptions: var TOptions) =
  233. if isTurnedOn(c, n): resOptions.incl op
  234. else: resOptions.excl op
  235. proc pragmaNoForward(c: PContext, n: PNode; flag=sfNoForward) =
  236. if isTurnedOn(c, n):
  237. incl(c.module.flags, flag)
  238. c.features.incl codeReordering
  239. else:
  240. excl(c.module.flags, flag)
  241. # c.features.excl codeReordering
  242. # deprecated as of 0.18.1
  243. message(c.config, n.info, warnDeprecated,
  244. "use {.experimental: \"codeReordering\".} instead; " &
  245. (if flag == sfNoForward: "{.noForward.}" else: "{.reorder.}") & " is deprecated")
  246. proc processCallConv(c: PContext, n: PNode) =
  247. if n.kind in nkPragmaCallKinds and n.len == 2 and n[1].kind == nkIdent:
  248. let sw = whichKeyword(n[1].ident)
  249. case sw
  250. of FirstCallConv..LastCallConv:
  251. c.optionStack[^1].defaultCC = wordToCallConv(sw)
  252. else: localError(c.config, n.info, "calling convention expected")
  253. else:
  254. localError(c.config, n.info, "calling convention expected")
  255. proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib =
  256. for it in c.libs:
  257. if it.kind == kind and trees.exprStructuralEquivalent(it.path, path):
  258. return it
  259. result = newLib(kind)
  260. result.path = path
  261. c.libs.add result
  262. if path.kind in {nkStrLit..nkTripleStrLit}:
  263. result.isOverriden = options.isDynlibOverride(c.config, path.strVal)
  264. proc expectDynlibNode(c: PContext, n: PNode): PNode =
  265. if n.kind notin nkPragmaCallKinds or n.len != 2:
  266. localError(c.config, n.info, errStringLiteralExpected)
  267. # error correction:
  268. result = newEmptyStrNode(c, n)
  269. else:
  270. # For the OpenGL wrapper we support:
  271. # {.dynlib: myGetProcAddr(...).}
  272. result = c.semExpr(c, n[1])
  273. if result.kind == nkSym and result.sym.kind == skConst:
  274. result = result.sym.ast # look it up
  275. if result.typ == nil or result.typ.kind notin {tyPointer, tyString, tyProc}:
  276. localError(c.config, n.info, errStringLiteralExpected)
  277. result = newEmptyStrNode(c, n)
  278. proc processDynLib(c: PContext, n: PNode, sym: PSym) =
  279. if (sym == nil) or (sym.kind == skModule):
  280. let lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  281. if not lib.isOverriden:
  282. c.optionStack[^1].dynlib = lib
  283. else:
  284. if n.kind in nkPragmaCallKinds:
  285. var lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  286. if not lib.isOverriden:
  287. addToLib(lib, sym)
  288. incl(sym.loc.flags, lfDynamicLib)
  289. else:
  290. incl(sym.loc.flags, lfExportLib)
  291. # since we'll be loading the dynlib symbols dynamically, we must use
  292. # a calling convention that doesn't introduce custom name mangling
  293. # cdecl is the default - the user can override this explicitly
  294. if sym.kind in routineKinds and sym.typ != nil and
  295. tfExplicitCallConv notin sym.typ.flags:
  296. sym.typ.callConv = ccCDecl
  297. proc processNote(c: PContext, n: PNode) =
  298. template handleNote(toStrArray, msgMin, notes) =
  299. let x = findStr(toStrArray, n[0][1].ident.s)
  300. if x >= 0:
  301. nk = TNoteKind(x + ord(msgMin))
  302. let x = c.semConstBoolExpr(c, n[1])
  303. n[1] = x
  304. if x.kind == nkIntLit and x.intVal != 0: incl(notes, nk)
  305. else: excl(notes, nk)
  306. else:
  307. invalidPragma(c, n)
  308. if n.kind in nkPragmaCallKinds and n.len == 2 and
  309. n[0].kind == nkBracketExpr and
  310. n[0].len == 2 and
  311. n[0][1].kind == nkIdent and n[0][0].kind == nkIdent:
  312. var nk: TNoteKind
  313. case whichKeyword(n[0][0].ident)
  314. of wHint: handleNote(HintsToStr, hintMin, c.config.notes)
  315. of wWarning: handleNote(WarningsToStr, warnMin, c.config.notes)
  316. of wWarningAsError: handleNote(WarningsToStr, warnMin, c.config.warningAsErrors)
  317. else: invalidPragma(c, n)
  318. else: invalidPragma(c, n)
  319. proc pragmaToOptions(w: TSpecialWord): TOptions {.inline.} =
  320. case w
  321. of wChecks: ChecksOptions
  322. of wObjChecks: {optObjCheck}
  323. of wFieldChecks: {optFieldCheck}
  324. of wRangeChecks: {optRangeCheck}
  325. of wBoundChecks: {optBoundsCheck}
  326. of wOverflowChecks: {optOverflowCheck}
  327. of wFloatChecks: {optNaNCheck, optInfCheck}
  328. of wNanChecks: {optNaNCheck}
  329. of wInfChecks: {optInfCheck}
  330. of wStaticBoundchecks: {optStaticBoundsCheck}
  331. of wStyleChecks: {optStyleCheck}
  332. of wAssertions: {optAssert}
  333. of wWarnings: {optWarns}
  334. of wHints: {optHints}
  335. of wLineDir: {optLineDir}
  336. of wStackTrace: {optStackTrace}
  337. of wLineTrace: {optLineTrace}
  338. of wDebugger: {optNone}
  339. of wProfiler: {optProfiler, optMemTracker}
  340. of wMemTracker: {optMemTracker}
  341. of wByRef: {optByRef}
  342. of wImplicitStatic: {optImplicitStatic}
  343. of wPatterns, wTrMacros: {optTrMacros}
  344. of wSinkInference: {optSinkInference}
  345. else: {}
  346. proc processExperimental(c: PContext; n: PNode) =
  347. if n.kind notin nkPragmaCallKinds or n.len != 2:
  348. c.features.incl oldExperimentalFeatures
  349. else:
  350. n[1] = c.semConstExpr(c, n[1])
  351. case n[1].kind
  352. of nkStrLit, nkRStrLit, nkTripleStrLit:
  353. try:
  354. let feature = parseEnum[Feature](n[1].strVal)
  355. c.features.incl feature
  356. if feature == codeReordering:
  357. if not isTopLevel(c):
  358. localError(c.config, n.info,
  359. "Code reordering experimental pragma only valid at toplevel")
  360. c.module.flags.incl sfReorder
  361. except ValueError:
  362. localError(c.config, n[1].info, "unknown experimental feature")
  363. else:
  364. localError(c.config, n.info, errStringLiteralExpected)
  365. proc tryProcessOption(c: PContext, n: PNode, resOptions: var TOptions): bool =
  366. result = true
  367. if n.kind notin nkPragmaCallKinds or n.len != 2: result = false
  368. elif n[0].kind == nkBracketExpr: processNote(c, n)
  369. elif n[0].kind != nkIdent: result = false
  370. else:
  371. let sw = whichKeyword(n[0].ident)
  372. if sw == wExperimental:
  373. processExperimental(c, n)
  374. return true
  375. let opts = pragmaToOptions(sw)
  376. if opts != {}:
  377. onOff(c, n, opts, resOptions)
  378. else:
  379. case sw
  380. of wCallconv: processCallConv(c, n)
  381. of wDynlib: processDynLib(c, n, nil)
  382. of wOptimization:
  383. if n[1].kind != nkIdent:
  384. invalidPragma(c, n)
  385. else:
  386. case n[1].ident.s.normalize
  387. of "speed":
  388. incl(resOptions, optOptimizeSpeed)
  389. excl(resOptions, optOptimizeSize)
  390. of "size":
  391. excl(resOptions, optOptimizeSpeed)
  392. incl(resOptions, optOptimizeSize)
  393. of "none":
  394. excl(resOptions, optOptimizeSpeed)
  395. excl(resOptions, optOptimizeSize)
  396. else: localError(c.config, n.info, "'none', 'speed' or 'size' expected")
  397. else: result = false
  398. proc processOption(c: PContext, n: PNode, resOptions: var TOptions) =
  399. if not tryProcessOption(c, n, resOptions):
  400. # calling conventions (boring...):
  401. localError(c.config, n.info, "option expected")
  402. proc processPush(c: PContext, n: PNode, start: int) =
  403. if n[start-1].kind in nkPragmaCallKinds:
  404. localError(c.config, n.info, "'push' cannot have arguments")
  405. var x = pushOptionEntry(c)
  406. for i in start..<n.len:
  407. if not tryProcessOption(c, n[i], c.config.options):
  408. # simply store it somewhere:
  409. if x.otherPragmas.isNil:
  410. x.otherPragmas = newNodeI(nkPragma, n.info)
  411. x.otherPragmas.add n[i]
  412. #localError(c.config, n.info, errOptionExpected)
  413. # If stacktrace is disabled globally we should not enable it
  414. if optStackTrace notin c.optionStack[0].options:
  415. c.config.options.excl(optStackTrace)
  416. when defined(debugOptions):
  417. echo c.config $ n.info, " PUSH config is now ", c.config.options
  418. proc processPop(c: PContext, n: PNode) =
  419. if c.optionStack.len <= 1:
  420. localError(c.config, n.info, "{.pop.} without a corresponding {.push.}")
  421. else:
  422. popOptionEntry(c)
  423. when defined(debugOptions):
  424. echo c.config $ n.info, " POP config is now ", c.config.options
  425. proc processDefine(c: PContext, n: PNode) =
  426. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  427. defineSymbol(c.config.symbols, n[1].ident.s)
  428. else:
  429. invalidPragma(c, n)
  430. proc processUndef(c: PContext, n: PNode) =
  431. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  432. undefSymbol(c.config.symbols, n[1].ident.s)
  433. else:
  434. invalidPragma(c, n)
  435. proc relativeFile(c: PContext; n: PNode; ext=""): AbsoluteFile =
  436. var s = expectStrLit(c, n)
  437. if ext.len > 0 and splitFile(s).ext == "":
  438. s = addFileExt(s, ext)
  439. result = AbsoluteFile parentDir(toFullPath(c.config, n.info)) / s
  440. if not fileExists(result):
  441. if isAbsolute(s): result = AbsoluteFile s
  442. else:
  443. result = findFile(c.config, s)
  444. if result.isEmpty: result = AbsoluteFile s
  445. proc processCompile(c: PContext, n: PNode) =
  446. proc docompile(c: PContext; it: PNode; src, dest: AbsoluteFile) =
  447. var cf = Cfile(nimname: splitFile(src).name,
  448. cname: src, obj: dest, flags: {CfileFlag.External})
  449. extccomp.addExternalFileToCompile(c.config, cf)
  450. recordPragma(c, it, "compile", src.string, dest.string)
  451. proc getStrLit(c: PContext, n: PNode; i: int): string =
  452. n[i] = c.semConstExpr(c, n[i])
  453. case n[i].kind
  454. of nkStrLit, nkRStrLit, nkTripleStrLit:
  455. shallowCopy(result, n[i].strVal)
  456. else:
  457. localError(c.config, n.info, errStringLiteralExpected)
  458. result = ""
  459. let it = if n.kind in nkPragmaCallKinds and n.len == 2: n[1] else: n
  460. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  461. let s = getStrLit(c, it, 0)
  462. let dest = getStrLit(c, it, 1)
  463. var found = parentDir(toFullPath(c.config, n.info)) / s
  464. for f in os.walkFiles(found):
  465. let obj = completeCfilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
  466. docompile(c, it, AbsoluteFile f, obj)
  467. else:
  468. let s = expectStrLit(c, n)
  469. var found = AbsoluteFile(parentDir(toFullPath(c.config, n.info)) / s)
  470. if not fileExists(found):
  471. if isAbsolute(s): found = AbsoluteFile s
  472. else:
  473. found = findFile(c.config, s)
  474. if found.isEmpty: found = AbsoluteFile s
  475. let obj = toObjFile(c.config, completeCfilePath(c.config, found, false))
  476. docompile(c, it, found, obj)
  477. proc processLink(c: PContext, n: PNode) =
  478. let found = relativeFile(c, n, CC[c.config.cCompiler].objExt)
  479. extccomp.addExternalFileToLink(c.config, found)
  480. recordPragma(c, n, "link", found.string)
  481. proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode =
  482. case n[1].kind
  483. of nkStrLit, nkRStrLit, nkTripleStrLit:
  484. result = newNodeI(if n.kind == nkAsmStmt: nkAsmStmt else: nkArgList, n.info)
  485. var str = n[1].strVal
  486. if str == "":
  487. localError(con.config, n.info, "empty 'asm' statement")
  488. return
  489. # now parse the string literal and substitute symbols:
  490. var a = 0
  491. while true:
  492. var b = strutils.find(str, marker, a)
  493. var sub = if b < 0: substr(str, a) else: substr(str, a, b - 1)
  494. if sub != "": result.add newStrNode(nkStrLit, sub)
  495. if b < 0: break
  496. var c = strutils.find(str, marker, b + 1)
  497. if c < 0: sub = substr(str, b + 1)
  498. else: sub = substr(str, b + 1, c - 1)
  499. if sub != "":
  500. var e = searchInScopes(con, getIdent(con.cache, sub))
  501. if e != nil:
  502. when false:
  503. if e.kind == skStub: loadStub(e)
  504. incl(e.flags, sfUsed)
  505. result.add newSymNode(e)
  506. else:
  507. result.add newStrNode(nkStrLit, sub)
  508. else:
  509. # an empty '``' produces a single '`'
  510. result.add newStrNode(nkStrLit, $marker)
  511. if c < 0: break
  512. a = c + 1
  513. else:
  514. illFormedAstLocal(n, con.config)
  515. result = newNodeI(nkAsmStmt, n.info)
  516. proc pragmaEmit(c: PContext, n: PNode) =
  517. if n.kind notin nkPragmaCallKinds or n.len != 2:
  518. localError(c.config, n.info, errStringLiteralExpected)
  519. else:
  520. let n1 = n[1]
  521. if n1.kind == nkBracket:
  522. var b = newNodeI(nkBracket, n1.info, n1.len)
  523. for i in 0..<n1.len:
  524. b[i] = c.semExpr(c, n1[i])
  525. n[1] = b
  526. else:
  527. n[1] = c.semConstExpr(c, n1)
  528. case n[1].kind
  529. of nkStrLit, nkRStrLit, nkTripleStrLit:
  530. n[1] = semAsmOrEmit(c, n, '`')
  531. else:
  532. localError(c.config, n.info, errStringLiteralExpected)
  533. proc noVal(c: PContext; n: PNode) =
  534. if n.kind in nkPragmaCallKinds and n.len > 1: invalidPragma(c, n)
  535. proc pragmaUnroll(c: PContext, n: PNode) =
  536. if c.p.nestedLoopCounter <= 0:
  537. invalidPragma(c, n)
  538. elif n.kind in nkPragmaCallKinds and n.len == 2:
  539. var unrollFactor = expectIntLit(c, n)
  540. if unrollFactor <% 32:
  541. n[1] = newIntNode(nkIntLit, unrollFactor)
  542. else:
  543. invalidPragma(c, n)
  544. proc pragmaLine(c: PContext, n: PNode) =
  545. if n.kind in nkPragmaCallKinds and n.len == 2:
  546. n[1] = c.semConstExpr(c, n[1])
  547. let a = n[1]
  548. if a.kind in {nkPar, nkTupleConstr}:
  549. # unpack the tuple
  550. var x = a[0]
  551. var y = a[1]
  552. if x.kind == nkExprColonExpr: x = x[1]
  553. if y.kind == nkExprColonExpr: y = y[1]
  554. if x.kind != nkStrLit:
  555. localError(c.config, n.info, errStringLiteralExpected)
  556. elif y.kind != nkIntLit:
  557. localError(c.config, n.info, errIntLiteralExpected)
  558. else:
  559. n.info.fileIndex = fileInfoIdx(c.config, AbsoluteFile(x.strVal))
  560. n.info.line = uint16(y.intVal)
  561. else:
  562. localError(c.config, n.info, "tuple expected")
  563. else:
  564. # sensible default:
  565. n.info = getInfoContext(c.config, -1)
  566. proc processPragma(c: PContext, n: PNode, i: int) =
  567. let it = n[i]
  568. if it.kind notin nkPragmaCallKinds and it.safeLen == 2: invalidPragma(c, n)
  569. elif it.safeLen != 2 or it[0].kind != nkIdent or it[1].kind != nkIdent:
  570. invalidPragma(c, n)
  571. var userPragma = newSym(skTemplate, it[1].ident, nil, it.info, c.config.options)
  572. userPragma.ast = newTreeI(nkPragma, n.info, n.sons[i+1..^1])
  573. strTableAdd(c.userPragmas, userPragma)
  574. proc pragmaRaisesOrTags(c: PContext, n: PNode) =
  575. proc processExc(c: PContext, x: PNode) =
  576. if c.hasUnresolvedArgs(c, x):
  577. x.typ = makeTypeFromExpr(c, x)
  578. else:
  579. var t = skipTypes(c.semTypeNode(c, x, nil), skipPtrs)
  580. if t.kind != tyObject and not t.isMetaType:
  581. localError(c.config, x.info, errGenerated, "invalid type for raises/tags list")
  582. x.typ = t
  583. if n.kind in nkPragmaCallKinds and n.len == 2:
  584. let it = n[1]
  585. if it.kind notin {nkCurly, nkBracket}:
  586. processExc(c, it)
  587. else:
  588. for e in items(it): processExc(c, e)
  589. else:
  590. invalidPragma(c, n)
  591. proc pragmaLockStmt(c: PContext; it: PNode) =
  592. if it.kind notin nkPragmaCallKinds or it.len != 2:
  593. invalidPragma(c, it)
  594. else:
  595. let n = it[1]
  596. if n.kind != nkBracket:
  597. localError(c.config, n.info, errGenerated, "locks pragma takes a list of expressions")
  598. else:
  599. for i in 0..<n.len:
  600. n[i] = c.semExpr(c, n[i])
  601. proc pragmaLocks(c: PContext, it: PNode): TLockLevel =
  602. if it.kind notin nkPragmaCallKinds or it.len != 2:
  603. invalidPragma(c, it)
  604. else:
  605. case it[1].kind
  606. of nkStrLit, nkRStrLit, nkTripleStrLit:
  607. if it[1].strVal == "unknown":
  608. result = UnknownLockLevel
  609. else:
  610. localError(c.config, it[1].info, "invalid string literal for locks pragma (only allowed string is \"unknown\")")
  611. else:
  612. let x = expectIntLit(c, it)
  613. if x < 0 or x > MaxLockLevel:
  614. localError(c.config, it[1].info, "integer must be within 0.." & $MaxLockLevel)
  615. else:
  616. result = TLockLevel(x)
  617. proc typeBorrow(c: PContext; sym: PSym, n: PNode) =
  618. if n.kind in nkPragmaCallKinds and n.len == 2:
  619. let it = n[1]
  620. if it.kind != nkAccQuoted:
  621. localError(c.config, n.info, "a type can only borrow `.` for now")
  622. incl(sym.typ.flags, tfBorrowDot)
  623. proc markCompilerProc(c: PContext; s: PSym) =
  624. # minor hack ahead: FlowVar is the only generic .compilerProc type which
  625. # should not have an external name set:
  626. if s.kind != skType or s.name.s != "FlowVar":
  627. makeExternExport(c, s, "$1", s.info)
  628. incl(s.flags, sfCompilerProc)
  629. incl(s.flags, sfUsed)
  630. registerCompilerProc(c.graph, s)
  631. proc deprecatedStmt(c: PContext; outerPragma: PNode) =
  632. let pragma = outerPragma[1]
  633. if pragma.kind in {nkStrLit..nkTripleStrLit}:
  634. incl(c.module.flags, sfDeprecated)
  635. c.module.constraint = getStrLitNode(c, outerPragma)
  636. return
  637. if pragma.kind != nkBracket:
  638. localError(c.config, pragma.info, "list of key:value pairs expected"); return
  639. for n in pragma:
  640. if n.kind in nkPragmaCallKinds and n.len == 2:
  641. let dest = qualifiedLookUp(c, n[1], {checkUndeclared})
  642. if dest == nil or dest.kind in routineKinds:
  643. localError(c.config, n.info, warnUser, "the .deprecated pragma is unreliable for routines")
  644. let src = considerQuotedIdent(c, n[0])
  645. let alias = newSym(skAlias, src, dest, n[0].info, c.config.options)
  646. incl(alias.flags, sfExported)
  647. if sfCompilerProc in dest.flags: markCompilerProc(c, alias)
  648. addInterfaceDecl(c, alias)
  649. n[1] = newSymNode(dest)
  650. else:
  651. localError(c.config, n.info, "key:value pair expected")
  652. proc pragmaGuard(c: PContext; it: PNode; kind: TSymKind): PSym =
  653. if it.kind notin nkPragmaCallKinds or it.len != 2:
  654. invalidPragma(c, it); return
  655. let n = it[1]
  656. if n.kind == nkSym:
  657. result = n.sym
  658. elif kind == skField:
  659. # First check if the guard is a global variable:
  660. result = qualifiedLookUp(c, n, {})
  661. if result.isNil or result.kind notin {skLet, skVar} or
  662. sfGlobal notin result.flags:
  663. # We return a dummy symbol; later passes over the type will repair it.
  664. # Generic instantiation needs to know about this too. But we're lazy
  665. # and perform the lookup on demand instead.
  666. result = newSym(skUnknown, considerQuotedIdent(c, n), nil, n.info,
  667. c.config.options)
  668. else:
  669. result = qualifiedLookUp(c, n, {checkUndeclared})
  670. proc semCustomPragma(c: PContext, n: PNode): PNode =
  671. var callNode: PNode
  672. if n.kind in {nkIdent, nkSym}:
  673. # pragma -> pragma()
  674. callNode = newTree(nkCall, n)
  675. elif n.kind == nkExprColonExpr:
  676. # pragma: arg -> pragma(arg)
  677. callNode = newTree(nkCall, n[0], n[1])
  678. elif n.kind in nkPragmaCallKinds:
  679. callNode = n
  680. else:
  681. invalidPragma(c, n)
  682. return n
  683. let r = c.semOverloadedCall(c, callNode, n, {skTemplate}, {efNoUndeclared})
  684. if r.isNil or sfCustomPragma notin r[0].sym.flags:
  685. invalidPragma(c, n)
  686. return n
  687. result = r
  688. # Transform the nkCall node back to its original form if possible
  689. if n.kind == nkIdent and r.len == 1:
  690. # pragma() -> pragma
  691. result = result[0]
  692. elif n.kind == nkExprColonExpr and r.len == 2:
  693. # pragma(arg) -> pragma: arg
  694. result.transitionSonsKind(n.kind)
  695. proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
  696. validPragmas: TSpecialWords,
  697. comesFromPush, isStatement: bool): bool =
  698. var it = n[i]
  699. var key = if it.kind in nkPragmaCallKinds and it.len > 1: it[0] else: it
  700. if key.kind == nkBracketExpr:
  701. processNote(c, it)
  702. return
  703. elif key.kind notin nkIdentKinds:
  704. n[i] = semCustomPragma(c, it)
  705. return
  706. let ident = considerQuotedIdent(c, key)
  707. var userPragma = strTableGet(c.userPragmas, ident)
  708. if userPragma != nil:
  709. if {optStyleHint, optStyleError} * c.config.globalOptions != {}:
  710. styleCheckUse(c.config, key.info, userPragma)
  711. # number of pragmas increase/decrease with user pragma expansion
  712. inc c.instCounter
  713. if c.instCounter > 100:
  714. globalError(c.config, it.info, "recursive dependency: " & userPragma.name.s)
  715. pragma(c, sym, userPragma.ast, validPragmas, isStatement)
  716. n.sons[i..i] = userPragma.ast.sons # expand user pragma with its content
  717. i.inc(userPragma.ast.len - 1) # inc by -1 is ok, user pragmas was empty
  718. dec c.instCounter
  719. else:
  720. let k = whichKeyword(ident)
  721. if k in validPragmas:
  722. if {optStyleHint, optStyleError} * c.config.globalOptions != {}:
  723. checkPragmaUse(c.config, key.info, k, ident.s)
  724. case k
  725. of wExportc, wExportCpp:
  726. makeExternExport(c, sym, getOptionalStr(c, it, "$1"), it.info)
  727. if k == wExportCpp:
  728. if c.config.backend != backendCpp:
  729. localError(c.config, it.info, "exportcpp requires `cpp` backend, got " & $c.config.backend)
  730. else:
  731. incl(sym.flags, sfMangleCpp)
  732. incl(sym.flags, sfUsed) # avoid wrong hints
  733. of wImportc:
  734. let name = getOptionalStr(c, it, "$1")
  735. cppDefine(c.config, name)
  736. recordPragma(c, it, "cppdefine", name)
  737. makeExternImport(c, sym, name, it.info)
  738. of wImportCompilerProc:
  739. let name = getOptionalStr(c, it, "$1")
  740. cppDefine(c.config, name)
  741. recordPragma(c, it, "cppdefine", name)
  742. processImportCompilerProc(c, sym, name, it.info)
  743. of wExtern: setExternName(c, sym, expectStrLit(c, it), it.info)
  744. of wDirty:
  745. if sym.kind == skTemplate: incl(sym.flags, sfDirty)
  746. else: invalidPragma(c, it)
  747. of wImportCpp:
  748. processImportCpp(c, sym, getOptionalStr(c, it, "$1"), it.info)
  749. of wImportJs:
  750. if c.config.backend != backendJs:
  751. localError(c.config, it.info, "`importjs` pragma requires the JavaScript target")
  752. let name = getOptionalStr(c, it, "$1")
  753. incl(sym.flags, sfImportc)
  754. incl(sym.flags, sfInfixCall)
  755. if sym.kind in skProcKinds and {'(', '#', '@'} notin name:
  756. localError(c.config, n.info, "`importjs` for routines requires a pattern")
  757. setExternName(c, sym, name, it.info)
  758. of wImportObjC:
  759. processImportObjC(c, sym, getOptionalStr(c, it, "$1"), it.info)
  760. of wSize:
  761. if sym.typ == nil: invalidPragma(c, it)
  762. var size = expectIntLit(c, it)
  763. case size
  764. of 1, 2, 4:
  765. sym.typ.size = size
  766. sym.typ.align = int16 size
  767. of 8:
  768. sym.typ.size = 8
  769. sym.typ.align = floatInt64Align(c.config)
  770. else:
  771. localError(c.config, it.info, "size may only be 1, 2, 4 or 8")
  772. of wAlign:
  773. let alignment = expectIntLit(c, it)
  774. if isPowerOfTwo(alignment) and alignment > 0:
  775. sym.alignment = max(sym.alignment, alignment)
  776. else:
  777. localError(c.config, it.info, "power of two expected")
  778. of wNodecl:
  779. noVal(c, it)
  780. incl(sym.loc.flags, lfNoDecl)
  781. of wPure, wAsmNoStackFrame:
  782. noVal(c, it)
  783. if sym != nil:
  784. if k == wPure and sym.kind in routineKinds: invalidPragma(c, it)
  785. else: incl(sym.flags, sfPure)
  786. of wVolatile:
  787. noVal(c, it)
  788. incl(sym.flags, sfVolatile)
  789. of wCursor:
  790. noVal(c, it)
  791. incl(sym.flags, sfCursor)
  792. of wRegister:
  793. noVal(c, it)
  794. incl(sym.flags, sfRegister)
  795. of wNoalias:
  796. noVal(c, it)
  797. incl(sym.flags, sfNoalias)
  798. of wThreadVar:
  799. noVal(c, it)
  800. incl(sym.flags, {sfThread, sfGlobal})
  801. of wDeadCodeElimUnused: discard # deprecated, dead code elim always on
  802. of wNoForward: pragmaNoForward(c, it)
  803. of wReorder: pragmaNoForward(c, it, flag = sfReorder)
  804. of wMagic: processMagic(c, it, sym)
  805. of wCompileTime:
  806. noVal(c, it)
  807. incl(sym.flags, sfCompileTime)
  808. #incl(sym.loc.flags, lfNoDecl)
  809. of wGlobal:
  810. noVal(c, it)
  811. incl(sym.flags, sfGlobal)
  812. incl(sym.flags, sfPure)
  813. of wMerge:
  814. # only supported for backwards compat, doesn't do anything anymore
  815. noVal(c, it)
  816. of wConstructor:
  817. noVal(c, it)
  818. incl(sym.flags, sfConstructor)
  819. of wHeader:
  820. var lib = getLib(c, libHeader, getStrLitNode(c, it))
  821. addToLib(lib, sym)
  822. incl(sym.flags, sfImportc)
  823. incl(sym.loc.flags, lfHeader)
  824. incl(sym.loc.flags, lfNoDecl)
  825. # implies nodecl, because otherwise header would not make sense
  826. if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
  827. of wNoSideEffect:
  828. noVal(c, it)
  829. if sym != nil:
  830. incl(sym.flags, sfNoSideEffect)
  831. if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
  832. of wSideEffect:
  833. noVal(c, it)
  834. incl(sym.flags, sfSideEffect)
  835. of wNoreturn:
  836. noVal(c, it)
  837. # Disable the 'noreturn' annotation when in the "Quirky Exceptions" mode!
  838. if c.config.exc != excQuirky:
  839. incl(sym.flags, sfNoReturn)
  840. if sym.typ[0] != nil:
  841. localError(c.config, sym.ast[paramsPos][0].info,
  842. ".noreturn with return type not allowed")
  843. of wNoDestroy:
  844. noVal(c, it)
  845. incl(sym.flags, sfGeneratedOp)
  846. of wNosinks:
  847. noVal(c, it)
  848. incl(sym.flags, sfWasForwarded)
  849. of wDynlib:
  850. processDynLib(c, it, sym)
  851. of wCompilerProc, wCore:
  852. noVal(c, it) # compilerproc may not get a string!
  853. cppDefine(c.graph.config, sym.name.s)
  854. recordPragma(c, it, "cppdefine", sym.name.s)
  855. if sfFromGeneric notin sym.flags: markCompilerProc(c, sym)
  856. of wNonReloadable:
  857. sym.flags.incl sfNonReloadable
  858. of wProcVar:
  859. noVal(c, it)
  860. incl(sym.flags, sfProcvar)
  861. of wExplain:
  862. sym.flags.incl sfExplain
  863. of wDeprecated:
  864. if sym != nil and sym.kind in routineKinds + {skType, skVar, skLet}:
  865. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  866. incl(sym.flags, sfDeprecated)
  867. elif sym != nil and sym.kind != skModule:
  868. # We don't support the extra annotation field
  869. if it.kind in nkPragmaCallKinds:
  870. localError(c.config, it.info, "annotation to deprecated not supported here")
  871. incl(sym.flags, sfDeprecated)
  872. # At this point we're quite sure this is a statement and applies to the
  873. # whole module
  874. elif it.kind in nkPragmaCallKinds: deprecatedStmt(c, it)
  875. else: incl(c.module.flags, sfDeprecated)
  876. of wVarargs:
  877. noVal(c, it)
  878. if sym.typ == nil: invalidPragma(c, it)
  879. else: incl(sym.typ.flags, tfVarargs)
  880. of wBorrow:
  881. if sym.kind == skType:
  882. typeBorrow(c, sym, it)
  883. else:
  884. noVal(c, it)
  885. incl(sym.flags, sfBorrow)
  886. of wFinal:
  887. noVal(c, it)
  888. if sym.typ == nil: invalidPragma(c, it)
  889. else: incl(sym.typ.flags, tfFinal)
  890. of wInheritable:
  891. noVal(c, it)
  892. if sym.typ == nil or tfFinal in sym.typ.flags: invalidPragma(c, it)
  893. else: incl(sym.typ.flags, tfInheritable)
  894. of wPackage:
  895. noVal(c, it)
  896. if sym.typ == nil: invalidPragma(c, it)
  897. else: incl(sym.flags, sfForward)
  898. of wAcyclic:
  899. noVal(c, it)
  900. if sym.typ == nil: invalidPragma(c, it)
  901. else: incl(sym.typ.flags, tfAcyclic)
  902. of wShallow:
  903. noVal(c, it)
  904. if sym.typ == nil: invalidPragma(c, it)
  905. else: incl(sym.typ.flags, tfShallow)
  906. of wThread:
  907. noVal(c, it)
  908. incl(sym.flags, sfThread)
  909. incl(sym.flags, sfProcvar)
  910. if sym.typ != nil:
  911. incl(sym.typ.flags, tfThread)
  912. if sym.typ.callConv == ccClosure: sym.typ.callConv = ccNimCall
  913. of wGcSafe:
  914. noVal(c, it)
  915. if sym != nil:
  916. if sym.kind != skType: incl(sym.flags, sfThread)
  917. if sym.typ != nil: incl(sym.typ.flags, tfGcSafe)
  918. else: invalidPragma(c, it)
  919. else:
  920. discard "no checking if used as a code block"
  921. of wPacked:
  922. noVal(c, it)
  923. if sym.typ == nil: invalidPragma(c, it)
  924. else: incl(sym.typ.flags, tfPacked)
  925. of wHint:
  926. let s = expectStrLit(c, it)
  927. recordPragma(c, it, "hint", s)
  928. message(c.config, it.info, hintUser, s)
  929. of wWarning:
  930. let s = expectStrLit(c, it)
  931. recordPragma(c, it, "warning", s)
  932. message(c.config, it.info, warnUser, s)
  933. of wError:
  934. if sym != nil and (sym.isRoutine or sym.kind == skType) and not isStatement:
  935. # This is subtle but correct: the error *statement* is only
  936. # allowed when 'wUsed' is not in validPragmas. Here this is the easiest way to
  937. # distinguish properly between
  938. # ``proc p() {.error}`` and ``proc p() = {.error: "msg".}``
  939. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  940. incl(sym.flags, sfError)
  941. excl(sym.flags, sfForward)
  942. else:
  943. let s = expectStrLit(c, it)
  944. recordPragma(c, it, "error", s)
  945. localError(c.config, it.info, errUser, s)
  946. of wFatal: fatal(c.config, it.info, errUser, expectStrLit(c, it))
  947. of wDefine: processDefine(c, it)
  948. of wUndef: processUndef(c, it)
  949. of wCompile: processCompile(c, it)
  950. of wLink: processLink(c, it)
  951. of wPassl:
  952. let s = expectStrLit(c, it)
  953. extccomp.addLinkOption(c.config, s)
  954. recordPragma(c, it, "passl", s)
  955. of wPassc:
  956. let s = expectStrLit(c, it)
  957. extccomp.addCompileOption(c.config, s)
  958. recordPragma(c, it, "passc", s)
  959. of wLocalPassc:
  960. assert sym != nil and sym.kind == skModule
  961. let s = expectStrLit(c, it)
  962. extccomp.addLocalCompileOption(c.config, s, toFullPathConsiderDirty(c.config, sym.info.fileIndex))
  963. recordPragma(c, it, "localpassl", s)
  964. of wPush:
  965. processPush(c, n, i + 1)
  966. result = true
  967. of wPop: processPop(c, it)
  968. of wPragma:
  969. if not sym.isNil and sym.kind == skTemplate:
  970. sym.flags.incl sfCustomPragma
  971. else:
  972. processPragma(c, n, i)
  973. result = true
  974. of wDiscardable:
  975. noVal(c, it)
  976. if sym != nil: incl(sym.flags, sfDiscardable)
  977. of wNoInit:
  978. noVal(c, it)
  979. if sym != nil: incl(sym.flags, sfNoInit)
  980. of wCodegenDecl: processCodegenDecl(c, it, sym)
  981. of wChecks, wObjChecks, wFieldChecks, wRangeChecks, wBoundChecks,
  982. wOverflowChecks, wNilChecks, wAssertions, wWarnings, wHints,
  983. wLineDir, wOptimization, wStaticBoundchecks, wStyleChecks,
  984. wCallconv, wDebugger, wProfiler,
  985. wFloatChecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
  986. processOption(c, it, c.config.options)
  987. of wStackTrace, wLineTrace:
  988. if sym.kind in {skProc, skMethod, skConverter}:
  989. processOption(c, it, sym.options)
  990. else:
  991. processOption(c, it, c.config.options)
  992. of FirstCallConv..LastCallConv:
  993. assert(sym != nil)
  994. if sym.typ == nil: invalidPragma(c, it)
  995. else:
  996. sym.typ.callConv = wordToCallConv(k)
  997. sym.typ.flags.incl tfExplicitCallConv
  998. of wEmit: pragmaEmit(c, it)
  999. of wUnroll: pragmaUnroll(c, it)
  1000. of wLinearScanEnd, wComputedGoto: noVal(c, it)
  1001. of wEffects:
  1002. # is later processed in effect analysis:
  1003. noVal(c, it)
  1004. of wIncompleteStruct:
  1005. noVal(c, it)
  1006. if sym.typ == nil: invalidPragma(c, it)
  1007. else: incl(sym.typ.flags, tfIncompleteStruct)
  1008. of wCompleteStruct:
  1009. noVal(c, it)
  1010. if sym.typ == nil: invalidPragma(c, it)
  1011. else: incl(sym.typ.flags, tfCompleteStruct)
  1012. of wUnchecked:
  1013. noVal(c, it)
  1014. if sym.typ == nil or sym.typ.kind notin {tyArray, tyUncheckedArray}:
  1015. invalidPragma(c, it)
  1016. else:
  1017. sym.typ.kind = tyUncheckedArray
  1018. of wUnion:
  1019. noVal(c, it)
  1020. if sym.typ == nil: invalidPragma(c, it)
  1021. else: incl(sym.typ.flags, tfUnion)
  1022. of wRequiresInit:
  1023. noVal(c, it)
  1024. if sym.kind == skField:
  1025. sym.flags.incl sfRequiresInit
  1026. elif sym.typ != nil:
  1027. incl(sym.typ.flags, tfNeedsFullInit)
  1028. else:
  1029. invalidPragma(c, it)
  1030. of wByRef:
  1031. noVal(c, it)
  1032. if sym == nil or sym.typ == nil:
  1033. processOption(c, it, c.config.options)
  1034. else:
  1035. incl(sym.typ.flags, tfByRef)
  1036. of wByCopy:
  1037. noVal(c, it)
  1038. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1039. else: incl(sym.typ.flags, tfByCopy)
  1040. of wPartial:
  1041. noVal(c, it)
  1042. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1043. else:
  1044. incl(sym.typ.flags, tfPartial)
  1045. of wInject, wGensym:
  1046. # We check for errors, but do nothing with these pragmas otherwise
  1047. # as they are handled directly in 'evalTemplate'.
  1048. noVal(c, it)
  1049. if sym == nil: invalidPragma(c, it)
  1050. of wLine: pragmaLine(c, it)
  1051. of wRaises, wTags: pragmaRaisesOrTags(c, it)
  1052. of wLocks:
  1053. if sym == nil: pragmaLockStmt(c, it)
  1054. elif sym.typ == nil: invalidPragma(c, it)
  1055. else: sym.typ.lockLevel = pragmaLocks(c, it)
  1056. of wBitsize:
  1057. if sym == nil or sym.kind != skField:
  1058. invalidPragma(c, it)
  1059. else:
  1060. sym.bitsize = expectIntLit(c, it)
  1061. if sym.bitsize <= 0:
  1062. localError(c.config, it.info, "bitsize needs to be positive")
  1063. of wGuard:
  1064. if sym == nil or sym.kind notin {skVar, skLet, skField}:
  1065. invalidPragma(c, it)
  1066. else:
  1067. sym.guard = pragmaGuard(c, it, sym.kind)
  1068. of wGoto:
  1069. if sym == nil or sym.kind notin {skVar, skLet}:
  1070. invalidPragma(c, it)
  1071. else:
  1072. sym.flags.incl sfGoto
  1073. of wExportNims:
  1074. if sym == nil: invalidPragma(c, it)
  1075. else: magicsys.registerNimScriptSymbol(c.graph, sym)
  1076. of wInjectStmt:
  1077. if it.kind notin nkPragmaCallKinds or it.len != 2:
  1078. localError(c.config, it.info, "expression expected")
  1079. else:
  1080. it[1] = c.semExpr(c, it[1])
  1081. of wExperimental:
  1082. if not isTopLevel(c):
  1083. localError(c.config, n.info, "'experimental' pragma only valid as toplevel statement or in a 'push' environment")
  1084. processExperimental(c, it)
  1085. of wThis:
  1086. if it.kind in nkPragmaCallKinds and it.len == 2:
  1087. c.selfName = considerQuotedIdent(c, it[1])
  1088. message(c.config, n.info, warnDeprecated, "the '.this' pragma is deprecated")
  1089. elif it.kind == nkIdent or it.len == 1:
  1090. c.selfName = getIdent(c.cache, "self")
  1091. message(c.config, n.info, warnDeprecated, "the '.this' pragma is deprecated")
  1092. else:
  1093. localError(c.config, it.info, "'this' pragma is allowed to have zero or one arguments")
  1094. of wNoRewrite:
  1095. noVal(c, it)
  1096. of wBase:
  1097. noVal(c, it)
  1098. sym.flags.incl sfBase
  1099. of wIntDefine:
  1100. sym.magic = mIntDefine
  1101. of wStrDefine:
  1102. sym.magic = mStrDefine
  1103. of wBoolDefine:
  1104. sym.magic = mBoolDefine
  1105. of wUsed:
  1106. noVal(c, it)
  1107. if sym == nil: invalidPragma(c, it)
  1108. else: sym.flags.incl sfUsed
  1109. of wLiftLocals: discard
  1110. of wRequires, wInvariant, wAssume, wAssert:
  1111. pragmaProposition(c, it)
  1112. of wEnsures:
  1113. pragmaEnsures(c, it)
  1114. else: invalidPragma(c, it)
  1115. elif comesFromPush and whichKeyword(ident) != wInvalid:
  1116. discard "ignore the .push pragma; it doesn't apply"
  1117. else:
  1118. if sym == nil or (sym.kind in {skVar, skLet, skParam,
  1119. skField, skProc, skFunc, skConverter, skMethod, skType}):
  1120. n[i] = semCustomPragma(c, it)
  1121. elif sym != nil:
  1122. illegalCustomPragma(c, it, sym)
  1123. else:
  1124. invalidPragma(c, it)
  1125. proc overwriteLineInfo(n: PNode; info: TLineInfo) =
  1126. n.info = info
  1127. for i in 0..<n.safeLen:
  1128. overwriteLineInfo(n[i], info)
  1129. proc mergePragmas(n, pragmas: PNode) =
  1130. var pragmas = copyTree(pragmas)
  1131. overwriteLineInfo pragmas, n.info
  1132. if n[pragmasPos].kind == nkEmpty:
  1133. n[pragmasPos] = pragmas
  1134. else:
  1135. for p in pragmas: n[pragmasPos].add p
  1136. proc implicitPragmas*(c: PContext, sym: PSym, n: PNode,
  1137. validPragmas: TSpecialWords) =
  1138. if sym != nil and sym.kind != skModule:
  1139. for it in c.optionStack:
  1140. let o = it.otherPragmas
  1141. if not o.isNil and sfFromGeneric notin sym.flags: # see issue #12985
  1142. pushInfoContext(c.config, n.info)
  1143. var i = 0
  1144. while i < o.len:
  1145. if singlePragma(c, sym, o, i, validPragmas, true, false):
  1146. internalError(c.config, n.info, "implicitPragmas")
  1147. inc i
  1148. popInfoContext(c.config)
  1149. if sym.kind in routineKinds and sym.ast != nil: mergePragmas(sym.ast, o)
  1150. if lfExportLib in sym.loc.flags and sfExportc notin sym.flags:
  1151. localError(c.config, n.info, ".dynlib requires .exportc")
  1152. var lib = c.optionStack[^1].dynlib
  1153. if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and
  1154. sfImportc in sym.flags and lib != nil:
  1155. incl(sym.loc.flags, lfDynamicLib)
  1156. addToLib(lib, sym)
  1157. if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
  1158. proc hasPragma*(n: PNode, pragma: TSpecialWord): bool =
  1159. if n == nil: return false
  1160. for p in n:
  1161. var key = if p.kind in nkPragmaCallKinds and p.len > 1: p[0] else: p
  1162. if key.kind == nkIdent and whichKeyword(key.ident) == pragma:
  1163. return true
  1164. return false
  1165. proc pragmaRec(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1166. isStatement: bool) =
  1167. if n == nil: return
  1168. var i = 0
  1169. while i < n.len:
  1170. if singlePragma(c, sym, n, i, validPragmas, false, isStatement): break
  1171. inc i
  1172. proc pragma(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1173. isStatement: bool) =
  1174. if n == nil: return
  1175. pragmaRec(c, sym, n, validPragmas, isStatement)
  1176. implicitPragmas(c, sym, n, validPragmas)