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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ jobs:
run: |
gem install pkg/archunit.gem --no-document
ruby scripts/check_dependency_analysis.rb
ruby scripts/check_constant_writes.rb
ruby -e "
require 'json'
require 'stringio'
Expand Down
5 changes: 5 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,11 @@ ambiguous definitions, inherited-member lookup, and dynamic metaprogramming stay
the bounded contract in the main guide. Namespaces that fail to stabilize within eight index passes
fall back to import-only results. Unknown third-party constants do not create architecture violations.

Declarations include ordinary `=` and conditional `||=`, with lexical/qualified/root-qualified
ownership and definition evidence. This does not predict runtime execution or load order. Multiple
definition files remain ambiguous; update-only compound and multiple-assignment forms are not
inferred as new declaration owners.

Expanded edges include `:constant_reference` in `import_kinds` and retain `DependencyEvidence` with
names and source lines in `edge.evidence` and JSON reports. An import and a constant use supporting
the same file pair merge into one edge. Import-only edge evidence stays empty for compatibility;
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
- Document verbosity, CI log artifacts, and existing colored violation reports.

- Add opt-in project constant-reference dependencies with lexical lookup and conservative ambiguity handling.
- Index lexical, qualified, and root-qualified `||=` declarations in expanded analysis without
executing source or changing import-only mode.
- Infer import paths from safely known local literal strings without evaluating application code.
- Preserve dependency source evidence in expanded mode through graph merging and JSON reporting,
while keeping import-only edge values compatible with existing consumers.
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,12 @@ It supports lexical nesting, compact namespaces, root-qualified names, and expli
lookup; top-level `module A::B` does not. A nearer namespace shadows a root namespace even when its
requested child is missing.

Ordinary `=` and conditional `||=` constant declarations are indexed, including qualified and
root-qualified forms. A conditional declaration records a possible definition file, not proof that
the assignment executes or its resulting value. Multiple candidate files stay ambiguous. Other
compound writes (`&&=`, operators) and multiple-assignment declarations are not inferred as new
definition owners; unsupported targets remain unresolved rather than inventing ownership.

References with multiple definition files (reopened classes/modules), missing definitions, and
dynamic definitions are omitted, never assigned to an arbitrary file. `Alias = Original` defines
`Alias` in its own file and records the reference to `Original`; lookup through aliases such as
Expand Down
5 changes: 5 additions & 0 deletions lib/archunit/extraction/constant_visitor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ def visit_constant_path_write_node(node)
visit(node.value)
end

# ||= introduces a possible declaration, like a conditional ordinary assignment.
# This records ownership, not whether the branch executes or what value it stores.
alias visit_constant_or_write_node visit_constant_write_node
alias visit_constant_path_or_write_node visit_constant_path_write_node

def visit_constant_read_node(node)
record_reference(node.name.to_s, node)
end
Expand Down
34 changes: 34 additions & 0 deletions scripts/check_constant_writes.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# frozen_string_literal: true

require 'archunit'
require 'fileutils'
require 'tmpdir'

# Also runs outside Bundler after installing the built gem in CI.
declarations = [
'module Db; DEFAULT ||= 42; end',
'module Db; end; Db::DEFAULT ||= 42',
'module Db; end; ::Db::DEFAULT ||= 42'
].freeze
options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants)
Dir.mktmpdir('archunit-installed-constant-writes') do |root|
%w[api db].each { |folder| FileUtils.mkdir_p(File.join(root, 'app', folder)) }
File.write(File.join(root, 'Gemfile'), "raise 'must not execute project source'\n")
File.write(File.join(root, 'app/api/request.rb'), '::Db::DEFAULT')
scope = ArchUnit.project_files(root).in_path('app/api/**')
forbidden = scope.should_not.depend_on_files.in_path('app/db/**')
allowed = scope.should.depend_on_files.in_path('app/db/**')
declarations.each do |declaration|
File.write(File.join(root, 'app/db/settings.rb'), declaration)
ArchUnit.clear_graph_cache
violations = forbidden.check(options)
abort 'conditional constant dependency missing' unless violations.length == 1
edge = violations.first.dependency.cumulated_edges.first
abort 'constant definition evidence missing' unless edge.evidence.first.target_line_number == 1
abort 'import-only behavior changed' unless forbidden.check.empty?
ArchUnit.assert_passes(allowed, options)
end
puts 'Conditional constant definitions passed in the installed-gem API.'
ensure
ArchUnit.clear_graph_cache
end
1 change: 1 addition & 0 deletions spec/ci/workflow_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"bundle exec ruby -w -Ilib -e \"require 'archunit'\"",
'gem build archunit.gemspec --strict --output pkg/archunit.gem',
'gem install pkg/archunit.gem', "require 'archunit'", 'ArchUnit.project_files',
'ruby scripts/check_constant_writes.rb',
'depend_on_files', 'depend_on_external_modules', "matching('json')",
'adhere_to', 'file.extension', 'ArchUnit::Checkable',
'ArchUnit.assert_passes', 'ArchUnit.format_violations',
Expand Down
113 changes: 113 additions & 0 deletions spec/extraction/constant_writes_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# frozen_string_literal: true

