Class: Steep::Services::TypeCheckService

Inherits:
Object
  • Object
show all
Defined in:
lib/steep/services/type_check_service.rb

Defined Under Namespace

Classes: SourceFile

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(project:) ⇒ TypeCheckService

Returns a new instance of TypeCheckService.



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/steep/services/type_check_service.rb', line 79

def initialize(project:)
  @project = project

  @source_files = {}
  @signature_services = project.targets.each.with_object({}) do |target, hash| #$ Hash[Symbol, SignatureService]
    loader = Project::Target.construct_env_loader(options: target.options, project: project)
    hash[target.name] = SignatureService.load_from(loader, implicitly_returns_nil: target.implicitly_returns_nil)
  end
  @signature_validation_diagnostics = project.targets.each.with_object({}) do |target, hash| #$ Hash[Symbol, Hash[Pathname, Array[Diagnostic::Signature::Base]]]
    hash[target.name] = {}
  end
end

Instance Attribute Details

#projectObject (readonly)

Returns the value of attribute project.



4
5
6
# File 'lib/steep/services/type_check_service.rb', line 4

def project
  @project
end

#signature_servicesObject (readonly)

Returns the value of attribute signature_services.



7
8
9
# File 'lib/steep/services/type_check_service.rb', line 7

def signature_services
  @signature_services
end

#signature_validation_diagnosticsObject (readonly)

Returns the value of attribute signature_validation_diagnostics.



5
6
7
# File 'lib/steep/services/type_check_service.rb', line 5

def signature_validation_diagnostics
  @signature_validation_diagnostics
end

#source_filesObject (readonly)

Returns the value of attribute source_files.



6
7
8
# File 'lib/steep/services/type_check_service.rb', line 6

def source_files
  @source_files
end

Class Method Details

.type_check(source:, subtyping:, constant_resolver:, cursor:) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/steep/services/type_check_service.rb', line 302

def self.type_check(source:, subtyping:, constant_resolver:, cursor:)
  annotations = source.annotations(block: source.node, factory: subtyping.factory, context: nil)

  case annotations.self_type
  when AST::Types::Name::Instance
    module_name = annotations.self_type.name
    module_type = AST::Types::Name::Singleton.new(name: module_name)
    instance_type = annotations.self_type
  when AST::Types::Name::Singleton
    module_name = annotations.self_type.name
    module_type = annotations.self_type
    instance_type = annotations.self_type
  else
    module_name = AST::Builtin::Object.module_name
    module_type = AST::Builtin::Object.module_type
    instance_type = AST::Builtin::Object.instance_type
  end

  definition = subtyping.factory.definition_builder.build_instance(module_name)

  const_env = TypeInference::ConstantEnv.new(
    factory: subtyping.factory,
    context: nil,
    resolver: constant_resolver
  )
  type_env = TypeInference::TypeEnv.new(const_env)
  type_env = TypeInference::TypeEnvBuilder.new(
    TypeInference::TypeEnvBuilder::Command::ImportConstantAnnotations.new(annotations),
    TypeInference::TypeEnvBuilder::Command::ImportGlobalDeclarations.new(subtyping.factory),
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableDefinition.new(definition, subtyping.factory),
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableAnnotations.new(annotations),
    TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(annotations)
  ).build(type_env)

  context = TypeInference::Context.new(
    block_context: nil,
    module_context: TypeInference::Context::ModuleContext.new(
      instance_type: instance_type,
      module_type: module_type,
      implement_name: nil,
      nesting: nil,
      class_name: module_name,
      instance_definition: subtyping.factory.definition_builder.build_instance(module_name),
      module_definition: subtyping.factory.definition_builder.build_singleton(module_name)
    ),
    method_context: nil,
    break_context: nil,
    self_type: instance_type,
    type_env: type_env,
    call_context: TypeInference::MethodCall::TopLevelContext.new,
    variable_context: TypeInference::Context::TypeVariableContext.empty
  )

  typing = Typing.new(source: source, root_context: context, cursor: cursor)

  construction = TypeConstruction.new(
    checker: subtyping,
    annotations: annotations,
    source: source,
    context: context,
    typing: typing
  )

  construction.synthesize(source.node) if source.node

  typing
end

Instance Method Details

#app_signature_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


382
383
384
385
386
387
# File 'lib/steep/services/type_check_service.rb', line 382

