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
3 changes: 3 additions & 0 deletions python/code/wypp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,6 @@ def record(cls=None, mutable=False, globals={}, locals={}):
resetTestCount = w.resetTestCount
deepEq = w.deepEq
wrapTypecheck = w.wrapTypecheck
WyppTypeError = w.WyppTypeError
WyppAttributeError = w.WyppAttributeError
WyppError = w.WyppError
6 changes: 6 additions & 0 deletions python/code/wypp/ansi.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re

RESET = "\u001b[0;0m"
BOLD = "\u001b[1m"
REVERSE = "\u001b[2m"
Expand Down Expand Up @@ -30,3 +32,7 @@ def red(s):

def blue(s):
return color(s, BLUE + BOLD)

_ANSI_ESCAPE_RE = re.compile(r'\u001b\[[0-9;]*m')
def stripAnsi(s: str) -> str:
return _ANSI_ESCAPE_RE.sub('', s)
5 changes: 0 additions & 5 deletions python/code/wypp/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ class WyppTypeError(TypeError, WyppError):
def __init__(self, msg: str, extraFrames: list[inspect.FrameInfo] = []):
WyppError.__init__(self, extraFrames)
self.msg = msg
self.add_note(msg)

def __str__(self):
return f'WyppTypeError: {self.msg}'
Expand Down Expand Up @@ -290,7 +289,6 @@ class WyppAttributeError(AttributeError, WyppError):
def __init__(self, msg: str, extraFrames: list[inspect.FrameInfo] = []):
WyppError.__init__(self, extraFrames)
self.msg = msg
self.add_note(msg)

@staticmethod
def unknownAttr(clsName: str, attrName: str) -> WyppAttributeError:
Expand All @@ -301,12 +299,9 @@ class TodoError(Exception, WyppError):
def __init__(self, msg: str, extraFrames: list[inspect.FrameInfo] = []):
WyppError.__init__(self, extraFrames)
self.msg = msg
self.add_note(msg)


class ImpossibleError(Exception, WyppError):
def __init__(self, msg: str, extraFrames: list[inspect.FrameInfo] = []):
WyppError.__init__(self, extraFrames)
self.msg = msg
self.add_note(msg)

28 changes: 23 additions & 5 deletions python/code/wypp/replTester.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import sys
import doctest
from contextlib import contextmanager
import ansi
from myLogging import *

# We use our own DocTestParser to replace exception names in stacktraces
Expand All @@ -8,7 +10,9 @@
def rewriteLines(lines: list[str]):
"""
Each line has exactly one of the following four kinds:
- COMMENT: if it starts with '#' (leading whitespace stripped)
- COMMENT: if it starts with '#' but not with '##' (leading whitespace stripped)
Rationale: lines starting with '##' are error messages from wypp, lines starting only with
'#' are real comments in the file defining the doctest.
- PROMPT: if it starts with '>>>' (leading whitespace stripped)
- EMPTY: if it contains only whitespace
- OUTPUT: otherwise
Expand All @@ -22,7 +26,7 @@ def get_line_kind(line: str) -> str:
stripped = line.lstrip()
if not stripped:
return 'EMPTY'
elif stripped.startswith('#'):
elif stripped.startswith('#') and not stripped.startswith('##'):
return 'COMMENT'
elif stripped.startswith('>>>'):
return 'PROMPT'
Expand Down Expand Up @@ -56,7 +60,6 @@ def find_next_non_empty(idx: int) -> tuple[int, str]:
if prev_kind in ['PROMPT', 'OUTPUT'] and next_kind == 'OUTPUT':
lines[i] = '<BLANKLINE>'


class MyDocTestParser(doctest.DocTestParser):
def get_examples(self, string, name='<string>'):
"""
Expand All @@ -76,10 +79,25 @@ def get_examples(self, string, name='<string>'):
x = super().get_examples(string, name)
return x

class MyOutputChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
got = ansi.stripAnsi(got)
return super().check_output(want, got, optionflags)

@contextmanager
def patchOutputChecker():
_Original = doctest.OutputChecker
doctest.OutputChecker = MyOutputChecker
try:
yield
finally:
doctest.OutputChecker = _Original

def testRepl(repl: str, defs: dict) -> tuple[int, int]:
doctestOptions = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
(failures, tests) = doctest.testfile(repl, globs=defs, module_relative=False,
optionflags=doctestOptions, parser=MyDocTestParser())
with patchOutputChecker():
(failures, tests) = doctest.testfile(repl, globs=defs, module_relative=False,
optionflags=doctestOptions, parser=MyDocTestParser())
if failures == 0:
if tests == 0:
print(f'No tests in {repl}')
Expand Down
14 changes: 8 additions & 6 deletions python/code/wypp/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,14 @@ def main(globals, argList=None):
printStderr(f'Unsupported language {args.lang}. Supported: ' + ', '.join(i18n.allLanguages))
sys.exit(1)

fileToRun: str = args.file
isInteractive = args.interactive
version = versionMod.readVersion()
fileToRun: str|None = args.file
if fileToRun is None:
if args.repls:
import replTester
replTester.testRepls(args.repls, globals)
return
if not os.path.exists(fileToRun):
printStderr(f'File {fileToRun} does not exist')
sys.exit(1)
Expand All @@ -75,11 +82,6 @@ def main(globals, argList=None):
fileToRun = os.path.basename(fileToRun)
debug(f'Changed directory to {d}, fileToRun={fileToRun}')

isInteractive = args.interactive
version = versionMod.readVersion()

if fileToRun is None:
return

if not args.checkRunnable and (not args.quiet or args.verbose):
printWelcomeString(fileToRun, version, doTypecheck=args.checkTypes)
Expand Down
11 changes: 10 additions & 1 deletion python/code/wypp/stacktrace.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
import traceback
import utils
import inspect
import threading
from typing import Optional, Any
import os
import sys
from collections import deque
from myLogging import *

def tbToFrameList(tb: types.TracebackType) -> list[types.FrameType]:
cur = tb
Expand Down Expand Up @@ -130,5 +132,12 @@ def getReturnTracker():
obj = sys.getprofile()
if isinstance(obj, ReturnTracker):
return obj
elif obj is None:
if threading.current_thread() is threading.main_thread():
raise ValueError(f'No ReturnTracker set, must use installProfileHook before')
else:
debug('ReturnTracker not available in threads')
return None
else:
raise ValueError(f'No ReturnTracker set, must use installProfileHook before')
debug(f'Profiling set to some custom profiler: {obj}')
return None
2 changes: 1 addition & 1 deletion python/code/wypp/typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ 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)
ft = returnTracker.getReturnFrameType(0)
ft = returnTracker.getReturnFrameType(0) if returnTracker else None
utils._call_with_frames_removed(
checkReturn, sig, ft, result, info, checkCfg
)
Expand Down
4 changes: 4 additions & 0 deletions python/code/wypp/writeYourProgram.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,7 @@ def impossible(msg=None):
math = moduleMath

wrapTypecheck = typecheck.wrapTypecheck

WyppTypeError = errors.WyppTypeError
WyppAttributeError = errors.WyppAttributeError
WyppError = errors.WyppError
Loading