Class: Ryac::Pipeline::Analyzer

Inherits:
Object
  • Object
show all
Includes:
AnalysisPhases
Defined in:
lib/ryac/pipeline/analyzer.rb,
sig/ryac/pipeline/analyzer.rbs

Overview

Stage 3: Analysis Parses source with TypeProf, builds scope mappings, collects constants and their references, and freezes mappings.

Constant Summary collapse

META_CALL_METHODS =

Returns:

  • (Array[Symbol])
%i[include attr_reader attr_accessor].freeze

Constants included from AnalysisPhases

AnalysisPhases::ATTR_DECLARATION_METHODS, AnalysisPhases::CVAR_WRITE_NODES, AnalysisPhases::DYNAMIC_CVAR_METHODS, AnalysisPhases::DYNAMIC_DISPATCH_METHODS, AnalysisPhases::DYNAMIC_IVAR_METHODS, AnalysisPhases::GVAR_NODES, AnalysisPhases::IVAR_WRITE_NODES, AnalysisPhases::UNRESOLVED_CALL_NODES, AnalysisPhases::VISIBILITY_MODIFIERS

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AnalysisPhases

#apply_accessor_call_renames, #apply_ivar_renames, #assign_ivar_driven_names, #attr_backed_ivar?, #augment_constant_counts_via_oracle, #build_attr_rename_map, #carries_keyword_arguments?, #class_definition_cpath, #classify_attr_declarations, #classify_unresolved_call, #collect_alias_undef_methods, #collect_attr_backed_ivars, #collect_attr_write_exclusions, #collect_constants, #collect_cvar_definitions, #collect_dynamic_ivar_attr_exclusions, #collect_external_references, #collect_gvar_definitions, #collect_inherited_attr_exclusions, #collect_ivar_definitions, #collect_ivar_nodes_by_key, #collect_keyword_call_sites, #collect_keyword_info, #collect_method_definitions, #collect_shorthand_pun_methods, #collect_string_literal_mentions, #collect_visibility_modifier_methods, #complete_const_chain?, #coordinate_attr_renames, #count_constant_references, #def_keyword_names, #def_keyword_rest?, #dynamic_root?, #each_attr_declaration, #each_constant_event, #exclude_dynamic_root_reads, #exclude_lazy_definitions, #exclude_method_valued_shorthand_calls, #exclude_private_constants, #exclude_unreachable_keyword_methods, #exclude_unresolved_keyword_calls, #external_prefix_for, #forwards_parameters_to_super?, #increment_constant_read_usage, #link_module_function_variant, #mark_chain_prefixes, #merge_inherited_cvars, #merge_inherited_ivars, #merge_inherited_sites, #merge_polymorphic_groups, #merge_polymorphic_keyword_groups, #merge_super_forwarding, #merge_super_groups, #merge_unresolved_calls, #precompute_constant_resolution, #qualified_write_cpath, #record_constant_read, #register_keyword_calls, #register_size_comparison, #required_external_root?, #reserve_attr_ivar_names, #resolve_method_aliases_and_transforms, #resolve_method_calls, #resolve_superclass_path, #resolve_user_defined_cpath, #scan_alias_globals, #scan_dynamic_cvar_access, #scan_dynamic_ivar_access, #scan_dynamic_method_references, #scan_dynamic_sigil_access, #struct_definition_write?, #syntactic_const_segments

Constructor Details

#initialize(method_policy: :aggressive) ⇒ Analyzer

Returns a new instance of Analyzer.

Parameters:

  • method_policy: (Symbol) (defaults to: :aggressive)


45
46
47
# File 'lib/ryac/pipeline/analyzer.rb', line 45

def initialize(method_policy: :aggressive)
  @method_policy = method_policy
end

Class Method Details

.prism_only(source) ⇒ AnalysisResult

Parameters:

Returns:



13
14
15
# File 'lib/ryac/pipeline/analyzer.rb', line 13

def self.prism_only(source)
  prism_only_from_string(source.content, source: source)
end

.prism_only_from_string(content, source: nil) ⇒ AnalysisResult

Parameters:

Returns:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ryac/pipeline/analyzer.rb', line 17

