about summary refs log tree commit diff stats
path: root/045closure_name.cc
blob: 6b2defd3b66faf05f8b969b3ad03c240c5cd99e8 (plain) (blame)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
//: Writing to a literal (not computed) address of 0 in a recipe chains two
//: spaces together. When a variable has a property of /space:1, it looks up
//: the variable in the chained/surrounding space. /space:2 looks up the
//: surrounding space of the surrounding space, etc.
//:
//: todo: warn on default-space abuse. default-space for one recipe should
//: never come from another, otherwise memory will be corrupted.

:(scenario closure)
def main [
  default-space:space <- new location:type, 30
  2:space/names:new-counter <- new-counter
  10:num/raw <- increment-counter 2:space/names:new-counter
  11:num/raw <- increment-counter 2:space/names:new-counter
]
def new-counter [
  default-space:space <- new location:type, 30
  x:num <- copy 23
  y:num <- copy 13  # variable that will be incremented
  return default-space:space
]
def increment-counter [
  default-space:space <- new location:type, 30
  0:space/names:new-counter <- next-ingredient  # outer space must be created by 'new-counter' above
  y:num/space:1 <- add y:num/space:1, 1  # increment
  y:num <- copy 234  # dummy
  return y:num/space:1
]
+name: lexically surrounding space for recipe increment-counter comes from new-counter
+mem: storing 15 in location 11

//: To make this work, compute the recipe that provides names for the
//: surrounding space of each recipe.

:(before "End Globals")
map<recipe_ordinal, recipe_ordinal> Surrounding_space;  // internal to transform; no need to snapshot
:(before "End Reset")
Surrounding_space.clear();

:(before "Begin Type Modifying Transforms")
Transform.push_back(collect_surrounding_spaces);  // idempotent

:(code)
void collect_surrounding_spaces(const recipe_ordinal r) {
  trace(9991, "transform") << "--- collect surrounding spaces for recipe " << get(Recipe, r).name << end();
  for (int i = 0;  i < SIZE(get(Recipe, r).steps);  ++i) {
    const instruction& inst = get(Recipe, r).steps.at(i);
    if (inst.is_label) continue;
    for (int j = 0;  j < SIZE(inst.products);  ++j) {
      if (is_literal(inst.products.at(j))) continue;
      if (inst.products.at(j).name != "0") continue;
      if (!is_mu_space(inst.products.at(j))) {
        raise << "slot 0 should always have type address:array:location, but is '" << to_string(inst.products.at(j)) << "'\n" << end();
        continue;
      }
      string_tree* s = property(inst.products.at(j), "names");
      if (!s) {
        raise << "slot 0 requires a /names property in recipe '" << get(Recipe, r).name << "'\n" << end();
        continue;
      }
      if (!s->atom) raise << "slot 0 should have a single value in /names, but got '" << to_string(inst.products.at(j)) << "'\n" << end();
      const string& surrounding_recipe_name = s->value;
      if (surrounding_recipe_name.empty()) {
        raise << "slot 0 doesn't initialize its /names property in recipe '" << get(Recipe, r).name << "'\n" << end();
        continue;
      }
      if (contains_key(Surrounding_space, r)
          && get(Surrounding_space, r) != get(Recipe_ordinal, surrounding_recipe_name)) {
        raise << "recipe '" << get(Recipe, r).name << "' can have only one 'surrounding' recipe but has '" << get(Recipe, get(Surrounding_space, r)).name << "' and '" << surrounding_recipe_name << "'\n" << end();
        continue;
      }
      trace(9993, "name") << "lexically surrounding space for recipe " << get(Recipe, r).name << " comes from " << surrounding_recipe_name << end();
      if (!contains_key(Recipe_ordinal, surrounding_recipe_name)) {
        raise << "can't find recipe providing surrounding space for '" << get(Recipe, r).name << "'; looking for '" << surrounding_recipe_name << "'\n" << end();
        continue;
      }
      put(Surrounding_space, r, get(Recipe_ordinal, surrounding_recipe_name));
    }
  }
}

//: Once surrounding spaces are available, transform_names uses them to handle
//: /space properties.

