parampatterns.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the pattern matching features for term rewriting
  10. ## macro support.
  11. import strutils, ast, types, msgs, idents, renderer, wordrecg, trees,
  12. options
  13. # we precompile the pattern here for efficiency into some internal
  14. # stack based VM :-) Why? Because it's fun; I did no benchmarks to see if that
  15. # actually improves performance.
  16. type
  17. TAliasRequest* = enum # first byte of the bytecode determines alias checking
  18. aqNone = 1, # no alias analysis requested
  19. aqShouldAlias, # with some other param
  20. aqNoAlias # request noalias
  21. TOpcode = enum
  22. ppEof = 1, # end of compiled pattern
  23. ppOr, # we could short-cut the evaluation for 'and' and 'or',
  24. ppAnd, # but currently we don't
  25. ppNot,
  26. ppSym,
  27. ppAtom,
  28. ppLit,
  29. ppIdent,
  30. ppCall,
  31. ppSymKind,
  32. ppNodeKind,
  33. ppLValue,
  34. ppLocal,
  35. ppSideEffect,
  36. ppNoSideEffect
  37. TPatternCode = string
  38. const
  39. MaxStackSize* = 64 ## max required stack size by the VM
  40. proc patternError(n: PNode; conf: ConfigRef) =
  41. localError(conf, n.info, "illformed AST: " & renderTree(n, {renderNoComments}))
  42. proc add(code: var TPatternCode, op: TOpcode) {.inline.} =
  43. code.add chr(ord(op))
  44. proc whichAlias*(p: PSym): TAliasRequest =
  45. if p.constraint != nil:
  46. result = TAliasRequest(p.constraint.strVal[0].ord)
  47. else:
  48. result = aqNone
  49. proc compileConstraints(p: PNode, result: var TPatternCode; conf: ConfigRef) =
  50. case p.kind
  51. of nkCallKinds:
  52. if p[0].kind != nkIdent:
  53. patternError(p[0], conf)
  54. return
  55. let op = p[0].ident
  56. if p.len == 3:
  57. if op.s == "|" or op.id == ord(wOr):
  58. compileConstraints(p[1], result, conf)
  59. compileConstraints(p[2], result, conf)
  60. result.add(ppOr)
  61. elif op.s == "&" or op.id == ord(wAnd):
  62. compileConstraints(p[1], result, conf)
  63. compileConstraints(p[2], result, conf)
  64. result.add(ppAnd)
  65. else:
  66. patternError(p, conf)
  67. elif p.len == 2 and (op.s == "~" or op.id == ord(wNot)):
  68. compileConstraints(p[1], result, conf)
  69. result.add(ppNot)
  70. else:
  71. patternError(p, conf)
  72. of nkAccQuoted, nkPar:
  73. if p.len == 1:
  74. compileConstraints(p[0], result, conf)
  75. else:
  76. patternError(p, conf)
  77. of nkIdent:
  78. let spec = p.ident.s.normalize
  79. case spec
  80. of "atom": result.add(ppAtom)
  81. of "lit": result.add(ppLit)
  82. of "sym": result.add(ppSym)
  83. of "ident": result.add(ppIdent)
  84. of "call": result.add(ppCall)
  85. of "alias": result[0] = chr(aqShouldAlias.ord)
  86. of "noalias": result[0] = chr(aqNoAlias.ord)
  87. of "lvalue": result.add(ppLValue)
  88. of "local": result.add(ppLocal)
  89. of "sideeffect": result.add(ppSideEffect)
  90. of "nosideeffect": result.add(ppNoSideEffect)
  91. else:
  92. # check all symkinds:
  93. internalAssert conf, int(high(TSymKind)) < 255
  94. for i in TSymKind:
  95. if cmpIgnoreStyle(i.toHumanStr, spec) == 0:
  96. result.add(ppSymKind)
  97. result.add(chr(i.ord))
  98. return
  99. # check all nodekinds:
  100. internalAssert conf, int(high(TNodeKind)) < 255
  101. for i in TNodeKind:
  102. if cmpIgnoreStyle($i, spec) == 0:
  103. result.add(ppNodeKind)
  104. result.add(chr(i.ord))
  105. return
  106. patternError(p, conf)
  107. else:
  108. patternError(p, conf)
  109. proc semNodeKindConstraints*(n: PNode; conf: ConfigRef; start: Natural): PNode =
  110. ## does semantic checking for a node kind pattern and compiles it into an
  111. ## efficient internal format.
  112. result = newNodeI(nkStrLit, n.info)
  113. result.strVal = newStringOfCap(10)
  114. result.strVal.add(chr(aqNone.ord))
  115. if n.len >= 2:
  116. for i in start..<n.len:
  117. compileConstraints(n[i], result.strVal, conf)
  118. if result.strVal.len > MaxStackSize-1:
  119. internalError(conf, n.info, "parameter pattern too complex")
  120. else:
  121. patternError(n, conf)
  122. result.strVal.add(ppEof)
  123. type
  124. TSideEffectAnalysis* = enum
  125. seUnknown, seSideEffect, seNoSideEffect
  126. proc checkForSideEffects*(n: PNode): TSideEffectAnalysis =
  127. case n.kind
  128. of nkCallKinds:
  129. # only calls can produce side effects:
  130. let op = n[0]
  131. if op.kind == nkSym and isRoutine(op.sym):
  132. let s = op.sym
  133. if sfSideEffect in s.flags:
  134. return seSideEffect
  135. elif tfNoSideEffect in op.typ.flags:
  136. result = seNoSideEffect
  137. else:
  138. # assume side effect:
  139. result = seSideEffect
  140. elif tfNoSideEffect in op.typ.flags:
  141. # indirect call without side effects:
  142. result = seNoSideEffect
  143. else:
  144. # indirect call: assume side effect:
  145. return seSideEffect
  146. # we need to check n[0] too: (FwithSideEffectButReturnsProcWithout)(args)
  147. for i in 0..<n.len:
  148. let ret = checkForSideEffects(n[i])
  149. if ret == seSideEffect: return ret
  150. elif ret == seUnknown and result == seNoSideEffect:
  151. result = seUnknown
  152. of nkNone..nkNilLit:
  153. # an atom cannot produce a side effect:
  154. result = seNoSideEffect
  155. else:
  156. # assume no side effect:
  157. result = seNoSideEffect
  158. for i in 0..<n.len:
  159. let ret = checkForSideEffects(n[i])
  160. if ret == seSideEffect: return ret
  161. elif ret == seUnknown and result == seNoSideEffect:
  162. result = seUnknown
  163. type
  164. TAssignableResult* = enum
  165. arNone, # no l-value and no discriminant
  166. arLValue, # is an l-value
  167. arLocalLValue, # is an l-value, but local var; must not escape
  168. # its stack frame!
  169. arDiscriminant, # is a discriminant
  170. arAddressableConst, # an addressable const
  171. arLentValue, # lent value
  172. arStrange # it is a strange beast like 'typedesc[var T]'
  173. proc exprRoot*(n: PNode; allowCalls = true): PSym =
  174. var it = n
  175. while true:
  176. case it.kind
  177. of nkSym: return it.sym
  178. of nkHiddenDeref, nkDerefExpr:
  179. if it[0].typ.skipTypes(abstractInst).kind in {tyPtr, tyRef}:
  180. # 'ptr' is unsafe anyway and 'ref' is always on the heap,
  181. # so allow these derefs:
  182. break
  183. else:
  184. it = it[0]
  185. of nkDotExpr, nkBracketExpr, nkHiddenAddr,
  186. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  187. it = it[0]
  188. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  189. it = it[1]
  190. of nkStmtList, nkStmtListExpr:
  191. if it.len > 0 and it.typ != nil: it = it.lastSon
  192. else: break
  193. of nkCallKinds:
  194. if allowCalls and it.typ != nil and it.typ.kind in {tyVar, tyLent} and it.len > 1:
  195. # See RFC #7373, calls returning 'var T' are assumed to
  196. # return a view into the first argument (if there is one):
  197. it = it[1]
  198. else:
  199. break
  200. else:
  201. break
  202. proc isAssignable*(owner: PSym, n: PNode): TAssignableResult =
  203. ## 'owner' can be nil!
  204. result = arNone
  205. case n.kind
  206. of nkEmpty:
  207. if n.typ != nil and n.typ.kind in {tyVar}:
  208. result = arLValue
  209. of nkSym:
  210. const kinds = {skVar, skResult, skTemp, skParam, skLet, skForVar}
  211. if n.sym.kind == skParam:
  212. result = if n.sym.typ.kind in {tyVar, tySink}: arLValue else: arAddressableConst
  213. elif n.sym.kind == skConst and dontInlineConstant(n, n.sym.astdef):
  214. result = arAddressableConst
  215. elif n.sym.kind in kinds:
  216. if n.sym.kind in {skParam, skLet, skForVar}:
  217. result = arAddressableConst
  218. else:
  219. if owner != nil and owner == n.sym.owner and
  220. sfGlobal notin n.sym.flags:
  221. result = arLocalLValue
  222. else:
  223. result = arLValue
  224. elif n.sym.kind == skType:
  225. let t = n.sym.typ.skipTypes({tyTypeDesc})
  226. if t.kind in {tyVar}: result = arStrange
  227. of nkDotExpr:
  228. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  229. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  230. result = arLValue
  231. elif t.kind == tyLent:
  232. result = arAddressableConst
  233. else:
  234. result = isAssignable(owner, n[0])
  235. if result != arNone and n[1].kind == nkSym and
  236. sfDiscriminant in n[1].sym.flags:
  237. result = arDiscriminant
  238. of nkBracketExpr:
  239. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  240. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  241. result = arLValue
  242. elif t.kind == tyLent:
  243. result = arAddressableConst
  244. else:
  245. result = isAssignable(owner, n[0])
  246. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  247. # Object and tuple conversions are still addressable, so we skip them
  248. # XXX why is 'tyOpenArray' allowed here?
  249. if skipTypes(n.typ, abstractPtrs-{tyTypeDesc}).kind in
  250. {tyOpenArray, tyTuple, tyObject}:
  251. result = isAssignable(owner, n[1])
  252. elif compareTypes(n.typ, n[1].typ, dcEqIgnoreDistinct):
  253. # types that are equal modulo distinction preserve l-value:
  254. result = isAssignable(owner, n[1])
  255. of nkHiddenDeref:
  256. let n0 = n[0]
  257. if n0.typ.kind == tyLent:
  258. if n0.kind == nkSym and n0.sym.kind == skResult:
  259. result = arLValue
  260. else:
  261. result = arLentValue
  262. else:
  263. result = arLValue
  264. of nkDerefExpr, nkHiddenAddr:
  265. result = arLValue
  266. of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  267. result = isAssignable(owner, n[0])
  268. of nkCallKinds:
  269. # builtin slice keeps lvalue-ness:
  270. if getMagic(n) in {mArrGet, mSlice}:
  271. result = isAssignable(owner, n[1])
  272. elif n.typ != nil:
  273. case n.typ.kind
  274. of tyVar: result = arLValue
  275. of tyLent: result = arLentValue
  276. else: discard
  277. of nkStmtList, nkStmtListExpr:
  278. if n.typ != nil:
  279. result = isAssignable(owner, n.lastSon)
  280. of nkVarTy:
  281. # XXX: The fact that this is here is a bit of a hack.
  282. # The goal is to allow the use of checks such as "foo(var T)"
  283. # within concepts. Semantically, it's not correct to say that
  284. # nkVarTy denotes an lvalue, but the example above is the only
  285. # possible code which will get us here
  286. result = arLValue
  287. else:
  288. discard
  289. proc isLValue*(n: PNode): bool =
  290. isAssignable(nil, n) in {arLValue, arLocalLValue, arStrange}
  291. proc matchNodeKinds*(p, n: PNode): bool =
  292. # matches the parameter constraint 'p' against the concrete AST 'n'.
  293. # Efficiency matters here.
  294. var stack {.noinit.}: array[0..MaxStackSize, bool]
  295. # empty patterns are true:
  296. stack[0] = true
  297. var sp = 1
  298. template push(x: bool) =
  299. stack[sp] = x
  300. inc sp
  301. let code = p.strVal
  302. var pc = 1
  303. while true:
  304. case TOpcode(code[pc])
  305. of ppEof: break
  306. of ppOr:
  307. stack[sp-2] = stack[sp-1] or stack[sp-2]
  308. dec sp
  309. of ppAnd:
  310. stack[sp-2] = stack[sp-1] and stack[sp-2]
  311. dec sp
  312. of ppNot: stack[sp-1] = not stack[sp-1]
  313. of ppSym: push n.kind == nkSym
  314. of ppAtom: push isAtom(n)
  315. of ppLit: push n.kind in {nkCharLit..nkNilLit}
  316. of ppIdent: push n.kind == nkIdent
  317. of ppCall: push n.kind in nkCallKinds
  318. of ppSymKind:
  319. let kind = TSymKind(code[pc+1])
  320. push n.kind == nkSym and n.sym.kind == kind
  321. inc pc
  322. of ppNodeKind:
  323. let kind = TNodeKind(code[pc+1])
  324. push n.kind == kind
  325. inc pc
  326. of ppLValue: push isAssignable(nil, n) in {arLValue, arLocalLValue}
  327. of ppLocal: push isAssignable(nil, n) == arLocalLValue
  328. of ppSideEffect: push checkForSideEffects(n) == seSideEffect
  329. of ppNoSideEffect: push checkForSideEffects(n) != seSideEffect
  330. inc pc
  331. result = stack[sp-1]