def self.prism_only_from_string(content, source: nil)
  prism_result = Prism.parse(content)

  analyzer = new
  syntax_data = analyzer.syntax_data_for(prism_result.value)

  source ||= ConcatenatedSource.new(content: content)

  AnalysisResult.new(
    prism_ast: prism_result.value,
    scope_mappings: {},
    constant_mapping: nil,
    rename_map: {},
    method_alias_map: {},
    method_transform_map: {},
    source: source,
    attr_rename_map: {},
    block_param_names_map: {},
    syntax_data: syntax_data,
    const_resolution_map: {},
    const_full_path_map: {},
    const_write_cpath_map: {},
    class_cpath_map: {},
    superclass_resolution_map: {},
    meta_node_map: {}
  )
end

Instance Method Details

#analyze_constants_phase ⇒ void

This method returns an undefined value.



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/ryac/pipeline/analyzer.rb', line 175

def analyze_constants_phase
  @constant_mapping = ConstantRenameMapping.new(
    boot_roots: @boot_constant_roots,
    alias_surface: @alias_surface
  )
  collect_constants(@prism_root)
  exclude_private_constants(@prism_root)
  exclude_lazy_definitions(@prism_root)
  exclude_dynamic_root_reads(@prism_root)
  count_constant_references(@prism_root)
  augment_constant_counts_via_oracle
  collect_external_references(@prism_root)
end

#analyze_keywords_and_scopes ⇒ void

This method returns an undefined value.



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/ryac/pipeline/analyzer.rb', line 115

def analyze_keywords_and_scopes
  @local_scopes = LocalScopes.new(@prism_root)

  @keyword_rename_mapping = KeywordRenameMapping.new
  collect_keyword_info(@prism_root)
  @keyword_rename_mapping.assign_short_names

  # Inline rather than through locals: a local passed as the same-named
  # keyword gets hint-aligned and collapses to shorthand, and the
  # re-minified form of that shorthand no longer carries the hint — the
  # names then oscillate between passes instead of reaching a fixed
  # point under self-hosting.
  @local_scopes.allocate(
    kw_def_map: @keyword_rename_mapping.def_node_mapping(@keyword_def_node_registry || {}),
    var_hints: @keyword_rename_mapping.build_variable_hints { |val_node| @local_scopes.scope_id_of(val_node) }
  )
  @local_scopes.resolve
  @scope_mappings = @local_scopes.scope_mappings
  @scope_visible_names = @local_scopes.visible_local_names
end

#analyze_methods_phase ⇒ void

This method returns an undefined value.



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/ryac/pipeline/analyzer.rb', line 136

def analyze_methods_phase
  @method_rename_mapping = MethodRenameMapping.new
  collect_method_definitions(@prism_root)
  collect_dynamic_ivar_attr_exclusions(@prism_root)
  collect_inherited_attr_exclusions(@prism_root)
  resolve_method_calls
  collect_alias_undef_methods(@prism_root)
  scan_dynamic_method_references(@prism_root)
  collect_visibility_modifier_methods(@prism_root)
  collect_attr_write_exclusions(@prism_root)
  collect_shorthand_pun_methods(@prism_root)
  if @method_policy == :safe
    collect_string_literal_mentions(@prism_root)
    @method_rename_mapping.exclude_uncalled_methods
  end
  @method_rename_mapping.assign_short_names(@scope_visible_names, @oracle)
end

#analyze_variables_phase ⇒ void

This method returns an undefined value.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/ryac/pipeline/analyzer.rb', line 154

def analyze_variables_phase
  @ivar_rename_mapping = SiteBucketMapping.new(prefix: '@')
  attr_backed = collect_attr_backed_ivars(@prism_root)
  collect_ivar_definitions(@prism_root, attr_backed)
  scan_dynamic_ivar_access(@prism_root)
  merge_inherited_ivars
  reserve_attr_ivar_names(@prism_root)
  @ivar_rename_mapping.assign_short_names

  @cvar_rename_mapping = SiteBucketMapping.new(prefix: '@@')
  collect_cvar_definitions(@prism_root)
  scan_dynamic_cvar_access(@prism_root)
  merge_inherited_cvars
  @cvar_rename_mapping.assign_short_names

  @gvar_rename_mapping = GvarRenameMapping.new
  collect_gvar_definitions(@prism_root)
  scan_alias_globals(@prism_root)
  @gvar_rename_mapping.assign_short_names
