Module: Jazzy::SourceKitten

Defined in:
lib/jazzy/sourcekitten.rb

Overview

This module interacts with the sourcekitten command-line executable

Class Method Summary collapse

Class Method Details

.ancestor_name_match(name_part, doc) ⇒ Object

Find the first ancestor of doc whose name matches name_part.



415
416
417
418
419
420
421
422
# File 'lib/jazzy/sourcekitten.rb', line 415

def self.ancestor_name_match(name_part, doc)
  doc.namespace_ancestors.reverse_each do |ancestor|
    if match = name_match(name_part, ancestor.children)
      return match
    end
  end
  nil
end

.arguments_from_options(options) ⇒ Object

Builds SourceKitten arguments based on Jazzy options



118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/jazzy/sourcekitten.rb', line 118

def self.arguments_from_options(options)
  arguments = ['doc']
  if options.objc_mode
    if options.xcodebuild_arguments.empty?
      arguments += ['--objc', options.umbrella_header.to_s, '-x',
                    'objective-c', '-isysroot',
                    `xcrun --show-sdk-path`.chomp, '-I',
                    options.framework_root.to_s]
    end
  elsif !options.module_name.empty?
    arguments += ['--module-name', options.module_name]
  end
  arguments + options.xcodebuild_arguments
end


457
458
459
460
461
462
463
# File 'lib/jazzy/sourcekitten.rb', line 457

def self.autolink(docs, root_decls)
  docs.each do |doc|
    doc.abstract = autolink_text(doc.abstract, doc, root_decls)
    doc.return = autolink_text(doc.return, doc, root_decls) if doc.return
    doc.children = autolink(doc.children, root_decls)
  end
end


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/jazzy/sourcekitten.rb', line 432

def self.autolink_text(text, doc, root_decls)
  text.gsub(%r{<code>[ \t]*([^\s]+)[ \t]*</code>}) do
    original = Regexp.last_match(0)
    raw_name = Regexp.last_match(1)
    parts = raw_name
            .split(/(?<!\.)\.(?!\.)/) # dot with no neighboring dots
            .reject(&:empty?)

    # First dot-separated component can match any ancestor or top-level doc
    first_part = parts.shift
    name_root = ancestor_name_match(first_part, doc) ||
                name_match(first_part, root_decls)

    # Traverse children via subsequence components, if any
    link_target = name_traversal(parts, name_root)

    if link_target && link_target.url && link_target.url != doc.url
      "<code><a href=\"#{ELIDED_AUTOLINK_TOKEN}#{link_target.url}\">" +
        raw_name + '</a></code>'
    else
      original
    end
  end
end

.comment_from_doc(doc) ⇒ Object



235
236
237
238
239
240
241
242
243
244
# File 'lib/jazzy/sourcekitten.rb', line 235

def self.comment_from_doc(doc)
  swift_version = Config.instance.swift_version.to_f
  comment = doc['key.doc.comment'] || ''
  if swift_version < 2
    # comment until first ReST definition
    matches = /^\s*:[^\s]+:/.match(comment)
    comment = comment[0...matches.begin(0)] if matches
  end
  Jazzy.markdown.render(comment)
end

.deduplicate_declarations(declarations) ⇒ Object

Merges multiple extensions of the same entity into a single document.

Merges extensions into the protocol/class/struct/enum they extend, if it occurs in the same project.

Merges redundant declarations when documenting podspecs.



319
320
321
322
323
324
325
326
327
328
# File 'lib/jazzy/sourcekitten.rb', line 319

def self.deduplicate_declarations(declarations)
  duplicate_groups = declarations
                     .group_by { |d| deduplication_key(d) }
                     .values

  duplicate_groups.map do |group|
    # Put extended type (if present) before extensions
    merge_declarations(group)
  end
end

.deduplication_key(decl) ⇒ Object

Two declarations get merged if they have the same deduplication key.



331
332
333
334
335
336
337
# File 'lib/jazzy/sourcekitten.rb', line 331

def self.deduplication_key(decl)
  if decl.type.swift_extensible? || decl.type.swift_extension?
    [decl.usr]
  else
    [decl.usr, decl.type.kind]
  end
