Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ jobs:
- name: Exercise opt-in declaration extraction
run: bundle exec ruby scripts/check_declarations.rb

- name: Exercise declared method signatures
run: bundle exec ruby scripts/check_method_signatures.rb

- name: Exercise architecture presets
run: bundle exec ruby scripts/check_presets.rb

Expand Down Expand Up @@ -185,6 +188,7 @@ jobs:
ruby scripts/check_analysis_diagnostics.rb
ruby scripts/check_baselines.rb
ruby scripts/check_declarations.rb
ruby scripts/check_method_signatures.rb
ruby scripts/check_presets.rb
ruby scripts/check_named_calls.rb
ruby scripts/check_documentation_examples.rb
Expand Down
31 changes: 31 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,37 @@ selector covers all in-scope declaration sites for a class, not a particular fol
Use `CheckOptions.new(source_exclusions: ...)` to limit the source set. Cached declaration facts
refresh with `clear_cache: true` or `ArchUnit.clear_graph_cache`.

### Declared method signatures (unreleased)

~~~ ruby
shape = ArchUnit::MethodSignature.new(name: :call, positional: 1, keywords: %i[actor request_id])
rule = ArchUnit.project_classes(root).in_namespace('Commands').should.declare_method(shape)
ArchUnit.assert_passes(rule)
~~~

The rule requires an ordinary `def` on each selected class that accepts the specified call.
`positional` is the number passed, not the number written. `keywords` is the exact set passed:
omitting a required keyword fails, and a keyword-rest parameter accepts extras. Implicit conversion
to a positional Hash is not a named keyword interface. `scope: :singleton` checks `def self.call`
and `class << self`; `block: :declared` requires explicit block capture or forwarding syntax.
The default is `scope: :instance, block: :any`.
Use method and keyword names in their declared source encoding for non-ASCII identifiers.

This is declaration-only: methods inherited or supplied by mixins, aliasing, or metaprogramming
do not satisfy it. It does not prove public visibility, receiver behavior, or return types.
Conditional definitions, ambiguous class selection, or conflicting signatures fail as unknown.
Multiple known declarations satisfy the rule if they all accept the requested call. Empty scopes
fail unless explicitly allowed; that option does not suppress unknown results. The negative mood
is not offered.

The same scope is available as `project_classes` in a named CLI rule. JSON adds a
`method_signature` object carrying the expected shape, observed candidates and source locations.
Non-ASCII identifiers in legacy encodings are reported with `text`, `encoding`, and hex
`bytes` rather than a bare string; this preserves distinct Ruby names with the same spelling.
Confirmed failures can use baselines; the fingerprint includes the normalized selector and
expected shape. Unknowns fail a plain CLI check (exit 1) and reject baseline creation or use
before any accepted-debt write (exit 2).

## Checking and test frameworks

Every architecture rule includes `ArchUnit::Checkable` and exposes `check(options = nil)`. It returns
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
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.
- Require written instance or singleton methods with a compatible call shape, reporting uncertainty
as a failure rather than counting it as a supported signature or accepted debt.
- 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.
Expand Down
8 changes: 8 additions & 0 deletions benchmark/study/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,14 @@ Ruby allocations respectively. The median post-GC heap increase after the cold c
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.

Run `bundle exec ruby benchmark/study/method_signatures.rb` to reuse that fixture for 20
declaration-based rules (ten passing, ten rejecting all 499 subclasses). Every trial checks all
findings before accepting the measurement. Five Windows / Ruby 4.0.6 trials measured a median
**560,233 allocations with one shared inventory** versus **2,244,077** when deliberately
rebuilding before each rule. Median added Ruby heap after GC for the shared run was about
**287 KiB**. The timings (1.78 s and 14.98 s respectively) and startup sample were taken with
other checks running on the local machine; do not read them as isolated latency guarantees.

## Real production source

`real_project.rb` checks pinned Discourse `2de9c9be4f89e392fe500dd27f928d6b1184bf09`, with three
Expand Down
2 changes: 1 addition & 1 deletion benchmark/study/declaration_selection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,4 @@ def median(samples)
end
end

DeclarationSelectionStudy.run
DeclarationSelectionStudy.run if $PROGRAM_NAME == __FILE__
58 changes: 58 additions & 0 deletions benchmark/study/method_signatures.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# frozen_string_literal: true

require_relative 'declaration_selection'

# Compares one shared index with deliberately refreshing it before each rule.
module MethodSignatureStudy
STUDY = DeclarationSelectionStudy
RULES = 20
private_constant :STUDY, :RULES

module_function