def app_signature_file?(path)
  target_names = signature_services.select {|_, sig| sig.files.key?(path) }.keys
  unless target_names.empty?
    target_names
  end
end

#diagnosticsObject



126
127
128
# File 'lib/steep/services/type_check_service.rb', line 126

def diagnostics
  each_diagnostics.to_h
end

#each_diagnostics(&block) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/steep/services/type_check_service.rb', line 130

def each_diagnostics(&block)
  if block
    signature_diagnostics.each do |path, diagnostics|
      yield [path, diagnostics]
    end

    source_files.each_value do |file|
      yield [file.path, file.diagnostics]
    end
  else
    enum_for :each_diagnostics
  end
end

#has_diagnostics?Boolean

Returns:

  • (Boolean)


122
123
124
# File 'lib/steep/services/type_check_service.rb', line 122

def has_diagnostics?
  each_diagnostics.count > 0
end

#lib_signature_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


389
390
391
# File 'lib/steep/services/type_check_service.rb', line 389

def lib_signature_file?(path)
  signature_services.each_value.any? {|sig| sig.env_rbs_paths.include?(path) }
end

#signature_diagnosticsObject



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/steep/services/type_check_service.rb', line 92

def signature_diagnostics
  # @type var signature_diagnostics: Hash[Pathname, Array[Diagnostic::Signature::Base]]
  signature_diagnostics = {}

  project.targets.each do |target|
    service = signature_services.fetch(target.name)

    service.each_rbs_path do |path|
      signature_diagnostics[path] ||= []
    end

    case service.status
    when SignatureService::SyntaxErrorStatus, SignatureService::AncestorErrorStatus
      service.status.diagnostics.group_by {|diag| diag.location&.buffer&.name&.to_s }.each do |path_string, diagnostics|
        if path_string
          path = Pathname(path_string)
          signature_diagnostics.fetch(path).push(*diagnostics)
        end
      end
    when SignatureService::LoadedStatus
      validation_diagnostics = signature_validation_diagnostics[target.name] || {}
      validation_diagnostics.each do |path, diagnostics|
        signature_diagnostics.fetch(path).push(*diagnostics)
      end
    end
  end

  signature_diagnostics
end

#signature_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


374
375
376
377
378
379
380
# File 'lib/steep/services/type_check_service.rb', line 374

def signature_file?(path)
  relative_path = project.relative_path(path)
  targets = signature_services.select {|_, sig| sig.files.key?(relative_path) || sig.env_rbs_paths.include?(path) }
  unless targets.empty?
    targets.keys
  end
end

#source_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


370
371
372
# File 'lib/steep/services/type_check_service.rb', line 370

def source_file?(path)
  source_files.key?(path) || (project.target_for_source_path(path) ? true : false)
end

#type_check_file(target:, subtyping:, path:, text:) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/steep/services/type_check_service.rb', line 282

def type_check_file(target:, subtyping:, path:, text:)
  Steep.logger.tagged "#type_check_file(#{path}@#{target.name})" do
    source = Source.parse(text, path: path, factory: subtyping.factory)
    typing = TypeCheckService.type_check(source: source, subtyping: subtyping, constant_resolver: yield, cursor: nil)
    ignores = Source::IgnoreRanges.new(ignores: source.ignores)
    SourceFile.with_typing(path: path, content: text, node: source.node, typing: typing, ignores: ignores)
  end
rescue AnnotationParser::SyntaxError => exn
  error = Diagnostic::Ruby::AnnotationSyntaxError.new(message: exn.message, location: exn.location)
  SourceFile.with_syntax_error(path: path, content: text, error: error)
rescue ::Parser::SyntaxError => exn
  error = Diagnostic::Ruby::SyntaxError.new(message: exn.message, location: (_ = exn).diagnostic.location)
  SourceFile.with_syntax_error(path: path, content: text, error: error)
rescue EncodingError => exn
  SourceFile.no_data(path: path, content: "")
rescue RuntimeError => exn
  Steep.log_error(exn)
  SourceFile.no_data(path: path, content: text)
end

#typecheck_source(path:, target:) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/steep/services/type_check_service.rb', line 229

