pragmas.nim 47 KB

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