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 architecture presets
run: bundle exec ruby scripts/check_presets.rb

- name: Exercise named method calls
run: bundle exec ruby scripts/check_named_calls.rb

- name: Exercise documented library examples
run: bundle exec ruby scripts/check_documentation_examples.rb

Expand Down Expand Up @@ -179,6 +182,7 @@ jobs:
ruby scripts/check_analysis_diagnostics.rb
ruby scripts/check_baselines.rb
ruby scripts/check_presets.rb
ruby scripts/check_named_calls.rb
ruby scripts/check_documentation_examples.rb
ruby scripts/check_cli.rb
ruby -e "
Expand Down
24 changes: 24 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,30 @@ dense graphs can have exponentially many results. Scope cycle rules to meaningfu

<a id="layer-rules"></a>

### Named method calls (unreleased)

Use `should_not.contain_calls_named(:delete_all)` or pass a nonempty array of exact names. The
optional `ArchUnit::NamedCallOptions.new(receiver: :bare)` limits the rule to calls with no
explicit receiver. The default `:any` includes explicit `self`, other receivers, and safe
navigation. The positive mood is not supported.

This is a syntactic check. A call to a locally defined method with the same name also matches;
Prism distinguishes method definitions, comments, strings, and local variable reads from calls.
Ordinary operators and attribute/index assignments are included when parsed as explicit calls.
Implicit sends in compound assignments, `receiver.()`, and targets of `send` or `public_send`
are not inferred. Neither alias expansion nor runtime receiver types are checked.

CLI violations add a `call` object with `file`, `name`, `receiver` (`bare`, `self` or
`explicit`), `safe_navigation`, and one-based `line` and byte `column` of the call token.
The `source_calls` analysis scope has no dependency counts. A baseline matches occurrences by
file, method name, receiver form and safe-navigation flag, not receiver identity or line number.
It accepts at most the previously recorded number of matching calls.

Named-call rules share a cached source inventory per project and effective source exclusions. They
don't change or reuse the dependency graph: a mixed graph and call suite has separate source passes.
Use `clear_cache: true` or `ArchUnit.clear_graph_cache` after source edits in a long-lived process.
Included parse errors fail the check, even when the malformed file isn't selected by the rule.

## Layer rules

Use `ArchUnit.project_layers(project_locator = nil)` to name architectural layers and then declare
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## 1.1.1 (unreleased)

- Add file-scoped named method-call restrictions, with an optional bare-call mode, source
coordinates in test and CLI output, and explicit occurrence-based baseline support.

- Add opt-in static Rails association dependencies for explicit literal `class_name` on supported
model-body macros, with evidence, isolated baselines and CLI uncertainty counts. No Rails boot,
automatic inflection, or change to existing default graphs.
Expand Down
12 changes: 12 additions & 0 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,18 @@ rule = ArchUnit.project_files.in_folder('app/services/**')
)
~~~

### Keep write calls out of query files (unreleased)

~~~ruby
rule = ArchUnit.project_files.in_path('app/queries/**')
.should_not.contain_calls_named(%i[delete_all destroy_all])
expect(rule).to pass
~~~

`store.read` is allowed; `store.delete_all` is reported at the written call site. This also
matches the same spelling on unrelated receivers, and does not infer `send(:delete_all)`.
Use it for a naming policy in a known part of your own code, not as proof of read-only behavior.

### Layer Dependencies

Named layers express an allowlist or blocklist over groups of files:
Expand Down
3 changes: 3 additions & 0 deletions benchmark/semantic/cases.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
{
"name": "explicit_constant_forbidden_method",
"source": "module Api; class Request; def call = ::Db::Store.delete_all; end; end",
"expected_named_calls": 1,
"expected_direct_db": 1,
"comparator_policy": "method_name"
},
{
"name": "explicit_constant_allowed_method",
"source": "module Api; class Request; def call = ::Db::Store.read; end; end",
"expected_named_calls": 0,
"expected_direct_db": 1,
"comparator_policy": "method_name"
},
Expand All @@ -20,6 +22,7 @@
{
"name": "dynamic_parameter_receiver",
"source": "module Api; class Request; def call(store) = store.delete_all; end; end",
"expected_named_calls": 1,
"expected_direct_db": 0,
"comparator_policy": "method"
},
Expand Down
13 changes: 12 additions & 1 deletion benchmark/semantic/probes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,23 @@ def library_facts(root, specification)
options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants)
graph = ArchUnit::Extraction.extract_graph(root, options:, profile:)
count = boundary_count(root, specification, options)
calls = named_call_count(root, specification)
{ name: specification['name'], direct_file_boundary_violations: count,
counters: profile.counters, syntax: syntax_facts(specification),
named_call_violations: calls, counters: profile.counters,
syntax: syntax_facts(specification),
metric_method_fields: ArchUnit::MetricMethodInfo.members,
has_semantic_method_edges: graph.any? { |edge| edge.respond_to?(:resolved_method) } }
end

