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

#const_from, #drill_signature, #infer, #pack_name, #resolve_node_signature, #stack_node_signature, #unpack_name, #yard_options

Constructor Details

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

Returns a new instance of CodeMap.



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

def initialize code: '', filename: nil, workspace: nil, api_map: nil
  unless workspace.nil?
    workspace = workspace.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
  end
  if workspace.nil? and !filename.nil?
    filename = filename.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
    workspace = CodeMap.find_workspace(filename)
  end
  @filename = filename
  @api_map = api_map
  if @api_map.nil?
    @api_map = ApiMap.new(workspace)
  end
  @code = code.gsub(/\r/, '')
  tries = 0
  tmp = @code
  begin
    node, comments = Parser::CurrentRuby.parse_with_comments(tmp)
    @node = @api_map.append_node(node, comments, filename)
    @parsed = tmp
    @code.freeze
    @parsed.freeze
  rescue Parser::SyntaxError => e
    if tries < 10
      STDERR.puts "Error parsing #{filename}: #{e.message}"
      STDERR.puts "Retrying..."
      tries += 1
      spot = e.diagnostic.location.begin_pos
      repl = '_'
      if tmp[spot] == '@' or tmp[spot] == ':'
        # Stub unfinished instance variables and symbols
        spot -= 1
      elsif tmp[spot - 1] == '.'
        # Stub unfinished method calls
        repl = '#' if spot == tmp.length or tmp[spot] == '\n'
        spot -= 2
      else
        # Stub the whole line
        spot = beginning_of_line_from(tmp, spot)
        repl = '#'
        if tmp[spot+1..-1].rstrip == 'end'
          repl= 'end;end'
        end
      end
      tmp = tmp[0..spot] + repl + tmp[spot+repl.length+1..-1].to_s
      retry
    end
    raise e
  end
end

Instance Attribute Details

#api_map ⇒ Object

Returns the value of attribute api_map.



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

def api_map
  @api_map
end

#code ⇒ Object (readonly)

Returns the value of attribute code.



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

def code
  @code
end

#node ⇒ Object

Returns the value of attribute node.



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

def node
  @node
end

#parsed ⇒ Object (readonly)

Returns the value of attribute parsed.



8
9
10
# File 'lib/solargraph/code_map.rb', line 8

def parsed
  @parsed
end

Class Method Details

.find_workspace(filename) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/solargraph/code_map.rb', line 63

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



430
431
432
433
434
435
436
437
438
439
# File 'lib/solargraph/code_map.rb', line 430

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_variables_at(index) ⇒ Object



161
162
163
164
165
# File 'lib/solargraph/code_map.rb', line 161

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



460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/solargraph/code_map.rb', line 460

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, visibility: [:public, :private, :protected])
  else
    result += @api_map.get_methods(scope, visibility: [:public, :private, :protected])
  end
  result += @api_map.get_methods('Kernel')
  result
end

#get_offset(line, col) ⇒ Object



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

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



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/solargraph/code_map.rb', line 398

def get_signature_at index
  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)
      break if char == '@'
    end
    index -= 1
  end
  signature
end

#get_snippets_at(index) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/solargraph/code_map.rb', line 441

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::SNIPPET, detail: name, insert: detail['body'].join("\r\n"))
    end
  }
  result
end

#get_type_comment(node) ⇒ Object



388
389
390
391
392
393
394
395
396
# File 'lib/solargraph/code_map.rb', line 388

def get_type_comment node
  obj = nil
  cmnt = @api_map.get_comment_for(node)
  unless cmnt.nil?
    tag = cmnt.tag(:type)
    obj = tag.types[0] unless tag.nil? or tag.types.empty?
  end
  obj
end

#merge(node) ⇒ Object



91
92
93
# File 'lib/solargraph/code_map.rb', line 91

def merge node
  api_map.merge node
end

#namespace_at(index) ⇒ Object



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

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