require 'fileutils'
require 'json'
require 'tmpdir'

RSpec.describe 'constant-write dependency analysis' do
let(:options) { ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants) }

around do |example|
Dir.mktmpdir('archunit-constant-writes') do |directory|
@root = File.realpath(directory)
source('Gemfile', "raise 'must not execute'\n")
source('app/api/request.rb', 'module Api; class Request; def call = ::Db::DEFAULT; end; end')
ArchUnit.clear_graph_cache
example.run
ensure
ArchUnit.clear_graph_cache
end
end

def source(path, contents)
file = File.join(@root, path)
FileUtils.mkdir_p(File.dirname(file))
File.write(file, contents)
end

def rule(mood = :should_not)
ArchUnit.project_files(@root).in_path('app/api/**')
.public_send(mood).depend_on_files.in_path('app/db/**')
end

def edges(**keywords)
ArchUnit::Extraction.extract_graph(@root, options:, **keywords).reject do |edge|
edge.source == edge.target
end
end

{
lexical: 'module Db; DEFAULT ||= 42; end',
qualified: 'module Db; end; Db::DEFAULT ||= 42',
root_qualified: 'module Db; end; ::Db::DEFAULT ||= 42'
}.each do |form, declaration|
it "resolves #{form} ||= definitions through the public file rule without executing them" do
source('app/db/settings.rb', "#{declaration}\nraise 'must not execute'\n")
violations = rule.check(options)
expect(violations.length).to eq(1)
attributes = {
source: 'app/api/request.rb', target: 'app/db/settings.rb',
import_kinds: [:constant_reference],
evidence: contain_exactly(have_attributes(name: '::Db::DEFAULT', target_line_number: 1))
}
expect(edges).to contain_exactly(have_attributes(attributes))
ArchUnit.assert_passes(rule(:should), options)
expect(rule.check).to be_empty
end
end

it 'preserves nested lexical ownership instead of attributing a same-name root constant' do
source('lib/root.rb', 'DEFAULT = 1')
source('app/db/settings.rb', 'module Outer; module Db; DEFAULT ||= 42; end; end')
source('app/api/request.rb', '::Outer::Db::DEFAULT')
expect(edges).to contain_exactly(have_attributes(target: 'app/db/settings.rb'))
end

it 'visits right-hand dependencies and merges parallel import/reference evidence' do
source('app/db/settings.rb', 'module Db; DEFAULT ||= ::Seed::VALUE; end')
source('lib/seed.rb', 'module Seed; VALUE = 42; end')
source('app/api/request.rb', "require_relative '../db/settings'\n::Db::DEFAULT\n")
dependency = edges.find { |edge| edge.source == 'app/api/request.rb' }
expect(dependency.import_kinds).to match_array(%i[require_relative constant_reference])
expect(dependency.evidence.map(&:kind)).to match_array(%i[require_relative constant_reference])
expect(edges).to include(have_attributes(source: 'app/db/settings.rb', target: 'lib/seed.rb'))
expect(rule.check(options).length).to eq(1)
end

it 'treats multiple candidate definition files as ambiguous rather than selecting one' do
%w[settings other].each do |name|
source("app/db/#{name}.rb", 'module Db; DEFAULT ||= 42; end')
end
profile = ArchUnit::Extraction::ExtractionProfile.new
expect(edges(profile:)).to be_empty
expect(profile.counters.fetch(:ambiguous_constant_references)).to eq(1)
end

it 'refreshes changed conditional definitions only with the documented cache-clearing option' do
source('app/db/settings.rb', 'module Db; DEFAULT ||= 42; end')
expect(rule.check(options).length).to eq(1)
source('app/db/settings.rb', 'module Db; OTHER ||= 42; end')
expect(rule.check(options).length).to eq(1)
expect(rule.check(options.with(clear_cache: true))).to be_empty
end

it 'does not invent declarations from update-only or unsupported multiple-assignment forms' do
['DEFAULT &&= 42', 'DEFAULT += 42', 'DEFAULT, OTHER = 1, 2'].each do |assignment|
source('app/db/settings.rb', "module Db; #{assignment}; end")
expect(rule.check(options.with(clear_cache: true))).to be_empty
end
end

it 'shares the same conditional-definition edges with layers, slices, and JSON reports' do
source('app/db/settings.rb', 'module Db; DEFAULT ||= 42; end')
layers = ArchUnit.project_layers(@root)
.layer('api').defined_by('app/api/**')
.layer('db').defined_by('app/db/**')
.where_layer('api').may_not_depend_on_layers('db')
slices = ArchUnit.project_slices(@root).defined_by('app/(**)/')
expect(layers.check(options).length).to eq(1)
expect(slices.should_not.contain_dependency('api', 'db').check(options).length).to eq(1)
report = JSON.parse(ArchUnit.project_graph(@root).with_check_options(options).to_json)
expect(report.fetch('edges').first.fetch('evidence').first.fetch('name')).to eq('::Db::DEFAULT')
end
end
Loading