def named_call_count(root, specification)
file = ArchUnit.project_files(root).in_path('app/api/**')
count = file.should_not.contain_calls_named(:delete_all).check.length
return count unless specification.key?('expected_named_calls')
return count if specification['expected_named_calls'] == count

raise "unexpected named call count: #{specification['name']}"
end

def boundary_count(root, specification, options)
rule = ArchUnit.project_files(root).in_path('app/api/**')
.should_not.depend_on_files.in_path('app/db/**')
Expand Down
2 changes: 2 additions & 0 deletions lib/archunit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ module ArchUnit
Violation = Common::Assertion::Violation
EmptyTestViolation = Common::Assertion::EmptyTestViolation
CheckOptions = Common::FluentApi::CheckOptions
NamedCallOptions = Files::FluentApi::NamedCallOptions
NamedCallViolation = Files::Assertion::NamedCallViolation
Checkable = Common::FluentApi::Checkable
ImportKind = Common::Extraction::ImportKind
Edge = Common::Extraction::Edge
Expand Down
8 changes: 7 additions & 1 deletion lib/archunit/cli/analysis_text.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,20 @@ def self.write(analysis, out)
end

def self.write_scope(scope, out)
mode = scope[:dependency_analysis] || 'source metrics (dependency analysis unavailable)'
mode = scope[:dependency_analysis] || source_scope(scope)
out.puts(" Scope #{scope[:id]}: #{scope[:project_root]} — #{mode}; #{scope[:status]}")
counts = scope[:counters].map do |name, value|
"#{name}=#{value.nil? ? 'unavailable' : value}"
end
out.puts(" #{counts.join(', ')}; cache_hits=#{scope[:cache_hits]}")
end
private_class_method :write_scope

def self.source_scope(scope)
name = scope[:kind] == 'source_calls' ? 'source calls' : 'source metrics'
"#{name} (dependency analysis unavailable)"
end
private_class_method :source_scope
end
end
end
11 changes: 9 additions & 2 deletions lib/archunit/cli/baseline_identity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module BaselineIdentity
Files::Assertion::FileDependencyViolation => :dependency,
Files::Assertion::ExternalModuleDependencyViolation => :dependency,
Files::Assertion::FilePatternViolation => :pattern,
Files::Assertion::NamedCallViolation => :named_call,
Files::Assertion::CycleViolation => :cycle,
Layers::Assertion::LayerDependencyViolation => :layer,
Slices::Assertion::SliceDependencyViolation => :slice,
Expand Down Expand Up @@ -51,6 +52,12 @@ def self.pattern(value)
'negated' => value.negated? }
end

def self.named_call(value)
call = value.call
{ 'file' => identifier(call.file), 'name' => call.name, 'receiver' => call.receiver.to_s,
'safe_navigation' => call.safe_navigation }
end

def self.filter(value)
[value.regexp.source, value.regexp.options, value.target.to_s, value.matching.to_s,
value.exclusions.map { |item| filter(item) }.sort_by { |item| JSON.generate(item) }]
Expand Down Expand Up @@ -78,8 +85,8 @@ def self.identifier(value)

normalized
end
private_class_method :dependency, :edge, :layer, :slice, :pattern, :filter, :cycle,
:threshold, :identifier
private_class_method :dependency, :edge, :layer, :slice, :pattern, :named_call, :filter,
:cycle, :threshold, :identifier
end
end
end
11 changes: 10 additions & 1 deletion lib/archunit/cli/report.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,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: (violations || []).map { |violation| violation_payload(violation) }
violations: violation_payloads(violations)
}
end

Expand Down Expand Up @@ -86,6 +86,15 @@ def violation_payload(violation)
{ type: violation.class.name, message: formatted.message, details: formatted.details }
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)
Expand Down
10 changes: 10 additions & 0 deletions lib/archunit/common/extraction/call_site.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# frozen_string_literal: true

module ArchUnit
module Common
module Extraction
# A direct call as written in Ruby source, without inferred receiver type.
CallSite = Data.define(:file, :name, :receiver, :safe_navigation, :line, :column)
end
end
end
4 changes: 2 additions & 2 deletions lib/archunit/extraction/analysis_snapshot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ def self.graph(root, patterns, options, counters: nil, status: 'analyzed')
build(root, patterns, settings, graph_counters(options, counters), status)
end