:(replace{} "int lookup_name(const reagent& r, const recipe_ordinal default_recipe)")
int lookup_name(const reagent& x, const recipe_ordinal default_recipe) {
  if (!has_property(x, "space")) {
    if (Name[default_recipe].empty()) raise << "name not found: " << x.name << '\n' << end();
    return Name[default_recipe][x.name];
  }
  string_tree* p = property(x, "space");
  if (!p || !p->atom) raise << "/space property should have exactly one (non-negative integer) value\n" << end();
  int n = to_integer(p->value);
  assert(n >= 0);
  recipe_ordinal surrounding_recipe = lookup_surrounding_recipe(default_recipe, n);
  if (surrounding_recipe == -1) return -1;
  set<recipe_ordinal> done;
  vector<recipe_ordinal> path;
  return lookup_name(x, surrounding_recipe, done, path);
}

// If the recipe we need to lookup this name in doesn't have names done yet,
// recursively call transform_names on it.
int lookup_name(const reagent& x, const recipe_ordinal r, set<recipe_ordinal>& done, vector<recipe_ordinal>& path) {
  if (!Name[r].empty()) return Name[r][x.name];
  if (contains_key(done, r)) {
    raise << "can't compute address of '" << to_string(x) << "' because\n" << end();
    for (int i = 1;  i < SIZE(path);  ++i) {
      raise << path.at(i-1) << " requires computing names of " << path.at(i) << '\n' << end();
    }
    raise << path.at(SIZE(path)-1) << " requires computing names of " << r << "..ad infinitum\n" << end();
    return -1;
  }
  done.insert(r);
  path.push_back(r);
  transform_names(r);  // Not passing 'done' through. Might this somehow cause an infinite loop?
  assert(!Name[r].empty());
  return Name[r][x.name];
}

recipe_ordinal lookup_surrounding_recipe(const recipe_ordinal r, int n) {
  if (n == 0) return r;
  if (!contains_key(Surrounding_space, r)) {
    raise << "don't know surrounding recipe of '" << get(Recipe, r).name << "'\n" << end();
    return -1;
  }
  assert(contains_key(Surrounding_space, r));
  return lookup_surrounding_recipe(get(Surrounding_space, r), n-1);
}

//: weaken use-before-set detection just a tad
:(replace{} "bool already_transformed(const reagent& r, const map<string, int>& names)")
bool already_transformed(const reagent& r, const map<string, int>& names) {
  if (has_property(r, "space")) {
    string_tree* p = property(r, "space");
    if (!p || !p->atom) {
      raise << "/space property should have exactly one (non-negative integer) value in '" << r.original_string << "'\n" << end();
      return false;
    }
    if (p->value != "0") return true;
  }
  return contains_key(names, r.name);
}

:(scenario missing_surrounding_space)
% Hide_errors = true;
def f [
  local-scope
  x:num/space:1 <- copy 34
]
+error: don't know surrounding recipe of 'f'
+error: f: can't find a place to store 'x'

//: extra test for try_reclaim_locals() from previous layers
:(scenario local_scope_ignores_nonlocal_spaces)
def new-scope [
  local-scope
  x:&:num <- new number:type
  *x:&:num <- copy 34
  return default-space:space
]
def use-scope [
  local-scope
  outer:space/names:new-scope <- next-ingredient
  0:space/names:new-scope <- copy outer:space
  return *x:&:num/space:1
]
def main [
  1:space/raw <- new-scope
  3:num/raw <- use-scope 1:space/raw
]
+mem: storing 34 in location 3

:(scenario recursive_transform_names)
def foo [
  local-scope
  x:num <- copy 0
  return default-space:space/names:foo
]
def main [
  local-scope
  0:space/names:foo <- foo
  x:num/space:1 <- copy 34
]
$error: 0
om> 2013-04-21 21:32:07 +0200 committer hut <hut@lavabit.com> 2013-04-21 21:32:30 +0200 container.settings: fix "setintag" with certain settings' href='/akspecs/ranger/commit/ranger/container/settings.py?h=v1.9.0b6&id=f28d418a7e6e22b5f0661e30a8d0fceb22067661'>f28d418a ^
1687e0f4 ^
94dc542c ^
f28d418a ^

48d5bf92 ^

f28d418a ^
48d5bf92 ^
84a22ae0 ^
56278294 ^
f28d418a ^


56278294 ^

84a22ae0 ^

51e86c62 ^
56278294 ^
d1a1173d ^
84a22ae0 ^
d1a1173d ^