#node_at(index) ⇒ Object



102
103
104
# File 'lib/solargraph/code_map.rb', line 102

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

#parent_node_from(index, *types) ⇒ Object



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

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



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

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_object_at(index) ⇒ Object



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

def resolve_object_at index
  signature = get_signature_at(index)
  cursor = index
  while @code[cursor] =~ /[a-z0-9_\?]/i
    signature += @code[cursor]
    cursor += 1
    break if cursor >= @code.length
  end
  return [] if signature.to_s == ''
  ns_here = namespace_at(index)
  scope = parent_node_from(index, :class, :module, :def, :defs) || @node
  parts = signature.split('.')
  if parts.length > 1
    beginner = parts[0..-2].join('.')
    ender = parts.last
  else
    beginner = signature
    ender = nil
  end
  var = find_local_variable_node(parts[0], scope)
  if var.nil?
    # It's not a local variable
    fqns = @api_map.find_fully_qualified_namespace(beginner, ns_here)
    if fqns.nil?
      # It's a method call
      if ender.nil?
        return @api_map.yard_map.objects(beginner, ns_here)
      else
        sig_scope = (scope.type == :def ? :instance : :class)
        type = @api_map.infer_signature_type(beginner, ns_here, scope: sig_scope)
        return [] if type.nil?
        path = type
        path += "##{ender}" unless ender.nil?
        return @api_map.yard_map.objects(path, ns_here)
      end
    else
      path = beginner
      path += "##{ender}" unless ender.nil?
      return @api_map.yard_map.objects(path, ns_here)
    end
  else
    # It's a local variable. Get the type from the node
    type = get_type_comment(var)
    type = infer(var.children[1]) if type.nil?
    if type.nil?
      vsig = resolve_node_signature(var.children[1])
      vparts = vsig.split('.')
      fqns = @api_map.find_fully_qualified_namespace(vparts[0], ns_here)
      if fqns.nil?
        vtype = @api_map.infer_signature_type(vsig, ns_here, scope: :instance)
      else
        vtype = @api_map.infer_signature_type(vparts[1..-1].join('.'), fqns, scope: :class)
      end
      return [] if vtype.nil?
      fqns = @api_map.find_fully_qualified_namespace(vtype, ns_here)
      if ender.nil?
        signature = parts[1..-1].join('.')
      else
        signature = parts[1..-2].join('.')
      end
      type = @api_map.infer_signature_type(signature, fqns, scope: :instance)
    end
    unless type.nil?
      path = type
      path += "##{ender}" unless ender.nil?
      return @api_map.yard_map.objects(path, ns_here)
    end
  end
  return []
end

#resolve_signature_at(index) ⇒ Array<Solargraph::Suggestion>

Find the signature at the specified index and get suggestions based on its inferred type.

Returns:



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/solargraph/code_map.rb', line 314