def self.source(discovery, count: nil, status: 'analyzed')
def self.source(discovery, count: nil, status: 'analyzed', kind: 'source_metrics')
settings = {
kind: 'source_metrics', dependency_analysis: nil, rails_imports: nil, load_paths: nil
kind:, dependency_analysis: nil, rails_imports: nil, load_paths: nil
}
counters = COUNTERS.to_h { |key| [key, key == :source_files ? count : nil] }
build(discovery.root, discovery.patterns, settings, counters, status)
Expand Down
2 changes: 2 additions & 0 deletions lib/archunit/extraction/extract_graph.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
require_relative 'analysis_observer'
require_relative 'graph_assembly'
require_relative 'graph_views'
require_relative 'named_call_analysis'

module ArchUnit
# Assembles the normalized dependency graph for a Ruby project.
Expand Down Expand Up @@ -54,6 +55,7 @@ def extract_graph_entry(

def clear_graph_cache
GRAPH_CACHE_MUTEX.synchronize { graph_cache.clear }
clear_named_calls
nil
end

Expand Down
76 changes: 76 additions & 0 deletions lib/archunit/extraction/named_call_analysis.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# frozen_string_literal: true

require_relative 'analysis_observer'
require_relative 'analysis_snapshot'
require_relative 'enumerate_source_files'
require_relative 'extract_imports'
require_relative 'locate_project'
require_relative 'named_call_visitor'

module ArchUnit
# Ruby-specific extraction of source facts for file policies.
module Extraction
# Independent, on-demand source facts; graph-only checks never collect or cache them.
NamedCalls = Data.define(:by_file, :snapshot)
NAMED_CALL_MUTEX = Mutex.new
private_constant :NamedCalls, :NAMED_CALL_MUTEX

module_function

# @api private
def extract_named_calls(locator, options:)
root = Pathname.new(locate_project(locator))
patterns = resolve_project_exclude_patterns(
root, nil, source_exclusions: options.source_exclusions
)
entry, cache_hit = fetch_named_calls(root, patterns.sort.freeze, options)
AnalysisObserver.record(entry.snapshot, cache_hit:)
entry.by_file
end

def clear_named_calls
NAMED_CALL_MUTEX.synchronize { @named_call_cache&.clear }
end
private_class_method :clear_named_calls

def fetch_named_calls(root, patterns, options)
key = [root.to_s, patterns]
NAMED_CALL_MUTEX.synchronize do
named_call_cache.delete(key) if options.clear_cache?
entry = named_call_cache[key]
return [entry, true] if entry

[named_call_cache[key] = build_named_calls(root, patterns), false]
end
rescue StandardError
AnalysisObserver.record(call_snapshot(root, patterns, nil, 'error'))
raise
end
private_class_method :fetch_named_calls

def build_named_calls(root, patterns)
files = enumerate_source_files_with_patterns(root, patterns)
by_file = files.to_h { |file| [file, calls_in_file(root, file)] }.freeze
NamedCalls.new(by_file:, snapshot: call_snapshot(root, patterns, files.length, 'analyzed'))
end
private_class_method :build_named_calls

def calls_in_file(root, file)
visitor = NamedCallVisitor.new(file)
visitor.visit(parse_source(root.join(file), nil).value)
visitor.calls.sort_by { |call| [call.line, call.column] }.freeze
end
private_class_method :calls_in_file

def call_snapshot(root, patterns, count, status)
discovery = SourceDiscovery.new(root:, patterns:, files: [])
AnalysisSnapshot.source(discovery, count:, status:, kind: 'source_calls')
end
private_class_method :call_snapshot

def named_call_cache
@named_call_cache ||= {}
end
private_class_method :named_call_cache
end
end
42 changes: 42 additions & 0 deletions lib/archunit/extraction/named_call_visitor.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# frozen_string_literal: true

require 'prism'
require_relative '../common/extraction/call_site'

module ArchUnit
module Extraction
# Collects syntactic calls. Generated and dynamically dispatched names are not inferred.
class NamedCallVisitor < Prism::Visitor
attr_reader :calls

def initialize(file)
super()
@file = file
@calls = []
end

def visit_call_node(node)
@calls << call_site(node) if node.message_loc
super
end

private

def call_site(node)
location = node.message_loc
Common::Extraction::CallSite.new(
file: @file, name: node.name.to_s.encode(Encoding::UTF_8).freeze,
receiver: receiver_form(node.receiver), safe_navigation: node.safe_navigation?,
line: location.start_line, column: location.start_column + 1
)
end

def receiver_form(receiver)
return :bare if receiver.nil?

receiver.is_a?(Prism::SelfNode) ? :self : :explicit
end
end
private_constant :NamedCallVisitor
end
end
Loading