Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/code/typeguard/_checkers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -914,6 +914,10 @@ def check_type_internal(
:param memo: a memo object containing configuration and information necessary for
looking up forward references
"""
ty = type(value)
if ty == annotation or (value is None and annotation is type(None)):
# some early exits for better performance
return
annotation = resolve_alias_chains(annotation)

if isinstance(annotation, ForwardRef):
Expand Down
24 changes: 24 additions & 0 deletions python/code/wypp/errors.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,6 +78,30 @@ def invalidType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidRestArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidRestArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def invalidKwArgType(ty: Any, loc: Optional[location.Loc]) -> WyppTypeError:
lines = []
tyStr = renderTy(ty)
lines.append(i18n.invalidKwArgTy(tyStr))
lines.append('')
if loc is not None:
lines.append(f'## {i18n.tr("File")} {loc.filename}')
lines.append(f'## {i18n.tr("Type declared in line")} {loc.startLine}:\n')
lines.append(renderLoc(loc))
raise WyppTypeError('\n'.join(lines))

@staticmethod
def unknownKeywordArgument(callableName: location.CallableName, callLoc: Optional[location.Loc], name: str) -> WyppTypeError:
lines = []
Expand Down
10 changes: 10 additions & 0 deletions python/code/wypp/i18n.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,6 +102,10 @@ def tr(key: str, **kws) -> str:

'invalid type `{ty}`':
'ungültiger Typ `{ty}`',
'invalid type for rest argument: `{ty}`':
'ungültiger Typ für Restargument: `{ty}`',
'invalid type for keyword argument: `{ty}`':
'ungültiger Typ für Schlüsselwort-Argument: `{ty}`',
'Cannot set attribute to value of type `{ty}`.':
'Das Attribut kann nicht auf einen Wert vom Typ `{ty}` gesetzt werden.',
'Problematic assignment in line': 'Fehlerhafte Zuweisung in Zeile',
Expand DownExpand Up@@ -342,6 +346,12 @@ def noTypeAnnotationForAttribute(attrName: str, recordName: str) -> str:
def invalidTy(ty: Any) -> str:
return tr('invalid type `{ty}`', ty=ty)

def invalidRestArgTy(ty: Any) -> str:
return tr('invalid type for rest argument: `{ty}`', ty=ty)

def invalidKwArgTy(ty: Any) -> str:
return tr('invalid type for keyword argument: `{ty}`', ty=ty)

def didYouMean(ty: str) -> str:
return tr('Did you mean `{ty}`?', ty=ty)

Expand Down
7 changes: 5 additions & 2 deletions python/code/wypp/location.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -217,6 +217,7 @@ def __init__(self, f: Callable, kind: CallableKind):
self.__lineno = f.__code__.co_firstlineno
self.__name = f.__name__
self.__ast = parsecache.getAST(self.file)
self.__async = None

def __repr__(self):
return f'StdCallableInfo({self.name}, {self.kind})'
Expand DownExpand Up@@ -282,8 +283,10 @@ def getParamSourceLocation(self, paramName: str) -> Optional[Loc]:

@property
def isAsync(self) -> bool:
node = self._findDef()
return isinstance(node, ast.AsyncFunctionDef)
if self.__async is None:
node = self._findDef()
self.__async = isinstance(node, ast.AsyncFunctionDef)
return self.__async

def classFilename(cls) -> str | None:
"""Best-effort path to the file that defined `cls`."""
Expand Down
14 changes: 14 additions & 0 deletions python/code/wypp/stacktrace.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,11 @@ def __call__(self, frame: types.FrameType, event: str, arg: Any):
pass
case 'c_exception':
pass
def getReturnFrameType(self, idx: int) -> Optional[types.FrameType]:
try:
return self.__returnFrames[idx]
except IndexError:
return None
def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
try:
f = self.__returnFrames[idx]
Expand All@@ -102,6 +107,15 @@ def getReturnFrame(self, idx: int) -> Optional[inspect.FrameInfo]:
else:
return None

def frameTypeToFrameInfo(f: Optional[types.FrameType]) -> Optional[inspect.FrameInfo]:
if f:
tb = inspect.getframeinfo(f, context=1)
fi = inspect.FrameInfo(f, tb.filename, tb.lineno, tb.function, tb.code_context, tb.index)
del f
return fi
else:
return None

# when using _call_with_next_frame_removed, we have to take the second-to-last
# return. Hence, we keep the two most recent returns byn setting entriesToKeep = 2.
def installProfileHook(entriesToKeep: int=2) -> ReturnTracker:
Expand Down
77 changes: 49 additions & 28 deletions python/code/wypp/typecheck.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar, Any, Optional, Literal
import types
import inspect
from dataclasses import dataclass
import utils
Expand All@@ -24,14 +25,14 @@ def isEmptySignature(sig: inspect.Signature) -> bool:
return False
return isEmptyAnnotation(sig.return_annotation)

def handleMatchesTyResult(res: MatchesTyResult, tyLoc: Optional[location.Loc]) -> bool:
def handleMatchesTyResult(res: MatchesTyResult, getTyLoc: Callable[[], Optional[location.Loc]]) -> bool:
match res:
case MatchesTyFailure(exc, ty):
if isDebug():
debug(f'Exception occurred while calling matchesTy with type {ty}, re-raising')
raise exc
else:
raise errors.WyppTypeError.invalidType(ty, tyLoc)
raise errors.WyppTypeError.invalidType(ty, getTyLoc())
case b:
return b

Expand DownExpand Up@@ -63,9 +64,11 @@ def checkSignature(sig: inspect.Signature, info: location.CallableInfo, cfg: Che
locDecl = info.getParamSourceLocation(name)
raise errors.WyppTypeError.partialAnnotationError(location.CallableName.mk(info), name, locDecl)
if p.default is not inspect.Parameter.empty:
locDecl = info.getParamSourceLocation(name)
locDecl = lambda: info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(p.default, ty, cfg.ns), locDecl):
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name, locDecl, ty, p.default)
raise errors.WyppTypeError.defaultError(location.CallableName.mk(info), name,
locDecl(), ty, p.default)


def mandatoryArgCount(sig: inspect.Signature) -> int:
required_kinds = {
Expand All@@ -80,24 +83,34 @@ def mandatoryArgCount(sig: inspect.Signature) -> int:
return res

def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
locArg: Optional[location.Loc], info: location.CallableInfo, cfg: CheckCfg):
getLocArg: Callable[[], Optional[location.Loc]],
info: location.CallableInfo, cfg: CheckCfg):
t = p.annotation
if not isEmptyAnnotation(t):
locDecl = lambda: info.getParamSourceLocation(name)
if p.kind == inspect.Parameter.VAR_POSITIONAL:
if type(t) == str:
t = eval(t)
argT = None
# For *args annotated as tuple[X, ...], extract the element type X
origin = getattr(t, '__origin__', None)
if origin is tuple:
args = getattr(t, '__args__', None)
if args:
if args and len(args) == 2 and args[1] is Ellipsis:
# tuple[X, ...] — homogeneous variadic
argT = args[0]
elif args:
# tuple[X, Y, ...] — fixed-length tuple, no single element type to extract
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
elif t is tuple:
# bare `tuple` without type parameters, nothing to check
return
else:
raise ValueError(f'Invalid type for rest argument: {t}')
raise errors.WyppTypeError.invalidRestArgType(t, locDecl())
t = argT
elif p.kind == inspect.Parameter.VAR_KEYWORD:
if type(t) == str:
t = eval(t)
valT = None
# For **kwargs annotated as dict[str, X], extract the value type X
origin = getattr(t, '__origin__', None)
Expand All@@ -108,31 +121,39 @@ def checkArgument(p: inspect.Parameter, name: str, idx: Optional[int], a: Any,
elif t is dict:
return
else:
raise ValueError(f'Invalid type for keyword argument: {t}')
raise errors.WyppTypeError.invalidKwArgType(t, info.getParamSourceLocation(p.name))
t = valT
locDecl = info.getParamSourceLocation(name)
if not handleMatchesTyResult(matchesTy(a, t, cfg.ns), locDecl):
cn = location.CallableName.mk(info)
raise errors.WyppTypeError.argumentError(cn,
name,
idx,
locDecl,
locDecl(),
t,
a,
locArg)
getLocArg())

def checkArguments(sig: inspect.Signature, args: tuple, kwargs: dict,
info: location.CallableInfo, cfg: CheckCfg) -> None:
debug(f'Checking arguments when calling {info}')
if isDebug():
debug(f'Checking arguments when calling {info}')
paramNames = list(sig.parameters)
mandatory = mandatoryArgCount(sig)
kind = getKind(cfg, paramNames)
offset = 1 if kind == 'method' else 0
fi = stacktrace.callerOutsideWypp()
callLoc = None if not fi else location.Loc.fromFrameInfo(fi)
cn = location.CallableName.mk(info)
# stacktrace.callerOutsideWypp() is expensive, only access it lazily
def getCallLoc() -> Optional[location.Loc]:
fi = stacktrace.callerOutsideWypp()
return None if not fi else location.Loc.fromFrameInfo(fi)
def getLocArg(idxOrName: int | str) -> Callable[[], Optional[location.Loc]]:
def f():
fi = stacktrace.callerOutsideWypp()
return None if fi is None else location.locationOfArgument(fi, i)
return f
def raiseArgMismatch():
raise errors.WyppTypeError.argCountMismatch(cn,
callLoc,
getCallLoc(),
len(paramNames) - offset,
mandatory - offset,
len(args) - offset)
Expand All@@ -152,46 +173,46 @@ def raiseArgMismatch():
raiseArgMismatch()
# Check positional args
for i in range(len(args)):
locArg = None if fi is None else location.locationOfArgument(fi, i)
if i < len(positionalNames):
name = positionalNames[i]
p = sig.parameters[name]
checkArgument(p, name, i - offset, args[i], locArg, info, cfg)
checkArgument(p, name, i - offset, args[i], getLocArg(i), info, cfg)
elif varPositionalParam is not None:
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], locArg, info, cfg)
checkArgument(varPositionalParam, varPositionalParam.name, i - offset, args[i], getLocArg(i), info, cfg)
else:
raiseArgMismatch()
# Check keyword args
for name in kwargs:
locArg = None if fi is None else location.locationOfArgument(fi, name)
if name in sig.parameters and sig.parameters[name].kind not in (
inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD
):
checkArgument(sig.parameters[name], name, None, kwargs[name], locArg, info, cfg)
checkArgument(sig.parameters[name], name, None, kwargs[name], getLocArg(name), info, cfg)
elif varKeywordParam is not None:
checkArgument(varKeywordParam, name, None, kwargs[name], locArg, info, cfg)
checkArgument(varKeywordParam, name, None, kwargs[name], getLocArg(name), info, cfg)
else:
raise errors.WyppTypeError.unknownKeywordArgument(cn, callLoc, name)
raise errors.WyppTypeError.unknownKeywordArgument(cn, getCallLoc(), name)

def checkReturn(sig: inspect.Signature, returnFrame: Optional[inspect.FrameInfo],
def checkReturn(sig: inspect.Signature, returnFrameType: Optional[types.FrameType],
result: Any, info: location.CallableInfo, cfg: CheckCfg) -> None:
if info.isAsync:
return
t = sig.return_annotation
if isEmptyAnnotation(t):
t = None
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = info.getResultTypeLocation()
if isDebug():
debug(f'Checking return value when calling {info}, return type: {t}')
locDecl = lambda: info.getResultTypeLocation()
if not handleMatchesTyResult(matchesTy(result, t, cfg.ns), locDecl):
fi = stacktrace.callerOutsideWypp()
if fi is not None:
locRes = location.Loc.fromFrameInfo(fi)
returnLoc = None
extraFrames = []
returnFrame = stacktrace.frameTypeToFrameInfo(returnFrameType)
if returnFrame:
returnLoc = location.Loc.fromFrameInfo(returnFrame)
extraFrames = [returnFrame]
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl, t, returnLoc, result,
raise errors.WyppTypeError.resultError(location.CallableName.mk(info), locDecl(), t, returnLoc, result,
locRes, extraFrames)


Expand DownExpand Up@@ -232,9 +253,9 @@ def wrapped(*args, **kwargs) -> T:
utils._call_with_frames_removed(checkArguments, sig, args, kwargs, info, checkCfg)
returnTracker = stacktrace.getReturnTracker()
result = utils._call_with_next_frame_removed(f, *args, **kwargs)
retFrame = returnTracker.getReturnFrame(0)
ft = returnTracker.getReturnFrameType(0)
utils._call_with_frames_removed(
checkReturn, sig, retFrame, result, info, checkCfg
checkReturn, sig, ft, result, info, checkCfg
)
return result
return wrapped
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args3_ok.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,4 +14,4 @@ f(1, 10, '11', y=2, z=3)

## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args5.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
2 changes: 1 addition & 1 deletion python/file-test-data/extras/args6.py
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int], **kw: dict[str, int]):
def f(x: int, *rest: tuple[int, ...], **kw: dict[str, int]):
print(f'x={x}, kw={kw}')

f(1)
Expand Down
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args7.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args7.py", line 6, in <module>
f(1, 2)

WyppTypeError: ungültiger Typ für Restargument: `tuple[int]`

## Datei file-test-data/extras/args7.py
## Typ deklariert in Zeile 3:

def f(x: int, *rest: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args7.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, *rest: tuple[int]):
pass

f(1, 2)
10 changes: 10 additions & 0 deletions python/file-test-data/extras/args8.err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "file-test-data/extras/args8.py", line 6, in <module>
f(1, y=2)

WyppTypeError: ungültiger Typ für Schlüsselwort-Argument: `tuple[int]`

## Datei file-test-data/extras/args8.py
## Typ deklariert in Zeile 3:

def f(x: int, **kw: tuple[int]):
Empty file.
6 changes: 6 additions & 0 deletions python/file-test-data/extras/args8.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
from wypp import *

def f(x: int, **kw: tuple[int]):
pass

f(1, y=2)
4 changes: 2 additions & 2 deletions python/file-test-data/extras/testForwardRef5.err
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,8 +9,8 @@ Der Aufruf des Konstruktors des Records `Garage` erwartet einen Wert vom Typ `li
## Datei file-test-data/extras/testForwardRef5.py
## Fehlerhafter Aufruf in Zeile 22:

garage = Garage(cars=[Car(color='red'), "Not A Car"])
garage = Garage(cars=[Car(color='red'), "Not A Car"])

## Typ deklariert in Zeile 11:

cars: list['Car']
cars: list['Car']
5 changes: 4 additions & 1 deletion python/run
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,9 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
OPTS="--quiet"
# OPTS="--verbose"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
# For profiling, uncomment the line below
# PROF="-m cProfile -o profile.out"

PYTHONPATH="$SCRIPT_DIR"/code:"$PYTHONPATH" $PY $PROF "$SCRIPT_DIR"/code/wypp/runYourProgram.py \
--no-clear $OPTS "$@"
exit $?
Loading