Module: PuppetLanguageServer::PuppetParserHelper

Defined in:
lib/puppet-languageserver/puppet_parser_helper.rb

Class Method Summary collapse

Class Method Details

.check_for_valid_item(item, abs_offset, disallowed_classes) ⇒ Object



193
194
195
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 193

def self.check_for_valid_item(item, abs_offset, disallowed_classes)
  item.respond_to?(:offset) && !item.offset.nil? && !item.length.nil? && abs_offset >= item.offset && abs_offset <= item.offset + item.length && !disallowed_classes.include?(item.class)
end

.construct_path(item) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 182

def self.construct_path(item)
  path = []
  item = item.eContainer
  while item.class != Puppet::Pops::Model::Program
    path.unshift item
    item = item.eContainer
  end

  path
end

.get_char_at(content, line_offsets, line_num, char_num) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 17

def self.get_char_at(content, line_offsets, line_num, char_num)
  line_offset = line_offsets[line_num]
  raise if line_offset.nil?

  absolute_offset = line_offset + (char_num - 1)

  content[absolute_offset]
end

.get_line_at(content, line_offsets, line_num) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 49

def self.get_line_at(content, line_offsets, line_num)
  # Get the text of the designated line
  start_index = line_offsets[line_num]
  if line_offsets[line_num + 1].nil?
    content.slice(start_index, content.length - start_index)
  else
    content.slice(start_index, line_offsets[line_num + 1] - start_index - 1)
  end
end

.insert_text_at(content, line_offsets, line_num, char_num, text) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 26

def self.insert_text_at(content, line_offsets, line_num, char_num, text)
  # Insert text after where the cursor is
  # This helps due to syntax errors like `$facts[]` or `ensure =>`
  line_offset = line_offsets[line_num]
  raise if line_offset.nil?

  # Insert the text
  content.slice(0, line_offset + char_num) + text + content.slice(line_offset + char_num, content.length - 1)
end

.line_offsets(content) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 36

def self.line_offsets(content)
  # Calculate all of the offsets of \n in the file
  line_offsets = [0]
  line_offset = -1
  loop do
    line_offset = content.index("\n", line_offset + 1)
    break if line_offset.nil?

    line_offsets << (line_offset + 1)
  end
  line_offsets
end

.object_under_cursor(content, line_num, char_num, options) ⇒ Object



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
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 59

