# Buggy code
def visit_instance(self, t: Instance) -> None:
    info = t.type
    if info.replaced or info.tuple_type:
        self.indicator["synthetic"] = True
    # Check type argument count.
    if len(t.args) != len(info.type_vars):
        if len(t.args) == 0:
            from_builtins = (
                t.type.fullname() in nongen_builtins and not t.from_generic_builtin
            )
            if (
                self.options.disallow_any_generics
                and not self.is_typeshed_stub
                and from_builtins
            ):
                alternative = nongen_builtins[t.type.fullname()]
                self.fail(messages.IMPLICIT_GENERIC_ANY_BUILTIN.format(alternative), t)
            # Insert implicit 'Any' type arguments.
            if from_builtins:
                # this 'Any' was already reported elsewhere
                any_type = AnyType(TypeOfAny.special_form, line=t.line, column=t.column)
            else:
                any_type = AnyType(
                    TypeOfAny.from_omitted_generics, line=t.line, column=t.column
                )
            t.args = [any_type] * len(info.type_vars)
            return
        # Invalid number of type parameters.
        n = len(info.type_vars)
        s = "{} type arguments".format(n)
        if n == 0:
            s = "no type arguments"
        elif n == 1:
            s = "1 type argument"
        act = str(len(t.args))
        if act == "0":
            act = "none"
        self.fail('"{}" expects {}, but {} given'.format(info.name(), s, act), t)
        # Construct the correct number of type arguments, as
        # otherwise the type checker may crash as it expects
        # things to be right.
        t.args = [AnyType(TypeOfAny.from_error) for _ in info.type_vars]
        t.invalid = True
    elif info.defn.type_vars:
        # Check type argument values.
        # TODO: Calling is_subtype and is_same_types in semantic analysis is a bad idea
        for (i, arg), tvar in zip(enumerate(t.args), info.defn.type_vars):
            if tvar.values:
                if isinstance(arg, TypeVarType):
                    arg_values = arg.values
                    if not arg_values:
                        self.fail(
                            'Type variable "{}" not valid as type '
                            'argument value for "{}"'.format(arg.name, info.name()),
                            t,
                        )
                        continue
                else:
                    arg_values = [arg]
                self.check_type_var_values(
                    info, arg_values, tvar.name, tvar.values, i + 1, t
                )
            # TODO: These hacks will be not necessary when this will be moved to later stage.
            arg = self.resolve_type(arg)
            bound = self.resolve_type(tvar.upper_bound)
            if not is_subtype(arg, bound):
                self.fail(
                    'Type argument "{}" of "{}" must be a subtype of "{}"'.format(
                        arg, info.name(), bound
                    ),
                    t,
                )
    for arg in t.args:
        arg.accept(self)
    if info.is_newtype:
        for base in info.bases:
            base.accept(self)


# Traceback (RuntimeError)
forward.py:1: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.540
Traceback (most recent call last):
File "/Users/joshstaiger/anaconda/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/main.py", line 50, in main
res = type_check_only(sources, bin_dir, options)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/main.py", line 103, in type_check_only
options=options)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/build.py", line 201, in build
graph = dispatch(sources, manager)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/build.py", line 1867, in dispatch
process_graph(graph, manager)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/build.py", line 2117, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/build.py", line 2214, in process_stale_scc
graph[id].semantic_analysis_pass_three()
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/build.py", line 1760, in semantic_analysis_pass_three
self.options, patches)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/semanal_pass3.py", line 56, in visit_file
self.accept(file_node)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/semanal_pass3.py", line 73, in accept
node.accept(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/nodes.py", line 228, in accept
return visitor.visit_mypy_file(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/traverser.py", line 30, in visit_mypy_file
d.accept(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/nodes.py", line 794, in accept
return visitor.visit_assignment_stmt(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/semanal_pass3.py", line 187, in visit_assignment_stmt
self.analyze(s.rvalue.analyzed.type, s.rvalue.analyzed, warn=True)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/semanal_pass3.py", line 311, in analyze
type.accept(analyzer)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/types.py", line 476, in accept
return visitor.visit_instance(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/typeanal.py", line 716, in visit_instance
if not is_subtype(arg, bound):
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/subtypes.py", line 83, in is_subtype
ignore_declared_variance=ignore_declared_variance))
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/types.py", line 1227, in accept
return visitor.visit_union_type(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/subtypes.py", line 312, in visit_union_type
for item in left.items)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/subtypes.py", line 312, in <genexpr>
for item in left.items)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/subtypes.py", line 83, in is_subtype
ignore_declared_variance=ignore_declared_variance))
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/types.py", line 1412, in accept
return visitor.visit_forwardref_type(self)
File "/Users/joshstaiger/anaconda/lib/python3.6/site-packages/mypy/types.py", line 1497, in visit_forwardref_type
raise RuntimeError('Internal error: unresolved forward reference')
RuntimeError: Internal error: unresolved forward reference
forward.py:1: : note: use --pdb to drop into pdb

# Fixed code
def visit_instance(self, t: Instance) -> None:
    info = t.type
    if info.replaced or info.tuple_type:
        self.indicator["synthetic"] = True
    # Check type argument count.
    if len(t.args) != len(info.type_vars):
        if len(t.args) == 0:
            from_builtins = (
                t.type.fullname() in nongen_builtins and not t.from_generic_builtin
            )
            if (
                self.options.disallow_any_generics
                and not self.is_typeshed_stub
                and from_builtins
            ):
                alternative = nongen_builtins[t.type.fullname()]
                self.fail(messages.IMPLICIT_GENERIC_ANY_BUILTIN.format(alternative), t)
            # Insert implicit 'Any' type arguments.
            if from_builtins:
                # this 'Any' was already reported elsewhere
                any_type = AnyType(TypeOfAny.special_form, line=t.line, column=t.column)
            else:
                any_type = AnyType(
                    TypeOfAny.from_omitted_generics, line=t.line, column=t.column
                )
            t.args = [any_type] * len(info.type_vars)
            return
        # Invalid number of type parameters.
        n = len(info.type_vars)
        s = "{} type arguments".format(n)
        if n == 0:
            s = "no type arguments"
        elif n == 1:
            s = "1 type argument"
        act = str(len(t.args))
        if act == "0":
            act = "none"
        self.fail('"{}" expects {}, but {} given'.format(info.name(), s, act), t)
        # Construct the correct number of type arguments, as
        # otherwise the type checker may crash as it expects
        # things to be right.
        t.args = [AnyType(TypeOfAny.from_error) for _ in info.type_vars]
        t.invalid = True
    elif info.defn.type_vars:
        # Check type argument values. This is postponed to the end of semantic analysis
        # since we need full MROs and resolved forward references.
        for tvar in info.defn.type_vars:
            if (
                tvar.values
                or not isinstance(tvar.upper_bound, Instance)
                or tvar.upper_bound.type.fullname() != "builtins.object"
            ):
                # Some restrictions on type variable. These can only be checked later
                # after we have final MROs and forward references have been resolved.
                self.indicator["typevar"] = True
    for arg in t.args:
        arg.accept(self)
    if info.is_newtype:
        for base in info.bases:
            base.accept(self)