jwutils: Move to jwutils -> jw.util
Move all implementation source code from the jwutils module to jw.util. For compatibility with existing Python modules, keep a thin, autogenerated compatibility shim under jwutils. Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
bc7652fdf9
commit
a2684dd601
126 changed files with 678 additions and 52 deletions
4
src/python/Makefile
Normal file
4
src/python/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mods.mk
|
||||
4
src/python/jw/Makefile
Normal file
4
src/python/jw/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-ns-dir.mk
|
||||
3
src/python/jw/__init__.py
Normal file
3
src/python/jw/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
from pkgutil import extend_path
|
||||
|
||||
__path__ = extend_path(__path__, __name__)
|
||||
83
src/python/jw/util/ArgsContainer.py
Normal file
83
src/python/jw/util/ArgsContainer.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import argparse
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
from .log import slog
|
||||
|
||||
class ArgsContainer: # export
|
||||
|
||||
__args: OrderedDict[str, str] = OrderedDict()
|
||||
__kwargs: OrderedDict[str, str] = OrderedDict()
|
||||
__values: dict[str, str] = {}
|
||||
__specified_args: list[str] = list()
|
||||
|
||||
def __getattr__(self, name):
|
||||
values = self.__values
|
||||
if name in self.__values:
|
||||
return self.__values[name]
|
||||
if name in self.__kwargs.keys():
|
||||
d = self.__kwargs[name]
|
||||
if 'default' in d:
|
||||
return d['default']
|
||||
raise Exception(f'No value for argument "{name}"')
|
||||
raise Exception(f'No argument "{name}" defined')
|
||||
|
||||
def __setattr__(self, name, value):
|
||||
if not name in self.__kwargs.keys():
|
||||
raise Exception(f'No argument "{name}" defined')
|
||||
self.__values[name] = value
|
||||
self.__specified_args.append(name)
|
||||
|
||||
def add_argument(self, *args, **kwargs):
|
||||
for arg in args:
|
||||
if arg[0] != '-':
|
||||
name = arg
|
||||
break
|
||||
if arg[:2] == '--':
|
||||
name = arg[2:]
|
||||
break
|
||||
else:
|
||||
raise Exception('Missing argument name')
|
||||
name = name.replace('-', '_')
|
||||
self.__args[name] = args
|
||||
self.__kwargs[name] = kwargs
|
||||
|
||||
def keys(self):
|
||||
return self.__args.keys()
|
||||
|
||||
def args(self, name) -> str:
|
||||
return self.__args[name]
|
||||
|
||||
def kwargs(self, name) -> str:
|
||||
return self.__kwargs[name]
|
||||
|
||||
def dump(self, prio, *args, **kwargs):
|
||||
caller = get_caller_pos(**kwargs)
|
||||
for name in self.__kwargs.keys():
|
||||
val = None
|
||||
try:
|
||||
val = self.__getattr__(name)
|
||||
except:
|
||||
pass
|
||||
slog(prio, f'{name}: {val}', caller=caller)
|
||||
|
||||
@property
|
||||
def specified_args(self):
|
||||
return self.__specified_args
|
||||
|
||||
def add_argument(p: argparse.ArgumentParser|ArgsContainer, name: str, *args, **kwargs): # export
|
||||
|
||||
key = name.strip('--').replace('-', '_')
|
||||
if isinstance(p, ArgsContainer):
|
||||
if key in p.keys():
|
||||
return
|
||||
elif isinstance(p, argparse.ArgumentParser):
|
||||
for action in p._actions:
|
||||
if key == action.dest:
|
||||
return
|
||||
else:
|
||||
raise Exception('Unknown type {type(p)} of {p} passed to add_argument()')
|
||||
|
||||
p.add_argument(name, *args, **kwargs)
|
||||
11
src/python/jw/util/Bunch.py
Normal file
11
src/python/jw/util/Bunch.py
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
|
||||
class Bunch: # export
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.__dict__.update(kwargs)
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
return self.__dict__[key]
|
||||
61
src/python/jw/util/Cmd.py
Normal file
61
src/python/jw/util/Cmd.py
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
import inspect, sys, re, abc, argparse
|
||||
from argparse import ArgumentParser, _SubParsersAction
|
||||
|
||||
from . import log
|
||||
|
||||
# full blown example of one level of nested subcommands
|
||||
# git -C project remote -v show -n myremote
|
||||
|
||||
class Cmd(abc.ABC): # export
|
||||
|
||||
@abc.abstractmethod
|
||||
async def run(self, args):
|
||||
pass
|
||||
|
||||
def __init__(self, name: str, help: str) -> None:
|
||||
from . import Cmds
|
||||
self.name = name
|
||||
self.help = help
|
||||
self.parent = None
|
||||
self.children: list[Cmd] = []
|
||||
self.child_classes: list[type[Cmd]] = []
|
||||
self.app: Cmds|None = None
|
||||
|
||||
async def _run(self, args):
|
||||
pass
|
||||
|
||||
def add_parser(self, parsers) -> ArgumentParser:
|
||||
r = parsers.add_parser(self.name, help=self.help,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
r.set_defaults(func=self.run)
|
||||
return r
|
||||
|
||||
def add_subcommands(self, cmd: str|type[Cmd]|list[type[Cmd]]) -> None:
|
||||
if isinstance(cmd, str):
|
||||
sc = []
|
||||
for name, obj in inspect.getmembers(sys.modules[self.__class__.__module__]):
|
||||
if inspect.isclass(obj):
|
||||
if re.search(cmd, str(obj)):
|
||||
sc.append(obj)
|
||||
log.slog(log.DEBUG, f"Found subcommand {obj}")
|
||||
self.add_subcommands(sc)
|
||||
return
|
||||
if isinstance(cmd, list):
|
||||
for c in cmd:
|
||||
self.add_subcommands(c)
|
||||
return
|
||||
self.child_classes.append(cmd)
|
||||
|
||||
# To be overridden by derived class in case the command does take arguments.
|
||||
# Will be called from App base class constructor and set up the parser hierarchy
|
||||
def add_arguments(self, parser: ArgumentParser) -> None:
|
||||
pass
|
||||
|
||||
def conf_value(self, path, default=None):
|
||||
ret = None if self.app is None else self.app.conf_value(path, default)
|
||||
if ret is None and default is not None:
|
||||
return default
|
||||
return ret
|
||||
178
src/python/jw/util/Cmds.py
Normal file
178
src/python/jw/util/Cmds.py
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os, sys, argcomplete, argparse, importlib, inspect, re, pickle, asyncio, cProfile
|
||||
from argparse import ArgumentParser
|
||||
from pathlib import Path, PurePath
|
||||
|
||||
from .log import *
|
||||
from .stree import serdes
|
||||
|
||||
class Cmds: # export
|
||||
|
||||
def __instantiate(self, cls):
|
||||
try:
|
||||
r = cls()
|
||||
except Exception as e:
|
||||
slog(ERR, f'Failed to instantiate command of type {cls}: {e}')
|
||||
raise
|
||||
r.cmds = self # TODO: Rename Cmds class to App, "Cmds" isn't very self-explanatory
|
||||
r.app = self
|
||||
return r
|
||||
|
||||
def __add_cmd_to_parser(self, cmd, parsers):
|
||||
parser = cmd.add_parser(parsers)
|
||||
cmd.add_arguments(parser)
|
||||
if len(cmd.child_classes) > len(cmd.children):
|
||||
for c in cmd.child_classes:
|
||||
cmd.children.append(self.__instantiate(c))
|
||||
if len(cmd.children) > 0:
|
||||
subparsers = parser.add_subparsers(title='Available subcommands of ' + cmd.name, metavar='')
|
||||
for sub_cmd in cmd.children:
|
||||
self.__add_cmd_to_parser(sub_cmd, subparsers)
|
||||
|
||||
def __parse_config(self):
|
||||
exe_stem = str(PurePath(sys.argv[0]).stem)
|
||||
path = str(Path.home()) + '/.' + exe_stem + 'rc'
|
||||
if not os.path.exists(path):
|
||||
return None, []
|
||||
slog(DEBUG, 'Reading configuration "{}"'.format(path))
|
||||
return serdes.read(path, ''), [path]
|
||||
|
||||
def __init__(self, description: str = '', filter: str = '^Cmd.*', modules: None=None, eloop: None=None) -> None:
|
||||
self.__description = description
|
||||
self.__filter = filter
|
||||
self.__modules = modules
|
||||
self.__conf, self.__conf_paths = self.__parse_config()
|
||||
self.__cmds = []
|
||||
self.eloop = eloop
|
||||
self.__own_eloop = False
|
||||
if eloop is None:
|
||||
self.eloop = asyncio.get_event_loop()
|
||||
self.__own_eloop = True
|
||||
|
||||
log_level = "notice"
|
||||
log_flags = 'stderr,position,prio,color'
|
||||
log_file = None
|
||||
# poor man's parsing in the absence of a complete command-line definition
|
||||
for i in range(1, len(sys.argv)):
|
||||
if i >= len(sys.argv) - 1:
|
||||
break
|
||||
arg = sys.argv[i]
|
||||
if arg == '--log-level':
|
||||
i += 1
|
||||
log_level = sys.argv[i]
|
||||
continue
|
||||
if arg == '--log-flags':
|
||||
log_flags = sys.argv[i]
|
||||
continue
|
||||
set_flags(log_flags)
|
||||
set_level(log_level)
|
||||
slog(DEBUG, "set log level to {}".format(log_level))
|
||||
self.__parser = argparse.ArgumentParser(usage=os.path.basename(sys.argv[0]) + ' [options]',
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=self.__description)
|
||||
self.__parser.add_argument('--log-flags', help='Log flags', default=log_flags)
|
||||
self.__parser.add_argument('--log-level', help='Log level', default=log_level)
|
||||
self.__parser.add_argument('--backtrace', help='Show exception backtraces', action='store_true', default=False)
|
||||
self.__parser.add_argument('--write-profile', help='Profile code and store output to file', default=None)
|
||||
self.__parser.add_argument('--log-file', help='Log file', default=log_file)
|
||||
if self.__modules == None:
|
||||
self.__modules = [ '__main__' ]
|
||||
subcmds = set()
|
||||
slog(DEBUG, '-- searching for commands')
|
||||
for m in self.__modules: # type: ignore
|
||||
if m != '__main__':
|
||||
importlib.import_module(m)
|
||||
for name, c in inspect.getmembers(sys.modules[m], inspect.isclass):
|
||||
if not re.match(self.__filter, name):
|
||||
slog(DEBUG, 'o "{}.{}" has wrong name'.format(m, name))
|
||||
continue
|
||||
if inspect.isabstract(c):
|
||||
slog(DEBUG, 'o "{}.{}" is abstract'.format(m, name))
|
||||
continue
|
||||
slog(DEBUG, 'o "{}.{}" is fine, instantiating'.format(m, name))
|
||||
cmd = self.__instantiate(c)
|
||||
#cmd.add_parser(subparsers)
|
||||
self.__cmds.append(cmd)
|
||||
subcmds.update(cmd.child_classes)
|
||||
|
||||
cmds = [cmd for cmd in self.__cmds if type(cmd) not in subcmds]
|
||||
subparsers = self.__parser.add_subparsers(title='Available commands', metavar='')
|
||||
for cmd in cmds:
|
||||
slog(DEBUG, f'Adding top-level command {cmd} to parser')
|
||||
self.__add_cmd_to_parser(cmd, subparsers)
|
||||
|
||||
# Run all sub-commands. Overwrite if you want to do anything before or after
|
||||
async def _run(self, argv=None):
|
||||
return await self.args.func(self.args)
|
||||
|
||||
async def __run(self, argv=None):
|
||||
argcomplete.autocomplete(self.__parser)
|
||||
self.args = self.__parser.parse_args(args=argv)
|
||||
set_flags(self.args.log_flags)
|
||||
set_level(self.args.log_level)
|
||||
self.__back_trace = self.args.backtrace
|
||||
exit_status = 0
|
||||
|
||||
# This is the toplevel parser, i.e. no func member has been added to the args via
|
||||
#
|
||||
# Cmds.__init__()
|
||||
# Cmds.__add_cmd_to_parser(cmd, subparsers)
|
||||
# CmdXXX.add_parser(parsers)
|
||||
# super().add_parser(parsers)
|
||||
# Cmd.__parser.set_defaults(func=self.run)
|
||||
#
|
||||
if not hasattr(self.args, 'func'):
|
||||
self.__parser.print_help()
|
||||
return None
|
||||
|
||||
pr = None if self.args.write_profile is None else cProfile.Profile()
|
||||
if pr is not None:
|
||||
pr.enable()
|
||||
|
||||
if self.__conf:
|
||||
self.__conf.dump(DEBUG, "Configuration")
|
||||
if self.args.log_file is not None:
|
||||
add_log_file(self.args.log_file)
|
||||
|
||||
try:
|
||||
ret = await self._run(self.args)
|
||||
except Exception as e:
|
||||
if hasattr(e, 'message'):
|
||||
slog(ERR, e.message)
|
||||
else:
|
||||
slog(ERR, f'Exception: {type(e)}: {e}')
|
||||
exit_status = 1
|
||||
if self.__back_trace:
|
||||
raise
|
||||
finally:
|
||||
if pr is not None:
|
||||
pr.disable()
|
||||
slog(NOTICE, f'Writing profile statistics to {self.args.write_profile}')
|
||||
pr.dump_stats(self.args.write_profile)
|
||||
|
||||
if exit_status:
|
||||
sys.exit(exit_status)
|
||||
|
||||
def __del__(self):
|
||||
if self.__own_eloop:
|
||||
if self.eloop is not None:
|
||||
self.eloop.close()
|
||||
self.eloop = None
|
||||
self.__own_eloop = False
|
||||
|
||||
def conf_value(self, path, default=None):
|
||||
ret = None if self.__conf is None else self.__conf.value(path)
|
||||
if ret is None and default is not None:
|
||||
return default
|
||||
return ret
|
||||
|
||||
def parser(self) -> ArgumentParser:
|
||||
return self.__parser
|
||||
|
||||
def run(self, argv=None) -> None:
|
||||
#return self.__run()
|
||||
return self.eloop.run_until_complete(self.__run(argv)) # type: ignore
|
||||
|
||||
def run_sub_commands(description = '', filter = '^Cmd.*', modules=None, argv=None): # export
|
||||
cmds = Cmds(description, filter, modules)
|
||||
return cmds.run(argv=argv)
|
||||
169
src/python/jw/util/Config.py
Normal file
169
src/python/jw/util/Config.py
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Dict, cast
|
||||
import os, re, glob, sys
|
||||
from pathlib import Path, PosixPath
|
||||
|
||||
from . import stree
|
||||
from .stree.StringTree import StringTree
|
||||
from .log import *
|
||||
|
||||
class Config(): # export
|
||||
|
||||
def __load(self, search_dirs, glob_paths, refuse_mode_mask):
|
||||
|
||||
def __is_abs(path):
|
||||
if path is None:
|
||||
return False
|
||||
if len(path) == 0:
|
||||
return False
|
||||
if path[0] != '/':
|
||||
return False
|
||||
return True
|
||||
|
||||
ret = StringTree("", "")
|
||||
exe = Path(os.path.basename(sys.argv[0])).stem
|
||||
if glob_paths is None:
|
||||
glob_paths = [f'.{exe}', f'{exe}.conf']
|
||||
elif isinstance(glob_paths, str):
|
||||
glob_paths = [glob_paths]
|
||||
if search_dirs is None:
|
||||
env_key = re.sub('[-.]', '_', exe)
|
||||
search_dirs = os.getenv(env_key)
|
||||
for path in glob_paths:
|
||||
dirs = search_dirs
|
||||
if dirs is None:
|
||||
dirs = [''] if __is_abs(path) else [ str(Path.home()), str(Path.cwd()) ]
|
||||
for d in dirs:
|
||||
g = d + '/' + path if len(d) else path
|
||||
slog(DEBUG, 'Looking for config "{}"'.format(g))
|
||||
for f in glob.glob(g):
|
||||
slog(DEBUG, 'Reading config "{}"'.format(f))
|
||||
paths_buf = []
|
||||
tree = stree.read(f, paths_buf=paths_buf)
|
||||
assert(len(paths_buf))
|
||||
if refuse_mode_mask is not None:
|
||||
for p in paths_buf:
|
||||
st = os.stat(p)
|
||||
if st.st_mode & refuse_mode_mask:
|
||||
for item in tree.child_list():
|
||||
if item.content is None:
|
||||
continue
|
||||
if not re.search('password|secret', cast(str, item.content), flags=re.IGNORECASE):
|
||||
continue
|
||||
msg = "Config files define secret, but at least one has file permissions open for world"
|
||||
slog(ERR, f'{msg}:')
|
||||
for pp in paths_buf:
|
||||
slog(ERR, f' {((os.stat(pp).st_mode) & 0o7777):o} {pp}')
|
||||
raise Exception(msg)
|
||||
tree.dump(DEBUG, f)
|
||||
ret.add("", tree)
|
||||
return ret
|
||||
|
||||
def __init__(self,
|
||||
search_dirs: Optional[list[str]]=None,
|
||||
glob_paths: Optional[list[str]]=None,
|
||||
glob_paths_env_key: Optional[str]=None,
|
||||
defaults: Optional[Dict[str, str]]=None,
|
||||
tree: Optional[StringTree]=None,
|
||||
parent=None,
|
||||
root_section=None,
|
||||
refuse_mode_mask=0o0027
|
||||
) -> None:
|
||||
|
||||
self.__parent = parent
|
||||
|
||||
if tree is not None:
|
||||
assert(search_dirs is None)
|
||||
assert(glob_paths is None)
|
||||
assert(glob_paths_env_key is None)
|
||||
self.__conf = tree
|
||||
else:
|
||||
assert(tree is None)
|
||||
if glob_paths_env_key is not None:
|
||||
glob_paths_env = os.getenv(glob_paths_env_key)
|
||||
if glob_paths_env is not None:
|
||||
if glob_paths is None:
|
||||
glob_paths = []
|
||||
glob_paths.extend(glob_paths_env.split(':'))
|
||||
|
||||
self.__conf = self.__load(search_dirs=search_dirs, glob_paths=glob_paths,
|
||||
refuse_mode_mask=refuse_mode_mask)
|
||||
|
||||
if root_section is not None:
|
||||
tmp = self.__conf.get(root_section)
|
||||
if tmp is None:
|
||||
tmp = StringTree("", "")
|
||||
self.__conf = tmp
|
||||
|
||||
if defaults is not None:
|
||||
for key, val in defaults.items():
|
||||
if self.__conf.get(key) is None:
|
||||
self.__conf[key] = val
|
||||
|
||||
self.__conf.dump(DEBUG, "superposed configuration")
|
||||
|
||||
def __getitem__(self, key: str) -> str:
|
||||
ret = self.get(key)
|
||||
if ret is None:
|
||||
raise KeyError(key)
|
||||
return ret
|
||||
|
||||
def __setitem__(self, key: str, value: str):
|
||||
return self.set(key, value)
|
||||
|
||||
@property
|
||||
def parent(self):
|
||||
return self.__parent
|
||||
|
||||
@property
|
||||
def root(self):
|
||||
if self.__parent is None:
|
||||
return self
|
||||
return self.__parent.root
|
||||
|
||||
def set(self, key: str, val):
|
||||
self.__conf[key] = val
|
||||
|
||||
def get(self, key: str, default = None) -> Optional[str]:
|
||||
item = self.__conf.get(key)
|
||||
if item:
|
||||
return item.value()
|
||||
return default
|
||||
|
||||
def entries(self, key: str) -> list[str]:
|
||||
item = self.__conf.get(key)
|
||||
if item is None:
|
||||
return []
|
||||
return [name for name, child in item.children.items()]
|
||||
|
||||
# This is an alias for get()
|
||||
def value(self, key: str, default = None) -> Optional[str]:
|
||||
return self.get(key, default)
|
||||
|
||||
def branch(self, path: str, throw: bool=True): # type: ignore # Optional[Config]: FIXME: Don't know how to get hold of this type here
|
||||
if self.__conf:
|
||||
tree = self.__conf.get(path)
|
||||
if tree is None:
|
||||
msg = f'Tried to get non-existent branch "{path}" from config'
|
||||
if not throw:
|
||||
slog(DEBUG, msg)
|
||||
return None
|
||||
self.dump(ERR, msg)
|
||||
raise Exception(msg)
|
||||
return Config(tree=tree, parent=self) # type: ignore
|
||||
return None
|
||||
|
||||
def dump(self, prio: int, *args, **kwargs) -> None:
|
||||
caller = get_caller_pos(1, kwargs)
|
||||
self.__conf.dump(prio, caller=caller, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.__conf.content
|
||||
|
||||
def find(self, key: str|None, val: str|None, match:StringTree.Match=StringTree.Match.Equal) -> list[str]:
|
||||
return self.__conf.find(key, val, match=match)
|
||||
|
||||
#def __getattr__(self, name: str):
|
||||
# return getattr(self.__conf, name)
|
||||
104
src/python/jw/util/CppState.py
Normal file
104
src/python/jw/util/CppState.py
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
class CppState: # export
|
||||
|
||||
def __init__(self):
|
||||
self.__pair_square = ['[', ']']
|
||||
self.__pair_curly = ['{', '}']
|
||||
self.__pair_ext = ['<', '>']
|
||||
self.__pair_paren = ['(', ')']
|
||||
self.__pair_c_comment = ['/*', '*/']
|
||||
self.__pair_special = ['?', '?']
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.curly = 0
|
||||
self.square = 0
|
||||
self.ext = 0
|
||||
self.paren = 0
|
||||
self.in_c_comment = False
|
||||
self.in_cpp_comment = False
|
||||
self.in_special = False
|
||||
self.rule = []
|
||||
self.rules = []
|
||||
self.things = []
|
||||
|
||||
def optional(self):
|
||||
return self.square != 0 or self.curly != 0
|
||||
|
||||
def update(self, tok, line):
|
||||
if not self.in_comment():
|
||||
if tok == '[':
|
||||
self.square += 1
|
||||
self.things.append(self.__pair_square)
|
||||
elif tok == ']':
|
||||
self.square -= 1
|
||||
assert(self.things.pop() == self.__pair_square)
|
||||
elif tok == '{':
|
||||
self.curly += 1
|
||||
self.things.append(self.__pair_curly)
|
||||
elif tok == '}':
|
||||
self.curly -= 1
|
||||
assert(self.things.pop() == self.__pair_curly)
|
||||
elif tok == '(':
|
||||
self.paren += 1
|
||||
self.things.append(self.__pair_paren)
|
||||
elif tok == ')':
|
||||
self.paren -= 1
|
||||
assert(self.things.pop() == self.__pair_paren)
|
||||
elif tok == '<':
|
||||
self.ext += 1
|
||||
self.things.append(self.__pair_ext)
|
||||
elif tok == '>':
|
||||
self.ext -= 1
|
||||
assert(self.things.pop() == self.__pair_ext)
|
||||
elif tok == '?':
|
||||
if not self.in_special:
|
||||
self.in_special = True
|
||||
self.things.append(self.__pair_special)
|
||||
else:
|
||||
self.in_special = False
|
||||
assert(self.things.pop() == self.__pair_special)
|
||||
elif tok == '/*':
|
||||
self.in_c_comment = True
|
||||
self.things.append(self.__pair_c_comment)
|
||||
elif tok == '*/':
|
||||
raise Exception("Unmatched closing C-style comment mark", tok, "in line", line)
|
||||
else:
|
||||
if self.in_cpp_comment:
|
||||
if tok == '\n':
|
||||
self.in_cpp_comment = False
|
||||
return
|
||||
if tok == '/*':
|
||||
raise Exception("Nested C-style comment", tok, "in line", line)
|
||||
elif tok == '*/':
|
||||
assert(self.things.pop() == self.__pair_c_comment)
|
||||
self.in_c_comment = False
|
||||
|
||||
if self.curly < 0 or self.square < 0 or self.ext < 0 or self.paren < 0:
|
||||
raise Exception("Unbalanced BNF bracket", tok, "in line", line)
|
||||
return self.optional()
|
||||
|
||||
def in_list(self):
|
||||
return self.curly > 0
|
||||
|
||||
def in_option(self):
|
||||
return self.square > 0
|
||||
|
||||
def in_paren(self):
|
||||
return self.paren > 0
|
||||
|
||||
def in_ext(self):
|
||||
return self.ext > 0
|
||||
|
||||
def in_comment(self):
|
||||
return self.in_c_comment or self.in_cpp_comment
|
||||
|
||||
def in_something(self):
|
||||
if len(self.things) == 0:
|
||||
return None
|
||||
return self.things[-1]
|
||||
|
||||
def is_optional(self):
|
||||
return self.in_list() or self.in_option()
|
||||
|
||||
6
src/python/jw/util/Makefile
Normal file
6
src/python/jw/util/Makefile
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
TOPDIR = ../../../..
|
||||
|
||||
PY_UPDATE_INIT_PY ?= false
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
24
src/python/jw/util/Object.py
Normal file
24
src/python/jw/util/Object.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
from . import log
|
||||
|
||||
class Object(object): # export
|
||||
|
||||
def __init__(self):
|
||||
self.log_level = log.level
|
||||
|
||||
def log(self, prio, *args):
|
||||
if self.log_level == log.level:
|
||||
log.slog(prio, args)
|
||||
return
|
||||
if prio <= self.log_level:
|
||||
msg = ""
|
||||
for count, thing in enumerate(args):
|
||||
msg += ' ' + str(*thing)
|
||||
if len(msg):
|
||||
print(msg[1:])
|
||||
|
||||
def debug(self, *args):
|
||||
log.slog(log.DEBUG, args)
|
||||
168
src/python/jw/util/Options.py
Normal file
168
src/python/jw/util/Options.py
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import re
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
from .log import *
|
||||
import shlex
|
||||
import traceback
|
||||
|
||||
class Options: # export
|
||||
|
||||
class OrderedData:
|
||||
|
||||
def __init__(self, pairs = None):
|
||||
self.__pairs = [] if pairs is None else pairs
|
||||
|
||||
def add(self, lhs, rhs):
|
||||
self.__pairs.append((lhs, rhs))
|
||||
|
||||
def dump(self):
|
||||
for p in self.__pairs:
|
||||
print(p)
|
||||
|
||||
@property
|
||||
def pairs(self):
|
||||
return self.__pairs
|
||||
|
||||
def __parse_json(self, spec, cls):
|
||||
spec = spec.strip()
|
||||
if len(spec) < 3:
|
||||
return None
|
||||
if spec[0] != '{':
|
||||
spec = '{' + spec + '}'
|
||||
try:
|
||||
return json.loads(spec, object_pairs_hook=cls)
|
||||
except:
|
||||
pass
|
||||
return None
|
||||
|
||||
def __parse(self, opts_str, cls):
|
||||
r = self.__parse_json(opts_str, cls)
|
||||
if r is not None:
|
||||
return r
|
||||
r = cls()
|
||||
try:
|
||||
opt_strs = shlex.split(opts_str)
|
||||
except Exception as e:
|
||||
slog_m(ERR, traceback.format_exc())
|
||||
slog(ERR, 'Failed to split options string >{}<'.format(opts_str))
|
||||
raise
|
||||
for opt_str in opt_strs:
|
||||
opt_str = re.sub(r'\s*=\s*', '=', opt_str)
|
||||
sides = opt_str.split('=')
|
||||
lhs = sides[0].strip()
|
||||
if not len(lhs):
|
||||
continue
|
||||
if self.__allowed_keys and not lhs in self.__allowed_keys:
|
||||
raise Exception('Field "{}" not supported'.format(lhs))
|
||||
rhs = ' '.join(sides[1:]).strip() if len(sides) > 1 else self.__true_val
|
||||
if cls == OrderedDict:
|
||||
r[lhs] = rhs
|
||||
elif cls == self.OrderedData:
|
||||
r.add(lhs, rhs)
|
||||
return r
|
||||
|
||||
def __recache(self):
|
||||
self.__list.clear()
|
||||
self.__dict.clear()
|
||||
for key, val in self.__data.pairs:
|
||||
self.__list.append(key)
|
||||
if key not in self.__dict.keys():
|
||||
self.__dict[key] = val
|
||||
else:
|
||||
cur = self.__dict[key]
|
||||
if isinstance(cur, str):
|
||||
cur = [cur, val]
|
||||
elif isinstance(cur, set):
|
||||
cur.add(val)
|
||||
elif isinstance(cur, list):
|
||||
cur.append(val)
|
||||
else:
|
||||
cur = [cur, val]
|
||||
self.__dict[key] = cur
|
||||
self.__str = self.__str__()
|
||||
|
||||
def __getitem__(self, key):
|
||||
if not key in self.__dict.keys():
|
||||
return None
|
||||
return self.__dict[key]
|
||||
|
||||
def __str__(self):
|
||||
return ', '.join(str(p[0]) + ': ' + str(p[1]) for p in self.__data.pairs)
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
def __format__(self, fmt):
|
||||
return self.__str__()
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__data.pairs)
|
||||
|
||||
def __contains__(self, keys):
|
||||
if not type(keys) in [list, set]:
|
||||
return keys in self.__dict.keys()
|
||||
for key in keys:
|
||||
if not key in self.__dict.keys():
|
||||
return False
|
||||
return True
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.__list)
|
||||
|
||||
def __next__(self):
|
||||
return next(self.__list)
|
||||
|
||||
def __init__(self, spec=None, delimiter=',', allowed_keys=None, true_val=True):
|
||||
self.__true_val = true_val
|
||||
self.__allowed_keys = None
|
||||
self.__delimiter = delimiter
|
||||
self.__data = self.OrderedData() if spec is None else self.__parse(spec, self.OrderedData)
|
||||
self.__dict = {}
|
||||
#self.__dict = OrderedDict() if spec is None else self.__parse(spec, OrderedDict)
|
||||
self.__list = []
|
||||
self.__str = None
|
||||
self.__recache()
|
||||
|
||||
def dump(self, prio, caller=None):
|
||||
if caller is None:
|
||||
caller = get_caller_pos()
|
||||
for key, val in self.__data.pairs:
|
||||
slog(prio, "{}=\"{}\"".format(key, val), caller=caller)
|
||||
|
||||
def keys(self):
|
||||
return self.__dict.keys()
|
||||
|
||||
def items(self):
|
||||
#return self.__dict.items()
|
||||
return self.__data.pairs
|
||||
|
||||
def get(self, key, default=None, by_index=False):
|
||||
if by_index:
|
||||
if type(key) != int:
|
||||
raise KeyError('Tried to get value from options string with ' +
|
||||
'index {} of type "{}": {}'.format(key, type(key), str(self)))
|
||||
if key >= len(self.__data.pairs):
|
||||
if default is not None:
|
||||
return default
|
||||
raise KeyError('Tried to get value from options string with ' +
|
||||
'index {} of {}: {}'.format(key, len(self.__data.pairs), str(self)))
|
||||
return self.__list[key]
|
||||
if key in self.__dict.keys():
|
||||
return self.__dict[key]
|
||||
if default is not None:
|
||||
return default
|
||||
raise KeyError('Key "{}" is not present in options string: {}'.format(key, str(self)))
|
||||
|
||||
def update(self, rhs):
|
||||
if hasattr(rhs, 'items'):
|
||||
for key, val in rhs.items():
|
||||
self.__dict[key] = val
|
||||
return
|
||||
if isinstance(rhs, str):
|
||||
self.update(self.__parse(rhs))
|
||||
return
|
||||
raise Exception('Tried to update options with object of incompatible type {}'.format(type(rhs)))
|
||||
|
||||
def append_to(self, obj):
|
||||
for opt in self.__list:
|
||||
setattr(obj, opt[0], opt[1])
|
||||
72
src/python/jw/util/Process.py
Normal file
72
src/python/jw/util/Process.py
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
from abc import ABC, abstractmethod
|
||||
from enum import Enum, Flag, auto
|
||||
from typing import List
|
||||
|
||||
def _sigchld_handler(signum, process):
|
||||
if not signum == signal.SIGCHLD:
|
||||
return
|
||||
Process.propagate_signal(signum)
|
||||
|
||||
class Process(ABC): # export
|
||||
|
||||
__processes: List[Process] = []
|
||||
|
||||
class State(Enum):
|
||||
Running = auto()
|
||||
Shutdown = auto()
|
||||
Done = auto()
|
||||
|
||||
class Flags(Flag):
|
||||
FailOnExitWithoutShutdown = auto()
|
||||
|
||||
def __init__(self):
|
||||
self.__state = Running
|
||||
self.__flags = Flags.FailOnExitWithoutShutdown
|
||||
if len(self.__processes) == 0:
|
||||
self._signals().add_handler(signals.SIGCHLD, _sigchld_handler)
|
||||
self.__processes.add(self)
|
||||
|
||||
@classmethod
|
||||
def propagate_signal(cls, signum):
|
||||
for p in cls.__processes:
|
||||
p.__signal(signum)
|
||||
|
||||
def signal(self, signum):
|
||||
if signum == signals.SIGCHLD:
|
||||
self.exited()
|
||||
|
||||
@abstractmethod
|
||||
def _pid(self):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def signals(cls):
|
||||
pass
|
||||
|
||||
# to be reimplemented
|
||||
def _request_shutdown(self):
|
||||
pass
|
||||
|
||||
# to be reimplemented
|
||||
def name(self):
|
||||
return str(self._pid())
|
||||
|
||||
def request_shutdown(self):
|
||||
if not self.__state == Shutdown:
|
||||
self.__state = Shutdown
|
||||
self._request_shutdown()
|
||||
|
||||
def exited(self):
|
||||
if self.__state == Process.State.Running:
|
||||
slog(ERR, 'process "{}" exited unexpectedly'.format(process.name()))
|
||||
if __flags & Process.Flags.FailOnExitWithoutShutdown:
|
||||
slog(ERR, 'exiting')
|
||||
exit(1)
|
||||
self.__state = Process.State.Done
|
||||
self.__processes.erase(self)
|
||||
if len(self.__processes) == 0:
|
||||
self._signals().remove_handler(signals.SIGCHLD) # FIXME: broken logic
|
||||
41
src/python/jw/util/RedirectStdIO.py
Normal file
41
src/python/jw/util/RedirectStdIO.py
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import os, io, sys, traceback
|
||||
from fcntl import fcntl, F_GETFL, F_SETFL
|
||||
|
||||
class RedirectStdIO: # export
|
||||
|
||||
def __init__(self, stderr='on', stdout='off'):
|
||||
self.__stderr = stderr
|
||||
self.__stdout = stdout
|
||||
# TODO: arguments not fully implemented,
|
||||
# Add support for 'off', 'on', 'stdxxx' (redirection)
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
if self.__stdout == 'off':
|
||||
rfd, wfd = os.pipe()
|
||||
flags = fcntl(rfd, F_GETFL)
|
||||
fcntl(rfd, F_SETFL, flags | os.O_NONBLOCK)
|
||||
self.rfile = io.open(rfd, 'r')
|
||||
self.fake_stdout_stream = io.open(wfd, 'w')
|
||||
self.real_stdout_fd = os.dup(1)
|
||||
#os.close(1)
|
||||
os.dup2(wfd, 1)
|
||||
|
||||
def __exit__(self, type, value, traceback):
|
||||
if self.__stdout == 'off':
|
||||
sys.stdout.flush()
|
||||
os.dup2(self.real_stdout_fd, 1)
|
||||
if type is not None:
|
||||
#print("-------- Error while stdio was suppressed --------")
|
||||
#traceback.print_stack()
|
||||
#print(traceback)
|
||||
print("-------- Captured output --------")
|
||||
print(*self.rfile.readlines())
|
||||
self.rfile.close()
|
||||
#print('type = ' + str(type))
|
||||
#print('value = ' + str(value))
|
||||
raise type(value)
|
||||
37
src/python/jw/util/Signals.py
Normal file
37
src/python/jw/util/Signals.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Dict, Callable
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
_handled_signals: Dict[int, Callable] = {}
|
||||
|
||||
def _signal_handler(signal, frame):
|
||||
if not signal in _handled_signals.keys():
|
||||
return
|
||||
for h in _handled_signals[signal]:
|
||||
h.func(signal, *h.args)
|
||||
|
||||
class Signals:
|
||||
|
||||
class Handler:
|
||||
def __init__(self, func, args):
|
||||
self.func = func
|
||||
self.args = args
|
||||
|
||||
def __init(self):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def _add_handler(self, signal, handler):
|
||||
raise Exception("_add_handler() is not reimplemented")
|
||||
|
||||
@classmethod
|
||||
def add_handler(cls, signals, handler, *args):
|
||||
for signal in signals:
|
||||
h = Signals.Handler(handler, args)
|
||||
if not signal in _handled_signals.keys():
|
||||
_handled_signals[signal] = [h]
|
||||
cls._add_signal_handler(signal, _signal_handler)
|
||||
else:
|
||||
_handled_signals[signal].add(h)
|
||||
25
src/python/jw/util/StopWatch.py
Normal file
25
src/python/jw/util/StopWatch.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from .log import *
|
||||
|
||||
class StopWatch: # export
|
||||
|
||||
def __init__(self, name=''):
|
||||
self.__start = datetime.now()
|
||||
self.__last = self.__start
|
||||
self.name = name
|
||||
|
||||
def reset(self):
|
||||
self.__start = datetime.now()
|
||||
|
||||
def logDelta(self, prio, *args, **kwargs):
|
||||
now = datetime.now()
|
||||
if args is not None:
|
||||
msg = ' '.join(args)
|
||||
else:
|
||||
msg = '------------------ '
|
||||
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
|
||||
slog(prio, '{} {} {}'.format(self.name, str(now - self.__last), msg), caller=caller)
|
||||
self.__last = now
|
||||
3
src/python/jw/util/__init__.py
Normal file
3
src/python/jw/util/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
from pkgutil import extend_path
|
||||
|
||||
__path__ = extend_path(__path__, __name__)
|
||||
4
src/python/jw/util/algo/Makefile
Normal file
4
src/python/jw/util/algo/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
341
src/python/jw/util/algo/ShuntingYard.py
Normal file
341
src/python/jw/util/algo/ShuntingYard.py
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import re, shlex
|
||||
from collections import namedtuple
|
||||
|
||||
from ..log import *
|
||||
|
||||
L, R = 'Left Right'.split()
|
||||
ARG, KEYW, QUOTED, LPAREN, RPAREN = 'arg kw quoted ( )'.split()
|
||||
|
||||
class Operator: # export
|
||||
|
||||
def __init__(self, func=None, nargs=2, precedence=3, assoc=L):
|
||||
self.func = func
|
||||
self.nargs = nargs
|
||||
self.prec = precedence
|
||||
self.assoc = assoc
|
||||
|
||||
class Stack:
|
||||
|
||||
def __init__(self, itemlist=[]):
|
||||
self.items = itemlist
|
||||
|
||||
def __repr__(self):
|
||||
return str(self.items)
|
||||
|
||||
def isEmpty(self):
|
||||
if self.items == []:
|
||||
return True
|
||||
return False
|
||||
|
||||
def peek(self):
|
||||
return self.items[-1:][0]
|
||||
|
||||
def pop(self):
|
||||
return self.items.pop()
|
||||
|
||||
def push(self, item):
|
||||
self.items.append(item)
|
||||
return 0
|
||||
|
||||
class ShuntingYard(object): # export
|
||||
|
||||
def __init__(self, operators = None):
|
||||
self.do_debug = prio_gets_logged(DEBUG)
|
||||
self.__ops = {}
|
||||
if operators is not None:
|
||||
for k, v in operators.items():
|
||||
self.add_operator(k, v.func, v.nargs, v.prec, v.assoc)
|
||||
|
||||
def debug(self, *args):
|
||||
if self.do_debug:
|
||||
msg = ""
|
||||
for count, thing in enumerate(args):
|
||||
msg += ' ' + str(thing)
|
||||
if len(msg):
|
||||
slog(DEBUG, msg[1:], caller=get_caller_pos())
|
||||
|
||||
def operator(self, key: str) -> Operator:
|
||||
return self.__ops[key]
|
||||
|
||||
def token_string(self):
|
||||
r = ""
|
||||
for k in sorted(self.__ops):
|
||||
v = self.__ops[k]
|
||||
buf = ", \"" + k
|
||||
if v.nargs == 1:
|
||||
if k[len(k)-1].isalnum():
|
||||
buf = buf + ' '
|
||||
buf = buf + "xxx"
|
||||
buf = buf + "\""
|
||||
r = r + buf
|
||||
|
||||
if len(r):
|
||||
return r[2:]
|
||||
return r
|
||||
|
||||
def tokenize(self, spec):
|
||||
|
||||
regex = ""
|
||||
for k in self.__ops.keys():
|
||||
regex = regex + "|" + re.escape(k)
|
||||
|
||||
regex = regex[1:]
|
||||
|
||||
scanner = re.Scanner([
|
||||
(regex, lambda scanner,token:(KEYW, token)),
|
||||
(r"\"[^\"]*\"|'[^']*'", lambda scanner,token:(QUOTED, token[1:-1])),
|
||||
(r"[^\s()]+", lambda scanner,token:(ARG, token)),
|
||||
(r"\s+", None), # None == skip token.
|
||||
])
|
||||
|
||||
tokens, remainder = scanner.scan(spec)
|
||||
if len(remainder)>0:
|
||||
raise Exception("Failed to tokenize " + spec + ", remaining bit is ", remainder)
|
||||
|
||||
#self.debug(tokens)
|
||||
return tokens
|
||||
r = []
|
||||
for e in tokens:
|
||||
if e[0] == "quoted":
|
||||
r.append(e[1][1:-1])
|
||||
else:
|
||||
r.append(e[1])
|
||||
|
||||
return r
|
||||
|
||||
def add_operator(self, name, func, nargs, precedence, assoc):
|
||||
self.__ops[name] = Operator(func, nargs, precedence, assoc)
|
||||
|
||||
def infix_to_postfix(self, infix):
|
||||
tokenized = self.tokenize(infix)
|
||||
self.debug("tokenized = ", tokenized)
|
||||
outq, stack = [], []
|
||||
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
|
||||
for toktype, token in tokenized:
|
||||
self.debug("Checking token", token)
|
||||
note = action = ''
|
||||
if toktype in [ ARG, QUOTED ]:
|
||||
action = 'Add arg to output'
|
||||
outq.append(token)
|
||||
table.append( (token, action, outq, (s[0] for s in stack), note) )
|
||||
elif toktype == KEYW:
|
||||
val = self.__ops[token]
|
||||
t1, op1 = token, val
|
||||
v = t1
|
||||
note = 'Pop ops from stack to output'
|
||||
while stack:
|
||||
t2, op2 = stack[-1]
|
||||
if (op1.assoc == L and op1.prec <= op2.prec) or (op1.assoc == R and op1.prec < op2.prec):
|
||||
if t1 != RPAREN:
|
||||
if t2 != LPAREN:
|
||||
stack.pop()
|
||||
action = '(Pop op)'
|
||||
outq.append(t2)
|
||||
else:
|
||||
break
|
||||
else:
|
||||
if t2 != LPAREN:
|
||||
stack.pop()
|
||||
action = '(Pop op)'
|
||||
outq.append(t2)
|
||||
else:
|
||||
stack.pop()
|
||||
action = '(Pop & discard "(")'
|
||||
table.append( (v, action, outq, (s[0] for s in stack), note) )
|
||||
break
|
||||
table.append( (v, action, (outq), (s[0] for s in stack), note) )
|
||||
v = note = ''
|
||||
else:
|
||||
note = ''
|
||||
break
|
||||
note = ''
|
||||
note = ''
|
||||
if t1 != RPAREN:
|
||||
stack.append((token, val))
|
||||
action = 'Push op token to stack'
|
||||
else:
|
||||
action = 'Discard ")"'
|
||||
table.append( (v, action, (outq), (s[0] for s in stack), note) )
|
||||
note = 'Drain stack to output'
|
||||
while stack:
|
||||
v = ''
|
||||
t2, op2 = stack[-1]
|
||||
action = '(Pop op)'
|
||||
stack.pop()
|
||||
outq.append(t2)
|
||||
table.append( (v, action, outq, (s[0] for s in stack), note) )
|
||||
v = note = ''
|
||||
if self.do_debug:
|
||||
maxcolwidths = [len(max(x, key=len)) for x in [zip(*table)]]
|
||||
caller = get_caller_pos()
|
||||
row = table[0]
|
||||
slog(DEBUG, ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
|
||||
for row in table[1:]:
|
||||
slog(DEBUG, ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
|
||||
return table[-1][2]
|
||||
|
||||
def infix_to_postfix_orig(self, infix):
|
||||
|
||||
s = Stack()
|
||||
r = []
|
||||
tokens = self.tokenize(infix)
|
||||
|
||||
for tokinfo in tokens:
|
||||
|
||||
self.debug(tokinfo)
|
||||
toktype, token = tokinfo[0], tokinfo[1]
|
||||
|
||||
self.debug("Checking token ", token)
|
||||
|
||||
if token not in self.__ops.keys():
|
||||
r.append(token)
|
||||
continue
|
||||
|
||||
if token == '(':
|
||||
s.push(token)
|
||||
continue
|
||||
|
||||
if token == ')':
|
||||
topToken = s.pop()
|
||||
while topToken != '(':
|
||||
r.append(topToken)
|
||||
topToken = s.pop()
|
||||
continue
|
||||
|
||||
while (not s.isEmpty()) and (self.__ops[s.peek()].prec >= self.__ops[token].prec):
|
||||
#self.debug(token)
|
||||
r.append(s.pop())
|
||||
#self.debug(r)
|
||||
|
||||
s.push(token)
|
||||
self.debug((s.peek()))
|
||||
|
||||
while not s.isEmpty():
|
||||
opToken = s.pop()
|
||||
r.append(opToken)
|
||||
#self.debug(r)
|
||||
|
||||
return r
|
||||
#return " ".join(r)
|
||||
|
||||
def eval_postfix(self, postfixexpr):
|
||||
|
||||
self.debug("postfix = ", postfixexpr)
|
||||
vals = Stack()
|
||||
|
||||
for token in postfixexpr:
|
||||
|
||||
self.debug("Evaluating token %s" % (token))
|
||||
if token not in self.__ops.keys():
|
||||
vals.push(token)
|
||||
continue
|
||||
|
||||
op = self.__ops[token]
|
||||
args = []
|
||||
self.debug(f'Adding {op.nargs} arguments: {vals}')
|
||||
for i in range(0, op.nargs):
|
||||
self.debug("Adding argument %d" % (i))
|
||||
args.append(vals.pop())
|
||||
#self.debug("running %s(%s)" % (token, ', '.join(reversed(args))))
|
||||
val = op.func(*reversed(args))
|
||||
self.debug("%s(%s) = %s" % (token, ', '.join(map(str, reversed(args))), val))
|
||||
vals.push(val)
|
||||
|
||||
return vals.pop()
|
||||
|
||||
def eval(self, infix):
|
||||
if not isinstance(infix, str):
|
||||
return infix
|
||||
postfix = self.infix_to_postfix(infix)
|
||||
self.debug(f'"{infix}" --> {postfix}')
|
||||
for token in postfix:
|
||||
self.debug("Token is %s" % (token))
|
||||
return self.eval_postfix(postfix)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
# ------------- testbed calculator
|
||||
|
||||
from locale import atof
|
||||
|
||||
class Calculator(ShuntingYard):
|
||||
|
||||
#def tokenize(self, string):
|
||||
# return string.split()
|
||||
|
||||
def f_mult(self, a, b):
|
||||
return str(atof(a) * atof(b));
|
||||
|
||||
def f_div(self, a, b):
|
||||
return str(atof(a) / atof(b));
|
||||
|
||||
def f_add(self, a, b):
|
||||
return str(atof(a) + atof(b));
|
||||
|
||||
def f_sub(self, a, b):
|
||||
return str(atof(a) - atof(b));
|
||||
|
||||
def __init__(self):
|
||||
Op = Operator
|
||||
operators = {
|
||||
'^': Op(None, 2, 4, R),
|
||||
'*': Op(self.f_mult, 2, 3, L),
|
||||
'/': Op(self.f_div, 2, 3, L),
|
||||
'+': Op(self.f_add, 2, 2, L),
|
||||
'-': Op(self.f_sub, 2, 2, L),
|
||||
'(': Op(None, 0, 9, L),
|
||||
')': Op(None, 0, 0, L),
|
||||
}
|
||||
super(Calculator, self).__init__(operators)
|
||||
|
||||
rr = Calculator().eval("( 2 * 3 + 4 * 5 ) / ( 5 - 3 )")
|
||||
print("Result =", rr)
|
||||
|
||||
# ------------- testbed match object
|
||||
|
||||
Object = namedtuple("Object", [ "Name", "Label" ])
|
||||
|
||||
class Matcher(ShuntingYard):
|
||||
|
||||
def f_is_name(self, a):
|
||||
if obj.Name == a:
|
||||
return "True"
|
||||
return "False"
|
||||
|
||||
def f_matches_label(self, a):
|
||||
if re.match(a, obj.Label):
|
||||
return "True"
|
||||
return "False"
|
||||
|
||||
def f_is_not(self, a):
|
||||
if a == "True":
|
||||
return "False"
|
||||
return "True"
|
||||
|
||||
def f_and(self, a_, b_):
|
||||
a = a_ == "True"
|
||||
b = b_ == "True"
|
||||
if a and b:
|
||||
return "True"
|
||||
return "False"
|
||||
|
||||
def __init__(self, obj):
|
||||
Op = Operator
|
||||
operators = {
|
||||
'(': Op(None, 2, 9, L),
|
||||
')': Op(None, 2, 0, L),
|
||||
'name=': Op(self.f_is_name, 1, 3, R),
|
||||
'and': Op(self.f_and, 2, 3, L),
|
||||
'label~=': Op(self.f_matches_label, 1, 3, R),
|
||||
'False': Op(None, 0, 3, L),
|
||||
'True': Op(None, 0, 3, L),
|
||||
'not': Op(self.f_is_not, 1, 3, R),
|
||||
}
|
||||
super(Matcher, self).__init__(operators)
|
||||
|
||||
obj = Object("hans", "wurst")
|
||||
|
||||
r = Matcher(obj).eval("name=hans and (not label~=worst)")
|
||||
print("Result =", r)
|
||||
4
src/python/jw/util/asyncio/Makefile
Normal file
4
src/python/jw/util/asyncio/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue