diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4516082..6b19ffd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,9 @@ jobs: - name: Exercise explicit accepted-debt baselines run: bundle exec ruby scripts/check_baselines.rb + - name: Exercise opt-in declaration extraction + run: bundle exec ruby scripts/check_declarations.rb + - name: Exercise architecture presets run: bundle exec ruby scripts/check_presets.rb @@ -181,6 +184,7 @@ jobs: ruby scripts/check_source_exclusions.rb ruby scripts/check_analysis_diagnostics.rb ruby scripts/check_baselines.rb + ruby scripts/check_declarations.rb ruby scripts/check_presets.rb ruby scripts/check_named_calls.rb ruby scripts/check_documentation_examples.rb diff --git a/API.md b/API.md index 6a2b597..6f7ebed 100644 --- a/API.md +++ b/API.md @@ -264,6 +264,31 @@ for a calculation over `ClassInfo`; zone guards are `not_in_zone_of_pain` and +## Class declaration selection (unreleased) + +~~~ ruby +selection = ArchUnit.project_classes(root) + .in_namespace('Billing') + .descendants_of('::Commands::Base') + .selection +~~~ + +`with_constant_name('Billing::Invoice')` selects an exact class name. `in_namespace` matches +namespace segments, and chained filters use AND. Non-ASCII names retain their Ruby source +encoding; use a selector string in the same encoding as its declaration. Builders are lazy +and immutable. `selection` returns matched classes with contributing declaration locations, +written methods and relationships, plus a separate list of uncertainties. +Its status is `:complete` (matches and no uncertainties), +`:empty` (no match and no uncertainty), or `:unknown` (uncertainties may coexist with matches). +This is inspection, not a test assertion or a baseline-supported rule. + +Ancestry uses only known, explicit superclass links. A missing external parent, conflicting reopens, +rebinding, relative lookup we cannot prove, or a cyclic chain can leave selection unknown. No +runtime reflection, effective methods, implicit `Object`, or mixin ancestry is inferred. The +selector covers all in-scope declaration sites for a class, not a particular folder or load order. +Use `CheckOptions.new(source_exclusions: ...)` to limit the source set. Cached declaration facts +refresh with `clear_cache: true` or `ArchUnit.clear_graph_cache`. + ## Checking and test frameworks Every architecture rule includes `ArchUnit::Checkable` and exposes `check(options = nil)`. It returns diff --git a/CHANGELOG.md b/CHANGELOG.md index bba4ba5..ecb7b85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ automatic inflection, or change to existing default graphs. - Keep an external import distinct from a same-named project file in dependency rules and graph reports. This can reveal previously missed violations, including in imports-only projects. +- Inspect declared classes by exact constant name, namespace, or bounded superclass ancestry. + Keep reopened source sites and surface uncertain results without changing file dependency rules. - Lazily reuse immutable node/internal/external-edge views within each cached graph analysis across file and layer checks. Invalidation, per-rule filtering, callbacks and logging stay intact; views trade additional retained memory for less repeated projection work. diff --git a/benchmark/study/README.md b/benchmark/study/README.md index 9afe840..c47a2e1 100644 --- a/benchmark/study/README.md +++ b/benchmark/study/README.md @@ -139,6 +139,17 @@ Ruby coverage. Engine shapes are generated, not full monorepo/Rails applications a universal winner or optimize to a leaderboard. Shared-runner times are observations, not hard timing gates; no graph baseline is auto-updated. Existing correctness canaries stay separate. +## Opt-in class declaration selection + +From the root, run `bundle exec ruby benchmark/study/declaration_selection.rb`. The fixture +contains 500 single-class files in an explicit superclass chain. Every sample checks that it +selects the 499 descendants of the root. On Windows / Ruby 4.0.6, five trials gave median +end-to-end selector times of **253 ms cold** and **15.9 ms warm**, with **104,109** and **15,548** +Ruby allocations respectively. The median post-GC heap increase after the cold check was +**273,792 bytes** (Ruby object storage, not RSS). The script separately reports the ordinary +gem require and first opt-in scope setup, and verifies the default require did not load +declaration extraction. These are fixture measurements, not timing ceilings. + ## Real production source `real_project.rb` checks pinned Discourse `2de9c9be4f89e392fe500dd27f928d6b1184bf09`, with three diff --git a/benchmark/study/declaration_selection.rb b/benchmark/study/declaration_selection.rb new file mode 100644 index 0000000..c2269e6 --- /dev/null +++ b/benchmark/study/declaration_selection.rb @@ -0,0 +1,90 @@ +# frozen_string_literal: true + +require 'json' +require 'objspace' +require 'pathname' +require 'tmpdir' + +# Reproducible opt-in timing; the completed selection is checked against a known chain. +module DeclarationSelectionStudy + FILES = 500 + TRIALS = 5 + + module_function + + def run + startup = measure_default_load + Dir.mktmpdir('archunit-declarations-bench') do |directory| + root = Pathname.new(directory) + fixture(root) + setup = measure { ArchUnit.project_classes(root) } + scope = ArchUnit.project_classes(root).descendants_of('Node0') + data = { ruby: RUBY_DESCRIPTION, files: FILES, trials: TRIALS, startup:, setup: } + puts JSON.pretty_generate(data.merge(benchmarks(scope))) + end + end + + def measure_default_load + startup = measure { require 'archunit' } + loaded = ArchUnit::Extraction.respond_to?(:extract_declarations) + raise 'default load built declarations' if loaded + + startup + end + + def fixture(root) + root.join('Gemfile').write("raise 'do not boot fixture'") + FILES.times do |index| + parent = index.zero? ? '' : " < ::Node#{index - 1}" + root.join("node#{index}.rb").write("class Node#{index}#{parent}; def call(id); end; end") + end + end + + def benchmarks(scope) + cold, warm, retained = samples(scope) + { cold_median: median(cold), warm_median: median(warm), + retained_heap_bytes_median: retained.sort.fetch(TRIALS / 2) } + end + + def samples(scope) + Array.new(TRIALS) { paired_sample(scope) }.transpose + end + + def paired_sample(scope) + ArchUnit.clear_graph_cache + before = heap_bytes + cold = measure { verify(scope) } + retained = heap_bytes - before + warm = measure { verify(scope) } + [cold, warm, retained] + end + + def verify(scope) + result = scope.selection + return if result.status == :complete && result.matches.length == FILES - 1 + + raise 'declaration selection did not match the fixture oracle' + end + + def measure + GC.start + before = GC.stat(:total_allocated_objects) + start = Process.clock_gettime(Process::CLOCK_MONOTONIC) + yield + milliseconds = 1000 * (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) + { milliseconds: milliseconds.round(2), allocations: GC.stat(:total_allocated_objects) - before } + end + + def heap_bytes + GC.start + ObjectSpace.memsize_of_all + end + + def median(samples) + samples.first.keys.to_h do |metric| + [metric, samples.map { |sample| sample.fetch(metric) }.sort.fetch(TRIALS / 2)] + end + end +end + +DeclarationSelectionStudy.run diff --git a/design/declaration-facts.md b/design/declaration-facts.md new file mode 100644 index 0000000..a695dc5 --- /dev/null +++ b/design/declaration-facts.md @@ -0,0 +1,62 @@ +# Declaration facts and selectors (#103) + +This is an amendment to [the semantic-boundaries decision](semantic-boundaries.md). It does not +change file graph identity, import/constant modes, existing rule fingerprints, or the parser +dependency. No app, load path setup, reflection, or target configuration is evaluated. + +## First slice: facts, not runtime classes + +Read Prism declarations once from an already parsed source. Keep each version of a namespace +declaration, even when names coincide. The stable evidence key is project-relative file, line +and byte column, not traversal order or the last file to reopen a constant. Record class vs +module, written constant path, bounded qualified name, enclosing lexical declarations, and +`direct`, `conditional` or `dynamic` context. Context applies to the enclosing syntax, not to +whether Ruby would have loaded a file. A method records its enclosing declaration site, not an +invented merged runtime owner. When the method receiver is dynamic, the enclosing site stays +known independently from the method's unknown ownership. + +- Simple declarations use lexical nesting. Root-qualified paths stay rooted. A qualified path + written at top level keeps its explicit path. A relative qualified path inside another + declaration is **unknown** until the owner can be established; never assume the root. +- Reopens with one name do not replace earlier facts. A class/module collision is not resolved + by input order. Conditional facts and facts under a receiver whose identity is unknown + must remain inspectable; they are not proof of a single runtime class. +- `def`, `def self.name` and `class << self` record literal method positions, with parameters + classified by written shape. Explicit receivers other than self have unknown method scope. + Default expressions are not evaluated. Superclass and literal mixin arguments are facts + about written expressions, not resolved edges. Non-constant expressions are retained as + unresolved source sites, not treated as absent. +- Mixin observations cover bare or explicit-`self` calls inside a named class/module's lexical + scope, outside singleton-class bodies. They are not an inventory of every possible mixin. +- The opt-in project collector uses the existing project locator, exclusions and fail-closed + parser. It parses each included file once per cold inventory and retains facts, not ASTs. + The ordinary `require 'archunit'` path does not load the collector at all. + +## Bounded selector contract + +The sentence is “project classes in namespace Billing, with constant name Billing::Invoice, +should ...”. A classes scope is separate from the file scope and does not introduce class +nodes in the file graph. Following the siblings' scope grammar, use +`project_classes(root).in_namespace('Billing').with_constant_name('Billing::Invoice')`. +The exact selector normalizes a leading `::`; the namespace selector includes descendants by +segment (`Billing::Invoice`, not `BillingTools::Invoice` or `Billing` itself). Source exclusions +remove contributing sites before grouping; excluded reopens are not read. Only ordinary +class declarations are class candidates, not constants assigned `Class.new` or an alias. + +`descendants_of` follows an iterative chain of explicit superclass declarations. It considers +root-qualified names, top-level spellings, and unqualified names with a known lexical declaration +inside a namespace. It does not guess at imported, inherited or alias-based lookup. External, +dynamic, cyclic and conflicting ancestry are unknown unless a known link already proves the +requested ancestry and the chain is not cyclic. No implicit `Object` or mixin edges are created. +Explicit constant assignments that may rebind a selected class or namespace make it uncertain. +Reflection and metaprogramming are not modeled. + +Class selection is inspection, not an architecture rule. `selection` exposes matches and +uncertainties, with status `:complete`, `:empty`, or `:unknown`. Known matches can coexist with +unknown candidates. Future rule terminals must propagate unknowns and fail normally on an empty +selection. #105 is responsible for the rule/violation model and its baseline adapter. + +The inventory stays opt-in and cached by canonical root and effective exclusions. Reporting uses +the distinct `source_declarations` analysis scope, not dependency graph counts. The fact collector +can also accept an already parsed AST. Each feature that starts enforcing these facts must define +its baseline identity explicitly before accepting debt. diff --git a/lib/archunit.rb b/lib/archunit.rb index eecacf6..9357430 100644 --- a/lib/archunit.rb +++ b/lib/archunit.rb @@ -23,6 +23,7 @@ require_relative 'archunit/common/projection/edge_projections' require_relative 'archunit/common/projection/project_edges' require_relative 'archunit/common/projection/project_to_nodes' +require_relative 'archunit/classes/fluentapi/classes' require_relative 'archunit/common/projection/project_cycles' require_relative 'archunit/extraction/locate_project' require_relative 'archunit/extraction/enumerate_source_files' diff --git a/lib/archunit/classes/fluentapi/class_filters.rb b/lib/archunit/classes/fluentapi/class_filters.rb new file mode 100644 index 0000000..590d5e6 --- /dev/null +++ b/lib/archunit/classes/fluentapi/class_filters.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +require 'prism' + +module ArchUnit + module Classes + module FluentApi + ASCII_CONSTANT = /\A[A-Z][A-Za-z0-9_]*\z/ + private_constant :ASCII_CONSTANT + + # Lexical inputs, not Ruby expressions or paths. + ClassFilters = Data.define(:constants, :namespaces, :ancestors) do + def self.empty + new(constants: [].freeze, namespaces: [].freeze, ancestors: [].freeze) + end + + def add(kind, raw) + name = normalized_name(raw) + case kind + when :constant then with(constants: append(constants, name)) + when :namespace then with(namespaces: append(namespaces, name)) + when :ancestor then with(ancestors: append(ancestors, name)) + end + end + + def matches_name?(name) + (constants.empty? || constants.all? { |exact| exact == name }) && + namespaces.all? { |prefix| in_namespace?(name, prefix) } + end + + def possible? + return false if constants.size > 1 + return matches_name?(constants.first) unless constants.empty? + + deepest = namespaces.max_by(&:length) + namespaces.all? { |prefix| deepest == prefix || in_namespace?(deepest, prefix) } + end + + def unresolved_name_possible?(written) + return true if written.nil? || constants.empty? + + constant_leaf(written) == constant_leaf(constants.first) + end + + private + + def in_namespace?(name, prefix) + Encoding.compatible?(name, prefix) && name.start_with?("#{prefix}::") + end + + def constant_leaf(name) + name.split('::').last + end + + def normalized_name(raw) + if raw.is_a?(String) && raw.encoding.ascii_compatible? && raw.valid_encoding? + value = raw.delete_prefix('::') + segments = value.split('::', -1) + return value.freeze if !segments.empty? && segments.all? { |part| constant?(part) } + end + + raise ArgumentError, 'expected a qualified constant name such as Billing::Invoice' + end + + def constant?(part) + return ASCII_CONSTANT.match?(part) if part.ascii_only? + + # Ruby accepts some Unicode identifiers a category regex cannot describe. + result = Prism.lex(part, encoding: part.encoding) + result.success? && result.value.size == 2 && + whole_constant?(result.value.first.first, part) + end + + def whole_constant?(token, part) + token.type == :CONSTANT && token.location.start_offset.zero? && + token.location.length == part.bytesize + end + + def append(values, name) + [*values, name].uniq.freeze + end + end + private_constant :ClassFilters + end + end +end diff --git a/lib/archunit/classes/fluentapi/class_scope.rb b/lib/archunit/classes/fluentapi/class_scope.rb new file mode 100644 index 0000000..29ef098 --- /dev/null +++ b/lib/archunit/classes/fluentapi/class_scope.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require_relative '../../common/fluentapi/check_options' +require_relative '../../extraction/declarations' +require_relative '../projection/select_classes' +require_relative 'class_filters' + +module ArchUnit + # Inspection of bounded class declarations, kept separate from file graph rules. + module Classes + module FluentApi + # Lazy scope. Chained filters narrow the inspection with AND semantics. + class ClassScope + def initialize(project_locator, filters: ClassFilters.empty) + @project_locator = immutable_locator(project_locator) + @filters = filters + freeze + end + + # Includes classes owned by this namespace or one of its subnamespaces. + # @return [ClassScope] + def in_namespace(name) + adding(:namespace, name) + end + + # Selects an exact normalized constant name, not a file name or pattern. + # @return [ClassScope] + def with_constant_name(name) + adding(:constant, name) + end + + # Requires statically known transitive superclass ancestry (not mixins). + # @return [ClassScope] + def descendants_of(name) + adding(:ancestor, name) + end + + # Reads a declaration snapshot. This is inspection, not a passing/failing rule. + # @param options [CheckOptions, nil] + # @return [ClassSelection] + def selection(options = nil) + options = Common::FluentApi::CheckOptions.resolve(options) + inventory = ArchUnit::Extraction.extract_declarations(@project_locator, options:) + Projection::SelectClasses.call(inventory, @filters) + end + + private + + def adding(kind, name) + self.class.new(@project_locator, filters: @filters.add(kind, name)) + end + + def immutable_locator(locator) + locator = locator.to_path if locator.respond_to?(:to_path) + return if locator.nil? + return locator.dup.freeze if locator.is_a?(String) && !locator.empty? + + raise ArgumentError, 'project_locator must be a non-empty path or nil' + end + end + end + end +end diff --git a/lib/archunit/classes/fluentapi/classes.rb b/lib/archunit/classes/fluentapi/classes.rb new file mode 100644 index 0000000..8ec982d --- /dev/null +++ b/lib/archunit/classes/fluentapi/classes.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +# Public entry to declaration inspection alongside the existing file and graph APIs. +module ArchUnit + # Starts an immutable class declaration scope without reading the project. + # @param project_locator [String, Pathname, nil] + # @return [Classes::FluentApi::ClassScope] + def self.project_classes(project_locator = nil) + require_relative 'class_scope' + Classes::FluentApi::ClassScope.new(project_locator) + end +end diff --git a/lib/archunit/classes/projection/ancestry_selection.rb b/lib/archunit/classes/projection/ancestry_selection.rb new file mode 100644 index 0000000..0d05a3f --- /dev/null +++ b/lib/archunit/classes/projection/ancestry_selection.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require_relative 'parent_links' + +module ArchUnit + module Classes + module Projection + # Iterative memoized traversal of a bounded, single-superclass declaration graph. + class AncestrySelection + def initialize(parents, target) + @parents = parents + @target = target + @results = {} + end + + def status(name) + return @results.fetch(name) if @results.key?(name) + + compute(name) + @results.fetch(name) + end + + private + + def compute(name) + path = {} + current = name + until @results.key?(current) + return record_cycle(path) if path.key?(current) + return finish(path, current) if end_of_chain?(current) + + path[current] = true + current = @parents.fetch(current) + end + propagate(path, @results.fetch(current)) + end + + def end_of_chain?(name) + parent = @parents.fetch(name) + parent.nil? || parent == ParentLinks::UNKNOWN + end + + def finish(path, name) + result = @parents.fetch(name).nil? ? :not_matched : :unresolved_ancestry + @results[name] = result + propagate(path, result) + end + + def record_cycle(path) + path.each_key { |name| @results[name] = :cyclic_ancestry } + end + + def propagate(path, result) + path.keys.reverse_each do |name| + result = :matched if result != :cyclic_ancestry && @parents.fetch(name) == @target + @results[name] = result + end + end + end + private_constant :AncestrySelection + end + end +end diff --git a/lib/archunit/classes/projection/class_selection.rb b/lib/archunit/classes/projection/class_selection.rb new file mode 100644 index 0000000..d2191c3 --- /dev/null +++ b/lib/archunit/classes/projection/class_selection.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +module ArchUnit + module Classes + # All contributing in-scope sites for one class constant, not its runtime method table. + DeclaredClass = Data.define(:name, :declarations, :method_declarations, :relationships) + # What prevents a fact or class from being selected decisively. + UncertainClass = Data.define(:name, :declarations, :reason, :ancestor) + + # Inspection result. An unknown selection may include some definite matches. + ClassSelection = Data.define(:matches, :uncertainties) do + def status + return :unknown unless uncertainties.empty? + + matches.empty? ? :empty : :complete + end + end + end +end diff --git a/lib/archunit/classes/projection/declaration_owners.rb b/lib/archunit/classes/projection/declaration_owners.rb new file mode 100644 index 0000000..223c01f --- /dev/null +++ b/lib/archunit/classes/projection/declaration_owners.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require_relative 'class_selection' + +module ArchUnit + module Classes + module Projection + # Groups immutable declaration sites without silently dropping reopens or kind conflicts. + class DeclarationOwners + attr_reader :unresolved, :names + + def initialize(inventory) + @by_name = inventory.namespaces.group_by(&:name) + @unresolved = @by_name.delete(nil) || [] + @names = @by_name.keys.sort + @methods = inventory.method_declarations.group_by(&:owner) + @relationships = inventory.relationships.group_by(&:owner) + end + + def declarations(name) + @by_name.fetch(name).dup.freeze + end + + def candidate?(name) + @by_name.fetch(name).any? { |decl| decl.kind == :class } + end + + def certainty_reason(name) + sites = @by_name.fetch(name) + kinds = sites.map(&:kind) + return :conflicting_constant_write if kinds.include?(:constant_write) + return :conflicting_declaration_kind if kinds.include?(:module) + return :uncertain_namespace_owner if uncertain_prefix?(name) + + :conditional_or_dynamic_declaration if sites.any? { |decl| decl.context != :direct } + end + + def known_class?(name) + @by_name.key?(name) && candidate?(name) && certainty_reason(name).nil? + end + + def known_name?(name) + @by_name.key?(name) + end + + def declared_class(name) + sites = declarations(name) + DeclaredClass.new( + name:, declarations: sites, method_declarations: for_sites(@methods, sites), + relationships: for_sites(@relationships, sites) + ) + end + + def superclass_sites(name) + for_sites(@relationships, @by_name.fetch(name)).select { |ref| ref.kind == :superclass } + end + + private + + def uncertain_prefix?(name) + prefix = name + while prefix.include?('::') + prefix = prefix.rpartition('::').first + sites = @by_name.fetch(prefix, []) + return true if conflicting_prefix?(sites) + end + false + end + + def conflicting_prefix?(sites) + sites.map(&:kind).uniq.size > 1 || + sites.any? { |decl| decl.kind == :constant_write || decl.context != :direct } + end + + def for_sites(map, sites) + sites.flat_map { |decl| map.fetch(decl.site, []) }.freeze + end + end + private_constant :DeclarationOwners + end + end +end diff --git a/lib/archunit/classes/projection/parent_links.rb b/lib/archunit/classes/projection/parent_links.rb new file mode 100644 index 0000000..d1e6e3f --- /dev/null +++ b/lib/archunit/classes/projection/parent_links.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +module ArchUnit + module Classes + module Projection + # Builds only unambiguous written superclass links. Nil is a declared-graph end. + module ParentLinks + UNKNOWN = :unresolved_ancestry + + def self.build(owners) + owners.names.to_h { |name| [name, parent(owners, name)] }.freeze + end + + def self.parent(owners, name) + return UNKNOWN unless owners.known_class?(name) + + scopes = owners.declarations(name).to_h { |decl| [decl.site, decl.nesting] } + targets = owners.superclass_sites(name).map do |site| + resolve(site.written_target, scopes.fetch(site.owner), owners) + end.uniq + return targets.first if targets.size < 2 + + UNKNOWN + end + + def self.resolve(written, nesting, owners) + return UNKNOWN if written.nil? + + resolved = bounded_name(written, nesting, owners) + owners.known_class?(resolved) ? resolved : UNKNOWN + end + + def self.bounded_name(written, nesting, owners) + return written.delete_prefix('::') if written.start_with?('::') + return written if nesting.empty? + return if written.include?('::') + + lexical_name(written, nesting, owners) + end + + def self.lexical_name(written, nesting, owners) + return if nesting.any?(&:nil?) + + nesting.lazy.map { |prefix| "#{prefix}::#{written}" } + .find { |candidate| owners.known_name?(candidate) } + end + private_class_method :parent, :resolve, :bounded_name, :lexical_name + end + private_constant :ParentLinks + end + end +end diff --git a/lib/archunit/classes/projection/select_classes.rb b/lib/archunit/classes/projection/select_classes.rb new file mode 100644 index 0000000..f280320 --- /dev/null +++ b/lib/archunit/classes/projection/select_classes.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require_relative 'ancestry_selection' +require_relative 'declaration_owners' + +module ArchUnit + module Classes + module Projection + # Pure selection; all IO and snapshot management live in extraction. + # @api private + class SelectClasses + def self.call(inventory, filters) + new(inventory, filters).call + end + + def initialize(inventory, filters) + @owners = DeclarationOwners.new(inventory) + @filters = filters + @matches = [] + @uncertainties = [] + @ancestors = ancestry_queries + end + + def call + if @filters.possible? + @owners.names.each { |name| classify(name) } + @owners.unresolved.each { |site| classify_unresolved(site) } + end + ClassSelection.new(matches: @matches.freeze, uncertainties: @uncertainties.freeze) + end + + private + + def ancestry_queries + return {} if @filters.ancestors.empty? + + parents = ParentLinks.build(@owners) + @filters.ancestors.to_h { |target| [target, AncestrySelection.new(parents, target)] } + end + + def classify(name) + return unless @filters.matches_name?(name) && @owners.candidate?(name) + return if @ancestors.key?(name) + + reason = @owners.certainty_reason(name) + return uncertain(name, reason) if reason + + classify_ancestry(name) + end + + def classify_ancestry(name) + states = @ancestors.transform_values { |traversal| traversal.status(name) } + return if states.value?(:not_matched) + + unresolved = states.reject { |_target, status| status == :matched } + unresolved.each { |ancestor, reason| uncertain(name, reason, ancestor) } + @matches << @owners.declared_class(name) if unresolved.empty? + end + + def uncertain(name, reason, ancestor = nil) + @uncertainties << UncertainClass.new( + name:, reason:, ancestor:, declarations: @owners.declarations(name) + ) + end + + def classify_unresolved(site) + return unless @filters.unresolved_name_possible?(site.written_name) + + @uncertainties << UncertainClass.new( + name: nil, reason: :unresolved_owner, ancestor: nil, declarations: [site].freeze + ) + end + end + end + end +end diff --git a/lib/archunit/cli/analysis_text.rb b/lib/archunit/cli/analysis_text.rb index 02365ba..8f4e6fc 100644 --- a/lib/archunit/cli/analysis_text.rb +++ b/lib/archunit/cli/analysis_text.rb @@ -5,6 +5,13 @@ module CLI # Concise human diagnostics; nil remains unavailable, never zero. # @api private module AnalysisText + SOURCE_LABELS = { + 'source_calls' => 'source calls', + 'source_declarations' => 'source declarations', + 'source_metrics' => 'source metrics' + }.freeze + private_constant :SOURCE_LABELS + def self.write(analysis, out) out.puts("Analysis: #{analysis[:status]}") analysis[:scopes].each { |scope| write_scope(scope, out) } @@ -25,7 +32,7 @@ def self.write_scope(scope, out) private_class_method :write_scope def self.source_scope(scope) - name = scope[:kind] == 'source_calls' ? 'source calls' : 'source metrics' + name = SOURCE_LABELS.fetch(scope[:kind], 'source analysis') "#{name} (dependency analysis unavailable)" end private_class_method :source_scope diff --git a/lib/archunit/cli/report.rb b/lib/archunit/cli/report.rb index bed0135..e6cc35c 100644 --- a/lib/archunit/cli/report.rb +++ b/lib/archunit/cli/report.rb @@ -2,11 +2,11 @@ require 'json' require_relative '../version' -require_relative '../testing/violation_factory' require_relative '../error/source_parse_error' require_relative 'analysis_report' require_relative 'analysis_text' require_relative 'baseline_text' +require_relative 'violation_payload' module ArchUnit module CLI @@ -39,7 +39,7 @@ def add_rule(rule, violations: nil, analysis: nil) payload[:rules] << { name: rule.name, rationale: rule.checkable.rationale, status: rule_status(violations), analysis: analysis || { status: 'unavailable', scope_ids: [] }, - violations: violation_payloads(violations) + violations: Array(violations).map { |violation| ViolationPayload.build(violation) } } end @@ -82,26 +82,6 @@ def rule_status(violations) violations.empty? ? 'passed' : 'failed' end - def violation_payload(violation) - formatted = Testing::ViolationFactory.from_violation(violation) - result = { - type: violation.class.name, message: formatted.message, details: formatted.details - } - if violation.is_a?(Files::Assertion::CycleViolation) && violation.witness? - result[:cycle_reporting] = 'witness' - end - result - end - - def violation_payloads(violations) - (violations || []).map do |violation| - result = violation_payload(violation) - named_call = violation.is_a?(Files::Assertion::NamedCallViolation) - result[:call] = violation.call.to_h if named_call - result - end - end - def write_text(out) write_header(out) write_notice(out) diff --git a/lib/archunit/cli/violation_payload.rb b/lib/archunit/cli/violation_payload.rb new file mode 100644 index 0000000..9195f78 --- /dev/null +++ b/lib/archunit/cli/violation_payload.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require_relative '../testing/violation_factory' + +module ArchUnit + module CLI + # Serializes violations without coupling their types to the report lifecycle. + # @api private + module ViolationPayload + def self.build(violation) + formatted = Testing::ViolationFactory.from_violation(violation) + result = { + type: violation.class.name, message: formatted.message, details: formatted.details + } + add_evidence(result, violation) + result + end + + def self.add_evidence(result, violation) + case violation + when Files::Assertion::CycleViolation + result[:cycle_reporting] = 'witness' if violation.witness? + when Files::Assertion::NamedCallViolation + result[:call] = violation.call.to_h + end + end + private_class_method :add_evidence + end + end +end diff --git a/lib/archunit/common/extraction/declaration_facts.rb b/lib/archunit/common/extraction/declaration_facts.rb new file mode 100644 index 0000000..aa2ba40 --- /dev/null +++ b/lib/archunit/common/extraction/declaration_facts.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +module ArchUnit + module Common + module Extraction + # Internal immutable syntax facts. A location, rather than a name, owns method facts. + # @api private + module DeclarationFacts + Site = Data.define(:file, :line, :column) + Namespace = Data.define(:kind, :name, :written_name, :nesting, :context, :site) + Method = Data.define(:name, :scope, :owner, :context, :site, :parameters) + Parameter = Data.define(:kind, :name) + Relationship = Data.define(:kind, :written_target, :owner, :context, :site) + Inventory = Data.define(:namespaces, :method_declarations, :relationships) + end + end + end +end diff --git a/lib/archunit/extraction/declarations.rb b/lib/archunit/extraction/declarations.rb new file mode 100644 index 0000000..89e82d9 --- /dev/null +++ b/lib/archunit/extraction/declarations.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +require_relative 'declarations/collector' +require_relative 'declarations/cache' +require_relative 'analysis_observer' +require_relative 'analysis_snapshot' +require_relative '../error/source_parse_error' +require_relative 'enumerate_source_files' +require_relative 'extract_imports' +require_relative 'locate_project' + +module ArchUnit + # Ruby-specific extraction of declaration facts from the existing source inventory. + module Extraction + module_function + + # Returns facts from one project without changing file-graph analysis or cache identity. + # @api private + def extract_declarations(locator = nil, options: nil) + root = Pathname.new(locate_project(locator)) + options = Common::FluentApi::CheckOptions.resolve(options) + patterns = resolve_project_exclude_patterns( + root, nil, source_exclusions: options.source_exclusions + ).sort.freeze + cached_declarations(root, patterns, options).first + end + + def cached_declarations(root, patterns, options) + key = [root.to_s.freeze, patterns].freeze + bundle, hit = Declarations::Cache.fetch(key, refresh: options.clear_cache?) do + declaration_bundle(root, patterns) + end + AnalysisObserver.record(bundle.last, cache_hit: hit) + bundle + rescue StandardError + AnalysisObserver.record(declaration_snapshot(root, patterns, nil, 'error')) + raise + end + private_class_method :cached_declarations + + def declaration_bundle(root, patterns) + files = enumerate_source_files_with_patterns(root, patterns) + inventories = files.map do |file| + Declarations.collect(parse_source(root.join(file), nil), file:) + end + snapshot = declaration_snapshot(root, patterns, files.length, 'analyzed') + [Declarations.combine(inventories), snapshot].freeze + end + private_class_method :declaration_bundle + + def declaration_snapshot(root, patterns, count, status) + discovery = SourceDiscovery.new(root:, patterns:, files: [].freeze) + AnalysisSnapshot.source(discovery, count:, status:).merge(kind: 'source_declarations').freeze + end + private_class_method :declaration_snapshot + + # Internal entry point for facts from an already parsed Ruby file. + # @api private + module Declarations + def self.collect(result, file:) + tree = SourceParseError.validate!(result, path: file).value + Collector.new(file).collect(tree) + end + + def self.combine(inventories) + type = Common::Extraction::DeclarationFacts::Inventory + fields = type.members.to_h do |attribute| + [attribute, inventories.flat_map { |inventory| inventory.public_send(attribute) }.freeze] + end + type.new(**fields) + end + end + end +end diff --git a/lib/archunit/extraction/declarations/cache.rb b/lib/archunit/extraction/declarations/cache.rb new file mode 100644 index 0000000..7fb585c --- /dev/null +++ b/lib/archunit/extraction/declarations/cache.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module ArchUnit + module Extraction + module Declarations + # Shares completed immutable inventories only; failed reads never populate the cache. + module Cache + MUTEX = Mutex.new + private_constant :MUTEX + + def self.fetch(key, refresh:) + MUTEX.synchronize do + @entries ||= {} + @entries.delete(key) if refresh + if @entries.key?(key) + [@entries.fetch(key), true] + else + [@entries[key] = yield, false] + end + end + end + + def self.clear + MUTEX.synchronize { @entries&.clear } + end + end + end + end +end diff --git a/lib/archunit/extraction/declarations/collector.rb b/lib/archunit/extraction/declarations/collector.rb new file mode 100644 index 0000000..e103056 --- /dev/null +++ b/lib/archunit/extraction/declarations/collector.rb @@ -0,0 +1,136 @@ +# frozen_string_literal: true + +require_relative '../static_constant_name' +require_relative 'constant_assignment' +require_relative 'parameters' +require_relative 'scope' + +module ArchUnit + module Extraction + # Opt-in, read-only extraction over accepted Prism parse results. + module Declarations + # Records written declarations without resolving what Ruby defines at runtime. + class Collector + include StaticConstantName + + Facts = Common::Extraction::DeclarationFacts + CONDITIONAL = %i[ + if_node unless_node while_node until_node for_node case_node case_match_node + rescue_node rescue_modifier_node else_node ensure_node and_node or_node + ].freeze + DYNAMIC = %i[block_node lambda_node].freeze + MIXINS = %i[include prepend extend].freeze + private_constant :Facts, :CONDITIONAL, :DYNAMIC, :MIXINS + + def initialize(file) + @file = file.dup.freeze + @namespaces = [] + @methods = [] + @relationships = [] + end + + def collect(tree) + pending = [[tree, Scope.root]] + until pending.empty? + node, scope = pending.pop + advance(node, scope, pending) + end + Facts::Inventory.new(namespaces: @namespaces.freeze, method_declarations: @methods.freeze, + relationships: @relationships.freeze) + end + + private + + def advance(node, scope, pending) + case node + when Prism::ClassNode, Prism::ModuleNode + add_body(pending, node.body, collect_namespace(node, scope)) + when Prism::DefNode + add_body(pending, node.body, method_body_scope(node, scope)) + when Prism::SingletonClassNode + add_body(pending, node.body, scope.within_singleton(node.expression)) + else + advance_children(node, scope, pending) + end + end + + def add_body(pending, body, scope) + pending << [body, scope] if body + end + + def advance_children(node, scope, pending) + collect_mixins(node, scope) if node.is_a?(Prism::CallNode) + record_assignment(node, scope) + scope = nested_context(node, scope) + node.compact_child_nodes.reverse_each { |child| pending << [child, scope] } + end + + def record_assignment(node, scope) + written = ConstantAssignment.written_name(node) + return unless written + + @namespaces << Facts::Namespace.new( + kind: :constant_write, name: scope.qualify(written.freeze), written_name: written, + nesting: scope.nesting, context: scope.context, site: site(node.location) + ) + end + + def nested_context(node, scope) + return scope.with(context: :dynamic) if DYNAMIC.include?(node.type) + return scope.conditional if CONDITIONAL.include?(node.type) + + scope + end + + def collect_namespace(node, scope) + namespace = namespace_fact(node, scope) + @namespaces << namespace + inner = scope.inside(namespace) + superclass = node.superclass if namespace.kind == :class + relationship(:superclass, superclass, inner) if superclass + inner + end + + def namespace_fact(node, scope) + kind = node.is_a?(Prism::ClassNode) ? :class : :module + written = static_name(node.constant_path)&.freeze + Facts::Namespace.new( + kind:, name: scope.qualify(written), written_name: written, + nesting: scope.nesting, context: scope.context, site: site(node.constant_path.location) + ) + end + + def method_body_scope(node, scope) + @methods << Facts::Method.new( + name: node.name, scope: scope.method_scope(node.receiver), owner: scope.owner, + context: scope.context, site: site(node.name_loc), + parameters: Parameters.collect(node.parameters) + ) + scope.with(context: :dynamic) + end + + def collect_mixins(node, scope) + return unless scope.owner && scope.singleton == :none && mixin_call?(node) + + node.arguments&.arguments&.each { |argument| relationship(node.name, argument, scope) } + end + + def mixin_call?(node) + MIXINS.include?(node.name) && (node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode)) + end + + def relationship(kind, node, scope) + @relationships << Facts::Relationship.new( + kind:, written_target: static_name(node)&.freeze, owner: scope.owner, + context: scope.context, site: site(node.location) + ) + end + + def site(location) + Facts::Site.new(file: @file, line: location.start_line, column: location.start_column + 1) + end + end + private_constant :Collector + end + end +end diff --git a/lib/archunit/extraction/declarations/constant_assignment.rb b/lib/archunit/extraction/declarations/constant_assignment.rb new file mode 100644 index 0000000..2b88bd1 --- /dev/null +++ b/lib/archunit/extraction/declarations/constant_assignment.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require_relative '../static_constant_name' + +module ArchUnit + module Extraction + module Declarations + # Records a possible alias or rebinding without trying to read the assigned value. + module ConstantAssignment + extend StaticConstantName + + BARE = %i[ + constant_write_node constant_and_write_node constant_or_write_node + constant_operator_write_node constant_target_node + ].freeze + PATH = %i[ + constant_path_write_node constant_path_and_write_node constant_path_or_write_node + constant_path_operator_write_node + ].freeze + private_constant :BARE, :PATH + + def self.written_name(node) + return node.name.to_s if BARE.include?(node.type) + return static_name(node.target) if PATH.include?(node.type) + return unless node.type == :constant_path_target_node + + parent = node.parent ? static_name(node.parent) : '' + "#{parent}::#{node.name}" if parent + end + end + private_constant :ConstantAssignment + end + end +end diff --git a/lib/archunit/extraction/declarations/parameters.rb b/lib/archunit/extraction/declarations/parameters.rb new file mode 100644 index 0000000..9a2315a --- /dev/null +++ b/lib/archunit/extraction/declarations/parameters.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require 'prism' +require_relative '../../common/extraction/declaration_facts' + +module ArchUnit + module Extraction + module Declarations + # Represents written parameter shape, not Ruby argument binding or a runtime API. + module Parameters + FIELDS = { + requireds: :required, optionals: :optional, rest: :rest, posts: :post, + keywords: :keyword, keyword_rest: :keyword_rest, block: :block + }.freeze + private_constant :FIELDS + + def self.collect(parameters) + return [].freeze unless parameters + + FIELDS.flat_map do |field, kind| + Array(parameters.public_send(field)).map { |node| parameter(node, kind) } + end.freeze + end + + def self.parameter(node, kind) + name = node.respond_to?(:name) ? node.name : nil + Common::Extraction::DeclarationFacts::Parameter.new(kind: parameter_kind(node, kind), + name:) + end + private_class_method :parameter + + def self.parameter_kind(node, kind) + case node.type + when :forwarding_parameter_node then :forwarding + when :no_keywords_parameter_node then :no_keywords + when :required_keyword_parameter_node then :required_keyword + when :optional_keyword_parameter_node then :optional_keyword + when :multi_target_node then :destructured + else kind + end + end + private_class_method :parameter_kind + end + private_constant :Parameters + end + end +end diff --git a/lib/archunit/extraction/declarations/scope.rb b/lib/archunit/extraction/declarations/scope.rb new file mode 100644 index 0000000..171439b --- /dev/null +++ b/lib/archunit/extraction/declarations/scope.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module ArchUnit + module Extraction + module Declarations + # Immutable lexical state for a single node; nothing is inferred from runtime loading. + Scope = Data.define(:nesting, :owner, :context, :singleton) do + def self.root + new(nesting: [].freeze, owner: nil, context: :direct, singleton: :none) + end + + def qualify(written) + return unless written + return written.delete_prefix('::').freeze if written.start_with?('::') + return if unknown_lexical_owner? + return written if nesting.empty? + return if written.include?('::') + + "#{nesting.first}::#{written}".freeze + end + + def inside(namespace) + with(nesting: [namespace.name, *nesting].freeze, owner: namespace.site, singleton: :none) + end + + def within_singleton(expression) + if singleton == :none && expression.is_a?(Prism::SelfNode) + with(singleton: :self) + else + with(singleton: :other, context: :dynamic) + end + end + + def conditional + context == :dynamic ? self : with(context: :conditional) + end + + def method_scope(receiver) + return :unknown unless owner + return :unknown if singleton == :other + return singleton == :self ? :singleton : :instance unless receiver + return :singleton if singleton == :none && receiver.is_a?(Prism::SelfNode) + + :unknown + end + + private + + def unknown_lexical_owner? + singleton != :none || (owner && nesting.first.nil?) + end + end + private_constant :Scope + end + end +end diff --git a/lib/archunit/extraction/extract_graph.rb b/lib/archunit/extraction/extract_graph.rb index a8933f8..1ac2a01 100644 --- a/lib/archunit/extraction/extract_graph.rb +++ b/lib/archunit/extraction/extract_graph.rb @@ -54,6 +54,7 @@ def extract_graph_entry( private_class_method :extract_graph_entry def clear_graph_cache + Declarations::Cache.clear if const_defined?(:Declarations, false) GRAPH_CACHE_MUTEX.synchronize { graph_cache.clear } clear_named_calls nil diff --git a/scripts/check_declarations.rb b/scripts/check_declarations.rb new file mode 100644 index 0000000..a2aa2b9 --- /dev/null +++ b/scripts/check_declarations.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'archunit' +require 'pathname' +require 'tmpdir' + +loaded = ArchUnit::Extraction.respond_to?(:extract_declarations) +abort 'default load unexpectedly loaded declaration analysis' if loaded +require 'archunit/extraction/declarations' + +Dir.mktmpdir('archunit-declaration-smoke') do |directory| + root = Pathname.new(directory) + root.join('Gemfile').write("raise 'must not boot'") + root.join('a.rb').write(<<~RUBY) + module Orders + class Create < ::Base + def call(amount, auth:); end + end + end + raise 'must not execute' + RUBY + root.join('b.rb').write('class Orders::Create; def self.build(...); end; end') + root.join('base.rb').write('class Base; end') + + facts = ArchUnit::Extraction.extract_declarations(root) + files = facts.namespaces.select { |item| item.name == 'Orders::Create' }.map { |item| item.site.file } + abort 'reopened declaration lost ownership' unless files == %w[a.rb b.rb] + scopes = facts.method_declarations.map(&:scope) + abort 'wrong method scopes' unless scopes == %i[instance singleton] + abort 'wrong written superclass' unless facts.relationships.first.written_target == '::Base' + scope = ArchUnit.project_classes(root).in_namespace('Orders').descendants_of('::Base') + result = scope.selection + abort 'lost installed class selection' unless result.status == :complete && + result.matches.map(&:name) == ['Orders::Create'] +end +puts 'Declaration facts passed read-only extraction and installed-gem smoke.' diff --git a/spec/architecture_spec.rb b/spec/architecture_spec.rb index b566539..313c0ca 100644 --- a/spec/architecture_spec.rb +++ b/spec/architecture_spec.rb @@ -2,7 +2,7 @@ RSpec.describe 'ArchUnitRuby architecture' do let(:project_root) { File.expand_path('..', __dir__) } - let(:domain_names) { %w[files graph layers metrics slices] } + let(:domain_names) { %w[classes files graph layers metrics slices] } it 'keeps common independent from project code and limits its external toolchain' do internal_dependencies = ArchUnit.project_files(project_root) diff --git a/spec/classes/ancestry_selection_spec.rb b/spec/classes/ancestry_selection_spec.rb new file mode 100644 index 0000000..cc8c2ea --- /dev/null +++ b/spec/classes/ancestry_selection_spec.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require 'archunit/classes/projection/ancestry_selection' + +RSpec.describe 'Bounded ancestry traversal' do + it 'classifies a deep chain iteratively and reuses its already visited suffix' do + names = Array.new(15_000) { |index| "Node#{index}" } + parents = names.each_cons(2).to_h.merge(names.last => nil) + type = ArchUnit::Classes::Projection.const_get(:AncestrySelection) + traversal = type.new(parents, names.last) + expect(traversal.status(names.first)).to eq(:matched) + expect(traversal.status(names.fetch(7000))).to eq(:matched) + expect(traversal.status(names.last)).to eq(:not_matched) + end +end diff --git a/spec/classes/class_scope_spec.rb b/spec/classes/class_scope_spec.rb new file mode 100644 index 0000000..3749c1e --- /dev/null +++ b/spec/classes/class_scope_spec.rb @@ -0,0 +1,245 @@ +# frozen_string_literal: true + +require 'archunit/cli' +require 'pathname' +require 'stringio' +require 'tmpdir' + +RSpec.describe 'Declaration-backed class selectors' do + around do |example| + Dir.mktmpdir('archunit-class-selectors') do |dir| + @root = Pathname.new(dir) + @root.join('Gemfile').write("raise 'must not boot target'") + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def write(relative, source) + file = @root.join(relative) + file.dirname.mkpath + file.write(source) + end + + def classes + ArchUnit.project_classes(@root) + end + + it 'selects exact classes, not modules or similarly prefixed namespaces, across files' do + write('not_billing/a.rb', 'module Billing; class Invoice; def call(a); end; end; end') + write('not_billing/b.rb', 'class Billing::Invoice; def self.build; end; end') + write('edge.rb', 'module BillingTools; class Invoice; end; end; module Billing::Reports; end') + write('deep.rb', 'module Billing::Reports; class Export; end; end') + result = classes.in_namespace('::Billing').selection + expect(result.status).to eq(:complete) + expect(result.matches.map(&:name)).to eq(%w[Billing::Invoice Billing::Reports::Export]) + invoice = classes.with_constant_name('::Billing::Invoice').in_namespace('Billing').selection + match = invoice.matches.first + expect(match.declarations.map { |decl| decl.site.file }) + .to eq(%w[not_billing/a.rb not_billing/b.rb]) + expect(match.method_declarations.map(&:name)).to eq(%i[call build]) + expect([invoice, match, match.declarations, match.method_declarations]).to all(be_frozen) + expect(classes.with_constant_name('Billing').selection.status).to eq(:empty) + end + + it 'retains ambiguous, conditional and unresolved declarations rather than passing them' do + write('mixed.rb', <<~RUBY) + class Known; end + class Mixed; end + module Mixed; end + class Conditional; end if feature? + module Outer; class Relative::Unclear; end; end + RUBY + result = classes.selection + expect(result.status).to eq(:unknown) + expect(result.matches.map(&:name)).to eq(['Known']) + expect(result.uncertainties.map { |value| [value.name, value.reason] }).to eq( + [['Conditional', :conditional_or_dynamic_declaration], + ['Mixed', :conflicting_declaration_kind], [nil, :unresolved_owner]] + ) + expect(classes.with_constant_name('Tester::Unclear').selection.status).to eq(:unknown) + expect(classes.with_constant_name('Tester::Unrelated').selection.status).to eq(:empty) + expect(classes.with_constant_name('Known').with_constant_name('Mixed').selection.status) + .to eq(:empty) + end + + it 'accepts Ruby constant tokens that do not fit an uppercase-letter category' do + name = "Billing::\u01C5emo\u{1F680}" + write('unicode.rb', "class #{name}; end") + expect(classes.with_constant_name("::#{name}").selection.matches.map(&:name)).to eq([name]) + invalid_names = ["#{name}::", "#{name}#suffix", "#{name} ", "#{name}; Other", "#{name}\nOther"] + invalid_names.each do |invalid| + expect { classes.with_constant_name(invalid) }.to raise_error(ArgumentError) + end + end + + it 'keeps same-spelled constants in UTF-8 and Latin-1 separate' do + utf8 = "\u00C9quipe" + latin1 = utf8.encode('ISO-8859-1') + body = "module #{utf8}; class Invoice; end; end" + @root.join('utf8.rb').binwrite(body) + @root.join('latin.rb').binwrite("# encoding: ISO-8859-1\n#{body}".encode(latin1.encoding)) + + [utf8, latin1].each do |namespace| + qualified = "#{namespace}::Invoice" + expect(classes.in_namespace(namespace).selection.matches.map(&:name)).to eq([qualified]) + match = classes.with_constant_name(qualified).selection.matches.first + expect(match.declarations.size).to eq(1) + expect(match.name).to eq(qualified) + end + expect(classes.in_namespace(utf8).in_namespace(latin1).selection.status).to eq(:empty) + expect(classes.selection.matches.size).to eq(2) + end + + it 'selects bounded transitive superclass links without using mixins or inferring Object' do + write('relations.rb', <<~RUBY) + class Root < ::Outside; end + class Independent; end + module App + class Base < ::Root; end + class Middle < Base; end + class Leaf < ::App::Middle; end + class Unrelated; include ::Root; end + end + RUBY + result = classes.in_namespace('App').descendants_of('::Root').selection + expect(result.status).to eq(:complete) + expect(result.matches.map(&:name)).to eq(%w[App::Base App::Leaf App::Middle]) + expect(result.matches.first.relationships.first.written_target).to eq('::Root') + expect(classes.with_constant_name('Independent').descendants_of('Object').selection.status) + .to eq(:empty) + expect(classes.with_constant_name('Root').descendants_of('Outside').selection.status) + .to eq(:unknown) + end + + it 'does not turn an unknown superclass, conflicting reopens or cycles into ancestry matches' do + write('edges.rb', <<~RUBY) + class Target; end + class Other; end + class Dynamic < select_base; end + class Conflict < Target; end + class Conflict < Other; end + class CycleA < CycleB; end + class CycleB < CycleA; end + class ChildOfCycle < CycleA; end + module App + module Target; end + class Masked < Target; end + class Missing < Other; end + end + RUBY + result = classes.descendants_of('Target').selection + expect(result.matches).to be_empty + expect(result.status).to eq(:unknown) + expected = [ + ['App::Masked', :unresolved_ancestry], ['App::Missing', :unresolved_ancestry], + ['ChildOfCycle', :cyclic_ancestry], ['Conflict', :unresolved_ancestry], + ['CycleA', :cyclic_ancestry], ['CycleB', :cyclic_ancestry], + ['Dynamic', :unresolved_ancestry] + ] + expect(result.uncertainties.map { |fact| [fact.name, fact.reason] }).to eq(expected) + cycle = classes.with_constant_name('ChildOfCycle').descendants_of('CycleA').selection + expect(cycle.uncertainties.map(&:reason)).to eq([:cyclic_ancestry]) + end + + it 'keeps construction lazy and rejects patterns in exact selectors' do + write('billing.rb', 'module Billing; class Invoice; end; end') + base = classes + expect(ArchUnit::Extraction).not_to receive(:extract_declarations) + selection = base.in_namespace('Billing') + expect(base).to be_frozen + expect(selection).to be_frozen + expect(selection).not_to equal(base) + expect { base.with_constant_name('Billing::*') }.to raise_error(ArgumentError) + expect { base.in_namespace('::') }.to raise_error(ArgumentError) + expect { base.descendants_of(nil) }.to raise_error(ArgumentError) + end + + it 'uses only in-scope source sites to establish a superclass' do + write('base.rb', 'class Parent; end') + write('child.rb', 'class Child < ::Parent; end') + scope = classes.with_constant_name('Child').descendants_of('Parent') + expect(scope.selection.matches.map(&:name)).to eq(['Child']) + options = ArchUnit::CheckOptions.new(source_exclusions: ['base.rb']) + result = scope.selection(options) + expect(result.status).to eq(:unknown) + expect(result.uncertainties.map(&:ancestor)).to eq(['Parent']) + end + + it 'does not resolve ancestry through a class or namespace rebound by a constant write' do + write('bindings.rb', <<~RUBY) + class Direct; end + Direct = replacement + module Billing + class Base; end + end + ::Billing = other_namespace + class Child < ::Billing::Base; end + RUBY + direct = classes.with_constant_name('Direct').selection + expect(direct.uncertainties.first.reason).to eq(:conflicting_constant_write) + base = classes.with_constant_name('Billing::Base').selection + expect(base.uncertainties.first.reason).to eq(:uncertain_namespace_owner) + child = classes.with_constant_name('Child').descendants_of('Billing::Base').selection + expect(child.uncertainties.first.reason).to eq(:unresolved_ancestry) + end + + it 'uses the same warm inventory between selectors and separates exclusions and refreshes' do + write('class.rb', 'class Alpha; end') + scope = classes + name = +'Alpha' + alpha = scope.with_constant_name(name) + name.replace('Beta') + expect(Prism).to receive(:parse).exactly(3).times.and_call_original + expect(alpha.selection.matches.map(&:name)).to eq(['Alpha']) + expect(scope.with_constant_name('Beta').selection.status).to eq(:empty) + write('class.rb', 'class Beta; end') + expect(alpha.selection.status).to eq(:complete) + excluded = ArchUnit::CheckOptions.new(source_exclusions: ['class.rb']) + expect(alpha.selection(excluded).status).to eq(:empty) + expect(alpha.selection(ArchUnit::CheckOptions.new(clear_cache: true)).status).to eq(:empty) + ArchUnit.clear_graph_cache + expect(scope.selection.matches.map(&:name)).to eq(['Beta']) + end + + it 'records its own cache-aware analysis scope and never caches a failed analysis' do + write('broken.rb', 'class Broken <') + report = ArchUnit::CLI::AnalysisReport.new + ArchUnit::Extraction::AnalysisObserver.capture(report) do + expect { classes.selection }.to raise_error(ArchUnit::SourceParseError) + write('broken.rb', 'class Fixed; end') + expect(classes.selection.status).to eq(:complete) + expect(classes.with_constant_name('Fixed').selection.status).to eq(:complete) + end + expect(report.to_h[:scopes]).to contain_exactly( + include(kind: 'source_declarations', status: 'error', cache_hits: 0), + include(kind: 'source_declarations', status: 'analyzed', cache_hits: 1, observations: 2) + ) + output = StringIO.new + ArchUnit::CLI::AnalysisText.write(report.to_h, output) + expect(output.string).to include('source declarations (dependency analysis unavailable)') + end + + it 'reports calls, declarations and dependency graphs separately in one analysis session' do + write('a.rb', "require_relative 'b'\nclass A; end") + write('b.rb', "require_relative 'a'\nstore.delete_all") + files = ArchUnit.project_files(@root) + report = ArchUnit::CLI::AnalysisReport.new + + ArchUnit::Extraction::AnalysisObserver.capture(report) do + expect(classes.selection.matches.map(&:name)).to eq(['A']) + expect(files.should_not.contain_calls_named(:delete_all).check.size).to eq(1) + witness = ArchUnit::CheckOptions.new(cycle_reporting: :witness) + expect(files.should.have_no_cycles.check(witness).first).to be_witness + end + + expect(report.to_h[:scopes].map { |scope| scope[:kind] }) + .to eq(%w[source_declarations source_calls dependency_graph]) + output = StringIO.new + ArchUnit::CLI::AnalysisText.write(report.to_h, output) + headings = ['source declarations (dependency analysis unavailable)', + 'source calls (dependency analysis unavailable)', ' — imports; analyzed'] + expect(output.string).to include(*headings) + end +end diff --git a/spec/extraction/declarations_spec.rb b/spec/extraction/declarations_spec.rb new file mode 100644 index 0000000..816aae0 --- /dev/null +++ b/spec/extraction/declarations_spec.rb @@ -0,0 +1,179 @@ +# frozen_string_literal: true + +require 'archunit/extraction/declarations' +require 'tmpdir' + +RSpec.describe ArchUnit::Extraction::Declarations do + def collect(source, file: 'app/billing.rb') + described_class.collect(Prism.parse(source), file:) + end + + it 'distinguishes syntactic lexical nesting, explicit paths, and ambiguous relative owners' do + facts = collect(<<~RUBY) + module Billing + class Invoice; end + class ::Shared::Adapter; end + class Commands::Import + class Detail; end + end + end + class Billing::Invoice; end + class Commands::Query; end + RUBY + observations = facts.namespaces.map { |fact| [fact.kind, fact.name, fact.nesting] } + expect(observations).to eq([ + [:module, 'Billing', []], + [:class, 'Billing::Invoice', ['Billing']], + [:class, 'Shared::Adapter', ['Billing']], + [:class, nil, ['Billing']], + [:class, nil, [nil, 'Billing']], + [:class, 'Billing::Invoice', []], + [:class, 'Commands::Query', []] + ]) + expect(facts.namespaces[3].written_name).to eq('Commands::Import') + expect(facts.namespaces[2].site.to_h).to eq(file: 'app/billing.rb', line: 3, column: 9) + end + + it 'records conditional and block-based declarations without treating them as certain' do + facts = collect(<<~RUBY) + if enabled? + class Optional; end + else + class Alternative; end + end + register do + module Dynamic + class Nested; end + end + end + module Features + class lookup()::Extension; end + end + RUBY + expected = [ + ['Optional', :conditional], ['Alternative', :conditional], ['Dynamic', :dynamic], + ['Dynamic::Nested', :dynamic], ['Features', :direct], [nil, :direct] + ] + expect(facts.namespaces.map { |fact| [fact.name, fact.context] }).to eq(expected) + expect(facts.namespaces.last.written_name).to be_nil + end + + it 'keeps exact declaration sites on written class, instance and unknown-scope methods' do + facts = collect(<<~RUBY) + def top_level; end + module Billing + def instance; end + def self.singleton; end + def other.unknown; end + class << self + def on_metaclass; end + def self.not_on_billing; end + end + class << other + def not_owned; end + end + end + RUBY + expected = [ + %i[top_level unknown direct], %i[instance instance direct], + %i[singleton singleton direct], %i[unknown unknown direct], + %i[on_metaclass singleton direct], %i[not_on_billing unknown direct], + %i[not_owned unknown dynamic] + ] + expect(facts.method_declarations.map { |m| [m.name, m.scope, m.context] }).to eq(expected) + expect(facts.method_declarations.first.owner).to be_nil + expect(facts.method_declarations.drop(1).map(&:owner)).to all(eq(facts.namespaces.first.site)) + end + + it 'represents parameter shapes without running expressions or expanding forwarding' do + facts = collect(<<~RUBY) + class Command + def call(a, b = raise, *extra, tail, force:, limit: raise, **opts, &block); end + def forward(...); end + def no_keywords(**nil); end + def destructure((left, right)); end + def anonymous(*, **, &); end + def plain; end + end + RUBY + signatures = facts.method_declarations.to_h do |method| + [method.name, method.parameters.map { |param| [param.kind, param.name] }] + end + expect(signatures).to eq( + call: [%i[required a], %i[optional b], %i[rest extra], %i[post tail], + %i[required_keyword force], %i[optional_keyword limit], %i[keyword_rest opts], + %i[block block]], + forward: [[:forwarding, nil]], no_keywords: [[:no_keywords, nil]], + destructure: [[:destructured, nil]], anonymous: [[:rest, nil], [:keyword_rest, nil], + [:block, nil]], + plain: [] + ) + end + + it 'retains static and unresolved written relationships instead of resolving targets' do + facts = collect(<<~RUBY) + class Invoice < build_parent() + include ::Billing::Audit, build_mixin() + self.prepend Decorator + extend OwnClassMethods if enabled? + another.include Ignored + class Entry < ::Record + end + end + RUBY + expected = [ + [:superclass, nil, :direct], [:include, '::Billing::Audit', :direct], + [:include, nil, :direct], [:prepend, 'Decorator', :direct], + [:extend, 'OwnClassMethods', :conditional], [:superclass, '::Record', :direct] + ] + observed = facts.relationships.map { |ref| [ref.kind, ref.written_target, ref.context] } + expect(observed).to eq(expected) + expect(facts.relationships.last.owner).to eq(facts.namespaces.last.site) + end + + it 'rejects malformed parse results rather than returning a partial inventory' do + expect { collect("class Known; end\nclass Broken <") } + .to raise_error(ArchUnit::SourceParseError, %r{app/billing.rb:2}) + end + + it 'returns immutable nested provenance without keeping the caller’s identifier by reference' do + file = +'app/foo.rb' + facts = collect('class C < B; def x(arg); end; end', file:) + file.replace('altered.rb') + expect(facts).to be_frozen + expect(facts.to_h.values).to all(be_frozen) + namespace = facts.namespaces.first + expect([namespace, namespace.name, namespace.nesting, namespace.site.file]).to all(be_frozen) + expect(namespace.site.file).to eq('app/foo.rb') + expect(facts.method_declarations.first.parameters).to be_frozen + expect(facts.relationships.first.written_target).to be_frozen + end + + it 'walks multiple roots separately and preserves all reopens and conflicting definitions' do + Dir.mktmpdir('archunit-declarations') do |base| + root = Pathname.new(base) + first = fixture(root.join('first'), 'module Billing; class Invoice; end; end') + second = fixture(root.join('second'), 'class Unrelated; end') + first.join('b.rb').write('class Billing::Invoice; def call; end; end') + first.join('c.rb').write('module Billing::Invoice; end') + expect(Prism).to receive(:parse).exactly(5).times.and_call_original + facts = ArchUnit::Extraction.extract_declarations(first) + invoices = facts.namespaces.select { |item| item.name == 'Billing::Invoice' } + expect(invoices.map { |item| [item.kind, item.site.file] }) + .to eq([[:class, 'a.rb'], [:class, 'b.rb'], [:module, 'c.rb']]) + options = ArchUnit::CheckOptions.new(source_exclusions: %w[b.rb c.rb]) + limited = ArchUnit::Extraction.extract_declarations(first, options:) + expect(limited.namespaces.map(&:name)).to eq(%w[Billing Billing::Invoice]) + expect(limited.method_declarations).to be_empty + expect(ArchUnit::Extraction.extract_declarations(second).namespaces.map(&:name)) + .to eq(['Unrelated']) + end + end + + def fixture(root, source) + root.mkpath + root.join('Gemfile').write("raise 'do not run the project Gemfile'") + root.join('a.rb').write("#{source}\nraise 'do not run the project source'") + root + end +end