def typecheck_source(path:, target:)
  return unless target

  Steep.logger.tagged "#typecheck_source(path=#{path})" do
    Steep.measure "typecheck" do
      signature_service = signature_services.fetch(target.name)
      subtyping = signature_service.current_subtyping

      if subtyping
        text = source_files.fetch(path).content
        file = type_check_file(target: target, subtyping: subtyping, path: path, text: text) { signature_service.latest_constant_resolver }
        source_files[path] = file

        file.diagnostics
      end
    end
  end
end

#update(changes:) ⇒ Object



144
145
146
147
148
149
150
151
152
# File 'lib/steep/services/type_check_service.rb', line 144

def update(changes:)
  Steep.measure "#update_signature" do
    update_signature(changes: changes)
  end

  Steep.measure "#update_sources" do
    update_sources(changes: changes)
  end
end

#update_signature(changes:) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/steep/services/type_check_service.rb', line 248

def update_signature(changes:)
  Steep.logger.tagged "#update_signature" do
    signature_targets = {} #: Hash[Pathname, Project::Target]
    changes.each do |path, changes|
      target = project.targets.find { _1.possible_signature_file?(path) } or next
      signature_targets[path] = target
    end

    project.targets.each do |target|
      Steep.logger.tagged "#{target.name}" do
        # Load signatures from all project targets but `#unreferenced` ones
        target_changes = changes.select do |path, _|
          signature_target = signature_targets.fetch(path, nil) or next
          signature_target == target || !signature_target.unreferenced
        end

        unless target_changes.empty?
          signature_services.fetch(target.name).update(target_changes)
        end
      end
    end
  end
end

#update_sources(changes:) ⇒ Object



272
273
274
275
276
277
278
279
280
# File 'lib/steep/services/type_check_service.rb', line 272

def update_sources(changes:)
  changes.each do |path, changes|
    if source_file?(path)
      file = source_files[path] || SourceFile.no_data(path: path, content: "")
      content = changes.inject(file.content) {|text, change| change.apply_to(text) }
      source_files[path] = file.update_content(content)
    end
  end
end

#validate_signature(path:, target:) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
# File 'lib/steep/services/type_check_service.rb', line 154

def validate_signature(path:, target:)
  Steep.logger.tagged "#validate_signature(path=#{path})" do
    Steep.measure "validation" do
      service = signature_services.fetch(target.name)

      raise "#{path} is not library nor signature of #{target.name}" unless target.possible_signature_file?(path) || service.env_rbs_paths.include?(path)

      case service.status
      when SignatureService::SyntaxErrorStatus
        diagnostics = service.status.diagnostics.select do |diag|
          diag.location or raise
          Pathname(diag.location.buffer.name) == path &&
            (diag.is_a?(Diagnostic::Signature::SyntaxError) || diag.is_a?(Diagnostic::Signature::UnexpectedError))
        end

      when SignatureService::AncestorErrorStatus
        diagnostics = service.status.diagnostics.select do |diag|
          diag.location or raise
          Pathname(diag.location.buffer.name) == path
        end

      when SignatureService::LoadedStatus
        validator = Signature::Validator.new(checker: service.current_subtyping || raise)
        type_names = service.type_names(paths: Set[path], env: service.latest_env).to_set

        unless type_names.empty?
          Steep.measure2 "Validating #{type_names.size} types" do |sampler|
            type_names.each do |type_name|
              sampler.sample(type_name.to_s) do
                case
                when type_name.class?
                  validator.validate_one_class(type_name)
                when type_name.interface?
                  validator.validate_one_interface(type_name)
                when type_name.alias?
                  validator.validate_one_alias(type_name)
                end
              end
            end
          end
        end

        const_decls = service.const_decls(paths: Set[path], env: service.latest_env)
        unless const_decls.empty?
          Steep.measure2 "Validating #{const_decls.size} constants" do |sampler|
            const_decls.each do |name, entry|
              sampler.sample(name.to_s) do
                validator.validate_one_constant(name, entry)
              end
            end
          end
        end

        global_decls = service.global_decls(paths: Set[path])
        unless global_decls.empty?
          Steep.measure2 "Validating #{global_decls.size} globals" do |sampler|
            global_decls.each do |name, entry|
              sampler.sample(name.to_s) do
                validator.validate_one_global(name, entry)
              end
            end
          end
        end

        diagnostics = validator.each_error.select do |error|
          error.location or raise
          Pathname(error.location.buffer.name) == path
        end
      end

      signature_validation_diagnostics.fetch(target.name)[path] = diagnostics
    end
  end
end