end

.doc_coverageObject

rubocop:enable Metrics/PerceivedComplexity rubocop:enable Metrics/CyclomaticComplexity rubocop:enable Metrics/MethodLength



307
308
309
310
311
# File 'lib/jazzy/sourcekitten.rb', line 307

def self.doc_coverage
  return 0 if @documented_count == 0 && @undocumented_tokens.count == 0
  (100 * @documented_count) /
    (@undocumented_tokens.count + @documented_count)
end

.documented_child?(doc) ⇒ Boolean

Returns:

  • (Boolean)


154
155
156
157
# File 'lib/jazzy/sourcekitten.rb', line 154

def self.documented_child?(doc)
  return false unless doc['key.substructure']
  doc['key.substructure'].any? { |child| documented_child?(child) }
end

.filter_excluded_files(json) ⇒ Object



395
396
397
398
399
400
401
# File 'lib/jazzy/sourcekitten.rb', line 395

def self.filter_excluded_files(json)
  excluded_files = Config.instance.excluded_files
  json.map do |doc|
    key = doc.keys.first
    doc[key] unless excluded_files.include?(Pathname(key))
  end.compact
end

.group_custom_categories(docs) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/jazzy/sourcekitten.rb', line 28

def self.group_custom_categories(docs)
  group = Config.instance.custom_categories.map do |category|
    children = category['children'].flat_map do |name|
      docs_with_name, docs = docs.partition { |doc| doc.name == name }
      if docs_with_name.empty?
        STDERR.puts 'WARNING: No documented top-level declarations match ' \
                    "name \"#{name}\" specified in categories file"
      end
      docs_with_name
    end
    # Category config overrides alphabetization
    children.each.with_index { |child, i| child.nav_order = i }
    make_group(children, category['name'], '')
  end
  [group.compact, docs]
end

.group_docs(docs) ⇒ Object

Group root-level docs by custom categories (if any) and type



21
22
23
24
25
26
# File 'lib/jazzy/sourcekitten.rb', line 21

def self.group_docs(docs)
  custom_categories, docs = group_custom_categories(docs)
  type_categories, uncategorized = group_type_categories(
    docs, custom_categories.any? ? 'Other ' : '')
  custom_categories + type_categories + uncategorized
end

.group_type_categories(docs, type_category_prefix) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/jazzy/sourcekitten.rb', line 45

def self.group_type_categories(docs, type_category_prefix)
  group = SourceDeclaration::Type.all.map do |type|
    children, docs = docs.partition { |doc| doc.type == type }
    make_group(
      children,
      type_category_prefix + type.plural_name,
      "The following #{type.plural_name.downcase} are available globally.")
  end
  [group.compact, docs]
end

.make_default_doc_info(declaration) ⇒ Object



145
146
147
148
149
150
151
152
# File 'lib/jazzy/sourcekitten.rb', line 145

def self.make_default_doc_info(declaration)
  # @todo: Fix these
  declaration.line = 0
  declaration.column = 0
  declaration.abstract = 'Undocumented'
  declaration.parameters = []
  declaration.children = []
end

.make_doc_info(doc, declaration) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/jazzy/sourcekitten.rb', line 214

def self.make_doc_info(doc, declaration)
  return unless should_document?(doc)
  unless doc['key.doc.full_as_xml']
    return process_undocumented_token(doc, declaration)
  end

  declaration.line = doc['key.doc.line']
  declaration.column = doc['key.doc.column']
  declaration.declaration = Highlighter.highlight(
    doc['key.parsed_declaration'] || doc['key.doc.declaration'],
    Config.instance.objc_mode ? 'objc' : 'swift',
  )
  declaration.abstract = comment_from_doc(doc)
  declaration.discussion = ''
  declaration.return = make_paragraphs(doc, 'key.doc.result_discussion')

  declaration.parameters = parameters(doc)

  @documented_count += 1
end

.make_doc_urls(docs) ⇒ Hash

rubocop:disable Metrics/MethodLength Generate doc URL by prepending its parents URLs