def run
startup = STUDY.measure_default_load
Dir.mktmpdir('archunit-signature-bench') do |directory|
root = Pathname.new(directory)
STUDY.fixture(root)
rules = fixtures(root)
result = measurements(rules).merge(ruby: RUBY_DESCRIPTION, startup:, rules: RULES,
files: STUDY::FILES, trials: STUDY::TRIALS)
puts JSON.pretty_generate(result)
end
end

def fixtures(root)
scope = ArchUnit.project_classes(root).descendants_of('Node0')
Array.new(RULES) do |index|
signature = ArchUnit::MethodSignature.new(name: :call, positional: index.even? ? 1 : 2)
scope.should.declare_method(signature)
end
end

def measurements(rules)
shared, refresh, retained = Array.new(STUDY::TRIALS) { paired_sample(rules) }.transpose
{ shared_median: STUDY.median(shared), refreshed_median: STUDY.median(refresh),
retained_heap_bytes: retained.sort.fetch(STUDY::TRIALS / 2) }
end

def paired_sample(rules)
ArchUnit.clear_graph_cache
before = STUDY.heap_bytes
shared = STUDY.measure { verify(rules) }
retained = STUDY.heap_bytes - before
clear = ArchUnit::CheckOptions.new(clear_cache: true)
refreshed = STUDY.measure { verify(rules, clear) }
[shared, refreshed, retained]
end

def verify(rules, options = nil)
rules.each_with_index do |rule, index|
results = rule.check(options)
expected = index.even? ? 0 : STUDY::FILES - 1
raise 'wrong number of findings' unless results.size == expected && results.none?(&:unknown?)
end
end
end