84a22ae0 ^
d1a1173d ^

b3d031a9 ^

d1a1173d ^
b3d031a9 ^

d1a1173d ^






84a22ae0 ^
d1a1173d ^
d1a1173d ^















56278294 ^
d1a1173d ^
70ec0b26 ^
48d5bf92 ^

1687e0f4 ^
48d5bf92 ^

d1a1173d ^


e124e269 ^

70ec0b26 ^
d1a1173d ^


56278294 ^




d1a1173d ^



56278294 ^
864331a0 ^

916c2390 ^
76791a70 ^
d1a1173d ^












fbf6d83a ^

84a22ae0 ^
d1a1173d ^

b3d031a9 ^

d1a1173d ^


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

                                                                 
 
                                                                  
 

              
                              
 
             
                                               
                                               
                                                             
 

                                                                            




                                                                               
                                                                     
                               

 
                    
                                      

                                       
                         
                       
                         










                                            
                         
                                    
                         
                      
                        

                                                  
                                 
                          
                            

                                
                          
                           
                                 
                            
                                        

                                 
                         
                                              
                                       

                                  


                                   
                         
                
                              
                                 




                               
                    
                      
                           

                           
                           
                        
                          
                                        
                              
 
 
                  
                                                         
                                                         
                                                      
                                                                      



                                                        
                                        

 
                  





                     
 
 
 
                                                   
 


                                                
                                               
                                              

                                           
                                                              
                                                               
                                                                         
                                                           



                                                   
 

                                                  


                                         
                                          
                                                             
                                     
                 
                                                                 
                                               

                                   
                                              




                                                  

                                         
                                                                                                  
                                       

                                          
                                                                                           
                                                                        
                                        
 
                                                     



                                                                             
                                           
                                            

                                                                             
                                                                
                                                    
                                         
                                                 
 












                                                            

                                                                             


                            
                
                                                
                                  
                                

                     

                                                             
                                                
                                                             
 
                                      


                                                   

                                                                               

                                      
                                           
                                      
                                         
                                   









                                       
                                   

                       

                                      
 

                       






                                        
                         
 















                                                                              
                                                          
                
                                               

                                            
                                                          

                                                


                                                   

                                                                      
                                          


                                              




                                                    



                                           
                                                                             

 
                                                                      
 












                                                     

                                              
                                                 

                       

                                                                                  


                             
# This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.

from __future__ import (absolute_import, division, print_function)

import re
import os.path
from inspect import isfunction

import ranger
from ranger.ext.signals import SignalDispatcher
from ranger.core.shared import FileManagerAware
from ranger.gui.colorscheme import _colorscheme_name_to_class

# Use these priority constants to trigger events at specific points in time
# during processing of the signals "setopt" and "setopt.<some_setting_name>"
# pylint: disable=bad-whitespace
SIGNAL_PRIORITY_RAW        = 2.0  # signal.value will be raw
SIGNAL_PRIORITY_SANITIZE   = 1.0  # (Internal) post-processing signal.value
SIGNAL_PRIORITY_BETWEEN    = 0.6  # sanitized signal.value, old fm.settings.XYZ
SIGNAL_PRIORITY_SYNC       = 0.2  # (Internal) updating fm.settings.XYZ
SIGNAL_PRIORITY_AFTER_SYNC = 0.1  # after fm.settings.XYZ was updated
# pylint: enable=bad-whitespace


