parampatterns.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. # assume no side effect:
  136. result = seNoSideEffect
  137. elif tfNoSideEffect in op.typ.flags:
  138. # indirect call without side effects:
  139. result = seNoSideEffect
  140. else:
  141. # indirect call: assume side effect:
  142. return seSideEffect
  143. # we need to check n[0] too: (FwithSideEffectButReturnsProcWithout)(args)
  144. for i in 0..<n.len:
  145. let ret = checkForSideEffects(n[i])
  146. if ret == seSideEffect: return ret
  147. elif ret == seUnknown and result == seNoSideEffect:
  148. result = seUnknown
  149. of nkNone..nkNilLit:
  150. # an atom cannot produce a side effect:
  151. result = seNoSideEffect
  152. else:
  153. # assume no side effect:
  154. result = seNoSideEffect
  155. for i in 0..<n.len:
  156. let ret = checkForSideEffects(n[i])
  157. if ret == seSideEffect: return ret
  158. elif ret == seUnknown and result == seNoSideEffect:
  159. result = seUnknown
  160. type
  161. TAssignableResult* = enum
  162. arNone, # no l-value and no discriminant
  163. arLValue, # is an l-value
  164. arLocalLValue, # is an l-value, but local var; must not escape
  165. # its stack frame!
  166. arDiscriminant, # is a discriminant
  167. arLentValue, # lent value
  168. arStrange # it is a strange beast like 'typedesc[var T]'
  169. proc exprRoot*(n: PNode): PSym =
  170. var it = n
  171. while true:
  172. case it.kind
  173. of nkSym: return it.sym
  174. of nkHiddenDeref, nkDerefExpr:
  175. if it[0].typ.skipTypes(abstractInst).kind in {tyPtr, tyRef}:
  176. # 'ptr' is unsafe anyway and 'ref' is always on the heap,
  177. # so allow these derefs:
  178. break
  179. else:
  180. it = it[0]
  181. of nkDotExpr, nkBracketExpr, nkHiddenAddr,
  182. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  183. it = it[0]
  184. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  185. it = it[1]
  186. of nkStmtList, nkStmtListExpr:
  187. if it.len > 0 and it.typ != nil: it = it.lastSon
  188. else: break
  189. of nkCallKinds:
  190. if it.typ != nil and it.typ.kind in {tyVar, tyLent} and it.len > 1:
  191. # See RFC #7373, calls returning 'var T' are assumed to
  192. # return a view into the first argument (if there is one):
  193. it = it[1]
  194. else:
  195. break
  196. else:
  197. break
  198. proc isAssignable*(owner: PSym, n: PNode; isUnsafeAddr=false): TAssignableResult =
  199. ## 'owner' can be nil!
  200. result = arNone
  201. case n.kind
  202. of nkEmpty:
  203. if n.typ != nil and n.typ.kind in {tyVar}:
  204. result = arLValue
  205. of nkSym:
  206. let kinds = if isUnsafeAddr: {skVar, skResult, skTemp, skParam, skLet, skForVar}
  207. else: {skVar, skResult, skTemp}
  208. if n.sym.kind == skParam and n.sym.typ.kind in {tyVar, tySink}:
  209. result = arLValue
  210. elif isUnsafeAddr and n.sym.kind == skParam:
  211. result = arLValue
  212. elif isUnsafeAddr and n.sym.kind == skConst and dontInlineConstant(n, n.sym.ast):
  213. result = arLValue
  214. elif n.sym.kind in kinds:
  215. if owner != nil and owner == n.sym.owner and
  216. sfGlobal notin n.sym.flags:
  217. result = arLocalLValue
  218. else:
  219. result = arLValue
  220. elif n.sym.kind == skType:
  221. let t = n.sym.typ.skipTypes({tyTypeDesc})
  222. if t.kind in {tyVar}: result = arStrange
  223. of nkDotExpr:
  224. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  225. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  226. result = arLValue
  227. elif isUnsafeAddr and t.kind == tyLent:
  228. result = arLValue
  229. else:
  230. result = isAssignable(owner, n[0], isUnsafeAddr)
  231. if result != arNone and n[1].kind == nkSym and
  232. sfDiscriminant in n[1].sym.flags:
  233. result = arDiscriminant
  234. of nkBracketExpr:
  235. let t = skipTypes(n[0].typ, abstractInst-{tyTypeDesc})
  236. if t.kind in {tyVar, tySink, tyPtr, tyRef}:
  237. result = arLValue
  238. elif isUnsafeAddr and t.kind == tyLent:
  239. result = arLValue
  240. else:
  241. result = isAssignable(owner, n[0], isUnsafeAddr)
  242. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  243. # Object and tuple conversions are still addressable, so we skip them
  244. # XXX why is 'tyOpenArray' allowed here?
  245. if skipTypes(n.typ, abstractPtrs-{tyTypeDesc}).kind in
  246. {tyOpenArray, tyTuple, tyObject}:
  247. result = isAssignable(owner, n[1], isUnsafeAddr)
  248. elif compareTypes(n.typ, n[1].typ, dcEqIgnoreDistinct):
  249. # types that are equal modulo distinction preserve l-value:
  250. result = isAssignable(owner, n[1], isUnsafeAddr)
  251. of nkHiddenDeref:
  252. let n0 = n[0]
  253. if n0.typ.kind == tyLent:
  254. if isUnsafeAddr or (n0.kind == nkSym and n0.sym.kind == skResult):
  255. result = arLValue
  256. else:
  257. result = arLentValue
  258. else:
  259. result = arLValue
  260. of nkDerefExpr, nkHiddenAddr:
  261. result = arLValue
  262. of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  263. result = isAssignable(owner, n[0], isUnsafeAddr)
  264. of nkCallKinds:
  265. # builtin slice keeps lvalue-ness:
  266. if getMagic(n) in {mArrGet, mSlice}:
  267. result = isAssignable(owner, n[1], isUnsafeAddr)
  268. elif n.typ != nil and n.typ.kind in {tyVar}:
  269. result = arLValue
  270. elif isUnsafeAddr and n.typ != nil and n.typ.kind == tyLent:
  271. result = arLValue
  272. of nkStmtList, nkStmtListExpr:
  273. if n.typ != nil:
  274. result = isAssignable(owner, n.lastSon, isUnsafeAddr)
  275. of nkVarTy:
  276. # XXX: The fact that this is here is a bit of a hack.
  277. # The goal is to allow the use of checks such as "foo(var T)"
  278. # within concepts. Semantically, it's not correct to say that
  279. # nkVarTy denotes an lvalue, but the example above is the only
  280. # possible code which will get us here
  281. result = arLValue
  282. else:
  283. discard
  284. proc isLValue*(n: PNode): bool =
  285. isAssignable(nil, n) in {arLValue, arLocalLValue, arStrange}
  286. proc matchNodeKinds*(p, n: PNode): bool =
  287. # matches the parameter constraint 'p' against the concrete AST 'n'.
  288. # Efficiency matters here.
  289. var stack {.noinit.}: array[0..MaxStackSize, bool]
  290. # empty patterns are true:
  291. stack[0] = true
  292. var sp = 1
  293. template push(x: bool) =
  294. stack[sp] = x
  295. inc sp
  296. let code = p.strVal
  297. var pc = 1
  298. while true:
  299. case TOpcode(code[pc])
  300. of ppEof: break
  301. of ppOr:
  302. stack[sp-2] = stack[sp-1] or stack[sp-2]
  303. dec sp
  304. of ppAnd:
  305. stack[sp-2] = stack[sp-1] and stack[sp-2]
  306. dec sp
  307. of ppNot: stack[sp-1] = not stack[sp-1]
  308. of ppSym: push n.kind == nkSym
  309. of ppAtom: push isAtom(n)
  310. of ppLit: push n.kind in {nkCharLit..nkNilLit}
  311. of ppIdent: push n.kind == nkIdent
  312. of ppCall: push n.kind in nkCallKinds
  313. of ppSymKind:
  314. let kind = TSymKind(code[pc+1])
  315. push n.kind == nkSym and n.sym.kind == kind
  316. inc pc
  317. of ppNodeKind:
  318. let kind = TNodeKind(code[pc+1])
  319. push n.kind == kind
  320. inc pc
  321. of ppLValue: push isAssignable(nil, n) in {arLValue, arLocalLValue}
  322. of ppLocal: push isAssignable(nil, n) == arLocalLValue
  323. of ppSideEffect: push checkForSideEffects(n) == seSideEffect
  324. of ppNoSideEffect: push checkForSideEffects(n) != seSideEffect
  325. inc pc
  326. result = stack[sp-1]