1# -*- coding: utf8 -*-
2"""
3.. module:: lesscpy.plib.node
4    :synopsis: Base Node
5
6    Copyright (c)
7    See LICENSE for details.
8.. moduleauthor:: Johann T. Mariusson <jtm@robot.is>
9"""
10from lesscpy.lessc import utility
11
12
13class Node(object):
14    def __init__(self, tokens, lineno=0):
15        """ Base Node
16        args:
17            tokens (list): tokenlist
18            lineno (int): Line number of node
19        """
20        self.tokens = tokens
21        self.lineno = lineno
22        self.parsed = False
23
24    def parse(self, scope):
25        """ Base parse function
26        args:
27            scope (Scope): Current scope
28        returns:
29            self
30        """
31        return self
32
33    def process(self, tokens, scope):
34        """ Process tokenslist, flattening and parsing it
35        args:
36            tokens (list): tokenlist
37            scope (Scope): Current scope
38        returns:
39            list
40        """
41        while True:
42            tokens = list(utility.flatten(tokens))
43            done = True
44            if any(t for t in tokens if hasattr(t, 'parse')):
45                tokens = [
46                    t.parse(scope) if hasattr(t, 'parse') else t
47                    for t in tokens
48                ]
49                done = False
50            if any(
51                    t for t in tokens
52                    if (utility.is_variable(t)) or str(type(t)) ==
53                    "<class 'lesscpy.plib.variable.Variable'>"):
54                tokens = self.replace_variables(tokens, scope)
55                done = False
56            if done:
57                break
58        return tokens
59
60    def replace_variables(self, tokens, scope):
61        """ Replace variables in tokenlist
62        args:
63            tokens (list): tokenlist
64            scope (Scope): Current scope
65        returns:
66            list
67        """
68        list = []
69        for t in tokens:
70            if utility.is_variable(t):
71                list.append(scope.swap(t))
72            elif str(type(t)) == "<class 'lesscpy.plib.variable.Variable'>":
73                list.append(scope.swap(t.name))
74            else:
75                list.append(t)
76        return list
77
78    def fmt(self, fills):
79        """ Format node
80        args:
81            fills (dict): replacements
82        returns:
83            str
84        """
85        raise ValueError('No defined format')
86