Returns:

  • (Hash)

    input docs with URLs



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
# File 'lib/jazzy/sourcekitten.rb', line 68

def self.make_doc_urls(docs)
  docs.each do |doc|
    if !doc.parent_in_docs || doc.children.count > 0
      # Create HTML page for this doc if it has children or is root-level
      doc.url = (
        subdir_for_doc(doc) +
        [doc.name + '.html']
      ).join('/')
      doc.children = make_doc_urls(doc.children)
    else
      # Don't create HTML page for this doc if it doesn't have children
      # Instead, make its link a hash-link on its parent's page
      if doc.typename == '<<error type>>'
        warn 'A compile error prevented ' +
          doc.fully_qualified_name +
          ' from receiving a unique USR. Documentation may be ' \
          'incomplete. Please check for compile errors by running ' \
          "`xcodebuild #{Config.instance.xcodebuild_arguments.shelljoin}`."
      end
      id = doc.usr
      unless id
        id = doc.name || 'unknown'
        warn "`#{id}` has no USR. First make sure all modules used in " \
          'your project have been imported. If all used modules are ' \
          'imported, please report this problem by filing an issue at ' \
          'https://github.com/realm/jazzy/issues along with your Xcode ' \
          'project. If this token is declared in an `#if` block, please ' \
          'ignore this message.'
      end
      doc.url = doc.parent_in_docs.url + '#/' + id
    end
  end
end

.make_group(group, name, abstract) ⇒ Object



56
57
58
59
60
61
62
63
# File 'lib/jazzy/sourcekitten.rb', line 56

def self.make_group(group, name, abstract)
  SourceDeclaration.new.tap do |sd|
    sd.type     = SourceDeclaration::Type.overview
    sd.name     = name
    sd.abstract = abstract
    sd.children = group
  end unless group.empty?
end

.make_paragraphs(doc, key) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/jazzy/sourcekitten.rb', line 188

def self.make_paragraphs(doc, key)
  return nil unless doc[key]
  doc[key].map do |p|
    if para = p['Para']
      Jazzy.markdown.render(para)
    elsif code = p['Verbatim'] || p['CodeListing']
      Jazzy.markdown.render("```\n#{code}```\n")
    else
      warn "Jazzy could not recognize the `#{p.keys.first}` tag. " \
           'Please report this by filing an issue at ' \
           'https://github.com/realm/jazzy/issues along with the comment ' \
           'including this tag.'
      Jazzy.markdown.render(p.values.first)
    end
  end.join
end

.make_source_declarations(docs, parent = nil) ⇒ Object

rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity



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
# File 'lib/jazzy/sourcekitten.rb', line 260

def self.make_source_declarations(docs, parent = nil)
  declarations = []
  current_mark = SourceMark.new
  Array(docs).each do |doc|
    if doc.key?('key.diagnostic_stage')
      declarations += make_source_declarations(
        doc['key.substructure'], parent)
      next
    end
    declaration = SourceDeclaration.new
    declaration.parent_in_code = parent
    declaration.type = SourceDeclaration::Type.new(doc['key.kind'])
    declaration.typename = doc['key.typename']
    current_mark = SourceMark.new(doc['key.name']) if declaration.type.mark?
    if declaration.type.swift_enum_case?
      # Enum "cases" are thin wrappers around enum "elements".
      declarations += make_source_declarations(
        doc['key.substructure'], parent)
      next
    end
    next unless declaration.type.should_document?

    unless declaration.type.name
      raise 'Please file an issue at ' \
            'https://github.com/realm/jazzy/issues about adding support ' \
            "for `#{declaration.type.kind}`."
    end

    declaration.file = Pathname(doc['key.filepath']) if doc['key.filepath']
    declaration.usr  = doc['key.usr']
    declaration.name = doc['key.name']
    declaration.mark = current_mark
    declaration.access_control_level =
      SourceDeclaration::AccessControlLevel.from_doc(doc)
    declaration.start_line = doc['key.parsed_scope.start']
    declaration.end_line = doc['key.parsed_scope.end']

    next unless make_doc_info(doc, declaration)
    make_substructure(doc, declaration)
    declarations << declaration
  end
  declarations
