1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 '''
31 Encapsulate global (per thread) state.
32
33 This is for state that can affect the current parse. It's probably simplest to
34 explain an example of what it can be used for. Memoization records results
35 for a particular state to avoid repeating matches needlessly. The state used
36 to identify when "the same thing is happening" is based on:
37 - the matcher being called
38 - the stream passed to the matcher
39 - this state
40
41 So a good shorthand for deciding whether or not this state should be used is
42 to ask whether the state will affect whether or not memoisation will work
43 correctly.
44
45 For example, with offside parsing, the current indentation level should be
46 stored here, because a (matcher, stream) combination that has previously failed
47 may work correctly when it changes.
48 '''
49
50 from threading import local
51
52 from lepl.support.lib import singleton
56 '''
57 A thread local map from key (typically calling class) to value. The hash
58 attribute is updated on each mutation and cached for rapid access.
59 '''
60
62 '''
63 Do not call directly - use the singleton.
64 '''
65 super(State, self).__init__()
66 self.__map = {}
67 self.hash = self.__hash()
68
69 @classmethod
71 '''
72 Get a singleton instance.
73 '''
74 return singleton(cls)
75
77 '''
78 Calculate the hash for the current dict.
79 '''
80 value = 0
81 for key in self.__map:
82 value ^= hash(key) ^ hash(self.__map[key])
83 return value
84
86 return self.__map[key]
87
88 - def get(self, key, default=None):
89 '''
90 As for dict (lookup with default).
91 '''
92 return self.__map.get(key, default)
93
95 self.__map[key] = value
96 self.hash = self.__hash()
97
99 del self.__map[key]
100 self.hash = self.__hash()
101
104