nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
split_template_path
(template: str)
return pieces
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error.
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error.
24
38
def split_template_path(template: str) -> t.List[str]: """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in template.split("/"): if ( os.sep in piece or (os.path.altsep and os.path.altsep in piece) or piece == os.path.pardir ): raise TemplateNotFound(template) elif piece and piece != ".": pieces.append(piece) return pieces
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L24-L38
42
[ 1, 5, 6, 12, 13, 14 ]
40
[ 0, 4, 11 ]
20
false
66.478873
15
8
80
2
def split_template_path(template: str) -> t.List[str]: pieces = [] for piece in template.split("/"): if ( os.sep in piece or (os.path.altsep and os.path.altsep in piece) or piece == os.path.pardir ): raise TemplateNotFound(template) elif piece and piece != ".": pieces.append(piece) return pieces
27,861
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
BaseLoader.get_source
( self, environment: "Environment", template: str )
Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as a string. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise ``None``. The filename is used by Python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded.
Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template.
74
98
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: """Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as a string. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise ``None``. The filename is used by Python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded. """ if not self.has_source_access: raise RuntimeError( f"{type(self).__name__} cannot provide access to the source" ) raise TemplateNotFound(template)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L74-L98
42
[ 0, 3 ]
8
[ 20, 21, 24 ]
12
false
66.478873
25
2
88
16
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: if not self.has_source_access: raise RuntimeError( f"{type(self).__name__} cannot provide access to the source" ) raise TemplateNotFound(template)
27,862
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
BaseLoader.list_templates
(self)
Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.
Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.
100
104
def list_templates(self) -> t.List[str]: """Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior. """ raise TypeError("this loader cannot iterate over all templates")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L100-L104
42
[ 1 ]
20
[ 0, 4 ]
40
false
66.478873
5
1
60
2
def list_templates(self) -> t.List[str]: raise TypeError("this loader cannot iterate over all templates")
27,863
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
BaseLoader.load
( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
return environment.template_class.from_code( environment, code, globals, uptodate )
Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly.
Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly.
107
148
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": """Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly. """ code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) return environment.template_class.from_code( environment, code, globals, uptodate )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L107-L148
42
[ 0, 6, 13, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 36, 37, 38, 39 ]
59.52381
[ 12, 18, 22, 29, 35 ]
11.904762
false
66.478873
42
6
88.095238
5
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) return environment.template_class.from_code( environment, code, globals, uptodate )
27,864
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
FileSystemLoader.__init__
( self, searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]], encoding: str = "utf-8", followlinks: bool = False, )
178
189
def __init__( self, searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]], encoding: str = "utf-8", followlinks: bool = False, ) -> None: if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str): searchpath = [searchpath] self.searchpath = [os.fspath(p) for p in searchpath] self.encoding = encoding self.followlinks = followlinks
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L178-L189
42
[ 0, 6, 7, 8, 10, 11 ]
50
[ 9 ]
8.333333
false
66.478873
12
4
91.666667
0
def __init__( self, searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]], encoding: str = "utf-8", followlinks: bool = False, ) -> None: if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str): searchpath = [searchpath] self.searchpath = [os.fspath(p) for p in searchpath] self.encoding = encoding self.followlinks = followlinks
27,865
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
FileSystemLoader.get_source
( self, environment: "Environment", template: str )
return contents, os.path.normpath(filename), uptodate
191
218
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, str, t.Callable[[], bool]]: pieces = split_template_path(template) for searchpath in self.searchpath: # Use posixpath even on Windows to avoid "drive:" or UNC # segments breaking out of the search directory. filename = posixpath.join(searchpath, *pieces) if os.path.isfile(filename): break else: raise TemplateNotFound(template) with open(filename, encoding=self.encoding) as f: contents = f.read() mtime = os.path.getmtime(filename) def uptodate() -> bool: try: return os.path.getmtime(filename) == mtime except OSError: return False # Use normpath to convert Windows altsep to sep. return contents, os.path.normpath(filename), uptodate
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L191-L218
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 19, 20, 21, 25, 26, 27 ]
75
[ 16, 18, 22, 23, 24 ]
17.857143
false
66.478873
28
6
82.142857
0
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, str, t.Callable[[], bool]]: pieces = split_template_path(template) for searchpath in self.searchpath: # Use posixpath even on Windows to avoid "drive:" or UNC # segments breaking out of the search directory. filename = posixpath.join(searchpath, *pieces) if os.path.isfile(filename): break else: raise TemplateNotFound(template) with open(filename, encoding=self.encoding) as f: contents = f.read() mtime = os.path.getmtime(filename) def uptodate() -> bool: try: return os.path.getmtime(filename) == mtime except OSError: return False # Use normpath to convert Windows altsep to sep. return contents, os.path.normpath(filename), uptodate
27,866
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
FileSystemLoader.list_templates
(self)
return sorted(found)
220
235
def list_templates(self) -> t.List[str]: found = set() for searchpath in self.searchpath: walk_dir = os.walk(searchpath, followlinks=self.followlinks) for dirpath, _, filenames in walk_dir: for filename in filenames: template = ( os.path.join(dirpath, filename)[len(searchpath) :] .strip(os.sep) .replace(os.sep, "/") ) if template[:2] == "./": template = template[2:] if template not in found: found.add(template) return sorted(found)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L220-L235
42
[ 0, 1, 2, 3, 4, 5, 6, 11, 13, 14, 15 ]
68.75
[ 12 ]
6.25
false
66.478873
16
6
93.75
0
def list_templates(self) -> t.List[str]: found = set() for searchpath in self.searchpath: walk_dir = os.walk(searchpath, followlinks=self.followlinks) for dirpath, _, filenames in walk_dir: for filename in filenames: template = ( os.path.join(dirpath, filename)[len(searchpath) :] .strip(os.sep) .replace(os.sep, "/") ) if template[:2] == "./": template = template[2:] if template not in found: found.add(template) return sorted(found)
27,867
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PackageLoader.__init__
( self, package_name: str, package_path: "str" = "templates", encoding: str = "utf-8", )
271
328
def __init__( self, package_name: str, package_path: "str" = "templates", encoding: str = "utf-8", ) -> None: package_path = os.path.normpath(package_path).rstrip(os.sep) # normpath preserves ".", which isn't valid in zip paths. if package_path == os.path.curdir: package_path = "" elif package_path[:2] == os.path.curdir + os.sep: package_path = package_path[2:] self.package_path = package_path self.package_name = package_name self.encoding = encoding # Make sure the package exists. This also makes namespace # packages work, otherwise get_loader returns None. import_module(package_name) spec = importlib.util.find_spec(package_name) assert spec is not None, "An import spec was not found for the package." loader = spec.loader assert loader is not None, "A loader was not found for the package." self._loader = loader self._archive = None template_root = None if isinstance(loader, zipimport.zipimporter): self._archive = loader.archive pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore template_root = os.path.join(pkgdir, package_path).rstrip(os.sep) else: roots: t.List[str] = [] # One element for regular packages, multiple for namespace # packages, or None for single module file. if spec.submodule_search_locations: roots.extend(spec.submodule_search_locations) # A single module file, use the parent directory instead. elif spec.origin is not None: roots.append(os.path.dirname(spec.origin)) for root in roots: root = os.path.join(root, package_path) if os.path.isdir(root): template_root = root break if template_root is None: raise ValueError( f"The {package_name!r} package was not installed in a" " way that PackageLoader understands." ) self._template_root = template_root
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L271-L328
42
[ 0, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 56, 57 ]
81.034483
[ 12, 52 ]
3.448276
false
66.478873
58
11
96.551724
0
def __init__( self, package_name: str, package_path: "str" = "templates", encoding: str = "utf-8", ) -> None: package_path = os.path.normpath(package_path).rstrip(os.sep) # normpath preserves ".", which isn't valid in zip paths. if package_path == os.path.curdir: package_path = "" elif package_path[:2] == os.path.curdir + os.sep: package_path = package_path[2:] self.package_path = package_path self.package_name = package_name self.encoding = encoding # Make sure the package exists. This also makes namespace # packages work, otherwise get_loader returns None. import_module(package_name) spec = importlib.util.find_spec(package_name) assert spec is not None, "An import spec was not found for the package." loader = spec.loader assert loader is not None, "A loader was not found for the package." self._loader = loader self._archive = None template_root = None if isinstance(loader, zipimport.zipimporter): self._archive = loader.archive pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore template_root = os.path.join(pkgdir, package_path).rstrip(os.sep) else: roots: t.List[str] = [] # One element for regular packages, multiple for namespace # packages, or None for single module file. if spec.submodule_search_locations: roots.extend(spec.submodule_search_locations) # A single module file, use the parent directory instead. elif spec.origin is not None: roots.append(os.path.dirname(spec.origin)) for root in roots: root = os.path.join(root, package_path) if os.path.isdir(root): template_root = root break if template_root is None: raise ValueError( f"The {package_name!r} package was not installed in a" " way that PackageLoader understands." ) self._template_root = template_root
27,868
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PackageLoader.get_source
( self, environment: "Environment", template: str )
return source.decode(self.encoding), p, up_to_date
330
366
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]: # Use posixpath even on Windows to avoid "drive:" or UNC # segments breaking out of the search directory. Use normpath to # convert Windows altsep to sep. p = os.path.normpath( posixpath.join(self._template_root, *split_template_path(template)) ) up_to_date: t.Optional[t.Callable[[], bool]] if self._archive is None: # Package is a directory. if not os.path.isfile(p): raise TemplateNotFound(template) with open(p, "rb") as f: source = f.read() mtime = os.path.getmtime(p) def up_to_date() -> bool: return os.path.isfile(p) and os.path.getmtime(p) == mtime else: # Package is a zip file. try: source = self._loader.get_data(p) # type: ignore except OSError as e: raise TemplateNotFound(template) from e # Could use the zip's mtime for all template mtimes, but # would need to safely reload the module if it's out of # date, so just report it as always current. up_to_date = None return source.decode(self.encoding), p, up_to_date
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L330-L366
42
[ 0, 5, 6, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 33, 34, 35, 36 ]
64.864865
[ 28, 29 ]
5.405405
false
66.478873
37
7
94.594595
0
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]: # Use posixpath even on Windows to avoid "drive:" or UNC # segments breaking out of the search directory. Use normpath to # convert Windows altsep to sep. p = os.path.normpath( posixpath.join(self._template_root, *split_template_path(template)) ) up_to_date: t.Optional[t.Callable[[], bool]] if self._archive is None: # Package is a directory. if not os.path.isfile(p): raise TemplateNotFound(template) with open(p, "rb") as f: source = f.read() mtime = os.path.getmtime(p) def up_to_date() -> bool: return os.path.isfile(p) and os.path.getmtime(p) == mtime else: # Package is a zip file. try: source = self._loader.get_data(p) # type: ignore except OSError as e: raise TemplateNotFound(template) from e # Could use the zip's mtime for all template mtimes, but # would need to safely reload the module if it's out of # date, so just report it as always current. up_to_date = None return source.decode(self.encoding), p, up_to_date
27,869
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PackageLoader.list_templates
(self)
return results
368
398
def list_templates(self) -> t.List[str]: results: t.List[str] = [] if self._archive is None: # Package is a directory. offset = len(self._template_root) for dirpath, _, filenames in os.walk(self._template_root): dirpath = dirpath[offset:].lstrip(os.sep) results.extend( os.path.join(dirpath, name).replace(os.sep, "/") for name in filenames ) else: if not hasattr(self._loader, "_files"): raise TypeError( "This zip import does not have the required" " metadata to list templates." ) # Package is a zip file. prefix = self._template_root[len(self._archive) :].lstrip(os.sep) + os.sep offset = len(prefix) for name in self._loader._files.keys(): # Find names under the templates directory that aren't directories. if name.startswith(prefix) and name[-1] != os.sep: results.append(name[offset:].replace(os.sep, "/")) results.sort() return results
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L368-L398
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 20, 21, 22, 23, 25, 27, 28, 29, 30 ]
64.516129
[ 15, 24, 26 ]
9.677419
false
66.478873
31
7
90.322581
0
def list_templates(self) -> t.List[str]: results: t.List[str] = [] if self._archive is None: # Package is a directory. offset = len(self._template_root) for dirpath, _, filenames in os.walk(self._template_root): dirpath = dirpath[offset:].lstrip(os.sep) results.extend( os.path.join(dirpath, name).replace(os.sep, "/") for name in filenames ) else: if not hasattr(self._loader, "_files"): raise TypeError( "This zip import does not have the required" " metadata to list templates." ) # Package is a zip file. prefix = self._template_root[len(self._archive) :].lstrip(os.sep) + os.sep offset = len(prefix) for name in self._loader._files.keys(): # Find names under the templates directory that aren't directories. if name.startswith(prefix) and name[-1] != os.sep: results.append(name[offset:].replace(os.sep, "/")) results.sort() return results
27,870
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
DictLoader.__init__
(self, mapping: t.Mapping[str, str])
410
411
def __init__(self, mapping: t.Mapping[str, str]) -> None: self.mapping = mapping
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L410-L411
42
[]
0
[ 0, 1 ]
100
false
66.478873
2
1
0
0
def __init__(self, mapping: t.Mapping[str, str]) -> None: self.mapping = mapping
27,871
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
DictLoader.get_source
( self, environment: "Environment", template: str )
413
419
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, None, t.Callable[[], bool]]: if template in self.mapping: source = self.mapping[template] return source, None, lambda: source == self.mapping.get(template) raise TemplateNotFound(template)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L413-L419
42
[ 0, 3, 4, 5, 6 ]
71.428571
[]
0
false
66.478873
7
2
100
0
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, None, t.Callable[[], bool]]: if template in self.mapping: source = self.mapping[template] return source, None, lambda: source == self.mapping.get(template) raise TemplateNotFound(template)
27,872
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
DictLoader.list_templates
(self)
return sorted(self.mapping)
421
422
def list_templates(self) -> t.List[str]: return sorted(self.mapping)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L421-L422
42
[ 0, 1 ]
100
[]
0
true
66.478873
2
1
100
0
def list_templates(self) -> t.List[str]: return sorted(self.mapping)
27,873
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
FunctionLoader.__init__
( self, load_func: t.Callable[ [str], t.Optional[ t.Union[ str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]] ] ], ], )
443
454
def __init__( self, load_func: t.Callable[ [str], t.Optional[ t.Union[ str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]] ] ], ], ) -> None: self.load_func = load_func
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L443-L454
42
[ 0 ]
8.333333
[ 11 ]
8.333333
false
66.478873
12
1
91.666667
0
def __init__( self, load_func: t.Callable[ [str], t.Optional[ t.Union[ str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]] ] ], ], ) -> None: self.load_func = load_func
27,874
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
FunctionLoader.get_source
( self, environment: "Environment", template: str )
return rv
456
467
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: rv = self.load_func(template) if rv is None: raise TemplateNotFound(template) if isinstance(rv, str): return rv, None, None return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L456-L467
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
83.333333
[]
0
false
66.478873
12
3
100
0
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: rv = self.load_func(template) if rv is None: raise TemplateNotFound(template) if isinstance(rv, str): return rv, None, None return rv
27,875
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PrefixLoader.__init__
( self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/" )
485
489
def __init__( self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/" ) -> None: self.mapping = mapping self.delimiter = delimiter
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L485-L489
42
[ 3, 4 ]
40
[ 0 ]
20
false
66.478873
5
1
80
0
def __init__( self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/" ) -> None: self.mapping = mapping self.delimiter = delimiter
27,876
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PrefixLoader.get_loader
(self, template: str)
return loader, name
491
497
def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]: try: prefix, name = template.split(self.delimiter, 1) loader = self.mapping[prefix] except (ValueError, KeyError) as e: raise TemplateNotFound(template) from e return loader, name
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L491-L497
42
[ 0, 1, 3, 4, 5, 6 ]
85.714286
[ 2 ]
14.285714
false
66.478873
7
2
85.714286
0
def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]: try: prefix, name = template.split(self.delimiter, 1) loader = self.mapping[prefix] except (ValueError, KeyError) as e: raise TemplateNotFound(template) from e return loader, name
27,877
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PrefixLoader.get_source
( self, environment: "Environment", template: str )
499
508
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: loader, name = self.get_loader(template) try: return loader.get_source(environment, name) except TemplateNotFound as e: # re-raise the exception with the correct filename here. # (the one that includes the prefix) raise TemplateNotFound(template) from e
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L499-L508
42
[ 0, 3, 4, 5, 6, 7, 8 ]
70
[ 9 ]
10
false
66.478873
10
2
90
0
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: loader, name = self.get_loader(template) try: return loader.get_source(environment, name) except TemplateNotFound as e: # re-raise the exception with the correct filename here. # (the one that includes the prefix) raise TemplateNotFound(template) from e
27,878
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PrefixLoader.load
( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
511
523
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": loader, local_name = self.get_loader(name) try: return loader.load(environment, local_name, globals) except TemplateNotFound as e: # re-raise the exception with the correct filename here. # (the one that includes the prefix) raise TemplateNotFound(name) from e
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L511-L523
42
[ 0, 6, 7, 8, 9, 10, 11, 12 ]
61.538462
[]
0
false
66.478873
13
2
100
0
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": loader, local_name = self.get_loader(name) try: return loader.load(environment, local_name, globals) except TemplateNotFound as e: # re-raise the exception with the correct filename here. # (the one that includes the prefix) raise TemplateNotFound(name) from e
27,879
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
PrefixLoader.list_templates
(self)
return result
525
530
def list_templates(self) -> t.List[str]: result = [] for prefix, loader in self.mapping.items(): for template in loader.list_templates(): result.append(prefix + self.delimiter + template) return result
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L525-L530
42
[ 1, 3, 4, 5 ]
66.666667
[ 0, 2 ]
33.333333
false
66.478873
6
3
66.666667
0
def list_templates(self) -> t.List[str]: result = [] for prefix, loader in self.mapping.items(): for template in loader.list_templates(): result.append(prefix + self.delimiter + template) return result
27,880
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ChoiceLoader.__init__
(self, loaders: t.Sequence[BaseLoader])
547
548
def __init__(self, loaders: t.Sequence[BaseLoader]) -> None: self.loaders = loaders
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L547-L548
42
[]
0
[ 0, 1 ]
100
false
66.478873
2
1
0
0
def __init__(self, loaders: t.Sequence[BaseLoader]) -> None: self.loaders = loaders
27,881
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ChoiceLoader.get_source
( self, environment: "Environment", template: str )
550
558
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: for loader in self.loaders: try: return loader.get_source(environment, template) except TemplateNotFound: pass raise TemplateNotFound(template)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L550-L558
42
[ 0, 3, 4, 5 ]
44.444444
[ 6, 7, 8 ]
33.333333
false
66.478873
9
3
66.666667
0
def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: for loader in self.loaders: try: return loader.get_source(environment, template) except TemplateNotFound: pass raise TemplateNotFound(template)
27,882
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ChoiceLoader.load
( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
561
572
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": for loader in self.loaders: try: return loader.load(environment, name, globals) except TemplateNotFound: pass raise TemplateNotFound(name)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L561-L572
42
[ 0, 6, 7, 8, 9, 10, 11 ]
58.333333
[]
0
false
66.478873
12
3
100
0
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": for loader in self.loaders: try: return loader.load(environment, name, globals) except TemplateNotFound: pass raise TemplateNotFound(name)
27,883
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ChoiceLoader.list_templates
(self)
return sorted(found)
574
578
def list_templates(self) -> t.List[str]: found = set() for loader in self.loaders: found.update(loader.list_templates()) return sorted(found)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L574-L578
42
[ 0, 1, 3 ]
60
[ 2, 4 ]
40
false
66.478873
5
2
60
0
def list_templates(self) -> t.List[str]: found = set() for loader in self.loaders: found.update(loader.list_templates()) return sorted(found)
27,884
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ModuleLoader.__init__
( self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]] )
600
622
def __init__( self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]] ) -> None: package_name = f"_jinja2_module_templates_{id(self):x}" # create a fake module that looks for the templates in the # path given. mod = _TemplateModule(package_name) if not isinstance(path, abc.Iterable) or isinstance(path, str): path = [path] mod.__path__ = [os.fspath(p) for p in path] sys.modules[package_name] = weakref.proxy( mod, lambda x: sys.modules.pop(package_name, None) ) # the only strong reference, the sys.modules entry is weak # so that the garbage collector can remove it once the # loader that created it goes out of business. self.module = mod self.package_name = package_name
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L600-L622
42
[ 0, 3, 4, 5, 6, 10, 11, 12, 13, 14, 17, 18, 19, 20 ]
60.869565
[ 7, 9, 21, 22 ]
17.391304
false
66.478873
23
4
82.608696
0
def __init__( self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]] ) -> None: package_name = f"_jinja2_module_templates_{id(self):x}" # create a fake module that looks for the templates in the # path given. mod = _TemplateModule(package_name) if not isinstance(path, abc.Iterable) or isinstance(path, str): path = [path] mod.__path__ = [os.fspath(p) for p in path] sys.modules[package_name] = weakref.proxy( mod, lambda x: sys.modules.pop(package_name, None) ) # the only strong reference, the sys.modules entry is weak # so that the garbage collector can remove it once the # loader that created it goes out of business. self.module = mod self.package_name = package_name
27,885
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ModuleLoader.get_template_key
(name: str)
return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
625
626
def get_template_key(name: str) -> str: return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L625-L626
42
[ 0 ]
50
[ 1 ]
50
false
66.478873
2
1
50
0
def get_template_key(name: str) -> str: return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
27,886
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ModuleLoader.get_module_filename
(name: str)
return ModuleLoader.get_template_key(name) + ".py"
629
630
def get_module_filename(name: str) -> str: return ModuleLoader.get_template_key(name) + ".py"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L629-L630
42
[ 0 ]
50
[ 1 ]
50
false
66.478873
2
1
50
0
def get_module_filename(name: str) -> str: return ModuleLoader.get_template_key(name) + ".py"
27,887
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/loaders.py
ModuleLoader.load
( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
return environment.template_class.from_module_dict( environment, mod.__dict__, globals )
633
658
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": key = self.get_template_key(name) module = f"{self.package_name}.{key}" mod = getattr(self.module, module, None) if mod is None: try: mod = __import__(module, None, None, ["root"]) except ImportError as e: raise TemplateNotFound(name) from e # remove the entry from sys.modules, we only want the attribute # on the module object we have stored on the loader. sys.modules.pop(module, None) if globals is None: globals = {} return environment.template_class.from_module_dict( environment, mod.__dict__, globals )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/loaders.py#L633-L658
42
[ 0, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 21, 22, 23 ]
57.692308
[ 12, 18, 20 ]
11.538462
false
66.478873
26
4
88.461538
0
def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": key = self.get_template_key(name) module = f"{self.package_name}.{key}" mod = getattr(self.module, module, None) if mod is None: try: mod = __import__(module, None, None, ["root"]) except ImportError as e: raise TemplateNotFound(name) from e # remove the entry from sys.modules, we only want the attribute # on the module object we have stored on the loader. sys.modules.pop(module, None) if globals is None: globals = {} return environment.template_class.from_module_dict( environment, mod.__dict__, globals )
27,888
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/meta.py
find_undeclared_variables
(ast: nodes.Template)
return codegen.undeclared_identifiers
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == {'bar'} True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well.
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned.
33
54
def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]: """Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == {'bar'} True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well. """ codegen = TrackingCodeGenerator(ast.environment) # type: ignore codegen.visit(ast) return codegen.undeclared_identifiers
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/meta.py#L33-L54
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
77.61194
22
1
100
17
def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]: codegen = TrackingCodeGenerator(ast.environment) # type: ignore codegen.visit(ast) return codegen.undeclared_identifiers
27,889
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/meta.py
find_referenced_templates
(ast: nodes.Template)
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') >>> list(meta.find_referenced_templates(ast)) ['layout.html', None] This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed.
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded.
61
111
def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]: """Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') >>> list(meta.find_referenced_templates(ast)) ['layout.html', None] This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed. """ template_name: t.Any for node in ast.find_all(_ref_types): template: nodes.Expr = node.template # type: ignore if not isinstance(template, nodes.Const): # a tuple with some non consts in there if isinstance(template, (nodes.Tuple, nodes.List)): for template_name in template.items: # something const, only yield the strings and ignore # non-string consts that really just make no sense if isinstance(template_name, nodes.Const): if isinstance(template_name.value, str): yield template_name.value # something dynamic in there else: yield None # something dynamic we don't know about here else: yield None continue # constant is a basestring, direct template name if isinstance(template.value, str): yield template.value # a tuple or list (latter *should* not happen) made of consts, # yield the consts that are strings. We could warn here for # non string values elif isinstance(node, nodes.Include) and isinstance( template.value, (tuple, list) ): for template_name in template.value: if isinstance(template_name, str): yield template_name # something else we don't care about, we could warn here else: yield None
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/meta.py#L61-L111
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
82.352941
[ 42, 45, 46, 47, 50 ]
9.803922
false
77.61194
51
12
90.196078
13
def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]: template_name: t.Any for node in ast.find_all(_ref_types): template: nodes.Expr = node.template # type: ignore if not isinstance(template, nodes.Const): # a tuple with some non consts in there if isinstance(template, (nodes.Tuple, nodes.List)): for template_name in template.items: # something const, only yield the strings and ignore # non-string consts that really just make no sense if isinstance(template_name, nodes.Const): if isinstance(template_name.value, str): yield template_name.value # something dynamic in there else: yield None # something dynamic we don't know about here else: yield None continue # constant is a basestring, direct template name if isinstance(template.value, str): yield template.value # a tuple or list (latter *should* not happen) made of consts, # yield the consts that are strings. We could warn here for # non string values elif isinstance(node, nodes.Include) and isinstance( template.value, (tuple, list) ): for template_name in template.value: if isinstance(template_name, str): yield template_name # something else we don't care about, we could warn here else: yield None
27,890
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/meta.py
TrackingCodeGenerator.__init__
(self, environment: "Environment")
17
19
def __init__(self, environment: "Environment") -> None: super().__init__(environment, "<introspection>", "<introspection>") self.undeclared_identifiers: t.Set[str] = set()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/meta.py#L17-L19
42
[ 0, 1, 2 ]
100
[]
0
true
77.61194
3
1
100
0
def __init__(self, environment: "Environment") -> None: super().__init__(environment, "<introspection>", "<introspection>") self.undeclared_identifiers: t.Set[str] = set()
27,891
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/meta.py
TrackingCodeGenerator.write
(self, x: str)
Don't write.
Don't write.
21
22
def write(self, x: str) -> None: """Don't write."""
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/meta.py#L21-L22
42
[ 0, 1 ]
100
[]
0
true
77.61194
2
1
100
1
def write(self, x: str) -> None:
27,892
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/meta.py
TrackingCodeGenerator.enter_frame
(self, frame: Frame)
Remember all undeclared identifiers.
Remember all undeclared identifiers.
24
30
def enter_frame(self, frame: Frame) -> None: """Remember all undeclared identifiers.""" super().enter_frame(frame) for _, (action, param) in frame.symbols.loads.items(): if action == "resolve" and param not in self.environment.globals: self.undeclared_identifiers.add(param)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/meta.py#L24-L30
42
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
77.61194
7
4
100
1
def enter_frame(self, frame: Frame) -> None: super().enter_frame(frame) for _, (action, param) in frame.symbols.loads.items(): if action == "resolve" and param not in self.environment.globals: self.undeclared_identifiers.add(param)
27,893
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
optimizeconst
(f: F)
return update_wrapper(t.cast(F, new_func), f)
43
56
def optimizeconst(f: F) -> F: def new_func( self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any ) -> t.Any: # Only optimize if the frame is not volatile if self.optimizer is not None and not frame.eval_ctx.volatile: new_node = self.optimizer.visit(node, frame.eval_ctx) if new_node != node: return self.visit(new_node, frame) return f(self, node, frame, **kwargs) return update_wrapper(t.cast(F, new_func), f)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L43-L56
42
[ 0, 1, 4, 5, 6, 7, 8, 10, 11, 12, 13 ]
78.571429
[ 9 ]
7.142857
false
92.742927
14
5
92.857143
0
def optimizeconst(f: F) -> F: def new_func( self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any ) -> t.Any: # Only optimize if the frame is not volatile if self.optimizer is not None and not frame.eval_ctx.volatile: new_node = self.optimizer.visit(node, frame.eval_ctx) if new_node != node: return self.visit(new_node, frame) return f(self, node, frame, **kwargs) return update_wrapper(t.cast(F, new_func), f)
27,894
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
_make_binop
(op: str)
return visitor
59
78
def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: @optimizeconst def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: if ( self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore ): self.write(f"environment.call_binop(context, {op!r}, ") self.visit(node.left, frame) self.write(", ") self.visit(node.right, frame) else: self.write("(") self.visit(node.left, frame) self.write(f" {op} ") self.visit(node.right, frame) self.write(")") return visitor
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L59-L78
42
[ 0, 1, 2, 3, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19 ]
80
[]
0
false
92.742927
20
4
100
0
def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: @optimizeconst def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: if ( self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore ): self.write(f"environment.call_binop(context, {op!r}, ") self.visit(node.left, frame) self.write(", ") self.visit(node.right, frame) else: self.write("(") self.visit(node.left, frame) self.write(f" {op} ") self.visit(node.right, frame) self.write(")") return visitor
27,895
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
_make_unop
( op: str, )
return visitor
81
98
def _make_unop( op: str, ) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: @optimizeconst def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: if ( self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore ): self.write(f"environment.call_unop(context, {op!r}, ") self.visit(node.node, frame) else: self.write("(" + op) self.visit(node.node, frame) self.write(")") return visitor
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L81-L98
42
[ 0, 3, 4, 5, 9, 10, 12, 13, 14, 15, 16, 17 ]
66.666667
[]
0
false
92.742927
18
4
100
0
def _make_unop( op: str, ) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: @optimizeconst def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: if ( self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore ): self.write(f"environment.call_unop(context, {op!r}, ") self.visit(node.node, frame) else: self.write("(" + op) self.visit(node.node, frame) self.write(")") return visitor
27,896
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
generate
( node: nodes.Template, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, )
return None
Generate the python source for a node tree.
Generate the python source for a node tree.
101
122
def generate( node: nodes.Template, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, ) -> t.Optional[str]: """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError("Can't compile non template nodes") generator = environment.code_generator_class( environment, name, filename, stream, defer_init, optimized ) generator.visit(node) if stream is None: return generator.stream.getvalue() # type: ignore return None
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L101-L122
42
[ 0, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
54.545455
[ 11, 21 ]
9.090909
false
92.742927
22
3
90.909091
1
def generate( node: nodes.Template, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, ) -> t.Optional[str]: if not isinstance(node, nodes.Template): raise TypeError("Can't compile non template nodes") generator = environment.code_generator_class( environment, name, filename, stream, defer_init, optimized ) generator.visit(node) if stream is None: return generator.stream.getvalue() # type: ignore return None
27,897
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
has_safe_repr
(value: t.Any)
return False
Does the node have a safe representation?
Does the node have a safe representation?
125
139
def has_safe_repr(value: t.Any) -> bool: """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in {bool, int, float, complex, range, str, Markup}: return True if type(value) in {tuple, list, set, frozenset}: return all(has_safe_repr(v) for v in value) if type(value) is dict: return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) return False
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L125-L139
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
92.742927
15
8
100
1
def has_safe_repr(value: t.Any) -> bool: if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in {bool, int, float, complex, range, str, Markup}: return True if type(value) in {tuple, list, set, frozenset}: return all(has_safe_repr(v) for v in value) if type(value) is dict: return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) return False
27,898
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
find_undeclared
( nodes: t.Iterable[nodes.Node], names: t.Iterable[str] )
return visitor.undeclared
Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found.
Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found.
142
154
def find_undeclared( nodes: t.Iterable[nodes.Node], names: t.Iterable[str] ) -> t.Set[str]: """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L142-L154
42
[ 0, 5, 6, 7, 8, 9, 10, 11, 12 ]
69.230769
[]
0
false
92.742927
13
3
100
2
def find_undeclared( nodes: t.Iterable[nodes.Node], names: t.Iterable[str] ) -> t.Set[str]: visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared
27,899
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
MacroRef.__init__
(self, node: t.Union[nodes.Macro, nodes.CallBlock])
158
162
def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: self.node = node self.accesses_caller = False self.accesses_kwargs = False self.accesses_varargs = False
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L158-L162
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.742927
5
1
100
0
def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: self.node = node self.accesses_caller = False self.accesses_kwargs = False self.accesses_varargs = False
27,900
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
Frame.__init__
( self, eval_ctx: EvalContext, parent: t.Optional["Frame"] = None, level: t.Optional[int] = None, )
168
217
def __init__( self, eval_ctx: EvalContext, parent: t.Optional["Frame"] = None, level: t.Optional[int] = None, ) -> None: self.eval_ctx = eval_ctx # the parent of this frame self.parent = parent if parent is None: self.symbols = Symbols(level=level) # in some dynamic inheritance situations the compiler needs to add # write tests around output statements. self.require_output_check = False # inside some tags we are using a buffer rather than yield statements. # this for example affects {% filter %} or {% macro %}. If a frame # is buffered this variable points to the name of the list used as # buffer. self.buffer: t.Optional[str] = None # the name of the block we're in, otherwise None. self.block: t.Optional[str] = None else: self.symbols = Symbols(parent.symbols, level=level) self.require_output_check = parent.require_output_check self.buffer = parent.buffer self.block = parent.block # a toplevel frame is the root + soft frames such as if conditions. self.toplevel = False # the root frame is basically just the outermost frame, so no if # conditions. This information is used to optimize inheritance # situations. self.rootlevel = False # variables set inside of loops and blocks should not affect outer frames, # but they still needs to be kept track of as part of the active context. self.loop_frame = False self.block_frame = False # track whether the frame is being used in an if-statement or conditional # expression as it determines which errors should be raised during runtime # or compile time. self.soft_frame = False
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L168-L217
42
[ 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 ]
88
[]
0
false
92.742927
50
2
100
0
def __init__( self, eval_ctx: EvalContext, parent: t.Optional["Frame"] = None, level: t.Optional[int] = None, ) -> None: self.eval_ctx = eval_ctx # the parent of this frame self.parent = parent if parent is None: self.symbols = Symbols(level=level) # in some dynamic inheritance situations the compiler needs to add # write tests around output statements. self.require_output_check = False # inside some tags we are using a buffer rather than yield statements. # this for example affects {% filter %} or {% macro %}. If a frame # is buffered this variable points to the name of the list used as # buffer. self.buffer: t.Optional[str] = None # the name of the block we're in, otherwise None. self.block: t.Optional[str] = None else: self.symbols = Symbols(parent.symbols, level=level) self.require_output_check = parent.require_output_check self.buffer = parent.buffer self.block = parent.block # a toplevel frame is the root + soft frames such as if conditions. self.toplevel = False # the root frame is basically just the outermost frame, so no if # conditions. This information is used to optimize inheritance # situations. self.rootlevel = False # variables set inside of loops and blocks should not affect outer frames, # but they still needs to be kept track of as part of the active context. self.loop_frame = False self.block_frame = False # track whether the frame is being used in an if-statement or conditional # expression as it determines which errors should be raised during runtime # or compile time. self.soft_frame = False
27,901
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
Frame.copy
(self)
return rv
Create a copy of the current one.
Create a copy of the current one.
219
224
def copy(self) -> "Frame": """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L219-L224
42
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
92.742927
6
1
100
1
def copy(self) -> "Frame": rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
27,902
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
Frame.inner
(self, isolated: bool = False)
return Frame(self.eval_ctx, self)
Return an inner frame.
Return an inner frame.
226
230
def inner(self, isolated: bool = False) -> "Frame": """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L226-L230
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.742927
5
2
100
1
def inner(self, isolated: bool = False) -> "Frame": if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
27,903
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
Frame.soft
(self)
return rv
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. This is only used to implement if-statements and conditional expressions.
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer.
232
243
def soft(self) -> "Frame": """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. This is only used to implement if-statements and conditional expressions. """ rv = self.copy() rv.rootlevel = False rv.soft_frame = True return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L232-L243
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
92.742927
12
1
100
6
def soft(self) -> "Frame": rv = self.copy() rv.rootlevel = False rv.soft_frame = True return rv
27,904
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
DependencyFinderVisitor.__init__
(self)
255
257
def __init__(self) -> None: self.filters: t.Set[str] = set() self.tests: t.Set[str] = set()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L255-L257
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
0
def __init__(self) -> None: self.filters: t.Set[str] = set() self.tests: t.Set[str] = set()
27,905
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
DependencyFinderVisitor.visit_Filter
(self, node: nodes.Filter)
259
261
def visit_Filter(self, node: nodes.Filter) -> None: self.generic_visit(node) self.filters.add(node.name)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L259-L261
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
0
def visit_Filter(self, node: nodes.Filter) -> None: self.generic_visit(node) self.filters.add(node.name)
27,906
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
DependencyFinderVisitor.visit_Block
(self, node: nodes.Block)
Stop visiting at blocks.
Stop visiting at blocks.
267
268
def visit_Block(self, node: nodes.Block) -> None: """Stop visiting at blocks."""
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L267-L268
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
1
def visit_Block(self, node: nodes.Block) -> None:
27,907
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
UndeclaredNameVisitor.__init__
(self, names: t.Iterable[str])
277
279
def __init__(self, names: t.Iterable[str]) -> None: self.names = set(names) self.undeclared: t.Set[str] = set()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L277-L279
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
0
def __init__(self, names: t.Iterable[str]) -> None: self.names = set(names) self.undeclared: t.Set[str] = set()
27,908
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
UndeclaredNameVisitor.visit_Name
(self, node: nodes.Name)
281
287
def visit_Name(self, node: nodes.Name) -> None: if node.ctx == "load" and node.name in self.names: self.undeclared.add(node.name) if self.undeclared == self.names: raise VisitorExit() else: self.names.discard(node.name)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L281-L287
42
[ 0, 1, 2, 3, 4, 6 ]
85.714286
[]
0
false
92.742927
7
4
100
0
def visit_Name(self, node: nodes.Name) -> None: if node.ctx == "load" and node.name in self.names: self.undeclared.add(node.name) if self.undeclared == self.names: raise VisitorExit() else: self.names.discard(node.name)
27,909
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
UndeclaredNameVisitor.visit_Block
(self, node: nodes.Block)
Stop visiting a blocks.
Stop visiting a blocks.
289
290
def visit_Block(self, node: nodes.Block) -> None: """Stop visiting a blocks."""
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L289-L290
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
1
def visit_Block(self, node: nodes.Block) -> None:
27,910
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.__init__
( self, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, )
301
372
def __init__( self, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, ) -> None: if stream is None: stream = StringIO() self.environment = environment self.name = name self.filename = filename self.stream = stream self.created_block_context = False self.defer_init = defer_init self.optimizer: t.Optional[Optimizer] = None if optimized: self.optimizer = Optimizer(environment) # aliases for imports self.import_aliases: t.Dict[str, str] = {} # a registry for all blocks. Because blocks are moved out # into the global python scope they are registered here self.blocks: t.Dict[str, nodes.Block] = {} # the number of extends statements so far self.extends_so_far = 0 # some templates have a rootlevel extends. In this case we # can safely assume that we're a child template and do some # more optimizations. self.has_known_extends = False # the current line number self.code_lineno = 1 # registry of all filters and tests (global, not block local) self.tests: t.Dict[str, str] = {} self.filters: t.Dict[str, str] = {} # the debug information self.debug_info: t.List[t.Tuple[int, int]] = [] self._write_debug_info: t.Optional[int] = None # the number of new lines before the next write() self._new_lines = 0 # the line number of the last written statement self._last_line = 0 # true if nothing was written so far. self._first_write = True # used by the `temporary_identifier` method to get new # unique, temporary identifier self._last_identifier = 0 # the current indentation self._indentation = 0 # Tracks toplevel assignments self._assign_stack: t.List[t.Set[str]] = [] # Tracks parameter definition blocks self._param_def_block: t.List[t.Set[str]] = [] # Tracks the current context. self._context_reference_stack = ["context"]
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L301-L372
42
[ 0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71 ]
88.888889
[]
0
false
92.742927
72
3
100
0
def __init__( self, environment: "Environment", name: t.Optional[str], filename: t.Optional[str], stream: t.Optional[t.TextIO] = None, defer_init: bool = False, optimized: bool = True, ) -> None: if stream is None: stream = StringIO() self.environment = environment self.name = name self.filename = filename self.stream = stream self.created_block_context = False self.defer_init = defer_init self.optimizer: t.Optional[Optimizer] = None if optimized: self.optimizer = Optimizer(environment) # aliases for imports self.import_aliases: t.Dict[str, str] = {} # a registry for all blocks. Because blocks are moved out # into the global python scope they are registered here self.blocks: t.Dict[str, nodes.Block] = {} # the number of extends statements so far self.extends_so_far = 0 # some templates have a rootlevel extends. In this case we # can safely assume that we're a child template and do some # more optimizations. self.has_known_extends = False # the current line number self.code_lineno = 1 # registry of all filters and tests (global, not block local) self.tests: t.Dict[str, str] = {} self.filters: t.Dict[str, str] = {} # the debug information self.debug_info: t.List[t.Tuple[int, int]] = [] self._write_debug_info: t.Optional[int] = None # the number of new lines before the next write() self._new_lines = 0 # the line number of the last written statement self._last_line = 0 # true if nothing was written so far. self._first_write = True # used by the `temporary_identifier` method to get new # unique, temporary identifier self._last_identifier = 0 # the current indentation self._indentation = 0 # Tracks toplevel assignments self._assign_stack: t.List[t.Set[str]] = [] # Tracks parameter definition blocks self._param_def_block: t.List[t.Set[str]] = [] # Tracks the current context. self._context_reference_stack = ["context"]
27,911
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.optimized
(self)
return self.optimizer is not None
375
376
def optimized(self) -> bool: return self.optimizer is not None
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L375-L376
42
[ 0 ]
50
[ 1 ]
50
false
92.742927
2
1
50
0
def optimized(self) -> bool: return self.optimizer is not None
27,912
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.fail
(self, msg: str, lineno: int)
Fail with a :exc:`TemplateAssertionError`.
Fail with a :exc:`TemplateAssertionError`.
380
382
def fail(self, msg: str, lineno: int) -> "te.NoReturn": """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L380-L382
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
1
def fail(self, msg: str, lineno: int) -> "te.NoReturn": raise TemplateAssertionError(msg, lineno, self.name, self.filename)
27,913
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.temporary_identifier
(self)
return f"t_{self._last_identifier}"
Get a new unique identifier.
Get a new unique identifier.
384
387
def temporary_identifier(self) -> str: """Get a new unique identifier.""" self._last_identifier += 1 return f"t_{self._last_identifier}"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L384-L387
42
[ 0, 1, 2, 3 ]
100
[]
0
true
92.742927
4
1
100
1
def temporary_identifier(self) -> str: self._last_identifier += 1 return f"t_{self._last_identifier}"
27,914
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.buffer
(self, frame: Frame)
Enable buffering for the frame from that point onwards.
Enable buffering for the frame from that point onwards.
389
392
def buffer(self, frame: Frame) -> None: """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline(f"{frame.buffer} = []")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L389-L392
42
[ 0, 1, 2, 3 ]
100
[]
0
true
92.742927
4
1
100
1
def buffer(self, frame: Frame) -> None: frame.buffer = self.temporary_identifier() self.writeline(f"{frame.buffer} = []")
27,915
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.return_buffer_contents
( self, frame: Frame, force_unescaped: bool = False )
Return the buffer contents of the frame.
Return the buffer contents of the frame.
394
412
def return_buffer_contents( self, frame: Frame, force_unescaped: bool = False ) -> None: """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline("if context.eval_ctx.autoescape:") self.indent() self.writeline(f"return Markup(concat({frame.buffer}))") self.outdent() self.writeline("else:") self.indent() self.writeline(f"return concat({frame.buffer})") self.outdent() return elif frame.eval_ctx.autoescape: self.writeline(f"return Markup(concat({frame.buffer}))") return self.writeline(f"return concat({frame.buffer})")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L394-L412
42
[ 0, 3, 4, 5, 15, 18 ]
31.578947
[ 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17 ]
57.894737
false
92.742927
19
4
42.105263
1
def return_buffer_contents( self, frame: Frame, force_unescaped: bool = False ) -> None: if not force_unescaped: if frame.eval_ctx.volatile: self.writeline("if context.eval_ctx.autoescape:") self.indent() self.writeline(f"return Markup(concat({frame.buffer}))") self.outdent() self.writeline("else:") self.indent() self.writeline(f"return concat({frame.buffer})") self.outdent() return elif frame.eval_ctx.autoescape: self.writeline(f"return Markup(concat({frame.buffer}))") return self.writeline(f"return concat({frame.buffer})")
27,916
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.indent
(self)
Indent by one.
Indent by one.
414
416
def indent(self) -> None: """Indent by one.""" self._indentation += 1
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L414-L416
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
1
def indent(self) -> None: self._indentation += 1
27,917
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.outdent
(self, step: int = 1)
Outdent by step.
Outdent by step.
418
420
def outdent(self, step: int = 1) -> None: """Outdent by step.""" self._indentation -= step
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L418-L420
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
1
def outdent(self, step: int = 1) -> None: self._indentation -= step
27,918
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.start_write
(self, frame: Frame, node: t.Optional[nodes.Node] = None)
Yield or write into the frame buffer.
Yield or write into the frame buffer.
422
427
def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline("yield ", node) else: self.writeline(f"{frame.buffer}.append(", node)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L422-L427
42
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
92.742927
6
2
100
1
def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: if frame.buffer is None: self.writeline("yield ", node) else: self.writeline(f"{frame.buffer}.append(", node)
27,919
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.end_write
(self, frame: Frame)
End the writing process started by `start_write`.
End the writing process started by `start_write`.
429
432
def end_write(self, frame: Frame) -> None: """End the writing process started by `start_write`.""" if frame.buffer is not None: self.write(")")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L429-L432
42
[ 0, 1, 2, 3 ]
100
[]
0
true
92.742927
4
2
100
1
def end_write(self, frame: Frame) -> None: if frame.buffer is not None: self.write(")")
27,920
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.simple_write
( self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None )
Simple shortcut for start_write + write + end_write.
Simple shortcut for start_write + write + end_write.
434
440
def simple_write( self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None ) -> None: """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L434-L440
42
[ 0, 3, 4, 5, 6 ]
71.428571
[]
0
false
92.742927
7
1
100
1
def simple_write( self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None ) -> None: self.start_write(frame, node) self.write(s) self.end_write(frame)
27,921
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.blockvisit
(self, nodes: t.Iterable[nodes.Node], frame: Frame)
Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically.
Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically.
442
451
def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: """Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically. """ try: self.writeline("pass") for node in nodes: self.visit(node, frame) except CompilerExit: pass
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L442-L451
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
92.742927
10
3
100
2
def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: try: self.writeline("pass") for node in nodes: self.visit(node, frame) except CompilerExit: pass
27,922
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.write
(self, x: str)
Write a string into the output stream.
Write a string into the output stream.
453
465
def write(self, x: str) -> None: """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write("\n" * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(" " * self._indentation) self._new_lines = 0 self.stream.write(x)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L453-L465
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
92.742927
13
4
100
1
def write(self, x: str) -> None: if self._new_lines: if not self._first_write: self.stream.write("\n" * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(" " * self._indentation) self._new_lines = 0 self.stream.write(x)
27,923
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.writeline
( self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 )
Combination of newline and write.
Combination of newline and write.
467
472
def writeline( self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 ) -> None: """Combination of newline and write.""" self.newline(node, extra) self.write(x)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L467-L472
42
[ 0, 3, 4, 5 ]
66.666667
[]
0
false
92.742927
6
1
100
1
def writeline( self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 ) -> None: self.newline(node, extra) self.write(x)
27,924
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.newline
(self, node: t.Optional[nodes.Node] = None, extra: int = 0)
Add one or more newlines before the next write.
Add one or more newlines before the next write.
474
479
def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L474-L479
42
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
92.742927
6
3
100
1
def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
27,925
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.signature
( self, node: t.Union[nodes.Call, nodes.Filter, nodes.Test], frame: Frame, extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, )
Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occur. The extra keyword arguments should be given as python dict.
Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occur. The extra keyword arguments should be given as python dict.
481
536
def signature( self, node: t.Union[nodes.Call, nodes.Filter, nodes.Test], frame: Frame, extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, ) -> None: """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occur. The extra keyword arguments should be given as python dict. """ # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = any( is_python_keyword(t.cast(str, k)) for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) ) for arg in node.args: self.write(", ") self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(", ") self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in extra_kwargs.items(): self.write(f", {key}={value}") if node.dyn_args: self.write(", *") self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(", **dict({") else: self.write(", **{") for kwarg in node.kwargs: self.write(f"{kwarg.key!r}: ") self.visit(kwarg.value, frame) self.write(", ") if extra_kwargs is not None: for key, value in extra_kwargs.items(): self.write(f"{key!r}: {value}, ") if node.dyn_kwargs is not None: self.write("}, **") self.visit(node.dyn_kwargs, frame) self.write(")") else: self.write("}") elif node.dyn_kwargs is not None: self.write(", **") self.visit(node.dyn_kwargs, frame)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L481-L536
42
[ 0, 13, 14, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 52, 53, 54, 55 ]
42.857143
[ 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51 ]
26.785714
false
92.742927
56
15
73.214286
5
def signature( self, node: t.Union[nodes.Call, nodes.Filter, nodes.Test], frame: Frame, extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, ) -> None: # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = any( is_python_keyword(t.cast(str, k)) for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) ) for arg in node.args: self.write(", ") self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(", ") self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in extra_kwargs.items(): self.write(f", {key}={value}") if node.dyn_args: self.write(", *") self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(", **dict({") else: self.write(", **{") for kwarg in node.kwargs: self.write(f"{kwarg.key!r}: ") self.visit(kwarg.value, frame) self.write(", ") if extra_kwargs is not None: for key, value in extra_kwargs.items(): self.write(f"{key!r}: {value}, ") if node.dyn_kwargs is not None: self.write("}, **") self.visit(node.dyn_kwargs, frame) self.write(")") else: self.write("}") elif node.dyn_kwargs is not None: self.write(", **") self.visit(node.dyn_kwargs, frame)
27,926
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.pull_dependencies
(self, nodes: t.Iterable[nodes.Node])
Find all filter and test names used in the template and assign them to variables in the compiled namespace. Checking that the names are registered with the environment is done when compiling the Filter and Test nodes. If the node is in an If or CondExpr node, the check is done at runtime instead. .. versionchanged:: 3.0 Filters and tests in If and CondExpr nodes are checked at runtime instead of compile time.
Find all filter and test names used in the template and assign them to variables in the compiled namespace. Checking that the names are registered with the environment is done when compiling the Filter and Test nodes. If the node is in an If or CondExpr node, the check is done at runtime instead.
538
579
def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: """Find all filter and test names used in the template and assign them to variables in the compiled namespace. Checking that the names are registered with the environment is done when compiling the Filter and Test nodes. If the node is in an If or CondExpr node, the check is done at runtime instead. .. versionchanged:: 3.0 Filters and tests in If and CondExpr nodes are checked at runtime instead of compile time. """ visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for id_map, names, dependency in (self.filters, visitor.filters, "filters"), ( self.tests, visitor.tests, "tests", ): for name in sorted(names): if name not in id_map: id_map[name] = self.temporary_identifier() # add check during runtime that dependencies used inside of executed # blocks are defined, as this step may be skipped during compile time self.writeline("try:") self.indent() self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") self.outdent() self.writeline("except KeyError:") self.indent() self.writeline("@internalcode") self.writeline(f"def {id_map[name]}(*unused):") self.indent() self.writeline( f'raise TemplateRuntimeError("No {dependency[:-1]}' f' named {name!r} found.")' ) self.outdent() self.outdent()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L538-L579
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
100
[]
0
true
92.742927
42
5
100
9
def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for id_map, names, dependency in (self.filters, visitor.filters, "filters"), ( self.tests, visitor.tests, "tests", ): for name in sorted(names): if name not in id_map: id_map[name] = self.temporary_identifier() # add check during runtime that dependencies used inside of executed # blocks are defined, as this step may be skipped during compile time self.writeline("try:") self.indent() self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") self.outdent() self.writeline("except KeyError:") self.indent() self.writeline("@internalcode") self.writeline(f"def {id_map[name]}(*unused):") self.indent() self.writeline( f'raise TemplateRuntimeError("No {dependency[:-1]}' f' named {name!r} found.")' ) self.outdent() self.outdent()
27,927
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.enter_frame
(self, frame: Frame)
581
595
def enter_frame(self, frame: Frame) -> None: undefs = [] for target, (action, param) in frame.symbols.loads.items(): if action == VAR_LOAD_PARAMETER: pass elif action == VAR_LOAD_RESOLVE: self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") elif action == VAR_LOAD_ALIAS: self.writeline(f"{target} = {param}") elif action == VAR_LOAD_UNDEFINED: undefs.append(target) else: raise NotImplementedError("unknown load instruction") if undefs: self.writeline(f"{' = '.join(undefs)} = missing")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L581-L595
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14 ]
86.666667
[ 12 ]
6.666667
false
92.742927
15
7
93.333333
0
def enter_frame(self, frame: Frame) -> None: undefs = [] for target, (action, param) in frame.symbols.loads.items(): if action == VAR_LOAD_PARAMETER: pass elif action == VAR_LOAD_RESOLVE: self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") elif action == VAR_LOAD_ALIAS: self.writeline(f"{target} = {param}") elif action == VAR_LOAD_UNDEFINED: undefs.append(target) else: raise NotImplementedError("unknown load instruction") if undefs: self.writeline(f"{' = '.join(undefs)} = missing")
27,928
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.leave_frame
(self, frame: Frame, with_python_scope: bool = False)
597
603
def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: if not with_python_scope: undefs = [] for target in frame.symbols.loads: undefs.append(target) if undefs: self.writeline(f"{' = '.join(undefs)} = missing")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L597-L603
42
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
92.742927
7
4
100
0
def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: if not with_python_scope: undefs = [] for target in frame.symbols.loads: undefs.append(target) if undefs: self.writeline(f"{' = '.join(undefs)} = missing")
27,929
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.choose_async
(self, async_value: str = "async ", sync_value: str = "")
return async_value if self.environment.is_async else sync_value
605
606
def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: return async_value if self.environment.is_async else sync_value
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L605-L606
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
0
def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: return async_value if self.environment.is_async else sync_value
27,930
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.func
(self, name: str)
return f"{self.choose_async()}def {name}"
608
609
def func(self, name: str) -> str: return f"{self.choose_async()}def {name}"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L608-L609
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
0
def func(self, name: str) -> str: return f"{self.choose_async()}def {name}"
27,931
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.macro_body
( self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame )
return frame, macro_ref
Dump the function def of a macro or call block.
Dump the function def of a macro or call block.
611
692
def macro_body( self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame ) -> t.Tuple[Frame, MacroRef]: """Dump the function def of a macro or call block.""" frame = frame.inner() frame.symbols.analyze_node(node) macro_ref = MacroRef(node) explicit_caller = None skip_special_params = set() args = [] for idx, arg in enumerate(node.args): if arg.name == "caller": explicit_caller = idx if arg.name in ("kwargs", "varargs"): skip_special_params.add(arg.name) args.append(frame.symbols.ref(arg.name)) undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) if "caller" in undeclared: # In older Jinja versions there was a bug that allowed caller # to retain the special behavior even if it was mentioned in # the argument list. However thankfully this was only really # working if it was the last argument. So we are explicitly # checking this now and error out if it is anywhere else in # the argument list. if explicit_caller is not None: try: node.defaults[explicit_caller - len(node.args)] except IndexError: self.fail( "When defining macros or call blocks the " 'special "caller" argument must be omitted ' "or be given a default.", node.lineno, ) else: args.append(frame.symbols.declare_parameter("caller")) macro_ref.accesses_caller = True if "kwargs" in undeclared and "kwargs" not in skip_special_params: args.append(frame.symbols.declare_parameter("kwargs")) macro_ref.accesses_kwargs = True if "varargs" in undeclared and "varargs" not in skip_special_params: args.append(frame.symbols.declare_parameter("varargs")) macro_ref.accesses_varargs = True # macros are delayed, they never require output checks frame.require_output_check = False frame.symbols.analyze_node(node) self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) self.indent() self.buffer(frame) self.enter_frame(frame) self.push_parameter_definitions(frame) for idx, arg in enumerate(node.args): ref = frame.symbols.ref(arg.name) self.writeline(f"if {ref} is missing:") self.indent() try: default = node.defaults[idx - len(node.args)] except IndexError: self.writeline( f'{ref} = undefined("parameter {arg.name!r} was not provided",' f" name={arg.name!r})" ) else: self.writeline(f"{ref} = ") self.visit(default, frame) self.mark_parameter_stored(ref) self.outdent() self.pop_parameter_definitions() self.blockvisit(node.body, frame) self.return_buffer_contents(frame, force_unescaped=True) self.leave_frame(frame, with_python_scope=True) self.outdent() return frame, macro_ref
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L611-L692
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81 ]
96.341463
[ 16 ]
1.219512
false
92.742927
82
13
98.780488
1
def macro_body( self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame ) -> t.Tuple[Frame, MacroRef]: frame = frame.inner() frame.symbols.analyze_node(node) macro_ref = MacroRef(node) explicit_caller = None skip_special_params = set() args = [] for idx, arg in enumerate(node.args): if arg.name == "caller": explicit_caller = idx if arg.name in ("kwargs", "varargs"): skip_special_params.add(arg.name) args.append(frame.symbols.ref(arg.name)) undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) if "caller" in undeclared: # In older Jinja versions there was a bug that allowed caller # to retain the special behavior even if it was mentioned in # the argument list. However thankfully this was only really # working if it was the last argument. So we are explicitly # checking this now and error out if it is anywhere else in # the argument list. if explicit_caller is not None: try: node.defaults[explicit_caller - len(node.args)] except IndexError: self.fail( "When defining macros or call blocks the " 'special "caller" argument must be omitted ' "or be given a default.", node.lineno, ) else: args.append(frame.symbols.declare_parameter("caller")) macro_ref.accesses_caller = True if "kwargs" in undeclared and "kwargs" not in skip_special_params: args.append(frame.symbols.declare_parameter("kwargs")) macro_ref.accesses_kwargs = True if "varargs" in undeclared and "varargs" not in skip_special_params: args.append(frame.symbols.declare_parameter("varargs")) macro_ref.accesses_varargs = True # macros are delayed, they never require output checks frame.require_output_check = False frame.symbols.analyze_node(node) self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) self.indent() self.buffer(frame) self.enter_frame(frame) self.push_parameter_definitions(frame) for idx, arg in enumerate(node.args): ref = frame.symbols.ref(arg.name) self.writeline(f"if {ref} is missing:") self.indent() try: default = node.defaults[idx - len(node.args)] except IndexError: self.writeline( f'{ref} = undefined("parameter {arg.name!r} was not provided",' f" name={arg.name!r})" ) else: self.writeline(f"{ref} = ") self.visit(default, frame) self.mark_parameter_stored(ref) self.outdent() self.pop_parameter_definitions() self.blockvisit(node.body, frame) self.return_buffer_contents(frame, force_unescaped=True) self.leave_frame(frame, with_python_scope=True) self.outdent() return frame, macro_ref
27,932
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.macro_def
(self, macro_ref: MacroRef, frame: Frame)
Dump the macro definition for the def created by macro_body.
Dump the macro definition for the def created by macro_body.
694
704
def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: """Dump the macro definition for the def created by macro_body.""" arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, "name", None) if len(macro_ref.node.args) == 1: arg_tuple += "," self.write( f"Macro(environment, macro, {name!r}, ({arg_tuple})," f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L694-L704
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
92.742927
11
2
100
1
def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, "name", None) if len(macro_ref.node.args) == 1: arg_tuple += "," self.write( f"Macro(environment, macro, {name!r}, ({arg_tuple})," f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" )
27,933
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.position
(self, node: nodes.Node)
return rv
Return a human readable position for the node.
Return a human readable position for the node.
706
711
def position(self, node: nodes.Node) -> str: """Return a human readable position for the node.""" rv = f"line {node.lineno}" if self.name is not None: rv = f"{rv} in {self.name!r}" return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L706-L711
42
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
92.742927
6
2
100
1
def position(self, node: nodes.Node) -> str: rv = f"line {node.lineno}" if self.name is not None: rv = f"{rv} in {self.name!r}" return rv
27,934
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.dump_local_context
(self, frame: Frame)
return f"{{{items_kv}}}"
713
718
def dump_local_context(self, frame: Frame) -> str: items_kv = ", ".join( f"{name!r}: {target}" for name, target in frame.symbols.dump_stores().items() ) return f"{{{items_kv}}}"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L713-L718
42
[ 0, 1, 5 ]
50
[]
0
false
92.742927
6
1
100
0
def dump_local_context(self, frame: Frame) -> str: items_kv = ", ".join( f"{name!r}: {target}" for name, target in frame.symbols.dump_stores().items() ) return f"{{{items_kv}}}"
27,935
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.write_commons
(self)
Writes a common preamble that is used by root and block functions. Primarily this sets up common local helpers and enforces a generator through a dead branch.
Writes a common preamble that is used by root and block functions. Primarily this sets up common local helpers and enforces a generator through a dead branch.
720
731
def write_commons(self) -> None: """Writes a common preamble that is used by root and block functions. Primarily this sets up common local helpers and enforces a generator through a dead branch. """ self.writeline("resolve = context.resolve_or_missing") self.writeline("undefined = environment.undefined") self.writeline("concat = environment.concat") # always use the standard Undefined class for the implicit else of # conditional expressions self.writeline("cond_expr_undefined = Undefined") self.writeline("if 0: yield None")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L720-L731
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
92.742927
12
1
100
3
def write_commons(self) -> None: self.writeline("resolve = context.resolve_or_missing") self.writeline("undefined = environment.undefined") self.writeline("concat = environment.concat") # always use the standard Undefined class for the implicit else of # conditional expressions self.writeline("cond_expr_undefined = Undefined") self.writeline("if 0: yield None")
27,936
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.push_parameter_definitions
(self, frame: Frame)
Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters.
Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters.
733
740
def push_parameter_definitions(self, frame: Frame) -> None: """Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters. """ self._param_def_block.append(frame.symbols.dump_param_targets())
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L733-L740
42
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
92.742927
8
1
100
5
def push_parameter_definitions(self, frame: Frame) -> None: self._param_def_block.append(frame.symbols.dump_param_targets())
27,937
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.pop_parameter_definitions
(self)
Pops the current parameter definitions set.
Pops the current parameter definitions set.
742
744
def pop_parameter_definitions(self) -> None: """Pops the current parameter definitions set.""" self._param_def_block.pop()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L742-L744
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
1
def pop_parameter_definitions(self) -> None: self._param_def_block.pop()
27,938
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.mark_parameter_stored
(self, target: str)
Marks a parameter in the current parameter definitions as stored. This will skip the enforced undefined checks.
Marks a parameter in the current parameter definitions as stored. This will skip the enforced undefined checks.
746
751
def mark_parameter_stored(self, target: str) -> None: """Marks a parameter in the current parameter definitions as stored. This will skip the enforced undefined checks. """ if self._param_def_block: self._param_def_block[-1].discard(target)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L746-L751
42
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
92.742927
6
2
100
2
def mark_parameter_stored(self, target: str) -> None: if self._param_def_block: self._param_def_block[-1].discard(target)
27,939
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.push_context_reference
(self, target: str)
753
754
def push_context_reference(self, target: str) -> None: self._context_reference_stack.append(target)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L753-L754
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
0
def push_context_reference(self, target: str) -> None: self._context_reference_stack.append(target)
27,940
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.pop_context_reference
(self)
756
757
def pop_context_reference(self) -> None: self._context_reference_stack.pop()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L756-L757
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
0
def pop_context_reference(self) -> None: self._context_reference_stack.pop()
27,941
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.get_context_ref
(self)
return self._context_reference_stack[-1]
759
760
def get_context_ref(self) -> str: return self._context_reference_stack[-1]
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L759-L760
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
0
def get_context_ref(self) -> str: return self._context_reference_stack[-1]
27,942
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.get_resolve_func
(self)
return f"{target}.resolve"
762
766
def get_resolve_func(self) -> str: target = self._context_reference_stack[-1] if target == "context": return "resolve" return f"{target}.resolve"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L762-L766
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.742927
5
2
100
0
def get_resolve_func(self) -> str: target = self._context_reference_stack[-1] if target == "context": return "resolve" return f"{target}.resolve"
27,943
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.derive_context
(self, frame: Frame)
return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"
768
769
def derive_context(self, frame: Frame) -> str: return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L768-L769
42
[ 0, 1 ]
100
[]
0
true
92.742927
2
1
100
0
def derive_context(self, frame: Frame) -> str: return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"
27,944
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.parameter_is_undeclared
(self, target: str)
return target in self._param_def_block[-1]
Checks if a given target is an undeclared parameter.
Checks if a given target is an undeclared parameter.
771
775
def parameter_is_undeclared(self, target: str) -> bool: """Checks if a given target is an undeclared parameter.""" if not self._param_def_block: return False return target in self._param_def_block[-1]
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L771-L775
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.742927
5
2
100
1
def parameter_is_undeclared(self, target: str) -> bool: if not self._param_def_block: return False return target in self._param_def_block[-1]
27,945
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.push_assign_tracking
(self)
Pushes a new layer for assignment tracking.
Pushes a new layer for assignment tracking.
777
779
def push_assign_tracking(self) -> None: """Pushes a new layer for assignment tracking.""" self._assign_stack.append(set())
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L777-L779
42
[ 0, 1, 2 ]
100
[]
0
true
92.742927
3
1
100
1
def push_assign_tracking(self) -> None: self._assign_stack.append(set())
27,946
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.pop_assign_tracking
(self, frame: Frame)
Pops the topmost level for assignment tracking and updates the context variables if necessary.
Pops the topmost level for assignment tracking and updates the context variables if necessary.
781
822
def pop_assign_tracking(self, frame: Frame) -> None: """Pops the topmost level for assignment tracking and updates the context variables if necessary. """ vars = self._assign_stack.pop() if ( not frame.block_frame and not frame.loop_frame and not frame.toplevel or not vars ): return public_names = [x for x in vars if x[:1] != "_"] if len(vars) == 1: name = next(iter(vars)) ref = frame.symbols.ref(name) if frame.loop_frame: self.writeline(f"_loop_vars[{name!r}] = {ref}") return if frame.block_frame: self.writeline(f"_block_vars[{name!r}] = {ref}") return self.writeline(f"context.vars[{name!r}] = {ref}") else: if frame.loop_frame: self.writeline("_loop_vars.update({") elif frame.block_frame: self.writeline("_block_vars.update({") else: self.writeline("context.vars.update({") for idx, name in enumerate(vars): if idx: self.write(", ") ref = frame.symbols.ref(name) self.write(f"{name!r}: {ref}") self.write("})") if not frame.block_frame and not frame.loop_frame and public_names: if len(public_names) == 1: self.writeline(f"context.exported_vars.add({public_names[0]!r})") else: names_str = ", ".join(map(repr, public_names)) self.writeline(f"context.exported_vars.update(({names_str}))")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L781-L822
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 36, 37, 38, 39 ]
66.666667
[ 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 40, 41 ]
30.952381
false
92.742927
42
17
69.047619
2
def pop_assign_tracking(self, frame: Frame) -> None: vars = self._assign_stack.pop() if ( not frame.block_frame and not frame.loop_frame and not frame.toplevel or not vars ): return public_names = [x for x in vars if x[:1] != "_"] if len(vars) == 1: name = next(iter(vars)) ref = frame.symbols.ref(name) if frame.loop_frame: self.writeline(f"_loop_vars[{name!r}] = {ref}") return if frame.block_frame: self.writeline(f"_block_vars[{name!r}] = {ref}") return self.writeline(f"context.vars[{name!r}] = {ref}") else: if frame.loop_frame: self.writeline("_loop_vars.update({") elif frame.block_frame: self.writeline("_block_vars.update({") else: self.writeline("context.vars.update({") for idx, name in enumerate(vars): if idx: self.write(", ") ref = frame.symbols.ref(name) self.write(f"{name!r}: {ref}") self.write("})") if not frame.block_frame and not frame.loop_frame and public_names: if len(public_names) == 1: self.writeline(f"context.exported_vars.add({public_names[0]!r})") else: names_str = ", ".join(map(repr, public_names)) self.writeline(f"context.exported_vars.update(({names_str}))")
27,947
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_Template
( self, node: nodes.Template, frame: t.Optional[Frame] = None )
826
942
def visit_Template( self, node: nodes.Template, frame: t.Optional[Frame] = None ) -> None: assert frame is None, "no root frame allowed" eval_ctx = EvalContext(self.environment, self.name) from .runtime import exported, async_exported if self.environment.is_async: exported_names = sorted(exported + async_exported) else: exported_names = sorted(exported) self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) # if we want a deferred initialization we cannot move the # environment into a local name envenv = "" if self.defer_init else ", environment=environment" # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail(f"block {block.name!r} defined twice", block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if "." in imp: module, obj = imp.rsplit(".", 1) self.writeline(f"from {module} import {obj} as {alias}") else: self.writeline(f"import {imp} as {alias}") # add the load name self.writeline(f"name = {self.name!r}") # generate the root render function. self.writeline( f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 ) self.indent() self.write_commons() # process the root frame = Frame(eval_ctx) if "self" in find_undeclared(node.body, ("self",)): ref = frame.symbols.declare_parameter("self") self.writeline(f"{ref} = TemplateReference(context)") frame.symbols.analyze_node(node) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends if have_extends: self.writeline("parent_template = None") self.enter_frame(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.leave_frame(frame, with_python_scope=True) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline("if parent_template is not None:") self.indent() if not self.environment.is_async: self.writeline("yield from parent_template.root_render_func(context)") else: self.writeline( "async for event in parent_template.root_render_func(context):" ) self.indent() self.writeline("yield event") self.outdent() self.outdent(1 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in self.blocks.items(): self.writeline( f"{self.func('block_' + name)}(context, missing=missing{envenv}):", block, 1, ) self.indent() self.write_commons() # It's important that we do not make this frame a child of the # toplevel template. This would cause a variety of # interesting issues with identifier tracking. block_frame = Frame(eval_ctx) block_frame.block_frame = True undeclared = find_undeclared(block.body, ("self", "super")) if "self" in undeclared: ref = block_frame.symbols.declare_parameter("self") self.writeline(f"{ref} = TemplateReference(context)") if "super" in undeclared: ref = block_frame.symbols.declare_parameter("super") self.writeline(f"{ref} = context.super({name!r}, block_{name})") block_frame.symbols.analyze_node(block) block_frame.block = name self.writeline("_block_vars = {}") self.enter_frame(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.leave_frame(block_frame, with_python_scope=True) self.outdent() blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) self.writeline(f"debug_info = {debug_kv_str!r}")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L826-L942
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 40, 41, 42, 43, 44, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 75, 78, 79, 80, 81, 82, 83, 84, 85, 90, 91, 92, 93, 94, 95, 96, 97, 98, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116 ]
84.615385
[ 26, 38, 99, 100 ]
3.418803
false
92.742927
117
17
96.581197
0
def visit_Template( self, node: nodes.Template, frame: t.Optional[Frame] = None ) -> None: assert frame is None, "no root frame allowed" eval_ctx = EvalContext(self.environment, self.name) from .runtime import exported, async_exported if self.environment.is_async: exported_names = sorted(exported + async_exported) else: exported_names = sorted(exported) self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) # if we want a deferred initialization we cannot move the # environment into a local name envenv = "" if self.defer_init else ", environment=environment" # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail(f"block {block.name!r} defined twice", block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if "." in imp: module, obj = imp.rsplit(".", 1) self.writeline(f"from {module} import {obj} as {alias}") else: self.writeline(f"import {imp} as {alias}") # add the load name self.writeline(f"name = {self.name!r}") # generate the root render function. self.writeline( f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 ) self.indent() self.write_commons() # process the root frame = Frame(eval_ctx) if "self" in find_undeclared(node.body, ("self",)): ref = frame.symbols.declare_parameter("self") self.writeline(f"{ref} = TemplateReference(context)") frame.symbols.analyze_node(node) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends if have_extends: self.writeline("parent_template = None") self.enter_frame(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.leave_frame(frame, with_python_scope=True) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline("if parent_template is not None:") self.indent() if not self.environment.is_async: self.writeline("yield from parent_template.root_render_func(context)") else: self.writeline( "async for event in parent_template.root_render_func(context):" ) self.indent() self.writeline("yield event") self.outdent() self.outdent(1 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in self.blocks.items(): self.writeline( f"{self.func('block_' + name)}(context, missing=missing{envenv}):", block, 1, ) self.indent() self.write_commons() # It's important that we do not make this frame a child of the # toplevel template. This would cause a variety of # interesting issues with identifier tracking. block_frame = Frame(eval_ctx) block_frame.block_frame = True undeclared = find_undeclared(block.body, ("self", "super")) if "self" in undeclared: ref = block_frame.symbols.declare_parameter("self") self.writeline(f"{ref} = TemplateReference(context)") if "super" in undeclared: ref = block_frame.symbols.declare_parameter("super") self.writeline(f"{ref} = context.super({name!r}, block_{name})") block_frame.symbols.analyze_node(block) block_frame.block = name self.writeline("_block_vars = {}") self.enter_frame(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.leave_frame(block_frame, with_python_scope=True) self.outdent() blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) self.writeline(f"debug_info = {debug_kv_str!r}")
27,948
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_Block
(self, node: nodes.Block, frame: Frame)
Call a block and register it for the template.
Call a block and register it for the template.
944
985
def visit_Block(self, node: nodes.Block, frame: Frame) -> None: """Call a block and register it for the template.""" level = 0 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline("if parent_template is None:") self.indent() level += 1 if node.scoped: context = self.derive_context(frame) else: context = self.get_context_ref() if node.required: self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) self.indent() self.writeline( f'raise TemplateRuntimeError("Required block {node.name!r} not found")', node, ) self.outdent() if not self.environment.is_async and frame.buffer is None: self.writeline( f"yield from context.blocks[{node.name!r}][0]({context})", node ) else: self.writeline( f"{self.choose_async()}for event in" f" context.blocks[{node.name!r}][0]({context}):", node, ) self.indent() self.simple_write("event", frame) self.outdent() self.outdent(level)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L944-L985
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
100
[]
0
true
92.742927
42
8
100
1
def visit_Block(self, node: nodes.Block, frame: Frame) -> None: level = 0 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline("if parent_template is None:") self.indent() level += 1 if node.scoped: context = self.derive_context(frame) else: context = self.get_context_ref() if node.required: self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) self.indent() self.writeline( f'raise TemplateRuntimeError("Required block {node.name!r} not found")', node, ) self.outdent() if not self.environment.is_async and frame.buffer is None: self.writeline( f"yield from context.blocks[{node.name!r}][0]({context})", node ) else: self.writeline( f"{self.choose_async()}for event in" f" context.blocks[{node.name!r}][0]({context}):", node, ) self.indent() self.simple_write("event", frame) self.outdent() self.outdent(level)
27,949
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_Extends
(self, node: nodes.Extends, frame: Frame)
Calls the extender.
Calls the extender.
987
1,028
def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: """Calls the extender.""" if not frame.toplevel: self.fail("cannot use extend from a non top-level scope", node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline("if parent_template is not None:") self.indent() self.writeline('raise TemplateRuntimeError("extended multiple times")') # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() else: self.outdent() self.writeline("parent_template = environment.get_template(", node) self.visit(node.template, frame) self.write(f", {self.name!r})") self.writeline("for name, parent_block in parent_template.blocks.items():") self.indent() self.writeline("context.blocks.setdefault(name, []).append(parent_block)") self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L987-L1028
42
[ 0, 1, 2, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
90.47619
[ 3 ]
2.380952
false
92.742927
42
6
97.619048
1
def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: if not frame.toplevel: self.fail("cannot use extend from a non top-level scope", node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline("if parent_template is not None:") self.indent() self.writeline('raise TemplateRuntimeError("extended multiple times")') # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() else: self.outdent() self.writeline("parent_template = environment.get_template(", node) self.visit(node.template, frame) self.write(f", {self.name!r})") self.writeline("for name, parent_block in parent_template.blocks.items():") self.indent() self.writeline("context.blocks.setdefault(name, []).append(parent_block)") self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1
27,950
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_Include
(self, node: nodes.Include, frame: Frame)
Handles includes.
Handles includes.
1,030
1,079
def visit_Include(self, node: nodes.Include, frame: Frame) -> None: """Handles includes.""" if node.ignore_missing: self.writeline("try:") self.indent() func_name = "get_or_select_template" if isinstance(node.template, nodes.Const): if isinstance(node.template.value, str): func_name = "get_template" elif isinstance(node.template.value, (tuple, list)): func_name = "select_template" elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = "select_template" self.writeline(f"template = environment.{func_name}(", node) self.visit(node.template, frame) self.write(f", {self.name!r})") if node.ignore_missing: self.outdent() self.writeline("except TemplateNotFound:") self.indent() self.writeline("pass") self.outdent() self.writeline("else:") self.indent() skip_event_yield = False if node.with_context: self.writeline( f"{self.choose_async()}for event in template.root_render_func(" "template.new_context(context.get_all(), True," f" {self.dump_local_context(frame)})):" ) elif self.environment.is_async: self.writeline( "for event in (await template._get_default_module_async())" "._body_stream:" ) else: self.writeline("yield from template._get_default_module()._body_stream") skip_event_yield = True if not skip_event_yield: self.indent() self.simple_write("event", frame) self.outdent() if node.ignore_missing: self.outdent()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1030-L1079
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 ]
96
[ 10, 11 ]
4
false
92.742927
50
11
96
1
def visit_Include(self, node: nodes.Include, frame: Frame) -> None: if node.ignore_missing: self.writeline("try:") self.indent() func_name = "get_or_select_template" if isinstance(node.template, nodes.Const): if isinstance(node.template.value, str): func_name = "get_template" elif isinstance(node.template.value, (tuple, list)): func_name = "select_template" elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = "select_template" self.writeline(f"template = environment.{func_name}(", node) self.visit(node.template, frame) self.write(f", {self.name!r})") if node.ignore_missing: self.outdent() self.writeline("except TemplateNotFound:") self.indent() self.writeline("pass") self.outdent() self.writeline("else:") self.indent() skip_event_yield = False if node.with_context: self.writeline( f"{self.choose_async()}for event in template.root_render_func(" "template.new_context(context.get_all(), True," f" {self.dump_local_context(frame)})):" ) elif self.environment.is_async: self.writeline( "for event in (await template._get_default_module_async())" "._body_stream:" ) else: self.writeline("yield from template._get_default_module()._body_stream") skip_event_yield = True if not skip_event_yield: self.indent() self.simple_write("event", frame) self.outdent() if node.ignore_missing: self.outdent()
27,951
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator._import_common
( self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame )
1,081
1,094
def _import_common( self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame ) -> None: self.write(f"{self.choose_async('await ')}environment.get_template(") self.visit(node.template, frame) self.write(f", {self.name!r}).") if node.with_context: f_name = f"make_module{self.choose_async('_async')}" self.write( f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" ) else: self.write(f"_get_default_module{self.choose_async('_async')}(context)")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1081-L1094
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 13 ]
64.285714
[]
0
false
92.742927
14
2
100
0
def _import_common( self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame ) -> None: self.write(f"{self.choose_async('await ')}environment.get_template(") self.visit(node.template, frame) self.write(f", {self.name!r}).") if node.with_context: f_name = f"make_module{self.choose_async('_async')}" self.write( f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" ) else: self.write(f"_get_default_module{self.choose_async('_async')}(context)")
27,952
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_Import
(self, node: nodes.Import, frame: Frame)
Visit regular imports.
Visit regular imports.
1,096
1,105
def visit_Import(self, node: nodes.Import, frame: Frame) -> None: """Visit regular imports.""" self.writeline(f"{frame.symbols.ref(node.target)} = ", node) if frame.toplevel: self.write(f"context.vars[{node.target!r}] = ") self._import_common(node, frame) if frame.toplevel and not node.target.startswith("_"): self.writeline(f"context.exported_vars.discard({node.target!r})")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1096-L1105
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
92.742927
10
4
100
1
def visit_Import(self, node: nodes.Import, frame: Frame) -> None: self.writeline(f"{frame.symbols.ref(node.target)} = ", node) if frame.toplevel: self.write(f"context.vars[{node.target!r}] = ") self._import_common(node, frame) if frame.toplevel and not node.target.startswith("_"): self.writeline(f"context.exported_vars.discard({node.target!r})")
27,953
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_FromImport
(self, node: nodes.FromImport, frame: Frame)
Visit named imports.
Visit named imports.
1,107
1,155
def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: """Visit named imports.""" self.newline(node) self.write("included_template = ") self._import_common(node, frame) var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline( f"{frame.symbols.ref(alias)} =" f" getattr(included_template, {name!r}, missing)" ) self.writeline(f"if {frame.symbols.ref(alias)} is missing:") self.indent() message = ( "the template {included_template.__name__!r}" f" (imported on {self.position(node)})" f" does not export the requested name {name!r}" ) self.writeline( f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" ) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith("_"): discarded_names.append(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") else: names_kv = ", ".join( f"{name!r}: {frame.symbols.ref(name)}" for name in var_names ) self.writeline(f"context.vars.update({{{names_kv}}})") if discarded_names: if len(discarded_names) == 1: self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") else: names_str = ", ".join(map(repr, discarded_names)) self.writeline( f"context.exported_vars.difference_update(({names_str}))" )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1107-L1155
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48 ]
97.959184
[ 9 ]
2.040816
false
92.742927
49
9
97.959184
1
def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: self.newline(node) self.write("included_template = ") self._import_common(node, frame) var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline( f"{frame.symbols.ref(alias)} =" f" getattr(included_template, {name!r}, missing)" ) self.writeline(f"if {frame.symbols.ref(alias)} is missing:") self.indent() message = ( "the template {included_template.__name__!r}" f" (imported on {self.position(node)})" f" does not export the requested name {name!r}" ) self.writeline( f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" ) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith("_"): discarded_names.append(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") else: names_kv = ", ".join( f"{name!r}: {frame.symbols.ref(name)}" for name in var_names ) self.writeline(f"context.vars.update({{{names_kv}}})") if discarded_names: if len(discarded_names) == 1: self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") else: names_str = ", ".join(map(repr, discarded_names)) self.writeline( f"context.exported_vars.difference_update(({names_str}))" )
27,954
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_For
(self, node: nodes.For, frame: Frame)
1,157
1,294
def visit_For(self, node: nodes.For, frame: Frame) -> None: loop_frame = frame.inner() loop_frame.loop_frame = True test_frame = frame.inner() else_frame = frame.inner() # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body if the body is a scoped block. extended_loop = ( node.recursive or "loop" in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) or any(block.scoped for block in node.find_all(nodes.Block)) ) loop_ref = None if extended_loop: loop_ref = loop_frame.symbols.declare_parameter("loop") loop_frame.symbols.analyze_node(node, for_branch="body") if node.else_: else_frame.symbols.analyze_node(node, for_branch="else") if node.test: loop_filter_func = self.temporary_identifier() test_frame.symbols.analyze_node(node, for_branch="test") self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) self.indent() self.enter_frame(test_frame) self.writeline(self.choose_async("async for ", "for ")) self.visit(node.target, loop_frame) self.write(" in ") self.write(self.choose_async("auto_aiter(fiter)", "fiter")) self.write(":") self.indent() self.writeline("if ", node.test) self.visit(node.test, test_frame) self.write(":") self.indent() self.writeline("yield ") self.visit(node.target, loop_frame) self.outdent(3) self.leave_frame(test_frame, with_python_scope=True) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if node.recursive: self.writeline( f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node ) self.indent() self.buffer(loop_frame) # Use the same buffer for the else frame else_frame.buffer = loop_frame.buffer # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: self.writeline(f"{loop_ref} = missing") for name in node.find_all(nodes.Name): if name.ctx == "store" and name.name == "loop": self.fail( "Can't assign to special loop variable in for-loop target", name.lineno, ) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline(f"{iteration_indicator} = 1") self.writeline(self.choose_async("async for ", "for "), node) self.visit(node.target, loop_frame) if extended_loop: self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") else: self.write(" in ") if node.test: self.write(f"{loop_filter_func}(") if node.recursive: self.write("reciter") else: if self.environment.is_async and not extended_loop: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async and not extended_loop: self.write(")") if node.test: self.write(")") if node.recursive: self.write(", undefined, loop_render_func, depth):") else: self.write(", undefined):" if extended_loop else ":") self.indent() self.enter_frame(loop_frame) self.writeline("_loop_vars = {}") self.blockvisit(node.body, loop_frame) if node.else_: self.writeline(f"{iteration_indicator} = 0") self.outdent() self.leave_frame( loop_frame, with_python_scope=node.recursive and not node.else_ ) if node.else_: self.writeline(f"if {iteration_indicator}:") self.indent() self.enter_frame(else_frame) self.blockvisit(node.else_, else_frame) self.leave_frame(else_frame) self.outdent() # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) self.write(f"{self.choose_async('await ')}loop(") if self.environment.is_async: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async: self.write(")") self.write(", loop)") self.end_write(frame) # at the end of the iteration, clear any assignments made in the # loop from the top level if self._assign_stack: self._assign_stack[-1].difference_update(loop_frame.symbols.stores)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1157-L1294
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 69, 70, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137 ]
89.130435
[]
0
false
92.742927
138
28
100
0
def visit_For(self, node: nodes.For, frame: Frame) -> None: loop_frame = frame.inner() loop_frame.loop_frame = True test_frame = frame.inner() else_frame = frame.inner() # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body if the body is a scoped block. extended_loop = ( node.recursive or "loop" in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) or any(block.scoped for block in node.find_all(nodes.Block)) ) loop_ref = None if extended_loop: loop_ref = loop_frame.symbols.declare_parameter("loop") loop_frame.symbols.analyze_node(node, for_branch="body") if node.else_: else_frame.symbols.analyze_node(node, for_branch="else") if node.test: loop_filter_func = self.temporary_identifier() test_frame.symbols.analyze_node(node, for_branch="test") self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) self.indent() self.enter_frame(test_frame) self.writeline(self.choose_async("async for ", "for ")) self.visit(node.target, loop_frame) self.write(" in ") self.write(self.choose_async("auto_aiter(fiter)", "fiter")) self.write(":") self.indent() self.writeline("if ", node.test) self.visit(node.test, test_frame) self.write(":") self.indent() self.writeline("yield ") self.visit(node.target, loop_frame) self.outdent(3) self.leave_frame(test_frame, with_python_scope=True) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if node.recursive: self.writeline( f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node ) self.indent() self.buffer(loop_frame) # Use the same buffer for the else frame else_frame.buffer = loop_frame.buffer # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: self.writeline(f"{loop_ref} = missing") for name in node.find_all(nodes.Name): if name.ctx == "store" and name.name == "loop": self.fail( "Can't assign to special loop variable in for-loop target", name.lineno, ) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline(f"{iteration_indicator} = 1") self.writeline(self.choose_async("async for ", "for "), node) self.visit(node.target, loop_frame) if extended_loop: self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") else: self.write(" in ") if node.test: self.write(f"{loop_filter_func}(") if node.recursive: self.write("reciter") else: if self.environment.is_async and not extended_loop: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async and not extended_loop: self.write(")") if node.test: self.write(")") if node.recursive: self.write(", undefined, loop_render_func, depth):") else: self.write(", undefined):" if extended_loop else ":") self.indent() self.enter_frame(loop_frame) self.writeline("_loop_vars = {}") self.blockvisit(node.body, loop_frame) if node.else_: self.writeline(f"{iteration_indicator} = 0") self.outdent() self.leave_frame( loop_frame, with_python_scope=node.recursive and not node.else_ ) if node.else_: self.writeline(f"if {iteration_indicator}:") self.indent() self.enter_frame(else_frame) self.blockvisit(node.else_, else_frame) self.leave_frame(else_frame) self.outdent() # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) self.write(f"{self.choose_async('await ')}loop(") if self.environment.is_async: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async: self.write(")") self.write(", loop)") self.end_write(frame) # at the end of the iteration, clear any assignments made in the # loop from the top level if self._assign_stack: self._assign_stack[-1].difference_update(loop_frame.symbols.stores)
27,955
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_If
(self, node: nodes.If, frame: Frame)
1,296
1,315
def visit_If(self, node: nodes.If, frame: Frame) -> None: if_frame = frame.soft() self.writeline("if ", node) self.visit(node.test, if_frame) self.write(":") self.indent() self.blockvisit(node.body, if_frame) self.outdent() for elif_ in node.elif_: self.writeline("elif ", elif_) self.visit(elif_.test, if_frame) self.write(":") self.indent() self.blockvisit(elif_.body, if_frame) self.outdent() if node.else_: self.writeline("else:") self.indent() self.blockvisit(node.else_, if_frame) self.outdent()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1296-L1315
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
92.742927
20
3
100
0
def visit_If(self, node: nodes.If, frame: Frame) -> None: if_frame = frame.soft() self.writeline("if ", node) self.visit(node.test, if_frame) self.write(":") self.indent() self.blockvisit(node.body, if_frame) self.outdent() for elif_ in node.elif_: self.writeline("elif ", elif_) self.visit(elif_.test, if_frame) self.write(":") self.indent() self.blockvisit(elif_.body, if_frame) self.outdent() if node.else_: self.writeline("else:") self.indent() self.blockvisit(node.else_, if_frame) self.outdent()
27,956
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_Macro
(self, node: nodes.Macro, frame: Frame)
1,317
1,325
def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: macro_frame, macro_ref = self.macro_body(node, frame) self.newline() if frame.toplevel: if not node.name.startswith("_"): self.write(f"context.exported_vars.add({node.name!r})") self.writeline(f"context.vars[{node.name!r}] = ") self.write(f"{frame.symbols.ref(node.name)} = ") self.macro_def(macro_ref, macro_frame)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1317-L1325
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
92.742927
9
3
100
0
def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: macro_frame, macro_ref = self.macro_body(node, frame) self.newline() if frame.toplevel: if not node.name.startswith("_"): self.write(f"context.exported_vars.add({node.name!r})") self.writeline(f"context.vars[{node.name!r}] = ") self.write(f"{frame.symbols.ref(node.name)} = ") self.macro_def(macro_ref, macro_frame)
27,957
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_CallBlock
(self, node: nodes.CallBlock, frame: Frame)
1,327
1,333
def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: call_frame, macro_ref = self.macro_body(node, frame) self.writeline("caller = ") self.macro_def(macro_ref, call_frame) self.start_write(frame, node) self.visit_Call(node.call, frame, forward_caller=True) self.end_write(frame)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1327-L1333
42
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
92.742927
7
1
100
0
def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: call_frame, macro_ref = self.macro_body(node, frame) self.writeline("caller = ") self.macro_def(macro_ref, call_frame) self.start_write(frame, node) self.visit_Call(node.call, frame, forward_caller=True) self.end_write(frame)
27,958
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_FilterBlock
(self, node: nodes.FilterBlock, frame: Frame)
1,335
1,344
def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: filter_frame = frame.inner() filter_frame.symbols.analyze_node(node) self.enter_frame(filter_frame) self.buffer(filter_frame) self.blockvisit(node.body, filter_frame) self.start_write(frame, node) self.visit_Filter(node.filter, filter_frame) self.end_write(frame) self.leave_frame(filter_frame)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1335-L1344
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
92.742927
10
1
100
0
def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: filter_frame = frame.inner() filter_frame.symbols.analyze_node(node) self.enter_frame(filter_frame) self.buffer(filter_frame) self.blockvisit(node.body, filter_frame) self.start_write(frame, node) self.visit_Filter(node.filter, filter_frame) self.end_write(frame) self.leave_frame(filter_frame)
27,959
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/compiler.py
CodeGenerator.visit_With
(self, node: nodes.With, frame: Frame)
1,346
1,356
def visit_With(self, node: nodes.With, frame: Frame) -> None: with_frame = frame.inner() with_frame.symbols.analyze_node(node) self.enter_frame(with_frame) for target, expr in zip(node.targets, node.values): self.newline() self.visit(target, with_frame) self.write(" = ") self.visit(expr, frame) self.blockvisit(node.body, with_frame) self.leave_frame(with_frame)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/compiler.py#L1346-L1356
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
92.742927
11
2
100
0
def visit_With(self, node: nodes.With, frame: Frame) -> None: with_frame = frame.inner() with_frame.symbols.analyze_node(node) self.enter_frame(with_frame) for target, expr in zip(node.targets, node.values): self.newline() self.visit(target, with_frame) self.write(" = ") self.visit(expr, frame) self.blockvisit(node.body, with_frame) self.leave_frame(with_frame)
27,960