code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if use_computation_graph: # use the action's annotations to generate the defaults if ignore_no_tokens is None: ignore_no_tokens = getattr(action, "ignore_no_tokens", False) if ignore_one_token is None: ignore_one_token = getattr(action, "ignore_one_token", False)...
def attach(item, action, greedy=False, ignore_no_tokens=None, ignore_one_token=None)
Set the parse action for the given item to create a node in the computation graph.
2.955889
2.796837
1.056868
logger.log_tag("unpack", tokens) if use_computation_graph: tokens = evaluate_tokens(tokens) if isinstance(tokens, ParseResults) and len(tokens) == 1: tokens = tokens[0] return tokens
def unpack(tokens)
Evaluate and unpack the given computation graph.
6.582388
6.483265
1.015289
for tokens, start, stop in grammar.parseWithTabs().scanString(text): yield unpack(tokens), start, stop
def all_matches(grammar, text)
Find all matches for grammar in text.
9.811892
10.018674
0.97936
for result in grammar.parseWithTabs().scanString(text): return True return False
def match_in(grammar, text)
Determine if there is a match for grammar in text.
8.784651
9.203596
0.95448
target_info = get_target_info(target) if not target_info: return py2_vers + py3_vers elif len(target_info) == 1: if target_info == (2,): return py2_vers elif target_info == (3,): return py3_vers else: raise CoconutInternalException("in...
def get_vers_for_target(target)
Gets a list of the versions supported by the given target.
2.896821
2.810807
1.030601
supported_vers = get_vers_for_target(target) if mode == "lowest": return supported_vers[0] elif mode == "highest": return supported_vers[-1] elif mode == "nearest": if sys.version_info[:2] in supported_vers: return sys.version_info[:2] else: r...
def get_target_info_len2(target, mode="lowest")
Converts target into a length 2 Python version tuple. Modes: - "lowest" (default): Gets the lowest version supported by the target. - "highest": Gets the highest version supported by the target. - "nearest": If the current version is supported, returns that, otherwise gets the highest.
2.589948
2.23242
1.160153
internal_assert(len(args) >= 2, "longest expects at least two args") matcher = args[0] + skip_whitespace for elem in args[1:]: matcher ^= elem + skip_whitespace return matcher
def longest(*args)
Match the longest of the given grammar elements.
6.854419
6.080754
1.127232
if skip < 1: complain(CoconutInternalException("invalid skip of line " + str(skip))) else: skips.append(skip) return skips
def addskip(skips, skip)
Add a line skip to the skips.
8.385513
7.371284
1.137592
count = 0 x = len(teststr) - 1 while x >= 0 and teststr[x] == testchar: count += 1 x -= 1 return count
def count_end(teststr, testchar)
Count instances of testchar at end of teststr.
2.032242
2.029298
1.001451
count = 0 for c in inputstring: if c in opens: # open parens/brackets/braces count -= 1 elif c in closes: # close parens/brackets/braces count += 1 return count
def paren_change(inputstring, opens=opens, closes=closes)
Determine the parenthetical change of level (num closes - num opens).
2.617823
2.588455
1.011346
return item | lparen.suppress() + item + rparen.suppress()
def maybeparens(lparen, item, rparen)
Wrap an item in optional parentheses, only applying them if necessary.
8.325788
9.711712
0.857294
if suppress: sep = sep.suppress() return item + ZeroOrMore(sep + item) + Optional(sep)
def tokenlist(item, sep, suppress=True)
Create a list of tokens matching the item.
5.909752
5.896377
1.002268
return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))
def itemlist(item, sep, suppress_trailing=True)
Create a list of items seperated by seps.
12.841146
12.906286
0.994953
last = rem_comment(code.splitlines()[-1]) return last.endswith(":") or last.endswith("\\") or paren_change(last) < 0
def should_indent(code)
Determines whether the next line should be indented.
11.364599
10.732272
1.058918
if inputstring.startswith("#"): comment, rest = inputstring.split("\n", 1) return comment + "\n", rest else: return "", inputstring
def split_leading_comment(inputstring)
Split into leading comment and rest.
2.875303
2.617639
1.098434
indent = "" while ( (max_indents is None or max_indents > 0) and line.startswith((openindent, closeindent)) ) or line.lstrip() != line: if max_indents is not None and line.startswith((openindent, closeindent)): max_indents -= 1 indent += line[0] line ...
def split_leading_indent(line, max_indents=None)
Split line into leading indent and main.
3.202756
3.022297
1.059709
indent = "" while ( (max_indents is None or max_indents > 0) and line.endswith((openindent, closeindent)) ) or line.rstrip() != line: if max_indents is not None and (line.endswith(openindent) or line.endswith(closeindent)): max_indents -= 1 indent = line[-1] ...
def split_trailing_indent(line, max_indents=None)
Split line into leading indent and main.
3.17908
3.084308
1.030727
leading_indent, line = split_leading_indent(line, max_indents) line, trailing_indent = split_trailing_indent(line, max_indents) return leading_indent, line, trailing_indent
def split_leading_trailing_indent(line, max_indents=None)
Split leading and trailing indent.
2.020414
1.840254
1.0979
change_in_level = ind_change(indentation) if change_in_level == 0: indents = "" elif change_in_level < 0: indents = closeindent * (-change_in_level) else: indents = openindent * change_in_level return indentation.replace(openindent, "").replace(closeindent, "") + indents
def collapse_indents(indentation)
Removes all openindent-closeindent pairs.
3.428651
3.096808
1.107157
results = [] intervals = [] for result, start, stop in all_matches(grammar, text): if result is not ignore_transform: internal_assert(isinstance(result, str), "got non-string transform result", result) if start == 0 and stop == len(text): return result ...
def transform(grammar, text)
Transform text by replacing matches to grammar.
2.81558
2.780078
1.01277
_invert = kwargs.get("_invert", False) internal_assert(set(kwargs.keys()) <= set(("_invert",)), "excess keyword arguments passed to disable_inside") level = [0] # number of wrapped items deep we are; in a list to allow modification @contextmanager def manage_item(self, instring, loc): ...
def disable_inside(item, *elems, **kwargs)
Prevent elems from matching inside of item. Returns (item with elem disabled, *new versions of elems).
5.10201
5.047875
1.010724
name = getattr(self.action, "__name__", None) # ascii(action) not defined for all actions, so must only be evaluated if getattr fails return name if name is not None else ascii(self.action)
def name(self)
Get the name of the action.
12.896206
11.811727
1.091814
if DEVELOP: internal_assert(not self.been_called, "inefficient reevaluation of action " + self.name + " with tokens", self.tokens) self.been_called = True evaluated_toks = evaluate_tokens(self.tokens) if logger.tracing: # avoid the overhead of the call if not tr...
def evaluate(self)
Get the result of evaluating the computation graph at this node.
6.728404
6.794354
0.990293
combined_tokens = super(CombineNode, self).postParse(original, loc, tokens) internal_assert(len(combined_tokens) == 1, "Combine produced multiple tokens", combined_tokens) return combined_tokens[0]
def _combine(self, original, loc, tokens)
Implement the parse action for Combine.
6.718801
5.647703
1.189652
return ComputationNode(self._combine, original, loc, tokens, ignore_no_tokens=True, ignore_one_token=True)
def postParse(self, original, loc, tokens)
Create a ComputationNode for Combine.
13.708963
6.788404
2.019468
with self.wrapper(self, instring, loc): return super(Wrap, self).parseImpl(instring, loc, *args, **kwargs)
def parseImpl(self, instring, loc, *args, **kwargs)
Wrapper around ParseElementEnhance.parseImpl.
4.496556
4.021086
1.118244
lines = compiled.splitlines() if len(lines) < 3 or not lines[2].startswith(hash_prefix): return None else: return lines[2][len(hash_prefix):]
def gethash(compiled)
Retrieve a hash from a header.
3.133818
2.963871
1.057339
compiled = compiled.strip() if compiled: out = [] for line in compiled.splitlines(): line = line.split("#", 1)[0].rstrip() if line: ind = 0 while line.startswith(" "): line = line[1:] ind += 1 ...
def minify(compiled)
Perform basic minifications. Fails on non-tabideal indentation or a string with a #.
3.593457
3.248208
1.106289
with open(os.path.join(template_dir, template) + template_ext, "r") as template_file: return template_file.read()
def get_template(template)
Read the given template file.
2.809493
2.78631
1.008321
internal_assert(which in allowed_headers, "invalid header type", which) if which == "none": return "" # initial, __coconut__, package, sys, code, file format_dict, target_startswith, target_info = process_header_args(which, target, use_hash, no_tco, strict) if which == "initial" or ...
def getheader(which, target="", use_hash=None, no_tco=False, strict=False)
Generate the specified header.
2.772531
2.755184
1.006296
return os.path.normpath(os.path.realpath(os.path.expanduser(path)))
def fixpath(path)
Uniformly format a path.
2.36969
2.352379
1.007359
out = [] for x in ver_str.split("."): try: x = int(x) except ValueError: pass out.append(x) return tuple(out)
def ver_str_to_tuple(ver_str)
Convert a version string into a version tuple.
2.155058
2.061974
1.045143
logger.log_cmd(["mypy"] + args) try: stdout, stderr, exit_code = run(args) except BaseException: traceback.print_exc() else: for line in stdout.splitlines(): yield line, False for line in stderr.splitlines(): yield line, True
def mypy_run(args)
Runs mypy with given arguments and shows the result.
3.505448
3.546743
0.988357
try: import coconut # NOQA except ImportError: sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def add_coconut_to_path()
Adds coconut to sys.path if it isn't there already.
2.331483
2.103389
1.108441
openedfile.seek(0) openedfile.truncate() openedfile.write(newcontents)
def writefile(openedfile, newcontents)
Set the contents of a file.
2.412438
2.610859
0.924001
if logger.verbose: return os.path.abspath(path) else: path = os.path.relpath(path) if path.startswith(os.curdir + os.sep): path = path[len(os.curdir + os.sep):] return path
def showpath(path)
Format a path for displaying.
2.495665
2.514508
0.992507
old_lines = code.splitlines() new_lines = [] for i in range(min(2, len(old_lines))): line = old_lines[i] if not (line.lstrip().startswith("#") and "coding" in line): new_lines.append(line) new_lines += old_lines[2:] return "\n".join(new_lines)
def rem_encoding(code)
Remove encoding declarations from compiled code so it can be passed to exec.
2.645057
2.344003
1.128436
if loc_vars is None: exec(code, glob_vars) else: exec(code, glob_vars, loc_vars)
def exec_func(code, glob_vars, loc_vars=None)
Wrapper around exec.
1.887233
1.937734
0.973938
try: result = eval(code, in_vars) except SyntaxError: pass # exec code outside of exception context else: if result is not None: print(ascii(result)) return # don't also exec code exec_func(code, in_vars)
def interpret(code, in_vars)
Try to evaluate the given code, otherwise execute it.
8.043476
6.812211
1.180744
try: import psutil except ImportError: logger.warn( "missing psutil; --jobs may not properly terminate", extra="run 'pip install coconut[jobs]' to fix", ) else: master = psutil.Process() children = master.children(recursive=True) w...
def kill_children()
Terminate all child processes.
4.110686
4.063108
1.01171
dirpath, filename = os.path.split(path) # we don't use os.path.splitext here because we want all extensions, # not just the last, to be put in exts name, exts = filename.split(os.extsep, 1) return dirpath, name, exts
def splitname(path)
Split a path into a directory, name, and extensions.
3.975421
3.696298
1.075514
if PY26: dirpath, name, _ = splitname(path) found = imp.find_module(name, [dirpath]) module = imp.load_module("__main__", *found) return vars(module) else: return runpy.run_path(path, run_name="__main__")
def run_file(path)
Run a module from a path and return its variables.
3.838845
3.27884
1.170793
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) stdout, stderr, retcode = [], [], None while retcode is None: if stdin is not None: logger.log_prefix("<0 ", stdin.rstrip()) raw_out, raw_err = p.communicate(stdin) stdin = None ...
def call_output(cmd, stdin=None, encoding_errors="replace", **kwargs)
Run command and read output.
2.56763
2.604442
0.985865
internal_assert(cmd and isinstance(cmd, list), "console commands must be passed as non-empty lists") try: from shutil import which except ImportError: pass else: cmd[0] = which(cmd[0]) or cmd[0] logger.log_cmd(cmd) try: if show_output and raise_errs: ...
def run_cmd(cmd, show_output=True, raise_errs=True, **kwargs)
Run a console command. When show_output=True, prints output and returns exit code, otherwise returns output. When raise_errs=True, raises a subprocess.CalledProcessError if the command fails.
2.933935
2.915137
1.006448
original = os.environ.get(mypy_path_env_var) if original is None: new_mypy_path = mypy_path elif not original.startswith(mypy_path): new_mypy_path = mypy_path + os.pathsep + original else: new_mypy_path = None if new_mypy_path is not None: logger.log(mypy_path_en...
def set_mypy_path(mypy_path)
Prepend to MYPYPATH.
1.998035
1.921117
1.040038
if not WINDOWS: try: return bool(select([sys.stdin], [], [], 0)[0]) except Exception: logger.log_exc() try: return not sys.stdin.isatty() except Exception: logger.log_exc() return False
def stdin_readable()
Determine whether stdin has any data to read.
3.315469
3.144743
1.054289
if limit < minimum_recursion_limit: raise CoconutException("--recursion-limit must be at least " + str(minimum_recursion_limit)) sys.setrecursionlimit(limit)
def set_recursion_limit(limit)
Set the Python recursion limit.
4.78482
4.590969
1.042224
old_error_method = argparser.error argparser.error = _raise_ValueError try: argparser.parse_args(args) except ValueError: return False else: return True finally: argparser.error = old_error_method
def canparse(argparser, args)
Determines if argparser can parse args.
2.93909
2.779966
1.05724
if style == "none": self.style = None elif prompt_toolkit is None: raise CoconutException("syntax highlighting is not supported on this Python version") elif style == "list": print("Coconut Styles: none, " + ", ".join(pygments.styles.get_all_styles())...
def set_style(self, style)
Set pygments syntax highlighting style.
4.765684
4.107213
1.160321
if path: self.history = prompt_toolkit.history.FileHistory(fixpath(path)) else: self.history = prompt_toolkit.history.InMemoryHistory()
def set_history_file(self, path)
Set path to history file. "" produces no file.
4.028476
3.606074
1.117136
sys.stdout.flush() if more: msg = more_prompt else: msg = main_prompt if self.style is not None: internal_assert(prompt_toolkit is not None, "without prompt_toolkit cannot highlight style", self.style) try: return s...
def input(self, more=False)
Prompt for code input.
10.125768
9.745038
1.039069
try: # prompt_toolkit v2 prompt = prompt_toolkit.PromptSession(history=self.history).prompt except AttributeError: # prompt_toolkit v1 prompt = partial(prompt_toolkit.prompt, history=self.history) return prompt( msg, ...
def prompt(self, msg)
Get input using prompt_toolkit.
2.724978
2.671419
1.020049
init_vars = { "__name__": "__main__", "__package__": None, "reload": reload, } if path is not None: init_vars["__file__"] = fixpath(path) # put reserved_vars in for auto-completion purposes for var in reserved_vars: ...
def build_vars(path=None)
Build initial vars.
4.768582
4.574793
1.04236
from coconut import __coconut__ # this is expensive, so only do it here for var in self.vars: if not var.startswith("__") and var in dir(__coconut__): self.vars[var] = getattr(__coconut__, var)
def fix_pickle(self)
Fix pickling of Coconut header objects.
5.288288
4.153641
1.273169
try: yield except SystemExit as err: self.exit(err.code) except BaseException: etype, value, tb = sys.exc_info() for _ in range(num_added_tb_layers): if tb is None: break tb = tb.tb_next ...
def handling_errors(self, all_errors_exit=False)
Handle execution errors.
2.890123
2.814338
1.026928
if use_eval is None: run_func = interpret elif use_eval is True: run_func = eval else: run_func = exec_func with self.handling_errors(all_errors_exit): if path is None: result = run_func(code, self.vars) ...
def run(self, code, use_eval=None, path=None, all_errors_exit=False, store=True)
Execute Python code.
2.858218
2.8013
1.020318
path = fixpath(path) with self.handling_errors(all_errors_exit): module_vars = run_file(path) self.vars.update(module_vars) self.store("from " + splitname(path)[1] + " import *")
def run_file(self, path, all_errors_exit=True)
Execute a Python file.
6.926007
6.155337
1.125203
if self.stored is None: return "" else: if get_all: self.stored = ["\n".join(self.stored)] return self.stored[-1]
def was_run_code(self, get_all=True)
Get all the code that was run.
4.706557
3.866259
1.217341
reqs = [] for req in all_reqs[which]: req_str = req + ">=" + ver_tuple_to_str(min_versions[req]) if req in version_strictly: req_str += ",<" + ver_tuple_to_str(min_versions[req][:-1]) + "." + str(min_versions[req][-1] + 1) reqs.append(req_str) return reqs
def get_reqs(which="main")
Gets requirements from all_reqs with versions.
3.404963
3.22397
1.05614
union = set(init_reqs) for reqs in other_reqs: union.update(reqs) return list(union)
def uniqueify_all(init_reqs, *other_reqs)
Find the union of all the given requirements.
2.925059
2.507409
1.166566
import requests url = "https://pypi.python.org/pypi/" + req + "/json" return tuple(requests.get(url).json()["releases"].keys())
def all_versions(req)
Get all versions of req from PyPI.
3.720831
3.036169
1.225502
if old_ver == new_ver or old_ver + (0,) == new_ver: return False for n, o in zip(new_ver, old_ver): if not isinstance(n, int): o = str(o) if o < n: return True elif o > n: return False return not strict
def newer(new_ver, old_ver, strict=False)
Determines if the first version tuple is newer than the second. True if newer, False if older, None if difference is after specified version parts.
2.891224
2.583633
1.119054
new_updates = [] same_updates = [] for req in everything_in(all_reqs): new_versions = [] same_versions = [] for ver_str in all_versions(req): if newer(ver_str_to_tuple(ver_str), min_versions[req], strict=True): new_versions.append(ver_str) ...
def print_new_versions(strict=False)
Prints new requirement versions.
2.686235
2.600416
1.033002
if err_trace is None: err_parts = "".join(traceback.format_exception_only(err_type, err_value)).strip().split(": ", 1) if len(err_parts) == 1: err_name, err_msg = err_parts[0], "" else: err_name, err_msg = err_parts err_name = err_name.split(".")[-1] ...
def format_error(err_type, err_value, err_trace=None)
Properly formats the specified error.
1.997766
1.981595
1.008161
if callable(error): if DEVELOP: raise error() elif DEVELOP: raise error else: logger.warn_err(error)
def complain(error)
Raises in develop; warns in release.
6.95113
5.611359
1.238761
self.verbose, self.quiet, self.path, self.name, self.tracing = other.verbose, other.quiet, other.path, other.name, other.tracing
def copy_from(self, other)
Copy other onto self.
4.770288
4.597212
1.037648
full_message = "".join( sig + line for line in " ".join( str(msg) for msg in messages ).splitlines(True) ) if not full_message: full_message = sig.rstrip() if debug: printerr(full_message) else: ...
def display(self, messages, sig="", debug=False)
Prints an iterator of messages.
3.983343
3.915399
1.017353
if not self.quiet: self.display(messages, main_sig, debug=True)
def show_error(self, *messages)
Prints error messages with main signature if not --quiet.
19.779165
8.390904
2.357215
if self.verbose: self.display(messages, prefix, debug=True)
def log_prefix(self, prefix, *messages)
Logs debug messages with the given signature if --verbose.
10.690601
7.710649
1.386472
if self.verbose: new_vars = dict(variables) for v in rem_vars: del new_vars[v] printerr(message, new_vars)
def log_vars(self, message, variables, rem_vars=("self",))
Logs variables with given message if --verbose.
3.818571
3.142371
1.215188
exc_info = sys.exc_info() if exc_info[0] is None: return None else: err_type, err_value, err_trace = exc_info[0], exc_info[1], None if self.verbose and len(exc_info) > 2: err_trace = exc_info[2] return format_error(err_type...
def get_error(self)
Properly formats the current error.
2.291239
2.1491
1.066139
self.path = new_path try: yield finally: self.path = old_path
def in_path(self, new_path, old_path=None)
Temporarily enters a path.
4.191994
3.511104
1.193925
errmsg = self.get_error() if errmsg is not None: if self.path is not None: errmsg_lines = ["in " + self.path + ":"] for line in errmsg.splitlines(): if line: line = " " * taberrfmt + line ...
def display_exc(self)
Properly prints an exception in the exception context.
3.699913
3.516494
1.052159
internal_assert(len(begin) < info_tabulation, "info message too long", begin) self.show(begin + " " * (info_tabulation - len(begin)) + middle + " " + end)
def show_tabulated(self, begin, middle, end)
Shows a tabulated message.
9.158987
7.180221
1.275586
if self.tracing: if callable(code): code = code() tagstr = "[" + str(tag) + "]" if multiline: printerr(tagstr + "\n" + displayable(code)) else: printerr(tagstr, ascii(code))
def log_tag(self, tag, code, multiline=False)
Logs a tagged message if tracing.
5.494926
4.595071
1.195831
if self.tracing: tag, original, loc = displayable(tag), displayable(original), int(loc) if "{" not in tag: out = ["[" + tag + "]"] add_line_col = True if tokens is not None: if isinstance(tokens, Exception): ...
def log_trace(self, tag, original, loc, tokens=None, extra=None)
Formats and displays a trace if tracing.
3.098585
2.992967
1.035289
if DEVELOP: item.debugActions = ( None, # no start action self._trace_success_action, self._trace_exc_action, ) item.debug = True return item
def trace(self, item)
Traces a parse element (only enabled in develop).
10.992188
9.244715
1.189024
if self.verbose: start_time = time.clock() try: yield finally: elapsed_time = time.clock() - start_time printerr("Time while parsing:", elapsed_time, "seconds") if packrat_cache: hits...
def gather_parsing_stats(self)
Times parsing if --verbose.
5.828049
4.970805
1.172456
if not hasattr(logging, "getLogger"): def getLogger(name=None): other = Logger(self) if name is not None: other.name = name return other logging.getLogger = getLogger
def patch_logging(self)
Patches built-in Python logging if necessary.
3.863239
3.210187
1.203431
printerr(self.name, args, kwargs, traceback.format_exc())
def pylog(self, *args, **kwargs)
Display all available logging information.
14.394556
13.921774
1.03396
if args and args[0] != "raiseonerror": self.original_add_filter(*args, **kwargs)
def lenient_add_filter(self, *args, **kwargs)
Disables the raiseonerror filter.
10.410138
4.874478
2.135641
path = event.src_path if path not in self.saw: self.saw.add(path) self.recompile(path)
def on_modified(self, event)
Handle a file modified event.
4.729693
4.47633
1.056601
pos_args = [] star_args = [] kwd_args = [] dubstar_args = [] for arg in tokens: argstr = "".join(arg) if len(arg) == 1: if star_args or kwd_args or dubstar_args: raise CoconutDeferredSyntaxError("positional arguments must come first", loc) ...
def split_function_call(tokens, loc)
Split into positional arguments and keyword arguments.
2.311936
2.183344
1.058897
if len(tokens) == 1: # .attr return tokens[0], None elif len(tokens) >= 2 and tokens[1] == "(": # .method(... if len(tokens) == 2: # .method() return tokens[0], "" elif len(tokens) == 3: # .method(args) return tokens[0], tokens[2] else: ...
def attrgetter_atom_split(tokens)
Split attrgetter_atom_tokens into (attr_or_method_name, method_args_or_none_if_attr).
2.940211
2.631003
1.117525
# list implies artificial tokens, which must be expr if isinstance(tokens, list) or "expr" in tokens: internal_assert(len(tokens) == 1, "invalid expr pipe item tokens", tokens) return "expr", (tokens[0],) elif "partial" in tokens: func, args = tokens pos_args, star_args,...
def pipe_item_split(tokens, loc)
Process a pipe item, which could be a partial, an attribute access, a method call, or an expression. Return (type, split) where split is - (expr,) for expression, - (func, pos_args, kwd_args) for partial, - (name, args) for attr/method, and - (op, args) for itemgetter.
4.656704
3.769391
1.2354
internal_assert(len(tokens) >= 3, "invalid infix tokens", tokens) (arg1, func, arg2), tokens = tokens[:3], tokens[3:] args = list(arg1) + list(arg2) while tokens: args = [callback([args, func, []])] (func, newarg), tokens = tokens[:2], tokens[2:] args += list(newarg) ret...
def get_infix_items(tokens, callback=infix_error)
Perform infix token processing. Takes a callback that (takes infix tokens and returns a string) to handle inner infix calls.
5.013297
4.934631
1.015941
if op == "..>": return "forwards", False elif op == "<..": return "backwards", False elif op == "..*>": return "forwards", True elif op == "<*..": return "backwards", True else: raise CoconutInternalException("invalid function composition pipe operator", ...
def comp_pipe_info(op)
Returns (direction, star) where direction is 'forwards' or 'backwards'.
4.396416
3.402045
1.292286
out = tokens.pop(0) for i, trailer in enumerate(tokens): if isinstance(trailer, str): out += trailer elif len(trailer) == 1: if trailer[0] == "$[]": out = "_coconut.functools.partial(_coconut_igetitem, " + out + ")" elif trailer[0] == "$":...
def item_handle(loc, tokens)
Process trailers.
2.307292
2.288876
1.008046
internal_assert(set(kwargs) <= set(("top",)), "unknown pipe_handle keyword arguments", kwargs) top = kwargs.get("top", True) if len(tokens) == 1: item = tokens.pop() if not top: # defer to other pipe_handle call return item # we've only been given one operand, so w...
def pipe_handle(loc, tokens, **kwargs)
Process pipe calls.
3.189774
3.204809
0.995309
internal_assert(len(tokens) >= 3 and len(tokens) % 2 == 1, "invalid composition pipe tokens", tokens) funcs = [tokens[0]] stars = [] direction = None for i in range(1, len(tokens), 2): op, fn = tokens[i], tokens[i + 1] new_direction, star = comp_pipe_info(op) if directio...
def comp_pipe_handle(loc, tokens)
Process pipe function composition.
3.515158
3.501405
1.003928
if len(tokens) == 1: return tokens[0] elif tokens[0].isalnum(): return "({b} if {a} is None else {a})".format( a=tokens[0], b=none_coalesce_handle(tokens[1:]), ) else: return "(lambda {x}: {b} if {x} is None else {x})({a})".format( x=n...
def none_coalesce_handle(tokens)
Process the None-coalescing operator.
2.332265
2.260886
1.031571
name, args = attrgetter_atom_split(tokens) if args is None: return '_coconut.operator.attrgetter("' + name + '")' elif "." in name: raise CoconutDeferredSyntaxError("cannot have attribute access in implicit methodcaller partial", loc) elif args == "": return '_coconut.operat...
def attrgetter_atom_handle(loc, tokens)
Process attrgetter literals.
4.622362
4.651503
0.993735
if len(tokens) == 0: return "_coconut.iter(())" else: return ( "(%s() for %s in (" % (func_var, func_var) + "lambda: " + ", lambda: ".join(tokens) + ("," if len(tokens) == 1 else "") + "))" )
def lazy_list_handle(tokens)
Process lazy lists.
6.179121
6.3178
0.97805
func, args = get_infix_items(tokens, callback=infix_handle) return "(" + func + ")(" + ", ".join(args) + ")"
def infix_handle(tokens)
Process infix calls.
6.098206
6.316127
0.965498
func, base_args = get_infix_items(tokens) args = [] for arg in base_args[:-1]: rstrip_arg = arg.rstrip() if not rstrip_arg.endswith(unwrapper): if not rstrip_arg.endswith(","): arg += ", " elif arg.endswith(","): arg += " " ...
def op_funcdef_handle(tokens)
Process infix defs.
3.224681
3.139517
1.027126
if len(tokens) == 1: return '_coconut.typing.Callable[..., ' + tokens[0] + ']' elif len(tokens) == 2: return '_coconut.typing.Callable[[' + tokens[0] + '], ' + tokens[1] + ']' else: raise CoconutInternalException("invalid Callable typedef tokens", tokens)
def typedef_callable_handle(tokens)
Process -> to Callable inside type annotations.
2.748438
2.624499
1.047224
internal_assert(len(tokens) == 2, "invalid assignment function definition tokens", tokens) return tokens[0] + ("" if tokens[1].startswith("\n") else " ") + tokens[1]
def math_funcdef_handle(tokens)
Process assignment function definition.
5.946635
4.839447
1.228784
defs = [] decorates = [] for i, tok in enumerate(tokens): if "simple" in tok and len(tok) == 1: decorates.append("@" + tok[0]) elif "test" in tok and len(tok) == 1: varname = decorator_var + "_" + str(i) defs.append(varname + " = " + tok[0]) ...
def decorator_handle(tokens)
Process decorators.
3.492228
3.530102
0.989271
if len(tokens) == 4: matches, match_type, item, stmts = tokens cond = None elif len(tokens) == 5: matches, match_type, item, cond, stmts = tokens else: raise CoconutInternalException("invalid match statement tokens", tokens) if match_type == "in": invert = F...
def match_handle(loc, tokens)
Process match blocks.
3.664276
3.606668
1.015972
if len(tokens) == 1: errs, asname = tokens[0], None elif len(tokens) == 2: errs, asname = tokens else: raise CoconutInternalException("invalid except tokens", tokens) out = "except " if "list" in tokens: out += "(" + errs + ")" else: out += errs i...
def except_handle(tokens)
Process except statements.
3.616086
3.458158
1.045668