Class: Solargraph::CodeMap

Inherits:
Object
  • Object
show all
Includes:
NodeMethods
Defined in:
lib/solargraph/code_map.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from NodeMethods

#infer, #pack_name, #unpack_name

Constructor Details

#initialize(code: '', filename: nil) ⇒ CodeMap

Returns a new instance of CodeMap.



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
# File 'lib/solargraph/code_map.rb', line 10

def initialize code: '', filename: nil
  workspace = nil
  unless filename.nil?
    filename.gsub!(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
    workspace = CodeMap.find_workspace(filename)
  end
  @api_map = ApiMap.new(workspace)
  unless workspace.nil?
    files = Dir[File.join workspace, '**', '*.rb']
    files.each { |f|
      unless filename == f
        @api_map.append_file f
      end
    }
  end

  @code = code.gsub(/\r/, '')
  tries = 0
  # Hide incomplete code to avoid syntax errors
  tmp = "#{code}\nX".gsub(/[\.@]([\s])/, '#\1').gsub(/([\A\s]?)def([\s]*?[\n\Z])/, '\1#ef\2')
  #tmp = code
  begin
    @node, comments = Parser::CurrentRuby.parse_with_comments(tmp)
    @api_map.append_node(@node, comments, filename)
  rescue Parser::SyntaxError => e
    if tries < 10
      tries += 1
      spot = e.diagnostic.location.begin_pos
      if spot == tmp.length
        puts e.message
        tmp = tmp[0..-2] + '#'
      else
        tmp = tmp[0..spot] + '#' + tmp[spot+2..-1].to_s
      end
      retry
    end
    raise e
  end
end

Instance Attribute Details

#api_mapObject

Returns the value of attribute api_map.



6
7
8
# File 'lib/solargraph/code_map.rb', line 6

def api_map
  @api_map
end

#nodeObject

Returns the value of attribute node.



5
6
7
# File 'lib/solargraph/code_map.rb', line 5

def node
  @node
end

Class Method Details

.find_workspace(filename) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/solargraph/code_map.rb', line 50

def self.find_workspace filename
  return nil if filename.nil?
  dirname = filename
  lastname = nil
  result = nil
  until dirname == lastname
    if File.file?("#{dirname}/Gemfile")
      result = dirname
      break
    end
    lastname = dirname
    dirname = File.dirname(dirname)
  end
  result ||= File.dirname(filename)
  result.gsub!(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
  result
end

Instance Method Details

#build_signature(node, parts) ⇒ Object



301
302
303
304
305
306
307
308
309
310
# File 'lib/solargraph/code_map.rb', line 301

def build_signature(node, parts)
  if node.kind_of?(AST::Node)
    if node.type == :send
      parts.unshift node.children[1].to_s
    elsif node.type == :const
      parts.unshift unpack_name(node)
    end
    build_signature(node.children[0], parts)
  end
end

#get_instance_method_return_value(namespace, root, method) ⇒ Object



252
253
254
255
256
257
258
259
260
261
# File 'lib/solargraph/code_map.rb', line 252

def get_instance_method_return_value namespace, root, method
  meths = @api_map.get_instance_methods(namespace, root).delete_if{ |m| m.label != method }
  meths.each { |m|
    unless m.documentation.nil?
      match = m.documentation.all.match(/@return \[([a-z0-9:_]*)/i)
      return match[1] unless match.nil?
    end
  }
  'Object'
end

#get_instance_variables_at(index) ⇒ Object



148
149
150
151
152
# File 'lib/solargraph/code_map.rb', line 148

def get_instance_variables_at(index)
  node = parent_node_from(index, :def, :defs, :class, :module)
  ns = namespace_at(index) || ''
  @api_map.get_instance_variables(ns, (node.type == :def ? :instance : :class))
end

#get_local_variables_and_methods_at(index) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/solargraph/code_map.rb', line 331

def get_local_variables_and_methods_at(index)
  result = []
  local = parent_node_from(index, :class, :module, :def, :defs) || @node
  result += get_local_variables_from(local)
  scope = namespace_at(index) || @node
  if local.type == :def
    result += @api_map.get_instance_methods(scope)
  else
    result += @api_map.get_methods(scope)
  end
  result += @api_map.get_methods('Kernel')
  result    
end

#get_method_return_value(namespace, root, method) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
# File 'lib/solargraph/code_map.rb', line 240

def get_method_return_value namespace, root, method
  meths = @api_map.get_methods(namespace, root).delete_if{ |m| m.label != method }
  meths.each { |m|
    unless m.documentation.nil?
      match = m.documentation.all.match(/@return \[([a-z0-9:_]*)/i)
      klass = match[1]
      return klass unless klass.nil?
    end
  }
  'Object'
end

#get_offset(line, col) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/solargraph/code_map.rb', line 68

def get_offset line, col
  offset = 0
  if line > 0
    @code.lines[0..line - 1].each { |l|
      offset += l.length
    }
  end
  offset + col
end

#get_signature_at(index) ⇒ Object



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
# File 'lib/solargraph/code_map.rb', line 263

def get_signature_at index
  #node = node_at(index - 1)
  #return '' unless node.type == :send
  #parts = []
  #build_signature(node, parts)
  #return parts.join('.')

  # TODO: Alternate rough version
  brackets = 0
  squares = 0
  parens = 0
  signature = ''
  index -=1
  while index > 0
    break if brackets > 0 or parens > 0 or squares > 0
    char = @code[index, 1]
    if char == ')'
      parens -=1
    elsif char == ']'
      squares -=1
    elsif char == '}'
      brackets -= 1
    elsif char == '('
      parens += 1
    elsif char == '{'
      brackets += 1
    elsif char == '['
      squares += 1
    end
    if brackets == 0 and parens == 0 and squares == 0
      break if ['"', "'", ',', ' ', "\t", "\n"].include?(char)
      signature = char + signature if char.match(/[a-z0-9:\._]/i)
    end
    index -= 1
  end
  signature
end

#get_snippets_at(index) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/solargraph/code_map.rb', line 312

def get_snippets_at(index)
  result = []
  Snippets.definitions.each_pair { |name, detail|
    matched = false
    prefix = detail['prefix']
    while prefix.length > 0
      if @code[index-prefix.length, prefix.length] == prefix
        matched = true
        break
      end
      prefix = prefix[0..-2]
    end
    if matched
      result.push Suggestion.new(detail['prefix'], kind: Suggestion::KEYWORD, detail: name, insert: detail['body'].join("\r\n"))
    end
  }
  result
end

#merge(node) ⇒ Object



78
79
80
# File 'lib/solargraph/code_map.rb', line 78

def merge node
  api_map.merge node
end

#namespace_at(index) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/solargraph/code_map.rb', line 108

def namespace_at(index)
  tree = tree_at(index)
  return nil if tree.length == 0
  node = parent_node_from(index, :module, :class)
  slice = tree[(tree.index(node) || 0)..-1]
  parts = []
  slice.reverse.each { |n|
    if n.type == :class or n.type == :module
      parts.push unpack_name(n.children[0])
    end
  }
  parts.join("::")
end

#node_at(index) ⇒ Object



89
90
91
# File 'lib/solargraph/code_map.rb', line 89

def node_at(index)
  tree_at(index).first
end

#parent_node_from(index, *types) ⇒ Object



98
99
100
101
102
103
104
105
106
# File 'lib/solargraph/code_map.rb', line 98

def parent_node_from(index, *types)
  arr = tree_at(index)
  arr.each { |a|
    if a.kind_of?(AST::Node) and (types.empty? or types.include?(a.type))
      return a
    end
  }
  @node
end

#phrase_at(index) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/solargraph/code_map.rb', line 122

def phrase_at index
  word = ''
  cursor = index - 1
  while cursor > -1
    char = @code[cursor, 1]
    break if char.nil? or char == ''
    break unless char.match(/[\s;=\(\)\[\]\{\}]/).nil?
    word = char + word
    cursor -= 1
  end
  word
end

#resolve_signature_at(index) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/solargraph/code_map.rb', line 215

def resolve_signature_at index
  signature = get_signature_at(index)
  ns_here = namespace_at(index)
  parts = signature.split('.')
  first = parts.shift
  scope = parent_node_from(index, :class, :module, :def, :defs) || @node
  var = find_local_variable_node(first, scope)
  if var.nil?
    if parts.length == 0
      return @api_map.get_methods(first, ns_here)
    end
    obj = get_method_return_value first, ns_here, parts.shift
    while parts.length > 0
      obj = get_instance_method_return_value obj, ns_here, parts.shift
    end
    return @api_map.get_instance_methods(obj) unless obj.nil?
  else
    obj = infer(var.children[1])
    while parts.length > 0
      obj = get_instance_method_return_value obj, ns_here, parts.shift
    end
    return @api_map.get_instance_methods(obj) unless obj.nil?
  end
end

#string_at?(index) ⇒ Boolean

Returns:

  • (Boolean)


93
94
95
96
# File 'lib/solargraph/code_map.rb', line 93

def string_at?(index)
  n = node_at(index)
  n.kind_of?(AST::Node) and n.type == :str
end

#suggest_at(index, filtered: true, with_snippets: false) ⇒ Object



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
# File 'lib/solargraph/code_map.rb', line 154

def suggest_at index, filtered: true, with_snippets: false
  return [] if string_at?(index)
  result = []
  phrase = phrase_at(index)
  if phrase.start_with?('@')
    if phrase.include?('.')
      result = []
      # TODO: Temporarily assuming one period
      var = phrase[0..phrase.index('.')-1]
      ns = namespace_at(index)
      obj = @api_map.infer_instance_variable(var, ns)
      result = @api_map.get_instance_methods(obj) unless obj.nil?
    else
      result = get_instance_variables_at(index)
    end
  elsif phrase.start_with?('$')
    result += @api_map.get_global_variables
  elsif phrase.start_with?(':') and !phrase.start_with?('::')
    # TODO: It's a symbol. Nothing to do for now.
    return []
  elsif phrase.include?('::')
    parts = phrase.split('::', -1)
    ns = parts[0..-2].join('::')
    if parts.last.include?('.')
      ns = parts[0..-2].join('::') + '::' + parts.last[0..parts.last.index('.')-1]
      result = @api_map.get_methods(ns)
    else
      result = @api_map.namespaces_in(ns)
    end
  elsif phrase.include?('.')
    # It's a method call
    # TODO: For now we're assuming only one period. That's obviously a bad assumption.
    #base = phrase[0..phrase.index('.')-1]
    #ns_here = namespace_at(index)
    #result = @api_map.get_methods(base, ns_here)
    #scope = parent_node_from(index, :class, :module, :def, :defs) || @node
    #var = find_local_variable_node(base, scope)
    #unless var.nil?
    #  obj = infer(var.children[1])
    #  result = @api_map.get_instance_methods(obj) unless obj.nil?
    #end
    
    # TODO: Alternate version that resolves signature
    result = resolve_signature_at index
  else
    current_namespace = namespace_at(index)
    parts = current_namespace.to_s.split('::')
    result += get_snippets_at(index) if with_snippets
    result += get_local_variables_and_methods_at(index)
    result += ApiMap.get_keywords(without_snippets: with_snippets)
    while parts.length > 0
      ns = parts.join('::')
      result += @api_map.namespaces_in(ns)
      parts.pop
    end
    result += @api_map.namespaces_in('')
  end
  result = reduce_starting_with(result, word_at(index)) if filtered
  result
end

#tree_at(index) ⇒ Object



82
83
84
85
86
87
# File 'lib/solargraph/code_map.rb', line 82

def tree_at(index)
  arr = []
  arr.push @node
  inner_node_at(index, @node, arr)
  arr
end

#word_at(index) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/solargraph/code_map.rb', line 135

def word_at index
  word = ''
  cursor = index - 1
  while cursor > -1
    char = @code[cursor, 1]
    break if char.nil? or char == ''
    break unless char.match(/[a-z0-9_]/i)
    word = char + word
    cursor -= 1
  end
  word
end