MethodSignatureStudy.run
34 changes: 34 additions & 0 deletions design/declared-method-signatures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Declared method signatures (#105)

The first rule reads “project classes in Commands should declare method call with this signature”:

~~~ruby
signature = ArchUnit::MethodSignature.new(name: :call, positional: 1, keywords: %i[actor request_id])
rule = ArchUnit.project_classes.in_namespace('Commands').should.declare_method(signature)
~~~

This is the **declared-here** milestone: an ordinary `def` on each selected class must accept the
given call shape. Inheritance, mixins, aliases, `define_method`, and `method_missing` do not count as
direct declarations. The rule does not claim runtime visibility, method behavior, or effective API
coverage. A separate effective-lookup feature needs precedence, alias, reflection, and uncertainty
decisions before it can share any public meaning of “implements”. Negative mood is not exposed.

Positional options describe the number passed (optional/rest parameters may accept it).
Keywords describe the exact named arguments passed: extra required keywords invalidate the
contract, `**kwargs` accepts extras, and `**nil` accepts no nonempty keyword set. Implicit Ruby
conversion of keywords to a positional Hash is not a declared keyword interface.
`scope: :singleton` matches methods written as `def self.name` or `class << self`.
`block: :declared` requires `&block`, anonymous `&`, or forwarding `...`; this does not prove
that code invokes a block. Without that option, no explicit block-capture parameter is required.

Conditional declarations, ambiguous ownership and mixed compatible/incompatible reopens are
unknown. If all direct candidates accept the shape, a compatible shape is known without choosing
load order. If none accepts it, the signature is incompatible. Missing written declarations,
incompatible shapes, and unknowns are distinct findings; all fail the check. A known empty
selection follows the standard empty-test guard. Unknowns cannot be suppressed with
`allow_empty_tests` or written to or accepted by an accepted-debt baseline.

Confirmed failures use a structured identity covering the normalized selector, policy version,
expected shape, class name, and observed shape/file evidence without line numbers. The observed
source snapshot has its own `source_declarations` context and the same exclusions/refresh rules as
class selection. The dependency graph does not change.
2 changes: 2 additions & 0 deletions lib/archunit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
require_relative 'archunit/common/projection/project_edges'
require_relative 'archunit/common/projection/project_to_nodes'
require_relative 'archunit/classes/fluentapi/classes'
require_relative 'archunit/classes/fluentapi/method_signature'
require_relative 'archunit/common/projection/project_cycles'
require_relative 'archunit/extraction/locate_project'
require_relative 'archunit/extraction/enumerate_source_files'
Expand Down Expand Up @@ -109,6 +110,7 @@ module ArchUnit
MetricPredicateViolation = Metrics::Assertion::MetricPredicateViolation
CustomMetricViolation = Metrics::Assertion::CustomMetricViolation
TestViolation = Testing::TestViolation
MethodSignatureViolation = Classes::Assertion::MethodSignatureViolation
TestResult = Testing::TestResult
ColorUtils = Testing::ColorUtils
ViolationFactory = Testing::ViolationFactory
Expand Down
48 changes: 48 additions & 0 deletions lib/archunit/classes/assertion/callable_shape.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# frozen_string_literal: true

module ArchUnit
module Classes
module Assertion
# Checks call compatibility using only a method's written parameter shapes.
module CallableShape
REQUIRED = %i[required post destructured].freeze
private_constant :REQUIRED

def self.matches?(parameters, signature)
groups = parameters.group_by(&:kind)
accepts_positionals?(groups, signature.positional) &&
accepts_keywords?(groups, signature.keywords) &&
accepts_block?(groups, signature.block)
end

def self.accepts_positionals?(groups, count)
minimum = REQUIRED.sum { |key| groups.fetch(key, []).size }
return false if count < minimum
return true if groups.key?(:rest) || groups.key?(:forwarding)

count <= minimum + groups.fetch(:optional, []).size
end

def self.accepts_keywords?(groups, requested)
return requested.empty? if groups.key?(:no_keywords)

required = names(groups, :required_keyword)
return false unless (required - requested).empty?
return true if groups.key?(:keyword_rest) || groups.key?(:forwarding)

(requested - required - names(groups, :optional_keyword)).empty?
end

def self.names(groups, kind)
groups.fetch(kind, []).map { |parameter| parameter.name.to_s }
end

def self.accepts_block?(groups, policy)
policy == :any || groups.key?(:block) || groups.key?(:forwarding)
end
private_class_method :accepts_positionals?, :accepts_keywords?, :names, :accepts_block?
end
private_constant :CallableShape
end
end
end
28 changes: 28 additions & 0 deletions lib/archunit/classes/assertion/empty_class_selection_violation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

require_relative '../../common/assertion/empty_test_violation'

module ArchUnit
module Classes
module Assertion
# The ordinary empty-test defense with the actual class selector attached.
class EmptyClassSelectionViolation < Common::Assertion::EmptyTestViolation
attr_reader :scope

def initialize(scope)
@scope = scope
super(filters: [])
end

def ==(other)
other.instance_of?(self.class) && scope == other.scope
end
alias eql? ==

def hash
[self.class, scope].hash
end
end
end
end
end
39 changes: 39 additions & 0 deletions lib/archunit/classes/assertion/method_signature_violation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# frozen_string_literal: true

require_relative '../../common/assertion/violation'

module ArchUnit
module Classes
module Assertion
# Data describing a missing, incompatible, or uncertain written method contract.
class MethodSignatureViolation < Common::Assertion::Violation
Finding = Data.define(:owner, :expected, :reason, :candidates, :declarations, :scope,
:ancestor)
CONFIRMED = %i[missing_declaration incompatible_signature].freeze
private_constant :CONFIRMED

attr_reader :finding

def initialize(finding)
raise ArgumentError, 'finding must be a method finding' unless finding.is_a?(Finding)

@finding = finding
super()
end

def unknown?
!CONFIRMED.include?(finding.reason)
end

def ==(other)
other.is_a?(self.class) && finding == other.finding
end
alias eql? ==

def hash
[self.class, finding].hash
end
end
end
end
end
64 changes: 64 additions & 0 deletions lib/archunit/classes/assertion/method_signatures.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# frozen_string_literal: true

require_relative 'callable_shape'
require_relative 'method_signature_violation'

module ArchUnit
module Classes
# Pure checks on explicit class/method declarations.
module Assertion
module_function

def gather_method_signature_violations(selection, signature, scope)
definite = selection.matches.filter_map { |klass| check_signature(klass, signature, scope) }
unresolved = selection.uncertainties.map do |subject|
signature_violation(subject, signature, scope, [].freeze, subject.reason)
end
definite + unresolved
end

def check_signature(subject, signature, scope)
candidates = method_candidates(subject, signature)
reason = signature_failure(candidates, signature)
signature_violation(subject, signature, scope, candidates, reason) if reason
end
private_class_method :check_signature

def method_candidates(subject, signature)
subject.method_declarations.select do |method|
(method.scope == signature.scope || method.scope == :unknown) &&
method.name.to_s == signature.name
end.freeze
end
private_class_method :method_candidates

def signature_failure(candidates, signature)
return :missing_declaration if candidates.empty?
return :uncertain_method_declaration if candidates.any? { |method| uncertain?(method) }

matching = candidates.count do |method|
CallableShape.matches?(method.parameters, signature)
end
return :incompatible_signature if matching.zero?

:conflicting_signatures if matching != candidates.size
end
private_class_method :signature_failure

def uncertain?(method)
method.context != :direct || method.scope == :unknown
end
private_class_method :uncertain?

def signature_violation(subject, expected, scope, candidates, reason)
ancestor = subject.ancestor if subject.respond_to?(:ancestor)
finding = MethodSignatureViolation::Finding.new(
owner: subject.name, expected:, reason:, candidates:, declarations: subject.declarations,
scope:, ancestor:
)
MethodSignatureViolation.new(finding)
end
private_class_method :signature_violation
end
end
end
Loading
Loading