Guest User

Constrain Macro

a guest
Dec 22nd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.60 KB | None | 0 0
  1. proc parseVars(node: NimNode): (seq[string], NimNode) =
  2.     ## Traverses the AST to find any identifiers
  3.     ## and either replaces them with a constraint
  4.     ## vararg access, or treats them as a Nim
  5.     ## identifier if prefixed `u` or not alphanumeric.
  6.     ##
  7.     ## Return: The Variable names in AST First Occurence Order
  8.     var tree = node.copy
  9.     var queue = initHeapQueue[NimNode]()
  10.     queue.push(tree)
  11.     var variables = newTable[string, int]()
  12.  
  13.     while queue.len > 0:
  14.         var current = queue.pop
  15.  
  16.         for i in 0..<current.len:
  17.             var child = current[i]
  18.             ## Find any Identifiers on the current Node
  19.             if child.kind == nnkIdent:
  20.                 if child.strVal[0] == 'u':
  21.                     ## If tagged as a literal, keep it, but drop tag
  22.                     current[i] = ident(child.strVal.substr(1))
  23.                 elif child.strVal.isAlphaNumeric:
  24.                     ## Any untagged identifier is assumed a Variable
  25.                     ## Track its order in the AST
  26.                     if not variables.hasKeyOrPut(child.strVal, variables.len):
  27.                         result[0].add(child.strVal)
  28.  
  29.                     ## Then replace the Identifier with an Array Access
  30.                     ## corresponding to its location in the constraint
  31.                     current[i] = newNimNode(nnkBracketExpr).add(
  32.                         ident("x"),
  33.                         newIntLitNode(variables[child.strVal])
  34.                     )
  35.                 echo tree.treeRepr
  36.             else:
  37.                 queue.push(child)
  38.    
  39.     return (result[0], tree)
Advertisement
Add Comment
Please, Sign In to add comment