Skip to content

Commit

Permalink
Fixes from rebase
Browse files Browse the repository at this point in the history
  • Loading branch information
KotlinIsland committed Jan 28, 2023
1 parent 4f29231 commit e24b373
Show file tree
Hide file tree
Showing 14 changed files with 1,295 additions and 1,001 deletions.
2,241 changes: 1,256 additions & 985 deletions .mypy/baseline.json

Large diffs are not rendered by default.

16 changes: 14 additions & 2 deletions mypy/dmypy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import sys
import time
import traceback
from argparse import RawTextHelpFormatter
from typing import Any, Callable, Mapping, NoReturn

from mypy.dmypy_os import alive, kill
Expand All @@ -32,7 +33,10 @@ def __init__(self, prog: str) -> None:


parser = argparse.ArgumentParser(
prog="dmypy", description="Client for mypy daemon mode", fromfile_prefix_chars="@"
prog="dmypy",
description="Client for mypy daemon mode",
fromfile_prefix_chars="@",
formatter_class=RawTextHelpFormatter,
)
parser.set_defaults(action=None)
parser.add_argument(
Expand All @@ -42,7 +46,7 @@ def __init__(self, prog: str) -> None:
"-V",
"--version",
action="version",
version=f"Basedmypy Daemon {__based_version__}\n" f"Based on %(prog)s {__version__}",
version=f"Basedmypy Daemon {__based_version__}\nBased on %(prog)s {__version__}",
help="Show program's version number and exit",
)
subparsers = parser.add_subparsers()
Expand Down Expand Up @@ -248,6 +252,7 @@ def __init__(self, prog: str) -> None:
"flags", metavar="FLAG", nargs="*", type=str, help="Regular mypy flags (precede with --)"
)
p.add_argument("--options-data", help=argparse.SUPPRESS)
p.add_argument("--legacy", action="store_true", help=argparse.SUPPRESS)
help_parser = p = subparsers.add_parser("help")

del p
Expand Down Expand Up @@ -606,8 +611,12 @@ def do_hang(args: argparse.Namespace) -> None:
def do_daemon(args: argparse.Namespace) -> None:
"""Serve requests in the foreground."""
# Lazy import so this import doesn't slow down other commands.
import mypy.options
from mypy.dmypy_server import Server, process_start_options

if args.legacy:
mypy.options._based = False

if args.options_data:
from mypy.options import Options

Expand All @@ -622,6 +631,9 @@ def do_daemon(args: argparse.Namespace) -> None:
else:
options = process_start_options(args.flags, allow_sources=False)
timeout = args.timeout
if args.legacy:
if not os.getenv("__MYPY_UNDER_TEST__"):
mypy.options._based = True
Server(options, args.status_file, timeout=timeout).serve()


