# Path: joy/utils/stack.py
# def list_to_stack(el, stack=()):
#   '''Convert a list (or other sequence) to a stack.
# 
#   [1, 2, 3] -> (1, (2, (3, ())))
# 
#   '''
#   for item in reversed(el):
#     stack = item, stack
#   return stack


from re import Scanner
from .utils.stack import list_to_stack
  tokens, rest = _scanner.scan(text)
  if rest:
    raise ParseError(
      'Scan failed at position %i, %r'
      % (len(text) - len(rest), rest[:10])
      )
  return tokens


def _parse(tokens):
  '''
  Return a stack/list expression of the tokens.
  '''
  frame = []
  stack = []
  for tok in tokens:
    if tok == '[':
      stack.append(frame)
      frame = []
      stack[-1].append(frame)
    elif tok == ']':
      try:
        frame = stack.pop()
      except IndexError:
        raise ParseError('One or more extra closing brackets.')
      frame[-1] = list_to_stack(frame[-1])
    else:
      frame.append(tok)
  if stack:
    raise ParseError('One or more unclosed brackets.')

# Path: joy/utils/stack.py
# def list_to_stack(el, stack=()):
#   '''Convert a list (or other sequence) to a stack.
# 
#   [1, 2, 3] -> (1, (2, (3, ())))
# 
#   '''
#   for item in reversed(el):
#     stack = item, stack
#   return stack


# Path: joy/parser.py
from re import Scanner
from .utils.stack import list_to_stack

  tokens, rest = _scanner.scan(text)
  if rest:
    raise ParseError(
      'Scan failed at position %i, %r'
      % (len(text) - len(rest), rest[:10])
      )
  return tokens


def _parse(tokens):
  '''
  Return a stack/list expression of the tokens.
  '''
  frame = []
  stack = []
  for tok in tokens:
    if tok == '[':
      stack.append(frame)
      frame = []
      stack[-1].append(frame)
    elif tok == ']':
      try:
        frame = stack.pop()
      except IndexError:
        raise ParseError('One or more extra closing brackets.')
      frame[-1] = list_to_stack(frame[-1])
    else:
      frame.append(tok)
  if stack:
    raise ParseError('One or more unclosed brackets.')

  return list_to_stack(frame)