def self.object_under_cursor(content, line_num, char_num, options)
  options = {
    multiple_attempts: false,
    disallowed_classes: [],
    tasks_mode: false,
    remove_trigger_char: true
  }.merge(options)

  # Use Puppet to generate the AST
  parser = Puppet::Pops::Parser::Parser.new

  # Calculating the line offsets can be expensive and is only required
  # if we're doing mulitple passes of parsing
  line_offsets = line_offsets(content) if options[:multiple_attempts]

  result = nil
  move_offset = 0
  %i[noop remove_word try_quotes try_quotes_and_comma remove_char].each do |method|
    new_content = nil
    case method
    when :noop
      new_content = content
    when :remove_char
      next if line_num.zero? && char_num.zero?

      new_content = remove_char_at(content, line_offsets, line_num, char_num)
      move_offset = -1
    when :remove_word
      next if line_num.zero? && char_num.zero?

      next_char = get_char_at(content, line_offsets, line_num, char_num)

      while /[[:word:]]/ =~ next_char
        move_offset -= 1
        next_char = get_char_at(content, line_offsets, line_num, char_num + move_offset)

        break if char_num + move_offset < 0
      end

      new_content = remove_chars_starting_at(content, line_offsets, line_num, char_num, -move_offset)
    when :try_quotes
      # Perhaps try inserting double quotes.  Useful in empty arrays or during variable assignment
      # Grab the line up to the cursor character + 1
      line = get_line_at(content, line_offsets, line_num).slice!(0, char_num + 1)
      if line.strip.end_with?('=') || line.end_with?('[]') # rubocop:disable Style/IfUnlessModifier  Nicer to read like this
        new_content = insert_text_at(content, line_offsets, line_num, char_num, "''")
      end
    when :try_quotes_and_comma
      # Perhaps try inserting double quotes with a comma.  Useful resource properties and parameter assignments
      # Grab the line up to the cursor character + 1
      line = get_line_at(content, line_offsets, line_num).slice!(0, char_num + 1)
      if line.strip.end_with?('=>') # rubocop:disable Style/IfUnlessModifier  Nicer to read like this
        new_content = insert_text_at(content, line_offsets, line_num, char_num, "'',")
      end
    else
      raise("Unknown parsing method #{method}")
    end
    # if we have no content to parse, try the next method.
    next if new_content.nil?

    begin
      result = parser.singleton_parse_string(new_content, options[:tasks_mode], '')
      break
    rescue Puppet::ParseErrorWithIssue
      next if options[:multiple_attempts]

      raise
    end
  end
  raise('Unable to parse content') if result.nil?

  # Convert line and char nums (base 0) to an absolute offset
  #   result.line_offsets contains an array of the offsets on a per line basis e.g.
  #     [0, 14, 34, 36]  means line number 2 starts at absolute offset 34
  #   Once we know the line offset, we can simply add on the char_num to get the absolute offset
  #   If during paring we modified the source we may need to change the cursor location
  line_offset = if result.respond_to?(:line_offsets)
                  result.line_offsets[line_num]
                else
                  result['locator'].line_index[line_num]
                end
  abs_offset = line_offset + char_num + move_offset
  # Typically we're completing after something was typed, so go back one char by default
  abs_offset -= 1 if options[:remove_trigger_char]

  # Enumerate the AST looking for items that span the line/char we want.
  # Once we have all valid items, sort them by the smallest span.  Typically the smallest span
  # is the most specific object in the AST
  #
  # TODO: Should probably walk the AST and only look for the deepest child, but integer sorting
  #       is so much easier and faster.
  model_path_locator_struct = Struct.new(:model, :path, :locator)

  valid_models = []
  if result.model.respond_to? :eAllContents
    valid_models = result.model.eAllContents.select do |item|
      check_for_valid_item(item, abs_offset, options[:disallowed_classes])
    end

    valid_models.sort! { |a, b| a.length - b.length }
  else
    path = []
    result.model._pcore_all_contents(path) do |item|
      if check_for_valid_item(item, abs_offset, options[:disallowed_classes]) # rubocop:disable Style/IfUnlessModifier  Nicer to read like this
        valid_models.push(model_path_locator_struct.new(item, path.dup))
      end
    end

    valid_models.sort! { |a, b| a[:model].length - b[:model].length }
  end
  # nil means the root of the document
  return nil if valid_models.empty?

  response = valid_models[0]

  if response.respond_to? :eAllContents # rubocop:disable Style/IfUnlessModifier  Nicer to read like this
    response = model_path_locator_struct.new(response, construct_path(response))
  end

  response.locator = result.model.locator
  response
end

.remove_char_at(content, line_offsets, line_num, char_num) ⇒ Object



13
14
15
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 13

def self.remove_char_at(content, line_offsets, line_num, char_num)
  remove_chars_starting_at(content, line_offsets, line_num, char_num, 1)
end

.remove_chars_starting_at(content, line_offsets, line_num, char_num, num_chars_to_remove) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/puppet-languageserver/puppet_parser_helper.rb', line 5

def self.remove_chars_starting_at(content, line_offsets, line_num, char_num, num_chars_to_remove)
  line_offset = line_offsets[line_num]
  raise if line_offset.nil?

  # Remove the offending character
  content.slice(0, line_offset + char_num - num_chars_to_remove) + content.slice(line_offset + char_num, content.length - num_chars_to_remove)
end