Expand Down
2 changes: 2 additions & 0 deletions mypy/dmypy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ def daemonize(
command = [sys.executable, "-m", "mypy.dmypy", "--status-file", status_file, "daemon"]
pickled_options = pickle.dumps((options.snapshot(), timeout, log_file))
command.append(f'--options-data="{base64.b64encode(pickled_options).decode()}"')
if not mypy.options._based:
command.append("--legacy")
info = STARTUPINFO()
info.dwFlags = 0x1 # STARTF_USESHOWWINDOW aka use wShowWindow's value
info.wShowWindow = 0 # SW_HIDE aka make the window invisible
Expand Down
3 changes: 3 additions & 0 deletions mypy/expandtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,9 @@ def expand_unpack_with_variables(
"""
if isinstance(t.type, TypeVarTupleType):
repl = get_proper_type(variables.get(t.type.id, t))
if isinstance(repl, UnionType):
# the type was joined (based) instead of `meet`ed, get the right hand side
repl = get_proper_type(repl.items[1])
if isinstance(repl, TupleType):
return repl.items
elif isinstance(repl, Instance) and repl.type.fullname == "builtins.tuple":
Expand Down
2 changes: 1 addition & 1 deletion mypy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,7 +1296,7 @@ def add_invertible_flag(
based_enabled_codes = (
{
"no-untyped-usage",
"partially-defined",
"possibly-undefined",
"redundant-expr",
"truthy-bool",
"ignore-without-code",
Expand Down
4 changes: 3 additions & 1 deletion mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2350,7 +2350,9 @@ def format_literal_value(typ: LiteralType) -> str:
base_str = itype.type.name
if not itype.args:
# No type arguments, just return the type name
return TypeStrVisitor.strip_builtins(base_str)
if not verbosity:
return TypeStrVisitor.strip_builtins(base_str)
return base_str
elif itype.type.fullname == "builtins.tuple":
item_type_str = format(itype.args[0])
if not mypy.options._based:
Expand Down
14 changes: 9 additions & 5 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@

from __future__ import annotations

from contextlib import contextmanager
from contextlib import contextmanager, nullcontext
from typing import Any, Callable, Collection, Iterable, Iterator, List, TypeVar, cast
from typing_extensions import Final, TypeAlias as _TypeAlias

Expand Down Expand Up @@ -3347,13 +3347,13 @@ def is_annotated_protocol_member(self, s: AssignmentStmt) -> bool:
)

def analyze_simple_literal_type(
self, rvalue: Expression, is_final: bool, do_bools=False
self, rvalue: Expression, is_final: bool, do_inner=False
) -> Type | None:
"""Return builtins.int if rvalue is an int literal, etc.
If this is a 'Final' context, we return "Literal[...]" instead.
"""
if self.function_stack and not do_bools:
if self.function_stack and not do_inner:
# Skip inside a function; this is to avoid confusing
# the code that handles dead code due to isinstance()
# inside type variables with value restrictions (like
Expand Down Expand Up @@ -4898,6 +4898,10 @@ def visit_call_expr(self, expr: CallExpr) -> None:
expr.analyzed = OpExpr("divmod", expr.args[0], expr.args[1])
expr.analyzed.line = expr.line
expr.analyzed.accept(self)
elif refers_to_fullname(expr.callee, "typing.TypeVar"):
for a, a_name in zip(expr.args, expr.arg_names):
with self.allow_unbound_tvars_set() if a_name == "bound" else nullcontext():
a.accept(self)
else:
# Normal call expression.
for a in expr.args:
Expand Down Expand Up @@ -6671,7 +6675,7 @@ def is_unannotated_any(typ_: Type) -> bool:
typ = None
if arg.variable.is_inferred and arg.initializer:
arg.initializer.accept(self)
typ = self.analyze_simple_literal_type(arg.initializer, False, do_bools=True)
typ = self.analyze_simple_literal_type(arg.initializer, False, do_inner=True)
arg_types.append(typ or UntypedType())
ret_type = None
if self.options.default_return and self.options.disallow_untyped_defs:
Expand Down Expand Up @@ -6706,7 +6710,7 @@ def is_unannotated_any(typ_: Type) -> bool:
if is_unannotated_any(defn.type.arg_types[i]):
if arg.variable.is_inferred and arg.initializer:
ret = self.analyze_simple_literal_type(
arg.initializer, False, do_bools=True
arg.initializer, False, do_inner=True
)
if ret:
defn.type.arg_types[i] = ret
Expand Down
2 changes: 1 addition & 1 deletion mypy/stubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def _verify_final(
) -> Iterator[Error]:
try:

class SubClass(runtime): # type: ignore[misc]
class SubClass(runtime): # type: ignore[no-subclass-any]
pass

except TypeError:
Expand Down
2 changes: 1 addition & 1 deletion mypy/test/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ def split_test_cases(
line_no += data.count("\n") + 1

# Record existing tests to prevent duplicates:
test_names.update({name})
test_names.update({name}) # type: ignore[no-untyped-call]


class DataSuiteCollector(pytest.Class):
Expand Down
1 change: 1 addition & 0 deletions mypy/test/testdaemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ def run_cmd(input: str) -> tuple[int, str]:
input = sys.executable + " -m" + input
env = os.environ.copy()
env["PYTHONPATH"] = PREFIX
env["__MYPY_UNDER_TEST__"] = "1"
try:
output = subprocess.check_output(
input, shell=True, stderr=subprocess.STDOUT, text=True, cwd=test_temp_dir, env=env
Expand Down
3 changes: 1 addition & 2 deletions mypy_self_check.ini
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@ nonlocal_partial_types = True
allow_any_expr = True
allow_any_explicit = True
allow_any_decorated = True
allow_subclassing_any = True
no_warn_unreachable = True
implicit_reexport = True
disallow_redefinition = True
disable_error_code = truthy-bool, no-untyped-usage, partially-defined
disable_error_code = truthy-bool, no-untyped-usage, possibly-undefined
bare_literals = True

[mypy-mypy.*,mypyc.*]
Expand Down
1 change: 0 additions & 1 deletion test-data/unit/check-parameter-specification.test
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ def foo3(x: Concatenate[int, P]) -> int: ... # E: Invalid location for Concaten
# N: You can use Concatenate as the first argument to Callable

def foo4(x: List[P]) -> None: ... # E: Invalid location for ParamSpec "P" \
# E: Invalid location for ParamSpec "P" \
# N: You can use ParamSpec as the first argument to Callable, e.g., 'Callable[P, int]'

def foo5(x: Callable[[int, str], P]) -> None: ... # E: Invalid location for ParamSpec "P" \
Expand Down
3 changes: 2 additions & 1 deletion test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -1401,7 +1401,8 @@ reveal_type(var) # N: Revealed type is "Any"
def foo() -> Self: ... # E: Self type is only allowed in annotations within class definition
reveal_type(foo) # N: Revealed type is "def () -> Any"

bad: Callable[[Self], Self] # E: Self type is only allowed in annotations within class definition
bad: Callable[[Self], Self] # E: Self type is only allowed in annotations within class definition \
# E: Self type is only allowed in annotations within class definition
reveal_type(bad) # N: Revealed type is "def (Any) -> Any"

def func() -> None:
Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/pythoneval.test
Original file line number Diff line number Diff line change
Expand Up @@ -1855,6 +1855,6 @@ _testTupleWithDifferentArgsPy310.py:17: note: Revealed type is "Union[builtins.t
_testTupleWithDifferentArgsPy310.py:18: note: Revealed type is "Tuple[builtins.float, builtins.str]"
_testTupleWithDifferentArgsPy310.py:19: note: Revealed type is "builtins.tuple[builtins.float, ...]"
_testTupleWithDifferentArgsPy310.py:20: note: Revealed type is "builtins.list[Tuple[builtins.int, builtins.str]]"
_testTupleWithDifferentArgsPy310.py:26: error: Invalid type: try using Literal[1] instead?
_testTupleWithDifferentArgsPy310.py:26: error: "1" is a bare literal and cannot be used here, try Literal[1] instead?
_testTupleWithDifferentArgsPy310.py:27: error: Unexpected "..."
_testTupleWithDifferentArgsPy310.py:30: note: Revealed type is "builtins.tuple[builtins.object, ...]"

0 comments on commit e24b373

Please sign in to comment.