# XPath "function" elements that transform their subpaths

import util
import xpath

##### Functions

funcs = {}

def process(path):
    if path == []: return path
    
    # Process subpaths
    path[1:] = process(path[1:])
    branches = path[0].other_branches
    for i, branch in enumerate(branches): branches[i] = process(branch)
    
    name = path[0].name
    if name.startswith('_') and name in funcs:
        return funcs[name](path.pop(0).attrs, path)
    else: return path

#### XPath functions

# Function names must start with _ to avoid collisions with real tags
# Functions take arguments (args, path)

def _forEach(args, path):
    '''Replaces '_val' in `do` with each item in the `in` list'''
    in_, do = [a[0] for a in args]
    assert in_.name == 'in'
    assert do.name == 'do'
    in_ = in_.attrs
    do = do.value
    
    for_path = []
    for with_, in in_: for_path += xpath.parse(do.replace('_val', with_.name))
    return for_path + path
funcs['_forEach'] = _forEach
