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 @@ -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

Expand Down Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,31 @@ for a calculation over `ClassInfo`; zone guards are `not_in_zone_of_pain` and

<a id="frameworks"></a>

## 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
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions benchmark/study/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 90 additions & 0 deletions benchmark/study/declaration_selection.rb
Original file line number Diff line number Diff line change
@@ -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
62 changes: 62 additions & 0 deletions design/declaration-facts.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions lib/archunit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
86 changes: 86 additions & 0 deletions lib/archunit/classes/fluentapi/class_filters.rb
Original file line number Diff line number Diff line change
@@ -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
63 changes: 63 additions & 0 deletions lib/archunit/classes/fluentapi/class_scope.rb
Original file line number Diff line number Diff line change
@@ -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
Loading