ALLOWED_SETTINGS = {
    'automatically_count_files': bool,
    'autosave_bookmarks': bool,
    'autoupdate_cumulative_size': bool,
    'cd_bookmarks': bool,
    'cd_tab_case': str,
    'cd_tab_smart': bool,
    'collapse_preview': bool,
    'colorscheme': str,
    'column_ratios': (tuple, list),
    'confirm_on_delete': str,
    'dirname_in_tabs': bool,
    'display_size_in_main_column': bool,
    'display_size_in_status_bar': bool,
    'display_tags_in_all_columns': bool,
    'draw_borders': bool,
    'draw_progress_bar_in_status_bar': bool,
    'flushinput': bool,
    'freeze_files': bool,
    'global_inode_type_filter': str,
    'hidden_filter': str,
    'idle_delay': int,
    'line_numbers': str,
    'max_console_history_size': (int, type(None)),
    'max_history_size': (int, type(None)),
    'metadata_deep_search': bool,
    'mouse_enabled': bool,
    'open_all_images': bool,
    'padding_right': bool,
    'preview_directories': bool,
    'preview_files': bool,
    'preview_images': bool,
    'preview_images_method': str,
    'preview_max_size': int,
    'preview_script': (str, type(None)),
    'save_console_history': bool,
    'scroll_offset': int,
    'shorten_title': int,
    'show_cursor': bool,  # TODO: not working?
    'show_selection_in_titlebar': bool,
    'show_hidden_bookmarks': bool,
    'show_hidden': bool,
    'sort_case_insensitive': bool,
    'sort_directories_first': bool,
    'sort_reverse': bool,
    'sort_unicode': bool,
    'sort': str,
    'status_bar_on_top': bool,
    'hostname_in_titlebar': bool,
    'tilde_in_titlebar': bool,
    'unicode_ellipsis': bool,
    'update_title': bool,
    'update_tmux_title': bool,
    'use_preview_script': bool,
    'viewmode': str,
    'vcs_aware': bool,
    'vcs_backend_bzr': str,
    'vcs_backend_git': str,
    'vcs_backend_hg': str,
    'vcs_backend_svn': str,
    'wrap_scroll': bool,
    'xterm_alt_key': bool,
    'clear_filters_on_dir_change': bool,
    'save_tabs_on_exit': bool,
}

ALLOWED_VALUES = {
    'cd_tab_case': ['sensitive', 'insensitive', 'smart'],
    'confirm_on_delete': ['multiple', 'always', 'never'],
    'line_numbers': ['false', 'absolute', 'relative'],
    'preview_images_method': ['w3m', 'iterm2', 'urxvt', 'urxvt-full'],
    'vcs_backend_bzr': ['disabled', 'local', 'enabled'],
    'vcs_backend_git': ['enabled', 'disabled', 'local'],
    'vcs_backend_hg': ['disabled', 'local', 'enabled'],
    'vcs_backend_svn': ['disabled', 'local', 'enabled'],
    'viewmode': ['miller', 'multipane'],
}

DEFAULT_VALUES = {
    bool: False,
    type(None): None,
    str: "",
    int: 0,
    list: [],
    tuple: tuple([]),
}