end

#build_analysis_result(prism_result, source, rename_map, method_alias_map, method_transform_map, attr_rename_map, attr_ivar_entries, local_rename_entries) ⇒ AnalysisResult

Parameters:

  • prism_result (Prism::ParseResult)
  • source (ConcatenatedSource)
  • rename_map (Hash[location_key, String])
  • method_alias_map (Hash[location_key, Symbol])
  • method_transform_map (Hash[location_key, String])
  • attr_rename_map (Hash[location_key, Hash[Symbol, String]])
  • attr_ivar_entries (Hash[location_key, String])
  • local_rename_entries (Hash[location_key, String])

Returns:



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/ryac/pipeline/analyzer.rb', line 201

def build_analysis_result(prism_result, source, rename_map, method_alias_map,
                          method_transform_map, attr_rename_map, attr_ivar_entries,
                          local_rename_entries)
  AnalysisResult.new(
    prism_ast: prism_result.value,
    scope_mappings: @scope_mappings,
    constant_mapping: @constant_mapping,
    rename_map: rename_map,
    method_alias_map: method_alias_map,
    method_transform_map: method_transform_map,
    source: source,
    attr_rename_map: attr_rename_map,
    block_param_names_map: @block_param_names_map,
    syntax_data: @syntax_data,
    const_resolution_map: @const_resolution_map,
    const_full_path_map: @const_full_path_map,
    const_write_cpath_map: @const_write_cpath_map,
    class_cpath_map: @class_cpath_map,
    superclass_resolution_map: @superclass_resolution_map,
    meta_node_map: @meta_node_map,
    local_rename_entries: local_rename_entries,
    keyword_rename_entries: @keyword_rename_mapping.node_mapping,
    ivar_rename_entries: @ivar_rename_mapping.node_mapping,
    attr_ivar_entries: attr_ivar_entries,
    cvar_rename_entries: @cvar_rename_mapping.node_mapping,
    gvar_rename_entries: @gvar_rename_mapping.node_mapping
  )
end

#call(source) ⇒ AnalysisResult

Parameters:

Returns:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/ryac/pipeline/analyzer.rb', line 49

def call(source)
  prism_result, @oracle = without_stdout_pollution { setup_typeprof(source) }
  @prism_root = prism_result.value
  @lazy_regions = LazyRegions.collect(@prism_root)
  # A program that loads files dynamically had enumerated its external
  # readers; bundled as lazy regions, they are all inside now, and what
  # is left outside is a launcher — which spells the class/module
  # skeleton, never a value constant.
  @alias_surface = source.lazy_files.empty? ? :full : :skeleton
  @boot_constant_roots = BootConstants.for(source.stdlib_requires)
  @syntax_data = collect_syntax_data(@prism_root)

  analyze_keywords_and_scopes
  analyze_methods_phase
  method_alias_map, method_transform_map = resolve_method_aliases_and_transforms(@prism_root)
  analyze_variables_phase

  rename_map = @method_rename_mapping.node_mapping.dup
  attr_ivar_entries = {} #: Hash[location_key, String]
  attr_rename_map = coordinate_attr_renames(@prism_root, rename_map, attr_ivar_entries)

  analyze_constants_phase
  local_rename_entries = precompute_rename_entries
  precompute_constant_resolution
  precompute_meta_nodes

  build_analysis_result(
    prism_result, source, rename_map, method_alias_map, method_transform_map,
    attr_rename_map, attr_ivar_entries, local_rename_entries
  )
end

#collect_syntax_data(prism_ast) ⇒ syntax_data_map

Parameters:

  • prism_ast (Prism::ProgramNode)

Returns:

  • (syntax_data_map)


248
249
250
251
252
# File 'lib/ryac/pipeline/analyzer.rb', line 248

def collect_syntax_data(prism_ast)
  data = {} #: syntax_data_map
  traverse_prism(prism_ast, data)
  data
end

#precompute_meta_nodes ⇒ void

This method returns an undefined value.

Calls the renamer rewrites structurally instead of as plain calls.



233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/ryac/pipeline/analyzer.rb', line 233

