partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
create_app
App Factory 工具 策略是: - 初始化app - 根据app_name,装载指定的模块 - 尝试装载app.run_app - 如果指定了`FANTASY_PRIMARY_NODE`,则尝试进行migrate操作 - 装载error handler :return:
fantasy/__init__.py
def create_app(app_name, config={}, db=None, celery=None): """ App Factory 工具 策略是: - 初始化app - 根据app_name,装载指定的模块 - 尝试装载app.run_app - 如果指定了`FANTASY_PRIMARY_NODE`,则尝试进行migrate操作 - 装载error handler :return: """ track_mode = os.environ['FANTASY_TRACK_MODE'] == 'yes' if track_mode: print('(00/14)fantasy track mode active...') active_db = os.environ['FANTASY_ACTIVE_DB'] == 'yes' if track_mode: print('(01/14)hacking webargs...') from webargs.flaskparser import parser from . import error_handler, hacker, cli hacker.hack_webargs() migrations_root = os.path.join( os.environ.get('FANTASY_MIGRATION_PATH', os.getcwd()), 'migrations') if track_mode: print('(02/14)initial app...') mod = importlib.import_module(app_name) app = FantasyFlask(__name__, root_path=os.path.dirname(mod.__file__)) if track_mode: print('(03/14)update app.config...') if config: app.config.update(config) # 由外部做显式声明,否则不做调用 config_module = os.environ.get('FANTASY_SETTINGS_MODULE', None) if track_mode: print(" found config module %s,try load it..." % config_module) if config_module: app.config.from_object(config_module) if track_mode: print('(04/14)confirm celery...') if celery: app.celery = celery pass if track_mode: print('(05/14)bind app context...') with app.app_context(): if track_mode: print('(06/14)confirm db handle...') if db is None: global _db app.db = _db else: app.db = db if track_mode: print('(07/14)confirm cache...') if os.environ['FANTASY_ACTIVE_CACHE'] != 'no': from flask_caching import Cache app.cache = Cache(app, config=app.config) pass if track_mode: print('(08/14)confirm sentry...') if os.environ.get('FANTASY_ACTIVE_SENTRY') != 'no': from raven.contrib.flask import Sentry Sentry(app) pass if track_mode: print('(09/14)active app...') if hasattr(mod, 'run_app'): run_app = getattr(mod, 'run_app') try: run_app(app) except Exception as e: if hasattr(app, 'sentry'): app.sentry.handle_exception(e) pass import sys import traceback traceback.print_exc() sys.exit(-1) pass if active_db and app.db: if track_mode: print('(10/14)trigger auto migrate...') smart_database(app) smart_migrate(app, migrations_root) smart_account(app) app.db.init_app(app) @app.teardown_request def session_clear(exception=None): if exception and app.db.session.is_active: app.db.session.rollback() app.db.session.remove() pass if track_mode: print('(11/14)bind error handle...') # 添加错误控制 @parser.error_handler def h_webargs(error): return error_handler.webargs_error(error) @app.errorhandler(422) def h_422(error): return error_handler.http422(error) @app.errorhandler(500) def h_500(error): return error_handler.http500(error) if hasattr(mod, 'error_handler'): error_handle = getattr(mod, 'error_handle') error_handle(app) pass if track_mode: print('(12/14)bind admin handle...') if hasattr(mod, 'run_admin'): import flask_admin admin = flask_admin.Admin(name=os.environ.get('FANTASY_ADMIN_NAME', 'Admin'), template_mode=os.environ.get( 'FANTASY_ADMIN_TEMPLATE_MODE', 'bootstrap3')) run_admin = getattr(mod, 'run_admin') run_admin(admin) admin.init_app(app) pass pass if track_mode: print('(13/14)bind ff command...') app.cli.add_command(cli.ff) if track_mode: print('(14/14)bind cli command...') if hasattr(mod, 'run_cli'): run_cli = getattr(mod, 'run_cli') run_cli(app) pass return app
def create_app(app_name, config={}, db=None, celery=None): """ App Factory 工具 策略是: - 初始化app - 根据app_name,装载指定的模块 - 尝试装载app.run_app - 如果指定了`FANTASY_PRIMARY_NODE`,则尝试进行migrate操作 - 装载error handler :return: """ track_mode = os.environ['FANTASY_TRACK_MODE'] == 'yes' if track_mode: print('(00/14)fantasy track mode active...') active_db = os.environ['FANTASY_ACTIVE_DB'] == 'yes' if track_mode: print('(01/14)hacking webargs...') from webargs.flaskparser import parser from . import error_handler, hacker, cli hacker.hack_webargs() migrations_root = os.path.join( os.environ.get('FANTASY_MIGRATION_PATH', os.getcwd()), 'migrations') if track_mode: print('(02/14)initial app...') mod = importlib.import_module(app_name) app = FantasyFlask(__name__, root_path=os.path.dirname(mod.__file__)) if track_mode: print('(03/14)update app.config...') if config: app.config.update(config) # 由外部做显式声明,否则不做调用 config_module = os.environ.get('FANTASY_SETTINGS_MODULE', None) if track_mode: print(" found config module %s,try load it..." % config_module) if config_module: app.config.from_object(config_module) if track_mode: print('(04/14)confirm celery...') if celery: app.celery = celery pass if track_mode: print('(05/14)bind app context...') with app.app_context(): if track_mode: print('(06/14)confirm db handle...') if db is None: global _db app.db = _db else: app.db = db if track_mode: print('(07/14)confirm cache...') if os.environ['FANTASY_ACTIVE_CACHE'] != 'no': from flask_caching import Cache app.cache = Cache(app, config=app.config) pass if track_mode: print('(08/14)confirm sentry...') if os.environ.get('FANTASY_ACTIVE_SENTRY') != 'no': from raven.contrib.flask import Sentry Sentry(app) pass if track_mode: print('(09/14)active app...') if hasattr(mod, 'run_app'): run_app = getattr(mod, 'run_app') try: run_app(app) except Exception as e: if hasattr(app, 'sentry'): app.sentry.handle_exception(e) pass import sys import traceback traceback.print_exc() sys.exit(-1) pass if active_db and app.db: if track_mode: print('(10/14)trigger auto migrate...') smart_database(app) smart_migrate(app, migrations_root) smart_account(app) app.db.init_app(app) @app.teardown_request def session_clear(exception=None): if exception and app.db.session.is_active: app.db.session.rollback() app.db.session.remove() pass if track_mode: print('(11/14)bind error handle...') # 添加错误控制 @parser.error_handler def h_webargs(error): return error_handler.webargs_error(error) @app.errorhandler(422) def h_422(error): return error_handler.http422(error) @app.errorhandler(500) def h_500(error): return error_handler.http500(error) if hasattr(mod, 'error_handler'): error_handle = getattr(mod, 'error_handle') error_handle(app) pass if track_mode: print('(12/14)bind admin handle...') if hasattr(mod, 'run_admin'): import flask_admin admin = flask_admin.Admin(name=os.environ.get('FANTASY_ADMIN_NAME', 'Admin'), template_mode=os.environ.get( 'FANTASY_ADMIN_TEMPLATE_MODE', 'bootstrap3')) run_admin = getattr(mod, 'run_admin') run_admin(admin) admin.init_app(app) pass pass if track_mode: print('(13/14)bind ff command...') app.cli.add_command(cli.ff) if track_mode: print('(14/14)bind cli command...') if hasattr(mod, 'run_cli'): run_cli = getattr(mod, 'run_cli') run_cli(app) pass return app
[ "App", "Factory", "工具" ]
wangwenpei/fantasy
python
https://github.com/wangwenpei/fantasy/blob/0fe92059bd868f14da84235beb05b217b1d46e4a/fantasy/__init__.py#L183-L362
[ "def", "create_app", "(", "app_name", ",", "config", "=", "{", "}", ",", "db", "=", "None", ",", "celery", "=", "None", ")", ":", "track_mode", "=", "os", ".", "environ", "[", "'FANTASY_TRACK_MODE'", "]", "==", "'yes'", "if", "track_mode", ":", "print", "(", "'(00/14)fantasy track mode active...'", ")", "active_db", "=", "os", ".", "environ", "[", "'FANTASY_ACTIVE_DB'", "]", "==", "'yes'", "if", "track_mode", ":", "print", "(", "'(01/14)hacking webargs...'", ")", "from", "webargs", ".", "flaskparser", "import", "parser", "from", ".", "import", "error_handler", ",", "hacker", ",", "cli", "hacker", ".", "hack_webargs", "(", ")", "migrations_root", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", ".", "get", "(", "'FANTASY_MIGRATION_PATH'", ",", "os", ".", "getcwd", "(", ")", ")", ",", "'migrations'", ")", "if", "track_mode", ":", "print", "(", "'(02/14)initial app...'", ")", "mod", "=", "importlib", ".", "import_module", "(", "app_name", ")", "app", "=", "FantasyFlask", "(", "__name__", ",", "root_path", "=", "os", ".", "path", ".", "dirname", "(", "mod", ".", "__file__", ")", ")", "if", "track_mode", ":", "print", "(", "'(03/14)update app.config...'", ")", "if", "config", ":", "app", ".", "config", ".", "update", "(", "config", ")", "# 由外部做显式声明,否则不做调用", "config_module", "=", "os", ".", "environ", ".", "get", "(", "'FANTASY_SETTINGS_MODULE'", ",", "None", ")", "if", "track_mode", ":", "print", "(", "\" found config module %s,try load it...\"", "%", "config_module", ")", "if", "config_module", ":", "app", ".", "config", ".", "from_object", "(", "config_module", ")", "if", "track_mode", ":", "print", "(", "'(04/14)confirm celery...'", ")", "if", "celery", ":", "app", ".", "celery", "=", "celery", "pass", "if", "track_mode", ":", "print", "(", "'(05/14)bind app context...'", ")", "with", "app", ".", "app_context", "(", ")", ":", "if", "track_mode", ":", "print", "(", "'(06/14)confirm db handle...'", ")", "if", "db", "is", "None", ":", "global", "_db", "app", ".", "db", "=", "_db", "else", ":", "app", ".", "db", "=", "db", "if", "track_mode", ":", "print", "(", "'(07/14)confirm cache...'", ")", "if", "os", ".", "environ", "[", "'FANTASY_ACTIVE_CACHE'", "]", "!=", "'no'", ":", "from", "flask_caching", "import", "Cache", "app", ".", "cache", "=", "Cache", "(", "app", ",", "config", "=", "app", ".", "config", ")", "pass", "if", "track_mode", ":", "print", "(", "'(08/14)confirm sentry...'", ")", "if", "os", ".", "environ", ".", "get", "(", "'FANTASY_ACTIVE_SENTRY'", ")", "!=", "'no'", ":", "from", "raven", ".", "contrib", ".", "flask", "import", "Sentry", "Sentry", "(", "app", ")", "pass", "if", "track_mode", ":", "print", "(", "'(09/14)active app...'", ")", "if", "hasattr", "(", "mod", ",", "'run_app'", ")", ":", "run_app", "=", "getattr", "(", "mod", ",", "'run_app'", ")", "try", ":", "run_app", "(", "app", ")", "except", "Exception", "as", "e", ":", "if", "hasattr", "(", "app", ",", "'sentry'", ")", ":", "app", ".", "sentry", ".", "handle_exception", "(", "e", ")", "pass", "import", "sys", "import", "traceback", "traceback", ".", "print_exc", "(", ")", "sys", ".", "exit", "(", "-", "1", ")", "pass", "if", "active_db", "and", "app", ".", "db", ":", "if", "track_mode", ":", "print", "(", "'(10/14)trigger auto migrate...'", ")", "smart_database", "(", "app", ")", "smart_migrate", "(", "app", ",", "migrations_root", ")", "smart_account", "(", "app", ")", "app", ".", "db", ".", "init_app", "(", "app", ")", "@", "app", ".", "teardown_request", "def", "session_clear", "(", "exception", "=", "None", ")", ":", "if", "exception", "and", "app", ".", "db", ".", "session", ".", "is_active", ":", "app", ".", "db", ".", "session", ".", "rollback", "(", ")", "app", ".", "db", ".", "session", ".", "remove", "(", ")", "pass", "if", "track_mode", ":", "print", "(", "'(11/14)bind error handle...'", ")", "# 添加错误控制", "@", "parser", ".", "error_handler", "def", "h_webargs", "(", "error", ")", ":", "return", "error_handler", ".", "webargs_error", "(", "error", ")", "@", "app", ".", "errorhandler", "(", "422", ")", "def", "h_422", "(", "error", ")", ":", "return", "error_handler", ".", "http422", "(", "error", ")", "@", "app", ".", "errorhandler", "(", "500", ")", "def", "h_500", "(", "error", ")", ":", "return", "error_handler", ".", "http500", "(", "error", ")", "if", "hasattr", "(", "mod", ",", "'error_handler'", ")", ":", "error_handle", "=", "getattr", "(", "mod", ",", "'error_handle'", ")", "error_handle", "(", "app", ")", "pass", "if", "track_mode", ":", "print", "(", "'(12/14)bind admin handle...'", ")", "if", "hasattr", "(", "mod", ",", "'run_admin'", ")", ":", "import", "flask_admin", "admin", "=", "flask_admin", ".", "Admin", "(", "name", "=", "os", ".", "environ", ".", "get", "(", "'FANTASY_ADMIN_NAME'", ",", "'Admin'", ")", ",", "template_mode", "=", "os", ".", "environ", ".", "get", "(", "'FANTASY_ADMIN_TEMPLATE_MODE'", ",", "'bootstrap3'", ")", ")", "run_admin", "=", "getattr", "(", "mod", ",", "'run_admin'", ")", "run_admin", "(", "admin", ")", "admin", ".", "init_app", "(", "app", ")", "pass", "pass", "if", "track_mode", ":", "print", "(", "'(13/14)bind ff command...'", ")", "app", ".", "cli", ".", "add_command", "(", "cli", ".", "ff", ")", "if", "track_mode", ":", "print", "(", "'(14/14)bind cli command...'", ")", "if", "hasattr", "(", "mod", ",", "'run_cli'", ")", ":", "run_cli", "=", "getattr", "(", "mod", ",", "'run_cli'", ")", "run_cli", "(", "app", ")", "pass", "return", "app" ]
0fe92059bd868f14da84235beb05b217b1d46e4a
test
get_config
Conveniently get the security configuration for the specified application without the annoying 'SECURITY_' prefix. :param app: The application to inspect
fantasy/utils.py
def get_config(app, prefix='hive_'): """Conveniently get the security configuration for the specified application without the annoying 'SECURITY_' prefix. :param app: The application to inspect """ items = app.config.items() prefix = prefix.upper() def strip_prefix(tup): return (tup[0].replace(prefix, ''), tup[1]) return dict([strip_prefix(i) for i in items if i[0].startswith(prefix)])
def get_config(app, prefix='hive_'): """Conveniently get the security configuration for the specified application without the annoying 'SECURITY_' prefix. :param app: The application to inspect """ items = app.config.items() prefix = prefix.upper() def strip_prefix(tup): return (tup[0].replace(prefix, ''), tup[1]) return dict([strip_prefix(i) for i in items if i[0].startswith(prefix)])
[ "Conveniently", "get", "the", "security", "configuration", "for", "the", "specified", "application", "without", "the", "annoying", "SECURITY_", "prefix", "." ]
wangwenpei/fantasy
python
https://github.com/wangwenpei/fantasy/blob/0fe92059bd868f14da84235beb05b217b1d46e4a/fantasy/utils.py#L14-L26
[ "def", "get_config", "(", "app", ",", "prefix", "=", "'hive_'", ")", ":", "items", "=", "app", ".", "config", ".", "items", "(", ")", "prefix", "=", "prefix", ".", "upper", "(", ")", "def", "strip_prefix", "(", "tup", ")", ":", "return", "(", "tup", "[", "0", "]", ".", "replace", "(", "prefix", ",", "''", ")", ",", "tup", "[", "1", "]", ")", "return", "dict", "(", "[", "strip_prefix", "(", "i", ")", "for", "i", "in", "items", "if", "i", "[", "0", "]", ".", "startswith", "(", "prefix", ")", "]", ")" ]
0fe92059bd868f14da84235beb05b217b1d46e4a
test
config_value
Get a Flask-Security configuration value. :param key: The configuration key without the prefix `SECURITY_` :param app: An optional specific application to inspect. Defaults to Flask's `current_app` :param default: An optional default value if the value is not set
fantasy/utils.py
def config_value(key, app=None, default=None, prefix='hive_'): """Get a Flask-Security configuration value. :param key: The configuration key without the prefix `SECURITY_` :param app: An optional specific application to inspect. Defaults to Flask's `current_app` :param default: An optional default value if the value is not set """ app = app or current_app return get_config(app, prefix=prefix).get(key.upper(), default)
def config_value(key, app=None, default=None, prefix='hive_'): """Get a Flask-Security configuration value. :param key: The configuration key without the prefix `SECURITY_` :param app: An optional specific application to inspect. Defaults to Flask's `current_app` :param default: An optional default value if the value is not set """ app = app or current_app return get_config(app, prefix=prefix).get(key.upper(), default)
[ "Get", "a", "Flask", "-", "Security", "configuration", "value", "." ]
wangwenpei/fantasy
python
https://github.com/wangwenpei/fantasy/blob/0fe92059bd868f14da84235beb05b217b1d46e4a/fantasy/utils.py#L29-L38
[ "def", "config_value", "(", "key", ",", "app", "=", "None", ",", "default", "=", "None", ",", "prefix", "=", "'hive_'", ")", ":", "app", "=", "app", "or", "current_app", "return", "get_config", "(", "app", ",", "prefix", "=", "prefix", ")", ".", "get", "(", "key", ".", "upper", "(", ")", ",", "default", ")" ]
0fe92059bd868f14da84235beb05b217b1d46e4a
test
random_str
生成随机字符串 :return:
fantasy/random.py
def random_str(length=16, only_digits=False): """ 生成随机字符串 :return: """ choices = string.digits if not only_digits: choices += string.ascii_uppercase return ''.join(random.SystemRandom().choice(choices) for _ in range(length))
def random_str(length=16, only_digits=False): """ 生成随机字符串 :return: """ choices = string.digits if not only_digits: choices += string.ascii_uppercase return ''.join(random.SystemRandom().choice(choices) for _ in range(length))
[ "生成随机字符串", ":", "return", ":" ]
wangwenpei/fantasy
python
https://github.com/wangwenpei/fantasy/blob/0fe92059bd868f14da84235beb05b217b1d46e4a/fantasy/random.py#L11-L22
[ "def", "random_str", "(", "length", "=", "16", ",", "only_digits", "=", "False", ")", ":", "choices", "=", "string", ".", "digits", "if", "not", "only_digits", ":", "choices", "+=", "string", ".", "ascii_uppercase", "return", "''", ".", "join", "(", "random", ".", "SystemRandom", "(", ")", ".", "choice", "(", "choices", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
0fe92059bd868f14da84235beb05b217b1d46e4a
test
vector
Creates a new vector.
src/basilisp/lang/vector.py
def vector(members: Iterable[T], meta: Optional[IPersistentMap] = None) -> Vector[T]: """Creates a new vector.""" return Vector(pvector(members), meta=meta)
def vector(members: Iterable[T], meta: Optional[IPersistentMap] = None) -> Vector[T]: """Creates a new vector.""" return Vector(pvector(members), meta=meta)
[ "Creates", "a", "new", "vector", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/vector.py#L98-L100
[ "def", "vector", "(", "members", ":", "Iterable", "[", "T", "]", ",", "meta", ":", "Optional", "[", "IPersistentMap", "]", "=", "None", ")", "->", "Vector", "[", "T", "]", ":", "return", "Vector", "(", "pvector", "(", "members", ")", ",", "meta", "=", "meta", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
v
Creates a new vector from members.
src/basilisp/lang/vector.py
def v(*members: T, meta: Optional[IPersistentMap] = None) -> Vector[T]: """Creates a new vector from members.""" return Vector(pvector(members), meta=meta)
def v(*members: T, meta: Optional[IPersistentMap] = None) -> Vector[T]: """Creates a new vector from members.""" return Vector(pvector(members), meta=meta)
[ "Creates", "a", "new", "vector", "from", "members", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/vector.py#L103-L105
[ "def", "v", "(", "*", "members", ":", "T", ",", "meta", ":", "Optional", "[", "IPersistentMap", "]", "=", "None", ")", "->", "Vector", "[", "T", "]", ":", "return", "Vector", "(", "pvector", "(", "members", ")", ",", "meta", "=", "meta", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
eval_file
Evaluate a file with the given name into a Python module AST node.
src/basilisp/cli.py
def eval_file(filename: str, ctx: compiler.CompilerContext, module: types.ModuleType): """Evaluate a file with the given name into a Python module AST node.""" last = None for form in reader.read_file(filename, resolver=runtime.resolve_alias): last = compiler.compile_and_exec_form(form, ctx, module) return last
def eval_file(filename: str, ctx: compiler.CompilerContext, module: types.ModuleType): """Evaluate a file with the given name into a Python module AST node.""" last = None for form in reader.read_file(filename, resolver=runtime.resolve_alias): last = compiler.compile_and_exec_form(form, ctx, module) return last
[ "Evaluate", "a", "file", "with", "the", "given", "name", "into", "a", "Python", "module", "AST", "node", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/cli.py#L55-L60
[ "def", "eval_file", "(", "filename", ":", "str", ",", "ctx", ":", "compiler", ".", "CompilerContext", ",", "module", ":", "types", ".", "ModuleType", ")", ":", "last", "=", "None", "for", "form", "in", "reader", ".", "read_file", "(", "filename", ",", "resolver", "=", "runtime", ".", "resolve_alias", ")", ":", "last", "=", "compiler", ".", "compile_and_exec_form", "(", "form", ",", "ctx", ",", "module", ")", "return", "last" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
eval_stream
Evaluate the forms in stdin into a Python module AST node.
src/basilisp/cli.py
def eval_stream(stream, ctx: compiler.CompilerContext, module: types.ModuleType): """Evaluate the forms in stdin into a Python module AST node.""" last = None for form in reader.read(stream, resolver=runtime.resolve_alias): last = compiler.compile_and_exec_form(form, ctx, module) return last
def eval_stream(stream, ctx: compiler.CompilerContext, module: types.ModuleType): """Evaluate the forms in stdin into a Python module AST node.""" last = None for form in reader.read(stream, resolver=runtime.resolve_alias): last = compiler.compile_and_exec_form(form, ctx, module) return last
[ "Evaluate", "the", "forms", "in", "stdin", "into", "a", "Python", "module", "AST", "node", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/cli.py#L63-L68
[ "def", "eval_stream", "(", "stream", ",", "ctx", ":", "compiler", ".", "CompilerContext", ",", "module", ":", "types", ".", "ModuleType", ")", ":", "last", "=", "None", "for", "form", "in", "reader", ".", "read", "(", "stream", ",", "resolver", "=", "runtime", ".", "resolve_alias", ")", ":", "last", "=", "compiler", ".", "compile_and_exec_form", "(", "form", ",", "ctx", ",", "module", ")", "return", "last" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
eval_str
Evaluate the forms in a string into a Python module AST node.
src/basilisp/cli.py
def eval_str(s: str, ctx: compiler.CompilerContext, module: types.ModuleType, eof: Any): """Evaluate the forms in a string into a Python module AST node.""" last = eof for form in reader.read_str(s, resolver=runtime.resolve_alias, eof=eof): last = compiler.compile_and_exec_form(form, ctx, module) return last
def eval_str(s: str, ctx: compiler.CompilerContext, module: types.ModuleType, eof: Any): """Evaluate the forms in a string into a Python module AST node.""" last = eof for form in reader.read_str(s, resolver=runtime.resolve_alias, eof=eof): last = compiler.compile_and_exec_form(form, ctx, module) return last
[ "Evaluate", "the", "forms", "in", "a", "string", "into", "a", "Python", "module", "AST", "node", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/cli.py#L71-L76
[ "def", "eval_str", "(", "s", ":", "str", ",", "ctx", ":", "compiler", ".", "CompilerContext", ",", "module", ":", "types", ".", "ModuleType", ",", "eof", ":", "Any", ")", ":", "last", "=", "eof", "for", "form", "in", "reader", ".", "read_str", "(", "s", ",", "resolver", "=", "runtime", ".", "resolve_alias", ",", "eof", "=", "eof", ")", ":", "last", "=", "compiler", ".", "compile_and_exec_form", "(", "form", ",", "ctx", ",", "module", ")", "return", "last" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
bootstrap_repl
Bootstrap the REPL with a few useful vars and returned the bootstrapped module so it's functions can be used by the REPL command.
src/basilisp/cli.py
def bootstrap_repl(which_ns: str) -> types.ModuleType: """Bootstrap the REPL with a few useful vars and returned the bootstrapped module so it's functions can be used by the REPL command.""" repl_ns = runtime.Namespace.get_or_create(sym.symbol("basilisp.repl")) ns = runtime.Namespace.get_or_create(sym.symbol(which_ns)) repl_module = importlib.import_module("basilisp.repl") ns.add_alias(sym.symbol("basilisp.repl"), repl_ns) ns.refer_all(repl_ns) return repl_module
def bootstrap_repl(which_ns: str) -> types.ModuleType: """Bootstrap the REPL with a few useful vars and returned the bootstrapped module so it's functions can be used by the REPL command.""" repl_ns = runtime.Namespace.get_or_create(sym.symbol("basilisp.repl")) ns = runtime.Namespace.get_or_create(sym.symbol(which_ns)) repl_module = importlib.import_module("basilisp.repl") ns.add_alias(sym.symbol("basilisp.repl"), repl_ns) ns.refer_all(repl_ns) return repl_module
[ "Bootstrap", "the", "REPL", "with", "a", "few", "useful", "vars", "and", "returned", "the", "bootstrapped", "module", "so", "it", "s", "functions", "can", "be", "used", "by", "the", "REPL", "command", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/cli.py#L79-L88
[ "def", "bootstrap_repl", "(", "which_ns", ":", "str", ")", "->", "types", ".", "ModuleType", ":", "repl_ns", "=", "runtime", ".", "Namespace", ".", "get_or_create", "(", "sym", ".", "symbol", "(", "\"basilisp.repl\"", ")", ")", "ns", "=", "runtime", ".", "Namespace", ".", "get_or_create", "(", "sym", ".", "symbol", "(", "which_ns", ")", ")", "repl_module", "=", "importlib", ".", "import_module", "(", "\"basilisp.repl\"", ")", "ns", ".", "add_alias", "(", "sym", ".", "symbol", "(", "\"basilisp.repl\"", ")", ",", "repl_ns", ")", "ns", ".", "refer_all", "(", "repl_ns", ")", "return", "repl_module" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
run
Run a Basilisp script or a line of code, if it is provided.
src/basilisp/cli.py
def run( # pylint: disable=too-many-arguments file_or_code, code, in_ns, use_var_indirection, warn_on_shadowed_name, warn_on_shadowed_var, warn_on_var_indirection, ): """Run a Basilisp script or a line of code, if it is provided.""" basilisp.init() ctx = compiler.CompilerContext( filename=CLI_INPUT_FILE_PATH if code else ( STDIN_INPUT_FILE_PATH if file_or_code == STDIN_FILE_NAME else file_or_code ), opts={ compiler.WARN_ON_SHADOWED_NAME: warn_on_shadowed_name, compiler.WARN_ON_SHADOWED_VAR: warn_on_shadowed_var, compiler.USE_VAR_INDIRECTION: use_var_indirection, compiler.WARN_ON_VAR_INDIRECTION: warn_on_var_indirection, }, ) eof = object() with runtime.ns_bindings(in_ns) as ns: if code: print(runtime.lrepr(eval_str(file_or_code, ctx, ns.module, eof))) elif file_or_code == STDIN_FILE_NAME: print( runtime.lrepr( eval_stream(click.get_text_stream("stdin"), ctx, ns.module) ) ) else: print(runtime.lrepr(eval_file(file_or_code, ctx, ns.module)))
def run( # pylint: disable=too-many-arguments file_or_code, code, in_ns, use_var_indirection, warn_on_shadowed_name, warn_on_shadowed_var, warn_on_var_indirection, ): """Run a Basilisp script or a line of code, if it is provided.""" basilisp.init() ctx = compiler.CompilerContext( filename=CLI_INPUT_FILE_PATH if code else ( STDIN_INPUT_FILE_PATH if file_or_code == STDIN_FILE_NAME else file_or_code ), opts={ compiler.WARN_ON_SHADOWED_NAME: warn_on_shadowed_name, compiler.WARN_ON_SHADOWED_VAR: warn_on_shadowed_var, compiler.USE_VAR_INDIRECTION: use_var_indirection, compiler.WARN_ON_VAR_INDIRECTION: warn_on_var_indirection, }, ) eof = object() with runtime.ns_bindings(in_ns) as ns: if code: print(runtime.lrepr(eval_str(file_or_code, ctx, ns.module, eof))) elif file_or_code == STDIN_FILE_NAME: print( runtime.lrepr( eval_stream(click.get_text_stream("stdin"), ctx, ns.module) ) ) else: print(runtime.lrepr(eval_file(file_or_code, ctx, ns.module)))
[ "Run", "a", "Basilisp", "script", "or", "a", "line", "of", "code", "if", "it", "is", "provided", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/cli.py#L214-L250
[ "def", "run", "(", "# pylint: disable=too-many-arguments", "file_or_code", ",", "code", ",", "in_ns", ",", "use_var_indirection", ",", "warn_on_shadowed_name", ",", "warn_on_shadowed_var", ",", "warn_on_var_indirection", ",", ")", ":", "basilisp", ".", "init", "(", ")", "ctx", "=", "compiler", ".", "CompilerContext", "(", "filename", "=", "CLI_INPUT_FILE_PATH", "if", "code", "else", "(", "STDIN_INPUT_FILE_PATH", "if", "file_or_code", "==", "STDIN_FILE_NAME", "else", "file_or_code", ")", ",", "opts", "=", "{", "compiler", ".", "WARN_ON_SHADOWED_NAME", ":", "warn_on_shadowed_name", ",", "compiler", ".", "WARN_ON_SHADOWED_VAR", ":", "warn_on_shadowed_var", ",", "compiler", ".", "USE_VAR_INDIRECTION", ":", "use_var_indirection", ",", "compiler", ".", "WARN_ON_VAR_INDIRECTION", ":", "warn_on_var_indirection", ",", "}", ",", ")", "eof", "=", "object", "(", ")", "with", "runtime", ".", "ns_bindings", "(", "in_ns", ")", "as", "ns", ":", "if", "code", ":", "print", "(", "runtime", ".", "lrepr", "(", "eval_str", "(", "file_or_code", ",", "ctx", ",", "ns", ".", "module", ",", "eof", ")", ")", ")", "elif", "file_or_code", "==", "STDIN_FILE_NAME", ":", "print", "(", "runtime", ".", "lrepr", "(", "eval_stream", "(", "click", ".", "get_text_stream", "(", "\"stdin\"", ")", ",", "ctx", ",", "ns", ".", "module", ")", ")", ")", "else", ":", "print", "(", "runtime", ".", "lrepr", "(", "eval_file", "(", "file_or_code", ",", "ctx", ",", "ns", ".", "module", ")", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
multifn
Decorator function which can be used to make Python multi functions.
src/basilisp/lang/multifn.py
def multifn(dispatch: DispatchFunction, default=None) -> MultiFunction[T]: """Decorator function which can be used to make Python multi functions.""" name = sym.symbol(dispatch.__qualname__, ns=dispatch.__module__) return MultiFunction(name, dispatch, default)
def multifn(dispatch: DispatchFunction, default=None) -> MultiFunction[T]: """Decorator function which can be used to make Python multi functions.""" name = sym.symbol(dispatch.__qualname__, ns=dispatch.__module__) return MultiFunction(name, dispatch, default)
[ "Decorator", "function", "which", "can", "be", "used", "to", "make", "Python", "multi", "functions", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L81-L84
[ "def", "multifn", "(", "dispatch", ":", "DispatchFunction", ",", "default", "=", "None", ")", "->", "MultiFunction", "[", "T", "]", ":", "name", "=", "sym", ".", "symbol", "(", "dispatch", ".", "__qualname__", ",", "ns", "=", "dispatch", ".", "__module__", ")", "return", "MultiFunction", "(", "name", ",", "dispatch", ",", "default", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
MultiFunction.__add_method
Swap the methods atom to include method with key.
src/basilisp/lang/multifn.py
def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map: """Swap the methods atom to include method with key.""" return m.assoc(key, method)
def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map: """Swap the methods atom to include method with key.""" return m.assoc(key, method)
[ "Swap", "the", "methods", "atom", "to", "include", "method", "with", "key", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L37-L39
[ "def", "__add_method", "(", "m", ":", "lmap", ".", "Map", ",", "key", ":", "T", ",", "method", ":", "Method", ")", "->", "lmap", ".", "Map", ":", "return", "m", ".", "assoc", "(", "key", ",", "method", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
MultiFunction.add_method
Add a new method to this function which will respond for key returned from the dispatch function.
src/basilisp/lang/multifn.py
def add_method(self, key: T, method: Method) -> None: """Add a new method to this function which will respond for key returned from the dispatch function.""" self._methods.swap(MultiFunction.__add_method, key, method)
def add_method(self, key: T, method: Method) -> None: """Add a new method to this function which will respond for key returned from the dispatch function.""" self._methods.swap(MultiFunction.__add_method, key, method)
[ "Add", "a", "new", "method", "to", "this", "function", "which", "will", "respond", "for", "key", "returned", "from", "the", "dispatch", "function", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L41-L44
[ "def", "add_method", "(", "self", ",", "key", ":", "T", ",", "method", ":", "Method", ")", "->", "None", ":", "self", ".", "_methods", ".", "swap", "(", "MultiFunction", ".", "__add_method", ",", "key", ",", "method", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
MultiFunction.get_method
Return the method which would handle this dispatch key or None if no method defined for this key and no default.
src/basilisp/lang/multifn.py
def get_method(self, key: T) -> Optional[Method]: """Return the method which would handle this dispatch key or None if no method defined for this key and no default.""" method_cache = self.methods # The 'type: ignore' comment below silences a spurious MyPy error # about having a return statement in a method which does not return. return Maybe(method_cache.entry(key, None)).or_else( lambda: method_cache.entry(self._default, None) # type: ignore )
def get_method(self, key: T) -> Optional[Method]: """Return the method which would handle this dispatch key or None if no method defined for this key and no default.""" method_cache = self.methods # The 'type: ignore' comment below silences a spurious MyPy error # about having a return statement in a method which does not return. return Maybe(method_cache.entry(key, None)).or_else( lambda: method_cache.entry(self._default, None) # type: ignore )
[ "Return", "the", "method", "which", "would", "handle", "this", "dispatch", "key", "or", "None", "if", "no", "method", "defined", "for", "this", "key", "and", "no", "default", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L46-L54
[ "def", "get_method", "(", "self", ",", "key", ":", "T", ")", "->", "Optional", "[", "Method", "]", ":", "method_cache", "=", "self", ".", "methods", "# The 'type: ignore' comment below silences a spurious MyPy error", "# about having a return statement in a method which does not return.", "return", "Maybe", "(", "method_cache", ".", "entry", "(", "key", ",", "None", ")", ")", ".", "or_else", "(", "lambda", ":", "method_cache", ".", "entry", "(", "self", ".", "_default", ",", "None", ")", "# type: ignore", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
MultiFunction.__remove_method
Swap the methods atom to remove method with key.
src/basilisp/lang/multifn.py
def __remove_method(m: lmap.Map, key: T) -> lmap.Map: """Swap the methods atom to remove method with key.""" return m.dissoc(key)
def __remove_method(m: lmap.Map, key: T) -> lmap.Map: """Swap the methods atom to remove method with key.""" return m.dissoc(key)
[ "Swap", "the", "methods", "atom", "to", "remove", "method", "with", "key", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L57-L59
[ "def", "__remove_method", "(", "m", ":", "lmap", ".", "Map", ",", "key", ":", "T", ")", "->", "lmap", ".", "Map", ":", "return", "m", ".", "dissoc", "(", "key", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
MultiFunction.remove_method
Remove the method defined for this key and return it.
src/basilisp/lang/multifn.py
def remove_method(self, key: T) -> Optional[Method]: """Remove the method defined for this key and return it.""" method = self.methods.entry(key, None) if method: self._methods.swap(MultiFunction.__remove_method, key) return method
def remove_method(self, key: T) -> Optional[Method]: """Remove the method defined for this key and return it.""" method = self.methods.entry(key, None) if method: self._methods.swap(MultiFunction.__remove_method, key) return method
[ "Remove", "the", "method", "defined", "for", "this", "key", "and", "return", "it", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/multifn.py#L61-L66
[ "def", "remove_method", "(", "self", ",", "key", ":", "T", ")", "->", "Optional", "[", "Method", "]", ":", "method", "=", "self", ".", "methods", ".", "entry", "(", "key", ",", "None", ")", "if", "method", ":", "self", ".", "_methods", ".", "swap", "(", "MultiFunction", ".", "__remove_method", ",", "key", ")", "return", "method" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_is_async
Return True if the meta contains :async keyword.
src/basilisp/lang/compiler/parser.py
def _is_async(o: IMeta) -> bool: """Return True if the meta contains :async keyword.""" return ( # type: ignore Maybe(o.meta) .map(lambda m: m.entry(SYM_ASYNC_META_KEY, None)) .or_else_get(False) )
def _is_async(o: IMeta) -> bool: """Return True if the meta contains :async keyword.""" return ( # type: ignore Maybe(o.meta) .map(lambda m: m.entry(SYM_ASYNC_META_KEY, None)) .or_else_get(False) )
[ "Return", "True", "if", "the", "meta", "contains", ":", "async", "keyword", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L411-L417
[ "def", "_is_async", "(", "o", ":", "IMeta", ")", "->", "bool", ":", "return", "(", "# type: ignore", "Maybe", "(", "o", ".", "meta", ")", ".", "map", "(", "lambda", "m", ":", "m", ".", "entry", "(", "SYM_ASYNC_META_KEY", ",", "None", ")", ")", ".", "or_else_get", "(", "False", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_is_macro
Return True if the Var holds a macro function.
src/basilisp/lang/compiler/parser.py
def _is_macro(v: Var) -> bool: """Return True if the Var holds a macro function.""" return ( Maybe(v.meta) .map(lambda m: m.entry(SYM_MACRO_META_KEY, None)) # type: ignore .or_else_get(False) )
def _is_macro(v: Var) -> bool: """Return True if the Var holds a macro function.""" return ( Maybe(v.meta) .map(lambda m: m.entry(SYM_MACRO_META_KEY, None)) # type: ignore .or_else_get(False) )
[ "Return", "True", "if", "the", "Var", "holds", "a", "macro", "function", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L420-L426
[ "def", "_is_macro", "(", "v", ":", "Var", ")", "->", "bool", ":", "return", "(", "Maybe", "(", "v", ".", "meta", ")", ".", "map", "(", "lambda", "m", ":", "m", ".", "entry", "(", "SYM_MACRO_META_KEY", ",", "None", ")", ")", "# type: ignore", ".", "or_else_get", "(", "False", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_loc
Fetch the location of the form in the original filename from the input form, if it has metadata.
src/basilisp/lang/compiler/parser.py
def _loc(form: Union[LispForm, ISeq]) -> Optional[Tuple[int, int]]: """Fetch the location of the form in the original filename from the input form, if it has metadata.""" try: meta = form.meta # type: ignore line = meta.get(reader.READER_LINE_KW) # type: ignore col = meta.get(reader.READER_COL_KW) # type: ignore except AttributeError: return None else: assert isinstance(line, int) and isinstance(col, int) return line, col
def _loc(form: Union[LispForm, ISeq]) -> Optional[Tuple[int, int]]: """Fetch the location of the form in the original filename from the input form, if it has metadata.""" try: meta = form.meta # type: ignore line = meta.get(reader.READER_LINE_KW) # type: ignore col = meta.get(reader.READER_COL_KW) # type: ignore except AttributeError: return None else: assert isinstance(line, int) and isinstance(col, int) return line, col
[ "Fetch", "the", "location", "of", "the", "form", "in", "the", "original", "filename", "from", "the", "input", "form", "if", "it", "has", "metadata", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L432-L443
[ "def", "_loc", "(", "form", ":", "Union", "[", "LispForm", ",", "ISeq", "]", ")", "->", "Optional", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "try", ":", "meta", "=", "form", ".", "meta", "# type: ignore", "line", "=", "meta", ".", "get", "(", "reader", ".", "READER_LINE_KW", ")", "# type: ignore", "col", "=", "meta", ".", "get", "(", "reader", ".", "READER_COL_KW", ")", "# type: ignore", "except", "AttributeError", ":", "return", "None", "else", ":", "assert", "isinstance", "(", "line", ",", "int", ")", "and", "isinstance", "(", "col", ",", "int", ")", "return", "line", ",", "col" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_with_loc
Attach any available location information from the input form to the node environment returned from the parsing function.
src/basilisp/lang/compiler/parser.py
def _with_loc(f: ParseFunction): """Attach any available location information from the input form to the node environment returned from the parsing function.""" @wraps(f) def _parse_form(ctx: ParserContext, form: Union[LispForm, ISeq]) -> Node: form_loc = _loc(form) if form_loc is None: return f(ctx, form) else: return f(ctx, form).fix_missing_locations(form_loc) return _parse_form
def _with_loc(f: ParseFunction): """Attach any available location information from the input form to the node environment returned from the parsing function.""" @wraps(f) def _parse_form(ctx: ParserContext, form: Union[LispForm, ISeq]) -> Node: form_loc = _loc(form) if form_loc is None: return f(ctx, form) else: return f(ctx, form).fix_missing_locations(form_loc) return _parse_form
[ "Attach", "any", "available", "location", "information", "from", "the", "input", "form", "to", "the", "node", "environment", "returned", "from", "the", "parsing", "function", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L446-L458
[ "def", "_with_loc", "(", "f", ":", "ParseFunction", ")", ":", "@", "wraps", "(", "f", ")", "def", "_parse_form", "(", "ctx", ":", "ParserContext", ",", "form", ":", "Union", "[", "LispForm", ",", "ISeq", "]", ")", "->", "Node", ":", "form_loc", "=", "_loc", "(", "form", ")", "if", "form_loc", "is", "None", ":", "return", "f", "(", "ctx", ",", "form", ")", "else", ":", "return", "f", "(", "ctx", ",", "form", ")", ".", "fix_missing_locations", "(", "form_loc", ")", "return", "_parse_form" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_clean_meta
Remove reader metadata from the form's meta map.
src/basilisp/lang/compiler/parser.py
def _clean_meta(meta: Optional[lmap.Map]) -> Optional[lmap.Map]: """Remove reader metadata from the form's meta map.""" if meta is None: return None else: new_meta = meta.dissoc(reader.READER_LINE_KW, reader.READER_COL_KW) return None if len(new_meta) == 0 else new_meta
def _clean_meta(meta: Optional[lmap.Map]) -> Optional[lmap.Map]: """Remove reader metadata from the form's meta map.""" if meta is None: return None else: new_meta = meta.dissoc(reader.READER_LINE_KW, reader.READER_COL_KW) return None if len(new_meta) == 0 else new_meta
[ "Remove", "reader", "metadata", "from", "the", "form", "s", "meta", "map", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L461-L467
[ "def", "_clean_meta", "(", "meta", ":", "Optional", "[", "lmap", ".", "Map", "]", ")", "->", "Optional", "[", "lmap", ".", "Map", "]", ":", "if", "meta", "is", "None", ":", "return", "None", "else", ":", "new_meta", "=", "meta", ".", "dissoc", "(", "reader", ".", "READER_LINE_KW", ",", "reader", ".", "READER_COL_KW", ")", "return", "None", "if", "len", "(", "new_meta", ")", "==", "0", "else", "new_meta" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_with_meta
Wraps the node generated by gen_node in a :with-meta AST node if the original form has meta. :with-meta AST nodes are used for non-quoted collection literals and for function expressions.
src/basilisp/lang/compiler/parser.py
def _with_meta(gen_node): """Wraps the node generated by gen_node in a :with-meta AST node if the original form has meta. :with-meta AST nodes are used for non-quoted collection literals and for function expressions.""" @wraps(gen_node) def with_meta( ctx: ParserContext, form: Union[llist.List, lmap.Map, ISeq, lset.Set, vec.Vector], ) -> Node: assert not ctx.is_quoted, "with-meta nodes are not used in quoted expressions" descriptor = gen_node(ctx, form) if isinstance(form, IMeta): assert isinstance(form.meta, (lmap.Map, type(None))) form_meta = _clean_meta(form.meta) if form_meta is not None: meta_ast = _parse_ast(ctx, form_meta) assert isinstance(meta_ast, MapNode) or ( isinstance(meta_ast, Const) and meta_ast.type == ConstType.MAP ) return WithMeta( form=form, meta=meta_ast, expr=descriptor, env=ctx.get_node_env() ) return descriptor return with_meta
def _with_meta(gen_node): """Wraps the node generated by gen_node in a :with-meta AST node if the original form has meta. :with-meta AST nodes are used for non-quoted collection literals and for function expressions.""" @wraps(gen_node) def with_meta( ctx: ParserContext, form: Union[llist.List, lmap.Map, ISeq, lset.Set, vec.Vector], ) -> Node: assert not ctx.is_quoted, "with-meta nodes are not used in quoted expressions" descriptor = gen_node(ctx, form) if isinstance(form, IMeta): assert isinstance(form.meta, (lmap.Map, type(None))) form_meta = _clean_meta(form.meta) if form_meta is not None: meta_ast = _parse_ast(ctx, form_meta) assert isinstance(meta_ast, MapNode) or ( isinstance(meta_ast, Const) and meta_ast.type == ConstType.MAP ) return WithMeta( form=form, meta=meta_ast, expr=descriptor, env=ctx.get_node_env() ) return descriptor return with_meta
[ "Wraps", "the", "node", "generated", "by", "gen_node", "in", "a", ":", "with", "-", "meta", "AST", "node", "if", "the", "original", "form", "has", "meta", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L470-L500
[ "def", "_with_meta", "(", "gen_node", ")", ":", "@", "wraps", "(", "gen_node", ")", "def", "with_meta", "(", "ctx", ":", "ParserContext", ",", "form", ":", "Union", "[", "llist", ".", "List", ",", "lmap", ".", "Map", ",", "ISeq", ",", "lset", ".", "Set", ",", "vec", ".", "Vector", "]", ",", ")", "->", "Node", ":", "assert", "not", "ctx", ".", "is_quoted", ",", "\"with-meta nodes are not used in quoted expressions\"", "descriptor", "=", "gen_node", "(", "ctx", ",", "form", ")", "if", "isinstance", "(", "form", ",", "IMeta", ")", ":", "assert", "isinstance", "(", "form", ".", "meta", ",", "(", "lmap", ".", "Map", ",", "type", "(", "None", ")", ")", ")", "form_meta", "=", "_clean_meta", "(", "form", ".", "meta", ")", "if", "form_meta", "is", "not", "None", ":", "meta_ast", "=", "_parse_ast", "(", "ctx", ",", "form_meta", ")", "assert", "isinstance", "(", "meta_ast", ",", "MapNode", ")", "or", "(", "isinstance", "(", "meta_ast", ",", "Const", ")", "and", "meta_ast", ".", "type", "==", "ConstType", ".", "MAP", ")", "return", "WithMeta", "(", "form", "=", "form", ",", "meta", "=", "meta_ast", ",", "expr", "=", "descriptor", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ")", "return", "descriptor", "return", "with_meta" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
__deftype_impls
Roll up deftype* declared bases and method implementations.
src/basilisp/lang/compiler/parser.py
def __deftype_impls( # pylint: disable=too-many-branches ctx: ParserContext, form: ISeq ) -> Tuple[List[DefTypeBase], List[Method]]: """Roll up deftype* declared bases and method implementations.""" current_interface_sym: Optional[sym.Symbol] = None current_interface: Optional[DefTypeBase] = None interfaces = [] methods: List[Method] = [] interface_methods: MutableMapping[sym.Symbol, List[Method]] = {} for elem in form: if isinstance(elem, sym.Symbol): if current_interface is not None: if current_interface_sym in interface_methods: raise ParserException( f"deftype* forms may only implement an interface once", form=elem, ) assert ( current_interface_sym is not None ), "Symbol must be defined with interface" interface_methods[current_interface_sym] = methods current_interface_sym = elem current_interface = _parse_ast(ctx, elem) methods = [] if not isinstance(current_interface, (MaybeClass, MaybeHostForm, VarRef)): raise ParserException( f"deftype* interface implementation must be an existing interface", form=elem, ) interfaces.append(current_interface) elif isinstance(elem, ISeq): if current_interface is None: raise ParserException( f"deftype* method cannot be declared without interface", form=elem ) methods.append(__deftype_method(ctx, elem, current_interface)) else: raise ParserException( f"deftype* must consist of interface or protocol names and methods", form=elem, ) if current_interface is not None: if len(methods) > 0: if current_interface_sym in interface_methods: raise ParserException( f"deftype* forms may only implement an interface once", form=current_interface_sym, ) assert ( current_interface_sym is not None ), "Symbol must be defined with interface" interface_methods[current_interface_sym] = methods else: raise ParserException( f"deftype* may not declare interface without at least one method", form=current_interface_sym, ) return interfaces, list(chain.from_iterable(interface_methods.values()))
def __deftype_impls( # pylint: disable=too-many-branches ctx: ParserContext, form: ISeq ) -> Tuple[List[DefTypeBase], List[Method]]: """Roll up deftype* declared bases and method implementations.""" current_interface_sym: Optional[sym.Symbol] = None current_interface: Optional[DefTypeBase] = None interfaces = [] methods: List[Method] = [] interface_methods: MutableMapping[sym.Symbol, List[Method]] = {} for elem in form: if isinstance(elem, sym.Symbol): if current_interface is not None: if current_interface_sym in interface_methods: raise ParserException( f"deftype* forms may only implement an interface once", form=elem, ) assert ( current_interface_sym is not None ), "Symbol must be defined with interface" interface_methods[current_interface_sym] = methods current_interface_sym = elem current_interface = _parse_ast(ctx, elem) methods = [] if not isinstance(current_interface, (MaybeClass, MaybeHostForm, VarRef)): raise ParserException( f"deftype* interface implementation must be an existing interface", form=elem, ) interfaces.append(current_interface) elif isinstance(elem, ISeq): if current_interface is None: raise ParserException( f"deftype* method cannot be declared without interface", form=elem ) methods.append(__deftype_method(ctx, elem, current_interface)) else: raise ParserException( f"deftype* must consist of interface or protocol names and methods", form=elem, ) if current_interface is not None: if len(methods) > 0: if current_interface_sym in interface_methods: raise ParserException( f"deftype* forms may only implement an interface once", form=current_interface_sym, ) assert ( current_interface_sym is not None ), "Symbol must be defined with interface" interface_methods[current_interface_sym] = methods else: raise ParserException( f"deftype* may not declare interface without at least one method", form=current_interface_sym, ) return interfaces, list(chain.from_iterable(interface_methods.values()))
[ "Roll", "up", "deftype", "*", "declared", "bases", "and", "method", "implementations", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L764-L825
[ "def", "__deftype_impls", "(", "# pylint: disable=too-many-branches", "ctx", ":", "ParserContext", ",", "form", ":", "ISeq", ")", "->", "Tuple", "[", "List", "[", "DefTypeBase", "]", ",", "List", "[", "Method", "]", "]", ":", "current_interface_sym", ":", "Optional", "[", "sym", ".", "Symbol", "]", "=", "None", "current_interface", ":", "Optional", "[", "DefTypeBase", "]", "=", "None", "interfaces", "=", "[", "]", "methods", ":", "List", "[", "Method", "]", "=", "[", "]", "interface_methods", ":", "MutableMapping", "[", "sym", ".", "Symbol", ",", "List", "[", "Method", "]", "]", "=", "{", "}", "for", "elem", "in", "form", ":", "if", "isinstance", "(", "elem", ",", "sym", ".", "Symbol", ")", ":", "if", "current_interface", "is", "not", "None", ":", "if", "current_interface_sym", "in", "interface_methods", ":", "raise", "ParserException", "(", "f\"deftype* forms may only implement an interface once\"", ",", "form", "=", "elem", ",", ")", "assert", "(", "current_interface_sym", "is", "not", "None", ")", ",", "\"Symbol must be defined with interface\"", "interface_methods", "[", "current_interface_sym", "]", "=", "methods", "current_interface_sym", "=", "elem", "current_interface", "=", "_parse_ast", "(", "ctx", ",", "elem", ")", "methods", "=", "[", "]", "if", "not", "isinstance", "(", "current_interface", ",", "(", "MaybeClass", ",", "MaybeHostForm", ",", "VarRef", ")", ")", ":", "raise", "ParserException", "(", "f\"deftype* interface implementation must be an existing interface\"", ",", "form", "=", "elem", ",", ")", "interfaces", ".", "append", "(", "current_interface", ")", "elif", "isinstance", "(", "elem", ",", "ISeq", ")", ":", "if", "current_interface", "is", "None", ":", "raise", "ParserException", "(", "f\"deftype* method cannot be declared without interface\"", ",", "form", "=", "elem", ")", "methods", ".", "append", "(", "__deftype_method", "(", "ctx", ",", "elem", ",", "current_interface", ")", ")", "else", ":", "raise", "ParserException", "(", "f\"deftype* must consist of interface or protocol names and methods\"", ",", "form", "=", "elem", ",", ")", "if", "current_interface", "is", "not", "None", ":", "if", "len", "(", "methods", ")", ">", "0", ":", "if", "current_interface_sym", "in", "interface_methods", ":", "raise", "ParserException", "(", "f\"deftype* forms may only implement an interface once\"", ",", "form", "=", "current_interface_sym", ",", ")", "assert", "(", "current_interface_sym", "is", "not", "None", ")", ",", "\"Symbol must be defined with interface\"", "interface_methods", "[", "current_interface_sym", "]", "=", "methods", "else", ":", "raise", "ParserException", "(", "f\"deftype* may not declare interface without at least one method\"", ",", "form", "=", "current_interface_sym", ",", ")", "return", "interfaces", ",", "list", "(", "chain", ".", "from_iterable", "(", "interface_methods", ".", "values", "(", ")", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_assert_no_recur
Assert that `recur` forms do not appear in any position of this or child AST nodes.
src/basilisp/lang/compiler/parser.py
def _assert_no_recur(node: Node) -> None: """Assert that `recur` forms do not appear in any position of this or child AST nodes.""" if node.op == NodeOp.RECUR: raise ParserException( "recur must appear in tail position", form=node.form, lisp_ast=node ) elif node.op in {NodeOp.FN, NodeOp.LOOP}: pass else: node.visit(_assert_no_recur)
def _assert_no_recur(node: Node) -> None: """Assert that `recur` forms do not appear in any position of this or child AST nodes.""" if node.op == NodeOp.RECUR: raise ParserException( "recur must appear in tail position", form=node.form, lisp_ast=node ) elif node.op in {NodeOp.FN, NodeOp.LOOP}: pass else: node.visit(_assert_no_recur)
[ "Assert", "that", "recur", "forms", "do", "not", "appear", "in", "any", "position", "of", "this", "or", "child", "AST", "nodes", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L1501-L1511
[ "def", "_assert_no_recur", "(", "node", ":", "Node", ")", "->", "None", ":", "if", "node", ".", "op", "==", "NodeOp", ".", "RECUR", ":", "raise", "ParserException", "(", "\"recur must appear in tail position\"", ",", "form", "=", "node", ".", "form", ",", "lisp_ast", "=", "node", ")", "elif", "node", ".", "op", "in", "{", "NodeOp", ".", "FN", ",", "NodeOp", ".", "LOOP", "}", ":", "pass", "else", ":", "node", ".", "visit", "(", "_assert_no_recur", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_assert_recur_is_tail
Assert that `recur` forms only appear in the tail position of this or child AST nodes. `recur` forms may only appear in `do` nodes (both literal and synthetic `do` nodes) and in either the :then or :else expression of an `if` node.
src/basilisp/lang/compiler/parser.py
def _assert_recur_is_tail(node: Node) -> None: # pylint: disable=too-many-branches """Assert that `recur` forms only appear in the tail position of this or child AST nodes. `recur` forms may only appear in `do` nodes (both literal and synthetic `do` nodes) and in either the :then or :else expression of an `if` node.""" if node.op == NodeOp.DO: assert isinstance(node, Do) for child in node.statements: _assert_no_recur(child) _assert_recur_is_tail(node.ret) elif node.op in {NodeOp.FN, NodeOp.FN_METHOD, NodeOp.METHOD}: assert isinstance(node, (Fn, FnMethod, Method)) node.visit(_assert_recur_is_tail) elif node.op == NodeOp.IF: assert isinstance(node, If) _assert_no_recur(node.test) _assert_recur_is_tail(node.then) _assert_recur_is_tail(node.else_) elif node.op in {NodeOp.LET, NodeOp.LETFN}: assert isinstance(node, (Let, LetFn)) for binding in node.bindings: assert binding.init is not None _assert_no_recur(binding.init) _assert_recur_is_tail(node.body) elif node.op == NodeOp.LOOP: assert isinstance(node, Loop) for binding in node.bindings: assert binding.init is not None _assert_no_recur(binding.init) elif node.op == NodeOp.RECUR: pass elif node.op == NodeOp.TRY: assert isinstance(node, Try) _assert_recur_is_tail(node.body) for catch in node.catches: _assert_recur_is_tail(catch) if node.finally_: _assert_no_recur(node.finally_) else: node.visit(_assert_no_recur)
def _assert_recur_is_tail(node: Node) -> None: # pylint: disable=too-many-branches """Assert that `recur` forms only appear in the tail position of this or child AST nodes. `recur` forms may only appear in `do` nodes (both literal and synthetic `do` nodes) and in either the :then or :else expression of an `if` node.""" if node.op == NodeOp.DO: assert isinstance(node, Do) for child in node.statements: _assert_no_recur(child) _assert_recur_is_tail(node.ret) elif node.op in {NodeOp.FN, NodeOp.FN_METHOD, NodeOp.METHOD}: assert isinstance(node, (Fn, FnMethod, Method)) node.visit(_assert_recur_is_tail) elif node.op == NodeOp.IF: assert isinstance(node, If) _assert_no_recur(node.test) _assert_recur_is_tail(node.then) _assert_recur_is_tail(node.else_) elif node.op in {NodeOp.LET, NodeOp.LETFN}: assert isinstance(node, (Let, LetFn)) for binding in node.bindings: assert binding.init is not None _assert_no_recur(binding.init) _assert_recur_is_tail(node.body) elif node.op == NodeOp.LOOP: assert isinstance(node, Loop) for binding in node.bindings: assert binding.init is not None _assert_no_recur(binding.init) elif node.op == NodeOp.RECUR: pass elif node.op == NodeOp.TRY: assert isinstance(node, Try) _assert_recur_is_tail(node.body) for catch in node.catches: _assert_recur_is_tail(catch) if node.finally_: _assert_no_recur(node.finally_) else: node.visit(_assert_no_recur)
[ "Assert", "that", "recur", "forms", "only", "appear", "in", "the", "tail", "position", "of", "this", "or", "child", "AST", "nodes", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L1514-L1554
[ "def", "_assert_recur_is_tail", "(", "node", ":", "Node", ")", "->", "None", ":", "# pylint: disable=too-many-branches", "if", "node", ".", "op", "==", "NodeOp", ".", "DO", ":", "assert", "isinstance", "(", "node", ",", "Do", ")", "for", "child", "in", "node", ".", "statements", ":", "_assert_no_recur", "(", "child", ")", "_assert_recur_is_tail", "(", "node", ".", "ret", ")", "elif", "node", ".", "op", "in", "{", "NodeOp", ".", "FN", ",", "NodeOp", ".", "FN_METHOD", ",", "NodeOp", ".", "METHOD", "}", ":", "assert", "isinstance", "(", "node", ",", "(", "Fn", ",", "FnMethod", ",", "Method", ")", ")", "node", ".", "visit", "(", "_assert_recur_is_tail", ")", "elif", "node", ".", "op", "==", "NodeOp", ".", "IF", ":", "assert", "isinstance", "(", "node", ",", "If", ")", "_assert_no_recur", "(", "node", ".", "test", ")", "_assert_recur_is_tail", "(", "node", ".", "then", ")", "_assert_recur_is_tail", "(", "node", ".", "else_", ")", "elif", "node", ".", "op", "in", "{", "NodeOp", ".", "LET", ",", "NodeOp", ".", "LETFN", "}", ":", "assert", "isinstance", "(", "node", ",", "(", "Let", ",", "LetFn", ")", ")", "for", "binding", "in", "node", ".", "bindings", ":", "assert", "binding", ".", "init", "is", "not", "None", "_assert_no_recur", "(", "binding", ".", "init", ")", "_assert_recur_is_tail", "(", "node", ".", "body", ")", "elif", "node", ".", "op", "==", "NodeOp", ".", "LOOP", ":", "assert", "isinstance", "(", "node", ",", "Loop", ")", "for", "binding", "in", "node", ".", "bindings", ":", "assert", "binding", ".", "init", "is", "not", "None", "_assert_no_recur", "(", "binding", ".", "init", ")", "elif", "node", ".", "op", "==", "NodeOp", ".", "RECUR", ":", "pass", "elif", "node", ".", "op", "==", "NodeOp", ".", "TRY", ":", "assert", "isinstance", "(", "node", ",", "Try", ")", "_assert_recur_is_tail", "(", "node", ".", "body", ")", "for", "catch", "in", "node", ".", "catches", ":", "_assert_recur_is_tail", "(", "catch", ")", "if", "node", ".", "finally_", ":", "_assert_no_recur", "(", "node", ".", "finally_", ")", "else", ":", "node", ".", "visit", "(", "_assert_no_recur", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
__resolve_namespaced_symbol
Resolve a namespaced symbol into a Python name or Basilisp Var.
src/basilisp/lang/compiler/parser.py
def __resolve_namespaced_symbol( # pylint: disable=too-many-branches ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, MaybeHostForm, VarRef]: """Resolve a namespaced symbol into a Python name or Basilisp Var.""" assert form.ns is not None if form.ns == ctx.current_ns.name: v = ctx.current_ns.find(sym.symbol(form.name)) if v is not None: return VarRef(form=form, var=v, env=ctx.get_node_env()) elif form.ns == _BUILTINS_NS: class_ = munge(form.name, allow_builtins=True) target = getattr(builtins, class_, None) if target is None: raise ParserException( f"cannot resolve builtin function '{class_}'", form=form ) return MaybeClass( form=form, class_=class_, target=target, env=ctx.get_node_env() ) if "." in form.name: raise ParserException( "symbol names may not contain the '.' operator", form=form ) ns_sym = sym.symbol(form.ns) if ns_sym in ctx.current_ns.imports or ns_sym in ctx.current_ns.import_aliases: # We still import Basilisp code, so we'll want to make sure # that the symbol isn't referring to a Basilisp Var first v = Var.find(form) if v is not None: return VarRef(form=form, var=v, env=ctx.get_node_env()) # Fetch the full namespace name for the aliased namespace/module. # We don't need this for actually generating the link later, but # we _do_ need it for fetching a reference to the module to check # for membership. if ns_sym in ctx.current_ns.import_aliases: ns = ctx.current_ns.import_aliases[ns_sym] assert ns is not None ns_name = ns.name else: ns_name = ns_sym.name safe_module_name = munge(ns_name) assert ( safe_module_name in sys.modules ), f"Module '{safe_module_name}' is not imported" ns_module = sys.modules[safe_module_name] safe_name = munge(form.name) # Try without allowing builtins first if safe_name in vars(ns_module): return MaybeHostForm( form=form, class_=munge(ns_sym.name), field=safe_name, target=vars(ns_module)[safe_name], env=ctx.get_node_env(), ) # Then allow builtins safe_name = munge(form.name, allow_builtins=True) if safe_name not in vars(ns_module): raise ParserException("can't identify aliased form", form=form) # Aliased imports generate code which uses the import alias, so we # don't need to care if this is an import or an alias. return MaybeHostForm( form=form, class_=munge(ns_sym.name), field=safe_name, target=vars(ns_module)[safe_name], env=ctx.get_node_env(), ) elif ns_sym in ctx.current_ns.aliases: aliased_ns: runtime.Namespace = ctx.current_ns.aliases[ns_sym] v = Var.find(sym.symbol(form.name, ns=aliased_ns.name)) if v is None: raise ParserException( f"unable to resolve symbol '{sym.symbol(form.name, ns_sym.name)}' in this context", form=form, ) return VarRef(form=form, var=v, env=ctx.get_node_env()) else: raise ParserException( f"unable to resolve symbol '{form}' in this context", form=form )
def __resolve_namespaced_symbol( # pylint: disable=too-many-branches ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, MaybeHostForm, VarRef]: """Resolve a namespaced symbol into a Python name or Basilisp Var.""" assert form.ns is not None if form.ns == ctx.current_ns.name: v = ctx.current_ns.find(sym.symbol(form.name)) if v is not None: return VarRef(form=form, var=v, env=ctx.get_node_env()) elif form.ns == _BUILTINS_NS: class_ = munge(form.name, allow_builtins=True) target = getattr(builtins, class_, None) if target is None: raise ParserException( f"cannot resolve builtin function '{class_}'", form=form ) return MaybeClass( form=form, class_=class_, target=target, env=ctx.get_node_env() ) if "." in form.name: raise ParserException( "symbol names may not contain the '.' operator", form=form ) ns_sym = sym.symbol(form.ns) if ns_sym in ctx.current_ns.imports or ns_sym in ctx.current_ns.import_aliases: # We still import Basilisp code, so we'll want to make sure # that the symbol isn't referring to a Basilisp Var first v = Var.find(form) if v is not None: return VarRef(form=form, var=v, env=ctx.get_node_env()) # Fetch the full namespace name for the aliased namespace/module. # We don't need this for actually generating the link later, but # we _do_ need it for fetching a reference to the module to check # for membership. if ns_sym in ctx.current_ns.import_aliases: ns = ctx.current_ns.import_aliases[ns_sym] assert ns is not None ns_name = ns.name else: ns_name = ns_sym.name safe_module_name = munge(ns_name) assert ( safe_module_name in sys.modules ), f"Module '{safe_module_name}' is not imported" ns_module = sys.modules[safe_module_name] safe_name = munge(form.name) # Try without allowing builtins first if safe_name in vars(ns_module): return MaybeHostForm( form=form, class_=munge(ns_sym.name), field=safe_name, target=vars(ns_module)[safe_name], env=ctx.get_node_env(), ) # Then allow builtins safe_name = munge(form.name, allow_builtins=True) if safe_name not in vars(ns_module): raise ParserException("can't identify aliased form", form=form) # Aliased imports generate code which uses the import alias, so we # don't need to care if this is an import or an alias. return MaybeHostForm( form=form, class_=munge(ns_sym.name), field=safe_name, target=vars(ns_module)[safe_name], env=ctx.get_node_env(), ) elif ns_sym in ctx.current_ns.aliases: aliased_ns: runtime.Namespace = ctx.current_ns.aliases[ns_sym] v = Var.find(sym.symbol(form.name, ns=aliased_ns.name)) if v is None: raise ParserException( f"unable to resolve symbol '{sym.symbol(form.name, ns_sym.name)}' in this context", form=form, ) return VarRef(form=form, var=v, env=ctx.get_node_env()) else: raise ParserException( f"unable to resolve symbol '{form}' in this context", form=form )
[ "Resolve", "a", "namespaced", "symbol", "into", "a", "Python", "name", "or", "Basilisp", "Var", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L1788-L1876
[ "def", "__resolve_namespaced_symbol", "(", "# pylint: disable=too-many-branches", "ctx", ":", "ParserContext", ",", "form", ":", "sym", ".", "Symbol", ")", "->", "Union", "[", "MaybeClass", ",", "MaybeHostForm", ",", "VarRef", "]", ":", "assert", "form", ".", "ns", "is", "not", "None", "if", "form", ".", "ns", "==", "ctx", ".", "current_ns", ".", "name", ":", "v", "=", "ctx", ".", "current_ns", ".", "find", "(", "sym", ".", "symbol", "(", "form", ".", "name", ")", ")", "if", "v", "is", "not", "None", ":", "return", "VarRef", "(", "form", "=", "form", ",", "var", "=", "v", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ")", "elif", "form", ".", "ns", "==", "_BUILTINS_NS", ":", "class_", "=", "munge", "(", "form", ".", "name", ",", "allow_builtins", "=", "True", ")", "target", "=", "getattr", "(", "builtins", ",", "class_", ",", "None", ")", "if", "target", "is", "None", ":", "raise", "ParserException", "(", "f\"cannot resolve builtin function '{class_}'\"", ",", "form", "=", "form", ")", "return", "MaybeClass", "(", "form", "=", "form", ",", "class_", "=", "class_", ",", "target", "=", "target", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ")", "if", "\".\"", "in", "form", ".", "name", ":", "raise", "ParserException", "(", "\"symbol names may not contain the '.' operator\"", ",", "form", "=", "form", ")", "ns_sym", "=", "sym", ".", "symbol", "(", "form", ".", "ns", ")", "if", "ns_sym", "in", "ctx", ".", "current_ns", ".", "imports", "or", "ns_sym", "in", "ctx", ".", "current_ns", ".", "import_aliases", ":", "# We still import Basilisp code, so we'll want to make sure", "# that the symbol isn't referring to a Basilisp Var first", "v", "=", "Var", ".", "find", "(", "form", ")", "if", "v", "is", "not", "None", ":", "return", "VarRef", "(", "form", "=", "form", ",", "var", "=", "v", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ")", "# Fetch the full namespace name for the aliased namespace/module.", "# We don't need this for actually generating the link later, but", "# we _do_ need it for fetching a reference to the module to check", "# for membership.", "if", "ns_sym", "in", "ctx", ".", "current_ns", ".", "import_aliases", ":", "ns", "=", "ctx", ".", "current_ns", ".", "import_aliases", "[", "ns_sym", "]", "assert", "ns", "is", "not", "None", "ns_name", "=", "ns", ".", "name", "else", ":", "ns_name", "=", "ns_sym", ".", "name", "safe_module_name", "=", "munge", "(", "ns_name", ")", "assert", "(", "safe_module_name", "in", "sys", ".", "modules", ")", ",", "f\"Module '{safe_module_name}' is not imported\"", "ns_module", "=", "sys", ".", "modules", "[", "safe_module_name", "]", "safe_name", "=", "munge", "(", "form", ".", "name", ")", "# Try without allowing builtins first", "if", "safe_name", "in", "vars", "(", "ns_module", ")", ":", "return", "MaybeHostForm", "(", "form", "=", "form", ",", "class_", "=", "munge", "(", "ns_sym", ".", "name", ")", ",", "field", "=", "safe_name", ",", "target", "=", "vars", "(", "ns_module", ")", "[", "safe_name", "]", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ",", ")", "# Then allow builtins", "safe_name", "=", "munge", "(", "form", ".", "name", ",", "allow_builtins", "=", "True", ")", "if", "safe_name", "not", "in", "vars", "(", "ns_module", ")", ":", "raise", "ParserException", "(", "\"can't identify aliased form\"", ",", "form", "=", "form", ")", "# Aliased imports generate code which uses the import alias, so we", "# don't need to care if this is an import or an alias.", "return", "MaybeHostForm", "(", "form", "=", "form", ",", "class_", "=", "munge", "(", "ns_sym", ".", "name", ")", ",", "field", "=", "safe_name", ",", "target", "=", "vars", "(", "ns_module", ")", "[", "safe_name", "]", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ",", ")", "elif", "ns_sym", "in", "ctx", ".", "current_ns", ".", "aliases", ":", "aliased_ns", ":", "runtime", ".", "Namespace", "=", "ctx", ".", "current_ns", ".", "aliases", "[", "ns_sym", "]", "v", "=", "Var", ".", "find", "(", "sym", ".", "symbol", "(", "form", ".", "name", ",", "ns", "=", "aliased_ns", ".", "name", ")", ")", "if", "v", "is", "None", ":", "raise", "ParserException", "(", "f\"unable to resolve symbol '{sym.symbol(form.name, ns_sym.name)}' in this context\"", ",", "form", "=", "form", ",", ")", "return", "VarRef", "(", "form", "=", "form", ",", "var", "=", "v", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ")", "else", ":", "raise", "ParserException", "(", "f\"unable to resolve symbol '{form}' in this context\"", ",", "form", "=", "form", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
__resolve_bare_symbol
Resolve a non-namespaced symbol into a Python name or a local Basilisp Var.
src/basilisp/lang/compiler/parser.py
def __resolve_bare_symbol( ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, VarRef]: """Resolve a non-namespaced symbol into a Python name or a local Basilisp Var.""" assert form.ns is None # Look up the symbol in the namespace mapping of the current namespace. v = ctx.current_ns.find(form) if v is not None: return VarRef(form=form, var=v, env=ctx.get_node_env()) if "." in form.name: raise ParserException( "symbol names may not contain the '.' operator", form=form ) munged = munge(form.name, allow_builtins=True) if munged in vars(builtins): return MaybeClass( form=form, class_=munged, target=vars(builtins)[munged], env=ctx.get_node_env(), ) assert munged not in vars(ctx.current_ns.module) raise ParserException( f"unable to resolve symbol '{form}' in this context", form=form )
def __resolve_bare_symbol( ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, VarRef]: """Resolve a non-namespaced symbol into a Python name or a local Basilisp Var.""" assert form.ns is None # Look up the symbol in the namespace mapping of the current namespace. v = ctx.current_ns.find(form) if v is not None: return VarRef(form=form, var=v, env=ctx.get_node_env()) if "." in form.name: raise ParserException( "symbol names may not contain the '.' operator", form=form ) munged = munge(form.name, allow_builtins=True) if munged in vars(builtins): return MaybeClass( form=form, class_=munged, target=vars(builtins)[munged], env=ctx.get_node_env(), ) assert munged not in vars(ctx.current_ns.module) raise ParserException( f"unable to resolve symbol '{form}' in this context", form=form )
[ "Resolve", "a", "non", "-", "namespaced", "symbol", "into", "a", "Python", "name", "or", "a", "local", "Basilisp", "Var", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L1879-L1908
[ "def", "__resolve_bare_symbol", "(", "ctx", ":", "ParserContext", ",", "form", ":", "sym", ".", "Symbol", ")", "->", "Union", "[", "MaybeClass", ",", "VarRef", "]", ":", "assert", "form", ".", "ns", "is", "None", "# Look up the symbol in the namespace mapping of the current namespace.", "v", "=", "ctx", ".", "current_ns", ".", "find", "(", "form", ")", "if", "v", "is", "not", "None", ":", "return", "VarRef", "(", "form", "=", "form", ",", "var", "=", "v", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ")", "if", "\".\"", "in", "form", ".", "name", ":", "raise", "ParserException", "(", "\"symbol names may not contain the '.' operator\"", ",", "form", "=", "form", ")", "munged", "=", "munge", "(", "form", ".", "name", ",", "allow_builtins", "=", "True", ")", "if", "munged", "in", "vars", "(", "builtins", ")", ":", "return", "MaybeClass", "(", "form", "=", "form", ",", "class_", "=", "munged", ",", "target", "=", "vars", "(", "builtins", ")", "[", "munged", "]", ",", "env", "=", "ctx", ".", "get_node_env", "(", ")", ",", ")", "assert", "munged", "not", "in", "vars", "(", "ctx", ".", "current_ns", ".", "module", ")", "raise", "ParserException", "(", "f\"unable to resolve symbol '{form}' in this context\"", ",", "form", "=", "form", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_resolve_sym
Resolve a Basilisp symbol as a Var or Python name.
src/basilisp/lang/compiler/parser.py
def _resolve_sym( ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, MaybeHostForm, VarRef]: """Resolve a Basilisp symbol as a Var or Python name.""" # Support special class-name syntax to instantiate new classes # (Classname. *args) # (aliased.Classname. *args) # (fully.qualified.Classname. *args) if form.ns is None and form.name.endswith("."): try: ns, name = form.name[:-1].rsplit(".", maxsplit=1) form = sym.symbol(name, ns=ns) except ValueError: form = sym.symbol(form.name[:-1]) if form.ns is not None: return __resolve_namespaced_symbol(ctx, form) else: return __resolve_bare_symbol(ctx, form)
def _resolve_sym( ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, MaybeHostForm, VarRef]: """Resolve a Basilisp symbol as a Var or Python name.""" # Support special class-name syntax to instantiate new classes # (Classname. *args) # (aliased.Classname. *args) # (fully.qualified.Classname. *args) if form.ns is None and form.name.endswith("."): try: ns, name = form.name[:-1].rsplit(".", maxsplit=1) form = sym.symbol(name, ns=ns) except ValueError: form = sym.symbol(form.name[:-1]) if form.ns is not None: return __resolve_namespaced_symbol(ctx, form) else: return __resolve_bare_symbol(ctx, form)
[ "Resolve", "a", "Basilisp", "symbol", "as", "a", "Var", "or", "Python", "name", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L1911-L1929
[ "def", "_resolve_sym", "(", "ctx", ":", "ParserContext", ",", "form", ":", "sym", ".", "Symbol", ")", "->", "Union", "[", "MaybeClass", ",", "MaybeHostForm", ",", "VarRef", "]", ":", "# Support special class-name syntax to instantiate new classes", "# (Classname. *args)", "# (aliased.Classname. *args)", "# (fully.qualified.Classname. *args)", "if", "form", ".", "ns", "is", "None", "and", "form", ".", "name", ".", "endswith", "(", "\".\"", ")", ":", "try", ":", "ns", ",", "name", "=", "form", ".", "name", "[", ":", "-", "1", "]", ".", "rsplit", "(", "\".\"", ",", "maxsplit", "=", "1", ")", "form", "=", "sym", ".", "symbol", "(", "name", ",", "ns", "=", "ns", ")", "except", "ValueError", ":", "form", "=", "sym", ".", "symbol", "(", "form", ".", "name", "[", ":", "-", "1", "]", ")", "if", "form", ".", "ns", "is", "not", "None", ":", "return", "__resolve_namespaced_symbol", "(", "ctx", ",", "form", ")", "else", ":", "return", "__resolve_bare_symbol", "(", "ctx", ",", "form", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
parse_ast
Take a Lisp form as an argument and produce a Basilisp syntax tree matching the clojure.tools.analyzer AST spec.
src/basilisp/lang/compiler/parser.py
def parse_ast(ctx: ParserContext, form: ReaderForm) -> Node: """Take a Lisp form as an argument and produce a Basilisp syntax tree matching the clojure.tools.analyzer AST spec.""" return _parse_ast(ctx, form).assoc(top_level=True)
def parse_ast(ctx: ParserContext, form: ReaderForm) -> Node: """Take a Lisp form as an argument and produce a Basilisp syntax tree matching the clojure.tools.analyzer AST spec.""" return _parse_ast(ctx, form).assoc(top_level=True)
[ "Take", "a", "Lisp", "form", "as", "an", "argument", "and", "produce", "a", "Basilisp", "syntax", "tree", "matching", "the", "clojure", ".", "tools", ".", "analyzer", "AST", "spec", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L2163-L2166
[ "def", "parse_ast", "(", "ctx", ":", "ParserContext", ",", "form", ":", "ReaderForm", ")", "->", "Node", ":", "return", "_parse_ast", "(", "ctx", ",", "form", ")", ".", "assoc", "(", "top_level", "=", "True", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
ParserContext.warn_on_shadowed_var
If True, warn when a def'ed Var name is shadowed in an inner scope. Implied by warn_on_shadowed_name. The value of warn_on_shadowed_name supersedes the value of this flag.
src/basilisp/lang/compiler/parser.py
def warn_on_shadowed_var(self) -> bool: """If True, warn when a def'ed Var name is shadowed in an inner scope. Implied by warn_on_shadowed_name. The value of warn_on_shadowed_name supersedes the value of this flag.""" return self.warn_on_shadowed_name or self._opts.entry( WARN_ON_SHADOWED_VAR, False )
def warn_on_shadowed_var(self) -> bool: """If True, warn when a def'ed Var name is shadowed in an inner scope. Implied by warn_on_shadowed_name. The value of warn_on_shadowed_name supersedes the value of this flag.""" return self.warn_on_shadowed_name or self._opts.entry( WARN_ON_SHADOWED_VAR, False )
[ "If", "True", "warn", "when", "a", "def", "ed", "Var", "name", "is", "shadowed", "in", "an", "inner", "scope", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L310-L317
[ "def", "warn_on_shadowed_var", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "warn_on_shadowed_name", "or", "self", ".", "_opts", ".", "entry", "(", "WARN_ON_SHADOWED_VAR", ",", "False", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
ParserContext.put_new_symbol
Add a new symbol to the symbol table. This function allows individual warnings to be disabled for one run by supplying keyword arguments temporarily disabling those warnings. In certain cases, we do not want to issue warnings again for a previously checked case, so this is a simple way of disabling these warnings for those cases. If WARN_ON_SHADOWED_NAME compiler option is active and the warn_on_shadowed_name keyword argument is True, then a warning will be emitted if a local name is shadowed by another local name. Note that WARN_ON_SHADOWED_NAME implies WARN_ON_SHADOWED_VAR. If WARN_ON_SHADOWED_VAR compiler option is active and the warn_on_shadowed_var keyword argument is True, then a warning will be emitted if a named var is shadowed by a local name.
src/basilisp/lang/compiler/parser.py
def put_new_symbol( # pylint: disable=too-many-arguments self, s: sym.Symbol, binding: Binding, warn_on_shadowed_name: bool = True, warn_on_shadowed_var: bool = True, warn_if_unused: bool = True, ): """Add a new symbol to the symbol table. This function allows individual warnings to be disabled for one run by supplying keyword arguments temporarily disabling those warnings. In certain cases, we do not want to issue warnings again for a previously checked case, so this is a simple way of disabling these warnings for those cases. If WARN_ON_SHADOWED_NAME compiler option is active and the warn_on_shadowed_name keyword argument is True, then a warning will be emitted if a local name is shadowed by another local name. Note that WARN_ON_SHADOWED_NAME implies WARN_ON_SHADOWED_VAR. If WARN_ON_SHADOWED_VAR compiler option is active and the warn_on_shadowed_var keyword argument is True, then a warning will be emitted if a named var is shadowed by a local name.""" st = self.symbol_table if warn_on_shadowed_name and self.warn_on_shadowed_name: if st.find_symbol(s) is not None: logger.warning(f"name '{s}' shadows name from outer scope") if ( warn_on_shadowed_name or warn_on_shadowed_var ) and self.warn_on_shadowed_var: if self.current_ns.find(s) is not None: logger.warning(f"name '{s}' shadows def'ed Var from outer scope") if s.meta is not None and s.meta.entry(SYM_NO_WARN_WHEN_UNUSED_META_KEY, None): warn_if_unused = False st.new_symbol(s, binding, warn_if_unused=warn_if_unused)
def put_new_symbol( # pylint: disable=too-many-arguments self, s: sym.Symbol, binding: Binding, warn_on_shadowed_name: bool = True, warn_on_shadowed_var: bool = True, warn_if_unused: bool = True, ): """Add a new symbol to the symbol table. This function allows individual warnings to be disabled for one run by supplying keyword arguments temporarily disabling those warnings. In certain cases, we do not want to issue warnings again for a previously checked case, so this is a simple way of disabling these warnings for those cases. If WARN_ON_SHADOWED_NAME compiler option is active and the warn_on_shadowed_name keyword argument is True, then a warning will be emitted if a local name is shadowed by another local name. Note that WARN_ON_SHADOWED_NAME implies WARN_ON_SHADOWED_VAR. If WARN_ON_SHADOWED_VAR compiler option is active and the warn_on_shadowed_var keyword argument is True, then a warning will be emitted if a named var is shadowed by a local name.""" st = self.symbol_table if warn_on_shadowed_name and self.warn_on_shadowed_name: if st.find_symbol(s) is not None: logger.warning(f"name '{s}' shadows name from outer scope") if ( warn_on_shadowed_name or warn_on_shadowed_var ) and self.warn_on_shadowed_var: if self.current_ns.find(s) is not None: logger.warning(f"name '{s}' shadows def'ed Var from outer scope") if s.meta is not None and s.meta.entry(SYM_NO_WARN_WHEN_UNUSED_META_KEY, None): warn_if_unused = False st.new_symbol(s, binding, warn_if_unused=warn_if_unused)
[ "Add", "a", "new", "symbol", "to", "the", "symbol", "table", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L362-L397
[ "def", "put_new_symbol", "(", "# pylint: disable=too-many-arguments", "self", ",", "s", ":", "sym", ".", "Symbol", ",", "binding", ":", "Binding", ",", "warn_on_shadowed_name", ":", "bool", "=", "True", ",", "warn_on_shadowed_var", ":", "bool", "=", "True", ",", "warn_if_unused", ":", "bool", "=", "True", ",", ")", ":", "st", "=", "self", ".", "symbol_table", "if", "warn_on_shadowed_name", "and", "self", ".", "warn_on_shadowed_name", ":", "if", "st", ".", "find_symbol", "(", "s", ")", "is", "not", "None", ":", "logger", ".", "warning", "(", "f\"name '{s}' shadows name from outer scope\"", ")", "if", "(", "warn_on_shadowed_name", "or", "warn_on_shadowed_var", ")", "and", "self", ".", "warn_on_shadowed_var", ":", "if", "self", ".", "current_ns", ".", "find", "(", "s", ")", "is", "not", "None", ":", "logger", ".", "warning", "(", "f\"name '{s}' shadows def'ed Var from outer scope\"", ")", "if", "s", ".", "meta", "is", "not", "None", "and", "s", ".", "meta", ".", "entry", "(", "SYM_NO_WARN_WHEN_UNUSED_META_KEY", ",", "None", ")", ":", "warn_if_unused", "=", "False", "st", ".", "new_symbol", "(", "s", ",", "binding", ",", "warn_if_unused", "=", "warn_if_unused", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
map_lrepr
Produce a Lisp representation of an associative collection, bookended with the start and end string supplied. The entries argument must be a callable which will produce tuples of key-value pairs. The keyword arguments will be passed along to lrepr for the sequence elements.
src/basilisp/lang/obj.py
def map_lrepr( entries: Callable[[], Iterable[Tuple[Any, Any]]], start: str, end: str, meta=None, **kwargs, ) -> str: """Produce a Lisp representation of an associative collection, bookended with the start and end string supplied. The entries argument must be a callable which will produce tuples of key-value pairs. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = kwargs["print_level"] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL kwargs = _process_kwargs(**kwargs) def entry_reprs(): for k, v in entries(): yield "{k} {v}".format(k=lrepr(k, **kwargs), v=lrepr(v, **kwargs)) trailer = [] print_dup = kwargs["print_dup"] print_length = kwargs["print_length"] if not print_dup and isinstance(print_length, int): items = seq(entry_reprs()).take(print_length + 1).to_list() if len(items) > print_length: items.pop() trailer.append(SURPASSED_PRINT_LENGTH) else: items = list(entry_reprs()) seq_lrepr = PRINT_SEPARATOR.join(items + trailer) print_meta = kwargs["print_meta"] if print_meta and meta: return f"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}" return f"{start}{seq_lrepr}{end}"
def map_lrepr( entries: Callable[[], Iterable[Tuple[Any, Any]]], start: str, end: str, meta=None, **kwargs, ) -> str: """Produce a Lisp representation of an associative collection, bookended with the start and end string supplied. The entries argument must be a callable which will produce tuples of key-value pairs. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = kwargs["print_level"] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL kwargs = _process_kwargs(**kwargs) def entry_reprs(): for k, v in entries(): yield "{k} {v}".format(k=lrepr(k, **kwargs), v=lrepr(v, **kwargs)) trailer = [] print_dup = kwargs["print_dup"] print_length = kwargs["print_length"] if not print_dup and isinstance(print_length, int): items = seq(entry_reprs()).take(print_length + 1).to_list() if len(items) > print_length: items.pop() trailer.append(SURPASSED_PRINT_LENGTH) else: items = list(entry_reprs()) seq_lrepr = PRINT_SEPARATOR.join(items + trailer) print_meta = kwargs["print_meta"] if print_meta and meta: return f"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}" return f"{start}{seq_lrepr}{end}"
[ "Produce", "a", "Lisp", "representation", "of", "an", "associative", "collection", "bookended", "with", "the", "start", "and", "end", "string", "supplied", ".", "The", "entries", "argument", "must", "be", "a", "callable", "which", "will", "produce", "tuples", "of", "key", "-", "value", "pairs", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/obj.py#L67-L107
[ "def", "map_lrepr", "(", "entries", ":", "Callable", "[", "[", "]", ",", "Iterable", "[", "Tuple", "[", "Any", ",", "Any", "]", "]", "]", ",", "start", ":", "str", ",", "end", ":", "str", ",", "meta", "=", "None", ",", "*", "*", "kwargs", ",", ")", "->", "str", ":", "print_level", "=", "kwargs", "[", "\"print_level\"", "]", "if", "isinstance", "(", "print_level", ",", "int", ")", "and", "print_level", "<", "1", ":", "return", "SURPASSED_PRINT_LEVEL", "kwargs", "=", "_process_kwargs", "(", "*", "*", "kwargs", ")", "def", "entry_reprs", "(", ")", ":", "for", "k", ",", "v", "in", "entries", "(", ")", ":", "yield", "\"{k} {v}\"", ".", "format", "(", "k", "=", "lrepr", "(", "k", ",", "*", "*", "kwargs", ")", ",", "v", "=", "lrepr", "(", "v", ",", "*", "*", "kwargs", ")", ")", "trailer", "=", "[", "]", "print_dup", "=", "kwargs", "[", "\"print_dup\"", "]", "print_length", "=", "kwargs", "[", "\"print_length\"", "]", "if", "not", "print_dup", "and", "isinstance", "(", "print_length", ",", "int", ")", ":", "items", "=", "seq", "(", "entry_reprs", "(", ")", ")", ".", "take", "(", "print_length", "+", "1", ")", ".", "to_list", "(", ")", "if", "len", "(", "items", ")", ">", "print_length", ":", "items", ".", "pop", "(", ")", "trailer", ".", "append", "(", "SURPASSED_PRINT_LENGTH", ")", "else", ":", "items", "=", "list", "(", "entry_reprs", "(", ")", ")", "seq_lrepr", "=", "PRINT_SEPARATOR", ".", "join", "(", "items", "+", "trailer", ")", "print_meta", "=", "kwargs", "[", "\"print_meta\"", "]", "if", "print_meta", "and", "meta", ":", "return", "f\"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}\"", "return", "f\"{start}{seq_lrepr}{end}\"" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
seq_lrepr
Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.
src/basilisp/lang/obj.py
def seq_lrepr( iterable: Iterable[Any], start: str, end: str, meta=None, **kwargs ) -> str: """Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = kwargs["print_level"] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL kwargs = _process_kwargs(**kwargs) trailer = [] print_dup = kwargs["print_dup"] print_length = kwargs["print_length"] if not print_dup and isinstance(print_length, int): items = seq(iterable).take(print_length + 1).to_list() if len(items) > print_length: items.pop() trailer.append(SURPASSED_PRINT_LENGTH) else: items = iterable items = list(map(lambda o: lrepr(o, **kwargs), items)) seq_lrepr = PRINT_SEPARATOR.join(items + trailer) print_meta = kwargs["print_meta"] if print_meta and meta: return f"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}" return f"{start}{seq_lrepr}{end}"
def seq_lrepr( iterable: Iterable[Any], start: str, end: str, meta=None, **kwargs ) -> str: """Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = kwargs["print_level"] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL kwargs = _process_kwargs(**kwargs) trailer = [] print_dup = kwargs["print_dup"] print_length = kwargs["print_length"] if not print_dup and isinstance(print_length, int): items = seq(iterable).take(print_length + 1).to_list() if len(items) > print_length: items.pop() trailer.append(SURPASSED_PRINT_LENGTH) else: items = iterable items = list(map(lambda o: lrepr(o, **kwargs), items)) seq_lrepr = PRINT_SEPARATOR.join(items + trailer) print_meta = kwargs["print_meta"] if print_meta and meta: return f"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}" return f"{start}{seq_lrepr}{end}"
[ "Produce", "a", "Lisp", "representation", "of", "a", "sequential", "collection", "bookended", "with", "the", "start", "and", "end", "string", "supplied", ".", "The", "keyword", "arguments", "will", "be", "passed", "along", "to", "lrepr", "for", "the", "sequence", "elements", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/obj.py#L110-L140
[ "def", "seq_lrepr", "(", "iterable", ":", "Iterable", "[", "Any", "]", ",", "start", ":", "str", ",", "end", ":", "str", ",", "meta", "=", "None", ",", "*", "*", "kwargs", ")", "->", "str", ":", "print_level", "=", "kwargs", "[", "\"print_level\"", "]", "if", "isinstance", "(", "print_level", ",", "int", ")", "and", "print_level", "<", "1", ":", "return", "SURPASSED_PRINT_LEVEL", "kwargs", "=", "_process_kwargs", "(", "*", "*", "kwargs", ")", "trailer", "=", "[", "]", "print_dup", "=", "kwargs", "[", "\"print_dup\"", "]", "print_length", "=", "kwargs", "[", "\"print_length\"", "]", "if", "not", "print_dup", "and", "isinstance", "(", "print_length", ",", "int", ")", ":", "items", "=", "seq", "(", "iterable", ")", ".", "take", "(", "print_length", "+", "1", ")", ".", "to_list", "(", ")", "if", "len", "(", "items", ")", ">", "print_length", ":", "items", ".", "pop", "(", ")", "trailer", ".", "append", "(", "SURPASSED_PRINT_LENGTH", ")", "else", ":", "items", "=", "iterable", "items", "=", "list", "(", "map", "(", "lambda", "o", ":", "lrepr", "(", "o", ",", "*", "*", "kwargs", ")", ",", "items", ")", ")", "seq_lrepr", "=", "PRINT_SEPARATOR", ".", "join", "(", "items", "+", "trailer", ")", "print_meta", "=", "kwargs", "[", "\"print_meta\"", "]", "if", "print_meta", "and", "meta", ":", "return", "f\"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}\"", "return", "f\"{start}{seq_lrepr}{end}\"" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
lrepr
Return a string representation of a Lisp object. Permissible keyword arguments are: - human_readable: if logical True, print strings without quotations or escape sequences (default: false) - print_dup: if logical true, print objects in a way that preserves their types (default: false) - print_length: the number of items in a collection which will be printed, or no limit if bound to a logical falsey value (default: 50) - print_level: the depth of the object graph to print, starting with 0, or no limit if bound to a logical falsey value (default: nil) - print_meta: if logical true, print objects meta in a way that can be read back by the reader (default: false) - print_readably: if logical false, print strings and characters with non-alphanumeric characters converted to escape sequences (default: true) Note that this function is not capable of capturing the values bound at runtime to the basilisp.core dynamic variables which correspond to each of the keyword arguments to this function. To use a version of lrepr which does capture those values, call basilisp.lang.runtime.lrepr directly.
src/basilisp/lang/obj.py
def lrepr( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) -> str: """Return a string representation of a Lisp object. Permissible keyword arguments are: - human_readable: if logical True, print strings without quotations or escape sequences (default: false) - print_dup: if logical true, print objects in a way that preserves their types (default: false) - print_length: the number of items in a collection which will be printed, or no limit if bound to a logical falsey value (default: 50) - print_level: the depth of the object graph to print, starting with 0, or no limit if bound to a logical falsey value (default: nil) - print_meta: if logical true, print objects meta in a way that can be read back by the reader (default: false) - print_readably: if logical false, print strings and characters with non-alphanumeric characters converted to escape sequences (default: true) Note that this function is not capable of capturing the values bound at runtime to the basilisp.core dynamic variables which correspond to each of the keyword arguments to this function. To use a version of lrepr which does capture those values, call basilisp.lang.runtime.lrepr directly.""" if isinstance(o, LispObject): return o._lrepr( human_readable=human_readable, print_dup=print_dup, print_length=print_length, print_level=print_level, print_meta=print_meta, print_readably=print_readably, ) else: # pragma: no cover return _lrepr_fallback( o, human_readable=human_readable, print_dup=print_dup, print_length=print_length, print_level=print_level, print_meta=print_meta, print_readably=print_readably, )
def lrepr( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) -> str: """Return a string representation of a Lisp object. Permissible keyword arguments are: - human_readable: if logical True, print strings without quotations or escape sequences (default: false) - print_dup: if logical true, print objects in a way that preserves their types (default: false) - print_length: the number of items in a collection which will be printed, or no limit if bound to a logical falsey value (default: 50) - print_level: the depth of the object graph to print, starting with 0, or no limit if bound to a logical falsey value (default: nil) - print_meta: if logical true, print objects meta in a way that can be read back by the reader (default: false) - print_readably: if logical false, print strings and characters with non-alphanumeric characters converted to escape sequences (default: true) Note that this function is not capable of capturing the values bound at runtime to the basilisp.core dynamic variables which correspond to each of the keyword arguments to this function. To use a version of lrepr which does capture those values, call basilisp.lang.runtime.lrepr directly.""" if isinstance(o, LispObject): return o._lrepr( human_readable=human_readable, print_dup=print_dup, print_length=print_length, print_level=print_level, print_meta=print_meta, print_readably=print_readably, ) else: # pragma: no cover return _lrepr_fallback( o, human_readable=human_readable, print_dup=print_dup, print_length=print_length, print_level=print_level, print_meta=print_meta, print_readably=print_readably, )
[ "Return", "a", "string", "representation", "of", "a", "Lisp", "object", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/obj.py#L144-L192
[ "def", "lrepr", "(", "# pylint: disable=too-many-arguments", "o", ":", "Any", ",", "human_readable", ":", "bool", "=", "False", ",", "print_dup", ":", "bool", "=", "PRINT_DUP", ",", "print_length", ":", "PrintCountSetting", "=", "PRINT_LENGTH", ",", "print_level", ":", "PrintCountSetting", "=", "PRINT_LEVEL", ",", "print_meta", ":", "bool", "=", "PRINT_META", ",", "print_readably", ":", "bool", "=", "PRINT_READABLY", ",", ")", "->", "str", ":", "if", "isinstance", "(", "o", ",", "LispObject", ")", ":", "return", "o", ".", "_lrepr", "(", "human_readable", "=", "human_readable", ",", "print_dup", "=", "print_dup", ",", "print_length", "=", "print_length", ",", "print_level", "=", "print_level", ",", "print_meta", "=", "print_meta", ",", "print_readably", "=", "print_readably", ",", ")", "else", ":", "# pragma: no cover", "return", "_lrepr_fallback", "(", "o", ",", "human_readable", "=", "human_readable", ",", "print_dup", "=", "print_dup", ",", "print_length", "=", "print_length", ",", "print_level", "=", "print_level", ",", "print_meta", "=", "print_meta", ",", "print_readably", "=", "print_readably", ",", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_lrepr_fallback
Fallback function for lrepr for subclasses of standard types. The singledispatch used for standard lrepr dispatches using an exact type match on the first argument, so we will only hit this function for subclasses of common Python types like strings or lists.
src/basilisp/lang/obj.py
def _lrepr_fallback( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) -> str: # pragma: no cover """Fallback function for lrepr for subclasses of standard types. The singledispatch used for standard lrepr dispatches using an exact type match on the first argument, so we will only hit this function for subclasses of common Python types like strings or lists.""" kwargs = { "human_readable": human_readable, "print_dup": print_dup, "print_length": print_length, "print_level": print_level, "print_meta": print_meta, "print_readably": print_readably, } if isinstance(o, bool): return _lrepr_bool(o) elif o is None: return _lrepr_nil(o) elif isinstance(o, str): return _lrepr_str( o, human_readable=human_readable, print_readably=print_readably ) elif isinstance(o, dict): return _lrepr_py_dict(o, **kwargs) elif isinstance(o, list): return _lrepr_py_list(o, **kwargs) elif isinstance(o, set): return _lrepr_py_set(o, **kwargs) elif isinstance(o, tuple): return _lrepr_py_tuple(o, **kwargs) elif isinstance(o, complex): return _lrepr_complex(o) elif isinstance(o, datetime.datetime): return _lrepr_datetime(o) elif isinstance(o, Decimal): return _lrepr_decimal(o, print_dup=print_dup) elif isinstance(o, Fraction): return _lrepr_fraction(o) elif isinstance(o, Pattern): return _lrepr_pattern(o) elif isinstance(o, uuid.UUID): return _lrepr_uuid(o) else: return repr(o)
def _lrepr_fallback( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) -> str: # pragma: no cover """Fallback function for lrepr for subclasses of standard types. The singledispatch used for standard lrepr dispatches using an exact type match on the first argument, so we will only hit this function for subclasses of common Python types like strings or lists.""" kwargs = { "human_readable": human_readable, "print_dup": print_dup, "print_length": print_length, "print_level": print_level, "print_meta": print_meta, "print_readably": print_readably, } if isinstance(o, bool): return _lrepr_bool(o) elif o is None: return _lrepr_nil(o) elif isinstance(o, str): return _lrepr_str( o, human_readable=human_readable, print_readably=print_readably ) elif isinstance(o, dict): return _lrepr_py_dict(o, **kwargs) elif isinstance(o, list): return _lrepr_py_list(o, **kwargs) elif isinstance(o, set): return _lrepr_py_set(o, **kwargs) elif isinstance(o, tuple): return _lrepr_py_tuple(o, **kwargs) elif isinstance(o, complex): return _lrepr_complex(o) elif isinstance(o, datetime.datetime): return _lrepr_datetime(o) elif isinstance(o, Decimal): return _lrepr_decimal(o, print_dup=print_dup) elif isinstance(o, Fraction): return _lrepr_fraction(o) elif isinstance(o, Pattern): return _lrepr_pattern(o) elif isinstance(o, uuid.UUID): return _lrepr_uuid(o) else: return repr(o)
[ "Fallback", "function", "for", "lrepr", "for", "subclasses", "of", "standard", "types", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/obj.py#L195-L246
[ "def", "_lrepr_fallback", "(", "# pylint: disable=too-many-arguments", "o", ":", "Any", ",", "human_readable", ":", "bool", "=", "False", ",", "print_dup", ":", "bool", "=", "PRINT_DUP", ",", "print_length", ":", "PrintCountSetting", "=", "PRINT_LENGTH", ",", "print_level", ":", "PrintCountSetting", "=", "PRINT_LEVEL", ",", "print_meta", ":", "bool", "=", "PRINT_META", ",", "print_readably", ":", "bool", "=", "PRINT_READABLY", ",", ")", "->", "str", ":", "# pragma: no cover", "kwargs", "=", "{", "\"human_readable\"", ":", "human_readable", ",", "\"print_dup\"", ":", "print_dup", ",", "\"print_length\"", ":", "print_length", ",", "\"print_level\"", ":", "print_level", ",", "\"print_meta\"", ":", "print_meta", ",", "\"print_readably\"", ":", "print_readably", ",", "}", "if", "isinstance", "(", "o", ",", "bool", ")", ":", "return", "_lrepr_bool", "(", "o", ")", "elif", "o", "is", "None", ":", "return", "_lrepr_nil", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "str", ")", ":", "return", "_lrepr_str", "(", "o", ",", "human_readable", "=", "human_readable", ",", "print_readably", "=", "print_readably", ")", "elif", "isinstance", "(", "o", ",", "dict", ")", ":", "return", "_lrepr_py_dict", "(", "o", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "o", ",", "list", ")", ":", "return", "_lrepr_py_list", "(", "o", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "o", ",", "set", ")", ":", "return", "_lrepr_py_set", "(", "o", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "o", ",", "tuple", ")", ":", "return", "_lrepr_py_tuple", "(", "o", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "o", ",", "complex", ")", ":", "return", "_lrepr_complex", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "datetime", ".", "datetime", ")", ":", "return", "_lrepr_datetime", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "Decimal", ")", ":", "return", "_lrepr_decimal", "(", "o", ",", "print_dup", "=", "print_dup", ")", "elif", "isinstance", "(", "o", ",", "Fraction", ")", ":", "return", "_lrepr_fraction", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "Pattern", ")", ":", "return", "_lrepr_pattern", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "uuid", ".", "UUID", ")", ":", "return", "_lrepr_uuid", "(", "o", ")", "else", ":", "return", "repr", "(", "o", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
Node.visit
Visit all immediate children of this node, calling f(child, *args, **kwargs) on each child.
src/basilisp/lang/compiler/nodes.py
def visit(self, f: Callable[..., None], *args, **kwargs): """Visit all immediate children of this node, calling f(child, *args, **kwargs) on each child.""" for child_kw in self.children: child_attr = munge(child_kw.name) if child_attr.endswith("s"): iter_child: Iterable[Node] = getattr(self, child_attr) assert iter_child is not None, "Listed child must not be none" for item in iter_child: f(item, *args, **kwargs) else: child: Node = getattr(self, child_attr) assert child is not None, "Listed child must not be none" f(child, *args, **kwargs)
def visit(self, f: Callable[..., None], *args, **kwargs): """Visit all immediate children of this node, calling f(child, *args, **kwargs) on each child.""" for child_kw in self.children: child_attr = munge(child_kw.name) if child_attr.endswith("s"): iter_child: Iterable[Node] = getattr(self, child_attr) assert iter_child is not None, "Listed child must not be none" for item in iter_child: f(item, *args, **kwargs) else: child: Node = getattr(self, child_attr) assert child is not None, "Listed child must not be none" f(child, *args, **kwargs)
[ "Visit", "all", "immediate", "children", "of", "this", "node", "calling", "f", "(", "child", "*", "args", "**", "kwargs", ")", "on", "each", "child", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/nodes.py#L163-L177
[ "def", "visit", "(", "self", ",", "f", ":", "Callable", "[", "...", ",", "None", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "child_kw", "in", "self", ".", "children", ":", "child_attr", "=", "munge", "(", "child_kw", ".", "name", ")", "if", "child_attr", ".", "endswith", "(", "\"s\"", ")", ":", "iter_child", ":", "Iterable", "[", "Node", "]", "=", "getattr", "(", "self", ",", "child_attr", ")", "assert", "iter_child", "is", "not", "None", ",", "\"Listed child must not be none\"", "for", "item", "in", "iter_child", ":", "f", "(", "item", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "child", ":", "Node", "=", "getattr", "(", "self", ",", "child_attr", ")", "assert", "child", "is", "not", "None", ",", "\"Listed child must not be none\"", "f", "(", "child", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
Node.fix_missing_locations
Return a transformed copy of this node with location in this node's environment updated to match the `start_loc` if given, or using its existing location otherwise. All child nodes will be recursively transformed and replaced. Child nodes will use their parent node location if they do not have one.
src/basilisp/lang/compiler/nodes.py
def fix_missing_locations( self, start_loc: Optional[Tuple[int, int]] = None ) -> "Node": """Return a transformed copy of this node with location in this node's environment updated to match the `start_loc` if given, or using its existing location otherwise. All child nodes will be recursively transformed and replaced. Child nodes will use their parent node location if they do not have one.""" if self.env.line is None or self.env.col is None: loc = start_loc else: loc = (self.env.line, self.env.col) assert loc is not None and all( [e is not None for e in loc] ), "Must specify location information" new_attrs: MutableMapping[str, Union[NodeEnv, Node, Iterable[Node]]] = { "env": attr.evolve(self.env, line=loc[0], col=loc[1]) } for child_kw in self.children: child_attr = munge(child_kw.name) assert child_attr != "env", "Node environment already set" if child_attr.endswith("s"): iter_child: Iterable[Node] = getattr(self, child_attr) assert iter_child is not None, "Listed child must not be none" new_children = [] for item in iter_child: new_children.append(item.fix_missing_locations(start_loc)) new_attrs[child_attr] = vec.vector(new_children) else: child: Node = getattr(self, child_attr) assert child is not None, "Listed child must not be none" new_attrs[child_attr] = child.fix_missing_locations(start_loc) return self.assoc(**new_attrs)
def fix_missing_locations( self, start_loc: Optional[Tuple[int, int]] = None ) -> "Node": """Return a transformed copy of this node with location in this node's environment updated to match the `start_loc` if given, or using its existing location otherwise. All child nodes will be recursively transformed and replaced. Child nodes will use their parent node location if they do not have one.""" if self.env.line is None or self.env.col is None: loc = start_loc else: loc = (self.env.line, self.env.col) assert loc is not None and all( [e is not None for e in loc] ), "Must specify location information" new_attrs: MutableMapping[str, Union[NodeEnv, Node, Iterable[Node]]] = { "env": attr.evolve(self.env, line=loc[0], col=loc[1]) } for child_kw in self.children: child_attr = munge(child_kw.name) assert child_attr != "env", "Node environment already set" if child_attr.endswith("s"): iter_child: Iterable[Node] = getattr(self, child_attr) assert iter_child is not None, "Listed child must not be none" new_children = [] for item in iter_child: new_children.append(item.fix_missing_locations(start_loc)) new_attrs[child_attr] = vec.vector(new_children) else: child: Node = getattr(self, child_attr) assert child is not None, "Listed child must not be none" new_attrs[child_attr] = child.fix_missing_locations(start_loc) return self.assoc(**new_attrs)
[ "Return", "a", "transformed", "copy", "of", "this", "node", "with", "location", "in", "this", "node", "s", "environment", "updated", "to", "match", "the", "start_loc", "if", "given", "or", "using", "its", "existing", "location", "otherwise", ".", "All", "child", "nodes", "will", "be", "recursively", "transformed", "and", "replaced", ".", "Child", "nodes", "will", "use", "their", "parent", "node", "location", "if", "they", "do", "not", "have", "one", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/nodes.py#L179-L215
[ "def", "fix_missing_locations", "(", "self", ",", "start_loc", ":", "Optional", "[", "Tuple", "[", "int", ",", "int", "]", "]", "=", "None", ")", "->", "\"Node\"", ":", "if", "self", ".", "env", ".", "line", "is", "None", "or", "self", ".", "env", ".", "col", "is", "None", ":", "loc", "=", "start_loc", "else", ":", "loc", "=", "(", "self", ".", "env", ".", "line", ",", "self", ".", "env", ".", "col", ")", "assert", "loc", "is", "not", "None", "and", "all", "(", "[", "e", "is", "not", "None", "for", "e", "in", "loc", "]", ")", ",", "\"Must specify location information\"", "new_attrs", ":", "MutableMapping", "[", "str", ",", "Union", "[", "NodeEnv", ",", "Node", ",", "Iterable", "[", "Node", "]", "]", "]", "=", "{", "\"env\"", ":", "attr", ".", "evolve", "(", "self", ".", "env", ",", "line", "=", "loc", "[", "0", "]", ",", "col", "=", "loc", "[", "1", "]", ")", "}", "for", "child_kw", "in", "self", ".", "children", ":", "child_attr", "=", "munge", "(", "child_kw", ".", "name", ")", "assert", "child_attr", "!=", "\"env\"", ",", "\"Node environment already set\"", "if", "child_attr", ".", "endswith", "(", "\"s\"", ")", ":", "iter_child", ":", "Iterable", "[", "Node", "]", "=", "getattr", "(", "self", ",", "child_attr", ")", "assert", "iter_child", "is", "not", "None", ",", "\"Listed child must not be none\"", "new_children", "=", "[", "]", "for", "item", "in", "iter_child", ":", "new_children", ".", "append", "(", "item", ".", "fix_missing_locations", "(", "start_loc", ")", ")", "new_attrs", "[", "child_attr", "]", "=", "vec", ".", "vector", "(", "new_children", ")", "else", ":", "child", ":", "Node", "=", "getattr", "(", "self", ",", "child_attr", ")", "assert", "child", "is", "not", "None", ",", "\"Listed child must not be none\"", "new_attrs", "[", "child_attr", "]", "=", "child", ".", "fix_missing_locations", "(", "start_loc", ")", "return", "self", ".", "assoc", "(", "*", "*", "new_attrs", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_emit_ast_string
Emit the generated Python AST string either to standard out or to the *generated-python* dynamic Var for the current namespace. If the BASILISP_EMIT_GENERATED_PYTHON env var is not set True, this method is a no-op.
src/basilisp/lang/compiler/__init__.py
def _emit_ast_string(module: ast.AST) -> None: # pragma: no cover """Emit the generated Python AST string either to standard out or to the *generated-python* dynamic Var for the current namespace. If the BASILISP_EMIT_GENERATED_PYTHON env var is not set True, this method is a no-op.""" # TODO: eventually, this default should become "false" but during this # period of heavy development, having it set to "true" by default # is tremendously useful if os.getenv("BASILISP_EMIT_GENERATED_PYTHON", "true") != "true": return if runtime.print_generated_python(): print(to_py_str(module)) else: runtime.add_generated_python(to_py_str(module))
def _emit_ast_string(module: ast.AST) -> None: # pragma: no cover """Emit the generated Python AST string either to standard out or to the *generated-python* dynamic Var for the current namespace. If the BASILISP_EMIT_GENERATED_PYTHON env var is not set True, this method is a no-op.""" # TODO: eventually, this default should become "false" but during this # period of heavy development, having it set to "true" by default # is tremendously useful if os.getenv("BASILISP_EMIT_GENERATED_PYTHON", "true") != "true": return if runtime.print_generated_python(): print(to_py_str(module)) else: runtime.add_generated_python(to_py_str(module))
[ "Emit", "the", "generated", "Python", "AST", "string", "either", "to", "standard", "out", "or", "to", "the", "*", "generated", "-", "python", "*", "dynamic", "Var", "for", "the", "current", "namespace", ".", "If", "the", "BASILISP_EMIT_GENERATED_PYTHON", "env", "var", "is", "not", "set", "True", "this", "method", "is", "a", "no", "-", "op", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L70-L84
[ "def", "_emit_ast_string", "(", "module", ":", "ast", ".", "AST", ")", "->", "None", ":", "# pragma: no cover", "# TODO: eventually, this default should become \"false\" but during this", "# period of heavy development, having it set to \"true\" by default", "# is tremendously useful", "if", "os", ".", "getenv", "(", "\"BASILISP_EMIT_GENERATED_PYTHON\"", ",", "\"true\"", ")", "!=", "\"true\"", ":", "return", "if", "runtime", ".", "print_generated_python", "(", ")", ":", "print", "(", "to_py_str", "(", "module", ")", ")", "else", ":", "runtime", ".", "add_generated_python", "(", "to_py_str", "(", "module", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
compile_and_exec_form
Compile and execute the given form. This function will be most useful for the REPL and testing purposes. Returns the result of the executed expression. Callers may override the wrapped function name, which is used by the REPL to evaluate the result of an expression and print it back out.
src/basilisp/lang/compiler/__init__.py
def compile_and_exec_form( # pylint: disable= too-many-arguments form: ReaderForm, ctx: CompilerContext, module: types.ModuleType, wrapped_fn_name: str = _DEFAULT_FN, collect_bytecode: Optional[BytecodeCollector] = None, ) -> Any: """Compile and execute the given form. This function will be most useful for the REPL and testing purposes. Returns the result of the executed expression. Callers may override the wrapped function name, which is used by the REPL to evaluate the result of an expression and print it back out.""" if form is None: return None if not module.__basilisp_bootstrapped__: # type: ignore _bootstrap_module(ctx.generator_context, ctx.py_ast_optimizer, module) final_wrapped_name = genname(wrapped_fn_name) lisp_ast = parse_ast(ctx.parser_context, form) py_ast = gen_py_ast(ctx.generator_context, lisp_ast) form_ast = list( map( _statementize, itertools.chain( py_ast.dependencies, [_expressionize(GeneratedPyAST(node=py_ast.node), final_wrapped_name)], ), ) ) ast_module = ast.Module(body=form_ast) ast_module = ctx.py_ast_optimizer.visit(ast_module) ast.fix_missing_locations(ast_module) _emit_ast_string(ast_module) bytecode = compile(ast_module, ctx.filename, "exec") if collect_bytecode: collect_bytecode(bytecode) exec(bytecode, module.__dict__) return getattr(module, final_wrapped_name)()
def compile_and_exec_form( # pylint: disable= too-many-arguments form: ReaderForm, ctx: CompilerContext, module: types.ModuleType, wrapped_fn_name: str = _DEFAULT_FN, collect_bytecode: Optional[BytecodeCollector] = None, ) -> Any: """Compile and execute the given form. This function will be most useful for the REPL and testing purposes. Returns the result of the executed expression. Callers may override the wrapped function name, which is used by the REPL to evaluate the result of an expression and print it back out.""" if form is None: return None if not module.__basilisp_bootstrapped__: # type: ignore _bootstrap_module(ctx.generator_context, ctx.py_ast_optimizer, module) final_wrapped_name = genname(wrapped_fn_name) lisp_ast = parse_ast(ctx.parser_context, form) py_ast = gen_py_ast(ctx.generator_context, lisp_ast) form_ast = list( map( _statementize, itertools.chain( py_ast.dependencies, [_expressionize(GeneratedPyAST(node=py_ast.node), final_wrapped_name)], ), ) ) ast_module = ast.Module(body=form_ast) ast_module = ctx.py_ast_optimizer.visit(ast_module) ast.fix_missing_locations(ast_module) _emit_ast_string(ast_module) bytecode = compile(ast_module, ctx.filename, "exec") if collect_bytecode: collect_bytecode(bytecode) exec(bytecode, module.__dict__) return getattr(module, final_wrapped_name)()
[ "Compile", "and", "execute", "the", "given", "form", ".", "This", "function", "will", "be", "most", "useful", "for", "the", "REPL", "and", "testing", "purposes", ".", "Returns", "the", "result", "of", "the", "executed", "expression", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L87-L129
[ "def", "compile_and_exec_form", "(", "# pylint: disable= too-many-arguments", "form", ":", "ReaderForm", ",", "ctx", ":", "CompilerContext", ",", "module", ":", "types", ".", "ModuleType", ",", "wrapped_fn_name", ":", "str", "=", "_DEFAULT_FN", ",", "collect_bytecode", ":", "Optional", "[", "BytecodeCollector", "]", "=", "None", ",", ")", "->", "Any", ":", "if", "form", "is", "None", ":", "return", "None", "if", "not", "module", ".", "__basilisp_bootstrapped__", ":", "# type: ignore", "_bootstrap_module", "(", "ctx", ".", "generator_context", ",", "ctx", ".", "py_ast_optimizer", ",", "module", ")", "final_wrapped_name", "=", "genname", "(", "wrapped_fn_name", ")", "lisp_ast", "=", "parse_ast", "(", "ctx", ".", "parser_context", ",", "form", ")", "py_ast", "=", "gen_py_ast", "(", "ctx", ".", "generator_context", ",", "lisp_ast", ")", "form_ast", "=", "list", "(", "map", "(", "_statementize", ",", "itertools", ".", "chain", "(", "py_ast", ".", "dependencies", ",", "[", "_expressionize", "(", "GeneratedPyAST", "(", "node", "=", "py_ast", ".", "node", ")", ",", "final_wrapped_name", ")", "]", ",", ")", ",", ")", ")", "ast_module", "=", "ast", ".", "Module", "(", "body", "=", "form_ast", ")", "ast_module", "=", "ctx", ".", "py_ast_optimizer", ".", "visit", "(", "ast_module", ")", "ast", ".", "fix_missing_locations", "(", "ast_module", ")", "_emit_ast_string", "(", "ast_module", ")", "bytecode", "=", "compile", "(", "ast_module", ",", "ctx", ".", "filename", ",", "\"exec\"", ")", "if", "collect_bytecode", ":", "collect_bytecode", "(", "bytecode", ")", "exec", "(", "bytecode", ",", "module", ".", "__dict__", ")", "return", "getattr", "(", "module", ",", "final_wrapped_name", ")", "(", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_incremental_compile_module
Incrementally compile a stream of AST nodes in module mod. The source_filename will be passed to Python's native compile. Incremental compilation is an integral part of generating a Python module during the same process as macro-expansion.
src/basilisp/lang/compiler/__init__.py
def _incremental_compile_module( optimizer: PythonASTOptimizer, py_ast: GeneratedPyAST, mod: types.ModuleType, source_filename: str, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Incrementally compile a stream of AST nodes in module mod. The source_filename will be passed to Python's native compile. Incremental compilation is an integral part of generating a Python module during the same process as macro-expansion.""" module_body = list( map(_statementize, itertools.chain(py_ast.dependencies, [py_ast.node])) ) module = ast.Module(body=list(module_body)) module = optimizer.visit(module) ast.fix_missing_locations(module) _emit_ast_string(module) bytecode = compile(module, source_filename, "exec") if collect_bytecode: collect_bytecode(bytecode) exec(bytecode, mod.__dict__)
def _incremental_compile_module( optimizer: PythonASTOptimizer, py_ast: GeneratedPyAST, mod: types.ModuleType, source_filename: str, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Incrementally compile a stream of AST nodes in module mod. The source_filename will be passed to Python's native compile. Incremental compilation is an integral part of generating a Python module during the same process as macro-expansion.""" module_body = list( map(_statementize, itertools.chain(py_ast.dependencies, [py_ast.node])) ) module = ast.Module(body=list(module_body)) module = optimizer.visit(module) ast.fix_missing_locations(module) _emit_ast_string(module) bytecode = compile(module, source_filename, "exec") if collect_bytecode: collect_bytecode(bytecode) exec(bytecode, mod.__dict__)
[ "Incrementally", "compile", "a", "stream", "of", "AST", "nodes", "in", "module", "mod", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L132-L158
[ "def", "_incremental_compile_module", "(", "optimizer", ":", "PythonASTOptimizer", ",", "py_ast", ":", "GeneratedPyAST", ",", "mod", ":", "types", ".", "ModuleType", ",", "source_filename", ":", "str", ",", "collect_bytecode", ":", "Optional", "[", "BytecodeCollector", "]", "=", "None", ",", ")", "->", "None", ":", "module_body", "=", "list", "(", "map", "(", "_statementize", ",", "itertools", ".", "chain", "(", "py_ast", ".", "dependencies", ",", "[", "py_ast", ".", "node", "]", ")", ")", ")", "module", "=", "ast", ".", "Module", "(", "body", "=", "list", "(", "module_body", ")", ")", "module", "=", "optimizer", ".", "visit", "(", "module", ")", "ast", ".", "fix_missing_locations", "(", "module", ")", "_emit_ast_string", "(", "module", ")", "bytecode", "=", "compile", "(", "module", ",", "source_filename", ",", "\"exec\"", ")", "if", "collect_bytecode", ":", "collect_bytecode", "(", "bytecode", ")", "exec", "(", "bytecode", ",", "mod", ".", "__dict__", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_bootstrap_module
Bootstrap a new module with imports and other boilerplate.
src/basilisp/lang/compiler/__init__.py
def _bootstrap_module( gctx: GeneratorContext, optimizer: PythonASTOptimizer, mod: types.ModuleType, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Bootstrap a new module with imports and other boilerplate.""" _incremental_compile_module( optimizer, py_module_preamble(gctx), mod, source_filename=gctx.filename, collect_bytecode=collect_bytecode, ) mod.__basilisp_bootstrapped__ = True
def _bootstrap_module( gctx: GeneratorContext, optimizer: PythonASTOptimizer, mod: types.ModuleType, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Bootstrap a new module with imports and other boilerplate.""" _incremental_compile_module( optimizer, py_module_preamble(gctx), mod, source_filename=gctx.filename, collect_bytecode=collect_bytecode, ) mod.__basilisp_bootstrapped__ = True
[ "Bootstrap", "a", "new", "module", "with", "imports", "and", "other", "boilerplate", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L161-L175
[ "def", "_bootstrap_module", "(", "gctx", ":", "GeneratorContext", ",", "optimizer", ":", "PythonASTOptimizer", ",", "mod", ":", "types", ".", "ModuleType", ",", "collect_bytecode", ":", "Optional", "[", "BytecodeCollector", "]", "=", "None", ",", ")", "->", "None", ":", "_incremental_compile_module", "(", "optimizer", ",", "py_module_preamble", "(", "gctx", ")", ",", "mod", ",", "source_filename", "=", "gctx", ".", "filename", ",", "collect_bytecode", "=", "collect_bytecode", ",", ")", "mod", ".", "__basilisp_bootstrapped__", "=", "True" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
compile_module
Compile an entire Basilisp module into Python bytecode which can be executed as a Python module. This function is designed to generate bytecode which can be used for the Basilisp import machinery, to allow callers to import Basilisp modules from Python code.
src/basilisp/lang/compiler/__init__.py
def compile_module( forms: Iterable[ReaderForm], ctx: CompilerContext, module: types.ModuleType, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Compile an entire Basilisp module into Python bytecode which can be executed as a Python module. This function is designed to generate bytecode which can be used for the Basilisp import machinery, to allow callers to import Basilisp modules from Python code. """ _bootstrap_module(ctx.generator_context, ctx.py_ast_optimizer, module) for form in forms: nodes = gen_py_ast(ctx.generator_context, parse_ast(ctx.parser_context, form)) _incremental_compile_module( ctx.py_ast_optimizer, nodes, module, source_filename=ctx.filename, collect_bytecode=collect_bytecode, )
def compile_module( forms: Iterable[ReaderForm], ctx: CompilerContext, module: types.ModuleType, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Compile an entire Basilisp module into Python bytecode which can be executed as a Python module. This function is designed to generate bytecode which can be used for the Basilisp import machinery, to allow callers to import Basilisp modules from Python code. """ _bootstrap_module(ctx.generator_context, ctx.py_ast_optimizer, module) for form in forms: nodes = gen_py_ast(ctx.generator_context, parse_ast(ctx.parser_context, form)) _incremental_compile_module( ctx.py_ast_optimizer, nodes, module, source_filename=ctx.filename, collect_bytecode=collect_bytecode, )
[ "Compile", "an", "entire", "Basilisp", "module", "into", "Python", "bytecode", "which", "can", "be", "executed", "as", "a", "Python", "module", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L178-L201
[ "def", "compile_module", "(", "forms", ":", "Iterable", "[", "ReaderForm", "]", ",", "ctx", ":", "CompilerContext", ",", "module", ":", "types", ".", "ModuleType", ",", "collect_bytecode", ":", "Optional", "[", "BytecodeCollector", "]", "=", "None", ",", ")", "->", "None", ":", "_bootstrap_module", "(", "ctx", ".", "generator_context", ",", "ctx", ".", "py_ast_optimizer", ",", "module", ")", "for", "form", "in", "forms", ":", "nodes", "=", "gen_py_ast", "(", "ctx", ".", "generator_context", ",", "parse_ast", "(", "ctx", ".", "parser_context", ",", "form", ")", ")", "_incremental_compile_module", "(", "ctx", ".", "py_ast_optimizer", ",", "nodes", ",", "module", ",", "source_filename", "=", "ctx", ".", "filename", ",", "collect_bytecode", "=", "collect_bytecode", ",", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
compile_bytecode
Compile cached bytecode into the given module. The Basilisp import hook attempts to cache bytecode while compiling Basilisp namespaces. When the cached bytecode is reloaded from disk, it needs to be compiled within a bootstrapped module. This function bootstraps the module and then proceeds to compile a collection of bytecodes into the module.
src/basilisp/lang/compiler/__init__.py
def compile_bytecode( code: List[types.CodeType], gctx: GeneratorContext, optimizer: PythonASTOptimizer, module: types.ModuleType, ) -> None: """Compile cached bytecode into the given module. The Basilisp import hook attempts to cache bytecode while compiling Basilisp namespaces. When the cached bytecode is reloaded from disk, it needs to be compiled within a bootstrapped module. This function bootstraps the module and then proceeds to compile a collection of bytecodes into the module.""" _bootstrap_module(gctx, optimizer, module) for bytecode in code: exec(bytecode, module.__dict__)
def compile_bytecode( code: List[types.CodeType], gctx: GeneratorContext, optimizer: PythonASTOptimizer, module: types.ModuleType, ) -> None: """Compile cached bytecode into the given module. The Basilisp import hook attempts to cache bytecode while compiling Basilisp namespaces. When the cached bytecode is reloaded from disk, it needs to be compiled within a bootstrapped module. This function bootstraps the module and then proceeds to compile a collection of bytecodes into the module.""" _bootstrap_module(gctx, optimizer, module) for bytecode in code: exec(bytecode, module.__dict__)
[ "Compile", "cached", "bytecode", "into", "the", "given", "module", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L204-L218
[ "def", "compile_bytecode", "(", "code", ":", "List", "[", "types", ".", "CodeType", "]", ",", "gctx", ":", "GeneratorContext", ",", "optimizer", ":", "PythonASTOptimizer", ",", "module", ":", "types", ".", "ModuleType", ",", ")", "->", "None", ":", "_bootstrap_module", "(", "gctx", ",", "optimizer", ",", "module", ")", "for", "bytecode", "in", "code", ":", "exec", "(", "bytecode", ",", "module", ".", "__dict__", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
sequence
Create a Sequence from Iterable s.
src/basilisp/lang/seq.py
def sequence(s: Iterable) -> ISeq[Any]: """Create a Sequence from Iterable s.""" try: i = iter(s) return _Sequence(i, next(i)) except StopIteration: return EMPTY
def sequence(s: Iterable) -> ISeq[Any]: """Create a Sequence from Iterable s.""" try: i = iter(s) return _Sequence(i, next(i)) except StopIteration: return EMPTY
[ "Create", "a", "Sequence", "from", "Iterable", "s", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/seq.py#L170-L176
[ "def", "sequence", "(", "s", ":", "Iterable", ")", "->", "ISeq", "[", "Any", "]", ":", "try", ":", "i", "=", "iter", "(", "s", ")", "return", "_Sequence", "(", "i", ",", "next", "(", "i", ")", ")", "except", "StopIteration", ":", "return", "EMPTY" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
munge
Replace characters which are not valid in Python symbols with valid replacement strings.
src/basilisp/lang/util.py
def munge(s: str, allow_builtins: bool = False) -> str: """Replace characters which are not valid in Python symbols with valid replacement strings.""" new_str = [] for c in s: new_str.append(_MUNGE_REPLACEMENTS.get(c, c)) new_s = "".join(new_str) if keyword.iskeyword(new_s): return f"{new_s}_" if not allow_builtins and new_s in builtins.__dict__: return f"{new_s}_" return new_s
def munge(s: str, allow_builtins: bool = False) -> str: """Replace characters which are not valid in Python symbols with valid replacement strings.""" new_str = [] for c in s: new_str.append(_MUNGE_REPLACEMENTS.get(c, c)) new_s = "".join(new_str) if keyword.iskeyword(new_s): return f"{new_s}_" if not allow_builtins and new_s in builtins.__dict__: return f"{new_s}_" return new_s
[ "Replace", "characters", "which", "are", "not", "valid", "in", "Python", "symbols", "with", "valid", "replacement", "strings", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/util.py#L34-L49
[ "def", "munge", "(", "s", ":", "str", ",", "allow_builtins", ":", "bool", "=", "False", ")", "->", "str", ":", "new_str", "=", "[", "]", "for", "c", "in", "s", ":", "new_str", ".", "append", "(", "_MUNGE_REPLACEMENTS", ".", "get", "(", "c", ",", "c", ")", ")", "new_s", "=", "\"\"", ".", "join", "(", "new_str", ")", "if", "keyword", ".", "iskeyword", "(", "new_s", ")", ":", "return", "f\"{new_s}_\"", "if", "not", "allow_builtins", "and", "new_s", "in", "builtins", ".", "__dict__", ":", "return", "f\"{new_s}_\"", "return", "new_s" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
demunge
Replace munged string components with their original representation.
src/basilisp/lang/util.py
def demunge(s: str) -> str: """Replace munged string components with their original representation.""" def demunge_replacer(match: Match) -> str: full_match = match.group(0) replacement = _DEMUNGE_REPLACEMENTS.get(full_match, None) if replacement: return replacement return full_match return re.sub(_DEMUNGE_PATTERN, demunge_replacer, s).replace("_", "-")
def demunge(s: str) -> str: """Replace munged string components with their original representation.""" def demunge_replacer(match: Match) -> str: full_match = match.group(0) replacement = _DEMUNGE_REPLACEMENTS.get(full_match, None) if replacement: return replacement return full_match return re.sub(_DEMUNGE_PATTERN, demunge_replacer, s).replace("_", "-")
[ "Replace", "munged", "string", "components", "with", "their", "original", "representation", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/util.py#L56-L67
[ "def", "demunge", "(", "s", ":", "str", ")", "->", "str", ":", "def", "demunge_replacer", "(", "match", ":", "Match", ")", "->", "str", ":", "full_match", "=", "match", ".", "group", "(", "0", ")", "replacement", "=", "_DEMUNGE_REPLACEMENTS", ".", "get", "(", "full_match", ",", "None", ")", "if", "replacement", ":", "return", "replacement", "return", "full_match", "return", "re", ".", "sub", "(", "_DEMUNGE_PATTERN", ",", "demunge_replacer", ",", "s", ")", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
fraction
Create a Fraction from a numerator and denominator.
src/basilisp/lang/util.py
def fraction(numerator: int, denominator: int) -> Fraction: """Create a Fraction from a numerator and denominator.""" return Fraction(numerator=numerator, denominator=denominator)
def fraction(numerator: int, denominator: int) -> Fraction: """Create a Fraction from a numerator and denominator.""" return Fraction(numerator=numerator, denominator=denominator)
[ "Create", "a", "Fraction", "from", "a", "numerator", "and", "denominator", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/util.py#L92-L94
[ "def", "fraction", "(", "numerator", ":", "int", ",", "denominator", ":", "int", ")", "->", "Fraction", ":", "return", "Fraction", "(", "numerator", "=", "numerator", ",", "denominator", "=", "denominator", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
get_handler
Get the default logging handler for Basilisp.
src/basilisp/logconfig.py
def get_handler(level: str, fmt: str) -> logging.Handler: """Get the default logging handler for Basilisp.""" handler: logging.Handler = logging.NullHandler() if os.getenv("BASILISP_USE_DEV_LOGGER") == "true": handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt)) handler.setLevel(level) return handler
def get_handler(level: str, fmt: str) -> logging.Handler: """Get the default logging handler for Basilisp.""" handler: logging.Handler = logging.NullHandler() if os.getenv("BASILISP_USE_DEV_LOGGER") == "true": handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt)) handler.setLevel(level) return handler
[ "Get", "the", "default", "logging", "handler", "for", "Basilisp", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/logconfig.py#L10-L18
[ "def", "get_handler", "(", "level", ":", "str", ",", "fmt", ":", "str", ")", "->", "logging", ".", "Handler", ":", "handler", ":", "logging", ".", "Handler", "=", "logging", ".", "NullHandler", "(", ")", "if", "os", ".", "getenv", "(", "\"BASILISP_USE_DEV_LOGGER\"", ")", "==", "\"true\"", ":", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "fmt", ")", ")", "handler", ".", "setLevel", "(", "level", ")", "return", "handler" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
map
Creates a new map.
src/basilisp/lang/map.py
def map(kvs: Mapping[K, V], meta=None) -> Map[K, V]: # pylint:disable=redefined-builtin """Creates a new map.""" return Map(pmap(initial=kvs), meta=meta)
def map(kvs: Mapping[K, V], meta=None) -> Map[K, V]: # pylint:disable=redefined-builtin """Creates a new map.""" return Map(pmap(initial=kvs), meta=meta)
[ "Creates", "a", "new", "map", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/map.py#L177-L179
[ "def", "map", "(", "kvs", ":", "Mapping", "[", "K", ",", "V", "]", ",", "meta", "=", "None", ")", "->", "Map", "[", "K", ",", "V", "]", ":", "# pylint:disable=redefined-builtin", "return", "Map", "(", "pmap", "(", "initial", "=", "kvs", ")", ",", "meta", "=", "meta", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
timed
Time the execution of code in the with-block, calling the function f (if it is given) with the resulting time in nanoseconds.
src/basilisp/util.py
def timed(f: Optional[Callable[[int], None]] = None): """Time the execution of code in the with-block, calling the function f (if it is given) with the resulting time in nanoseconds.""" start = time.perf_counter() yield end = time.perf_counter() if f: ns = int((end - start) * 1_000_000_000) f(ns)
def timed(f: Optional[Callable[[int], None]] = None): """Time the execution of code in the with-block, calling the function f (if it is given) with the resulting time in nanoseconds.""" start = time.perf_counter() yield end = time.perf_counter() if f: ns = int((end - start) * 1_000_000_000) f(ns)
[ "Time", "the", "execution", "of", "code", "in", "the", "with", "-", "block", "calling", "the", "function", "f", "(", "if", "it", "is", "given", ")", "with", "the", "resulting", "time", "in", "nanoseconds", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/util.py#L10-L18
[ "def", "timed", "(", "f", ":", "Optional", "[", "Callable", "[", "[", "int", "]", ",", "None", "]", "]", "=", "None", ")", ":", "start", "=", "time", ".", "perf_counter", "(", ")", "yield", "end", "=", "time", ".", "perf_counter", "(", ")", "if", "f", ":", "ns", "=", "int", "(", "(", "end", "-", "start", ")", "*", "1_000_000_000", ")", "f", "(", "ns", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
partition
Partition coll into groups of size n.
src/basilisp/util.py
def partition(coll, n: int): """Partition coll into groups of size n.""" assert n > 0 start = 0 stop = n while stop <= len(coll): yield tuple(e for e in coll[start:stop]) start += n stop += n if start < len(coll) < stop: stop = len(coll) yield tuple(e for e in coll[start:stop])
def partition(coll, n: int): """Partition coll into groups of size n.""" assert n > 0 start = 0 stop = n while stop <= len(coll): yield tuple(e for e in coll[start:stop]) start += n stop += n if start < len(coll) < stop: stop = len(coll) yield tuple(e for e in coll[start:stop])
[ "Partition", "coll", "into", "groups", "of", "size", "n", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/util.py#L76-L87
[ "def", "partition", "(", "coll", ",", "n", ":", "int", ")", ":", "assert", "n", ">", "0", "start", "=", "0", "stop", "=", "n", "while", "stop", "<=", "len", "(", "coll", ")", ":", "yield", "tuple", "(", "e", "for", "e", "in", "coll", "[", "start", ":", "stop", "]", ")", "start", "+=", "n", "stop", "+=", "n", "if", "start", "<", "len", "(", "coll", ")", "<", "stop", ":", "stop", "=", "len", "(", "coll", ")", "yield", "tuple", "(", "e", "for", "e", "in", "coll", "[", "start", ":", "stop", "]", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_with_loc
Wrap a reader function in a decorator to supply line and column information along with relevant forms.
src/basilisp/lang/reader.py
def _with_loc(f: W) -> W: """Wrap a reader function in a decorator to supply line and column information along with relevant forms.""" @functools.wraps(f) def with_lineno_and_col(ctx): meta = lmap.map( {READER_LINE_KW: ctx.reader.line, READER_COL_KW: ctx.reader.col} ) v = f(ctx) try: return v.with_meta(meta) # type: ignore except AttributeError: return v return cast(W, with_lineno_and_col)
def _with_loc(f: W) -> W: """Wrap a reader function in a decorator to supply line and column information along with relevant forms.""" @functools.wraps(f) def with_lineno_and_col(ctx): meta = lmap.map( {READER_LINE_KW: ctx.reader.line, READER_COL_KW: ctx.reader.col} ) v = f(ctx) try: return v.with_meta(meta) # type: ignore except AttributeError: return v return cast(W, with_lineno_and_col)
[ "Wrap", "a", "reader", "function", "in", "a", "decorator", "to", "supply", "line", "and", "column", "information", "along", "with", "relevant", "forms", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L306-L321
[ "def", "_with_loc", "(", "f", ":", "W", ")", "->", "W", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "with_lineno_and_col", "(", "ctx", ")", ":", "meta", "=", "lmap", ".", "map", "(", "{", "READER_LINE_KW", ":", "ctx", ".", "reader", ".", "line", ",", "READER_COL_KW", ":", "ctx", ".", "reader", ".", "col", "}", ")", "v", "=", "f", "(", "ctx", ")", "try", ":", "return", "v", ".", "with_meta", "(", "meta", ")", "# type: ignore", "except", "AttributeError", ":", "return", "v", "return", "cast", "(", "W", ",", "with_lineno_and_col", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_namespaced
Read a namespaced token from the input stream.
src/basilisp/lang/reader.py
def _read_namespaced( ctx: ReaderContext, allowed_suffix: Optional[str] = None ) -> Tuple[Optional[str], str]: """Read a namespaced token from the input stream.""" ns: List[str] = [] name: List[str] = [] reader = ctx.reader has_ns = False while True: token = reader.peek() if token == "/": reader.next_token() if has_ns: raise SyntaxError("Found '/'; expected word character") elif len(name) == 0: name.append("/") else: if "/" in name: raise SyntaxError("Found '/' after '/'") has_ns = True ns = name name = [] elif ns_name_chars.match(token): reader.next_token() name.append(token) elif allowed_suffix is not None and token == allowed_suffix: reader.next_token() name.append(token) else: break ns_str = None if not has_ns else "".join(ns) name_str = "".join(name) # A small exception for the symbol '/ used for division if ns_str is None: if "/" in name_str and name_str != "/": raise SyntaxError("'/' character disallowed in names") assert ns_str is None or len(ns_str) > 0 return ns_str, name_str
def _read_namespaced( ctx: ReaderContext, allowed_suffix: Optional[str] = None ) -> Tuple[Optional[str], str]: """Read a namespaced token from the input stream.""" ns: List[str] = [] name: List[str] = [] reader = ctx.reader has_ns = False while True: token = reader.peek() if token == "/": reader.next_token() if has_ns: raise SyntaxError("Found '/'; expected word character") elif len(name) == 0: name.append("/") else: if "/" in name: raise SyntaxError("Found '/' after '/'") has_ns = True ns = name name = [] elif ns_name_chars.match(token): reader.next_token() name.append(token) elif allowed_suffix is not None and token == allowed_suffix: reader.next_token() name.append(token) else: break ns_str = None if not has_ns else "".join(ns) name_str = "".join(name) # A small exception for the symbol '/ used for division if ns_str is None: if "/" in name_str and name_str != "/": raise SyntaxError("'/' character disallowed in names") assert ns_str is None or len(ns_str) > 0 return ns_str, name_str
[ "Read", "a", "namespaced", "token", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L324-L365
[ "def", "_read_namespaced", "(", "ctx", ":", "ReaderContext", ",", "allowed_suffix", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "str", "]", ":", "ns", ":", "List", "[", "str", "]", "=", "[", "]", "name", ":", "List", "[", "str", "]", "=", "[", "]", "reader", "=", "ctx", ".", "reader", "has_ns", "=", "False", "while", "True", ":", "token", "=", "reader", ".", "peek", "(", ")", "if", "token", "==", "\"/\"", ":", "reader", ".", "next_token", "(", ")", "if", "has_ns", ":", "raise", "SyntaxError", "(", "\"Found '/'; expected word character\"", ")", "elif", "len", "(", "name", ")", "==", "0", ":", "name", ".", "append", "(", "\"/\"", ")", "else", ":", "if", "\"/\"", "in", "name", ":", "raise", "SyntaxError", "(", "\"Found '/' after '/'\"", ")", "has_ns", "=", "True", "ns", "=", "name", "name", "=", "[", "]", "elif", "ns_name_chars", ".", "match", "(", "token", ")", ":", "reader", ".", "next_token", "(", ")", "name", ".", "append", "(", "token", ")", "elif", "allowed_suffix", "is", "not", "None", "and", "token", "==", "allowed_suffix", ":", "reader", ".", "next_token", "(", ")", "name", ".", "append", "(", "token", ")", "else", ":", "break", "ns_str", "=", "None", "if", "not", "has_ns", "else", "\"\"", ".", "join", "(", "ns", ")", "name_str", "=", "\"\"", ".", "join", "(", "name", ")", "# A small exception for the symbol '/ used for division", "if", "ns_str", "is", "None", ":", "if", "\"/\"", "in", "name_str", "and", "name_str", "!=", "\"/\"", ":", "raise", "SyntaxError", "(", "\"'/' character disallowed in names\"", ")", "assert", "ns_str", "is", "None", "or", "len", "(", "ns_str", ")", ">", "0", "return", "ns_str", ",", "name_str" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_coll
Read a collection from the input stream and create the collection using f.
src/basilisp/lang/reader.py
def _read_coll( ctx: ReaderContext, f: Callable[[Collection[Any]], Union[llist.List, lset.Set, vector.Vector]], end_token: str, coll_name: str, ): """Read a collection from the input stream and create the collection using f.""" coll: List = [] reader = ctx.reader while True: token = reader.peek() if token == "": raise SyntaxError(f"Unexpected EOF in {coll_name}") if whitespace_chars.match(token): reader.advance() continue if token == end_token: reader.next_token() return f(coll) elem = _read_next(ctx) if elem is COMMENT: continue coll.append(elem)
def _read_coll( ctx: ReaderContext, f: Callable[[Collection[Any]], Union[llist.List, lset.Set, vector.Vector]], end_token: str, coll_name: str, ): """Read a collection from the input stream and create the collection using f.""" coll: List = [] reader = ctx.reader while True: token = reader.peek() if token == "": raise SyntaxError(f"Unexpected EOF in {coll_name}") if whitespace_chars.match(token): reader.advance() continue if token == end_token: reader.next_token() return f(coll) elem = _read_next(ctx) if elem is COMMENT: continue coll.append(elem)
[ "Read", "a", "collection", "from", "the", "input", "stream", "and", "create", "the", "collection", "using", "f", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L368-L391
[ "def", "_read_coll", "(", "ctx", ":", "ReaderContext", ",", "f", ":", "Callable", "[", "[", "Collection", "[", "Any", "]", "]", ",", "Union", "[", "llist", ".", "List", ",", "lset", ".", "Set", ",", "vector", ".", "Vector", "]", "]", ",", "end_token", ":", "str", ",", "coll_name", ":", "str", ",", ")", ":", "coll", ":", "List", "=", "[", "]", "reader", "=", "ctx", ".", "reader", "while", "True", ":", "token", "=", "reader", ".", "peek", "(", ")", "if", "token", "==", "\"\"", ":", "raise", "SyntaxError", "(", "f\"Unexpected EOF in {coll_name}\"", ")", "if", "whitespace_chars", ".", "match", "(", "token", ")", ":", "reader", ".", "advance", "(", ")", "continue", "if", "token", "==", "end_token", ":", "reader", ".", "next_token", "(", ")", "return", "f", "(", "coll", ")", "elem", "=", "_read_next", "(", "ctx", ")", "if", "elem", "is", "COMMENT", ":", "continue", "coll", ".", "append", "(", "elem", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_list
Read a list element from the input stream.
src/basilisp/lang/reader.py
def _read_list(ctx: ReaderContext) -> llist.List: """Read a list element from the input stream.""" start = ctx.reader.advance() assert start == "(" return _read_coll(ctx, llist.list, ")", "list")
def _read_list(ctx: ReaderContext) -> llist.List: """Read a list element from the input stream.""" start = ctx.reader.advance() assert start == "(" return _read_coll(ctx, llist.list, ")", "list")
[ "Read", "a", "list", "element", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L401-L405
[ "def", "_read_list", "(", "ctx", ":", "ReaderContext", ")", "->", "llist", ".", "List", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"(\"", "return", "_read_coll", "(", "ctx", ",", "llist", ".", "list", ",", "\")\"", ",", "\"list\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_vector
Read a vector element from the input stream.
src/basilisp/lang/reader.py
def _read_vector(ctx: ReaderContext) -> vector.Vector: """Read a vector element from the input stream.""" start = ctx.reader.advance() assert start == "[" return _read_coll(ctx, vector.vector, "]", "vector")
def _read_vector(ctx: ReaderContext) -> vector.Vector: """Read a vector element from the input stream.""" start = ctx.reader.advance() assert start == "[" return _read_coll(ctx, vector.vector, "]", "vector")
[ "Read", "a", "vector", "element", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L409-L413
[ "def", "_read_vector", "(", "ctx", ":", "ReaderContext", ")", "->", "vector", ".", "Vector", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"[\"", "return", "_read_coll", "(", "ctx", ",", "vector", ".", "vector", ",", "\"]\"", ",", "\"vector\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_set
Return a set from the input stream.
src/basilisp/lang/reader.py
def _read_set(ctx: ReaderContext) -> lset.Set: """Return a set from the input stream.""" start = ctx.reader.advance() assert start == "{" def set_if_valid(s: Collection) -> lset.Set: if len(s) != len(set(s)): raise SyntaxError("Duplicated values in set") return lset.set(s) return _read_coll(ctx, set_if_valid, "}", "set")
def _read_set(ctx: ReaderContext) -> lset.Set: """Return a set from the input stream.""" start = ctx.reader.advance() assert start == "{" def set_if_valid(s: Collection) -> lset.Set: if len(s) != len(set(s)): raise SyntaxError("Duplicated values in set") return lset.set(s) return _read_coll(ctx, set_if_valid, "}", "set")
[ "Return", "a", "set", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L417-L427
[ "def", "_read_set", "(", "ctx", ":", "ReaderContext", ")", "->", "lset", ".", "Set", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"{\"", "def", "set_if_valid", "(", "s", ":", "Collection", ")", "->", "lset", ".", "Set", ":", "if", "len", "(", "s", ")", "!=", "len", "(", "set", "(", "s", ")", ")", ":", "raise", "SyntaxError", "(", "\"Duplicated values in set\"", ")", "return", "lset", ".", "set", "(", "s", ")", "return", "_read_coll", "(", "ctx", ",", "set_if_valid", ",", "\"}\"", ",", "\"set\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_map
Return a map from the input stream.
src/basilisp/lang/reader.py
def _read_map(ctx: ReaderContext) -> lmap.Map: """Return a map from the input stream.""" reader = ctx.reader start = reader.advance() assert start == "{" d: MutableMapping[Any, Any] = {} while True: if reader.peek() == "}": reader.next_token() break k = _read_next(ctx) if k is COMMENT: continue while True: if reader.peek() == "}": raise SyntaxError("Unexpected token '}'; expected map value") v = _read_next(ctx) if v is COMMENT: continue if k in d: raise SyntaxError(f"Duplicate key '{k}' in map literal") break d[k] = v return lmap.map(d)
def _read_map(ctx: ReaderContext) -> lmap.Map: """Return a map from the input stream.""" reader = ctx.reader start = reader.advance() assert start == "{" d: MutableMapping[Any, Any] = {} while True: if reader.peek() == "}": reader.next_token() break k = _read_next(ctx) if k is COMMENT: continue while True: if reader.peek() == "}": raise SyntaxError("Unexpected token '}'; expected map value") v = _read_next(ctx) if v is COMMENT: continue if k in d: raise SyntaxError(f"Duplicate key '{k}' in map literal") break d[k] = v return lmap.map(d)
[ "Return", "a", "map", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L431-L455
[ "def", "_read_map", "(", "ctx", ":", "ReaderContext", ")", "->", "lmap", ".", "Map", ":", "reader", "=", "ctx", ".", "reader", "start", "=", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"{\"", "d", ":", "MutableMapping", "[", "Any", ",", "Any", "]", "=", "{", "}", "while", "True", ":", "if", "reader", ".", "peek", "(", ")", "==", "\"}\"", ":", "reader", ".", "next_token", "(", ")", "break", "k", "=", "_read_next", "(", "ctx", ")", "if", "k", "is", "COMMENT", ":", "continue", "while", "True", ":", "if", "reader", ".", "peek", "(", ")", "==", "\"}\"", ":", "raise", "SyntaxError", "(", "\"Unexpected token '}'; expected map value\"", ")", "v", "=", "_read_next", "(", "ctx", ")", "if", "v", "is", "COMMENT", ":", "continue", "if", "k", "in", "d", ":", "raise", "SyntaxError", "(", "f\"Duplicate key '{k}' in map literal\"", ")", "break", "d", "[", "k", "]", "=", "v", "return", "lmap", ".", "map", "(", "d", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_num
Return a numeric (complex, Decimal, float, int, Fraction) from the input stream.
src/basilisp/lang/reader.py
def _read_num( # noqa: C901 # pylint: disable=too-many-statements ctx: ReaderContext ) -> MaybeNumber: """Return a numeric (complex, Decimal, float, int, Fraction) from the input stream.""" chars: List[str] = [] reader = ctx.reader is_complex = False is_decimal = False is_float = False is_integer = False is_ratio = False while True: token = reader.peek() if token == "-": following_token = reader.next_token() if not begin_num_chars.match(following_token): reader.pushback() try: for _ in chars: reader.pushback() except IndexError: raise SyntaxError( "Requested to pushback too many characters onto StreamReader" ) return _read_sym(ctx) chars.append(token) continue elif token == ".": if is_float: raise SyntaxError("Found extra '.' in float; expected decimal portion") is_float = True elif token == "J": if is_complex: raise SyntaxError("Found extra 'J' suffix in complex literal") is_complex = True elif token == "M": if is_decimal: raise SyntaxError("Found extra 'M' suffix in decimal literal") is_decimal = True elif token == "N": if is_integer: raise SyntaxError("Found extra 'N' suffix in integer literal") is_integer = True elif token == "/": if is_ratio: raise SyntaxError("Found extra '/' in ratio literal") is_ratio = True elif not num_chars.match(token): break reader.next_token() chars.append(token) assert len(chars) > 0, "Must have at least one digit in integer or float" s = "".join(chars) if ( sum( [ is_complex and is_decimal, is_complex and is_integer, is_complex and is_ratio, is_decimal or is_float, is_integer, is_ratio, ] ) > 1 ): raise SyntaxError(f"Invalid number format: {s}") if is_complex: imaginary = float(s[:-1]) if is_float else int(s[:-1]) return complex(0, imaginary) elif is_decimal: try: return decimal.Decimal(s[:-1]) except decimal.InvalidOperation: raise SyntaxError(f"Invalid number format: {s}") from None elif is_float: return float(s) elif is_ratio: assert "/" in s, "Ratio must contain one '/' character" num, denominator = s.split("/") return Fraction(numerator=int(num), denominator=int(denominator)) elif is_integer: return int(s[:-1]) return int(s)
def _read_num( # noqa: C901 # pylint: disable=too-many-statements ctx: ReaderContext ) -> MaybeNumber: """Return a numeric (complex, Decimal, float, int, Fraction) from the input stream.""" chars: List[str] = [] reader = ctx.reader is_complex = False is_decimal = False is_float = False is_integer = False is_ratio = False while True: token = reader.peek() if token == "-": following_token = reader.next_token() if not begin_num_chars.match(following_token): reader.pushback() try: for _ in chars: reader.pushback() except IndexError: raise SyntaxError( "Requested to pushback too many characters onto StreamReader" ) return _read_sym(ctx) chars.append(token) continue elif token == ".": if is_float: raise SyntaxError("Found extra '.' in float; expected decimal portion") is_float = True elif token == "J": if is_complex: raise SyntaxError("Found extra 'J' suffix in complex literal") is_complex = True elif token == "M": if is_decimal: raise SyntaxError("Found extra 'M' suffix in decimal literal") is_decimal = True elif token == "N": if is_integer: raise SyntaxError("Found extra 'N' suffix in integer literal") is_integer = True elif token == "/": if is_ratio: raise SyntaxError("Found extra '/' in ratio literal") is_ratio = True elif not num_chars.match(token): break reader.next_token() chars.append(token) assert len(chars) > 0, "Must have at least one digit in integer or float" s = "".join(chars) if ( sum( [ is_complex and is_decimal, is_complex and is_integer, is_complex and is_ratio, is_decimal or is_float, is_integer, is_ratio, ] ) > 1 ): raise SyntaxError(f"Invalid number format: {s}") if is_complex: imaginary = float(s[:-1]) if is_float else int(s[:-1]) return complex(0, imaginary) elif is_decimal: try: return decimal.Decimal(s[:-1]) except decimal.InvalidOperation: raise SyntaxError(f"Invalid number format: {s}") from None elif is_float: return float(s) elif is_ratio: assert "/" in s, "Ratio must contain one '/' character" num, denominator = s.split("/") return Fraction(numerator=int(num), denominator=int(denominator)) elif is_integer: return int(s[:-1]) return int(s)
[ "Return", "a", "numeric", "(", "complex", "Decimal", "float", "int", "Fraction", ")", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L465-L552
[ "def", "_read_num", "(", "# noqa: C901 # pylint: disable=too-many-statements", "ctx", ":", "ReaderContext", ")", "->", "MaybeNumber", ":", "chars", ":", "List", "[", "str", "]", "=", "[", "]", "reader", "=", "ctx", ".", "reader", "is_complex", "=", "False", "is_decimal", "=", "False", "is_float", "=", "False", "is_integer", "=", "False", "is_ratio", "=", "False", "while", "True", ":", "token", "=", "reader", ".", "peek", "(", ")", "if", "token", "==", "\"-\"", ":", "following_token", "=", "reader", ".", "next_token", "(", ")", "if", "not", "begin_num_chars", ".", "match", "(", "following_token", ")", ":", "reader", ".", "pushback", "(", ")", "try", ":", "for", "_", "in", "chars", ":", "reader", ".", "pushback", "(", ")", "except", "IndexError", ":", "raise", "SyntaxError", "(", "\"Requested to pushback too many characters onto StreamReader\"", ")", "return", "_read_sym", "(", "ctx", ")", "chars", ".", "append", "(", "token", ")", "continue", "elif", "token", "==", "\".\"", ":", "if", "is_float", ":", "raise", "SyntaxError", "(", "\"Found extra '.' in float; expected decimal portion\"", ")", "is_float", "=", "True", "elif", "token", "==", "\"J\"", ":", "if", "is_complex", ":", "raise", "SyntaxError", "(", "\"Found extra 'J' suffix in complex literal\"", ")", "is_complex", "=", "True", "elif", "token", "==", "\"M\"", ":", "if", "is_decimal", ":", "raise", "SyntaxError", "(", "\"Found extra 'M' suffix in decimal literal\"", ")", "is_decimal", "=", "True", "elif", "token", "==", "\"N\"", ":", "if", "is_integer", ":", "raise", "SyntaxError", "(", "\"Found extra 'N' suffix in integer literal\"", ")", "is_integer", "=", "True", "elif", "token", "==", "\"/\"", ":", "if", "is_ratio", ":", "raise", "SyntaxError", "(", "\"Found extra '/' in ratio literal\"", ")", "is_ratio", "=", "True", "elif", "not", "num_chars", ".", "match", "(", "token", ")", ":", "break", "reader", ".", "next_token", "(", ")", "chars", ".", "append", "(", "token", ")", "assert", "len", "(", "chars", ")", ">", "0", ",", "\"Must have at least one digit in integer or float\"", "s", "=", "\"\"", ".", "join", "(", "chars", ")", "if", "(", "sum", "(", "[", "is_complex", "and", "is_decimal", ",", "is_complex", "and", "is_integer", ",", "is_complex", "and", "is_ratio", ",", "is_decimal", "or", "is_float", ",", "is_integer", ",", "is_ratio", ",", "]", ")", ">", "1", ")", ":", "raise", "SyntaxError", "(", "f\"Invalid number format: {s}\"", ")", "if", "is_complex", ":", "imaginary", "=", "float", "(", "s", "[", ":", "-", "1", "]", ")", "if", "is_float", "else", "int", "(", "s", "[", ":", "-", "1", "]", ")", "return", "complex", "(", "0", ",", "imaginary", ")", "elif", "is_decimal", ":", "try", ":", "return", "decimal", ".", "Decimal", "(", "s", "[", ":", "-", "1", "]", ")", "except", "decimal", ".", "InvalidOperation", ":", "raise", "SyntaxError", "(", "f\"Invalid number format: {s}\"", ")", "from", "None", "elif", "is_float", ":", "return", "float", "(", "s", ")", "elif", "is_ratio", ":", "assert", "\"/\"", "in", "s", ",", "\"Ratio must contain one '/' character\"", "num", ",", "denominator", "=", "s", ".", "split", "(", "\"/\"", ")", "return", "Fraction", "(", "numerator", "=", "int", "(", "num", ")", ",", "denominator", "=", "int", "(", "denominator", ")", ")", "elif", "is_integer", ":", "return", "int", "(", "s", "[", ":", "-", "1", "]", ")", "return", "int", "(", "s", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_str
Return a string from the input stream. If allow_arbitrary_escapes is True, do not throw a SyntaxError if an unknown escape sequence is encountered.
src/basilisp/lang/reader.py
def _read_str(ctx: ReaderContext, allow_arbitrary_escapes: bool = False) -> str: """Return a string from the input stream. If allow_arbitrary_escapes is True, do not throw a SyntaxError if an unknown escape sequence is encountered.""" s: List[str] = [] reader = ctx.reader while True: token = reader.next_token() if token == "": raise SyntaxError("Unexpected EOF in string") if token == "\\": token = reader.next_token() escape_char = _STR_ESCAPE_CHARS.get(token, None) if escape_char: s.append(escape_char) continue if allow_arbitrary_escapes: s.append("\\") else: raise SyntaxError("Unknown escape sequence: \\{token}") if token == '"': reader.next_token() return "".join(s) s.append(token)
def _read_str(ctx: ReaderContext, allow_arbitrary_escapes: bool = False) -> str: """Return a string from the input stream. If allow_arbitrary_escapes is True, do not throw a SyntaxError if an unknown escape sequence is encountered.""" s: List[str] = [] reader = ctx.reader while True: token = reader.next_token() if token == "": raise SyntaxError("Unexpected EOF in string") if token == "\\": token = reader.next_token() escape_char = _STR_ESCAPE_CHARS.get(token, None) if escape_char: s.append(escape_char) continue if allow_arbitrary_escapes: s.append("\\") else: raise SyntaxError("Unknown escape sequence: \\{token}") if token == '"': reader.next_token() return "".join(s) s.append(token)
[ "Return", "a", "string", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L568-L592
[ "def", "_read_str", "(", "ctx", ":", "ReaderContext", ",", "allow_arbitrary_escapes", ":", "bool", "=", "False", ")", "->", "str", ":", "s", ":", "List", "[", "str", "]", "=", "[", "]", "reader", "=", "ctx", ".", "reader", "while", "True", ":", "token", "=", "reader", ".", "next_token", "(", ")", "if", "token", "==", "\"\"", ":", "raise", "SyntaxError", "(", "\"Unexpected EOF in string\"", ")", "if", "token", "==", "\"\\\\\"", ":", "token", "=", "reader", ".", "next_token", "(", ")", "escape_char", "=", "_STR_ESCAPE_CHARS", ".", "get", "(", "token", ",", "None", ")", "if", "escape_char", ":", "s", ".", "append", "(", "escape_char", ")", "continue", "if", "allow_arbitrary_escapes", ":", "s", ".", "append", "(", "\"\\\\\"", ")", "else", ":", "raise", "SyntaxError", "(", "\"Unknown escape sequence: \\\\{token}\"", ")", "if", "token", "==", "'\"'", ":", "reader", ".", "next_token", "(", ")", "return", "\"\"", ".", "join", "(", "s", ")", "s", ".", "append", "(", "token", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_sym
Return a symbol from the input stream. If a symbol appears in a syntax quoted form, the reader will attempt to resolve the symbol using the resolver in the ReaderContext `ctx`. The resolver will look into the current namespace for an alias or namespace matching the symbol's namespace.
src/basilisp/lang/reader.py
def _read_sym(ctx: ReaderContext) -> MaybeSymbol: """Return a symbol from the input stream. If a symbol appears in a syntax quoted form, the reader will attempt to resolve the symbol using the resolver in the ReaderContext `ctx`. The resolver will look into the current namespace for an alias or namespace matching the symbol's namespace.""" ns, name = _read_namespaced(ctx, allowed_suffix="#") if not ctx.is_syntax_quoted and name.endswith("#"): raise SyntaxError("Gensym may not appear outside syntax quote") if ns is not None: if any(map(lambda s: len(s) == 0, ns.split("."))): raise SyntaxError( "All '.' separated segments of a namespace " "must contain at least one character." ) if name.startswith(".") and ns is not None: raise SyntaxError("Symbols starting with '.' may not have a namespace") if ns is None: if name == "nil": return None elif name == "true": return True elif name == "false": return False if ctx.is_syntax_quoted and not name.endswith("#"): return ctx.resolve(symbol.symbol(name, ns)) return symbol.symbol(name, ns=ns)
def _read_sym(ctx: ReaderContext) -> MaybeSymbol: """Return a symbol from the input stream. If a symbol appears in a syntax quoted form, the reader will attempt to resolve the symbol using the resolver in the ReaderContext `ctx`. The resolver will look into the current namespace for an alias or namespace matching the symbol's namespace.""" ns, name = _read_namespaced(ctx, allowed_suffix="#") if not ctx.is_syntax_quoted and name.endswith("#"): raise SyntaxError("Gensym may not appear outside syntax quote") if ns is not None: if any(map(lambda s: len(s) == 0, ns.split("."))): raise SyntaxError( "All '.' separated segments of a namespace " "must contain at least one character." ) if name.startswith(".") and ns is not None: raise SyntaxError("Symbols starting with '.' may not have a namespace") if ns is None: if name == "nil": return None elif name == "true": return True elif name == "false": return False if ctx.is_syntax_quoted and not name.endswith("#"): return ctx.resolve(symbol.symbol(name, ns)) return symbol.symbol(name, ns=ns)
[ "Return", "a", "symbol", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L596-L623
[ "def", "_read_sym", "(", "ctx", ":", "ReaderContext", ")", "->", "MaybeSymbol", ":", "ns", ",", "name", "=", "_read_namespaced", "(", "ctx", ",", "allowed_suffix", "=", "\"#\"", ")", "if", "not", "ctx", ".", "is_syntax_quoted", "and", "name", ".", "endswith", "(", "\"#\"", ")", ":", "raise", "SyntaxError", "(", "\"Gensym may not appear outside syntax quote\"", ")", "if", "ns", "is", "not", "None", ":", "if", "any", "(", "map", "(", "lambda", "s", ":", "len", "(", "s", ")", "==", "0", ",", "ns", ".", "split", "(", "\".\"", ")", ")", ")", ":", "raise", "SyntaxError", "(", "\"All '.' separated segments of a namespace \"", "\"must contain at least one character.\"", ")", "if", "name", ".", "startswith", "(", "\".\"", ")", "and", "ns", "is", "not", "None", ":", "raise", "SyntaxError", "(", "\"Symbols starting with '.' may not have a namespace\"", ")", "if", "ns", "is", "None", ":", "if", "name", "==", "\"nil\"", ":", "return", "None", "elif", "name", "==", "\"true\"", ":", "return", "True", "elif", "name", "==", "\"false\"", ":", "return", "False", "if", "ctx", ".", "is_syntax_quoted", "and", "not", "name", ".", "endswith", "(", "\"#\"", ")", ":", "return", "ctx", ".", "resolve", "(", "symbol", ".", "symbol", "(", "name", ",", "ns", ")", ")", "return", "symbol", ".", "symbol", "(", "name", ",", "ns", "=", "ns", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_kw
Return a keyword from the input stream.
src/basilisp/lang/reader.py
def _read_kw(ctx: ReaderContext) -> keyword.Keyword: """Return a keyword from the input stream.""" start = ctx.reader.advance() assert start == ":" ns, name = _read_namespaced(ctx) if "." in name: raise SyntaxError("Found '.' in keyword name") return keyword.keyword(name, ns=ns)
def _read_kw(ctx: ReaderContext) -> keyword.Keyword: """Return a keyword from the input stream.""" start = ctx.reader.advance() assert start == ":" ns, name = _read_namespaced(ctx) if "." in name: raise SyntaxError("Found '.' in keyword name") return keyword.keyword(name, ns=ns)
[ "Return", "a", "keyword", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L626-L633
[ "def", "_read_kw", "(", "ctx", ":", "ReaderContext", ")", "->", "keyword", ".", "Keyword", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\":\"", "ns", ",", "name", "=", "_read_namespaced", "(", "ctx", ")", "if", "\".\"", "in", "name", ":", "raise", "SyntaxError", "(", "\"Found '.' in keyword name\"", ")", "return", "keyword", ".", "keyword", "(", "name", ",", "ns", "=", "ns", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_meta
Read metadata and apply that to the next object in the input stream.
src/basilisp/lang/reader.py
def _read_meta(ctx: ReaderContext) -> IMeta: """Read metadata and apply that to the next object in the input stream.""" start = ctx.reader.advance() assert start == "^" meta = _read_next_consuming_comment(ctx) meta_map: Optional[lmap.Map[LispForm, LispForm]] = None if isinstance(meta, symbol.Symbol): meta_map = lmap.map({keyword.keyword("tag"): meta}) elif isinstance(meta, keyword.Keyword): meta_map = lmap.map({meta: True}) elif isinstance(meta, lmap.Map): meta_map = meta else: raise SyntaxError( f"Expected symbol, keyword, or map for metadata, not {type(meta)}" ) obj_with_meta = _read_next_consuming_comment(ctx) try: return obj_with_meta.with_meta(meta_map) # type: ignore except AttributeError: raise SyntaxError( f"Can not attach metadata to object of type {type(obj_with_meta)}" )
def _read_meta(ctx: ReaderContext) -> IMeta: """Read metadata and apply that to the next object in the input stream.""" start = ctx.reader.advance() assert start == "^" meta = _read_next_consuming_comment(ctx) meta_map: Optional[lmap.Map[LispForm, LispForm]] = None if isinstance(meta, symbol.Symbol): meta_map = lmap.map({keyword.keyword("tag"): meta}) elif isinstance(meta, keyword.Keyword): meta_map = lmap.map({meta: True}) elif isinstance(meta, lmap.Map): meta_map = meta else: raise SyntaxError( f"Expected symbol, keyword, or map for metadata, not {type(meta)}" ) obj_with_meta = _read_next_consuming_comment(ctx) try: return obj_with_meta.with_meta(meta_map) # type: ignore except AttributeError: raise SyntaxError( f"Can not attach metadata to object of type {type(obj_with_meta)}" )
[ "Read", "metadata", "and", "apply", "that", "to", "the", "next", "object", "in", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L636-L661
[ "def", "_read_meta", "(", "ctx", ":", "ReaderContext", ")", "->", "IMeta", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"^\"", "meta", "=", "_read_next_consuming_comment", "(", "ctx", ")", "meta_map", ":", "Optional", "[", "lmap", ".", "Map", "[", "LispForm", ",", "LispForm", "]", "]", "=", "None", "if", "isinstance", "(", "meta", ",", "symbol", ".", "Symbol", ")", ":", "meta_map", "=", "lmap", ".", "map", "(", "{", "keyword", ".", "keyword", "(", "\"tag\"", ")", ":", "meta", "}", ")", "elif", "isinstance", "(", "meta", ",", "keyword", ".", "Keyword", ")", ":", "meta_map", "=", "lmap", ".", "map", "(", "{", "meta", ":", "True", "}", ")", "elif", "isinstance", "(", "meta", ",", "lmap", ".", "Map", ")", ":", "meta_map", "=", "meta", "else", ":", "raise", "SyntaxError", "(", "f\"Expected symbol, keyword, or map for metadata, not {type(meta)}\"", ")", "obj_with_meta", "=", "_read_next_consuming_comment", "(", "ctx", ")", "try", ":", "return", "obj_with_meta", ".", "with_meta", "(", "meta_map", ")", "# type: ignore", "except", "AttributeError", ":", "raise", "SyntaxError", "(", "f\"Can not attach metadata to object of type {type(obj_with_meta)}\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_function
Read a function reader macro from the input stream.
src/basilisp/lang/reader.py
def _read_function(ctx: ReaderContext) -> llist.List: """Read a function reader macro from the input stream.""" if ctx.is_in_anon_fn: raise SyntaxError(f"Nested #() definitions not allowed") with ctx.in_anon_fn(): form = _read_list(ctx) arg_set = set() def arg_suffix(arg_num): if arg_num is None: return "1" elif arg_num == "&": return "rest" else: return arg_num def sym_replacement(arg_num): suffix = arg_suffix(arg_num) return symbol.symbol(f"arg-{suffix}") def identify_and_replace(f): if isinstance(f, symbol.Symbol): if f.ns is None: match = fn_macro_args.match(f.name) if match is not None: arg_num = match.group(2) suffix = arg_suffix(arg_num) arg_set.add(suffix) return sym_replacement(arg_num) return f body = walk.postwalk(identify_and_replace, form) if len(form) > 0 else None arg_list: List[symbol.Symbol] = [] numbered_args = sorted(map(int, filter(lambda k: k != "rest", arg_set))) if len(numbered_args) > 0: max_arg = max(numbered_args) arg_list = [sym_replacement(str(i)) for i in range(1, max_arg + 1)] if "rest" in arg_set: arg_list.append(_AMPERSAND) arg_list.append(sym_replacement("rest")) return llist.l(_FN, vector.vector(arg_list), body)
def _read_function(ctx: ReaderContext) -> llist.List: """Read a function reader macro from the input stream.""" if ctx.is_in_anon_fn: raise SyntaxError(f"Nested #() definitions not allowed") with ctx.in_anon_fn(): form = _read_list(ctx) arg_set = set() def arg_suffix(arg_num): if arg_num is None: return "1" elif arg_num == "&": return "rest" else: return arg_num def sym_replacement(arg_num): suffix = arg_suffix(arg_num) return symbol.symbol(f"arg-{suffix}") def identify_and_replace(f): if isinstance(f, symbol.Symbol): if f.ns is None: match = fn_macro_args.match(f.name) if match is not None: arg_num = match.group(2) suffix = arg_suffix(arg_num) arg_set.add(suffix) return sym_replacement(arg_num) return f body = walk.postwalk(identify_and_replace, form) if len(form) > 0 else None arg_list: List[symbol.Symbol] = [] numbered_args = sorted(map(int, filter(lambda k: k != "rest", arg_set))) if len(numbered_args) > 0: max_arg = max(numbered_args) arg_list = [sym_replacement(str(i)) for i in range(1, max_arg + 1)] if "rest" in arg_set: arg_list.append(_AMPERSAND) arg_list.append(sym_replacement("rest")) return llist.l(_FN, vector.vector(arg_list), body)
[ "Read", "a", "function", "reader", "macro", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L665-L708
[ "def", "_read_function", "(", "ctx", ":", "ReaderContext", ")", "->", "llist", ".", "List", ":", "if", "ctx", ".", "is_in_anon_fn", ":", "raise", "SyntaxError", "(", "f\"Nested #() definitions not allowed\"", ")", "with", "ctx", ".", "in_anon_fn", "(", ")", ":", "form", "=", "_read_list", "(", "ctx", ")", "arg_set", "=", "set", "(", ")", "def", "arg_suffix", "(", "arg_num", ")", ":", "if", "arg_num", "is", "None", ":", "return", "\"1\"", "elif", "arg_num", "==", "\"&\"", ":", "return", "\"rest\"", "else", ":", "return", "arg_num", "def", "sym_replacement", "(", "arg_num", ")", ":", "suffix", "=", "arg_suffix", "(", "arg_num", ")", "return", "symbol", ".", "symbol", "(", "f\"arg-{suffix}\"", ")", "def", "identify_and_replace", "(", "f", ")", ":", "if", "isinstance", "(", "f", ",", "symbol", ".", "Symbol", ")", ":", "if", "f", ".", "ns", "is", "None", ":", "match", "=", "fn_macro_args", ".", "match", "(", "f", ".", "name", ")", "if", "match", "is", "not", "None", ":", "arg_num", "=", "match", ".", "group", "(", "2", ")", "suffix", "=", "arg_suffix", "(", "arg_num", ")", "arg_set", ".", "add", "(", "suffix", ")", "return", "sym_replacement", "(", "arg_num", ")", "return", "f", "body", "=", "walk", ".", "postwalk", "(", "identify_and_replace", ",", "form", ")", "if", "len", "(", "form", ")", ">", "0", "else", "None", "arg_list", ":", "List", "[", "symbol", ".", "Symbol", "]", "=", "[", "]", "numbered_args", "=", "sorted", "(", "map", "(", "int", ",", "filter", "(", "lambda", "k", ":", "k", "!=", "\"rest\"", ",", "arg_set", ")", ")", ")", "if", "len", "(", "numbered_args", ")", ">", "0", ":", "max_arg", "=", "max", "(", "numbered_args", ")", "arg_list", "=", "[", "sym_replacement", "(", "str", "(", "i", ")", ")", "for", "i", "in", "range", "(", "1", ",", "max_arg", "+", "1", ")", "]", "if", "\"rest\"", "in", "arg_set", ":", "arg_list", ".", "append", "(", "_AMPERSAND", ")", "arg_list", ".", "append", "(", "sym_replacement", "(", "\"rest\"", ")", ")", "return", "llist", ".", "l", "(", "_FN", ",", "vector", ".", "vector", "(", "arg_list", ")", ",", "body", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_quoted
Read a quoted form from the input stream.
src/basilisp/lang/reader.py
def _read_quoted(ctx: ReaderContext) -> llist.List: """Read a quoted form from the input stream.""" start = ctx.reader.advance() assert start == "'" next_form = _read_next_consuming_comment(ctx) return llist.l(_QUOTE, next_form)
def _read_quoted(ctx: ReaderContext) -> llist.List: """Read a quoted form from the input stream.""" start = ctx.reader.advance() assert start == "'" next_form = _read_next_consuming_comment(ctx) return llist.l(_QUOTE, next_form)
[ "Read", "a", "quoted", "form", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L712-L717
[ "def", "_read_quoted", "(", "ctx", ":", "ReaderContext", ")", "->", "llist", ".", "List", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"'\"", "next_form", "=", "_read_next_consuming_comment", "(", "ctx", ")", "return", "llist", ".", "l", "(", "_QUOTE", ",", "next_form", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_expand_syntax_quote
Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other forms are recursively processed as by _process_syntax_quoted_form and are returned as: (list form)
src/basilisp/lang/reader.py
def _expand_syntax_quote( ctx: ReaderContext, form: IterableLispForm ) -> Iterable[LispForm]: """Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other forms are recursively processed as by _process_syntax_quoted_form and are returned as: (list form)""" expanded = [] for elem in form: if _is_unquote(elem): expanded.append(llist.l(_LIST, elem[1])) elif _is_unquote_splicing(elem): expanded.append(elem[1]) else: expanded.append(llist.l(_LIST, _process_syntax_quoted_form(ctx, elem))) return expanded
def _expand_syntax_quote( ctx: ReaderContext, form: IterableLispForm ) -> Iterable[LispForm]: """Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other forms are recursively processed as by _process_syntax_quoted_form and are returned as: (list form)""" expanded = [] for elem in form: if _is_unquote(elem): expanded.append(llist.l(_LIST, elem[1])) elif _is_unquote_splicing(elem): expanded.append(elem[1]) else: expanded.append(llist.l(_LIST, _process_syntax_quoted_form(ctx, elem))) return expanded
[ "Expand", "syntax", "quoted", "forms", "to", "handle", "unquoting", "and", "unquote", "-", "splicing", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L736-L760
[ "def", "_expand_syntax_quote", "(", "ctx", ":", "ReaderContext", ",", "form", ":", "IterableLispForm", ")", "->", "Iterable", "[", "LispForm", "]", ":", "expanded", "=", "[", "]", "for", "elem", "in", "form", ":", "if", "_is_unquote", "(", "elem", ")", ":", "expanded", ".", "append", "(", "llist", ".", "l", "(", "_LIST", ",", "elem", "[", "1", "]", ")", ")", "elif", "_is_unquote_splicing", "(", "elem", ")", ":", "expanded", ".", "append", "(", "elem", "[", "1", "]", ")", "else", ":", "expanded", ".", "append", "(", "llist", ".", "l", "(", "_LIST", ",", "_process_syntax_quoted_form", "(", "ctx", ",", "elem", ")", ")", ")", "return", "expanded" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_process_syntax_quoted_form
Post-process syntax quoted forms to generate forms that can be assembled into the correct types at runtime. Lists are turned into: (basilisp.core/seq (basilisp.core/concat [& rest])) Vectors are turned into: (basilisp.core/apply basilisp.core/vector (basilisp.core/concat [& rest])) Sets are turned into: (basilisp.core/apply basilisp.core/hash-set (basilisp.core/concat [& rest])) Maps are turned into: (basilisp.core/apply basilisp.core/hash-map (basilisp.core/concat [& rest])) The child forms (called rest above) are processed by _expand_syntax_quote. All other forms are passed through without modification.
src/basilisp/lang/reader.py
def _process_syntax_quoted_form(ctx: ReaderContext, form: ReaderForm) -> ReaderForm: """Post-process syntax quoted forms to generate forms that can be assembled into the correct types at runtime. Lists are turned into: (basilisp.core/seq (basilisp.core/concat [& rest])) Vectors are turned into: (basilisp.core/apply basilisp.core/vector (basilisp.core/concat [& rest])) Sets are turned into: (basilisp.core/apply basilisp.core/hash-set (basilisp.core/concat [& rest])) Maps are turned into: (basilisp.core/apply basilisp.core/hash-map (basilisp.core/concat [& rest])) The child forms (called rest above) are processed by _expand_syntax_quote. All other forms are passed through without modification.""" lconcat = lambda v: llist.list(v).cons(_CONCAT) if _is_unquote(form): return form[1] # type: ignore elif _is_unquote_splicing(form): raise SyntaxError("Cannot splice outside collection") elif isinstance(form, llist.List): return llist.l(_SEQ, lconcat(_expand_syntax_quote(ctx, form))) elif isinstance(form, vector.Vector): return llist.l(_APPLY, _VECTOR, lconcat(_expand_syntax_quote(ctx, form))) elif isinstance(form, lset.Set): return llist.l(_APPLY, _HASH_SET, lconcat(_expand_syntax_quote(ctx, form))) elif isinstance(form, lmap.Map): flat_kvs = seq(form.items()).flatten().to_list() return llist.l(_APPLY, _HASH_MAP, lconcat(_expand_syntax_quote(ctx, flat_kvs))) elif isinstance(form, symbol.Symbol): if form.ns is None and form.name.endswith("#"): try: return llist.l(_QUOTE, ctx.gensym_env[form.name]) except KeyError: genned = symbol.symbol(langutil.genname(form.name[:-1])).with_meta( form.meta ) ctx.gensym_env[form.name] = genned return llist.l(_QUOTE, genned) return llist.l(_QUOTE, form) else: return form
def _process_syntax_quoted_form(ctx: ReaderContext, form: ReaderForm) -> ReaderForm: """Post-process syntax quoted forms to generate forms that can be assembled into the correct types at runtime. Lists are turned into: (basilisp.core/seq (basilisp.core/concat [& rest])) Vectors are turned into: (basilisp.core/apply basilisp.core/vector (basilisp.core/concat [& rest])) Sets are turned into: (basilisp.core/apply basilisp.core/hash-set (basilisp.core/concat [& rest])) Maps are turned into: (basilisp.core/apply basilisp.core/hash-map (basilisp.core/concat [& rest])) The child forms (called rest above) are processed by _expand_syntax_quote. All other forms are passed through without modification.""" lconcat = lambda v: llist.list(v).cons(_CONCAT) if _is_unquote(form): return form[1] # type: ignore elif _is_unquote_splicing(form): raise SyntaxError("Cannot splice outside collection") elif isinstance(form, llist.List): return llist.l(_SEQ, lconcat(_expand_syntax_quote(ctx, form))) elif isinstance(form, vector.Vector): return llist.l(_APPLY, _VECTOR, lconcat(_expand_syntax_quote(ctx, form))) elif isinstance(form, lset.Set): return llist.l(_APPLY, _HASH_SET, lconcat(_expand_syntax_quote(ctx, form))) elif isinstance(form, lmap.Map): flat_kvs = seq(form.items()).flatten().to_list() return llist.l(_APPLY, _HASH_MAP, lconcat(_expand_syntax_quote(ctx, flat_kvs))) elif isinstance(form, symbol.Symbol): if form.ns is None and form.name.endswith("#"): try: return llist.l(_QUOTE, ctx.gensym_env[form.name]) except KeyError: genned = symbol.symbol(langutil.genname(form.name[:-1])).with_meta( form.meta ) ctx.gensym_env[form.name] = genned return llist.l(_QUOTE, genned) return llist.l(_QUOTE, form) else: return form
[ "Post", "-", "process", "syntax", "quoted", "forms", "to", "generate", "forms", "that", "can", "be", "assembled", "into", "the", "correct", "types", "at", "runtime", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L763-L815
[ "def", "_process_syntax_quoted_form", "(", "ctx", ":", "ReaderContext", ",", "form", ":", "ReaderForm", ")", "->", "ReaderForm", ":", "lconcat", "=", "lambda", "v", ":", "llist", ".", "list", "(", "v", ")", ".", "cons", "(", "_CONCAT", ")", "if", "_is_unquote", "(", "form", ")", ":", "return", "form", "[", "1", "]", "# type: ignore", "elif", "_is_unquote_splicing", "(", "form", ")", ":", "raise", "SyntaxError", "(", "\"Cannot splice outside collection\"", ")", "elif", "isinstance", "(", "form", ",", "llist", ".", "List", ")", ":", "return", "llist", ".", "l", "(", "_SEQ", ",", "lconcat", "(", "_expand_syntax_quote", "(", "ctx", ",", "form", ")", ")", ")", "elif", "isinstance", "(", "form", ",", "vector", ".", "Vector", ")", ":", "return", "llist", ".", "l", "(", "_APPLY", ",", "_VECTOR", ",", "lconcat", "(", "_expand_syntax_quote", "(", "ctx", ",", "form", ")", ")", ")", "elif", "isinstance", "(", "form", ",", "lset", ".", "Set", ")", ":", "return", "llist", ".", "l", "(", "_APPLY", ",", "_HASH_SET", ",", "lconcat", "(", "_expand_syntax_quote", "(", "ctx", ",", "form", ")", ")", ")", "elif", "isinstance", "(", "form", ",", "lmap", ".", "Map", ")", ":", "flat_kvs", "=", "seq", "(", "form", ".", "items", "(", ")", ")", ".", "flatten", "(", ")", ".", "to_list", "(", ")", "return", "llist", ".", "l", "(", "_APPLY", ",", "_HASH_MAP", ",", "lconcat", "(", "_expand_syntax_quote", "(", "ctx", ",", "flat_kvs", ")", ")", ")", "elif", "isinstance", "(", "form", ",", "symbol", ".", "Symbol", ")", ":", "if", "form", ".", "ns", "is", "None", "and", "form", ".", "name", ".", "endswith", "(", "\"#\"", ")", ":", "try", ":", "return", "llist", ".", "l", "(", "_QUOTE", ",", "ctx", ".", "gensym_env", "[", "form", ".", "name", "]", ")", "except", "KeyError", ":", "genned", "=", "symbol", ".", "symbol", "(", "langutil", ".", "genname", "(", "form", ".", "name", "[", ":", "-", "1", "]", ")", ")", ".", "with_meta", "(", "form", ".", "meta", ")", "ctx", ".", "gensym_env", "[", "form", ".", "name", "]", "=", "genned", "return", "llist", ".", "l", "(", "_QUOTE", ",", "genned", ")", "return", "llist", ".", "l", "(", "_QUOTE", ",", "form", ")", "else", ":", "return", "form" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_syntax_quoted
Read a syntax-quote and set the syntax-quoting state in the reader.
src/basilisp/lang/reader.py
def _read_syntax_quoted(ctx: ReaderContext) -> ReaderForm: """Read a syntax-quote and set the syntax-quoting state in the reader.""" start = ctx.reader.advance() assert start == "`" with ctx.syntax_quoted(): return _process_syntax_quoted_form(ctx, _read_next_consuming_comment(ctx))
def _read_syntax_quoted(ctx: ReaderContext) -> ReaderForm: """Read a syntax-quote and set the syntax-quoting state in the reader.""" start = ctx.reader.advance() assert start == "`" with ctx.syntax_quoted(): return _process_syntax_quoted_form(ctx, _read_next_consuming_comment(ctx))
[ "Read", "a", "syntax", "-", "quote", "and", "set", "the", "syntax", "-", "quoting", "state", "in", "the", "reader", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L818-L824
[ "def", "_read_syntax_quoted", "(", "ctx", ":", "ReaderContext", ")", "->", "ReaderForm", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"`\"", "with", "ctx", ".", "syntax_quoted", "(", ")", ":", "return", "_process_syntax_quoted_form", "(", "ctx", ",", "_read_next_consuming_comment", "(", "ctx", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_unquote
Read an unquoted form and handle any special logic of unquoting. Unquoted forms can take two, well... forms: `~form` is read as `(unquote form)` and any nested forms are read literally and passed along to the compiler untouched. `~@form` is read as `(unquote-splicing form)` which tells the compiler to splice in the contents of a sequential form such as a list or vector into the final compiled form. This helps macro writers create longer forms such as function calls, function bodies, or data structures with the contents of another collection they have.
src/basilisp/lang/reader.py
def _read_unquote(ctx: ReaderContext) -> LispForm: """Read an unquoted form and handle any special logic of unquoting. Unquoted forms can take two, well... forms: `~form` is read as `(unquote form)` and any nested forms are read literally and passed along to the compiler untouched. `~@form` is read as `(unquote-splicing form)` which tells the compiler to splice in the contents of a sequential form such as a list or vector into the final compiled form. This helps macro writers create longer forms such as function calls, function bodies, or data structures with the contents of another collection they have.""" start = ctx.reader.advance() assert start == "~" with ctx.unquoted(): next_char = ctx.reader.peek() if next_char == "@": ctx.reader.advance() next_form = _read_next_consuming_comment(ctx) return llist.l(_UNQUOTE_SPLICING, next_form) else: next_form = _read_next_consuming_comment(ctx) return llist.l(_UNQUOTE, next_form)
def _read_unquote(ctx: ReaderContext) -> LispForm: """Read an unquoted form and handle any special logic of unquoting. Unquoted forms can take two, well... forms: `~form` is read as `(unquote form)` and any nested forms are read literally and passed along to the compiler untouched. `~@form` is read as `(unquote-splicing form)` which tells the compiler to splice in the contents of a sequential form such as a list or vector into the final compiled form. This helps macro writers create longer forms such as function calls, function bodies, or data structures with the contents of another collection they have.""" start = ctx.reader.advance() assert start == "~" with ctx.unquoted(): next_char = ctx.reader.peek() if next_char == "@": ctx.reader.advance() next_form = _read_next_consuming_comment(ctx) return llist.l(_UNQUOTE_SPLICING, next_form) else: next_form = _read_next_consuming_comment(ctx) return llist.l(_UNQUOTE, next_form)
[ "Read", "an", "unquoted", "form", "and", "handle", "any", "special", "logic", "of", "unquoting", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L827-L851
[ "def", "_read_unquote", "(", "ctx", ":", "ReaderContext", ")", "->", "LispForm", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"~\"", "with", "ctx", ".", "unquoted", "(", ")", ":", "next_char", "=", "ctx", ".", "reader", ".", "peek", "(", ")", "if", "next_char", "==", "\"@\"", ":", "ctx", ".", "reader", ".", "advance", "(", ")", "next_form", "=", "_read_next_consuming_comment", "(", "ctx", ")", "return", "llist", ".", "l", "(", "_UNQUOTE_SPLICING", ",", "next_form", ")", "else", ":", "next_form", "=", "_read_next_consuming_comment", "(", "ctx", ")", "return", "llist", ".", "l", "(", "_UNQUOTE", ",", "next_form", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_deref
Read a derefed form from the input stream.
src/basilisp/lang/reader.py
def _read_deref(ctx: ReaderContext) -> LispForm: """Read a derefed form from the input stream.""" start = ctx.reader.advance() assert start == "@" next_form = _read_next_consuming_comment(ctx) return llist.l(_DEREF, next_form)
def _read_deref(ctx: ReaderContext) -> LispForm: """Read a derefed form from the input stream.""" start = ctx.reader.advance() assert start == "@" next_form = _read_next_consuming_comment(ctx) return llist.l(_DEREF, next_form)
[ "Read", "a", "derefed", "form", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L855-L860
[ "def", "_read_deref", "(", "ctx", ":", "ReaderContext", ")", "->", "LispForm", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"@\"", "next_form", "=", "_read_next_consuming_comment", "(", "ctx", ")", "return", "llist", ".", "l", "(", "_DEREF", ",", "next_form", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_character
Read a character literal from the input stream. Character literals may appear as: - \\a \\b \\c etc will yield 'a', 'b', and 'c' respectively - \\newline, \\space, \\tab, \\formfeed, \\backspace, \\return yield the named characters - \\uXXXX yield the unicode digit corresponding to the code point named by the hex digits XXXX
src/basilisp/lang/reader.py
def _read_character(ctx: ReaderContext) -> str: """Read a character literal from the input stream. Character literals may appear as: - \\a \\b \\c etc will yield 'a', 'b', and 'c' respectively - \\newline, \\space, \\tab, \\formfeed, \\backspace, \\return yield the named characters - \\uXXXX yield the unicode digit corresponding to the code point named by the hex digits XXXX""" start = ctx.reader.advance() assert start == "\\" s: List[str] = [] reader = ctx.reader token = reader.peek() while True: if token == "" or whitespace_chars.match(token): break if not alphanumeric_chars.match(token): break s.append(token) token = reader.next_token() char = "".join(s) special = _SPECIAL_CHARS.get(char, None) if special is not None: return special match = unicode_char.match(char) if match is not None: try: return chr(int(f"0x{match.group(1)}", 16)) except (ValueError, OverflowError): raise SyntaxError(f"Unsupported character \\u{char}") from None if len(char) > 1: raise SyntaxError(f"Unsupported character \\{char}") return char
def _read_character(ctx: ReaderContext) -> str: """Read a character literal from the input stream. Character literals may appear as: - \\a \\b \\c etc will yield 'a', 'b', and 'c' respectively - \\newline, \\space, \\tab, \\formfeed, \\backspace, \\return yield the named characters - \\uXXXX yield the unicode digit corresponding to the code point named by the hex digits XXXX""" start = ctx.reader.advance() assert start == "\\" s: List[str] = [] reader = ctx.reader token = reader.peek() while True: if token == "" or whitespace_chars.match(token): break if not alphanumeric_chars.match(token): break s.append(token) token = reader.next_token() char = "".join(s) special = _SPECIAL_CHARS.get(char, None) if special is not None: return special match = unicode_char.match(char) if match is not None: try: return chr(int(f"0x{match.group(1)}", 16)) except (ValueError, OverflowError): raise SyntaxError(f"Unsupported character \\u{char}") from None if len(char) > 1: raise SyntaxError(f"Unsupported character \\{char}") return char
[ "Read", "a", "character", "literal", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L873-L913
[ "def", "_read_character", "(", "ctx", ":", "ReaderContext", ")", "->", "str", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"\\\\\"", "s", ":", "List", "[", "str", "]", "=", "[", "]", "reader", "=", "ctx", ".", "reader", "token", "=", "reader", ".", "peek", "(", ")", "while", "True", ":", "if", "token", "==", "\"\"", "or", "whitespace_chars", ".", "match", "(", "token", ")", ":", "break", "if", "not", "alphanumeric_chars", ".", "match", "(", "token", ")", ":", "break", "s", ".", "append", "(", "token", ")", "token", "=", "reader", ".", "next_token", "(", ")", "char", "=", "\"\"", ".", "join", "(", "s", ")", "special", "=", "_SPECIAL_CHARS", ".", "get", "(", "char", ",", "None", ")", "if", "special", "is", "not", "None", ":", "return", "special", "match", "=", "unicode_char", ".", "match", "(", "char", ")", "if", "match", "is", "not", "None", ":", "try", ":", "return", "chr", "(", "int", "(", "f\"0x{match.group(1)}\"", ",", "16", ")", ")", "except", "(", "ValueError", ",", "OverflowError", ")", ":", "raise", "SyntaxError", "(", "f\"Unsupported character \\\\u{char}\"", ")", "from", "None", "if", "len", "(", "char", ")", ">", "1", ":", "raise", "SyntaxError", "(", "f\"Unsupported character \\\\{char}\"", ")", "return", "char" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_regex
Read a regex reader macro from the input stream.
src/basilisp/lang/reader.py
def _read_regex(ctx: ReaderContext) -> Pattern: """Read a regex reader macro from the input stream.""" s = _read_str(ctx, allow_arbitrary_escapes=True) try: return langutil.regex_from_str(s) except re.error: raise SyntaxError(f"Unrecognized regex pattern syntax: {s}")
def _read_regex(ctx: ReaderContext) -> Pattern: """Read a regex reader macro from the input stream.""" s = _read_str(ctx, allow_arbitrary_escapes=True) try: return langutil.regex_from_str(s) except re.error: raise SyntaxError(f"Unrecognized regex pattern syntax: {s}")
[ "Read", "a", "regex", "reader", "macro", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L916-L922
[ "def", "_read_regex", "(", "ctx", ":", "ReaderContext", ")", "->", "Pattern", ":", "s", "=", "_read_str", "(", "ctx", ",", "allow_arbitrary_escapes", "=", "True", ")", "try", ":", "return", "langutil", ".", "regex_from_str", "(", "s", ")", "except", "re", ".", "error", ":", "raise", "SyntaxError", "(", "f\"Unrecognized regex pattern syntax: {s}\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_reader_macro
Return a data structure evaluated as a reader macro from the input stream.
src/basilisp/lang/reader.py
def _read_reader_macro(ctx: ReaderContext) -> LispReaderForm: """Return a data structure evaluated as a reader macro from the input stream.""" start = ctx.reader.advance() assert start == "#" token = ctx.reader.peek() if token == "{": return _read_set(ctx) elif token == "(": return _read_function(ctx) elif token == "'": ctx.reader.advance() s = _read_sym(ctx) return llist.l(_VAR, s) elif token == '"': return _read_regex(ctx) elif token == "_": ctx.reader.advance() _read_next(ctx) # Ignore the entire next form return COMMENT elif ns_name_chars.match(token): s = _read_sym(ctx) assert isinstance(s, symbol.Symbol) v = _read_next_consuming_comment(ctx) if s in ctx.data_readers: f = ctx.data_readers[s] return f(v) else: raise SyntaxError(f"No data reader found for tag #{s}") raise SyntaxError(f"Unexpected token '{token}' in reader macro")
def _read_reader_macro(ctx: ReaderContext) -> LispReaderForm: """Return a data structure evaluated as a reader macro from the input stream.""" start = ctx.reader.advance() assert start == "#" token = ctx.reader.peek() if token == "{": return _read_set(ctx) elif token == "(": return _read_function(ctx) elif token == "'": ctx.reader.advance() s = _read_sym(ctx) return llist.l(_VAR, s) elif token == '"': return _read_regex(ctx) elif token == "_": ctx.reader.advance() _read_next(ctx) # Ignore the entire next form return COMMENT elif ns_name_chars.match(token): s = _read_sym(ctx) assert isinstance(s, symbol.Symbol) v = _read_next_consuming_comment(ctx) if s in ctx.data_readers: f = ctx.data_readers[s] return f(v) else: raise SyntaxError(f"No data reader found for tag #{s}") raise SyntaxError(f"Unexpected token '{token}' in reader macro")
[ "Return", "a", "data", "structure", "evaluated", "as", "a", "reader", "macro", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L925-L955
[ "def", "_read_reader_macro", "(", "ctx", ":", "ReaderContext", ")", "->", "LispReaderForm", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"#\"", "token", "=", "ctx", ".", "reader", ".", "peek", "(", ")", "if", "token", "==", "\"{\"", ":", "return", "_read_set", "(", "ctx", ")", "elif", "token", "==", "\"(\"", ":", "return", "_read_function", "(", "ctx", ")", "elif", "token", "==", "\"'\"", ":", "ctx", ".", "reader", ".", "advance", "(", ")", "s", "=", "_read_sym", "(", "ctx", ")", "return", "llist", ".", "l", "(", "_VAR", ",", "s", ")", "elif", "token", "==", "'\"'", ":", "return", "_read_regex", "(", "ctx", ")", "elif", "token", "==", "\"_\"", ":", "ctx", ".", "reader", ".", "advance", "(", ")", "_read_next", "(", "ctx", ")", "# Ignore the entire next form", "return", "COMMENT", "elif", "ns_name_chars", ".", "match", "(", "token", ")", ":", "s", "=", "_read_sym", "(", "ctx", ")", "assert", "isinstance", "(", "s", ",", "symbol", ".", "Symbol", ")", "v", "=", "_read_next_consuming_comment", "(", "ctx", ")", "if", "s", "in", "ctx", ".", "data_readers", ":", "f", "=", "ctx", ".", "data_readers", "[", "s", "]", "return", "f", "(", "v", ")", "else", ":", "raise", "SyntaxError", "(", "f\"No data reader found for tag #{s}\"", ")", "raise", "SyntaxError", "(", "f\"Unexpected token '{token}' in reader macro\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_comment
Read (and ignore) a single-line comment from the input stream. Return the next form after the next line break.
src/basilisp/lang/reader.py
def _read_comment(ctx: ReaderContext) -> LispReaderForm: """Read (and ignore) a single-line comment from the input stream. Return the next form after the next line break.""" reader = ctx.reader start = reader.advance() assert start == ";" while True: token = reader.peek() if newline_chars.match(token): reader.advance() return _read_next(ctx) if token == "": return ctx.eof reader.advance()
def _read_comment(ctx: ReaderContext) -> LispReaderForm: """Read (and ignore) a single-line comment from the input stream. Return the next form after the next line break.""" reader = ctx.reader start = reader.advance() assert start == ";" while True: token = reader.peek() if newline_chars.match(token): reader.advance() return _read_next(ctx) if token == "": return ctx.eof reader.advance()
[ "Read", "(", "and", "ignore", ")", "a", "single", "-", "line", "comment", "from", "the", "input", "stream", ".", "Return", "the", "next", "form", "after", "the", "next", "line", "break", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L958-L971
[ "def", "_read_comment", "(", "ctx", ":", "ReaderContext", ")", "->", "LispReaderForm", ":", "reader", "=", "ctx", ".", "reader", "start", "=", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\";\"", "while", "True", ":", "token", "=", "reader", ".", "peek", "(", ")", "if", "newline_chars", ".", "match", "(", "token", ")", ":", "reader", ".", "advance", "(", ")", "return", "_read_next", "(", "ctx", ")", "if", "token", "==", "\"\"", ":", "return", "ctx", ".", "eof", "reader", ".", "advance", "(", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_next_consuming_comment
Read the next full form from the input stream, consuming any reader comments completely.
src/basilisp/lang/reader.py
def _read_next_consuming_comment(ctx: ReaderContext) -> ReaderForm: """Read the next full form from the input stream, consuming any reader comments completely.""" while True: v = _read_next(ctx) if v is ctx.eof: return ctx.eof if v is COMMENT or isinstance(v, Comment): continue return v
def _read_next_consuming_comment(ctx: ReaderContext) -> ReaderForm: """Read the next full form from the input stream, consuming any reader comments completely.""" while True: v = _read_next(ctx) if v is ctx.eof: return ctx.eof if v is COMMENT or isinstance(v, Comment): continue return v
[ "Read", "the", "next", "full", "form", "from", "the", "input", "stream", "consuming", "any", "reader", "comments", "completely", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L974-L983
[ "def", "_read_next_consuming_comment", "(", "ctx", ":", "ReaderContext", ")", "->", "ReaderForm", ":", "while", "True", ":", "v", "=", "_read_next", "(", "ctx", ")", "if", "v", "is", "ctx", ".", "eof", ":", "return", "ctx", ".", "eof", "if", "v", "is", "COMMENT", "or", "isinstance", "(", "v", ",", "Comment", ")", ":", "continue", "return", "v" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_read_next
Read the next full form from the input stream.
src/basilisp/lang/reader.py
def _read_next(ctx: ReaderContext) -> LispReaderForm: # noqa: C901 """Read the next full form from the input stream.""" reader = ctx.reader token = reader.peek() if token == "(": return _read_list(ctx) elif token == "[": return _read_vector(ctx) elif token == "{": return _read_map(ctx) elif begin_num_chars.match(token): return _read_num(ctx) elif whitespace_chars.match(token): reader.next_token() return _read_next(ctx) elif token == ":": return _read_kw(ctx) elif token == '"': return _read_str(ctx) elif token == "'": return _read_quoted(ctx) elif token == "\\": return _read_character(ctx) elif ns_name_chars.match(token): return _read_sym(ctx) elif token == "#": return _read_reader_macro(ctx) elif token == "^": return _read_meta(ctx) # type: ignore elif token == ";": return _read_comment(ctx) elif token == "`": return _read_syntax_quoted(ctx) elif token == "~": return _read_unquote(ctx) elif token == "@": return _read_deref(ctx) elif token == "": return ctx.eof else: raise SyntaxError("Unexpected token '{token}'".format(token=token))
def _read_next(ctx: ReaderContext) -> LispReaderForm: # noqa: C901 """Read the next full form from the input stream.""" reader = ctx.reader token = reader.peek() if token == "(": return _read_list(ctx) elif token == "[": return _read_vector(ctx) elif token == "{": return _read_map(ctx) elif begin_num_chars.match(token): return _read_num(ctx) elif whitespace_chars.match(token): reader.next_token() return _read_next(ctx) elif token == ":": return _read_kw(ctx) elif token == '"': return _read_str(ctx) elif token == "'": return _read_quoted(ctx) elif token == "\\": return _read_character(ctx) elif ns_name_chars.match(token): return _read_sym(ctx) elif token == "#": return _read_reader_macro(ctx) elif token == "^": return _read_meta(ctx) # type: ignore elif token == ";": return _read_comment(ctx) elif token == "`": return _read_syntax_quoted(ctx) elif token == "~": return _read_unquote(ctx) elif token == "@": return _read_deref(ctx) elif token == "": return ctx.eof else: raise SyntaxError("Unexpected token '{token}'".format(token=token))
[ "Read", "the", "next", "full", "form", "from", "the", "input", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L986-L1026
[ "def", "_read_next", "(", "ctx", ":", "ReaderContext", ")", "->", "LispReaderForm", ":", "# noqa: C901", "reader", "=", "ctx", ".", "reader", "token", "=", "reader", ".", "peek", "(", ")", "if", "token", "==", "\"(\"", ":", "return", "_read_list", "(", "ctx", ")", "elif", "token", "==", "\"[\"", ":", "return", "_read_vector", "(", "ctx", ")", "elif", "token", "==", "\"{\"", ":", "return", "_read_map", "(", "ctx", ")", "elif", "begin_num_chars", ".", "match", "(", "token", ")", ":", "return", "_read_num", "(", "ctx", ")", "elif", "whitespace_chars", ".", "match", "(", "token", ")", ":", "reader", ".", "next_token", "(", ")", "return", "_read_next", "(", "ctx", ")", "elif", "token", "==", "\":\"", ":", "return", "_read_kw", "(", "ctx", ")", "elif", "token", "==", "'\"'", ":", "return", "_read_str", "(", "ctx", ")", "elif", "token", "==", "\"'\"", ":", "return", "_read_quoted", "(", "ctx", ")", "elif", "token", "==", "\"\\\\\"", ":", "return", "_read_character", "(", "ctx", ")", "elif", "ns_name_chars", ".", "match", "(", "token", ")", ":", "return", "_read_sym", "(", "ctx", ")", "elif", "token", "==", "\"#\"", ":", "return", "_read_reader_macro", "(", "ctx", ")", "elif", "token", "==", "\"^\"", ":", "return", "_read_meta", "(", "ctx", ")", "# type: ignore", "elif", "token", "==", "\";\"", ":", "return", "_read_comment", "(", "ctx", ")", "elif", "token", "==", "\"`\"", ":", "return", "_read_syntax_quoted", "(", "ctx", ")", "elif", "token", "==", "\"~\"", ":", "return", "_read_unquote", "(", "ctx", ")", "elif", "token", "==", "\"@\"", ":", "return", "_read_deref", "(", "ctx", ")", "elif", "token", "==", "\"\"", ":", "return", "ctx", ".", "eof", "else", ":", "raise", "SyntaxError", "(", "\"Unexpected token '{token}'\"", ".", "format", "(", "token", "=", "token", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
read
Read the contents of a stream as a Lisp expression. Callers may optionally specify a namespace resolver, which will be used to adjudicate the fully-qualified name of symbols appearing inside of a syntax quote. Callers may optionally specify a map of custom data readers that will be used to resolve values in reader macros. Data reader tags specified by callers must be namespaced symbols; non-namespaced symbols are reserved by the reader. Data reader functions must be functions taking one argument and returning a value. The caller is responsible for closing the input stream.
src/basilisp/lang/reader.py
def read( stream, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = EOF, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a stream as a Lisp expression. Callers may optionally specify a namespace resolver, which will be used to adjudicate the fully-qualified name of symbols appearing inside of a syntax quote. Callers may optionally specify a map of custom data readers that will be used to resolve values in reader macros. Data reader tags specified by callers must be namespaced symbols; non-namespaced symbols are reserved by the reader. Data reader functions must be functions taking one argument and returning a value. The caller is responsible for closing the input stream.""" reader = StreamReader(stream) ctx = ReaderContext(reader, resolver=resolver, data_readers=data_readers, eof=eof) while True: expr = _read_next(ctx) if expr is ctx.eof: if is_eof_error: raise EOFError return if expr is COMMENT or isinstance(expr, Comment): continue yield expr
def read( stream, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = EOF, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a stream as a Lisp expression. Callers may optionally specify a namespace resolver, which will be used to adjudicate the fully-qualified name of symbols appearing inside of a syntax quote. Callers may optionally specify a map of custom data readers that will be used to resolve values in reader macros. Data reader tags specified by callers must be namespaced symbols; non-namespaced symbols are reserved by the reader. Data reader functions must be functions taking one argument and returning a value. The caller is responsible for closing the input stream.""" reader = StreamReader(stream) ctx = ReaderContext(reader, resolver=resolver, data_readers=data_readers, eof=eof) while True: expr = _read_next(ctx) if expr is ctx.eof: if is_eof_error: raise EOFError return if expr is COMMENT or isinstance(expr, Comment): continue yield expr
[ "Read", "the", "contents", "of", "a", "stream", "as", "a", "Lisp", "expression", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L1029-L1059
[ "def", "read", "(", "stream", ",", "resolver", ":", "Resolver", "=", "None", ",", "data_readers", ":", "DataReaders", "=", "None", ",", "eof", ":", "Any", "=", "EOF", ",", "is_eof_error", ":", "bool", "=", "False", ",", ")", "->", "Iterable", "[", "ReaderForm", "]", ":", "reader", "=", "StreamReader", "(", "stream", ")", "ctx", "=", "ReaderContext", "(", "reader", ",", "resolver", "=", "resolver", ",", "data_readers", "=", "data_readers", ",", "eof", "=", "eof", ")", "while", "True", ":", "expr", "=", "_read_next", "(", "ctx", ")", "if", "expr", "is", "ctx", ".", "eof", ":", "if", "is_eof_error", ":", "raise", "EOFError", "return", "if", "expr", "is", "COMMENT", "or", "isinstance", "(", "expr", ",", "Comment", ")", ":", "continue", "yield", "expr" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
read_str
Read the contents of a string as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilisp.lang.reader.read.
src/basilisp/lang/reader.py
def read_str( s: str, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = None, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a string as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilisp.lang.reader.read.""" with io.StringIO(s) as buf: yield from read( buf, resolver=resolver, data_readers=data_readers, eof=eof, is_eof_error=is_eof_error, )
def read_str( s: str, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = None, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a string as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilisp.lang.reader.read.""" with io.StringIO(s) as buf: yield from read( buf, resolver=resolver, data_readers=data_readers, eof=eof, is_eof_error=is_eof_error, )
[ "Read", "the", "contents", "of", "a", "string", "as", "a", "Lisp", "expression", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L1062-L1080
[ "def", "read_str", "(", "s", ":", "str", ",", "resolver", ":", "Resolver", "=", "None", ",", "data_readers", ":", "DataReaders", "=", "None", ",", "eof", ":", "Any", "=", "None", ",", "is_eof_error", ":", "bool", "=", "False", ",", ")", "->", "Iterable", "[", "ReaderForm", "]", ":", "with", "io", ".", "StringIO", "(", "s", ")", "as", "buf", ":", "yield", "from", "read", "(", "buf", ",", "resolver", "=", "resolver", ",", "data_readers", "=", "data_readers", ",", "eof", "=", "eof", ",", "is_eof_error", "=", "is_eof_error", ",", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
read_file
Read the contents of a file as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilisp.lang.reader.read.
src/basilisp/lang/reader.py
def read_file( filename: str, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = None, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a file as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilisp.lang.reader.read.""" with open(filename) as f: yield from read( f, resolver=resolver, data_readers=data_readers, eof=eof, is_eof_error=is_eof_error, )
def read_file( filename: str, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = None, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a file as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilisp.lang.reader.read.""" with open(filename) as f: yield from read( f, resolver=resolver, data_readers=data_readers, eof=eof, is_eof_error=is_eof_error, )
[ "Read", "the", "contents", "of", "a", "file", "as", "a", "Lisp", "expression", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L1083-L1101
[ "def", "read_file", "(", "filename", ":", "str", ",", "resolver", ":", "Resolver", "=", "None", ",", "data_readers", ":", "DataReaders", "=", "None", ",", "eof", ":", "Any", "=", "None", ",", "is_eof_error", ":", "bool", "=", "False", ",", ")", "->", "Iterable", "[", "ReaderForm", "]", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "yield", "from", "read", "(", "f", ",", "resolver", "=", "resolver", ",", "data_readers", "=", "data_readers", ",", "eof", "=", "eof", ",", "is_eof_error", "=", "is_eof_error", ",", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
StreamReader._update_loc
Update the internal line and column buffers after a new character is added. The column number is set to 0, so the first character on the next line is column number 1.
src/basilisp/lang/reader.py
def _update_loc(self, c): """Update the internal line and column buffers after a new character is added. The column number is set to 0, so the first character on the next line is column number 1.""" if newline_chars.match(c): self._col.append(0) self._line.append(self._line[-1] + 1) else: self._col.append(self._col[-1] + 1) self._line.append(self._line[-1])
def _update_loc(self, c): """Update the internal line and column buffers after a new character is added. The column number is set to 0, so the first character on the next line is column number 1.""" if newline_chars.match(c): self._col.append(0) self._line.append(self._line[-1] + 1) else: self._col.append(self._col[-1] + 1) self._line.append(self._line[-1])
[ "Update", "the", "internal", "line", "and", "column", "buffers", "after", "a", "new", "character", "is", "added", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L121-L132
[ "def", "_update_loc", "(", "self", ",", "c", ")", ":", "if", "newline_chars", ".", "match", "(", "c", ")", ":", "self", ".", "_col", ".", "append", "(", "0", ")", "self", ".", "_line", ".", "append", "(", "self", ".", "_line", "[", "-", "1", "]", "+", "1", ")", "else", ":", "self", ".", "_col", ".", "append", "(", "self", ".", "_col", "[", "-", "1", "]", "+", "1", ")", "self", ".", "_line", ".", "append", "(", "self", ".", "_line", "[", "-", "1", "]", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
StreamReader.pushback
Push one character back onto the stream, allowing it to be read again.
src/basilisp/lang/reader.py
def pushback(self) -> None: """Push one character back onto the stream, allowing it to be read again.""" if abs(self._idx - 1) > self._pushback_depth: raise IndexError("Exceeded pushback depth") self._idx -= 1
def pushback(self) -> None: """Push one character back onto the stream, allowing it to be read again.""" if abs(self._idx - 1) > self._pushback_depth: raise IndexError("Exceeded pushback depth") self._idx -= 1
[ "Push", "one", "character", "back", "onto", "the", "stream", "allowing", "it", "to", "be", "read", "again", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L138-L143
[ "def", "pushback", "(", "self", ")", "->", "None", ":", "if", "abs", "(", "self", ".", "_idx", "-", "1", ")", ">", "self", ".", "_pushback_depth", ":", "raise", "IndexError", "(", "\"Exceeded pushback depth\"", ")", "self", ".", "_idx", "-=", "1" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
StreamReader.next_token
Advance the stream forward by one character and return the next token in the stream.
src/basilisp/lang/reader.py
def next_token(self) -> str: """Advance the stream forward by one character and return the next token in the stream.""" if self._idx < StreamReader.DEFAULT_INDEX: self._idx += 1 else: c = self._stream.read(1) self._update_loc(c) self._buffer.append(c) return self.peek()
def next_token(self) -> str: """Advance the stream forward by one character and return the next token in the stream.""" if self._idx < StreamReader.DEFAULT_INDEX: self._idx += 1 else: c = self._stream.read(1) self._update_loc(c) self._buffer.append(c) return self.peek()
[ "Advance", "the", "stream", "forward", "by", "one", "character", "and", "return", "the", "next", "token", "in", "the", "stream", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L152-L161
[ "def", "next_token", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_idx", "<", "StreamReader", ".", "DEFAULT_INDEX", ":", "self", ".", "_idx", "+=", "1", "else", ":", "c", "=", "self", ".", "_stream", ".", "read", "(", "1", ")", "self", ".", "_update_loc", "(", "c", ")", "self", ".", "_buffer", ".", "append", "(", "c", ")", "return", "self", ".", "peek", "(", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_basilisp_bytecode
Return the bytes for a Basilisp bytecode cache file.
src/basilisp/importer.py
def _basilisp_bytecode( mtime: int, source_size: int, code: List[types.CodeType] ) -> bytes: """Return the bytes for a Basilisp bytecode cache file.""" data = bytearray(MAGIC_NUMBER) data.extend(_w_long(mtime)) data.extend(_w_long(source_size)) data.extend(marshal.dumps(code)) # type: ignore return data
def _basilisp_bytecode( mtime: int, source_size: int, code: List[types.CodeType] ) -> bytes: """Return the bytes for a Basilisp bytecode cache file.""" data = bytearray(MAGIC_NUMBER) data.extend(_w_long(mtime)) data.extend(_w_long(source_size)) data.extend(marshal.dumps(code)) # type: ignore return data
[ "Return", "the", "bytes", "for", "a", "Basilisp", "bytecode", "cache", "file", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L35-L43
[ "def", "_basilisp_bytecode", "(", "mtime", ":", "int", ",", "source_size", ":", "int", ",", "code", ":", "List", "[", "types", ".", "CodeType", "]", ")", "->", "bytes", ":", "data", "=", "bytearray", "(", "MAGIC_NUMBER", ")", "data", ".", "extend", "(", "_w_long", "(", "mtime", ")", ")", "data", ".", "extend", "(", "_w_long", "(", "source_size", ")", ")", "data", ".", "extend", "(", "marshal", ".", "dumps", "(", "code", ")", ")", "# type: ignore", "return", "data" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_get_basilisp_bytecode
Unmarshal the bytes from a Basilisp bytecode cache file, validating the file header prior to returning. If the file header does not match, throw an exception.
src/basilisp/importer.py
def _get_basilisp_bytecode( fullname: str, mtime: int, source_size: int, cache_data: bytes ) -> List[types.CodeType]: """Unmarshal the bytes from a Basilisp bytecode cache file, validating the file header prior to returning. If the file header does not match, throw an exception.""" exc_details = {"name": fullname} magic = cache_data[:4] raw_timestamp = cache_data[4:8] raw_size = cache_data[8:12] if magic != MAGIC_NUMBER: message = ( f"Incorrect magic number ({magic}) in {fullname}; expected {MAGIC_NUMBER}" ) logger.debug(message) raise ImportError(message, **exc_details) # type: ignore elif len(raw_timestamp) != 4: message = f"Reached EOF while reading timestamp in {fullname}" logger.debug(message) raise EOFError(message) elif _r_long(raw_timestamp) != mtime: message = f"Non-matching timestamp ({_r_long(raw_timestamp)}) in {fullname} bytecode cache; expected {mtime}" logger.debug(message) raise ImportError(message, **exc_details) # type: ignore elif len(raw_size) != 4: message = f"Reached EOF while reading size of source in {fullname}" logger.debug(message) raise EOFError(message) elif _r_long(raw_size) != source_size: message = f"Non-matching filesize ({_r_long(raw_size)}) in {fullname} bytecode cache; expected {source_size}" logger.debug(message) raise ImportError(message, **exc_details) # type: ignore return marshal.loads(cache_data[12:])
def _get_basilisp_bytecode( fullname: str, mtime: int, source_size: int, cache_data: bytes ) -> List[types.CodeType]: """Unmarshal the bytes from a Basilisp bytecode cache file, validating the file header prior to returning. If the file header does not match, throw an exception.""" exc_details = {"name": fullname} magic = cache_data[:4] raw_timestamp = cache_data[4:8] raw_size = cache_data[8:12] if magic != MAGIC_NUMBER: message = ( f"Incorrect magic number ({magic}) in {fullname}; expected {MAGIC_NUMBER}" ) logger.debug(message) raise ImportError(message, **exc_details) # type: ignore elif len(raw_timestamp) != 4: message = f"Reached EOF while reading timestamp in {fullname}" logger.debug(message) raise EOFError(message) elif _r_long(raw_timestamp) != mtime: message = f"Non-matching timestamp ({_r_long(raw_timestamp)}) in {fullname} bytecode cache; expected {mtime}" logger.debug(message) raise ImportError(message, **exc_details) # type: ignore elif len(raw_size) != 4: message = f"Reached EOF while reading size of source in {fullname}" logger.debug(message) raise EOFError(message) elif _r_long(raw_size) != source_size: message = f"Non-matching filesize ({_r_long(raw_size)}) in {fullname} bytecode cache; expected {source_size}" logger.debug(message) raise ImportError(message, **exc_details) # type: ignore return marshal.loads(cache_data[12:])
[ "Unmarshal", "the", "bytes", "from", "a", "Basilisp", "bytecode", "cache", "file", "validating", "the", "file", "header", "prior", "to", "returning", ".", "If", "the", "file", "header", "does", "not", "match", "throw", "an", "exception", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L46-L79
[ "def", "_get_basilisp_bytecode", "(", "fullname", ":", "str", ",", "mtime", ":", "int", ",", "source_size", ":", "int", ",", "cache_data", ":", "bytes", ")", "->", "List", "[", "types", ".", "CodeType", "]", ":", "exc_details", "=", "{", "\"name\"", ":", "fullname", "}", "magic", "=", "cache_data", "[", ":", "4", "]", "raw_timestamp", "=", "cache_data", "[", "4", ":", "8", "]", "raw_size", "=", "cache_data", "[", "8", ":", "12", "]", "if", "magic", "!=", "MAGIC_NUMBER", ":", "message", "=", "(", "f\"Incorrect magic number ({magic}) in {fullname}; expected {MAGIC_NUMBER}\"", ")", "logger", ".", "debug", "(", "message", ")", "raise", "ImportError", "(", "message", ",", "*", "*", "exc_details", ")", "# type: ignore", "elif", "len", "(", "raw_timestamp", ")", "!=", "4", ":", "message", "=", "f\"Reached EOF while reading timestamp in {fullname}\"", "logger", ".", "debug", "(", "message", ")", "raise", "EOFError", "(", "message", ")", "elif", "_r_long", "(", "raw_timestamp", ")", "!=", "mtime", ":", "message", "=", "f\"Non-matching timestamp ({_r_long(raw_timestamp)}) in {fullname} bytecode cache; expected {mtime}\"", "logger", ".", "debug", "(", "message", ")", "raise", "ImportError", "(", "message", ",", "*", "*", "exc_details", ")", "# type: ignore", "elif", "len", "(", "raw_size", ")", "!=", "4", ":", "message", "=", "f\"Reached EOF while reading size of source in {fullname}\"", "logger", ".", "debug", "(", "message", ")", "raise", "EOFError", "(", "message", ")", "elif", "_r_long", "(", "raw_size", ")", "!=", "source_size", ":", "message", "=", "f\"Non-matching filesize ({_r_long(raw_size)}) in {fullname} bytecode cache; expected {source_size}\"", "logger", ".", "debug", "(", "message", ")", "raise", "ImportError", "(", "message", ",", "*", "*", "exc_details", ")", "# type: ignore", "return", "marshal", ".", "loads", "(", "cache_data", "[", "12", ":", "]", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_cache_from_source
Return the path to the cached file for the given path. The original path does not have to exist.
src/basilisp/importer.py
def _cache_from_source(path: str) -> str: """Return the path to the cached file for the given path. The original path does not have to exist.""" cache_path, cache_file = os.path.split(importlib.util.cache_from_source(path)) filename, _ = os.path.splitext(cache_file) return os.path.join(cache_path, filename + ".lpyc")
def _cache_from_source(path: str) -> str: """Return the path to the cached file for the given path. The original path does not have to exist.""" cache_path, cache_file = os.path.split(importlib.util.cache_from_source(path)) filename, _ = os.path.splitext(cache_file) return os.path.join(cache_path, filename + ".lpyc")
[ "Return", "the", "path", "to", "the", "cached", "file", "for", "the", "given", "path", ".", "The", "original", "path", "does", "not", "have", "to", "exist", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L82-L87
[ "def", "_cache_from_source", "(", "path", ":", "str", ")", "->", "str", ":", "cache_path", ",", "cache_file", "=", "os", ".", "path", ".", "split", "(", "importlib", ".", "util", ".", "cache_from_source", "(", "path", ")", ")", "filename", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "cache_file", ")", "return", "os", ".", "path", ".", "join", "(", "cache_path", ",", "filename", "+", "\".lpyc\"", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
hook_imports
Hook into Python's import machinery with a custom Basilisp code importer. Once this is called, Basilisp code may be called from within Python code using standard `import module.submodule` syntax.
src/basilisp/importer.py
def hook_imports(): """Hook into Python's import machinery with a custom Basilisp code importer. Once this is called, Basilisp code may be called from within Python code using standard `import module.submodule` syntax.""" if any([isinstance(o, BasilispImporter) for o in sys.meta_path]): return sys.meta_path.insert( 0, BasilispImporter() # pylint:disable=abstract-class-instantiated )
def hook_imports(): """Hook into Python's import machinery with a custom Basilisp code importer. Once this is called, Basilisp code may be called from within Python code using standard `import module.submodule` syntax.""" if any([isinstance(o, BasilispImporter) for o in sys.meta_path]): return sys.meta_path.insert( 0, BasilispImporter() # pylint:disable=abstract-class-instantiated )
[ "Hook", "into", "Python", "s", "import", "machinery", "with", "a", "custom", "Basilisp", "code", "importer", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L286-L296
[ "def", "hook_imports", "(", ")", ":", "if", "any", "(", "[", "isinstance", "(", "o", ",", "BasilispImporter", ")", "for", "o", "in", "sys", ".", "meta_path", "]", ")", ":", "return", "sys", ".", "meta_path", ".", "insert", "(", "0", ",", "BasilispImporter", "(", ")", "# pylint:disable=abstract-class-instantiated", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
BasilispImporter.find_spec
Find the ModuleSpec for the specified Basilisp module. Returns None if the module is not a Basilisp module to allow import processing to continue.
src/basilisp/importer.py
def find_spec( self, fullname: str, path, # Optional[List[str]] # MyPy complains this is incompatible with supertype target: types.ModuleType = None, ) -> Optional[importlib.machinery.ModuleSpec]: """Find the ModuleSpec for the specified Basilisp module. Returns None if the module is not a Basilisp module to allow import processing to continue.""" package_components = fullname.split(".") if path is None: path = sys.path module_name = package_components else: module_name = [package_components[-1]] for entry in path: filenames = [ f"{os.path.join(entry, *module_name, '__init__')}.lpy", f"{os.path.join(entry, *module_name)}.lpy", ] for filename in filenames: if os.path.exists(filename): state = { "fullname": fullname, "filename": filename, "path": entry, "target": target, "cache_filename": _cache_from_source(filename), } logger.debug( f"Found potential Basilisp module '{fullname}' in file '{filename}'" ) return importlib.machinery.ModuleSpec( fullname, self, origin=filename, loader_state=state ) return None
def find_spec( self, fullname: str, path, # Optional[List[str]] # MyPy complains this is incompatible with supertype target: types.ModuleType = None, ) -> Optional[importlib.machinery.ModuleSpec]: """Find the ModuleSpec for the specified Basilisp module. Returns None if the module is not a Basilisp module to allow import processing to continue.""" package_components = fullname.split(".") if path is None: path = sys.path module_name = package_components else: module_name = [package_components[-1]] for entry in path: filenames = [ f"{os.path.join(entry, *module_name, '__init__')}.lpy", f"{os.path.join(entry, *module_name)}.lpy", ] for filename in filenames: if os.path.exists(filename): state = { "fullname": fullname, "filename": filename, "path": entry, "target": target, "cache_filename": _cache_from_source(filename), } logger.debug( f"Found potential Basilisp module '{fullname}' in file '{filename}'" ) return importlib.machinery.ModuleSpec( fullname, self, origin=filename, loader_state=state ) return None
[ "Find", "the", "ModuleSpec", "for", "the", "specified", "Basilisp", "module", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L97-L133
[ "def", "find_spec", "(", "self", ",", "fullname", ":", "str", ",", "path", ",", "# Optional[List[str]] # MyPy complains this is incompatible with supertype", "target", ":", "types", ".", "ModuleType", "=", "None", ",", ")", "->", "Optional", "[", "importlib", ".", "machinery", ".", "ModuleSpec", "]", ":", "package_components", "=", "fullname", ".", "split", "(", "\".\"", ")", "if", "path", "is", "None", ":", "path", "=", "sys", ".", "path", "module_name", "=", "package_components", "else", ":", "module_name", "=", "[", "package_components", "[", "-", "1", "]", "]", "for", "entry", "in", "path", ":", "filenames", "=", "[", "f\"{os.path.join(entry, *module_name, '__init__')}.lpy\"", ",", "f\"{os.path.join(entry, *module_name)}.lpy\"", ",", "]", "for", "filename", "in", "filenames", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "state", "=", "{", "\"fullname\"", ":", "fullname", ",", "\"filename\"", ":", "filename", ",", "\"path\"", ":", "entry", ",", "\"target\"", ":", "target", ",", "\"cache_filename\"", ":", "_cache_from_source", "(", "filename", ")", ",", "}", "logger", ".", "debug", "(", "f\"Found potential Basilisp module '{fullname}' in file '{filename}'\"", ")", "return", "importlib", ".", "machinery", ".", "ModuleSpec", "(", "fullname", ",", "self", ",", "origin", "=", "filename", ",", "loader_state", "=", "state", ")", "return", "None" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
BasilispImporter._exec_cached_module
Load and execute a cached Basilisp module.
src/basilisp/importer.py
def _exec_cached_module( self, fullname: str, loader_state: Mapping[str, str], path_stats: Mapping[str, int], module: types.ModuleType, ): """Load and execute a cached Basilisp module.""" filename = loader_state["filename"] cache_filename = loader_state["cache_filename"] with timed( lambda duration: logger.debug( f"Loaded cached Basilisp module '{fullname}' in {duration / 1000000}ms" ) ): logger.debug(f"Checking for cached Basilisp module '{fullname}''") cache_data = self.get_data(cache_filename) cached_code = _get_basilisp_bytecode( fullname, path_stats["mtime"], path_stats["size"], cache_data ) compiler.compile_bytecode( cached_code, compiler.GeneratorContext(filename=filename), compiler.PythonASTOptimizer(), module, )
def _exec_cached_module( self, fullname: str, loader_state: Mapping[str, str], path_stats: Mapping[str, int], module: types.ModuleType, ): """Load and execute a cached Basilisp module.""" filename = loader_state["filename"] cache_filename = loader_state["cache_filename"] with timed( lambda duration: logger.debug( f"Loaded cached Basilisp module '{fullname}' in {duration / 1000000}ms" ) ): logger.debug(f"Checking for cached Basilisp module '{fullname}''") cache_data = self.get_data(cache_filename) cached_code = _get_basilisp_bytecode( fullname, path_stats["mtime"], path_stats["size"], cache_data ) compiler.compile_bytecode( cached_code, compiler.GeneratorContext(filename=filename), compiler.PythonASTOptimizer(), module, )
[ "Load", "and", "execute", "a", "cached", "Basilisp", "module", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L175-L201
[ "def", "_exec_cached_module", "(", "self", ",", "fullname", ":", "str", ",", "loader_state", ":", "Mapping", "[", "str", ",", "str", "]", ",", "path_stats", ":", "Mapping", "[", "str", ",", "int", "]", ",", "module", ":", "types", ".", "ModuleType", ",", ")", ":", "filename", "=", "loader_state", "[", "\"filename\"", "]", "cache_filename", "=", "loader_state", "[", "\"cache_filename\"", "]", "with", "timed", "(", "lambda", "duration", ":", "logger", ".", "debug", "(", "f\"Loaded cached Basilisp module '{fullname}' in {duration / 1000000}ms\"", ")", ")", ":", "logger", ".", "debug", "(", "f\"Checking for cached Basilisp module '{fullname}''\"", ")", "cache_data", "=", "self", ".", "get_data", "(", "cache_filename", ")", "cached_code", "=", "_get_basilisp_bytecode", "(", "fullname", ",", "path_stats", "[", "\"mtime\"", "]", ",", "path_stats", "[", "\"size\"", "]", ",", "cache_data", ")", "compiler", ".", "compile_bytecode", "(", "cached_code", ",", "compiler", ".", "GeneratorContext", "(", "filename", "=", "filename", ")", ",", "compiler", ".", "PythonASTOptimizer", "(", ")", ",", "module", ",", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
BasilispImporter._exec_module
Load and execute a non-cached Basilisp module.
src/basilisp/importer.py
def _exec_module( self, fullname: str, loader_state: Mapping[str, str], path_stats: Mapping[str, int], module: types.ModuleType, ): """Load and execute a non-cached Basilisp module.""" filename = loader_state["filename"] cache_filename = loader_state["cache_filename"] with timed( lambda duration: logger.debug( f"Loaded Basilisp module '{fullname}' in {duration / 1000000}ms" ) ): # During compilation, bytecode objects are added to the list via the closure # add_bytecode below, which is passed to the compiler. The collected bytecodes # will be used to generate an .lpyc file for caching the compiled file. all_bytecode = [] def add_bytecode(bytecode: types.CodeType): all_bytecode.append(bytecode) logger.debug(f"Reading and compiling Basilisp module '{fullname}'") forms = reader.read_file(filename, resolver=runtime.resolve_alias) compiler.compile_module( # pylint: disable=unexpected-keyword-arg forms, compiler.CompilerContext(filename=filename), module, collect_bytecode=add_bytecode, ) # Cache the bytecode that was collected through the compilation run. cache_file_bytes = _basilisp_bytecode( path_stats["mtime"], path_stats["size"], all_bytecode ) self._cache_bytecode(filename, cache_filename, cache_file_bytes)
def _exec_module( self, fullname: str, loader_state: Mapping[str, str], path_stats: Mapping[str, int], module: types.ModuleType, ): """Load and execute a non-cached Basilisp module.""" filename = loader_state["filename"] cache_filename = loader_state["cache_filename"] with timed( lambda duration: logger.debug( f"Loaded Basilisp module '{fullname}' in {duration / 1000000}ms" ) ): # During compilation, bytecode objects are added to the list via the closure # add_bytecode below, which is passed to the compiler. The collected bytecodes # will be used to generate an .lpyc file for caching the compiled file. all_bytecode = [] def add_bytecode(bytecode: types.CodeType): all_bytecode.append(bytecode) logger.debug(f"Reading and compiling Basilisp module '{fullname}'") forms = reader.read_file(filename, resolver=runtime.resolve_alias) compiler.compile_module( # pylint: disable=unexpected-keyword-arg forms, compiler.CompilerContext(filename=filename), module, collect_bytecode=add_bytecode, ) # Cache the bytecode that was collected through the compilation run. cache_file_bytes = _basilisp_bytecode( path_stats["mtime"], path_stats["size"], all_bytecode ) self._cache_bytecode(filename, cache_filename, cache_file_bytes)
[ "Load", "and", "execute", "a", "non", "-", "cached", "Basilisp", "module", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L203-L240
[ "def", "_exec_module", "(", "self", ",", "fullname", ":", "str", ",", "loader_state", ":", "Mapping", "[", "str", ",", "str", "]", ",", "path_stats", ":", "Mapping", "[", "str", ",", "int", "]", ",", "module", ":", "types", ".", "ModuleType", ",", ")", ":", "filename", "=", "loader_state", "[", "\"filename\"", "]", "cache_filename", "=", "loader_state", "[", "\"cache_filename\"", "]", "with", "timed", "(", "lambda", "duration", ":", "logger", ".", "debug", "(", "f\"Loaded Basilisp module '{fullname}' in {duration / 1000000}ms\"", ")", ")", ":", "# During compilation, bytecode objects are added to the list via the closure", "# add_bytecode below, which is passed to the compiler. The collected bytecodes", "# will be used to generate an .lpyc file for caching the compiled file.", "all_bytecode", "=", "[", "]", "def", "add_bytecode", "(", "bytecode", ":", "types", ".", "CodeType", ")", ":", "all_bytecode", ".", "append", "(", "bytecode", ")", "logger", ".", "debug", "(", "f\"Reading and compiling Basilisp module '{fullname}'\"", ")", "forms", "=", "reader", ".", "read_file", "(", "filename", ",", "resolver", "=", "runtime", ".", "resolve_alias", ")", "compiler", ".", "compile_module", "(", "# pylint: disable=unexpected-keyword-arg", "forms", ",", "compiler", ".", "CompilerContext", "(", "filename", "=", "filename", ")", ",", "module", ",", "collect_bytecode", "=", "add_bytecode", ",", ")", "# Cache the bytecode that was collected through the compilation run.", "cache_file_bytes", "=", "_basilisp_bytecode", "(", "path_stats", "[", "\"mtime\"", "]", ",", "path_stats", "[", "\"size\"", "]", ",", "all_bytecode", ")", "self", ".", "_cache_bytecode", "(", "filename", ",", "cache_filename", ",", "cache_file_bytes", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
BasilispImporter.exec_module
Compile the Basilisp module into Python code. Basilisp is fundamentally a form-at-a-time compilation, meaning that each form in a module may require code compiled from an earlier form, so we incrementally compile a Python module by evaluating a single top-level form at a time and inserting the resulting AST nodes into the Pyton module.
src/basilisp/importer.py
def exec_module(self, module): """Compile the Basilisp module into Python code. Basilisp is fundamentally a form-at-a-time compilation, meaning that each form in a module may require code compiled from an earlier form, so we incrementally compile a Python module by evaluating a single top-level form at a time and inserting the resulting AST nodes into the Pyton module.""" fullname = module.__name__ cached = self._cache[fullname] cached["module"] = module spec = cached["spec"] filename = spec.loader_state["filename"] path_stats = self.path_stats(filename) # During the bootstrapping process, the 'basilisp.core namespace is created with # a blank module. If we do not replace the module here with the module we are # generating, then we will not be able to use advanced compilation features such # as direct Python variable access to functions and other def'ed values. ns_name = demunge(fullname) ns: runtime.Namespace = runtime.set_current_ns(ns_name).value ns.module = module # Check if a valid, cached version of this Basilisp namespace exists and, if so, # load it and bypass the expensive compilation process below. if os.getenv(_NO_CACHE_ENVVAR, None) == "true": self._exec_module(fullname, spec.loader_state, path_stats, module) else: try: self._exec_cached_module( fullname, spec.loader_state, path_stats, module ) except (EOFError, ImportError, IOError, OSError) as e: logger.debug(f"Failed to load cached Basilisp module: {e}") self._exec_module(fullname, spec.loader_state, path_stats, module) # Because we want to (by default) add 'basilisp.core into every namespace by default, # we want to make sure we don't try to add 'basilisp.core into itself, causing a # circular import error. # # Later on, we can probably remove this and just use the 'ns macro to auto-refer # all 'basilisp.core values into the current namespace. runtime.Namespace.add_default_import(ns_name)
def exec_module(self, module): """Compile the Basilisp module into Python code. Basilisp is fundamentally a form-at-a-time compilation, meaning that each form in a module may require code compiled from an earlier form, so we incrementally compile a Python module by evaluating a single top-level form at a time and inserting the resulting AST nodes into the Pyton module.""" fullname = module.__name__ cached = self._cache[fullname] cached["module"] = module spec = cached["spec"] filename = spec.loader_state["filename"] path_stats = self.path_stats(filename) # During the bootstrapping process, the 'basilisp.core namespace is created with # a blank module. If we do not replace the module here with the module we are # generating, then we will not be able to use advanced compilation features such # as direct Python variable access to functions and other def'ed values. ns_name = demunge(fullname) ns: runtime.Namespace = runtime.set_current_ns(ns_name).value ns.module = module # Check if a valid, cached version of this Basilisp namespace exists and, if so, # load it and bypass the expensive compilation process below. if os.getenv(_NO_CACHE_ENVVAR, None) == "true": self._exec_module(fullname, spec.loader_state, path_stats, module) else: try: self._exec_cached_module( fullname, spec.loader_state, path_stats, module ) except (EOFError, ImportError, IOError, OSError) as e: logger.debug(f"Failed to load cached Basilisp module: {e}") self._exec_module(fullname, spec.loader_state, path_stats, module) # Because we want to (by default) add 'basilisp.core into every namespace by default, # we want to make sure we don't try to add 'basilisp.core into itself, causing a # circular import error. # # Later on, we can probably remove this and just use the 'ns macro to auto-refer # all 'basilisp.core values into the current namespace. runtime.Namespace.add_default_import(ns_name)
[ "Compile", "the", "Basilisp", "module", "into", "Python", "code", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L242-L283
[ "def", "exec_module", "(", "self", ",", "module", ")", ":", "fullname", "=", "module", ".", "__name__", "cached", "=", "self", ".", "_cache", "[", "fullname", "]", "cached", "[", "\"module\"", "]", "=", "module", "spec", "=", "cached", "[", "\"spec\"", "]", "filename", "=", "spec", ".", "loader_state", "[", "\"filename\"", "]", "path_stats", "=", "self", ".", "path_stats", "(", "filename", ")", "# During the bootstrapping process, the 'basilisp.core namespace is created with", "# a blank module. If we do not replace the module here with the module we are", "# generating, then we will not be able to use advanced compilation features such", "# as direct Python variable access to functions and other def'ed values.", "ns_name", "=", "demunge", "(", "fullname", ")", "ns", ":", "runtime", ".", "Namespace", "=", "runtime", ".", "set_current_ns", "(", "ns_name", ")", ".", "value", "ns", ".", "module", "=", "module", "# Check if a valid, cached version of this Basilisp namespace exists and, if so,", "# load it and bypass the expensive compilation process below.", "if", "os", ".", "getenv", "(", "_NO_CACHE_ENVVAR", ",", "None", ")", "==", "\"true\"", ":", "self", ".", "_exec_module", "(", "fullname", ",", "spec", ".", "loader_state", ",", "path_stats", ",", "module", ")", "else", ":", "try", ":", "self", ".", "_exec_cached_module", "(", "fullname", ",", "spec", ".", "loader_state", ",", "path_stats", ",", "module", ")", "except", "(", "EOFError", ",", "ImportError", ",", "IOError", ",", "OSError", ")", "as", "e", ":", "logger", ".", "debug", "(", "f\"Failed to load cached Basilisp module: {e}\"", ")", "self", ".", "_exec_module", "(", "fullname", ",", "spec", ".", "loader_state", ",", "path_stats", ",", "module", ")", "# Because we want to (by default) add 'basilisp.core into every namespace by default,", "# we want to make sure we don't try to add 'basilisp.core into itself, causing a", "# circular import error.", "#", "# Later on, we can probably remove this and just use the 'ns macro to auto-refer", "# all 'basilisp.core values into the current namespace.", "runtime", ".", "Namespace", ".", "add_default_import", "(", "ns_name", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
symbol
Create a new symbol.
src/basilisp/lang/symbol.py
def symbol(name: str, ns: Optional[str] = None, meta=None) -> Symbol: """Create a new symbol.""" return Symbol(name, ns=ns, meta=meta)
def symbol(name: str, ns: Optional[str] = None, meta=None) -> Symbol: """Create a new symbol.""" return Symbol(name, ns=ns, meta=meta)
[ "Create", "a", "new", "symbol", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/symbol.py#L58-L60
[ "def", "symbol", "(", "name", ":", "str", ",", "ns", ":", "Optional", "[", "str", "]", "=", "None", ",", "meta", "=", "None", ")", "->", "Symbol", ":", "return", "Symbol", "(", "name", ",", "ns", "=", "ns", ",", "meta", "=", "meta", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
complete
Return an iterable of possible completions for the given text.
src/basilisp/lang/keyword.py
def complete( text: str, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN ) -> Iterable[str]: """Return an iterable of possible completions for the given text.""" assert text.startswith(":") interns = kw_cache.deref() text = text[1:] if "/" in text: prefix, suffix = text.split("/", maxsplit=1) results = filter( lambda kw: (kw.ns is not None and kw.ns == prefix) and kw.name.startswith(suffix), interns.itervalues(), ) else: results = filter( lambda kw: kw.name.startswith(text) or (kw.ns is not None and kw.ns.startswith(text)), interns.itervalues(), ) return map(str, results)
def complete( text: str, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN ) -> Iterable[str]: """Return an iterable of possible completions for the given text.""" assert text.startswith(":") interns = kw_cache.deref() text = text[1:] if "/" in text: prefix, suffix = text.split("/", maxsplit=1) results = filter( lambda kw: (kw.ns is not None and kw.ns == prefix) and kw.name.startswith(suffix), interns.itervalues(), ) else: results = filter( lambda kw: kw.name.startswith(text) or (kw.ns is not None and kw.ns.startswith(text)), interns.itervalues(), ) return map(str, results)
[ "Return", "an", "iterable", "of", "possible", "completions", "for", "the", "given", "text", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/keyword.py#L44-L66
[ "def", "complete", "(", "text", ":", "str", ",", "kw_cache", ":", "atom", ".", "Atom", "[", "\"PMap[int, Keyword]\"", "]", "=", "__INTERN", ")", "->", "Iterable", "[", "str", "]", ":", "assert", "text", ".", "startswith", "(", "\":\"", ")", "interns", "=", "kw_cache", ".", "deref", "(", ")", "text", "=", "text", "[", "1", ":", "]", "if", "\"/\"", "in", "text", ":", "prefix", ",", "suffix", "=", "text", ".", "split", "(", "\"/\"", ",", "maxsplit", "=", "1", ")", "results", "=", "filter", "(", "lambda", "kw", ":", "(", "kw", ".", "ns", "is", "not", "None", "and", "kw", ".", "ns", "==", "prefix", ")", "and", "kw", ".", "name", ".", "startswith", "(", "suffix", ")", ",", "interns", ".", "itervalues", "(", ")", ",", ")", "else", ":", "results", "=", "filter", "(", "lambda", "kw", ":", "kw", ".", "name", ".", "startswith", "(", "text", ")", "or", "(", "kw", ".", "ns", "is", "not", "None", "and", "kw", ".", "ns", ".", "startswith", "(", "text", ")", ")", ",", "interns", ".", "itervalues", "(", ")", ",", ")", "return", "map", "(", "str", ",", "results", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
__get_or_create
Private swap function used to either get the interned keyword instance from the input string.
src/basilisp/lang/keyword.py
def __get_or_create( kw_cache: "PMap[int, Keyword]", h: int, name: str, ns: Optional[str] ) -> PMap: """Private swap function used to either get the interned keyword instance from the input string.""" if h in kw_cache: return kw_cache kw = Keyword(name, ns=ns) return kw_cache.set(h, kw)
def __get_or_create( kw_cache: "PMap[int, Keyword]", h: int, name: str, ns: Optional[str] ) -> PMap: """Private swap function used to either get the interned keyword instance from the input string.""" if h in kw_cache: return kw_cache kw = Keyword(name, ns=ns) return kw_cache.set(h, kw)
[ "Private", "swap", "function", "used", "to", "either", "get", "the", "interned", "keyword", "instance", "from", "the", "input", "string", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/keyword.py#L69-L77
[ "def", "__get_or_create", "(", "kw_cache", ":", "\"PMap[int, Keyword]\"", ",", "h", ":", "int", ",", "name", ":", "str", ",", "ns", ":", "Optional", "[", "str", "]", ")", "->", "PMap", ":", "if", "h", "in", "kw_cache", ":", "return", "kw_cache", "kw", "=", "Keyword", "(", "name", ",", "ns", "=", "ns", ")", "return", "kw_cache", ".", "set", "(", "h", ",", "kw", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
keyword
Create a new keyword.
src/basilisp/lang/keyword.py
def keyword( name: str, ns: Optional[str] = None, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN, ) -> Keyword: """Create a new keyword.""" h = hash((name, ns)) return kw_cache.swap(__get_or_create, h, name, ns)[h]
def keyword( name: str, ns: Optional[str] = None, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN, ) -> Keyword: """Create a new keyword.""" h = hash((name, ns)) return kw_cache.swap(__get_or_create, h, name, ns)[h]
[ "Create", "a", "new", "keyword", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/keyword.py#L80-L87
[ "def", "keyword", "(", "name", ":", "str", ",", "ns", ":", "Optional", "[", "str", "]", "=", "None", ",", "kw_cache", ":", "atom", ".", "Atom", "[", "\"PMap[int, Keyword]\"", "]", "=", "__INTERN", ",", ")", "->", "Keyword", ":", "h", "=", "hash", "(", "(", "name", ",", "ns", ")", ")", "return", "kw_cache", ".", "swap", "(", "__get_or_create", ",", "h", ",", "name", ",", "ns", ")", "[", "h", "]" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_chain_py_ast
Chain a sequence of generated Python ASTs into a tuple of dependency nodes
src/basilisp/lang/compiler/generator.py
def _chain_py_ast(*genned: GeneratedPyAST,) -> Tuple[PyASTStream, PyASTStream]: """Chain a sequence of generated Python ASTs into a tuple of dependency nodes""" deps = chain.from_iterable(map(lambda n: n.dependencies, genned)) nodes = map(lambda n: n.node, genned) return deps, nodes
def _chain_py_ast(*genned: GeneratedPyAST,) -> Tuple[PyASTStream, PyASTStream]: """Chain a sequence of generated Python ASTs into a tuple of dependency nodes""" deps = chain.from_iterable(map(lambda n: n.dependencies, genned)) nodes = map(lambda n: n.node, genned) return deps, nodes
[ "Chain", "a", "sequence", "of", "generated", "Python", "ASTs", "into", "a", "tuple", "of", "dependency", "nodes" ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L294-L298
[ "def", "_chain_py_ast", "(", "*", "genned", ":", "GeneratedPyAST", ",", ")", "->", "Tuple", "[", "PyASTStream", ",", "PyASTStream", "]", ":", "deps", "=", "chain", ".", "from_iterable", "(", "map", "(", "lambda", "n", ":", "n", ".", "dependencies", ",", "genned", ")", ")", "nodes", "=", "map", "(", "lambda", "n", ":", "n", ".", "node", ",", "genned", ")", "return", "deps", ",", "nodes" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_load_attr
Generate recursive Python Attribute AST nodes for resolving nested names.
src/basilisp/lang/compiler/generator.py
def _load_attr(name: str, ctx: ast.AST = ast.Load()) -> ast.Attribute: """Generate recursive Python Attribute AST nodes for resolving nested names.""" attrs = name.split(".") def attr_node(node, idx): if idx >= len(attrs): node.ctx = ctx return node return attr_node( ast.Attribute(value=node, attr=attrs[idx], ctx=ast.Load()), idx + 1 ) return attr_node(ast.Name(id=attrs[0], ctx=ast.Load()), 1)
def _load_attr(name: str, ctx: ast.AST = ast.Load()) -> ast.Attribute: """Generate recursive Python Attribute AST nodes for resolving nested names.""" attrs = name.split(".") def attr_node(node, idx): if idx >= len(attrs): node.ctx = ctx return node return attr_node( ast.Attribute(value=node, attr=attrs[idx], ctx=ast.Load()), idx + 1 ) return attr_node(ast.Name(id=attrs[0], ctx=ast.Load()), 1)
[ "Generate", "recursive", "Python", "Attribute", "AST", "nodes", "for", "resolving", "nested", "names", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L301-L314
[ "def", "_load_attr", "(", "name", ":", "str", ",", "ctx", ":", "ast", ".", "AST", "=", "ast", ".", "Load", "(", ")", ")", "->", "ast", ".", "Attribute", ":", "attrs", "=", "name", ".", "split", "(", "\".\"", ")", "def", "attr_node", "(", "node", ",", "idx", ")", ":", "if", "idx", ">=", "len", "(", "attrs", ")", ":", "node", ".", "ctx", "=", "ctx", "return", "node", "return", "attr_node", "(", "ast", ".", "Attribute", "(", "value", "=", "node", ",", "attr", "=", "attrs", "[", "idx", "]", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "idx", "+", "1", ")", "return", "attr_node", "(", "ast", ".", "Name", "(", "id", "=", "attrs", "[", "0", "]", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "1", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_simple_ast_generator
Wrap simpler AST generators to return a GeneratedPyAST.
src/basilisp/lang/compiler/generator.py
def _simple_ast_generator(gen_ast): """Wrap simpler AST generators to return a GeneratedPyAST.""" @wraps(gen_ast) def wrapped_ast_generator(ctx: GeneratorContext, form: LispForm) -> GeneratedPyAST: return GeneratedPyAST(node=gen_ast(ctx, form)) return wrapped_ast_generator
def _simple_ast_generator(gen_ast): """Wrap simpler AST generators to return a GeneratedPyAST.""" @wraps(gen_ast) def wrapped_ast_generator(ctx: GeneratorContext, form: LispForm) -> GeneratedPyAST: return GeneratedPyAST(node=gen_ast(ctx, form)) return wrapped_ast_generator
[ "Wrap", "simpler", "AST", "generators", "to", "return", "a", "GeneratedPyAST", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L317-L324
[ "def", "_simple_ast_generator", "(", "gen_ast", ")", ":", "@", "wraps", "(", "gen_ast", ")", "def", "wrapped_ast_generator", "(", "ctx", ":", "GeneratorContext", ",", "form", ":", "LispForm", ")", "->", "GeneratedPyAST", ":", "return", "GeneratedPyAST", "(", "node", "=", "gen_ast", "(", "ctx", ",", "form", ")", ")", "return", "wrapped_ast_generator" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_collection_ast
Turn a collection of Lisp forms into Python AST nodes.
src/basilisp/lang/compiler/generator.py
def _collection_ast( ctx: GeneratorContext, form: Iterable[Node] ) -> Tuple[PyASTStream, PyASTStream]: """Turn a collection of Lisp forms into Python AST nodes.""" return _chain_py_ast(*map(partial(gen_py_ast, ctx), form))
def _collection_ast( ctx: GeneratorContext, form: Iterable[Node] ) -> Tuple[PyASTStream, PyASTStream]: """Turn a collection of Lisp forms into Python AST nodes.""" return _chain_py_ast(*map(partial(gen_py_ast, ctx), form))
[ "Turn", "a", "collection", "of", "Lisp", "forms", "into", "Python", "AST", "nodes", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L327-L331
[ "def", "_collection_ast", "(", "ctx", ":", "GeneratorContext", ",", "form", ":", "Iterable", "[", "Node", "]", ")", "->", "Tuple", "[", "PyASTStream", ",", "PyASTStream", "]", ":", "return", "_chain_py_ast", "(", "*", "map", "(", "partial", "(", "gen_py_ast", ",", "ctx", ")", ",", "form", ")", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92
test
_clean_meta
Remove reader metadata from the form's meta map.
src/basilisp/lang/compiler/generator.py
def _clean_meta(form: IMeta) -> LispForm: """Remove reader metadata from the form's meta map.""" assert form.meta is not None, "Form must have non-null 'meta' attribute" meta = form.meta.dissoc(reader.READER_LINE_KW, reader.READER_COL_KW) if len(meta) == 0: return None return cast(lmap.Map, meta)
def _clean_meta(form: IMeta) -> LispForm: """Remove reader metadata from the form's meta map.""" assert form.meta is not None, "Form must have non-null 'meta' attribute" meta = form.meta.dissoc(reader.READER_LINE_KW, reader.READER_COL_KW) if len(meta) == 0: return None return cast(lmap.Map, meta)
[ "Remove", "reader", "metadata", "from", "the", "form", "s", "meta", "map", "." ]
chrisrink10/basilisp
python
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L334-L340
[ "def", "_clean_meta", "(", "form", ":", "IMeta", ")", "->", "LispForm", ":", "assert", "form", ".", "meta", "is", "not", "None", ",", "\"Form must have non-null 'meta' attribute\"", "meta", "=", "form", ".", "meta", ".", "dissoc", "(", "reader", ".", "READER_LINE_KW", ",", "reader", ".", "READER_COL_KW", ")", "if", "len", "(", "meta", ")", "==", "0", ":", "return", "None", "return", "cast", "(", "lmap", ".", "Map", ",", "meta", ")" ]
3d82670ee218ec64eb066289c82766d14d18cc92