class Settings(SignalDispatcher, FileManagerAware):

    def __init__(self):
        SignalDispatcher.__init__(self)
        self.__dict__['_localsettings'] = dict()
        self.__dict__['_localregexes'] = dict()
        self.__dict__['_tagsettings'] = dict()
        self.__dict__['_settings'] = dict()
        for name in ALLOWED_SETTINGS:
            self.signal_bind('setopt.' + name, self._sanitize,
                             priority=SIGNAL_PRIORITY_SANITIZE)
            self.signal_bind('setopt.' + name, self._raw_set_with_signal,
                             priority=SIGNAL_PRIORITY_SYNC)
        for name, values in ALLOWED_VALUES.items():
            assert values
            assert name in ALLOWED_SETTINGS
            self._raw_set(name, values[0])

    def _sanitize(self, signal):
        name, value = signal.setting, signal.value
        if name == 'column_ratios':
            # TODO: cover more cases here
            if isinstance(value, tuple):
                signal.value = list(value)
            if not isinstance(value, list) or len(value) < 2:
                signal.value = [1, 1]
            else:
                signal.value = [int(i) if str(i).isdigit() else 1
                                for i in value]

        elif name == 'colorscheme':
            _colorscheme_name_to_class(signal)

        elif name == 'preview_script':
            if isinstance(value, str):
                result = os.path.expanduser(value)
                if os.path.exists(result):
                    signal.value = result
                else:
                    self.fm.notify("Preview script `{0}` doesn't exist!".format(result), bad=True)
                    signal.value = None

        elif name == 'use_preview_script':
            if self._settings.get('preview_script') is None and value and self.fm.ui.is_on:
                self.fm.notify("Preview script undefined or not found!",
                               bad=True)

    def set(self, name, value, path=None, tags=None):
        assert name in ALLOWED_SETTINGS, "No such setting: {0}!".format(name)
        if name not in self._settings:
            previous = None
        else:
            previous = self._settings[name]
        assert self._check_type(name, value)
        assert not (tags and path), "Can't set a setting for path and tag " \
            "at the same time!"
        kws = dict(setting=name, value=value, previous=previous,
                   path=path, tags=tags, fm=self.fm)
        self.signal_emit('setopt', **kws)
        self.signal_emit('setopt.' + name, **kws)

    def _get_default(self, name):
        if name == 'preview_script':
            if ranger.args.clean:
                value = self.fm.relpath('data/scope.sh')
            else:
                value = self.fm.confpath('scope.sh')
                if not os.path.exists(value):
                    value = self.fm.relpath('data/scope.sh')
        else:
            value = DEFAULT_VALUES[self.types_of(name)[0]]

        return value

    def get(self, name, path=None):
        assert name in ALLOWED_SETTINGS, "No such setting: {0}!".format(name)
        if path:
            localpath = path
        else:
            try:
                localpath = self.fm.thisdir.path
            except AttributeError:
                localpath = None

        if localpath:
            for pattern, regex in self._localregexes.items():
                if name in self._localsettings[pattern] and\
                        regex.search(localpath):
                    return self._localsettings[pattern][name]

        if self._tagsettings and path:
            realpath = os.path.realpath(path)
            if realpath in self.fm.tags:
                tag = self.fm.tags.marker(realpath)
                if tag in self._tagsettings and name in self._tagsettings[tag]:
                    return self._tagsettings[tag][name]

        if name not in self._settings:
            value = self._get_default(name)
            self._raw_set(name, value)
            self.__setattr__(name, value)
        return self._settings[name]

    def __setattr__(self, name, value):
        if name.startswith('_'):
            self.__dict__[name] = value
        else:
            self.set(name, value, None)

    def __getattr__(self, name):
        if name.startswith('_'):
            return self.__dict__[name]
        return self.get(name, None)

    def __iter__(self):
        for setting in self._settings:
            yield setting

    @staticmethod
    def types_of(name):
        try:
            typ = ALLOWED_SETTINGS[name]
        except KeyError:
            return tuple()
        else:
            if isinstance(typ, tuple):
                return typ
            return (typ,)

    def _check_type(self, name, value):
        typ = ALLOWED_SETTINGS[name]
        if isfunction(typ):
            assert typ(value), \
                "Warning: The option `" + name + "' has an incorrect type!"
        else:
            assert isinstance(value, typ), \
                "Warning: The option `" + name + "' has an incorrect type!"\
                " Got " + str(type(value)) + ", expected " + str(typ) + "!" +\
                " Please check if your commands.py is up to date." if not \
                self.fm.ui.is_set_up else ""
        return True

    __getitem__ = __getattr__
    __setitem__ = __setattr__

    def _raw_set(self, name, value, path=None, tags=None):
        if path:
            if path not in self._localsettings:
                try:
                    regex = re.compile(path)
                except re.error:  # Bad regular expression
                    return
                self._localregexes[path] = regex
                self._localsettings[path] = dict()
            self._localsettings[path][name] = value

            # make sure name is in _settings, so __iter__ runs through
            # local settings too.
            if name not in self._settings:
                type_ = self.types_of(name)[0]
                value = DEFAULT_VALUES[type_]
                self._settings[name] = value
        elif tags:
            for tag in tags:
                if tag not in self._tagsettings:
                    self._tagsettings[tag] = dict()
                self._tagsettings[tag][name] = value
        else:
            self._settings[name] = value

    def _raw_set_with_signal(self, signal):
        self._raw_set(signal.setting, signal.value, signal.path, signal.tags)


class LocalSettings(object):  # pylint: disable=too-few-public-methods

    def __init__(self, path, parent):
        self.__dict__['_parent'] = parent
        self.__dict__['_path'] = path

    def __setattr__(self, name, value):
        if name.startswith('_'):
            self.__dict__[name] = value
        else:
            self._parent.set(name, value, self._path)

    def __getattr__(self, name):
        if name.startswith('_'):
            return self.__dict__[name]
        if name.startswith('signal_'):
            return getattr(self._parent, name)
        return self._parent.get(name, self._path)

    def __iter__(self):
        for setting in self._parent._settings:  # pylint: disable=protected-access
            yield setting

    __getitem__ = __getattr__
    __setitem__ = __setattr__