code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
return self._pipeline.history(name=self.data.name, offset=offset)
|
def history(self, offset=0)
|
The pipeline history allows users to list pipeline instances.
:param offset: number of pipeline instances to be skipped.
:return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: list of yagocd.resources.pipeline.PipelineInstance
| 11.923245 | 20.639627 | 0.577687 |
return self._pipeline.get(name=self.data.name, counter=counter)
|
def get(self, counter)
|
Gets pipeline instance object.
:param counter pipeline counter:
:return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: yagocd.resources.pipeline.PipelineInstance
| 10.798785 | 16.899727 | 0.638992 |
self._pipeline.pause(name=self.data.name, cause=cause)
|
def pause(self, cause)
|
Pause the current pipeline.
:param cause: reason for pausing the pipeline.
| 11.876667 | 12.268448 | 0.968066 |
return self._pipeline.schedule(
name=self.data.name,
materials=materials,
variables=variables,
secure_variables=secure_variables
)
|
def schedule(self, materials=None, variables=None, secure_variables=None)
|
Scheduling allows user to trigger a specific pipeline.
:param materials: material revisions to use.
:param variables: environment variables to set.
:param secure_variables: secure environment variables to set.
:return: a text confirmation.
| 3.909457 | 4.293263 | 0.910603 |
return self._pipeline.schedule_with_instance(
name=self.data.name,
materials=materials,
variables=variables,
secure_variables=secure_variables,
backoff=backoff,
max_tries=max_tries
)
|
def schedule_with_instance(
self,
materials=None,
variables=None,
secure_variables=None,
backoff=0.5,
max_tries=20
)
|
Schedule pipeline and return instance.
Credits of implementation comes to `gaqzi`:
https://github.com/gaqzi/py-gocd/blob/master/gocd/api/pipeline.py#L122
:warning: Replace this with whatever is the official way as soon as gocd#990 is fixed. \
https://github.com/gocd/gocd/issues/990
:param materials: material revisions to use.
:param variables: environment variables to set.
:param secure_variables: secure environment variables to set.
:param backoff: time to wait before checking for new instance.
:param max_tries: maximum tries to do.
:return: possible triggered instance of pipeline.
:rtype: yagocd.resources.pipeline.PipelineInstance
| 2.423152 | 2.887395 | 0.839217 |
return PipelineEntity.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)
|
def pipeline_url(self)
|
Returns url for accessing pipeline entity.
| 9.335773 | 6.172204 | 1.512551 |
stages = list()
for data in self.data.stages:
stages.append(StageInstance(session=self._session, data=data, pipeline=self))
return stages
|
def stages(self)
|
Method for getting stages from pipeline instance.
:return: arrays of stages
:rtype: list of yagocd.resources.stage.StageInstance
| 6.368313 | 5.639705 | 1.129193 |
for stage in self.stages():
if stage.data.name == name:
return stage
|
def stage(self, name)
|
Method for searching specific stage by it's name.
:param name: name of the stage to search.
:return: found stage or None.
:rtype: yagocd.resources.stage.StageInstance
| 5.535012 | 8.265962 | 0.669615 |
values = [values[name]]
instance_name = '_{}'.format(name)
values.append(getattr(self, instance_name, None))
try:
return next(item for item in values if item is not None)
except StopIteration:
raise ValueError("The value for parameter '{}' is required!".format(name))
|
def _require_param(self, name, values)
|
Method for finding the value for the given parameter name.
The value for the parameter could be extracted from two places:
* `values` dictionary
* `self._<name>` attribute
The use case for this method is that some resources are nested and
managers could have dependencies on parent data, for example
:class:`ArtifactManager` should know about pipeline, stage and job
in order to get data for specific instance of artifact. In case we
obtain this information from pipeline and going down to the
artifact, it will be provided in constructor for that manager.
But in case we would like to use functionality of specific manager
without getting parents -- directly from :class:`Yagocd`, then we
have to be able to execute method with given parameters for parents.
Current method - `_require_param` - is used to find out which
parameters should one use: either provided at construction time and
stored as `self._<name>` or provided as function arguments.
:param name: name of the parameter, which value to extract.
:param values: dictionary, which could contain the value
for our parameter.
:return: founded value or raises `ValueError`.
| 3.573759 | 4.496383 | 0.794807 |
if not self.VERSION_TO_ACCEPT_HEADER:
return self.ACCEPT_HEADER
return YagocdUtil.choose_option(
version_to_options=self.VERSION_TO_ACCEPT_HEADER,
default=self.ACCEPT_HEADER,
server_version=self._session.server_version
)
|
def _accept_header(self)
|
Method for determining correct `Accept` header.
Different resources and different GoCD version servers prefer
a diverse headers. In order to manage all of them, this method
tries to help: if `VERSION_TO_ACCEPT_HEADER` is not provided,
if would simply return default `ACCEPT_HEADER`.
Though if some manager specifies `VERSION_TO_ACCEPT_HEADER`
class variable, then it should be a dictionary: keys should be
a versions and values should be desired accept headers.
Choosing is pessimistic: if version of a server is less or
equal to one of the dictionary, the value of that key would be
used.
:return: accept header to use in request.
| 7.27164 | 4.872437 | 1.492403 |
result = self._predecessors
if transitive:
return YagocdUtil.graph_depth_walk(result, lambda v: v.predecessors)
return result
|
def get_predecessors(self, transitive=False)
|
Property for getting predecessors (parents) of current pipeline.
This property automatically populates from API call
:return: list of :class:`yagocd.resources.pipeline.PipelineEntity`.
:rtype: list of yagocd.resources.pipeline.PipelineEntity
| 10.377913 | 10.678138 | 0.971884 |
result = self._descendants
if transitive:
return YagocdUtil.graph_depth_walk(result, lambda v: v.descendants)
return result
|
def get_descendants(self, transitive=False)
|
Property for getting descendants (children) of current pipeline.
It's calculated by :meth:`yagocd.resources.pipeline.PipelineManager#tie_descendants` method during listing of
all pipelines.
:return: list of :class:`yagocd.resources.pipeline.PipelineEntity`.
:rtype: list of yagocd.resources.pipeline.PipelineEntity
| 12.270678 | 11.215253 | 1.094106 |
return self._manager.walk(top=self._path, topdown=topdown)
|
def walk(self, topdown=True)
|
Artifact tree generator - analogue of `os.walk`.
:param topdown: if is True or not specified, directories are scanned
from top-down. If topdown is set to False, directories are scanned
from bottom-up.
:rtype: collections.Iterator[
(str, list[yagocd.resources.artifact.Artifact], list[yagocd.resources.artifact.Artifact])
]
| 9.754908 | 10.233301 | 0.953251 |
if self.data.type == self._manager.FOLDER_TYPE:
raise YagocdException("Can't fetch folder <{}>, only file!".format(self._path))
response = self._session.get(self.data.url)
return response.content
|
def fetch(self)
|
Method for getting artifact's content.
Could only be applicable for file type.
:return: content of the artifact.
| 9.572053 | 8.513043 | 1.124398 |
# Validate args!
if 'oauth_consumer_key' not in args:
raise web.HTTPError(401, "oauth_consumer_key missing")
if args['oauth_consumer_key'] not in self.consumers:
raise web.HTTPError(401, "oauth_consumer_key not known")
if 'oauth_signature' not in args:
raise web.HTTPError(401, "oauth_signature missing")
if 'oauth_timestamp' not in args:
raise web.HTTPError(401, 'oauth_timestamp missing')
# Allow 30s clock skew between LTI Consumer and Provider
# Also don't accept timestamps from before our process started, since that could be
# a replay attack - we won't have nonce lists from back then. This would allow users
# who can control / know when our process restarts to trivially do replay attacks.
oauth_timestamp = int(float(args['oauth_timestamp']))
if (
int(time.time()) - oauth_timestamp > 30
or oauth_timestamp < LTILaunchValidator.PROCESS_START_TIME
):
raise web.HTTPError(401, "oauth_timestamp too old")
if 'oauth_nonce' not in args:
raise web.HTTPError(401, 'oauth_nonce missing')
if (
oauth_timestamp in LTILaunchValidator.nonces
and args['oauth_nonce'] in LTILaunchValidator.nonces[oauth_timestamp]
):
raise web.HTTPError(401, "oauth_nonce + oauth_timestamp already used")
LTILaunchValidator.nonces.setdefault(oauth_timestamp, set()).add(args['oauth_nonce'])
args_list = []
for key, values in args.items():
if type(values) is list:
args_list += [(key, value) for value in values]
else:
args_list.append((key, values))
base_string = signature.construct_base_string(
'POST',
signature.normalize_base_string_uri(launch_url),
signature.normalize_parameters(
signature.collect_parameters(body=args_list, headers=headers)
)
)
consumer_secret = self.consumers[args['oauth_consumer_key']]
sign = signature.sign_hmac_sha1(base_string, consumer_secret, None)
is_valid = signature.safe_string_equals(sign, args['oauth_signature'])
if not is_valid:
raise web.HTTPError(401, "Invalid oauth_signature")
return True
|
def validate_launch_request(
self,
launch_url,
headers,
args
)
|
Validate a given launch request
launch_url: Full URL that the launch request was POSTed to
headers: k/v pair of HTTP headers coming in with the POST
args: dictionary of body arguments passed to the launch_url
Must have the following keys to be valid:
oauth_consumer_key, oauth_timestamp, oauth_nonce,
oauth_signature
| 2.853112 | 2.816817 | 1.012885 |
# inspired by code powering similar functionality in mpld3
# https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L357
from IPython.core.getipython import get_ipython
from IPython.display import display, Javascript, HTML
self.ipython_enabled = True
self.set_size('medium')
ip = get_ipython()
formatter = ip.display_formatter.formatters['text/html']
if self.local_enabled:
from lightning.visualization import VisualizationLocal
js = VisualizationLocal.load_embed()
display(HTML("<script>" + js + "</script>"))
if not self.quiet:
print('Running local mode, some functionality limited.\n')
formatter.for_type(VisualizationLocal, lambda viz, kwds=kwargs: viz.get_html())
else:
formatter.for_type(Visualization, lambda viz, kwds=kwargs: viz.get_html())
r = requests.get(self.get_ipython_markup_link(), auth=self.auth)
display(Javascript(r.text))
|
def enable_ipython(self, **kwargs)
|
Enable plotting in the iPython notebook.
Once enabled, all lightning plots will be automatically produced
within the iPython notebook. They will also be available on
your lightning server within the current session.
| 5.270133 | 5.077212 | 1.037997 |
from IPython.core.getipython import get_ipython
self.ipython_enabled = False
ip = get_ipython()
formatter = ip.display_formatter.formatters['text/html']
formatter.type_printers.pop(Visualization, None)
formatter.type_printers.pop(VisualizationLocal, None)
|
def disable_ipython(self)
|
Disable plotting in the iPython notebook.
After disabling, lightning plots will be produced in your lightning server,
but will not appear in the notebook.
| 4.947758 | 5.177229 | 0.955677 |
self.session = Session.create(self, name=name)
return self.session
|
def create_session(self, name=None)
|
Create a lightning session.
Can create a session with the provided name, otherwise session name
will be "Session No." with the number automatically generated.
| 4.489503 | 5.81019 | 0.772695 |
self.session = Session(lgn=self, id=session_id)
return self.session
|
def use_session(self, session_id)
|
Use the specified lightning session.
Specify a lightning session by id number. Check the number of an existing
session in the attribute lightning.session.id.
| 8.241739 | 7.836317 | 1.051736 |
from requests.auth import HTTPBasicAuth
self.auth = HTTPBasicAuth(username, password)
return self
|
def set_basic_auth(self, username, password)
|
Set authenatication.
| 3.310418 | 2.944153 | 1.124404 |
if host[-1] == '/':
host = host[:-1]
self.host = host
return self
|
def set_host(self, host)
|
Set the host for a lightning server.
Host can be local (e.g. http://localhost:3000), a heroku
instance (e.g. http://lightning-test.herokuapp.com), or
a independently hosted lightning server.
| 4.035933 | 4.954961 | 0.814524 |
try:
r = requests.get(self.host + '/status', auth=self.auth,
timeout=(10.0, 10.0))
if not r.status_code == requests.codes.ok:
print("Problem connecting to server at %s" % self.host)
print("status code: %s" % r.status_code)
return False
else:
print("Connected to server at %s" % self.host)
return True
except (requests.exceptions.ConnectionError,
requests.exceptions.MissingSchema,
requests.exceptions.InvalidSchema) as e:
print("Problem connecting to server at %s" % self.host)
print("error: %s" % e)
return False
|
def check_status(self)
|
Check the server for status
| 2.033027 | 1.945417 | 1.045034 |
datadict = cls.clean(*args, **kwargs)
if 'data' in datadict:
data = datadict['data']
data = cls._ensure_dict_or_list(data)
else:
data = {}
for key in datadict:
if key == 'images':
data[key] = datadict[key]
else:
d = cls._ensure_dict_or_list(datadict[key])
data[key] = cls._check_unkeyed_arrays(key, d)
return data
|
def _clean_data(cls, *args, **kwargs)
|
Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Otherwise, it should be a
dictionary of data-type specific array data (e.g. 'points',
'timeseries'), which will be labeled appropriately
(see _check_unkeyed_arrays).
| 3.02562 | 2.278565 | 1.327862 |
if not type:
raise Exception("Must provide a plot type")
options, description = cls._clean_options(**kwargs)
data = cls._clean_data(*args)
if 'images' in data and len(data) > 1:
images = data['images']
del data['images']
viz = cls._create(session, data=data, type=type, options=options, description=description)
first_image, remaining_images = images[0], images[1:]
viz._append_image(first_image)
for image in remaining_images:
viz._append_image(image)
elif 'images' in data:
images = data['images']
viz = cls._create(session, images=images, type=type, options=options, description=description)
else:
viz = cls._create(session, data=data, type=type, options=options, description=description)
return viz
|
def _baseplot(cls, session, type, *args, **kwargs)
|
Base method for plotting data and images.
Applies a plot-type specific cleaning operation to generate
a dictionary with the data, then creates a visualization with the data.
Expects a session and a type, followed by all plot-type specific
positional and keyword arguments, which will be handled by the clean
method of the given plot type.
If the dictionary contains only images, or only non-image data,
they will be passed on their own. If the dictionary contains
both images and non-image data, the images will be appended
to the visualization.
| 2.598587 | 2.342365 | 1.109386 |
data = self._clean_data(*args, **kwargs)
if 'images' in data:
images = data['images']
for img in images:
self._update_image(img)
else:
self._update_data(data=data)
|
def update(self, *args, **kwargs)
|
Base method for updating data.
Applies a plot-type specific cleaning operation, then
updates the data in the visualization.
| 3.778011 | 3.237715 | 1.166876 |
data = self._clean_data(*args, **kwargs)
if 'images' in data:
images = data['images']
for img in images:
self._append_image(img)
else:
self._append_data(data=data)
|
def append(self, *args, **kwargs)
|
Base method for appending data.
Applies a plot-type specific cleaning operation, then
appends data to the visualization.
| 3.637443 | 3.168438 | 1.148024 |
url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/'
r = requests.get(url)
if r.status_code == 200:
content = r.json()
else:
raise Exception('Error retrieving user data from server')
return content
|
def _get_user_data(self)
|
Base method for retrieving user data from a viz.
| 3.826863 | 3.115279 | 1.228418 |
checkers = {
'color': check_color,
'alpha': check_alpha,
'size': check_size,
'thickness': check_thickness,
'index': check_index,
'coordinates': check_coordinates,
'colormap': check_colormap,
'bins': check_bins,
'spec': check_spec
}
if name in checkers:
return checkers[name](prop, **kwargs)
elif isinstance(prop, list) or isinstance(prop, ndarray) or isscalar(prop):
return check_1d(prop, name)
else:
return prop
|
def check_property(prop, name, **kwargs)
|
Check and parse a property with either a specific checking function
or a generic parser
| 2.888116 | 2.902168 | 0.995158 |
if isinstance(co, ndarray):
co = co.tolist()
if not (isinstance(co[0][0], list) or isinstance(co[0][0], tuple)):
co = [co]
if xy is not True:
co = map(lambda p: asarray(p)[:, ::-1].tolist(), co)
return co
|
def check_coordinates(co, xy=None)
|
Check and parse coordinates as either a single coordinate list [[r,c],[r,c]] or a
list of coordinates for multiple regions [[[r0,c0],[r0,c0]], [[r1,c1],[r1,c1]]]
| 3.233898 | 3.130569 | 1.033007 |
c = asarray(c)
if c.ndim == 1:
c = c.flatten()
c = c[newaxis, :]
if c.shape[1] != 3:
raise Exception("Color must have three values per point")
elif c.ndim == 2:
if c.shape[1] != 3:
raise Exception("Color array must have three values per point")
return c
|
def check_color(c)
|
Check and parse color specs as either a single [r,g,b] or a list of
[[r,g,b],[r,g,b]...]
| 2.933234 | 2.851084 | 1.028814 |
names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning'])
if cmap not in names:
raise Exception("Invalid cmap '%s', must be one of %s" % (cmap, names))
else:
return cmap
|
def check_colormap(cmap)
|
Check if cmap is one of the colorbrewer maps
| 1.745488 | 1.666742 | 1.047245 |
s = check_1d(s, "size")
if any(map(lambda d: d <= 0, s)):
raise Exception('Size cannot be 0 or negative')
return s
|
def check_size(s)
|
Check and parse size specs as either a single [s] or a list of [s,s,s,...]
| 6.276177 | 5.504175 | 1.140257 |
s = check_1d(s, "thickness")
if any(map(lambda d: d <= 0, s)):
raise Exception('Thickness cannot be 0 or negative')
return s
|
def check_thickness(s)
|
Check and parse thickness specs as either a single [s] or a list of [s,s,s,...]
| 6.209819 | 5.288258 | 1.174266 |
i = asarray(i)
if (i.ndim > 1) or (size(i) < 1):
raise Exception("Index must be one-dimensional and non-singleton")
return i
|
def check_index(i)
|
Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...]
| 5.488456 | 4.378602 | 1.253472 |
a = check_1d(a, "alpha")
if any(map(lambda d: d <= 0, a)):
raise Exception('Alpha cannot be 0 or negative')
return a
|
def check_alpha(a)
|
Check and parse alpha specs as either a single [a] or a list of [a,a,a,...]
| 6.173 | 5.745897 | 1.074332 |
x = asarray(x)
if size(x) == 1:
x = asarray([x])
if x.ndim == 2:
raise Exception("Property: %s must be one-dimensional" % name)
x = x.flatten()
return x
|
def check_1d(x, name)
|
Check and parse a one-dimensional spec as either a single [x] or a list of [x,x,x...]
| 4.341167 | 3.962763 | 1.09549 |
bounds = array(coords).astype('int')
path = Path(bounds)
grid = meshgrid(range(dims[1]), range(dims[0]))
grid_flat = zip(grid[0].ravel(), grid[1].ravel())
mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int')
if z is not None:
if len(dims) < 3:
raise Exception('Dims must have three-dimensions for embedding z-index')
if z >= dims[2]:
raise Exception('Z-index %g exceeds third dimension %g' % (z, dims[2]))
tmp = zeros(dims)
tmp[:, :, z] = mask
mask = tmp
return mask
|
def polygon_to_mask(coords, dims, z=None)
|
Given a list of pairs of points which define a polygon, return a binary
mask covering the interior of the polygon with dimensions dim
| 3.703722 | 3.906754 | 0.948031 |
bounds = array(coords).astype('int')
bmax = bounds.max(0)
bmin = bounds.min(0)
path = Path(bounds)
grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1))
grid_flat = zip(grid[0].ravel(), grid[1].ravel())
points = path.contains_points(grid_flat).reshape(grid[0].shape).astype('int')
points = where(points)
points = (vstack([points[0], points[1]]).T + bmin[-1::-1]).tolist()
if z is not None:
points = map(lambda p: [p[0], p[1], z], points)
return points
|
def polygon_to_points(coords, z=None)
|
Given a list of pairs of points which define a polygon,
return a list of points interior to the polygon
| 2.792841 | 2.947939 | 0.947388 |
if filename is None:
raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").')
import os
base = self._html
js = self.load_embed()
if os.path.exists(filename):
if overwrite is False:
raise ValueError("File '%s' exists. To ovewrite call save_html with overwrite=True."
% os.path.abspath(filename))
else:
os.remove(filename)
with open(filename, "wb") as f:
f.write(base.encode('utf-8'))
f.write('<script>' + js.encode('utf-8') + '</script>')
|
def save_html(self, filename=None, overwrite=False)
|
Save self-contained html to a file.
Parameters
----------
filename : str
The filename to save to
| 3.132999 | 3.440988 | 0.910494 |
context = {
'request_path': request.path,
}
return http.HttpResponseTemporaryUnavailable(
render_to_string(template_name, context))
|
def temporary_unavailable(request, template_name='503.html')
|
Default 503 handler, which looks for the requested URL in the
redirects table, redirects if found, and displays 404 page if not
redirected.
Templates: ``503.html``
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
| 3.888456 | 5.263623 | 0.738741 |
def key(s):
return (s.version, 1 if s.operator in ['>=', '<'] else 2)
def in_bounds(v, lo, hi):
if lo and v not in lo:
return False
if hi and v not in hi:
return False
return True
def err(reason='inconsistent'):
return ValueError('{} specifier set {}'.format(reason, spec))
gt = None
lt = None
eq = None
ne = []
for i in spec:
if i.operator == '==':
if eq is None:
eq = i
elif eq != i: # pragma: no branch
raise err()
elif i.operator == '!=':
ne.append(i)
elif i.operator in ['>', '>=']:
gt = i if gt is None else max(gt, i, key=key)
elif i.operator in ['<', '<=']:
lt = i if lt is None else min(lt, i, key=key)
else:
raise err('invalid')
ne = [i for i in ne if in_bounds(i.version, gt, lt)]
if eq:
if ( any(i.version in eq for i in ne) or
not in_bounds(eq.version, gt, lt)):
raise err()
return SpecifierSet(str(eq))
if lt and gt:
if lt.version not in gt or gt.version not in lt:
raise err()
if ( gt.version == lt.version and gt.operator == '>=' and
lt.operator == '<='):
return SpecifierSet('=={}'.format(gt.version))
return SpecifierSet(
','.join(str(i) for i in chain(iterate(gt), iterate(lt), ne))
)
|
def simplify_specifiers(spec)
|
Try to simplify a SpecifierSet by combining redundant specifiers.
| 2.907666 | 2.79854 | 1.038994 |
self.lineno = self.lineno if lineno is None else lineno
self.type_ = self.type_ if type_ is None else type_
self.offset = self.offset if offset is None else offset
self.callable = True
self.params = SymbolPARAMLIST()
self.body = SymbolBLOCK()
self.__kind = KIND.unknown
self.local_symbol_table = None
|
def reset(self, lineno=None, offset=None, type_=None)
|
This is called when we need to reinitialize the instance state
| 4.644276 | 4.504463 | 1.031039 |
entry = global_.SYMBOL_TABLE.declare_func(func_name, lineno, type_=type_)
if entry is None:
return None
entry.declared = True
return cls(entry, lineno)
|
def make_node(cls, func_name, lineno, type_=None)
|
This will return a node with the symbol as a function.
| 7.902792 | 7.662048 | 1.03142 |
''' Checks the function types
'''
args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args)
kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs}
def decorate(func):
types = args
kwtypes = kwargs
gi = "Got <{}> instead"
errmsg1 = "to be of type <{}>. " + gi
errmsg2 = "to be one of type ({}). " + gi
errar = "{}:{} expected '{}' "
errkw = "{}:{} expected {} "
def check(*ar, **kw):
line = inspect.getouterframes(inspect.currentframe())[1][2]
fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1])
for arg, type_ in zip(ar, types):
if type(arg) not in type_:
if len(type_) == 1:
raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__,
type(arg).__name__))
else:
raise TypeError((errar + errmsg2).format(fname, line, arg,
', '.join('<%s>' % x.__name__ for x in type_),
type(arg).__name__))
for kwarg in kw:
if kwtypes.get(kwarg, None) is None:
continue
if type(kw[kwarg]) not in kwtypes[kwarg]:
if len(kwtypes[kwarg]) == 1:
raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__,
type(kw[kwarg]).__name__))
else:
raise TypeError((errkw + errmsg2).format(
fname,
line,
kwarg,
', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]),
type(kw[kwarg]).__name__)
)
return func(*ar, **kw)
return check
return decorate
|
def check_type(*args, **kwargs)
|
Checks the function types
| 2.454309 | 2.431175 | 1.009516 |
if self.STRING_LABELS.get(str_, None) is None:
self.STRING_LABELS[str_] = backend.tmp_label()
return self.STRING_LABELS[str_]
|
def add_string_label(self, str_)
|
Maps ("folds") the given string, returning an unique label ID.
This allows several constant labels to be initialized to the same address
thus saving memory space.
:param str_: the string to map
:return: the unique label ID
| 4.113895 | 4.434441 | 0.927715 |
if isinstance(type_, symbols.TYPE):
return type_
assert TYPE.is_valid(type_)
return gl.SYMBOL_TABLE.basic_types[type_]
|
def TYPE(type_)
|
Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done.
| 12.278584 | 9.401475 | 1.306027 |
quad = Quad(*args)
__DEBUG__('EMIT ' + str(quad))
MEMORY.append(quad)
|
def emit(*args)
|
Convert the given args to a Quad (3 address code) instruction
| 21.139194 | 14.325183 | 1.475667 |
if not self.HAS_ATTR:
return
self.HAS_ATTR = False
self.emit('call', 'COPY_ATTR', 0)
backend.REQUIRES.add('copy_attr.asm')
|
def norm_attr(self)
|
Normalize attr state
| 16.111429 | 15.427781 | 1.044313 |
if node.token == 'NUMBER':
return node.t
if node.token == 'UNARY':
mid = node.operator
if mid == 'MINUS':
result = ' -' + Translator.traverse_const(node.operand)
elif mid == 'ADDRESS':
if node.operand.scope == SCOPE.global_ or node.operand.token in ('LABEL', 'FUNCTION'):
result = Translator.traverse_const(node.operand)
else:
syntax_error_not_constant(node.operand.lineno)
return
else:
raise InvalidOperatorError(mid)
return result
if node.token == 'BINARY':
mid = node.operator
if mid == 'PLUS':
mid = '+'
elif mid == 'MINUS':
mid = '-'
elif mid == 'MUL':
mid = '*'
elif mid == 'DIV':
mid = '/'
elif mid == 'MOD':
mid = '%'
elif mid == 'POW':
mid = '^'
elif mid == 'SHL':
mid = '>>'
elif mid == 'SHR':
mid = '<<'
else:
raise InvalidOperatorError(mid)
return '(%s) %s (%s)' % (Translator.traverse_const(node.left), mid, Translator.traverse_const(node.right))
if node.token == 'TYPECAST':
if node.type_ in (Type.byte_, Type.ubyte):
return '(' + Translator.traverse_const(node.operand) + ') & 0xFF'
if node.type_ in (Type.integer, Type.uinteger):
return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFF'
if node.type_ in (Type.long_, Type.ulong):
return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFFFFFF'
if node.type_ == Type.fixed:
return '((' + Translator.traverse_const(node.operand) + ') & 0xFFFF) << 16'
syntax_error_cant_convert_to_type(node.lineno, str(node.operand), node.type_)
return
if node.token in ('VAR', 'VARARRAY', 'LABEL', 'FUNCTION'):
# TODO: Check what happens with local vars and params
return node.t
if node.token == 'CONST':
return Translator.traverse_const(node.expr)
if node.token == 'ARRAYACCESS':
return '({} + {})'.format(node.entry.mangled, node.offset)
raise InvalidCONSTexpr(node)
|
def traverse_const(node)
|
Traverses a constant and returns an string
with the arithmetic expression
| 2.757532 | 2.706004 | 1.019042 |
if len(node.children) > n:
return node.children[n]
|
def check_attr(node, n)
|
Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
| 5.035376 | 6.233776 | 0.807757 |
p = '*' if var.byref else '' # Indirection prefix
if self.O_LEVEL > 1 and not var.accessed:
return
if not var.type_.is_basic:
raise NotImplementedError()
if var.scope == SCOPE.global_:
self.emit('store' + self.TSUFFIX(var.type_), var.mangled, t)
elif var.scope == SCOPE.parameter:
self.emit('pstore' + self.TSUFFIX(var.type_), p + str(var.offset), t)
elif var.scope == SCOPE.local:
if var.alias is not None and var.alias.class_ == CLASS.array:
var.offset -= 1 + 2 * var.alias.count
self.emit('pstore' + self.TSUFFIX(var.type_), p + str(-var.offset), t)
|
def emit_var_assign(self, var, t)
|
Emits code for storing a value into a variable
:param var: variable (node) to be updated
:param t: the value to emmit (e.g. a _label, a const, a tN...)
| 5.219869 | 5.140067 | 1.015526 |
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][1]
raise InvalidLoopError(loop_type)
|
def loop_exit_label(self, loop_type)
|
Returns the label for the given loop type which
exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
| 2.663501 | 2.729361 | 0.97587 |
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][2]
raise InvalidLoopError(loop_type)
|
def loop_cont_label(self, loop_type)
|
Returns the label for the given loop type which
continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
| 2.826164 | 2.847243 | 0.992597 |
syntax_error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name))
return ['<ERROR>']
val = Translator.traverse_const(expr)
if type_.size == 1: # U/byte
if expr.type_.size != 1:
return ['#({0}) & 0xFF'.format(val)]
else:
return ['#{0}'.format(val)]
if type_.size == 2: # U/integer
if expr.type_.size != 2:
return ['##({0}) & 0xFFFF'.format(val)]
else:
return ['##{0}'.format(val)]
if type_ == cls.TYPE(TYPE.fixed):
return ['0000', '##({0}) & 0xFFFF'.format(val)]
# U/Long
return ['##({0}) & 0xFFFF'.format(val), '##(({0}) >> 16) & 0xFFFF'.format(val)]
if type_ == cls.TYPE(TYPE.float_):
C, DE, HL = _float(expr.value)
C = C[:-1] # Remove 'h' suffix
if len(C) > 2:
C = C[-2:]
DE = DE[:-1] # Remove 'h' suffix
if len(DE) > 4:
DE = DE[-4:]
elif len(DE) < 3:
DE = '00' + DE
HL = HL[:-1] # Remove 'h' suffix
if len(HL) > 4:
HL = HL[-4:]
elif len(HL) < 3:
HL = '00' + HL
return [C, DE[-2:], DE[:-2], HL[-2:], HL[:-2]]
if type_ == cls.TYPE(TYPE.fixed):
value = 0xFFFFFFFF & int(expr.value * 2 ** 16)
else:
value = int(expr.value)
result = [value, value >> 8, value >> 16, value >> 24]
result = ['%02X' % (v & 0xFF) for v in result]
return result[:type_.size]
|
def default_value(cls, type_, expr): # TODO: This function must be moved to api.xx
assert isinstance(type_, symbols.TYPE)
assert type_.is_basic
assert check.is_static(expr)
if isinstance(expr, (symbols.CONST, symbols.VAR)): # a constant expression like @label + 1
if type_ in (cls.TYPE(TYPE.float_), cls.TYPE(TYPE.string))
|
Returns a list of bytes (as hexadecimal 2 char string)
| 3.035423 | 2.955439 | 1.027063 |
if not isinstance(values, list):
return Translator.default_value(type_, values)
l = []
for row in values:
l.extend(Translator.array_default_value(type_, row))
return l
|
def array_default_value(type_, values)
|
Returns a list of bytes (as hexadecimal 2 char string)
which represents the array initial value.
| 3.882859 | 3.839931 | 1.011179 |
if not hasattr(i, 'type_'):
return False
if i.type_ != Type.string:
return False
if i.token in ('VAR', 'PARAMDECL'):
return True # We don't know what an alphanumeric variable will hold
if i.token == 'STRING':
for c in i.value:
if 15 < ord(c) < 22: # is it an attr char?
return True
return False
for j in i.children:
if Translator.has_control_chars(j):
return True
return False
|
def has_control_chars(i)
|
Returns true if the passed token is an unknown string
or a constant string having control chars (inverse, etc
| 6.172932 | 6.098588 | 1.01219 |
self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t)
self.emit('call', 'USR', node.type_.size)
backend.REQUIRES.add('usr.asm')
|
def visit_USR(self, node)
|
Machine code call from basic
| 29.461655 | 28.5732 | 1.031094 |
if not isinstance(other, Symbol):
return # Nothing done if not a Symbol object
tmp = re.compile('__.*__')
for attr in (x for x in dir(other) if not tmp.match(x)):
if (
hasattr(self.__class__, attr) and
str(type(getattr(self.__class__, attr)) in ('property', 'function', 'instancemethod'))
):
continue
val = getattr(other, attr)
if isinstance(val, str) or str(val)[0] != '<': # Not a value
setattr(self, attr, val)
|
def copy_attr(self, other)
|
Copies all other attributes (not methods)
from the other object to this instance.
| 4.723786 | 4.561047 | 1.03568 |
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use owns program fname
fname = sys.argv[0]
if self.defined(id_):
i = self.table[id_]
warning(lineno, '"%s" redefined (previous definition at %s:%i)' %
(i.name, i.fname, i.lineno))
self.set(id_, lineno, value, fname, args)
|
def define(self, id_, lineno, value='', fname=None, args=None)
|
Defines the value of a macro.
Issues a warning if the macro is already defined.
| 5.360931 | 5.297187 | 1.012033 |
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use owns program fname
fname = sys.argv[0]
self.table[id_] = ID(id_, args, value, lineno, fname)
|
def set(self, id_, lineno, value='', fname=None, args=None)
|
Like the above, but issues no warning on duplicate macro
definitions.
| 7.853394 | 8.200533 | 0.957669 |
if is_int(op1):
if swap:
return op2, int(op1)
else:
return int(op1), op2
if is_int(op2):
return op1, int(op2)
return None
|
def _int_ops(op1, op2, swap=True)
|
Receives a list with two strings (operands).
If none of them contains integers, returns None.
Otherwise, returns a t-uple with (op[0], op[1]),
where op[1] is the integer one (the list is swapped)
unless swap is False (e.g. sub and div used this
because they're not commutative).
The integer operand is always converted to int type.
| 2.44322 | 2.342931 | 1.042805 |
if is_float(op1):
if swap:
return op2, float(op1)
else:
return float(op1), op2
if is_float(op2):
return op1, float(op2)
return None
|
def _f_ops(op1, op2, swap=True)
|
Receives a list with two strings (operands).
If none of them contains integers, returns None.
Otherwise, returns a t-uple with (op[0], op[1]),
where op[1] is the integer one (the list is swapped)
unless swap is False (e.g. sub and div used this
because they're not commutative).
The integer operand is always converted to int type.
| 2.638116 | 2.666523 | 0.989347 |
assert isinstance(params, SymbolARGLIST)
entry = gl.SYMBOL_TABLE.access_func(id_, lineno)
if entry is None: # A syntax / semantic error
return None
if entry.callable is False: # Is it NOT callable?
if entry.type_ != Type.string:
errmsg.syntax_error_not_array_nor_func(lineno, id_)
return None
gl.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno)
entry.accessed = True
if entry.declared and not entry.forwarded:
check_call_arguments(lineno, id_, params)
else: # All functions goes to global scope by default
if not isinstance(entry, SymbolFUNCTION):
entry = SymbolVAR.to_function(entry, lineno)
gl.SYMBOL_TABLE.move_to_global_scope(id_)
gl.FUNCTION_CALLS.append((id_, params, lineno,))
return cls(entry, params, lineno)
|
def make_node(cls, id_, params, lineno)
|
This will return an AST node for a function/procedure call.
| 9.014995 | 8.578177 | 1.050922 |
''' This will return a node with a param_list
(declared in a function declaration)
Parameters:
-node: A SymbolPARAMLIST instance or None
-params: SymbolPARAMDECL insances
'''
if node is None:
node = clss()
if node.token != 'PARAMLIST':
return clss.make_node(None, node, *params)
for i in params:
if i is not None:
node.appendChild(i)
return node
|
def make_node(clss, node, *params)
|
This will return a node with a param_list
(declared in a function declaration)
Parameters:
-node: A SymbolPARAMLIST instance or None
-params: SymbolPARAMDECL insances
| 10.005521 | 2.742689 | 3.64807 |
''' Overrides base class.
'''
Symbol.appendChild(self, param)
if param.offset is None:
param.offset = self.size
self.size += param.size
|
def appendChild(self, param)
|
Overrides base class.
| 6.823351 | 5.979255 | 1.141171 |
if left is None or right is None:
return None
a, b = left, right # short form names
# Check for constant non-numeric operations
c_type = common_type(a, b) # Resulting operation type or None
if c_type: # there must be a common type for a and b
if is_numeric(a, b) and (is_const(a) or is_number(a)) and \
(is_const(b) or is_number(b)):
if func is not None:
a = SymbolTYPECAST.make_node(c_type, a, lineno) # ensure type
b = SymbolTYPECAST.make_node(c_type, b, lineno) # ensure type
return SymbolNUMBER(func(a.value, b.value), type_=type_, lineno=lineno)
if is_static(a, b):
a = SymbolTYPECAST.make_node(c_type, a, lineno) # ensure type
b = SymbolTYPECAST.make_node(c_type, b, lineno) # ensure type
return SymbolCONST(cls(operator, a, b, lineno, type_=type_, func=func), lineno=lineno)
if operator in ('BNOT', 'BAND', 'BOR', 'BXOR', 'NOT', 'AND', 'OR',
'XOR', 'MINUS', 'MULT', 'DIV', 'SHL', 'SHR') and \
not is_numeric(a, b):
syntax_error(lineno, 'Operator %s cannot be used with STRINGS' % operator)
return None
if is_string(a, b) and func is not None: # Are they STRING Constants?
if operator == 'PLUS':
return SymbolSTRING(func(a.value, b.value), lineno)
return SymbolNUMBER(int(func(a.text, b.text)), type_=TYPE.ubyte,
lineno=lineno) # Convert to u8 (boolean)
if operator in ('BNOT', 'BAND', 'BOR', 'BXOR'):
if TYPE.is_decimal(c_type):
c_type = TYPE.long_
if a.type_ != b.type_ and TYPE.string in (a.type_, b.type_):
c_type = a.type_ # Will give an error based on the fist operand
if operator not in ('SHR', 'SHL'):
a = SymbolTYPECAST.make_node(c_type, a, lineno)
b = SymbolTYPECAST.make_node(c_type, b, lineno)
if a is None or b is None:
return None
if type_ is None:
if operator in ('LT', 'GT', 'EQ', 'LE', 'GE', 'NE', 'AND', 'OR',
'XOR', 'NOT'):
type_ = TYPE.ubyte # Boolean type
else:
type_ = c_type
return cls(operator, a, b, type_=type_, lineno=lineno)
|
def make_node(cls, operator, left, right, lineno, func=None,
type_=None)
|
Creates a binary node for a binary operation,
e.g. A + 6 => '+' (A, 6) in prefix notation.
Parameters:
-operator: the binary operation token. e.g. 'PLUS' for A + 6
-left: left operand
-right: right operand
-func: is a lambda function used when constant folding is applied
-type_: resulting type (to enforce it).
If no type_ is specified the resulting one will be guessed.
| 3.390134 | 3.331727 | 1.01753 |
if self is not self.final:
return self.final.is_dynamic
return any([x.is_dynamic for x in self.children])
|
def is_dynamic(self)
|
True if this type uses dynamic (Heap) memory.
e.g. strings or dynamic arrays
| 7.342703 | 7.384294 | 0.994368 |
assert isinstance(t, SymbolTYPE)
t = t.final
assert t.is_basic
if cls.is_unsigned(t):
return {cls.ubyte: cls.byte_,
cls.uinteger: cls.integer,
cls.ulong: cls.long_}[t]
if cls.is_signed(t) or cls.is_decimal(t):
return t
return cls.unknown
|
def to_signed(cls, t)
|
Return signed type or equivalent
| 5.583557 | 5.313506 | 1.050824 |
if id_[-1] in DEPRECATED_SUFFIXES:
id_ = id_[:-1] # Remove it
if scope is not None:
assert len(self.table) > scope
return self[scope][id_]
for sc in self:
if sc[id_] is not None:
return sc[id_]
return None
|
def get_entry(self, id_, scope=None)
|
Returns the ID entry stored in self.table, starting
by the first one. Returns None if not found.
If scope is not None, only the given scope is searched.
| 5.472394 | 4.825232 | 1.13412 |
id2 = id_
type_ = entry.type_
if id2[-1] in DEPRECATED_SUFFIXES:
id2 = id2[:-1] # Remove it
type_ = symbols.TYPEREF(self.basic_types[SUFFIX_TYPE[id_[-1]]], lineno) # Overrides type_
if entry.type_ is not None and not entry.type_.implicit and type_ != entry.type_:
syntax_error(lineno, "expected type {2} for '{0}', got {1}".format(id_, entry.type_.name, type_.name))
# Checks if already declared
if self[self.current_scope][id2] is not None:
return None
entry.caseins = OPTIONS.case_insensitive.value
self[self.current_scope][id2] = entry
entry.name = id2 # Removes DEPRECATED SUFFIXES if any
if isinstance(entry, symbols.TYPE):
return entry # If it's a type declaration, we're done
# HINT: The following should be done by the respective callers!
# entry.callable = None # True if function, strings or arrays
# entry.class_ = None # TODO: important
entry.forwarded = False # True for a function header
entry.mangled = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, entry.name) # Mangled name
entry.type_ = type_ # type_ now reflects entry sigil (i.e. a$ => 'string' type) if any
entry.scopeRef = self[self.current_scope]
return entry
|
def declare(self, id_, lineno, entry)
|
Check there is no 'id' already declared in the current scope, and
creates and returns it. Otherwise, returns None,
and the caller function raises the syntax/semantic error.
Parameter entry is the SymbolVAR, SymbolVARARRAY, etc. instance
The entry 'declared' field is leave untouched. Setting it if on
behalf of the caller.
| 8.27202 | 7.855386 | 1.053038 |
result = self.get_entry(id_, scope)
if isinstance(result, symbols.TYPE):
return True
if result is None or not result.declared:
if show_error:
syntax_error(lineno, 'Undeclared %s "%s"' % (classname, id_))
return False
return True
|
def check_is_declared(self, id_, lineno, classname='identifier',
scope=None, show_error=True)
|
Checks if the given id is already defined in any scope
or raises a Syntax Error.
Note: classname is not the class attribute, but the name of
the class as it would appear on compiler messages.
| 4.078042 | 4.328437 | 0.942151 |
result = self.get_entry(id_, scope)
if result is None or not result.declared:
return True
if scope is None:
scope = self.current_scope
if show_error:
syntax_error(lineno,
'Duplicated %s "%s" (previous one at %s:%i)' %
(classname, id_, self.table[scope][id_].filename,
self.table[scope][id_].lineno))
return False
|
def check_is_undeclared(self, id_, lineno, classname='identifier',
scope=None, show_error=False)
|
The reverse of the above.
Check the given identifier is not already declared. Returns True
if OK, False otherwise.
| 3.777091 | 3.56519 | 1.059436 |
assert CLASS.is_valid(class_)
entry = self.get_entry(id_, scope)
if entry is None or entry.class_ == CLASS.unknown: # Undeclared yet
return True
if entry.class_ != class_:
if show_error:
if entry.class_ == CLASS.array:
a1 = 'n'
else:
a1 = ''
if class_ == CLASS.array:
a2 = 'n'
else:
a2 = ''
syntax_error(lineno, "identifier '%s' is a%s %s, not a%s %s" %
(id_, a1, entry.class_, a2, class_))
return False
return True
|
def check_class(self, id_, class_, lineno, scope=None, show_error=True)
|
Check the id is either undefined or defined with
the given class.
- If the identifier (e.g. variable) does not exists means
it's undeclared, and returns True (OK).
- If the identifier exists, but its class_ attribute is
unknown yet (None), returns also True. This means the
identifier has been referenced in advanced and it's undeclared.
Otherwise fails returning False.
| 3.337528 | 3.230715 | 1.033062 |
old_mangle = self.mangle
self.mangle = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, funcname)
self.table.append(SymbolTable.Scope(self.mangle, parent_mangle=old_mangle))
global_.META_LOOPS.append(global_.LOOPS) # saves current LOOPS state
global_.LOOPS = []
|
def enter_scope(self, funcname)
|
Starts a new variable scope.
Notice the *IMPORTANT* marked lines. This is how a new scope is added,
by pushing a new dict at the end (and popped out later).
| 6.161984 | 6.809991 | 0.904845 |
def entry_size(entry):
if entry.scope == SCOPE.global_ or \
entry.is_aliased: # aliases or global variables = 0
return 0
if entry.class_ != CLASS.array:
return entry.size
return entry.memsize
for v in self.table[self.current_scope].values(filter_by_opt=False):
if not v.accessed:
if v.scope == SCOPE.parameter:
kind = 'Parameter'
v.accessed = True # HINT: Parameters must always be present even if not used!
warning_not_used(v.lineno, v.name, kind=kind)
entries = sorted(self.table[self.current_scope].values(filter_by_opt=True), key=entry_size)
offset = 0
for entry in entries: # Symbols of the current level
if entry.class_ is CLASS.unknown:
self.move_to_global_scope(entry.name)
if entry.class_ in (CLASS.function, CLASS.label, CLASS.type_):
continue
# Local variables offset
if entry.class_ == CLASS.var and entry.scope == SCOPE.local:
if entry.alias is not None: # alias of another variable?
if entry.offset is None:
entry.offset = entry.alias.offset
else:
entry.offset = entry.alias.offset - entry.offset
else:
offset += entry_size(entry)
entry.offset = offset
if entry.class_ == CLASS.array and entry.scope == SCOPE.local:
entry.offset = entry_size(entry) + offset
offset = entry.offset
self.mangle = self[self.current_scope].parent_mangle
self.table.pop()
global_.LOOPS = global_.META_LOOPS.pop()
return offset
|
def leave_scope(self)
|
Ends a function body and pops current scope out of the symbol table.
| 5.127971 | 5.021833 | 1.021135 |
# In the current scope and more than 1 scope?
if id_ in self.table[self.current_scope].keys(filter_by_opt=False) and len(self.table) > 1:
symbol = self.table[self.current_scope][id_]
symbol.offset = None
symbol.scope = SCOPE.global_
if symbol.class_ != CLASS.label:
symbol.mangled = "%s%s%s" % (self.table[self.global_scope].mangle, global_.MANGLE_CHR, id_)
self.table[self.global_scope][id_] = symbol
del self.table[self.current_scope][id_] # Removes it from the current scope
__DEBUG__("'{}' entry moved to global scope".format(id_))
|
def move_to_global_scope(self, id_)
|
If the given id is in the current scope, and there is more than
1 scope, move the current id to the global scope and make it global.
Labels need this.
| 5.932011 | 4.932583 | 1.202618 |
entry = self.table[self.current_scope][id_]
entry.scope = SCOPE.global_
self.table[self.global_scope][entry.mangled] = entry
|
def make_static(self, id_)
|
The given ID in the current scope is changed to 'global', but the
variable remains in the current scope, if it's a 'global private'
variable: A variable private to a function scope, but whose contents
are not in the stack, not in the global variable area.
These are called 'static variables' in C.
A copy of the instance, but mangled, is also allocated in the global
symbol table.
| 8.880704 | 6.297133 | 1.410277 |
if isinstance(default_type, symbols.BASICTYPE):
default_type = symbols.TYPEREF(default_type, lineno, implicit=False)
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
if not check_is_declared_explicit(lineno, id_):
return None
result = self.get_entry(id_, scope)
if result is None:
if default_type is None:
default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_IMPLICIT_TYPE],
lineno, implicit=True)
result = self.declare_variable(id_, lineno, default_type)
result.declared = False # It was implicitly declared
result.class_ = default_class
return result
# The entry was already declared. If it's type is auto and the default type is not None,
# update its type.
if default_type is not None and result.type_ == self.basic_types[TYPE.auto]:
result.type_ = default_type
warning_implicit_type(lineno, id_, default_type)
return result
|
def access_id(self, id_, lineno, scope=None, default_type=None, default_class=CLASS.unknown)
|
Access a symbol by its identifier and checks if it exists.
If not, it's supposed to be an implicit declared variable.
default_class is the class to use in case of an undeclared-implicit-accessed id
| 4.532135 | 4.252384 | 1.065787 |
result = self.access_id(id_, lineno, scope, default_type)
if result is None:
return None
if not self.check_class(id_, CLASS.var, lineno, scope):
return None
assert isinstance(result, symbols.VAR)
result.class_ = CLASS.var
return result
|
def access_var(self, id_, lineno, scope=None, default_type=None)
|
Since ZX BASIC allows access to undeclared variables, we must allow
them, and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry so.
Otherwise, creates an implicit declared variable entry and returns it.
If the --strict command line flag is enabled (or #pragma option explicit
is in use) checks ensures the id_ is already declared.
Returns None on error.
| 5.093828 | 5.403093 | 0.942761 |
if not self.check_is_declared(id_, lineno, 'array', scope):
return None
if not self.check_class(id_, CLASS.array, lineno, scope):
return None
return self.access_id(id_, lineno, scope=scope, default_type=default_type)
|
def access_array(self, id_, lineno, scope=None, default_type=None)
|
Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array.
| 4.014217 | 3.617508 | 1.109664 |
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
result = self.get_entry(id_, scope)
if result is None:
if default_type is None:
if global_.DEFAULT_IMPLICIT_TYPE == TYPE.auto:
default_type = symbols.TYPEREF(self.basic_types[TYPE.auto], lineno, implicit=True)
else:
default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_TYPE], lineno, implicit=True)
return self.declare_func(id_, lineno, default_type)
if not self.check_class(id_, CLASS.function, lineno, scope):
return None
return result
|
def access_func(self, id_, lineno, scope=None, default_type=None)
|
Since ZX BASIC allows access to undeclared functions, we must allow
and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry if so.
Otherwise, creates an implicit declared variable entry and returns it.
| 4.188663 | 3.971503 | 1.05468 |
entry = self.access_id(id_, lineno, scope, default_type=type_)
if entry is None:
return self.access_func(id_, lineno)
if entry.callable is False: # Is it NOT callable?
if entry.type_ != self.basic_types[TYPE.string]:
syntax_error_not_array_nor_func(lineno, id_)
return None
else: # Ok, it is a string slice if it has 0 or 1 parameters
return entry
if entry.callable is None and entry.type_ == self.basic_types[TYPE.string]:
# Ok, it is a string slice if it has 0 or 1 parameters
entry.callable = False
return entry
# Mangled name (functions always has _name as mangled)
# entry.mangled = '_%s' % entry.name
# entry.callable = True # HINT: must be true already
return entry
|
def access_call(self, id_, lineno, scope=None, type_=None)
|
Creates a func/array/string call. Checks if id is callable or not.
An identifier is "callable" if it can be followed by a list of para-
meters.
This does not mean the id_ is a function, but that it allows the same
syntax a function does:
For example:
- MyFunction(a, "hello", 5) is a Function so MyFuncion is callable
- MyArray(5, 3.7, VAL("32")) makes MyArray identifier "callable".
- MyString(5 TO 7) or MyString(5) is a "callable" string.
| 6.100744 | 6.061376 | 1.006495 |
assert isinstance(type_, symbols.TYPEREF)
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
"Variable '%s' already declared as a parameter "
"at %s:%i" % (id_, entry.filename, entry.lineno))
else:
syntax_error(lineno, "Variable '%s' already declared at "
"%s:%i" % (id_, entry.filename, entry.lineno))
return None
if not self.check_class(id_, CLASS.var, lineno, scope=self.current_scope):
return None
entry = (self.get_entry(id_, scope=self.current_scope) or
self.declare(id_, lineno, symbols.VAR(id_, lineno, class_=CLASS.var)))
__DEBUG__("Entry %s declared with class %s at scope %i" % (entry.name, CLASS.to_string(entry.class_),
self.current_scope))
if entry.type_ is None or entry.type_ == self.basic_types[TYPE.unknown]:
entry.type_ = type_
if entry.type_ != type_:
if not type_.implicit and entry.type_ is not None:
syntax_error(lineno,
"'%s' suffix is for type '%s' but it was "
"declared as '%s'" %
(id_, entry.type_, type_))
return None
# type_ = entry.type_ # TODO: Unused??
entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local
entry.callable = False
entry.class_ = CLASS.var # HINT: class_ attribute could be erased if access_id was used.
entry.declared = True # marks it as declared
if entry.type_.implicit and entry.type_ != self.basic_types[TYPE.unknown]:
warning_implicit_type(lineno, id_, entry.type_.name)
if default_value is not None and entry.type_ != default_value.type_:
if is_number(default_value):
default_value = symbols.TYPECAST.make_node(entry.type_, default_value,
lineno)
if default_value is None:
return None
else:
syntax_error(lineno,
"Variable '%s' declared as '%s' but initialized "
"with a '%s' value" %
(id_, entry.type_, default_value.type_))
return None
entry.default_value = default_value
return entry
|
def declare_variable(self, id_, lineno, type_, default_value=None)
|
Like the above, but checks that entry.declared is False.
Otherwise raises an error.
Parameter default_value specifies an initialized variable, if set.
| 3.659601 | 3.59163 | 1.018925 |
assert isinstance(type_, symbols.TYPE)
# Checks it's not a basic type
if not type_.is_basic and type_.name.lower() in TYPE.TYPE_NAMES.values():
syntax_error(type_.lineno, "'%s' is a basic type and cannot be redefined" %
type_.name)
return None
if not self.check_is_undeclared(type_.name, type_.lineno, scope=self.current_scope, show_error=True):
return None
entry = self.declare(type_.name, type_.lineno, type_)
return entry
|
def declare_type(self, type_)
|
Declares a type.
Checks its name is not already used in the current scope,
and that it's not a basic type.
Returns the given type_ Symbol, or None on error.
| 5.71261 | 4.768314 | 1.198036 |
if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
entry = self.get_entry(id_)
if entry.scope == SCOPE.parameter:
syntax_error(lineno,
"Constant '%s' already declared as a parameter "
"at %s:%i" % (id_, entry.filename, entry.lineno))
else:
syntax_error(lineno, "Constant '%s' already declared at "
"%s:%i" % (id_, entry.filename, entry.lineno))
return None
entry = self.declare_variable(id_, lineno, type_, default_value)
if entry is None:
return None
entry.class_ = CLASS.const
return entry
|
def declare_const(self, id_, lineno, type_, default_value)
|
Similar to the above. But declares a Constant.
| 3.29257 | 3.178233 | 1.035975 |
# TODO: consider to make labels private
id1 = id_
id_ = str(id_)
if not self.check_is_undeclared(id_, lineno, 'label'):
entry = self.get_entry(id_)
syntax_error(lineno, "Label '%s' already used at %s:%i" %
(id_, entry.filename, entry.lineno))
return entry
entry = self.get_entry(id_)
if entry is not None and entry.declared:
if entry.is_line_number:
syntax_error(lineno, "Duplicated line number '%s'. "
"Previous was at %i" % (entry.name, entry.lineno))
else:
syntax_error(lineno, "Label '%s' already declared at line %i" %
(id_, entry.lineno))
return None
entry = (self.get_entry(id_, scope=self.current_scope) or
self.get_entry(id_, scope=self.global_scope) or
self.declare(id_, lineno, symbols.LABEL(id_, lineno)))
if entry is None:
return None
if not isinstance(entry, symbols.LABEL):
entry = symbols.VAR.to_label(entry)
if id_[0] == '.':
id_ = id_[1:]
# HINT: ??? Mangled name. Just the label, 'cause it starts with '.'
entry.mangled = '%s' % id_
else:
# HINT: Mangled name. Labels are __LABEL__
entry.mangled = '__LABEL__%s' % entry.name
entry.is_line_number = isinstance(id1, int)
if global_.FUNCTION_LEVEL:
entry.scope_owner = list(global_.FUNCTION_LEVEL)
self.move_to_global_scope(id_) # Labels are always global # TODO: not in the future
entry.declared = True
entry.type_ = self.basic_types[global_.PTR_TYPE]
return entry
|
def declare_label(self, id_, lineno)
|
Declares a label (line numbers are also labels).
Unlike variables, labels are always global.
| 5.133323 | 4.993732 | 1.027953 |
if not self.check_is_undeclared(id_, lineno, classname='parameter',
scope=self.current_scope, show_error=True):
return None
entry = self.declare(id_, lineno, symbols.PARAMDECL(id_, lineno, type_))
if entry is None:
return
entry.declared = True
if entry.type_.implicit:
warning_implicit_type(lineno, id_, type_)
return entry
|
def declare_param(self, id_, lineno, type_=None)
|
Declares a parameter
Check if entry.declared is False. Otherwise raises an error.
| 7.570578 | 6.117818 | 1.237464 |
assert isinstance(type_, symbols.TYPEREF)
assert isinstance(bounds, symbols.BOUNDLIST)
if not self.check_class(id_, CLASS.array, lineno, scope=self.current_scope):
return None
entry = self.get_entry(id_, self.current_scope)
if entry is None:
entry = self.declare(id_, lineno, symbols.VARARRAY(id_, bounds, lineno, type_=type_))
if not entry.declared:
if entry.callable:
syntax_error(lineno,
"Array '%s' must be declared before use. "
"First used at line %i" %
(id_, entry.lineno))
return None
else:
if entry.scope == SCOPE.parameter:
syntax_error(lineno, "variable '%s' already declared as a "
"parameter at line %i" % (id_, entry.lineno))
else:
syntax_error(lineno, "variable '%s' already declared at "
"line %i" % (id_, entry.lineno))
return None
if entry.type_ != self.basic_types[TYPE.unknown] and entry.type_ != type_:
if not type_.implicit:
syntax_error(lineno, "Array suffix for '%s' is for type '%s' "
"but declared as '%s'" %
(entry.name, entry.type_, type_))
return None
type_.implicit = False
type_ = entry.type_
if type_.implicit:
warning_implicit_type(lineno, id_, type_)
if not isinstance(entry, symbols.VARARRAY):
entry = symbols.VAR.to_vararray(entry, bounds)
entry.declared = True
entry.type_ = type_
entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local
entry.default_value = default_value
entry.callable = True
entry.class_ = CLASS.array
entry.lbound_used = entry.ubound_used = False # Flag to true when LBOUND/UBOUND used somewhere in the code
__DEBUG__('Entry %s declared with class %s at scope %i' % (id_, CLASS.to_string(entry.class_),
self.current_scope))
return entry
|
def declare_array(self, id_, lineno, type_, bounds, default_value=None)
|
Declares an array in the symbol table (VARARRAY). Error if already
exists.
| 4.089668 | 3.911434 | 1.045567 |
if not self.check_class(id_, 'function', lineno):
entry = self.get_entry(id_) # Must not exist or have _class = None or Function and declared = False
an = 'an' if entry.class_.lower()[0] in 'aeio' else 'a'
syntax_error(lineno, "'%s' already declared as %s %s at %i" % (id_, an, entry.class_, entry.lineno))
return None
entry = self.get_entry(id_) # Must not exist or have _class = None or Function and declared = False
if entry is not None:
if entry.declared and not entry.forwarded:
syntax_error(lineno, "Duplicate function name '%s', previously defined at %i" % (id_, entry.lineno))
return None
if entry.class_ != CLASS.unknown and entry.callable is False: # HINT: Must use is False here.
syntax_error_not_array_nor_func(lineno, id_)
return None
if id_[-1] in DEPRECATED_SUFFIXES and entry.type_ != self.basic_types[SUFFIX_TYPE[id_[-1]]]:
syntax_error_func_type_mismatch(lineno, entry)
if entry.token == 'VAR': # This was a function used in advance
symbols.VAR.to_function(entry, lineno=lineno)
entry.mangled = '%s_%s' % (self.mangle, entry.name) # HINT: mangle for nexted scopes
else:
entry = self.declare(id_, lineno, symbols.FUNCTION(id_, lineno, type_=type_))
if entry.forwarded:
entry.forwared = False # No longer forwarded
old_type = entry.type_ # Remembers the old type
if entry.type_ is not None:
if entry.type_ != old_type:
syntax_error_func_type_mismatch(lineno, entry)
else:
entry.type_ = old_type
else:
entry.params_size = 0 # Size of parameters
entry.locals_size = 0 # Size of local variables
return entry
|
def declare_func(self, id_, lineno, type_=None)
|
Declares a function in the current scope.
Checks whether the id exist or not (error if exists).
And creates the entry at the symbol table.
| 5.381731 | 5.264685 | 1.022232 |
for entry in self.labels:
self.check_is_declared(entry.name, entry.lineno, CLASS.label)
|
def check_labels(self)
|
Checks if all the labels has been declared
| 15.552096 | 10.244383 | 1.51811 |
for entry in self[scope].values():
if entry.class_ is None:
syntax_error(entry.lineno, "Unknown identifier '%s'" % entry.name)
|
def check_classes(self, scope=-1)
|
Check if pending identifiers are defined or not. If not,
returns a syntax error. If no scope is given, the current
one is checked.
| 7.410211 | 6.043907 | 1.226063 |
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]
|
def vars_(self)
|
Returns symbol instances corresponding to variables
of the current scope.
| 12.54389 | 9.422091 | 1.331328 |
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
|
def labels(self)
|
Returns symbol instances corresponding to labels
in the current scope.
| 15.045202 | 8.435833 | 1.783487 |
return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]
|
def types(self)
|
Returns symbol instances corresponding to type declarations
within the current scope.
| 13.652265 | 7.150766 | 1.909203 |
return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]
|
def arrays(self)
|
Returns symbol instances corresponding to arrays
of the current scope.
| 13.439099 | 7.991371 | 1.681701 |
return [x for x in self[self.current_scope].values() if x.class_ in
(CLASS.function, CLASS.sub)]
|
def functions(self)
|
Returns symbol instances corresponding to functions
of the current scope.
| 14.472766 | 9.435399 | 1.53388 |
return [x for x in self[self.current_scope].values() if x.is_aliased]
|
def aliases(self)
|
Returns symbol instances corresponding to aliased vars.
| 11.038753 | 6.496735 | 1.699123 |
if not isinstance(type_list, list):
type_list = [type_list]
if arg.type_ in type_list:
return True
if len(type_list) == 1:
syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" %
(arg.type_, type_list[0]))
else:
syntax_error(lineno, "Wrong expression type '%s'. Expected one of '%s'"
% (arg.type_, tuple(type_list)))
return False
|
def check_type(lineno, type_list, arg)
|
Check arg's type is one in type_list, otherwise,
raises an error.
| 2.294295 | 2.320087 | 0.988883 |
if not config.OPTIONS.explicit.value:
return True
entry = global_.SYMBOL_TABLE.check_is_declared(id_, lineno, classname)
return entry is not None
|
def check_is_declared_explicit(lineno, id_, classname='variable')
|
Check if the current ID is already declared.
If not, triggers a "undeclared identifier" error,
if the --explicit command line flag is enabled (or #pragma
option strict is in use).
If not in strict mode, passes it silently.
| 11.894952 | 11.919105 | 0.997974 |
if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'):
return False
if not global_.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno):
return False
entry = global_.SYMBOL_TABLE.get_entry(id_)
if len(args) != len(entry.params):
c = 's' if len(entry.params) != 1 else ''
syntax_error(lineno, "Function '%s' takes %i parameter%s, not %i" %
(id_, len(entry.params), c, len(args)))
return False
for arg, param in zip(args, entry.params):
if not arg.typecast(param.type_):
return False
if param.byref:
from symbols.var import SymbolVAR
if not isinstance(arg.value, SymbolVAR):
syntax_error(lineno, "Expected a variable name, not an "
"expression (parameter By Reference)")
return False
if arg.class_ not in (CLASS.var, CLASS.array):
syntax_error(lineno, "Expected a variable or array name "
"(parameter By Reference)")
return False
arg.byref = True
if entry.forwarded: # The function / sub was DECLARED but not implemented
syntax_error(lineno, "%s '%s' declared but not implemented" % (CLASS.to_string(entry.class_), entry.name))
return False
return True
|
def check_call_arguments(lineno, id_, args)
|
Check arguments against function signature.
Checks every argument in a function call against a function.
Returns True on success.
| 4.269345 | 4.235202 | 1.008062 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.