Module: Jazzy::SourceKitten
- Defined in:
- lib/jazzy/sourcekitten.rb
Overview
This module interacts with the sourcekitten command-line executable
Constant Summary collapse
- DEFAULT_ATTRIBUTES =
Strip default property attributes because libclang adds them all, even if absent in the original source code.
%w[atomic readwrite assign unsafe_unretained].freeze
- AUTOLINK_TEXT_FIELDS =
rubocop:enable Metrics/MethodLength
%w[return abstract unavailable_message deprecation_message].freeze
- AUTOLINK_HIGHLIGHT_FIELDS =
%w[declaration other_language_declaration].freeze
Class Method Summary collapse
-
.ancestor_name_match(name_part, doc) ⇒ Object
Find the first ancestor of doc whose name matches name_part.
-
.arguments_from_options(options) ⇒ Object
Builds SourceKitten arguments based on Jazzy options.
-
.attribute_regexp(name) ⇒ Object
Regexp to match an @attribute.
- .autolink(docs, root_decls) ⇒ Object
-
.autolink_document(html, doc) ⇒ Object
For autolinking external markdown documents.
- .autolink_highlight_fields(doc, root_decls) ⇒ Object
-
.autolink_text(text, doc, root_decls, after_highlight: false) ⇒ Object
Links recognized top-level declarations within - inlined code within docs - method signatures after they’ve been processed by the highlighter.
- .autolink_text_fields(doc, root_decls) ⇒ Object
- .availability_attribute?(doc) ⇒ Boolean
-
.deduplicate_declarations(declarations) ⇒ Object
Merges multiple extensions of the same entity into a single document.
-
.deduplication_key(decl, root_decls) ⇒ Object
Two declarations get merged if they have the same deduplication key.
- .expand_extension(extension, name_parts, decls) ⇒ Object
-
.expand_extensions(decls) ⇒ Object
Expands extensions of nested types declared at the top level into a tree so they can be deduplicated properly.
-
.extract_attributes(declaration, name = '\w+') ⇒ Object
Get all attributes of some name.
- .extract_availability(declaration) ⇒ Object
-
.filter_excluded_files(json) ⇒ Object
Filter based on the “excluded” flag.
-
.filter_files(json) ⇒ Object
Apply filtering based on the “included” and “excluded” flags.
-
.filter_included_files(json) ⇒ Object
Filter based on the “included” flag.
-
.find_generic_requirements(parsed_declaration) ⇒ Object
rubocop:enable Metrics/PerceivedComplexity rubocop:enable Metrics/CyclomaticComplexity rubocop:enable Metrics/MethodLength.
-
.fix_up_compiler_decl(annotated_decl, declaration) ⇒ Object
Apply fixes to improve the compiler’s declaration.
- .group_custom_categories(docs) ⇒ Object
-
.group_docs(docs) ⇒ Object
Group root-level docs by custom categories (if any) and type.
- .group_type_categories(docs, type_category_prefix) ⇒ Object
- .highlight_declaration(doc, declaration) ⇒ Object
- .make_default_doc_info(declaration) ⇒ Object
- .make_deprecation_info(doc, declaration) ⇒ Object
- .make_doc_info(doc, declaration) ⇒ Object
-
.make_doc_urls(docs) ⇒ Hash
rubocop:disable Metrics/MethodLength Generate doc URL by prepending its parents URLs.
- .make_group(group, name, abstract, url_name = nil) ⇒ Object
- .make_objc_declaration(declaration) ⇒ Object
-
.make_source_declarations(docs, parent = nil, mark = SourceMark.new) ⇒ Object
rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity.
- .make_substructure(doc, declaration) ⇒ Object
-
.make_swift_declaration(doc, declaration) ⇒ Object
Find the best Swift declaration.
-
.mark_and_merge_protocol_extensions(protocol, extensions) ⇒ Object
Protocol extensions.
-
.merge_categories(categories) ⇒ Object
Join categories with the same name (eg. ObjC and Swift classes).
-
.merge_code_declaration(decls) ⇒ Object
Merge useful information added by extensions into the main declaration: public protocol conformances and, for top-level extensions, further conditional extensions of the same type.
-
.merge_consecutive_marks(docs) ⇒ Object
Merge consecutive sections with the same mark into one section.
-
.merge_declarations(decls) ⇒ Object
rubocop:disable Metrics/MethodLength rubocop:disable Metrics/PerceivedComplexity Merges all of the given types and extensions into a single document.
-
.merge_objc_declaration_marks(typedecl, extensions) ⇒ Object
Mark children merged from categories with the name of category (unless they already have a mark).
-
.merge_type_and_extensions(typedecls, extensions) ⇒ Object
rubocop:enable Metrics/PerceivedComplexity rubocop:enable Metrics/MethodLength.
-
.mergeable_objc?(decl, root_decls) ⇒ Boolean
Returns true if an Objective-C declaration is mergeable.
-
.mergeable_swift?(decl) ⇒ Boolean
Returns if a Swift declaration is mergeable.
-
.move_merged_extension_marks(decls) ⇒ Object
For each extension to be merged, move any MARK from the extension declaration down to the extension contents so it still shows up.
- .name_match(name_part, docs) ⇒ Object
- .name_traversal(name_parts, doc) ⇒ Object
- .objc_arguments_from_options(options) ⇒ Object
- .parameters(doc, discovered) ⇒ Object
-
.parse(sourcekitten_output, min_acl, skip_undocumented, inject_docs) ⇒ Hash
Parse sourcekitten STDOUT output as JSON.
- .prefer_parsed_decl?(parsed, annotated, type) ⇒ Boolean
- .process_undocumented_token(doc, declaration) ⇒ Object
-
.rec_path(path) ⇒ Object
returns all subdirectories of specified path.
-
.reject_inaccessible_extensions(typedecl, extensions) ⇒ Object
Now we know all the public types and all the private protocols, reject extensions that add public protocols to private types or add private protocols to public types.
- .reject_objc_types(docs) ⇒ Object
-
.run_sourcekitten(arguments) ⇒ Object
Run sourcekitten with given arguments and return STDOUT.
- .sanitize_filename(doc) ⇒ Object
- .should_document?(doc) ⇒ Boolean
- .should_document_swift_extension?(doc) ⇒ Boolean
-
.should_mark_undocumented(declaration) ⇒ Object
Call things undocumented if they were compiled properly and came from our module.
-
.split_decl_attributes(declaration) ⇒ Object
Split leading attributes from a decl, returning both parts.
-
.subdir_for_doc(doc) ⇒ Object
Determine the subdirectory in which a doc should be placed.
- .undocumented_abstract ⇒ Object
- .use_spm?(options) ⇒ Boolean
-
.xml_to_text(xml) ⇒ Object
Strip tags and convert entities.
Class Method Details
.ancestor_name_match(name_part, doc) ⇒ Object
Find the first ancestor of doc whose name matches name_part.
903 904 905 906 907 908 909 910 |
# File 'lib/jazzy/sourcekitten.rb', line 903 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
222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/jazzy/sourcekitten.rb', line 222 def self.() arguments = ['doc'] if .objc_mode arguments += () else arguments += ['--spm'] if use_spm?() unless .module_name.empty? arguments += ['--module-name', .module_name] end arguments += ['--'] end arguments + .build_tool_arguments end |
.attribute_regexp(name) ⇒ Object
Regexp to match an @attribute. Complex to handle @available().
411 412 413 414 415 416 417 418 419 420 421 |
# File 'lib/jazzy/sourcekitten.rb', line 411 def self.attribute_regexp(name) qstring = /"(?:[^"\\]*|\\.)*"/ %r{@#{name} # @attr name (?:\s*\( # optionally followed by spaces + parens, (?: # containing any number of either.. [^")]*| # normal characters or... #{qstring} # quoted strings. )* # (end parens content) \))? # (end optional parens) }x end |
.autolink(docs, root_decls) ⇒ Object
994 995 996 997 998 999 1000 1001 |
# File 'lib/jazzy/sourcekitten.rb', line 994 def self.autolink(docs, root_decls) @autolink_root_decls = root_decls docs.each do |doc| doc.children = autolink(doc.children, root_decls) autolink_text_fields(doc, root_decls) autolink_highlight_fields(doc, root_decls) end end |
.autolink_document(html, doc) ⇒ Object
For autolinking external markdown documents
1004 1005 1006 |
# File 'lib/jazzy/sourcekitten.rb', line 1004 def self.autolink_document(html, doc) autolink_text(html, doc, @autolink_root_decls || []) end |
.autolink_highlight_fields(doc, root_decls) ⇒ Object
985 986 987 988 989 990 991 992 |
# File 'lib/jazzy/sourcekitten.rb', line 985 def self.autolink_highlight_fields(doc, root_decls) AUTOLINK_HIGHLIGHT_FIELDS.each do |field| if text = doc.send(field) doc.send(field + '=', autolink_text(text, doc, root_decls, after_highlight: true)) end end end |
.autolink_text(text, doc, root_decls, after_highlight: false) ⇒ Object
Links recognized top-level declarations within
-
inlined code within docs
-
method signatures after they’ve been processed by the highlighter
The ‘after_highlight` flag is used to differentiate between the two modes.
DocC link format - follow Xcode and don’t display slash-separated parts. rubocop:disable Metrics/MethodLength
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 |
# File 'lib/jazzy/sourcekitten.rb', line 928 def self.autolink_text(text, doc, root_decls, after_highlight: false) text.autolink_block(doc.url, '[^\s]+', after_highlight) do |raw_name| sym_name = (raw_name[/^<doc:(.*)>$/, 1] || raw_name).sub(/(?<!^)-.+$/, '') parts = sym_name .sub(/^@/, '') # ignore for custom attribute ref .split(%r{(?<!\.)[/.](?!\.)}) # dot or slash, but not '...' .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 subsequent components, if any [name_traversal(parts, name_root), sym_name.sub(%r{^.*/}, '')] end.autolink_block(doc.url, '[+-]\[\w+(?: ?\(\w+\))? [\w:]+\]', after_highlight) do |raw_name| match = raw_name.match(/([+-])\[(\w+(?: ?\(\w+\))?) ([\w:]+)\]/) # Subject component can match any ancestor or top-level doc subject = match[2].delete(' ') name_root = ancestor_name_match(subject, doc) || name_match(subject, root_decls) if name_root # Look up the verb in the subject’s children [name_match(match[1] + match[3], name_root.children), raw_name] end end.autolink_block(doc.url, '[+-]\w[\w:]*', after_highlight) do |raw_name| [name_match(raw_name, doc.children), raw_name] end end |
.autolink_text_fields(doc, root_decls) ⇒ Object
969 970 971 972 973 974 975 976 977 978 979 980 |
# File 'lib/jazzy/sourcekitten.rb', line 969 def self.autolink_text_fields(doc, root_decls) AUTOLINK_TEXT_FIELDS.each do |field| if text = doc.send(field) doc.send(field + '=', autolink_text(text, doc, root_decls)) end end (doc.parameters || []).each do |param| param[:discussion] = autolink_text(param[:discussion], doc, root_decls) end end |
.availability_attribute?(doc) ⇒ Boolean
280 281 282 283 284 285 286 |
# File 'lib/jazzy/sourcekitten.rb', line 280 def self.availability_attribute?(doc) return false unless doc['key.attributes'] !doc['key.attributes'].select do |attribute| attribute.values.first == 'source.decl.attribute.available' end.empty? 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.
649 650 651 652 653 654 655 656 657 658 |
# File 'lib/jazzy/sourcekitten.rb', line 649 def self.deduplicate_declarations(declarations) duplicate_groups = declarations .group_by { |d| deduplication_key(d, declarations) } .values duplicate_groups.flat_map do |group| # Put extended type (if present) before extensions merge_declarations(group) end.compact end |
.deduplication_key(decl, root_decls) ⇒ Object
Two declarations get merged if they have the same deduplication key.
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 |
# File 'lib/jazzy/sourcekitten.rb', line 676 def self.deduplication_key(decl, root_decls) # Swift extension of objc class if decl.swift_objc_extension? [decl.swift_extension_objc_name, :objc_class_and_categories] # Swift type or Swift extension of Swift type elsif mergeable_swift?(decl) [decl.usr, decl.name] # Objc categories and classes elsif mergeable_objc?(decl, root_decls) # Using the ObjC name to match swift_objc_extension. name, _ = decl.objc_category_name || decl.objc_name [name, :objc_class_and_categories] # Non-mergable declarations (funcs, typedefs etc...) else [decl.usr, decl.name, decl.type.kind] end end |
.expand_extension(extension, name_parts, decls) ⇒ Object
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 |
# File 'lib/jazzy/sourcekitten.rb', line 623 def self.(extension, name_parts, decls) return extension if name_parts.empty? name = name_parts.shift candidates = decls.select { |decl| decl.name == name } SourceDeclaration.new.tap do |decl| make_default_doc_info(decl) decl.name = name decl.modulename = extension.modulename decl.type = extension.type decl.mark = extension.mark decl.usr = candidates.first.usr unless candidates.empty? child = (extension, name_parts, candidates.flat_map(&:children).uniq) child.parent_in_code = decl decl.children = [child] end end |
.expand_extensions(decls) ⇒ Object
Expands extensions of nested types declared at the top level into a tree so they can be deduplicated properly
609 610 611 612 613 614 615 616 617 618 619 620 621 |
# File 'lib/jazzy/sourcekitten.rb', line 609 def self.(decls) decls.map do |decl| next decl unless decl.type.extension? && decl.name.include?('.') # Don't expand the Swift namespace if we're in ObjC mode. # ex: NS_SWIFT_NAME(Foo.Bar) should not create top-level Foo next decl if decl.swift_objc_extension? && !Config.instance.hide_objc? name_parts = decl.name.split('.') decl.name = name_parts.pop (decl, name_parts, decls) end end |
.extract_attributes(declaration, name = '\w+') ⇒ Object
Get all attributes of some name
424 425 426 427 428 |
# File 'lib/jazzy/sourcekitten.rb', line 424 def self.extract_attributes(declaration, name = '\w+') attrs = declaration.scan(attribute_regexp(name)) # Rouge #806 workaround, use unicode lookalike for ')' inside attributes. attrs.map { |str| str.gsub(/\)(?!\s*$)/, "\ufe5a") } end |
.extract_availability(declaration) ⇒ Object
430 431 432 |
# File 'lib/jazzy/sourcekitten.rb', line 430 def self.extract_availability(declaration) extract_attributes(declaration, 'available') end |
.filter_excluded_files(json) ⇒ Object
Filter based on the “excluded” flag.
879 880 881 882 883 884 885 886 887 |
# File 'lib/jazzy/sourcekitten.rb', line 879 def self.filter_excluded_files(json) excluded_files = Config.instance.excluded_files json.map do |doc| key = doc.keys.first doc unless excluded_files.detect do |exclude| File.fnmatch?(exclude, key) end end.compact end |
.filter_files(json) ⇒ Object
Apply filtering based on the “included” and “excluded” flags.
858 859 860 861 862 863 864 865 |
# File 'lib/jazzy/sourcekitten.rb', line 858 def self.filter_files(json) json = filter_included_files(json) if Config.instance.included_files.any? json = filter_excluded_files(json) if Config.instance.excluded_files.any? json.map do |doc| key = doc.keys.first doc[key] end.compact end |
.filter_included_files(json) ⇒ Object
Filter based on the “included” flag.
868 869 870 871 872 873 874 875 876 |
# File 'lib/jazzy/sourcekitten.rb', line 868 def self.filter_included_files(json) included_files = Config.instance.included_files json.map do |doc| key = doc.keys.first doc if included_files.detect do |include| File.fnmatch?(include, key) end end.compact end |
.find_generic_requirements(parsed_declaration) ⇒ Object
rubocop:enable Metrics/PerceivedComplexity rubocop:enable Metrics/CyclomaticComplexity rubocop:enable Metrics/MethodLength
600 601 602 603 604 605 |
# File 'lib/jazzy/sourcekitten.rb', line 600 def self.find_generic_requirements(parsed_declaration) parsed_declaration =~ /\bwhere\s+(.*)$/m return nil unless Regexp.last_match Regexp.last_match[1].gsub(/\s+/, ' ') end |
.fix_up_compiler_decl(annotated_decl, declaration) ⇒ Object
Apply fixes to improve the compiler’s declaration
452 453 454 455 456 457 458 459 460 461 |
# File 'lib/jazzy/sourcekitten.rb', line 452 def self.fix_up_compiler_decl(annotated_decl, declaration) annotated_decl. # Replace the fully qualified name of a type with its base name gsub(declaration.fully_qualified_name_regexp, declaration.name). # Workaround for SR-9816 gsub(" {\n get\n }", ''). # Workaround for SR-12139 gsub(/mutating\s+mutating/, 'mutating') end |
.group_custom_categories(docs) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/jazzy/sourcekitten.rb', line 73 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? warn '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
64 65 66 67 68 69 70 71 |
# File 'lib/jazzy/sourcekitten.rb', line 64 def self.group_docs(docs) custom_categories, docs = group_custom_categories(docs) unlisted_prefix = Config.instance.custom_categories_unlisted_prefix type_categories, uncategorized = group_type_categories( docs, custom_categories.any? ? unlisted_prefix : '' ) custom_categories + merge_categories(type_categories) + uncategorized end |
.group_type_categories(docs, type_category_prefix) ⇒ Object
90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/jazzy/sourcekitten.rb', line 90 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.", type_category_prefix + type.plural_url_name, ) end [group.compact, docs] end |
.highlight_declaration(doc, declaration) ⇒ Object
377 378 379 380 381 382 383 384 385 386 387 388 389 |
# File 'lib/jazzy/sourcekitten.rb', line 377 def self.highlight_declaration(doc, declaration) if declaration.swift? declaration.declaration = Highlighter.highlight_swift(make_swift_declaration(doc, declaration)) else declaration.declaration = Highlighter.highlight_objc( make_objc_declaration(doc['key.parsed_declaration']), ) declaration.other_language_declaration = Highlighter.highlight_swift(doc['key.swift_declaration']) end end |
.make_default_doc_info(declaration) ⇒ Object
273 274 275 276 277 278 |
# File 'lib/jazzy/sourcekitten.rb', line 273 def self.make_default_doc_info(declaration) # @todo: Fix these declaration.abstract = '' declaration.parameters = [] declaration.children = [] end |
.make_deprecation_info(doc, declaration) ⇒ Object
391 392 393 394 395 396 397 398 399 400 |
# File 'lib/jazzy/sourcekitten.rb', line 391 def self.make_deprecation_info(doc, declaration) if declaration.deprecated declaration. = Markdown.render(doc['key.deprecation_message'] || '') end if declaration.unavailable declaration. = Markdown.render(doc['key.unavailable_message'] || '') end end |
.make_doc_info(doc, declaration) ⇒ Object
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/jazzy/sourcekitten.rb', line 358 def self.make_doc_info(doc, declaration) return unless should_document?(doc) highlight_declaration(doc, declaration) make_deprecation_info(doc, declaration) unless doc['key.doc.full_as_xml'] return process_undocumented_token(doc, declaration) end declaration.abstract = Markdown.render(doc['key.doc.comment'] || '', declaration.highlight_language) declaration.discussion = '' declaration.return = Markdown.rendered_returns declaration.parameters = parameters(doc, Markdown.rendered_parameters) @stats.add_documented end |
.make_doc_urls(docs) ⇒ Hash
rubocop:disable Metrics/MethodLength Generate doc URL by prepending its parents URLs
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 |
# File 'lib/jazzy/sourcekitten.rb', line 154 def self.make_doc_urls(docs) docs.each do |doc| if doc.render_as_page? doc.url = ( subdir_for_doc(doc) + [sanitize_filename(doc) + '.html'] ).map { |path| ERB::Util.url_encode(path) }.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` or `swift build` with arguments ' \ "`#{Config.instance.build_tool_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, url_name = nil) ⇒ Object
116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/jazzy/sourcekitten.rb', line 116 def self.make_group(group, name, abstract, url_name = nil) group.reject! { |doc| doc.name.empty? } unless group.empty? SourceDeclaration.new.tap do |sd| sd.type = SourceDeclaration::Type.overview sd.name = name sd.url_name = url_name sd.abstract = Markdown.render(abstract) sd.children = group end end end |
.make_objc_declaration(declaration) ⇒ Object
502 503 504 505 506 507 508 509 510 511 512 513 514 |
# File 'lib/jazzy/sourcekitten.rb', line 502 def self.make_objc_declaration(declaration) return declaration if Config.instance.keep_property_attributes declaration =~ /\A@property\s+\((.*?)\)/ return declaration unless Regexp.last_match attrs = Regexp.last_match[1].split(',').map(&:strip) - DEFAULT_ATTRIBUTES attrs_text = attrs.empty? ? '' : " (#{attrs.join(', ')})" declaration .sub(/(?<=@property)\s+\(.*?\)/, attrs_text) .gsub(/\s+/, ' ') end |
.make_source_declarations(docs, parent = nil, mark = SourceMark.new) ⇒ Object
rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
# File 'lib/jazzy/sourcekitten.rb', line 527 def self.make_source_declarations(docs, parent = nil, mark = SourceMark.new) declarations = [] current_mark = mark 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'] declaration.objc_name = doc['key.name'] documented_name = if Config.instance.hide_objc? && doc['key.swift_name'] doc['key.swift_name'] else declaration.objc_name end if declaration.type.task_mark?(documented_name) current_mark = SourceMark.new(documented_name) end if declaration.type.swift_enum_case? # Enum "cases" are thin wrappers around enum "elements". declarations += make_source_declarations( doc['key.substructure'], parent, current_mark ) 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.type_usr = doc['key.typeusr'] declaration.modulename = doc['key.modulename'] declaration.name = documented_name declaration.mark = current_mark declaration.access_control_level = SourceDeclaration::AccessControlLevel.from_doc(doc) declaration.line = doc['key.doc.line'] || doc['key.line'] declaration.column = doc['key.doc.column'] || doc['key.column'] declaration.start_line = doc['key.parsed_scope.start'] declaration.end_line = doc['key.parsed_scope.end'] declaration.deprecated = doc['key.always_deprecated'] declaration.unavailable = doc['key.always_unavailable'] declaration.generic_requirements = find_generic_requirements(doc['key.parsed_declaration']) inherited_types = doc['key.inheritedtypes'] || [] declaration.inherited_types = inherited_types.map { |type| type['key.name'] }.compact next unless make_doc_info(doc, declaration) declaration.children = make_substructure(doc, declaration) next if declaration.type.extension? && declaration.children.empty? && !declaration.inherited_types? declarations << declaration end declarations end |
.make_substructure(doc, declaration) ⇒ Object
516 517 518 519 520 521 522 |
# File 'lib/jazzy/sourcekitten.rb', line 516 def self.make_substructure(doc, declaration) return [] unless subdocs = doc['key.substructure'] make_source_declarations(subdocs, declaration, declaration.mark_for_children) end |
.make_swift_declaration(doc, declaration) ⇒ Object
Find the best Swift declaration
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
# File 'lib/jazzy/sourcekitten.rb', line 464 def self.make_swift_declaration(doc, declaration) # From compiler 'quick help' style annotated_decl_xml = doc['key.annotated_decl'] return nil unless annotated_decl_xml annotated_decl_attrs, annotated_decl_body = split_decl_attributes(xml_to_text(annotated_decl_xml)) # From source code parsed_decl = doc['key.parsed_declaration'] # Don't present type attributes on extensions return parsed_decl if declaration.type.extension? decl = if prefer_parsed_decl?(parsed_decl, annotated_decl_body, declaration.type) # Strip any attrs captured by parsed version inline_attrs, parsed_decl_body = split_decl_attributes(parsed_decl) parsed_decl_body.unindent(inline_attrs.length) else # Improve the compiler declaration fix_up_compiler_decl(annotated_decl_body, declaration) end # @available attrs only in compiler 'interface' style extract_availability(doc['key.doc.declaration'] || '') .concat(extract_attributes(annotated_decl_attrs)) .push(decl) .join("\n") end |
.mark_and_merge_protocol_extensions(protocol, extensions) ⇒ Object
Protocol extensions.
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. Default implementations added by conditional extensions are annotated but listed separately.
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.
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 |
# File 'lib/jazzy/sourcekitten.rb', line 789 def self.mark_and_merge_protocol_extensions(protocol, extensions) extensions.each do |ext| ext.children = ext.children.select do |ext_member| proto_member = protocol.children.find do |p| p.name == ext_member.name && p.type == ext_member.type end # Extension-only method, keep. unless proto_member ext_member.from_protocol_extension = true next true end # Default impl but constrained, mark and keep. if ext.constrained_extension? ext_member.default_impl_abstract = ext_member.abstract ext_member.abstract = nil next true end # Default impl for all users, merge. proto_member.default_impl_abstract = ext_member.abstract next false end end end |
.merge_categories(categories) ⇒ Object
Join categories with the same name (eg. ObjC and Swift classes)
104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/jazzy/sourcekitten.rb', line 104 def self.merge_categories(categories) merged = [] categories.each do |new_category| if existing = merged.find { |c| c.name == new_category.name } existing.children += new_category.children else merged.append(new_category) end end merged end |
.merge_code_declaration(decls) ⇒ Object
Merge useful information added by extensions into the main declaration: public protocol conformances and, for top-level extensions, further conditional extensions of the same type.
843 844 845 846 847 848 849 850 851 852 853 854 855 |
# File 'lib/jazzy/sourcekitten.rb', line 843 def self.merge_code_declaration(decls) first = decls.first declarations = decls[1..].select do |decl| decl.type.swift_extension? && (decl.other_inherited_types?(@inaccessible_protocols) || (first.type.swift_extension? && decl.constrained_extension?)) end.map(&:declaration) unless declarations.empty? first.declaration = declarations.prepend(first.declaration).uniq.join end end |
.merge_consecutive_marks(docs) ⇒ Object
Merge consecutive sections with the same mark into one section
130 131 132 133 134 135 136 137 138 139 |
# File 'lib/jazzy/sourcekitten.rb', line 130 def self.merge_consecutive_marks(docs) prev_mark = nil docs.each do |doc| if prev_mark&.can_merge?(doc.mark) doc.mark = prev_mark end prev_mark = doc.mark merge_consecutive_marks(doc.children) end end |
.merge_declarations(decls) ⇒ Object
rubocop:disable Metrics/MethodLength rubocop:disable Metrics/PerceivedComplexity Merges all of the given types and extensions into a single document.
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 |
# File 'lib/jazzy/sourcekitten.rb', line 697 def self.merge_declarations(decls) extensions, typedecls = decls.partition { |d| d.type.extension? } if typedecls.size > 1 info = typedecls .map { |t| "#{t.type.name.downcase} #{t.name}" } .join(', ') warn 'Found conflicting type declarations with the same name, which ' \ "may indicate a build issue or a bug in Jazzy: #{info}" end typedecl = typedecls.first extensions = reject_inaccessible_extensions(typedecl, extensions) if typedecl if typedecl.type.swift_protocol? mark_and_merge_protocol_extensions(typedecl, extensions) extensions.reject! { |ext| ext.children.empty? } end merge_objc_declaration_marks(typedecl, extensions) end # Keep type-aliases separate from any extensions if typedecl&.type&.swift_typealias? [merge_type_and_extensions(typedecls, []), merge_type_and_extensions([], extensions)] else merge_type_and_extensions(typedecls, extensions) end end |
.merge_objc_declaration_marks(typedecl, extensions) ⇒ Object
Mark children merged from categories with the name of category (unless they already have a mark)
818 819 820 821 822 823 824 825 |
# File 'lib/jazzy/sourcekitten.rb', line 818 def self.merge_objc_declaration_marks(typedecl, extensions) return unless typedecl.type.objc_class? extensions.each do |ext| _, category_name = ext.objc_category_name ext.children.each { |c| c.mark.name ||= category_name } end end |
.merge_type_and_extensions(typedecls, extensions) ⇒ Object
rubocop:enable Metrics/PerceivedComplexity rubocop:enable Metrics/MethodLength
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 |
# File 'lib/jazzy/sourcekitten.rb', line 731 def self.merge_type_and_extensions(typedecls, extensions) # Constrained extensions at the end constrained, regular_exts = extensions.partition(&:constrained_extension?) decls = typedecls + regular_exts + constrained return nil if decls.empty? move_merged_extension_marks(decls) merge_code_declaration(decls) 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 |
.mergeable_objc?(decl, root_decls) ⇒ Boolean
Returns true if an Objective-C declaration is mergeable.
661 662 663 664 665 |
# File 'lib/jazzy/sourcekitten.rb', line 661 def self.mergeable_objc?(decl, root_decls) decl.type.objc_class? \ || (decl.type.objc_category? \ && name_match(decl.objc_category_name[0], root_decls)) end |
.mergeable_swift?(decl) ⇒ Boolean
Returns if a Swift declaration is mergeable. Start off merging in typealiases to help understand extensions.
669 670 671 672 673 |
# File 'lib/jazzy/sourcekitten.rb', line 669 def self.mergeable_swift?(decl) decl.type.swift_extensible? || decl.type.swift_extension? || decl.type.swift_typealias? end |
.move_merged_extension_marks(decls) ⇒ Object
For each extension to be merged, move any MARK from the extension declaration down to the extension contents so it still shows up.
829 830 831 832 833 834 835 836 837 838 |
# File 'lib/jazzy/sourcekitten.rb', line 829 def self.move_merged_extension_marks(decls) return unless to_be_merged = decls[1..] to_be_merged.each do |ext| child = ext.children.first if child && child.mark.empty? child.mark.copy(ext.mark) end end end |
.name_match(name_part, docs) ⇒ Object
889 890 891 892 893 894 895 896 897 898 899 900 |
# File 'lib/jazzy/sourcekitten.rb', line 889 def self.name_match(name_part, docs) return nil unless name_part wildcard_expansion = Regexp.escape(name_part) .gsub('\.\.\.', '[^)]*') .gsub(/<.*>/, '') whole_name_pat = /\A#{wildcard_expansion}\Z/ docs.find do |doc| whole_name_pat =~ doc.name end end |
.name_traversal(name_parts, doc) ⇒ Object
912 913 914 915 916 917 918 |
# File 'lib/jazzy/sourcekitten.rb', line 912 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 |
.objc_arguments_from_options(options) ⇒ Object
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/jazzy/sourcekitten.rb', line 237 def self.() arguments = [] if .build_tool_arguments.empty? arguments += ['--objc', .umbrella_header.to_s, '--', '-x', 'objective-c', '-isysroot', `xcrun --show-sdk-path --sdk #{options.sdk}`.chomp, '-I', .framework_root.to_s, '-fmodules'] end # add additional -I arguments for each subdirectory of framework_root unless .framework_root.nil? rec_path(Pathname.new(.framework_root.to_s)).collect do |child| if child.directory? arguments += ['-I', child.to_s] end end end arguments end |
.parameters(doc, discovered) ⇒ Object
348 349 350 351 352 353 354 355 356 |
# File 'lib/jazzy/sourcekitten.rb', line 348 def self.parameters(doc, discovered) (doc['key.doc.parameters'] || []).map do |p| name = p['name'] { name: name, discussion: discovered[name], } end.reject { |param| param[:discussion].nil? } end |
.parse(sourcekitten_output, min_acl, skip_undocumented, inject_docs) ⇒ Hash
Parse sourcekitten STDOUT output as JSON
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 |
# File 'lib/jazzy/sourcekitten.rb', line 1025 def self.parse(sourcekitten_output, min_acl, skip_undocumented, inject_docs) @min_acl = min_acl @skip_undocumented = skip_undocumented @stats = Stats.new @inaccessible_protocols = [] sourcekitten_json = filter_files(JSON.parse(sourcekitten_output).flatten) docs = make_source_declarations(sourcekitten_json).concat inject_docs docs = (docs) docs = deduplicate_declarations(docs) docs = reject_objc_types(docs) # 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? } ungrouped_docs = docs docs = group_docs(docs) merge_consecutive_marks(docs) make_doc_urls(docs) autolink(docs, ungrouped_docs) [docs, @stats] end |
.prefer_parsed_decl?(parsed, annotated, type) ⇒ Boolean
440 441 442 443 444 445 446 447 448 449 |
# File 'lib/jazzy/sourcekitten.rb', line 440 def self.prefer_parsed_decl?(parsed, annotated, type) return true if annotated.empty? return false unless parsed return false if type.swift_variable? # prefer { get }-style annotated.include?(' = default') || # SR-2608 (parsed.scan(/@autoclosure|@escaping/).count > annotated.scan(/@autoclosure|@escaping/).count) || # SR-6321 parsed.include?("\n") # user formatting end |
.process_undocumented_token(doc, declaration) ⇒ Object
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/jazzy/sourcekitten.rb', line 332 def self.process_undocumented_token(doc, declaration) make_default_doc_info(declaration) if !declaration.swift? || should_mark_undocumented(declaration) @stats.add_undocumented(declaration) return nil if @skip_undocumented declaration.abstract = undocumented_abstract else declaration.abstract = Markdown.render(doc['key.doc.comment'] || '', declaration.highlight_language) end declaration end |
.rec_path(path) ⇒ Object
returns all subdirectories of specified path
205 206 207 208 209 210 211 |
# File 'lib/jazzy/sourcekitten.rb', line 205 def self.rec_path(path) path.children.collect do |child| if child.directory? rec_path(child) + [child] end end.select { |x| x }.flatten(1) end |
.reject_inaccessible_extensions(typedecl, extensions) ⇒ Object
Now we know all the public types and all the private protocols, reject extensions that add public protocols to private types or add private protocols to public types.
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 |
# File 'lib/jazzy/sourcekitten.rb', line 753 def self.reject_inaccessible_extensions(typedecl, extensions) swift_exts, objc_exts = extensions.partition(&:swift?) # Reject extensions that are just conformances to private protocols unwanted_exts, wanted_exts = swift_exts.partition do |ext| ext.children.empty? && !ext.other_inherited_types?(@inaccessible_protocols) end # Given extensions of a type from this module, without the # type itself, the type must be private and the extensions # should be rejected. if !typedecl && wanted_exts.first && wanted_exts.first.type_from_doc_module? unwanted_exts += wanted_exts wanted_exts = [] end # Don't tell the user to document them unwanted_exts.each { |e| @stats.remove_undocumented(e) } objc_exts + wanted_exts end |
.reject_objc_types(docs) ⇒ Object
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 |
# File 'lib/jazzy/sourcekitten.rb', line 1008 def self.reject_objc_types(docs) enums = docs.map do |doc| [doc, doc.children] end.flatten.select { |child| child.type.objc_enum? }.map(&:objc_name) docs.map do |doc| doc.children = doc.children.reject do |child| child.type.objc_typedef? && enums.include?(child.name) end doc end.reject do |doc| doc.type.objc_unexposed? || (doc.type.objc_typedef? && enums.include?(doc.name)) end end |
.run_sourcekitten(arguments) ⇒ Object
Run sourcekitten with given arguments and return STDOUT
258 259 260 261 262 263 264 265 266 267 268 269 270 271 |
# File 'lib/jazzy/sourcekitten.rb', line 258 def self.run_sourcekitten(arguments) if 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 env = xcode.as_env else env = ENV end bin_path = Pathname(__FILE__) + '../../../bin/sourcekitten' output, = Executable.execute_command(bin_path, arguments, true, env: env) output end |
.sanitize_filename(doc) ⇒ Object
141 142 143 144 145 146 147 148 149 |
# File 'lib/jazzy/sourcekitten.rb', line 141 def self.sanitize_filename(doc) unsafe_filename = doc.docs_filename sanitzation_enabled = Config.instance.use_safe_filenames if sanitzation_enabled && !doc.type.name_controlled_manually? CGI.escape(unsafe_filename).gsub('_', '%5F').tr('%', '_') else unsafe_filename end end |
.should_document?(doc) ⇒ Boolean
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 313 314 315 316 |
# File 'lib/jazzy/sourcekitten.rb', line 288 def self.should_document?(doc) return false if doc['key.doc.comment'].to_s.include?(':nodoc:') type = SourceDeclaration::Type.new(doc['key.kind']) # Always document Objective-C declarations. return true unless type.swift_type? # Don't document Swift types if we are hiding Swift return false if Config.instance.hide_swift? # Don't document @available declarations with no USR, since it means # they're unavailable. if availability_attribute?(doc) && !doc['key.usr'] return false end # Document enum elements, since we can't tell their ACL. return true if type.swift_enum_element? # Document extensions if they might have parts covered by the ACL. return should_document_swift_extension?(doc) if type.swift_extension? acl_ok = SourceDeclaration::AccessControlLevel.from_doc(doc) >= @min_acl unless acl_ok @stats.add_acl_skipped @inaccessible_protocols.append(doc['key.name']) if type.swift_protocol? end acl_ok end |
.should_document_swift_extension?(doc) ⇒ Boolean
318 319 320 321 322 323 324 |
# File 'lib/jazzy/sourcekitten.rb', line 318 def self.should_document_swift_extension?(doc) doc['key.inheritedtypes'] || Array(doc['key.substructure']).any? do |subdoc| subtype = SourceDeclaration::Type.new(subdoc['key.kind']) !subtype.mark? && should_document?(subdoc) end end |
.should_mark_undocumented(declaration) ⇒ Object
Call things undocumented if they were compiled properly and came from our module.
328 329 330 |
# File 'lib/jazzy/sourcekitten.rb', line 328 def self.should_mark_undocumented(declaration) declaration.usr && !declaration.modulename end |
.split_decl_attributes(declaration) ⇒ Object
Split leading attributes from a decl, returning both parts.
435 436 437 438 |
# File 'lib/jazzy/sourcekitten.rb', line 435 def self.split_decl_attributes(declaration) declaration =~ /^((?:#{attribute_regexp('\w+')}\s*)*)(.*)$/m Regexp.last_match.captures end |
.subdir_for_doc(doc) ⇒ Object
Determine the subdirectory in which a doc should be placed. Guides in the root for back-compatibility. Declarations under outer namespace type (Structures, Classes, etc.)
191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/jazzy/sourcekitten.rb', line 191 def self.subdir_for_doc(doc) return [] if doc.type.markdown? top_level_decl = doc.namespace_path.first if top_level_decl.type.name [top_level_decl.type.plural_url_name] + doc.namespace_ancestors.map(&:name) else # Category - in the root [] end end |
.undocumented_abstract ⇒ Object
57 58 59 60 61 |
# File 'lib/jazzy/sourcekitten.rb', line 57 def self.undocumented_abstract @undocumented_abstract ||= Markdown.render( Config.instance.undocumented_text, ).freeze end |
.use_spm?(options) ⇒ Boolean
213 214 215 216 217 218 219 |
# File 'lib/jazzy/sourcekitten.rb', line 213 def self.use_spm?() .swift_build_tool == :spm || (!.swift_build_tool_configured && Dir['*.xcodeproj', '*.xcworkspace'].empty? && !.build_tool_arguments.include?('-project') && !.build_tool_arguments.include?('-workspace')) end |
.xml_to_text(xml) ⇒ Object
Strip tags and convert entities
403 404 405 406 407 408 |
# File 'lib/jazzy/sourcekitten.rb', line 403 def self.xml_to_text(xml) document = REXML::Document.new(xml) REXML::XPath.match(document.root, '//text()').map(&:value).join rescue StandardError '' end |