end

.make_substructure(doc, declaration) ⇒ Object



246
247
248
249
250
251
252
253
254
255
# File 'lib/jazzy/sourcekitten.rb', line 246

def self.make_substructure(doc, declaration)
  if doc['key.substructure']
    declaration.children = make_source_declarations(
      doc['key.substructure'],
      declaration,
    )
  else
    declaration.children = []
  end
end

.mark_members_from_protocol_extension(extensions) ⇒ Object

Protocol methods provided only in an extension and not in the protocol itself are a special beast: they do not use dynamic dispatch. These get an “Extension method” annotation in the generated docs.



387
388
389
390
391
392
393
# File 'lib/jazzy/sourcekitten.rb', line 387

def self.mark_members_from_protocol_extension(extensions)
  extensions.each do |ext|
    ext.children.each do |ext_member|
      ext_member.from_protocol_extension = true
    end
  end
end

.merge_declarations(decls) ⇒ Object

Merges all of the given types and extensions into a single document.



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
# File 'lib/jazzy/sourcekitten.rb', line 340

def self.merge_declarations(decls)
  extensions, typedecls = decls.partition { |d| d.type.swift_extension? }

  if typedecls.size > 1
    warn 'Found conflicting type declarations with the same name, which ' \
      'may indicate a build issue or a bug in Jazzy: ' +
      typedecls.map { |t| "#{t.type.name.downcase} #{t.name}" }.join(', ')
  end
  typedecl = typedecls.first

  if typedecl && typedecl.type.swift_protocol?
    merge_default_implementations_into_protocol(typedecl, extensions)
    mark_members_from_protocol_extension(extensions)
    extensions.reject! { |ext| ext.children.empty? }
  end

  decls = typedecls + extensions
  decls.first.tap do |merged|
    merged.children = deduplicate_declarations(
      decls.flat_map(&:children).uniq)
    merged.children.each do |child|
      child.parent_in_code = merged
    end
  end
end

.merge_default_implementations_into_protocol(protocol, extensions) ⇒ Object

If any of the extensions provide default implementations for methods in the given protocol, merge those members into the protocol doc instead of keeping them on the extension. These get a “Default implementation” annotation in the generated docs.



370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/jazzy/sourcekitten.rb', line 370

def self.merge_default_implementations_into_protocol(protocol, extensions)
  protocol.children.each do |proto_method|
    extensions.each do |ext|
      defaults, ext.children = ext.children.partition do |ext_member|
        ext_member.name == proto_method.name
      end
      unless defaults.empty?
        proto_method.default_impl_abstract =
          defaults.flat_map { |d| [d.abstract, d.discussion] }.join("\n\n")
      end
    end
  end
end

.name_match(name_part, docs) ⇒ Object



403
404
405
406
407
408
409
410
411
412
# File 'lib/jazzy/sourcekitten.rb', line 403

def self.name_match(name_part, docs)
  return nil unless name_part
  wildcard_expansion = Regexp.escape(name_part)
                       .gsub('\.\.\.', '[^)]*')
                       .gsub(/&lt;.*&gt;/, '')
  whole_name_pat = /\A#{wildcard_expansion}\Z/
  docs.find do |doc|
    whole_name_pat =~ doc.name
  end
end

.name_traversal(name_parts, doc) ⇒ Object



424
425
426
427
428
429
430
# File 'lib/jazzy/sourcekitten.rb', line 424

def self.name_traversal(name_parts, doc)
  while doc && !name_parts.empty?
    next_part = name_parts.shift
    doc = name_match(next_part, doc.children)
  end
  doc
end

.parameters(doc) ⇒ Object



205
206
207
208
209
210
211
212
# File 'lib/jazzy/sourcekitten.rb', line 205

def self.parameters(doc)
  (doc['key.doc.parameters'] || []).map do |p|
    {
      name: p['name'],
      discussion: make_paragraphs(p, 'discussion'),
    }
  end
end

