pragmas.nim 43 KB

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