id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
3,400
grundic/yagocd
yagocd/resources/artifact.py
Artifact.fetch
def fetch(self): """ Method for getting artifact's content. Could only be applicable for file type. :return: content of the artifact. """ 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
python
def fetch(self): 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", ")", ":", "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" ]
Method for getting artifact's content. Could only be applicable for file type. :return: content of the artifact.
[ "Method", "for", "getting", "artifact", "s", "content", ".", "Could", "only", "be", "applicable", "for", "file", "type", "." ]
4c75336ae6f107c8723d37b15e52169151822127
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/artifact.py#L528-L539
3,401
jupyterhub/ltiauthenticator
ltiauthenticator/__init__.py
LTILaunchValidator.validate_launch_request
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 """ # 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
python
def validate_launch_request( self, launch_url, headers, args ): # 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 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" ]
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
[ "Validate", "a", "given", "launch", "request" ]
ae4d95959116c5a2c5d3cbefa6a3ee1be574cc4e
https://github.com/jupyterhub/ltiauthenticator/blob/ae4d95959116c5a2c5d3cbefa6a3ee1be574cc4e/ltiauthenticator/__init__.py#L25-L97
3,402
lightning-viz/lightning-python
lightning/main.py
Lightning.enable_ipython
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. """ # 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))
python
def enable_ipython(self, **kwargs): # 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", ")", ":", "# 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", ")", ")" ]
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.
[ "Enable", "plotting", "in", "the", "iPython", "notebook", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L52-L83
3,403
lightning-viz/lightning-python
lightning/main.py
Lightning.disable_ipython
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. """ 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)
python
def disable_ipython(self): 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", ")", ":", "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", ")" ]
Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook.
[ "Disable", "plotting", "in", "the", "iPython", "notebook", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L85-L98
3,404
lightning-viz/lightning-python
lightning/main.py
Lightning.create_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. """ self.session = Session.create(self, name=name) return self.session
python
def create_session(self, name=None): self.session = Session.create(self, name=name) return self.session
[ "def", "create_session", "(", "self", ",", "name", "=", "None", ")", ":", "self", ".", "session", "=", "Session", ".", "create", "(", "self", ",", "name", "=", "name", ")", "return", "self", ".", "session" ]
Create a lightning session. Can create a session with the provided name, otherwise session name will be "Session No." with the number automatically generated.
[ "Create", "a", "lightning", "session", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L100-L108
3,405
lightning-viz/lightning-python
lightning/main.py
Lightning.use_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. """ self.session = Session(lgn=self, id=session_id) return self.session
python
def use_session(self, session_id): self.session = Session(lgn=self, id=session_id) return self.session
[ "def", "use_session", "(", "self", ",", "session_id", ")", ":", "self", ".", "session", "=", "Session", "(", "lgn", "=", "self", ",", "id", "=", "session_id", ")", "return", "self", ".", "session" ]
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.
[ "Use", "the", "specified", "lightning", "session", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L110-L118
3,406
lightning-viz/lightning-python
lightning/main.py
Lightning.set_basic_auth
def set_basic_auth(self, username, password): """ Set authenatication. """ from requests.auth import HTTPBasicAuth self.auth = HTTPBasicAuth(username, password) return self
python
def set_basic_auth(self, username, password): from requests.auth import HTTPBasicAuth self.auth = HTTPBasicAuth(username, password) return self
[ "def", "set_basic_auth", "(", "self", ",", "username", ",", "password", ")", ":", "from", "requests", ".", "auth", "import", "HTTPBasicAuth", "self", ".", "auth", "=", "HTTPBasicAuth", "(", "username", ",", "password", ")", "return", "self" ]
Set authenatication.
[ "Set", "authenatication", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L136-L142
3,407
lightning-viz/lightning-python
lightning/main.py
Lightning.set_host
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. """ if host[-1] == '/': host = host[:-1] self.host = host return self
python
def set_host(self, host): if host[-1] == '/': host = host[:-1] self.host = host return self
[ "def", "set_host", "(", "self", ",", "host", ")", ":", "if", "host", "[", "-", "1", "]", "==", "'/'", ":", "host", "=", "host", "[", ":", "-", "1", "]", "self", ".", "host", "=", "host", "return", "self" ]
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.
[ "Set", "the", "host", "for", "a", "lightning", "server", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L144-L156
3,408
lightning-viz/lightning-python
lightning/main.py
Lightning.check_status
def check_status(self): """ Check the server for status """ 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
python
def check_status(self): 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", ")", ":", "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" ]
Check the server for status
[ "Check", "the", "server", "for", "status" ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L169-L188
3,409
lightning-viz/lightning-python
lightning/types/base.py
Base._clean_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). """ 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
python
def _clean_data(cls, *args, **kwargs): 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", ")", ":", "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" ]
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).
[ "Convert", "raw", "data", "into", "a", "dictionary", "with", "plot", "-", "type", "specific", "methods", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L80-L106
3,410
lightning-viz/lightning-python
lightning/types/base.py
Base._baseplot
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. """ 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
python
def _baseplot(cls, session, type, *args, **kwargs): 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", ")", ":", "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" ]
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.
[ "Base", "method", "for", "plotting", "data", "and", "images", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L141-L179
3,411
lightning-viz/lightning-python
lightning/types/base.py
Base.update
def update(self, *args, **kwargs): """ Base method for updating data. Applies a plot-type specific cleaning operation, then updates the data in the visualization. """ 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)
python
def update(self, *args, **kwargs): 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", ")", ":", "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", ")" ]
Base method for updating data. Applies a plot-type specific cleaning operation, then updates the data in the visualization.
[ "Base", "method", "for", "updating", "data", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L181-L195
3,412
lightning-viz/lightning-python
lightning/types/base.py
Base.append
def append(self, *args, **kwargs): """ Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization. """ 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)
python
def append(self, *args, **kwargs): 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", ")", ":", "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", ")" ]
Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization.
[ "Base", "method", "for", "appending", "data", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L197-L211
3,413
lightning-viz/lightning-python
lightning/types/base.py
Base._get_user_data
def _get_user_data(self): """ Base method for retrieving user data from a viz. """ 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
python
def _get_user_data(self): 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", ")", ":", "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" ]
Base method for retrieving user data from a viz.
[ "Base", "method", "for", "retrieving", "user", "data", "from", "a", "viz", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/base.py#L213-L225
3,414
lightning-viz/lightning-python
lightning/types/utils.py
check_property
def check_property(prop, name, **kwargs): """ Check and parse a property with either a specific checking function or a generic parser """ 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
python
def check_property(prop, name, **kwargs): 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", ")", ":", "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" ]
Check and parse a property with either a specific checking function or a generic parser
[ "Check", "and", "parse", "a", "property", "with", "either", "a", "specific", "checking", "function", "or", "a", "generic", "parser" ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L16-L39
3,415
lightning-viz/lightning-python
lightning/types/utils.py
check_colormap
def check_colormap(cmap): """ Check if cmap is one of the colorbrewer maps """ 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
python
def check_colormap(cmap): 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", ")", ":", "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" ]
Check if cmap is one of the colorbrewer maps
[ "Check", "if", "cmap", "is", "one", "of", "the", "colorbrewer", "maps" ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L77-L88
3,416
lightning-viz/lightning-python
lightning/types/utils.py
polygon_to_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 """ 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
python
def polygon_to_mask(coords, dims, z=None): 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", ")", ":", "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" ]
Given a list of pairs of points which define a polygon, return a binary mask covering the interior of the polygon with dimensions dim
[ "Given", "a", "list", "of", "pairs", "of", "points", "which", "define", "a", "polygon", "return", "a", "binary", "mask", "covering", "the", "interior", "of", "the", "polygon", "with", "dimensions", "dim" ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L295-L318
3,417
lightning-viz/lightning-python
lightning/types/utils.py
polygon_to_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 """ 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
python
def polygon_to_points(coords, z=None): 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", ")", ":", "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" ]
Given a list of pairs of points which define a polygon, return a list of points interior to the polygon
[ "Given", "a", "list", "of", "pairs", "of", "points", "which", "define", "a", "polygon", "return", "a", "list", "of", "points", "interior", "to", "the", "polygon" ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/types/utils.py#L321-L344
3,418
lightning-viz/lightning-python
lightning/visualization.py
VisualizationLocal.save_html
def save_html(self, filename=None, overwrite=False): """ Save self-contained html to a file. Parameters ---------- filename : str The filename to save to """ 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>')
python
def save_html(self, filename=None, overwrite=False): 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", ")", ":", "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>'", ")" ]
Save self-contained html to a file. Parameters ---------- filename : str The filename to save to
[ "Save", "self", "-", "contained", "html", "to", "a", "file", "." ]
68563e1da82d162d204069d7586f7c695b8bd4a6
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/visualization.py#L173-L197
3,419
shanx/django-maintenancemode
maintenancemode/views.py
temporary_unavailable
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/') """ context = { 'request_path': request.path, } return http.HttpResponseTemporaryUnavailable( render_to_string(template_name, context))
python
def temporary_unavailable(request, template_name='503.html'): context = { 'request_path': request.path, } return http.HttpResponseTemporaryUnavailable( render_to_string(template_name, context))
[ "def", "temporary_unavailable", "(", "request", ",", "template_name", "=", "'503.html'", ")", ":", "context", "=", "{", "'request_path'", ":", "request", ".", "path", ",", "}", "return", "http", ".", "HttpResponseTemporaryUnavailable", "(", "render_to_string", "(", "template_name", ",", "context", ")", ")" ]
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/')
[ "Default", "503", "handler", "which", "looks", "for", "the", "requested", "URL", "in", "the", "redirects", "table", "redirects", "if", "found", "and", "displays", "404", "page", "if", "not", "redirected", "." ]
16e256172dc289122643ec6f4882abbe02dc2b3c
https://github.com/shanx/django-maintenancemode/blob/16e256172dc289122643ec6f4882abbe02dc2b3c/maintenancemode/views.py#L19-L35
3,420
jimporter/bfg9000
bfg9000/versioning.py
simplify_specifiers
def simplify_specifiers(spec): """Try to simplify a SpecifierSet by combining redundant specifiers.""" 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)) )
python
def simplify_specifiers(spec): 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", ")", ":", "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", ")", ")", ")" ]
Try to simplify a SpecifierSet by combining redundant specifiers.
[ "Try", "to", "simplify", "a", "SpecifierSet", "by", "combining", "redundant", "specifiers", "." ]
33615fc67573f0d416297ee9a98dd1ec8b1aa960
https://github.com/jimporter/bfg9000/blob/33615fc67573f0d416297ee9a98dd1ec8b1aa960/bfg9000/versioning.py#L37-L88
3,421
boriel/zxbasic
symbols/function.py
SymbolFUNCTION.reset
def reset(self, lineno=None, offset=None, type_=None): """ This is called when we need to reinitialize the instance state """ 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
python
def reset(self, lineno=None, offset=None, type_=None): 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", ")", ":", "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" ]
This is called when we need to reinitialize the instance state
[ "This", "is", "called", "when", "we", "need", "to", "reinitialize", "the", "instance", "state" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/function.py#L28-L39
3,422
boriel/zxbasic
api/decorator.py
check_type
def check_type(*args, **kwargs): ''' 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
python
def check_type(*args, **kwargs): ''' 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", ")", ":", "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" ]
Checks the function types
[ "Checks", "the", "function", "types" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/decorator.py#L21-L69
3,423
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.norm_attr
def norm_attr(self): """ Normalize attr state """ if not self.HAS_ATTR: return self.HAS_ATTR = False self.emit('call', 'COPY_ATTR', 0) backend.REQUIRES.add('copy_attr.asm')
python
def norm_attr(self): 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", ")", ":", "if", "not", "self", ".", "HAS_ATTR", ":", "return", "self", ".", "HAS_ATTR", "=", "False", "self", ".", "emit", "(", "'call'", ",", "'COPY_ATTR'", ",", "0", ")", "backend", ".", "REQUIRES", ".", "add", "(", "'copy_attr.asm'", ")" ]
Normalize attr state
[ "Normalize", "attr", "state" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L217-L225
3,424
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.traverse_const
def traverse_const(node): """ Traverses a constant and returns an string with the arithmetic expression """ 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)
python
def traverse_const(node): 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", ")", ":", "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", ")" ]
Traverses a constant and returns an string with the arithmetic expression
[ "Traverses", "a", "constant", "and", "returns", "an", "string", "with", "the", "arithmetic", "expression" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L228-L294
3,425
boriel/zxbasic
arch/zx48k/translator.py
TranslatorVisitor.check_attr
def check_attr(node, n): """ Check if ATTR has to be normalized after this instruction has been translated to intermediate code. """ if len(node.children) > n: return node.children[n]
python
def check_attr(node, n): if len(node.children) > n: return node.children[n]
[ "def", "check_attr", "(", "node", ",", "n", ")", ":", "if", "len", "(", "node", ".", "children", ")", ">", "n", ":", "return", "node", ".", "children", "[", "n", "]" ]
Check if ATTR has to be normalized after this instruction has been translated to intermediate code.
[ "Check", "if", "ATTR", "has", "to", "be", "normalized", "after", "this", "instruction", "has", "been", "translated", "to", "intermediate", "code", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L297-L303
3,426
boriel/zxbasic
arch/zx48k/translator.py
Translator.loop_exit_label
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' """ 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)
python
def loop_exit_label(self, loop_type): 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", ")", ":", "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", ")" ]
Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
[ "Returns", "the", "label", "for", "the", "given", "loop", "type", "which", "exits", "the", "loop", ".", "loop_type", "must", "be", "one", "of", "FOR", "WHILE", "DO" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1195-L1203
3,427
boriel/zxbasic
arch/zx48k/translator.py
Translator.loop_cont_label
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' """ 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)
python
def loop_cont_label(self, loop_type): 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", ")", ":", "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", ")" ]
Returns the label for the given loop type which continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
[ "Returns", "the", "label", "for", "the", "given", "loop", "type", "which", "continues", "the", "loop", ".", "loop_type", "must", "be", "one", "of", "FOR", "WHILE", "DO" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1205-L1213
3,428
boriel/zxbasic
arch/zx48k/translator.py
Translator.has_control_chars
def has_control_chars(i): """ Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc """ 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
python
def has_control_chars(i): 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", ")", ":", "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" ]
Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc
[ "Returns", "true", "if", "the", "passed", "token", "is", "an", "unknown", "string", "or", "a", "constant", "string", "having", "control", "chars", "(", "inverse", "etc" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1291-L1314
3,429
boriel/zxbasic
arch/zx48k/translator.py
BuiltinTranslator.visit_USR
def visit_USR(self, node): """ Machine code call from basic """ self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t) self.emit('call', 'USR', node.type_.size) backend.REQUIRES.add('usr.asm')
python
def visit_USR(self, node): 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", ")", ":", "self", ".", "emit", "(", "'fparam'", "+", "self", ".", "TSUFFIX", "(", "gl", ".", "PTR_TYPE", ")", ",", "node", ".", "children", "[", "0", "]", ".", "t", ")", "self", ".", "emit", "(", "'call'", ",", "'USR'", ",", "node", ".", "type_", ".", "size", ")", "backend", ".", "REQUIRES", ".", "add", "(", "'usr.asm'", ")" ]
Machine code call from basic
[ "Machine", "code", "call", "from", "basic" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L1559-L1564
3,430
boriel/zxbasic
prepro/definestable.py
DefinesTable.define
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. """ 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)
python
def define(self, id_, lineno, value='', fname=None, args=None): 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", ")", ":", "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", ")" ]
Defines the value of a macro. Issues a warning if the macro is already defined.
[ "Defines", "the", "value", "of", "a", "macro", ".", "Issues", "a", "warning", "if", "the", "macro", "is", "already", "defined", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/prepro/definestable.py#L31-L45
3,431
boriel/zxbasic
prepro/definestable.py
DefinesTable.set
def set(self, id_, lineno, value='', fname=None, args=None): """ Like the above, but issues no warning on duplicate macro definitions. """ 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)
python
def set(self, id_, lineno, value='', fname=None, args=None): 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", ")", ":", "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", ")" ]
Like the above, but issues no warning on duplicate macro definitions.
[ "Like", "the", "above", "but", "issues", "no", "warning", "on", "duplicate", "macro", "definitions", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/prepro/definestable.py#L47-L56
3,432
boriel/zxbasic
symbols/paramlist.py
SymbolPARAMLIST.appendChild
def appendChild(self, param): ''' Overrides base class. ''' Symbol.appendChild(self, param) if param.offset is None: param.offset = self.size self.size += param.size
python
def appendChild(self, param): ''' Overrides base class. ''' Symbol.appendChild(self, param) if param.offset is None: param.offset = self.size self.size += param.size
[ "def", "appendChild", "(", "self", ",", "param", ")", ":", "Symbol", ".", "appendChild", "(", "self", ",", "param", ")", "if", "param", ".", "offset", "is", "None", ":", "param", ".", "offset", "=", "self", ".", "size", "self", ".", "size", "+=", "param", ".", "size" ]
Overrides base class.
[ "Overrides", "base", "class", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/paramlist.py#L51-L57
3,433
boriel/zxbasic
api/symboltable.py
SymbolTable.get_entry
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. """ 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
python
def get_entry(self, id_, scope=None): 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", ")", ":", "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" ]
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.
[ "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", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L147-L163
3,434
boriel/zxbasic
api/symboltable.py
SymbolTable.check_is_declared
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. """ 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
python
def check_is_declared(self, id_, lineno, classname='identifier', scope=None, show_error=True): 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", ")", ":", "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" ]
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.
[ "Checks", "if", "the", "given", "id", "is", "already", "defined", "in", "any", "scope", "or", "raises", "a", "Syntax", "Error", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L207-L223
3,435
boriel/zxbasic
api/symboltable.py
SymbolTable.check_is_undeclared
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. """ 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
python
def check_is_undeclared(self, id_, lineno, classname='identifier', scope=None, show_error=False): 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", ")", ":", "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" ]
The reverse of the above. Check the given identifier is not already declared. Returns True if OK, False otherwise.
[ "The", "reverse", "of", "the", "above", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L225-L244
3,436
boriel/zxbasic
api/symboltable.py
SymbolTable.check_class
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. """ 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
python
def check_class(self, id_, class_, lineno, scope=None, show_error=True): 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", ")", ":", "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" ]
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.
[ "Check", "the", "id", "is", "either", "undefined", "or", "defined", "with", "the", "given", "class", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L246-L277
3,437
boriel/zxbasic
api/symboltable.py
SymbolTable.enter_scope
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). """ 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 = []
python
def enter_scope(self, funcname): 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", ")", ":", "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", "=", "[", "]" ]
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).
[ "Starts", "a", "new", "variable", "scope", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L282-L292
3,438
boriel/zxbasic
api/symboltable.py
SymbolTable.leave_scope
def leave_scope(self): """ Ends a function body and pops current scope out of the symbol table. """ def entry_size(entry): """ For local variables and params, returns the real variable or local array size in bytes """ 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
python
def leave_scope(self): def entry_size(entry): """ For local variables and params, returns the real variable or local array size in bytes """ 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", ")", ":", "def", "entry_size", "(", "entry", ")", ":", "\"\"\" For local variables and params, returns the real variable or\n local array size in bytes\n \"\"\"", "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" ]
Ends a function body and pops current scope out of the symbol table.
[ "Ends", "a", "function", "body", "and", "pops", "current", "scope", "out", "of", "the", "symbol", "table", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L294-L345
3,439
boriel/zxbasic
api/symboltable.py
SymbolTable.move_to_global_scope
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. """ # 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_))
python
def move_to_global_scope(self, id_): # 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_", ")", ":", "# 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_", ")", ")" ]
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.
[ "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", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L347-L362
3,440
boriel/zxbasic
api/symboltable.py
SymbolTable.access_id
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 """ 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
python
def access_id(self, id_, lineno, scope=None, default_type=None, default_class=CLASS.unknown): 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", ")", ":", "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" ]
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
[ "Access", "a", "symbol", "by", "its", "identifier", "and", "checks", "if", "it", "exists", ".", "If", "not", "it", "s", "supposed", "to", "be", "an", "implicit", "declared", "variable", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L390-L420
3,441
boriel/zxbasic
api/symboltable.py
SymbolTable.access_array
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. """ 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)
python
def access_array(self, id_, lineno, scope=None, default_type=None): 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", ")", ":", "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", ")" ]
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.
[ "Called", "whenever", "an", "accessed", "variable", "is", "expected", "to", "be", "an", "array", ".", "ZX", "BASIC", "requires", "arrays", "to", "be", "declared", "before", "usage", "so", "they", "re", "checked", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L446-L460
3,442
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_variable
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. """ 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
python
def declare_variable(self, id_, lineno, type_, default_value=None): 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", ")", ":", "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" ]
Like the above, but checks that entry.declared is False. Otherwise raises an error. Parameter default_value specifies an initialized variable, if set.
[ "Like", "the", "above", "but", "checks", "that", "entry", ".", "declared", "is", "False", ".", "Otherwise", "raises", "an", "error", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L534-L594
3,443
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_type
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. """ 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
python
def declare_type(self, type_): 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_", ")", ":", "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" ]
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.
[ "Declares", "a", "type", ".", "Checks", "its", "name", "is", "not", "already", "used", "in", "the", "current", "scope", "and", "that", "it", "s", "not", "a", "basic", "type", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L596-L614
3,444
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_const
def declare_const(self, id_, lineno, type_, default_value): """ Similar to the above. But declares a Constant. """ 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
python
def declare_const(self, id_, lineno, type_, default_value): 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", ")", ":", "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" ]
Similar to the above. But declares a Constant.
[ "Similar", "to", "the", "above", ".", "But", "declares", "a", "Constant", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L616-L635
3,445
boriel/zxbasic
api/symboltable.py
SymbolTable.declare_param
def declare_param(self, id_, lineno, type_=None): """ Declares a parameter Check if entry.declared is False. Otherwise raises an error. """ 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
python
def declare_param(self, id_, lineno, type_=None): 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", ")", ":", "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" ]
Declares a parameter Check if entry.declared is False. Otherwise raises an error.
[ "Declares", "a", "parameter", "Check", "if", "entry", ".", "declared", "is", "False", ".", "Otherwise", "raises", "an", "error", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L688-L702
3,446
boriel/zxbasic
api/symboltable.py
SymbolTable.check_labels
def check_labels(self): """ Checks if all the labels has been declared """ for entry in self.labels: self.check_is_declared(entry.name, entry.lineno, CLASS.label)
python
def check_labels(self): for entry in self.labels: self.check_is_declared(entry.name, entry.lineno, CLASS.label)
[ "def", "check_labels", "(", "self", ")", ":", "for", "entry", "in", "self", ".", "labels", ":", "self", ".", "check_is_declared", "(", "entry", ".", "name", ",", "entry", ".", "lineno", ",", "CLASS", ".", "label", ")" ]
Checks if all the labels has been declared
[ "Checks", "if", "all", "the", "labels", "has", "been", "declared" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L806-L810
3,447
boriel/zxbasic
api/symboltable.py
SymbolTable.check_classes
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. """ for entry in self[scope].values(): if entry.class_ is None: syntax_error(entry.lineno, "Unknown identifier '%s'" % entry.name)
python
def check_classes(self, scope=-1): 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", ")", ":", "for", "entry", "in", "self", "[", "scope", "]", ".", "values", "(", ")", ":", "if", "entry", ".", "class_", "is", "None", ":", "syntax_error", "(", "entry", ".", "lineno", ",", "\"Unknown identifier '%s'\"", "%", "entry", ".", "name", ")" ]
Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked.
[ "Check", "if", "pending", "identifiers", "are", "defined", "or", "not", ".", "If", "not", "returns", "a", "syntax", "error", ".", "If", "no", "scope", "is", "given", "the", "current", "one", "is", "checked", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L812-L819
3,448
boriel/zxbasic
api/symboltable.py
SymbolTable.vars_
def vars_(self): """ Returns symbol instances corresponding to variables of the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]
python
def vars_(self): return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]
[ "def", "vars_", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "var", "]" ]
Returns symbol instances corresponding to variables of the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "variables", "of", "the", "current", "scope", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L825-L829
3,449
boriel/zxbasic
api/symboltable.py
SymbolTable.labels
def labels(self): """ Returns symbol instances corresponding to labels in the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
python
def labels(self): return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
[ "def", "labels", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "label", "]" ]
Returns symbol instances corresponding to labels in the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "labels", "in", "the", "current", "scope", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L832-L836
3,450
boriel/zxbasic
api/symboltable.py
SymbolTable.types
def types(self): """ Returns symbol instances corresponding to type declarations within the current scope. """ return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]
python
def types(self): return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]
[ "def", "types", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "isinstance", "(", "x", ",", "symbols", ".", "TYPE", ")", "]" ]
Returns symbol instances corresponding to type declarations within the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "type", "declarations", "within", "the", "current", "scope", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L839-L843
3,451
boriel/zxbasic
api/symboltable.py
SymbolTable.arrays
def arrays(self): """ Returns symbol instances corresponding to arrays of the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]
python
def arrays(self): return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]
[ "def", "arrays", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "==", "CLASS", ".", "array", "]" ]
Returns symbol instances corresponding to arrays of the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "arrays", "of", "the", "current", "scope", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L846-L850
3,452
boriel/zxbasic
api/symboltable.py
SymbolTable.functions
def functions(self): """ Returns symbol instances corresponding to functions of the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ in (CLASS.function, CLASS.sub)]
python
def functions(self): return [x for x in self[self.current_scope].values() if x.class_ in (CLASS.function, CLASS.sub)]
[ "def", "functions", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "class_", "in", "(", "CLASS", ".", "function", ",", "CLASS", ".", "sub", ")", "]" ]
Returns symbol instances corresponding to functions of the current scope.
[ "Returns", "symbol", "instances", "corresponding", "to", "functions", "of", "the", "current", "scope", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L853-L858
3,453
boriel/zxbasic
api/symboltable.py
SymbolTable.aliases
def aliases(self): """ Returns symbol instances corresponding to aliased vars. """ return [x for x in self[self.current_scope].values() if x.is_aliased]
python
def aliases(self): return [x for x in self[self.current_scope].values() if x.is_aliased]
[ "def", "aliases", "(", "self", ")", ":", "return", "[", "x", "for", "x", "in", "self", "[", "self", ".", "current_scope", "]", ".", "values", "(", ")", "if", "x", ".", "is_aliased", "]" ]
Returns symbol instances corresponding to aliased vars.
[ "Returns", "symbol", "instances", "corresponding", "to", "aliased", "vars", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L861-L864
3,454
boriel/zxbasic
api/check.py
check_type
def check_type(lineno, type_list, arg): """ Check arg's type is one in type_list, otherwise, raises an error. """ 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
python
def check_type(lineno, type_list, arg): 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", ")", ":", "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" ]
Check arg's type is one in type_list, otherwise, raises an error.
[ "Check", "arg", "s", "type", "is", "one", "in", "type_list", "otherwise", "raises", "an", "error", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L44-L61
3,455
boriel/zxbasic
api/check.py
check_call_arguments
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. """ 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
python
def check_call_arguments(lineno, id_, args): 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", ")", ":", "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" ]
Check arguments against function signature. Checks every argument in a function call against a function. Returns True on success.
[ "Check", "arguments", "against", "function", "signature", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L87-L129
3,456
boriel/zxbasic
api/check.py
check_pending_calls
def check_pending_calls(): """ Calls the above function for each pending call of the current scope level """ result = True # Check for functions defined after calls (parametres, etc) for id_, params, lineno in global_.FUNCTION_CALLS: result = result and check_call_arguments(lineno, id_, params) return result
python
def check_pending_calls(): result = True # Check for functions defined after calls (parametres, etc) for id_, params, lineno in global_.FUNCTION_CALLS: result = result and check_call_arguments(lineno, id_, params) return result
[ "def", "check_pending_calls", "(", ")", ":", "result", "=", "True", "# Check for functions defined after calls (parametres, etc)", "for", "id_", ",", "params", ",", "lineno", "in", "global_", ".", "FUNCTION_CALLS", ":", "result", "=", "result", "and", "check_call_arguments", "(", "lineno", ",", "id_", ",", "params", ")", "return", "result" ]
Calls the above function for each pending call of the current scope level
[ "Calls", "the", "above", "function", "for", "each", "pending", "call", "of", "the", "current", "scope", "level" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L132-L142
3,457
boriel/zxbasic
api/check.py
check_pending_labels
def check_pending_labels(ast): """ Iteratively traverses the node looking for ID with no class set, marks them as labels, and check they've been declared. This way we avoid stack overflow for high line-numbered listings. """ result = True visited = set() pending = [ast] while pending: node = pending.pop() if node is None or node in visited: # Avoid recursive infinite-loop continue visited.add(node) for x in node.children: pending.append(x) if node.token != 'VAR' or (node.token == 'VAR' and node.class_ is not CLASS.unknown): continue tmp = global_.SYMBOL_TABLE.get_entry(node.name) if tmp is None or tmp.class_ is CLASS.unknown: syntax_error(node.lineno, 'Undeclared identifier "%s"' % node.name) else: assert tmp.class_ == CLASS.label node.to_label(node) result = result and tmp is not None return result
python
def check_pending_labels(ast): result = True visited = set() pending = [ast] while pending: node = pending.pop() if node is None or node in visited: # Avoid recursive infinite-loop continue visited.add(node) for x in node.children: pending.append(x) if node.token != 'VAR' or (node.token == 'VAR' and node.class_ is not CLASS.unknown): continue tmp = global_.SYMBOL_TABLE.get_entry(node.name) if tmp is None or tmp.class_ is CLASS.unknown: syntax_error(node.lineno, 'Undeclared identifier "%s"' % node.name) else: assert tmp.class_ == CLASS.label node.to_label(node) result = result and tmp is not None return result
[ "def", "check_pending_labels", "(", "ast", ")", ":", "result", "=", "True", "visited", "=", "set", "(", ")", "pending", "=", "[", "ast", "]", "while", "pending", ":", "node", "=", "pending", ".", "pop", "(", ")", "if", "node", "is", "None", "or", "node", "in", "visited", ":", "# Avoid recursive infinite-loop", "continue", "visited", ".", "add", "(", "node", ")", "for", "x", "in", "node", ".", "children", ":", "pending", ".", "append", "(", "x", ")", "if", "node", ".", "token", "!=", "'VAR'", "or", "(", "node", ".", "token", "==", "'VAR'", "and", "node", ".", "class_", "is", "not", "CLASS", ".", "unknown", ")", ":", "continue", "tmp", "=", "global_", ".", "SYMBOL_TABLE", ".", "get_entry", "(", "node", ".", "name", ")", "if", "tmp", "is", "None", "or", "tmp", ".", "class_", "is", "CLASS", ".", "unknown", ":", "syntax_error", "(", "node", ".", "lineno", ",", "'Undeclared identifier \"%s\"'", "%", "node", ".", "name", ")", "else", ":", "assert", "tmp", ".", "class_", "==", "CLASS", ".", "label", "node", ".", "to_label", "(", "node", ")", "result", "=", "result", "and", "tmp", "is", "not", "None", "return", "result" ]
Iteratively traverses the node looking for ID with no class set, marks them as labels, and check they've been declared. This way we avoid stack overflow for high line-numbered listings.
[ "Iteratively", "traverses", "the", "node", "looking", "for", "ID", "with", "no", "class", "set", "marks", "them", "as", "labels", "and", "check", "they", "ve", "been", "declared", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L145-L178
3,458
boriel/zxbasic
api/check.py
is_null
def is_null(*symbols): """ True if no nodes or all the given nodes are either None, NOP or empty blocks. For blocks this applies recursively """ from symbols.symbol_ import Symbol for sym in symbols: if sym is None: continue if not isinstance(sym, Symbol): return False if sym.token == 'NOP': continue if sym.token == 'BLOCK': if not is_null(*sym.children): return False continue return False return True
python
def is_null(*symbols): from symbols.symbol_ import Symbol for sym in symbols: if sym is None: continue if not isinstance(sym, Symbol): return False if sym.token == 'NOP': continue if sym.token == 'BLOCK': if not is_null(*sym.children): return False continue return False return True
[ "def", "is_null", "(", "*", "symbols", ")", ":", "from", "symbols", ".", "symbol_", "import", "Symbol", "for", "sym", "in", "symbols", ":", "if", "sym", "is", "None", ":", "continue", "if", "not", "isinstance", "(", "sym", ",", "Symbol", ")", ":", "return", "False", "if", "sym", ".", "token", "==", "'NOP'", ":", "continue", "if", "sym", ".", "token", "==", "'BLOCK'", ":", "if", "not", "is_null", "(", "*", "sym", ".", "children", ")", ":", "return", "False", "continue", "return", "False", "return", "True" ]
True if no nodes or all the given nodes are either None, NOP or empty blocks. For blocks this applies recursively
[ "True", "if", "no", "nodes", "or", "all", "the", "given", "nodes", "are", "either", "None", "NOP", "or", "empty", "blocks", ".", "For", "blocks", "this", "applies", "recursively" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L203-L221
3,459
boriel/zxbasic
api/check.py
is_const
def is_const(*p): """ A constant in the program, like CONST a = 5 """ return is_SYMBOL('VAR', *p) and all(x.class_ == CLASS.const for x in p)
python
def is_const(*p): return is_SYMBOL('VAR', *p) and all(x.class_ == CLASS.const for x in p)
[ "def", "is_const", "(", "*", "p", ")", ":", "return", "is_SYMBOL", "(", "'VAR'", ",", "*", "p", ")", "and", "all", "(", "x", ".", "class_", "==", "CLASS", ".", "const", "for", "x", "in", "p", ")" ]
A constant in the program, like CONST a = 5
[ "A", "constant", "in", "the", "program", "like", "CONST", "a", "=", "5" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L245-L248
3,460
boriel/zxbasic
api/check.py
is_number
def is_number(*p): """ Returns True if ALL of the arguments are AST nodes containing NUMBER or numeric CONSTANTS """ try: for i in p: if i.token != 'NUMBER' and (i.token != 'ID' or i.class_ != CLASS.const): return False return True except: pass return False
python
def is_number(*p): try: for i in p: if i.token != 'NUMBER' and (i.token != 'ID' or i.class_ != CLASS.const): return False return True except: pass return False
[ "def", "is_number", "(", "*", "p", ")", ":", "try", ":", "for", "i", "in", "p", ":", "if", "i", ".", "token", "!=", "'NUMBER'", "and", "(", "i", ".", "token", "!=", "'ID'", "or", "i", ".", "class_", "!=", "CLASS", ".", "const", ")", ":", "return", "False", "return", "True", "except", ":", "pass", "return", "False" ]
Returns True if ALL of the arguments are AST nodes containing NUMBER or numeric CONSTANTS
[ "Returns", "True", "if", "ALL", "of", "the", "arguments", "are", "AST", "nodes", "containing", "NUMBER", "or", "numeric", "CONSTANTS" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L268-L281
3,461
boriel/zxbasic
api/check.py
is_unsigned
def is_unsigned(*p): """ Returns false unless all types in p are unsigned """ from symbols.type_ import Type try: for i in p: if not i.type_.is_basic or not Type.is_unsigned(i.type_): return False return True except: pass return False
python
def is_unsigned(*p): from symbols.type_ import Type try: for i in p: if not i.type_.is_basic or not Type.is_unsigned(i.type_): return False return True except: pass return False
[ "def", "is_unsigned", "(", "*", "p", ")", ":", "from", "symbols", ".", "type_", "import", "Type", "try", ":", "for", "i", "in", "p", ":", "if", "not", "i", ".", "type_", ".", "is_basic", "or", "not", "Type", ".", "is_unsigned", "(", "i", ".", "type_", ")", ":", "return", "False", "return", "True", "except", ":", "pass", "return", "False" ]
Returns false unless all types in p are unsigned
[ "Returns", "false", "unless", "all", "types", "in", "p", "are", "unsigned" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L306-L320
3,462
boriel/zxbasic
api/check.py
is_type
def is_type(type_, *p): """ True if all args have the same type """ try: for i in p: if i.type_ != type_: return False return True except: pass return False
python
def is_type(type_, *p): try: for i in p: if i.type_ != type_: return False return True except: pass return False
[ "def", "is_type", "(", "type_", ",", "*", "p", ")", ":", "try", ":", "for", "i", "in", "p", ":", "if", "i", ".", "type_", "!=", "type_", ":", "return", "False", "return", "True", "except", ":", "pass", "return", "False" ]
True if all args have the same type
[ "True", "if", "all", "args", "have", "the", "same", "type" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L357-L369
3,463
boriel/zxbasic
api/check.py
is_block_accessed
def is_block_accessed(block): """ Returns True if a block is "accessed". A block of code is accessed if it has a LABEL and it is used in a GOTO, GO SUB or @address access :param block: A block of code (AST node) :return: True / False depending if it has labels accessed or not """ if is_LABEL(block) and block.accessed: return True for child in block.children: if not is_callable(child) and is_block_accessed(child): return True return False
python
def is_block_accessed(block): if is_LABEL(block) and block.accessed: return True for child in block.children: if not is_callable(child) and is_block_accessed(child): return True return False
[ "def", "is_block_accessed", "(", "block", ")", ":", "if", "is_LABEL", "(", "block", ")", "and", "block", ".", "accessed", ":", "return", "True", "for", "child", "in", "block", ".", "children", ":", "if", "not", "is_callable", "(", "child", ")", "and", "is_block_accessed", "(", "child", ")", ":", "return", "True", "return", "False" ]
Returns True if a block is "accessed". A block of code is accessed if it has a LABEL and it is used in a GOTO, GO SUB or @address access :param block: A block of code (AST node) :return: True / False depending if it has labels accessed or not
[ "Returns", "True", "if", "a", "block", "is", "accessed", ".", "A", "block", "of", "code", "is", "accessed", "if", "it", "has", "a", "LABEL", "and", "it", "is", "used", "in", "a", "GOTO", "GO", "SUB", "or" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L398-L411
3,464
boriel/zxbasic
api/check.py
common_type
def common_type(a, b): """ Returns a type which is common for both a and b types. Returns None if no common types allowed. """ from symbols.type_ import SymbolBASICTYPE as BASICTYPE from symbols.type_ import Type as TYPE from symbols.type_ import SymbolTYPE if a is None or b is None: return None if not isinstance(a, SymbolTYPE): a = a.type_ if not isinstance(b, SymbolTYPE): b = b.type_ if a == b: # Both types are the same? return a # Returns it if a == TYPE.unknown and b == TYPE.unknown: return BASICTYPE(global_.DEFAULT_TYPE) if a == TYPE.unknown: return b if b == TYPE.unknown: return a # TODO: This will removed / expanded in the future assert a.is_basic assert b.is_basic types = (a, b) if TYPE.float_ in types: return TYPE.float_ if TYPE.fixed in types: return TYPE.fixed if TYPE.string in types: # TODO: Check this ?? return TYPE.unknown result = a if a.size > b.size else b if not TYPE.is_unsigned(a) or not TYPE.is_unsigned(b): result = TYPE.to_signed(result) return result
python
def common_type(a, b): from symbols.type_ import SymbolBASICTYPE as BASICTYPE from symbols.type_ import Type as TYPE from symbols.type_ import SymbolTYPE if a is None or b is None: return None if not isinstance(a, SymbolTYPE): a = a.type_ if not isinstance(b, SymbolTYPE): b = b.type_ if a == b: # Both types are the same? return a # Returns it if a == TYPE.unknown and b == TYPE.unknown: return BASICTYPE(global_.DEFAULT_TYPE) if a == TYPE.unknown: return b if b == TYPE.unknown: return a # TODO: This will removed / expanded in the future assert a.is_basic assert b.is_basic types = (a, b) if TYPE.float_ in types: return TYPE.float_ if TYPE.fixed in types: return TYPE.fixed if TYPE.string in types: # TODO: Check this ?? return TYPE.unknown result = a if a.size > b.size else b if not TYPE.is_unsigned(a) or not TYPE.is_unsigned(b): result = TYPE.to_signed(result) return result
[ "def", "common_type", "(", "a", ",", "b", ")", ":", "from", "symbols", ".", "type_", "import", "SymbolBASICTYPE", "as", "BASICTYPE", "from", "symbols", ".", "type_", "import", "Type", "as", "TYPE", "from", "symbols", ".", "type_", "import", "SymbolTYPE", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "a", ",", "SymbolTYPE", ")", ":", "a", "=", "a", ".", "type_", "if", "not", "isinstance", "(", "b", ",", "SymbolTYPE", ")", ":", "b", "=", "b", ".", "type_", "if", "a", "==", "b", ":", "# Both types are the same?", "return", "a", "# Returns it", "if", "a", "==", "TYPE", ".", "unknown", "and", "b", "==", "TYPE", ".", "unknown", ":", "return", "BASICTYPE", "(", "global_", ".", "DEFAULT_TYPE", ")", "if", "a", "==", "TYPE", ".", "unknown", ":", "return", "b", "if", "b", "==", "TYPE", ".", "unknown", ":", "return", "a", "# TODO: This will removed / expanded in the future", "assert", "a", ".", "is_basic", "assert", "b", ".", "is_basic", "types", "=", "(", "a", ",", "b", ")", "if", "TYPE", ".", "float_", "in", "types", ":", "return", "TYPE", ".", "float_", "if", "TYPE", ".", "fixed", "in", "types", ":", "return", "TYPE", ".", "fixed", "if", "TYPE", ".", "string", "in", "types", ":", "# TODO: Check this ??", "return", "TYPE", ".", "unknown", "result", "=", "a", "if", "a", ".", "size", ">", "b", ".", "size", "else", "b", "if", "not", "TYPE", ".", "is_unsigned", "(", "a", ")", "or", "not", "TYPE", ".", "is_unsigned", "(", "b", ")", ":", "result", "=", "TYPE", ".", "to_signed", "(", "result", ")", "return", "result" ]
Returns a type which is common for both a and b types. Returns None if no common types allowed.
[ "Returns", "a", "type", "which", "is", "common", "for", "both", "a", "and", "b", "types", ".", "Returns", "None", "if", "no", "common", "types", "allowed", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/check.py#L414-L463
3,465
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_sub16
def _sub16(ins): ''' Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used ''' op1, op2 = tuple(ins.quad[2:4]) if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op == 0: output.append('push hl') return output if op < 4: output.extend(['dec hl'] * op) output.append('push hl') return output if op > 65531: output.extend(['inc hl'] * (0x10000 - op)) output.append('push hl') return output output.append('ld de, -%i' % op) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('or a') output.append('sbc hl, de') output.append('push hl') return output
python
def _sub16(ins): ''' Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used ''' op1, op2 = tuple(ins.quad[2:4]) if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op == 0: output.append('push hl') return output if op < 4: output.extend(['dec hl'] * op) output.append('push hl') return output if op > 65531: output.extend(['inc hl'] * (0x10000 - op)) output.append('push hl') return output output.append('ld de, -%i' % op) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('or a') output.append('sbc hl, de') output.append('push hl') return output
[ "def", "_sub16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "4", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op", "==", "0", ":", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", "<", "4", ":", "output", ".", "extend", "(", "[", "'dec hl'", "]", "*", "op", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", ">", "65531", ":", "output", ".", "extend", "(", "[", "'inc hl'", "]", "*", "(", "0x10000", "-", "op", ")", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, -%i'", "%", "op", ")", "output", ".", "append", "(", "'add hl, de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# Optimization when 2nd operand is an id", "rev", "=", "True", "op1", ",", "op2", "=", "op2", ",", "op1", "else", ":", "rev", "=", "False", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ",", "rev", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used
[ "Pops", "last", "2", "words", "from", "the", "stack", "and", "subtract", "them", ".", "Then", "push", "the", "result", "onto", "the", "stack", ".", "Top", "of", "the", "stack", "is", "subtracted", "Top", "-", "1" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L173-L223
3,466
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_mul16
def _mul16(ins): ''' Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: # If any of the operands is constant op1, op2 = _int_ops(op1, op2) # put the constant one the 2nd output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op2 == 1: # A * 1 = 1 * A == A => Do nothing output.append('push hl') return output if op2 == 0xFFFF: # This is the same as (-1) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output if is_2n(op2) and log2(op2) < 4: output.extend(['add hl, hl'] * int(log2(op2))) output.append('push hl') return output output.append('ld de, %i' % op2) else: if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('call __MUL16_FAST') # Inmmediate output.append('push hl') REQUIRES.add('mul16.asm') return output
python
def _mul16(ins): ''' Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: # If any of the operands is constant op1, op2 = _int_ops(op1, op2) # put the constant one the 2nd output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op2 == 1: # A * 1 = 1 * A == A => Do nothing output.append('push hl') return output if op2 == 0xFFFF: # This is the same as (-1) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output if is_2n(op2) and log2(op2) < 4: output.extend(['add hl, hl'] * int(log2(op2))) output.append('push hl') return output output.append('ld de, %i' % op2) else: if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('call __MUL16_FAST') # Inmmediate output.append('push hl') REQUIRES.add('mul16.asm') return output
[ "def", "_mul16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "_int_ops", "(", "op1", ",", "op2", ")", "is", "not", "None", ":", "# If any of the operands is constant", "op1", ",", "op2", "=", "_int_ops", "(", "op1", ",", "op2", ")", "# put the constant one the 2nd", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "0", ":", "# A * 0 = 0 * A = 0", "if", "op1", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "==", "1", ":", "# A * 1 = 1 * A == A => Do nothing", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op2", "==", "0xFFFF", ":", "# This is the same as (-1)", "output", ".", "append", "(", "'call __NEGHL'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'neg16.asm'", ")", "return", "output", "if", "is_2n", "(", "op2", ")", "and", "log2", "(", "op2", ")", "<", "4", ":", "output", ".", "extend", "(", "[", "'add hl, hl'", "]", "*", "int", "(", "log2", "(", "op2", ")", ")", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op2", ")", "else", ":", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# stack optimization", "op1", ",", "op2", "=", "op2", ",", "op1", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ")", "output", ".", "append", "(", "'call __MUL16_FAST'", ")", "# Inmmediate", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'mul16.asm'", ")", "return", "output" ]
Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n
[ "Multiplies", "tow", "last", "16bit", "values", "on", "top", "of", "the", "stack", "and", "and", "returns", "the", "value", "on", "top", "of", "the", "stack" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L226-L276
3,467
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_divu16
def _divu16(ins): ''' Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op1) and int(op1) == 0: # 0 / A = 0 if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack else: output = _16bit_oper(op2) # Normalize stack output.append('ld hl, 0') output.append('push hl') return output if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op == 1: output.append('push hl') return output if op == 2: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld de, %i' % op) else: if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('call __DIVU16') output.append('push hl') REQUIRES.add('div16.asm') return output
python
def _divu16(ins): ''' Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op1) and int(op1) == 0: # 0 / A = 0 if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack else: output = _16bit_oper(op2) # Normalize stack output.append('ld hl, 0') output.append('push hl') return output if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op == 1: output.append('push hl') return output if op == 2: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld de, %i' % op) else: if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('call __DIVU16') output.append('push hl') REQUIRES.add('div16.asm') return output
[ "def", "_divu16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_int", "(", "op1", ")", "and", "int", "(", "op1", ")", "==", "0", ":", "# 0 / A = 0", "if", "op2", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "else", ":", "output", "=", "_16bit_oper", "(", "op2", ")", "# Normalize stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "0", ":", "# A * 0 = 0 * A = 0", "if", "op1", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", "==", "1", ":", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "op", "==", "2", ":", "output", ".", "append", "(", "'srl h'", ")", "output", ".", "append", "(", "'rr l'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op", ")", "else", ":", "if", "op2", "[", "0", "]", "==", "'_'", ":", "# Optimization when 2nd operand is an id", "rev", "=", "True", "op1", ",", "op2", "=", "op2", ",", "op1", "else", ":", "rev", "=", "False", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ",", "rev", ")", "output", ".", "append", "(", "'call __DIVU16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'div16.asm'", ")", "return", "output" ]
Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical
[ "Divides", "2", "16bit", "unsigned", "integers", ".", "The", "result", "is", "pushed", "onto", "the", "stack", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L279-L333
3,468
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_modu16
def _modu16(ins): ''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1) ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op2 = int16(op2) output = _16bit_oper(op1) if op2 == 1: if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if is_2n(op2): k = op2 - 1 if op2 > 255: # only affects H output.append('ld a, h') output.append('and %i' % (k >> 8)) output.append('ld h, a') else: output.append('ld h, 0') # High part goes 0 output.append('ld a, l') output.append('and %i' % (k % 0xFF)) output.append('ld l, a') output.append('push hl') return output output.append('ld de, %i' % op2) else: output = _16bit_oper(op1, op2) output.append('call __MODU16') output.append('push hl') REQUIRES.add('div16.asm') return output
python
def _modu16(ins): ''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1) ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op2 = int16(op2) output = _16bit_oper(op1) if op2 == 1: if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if is_2n(op2): k = op2 - 1 if op2 > 255: # only affects H output.append('ld a, h') output.append('and %i' % (k >> 8)) output.append('ld h, a') else: output.append('ld h, 0') # High part goes 0 output.append('ld a, l') output.append('and %i' % (k % 0xFF)) output.append('ld l, a') output.append('push hl') return output output.append('ld de, %i' % op2) else: output = _16bit_oper(op1, op2) output.append('call __MODU16') output.append('push hl') REQUIRES.add('div16.asm') return output
[ "def", "_modu16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op2", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op2", "==", "1", ":", "if", "op2", "[", "0", "]", "in", "(", "'_'", ",", "'$'", ")", ":", "output", "=", "[", "]", "# Optimization: Discard previous op if not from the stack", "output", ".", "append", "(", "'ld hl, 0'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "if", "is_2n", "(", "op2", ")", ":", "k", "=", "op2", "-", "1", "if", "op2", ">", "255", ":", "# only affects H", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'and %i'", "%", "(", "k", ">>", "8", ")", ")", "output", ".", "append", "(", "'ld h, a'", ")", "else", ":", "output", ".", "append", "(", "'ld h, 0'", ")", "# High part goes 0", "output", ".", "append", "(", "'ld a, l'", ")", "output", ".", "append", "(", "'and %i'", "%", "(", "k", "%", "0xFF", ")", ")", "output", ".", "append", "(", "'ld l, a'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld de, %i'", "%", "op2", ")", "else", ":", "output", "=", "_16bit_oper", "(", "op1", ",", "op2", ")", "output", ".", "append", "(", "'call __MODU16'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'div16.asm'", ")", "return", "output" ]
Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1)
[ "Reminder", "of", "div", ".", "2", "16bit", "unsigned", "integers", ".", "The", "result", "is", "pushed", "onto", "the", "stack", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L395-L438
3,469
boriel/zxbasic
arch/zx48k/backend/__16bit.py
_shru16
def _shru16(ins): ''' Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op = int16(op2) if op == 0: return [] output = _16bit_oper(op1) if op == 1: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld b, %i' % op) else: output = _8bit_oper(op2) output.append('ld b, a') output.extend(_16bit_oper(op1)) label = tmp_label() output.append('%s:' % label) output.append('srl h') output.append('rr l') output.append('djnz %s' % label) output.append('push hl') return output
python
def _shru16(ins): ''' Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op = int16(op2) if op == 0: return [] output = _16bit_oper(op1) if op == 1: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld b, %i' % op) else: output = _8bit_oper(op2) output.append('ld b, a') output.extend(_16bit_oper(op1)) label = tmp_label() output.append('%s:' % label) output.append('srl h') output.append('rr l') output.append('djnz %s' % label) output.append('push hl') return output
[ "def", "_shru16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "if", "op", "==", "0", ":", "return", "[", "]", "output", "=", "_16bit_oper", "(", "op1", ")", "if", "op", "==", "1", ":", "output", ".", "append", "(", "'srl h'", ")", "output", ".", "append", "(", "'rr l'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output", "output", ".", "append", "(", "'ld b, %i'", "%", "op", ")", "else", ":", "output", "=", "_8bit_oper", "(", "op2", ")", "output", ".", "append", "(", "'ld b, a'", ")", "output", ".", "extend", "(", "_16bit_oper", "(", "op1", ")", ")", "label", "=", "tmp_label", "(", ")", "output", ".", "append", "(", "'%s:'", "%", "label", ")", "output", ".", "append", "(", "'srl h'", ")", "output", ".", "append", "(", "'rr l'", ")", "output", ".", "append", "(", "'djnz %s'", "%", "label", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic
[ "Logical", "right", "shift", "16bit", "unsigned", "integer", ".", "The", "result", "is", "pushed", "onto", "the", "stack", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L894-L930
3,470
boriel/zxbasic
api/utils.py
read_txt_file
def read_txt_file(fname): """Reads a txt file, regardless of its encoding """ encodings = ['utf-8-sig', 'cp1252'] with open(fname, 'rb') as f: content = bytes(f.read()) for i in encodings: try: result = content.decode(i) if six.PY2: result = result.encode('utf-8') return result except UnicodeDecodeError: pass global_.FILENAME = fname errmsg.syntax_error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings)) return ''
python
def read_txt_file(fname): encodings = ['utf-8-sig', 'cp1252'] with open(fname, 'rb') as f: content = bytes(f.read()) for i in encodings: try: result = content.decode(i) if six.PY2: result = result.encode('utf-8') return result except UnicodeDecodeError: pass global_.FILENAME = fname errmsg.syntax_error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings)) return ''
[ "def", "read_txt_file", "(", "fname", ")", ":", "encodings", "=", "[", "'utf-8-sig'", ",", "'cp1252'", "]", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "f", ":", "content", "=", "bytes", "(", "f", ".", "read", "(", ")", ")", "for", "i", "in", "encodings", ":", "try", ":", "result", "=", "content", ".", "decode", "(", "i", ")", "if", "six", ".", "PY2", ":", "result", "=", "result", ".", "encode", "(", "'utf-8'", ")", "return", "result", "except", "UnicodeDecodeError", ":", "pass", "global_", ".", "FILENAME", "=", "fname", "errmsg", ".", "syntax_error", "(", "1", ",", "'Invalid file encoding. Use one of: %s'", "%", "', '", ".", "join", "(", "encodings", ")", ")", "return", "''" ]
Reads a txt file, regardless of its encoding
[ "Reads", "a", "txt", "file", "regardless", "of", "its", "encoding" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/utils.py#L15-L33
3,471
boriel/zxbasic
outfmt/tzx.py
TZX.out
def out(self, l): """ Adds a list of bytes to the output string """ if not isinstance(l, list): l = [l] self.output.extend([int(i) & 0xFF for i in l])
python
def out(self, l): if not isinstance(l, list): l = [l] self.output.extend([int(i) & 0xFF for i in l])
[ "def", "out", "(", "self", ",", "l", ")", ":", "if", "not", "isinstance", "(", "l", ",", "list", ")", ":", "l", "=", "[", "l", "]", "self", ".", "output", ".", "extend", "(", "[", "int", "(", "i", ")", "&", "0xFF", "for", "i", "in", "l", "]", ")" ]
Adds a list of bytes to the output string
[ "Adds", "a", "list", "of", "bytes", "to", "the", "output", "string" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L52-L58
3,472
boriel/zxbasic
outfmt/tzx.py
TZX.standard_block
def standard_block(self, _bytes): """ Adds a standard block of bytes """ self.out(self.BLOCK_STANDARD) # Standard block ID self.out(self.LH(1000)) # 1000 ms standard pause self.out(self.LH(len(_bytes) + 1)) # + 1 for CHECKSUM byte checksum = 0 for i in _bytes: checksum ^= (int(i) & 0xFF) self.out(i) self.out(checksum)
python
def standard_block(self, _bytes): self.out(self.BLOCK_STANDARD) # Standard block ID self.out(self.LH(1000)) # 1000 ms standard pause self.out(self.LH(len(_bytes) + 1)) # + 1 for CHECKSUM byte checksum = 0 for i in _bytes: checksum ^= (int(i) & 0xFF) self.out(i) self.out(checksum)
[ "def", "standard_block", "(", "self", ",", "_bytes", ")", ":", "self", ".", "out", "(", "self", ".", "BLOCK_STANDARD", ")", "# Standard block ID", "self", ".", "out", "(", "self", ".", "LH", "(", "1000", ")", ")", "# 1000 ms standard pause", "self", ".", "out", "(", "self", ".", "LH", "(", "len", "(", "_bytes", ")", "+", "1", ")", ")", "# + 1 for CHECKSUM byte", "checksum", "=", "0", "for", "i", "in", "_bytes", ":", "checksum", "^=", "(", "int", "(", "i", ")", "&", "0xFF", ")", "self", ".", "out", "(", "i", ")", "self", ".", "out", "(", "checksum", ")" ]
Adds a standard block of bytes
[ "Adds", "a", "standard", "block", "of", "bytes" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L60-L72
3,473
boriel/zxbasic
outfmt/tzx.py
TZX.dump
def dump(self, fname): """ Saves TZX file to fname """ with open(fname, 'wb') as f: f.write(self.output)
python
def dump(self, fname): with open(fname, 'wb') as f: f.write(self.output)
[ "def", "dump", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "output", ")" ]
Saves TZX file to fname
[ "Saves", "TZX", "file", "to", "fname" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L74-L78
3,474
boriel/zxbasic
outfmt/tzx.py
TZX.standard_bytes_header
def standard_bytes_header(self, title, addr, length): """ Generates a standard header block of CODE type """ self.save_header(self.HEADER_TYPE_CODE, title, length, param1=addr, param2=32768)
python
def standard_bytes_header(self, title, addr, length): self.save_header(self.HEADER_TYPE_CODE, title, length, param1=addr, param2=32768)
[ "def", "standard_bytes_header", "(", "self", ",", "title", ",", "addr", ",", "length", ")", ":", "self", ".", "save_header", "(", "self", ".", "HEADER_TYPE_CODE", ",", "title", ",", "length", ",", "param1", "=", "addr", ",", "param2", "=", "32768", ")" ]
Generates a standard header block of CODE type
[ "Generates", "a", "standard", "header", "block", "of", "CODE", "type" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L109-L112
3,475
boriel/zxbasic
outfmt/tzx.py
TZX.standard_program_header
def standard_program_header(self, title, length, line=32768): """ Generates a standard header block of PROGRAM type """ self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
python
def standard_program_header(self, title, length, line=32768): self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
[ "def", "standard_program_header", "(", "self", ",", "title", ",", "length", ",", "line", "=", "32768", ")", ":", "self", ".", "save_header", "(", "self", ".", "HEADER_TYPE_BASIC", ",", "title", ",", "length", ",", "param1", "=", "line", ",", "param2", "=", "length", ")" ]
Generates a standard header block of PROGRAM type
[ "Generates", "a", "standard", "header", "block", "of", "PROGRAM", "type" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L114-L117
3,476
boriel/zxbasic
outfmt/tzx.py
TZX.save_code
def save_code(self, title, addr, _bytes): """ Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes """ self.standard_bytes_header(title, addr, len(_bytes)) _bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] # & 0xFF truncates to bytes self.standard_block(_bytes)
python
def save_code(self, title, addr, _bytes): self.standard_bytes_header(title, addr, len(_bytes)) _bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] # & 0xFF truncates to bytes self.standard_block(_bytes)
[ "def", "save_code", "(", "self", ",", "title", ",", "addr", ",", "_bytes", ")", ":", "self", ".", "standard_bytes_header", "(", "title", ",", "addr", ",", "len", "(", "_bytes", ")", ")", "_bytes", "=", "[", "self", ".", "BLOCK_TYPE_DATA", "]", "+", "[", "(", "int", "(", "x", ")", "&", "0xFF", ")", "for", "x", "in", "_bytes", "]", "# & 0xFF truncates to bytes", "self", ".", "standard_block", "(", "_bytes", ")" ]
Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes
[ "Saves", "the", "given", "bytes", "as", "code", ".", "If", "bytes", "are", "strings", "its", "chars", "will", "be", "converted", "to", "bytes" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L119-L125
3,477
boriel/zxbasic
outfmt/tzx.py
TZX.save_program
def save_program(self, title, bytes, line=32768): """ Saves the given bytes as a BASIC program. """ self.standard_program_header(title, len(bytes), line) bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in bytes] # & 0xFF truncates to bytes self.standard_block(bytes)
python
def save_program(self, title, bytes, line=32768): self.standard_program_header(title, len(bytes), line) bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in bytes] # & 0xFF truncates to bytes self.standard_block(bytes)
[ "def", "save_program", "(", "self", ",", "title", ",", "bytes", ",", "line", "=", "32768", ")", ":", "self", ".", "standard_program_header", "(", "title", ",", "len", "(", "bytes", ")", ",", "line", ")", "bytes", "=", "[", "self", ".", "BLOCK_TYPE_DATA", "]", "+", "[", "(", "int", "(", "x", ")", "&", "0xFF", ")", "for", "x", "in", "bytes", "]", "# & 0xFF truncates to bytes", "self", ".", "standard_block", "(", "bytes", ")" ]
Saves the given bytes as a BASIC program.
[ "Saves", "the", "given", "bytes", "as", "a", "BASIC", "program", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tzx.py#L127-L132
3,478
boriel/zxbasic
symbols/strslice.py
SymbolSTRSLICE.make_node
def make_node(cls, lineno, s, lower, upper): """ Creates a node for a string slice. S is the string expression Tree. Lower and upper are the bounds, if lower & upper are constants, and s is also constant, then a string constant is returned. If lower > upper, an empty string is returned. """ if lower is None or upper is None or s is None: return None if not check_type(lineno, Type.string, s): return None lo = up = None base = NUMBER(api.config.OPTIONS.string_base.value, lineno=lineno) lower = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', lower, base, lineno=lineno, func=lambda x, y: x - y), lineno) upper = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', upper, base, lineno=lineno, func=lambda x, y: x - y), lineno) if lower is None or upper is None: return None if is_number(lower): lo = lower.value if lo < gl.MIN_STRSLICE_IDX: lower.value = lo = gl.MIN_STRSLICE_IDX if is_number(upper): up = upper.value if up > gl.MAX_STRSLICE_IDX: upper.value = up = gl.MAX_STRSLICE_IDX if is_number(lower, upper): if lo > up: return STRING('', lineno) if s.token == 'STRING': # A constant string? Recalculate it now up += 1 st = s.value.ljust(up) # Procrustean filled (right) return STRING(st[lo:up], lineno) # a$(0 TO INF.) = a$ if lo == gl.MIN_STRSLICE_IDX and up == gl.MAX_STRSLICE_IDX: return s return cls(s, lower, upper, lineno)
python
def make_node(cls, lineno, s, lower, upper): if lower is None or upper is None or s is None: return None if not check_type(lineno, Type.string, s): return None lo = up = None base = NUMBER(api.config.OPTIONS.string_base.value, lineno=lineno) lower = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', lower, base, lineno=lineno, func=lambda x, y: x - y), lineno) upper = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', upper, base, lineno=lineno, func=lambda x, y: x - y), lineno) if lower is None or upper is None: return None if is_number(lower): lo = lower.value if lo < gl.MIN_STRSLICE_IDX: lower.value = lo = gl.MIN_STRSLICE_IDX if is_number(upper): up = upper.value if up > gl.MAX_STRSLICE_IDX: upper.value = up = gl.MAX_STRSLICE_IDX if is_number(lower, upper): if lo > up: return STRING('', lineno) if s.token == 'STRING': # A constant string? Recalculate it now up += 1 st = s.value.ljust(up) # Procrustean filled (right) return STRING(st[lo:up], lineno) # a$(0 TO INF.) = a$ if lo == gl.MIN_STRSLICE_IDX and up == gl.MAX_STRSLICE_IDX: return s return cls(s, lower, upper, lineno)
[ "def", "make_node", "(", "cls", ",", "lineno", ",", "s", ",", "lower", ",", "upper", ")", ":", "if", "lower", "is", "None", "or", "upper", "is", "None", "or", "s", "is", "None", ":", "return", "None", "if", "not", "check_type", "(", "lineno", ",", "Type", ".", "string", ",", "s", ")", ":", "return", "None", "lo", "=", "up", "=", "None", "base", "=", "NUMBER", "(", "api", ".", "config", ".", "OPTIONS", ".", "string_base", ".", "value", ",", "lineno", "=", "lineno", ")", "lower", "=", "TYPECAST", ".", "make_node", "(", "gl", ".", "SYMBOL_TABLE", ".", "basic_types", "[", "gl", ".", "STR_INDEX_TYPE", "]", ",", "BINARY", ".", "make_node", "(", "'MINUS'", ",", "lower", ",", "base", ",", "lineno", "=", "lineno", ",", "func", "=", "lambda", "x", ",", "y", ":", "x", "-", "y", ")", ",", "lineno", ")", "upper", "=", "TYPECAST", ".", "make_node", "(", "gl", ".", "SYMBOL_TABLE", ".", "basic_types", "[", "gl", ".", "STR_INDEX_TYPE", "]", ",", "BINARY", ".", "make_node", "(", "'MINUS'", ",", "upper", ",", "base", ",", "lineno", "=", "lineno", ",", "func", "=", "lambda", "x", ",", "y", ":", "x", "-", "y", ")", ",", "lineno", ")", "if", "lower", "is", "None", "or", "upper", "is", "None", ":", "return", "None", "if", "is_number", "(", "lower", ")", ":", "lo", "=", "lower", ".", "value", "if", "lo", "<", "gl", ".", "MIN_STRSLICE_IDX", ":", "lower", ".", "value", "=", "lo", "=", "gl", ".", "MIN_STRSLICE_IDX", "if", "is_number", "(", "upper", ")", ":", "up", "=", "upper", ".", "value", "if", "up", ">", "gl", ".", "MAX_STRSLICE_IDX", ":", "upper", ".", "value", "=", "up", "=", "gl", ".", "MAX_STRSLICE_IDX", "if", "is_number", "(", "lower", ",", "upper", ")", ":", "if", "lo", ">", "up", ":", "return", "STRING", "(", "''", ",", "lineno", ")", "if", "s", ".", "token", "==", "'STRING'", ":", "# A constant string? Recalculate it now", "up", "+=", "1", "st", "=", "s", ".", "value", ".", "ljust", "(", "up", ")", "# Procrustean filled (right)", "return", "STRING", "(", "st", "[", "lo", ":", "up", "]", ",", "lineno", ")", "# a$(0 TO INF.) = a$", "if", "lo", "==", "gl", ".", "MIN_STRSLICE_IDX", "and", "up", "==", "gl", ".", "MAX_STRSLICE_IDX", ":", "return", "s", "return", "cls", "(", "s", ",", "lower", ",", "upper", ",", "lineno", ")" ]
Creates a node for a string slice. S is the string expression Tree. Lower and upper are the bounds, if lower & upper are constants, and s is also constant, then a string constant is returned. If lower > upper, an empty string is returned.
[ "Creates", "a", "node", "for", "a", "string", "slice", ".", "S", "is", "the", "string", "expression", "Tree", ".", "Lower", "and", "upper", "are", "the", "bounds", "if", "lower", "&", "upper", "are", "constants", "and", "s", "is", "also", "constant", "then", "a", "string", "constant", "is", "returned", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/strslice.py#L69-L117
3,479
boriel/zxbasic
arch/zx48k/backend/__init__.py
to_byte
def to_byte(stype): """ Returns the instruction sequence for converting from the given type to byte. """ output = [] if stype in ('i8', 'u8'): return [] if is_int_type(stype): output.append('ld a, l') elif stype == 'f16': output.append('ld a, e') elif stype == 'f': # Converts C ED LH to byte output.append('call __FTOU32REG') output.append('ld a, l') REQUIRES.add('ftou32reg.asm') return output
python
def to_byte(stype): output = [] if stype in ('i8', 'u8'): return [] if is_int_type(stype): output.append('ld a, l') elif stype == 'f16': output.append('ld a, e') elif stype == 'f': # Converts C ED LH to byte output.append('call __FTOU32REG') output.append('ld a, l') REQUIRES.add('ftou32reg.asm') return output
[ "def", "to_byte", "(", "stype", ")", ":", "output", "=", "[", "]", "if", "stype", "in", "(", "'i8'", ",", "'u8'", ")", ":", "return", "[", "]", "if", "is_int_type", "(", "stype", ")", ":", "output", ".", "append", "(", "'ld a, l'", ")", "elif", "stype", "==", "'f16'", ":", "output", ".", "append", "(", "'ld a, e'", ")", "elif", "stype", "==", "'f'", ":", "# Converts C ED LH to byte", "output", ".", "append", "(", "'call __FTOU32REG'", ")", "output", ".", "append", "(", "'ld a, l'", ")", "REQUIRES", ".", "add", "(", "'ftou32reg.asm'", ")", "return", "output" ]
Returns the instruction sequence for converting from the given type to byte.
[ "Returns", "the", "instruction", "sequence", "for", "converting", "from", "the", "given", "type", "to", "byte", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L252-L270
3,480
boriel/zxbasic
arch/zx48k/backend/__init__.py
_end
def _end(ins): """ Outputs the ending sequence """ global FLAG_end_emitted output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') if FLAG_end_emitted: return output + ['jp %s' % END_LABEL] FLAG_end_emitted = True output.append('%s:' % END_LABEL) if OPTIONS.headerless.value: return output + ['ret'] output.append('di') output.append('ld hl, (%s)' % CALL_BACK) output.append('ld sp, hl') output.append('exx') output.append('pop hl') output.append('exx') output.append('pop iy') output.append('pop ix') output.append('ei') output.append('ret') output.append('%s:' % CALL_BACK) output.append('DEFW 0') return output
python
def _end(ins): global FLAG_end_emitted output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') if FLAG_end_emitted: return output + ['jp %s' % END_LABEL] FLAG_end_emitted = True output.append('%s:' % END_LABEL) if OPTIONS.headerless.value: return output + ['ret'] output.append('di') output.append('ld hl, (%s)' % CALL_BACK) output.append('ld sp, hl') output.append('exx') output.append('pop hl') output.append('exx') output.append('pop iy') output.append('pop ix') output.append('ei') output.append('ret') output.append('%s:' % CALL_BACK) output.append('DEFW 0') return output
[ "def", "_end", "(", "ins", ")", ":", "global", "FLAG_end_emitted", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'ld b, h'", ")", "output", ".", "append", "(", "'ld c, l'", ")", "if", "FLAG_end_emitted", ":", "return", "output", "+", "[", "'jp %s'", "%", "END_LABEL", "]", "FLAG_end_emitted", "=", "True", "output", ".", "append", "(", "'%s:'", "%", "END_LABEL", ")", "if", "OPTIONS", ".", "headerless", ".", "value", ":", "return", "output", "+", "[", "'ret'", "]", "output", ".", "append", "(", "'di'", ")", "output", ".", "append", "(", "'ld hl, (%s)'", "%", "CALL_BACK", ")", "output", ".", "append", "(", "'ld sp, hl'", ")", "output", ".", "append", "(", "'exx'", ")", "output", ".", "append", "(", "'pop hl'", ")", "output", ".", "append", "(", "'exx'", ")", "output", ".", "append", "(", "'pop iy'", ")", "output", ".", "append", "(", "'pop ix'", ")", "output", ".", "append", "(", "'ei'", ")", "output", ".", "append", "(", "'ret'", ")", "output", ".", "append", "(", "'%s:'", "%", "CALL_BACK", ")", "output", ".", "append", "(", "'DEFW 0'", ")", "return", "output" ]
Outputs the ending sequence
[ "Outputs", "the", "ending", "sequence" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L403-L433
3,481
boriel/zxbasic
arch/zx48k/backend/__init__.py
_var
def _var(ins): """ Defines a memory variable. """ output = [] output.append('%s:' % ins.quad[1]) output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00')) return output
python
def _var(ins): output = [] output.append('%s:' % ins.quad[1]) output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00')) return output
[ "def", "_var", "(", "ins", ")", ":", "output", "=", "[", "]", "output", ".", "append", "(", "'%s:'", "%", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'DEFB %s'", "%", "(", "(", "int", "(", "ins", ".", "quad", "[", "2", "]", ")", "-", "1", ")", "*", "'00, '", "+", "'00'", ")", ")", "return", "output" ]
Defines a memory variable.
[ "Defines", "a", "memory", "variable", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L487-L494
3,482
boriel/zxbasic
arch/zx48k/backend/__init__.py
_lvarx
def _lvarx(ins): """ Defines a local variable. 1st param is offset of the local variable. 2nd param is the type a list of bytes in hexadecimal. """ output = [] l = eval(ins.quad[3]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = label ins.quad = tmp AT_END.extend(_varx(ins)) output.append('push ix') output.append('pop hl') output.append('ld bc, %i' % -offset) output.append('add hl, bc') output.append('ex de, hl') output.append('ld hl, %s' % label) output.append('ld bc, %i' % (len(l) * YY_TYPES[ins.quad[2]])) output.append('ldir') return output
python
def _lvarx(ins): output = [] l = eval(ins.quad[3]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = label ins.quad = tmp AT_END.extend(_varx(ins)) output.append('push ix') output.append('pop hl') output.append('ld bc, %i' % -offset) output.append('add hl, bc') output.append('ex de, hl') output.append('ld hl, %s' % label) output.append('ld bc, %i' % (len(l) * YY_TYPES[ins.quad[2]])) output.append('ldir') return output
[ "def", "_lvarx", "(", "ins", ")", ":", "output", "=", "[", "]", "l", "=", "eval", "(", "ins", ".", "quad", "[", "3", "]", ")", "# List of bytes to push", "label", "=", "tmp_label", "(", ")", "offset", "=", "int", "(", "ins", ".", "quad", "[", "1", "]", ")", "tmp", "=", "list", "(", "ins", ".", "quad", ")", "tmp", "[", "1", "]", "=", "label", "ins", ".", "quad", "=", "tmp", "AT_END", ".", "extend", "(", "_varx", "(", "ins", ")", ")", "output", ".", "append", "(", "'push ix'", ")", "output", ".", "append", "(", "'pop hl'", ")", "output", ".", "append", "(", "'ld bc, %i'", "%", "-", "offset", ")", "output", ".", "append", "(", "'add hl, bc'", ")", "output", ".", "append", "(", "'ex de, hl'", ")", "output", ".", "append", "(", "'ld hl, %s'", "%", "label", ")", "output", ".", "append", "(", "'ld bc, %i'", "%", "(", "len", "(", "l", ")", "*", "YY_TYPES", "[", "ins", ".", "quad", "[", "2", "]", "]", ")", ")", "output", ".", "append", "(", "'ldir'", ")", "return", "output" ]
Defines a local variable. 1st param is offset of the local variable. 2nd param is the type a list of bytes in hexadecimal.
[ "Defines", "a", "local", "variable", ".", "1st", "param", "is", "offset", "of", "the", "local", "variable", ".", "2nd", "param", "is", "the", "type", "a", "list", "of", "bytes", "in", "hexadecimal", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L558-L581
3,483
boriel/zxbasic
arch/zx48k/backend/__init__.py
_lvard
def _lvard(ins): """ Defines a local variable. 1st param is offset of the local variable. 2nd param is a list of bytes in hexadecimal. """ output = [] l = eval(ins.quad[2]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = label ins.quad = tmp AT_END.extend(_vard(ins)) output.append('push ix') output.append('pop hl') output.append('ld bc, %i' % -offset) output.append('add hl, bc') output.append('ex de, hl') output.append('ld hl, %s' % label) output.append('ld bc, %i' % len(l)) output.append('ldir') return output
python
def _lvard(ins): output = [] l = eval(ins.quad[2]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = label ins.quad = tmp AT_END.extend(_vard(ins)) output.append('push ix') output.append('pop hl') output.append('ld bc, %i' % -offset) output.append('add hl, bc') output.append('ex de, hl') output.append('ld hl, %s' % label) output.append('ld bc, %i' % len(l)) output.append('ldir') return output
[ "def", "_lvard", "(", "ins", ")", ":", "output", "=", "[", "]", "l", "=", "eval", "(", "ins", ".", "quad", "[", "2", "]", ")", "# List of bytes to push", "label", "=", "tmp_label", "(", ")", "offset", "=", "int", "(", "ins", ".", "quad", "[", "1", "]", ")", "tmp", "=", "list", "(", "ins", ".", "quad", ")", "tmp", "[", "1", "]", "=", "label", "ins", ".", "quad", "=", "tmp", "AT_END", ".", "extend", "(", "_vard", "(", "ins", ")", ")", "output", ".", "append", "(", "'push ix'", ")", "output", ".", "append", "(", "'pop hl'", ")", "output", ".", "append", "(", "'ld bc, %i'", "%", "-", "offset", ")", "output", ".", "append", "(", "'add hl, bc'", ")", "output", ".", "append", "(", "'ex de, hl'", ")", "output", ".", "append", "(", "'ld hl, %s'", "%", "label", ")", "output", ".", "append", "(", "'ld bc, %i'", "%", "len", "(", "l", ")", ")", "output", ".", "append", "(", "'ldir'", ")", "return", "output" ]
Defines a local variable. 1st param is offset of the local variable. 2nd param is a list of bytes in hexadecimal.
[ "Defines", "a", "local", "variable", ".", "1st", "param", "is", "offset", "of", "the", "local", "variable", ".", "2nd", "param", "is", "a", "list", "of", "bytes", "in", "hexadecimal", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L584-L607
3,484
boriel/zxbasic
arch/zx48k/backend/__init__.py
_out
def _out(ins): """ Translates OUT to asm. """ output = _8bit_oper(ins.quad[2]) output.extend(_16bit_oper(ins.quad[1])) output.append('ld b, h') output.append('ld c, l') output.append('out (c), a') return output
python
def _out(ins): output = _8bit_oper(ins.quad[2]) output.extend(_16bit_oper(ins.quad[1])) output.append('ld b, h') output.append('ld c, l') output.append('out (c), a') return output
[ "def", "_out", "(", "ins", ")", ":", "output", "=", "_8bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "extend", "(", "_16bit_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", ")", "output", ".", "append", "(", "'ld b, h'", ")", "output", ".", "append", "(", "'ld c, l'", ")", "output", ".", "append", "(", "'out (c), a'", ")", "return", "output" ]
Translates OUT to asm.
[ "Translates", "OUT", "to", "asm", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L610-L619
3,485
boriel/zxbasic
arch/zx48k/backend/__init__.py
_in
def _in(ins): """ Translates IN to asm. """ output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') output.append('in a, (c)') output.append('push af') return output
python
def _in(ins): output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') output.append('in a, (c)') output.append('push af') return output
[ "def", "_in", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'ld b, h'", ")", "output", ".", "append", "(", "'ld c, l'", ")", "output", ".", "append", "(", "'in a, (c)'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Translates IN to asm.
[ "Translates", "IN", "to", "asm", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L622-L631
3,486
boriel/zxbasic
arch/zx48k/backend/__init__.py
_jzerostr
def _jzerostr(ins): """ Jumps if top of the stack contains a NULL pointer or its len is Zero """ output = [] disposable = False # True if string must be freed from memory if ins.quad[1][0] == '_': # Variable? output.append('ld hl, (%s)' % ins.quad[1][0]) else: output.append('pop hl') output.append('push hl') # Saves it for later disposable = True output.append('call __STRLEN') if disposable: output.append('ex (sp), hl') output.append('call __MEM_FREE') output.append('pop hl') REQUIRES.add('alloc.asm') output.append('ld a, h') output.append('or l') output.append('jp z, %s' % str(ins.quad[2])) REQUIRES.add('strlen.asm') return output
python
def _jzerostr(ins): output = [] disposable = False # True if string must be freed from memory if ins.quad[1][0] == '_': # Variable? output.append('ld hl, (%s)' % ins.quad[1][0]) else: output.append('pop hl') output.append('push hl') # Saves it for later disposable = True output.append('call __STRLEN') if disposable: output.append('ex (sp), hl') output.append('call __MEM_FREE') output.append('pop hl') REQUIRES.add('alloc.asm') output.append('ld a, h') output.append('or l') output.append('jp z, %s' % str(ins.quad[2])) REQUIRES.add('strlen.asm') return output
[ "def", "_jzerostr", "(", "ins", ")", ":", "output", "=", "[", "]", "disposable", "=", "False", "# True if string must be freed from memory", "if", "ins", ".", "quad", "[", "1", "]", "[", "0", "]", "==", "'_'", ":", "# Variable?", "output", ".", "append", "(", "'ld hl, (%s)'", "%", "ins", ".", "quad", "[", "1", "]", "[", "0", "]", ")", "else", ":", "output", ".", "append", "(", "'pop hl'", ")", "output", ".", "append", "(", "'push hl'", ")", "# Saves it for later", "disposable", "=", "True", "output", ".", "append", "(", "'call __STRLEN'", ")", "if", "disposable", ":", "output", ".", "append", "(", "'ex (sp), hl'", ")", "output", ".", "append", "(", "'call __MEM_FREE'", ")", "output", ".", "append", "(", "'pop hl'", ")", "REQUIRES", ".", "add", "(", "'alloc.asm'", ")", "output", ".", "append", "(", "'ld a, h'", ")", "output", ".", "append", "(", "'or l'", ")", "output", ".", "append", "(", "'jp z, %s'", "%", "str", "(", "ins", ".", "quad", "[", "2", "]", ")", ")", "REQUIRES", ".", "add", "(", "'strlen.asm'", ")", "return", "output" ]
Jumps if top of the stack contains a NULL pointer or its len is Zero
[ "Jumps", "if", "top", "of", "the", "stack", "contains", "a", "NULL", "pointer", "or", "its", "len", "is", "Zero" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L1098-L1124
3,487
boriel/zxbasic
arch/zx48k/backend/__init__.py
_param32
def _param32(ins): """ Pushes 32bit param into the stack """ output = _32bit_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
python
def _param32(ins): output = _32bit_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
[ "def", "_param32", "(", "ins", ")", ":", "output", "=", "_32bit_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'push de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Pushes 32bit param into the stack
[ "Pushes", "32bit", "param", "into", "the", "stack" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L1582-L1588
3,488
boriel/zxbasic
arch/zx48k/backend/__init__.py
_paramf16
def _paramf16(ins): """ Pushes 32bit fixed point param into the stack """ output = _f16_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
python
def _paramf16(ins): output = _f16_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
[ "def", "_paramf16", "(", "ins", ")", ":", "output", "=", "_f16_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'push de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
Pushes 32bit fixed point param into the stack
[ "Pushes", "32bit", "fixed", "point", "param", "into", "the", "stack" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L1591-L1597
3,489
boriel/zxbasic
arch/zx48k/backend/__init__.py
_memcopy
def _memcopy(ins): """ Copies a block of memory from param 2 addr to param 1 addr. """ output = _16bit_oper(ins.quad[3]) output.append('ld b, h') output.append('ld c, l') output.extend(_16bit_oper(ins.quad[1], ins.quad[2], reversed=True)) output.append('ldir') # *** return output
python
def _memcopy(ins): output = _16bit_oper(ins.quad[3]) output.append('ld b, h') output.append('ld c, l') output.extend(_16bit_oper(ins.quad[1], ins.quad[2], reversed=True)) output.append('ldir') # *** return output
[ "def", "_memcopy", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'ld b, h'", ")", "output", ".", "append", "(", "'ld c, l'", ")", "output", ".", "extend", "(", "_16bit_oper", "(", "ins", ".", "quad", "[", "1", "]", ",", "ins", ".", "quad", "[", "2", "]", ",", "reversed", "=", "True", ")", ")", "output", ".", "append", "(", "'ldir'", ")", "# ***", "return", "output" ]
Copies a block of memory from param 2 addr to param 1 addr.
[ "Copies", "a", "block", "of", "memory", "from", "param", "2", "addr", "to", "param", "1", "addr", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L1681-L1691
3,490
boriel/zxbasic
zxbpplex.py
Lexer.include_end
def include_end(self): """ Performs and end of include. """ self.lex = self.filestack[-1][2] self.input_data = self.filestack[-1][3] self.filestack.pop() if not self.filestack: # End of input? return self.filestack[-1][1] += 1 # Increment line counter of previous file result = lex.LexToken() result.value = self.put_current_line(suffix='\n') result.type = '_ENDFILE_' result.lineno = self.lex.lineno result.lexpos = self.lex.lexpos return result
python
def include_end(self): self.lex = self.filestack[-1][2] self.input_data = self.filestack[-1][3] self.filestack.pop() if not self.filestack: # End of input? return self.filestack[-1][1] += 1 # Increment line counter of previous file result = lex.LexToken() result.value = self.put_current_line(suffix='\n') result.type = '_ENDFILE_' result.lineno = self.lex.lineno result.lexpos = self.lex.lexpos return result
[ "def", "include_end", "(", "self", ")", ":", "self", ".", "lex", "=", "self", ".", "filestack", "[", "-", "1", "]", "[", "2", "]", "self", ".", "input_data", "=", "self", ".", "filestack", "[", "-", "1", "]", "[", "3", "]", "self", ".", "filestack", ".", "pop", "(", ")", "if", "not", "self", ".", "filestack", ":", "# End of input?", "return", "self", ".", "filestack", "[", "-", "1", "]", "[", "1", "]", "+=", "1", "# Increment line counter of previous file", "result", "=", "lex", ".", "LexToken", "(", ")", "result", ".", "value", "=", "self", ".", "put_current_line", "(", "suffix", "=", "'\\n'", ")", "result", ".", "type", "=", "'_ENDFILE_'", "result", ".", "lineno", "=", "self", ".", "lex", ".", "lineno", "result", ".", "lexpos", "=", "self", ".", "lex", ".", "lexpos", "return", "result" ]
Performs and end of include.
[ "Performs", "and", "end", "of", "include", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpplex.py#L419-L437
3,491
boriel/zxbasic
arch/zx48k/beep.py
getDEHL
def getDEHL(duration, pitch): """Converts duration,pitch to a pair of unsigned 16 bit integers, to be loaded in DE,HL, following the ROM listing. Returns a t-uple with the DE, HL values. """ intPitch = int(pitch) fractPitch = pitch - intPitch # Gets fractional part tmp = 1 + 0.0577622606 * fractPitch if not -60 <= intPitch <= 127: raise BeepError('Pitch out of range: must be between [-60, 127]') if duration < 0 or duration > 10: raise BeepError('Invalid duration: must be between [0, 10]') A = intPitch + 60 B = -5 + int(A / 12) # -5 <= B <= 10 A %= 0xC # Semitones above C frec = TABLE[A] tmp2 = tmp * frec f = tmp2 * 2.0 ** B DE = int(0.5 + f * duration - 1) HL = int(0.5 + 437500.0 / f - 30.125) return DE, HL
python
def getDEHL(duration, pitch): intPitch = int(pitch) fractPitch = pitch - intPitch # Gets fractional part tmp = 1 + 0.0577622606 * fractPitch if not -60 <= intPitch <= 127: raise BeepError('Pitch out of range: must be between [-60, 127]') if duration < 0 or duration > 10: raise BeepError('Invalid duration: must be between [0, 10]') A = intPitch + 60 B = -5 + int(A / 12) # -5 <= B <= 10 A %= 0xC # Semitones above C frec = TABLE[A] tmp2 = tmp * frec f = tmp2 * 2.0 ** B DE = int(0.5 + f * duration - 1) HL = int(0.5 + 437500.0 / f - 30.125) return DE, HL
[ "def", "getDEHL", "(", "duration", ",", "pitch", ")", ":", "intPitch", "=", "int", "(", "pitch", ")", "fractPitch", "=", "pitch", "-", "intPitch", "# Gets fractional part", "tmp", "=", "1", "+", "0.0577622606", "*", "fractPitch", "if", "not", "-", "60", "<=", "intPitch", "<=", "127", ":", "raise", "BeepError", "(", "'Pitch out of range: must be between [-60, 127]'", ")", "if", "duration", "<", "0", "or", "duration", ">", "10", ":", "raise", "BeepError", "(", "'Invalid duration: must be between [0, 10]'", ")", "A", "=", "intPitch", "+", "60", "B", "=", "-", "5", "+", "int", "(", "A", "/", "12", ")", "# -5 <= B <= 10", "A", "%=", "0xC", "# Semitones above C", "frec", "=", "TABLE", "[", "A", "]", "tmp2", "=", "tmp", "*", "frec", "f", "=", "tmp2", "*", "2.0", "**", "B", "DE", "=", "int", "(", "0.5", "+", "f", "*", "duration", "-", "1", ")", "HL", "=", "int", "(", "0.5", "+", "437500.0", "/", "f", "-", "30.125", ")", "return", "DE", ",", "HL" ]
Converts duration,pitch to a pair of unsigned 16 bit integers, to be loaded in DE,HL, following the ROM listing. Returns a t-uple with the DE, HL values.
[ "Converts", "duration", "pitch", "to", "a", "pair", "of", "unsigned", "16", "bit", "integers", "to", "be", "loaded", "in", "DE", "HL", "following", "the", "ROM", "listing", ".", "Returns", "a", "t", "-", "uple", "with", "the", "DE", "HL", "values", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/beep.py#L36-L60
3,492
boriel/zxbasic
symbols/block.py
SymbolBLOCK.make_node
def make_node(cls, *args): """ Creates a chain of code blocks. """ new_args = [] args = [x for x in args if not is_null(x)] for x in args: assert isinstance(x, Symbol) if x.token == 'BLOCK': new_args.extend(SymbolBLOCK.make_node(*x.children).children) else: new_args.append(x) result = SymbolBLOCK(*new_args) return result
python
def make_node(cls, *args): new_args = [] args = [x for x in args if not is_null(x)] for x in args: assert isinstance(x, Symbol) if x.token == 'BLOCK': new_args.extend(SymbolBLOCK.make_node(*x.children).children) else: new_args.append(x) result = SymbolBLOCK(*new_args) return result
[ "def", "make_node", "(", "cls", ",", "*", "args", ")", ":", "new_args", "=", "[", "]", "args", "=", "[", "x", "for", "x", "in", "args", "if", "not", "is_null", "(", "x", ")", "]", "for", "x", "in", "args", ":", "assert", "isinstance", "(", "x", ",", "Symbol", ")", "if", "x", ".", "token", "==", "'BLOCK'", ":", "new_args", ".", "extend", "(", "SymbolBLOCK", ".", "make_node", "(", "*", "x", ".", "children", ")", ".", "children", ")", "else", ":", "new_args", ".", "append", "(", "x", ")", "result", "=", "SymbolBLOCK", "(", "*", "new_args", ")", "return", "result" ]
Creates a chain of code blocks.
[ "Creates", "a", "chain", "of", "code", "blocks", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/block.py#L23-L37
3,493
boriel/zxbasic
zxblex.py
is_label
def is_label(token): """ Return whether the token is a label (an integer number or id at the beginning of a line. To do so, we compute find_column() and moves back to the beginning of the line if previous chars are spaces or tabs. If column 0 is reached, it's a label. """ if not LABELS_ALLOWED: return False c = i = token.lexpos input = token.lexer.lexdata c -= 1 while c > 0 and input[c] in (' ', '\t'): c -= 1 while i > 0: if input[i] == '\n': break i -= 1 column = c - i if column == 0: column += 1 return column == 1
python
def is_label(token): if not LABELS_ALLOWED: return False c = i = token.lexpos input = token.lexer.lexdata c -= 1 while c > 0 and input[c] in (' ', '\t'): c -= 1 while i > 0: if input[i] == '\n': break i -= 1 column = c - i if column == 0: column += 1 return column == 1
[ "def", "is_label", "(", "token", ")", ":", "if", "not", "LABELS_ALLOWED", ":", "return", "False", "c", "=", "i", "=", "token", ".", "lexpos", "input", "=", "token", ".", "lexer", ".", "lexdata", "c", "-=", "1", "while", "c", ">", "0", "and", "input", "[", "c", "]", "in", "(", "' '", ",", "'\\t'", ")", ":", "c", "-=", "1", "while", "i", ">", "0", ":", "if", "input", "[", "i", "]", "==", "'\\n'", ":", "break", "i", "-=", "1", "column", "=", "c", "-", "i", "if", "column", "==", "0", ":", "column", "+=", "1", "return", "column", "==", "1" ]
Return whether the token is a label (an integer number or id at the beginning of a line. To do so, we compute find_column() and moves back to the beginning of the line if previous chars are spaces or tabs. If column 0 is reached, it's a label.
[ "Return", "whether", "the", "token", "is", "a", "label", "(", "an", "integer", "number", "or", "id", "at", "the", "beginning", "of", "a", "line", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxblex.py#L643-L670
3,494
boriel/zxbasic
symbols/number.py
_get_val
def _get_val(other): """ Given a Number, a Numeric Constant or a python number return its value """ assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value return other
python
def _get_val(other): assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value return other
[ "def", "_get_val", "(", "other", ")", ":", "assert", "isinstance", "(", "other", ",", "(", "numbers", ".", "Number", ",", "SymbolNUMBER", ",", "SymbolCONST", ")", ")", "if", "isinstance", "(", "other", ",", "SymbolNUMBER", ")", ":", "return", "other", ".", "value", "if", "isinstance", "(", "other", ",", "SymbolCONST", ")", ":", "return", "other", ".", "expr", ".", "value", "return", "other" ]
Given a Number, a Numeric Constant or a python number return its value
[ "Given", "a", "Number", "a", "Numeric", "Constant", "or", "a", "python", "number", "return", "its", "value" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/number.py#L21-L31
3,495
boriel/zxbasic
prepro/id_.py
ID.__dumptable
def __dumptable(self, table): """ Dumps table on screen for debugging purposes """ for x in table.table.keys(): sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x]))) if isinstance(table[x], ID): sys.stdout(" {0}".format(table[x].value)), sys.stdout.write("\n")
python
def __dumptable(self, table): for x in table.table.keys(): sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x]))) if isinstance(table[x], ID): sys.stdout(" {0}".format(table[x].value)), sys.stdout.write("\n")
[ "def", "__dumptable", "(", "self", ",", "table", ")", ":", "for", "x", "in", "table", ".", "table", ".", "keys", "(", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"{0}\\t<--- {1} {2}\"", ".", "format", "(", "x", ",", "table", "[", "x", "]", ",", "type", "(", "table", "[", "x", "]", ")", ")", ")", "if", "isinstance", "(", "table", "[", "x", "]", ",", "ID", ")", ":", "sys", ".", "stdout", "(", "\" {0}\"", ".", "format", "(", "table", "[", "x", "]", ".", "value", ")", ")", ",", "sys", ".", "stdout", ".", "write", "(", "\"\\n\"", ")" ]
Dumps table on screen for debugging purposes
[ "Dumps", "table", "on", "screen", "for", "debugging", "purposes" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/prepro/id_.py#L44-L52
3,496
boriel/zxbasic
symbols/vararray.py
SymbolVARARRAY.count
def count(self): """ Total number of array cells """ return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
python
def count(self): return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
[ "def", "count", "(", "self", ")", ":", "return", "functools", ".", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "(", "x", ".", "count", "for", "x", "in", "self", ".", "bounds", ")", ")" ]
Total number of array cells
[ "Total", "number", "of", "array", "cells" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/vararray.py#L38-L41
3,497
boriel/zxbasic
symbols/vararray.py
SymbolVARARRAY.memsize
def memsize(self): """ Total array cell + indexes size """ return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)
python
def memsize(self): return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)
[ "def", "memsize", "(", "self", ")", ":", "return", "self", ".", "size", "+", "1", "+", "TYPE", ".", "size", "(", "gl", ".", "BOUND_TYPE", ")", "*", "len", "(", "self", ".", "bounds", ")" ]
Total array cell + indexes size
[ "Total", "array", "cell", "+", "indexes", "size" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/vararray.py#L48-L51
3,498
boriel/zxbasic
symbols/typecast.py
SymbolTYPECAST.make_node
def make_node(cls, new_type, node, lineno): """ Creates a node containing the type cast of the given one. If new_type == node.type, then nothing is done, and the same node is returned. Returns None on failure (and calls syntax_error) """ assert isinstance(new_type, SymbolTYPE) # None (null) means the given AST node is empty (usually an error) if node is None: return None # Do nothing. Return None assert isinstance(node, Symbol), '<%s> is not a Symbol' % node # The source and dest types are the same if new_type == node.type_: return node # Do nothing. Return as is STRTYPE = TYPE.string # Typecasting, at the moment, only for number if node.type_ == STRTYPE: syntax_error(lineno, 'Cannot convert string to a value. ' 'Use VAL() function') return None # Converting from string to number is done by STR if new_type == STRTYPE: syntax_error(lineno, 'Cannot convert value to string. ' 'Use STR() function') return None # If the given operand is a constant, perform a static typecast if is_CONST(node): node.expr = cls(new_type, node.expr, lineno) return node if not is_number(node) and not is_const(node): return cls(new_type, node, lineno) # It's a number. So let's convert it directly if is_const(node): node = SymbolNUMBER(node.value, node.lineno, node.type_) if new_type.is_basic and not TYPE.is_integral(new_type): # not an integer node.value = float(node.value) else: # It's an integer new_val = (int(node.value) & ((1 << (8 * new_type.size)) - 1)) # Mask it if node.value >= 0 and node.value != new_val: errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val elif node.value < 0 and (1 << (new_type.size * 8)) + \ node.value != new_val: # Test for positive to negative coercion errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val - (1 << (new_type.size * 8)) node.type_ = new_type return node
python
def make_node(cls, new_type, node, lineno): assert isinstance(new_type, SymbolTYPE) # None (null) means the given AST node is empty (usually an error) if node is None: return None # Do nothing. Return None assert isinstance(node, Symbol), '<%s> is not a Symbol' % node # The source and dest types are the same if new_type == node.type_: return node # Do nothing. Return as is STRTYPE = TYPE.string # Typecasting, at the moment, only for number if node.type_ == STRTYPE: syntax_error(lineno, 'Cannot convert string to a value. ' 'Use VAL() function') return None # Converting from string to number is done by STR if new_type == STRTYPE: syntax_error(lineno, 'Cannot convert value to string. ' 'Use STR() function') return None # If the given operand is a constant, perform a static typecast if is_CONST(node): node.expr = cls(new_type, node.expr, lineno) return node if not is_number(node) and not is_const(node): return cls(new_type, node, lineno) # It's a number. So let's convert it directly if is_const(node): node = SymbolNUMBER(node.value, node.lineno, node.type_) if new_type.is_basic and not TYPE.is_integral(new_type): # not an integer node.value = float(node.value) else: # It's an integer new_val = (int(node.value) & ((1 << (8 * new_type.size)) - 1)) # Mask it if node.value >= 0 and node.value != new_val: errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val elif node.value < 0 and (1 << (new_type.size * 8)) + \ node.value != new_val: # Test for positive to negative coercion errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val - (1 << (new_type.size * 8)) node.type_ = new_type return node
[ "def", "make_node", "(", "cls", ",", "new_type", ",", "node", ",", "lineno", ")", ":", "assert", "isinstance", "(", "new_type", ",", "SymbolTYPE", ")", "# None (null) means the given AST node is empty (usually an error)", "if", "node", "is", "None", ":", "return", "None", "# Do nothing. Return None", "assert", "isinstance", "(", "node", ",", "Symbol", ")", ",", "'<%s> is not a Symbol'", "%", "node", "# The source and dest types are the same", "if", "new_type", "==", "node", ".", "type_", ":", "return", "node", "# Do nothing. Return as is", "STRTYPE", "=", "TYPE", ".", "string", "# Typecasting, at the moment, only for number", "if", "node", ".", "type_", "==", "STRTYPE", ":", "syntax_error", "(", "lineno", ",", "'Cannot convert string to a value. '", "'Use VAL() function'", ")", "return", "None", "# Converting from string to number is done by STR", "if", "new_type", "==", "STRTYPE", ":", "syntax_error", "(", "lineno", ",", "'Cannot convert value to string. '", "'Use STR() function'", ")", "return", "None", "# If the given operand is a constant, perform a static typecast", "if", "is_CONST", "(", "node", ")", ":", "node", ".", "expr", "=", "cls", "(", "new_type", ",", "node", ".", "expr", ",", "lineno", ")", "return", "node", "if", "not", "is_number", "(", "node", ")", "and", "not", "is_const", "(", "node", ")", ":", "return", "cls", "(", "new_type", ",", "node", ",", "lineno", ")", "# It's a number. So let's convert it directly", "if", "is_const", "(", "node", ")", ":", "node", "=", "SymbolNUMBER", "(", "node", ".", "value", ",", "node", ".", "lineno", ",", "node", ".", "type_", ")", "if", "new_type", ".", "is_basic", "and", "not", "TYPE", ".", "is_integral", "(", "new_type", ")", ":", "# not an integer", "node", ".", "value", "=", "float", "(", "node", ".", "value", ")", "else", ":", "# It's an integer", "new_val", "=", "(", "int", "(", "node", ".", "value", ")", "&", "(", "(", "1", "<<", "(", "8", "*", "new_type", ".", "size", ")", ")", "-", "1", ")", ")", "# Mask it", "if", "node", ".", "value", ">=", "0", "and", "node", ".", "value", "!=", "new_val", ":", "errmsg", ".", "warning_conversion_lose_digits", "(", "node", ".", "lineno", ")", "node", ".", "value", "=", "new_val", "elif", "node", ".", "value", "<", "0", "and", "(", "1", "<<", "(", "new_type", ".", "size", "*", "8", ")", ")", "+", "node", ".", "value", "!=", "new_val", ":", "# Test for positive to negative coercion", "errmsg", ".", "warning_conversion_lose_digits", "(", "node", ".", "lineno", ")", "node", ".", "value", "=", "new_val", "-", "(", "1", "<<", "(", "new_type", ".", "size", "*", "8", ")", ")", "node", ".", "type_", "=", "new_type", "return", "node" ]
Creates a node containing the type cast of the given one. If new_type == node.type, then nothing is done, and the same node is returned. Returns None on failure (and calls syntax_error)
[ "Creates", "a", "node", "containing", "the", "type", "cast", "of", "the", "given", "one", ".", "If", "new_type", "==", "node", ".", "type", "then", "nothing", "is", "done", "and", "the", "same", "node", "is", "returned", "." ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/symbols/typecast.py#L44-L102
3,499
boriel/zxbasic
asmparse.py
assemble
def assemble(input_): """ Assembles input string, and leave the result in the MEMORY global object """ global MEMORY if MEMORY is None: MEMORY = Memory() parser.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 2) if len(MEMORY.scopes): error(MEMORY.scopes[-1], 'Missing ENDP to close this scope') return gl.has_errors
python
def assemble(input_): global MEMORY if MEMORY is None: MEMORY = Memory() parser.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 2) if len(MEMORY.scopes): error(MEMORY.scopes[-1], 'Missing ENDP to close this scope') return gl.has_errors
[ "def", "assemble", "(", "input_", ")", ":", "global", "MEMORY", "if", "MEMORY", "is", "None", ":", "MEMORY", "=", "Memory", "(", ")", "parser", ".", "parse", "(", "input_", ",", "lexer", "=", "LEXER", ",", "debug", "=", "OPTIONS", ".", "Debug", ".", "value", ">", "2", ")", "if", "len", "(", "MEMORY", ".", "scopes", ")", ":", "error", "(", "MEMORY", ".", "scopes", "[", "-", "1", "]", ",", "'Missing ENDP to close this scope'", ")", "return", "gl", ".", "has_errors" ]
Assembles input string, and leave the result in the MEMORY global object
[ "Assembles", "input", "string", "and", "leave", "the", "result", "in", "the", "MEMORY", "global", "object" ]
23b28db10e41117805bdb3c0f78543590853b132
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmparse.py#L1426-L1439