.parse(sourcekitten_output, min_acl, skip_undocumented) ⇒ Hash

Parse sourcekitten STDOUT output as JSON

Returns:

  • (Hash)

    structured docs



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/jazzy/sourcekitten.rb', line 479

def self.parse(sourcekitten_output, min_acl, skip_undocumented)
  @min_acl = min_acl
  @skip_undocumented = skip_undocumented
  sourcekitten_json = filter_excluded_files(JSON.parse(sourcekitten_output))
  docs = make_source_declarations(sourcekitten_json)
  docs = ungrouped_docs = deduplicate_declarations(docs)
  docs = group_docs(docs)
  if Config.instance.objc_mode
    docs = reject_objc_enum_typedefs(docs)
  else
    # Remove top-level enum cases because it means they have an ACL lower
    # than min_acl
    docs = docs.reject { |doc| doc.type.swift_enum_element? }
  end
  make_doc_urls(docs)
  autolink(docs, ungrouped_docs)
  [docs, doc_coverage, @undocumented_tokens]
end

.process_undocumented_token(doc, declaration) ⇒ Object



177
178
179
180
181
182
183
184
185
186
# File 'lib/jazzy/sourcekitten.rb', line 177

def self.process_undocumented_token(doc, declaration)
  source_directory = Config.instance.source_directory.to_s
  filepath = doc['key.filepath']
  objc = Config.instance.objc_mode
  if filepath && (filepath.start_with?(source_directory) || objc)
    @undocumented_tokens << doc
  end
  return nil if !documented_child?(doc) && @skip_undocumented
  make_default_doc_info(declaration)
end

.reject_objc_enum_typedefs(docs) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
# File 'lib/jazzy/sourcekitten.rb', line 465

def self.reject_objc_enum_typedefs(docs)
  enums = docs.flat_map do |doc|
    doc.children.select { |child| child.type.objc_enum? }.map(&:name)
  end
  docs.map do |doc|
    doc.children = doc.children.reject do |child|
      child.type.objc_typedef? && enums.include?(child.name)
    end
    doc
  end
end

.run_sourcekitten(arguments) ⇒ Object

Run sourcekitten with given arguments and return STDOUT



134
135
136
137
138
139
140
141
142
143
# File 'lib/jazzy/sourcekitten.rb', line 134

def self.run_sourcekitten(arguments)
  swift_version = Config.instance.swift_version
  unless xcode = XCInvoke::Xcode.find_swift_version(swift_version)
    raise "Unable to find an Xcode with swift version #{swift_version}."
  end
  bin_path = Pathname(__FILE__).parent + 'SourceKitten/bin/sourcekitten'
  output, = Executable.execute_command(bin_path, arguments, true,
                                       env: xcode.as_env)
  output
end

.should_document?(doc) ⇒ Boolean

Returns:

  • (Boolean)


159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/jazzy/sourcekitten.rb', line 159

def self.should_document?(doc)
  return false if doc['key.doc.comment'].to_s.include?(':nodoc:')

  # Always document Objective-C declarations.
  return true if Config.instance.objc_mode

  # Document extensions & enum elements, since we can't tell their ACL.
  type = SourceDeclaration::Type.new(doc['key.kind'])
  return true if type.swift_enum_element?
  if type.swift_extension?
    return Array(doc['key.substructure']).any? do |subdoc|
      should_document?(subdoc)
    end
  end

  SourceDeclaration::AccessControlLevel.from_doc(doc) >= @min_acl
end

.subdir_for_doc(doc) ⇒ Object

Determine the subdirectory in which a doc should be placed



104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/jazzy/sourcekitten.rb', line 104

def self.subdir_for_doc(doc)
  # We always want to create top-level subdirs according to type (Struct,
  # Class, etc).
  top_level_decl = doc.namespace_path.first
  if top_level_decl && top_level_decl.type && top_level_decl.type.name
    # File program elements under top ancestor’s type (Struct, Class, etc.)
    [top_level_decl.type.plural_name] + doc.namespace_ancestors.map(&:name)
  else
    # Categories live in their own directory
    []
  end
end