def resolve_signature_at index
  result = []
  signature = get_signature_at(index)
  ns_here = namespace_at(index)
  scope = parent_node_from(index, :class, :module, :def, :defs) || @node
  parts = signature.split('.')
  var = find_local_variable_node(parts[0], scope)
  if var.nil?
    # It's not a local variable
    fqns = @api_map.find_fully_qualified_namespace(signature, ns_here)
    if fqns.nil?
      # It's a method call
      sig_scope = (scope.type == :def ? :instance : :class)
      type = @api_map.infer_signature_type(signature, ns_here, scope: sig_scope)
      result.concat @api_map.get_instance_methods(type) unless type.nil?
    else
      if fqns == ns_here
        result.concat @api_map.get_methods(fqns, '', visibility: [:private, :protected, :public])
      else
        result.concat @api_map.get_methods(fqns)
      end
    end
  else
    # It's a local variable. Get the type from the node
    type = get_type_comment(var)
    type = infer(var.children[1]) if type.nil?
    skipdat = false
    if type.nil?
      vsig = resolve_node_signature(var.children[1])
      vparts = vsig.split('.')
      fqns = @api_map.find_fully_qualified_namespace(vparts[0], ns_here)
      if fqns.nil?
        lvar = find_local_variable_node(vparts[0], scope)
        if lvar.nil?
          vtype = @api_map.infer_signature_type(vsig, ns_here, scope: :instance)
        else
          type = get_type_comment(lvar)
          type = infer(lvar.children[1]) if type.nil?
          if type.nil?
            type = @api_map.infer_signature_type(resolve_node_signature(lvar.children[1]), ns_here, scope: :class)
          end
          unless type.nil?
            signature = "#{vparts[1..-1].join('.')}"
            skipdat = true
          end
        end
      else
        vtype = @api_map.infer_signature_type(vparts[1..-1].join('.'), fqns, scope: :class)
        type = fqns
        signature = parts[1..-1].join('.')
        skipdat = true
      end
      unless skipdat
        fqns = @api_map.find_fully_qualified_namespace(vtype, ns_here)
        signature = parts[1..-1].join('.')
        type = @api_map.infer_signature_type(signature, fqns, scope: :instance)
      end
    else
      signature = signature.split('.')[1..-1].join('.')
    end
    unless type.nil?
      lparts = signature.split('.')
      if lparts.length >= 1
        lsig = signature
        ltype = @api_map.infer_signature_type(lsig, type, scope: :instance)
        result.concat @api_map.get_instance_methods(ltype) unless ltype.nil?
      else
        result.concat @api_map.get_instance_methods(type)
      end
    end
  end
  result
end

#signatures_at(index) ⇒ Object



232
233
234
235
236
237
# File 'lib/solargraph/code_map.rb', line 232

def signatures_at index
  sig = signature_index_before(index)
  return [] if sig.nil?
  word = word_at(sig)
  suggest_at(sig).reject{|s| s.label != word}
end

#string_at?(index) ⇒ Boolean

Returns:

  • (Boolean)


106
107
108
109
# File 'lib/solargraph/code_map.rb', line 106

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

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



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

def suggest_at index, filtered: false, with_snippets: false
  node = node_at(index - 2)
  return [] if string_at?(index)
  result = []
  phrase = phrase_at(index)
  signature = get_signature_at(index)
  if (@code[index - 1] == '.')
    type = infer(node_at(index - 2))
    return @api_map.get_instance_methods(type) unless type.nil?
  end
  if signature.start_with?('@')
    parts = signature.split('.')
    var = parts.shift
    if parts.length > 0 or signature.end_with?('.')
      result = []
      ns = namespace_at(index)
      scope = :class
      node = parent_node_from(index, :def, :defs, :class, :module)
      scope = :instance if !node.nil? and node.type == :def
      obj = @api_map.infer_instance_variable(var, ns, scope)
      type = @api_map.infer_signature_type(parts.join('.'), obj, scope: :instance)
      result = @api_map.get_instance_methods(type) unless type.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 signature.include?('.')
    result = resolve_signature_at @code[0, index].rindex('.')
  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
    while parts.length > 0
      ns = parts.join('::')
      result += @api_map.namespaces_in(ns)
      parts.pop
    end
    result += @api_map.namespaces_in('')
    result += @api_map.get_instance_methods('Kernel')
    unless @filename.nil? or @api_map.yardoc_has_file?(@filename)
      m = @code.match(/# +@bind \[([a-z0-9_:]*)/i)
      unless m.nil?
        @api_map.get_instance_methods(m[1])
      end
    end
  end
  result = reduce_starting_with(result, word_at(index)) if filtered
  result.uniq{|s| s.path}
end

#tree_at(index) ⇒ Object



95
96
97
98
99
100
# File 'lib/solargraph/code_map.rb', line 95

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

#word_at(index) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/solargraph/code_map.rb', line 148

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