def precompute_meta_nodes
  @meta_node_map = {}
  Nesting.each_meta_call(@prism_root, META_CALL_METHODS) do |call_node, _cpath, _singleton|
    case call_node.name
    when :attr_reader, :attr_accessor
      next unless call_node.arguments

      @meta_node_map[AstUtils.location_key(call_node)] =
        { type: call_node.name, args: AstUtils.symbol_arguments(call_node) }
    when :include
      @meta_node_map[AstUtils.location_key(call_node)] = { type: :include }
    end
  end
end

#precompute_rename_entries ⇒ Hash[location_key, String]

Returns:

  • (Hash[location_key, String])


189
190
191
192
193
194
195
196
197
198
199
# File 'lib/ryac/pipeline/analyzer.rb', line 189

def precompute_rename_entries
  @local_scopes.def_param_names.each do |key, names|
    (@syntax_data[key] ||= {})[:param_names] = names
  end
  @local_scopes.for_index_names.each do |key, name|
    data = @syntax_data[key]
    data[:for_index_mangled] = name if data&.[](:index_name)
  end
  @block_param_names_map = @local_scopes.block_param_names
  @local_scopes.rename_entries
end

#setup_typeprof(source) ⇒ [Prism::ParseResult, TypeOracle]

Parameters:

Returns:



104
105
106
107
108
109
110
111
112
113
# File 'lib/ryac/pipeline/analyzer.rb', line 104

def setup_typeprof(source)
  prism_result = Prism.parse(source.content)
  # Every input file was parse-checked at collection, so a failure
  # here means an upstream stage broke the text.
  unless prism_result.errors.none?
    raise InvalidOutputError.new('pre-rename source', prism_result.errors)
  end

  [prism_result, TypeOracle.boot(source.content, source.rbs_files, prism_result.value)]
end

#syntax_data_for(prism_ast) ⇒ syntax_data_map

Parameters:

  • prism_ast (Prism::ProgramNode)

Returns:

  • (syntax_data_map)


81
82
83
# File 'lib/ryac/pipeline/analyzer.rb', line 81

def syntax_data_for(prism_ast)
  collect_syntax_data(prism_ast)
end

#traverse_prism(node, data) ⇒ void

This method returns an undefined value.

Parameters:

  • node (Prism::Node)
  • data (syntax_data_map)


254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/ryac/pipeline/analyzer.rb', line 254

def traverse_prism(node, data)
  key = AstUtils.line_col_key(node)
  case node
  when Prism::DefNode
    data[key] = { self_receiver: node.receiver.is_a?(Prism::SelfNode) }
  when Prism::ArrayNode
    data[key] = { opening: node.opening }
  when Prism::RangeNode
    data[key] = { exclude_end: node.exclude_end? }
  when Prism::RegularExpressionNode
    data[key] = { content: node.content, flags: node.closing.delete("/") }
  when Prism::InterpolatedRegularExpressionNode
    data[key] = { flags: node.closing.delete("/") }
  when Prism::ForNode
    idx = node.index
    if idx.is_a?(Prism::LocalVariableTargetNode)
      data[key] = { index_name: idx.name }
    else
      data[key] = { index_slice: idx.slice }
    end
  when Prism::DefinedNode
    data[key] = { value_slice: node.value.slice }
  when Prism::RationalNode, Prism::ImaginaryNode, Prism::LambdaNode,
       Prism::MatchLastLineNode, Prism::InterpolatedMatchLastLineNode,
       Prism::FlipFlopNode, Prism::AliasGlobalVariableNode,
       Prism::BackReferenceReadNode
    data[key] = { slice: node.slice }
  end
  node.compact_child_nodes.each { |child| traverse_prism(child, data) }
end

#without_stdout_pollution ⇒ void

This method returns an undefined value.

TypeProf prints diagnostics for node types it does not recognize straight to stdout, which is also where the minified program is written. Divert anything it emits to stderr so it can never end up inside the output.



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/ryac/pipeline/analyzer.rb', line 91

def without_stdout_pollution
  original = $stdout
  capture = StringIO.new
  $stdout = capture
  begin
    yield
  ensure
    $stdout = original
    noise = capture.string
    $stderr.print(noise) unless noise.empty?
  end
end