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.



102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/steep/services/type_check_service.rb', line 102

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



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/steep/services/type_check_service.rb', line 355

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

#diagnosticsObject



145
146
147
# File 'lib/steep/services/type_check_service.rb', line 145

def diagnostics
  each_diagnostics.to_h
end

#each_diagnostics(&block) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/steep/services/type_check_service.rb', line 149

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

#signature_diagnosticsObject



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/steep/services/type_check_service.rb', line 115

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)


430
431
432
433
434
435
436
# File 'lib/steep/services/type_check_service.rb', line 430

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)


423
424
425
426
427
428
# File 'lib/steep/services/type_check_service.rb', line 423

def source_file?(path)
  return true if source_files.key?(path)
  return true if project.target_for_source_path(path)
  return true if project.target_for_inline_source_path(path)
  false
end

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



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/steep/services/type_check_service.rb', line 335

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



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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/steep/services/type_check_service.rb', line 258

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
      else
        # Signature loading failed. If the errors originate from library RBS files,
        # they won't be reported by validate_signature (which filters by user file path).
        # Report them on source files so the user knows type checking is broken. (#2176)
        case signature_service.status
        when SignatureService::SyntaxErrorStatus, SignatureService::AncestorErrorStatus
          library_errors = signature_service.status.diagnostics.select do |diag|
            diag_path = diag.location && Pathname(diag.location.buffer.name)
            diag_path &&
              signature_service.env_rbs_paths.include?(diag_path) &&
              !signature_service.status.files.key?(diag_path)
          end

          unless library_errors.empty?
            text = source_files.fetch(path).content
            buffer = RBS::Buffer.new(name: path, content: text)
            location = RBS::Location.new(buffer: buffer, start_pos: 0, end_pos: text.size)

            library_errors.map do |error|
              Diagnostic::Ruby::LibraryRBSError.new(error: error, location: location)
            end
          end
        end
      end
    end
  end
end

#update(changes:) ⇒ Object



163
164
165
166
167
168
169
170
171
# File 'lib/steep/services/type_check_service.rb', line 163

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



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/steep/services/type_check_service.rb', line 300

def update_signature(changes:)
  Steep.logger.tagged "#update_signature" do
    signature_targets = {} #: Hash[Pathname, Project::Target]
    changes.each do |path, changes|
      if target = project.target_for_signature_path(path) || project.target_for_inline_source_path(path)
        signature_targets[path] = target
      end
    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



325
326
327
328
329
330
331
332
333
# File 'lib/steep/services/type_check_service.rb', line 325

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



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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/steep/services/type_check_service.rb', line 173

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

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

      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

      source = service.status.files[path]
      if source.is_a?(RBS::Source::Ruby)
        source.diagnostics.each do |d|
          diagnostic = Diagnostic::Signature::InlineDiagnostic.new(d)
          diagnostics.push(diagnostic)
        end
      end

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