repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
d0c-s4vage/pfp
pfp/fuzz/strats.py
FieldStrat.next_val
def next_val(self, field): """Return a new value to mutate a field with. Do not modify the field directly in this function. Override the ``mutate()`` function if that is needed (the field is only passed into this function as a reference). :field: The pfp.fields.Field instance that will receive the new value. Passed in for reference only. :returns: The next value for the field """ import pfp.fuzz.rand as rand if self.choices is not None: choices = self._resolve_member_val(self.choices, field) new_val = rand.choice(choices) return self._resolve_val(new_val) elif self.prob is not None: prob = self._resolve_member_val(self.prob, field) rand_val = rand.random() curr_total = 0.0 # iterate through each of the probability choices until # we reach one that matches the current rand_val for prob_percent, prob_val in prob: if rand_val <= curr_total + prob_percent: return self._resolve_val(prob_val) curr_total += prob_percent raise MutationError("probabilities did not add up to 100%! {}".format( [str(x[0]) + " - " + str(x[1])[:10] for x in prob] ))
python
def next_val(self, field): """Return a new value to mutate a field with. Do not modify the field directly in this function. Override the ``mutate()`` function if that is needed (the field is only passed into this function as a reference). :field: The pfp.fields.Field instance that will receive the new value. Passed in for reference only. :returns: The next value for the field """ import pfp.fuzz.rand as rand if self.choices is not None: choices = self._resolve_member_val(self.choices, field) new_val = rand.choice(choices) return self._resolve_val(new_val) elif self.prob is not None: prob = self._resolve_member_val(self.prob, field) rand_val = rand.random() curr_total = 0.0 # iterate through each of the probability choices until # we reach one that matches the current rand_val for prob_percent, prob_val in prob: if rand_val <= curr_total + prob_percent: return self._resolve_val(prob_val) curr_total += prob_percent raise MutationError("probabilities did not add up to 100%! {}".format( [str(x[0]) + " - " + str(x[1])[:10] for x in prob] ))
[ "def", "next_val", "(", "self", ",", "field", ")", ":", "import", "pfp", ".", "fuzz", ".", "rand", "as", "rand", "if", "self", ".", "choices", "is", "not", "None", ":", "choices", "=", "self", ".", "_resolve_member_val", "(", "self", ".", "choices", ...
Return a new value to mutate a field with. Do not modify the field directly in this function. Override the ``mutate()`` function if that is needed (the field is only passed into this function as a reference). :field: The pfp.fields.Field instance that will receive the new value. Passed in for reference only. :returns: The next value for the field
[ "Return", "a", "new", "value", "to", "mutate", "a", "field", "with", ".", "Do", "not", "modify", "the", "field", "directly", "in", "this", "function", ".", "Override", "the", "mutate", "()", "function", "if", "that", "is", "needed", "(", "the", "field", ...
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/fuzz/strats.py#L204-L232
train
expfactory/expfactory
expfactory/database/relational.py
generate_subid
def generate_subid(self, token=None, return_user=False): '''generate a new user in the database, still session based so we create a new identifier. ''' from expfactory.database.models import Participant if not token: p = Participant() else: p = Participant(token=token) self.session.add(p) self.session.commit() if return_user is True: return p return p.id
python
def generate_subid(self, token=None, return_user=False): '''generate a new user in the database, still session based so we create a new identifier. ''' from expfactory.database.models import Participant if not token: p = Participant() else: p = Participant(token=token) self.session.add(p) self.session.commit() if return_user is True: return p return p.id
[ "def", "generate_subid", "(", "self", ",", "token", "=", "None", ",", "return_user", "=", "False", ")", ":", "from", "expfactory", ".", "database", ".", "models", "import", "Participant", "if", "not", "token", ":", "p", "=", "Participant", "(", ")", "els...
generate a new user in the database, still session based so we create a new identifier.
[ "generate", "a", "new", "user", "in", "the", "database", "still", "session", "based", "so", "we", "create", "a", "new", "identifier", "." ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L65-L78
train
expfactory/expfactory
expfactory/database/relational.py
print_user
def print_user(self, user): '''print a relational database user ''' status = "active" token = user.token if token in ['finished', 'revoked']: status = token if token is None: token = '' subid = "%s\t%s[%s]" %(user.id, token, status) print(subid) return subid
python
def print_user(self, user): '''print a relational database user ''' status = "active" token = user.token if token in ['finished', 'revoked']: status = token if token is None: token = '' subid = "%s\t%s[%s]" %(user.id, token, status) print(subid) return subid
[ "def", "print_user", "(", "self", ",", "user", ")", ":", "status", "=", "\"active\"", "token", "=", "user", ".", "token", "if", "token", "in", "[", "'finished'", ",", "'revoked'", "]", ":", "status", "=", "token", "if", "token", "is", "None", ":", "t...
print a relational database user
[ "print", "a", "relational", "database", "user" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L81-L95
train
expfactory/expfactory
expfactory/database/relational.py
list_users
def list_users(self, user=None): '''list users, each having a model in the database. A headless experiment will use protected tokens, and interactive will be based on auto- incremented ids. ''' from expfactory.database.models import Participant participants = Participant.query.all() users = [] for user in participants: users.append(self.print_user(user)) return users
python
def list_users(self, user=None): '''list users, each having a model in the database. A headless experiment will use protected tokens, and interactive will be based on auto- incremented ids. ''' from expfactory.database.models import Participant participants = Participant.query.all() users = [] for user in participants: users.append(self.print_user(user)) return users
[ "def", "list_users", "(", "self", ",", "user", "=", "None", ")", ":", "from", "expfactory", ".", "database", ".", "models", "import", "Participant", "participants", "=", "Participant", ".", "query", ".", "all", "(", ")", "users", "=", "[", "]", "for", ...
list users, each having a model in the database. A headless experiment will use protected tokens, and interactive will be based on auto- incremented ids.
[ "list", "users", "each", "having", "a", "model", "in", "the", "database", ".", "A", "headless", "experiment", "will", "use", "protected", "tokens", "and", "interactive", "will", "be", "based", "on", "auto", "-", "incremented", "ids", "." ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L98-L108
train
expfactory/expfactory
expfactory/database/relational.py
generate_user
def generate_user(self): '''generate a new user in the database, still session based so we create a new identifier. This function is called from the users new entrypoint, and it assumes we want a user generated with a token. ''' token = str(uuid.uuid4()) return self.generate_subid(token=token, return_user=True)
python
def generate_user(self): '''generate a new user in the database, still session based so we create a new identifier. This function is called from the users new entrypoint, and it assumes we want a user generated with a token. ''' token = str(uuid.uuid4()) return self.generate_subid(token=token, return_user=True)
[ "def", "generate_user", "(", "self", ")", ":", "token", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "return", "self", ".", "generate_subid", "(", "token", "=", "token", ",", "return_user", "=", "True", ")" ]
generate a new user in the database, still session based so we create a new identifier. This function is called from the users new entrypoint, and it assumes we want a user generated with a token.
[ "generate", "a", "new", "user", "in", "the", "database", "still", "session", "based", "so", "we", "create", "a", "new", "identifier", ".", "This", "function", "is", "called", "from", "the", "users", "new", "entrypoint", "and", "it", "assumes", "we", "want"...
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L113-L119
train
expfactory/expfactory
expfactory/database/relational.py
finish_user
def finish_user(self, subid): '''finish user will remove a user's token, making the user entry not accesible if running in headless model''' p = self.revoke_token(subid) p.token = "finished" self.session.commit() return p
python
def finish_user(self, subid): '''finish user will remove a user's token, making the user entry not accesible if running in headless model''' p = self.revoke_token(subid) p.token = "finished" self.session.commit() return p
[ "def", "finish_user", "(", "self", ",", "subid", ")", ":", "p", "=", "self", ".", "revoke_token", "(", "subid", ")", "p", ".", "token", "=", "\"finished\"", "self", ".", "session", ".", "commit", "(", ")", "return", "p" ]
finish user will remove a user's token, making the user entry not accesible if running in headless model
[ "finish", "user", "will", "remove", "a", "user", "s", "token", "making", "the", "user", "entry", "not", "accesible", "if", "running", "in", "headless", "model" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L122-L129
train
expfactory/expfactory
expfactory/database/relational.py
restart_user
def restart_user(self, subid): '''restart a user, which means revoking and issuing a new token.''' p = self.revoke_token(subid) p = self.refresh_token(subid) return p
python
def restart_user(self, subid): '''restart a user, which means revoking and issuing a new token.''' p = self.revoke_token(subid) p = self.refresh_token(subid) return p
[ "def", "restart_user", "(", "self", ",", "subid", ")", ":", "p", "=", "self", ".", "revoke_token", "(", "subid", ")", "p", "=", "self", ".", "refresh_token", "(", "subid", ")", "return", "p" ]
restart a user, which means revoking and issuing a new token.
[ "restart", "a", "user", "which", "means", "revoking", "and", "issuing", "a", "new", "token", "." ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L132-L136
train
expfactory/expfactory
expfactory/database/relational.py
validate_token
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.token == token).first() if p is not None: if p.token.endswith(('finished','revoked')): p = None else: p = p.id return p
python
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.token == token).first() if p is not None: if p.token.endswith(('finished','revoked')): p = None else: p = p.id return p
[ "def", "validate_token", "(", "self", ",", "token", ")", ":", "from", "expfactory", ".", "database", ".", "models", "import", "Participant", "p", "=", "Participant", ".", "query", ".", "filter", "(", "Participant", ".", "token", "==", "token", ")", ".", ...
retrieve a subject based on a token. Valid means we return a participant invalid means we return None
[ "retrieve", "a", "subject", "based", "on", "a", "token", ".", "Valid", "means", "we", "return", "a", "participant", "invalid", "means", "we", "return", "None" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L142-L153
train
expfactory/expfactory
expfactory/database/relational.py
revoke_token
def revoke_token(self, subid): '''revoke a token by removing it. Is done at finish, and also available as a command line option''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = 'revoked' self.session.commit() return p
python
def revoke_token(self, subid): '''revoke a token by removing it. Is done at finish, and also available as a command line option''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = 'revoked' self.session.commit() return p
[ "def", "revoke_token", "(", "self", ",", "subid", ")", ":", "from", "expfactory", ".", "database", ".", "models", "import", "Participant", "p", "=", "Participant", ".", "query", ".", "filter", "(", "Participant", ".", "id", "==", "subid", ")", ".", "firs...
revoke a token by removing it. Is done at finish, and also available as a command line option
[ "revoke", "a", "token", "by", "removing", "it", ".", "Is", "done", "at", "finish", "and", "also", "available", "as", "a", "command", "line", "option" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L156-L164
train
expfactory/expfactory
expfactory/database/relational.py
refresh_token
def refresh_token(self, subid): '''refresh or generate a new token for a user''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = str(uuid.uuid4()) self.session.commit() return p
python
def refresh_token(self, subid): '''refresh or generate a new token for a user''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = str(uuid.uuid4()) self.session.commit() return p
[ "def", "refresh_token", "(", "self", ",", "subid", ")", ":", "from", "expfactory", ".", "database", ".", "models", "import", "Participant", "p", "=", "Participant", ".", "query", ".", "filter", "(", "Participant", ".", "id", "==", "subid", ")", ".", "fir...
refresh or generate a new token for a user
[ "refresh", "or", "generate", "a", "new", "token", "for", "a", "user" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L167-L174
train
expfactory/expfactory
expfactory/database/relational.py
save_data
def save_data(self,session, exp_id, content): '''save data will obtain the current subid from the session, and save it depending on the database type. Currently we just support flat files''' from expfactory.database.models import ( Participant, Result ) subid = session.get('subid') token = session.get('token') self.logger.info('Saving data for subid %s' % subid) # We only attempt save if there is a subject id, set at start if subid is not None: p = Participant.query.filter(Participant.id == subid).first() # better query here # Does if self.headless and p.token != token: self.logger.warning('%s attempting to use mismatched token [%s] skipping save' %(p.id, token)) elif self.headless and p.token.endswith(('finished','revoked')): self.logger.warning('%s attempting to use expired token [%s] skipping save' %(p.id, token)) else: # Preference is to save data under 'data', otherwise do all of it if "data" in content: content = content['data'] result = Result(data=content, exp_id=exp_id, participant_id=p.id) # check if changes from str/int # Create and save the result self.session.add(result) p.results.append(result) self.session.commit() self.logger.info("Save [participant] %s [result] %s" %(p, result))
python
def save_data(self,session, exp_id, content): '''save data will obtain the current subid from the session, and save it depending on the database type. Currently we just support flat files''' from expfactory.database.models import ( Participant, Result ) subid = session.get('subid') token = session.get('token') self.logger.info('Saving data for subid %s' % subid) # We only attempt save if there is a subject id, set at start if subid is not None: p = Participant.query.filter(Participant.id == subid).first() # better query here # Does if self.headless and p.token != token: self.logger.warning('%s attempting to use mismatched token [%s] skipping save' %(p.id, token)) elif self.headless and p.token.endswith(('finished','revoked')): self.logger.warning('%s attempting to use expired token [%s] skipping save' %(p.id, token)) else: # Preference is to save data under 'data', otherwise do all of it if "data" in content: content = content['data'] result = Result(data=content, exp_id=exp_id, participant_id=p.id) # check if changes from str/int # Create and save the result self.session.add(result) p.results.append(result) self.session.commit() self.logger.info("Save [participant] %s [result] %s" %(p, result))
[ "def", "save_data", "(", "self", ",", "session", ",", "exp_id", ",", "content", ")", ":", "from", "expfactory", ".", "database", ".", "models", "import", "(", "Participant", ",", "Result", ")", "subid", "=", "session", ".", "get", "(", "'subid'", ")", ...
save data will obtain the current subid from the session, and save it depending on the database type. Currently we just support flat files
[ "save", "data", "will", "obtain", "the", "current", "subid", "from", "the", "session", "and", "save", "it", "depending", "on", "the", "database", "type", ".", "Currently", "we", "just", "support", "flat", "files" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L177-L213
train
expfactory/expfactory
expfactory/database/relational.py
init_db
def init_db(self): '''initialize the database, with the default database path or custom with a format corresponding to the database type: Examples: sqlite:////scif/data/expfactory.db ''' # The user can provide a custom string if self.database is None: self.logger.error("You must provide a database url, exiting.") sys.exit(1) self.engine = create_engine(self.database, convert_unicode=True) self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) # Database Setup Base.query = self.session.query_property() # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import expfactory.database.models self.Base = Base self.Base.metadata.create_all(bind=self.engine)
python
def init_db(self): '''initialize the database, with the default database path or custom with a format corresponding to the database type: Examples: sqlite:////scif/data/expfactory.db ''' # The user can provide a custom string if self.database is None: self.logger.error("You must provide a database url, exiting.") sys.exit(1) self.engine = create_engine(self.database, convert_unicode=True) self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) # Database Setup Base.query = self.session.query_property() # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import expfactory.database.models self.Base = Base self.Base.metadata.create_all(bind=self.engine)
[ "def", "init_db", "(", "self", ")", ":", "# The user can provide a custom string", "if", "self", ".", "database", "is", "None", ":", "self", ".", "logger", ".", "error", "(", "\"You must provide a database url, exiting.\"", ")", "sys", ".", "exit", "(", "1", ")"...
initialize the database, with the default database path or custom with a format corresponding to the database type: Examples: sqlite:////scif/data/expfactory.db
[ "initialize", "the", "database", "with", "the", "default", "database", "path", "or", "custom", "with", "a", "format", "corresponding", "to", "the", "database", "type", ":" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/relational.py#L219-L246
train
d0c-s4vage/pfp
pfp/interp.py
LazyField
def LazyField(lookup_name, scope): """Super non-standard stuff here. Dynamically changing the base class using the scope and the lazy name when the class is instantiated. This works as long as the original base class is not directly inheriting from object (which we're not, since our original base class is fields.Field). """ def __init__(self, stream=None): base_cls = self._pfp__scope.get_id(self._pfp__lazy_name) self.__class__.__bases__ = (base_cls,) base_cls.__init__(self, stream) new_class = type(lookup_name + "_lazy", (fields.Field,), { "__init__" : __init__, "_pfp__scope" : scope, "_pfp__lazy_name" : lookup_name }) return new_class
python
def LazyField(lookup_name, scope): """Super non-standard stuff here. Dynamically changing the base class using the scope and the lazy name when the class is instantiated. This works as long as the original base class is not directly inheriting from object (which we're not, since our original base class is fields.Field). """ def __init__(self, stream=None): base_cls = self._pfp__scope.get_id(self._pfp__lazy_name) self.__class__.__bases__ = (base_cls,) base_cls.__init__(self, stream) new_class = type(lookup_name + "_lazy", (fields.Field,), { "__init__" : __init__, "_pfp__scope" : scope, "_pfp__lazy_name" : lookup_name }) return new_class
[ "def", "LazyField", "(", "lookup_name", ",", "scope", ")", ":", "def", "__init__", "(", "self", ",", "stream", "=", "None", ")", ":", "base_cls", "=", "self", ".", "_pfp__scope", ".", "get_id", "(", "self", ".", "_pfp__lazy_name", ")", "self", ".", "__...
Super non-standard stuff here. Dynamically changing the base class using the scope and the lazy name when the class is instantiated. This works as long as the original base class is not directly inheriting from object (which we're not, since our original base class is fields.Field).
[ "Super", "non", "-", "standard", "stuff", "here", ".", "Dynamically", "changing", "the", "base", "class", "using", "the", "scope", "and", "the", "lazy", "name", "when", "the", "class", "is", "instantiated", ".", "This", "works", "as", "long", "as", "the", ...
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L113-L130
train
d0c-s4vage/pfp
pfp/interp.py
PfpTypes._wrap_type_instantiation
def _wrap_type_instantiation(self, type_cls): """Wrap the creation of the type so that we can provide a null-stream to initialize it""" def wrapper(*args, **kwargs): # use args for struct arguments?? return type_cls(stream=self._null_stream) return wrapper
python
def _wrap_type_instantiation(self, type_cls): """Wrap the creation of the type so that we can provide a null-stream to initialize it""" def wrapper(*args, **kwargs): # use args for struct arguments?? return type_cls(stream=self._null_stream) return wrapper
[ "def", "_wrap_type_instantiation", "(", "self", ",", "type_cls", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# use args for struct arguments??", "return", "type_cls", "(", "stream", "=", "self", ".", "_null_stream", ")", ...
Wrap the creation of the type so that we can provide a null-stream to initialize it
[ "Wrap", "the", "creation", "of", "the", "type", "so", "that", "we", "can", "provide", "a", "null", "-", "stream", "to", "initialize", "it" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L241-L247
train
d0c-s4vage/pfp
pfp/interp.py
Scope.level
def level(self): """Return the current scope level """ res = len(self._scope_stack) if self._parent is not None: res += self._parent.level() return res
python
def level(self): """Return the current scope level """ res = len(self._scope_stack) if self._parent is not None: res += self._parent.level() return res
[ "def", "level", "(", "self", ")", ":", "res", "=", "len", "(", "self", ".", "_scope_stack", ")", "if", "self", ".", "_parent", "is", "not", "None", ":", "res", "+=", "self", ".", "_parent", ".", "level", "(", ")", "return", "res" ]
Return the current scope level
[ "Return", "the", "current", "scope", "level" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L273-L279
train
d0c-s4vage/pfp
pfp/interp.py
Scope.push
def push(self, new_scope=None): """Create a new scope :returns: TODO """ if new_scope is None: new_scope = { "types": {}, "vars": {} } self._curr_scope = new_scope self._dlog("pushing new scope, scope level = {}".format(self.level())) self._scope_stack.append(self._curr_scope)
python
def push(self, new_scope=None): """Create a new scope :returns: TODO """ if new_scope is None: new_scope = { "types": {}, "vars": {} } self._curr_scope = new_scope self._dlog("pushing new scope, scope level = {}".format(self.level())) self._scope_stack.append(self._curr_scope)
[ "def", "push", "(", "self", ",", "new_scope", "=", "None", ")", ":", "if", "new_scope", "is", "None", ":", "new_scope", "=", "{", "\"types\"", ":", "{", "}", ",", "\"vars\"", ":", "{", "}", "}", "self", ".", "_curr_scope", "=", "new_scope", "self", ...
Create a new scope :returns: TODO
[ "Create", "a", "new", "scope", ":", "returns", ":", "TODO" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L281-L293
train
d0c-s4vage/pfp
pfp/interp.py
Scope.clone
def clone(self): """Return a new Scope object that has the curr_scope pinned at the current one :returns: A new scope object """ self._dlog("cloning the stack") # TODO is this really necessary to create a brand new one? # I think it is... need to think about it more. # or... are we going to need ref counters and a global # scope object that allows a view into (or a snapshot of) # a specific scope stack? res = Scope(self._log) res._scope_stack = self._scope_stack res._curr_scope = self._curr_scope return res
python
def clone(self): """Return a new Scope object that has the curr_scope pinned at the current one :returns: A new scope object """ self._dlog("cloning the stack") # TODO is this really necessary to create a brand new one? # I think it is... need to think about it more. # or... are we going to need ref counters and a global # scope object that allows a view into (or a snapshot of) # a specific scope stack? res = Scope(self._log) res._scope_stack = self._scope_stack res._curr_scope = self._curr_scope return res
[ "def", "clone", "(", "self", ")", ":", "self", ".", "_dlog", "(", "\"cloning the stack\"", ")", "# TODO is this really necessary to create a brand new one?", "# I think it is... need to think about it more.", "# or... are we going to need ref counters and a global", "# scope object tha...
Return a new Scope object that has the curr_scope pinned at the current one :returns: A new scope object
[ "Return", "a", "new", "Scope", "object", "that", "has", "the", "curr_scope", "pinned", "at", "the", "current", "one", ":", "returns", ":", "A", "new", "scope", "object" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L295-L309
train
d0c-s4vage/pfp
pfp/interp.py
Scope.pop
def pop(self): """Leave the current scope :returns: TODO """ res = self._scope_stack.pop() self._dlog("popping scope, scope level = {}".format(self.level())) self._curr_scope = self._scope_stack[-1] return res
python
def pop(self): """Leave the current scope :returns: TODO """ res = self._scope_stack.pop() self._dlog("popping scope, scope level = {}".format(self.level())) self._curr_scope = self._scope_stack[-1] return res
[ "def", "pop", "(", "self", ")", ":", "res", "=", "self", ".", "_scope_stack", ".", "pop", "(", ")", "self", ".", "_dlog", "(", "\"popping scope, scope level = {}\"", ".", "format", "(", "self", ".", "level", "(", ")", ")", ")", "self", ".", "_curr_scop...
Leave the current scope :returns: TODO
[ "Leave", "the", "current", "scope", ":", "returns", ":", "TODO" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L311-L319
train
d0c-s4vage/pfp
pfp/interp.py
Scope.add_var
def add_var(self, field_name, field, root=False): """Add a var to the current scope (vars are fields that parse the input stream) :field_name: TODO :field: TODO :returns: TODO """ self._dlog("adding var '{}' (root={})".format(field_name, root)) # do both so it's not clobbered by intermediate values of the same name if root: self._scope_stack[0]["vars"][field_name] = field # TODO do we allow clobbering of vars??? self._curr_scope["vars"][field_name] = field
python
def add_var(self, field_name, field, root=False): """Add a var to the current scope (vars are fields that parse the input stream) :field_name: TODO :field: TODO :returns: TODO """ self._dlog("adding var '{}' (root={})".format(field_name, root)) # do both so it's not clobbered by intermediate values of the same name if root: self._scope_stack[0]["vars"][field_name] = field # TODO do we allow clobbering of vars??? self._curr_scope["vars"][field_name] = field
[ "def", "add_var", "(", "self", ",", "field_name", ",", "field", ",", "root", "=", "False", ")", ":", "self", ".", "_dlog", "(", "\"adding var '{}' (root={})\"", ".", "format", "(", "field_name", ",", "root", ")", ")", "# do both so it's not clobbered by intermed...
Add a var to the current scope (vars are fields that parse the input stream) :field_name: TODO :field: TODO :returns: TODO
[ "Add", "a", "var", "to", "the", "current", "scope", "(", "vars", "are", "fields", "that", "parse", "the", "input", "stream", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L321-L337
train
d0c-s4vage/pfp
pfp/interp.py
Scope.get_var
def get_var(self, name, recurse=True): """Return the first var of name ``name`` in the current scope stack (remember, vars are the ones that parse the input stream) :name: The name of the id :recurse: Whether parent scopes should also be searched (defaults to True) :returns: TODO """ self._dlog("getting var '{}'".format(name)) return self._search("vars", name, recurse)
python
def get_var(self, name, recurse=True): """Return the first var of name ``name`` in the current scope stack (remember, vars are the ones that parse the input stream) :name: The name of the id :recurse: Whether parent scopes should also be searched (defaults to True) :returns: TODO """ self._dlog("getting var '{}'".format(name)) return self._search("vars", name, recurse)
[ "def", "get_var", "(", "self", ",", "name", ",", "recurse", "=", "True", ")", ":", "self", ".", "_dlog", "(", "\"getting var '{}'\"", ".", "format", "(", "name", ")", ")", "return", "self", ".", "_search", "(", "\"vars\"", ",", "name", ",", "recurse", ...
Return the first var of name ``name`` in the current scope stack (remember, vars are the ones that parse the input stream) :name: The name of the id :recurse: Whether parent scopes should also be searched (defaults to True) :returns: TODO
[ "Return", "the", "first", "var", "of", "name", "name", "in", "the", "current", "scope", "stack", "(", "remember", "vars", "are", "the", "ones", "that", "parse", "the", "input", "stream", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L340-L351
train
d0c-s4vage/pfp
pfp/interp.py
Scope.add_local
def add_local(self, field_name, field): """Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None """ self._dlog("adding local '{}'".format(field_name)) field._pfp__name = field_name # TODO do we allow clobbering of locals??? self._curr_scope["vars"][field_name] = field
python
def add_local(self, field_name, field): """Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None """ self._dlog("adding local '{}'".format(field_name)) field._pfp__name = field_name # TODO do we allow clobbering of locals??? self._curr_scope["vars"][field_name] = field
[ "def", "add_local", "(", "self", ",", "field_name", ",", "field", ")", ":", "self", ".", "_dlog", "(", "\"adding local '{}'\"", ".", "format", "(", "field_name", ")", ")", "field", ".", "_pfp__name", "=", "field_name", "# TODO do we allow clobbering of locals???",...
Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None
[ "Add", "a", "local", "variable", "in", "the", "current", "scope" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L353-L364
train
d0c-s4vage/pfp
pfp/interp.py
Scope.get_local
def get_local(self, name, recurse=True): """Get the local field (search for it) from the scope stack. An alias for ``get_var`` :name: The name of the local field """ self._dlog("getting local '{}'".format(name)) return self._search("vars", name, recurse)
python
def get_local(self, name, recurse=True): """Get the local field (search for it) from the scope stack. An alias for ``get_var`` :name: The name of the local field """ self._dlog("getting local '{}'".format(name)) return self._search("vars", name, recurse)
[ "def", "get_local", "(", "self", ",", "name", ",", "recurse", "=", "True", ")", ":", "self", ".", "_dlog", "(", "\"getting local '{}'\"", ".", "format", "(", "name", ")", ")", "return", "self", ".", "_search", "(", "\"vars\"", ",", "name", ",", "recurs...
Get the local field (search for it) from the scope stack. An alias for ``get_var`` :name: The name of the local field
[ "Get", "the", "local", "field", "(", "search", "for", "it", ")", "from", "the", "scope", "stack", ".", "An", "alias", "for", "get_var" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L366-L373
train
d0c-s4vage/pfp
pfp/interp.py
Scope.add_type_struct_or_union
def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter """ self.add_type_class(name, StructUnionDef(name, interp, node))
python
def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter """ self.add_type_class(name, StructUnionDef(name, interp, node))
[ "def", "add_type_struct_or_union", "(", "self", ",", "name", ",", "interp", ",", "node", ")", ":", "self", ".", "add_type_class", "(", "name", ",", "StructUnionDef", "(", "name", ",", "interp", ",", "node", ")", ")" ]
Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter
[ "Store", "the", "node", "with", "the", "name", ".", "When", "it", "is", "instantiated", "the", "node", "itself", "will", "be", "handled", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L380-L388
train
d0c-s4vage/pfp
pfp/interp.py
Scope.add_type
def add_type(self, new_name, orig_names): """Record the typedefd name for orig_names. Resolve orig_names to their core names and save those. :new_name: TODO :orig_names: TODO :returns: TODO """ self._dlog("adding a type '{}'".format(new_name)) # TODO do we allow clobbering of types??? res = copy.copy(orig_names) resolved_names = self._resolve_name(res[-1]) if resolved_names is not None: res.pop() res += resolved_names self._curr_scope["types"][new_name] = res
python
def add_type(self, new_name, orig_names): """Record the typedefd name for orig_names. Resolve orig_names to their core names and save those. :new_name: TODO :orig_names: TODO :returns: TODO """ self._dlog("adding a type '{}'".format(new_name)) # TODO do we allow clobbering of types??? res = copy.copy(orig_names) resolved_names = self._resolve_name(res[-1]) if resolved_names is not None: res.pop() res += resolved_names self._curr_scope["types"][new_name] = res
[ "def", "add_type", "(", "self", ",", "new_name", ",", "orig_names", ")", ":", "self", ".", "_dlog", "(", "\"adding a type '{}'\"", ".", "format", "(", "new_name", ")", ")", "# TODO do we allow clobbering of types???", "res", "=", "copy", ".", "copy", "(", "ori...
Record the typedefd name for orig_names. Resolve orig_names to their core names and save those. :new_name: TODO :orig_names: TODO :returns: TODO
[ "Record", "the", "typedefd", "name", "for", "orig_names", ".", "Resolve", "orig_names", "to", "their", "core", "names", "and", "save", "those", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L390-L407
train
d0c-s4vage/pfp
pfp/interp.py
Scope.get_type
def get_type(self, name, recurse=True): """Get the names for the typename (created by typedef) :name: The typedef'd name to resolve :returns: An array of resolved names associated with the typedef'd name """ self._dlog("getting type '{}'".format(name)) return self._search("types", name, recurse)
python
def get_type(self, name, recurse=True): """Get the names for the typename (created by typedef) :name: The typedef'd name to resolve :returns: An array of resolved names associated with the typedef'd name """ self._dlog("getting type '{}'".format(name)) return self._search("types", name, recurse)
[ "def", "get_type", "(", "self", ",", "name", ",", "recurse", "=", "True", ")", ":", "self", ".", "_dlog", "(", "\"getting type '{}'\"", ".", "format", "(", "name", ")", ")", "return", "self", ".", "_search", "(", "\"types\"", ",", "name", ",", "recurse...
Get the names for the typename (created by typedef) :name: The typedef'd name to resolve :returns: An array of resolved names associated with the typedef'd name
[ "Get", "the", "names", "for", "the", "typename", "(", "created", "by", "typedef", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L409-L417
train
d0c-s4vage/pfp
pfp/interp.py
Scope.get_id
def get_id(self, name, recurse=True): """Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO """ self._dlog("getting id '{}'".format(name)) var = self._search("vars", name, recurse) return var
python
def get_id(self, name, recurse=True): """Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO """ self._dlog("getting id '{}'".format(name)) var = self._search("vars", name, recurse) return var
[ "def", "get_id", "(", "self", ",", "name", ",", "recurse", "=", "True", ")", ":", "self", ".", "_dlog", "(", "\"getting id '{}'\"", ".", "format", "(", "name", ")", ")", "var", "=", "self", ".", "_search", "(", "\"vars\"", ",", "name", ",", "recurse"...
Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO
[ "Get", "the", "first", "id", "matching", "name", ".", "Will", "either", "be", "a", "local", "or", "a", "var", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L419-L429
train
d0c-s4vage/pfp
pfp/interp.py
Scope._resolve_name
def _resolve_name(self, name): """TODO: Docstring for _resolve_names. :name: TODO :returns: TODO """ res = [name] while True: orig_names = self._search("types", name) if orig_names is not None: name = orig_names[-1] # pop off the typedefd name res.pop() # add back on the original names res += orig_names else: break return res
python
def _resolve_name(self, name): """TODO: Docstring for _resolve_names. :name: TODO :returns: TODO """ res = [name] while True: orig_names = self._search("types", name) if orig_names is not None: name = orig_names[-1] # pop off the typedefd name res.pop() # add back on the original names res += orig_names else: break return res
[ "def", "_resolve_name", "(", "self", ",", "name", ")", ":", "res", "=", "[", "name", "]", "while", "True", ":", "orig_names", "=", "self", ".", "_search", "(", "\"types\"", ",", "name", ")", "if", "orig_names", "is", "not", "None", ":", "name", "=", ...
TODO: Docstring for _resolve_names. :name: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_resolve_names", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L438-L457
train
d0c-s4vage/pfp
pfp/interp.py
Scope._search
def _search(self, category, name, recurse=True): """Search the scope stack for the name in the specified category (types/locals/vars). :category: the category to search in (locals/types/vars) :name: name to search for :returns: None if not found, the result of the found local/type/id """ idx = len(self._scope_stack) - 1 curr = self._curr_scope for scope in reversed(self._scope_stack): res = scope[category].get(name, None) if res is not None: return res if recurse and self._parent is not None: return self._parent._search(category, name, recurse) return None
python
def _search(self, category, name, recurse=True): """Search the scope stack for the name in the specified category (types/locals/vars). :category: the category to search in (locals/types/vars) :name: name to search for :returns: None if not found, the result of the found local/type/id """ idx = len(self._scope_stack) - 1 curr = self._curr_scope for scope in reversed(self._scope_stack): res = scope[category].get(name, None) if res is not None: return res if recurse and self._parent is not None: return self._parent._search(category, name, recurse) return None
[ "def", "_search", "(", "self", ",", "category", ",", "name", ",", "recurse", "=", "True", ")", ":", "idx", "=", "len", "(", "self", ".", "_scope_stack", ")", "-", "1", "curr", "=", "self", ".", "_curr_scope", "for", "scope", "in", "reversed", "(", ...
Search the scope stack for the name in the specified category (types/locals/vars). :category: the category to search in (locals/types/vars) :name: name to search for :returns: None if not found, the result of the found local/type/id
[ "Search", "the", "scope", "stack", "for", "the", "name", "in", "the", "specified", "category", "(", "types", "/", "locals", "/", "vars", ")", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L459-L477
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.add_native
def add_native(cls, name, func, ret, interp=None, send_interp=False): """Add the native python function ``func`` into the pfp interpreter with the name ``name`` and return value ``ret`` so that it can be called from within a template script. .. note:: The :any:`@native <pfp.native.native>` decorator exists to simplify this. All native functions must have the signature ``def func(params, ctxt, scope, stream, coord [,interp])``, optionally allowing an interpreter param if ``send_interp`` is ``True``. Example: The example below defines a function ``Sum`` using the ``add_native`` method. :: import pfp.fields from pfp.fields import PYVAL def native_sum(params, ctxt, scope, stream, coord): return PYVAL(params[0]) + PYVAL(params[1]) pfp.interp.PfpInterp.add_native("Sum", native_sum, pfp.fields.Int64) :param basestring name: The name the function will be exposed as in the interpreter. :param function func: The native python function that will be referenced. :param type(pfp.fields.Field) ret: The field class that the return value should be cast to. :param pfp.interp.PfpInterp interp: The specific pfp interpreter the function should be defined in. :param bool send_interp: If true, the current pfp interpreter will be added as an argument to the function. """ if interp is None: natives = cls._natives else: # the instance's natives natives = interp._natives natives[name] = functions.NativeFunction( name, func, ret, send_interp )
python
def add_native(cls, name, func, ret, interp=None, send_interp=False): """Add the native python function ``func`` into the pfp interpreter with the name ``name`` and return value ``ret`` so that it can be called from within a template script. .. note:: The :any:`@native <pfp.native.native>` decorator exists to simplify this. All native functions must have the signature ``def func(params, ctxt, scope, stream, coord [,interp])``, optionally allowing an interpreter param if ``send_interp`` is ``True``. Example: The example below defines a function ``Sum`` using the ``add_native`` method. :: import pfp.fields from pfp.fields import PYVAL def native_sum(params, ctxt, scope, stream, coord): return PYVAL(params[0]) + PYVAL(params[1]) pfp.interp.PfpInterp.add_native("Sum", native_sum, pfp.fields.Int64) :param basestring name: The name the function will be exposed as in the interpreter. :param function func: The native python function that will be referenced. :param type(pfp.fields.Field) ret: The field class that the return value should be cast to. :param pfp.interp.PfpInterp interp: The specific pfp interpreter the function should be defined in. :param bool send_interp: If true, the current pfp interpreter will be added as an argument to the function. """ if interp is None: natives = cls._natives else: # the instance's natives natives = interp._natives natives[name] = functions.NativeFunction( name, func, ret, send_interp )
[ "def", "add_native", "(", "cls", ",", "name", ",", "func", ",", "ret", ",", "interp", "=", "None", ",", "send_interp", "=", "False", ")", ":", "if", "interp", "is", "None", ":", "natives", "=", "cls", ".", "_natives", "else", ":", "# the instance's nat...
Add the native python function ``func`` into the pfp interpreter with the name ``name`` and return value ``ret`` so that it can be called from within a template script. .. note:: The :any:`@native <pfp.native.native>` decorator exists to simplify this. All native functions must have the signature ``def func(params, ctxt, scope, stream, coord [,interp])``, optionally allowing an interpreter param if ``send_interp`` is ``True``. Example: The example below defines a function ``Sum`` using the ``add_native`` method. :: import pfp.fields from pfp.fields import PYVAL def native_sum(params, ctxt, scope, stream, coord): return PYVAL(params[0]) + PYVAL(params[1]) pfp.interp.PfpInterp.add_native("Sum", native_sum, pfp.fields.Int64) :param basestring name: The name the function will be exposed as in the interpreter. :param function func: The native python function that will be referenced. :param type(pfp.fields.Field) ret: The field class that the return value should be cast to. :param pfp.interp.PfpInterp interp: The specific pfp interpreter the function should be defined in. :param bool send_interp: If true, the current pfp interpreter will be added as an argument to the function.
[ "Add", "the", "native", "python", "function", "func", "into", "the", "pfp", "interpreter", "with", "the", "name", "name", "and", "return", "value", "ret", "so", "that", "it", "can", "be", "called", "from", "within", "a", "template", "script", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L501-L538
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.define_natives
def define_natives(cls): """Define the native functions for PFP """ if len(cls._natives) > 0: return glob_pattern = os.path.join(os.path.dirname(__file__), "native", "*.py") for filename in glob.glob(glob_pattern): basename = os.path.basename(filename).replace(".py", "") if basename == "__init__": continue try: mod_base = __import__("pfp.native", globals(), locals(), fromlist=[basename]) except Exception as e: sys.stderr.write("cannot import native module {} at '{}'".format(basename, filename)) raise e continue mod = getattr(mod_base, basename) setattr(mod, "PYVAL", fields.get_value) setattr(mod, "PYSTR", fields.get_str)
python
def define_natives(cls): """Define the native functions for PFP """ if len(cls._natives) > 0: return glob_pattern = os.path.join(os.path.dirname(__file__), "native", "*.py") for filename in glob.glob(glob_pattern): basename = os.path.basename(filename).replace(".py", "") if basename == "__init__": continue try: mod_base = __import__("pfp.native", globals(), locals(), fromlist=[basename]) except Exception as e: sys.stderr.write("cannot import native module {} at '{}'".format(basename, filename)) raise e continue mod = getattr(mod_base, basename) setattr(mod, "PYVAL", fields.get_value) setattr(mod, "PYSTR", fields.get_str)
[ "def", "define_natives", "(", "cls", ")", ":", "if", "len", "(", "cls", ".", "_natives", ")", ">", "0", ":", "return", "glob_pattern", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"native...
Define the native functions for PFP
[ "Define", "the", "native", "functions", "for", "PFP" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L550-L571
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._dlog
def _dlog(self, msg, indent_increase=0): """log the message to the log""" self._log.debug("interp", msg, indent_increase, filename=self._orig_filename, coord=self._coord)
python
def _dlog(self, msg, indent_increase=0): """log the message to the log""" self._log.debug("interp", msg, indent_increase, filename=self._orig_filename, coord=self._coord)
[ "def", "_dlog", "(", "self", ",", "msg", ",", "indent_increase", "=", "0", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"interp\"", ",", "msg", ",", "indent_increase", ",", "filename", "=", "self", ".", "_orig_filename", ",", "coord", "=", "self...
log the message to the log
[ "log", "the", "message", "to", "the", "log" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L651-L653
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.parse
def parse(self, stream, template, predefines=True, orig_filename=None, keep_successful=False, printf=True): """Parse the data stream using the template (e.g. parse the 010 template and interpret the template using the stream as the data source). :stream: The input data stream :template: The template to parse the stream with :keep_successful: Return whatever was successfully parsed before an error. ``_pfp__error`` will contain the exception (if one was raised) :param bool printf: If ``False``, printfs will be noops (default=``True``) :returns: Pfp Dom """ self._dlog("parsing") self._printf = printf self._orig_filename = orig_filename self._stream = stream self._template = template self._template_lines = self._template.split("\n") self._ast = self._parse_string(template, predefines) self._dlog("parsed template into ast") res = self._run(keep_successful) return res
python
def parse(self, stream, template, predefines=True, orig_filename=None, keep_successful=False, printf=True): """Parse the data stream using the template (e.g. parse the 010 template and interpret the template using the stream as the data source). :stream: The input data stream :template: The template to parse the stream with :keep_successful: Return whatever was successfully parsed before an error. ``_pfp__error`` will contain the exception (if one was raised) :param bool printf: If ``False``, printfs will be noops (default=``True``) :returns: Pfp Dom """ self._dlog("parsing") self._printf = printf self._orig_filename = orig_filename self._stream = stream self._template = template self._template_lines = self._template.split("\n") self._ast = self._parse_string(template, predefines) self._dlog("parsed template into ast") res = self._run(keep_successful) return res
[ "def", "parse", "(", "self", ",", "stream", ",", "template", ",", "predefines", "=", "True", ",", "orig_filename", "=", "None", ",", "keep_successful", "=", "False", ",", "printf", "=", "True", ")", ":", "self", ".", "_dlog", "(", "\"parsing\"", ")", "...
Parse the data stream using the template (e.g. parse the 010 template and interpret the template using the stream as the data source). :stream: The input data stream :template: The template to parse the stream with :keep_successful: Return whatever was successfully parsed before an error. ``_pfp__error`` will contain the exception (if one was raised) :param bool printf: If ``False``, printfs will be noops (default=``True``) :returns: Pfp Dom
[ "Parse", "the", "data", "stream", "using", "the", "template", "(", "e", ".", "g", ".", "parse", "the", "010", "template", "and", "interpret", "the", "template", "using", "the", "stream", "as", "the", "data", "source", ")", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L659-L681
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.eval
def eval(self, statement, ctxt=None): """Eval a single statement (something returnable) """ self._no_debug = True statement = statement.strip() if not statement.endswith(";"): statement += ";" ast = self._parse_string(statement, predefines=False) self._dlog("evaluating statement: {}".format(statement)) try: res = None for child in ast.children(): res = self._handle_node(child, self._scope, self._ctxt, self._stream) return res except errors.InterpReturn as e: return e.value finally: self._no_debug = False
python
def eval(self, statement, ctxt=None): """Eval a single statement (something returnable) """ self._no_debug = True statement = statement.strip() if not statement.endswith(";"): statement += ";" ast = self._parse_string(statement, predefines=False) self._dlog("evaluating statement: {}".format(statement)) try: res = None for child in ast.children(): res = self._handle_node(child, self._scope, self._ctxt, self._stream) return res except errors.InterpReturn as e: return e.value finally: self._no_debug = False
[ "def", "eval", "(", "self", ",", "statement", ",", "ctxt", "=", "None", ")", ":", "self", ".", "_no_debug", "=", "True", "statement", "=", "statement", ".", "strip", "(", ")", "if", "not", "statement", ".", "endswith", "(", "\";\"", ")", ":", "statem...
Eval a single statement (something returnable)
[ "Eval", "a", "single", "statement", "(", "something", "returnable", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L698-L720
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.set_break
def set_break(self, break_type): """Set if the interpreter should break. :returns: TODO """ self._break_type = break_type self._break_level = self._scope.level()
python
def set_break(self, break_type): """Set if the interpreter should break. :returns: TODO """ self._break_type = break_type self._break_level = self._scope.level()
[ "def", "set_break", "(", "self", ",", "break_type", ")", ":", "self", ".", "_break_type", "=", "break_type", "self", ".", "_break_level", "=", "self", ".", "_scope", ".", "level", "(", ")" ]
Set if the interpreter should break. :returns: TODO
[ "Set", "if", "the", "interpreter", "should", "break", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L722-L728
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.get_curr_lines
def get_curr_lines(self): """Return the current line number in the template, as well as the surrounding source lines """ start = max(0, self._coord.line - 5) end = min(len(self._template_lines), self._coord.line + 4) lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)] return self._coord.line, lines
python
def get_curr_lines(self): """Return the current line number in the template, as well as the surrounding source lines """ start = max(0, self._coord.line - 5) end = min(len(self._template_lines), self._coord.line + 4) lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)] return self._coord.line, lines
[ "def", "get_curr_lines", "(", "self", ")", ":", "start", "=", "max", "(", "0", ",", "self", ".", "_coord", ".", "line", "-", "5", ")", "end", "=", "min", "(", "len", "(", "self", ".", "_template_lines", ")", ",", "self", ".", "_coord", ".", "line...
Return the current line number in the template, as well as the surrounding source lines
[ "Return", "the", "current", "line", "number", "in", "the", "template", "as", "well", "as", "the", "surrounding", "source", "lines" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L730-L738
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp.set_bitfield_padded
def set_bitfield_padded(self, val): """Set if the bitfield input/output stream should be padded :val: True/False :returns: None """ self._padded_bitfield = val self._stream.padded = val self._ctxt._pfp__padded_bitfield = val
python
def set_bitfield_padded(self, val): """Set if the bitfield input/output stream should be padded :val: True/False :returns: None """ self._padded_bitfield = val self._stream.padded = val self._ctxt._pfp__padded_bitfield = val
[ "def", "set_bitfield_padded", "(", "self", ",", "val", ")", ":", "self", ".", "_padded_bitfield", "=", "val", "self", ".", "_stream", ".", "padded", "=", "val", "self", ".", "_ctxt", ".", "_pfp__padded_bitfield", "=", "val" ]
Set if the bitfield input/output stream should be padded :val: True/False :returns: None
[ "Set", "if", "the", "bitfield", "input", "/", "output", "stream", "should", "be", "padded" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L740-L748
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._run
def _run(self, keep_successfull): """Interpret the parsed 010 AST :returns: PfpDom """ # example self._ast.show(): # FileAST: # Decl: data, [], [], [] # TypeDecl: data, [] # Struct: DATA # Decl: a, [], [], [] # TypeDecl: a, [] # IdentifierType: ['char'] # Decl: b, [], [], [] # TypeDecl: b, [] # IdentifierType: ['char'] # Decl: c, [], [], [] # TypeDecl: c, [] # IdentifierType: ['char'] # Decl: d, [], [], [] # TypeDecl: d, [] # IdentifierType: ['char'] self._dlog("interpreting template") try: # it is important to pass the stream in as the stream # may change (e.g. compressed data) res = self._handle_node(self._ast, None, None, self._stream) except errors.InterpReturn as e: # TODO handle exit/return codes (e.g. return -1) res = self._root except errors.InterpExit as e: res = self._root except Exception as e: if keep_successfull: # return the root and set _pfp__error res = self._root res._pfp__error = e else: exc_type, exc_obj, traceback = sys.exc_info() more_info = "\nException at {}:{}".format( self._orig_filename, self._coord.line ) six.reraise( errors.PfpError, errors.PfpError(exc_obj.__class__.__name__ + ": " + exc_obj.args[0] + more_info if len(exc_obj.args) > 0 else more_info), traceback ) # final drop-in after everything has executed if self._break_type != self.BREAK_NONE: self.debugger.cmdloop("execution finished") types = self.get_types() res._pfp__types = types return res
python
def _run(self, keep_successfull): """Interpret the parsed 010 AST :returns: PfpDom """ # example self._ast.show(): # FileAST: # Decl: data, [], [], [] # TypeDecl: data, [] # Struct: DATA # Decl: a, [], [], [] # TypeDecl: a, [] # IdentifierType: ['char'] # Decl: b, [], [], [] # TypeDecl: b, [] # IdentifierType: ['char'] # Decl: c, [], [], [] # TypeDecl: c, [] # IdentifierType: ['char'] # Decl: d, [], [], [] # TypeDecl: d, [] # IdentifierType: ['char'] self._dlog("interpreting template") try: # it is important to pass the stream in as the stream # may change (e.g. compressed data) res = self._handle_node(self._ast, None, None, self._stream) except errors.InterpReturn as e: # TODO handle exit/return codes (e.g. return -1) res = self._root except errors.InterpExit as e: res = self._root except Exception as e: if keep_successfull: # return the root and set _pfp__error res = self._root res._pfp__error = e else: exc_type, exc_obj, traceback = sys.exc_info() more_info = "\nException at {}:{}".format( self._orig_filename, self._coord.line ) six.reraise( errors.PfpError, errors.PfpError(exc_obj.__class__.__name__ + ": " + exc_obj.args[0] + more_info if len(exc_obj.args) > 0 else more_info), traceback ) # final drop-in after everything has executed if self._break_type != self.BREAK_NONE: self.debugger.cmdloop("execution finished") types = self.get_types() res._pfp__types = types return res
[ "def", "_run", "(", "self", ",", "keep_successfull", ")", ":", "# example self._ast.show():", "# FileAST:", "# Decl: data, [], [], []", "# TypeDecl: data, []", "# Struct: DATA", "# Decl: a, [], [], []", "# TypeDecl: a, []", "# ...
Interpret the parsed 010 AST :returns: PfpDom
[ "Interpret", "the", "parsed", "010", "AST", ":", "returns", ":", "PfpDom" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L823-L883
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_node
def _handle_node(self, node, scope=None, ctxt=None, stream=None): """Recursively handle nodes in the 010 AST :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ if scope is None: if self._scope is None: self._scope = scope = self._create_scope() else: scope = self._scope if ctxt is None and self._ctxt is not None: ctxt = self._ctxt else: self._ctxt = ctxt if type(node) is tuple: node = node[1] # TODO probably a better way to do this... # this occurs with if-statements that have a single statement # instead of a compound statement (no curly braces) elif type(node) is list and len(list(filter(lambda x: isinstance(x, AST.Node), node))) == len(node): node = AST.Compound( block_items=node, coord=node[0].coord ) return self._handle_node(node, scope, ctxt, stream) # need to check this so that debugger-eval'd statements # don't mess with the current state if not self._no_debug: self._coord = node.coord self._dlog("handling node type {}, line {}".format(node.__class__.__name__, node.coord.line if node.coord is not None else "?")) self._log.inc() breakable = self._node_is_breakable(node) if breakable and not self._no_debug and self._break_type != self.BREAK_NONE: # always break if self._break_type == self.BREAK_INTO: self._break_level = self._scope.level() self.debugger.cmdloop() # level <= _break_level elif self._break_type == self.BREAK_OVER: if self._scope.level() <= self._break_level: self._break_level = self._scope.level() self.debugger.cmdloop() else: pass if node.__class__ not in self._node_switch: raise errors.UnsupportedASTNode(node.coord, node.__class__.__name__) res = self._node_switch[node.__class__](node, scope, ctxt, stream) self._log.dec() return res
python
def _handle_node(self, node, scope=None, ctxt=None, stream=None): """Recursively handle nodes in the 010 AST :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ if scope is None: if self._scope is None: self._scope = scope = self._create_scope() else: scope = self._scope if ctxt is None and self._ctxt is not None: ctxt = self._ctxt else: self._ctxt = ctxt if type(node) is tuple: node = node[1] # TODO probably a better way to do this... # this occurs with if-statements that have a single statement # instead of a compound statement (no curly braces) elif type(node) is list and len(list(filter(lambda x: isinstance(x, AST.Node), node))) == len(node): node = AST.Compound( block_items=node, coord=node[0].coord ) return self._handle_node(node, scope, ctxt, stream) # need to check this so that debugger-eval'd statements # don't mess with the current state if not self._no_debug: self._coord = node.coord self._dlog("handling node type {}, line {}".format(node.__class__.__name__, node.coord.line if node.coord is not None else "?")) self._log.inc() breakable = self._node_is_breakable(node) if breakable and not self._no_debug and self._break_type != self.BREAK_NONE: # always break if self._break_type == self.BREAK_INTO: self._break_level = self._scope.level() self.debugger.cmdloop() # level <= _break_level elif self._break_type == self.BREAK_OVER: if self._scope.level() <= self._break_level: self._break_level = self._scope.level() self.debugger.cmdloop() else: pass if node.__class__ not in self._node_switch: raise errors.UnsupportedASTNode(node.coord, node.__class__.__name__) res = self._node_switch[node.__class__](node, scope, ctxt, stream) self._log.dec() return res
[ "def", "_handle_node", "(", "self", ",", "node", ",", "scope", "=", "None", ",", "ctxt", "=", "None", ",", "stream", "=", "None", ")", ":", "if", "scope", "is", "None", ":", "if", "self", ".", "_scope", "is", "None", ":", "self", ".", "_scope", "...
Recursively handle nodes in the 010 AST :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Recursively", "handle", "nodes", "in", "the", "010", "AST" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L885-L949
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_file_ast
def _handle_file_ast(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_file_ast. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._root = ctxt = fields.Dom(stream) ctxt._pfp__scope = scope self._root._pfp__name = "__root" self._root._pfp__interp = self self._dlog("handling file AST with {} children".format(len(node.children()))) for child in node.children(): self._handle_node(child, scope, ctxt, stream) ctxt._pfp__process_fields_metadata() return ctxt
python
def _handle_file_ast(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_file_ast. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._root = ctxt = fields.Dom(stream) ctxt._pfp__scope = scope self._root._pfp__name = "__root" self._root._pfp__interp = self self._dlog("handling file AST with {} children".format(len(node.children()))) for child in node.children(): self._handle_node(child, scope, ctxt, stream) ctxt._pfp__process_fields_metadata() return ctxt
[ "def", "_handle_file_ast", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_root", "=", "ctxt", "=", "fields", ".", "Dom", "(", "stream", ")", "ctxt", ".", "_pfp__scope", "=", "scope", "self", ".", "_root",...
TODO: Docstring for _handle_file_ast. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_file_ast", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L951-L972
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_cast
def _handle_cast(self, node, scope, ctxt, stream): """Handle cast nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling cast") to_type = self._handle_node(node.to_type, scope, ctxt, stream) val_to_cast = self._handle_node(node.expr, scope, ctxt, stream) res = to_type() res._pfp__set_value(val_to_cast) return res
python
def _handle_cast(self, node, scope, ctxt, stream): """Handle cast nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling cast") to_type = self._handle_node(node.to_type, scope, ctxt, stream) val_to_cast = self._handle_node(node.expr, scope, ctxt, stream) res = to_type() res._pfp__set_value(val_to_cast) return res
[ "def", "_handle_cast", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling cast\"", ")", "to_type", "=", "self", ".", "_handle_node", "(", "node", ".", "to_type", ",", "scope", ",", "ctxt...
Handle cast nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "cast", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L986-L1002
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_typename
def _handle_typename(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_typename :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling typename") return self._handle_node(node.type, scope, ctxt, stream)
python
def _handle_typename(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_typename :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling typename") return self._handle_node(node.type, scope, ctxt, stream)
[ "def", "_handle_typename", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling typename\"", ")", "return", "self", ".", "_handle_node", "(", "node", ".", "type", ",", "scope", ",", "ctxt", ...
TODO: Docstring for _handle_typename :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_typename" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1004-L1016
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._get_node_name
def _get_node_name(self, node): """Get the name of the node - check for node.name and node.type.declname. Not sure why the second one occurs exactly - it happens with declaring a new struct field with parameters""" res = getattr(node, "name", None) if res is None: return res if isinstance(res, AST.TypeDecl): return res.declname return res
python
def _get_node_name(self, node): """Get the name of the node - check for node.name and node.type.declname. Not sure why the second one occurs exactly - it happens with declaring a new struct field with parameters""" res = getattr(node, "name", None) if res is None: return res if isinstance(res, AST.TypeDecl): return res.declname return res
[ "def", "_get_node_name", "(", "self", ",", "node", ")", ":", "res", "=", "getattr", "(", "node", ",", "\"name\"", ",", "None", ")", "if", "res", "is", "None", ":", "return", "res", "if", "isinstance", "(", "res", ",", "AST", ".", "TypeDecl", ")", "...
Get the name of the node - check for node.name and node.type.declname. Not sure why the second one occurs exactly - it happens with declaring a new struct field with parameters
[ "Get", "the", "name", "of", "the", "node", "-", "check", "for", "node", ".", "name", "and", "node", ".", "type", ".", "declname", ".", "Not", "sure", "why", "the", "second", "one", "occurs", "exactly", "-", "it", "happens", "with", "declaring", "a", ...
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1018-L1030
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_decl
def _handle_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling decl") metadata_processor = None if node.metadata is not None: #metadata_info = self._handle_metadata(node, scope, ctxt, stream) def process_metadata(): metadata_info = self._handle_metadata(node, scope, ctxt, stream) return metadata_info metadata_processor = process_metadata field_name = self._get_node_name(node) field = self._handle_node(node.type, scope, ctxt, stream) bitsize = None bitfield_rw = None if getattr(node, "bitsize", None) is not None: bitsize = self._handle_node(node.bitsize, scope, ctxt, stream) has_prev = len(ctxt._pfp__children) > 0 bitfield_rw = None if has_prev: prev = ctxt._pfp__children[-1] # if it was a bitfield as well # TODO I don't think this will handle multiple bitfield groups in a row. # E.g. # char a: 8, b:8; # char c: 8, d:8; if ((self._padded_bitfield and prev.__class__.width == field.width) or not self._padded_bitfield) \ and prev.bitsize is not None and prev.bitfield_rw.reserve_bits(bitsize, stream): bitfield_rw = prev.bitfield_rw # either because there was no previous bitfield, or the previous was full if bitfield_rw is None: bitfield_rw = fields.BitfieldRW(self, field) bitfield_rw.reserve_bits(bitsize, stream) if getattr(node, "is_func_param", False): # we want to keep this as a class and not instantiate it # instantiation will be done in functions.ParamListDef.instantiate field = (field_name, field) # locals and consts still get a field instance, but DON'T parse the # stream! elif "local" in node.quals or "const" in node.quals: is_struct = issubclass(field, fields.Struct) if not isinstance(field, fields.Field) and not is_struct: field = field() scope.add_local(field_name, field) # this should only be able to be done with locals, right? # if not, move it to the bottom of the function if node.init is not None: val = self._handle_node(node.init, scope, ctxt, stream) if is_struct: field = val scope.add_local(field_name, field) else: field._pfp__set_value(val) if "const" in node.quals: field._pfp__freeze() field._pfp__interp = self elif isinstance(field, functions.Function): # eh, just add it as a local... # maybe the whole local/vars thinking needs to change... # and we should only have ONE map TODO field.name = field_name scope.add_local(field_name, field) elif field_name is not None: added_child = False # by this point, structs are already instantiated (they need to be # in order to set the new context) if not isinstance(field, fields.Field): if issubclass(field, fields.NumberBase): # use the default bitfield direction if self._bitfield_direction is self.BITFIELD_DIR_DEFAULT: bitfield_left_right = True if field.endian == fields.BIG_ENDIAN else False else: bitfield_left_right = (self._bitfield_direction is self.BITFIELD_DIR_LEFT_RIGHT) field = field( stream, bitsize=bitsize, metadata_processor=metadata_processor, bitfield_rw=bitfield_rw, bitfield_padded=self._padded_bitfield, bitfield_left_right=bitfield_left_right ) # TODO # for now if there's a struct inside of a union that is being # parsed when there's an error, the user will lose information # about how far the parsing got. Here we are explicitly checking for # adding structs and unions to a parent union. elif (issubclass(field, fields.Struct) or issubclass(field, fields.Union)) \ and not isinstance(ctxt, fields.Union) \ and hasattr(field, "_pfp__init"): # this is so that we can have all nested structs added to # the root DOM, even if there's an error in parsing the data. # If we didn't do this, any errors parsing the data would cause # the new struct to not be added to its parent, and the user would # not be able to see how far the script got field = field(stream, metadata_processor=metadata_processor, do_init=False) field._pfp__interp = self field_res = ctxt._pfp__add_child(field_name, field, stream) # when adding a new field to a struct/union/fileast, add it to the # root of the ctxt's scope so that it doesn't get lost by being declared # from within a function scope.add_var(field_name, field_res, root=True) field_res._pfp__interp = self field._pfp__init(stream) added_child = True else: field = field(stream, metadata_processor=metadata_processor) if not added_child: field._pfp__interp = self field_res = ctxt._pfp__add_child(field_name, field, stream) field_res._pfp__interp = self # when adding a new field to a struct/union/fileast, add it to the # root of the ctxt's scope so that it doesn't get lost by being declared # from within a function scope.add_var(field_name, field_res, root=True) # this shouldn't be used elsewhere, but should still be explicit with # this flag added_child = True # enums will get here. If there is no name, then no # field is being declared (but the enum values _will_ # get defined). E.g.: # enum <uchar blah { # BLAH1, # BLAH2, # BLAH3 # }; elif field_name is None: pass return field
python
def _handle_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling decl") metadata_processor = None if node.metadata is not None: #metadata_info = self._handle_metadata(node, scope, ctxt, stream) def process_metadata(): metadata_info = self._handle_metadata(node, scope, ctxt, stream) return metadata_info metadata_processor = process_metadata field_name = self._get_node_name(node) field = self._handle_node(node.type, scope, ctxt, stream) bitsize = None bitfield_rw = None if getattr(node, "bitsize", None) is not None: bitsize = self._handle_node(node.bitsize, scope, ctxt, stream) has_prev = len(ctxt._pfp__children) > 0 bitfield_rw = None if has_prev: prev = ctxt._pfp__children[-1] # if it was a bitfield as well # TODO I don't think this will handle multiple bitfield groups in a row. # E.g. # char a: 8, b:8; # char c: 8, d:8; if ((self._padded_bitfield and prev.__class__.width == field.width) or not self._padded_bitfield) \ and prev.bitsize is not None and prev.bitfield_rw.reserve_bits(bitsize, stream): bitfield_rw = prev.bitfield_rw # either because there was no previous bitfield, or the previous was full if bitfield_rw is None: bitfield_rw = fields.BitfieldRW(self, field) bitfield_rw.reserve_bits(bitsize, stream) if getattr(node, "is_func_param", False): # we want to keep this as a class and not instantiate it # instantiation will be done in functions.ParamListDef.instantiate field = (field_name, field) # locals and consts still get a field instance, but DON'T parse the # stream! elif "local" in node.quals or "const" in node.quals: is_struct = issubclass(field, fields.Struct) if not isinstance(field, fields.Field) and not is_struct: field = field() scope.add_local(field_name, field) # this should only be able to be done with locals, right? # if not, move it to the bottom of the function if node.init is not None: val = self._handle_node(node.init, scope, ctxt, stream) if is_struct: field = val scope.add_local(field_name, field) else: field._pfp__set_value(val) if "const" in node.quals: field._pfp__freeze() field._pfp__interp = self elif isinstance(field, functions.Function): # eh, just add it as a local... # maybe the whole local/vars thinking needs to change... # and we should only have ONE map TODO field.name = field_name scope.add_local(field_name, field) elif field_name is not None: added_child = False # by this point, structs are already instantiated (they need to be # in order to set the new context) if not isinstance(field, fields.Field): if issubclass(field, fields.NumberBase): # use the default bitfield direction if self._bitfield_direction is self.BITFIELD_DIR_DEFAULT: bitfield_left_right = True if field.endian == fields.BIG_ENDIAN else False else: bitfield_left_right = (self._bitfield_direction is self.BITFIELD_DIR_LEFT_RIGHT) field = field( stream, bitsize=bitsize, metadata_processor=metadata_processor, bitfield_rw=bitfield_rw, bitfield_padded=self._padded_bitfield, bitfield_left_right=bitfield_left_right ) # TODO # for now if there's a struct inside of a union that is being # parsed when there's an error, the user will lose information # about how far the parsing got. Here we are explicitly checking for # adding structs and unions to a parent union. elif (issubclass(field, fields.Struct) or issubclass(field, fields.Union)) \ and not isinstance(ctxt, fields.Union) \ and hasattr(field, "_pfp__init"): # this is so that we can have all nested structs added to # the root DOM, even if there's an error in parsing the data. # If we didn't do this, any errors parsing the data would cause # the new struct to not be added to its parent, and the user would # not be able to see how far the script got field = field(stream, metadata_processor=metadata_processor, do_init=False) field._pfp__interp = self field_res = ctxt._pfp__add_child(field_name, field, stream) # when adding a new field to a struct/union/fileast, add it to the # root of the ctxt's scope so that it doesn't get lost by being declared # from within a function scope.add_var(field_name, field_res, root=True) field_res._pfp__interp = self field._pfp__init(stream) added_child = True else: field = field(stream, metadata_processor=metadata_processor) if not added_child: field._pfp__interp = self field_res = ctxt._pfp__add_child(field_name, field, stream) field_res._pfp__interp = self # when adding a new field to a struct/union/fileast, add it to the # root of the ctxt's scope so that it doesn't get lost by being declared # from within a function scope.add_var(field_name, field_res, root=True) # this shouldn't be used elsewhere, but should still be explicit with # this flag added_child = True # enums will get here. If there is no name, then no # field is being declared (but the enum values _will_ # get defined). E.g.: # enum <uchar blah { # BLAH1, # BLAH2, # BLAH3 # }; elif field_name is None: pass return field
[ "def", "_handle_decl", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling decl\"", ")", "metadata_processor", "=", "None", "if", "node", ".", "metadata", "is", "not", "None", ":", "#metada...
TODO: Docstring for _handle_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_decl", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1032-L1189
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_metadata
def _handle_metadata(self, node, scope, ctxt, stream): """Handle metadata for the node """ self._dlog("handling node metadata {}".format(node.metadata.keyvals)) keyvals = node.metadata.keyvals metadata_info = [] if "watch" in node.metadata.keyvals or "update" in keyvals: metadata_info.append( self._handle_watch_metadata(node, scope, ctxt, stream) ) if "packtype" in node.metadata.keyvals or "packer" in keyvals: metadata_info.append( self._handle_packed_metadata(node, scope, ctxt, stream) ) return metadata_info
python
def _handle_metadata(self, node, scope, ctxt, stream): """Handle metadata for the node """ self._dlog("handling node metadata {}".format(node.metadata.keyvals)) keyvals = node.metadata.keyvals metadata_info = [] if "watch" in node.metadata.keyvals or "update" in keyvals: metadata_info.append( self._handle_watch_metadata(node, scope, ctxt, stream) ) if "packtype" in node.metadata.keyvals or "packer" in keyvals: metadata_info.append( self._handle_packed_metadata(node, scope, ctxt, stream) ) return metadata_info
[ "def", "_handle_metadata", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling node metadata {}\"", ".", "format", "(", "node", ".", "metadata", ".", "keyvals", ")", ")", "keyvals", "=", "n...
Handle metadata for the node
[ "Handle", "metadata", "for", "the", "node" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1191-L1210
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_watch_metadata
def _handle_watch_metadata(self, node, scope, ctxt, stream): """Handle watch vars for fields """ keyvals = node.metadata.keyvals if "watch" not in keyvals: raise errors.PfpError("Packed fields require a packer function set") if "update" not in keyvals: raise errors.PfpError("Packed fields require a packer function set") watch_field_name = keyvals["watch"] update_func_name = keyvals["update"] watch_fields = list(map(lambda x: self.eval(x.strip()), watch_field_name.split(";"))) update_func = scope.get_id(update_func_name) return { "type": "watch", "watch_fields": watch_fields, "update_func": update_func, "func_call_info": (ctxt, scope, stream, self, self._coord) }
python
def _handle_watch_metadata(self, node, scope, ctxt, stream): """Handle watch vars for fields """ keyvals = node.metadata.keyvals if "watch" not in keyvals: raise errors.PfpError("Packed fields require a packer function set") if "update" not in keyvals: raise errors.PfpError("Packed fields require a packer function set") watch_field_name = keyvals["watch"] update_func_name = keyvals["update"] watch_fields = list(map(lambda x: self.eval(x.strip()), watch_field_name.split(";"))) update_func = scope.get_id(update_func_name) return { "type": "watch", "watch_fields": watch_fields, "update_func": update_func, "func_call_info": (ctxt, scope, stream, self, self._coord) }
[ "def", "_handle_watch_metadata", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "keyvals", "=", "node", ".", "metadata", ".", "keyvals", "if", "\"watch\"", "not", "in", "keyvals", ":", "raise", "errors", ".", "PfpError", "(...
Handle watch vars for fields
[ "Handle", "watch", "vars", "for", "fields" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1216-L1236
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_packed_metadata
def _handle_packed_metadata(self, node, scope, ctxt, stream): """Handle packed metadata """ keyvals = node.metadata.keyvals if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals): raise errors.PfpError("Packed fields require a packer function to be set or pack and unpack functions to be set") if "packtype" not in keyvals: raise errors.PfpError("Packed fields require a packtype to be set") args_ = {} if "packer" in keyvals: packer_func_name = keyvals["packer"] packer_func = scope.get_id(packer_func_name) args_["packer"] = packer_func elif "pack" in keyvals and "unpack" in keyvals: pack_func = scope.get_id(keyvals["pack"]) unpack_func = scope.get_id(keyvals["unpack"]) args_["pack"] = pack_func args_["unpack"] = unpack_func packtype_cls_name = keyvals["packtype"] packtype_cls = scope.get_type(packtype_cls_name) args_["pack_type"] = packtype_cls args_["type"] = "packed" args_["func_call_info"] = (ctxt, scope, stream, self, self._coord) return args_
python
def _handle_packed_metadata(self, node, scope, ctxt, stream): """Handle packed metadata """ keyvals = node.metadata.keyvals if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals): raise errors.PfpError("Packed fields require a packer function to be set or pack and unpack functions to be set") if "packtype" not in keyvals: raise errors.PfpError("Packed fields require a packtype to be set") args_ = {} if "packer" in keyvals: packer_func_name = keyvals["packer"] packer_func = scope.get_id(packer_func_name) args_["packer"] = packer_func elif "pack" in keyvals and "unpack" in keyvals: pack_func = scope.get_id(keyvals["pack"]) unpack_func = scope.get_id(keyvals["unpack"]) args_["pack"] = pack_func args_["unpack"] = unpack_func packtype_cls_name = keyvals["packtype"] packtype_cls = scope.get_type(packtype_cls_name) args_["pack_type"] = packtype_cls args_["type"] = "packed" args_["func_call_info"] = (ctxt, scope, stream, self, self._coord) return args_
[ "def", "_handle_packed_metadata", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "keyvals", "=", "node", ".", "metadata", ".", "keyvals", "if", "\"packer\"", "not", "in", "keyvals", "and", "(", "\"pack\"", "not", "in", "key...
Handle packed metadata
[ "Handle", "packed", "metadata" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1238-L1264
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_byref_decl
def _handle_byref_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_byref_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling byref decl") field = self._handle_node(node.type.type, scope, ctxt, stream) # this will not really be used (maybe except for introspection) # with byref function params # see issue #35 - we need to wrap the field cls so that the byref # doesn't permanently stay on the class field = functions.ParamClsWrapper(field) field.byref = True return field
python
def _handle_byref_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_byref_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling byref decl") field = self._handle_node(node.type.type, scope, ctxt, stream) # this will not really be used (maybe except for introspection) # with byref function params # see issue #35 - we need to wrap the field cls so that the byref # doesn't permanently stay on the class field = functions.ParamClsWrapper(field) field.byref = True return field
[ "def", "_handle_byref_decl", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling byref decl\"", ")", "field", "=", "self", ".", "_handle_node", "(", "node", ".", "type", ".", "type", ",", ...
TODO: Docstring for _handle_byref_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_byref_decl", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1266-L1285
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_type_decl
def _handle_type_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_type_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling type decl") decl = self._handle_node(node.type, scope, ctxt, stream) return decl
python
def _handle_type_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_type_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling type decl") decl = self._handle_node(node.type, scope, ctxt, stream) return decl
[ "def", "_handle_type_decl", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling type decl\"", ")", "decl", "=", "self", ".", "_handle_node", "(", "node", ".", "type", ",", "scope", ",", "...
TODO: Docstring for _handle_type_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_type_decl", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1287-L1299
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_struct_ref
def _handle_struct_ref(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_struct_ref. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling struct ref") # name # field struct = self._handle_node(node.name, scope, ctxt, stream) try: sub_field = getattr(struct, node.field.name) except AttributeError as e: # should be able to access implicit array items by index OR # access the last one's members directly without index # # E.g.: # # local int total_length = 0; # while(!FEof()) { # HEADER header; # total_length += header.length; # } if isinstance(struct, fields.Array) and struct.implicit: last_item = struct[-1] sub_field = getattr(last_item, node.field.name) else: raise return sub_field
python
def _handle_struct_ref(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_struct_ref. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling struct ref") # name # field struct = self._handle_node(node.name, scope, ctxt, stream) try: sub_field = getattr(struct, node.field.name) except AttributeError as e: # should be able to access implicit array items by index OR # access the last one's members directly without index # # E.g.: # # local int total_length = 0; # while(!FEof()) { # HEADER header; # total_length += header.length; # } if isinstance(struct, fields.Array) and struct.implicit: last_item = struct[-1] sub_field = getattr(last_item, node.field.name) else: raise return sub_field
[ "def", "_handle_struct_ref", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling struct ref\"", ")", "# name", "# field", "struct", "=", "self", ".", "_handle_node", "(", "node", ".", "name",...
TODO: Docstring for _handle_struct_ref. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_struct_ref", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1301-L1336
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_union
def _handle_union(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_union. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling union") union_cls = StructUnionDef("union", self, node) return union_cls
python
def _handle_union(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_union. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling union") union_cls = StructUnionDef("union", self, node) return union_cls
[ "def", "_handle_union", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling union\"", ")", "union_cls", "=", "StructUnionDef", "(", "\"union\"", ",", "self", ",", "node", ")", "return", "un...
TODO: Docstring for _handle_union. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_union", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1338-L1351
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_init_list
def _handle_init_list(self, node, scope, ctxt, stream): """Handle InitList nodes (e.g. when initializing a struct) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling init list") res = [] for _,init_child in node.children(): init_field = self._handle_node(init_child, scope, ctxt, stream) res.append(init_field) return res
python
def _handle_init_list(self, node, scope, ctxt, stream): """Handle InitList nodes (e.g. when initializing a struct) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling init list") res = [] for _,init_child in node.children(): init_field = self._handle_node(init_child, scope, ctxt, stream) res.append(init_field) return res
[ "def", "_handle_init_list", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling init list\"", ")", "res", "=", "[", "]", "for", "_", ",", "init_child", "in", "node", ".", "children", "(",...
Handle InitList nodes (e.g. when initializing a struct) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "InitList", "nodes", "(", "e", ".", "g", ".", "when", "initializing", "a", "struct", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1369-L1384
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_struct_call_type_decl
def _handle_struct_call_type_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_struct_call_type_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling struct with parameters") struct_cls = self._handle_node(node.type, scope, ctxt, stream) struct_args = self._handle_node(node.args, scope, ctxt, stream) res = StructDeclWithParams(scope, struct_cls, struct_args) return res
python
def _handle_struct_call_type_decl(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_struct_call_type_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling struct with parameters") struct_cls = self._handle_node(node.type, scope, ctxt, stream) struct_args = self._handle_node(node.args, scope, ctxt, stream) res = StructDeclWithParams(scope, struct_cls, struct_args) return res
[ "def", "_handle_struct_call_type_decl", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling struct with parameters\"", ")", "struct_cls", "=", "self", ".", "_handle_node", "(", "node", ".", "type...
TODO: Docstring for _handle_struct_call_type_decl. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_struct_call_type_decl", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1386-L1402
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_struct
def _handle_struct(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_struct. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling struct") if node.args is not None: for param in node.args.params: param.is_func_param = True # it's actually being defined if node.decls is not None: struct_cls = StructUnionDef("struct", self, node) if node.name is not None: scope.add_type_class(node.name, struct_cls) return struct_cls # it's declaring a struct field. E.g. # struct IFD subDir; else: return scope.get_type(node.name)
python
def _handle_struct(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_struct. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling struct") if node.args is not None: for param in node.args.params: param.is_func_param = True # it's actually being defined if node.decls is not None: struct_cls = StructUnionDef("struct", self, node) if node.name is not None: scope.add_type_class(node.name, struct_cls) return struct_cls # it's declaring a struct field. E.g. # struct IFD subDir; else: return scope.get_type(node.name)
[ "def", "_handle_struct", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling struct\"", ")", "if", "node", ".", "args", "is", "not", "None", ":", "for", "param", "in", "node", ".", "arg...
TODO: Docstring for _handle_struct. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_struct", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1404-L1432
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_identifier_type
def _handle_identifier_type(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_identifier_type. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling identifier") cls = self._resolve_to_field_class(node.names, scope) return cls
python
def _handle_identifier_type(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_identifier_type. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling identifier") cls = self._resolve_to_field_class(node.names, scope) return cls
[ "def", "_handle_identifier_type", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling identifier\"", ")", "cls", "=", "self", ".", "_resolve_to_field_class", "(", "node", ".", "names", ",", "...
TODO: Docstring for _handle_identifier_type. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_identifier_type", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1454-L1467
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_typedef
def _handle_typedef(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_typedef. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ is_union_or_struct = (node.type.type.__class__ in [AST.Union, AST.Struct]) is_enum = (node.type.type.__class__ is AST.Enum) if is_union_or_struct: self._dlog("handling typedef struct/union '{}'".format(node.name)) scope.add_type_struct_or_union(node.name, self, node.type.type) elif is_enum: enum_cls = self._handle_node(node.type, scope, ctxt, stream) scope.add_type_class(node.name, enum_cls) elif isinstance(node.type, AST.ArrayDecl): # this does not parse data, just creates the ArrayDecl class array_cls = self._handle_node(node.type, scope, ctxt, stream) scope.add_type_class(node.name, array_cls) else: names = node.type.type.names self._dlog("handling typedef '{}' ({})".format(node.name, names)) # don't actually handle the TypeDecl and Identifier nodes, # just directly add the types. Example structure: # # Typedef: BLAH, [], ['typedef'] # TypeDecl: BLAH, [] # IdentifierType: ['unsigned', 'char'] # scope.add_type(node.name, names)
python
def _handle_typedef(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_typedef. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ is_union_or_struct = (node.type.type.__class__ in [AST.Union, AST.Struct]) is_enum = (node.type.type.__class__ is AST.Enum) if is_union_or_struct: self._dlog("handling typedef struct/union '{}'".format(node.name)) scope.add_type_struct_or_union(node.name, self, node.type.type) elif is_enum: enum_cls = self._handle_node(node.type, scope, ctxt, stream) scope.add_type_class(node.name, enum_cls) elif isinstance(node.type, AST.ArrayDecl): # this does not parse data, just creates the ArrayDecl class array_cls = self._handle_node(node.type, scope, ctxt, stream) scope.add_type_class(node.name, array_cls) else: names = node.type.type.names self._dlog("handling typedef '{}' ({})".format(node.name, names)) # don't actually handle the TypeDecl and Identifier nodes, # just directly add the types. Example structure: # # Typedef: BLAH, [], ['typedef'] # TypeDecl: BLAH, [] # IdentifierType: ['unsigned', 'char'] # scope.add_type(node.name, names)
[ "def", "_handle_typedef", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "is_union_or_struct", "=", "(", "node", ".", "type", ".", "type", ".", "__class__", "in", "[", "AST", ".", "Union", ",", "AST", ".", "Struct", "]"...
TODO: Docstring for _handle_typedef. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_typedef", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1469-L1503
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._str_to_int
def _str_to_int(self, string): """Check for the hex """ string = string.lower() if string.endswith("l"): string = string[:-1] if string.lower().startswith("0x"): # should always match match = re.match(r'0[xX]([a-fA-F0-9]+)', string) return int(match.group(1), 0x10) else: return int(string)
python
def _str_to_int(self, string): """Check for the hex """ string = string.lower() if string.endswith("l"): string = string[:-1] if string.lower().startswith("0x"): # should always match match = re.match(r'0[xX]([a-fA-F0-9]+)', string) return int(match.group(1), 0x10) else: return int(string)
[ "def", "_str_to_int", "(", "self", ",", "string", ")", ":", "string", "=", "string", ".", "lower", "(", ")", "if", "string", ".", "endswith", "(", "\"l\"", ")", ":", "string", "=", "string", "[", ":", "-", "1", "]", "if", "string", ".", "lower", ...
Check for the hex
[ "Check", "for", "the", "hex" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1505-L1516
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_constant
def _handle_constant(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_constant. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling constant type {}".format(node.type)) switch = { "int": (self._str_to_int, self._choose_const_int_class), "long": (self._str_to_int, self._choose_const_int_class), # TODO this isn't quite right, but py010parser wouldn't have # parsed it if it wasn't correct... "float": (lambda x: float(x.lower().replace("f", "")), fields.Float), "double": (float, fields.Double), # cut out the quotes "char": (lambda x: ord(utils.string_escape(x[1:-1])), fields.Char), # TODO should this be unicode?? will probably bite me later... # cut out the quotes "string": (lambda x: str(utils.string_escape(x[1:-1])), fields.String) } if node.type in switch: #return switch[node.type](node.value) conversion,field_cls = switch[node.type] val = conversion(node.value) if hasattr(field_cls, "__call__") and not type(field_cls) is type: field_cls = field_cls(val) field = field_cls() field._pfp__set_value(val) return field raise UnsupportedConstantType(node.coord, node.type)
python
def _handle_constant(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_constant. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling constant type {}".format(node.type)) switch = { "int": (self._str_to_int, self._choose_const_int_class), "long": (self._str_to_int, self._choose_const_int_class), # TODO this isn't quite right, but py010parser wouldn't have # parsed it if it wasn't correct... "float": (lambda x: float(x.lower().replace("f", "")), fields.Float), "double": (float, fields.Double), # cut out the quotes "char": (lambda x: ord(utils.string_escape(x[1:-1])), fields.Char), # TODO should this be unicode?? will probably bite me later... # cut out the quotes "string": (lambda x: str(utils.string_escape(x[1:-1])), fields.String) } if node.type in switch: #return switch[node.type](node.value) conversion,field_cls = switch[node.type] val = conversion(node.value) if hasattr(field_cls, "__call__") and not type(field_cls) is type: field_cls = field_cls(val) field = field_cls() field._pfp__set_value(val) return field raise UnsupportedConstantType(node.coord, node.type)
[ "def", "_handle_constant", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling constant type {}\"", ".", "format", "(", "node", ".", "type", ")", ")", "switch", "=", "{", "\"int\"", ":", ...
TODO: Docstring for _handle_constant. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_constant", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1528-L1567
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_binary_op
def _handle_binary_op(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_binary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling binary operation {}".format(node.op)) switch = { "+": lambda x,y: x+y, "-": lambda x,y: x-y, "*": lambda x,y: x*y, "/": lambda x,y: x/y, "|": lambda x,y: x|y, "^": lambda x,y: x^y, "&": lambda x,y: x&y, "%": lambda x,y: x%y, ">": lambda x,y: x>y, "<": lambda x,y: x<y, "||": lambda x,y: x or y, ">=": lambda x,y: x>=y, "<=": lambda x,y: x<=y, "==": lambda x,y: x == y, "!=": lambda x,y: x != y, "&&": lambda x,y: x and y, ">>": lambda x,y: x >> y, "<<": lambda x,y: x << y, } left_val = self._handle_node(node.left, scope, ctxt, stream) right_val = self._handle_node(node.right, scope, ctxt, stream) if node.op not in switch: raise errors.UnsupportedBinaryOperator(node.coord, node.op) res = switch[node.op](left_val, right_val) if type(res) is bool: new_res = fields.Int() if res: new_res._pfp__set_value(1) else: new_res._pfp__set_value(0) res = new_res return res
python
def _handle_binary_op(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_binary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling binary operation {}".format(node.op)) switch = { "+": lambda x,y: x+y, "-": lambda x,y: x-y, "*": lambda x,y: x*y, "/": lambda x,y: x/y, "|": lambda x,y: x|y, "^": lambda x,y: x^y, "&": lambda x,y: x&y, "%": lambda x,y: x%y, ">": lambda x,y: x>y, "<": lambda x,y: x<y, "||": lambda x,y: x or y, ">=": lambda x,y: x>=y, "<=": lambda x,y: x<=y, "==": lambda x,y: x == y, "!=": lambda x,y: x != y, "&&": lambda x,y: x and y, ">>": lambda x,y: x >> y, "<<": lambda x,y: x << y, } left_val = self._handle_node(node.left, scope, ctxt, stream) right_val = self._handle_node(node.right, scope, ctxt, stream) if node.op not in switch: raise errors.UnsupportedBinaryOperator(node.coord, node.op) res = switch[node.op](left_val, right_val) if type(res) is bool: new_res = fields.Int() if res: new_res._pfp__set_value(1) else: new_res._pfp__set_value(0) res = new_res return res
[ "def", "_handle_binary_op", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling binary operation {}\"", ".", "format", "(", "node", ".", "op", ")", ")", "switch", "=", "{", "\"+\"", ":", ...
TODO: Docstring for _handle_binary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_binary_op", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1569-L1617
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_unary_op
def _handle_unary_op(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_unary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling unary op {}".format(node.op)) special_switch = { "parentof" : self._handle_parentof, "exists" : self._handle_exists, "function_exists" : self._handle_function_exists, "p++" : self._handle_post_plus_plus, "p--" : self._handle_post_minus_minus, } switch = { # for ++i and --i "++": lambda x,v: x.__iadd__(1), "--": lambda x,v: x.__isub__(1), "~": lambda x,v: ~x, "!": lambda x,v: not x, "-": lambda x,v: -x, "sizeof": lambda x,v: (fields.UInt64()+x._pfp__width()), "startof": lambda x,v: (fields.UInt64()+x._pfp__offset), } if node.op not in switch and node.op not in special_switch: raise errors.UnsupportedUnaryOperator(node.coord, node.op) if node.op in special_switch: return special_switch[node.op](node, scope, ctxt, stream) field = self._handle_node(node.expr, scope, ctxt, stream) if type(field) is type: field = field() res = switch[node.op](field, 1) if type(res) is bool: new_res = field.__class__() new_res._pfp__set_value(1 if res == True else 0) res = new_res return res
python
def _handle_unary_op(self, node, scope, ctxt, stream): """TODO: Docstring for _handle_unary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling unary op {}".format(node.op)) special_switch = { "parentof" : self._handle_parentof, "exists" : self._handle_exists, "function_exists" : self._handle_function_exists, "p++" : self._handle_post_plus_plus, "p--" : self._handle_post_minus_minus, } switch = { # for ++i and --i "++": lambda x,v: x.__iadd__(1), "--": lambda x,v: x.__isub__(1), "~": lambda x,v: ~x, "!": lambda x,v: not x, "-": lambda x,v: -x, "sizeof": lambda x,v: (fields.UInt64()+x._pfp__width()), "startof": lambda x,v: (fields.UInt64()+x._pfp__offset), } if node.op not in switch and node.op not in special_switch: raise errors.UnsupportedUnaryOperator(node.coord, node.op) if node.op in special_switch: return special_switch[node.op](node, scope, ctxt, stream) field = self._handle_node(node.expr, scope, ctxt, stream) if type(field) is type: field = field() res = switch[node.op](field, 1) if type(res) is bool: new_res = field.__class__() new_res._pfp__set_value(1 if res == True else 0) res = new_res return res
[ "def", "_handle_unary_op", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling unary op {}\"", ".", "format", "(", "node", ".", "op", ")", ")", "special_switch", "=", "{", "\"parentof\"", "...
TODO: Docstring for _handle_unary_op. :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "TODO", ":", "Docstring", "for", "_handle_unary_op", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1619-L1665
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_parentof
def _handle_parentof(self, node, scope, ctxt, stream): """Handle the parentof unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ # if someone does something like parentof(this).blah, # we'll end up with a StructRef instead of an ID ref # for node.expr, but we'll also end up with a structref # if the user does parentof(a.b.c)... # # TODO how to differentiate between the two?? # # the proper way would be to do (parentof(a.b.c)).a or # (parentof a.b.c).a field = self._handle_node(node.expr, scope, ctxt, stream) parent = field._pfp__parent return parent
python
def _handle_parentof(self, node, scope, ctxt, stream): """Handle the parentof unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ # if someone does something like parentof(this).blah, # we'll end up with a StructRef instead of an ID ref # for node.expr, but we'll also end up with a structref # if the user does parentof(a.b.c)... # # TODO how to differentiate between the two?? # # the proper way would be to do (parentof(a.b.c)).a or # (parentof a.b.c).a field = self._handle_node(node.expr, scope, ctxt, stream) parent = field._pfp__parent return parent
[ "def", "_handle_parentof", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "# if someone does something like parentof(this).blah,", "# we'll end up with a StructRef instead of an ID ref", "# for node.expr, but we'll also end up with a structref", "# if...
Handle the parentof unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "the", "parentof", "unary", "operator" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1681-L1703
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_exists
def _handle_exists(self, node, scope, ctxt, stream): """Handle the exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ res = fields.Int() try: self._handle_node(node.expr, scope, ctxt, stream) res._pfp__set_value(1) except AttributeError: res._pfp__set_value(0) return res
python
def _handle_exists(self, node, scope, ctxt, stream): """Handle the exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ res = fields.Int() try: self._handle_node(node.expr, scope, ctxt, stream) res._pfp__set_value(1) except AttributeError: res._pfp__set_value(0) return res
[ "def", "_handle_exists", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "res", "=", "fields", ".", "Int", "(", ")", "try", ":", "self", ".", "_handle_node", "(", "node", ".", "expr", ",", "scope", ",", "ctxt", ",", ...
Handle the exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "the", "exists", "unary", "operator" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1705-L1721
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_function_exists
def _handle_function_exists(self, node, scope, ctxt, stream): """Handle the function_exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ res = fields.Int() try: func = self._handle_node(node.expr, scope, ctxt, stream) if isinstance(func, functions.BaseFunction): res._pfp__set_value(1) else: res._pfp__set_value(0) except errors.UnresolvedID: res._pfp__set_value(0) return res
python
def _handle_function_exists(self, node, scope, ctxt, stream): """Handle the function_exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ res = fields.Int() try: func = self._handle_node(node.expr, scope, ctxt, stream) if isinstance(func, functions.BaseFunction): res._pfp__set_value(1) else: res._pfp__set_value(0) except errors.UnresolvedID: res._pfp__set_value(0) return res
[ "def", "_handle_function_exists", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "res", "=", "fields", ".", "Int", "(", ")", "try", ":", "func", "=", "self", ".", "_handle_node", "(", "node", ".", "expr", ",", "scope", ...
Handle the function_exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "the", "function_exists", "unary", "operator" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1723-L1742
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_id
def _handle_id(self, node, scope, ctxt, stream): """Handle an ID node (return a field object for the ID) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ if node.name == "__root": return self._root if node.name == "__this" or node.name == "this": return ctxt self._dlog("handling id {}".format(node.name)) field = scope.get_id(node.name) is_lazy = getattr(node, "is_lazy", False) if field is None and not is_lazy: raise errors.UnresolvedID(node.coord, node.name) elif is_lazy: return LazyField(node.name, scope) return field
python
def _handle_id(self, node, scope, ctxt, stream): """Handle an ID node (return a field object for the ID) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ if node.name == "__root": return self._root if node.name == "__this" or node.name == "this": return ctxt self._dlog("handling id {}".format(node.name)) field = scope.get_id(node.name) is_lazy = getattr(node, "is_lazy", False) if field is None and not is_lazy: raise errors.UnresolvedID(node.coord, node.name) elif is_lazy: return LazyField(node.name, scope) return field
[ "def", "_handle_id", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "if", "node", ".", "name", "==", "\"__root\"", ":", "return", "self", ".", "_root", "if", "node", ".", "name", "==", "\"__this\"", "or", "node", ".", ...
Handle an ID node (return a field object for the ID) :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "an", "ID", "node", "(", "return", "a", "field", "object", "for", "the", "ID", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1744-L1769
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_assignment
def _handle_assignment(self, node, scope, ctxt, stream): """Handle assignment nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ def add_op(x,y): x += y def sub_op(x,y): x -= y def div_op(x,y): x /= y def mod_op(x,y): x %= y def mul_op(x,y): x *= y def xor_op(x,y): x ^= y def and_op(x,y): x &= y def or_op(x,y): x |= y def lshift_op(x,y): x <<= y def rshift_op(x,y): x >>= y def assign_op(x,y): x._pfp__set_value(y) switch = { "+=" : add_op, "-=" : sub_op, "/=" : div_op, "%=" : mod_op, "*=" : mul_op, "^=" : xor_op, "&=" : and_op, "|=" : or_op, "<<=" : lshift_op, ">>=" : rshift_op, "=" : assign_op } self._dlog("handling assignment") field = self._handle_node(node.lvalue, scope, ctxt, stream) self._dlog("field = {}".format(field)) value = self._handle_node(node.rvalue, scope, ctxt, stream) if node.op is None: self._dlog("value = {}".format(value)) field._pfp__set_value(value) else: self._dlog("value {}= {}".format(node.op, value)) if node.op not in switch: raise errors.UnsupportedAssignmentOperator(node.coord, node.op) switch[node.op](field, value)
python
def _handle_assignment(self, node, scope, ctxt, stream): """Handle assignment nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ def add_op(x,y): x += y def sub_op(x,y): x -= y def div_op(x,y): x /= y def mod_op(x,y): x %= y def mul_op(x,y): x *= y def xor_op(x,y): x ^= y def and_op(x,y): x &= y def or_op(x,y): x |= y def lshift_op(x,y): x <<= y def rshift_op(x,y): x >>= y def assign_op(x,y): x._pfp__set_value(y) switch = { "+=" : add_op, "-=" : sub_op, "/=" : div_op, "%=" : mod_op, "*=" : mul_op, "^=" : xor_op, "&=" : and_op, "|=" : or_op, "<<=" : lshift_op, ">>=" : rshift_op, "=" : assign_op } self._dlog("handling assignment") field = self._handle_node(node.lvalue, scope, ctxt, stream) self._dlog("field = {}".format(field)) value = self._handle_node(node.rvalue, scope, ctxt, stream) if node.op is None: self._dlog("value = {}".format(value)) field._pfp__set_value(value) else: self._dlog("value {}= {}".format(node.op, value)) if node.op not in switch: raise errors.UnsupportedAssignmentOperator(node.coord, node.op) switch[node.op](field, value)
[ "def", "_handle_assignment", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "def", "add_op", "(", "x", ",", "y", ")", ":", "x", "+=", "y", "def", "sub_op", "(", "x", ",", "y", ")", ":", "x", "-=", "y", "def", "d...
Handle assignment nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "assignment", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1771-L1819
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_func_def
def _handle_func_def(self, node, scope, ctxt, stream): """Handle FuncDef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function definition") func = self._handle_node(node.decl, scope, ctxt, stream) func.body = node.body
python
def _handle_func_def(self, node, scope, ctxt, stream): """Handle FuncDef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function definition") func = self._handle_node(node.decl, scope, ctxt, stream) func.body = node.body
[ "def", "_handle_func_def", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling function definition\"", ")", "func", "=", "self", ".", "_handle_node", "(", "node", ".", "decl", ",", "scope", ...
Handle FuncDef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "FuncDef", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1821-L1833
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_param_list
def _handle_param_list(self, node, scope, ctxt, stream): """Handle ParamList nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling param list") # params should be a list of tuples: # [(<name>, <field_class>), ...] params = [] for param in node.params: self._mark_id_as_lazy(param) param_info = self._handle_node(param, scope, ctxt, stream) params.append(param_info) param_list = functions.ParamListDef(params, node.coord) return param_list
python
def _handle_param_list(self, node, scope, ctxt, stream): """Handle ParamList nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling param list") # params should be a list of tuples: # [(<name>, <field_class>), ...] params = [] for param in node.params: self._mark_id_as_lazy(param) param_info = self._handle_node(param, scope, ctxt, stream) params.append(param_info) param_list = functions.ParamListDef(params, node.coord) return param_list
[ "def", "_handle_param_list", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling param list\"", ")", "# params should be a list of tuples:", "# [(<name>, <field_class>), ...]", "params", "=", "[", "]",...
Handle ParamList nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "ParamList", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1835-L1855
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_func_decl
def _handle_func_decl(self, node, scope, ctxt, stream): """Handle FuncDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling func decl") if node.args is not None: # could just call _handle_param_list directly... for param in node.args.params: # see the check in _handle_decl for how this is kept from # being added to the local context/scope param.is_func_param = True params = self._handle_node(node.args, scope, ctxt, stream) else: params = functions.ParamListDef([], node.coord) func_type = self._handle_node(node.type, scope, ctxt, stream) func = functions.Function(func_type, params, scope) return func
python
def _handle_func_decl(self, node, scope, ctxt, stream): """Handle FuncDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling func decl") if node.args is not None: # could just call _handle_param_list directly... for param in node.args.params: # see the check in _handle_decl for how this is kept from # being added to the local context/scope param.is_func_param = True params = self._handle_node(node.args, scope, ctxt, stream) else: params = functions.ParamListDef([], node.coord) func_type = self._handle_node(node.type, scope, ctxt, stream) func = functions.Function(func_type, params, scope) return func
[ "def", "_handle_func_decl", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling func decl\"", ")", "if", "node", ".", "args", "is", "not", "None", ":", "# could just call _handle_param_list direc...
Handle FuncDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "FuncDecl", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1857-L1883
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_func_call
def _handle_func_call(self, node, scope, ctxt, stream): """Handle FuncCall nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function call to '{}'".format(node.name.name)) if node.args is None: func_args = [] else: func_args = self._handle_node(node.args, scope, ctxt, stream) func = self._handle_node(node.name, scope, ctxt, stream) return func.call(func_args, ctxt, scope, stream, self, node.coord)
python
def _handle_func_call(self, node, scope, ctxt, stream): """Handle FuncCall nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function call to '{}'".format(node.name.name)) if node.args is None: func_args = [] else: func_args = self._handle_node(node.args, scope, ctxt, stream) func = self._handle_node(node.name, scope, ctxt, stream) return func.call(func_args, ctxt, scope, stream, self, node.coord)
[ "def", "_handle_func_call", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling function call to '{}'\"", ".", "format", "(", "node", ".", "name", ".", "name", ")", ")", "if", "node", ".", ...
Handle FuncCall nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "FuncCall", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1885-L1901
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_expr_list
def _handle_expr_list(self, node, scope, ctxt, stream): """Handle ExprList nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling expression list") exprs = [ self._handle_node(expr, scope, ctxt, stream) for expr in node.exprs ] return exprs
python
def _handle_expr_list(self, node, scope, ctxt, stream): """Handle ExprList nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling expression list") exprs = [ self._handle_node(expr, scope, ctxt, stream) for expr in node.exprs ] return exprs
[ "def", "_handle_expr_list", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling expression list\"", ")", "exprs", "=", "[", "self", ".", "_handle_node", "(", "expr", ",", "scope", ",", "ctx...
Handle ExprList nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "ExprList", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1903-L1917
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_compound
def _handle_compound(self, node, scope, ctxt, stream): """Handle Compound nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling compound statement") #scope.push() try: for child in node.children(): self._handle_node(child, scope, ctxt, stream) # in case a return occurs, be sure to pop the scope # (returns are implemented by raising an exception) finally: #scope.pop() pass
python
def _handle_compound(self, node, scope, ctxt, stream): """Handle Compound nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling compound statement") #scope.push() try: for child in node.children(): self._handle_node(child, scope, ctxt, stream) # in case a return occurs, be sure to pop the scope # (returns are implemented by raising an exception) finally: #scope.pop() pass
[ "def", "_handle_compound", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling compound statement\"", ")", "#scope.push()", "try", ":", "for", "child", "in", "node", ".", "children", "(", ")"...
Handle Compound nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "Compound", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1919-L1940
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_return
def _handle_return(self, node, scope, ctxt, stream): """Handle Return nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling return") if node.expr is None: ret_val = None else: ret_val = self._handle_node(node.expr, scope, ctxt, stream) self._dlog("return value = {}".format(ret_val)) raise errors.InterpReturn(ret_val)
python
def _handle_return(self, node, scope, ctxt, stream): """Handle Return nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling return") if node.expr is None: ret_val = None else: ret_val = self._handle_node(node.expr, scope, ctxt, stream) self._dlog("return value = {}".format(ret_val)) raise errors.InterpReturn(ret_val)
[ "def", "_handle_return", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling return\"", ")", "if", "node", ".", "expr", "is", "None", ":", "ret_val", "=", "None", "else", ":", "ret_val", ...
Handle Return nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "Return", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1942-L1958
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_enum
def _handle_enum(self, node, scope, ctxt, stream): """Handle enum nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling enum") if node.type is None: enum_cls = fields.Int else: enum_cls = self._handle_node(node.type, scope, ctxt, stream) enum_vals = {} curr_val = enum_cls() curr_val._pfp__value = -1 for enumerator in node.values.enumerators: if enumerator.value is not None: curr_val = self._handle_node(enumerator.value, scope, ctxt, stream) else: curr_val = curr_val + 1 curr_val._pfp__freeze() enum_vals[enumerator.name] = curr_val enum_vals[fields.PYVAL(curr_val)] = enumerator.name scope.add_local(enumerator.name, curr_val) if node.name is not None: enum_cls = EnumDef(node.name, enum_cls, enum_vals) scope.add_type_class(node.name, enum_cls) else: enum_cls = EnumDef("enum_" + enum_cls.__name__, enum_cls, enum_vals) # don't add to scope if we don't have a name return enum_cls
python
def _handle_enum(self, node, scope, ctxt, stream): """Handle enum nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling enum") if node.type is None: enum_cls = fields.Int else: enum_cls = self._handle_node(node.type, scope, ctxt, stream) enum_vals = {} curr_val = enum_cls() curr_val._pfp__value = -1 for enumerator in node.values.enumerators: if enumerator.value is not None: curr_val = self._handle_node(enumerator.value, scope, ctxt, stream) else: curr_val = curr_val + 1 curr_val._pfp__freeze() enum_vals[enumerator.name] = curr_val enum_vals[fields.PYVAL(curr_val)] = enumerator.name scope.add_local(enumerator.name, curr_val) if node.name is not None: enum_cls = EnumDef(node.name, enum_cls, enum_vals) scope.add_type_class(node.name, enum_cls) else: enum_cls = EnumDef("enum_" + enum_cls.__name__, enum_cls, enum_vals) # don't add to scope if we don't have a name return enum_cls
[ "def", "_handle_enum", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling enum\"", ")", "if", "node", ".", "type", "is", "None", ":", "enum_cls", "=", "fields", ".", "Int", "else", ":"...
Handle enum nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "enum", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1960-L1997
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_array_decl
def _handle_array_decl(self, node, scope, ctxt, stream): """Handle ArrayDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling array declaration '{}'".format(node.type.declname)) if node.dim is None: # will be used array_size = None else: array_size = self._handle_node(node.dim, scope, ctxt, stream) self._dlog("array size = {}".format(array_size)) # TODO node.dim_quals # node.type field_cls = self._handle_node(node.type, scope, ctxt, stream) self._dlog("field class = {}".format(field_cls)) array = ArrayDecl(field_cls, array_size) #array = fields.Array(array_size, field_cls) array._pfp__name = node.type.declname #array._pfp__parse(stream) return array
python
def _handle_array_decl(self, node, scope, ctxt, stream): """Handle ArrayDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling array declaration '{}'".format(node.type.declname)) if node.dim is None: # will be used array_size = None else: array_size = self._handle_node(node.dim, scope, ctxt, stream) self._dlog("array size = {}".format(array_size)) # TODO node.dim_quals # node.type field_cls = self._handle_node(node.type, scope, ctxt, stream) self._dlog("field class = {}".format(field_cls)) array = ArrayDecl(field_cls, array_size) #array = fields.Array(array_size, field_cls) array._pfp__name = node.type.declname #array._pfp__parse(stream) return array
[ "def", "_handle_array_decl", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling array declaration '{}'\"", ".", "format", "(", "node", ".", "type", ".", "declname", ")", ")", "if", "node", ...
Handle ArrayDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "ArrayDecl", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1999-L2025
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_array_ref
def _handle_array_ref(self, node, scope, ctxt, stream): """Handle ArrayRef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ ary = self._handle_node(node.name, scope, ctxt, stream) subscript = self._handle_node(node.subscript, scope, ctxt, stream) return ary[fields.PYVAL(subscript)]
python
def _handle_array_ref(self, node, scope, ctxt, stream): """Handle ArrayRef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ ary = self._handle_node(node.name, scope, ctxt, stream) subscript = self._handle_node(node.subscript, scope, ctxt, stream) return ary[fields.PYVAL(subscript)]
[ "def", "_handle_array_ref", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "ary", "=", "self", ".", "_handle_node", "(", "node", ".", "name", ",", "scope", ",", "ctxt", ",", "stream", ")", "subscript", "=", "self", ".",...
Handle ArrayRef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "ArrayRef", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2027-L2039
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_if
def _handle_if(self, node, scope, ctxt, stream): """Handle If nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling if/ternary_op") cond = self._handle_node(node.cond, scope, ctxt, stream) if cond: # there should always be an iftrue return self._handle_node(node.iftrue, scope, ctxt, stream) else: if node.iffalse is not None: return self._handle_node(node.iffalse, scope, ctxt, stream)
python
def _handle_if(self, node, scope, ctxt, stream): """Handle If nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling if/ternary_op") cond = self._handle_node(node.cond, scope, ctxt, stream) if cond: # there should always be an iftrue return self._handle_node(node.iftrue, scope, ctxt, stream) else: if node.iffalse is not None: return self._handle_node(node.iffalse, scope, ctxt, stream)
[ "def", "_handle_if", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling if/ternary_op\"", ")", "cond", "=", "self", ".", "_handle_node", "(", "node", ".", "cond", ",", "scope", ",", "ctx...
Handle If nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "If", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2041-L2058
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_for
def _handle_for(self, node, scope, ctxt, stream): """Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling for") if node.init is not None: # perform the init self._handle_node(node.init, scope, ctxt, stream) while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream): if node.stmt is not None: try: # do the for body self._handle_node(node.stmt, scope, ctxt, stream) except errors.InterpBreak as e: break # we still need to interpret the "next" statement, # so just pass except errors.InterpContinue as e: pass if node.next is not None: # do the next statement self._handle_node(node.next, scope, ctxt, stream)
python
def _handle_for(self, node, scope, ctxt, stream): """Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling for") if node.init is not None: # perform the init self._handle_node(node.init, scope, ctxt, stream) while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream): if node.stmt is not None: try: # do the for body self._handle_node(node.stmt, scope, ctxt, stream) except errors.InterpBreak as e: break # we still need to interpret the "next" statement, # so just pass except errors.InterpContinue as e: pass if node.next is not None: # do the next statement self._handle_node(node.next, scope, ctxt, stream)
[ "def", "_handle_for", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling for\"", ")", "if", "node", ".", "init", "is", "not", "None", ":", "# perform the init", "self", ".", "_handle_node"...
Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "For", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2060-L2090
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_while
def _handle_while(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling while") while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream): if node.stmt is not None: try: self._handle_node(node.stmt, scope, ctxt, stream) except errors.InterpBreak as e: break except errors.InterpContinue as e: pass
python
def _handle_while(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling while") while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream): if node.stmt is not None: try: self._handle_node(node.stmt, scope, ctxt, stream) except errors.InterpBreak as e: break except errors.InterpContinue as e: pass
[ "def", "_handle_while", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling while\"", ")", "while", "node", ".", "cond", "is", "None", "or", "self", ".", "_handle_node", "(", "node", ".",...
Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "break", "node" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2092-L2110
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_switch
def _handle_switch(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ def exec_case(idx, cases): # keep executing cases until a break is found, # or they've all been executed for case in cases[idx:]: stmts = case.stmts try: for stmt in stmts: self._handle_node(stmt, scope, ctxt, stream) except errors.InterpBreak as e: break def get_stmts(stmts, res=None): if res is None: res = [] stmts = self._flatten_list(stmts) for stmt in stmts: if isinstance(stmt, tuple): stmt = stmt[1] res.append(stmt) if stmt.__class__ in [AST.Case, AST.Default]: get_stmts(stmt.stmts, res) return res def get_cases(nodes, acc=None): cases = [] stmts = get_stmts(nodes) for stmt in stmts: if stmt.__class__ in [AST.Case, AST.Default]: cases.append(stmt) stmt.stmts = [] else: cases[-1].stmts.append(stmt) return cases cond = self._handle_node(node.cond, scope, ctxt, stream) default_idx = None found_match = False cases = getattr(node, "pfp_cases", None) if cases is None: cases = get_cases(node.stmt.children()) node.pfp_cases = cases for idx,child in enumerate(cases): if child.__class__ == AST.Default: default_idx = idx continue elif child.__class__ == AST.Case: expr = self._handle_node(child.expr, scope, ctxt, stream) if expr == cond: found_match = True exec_case(idx, cases) break if default_idx is not None and not found_match: exec_case(default_idx, cases)
python
def _handle_switch(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ def exec_case(idx, cases): # keep executing cases until a break is found, # or they've all been executed for case in cases[idx:]: stmts = case.stmts try: for stmt in stmts: self._handle_node(stmt, scope, ctxt, stream) except errors.InterpBreak as e: break def get_stmts(stmts, res=None): if res is None: res = [] stmts = self._flatten_list(stmts) for stmt in stmts: if isinstance(stmt, tuple): stmt = stmt[1] res.append(stmt) if stmt.__class__ in [AST.Case, AST.Default]: get_stmts(stmt.stmts, res) return res def get_cases(nodes, acc=None): cases = [] stmts = get_stmts(nodes) for stmt in stmts: if stmt.__class__ in [AST.Case, AST.Default]: cases.append(stmt) stmt.stmts = [] else: cases[-1].stmts.append(stmt) return cases cond = self._handle_node(node.cond, scope, ctxt, stream) default_idx = None found_match = False cases = getattr(node, "pfp_cases", None) if cases is None: cases = get_cases(node.stmt.children()) node.pfp_cases = cases for idx,child in enumerate(cases): if child.__class__ == AST.Default: default_idx = idx continue elif child.__class__ == AST.Case: expr = self._handle_node(child.expr, scope, ctxt, stream) if expr == cond: found_match = True exec_case(idx, cases) break if default_idx is not None and not found_match: exec_case(default_idx, cases)
[ "def", "_handle_switch", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "def", "exec_case", "(", "idx", ",", "cases", ")", ":", "# keep executing cases until a break is found,", "# or they've all been executed", "for", "case", "in", ...
Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "break", "node" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2143-L2215
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_break
def _handle_break(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling break") raise errors.InterpBreak()
python
def _handle_break(self, node, scope, ctxt, stream): """Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling break") raise errors.InterpBreak()
[ "def", "_handle_break", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling break\"", ")", "raise", "errors", ".", "InterpBreak", "(", ")" ]
Handle break node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "break", "node" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2217-L2228
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_continue
def _handle_continue(self, node, scope, ctxt, stream): """Handle continue node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling continue") raise errors.InterpContinue()
python
def _handle_continue(self, node, scope, ctxt, stream): """Handle continue node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling continue") raise errors.InterpContinue()
[ "def", "_handle_continue", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling continue\"", ")", "raise", "errors", ".", "InterpContinue", "(", ")" ]
Handle continue node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "continue", "node" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2230-L2241
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._handle_decl_list
def _handle_decl_list(self, node, scope, ctxt, stream): """Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling decl list") # just handle each declaration for decl in node.decls: self._handle_node(decl, scope, ctxt, stream)
python
def _handle_decl_list(self, node, scope, ctxt, stream): """Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling decl list") # just handle each declaration for decl in node.decls: self._handle_node(decl, scope, ctxt, stream)
[ "def", "_handle_decl_list", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling decl list\"", ")", "# just handle each declaration", "for", "decl", "in", "node", ".", "decls", ":", "self", ".",...
Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
[ "Handle", "For", "nodes" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2243-L2256
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._create_scope
def _create_scope(self): """TODO: Docstring for _create_scope. :returns: TODO """ res = Scope(self._log) for func_name,native_func in six.iteritems(self._natives): res.add_local(func_name, native_func) return res
python
def _create_scope(self): """TODO: Docstring for _create_scope. :returns: TODO """ res = Scope(self._log) for func_name,native_func in six.iteritems(self._natives): res.add_local(func_name, native_func) return res
[ "def", "_create_scope", "(", "self", ")", ":", "res", "=", "Scope", "(", "self", ".", "_log", ")", "for", "func_name", ",", "native_func", "in", "six", ".", "iteritems", "(", "self", ".", "_natives", ")", ":", "res", ".", "add_local", "(", "func_name",...
TODO: Docstring for _create_scope. :returns: TODO
[ "TODO", ":", "Docstring", "for", "_create_scope", ".", ":", "returns", ":", "TODO" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2306-L2316
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._get_value
def _get_value(self, node, scope, ctxt, stream): """Return the value of the node. It is expected to be either an AST.ID instance or a constant :node: TODO :returns: TODO """ res = self._handle_node(node, scope, ctxt, stream) if isinstance(res, fields.Field): return res._pfp__value # assume it's a constant else: return res
python
def _get_value(self, node, scope, ctxt, stream): """Return the value of the node. It is expected to be either an AST.ID instance or a constant :node: TODO :returns: TODO """ res = self._handle_node(node, scope, ctxt, stream) if isinstance(res, fields.Field): return res._pfp__value # assume it's a constant else: return res
[ "def", "_get_value", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "res", "=", "self", ".", "_handle_node", "(", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", "if", "isinstance", "(", "res", ",", "fields", "...
Return the value of the node. It is expected to be either an AST.ID instance or a constant :node: TODO :returns: TODO
[ "Return", "the", "value", "of", "the", "node", ".", "It", "is", "expected", "to", "be", "either", "an", "AST", ".", "ID", "instance", "or", "a", "constant" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2318-L2334
train
d0c-s4vage/pfp
pfp/interp.py
PfpInterp._resolve_to_field_class
def _resolve_to_field_class(self, names, scope): """Resolve the names to a class in fields.py, resolving past typedefs, etc :names: TODO :scope: TODO :ctxt: TODO :returns: TODO """ switch = { "char" : "Char", "int" : "Int", "long" : "Int", "int64" : "Int64", "uint64" : "UInt64", "short" : "Short", "double" : "Double", "float" : "Float", "void" : "Void", "string" : "String", "wstring" : "WString" } core = names[-1] if core not in switch: # will return a list of resolved names type_info = scope.get_type(core) if type(type_info) is type and issubclass(type_info, fields.Field): return type_info resolved_names = type_info if resolved_names is None: raise errors.UnresolvedType(self._coord, " ".join(names), " ") if resolved_names[-1] not in switch: raise errors.UnresolvedType(self._coord, " ".join(names), " ".join(resolved_names)) names = copy.copy(names) names.pop() names += resolved_names if len(names) >= 2 and names[-1] == names[-2] and names[-1] == "long": res = "Int64" else: res = switch[names[-1]] if names[-1] in ["char", "short", "int", "long"] and "unsigned" in names[:-1]: res = "U" + res cls = getattr(fields, res) return cls
python
def _resolve_to_field_class(self, names, scope): """Resolve the names to a class in fields.py, resolving past typedefs, etc :names: TODO :scope: TODO :ctxt: TODO :returns: TODO """ switch = { "char" : "Char", "int" : "Int", "long" : "Int", "int64" : "Int64", "uint64" : "UInt64", "short" : "Short", "double" : "Double", "float" : "Float", "void" : "Void", "string" : "String", "wstring" : "WString" } core = names[-1] if core not in switch: # will return a list of resolved names type_info = scope.get_type(core) if type(type_info) is type and issubclass(type_info, fields.Field): return type_info resolved_names = type_info if resolved_names is None: raise errors.UnresolvedType(self._coord, " ".join(names), " ") if resolved_names[-1] not in switch: raise errors.UnresolvedType(self._coord, " ".join(names), " ".join(resolved_names)) names = copy.copy(names) names.pop() names += resolved_names if len(names) >= 2 and names[-1] == names[-2] and names[-1] == "long": res = "Int64" else: res = switch[names[-1]] if names[-1] in ["char", "short", "int", "long"] and "unsigned" in names[:-1]: res = "U" + res cls = getattr(fields, res) return cls
[ "def", "_resolve_to_field_class", "(", "self", ",", "names", ",", "scope", ")", ":", "switch", "=", "{", "\"char\"", ":", "\"Char\"", ",", "\"int\"", ":", "\"Int\"", ",", "\"long\"", ":", "\"Int\"", ",", "\"int64\"", ":", "\"Int64\"", ",", "\"uint64\"", ":...
Resolve the names to a class in fields.py, resolving past typedefs, etc :names: TODO :scope: TODO :ctxt: TODO :returns: TODO
[ "Resolve", "the", "names", "to", "a", "class", "in", "fields", ".", "py", "resolving", "past", "typedefs", "etc" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2336-L2385
train
d0c-s4vage/pfp
pfp/bitwrap.py
bits_to_bytes
def bits_to_bytes(bits): """Convert the bit list into bytes. (Assumes bits is a list whose length is a multiple of 8) """ if len(bits) % 8 != 0: raise Exception("num bits must be multiple of 8") res = "" for x in six.moves.range(0, len(bits), 8): byte_bits = bits[x:x+8] byte_val = int(''.join(map(str, byte_bits)), 2) res += chr(byte_val) return utils.binary(res)
python
def bits_to_bytes(bits): """Convert the bit list into bytes. (Assumes bits is a list whose length is a multiple of 8) """ if len(bits) % 8 != 0: raise Exception("num bits must be multiple of 8") res = "" for x in six.moves.range(0, len(bits), 8): byte_bits = bits[x:x+8] byte_val = int(''.join(map(str, byte_bits)), 2) res += chr(byte_val) return utils.binary(res)
[ "def", "bits_to_bytes", "(", "bits", ")", ":", "if", "len", "(", "bits", ")", "%", "8", "!=", "0", ":", "raise", "Exception", "(", "\"num bits must be multiple of 8\"", ")", "res", "=", "\"\"", "for", "x", "in", "six", ".", "moves", ".", "range", "(", ...
Convert the bit list into bytes. (Assumes bits is a list whose length is a multiple of 8)
[ "Convert", "the", "bit", "list", "into", "bytes", ".", "(", "Assumes", "bits", "is", "a", "list", "whose", "length", "is", "a", "multiple", "of", "8", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L15-L29
train
d0c-s4vage/pfp
pfp/bitwrap.py
bytes_to_bits
def bytes_to_bits(bytes_): """Convert bytes to a list of bits """ res = [] for x in bytes_: if not isinstance(x, int): x = ord(x) res += byte_to_bits(x) return res
python
def bytes_to_bits(bytes_): """Convert bytes to a list of bits """ res = [] for x in bytes_: if not isinstance(x, int): x = ord(x) res += byte_to_bits(x) return res
[ "def", "bytes_to_bits", "(", "bytes_", ")", ":", "res", "=", "[", "]", "for", "x", "in", "bytes_", ":", "if", "not", "isinstance", "(", "x", ",", "int", ")", ":", "x", "=", "ord", "(", "x", ")", "res", "+=", "byte_to_bits", "(", "x", ")", "retu...
Convert bytes to a list of bits
[ "Convert", "bytes", "to", "a", "list", "of", "bits" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L31-L39
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.is_eof
def is_eof(self): """Return if the stream has reached EOF or not without discarding any unflushed bits :returns: True/False """ pos = self._stream.tell() byte = self._stream.read(1) self._stream.seek(pos, 0) return utils.binary(byte) == utils.binary("")
python
def is_eof(self): """Return if the stream has reached EOF or not without discarding any unflushed bits :returns: True/False """ pos = self._stream.tell() byte = self._stream.read(1) self._stream.seek(pos, 0) return utils.binary(byte) == utils.binary("")
[ "def", "is_eof", "(", "self", ")", ":", "pos", "=", "self", ".", "_stream", ".", "tell", "(", ")", "byte", "=", "self", ".", "_stream", ".", "read", "(", "1", ")", "self", ".", "_stream", ".", "seek", "(", "pos", ",", "0", ")", "return", "utils...
Return if the stream has reached EOF or not without discarding any unflushed bits :returns: True/False
[ "Return", "if", "the", "stream", "has", "reached", "EOF", "or", "not", "without", "discarding", "any", "unflushed", "bits" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L70-L80
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.close
def close(self): """Close the stream """ self.closed = True self._flush_bits_to_stream() self._stream.close()
python
def close(self): """Close the stream """ self.closed = True self._flush_bits_to_stream() self._stream.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "closed", "=", "True", "self", ".", "_flush_bits_to_stream", "(", ")", "self", ".", "_stream", ".", "close", "(", ")" ]
Close the stream
[ "Close", "the", "stream" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L82-L87
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.read
def read(self, num): """Read ``num`` number of bytes from the stream. Note that this will automatically resets/ends the current bit-reading if it does not end on an even byte AND ``self.padded`` is True. If ``self.padded`` is True, then the entire stream is treated as a bitstream. :num: number of bytes to read :returns: the read bytes, or empty string if EOF has been reached """ start_pos = self.tell() if self.padded: # we toss out any uneven bytes self._bits.clear() res = utils.binary(self._stream.read(num)) else: bits = self.read_bits(num * 8) res = bits_to_bytes(bits) res = utils.binary(res) end_pos = self.tell() self._update_consumed_ranges(start_pos, end_pos) return res
python
def read(self, num): """Read ``num`` number of bytes from the stream. Note that this will automatically resets/ends the current bit-reading if it does not end on an even byte AND ``self.padded`` is True. If ``self.padded`` is True, then the entire stream is treated as a bitstream. :num: number of bytes to read :returns: the read bytes, or empty string if EOF has been reached """ start_pos = self.tell() if self.padded: # we toss out any uneven bytes self._bits.clear() res = utils.binary(self._stream.read(num)) else: bits = self.read_bits(num * 8) res = bits_to_bytes(bits) res = utils.binary(res) end_pos = self.tell() self._update_consumed_ranges(start_pos, end_pos) return res
[ "def", "read", "(", "self", ",", "num", ")", ":", "start_pos", "=", "self", ".", "tell", "(", ")", "if", "self", ".", "padded", ":", "# we toss out any uneven bytes", "self", ".", "_bits", ".", "clear", "(", ")", "res", "=", "utils", ".", "binary", "...
Read ``num`` number of bytes from the stream. Note that this will automatically resets/ends the current bit-reading if it does not end on an even byte AND ``self.padded`` is True. If ``self.padded`` is True, then the entire stream is treated as a bitstream. :num: number of bytes to read :returns: the read bytes, or empty string if EOF has been reached
[ "Read", "num", "number", "of", "bytes", "from", "the", "stream", ".", "Note", "that", "this", "will", "automatically", "resets", "/", "ends", "the", "current", "bit", "-", "reading", "if", "it", "does", "not", "end", "on", "an", "even", "byte", "AND", ...
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L100-L123
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.read_bits
def read_bits(self, num): """Read ``num`` number of bits from the stream :num: number of bits to read :returns: a list of ``num`` bits, or an empty list if EOF has been reached """ if num > len(self._bits): needed = num - len(self._bits) num_bytes = int(math.ceil(needed / 8.0)) read_bytes = self._stream.read(num_bytes) for bit in bytes_to_bits(read_bytes): self._bits.append(bit) res = [] while len(res) < num and len(self._bits) > 0: res.append(self._bits.popleft()) return res
python
def read_bits(self, num): """Read ``num`` number of bits from the stream :num: number of bits to read :returns: a list of ``num`` bits, or an empty list if EOF has been reached """ if num > len(self._bits): needed = num - len(self._bits) num_bytes = int(math.ceil(needed / 8.0)) read_bytes = self._stream.read(num_bytes) for bit in bytes_to_bits(read_bytes): self._bits.append(bit) res = [] while len(res) < num and len(self._bits) > 0: res.append(self._bits.popleft()) return res
[ "def", "read_bits", "(", "self", ",", "num", ")", ":", "if", "num", ">", "len", "(", "self", ".", "_bits", ")", ":", "needed", "=", "num", "-", "len", "(", "self", ".", "_bits", ")", "num_bytes", "=", "int", "(", "math", ".", "ceil", "(", "need...
Read ``num`` number of bits from the stream :num: number of bits to read :returns: a list of ``num`` bits, or an empty list if EOF has been reached
[ "Read", "num", "number", "of", "bits", "from", "the", "stream" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L125-L143
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.write
def write(self, data): """Write data to the stream :data: the data to write to the stream :returns: None """ if self.padded: # flush out any remaining bits first if len(self._bits) > 0: self._flush_bits_to_stream() self._stream.write(data) else: # nothing to do here if len(data) == 0: return bits = bytes_to_bits(data) self.write_bits(bits)
python
def write(self, data): """Write data to the stream :data: the data to write to the stream :returns: None """ if self.padded: # flush out any remaining bits first if len(self._bits) > 0: self._flush_bits_to_stream() self._stream.write(data) else: # nothing to do here if len(data) == 0: return bits = bytes_to_bits(data) self.write_bits(bits)
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "self", ".", "padded", ":", "# flush out any remaining bits first", "if", "len", "(", "self", ".", "_bits", ")", ">", "0", ":", "self", ".", "_flush_bits_to_stream", "(", ")", "self", ".", "_strea...
Write data to the stream :data: the data to write to the stream :returns: None
[ "Write", "data", "to", "the", "stream" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L145-L162
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.write_bits
def write_bits(self, bits): """Write the bits to the stream. Add the bits to the existing unflushed bits and write complete bytes to the stream. """ for bit in bits: self._bits.append(bit) while len(self._bits) >= 8: byte_bits = [self._bits.popleft() for x in six.moves.range(8)] byte = bits_to_bytes(byte_bits) self._stream.write(byte)
python
def write_bits(self, bits): """Write the bits to the stream. Add the bits to the existing unflushed bits and write complete bytes to the stream. """ for bit in bits: self._bits.append(bit) while len(self._bits) >= 8: byte_bits = [self._bits.popleft() for x in six.moves.range(8)] byte = bits_to_bytes(byte_bits) self._stream.write(byte)
[ "def", "write_bits", "(", "self", ",", "bits", ")", ":", "for", "bit", "in", "bits", ":", "self", ".", "_bits", ".", "append", "(", "bit", ")", "while", "len", "(", "self", ".", "_bits", ")", ">=", "8", ":", "byte_bits", "=", "[", "self", ".", ...
Write the bits to the stream. Add the bits to the existing unflushed bits and write complete bytes to the stream.
[ "Write", "the", "bits", "to", "the", "stream", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L164-L176
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.tell
def tell(self): """Return the current position in the stream (ignoring bit position) :returns: int for the position in the stream """ res = self._stream.tell() if len(self._bits) > 0: res -= 1 return res
python
def tell(self): """Return the current position in the stream (ignoring bit position) :returns: int for the position in the stream """ res = self._stream.tell() if len(self._bits) > 0: res -= 1 return res
[ "def", "tell", "(", "self", ")", ":", "res", "=", "self", ".", "_stream", ".", "tell", "(", ")", "if", "len", "(", "self", ".", "_bits", ")", ">", "0", ":", "res", "-=", "1", "return", "res" ]
Return the current position in the stream (ignoring bit position) :returns: int for the position in the stream
[ "Return", "the", "current", "position", "in", "the", "stream", "(", "ignoring", "bit", "position", ")" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L180-L189
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.seek
def seek(self, pos, seek_type=0): """Seek to the specified position in the stream with seek_type. Unflushed bits will be discarded in the case of a seek. The stream will also keep track of which bytes have and have not been consumed so that the dom will capture all of the bytes in the stream. :pos: offset :seek_type: direction :returns: TODO """ self._bits.clear() return self._stream.seek(pos, seek_type)
python
def seek(self, pos, seek_type=0): """Seek to the specified position in the stream with seek_type. Unflushed bits will be discarded in the case of a seek. The stream will also keep track of which bytes have and have not been consumed so that the dom will capture all of the bytes in the stream. :pos: offset :seek_type: direction :returns: TODO """ self._bits.clear() return self._stream.seek(pos, seek_type)
[ "def", "seek", "(", "self", ",", "pos", ",", "seek_type", "=", "0", ")", ":", "self", ".", "_bits", ".", "clear", "(", ")", "return", "self", ".", "_stream", ".", "seek", "(", "pos", ",", "seek_type", ")" ]
Seek to the specified position in the stream with seek_type. Unflushed bits will be discarded in the case of a seek. The stream will also keep track of which bytes have and have not been consumed so that the dom will capture all of the bytes in the stream. :pos: offset :seek_type: direction :returns: TODO
[ "Seek", "to", "the", "specified", "position", "in", "the", "stream", "with", "seek_type", ".", "Unflushed", "bits", "will", "be", "discarded", "in", "the", "case", "of", "a", "seek", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L191-L205
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.size
def size(self): """Return the size of the stream, or -1 if it cannot be determined. """ pos = self._stream.tell() # seek to the end of the stream self._stream.seek(0,2) size = self._stream.tell() self._stream.seek(pos, 0) return size
python
def size(self): """Return the size of the stream, or -1 if it cannot be determined. """ pos = self._stream.tell() # seek to the end of the stream self._stream.seek(0,2) size = self._stream.tell() self._stream.seek(pos, 0) return size
[ "def", "size", "(", "self", ")", ":", "pos", "=", "self", ".", "_stream", ".", "tell", "(", ")", "# seek to the end of the stream", "self", ".", "_stream", ".", "seek", "(", "0", ",", "2", ")", "size", "=", "self", ".", "_stream", ".", "tell", "(", ...
Return the size of the stream, or -1 if it cannot be determined.
[ "Return", "the", "size", "of", "the", "stream", "or", "-", "1", "if", "it", "cannot", "be", "determined", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L207-L217
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream.unconsumed_ranges
def unconsumed_ranges(self): """Return an IntervalTree of unconsumed ranges, of the format (start, end] with the end value not being included """ res = IntervalTree() prev = None # normal iteration is not in a predictable order ranges = sorted([x for x in self.range_set], key=lambda x: x.begin) for rng in ranges: if prev is None: prev = rng continue res.add(Interval(prev.end, rng.begin)) prev = rng # means we've seeked past the end if len(self.range_set[self.tell()]) != 1: res.add(Interval(prev.end, self.tell())) return res
python
def unconsumed_ranges(self): """Return an IntervalTree of unconsumed ranges, of the format (start, end] with the end value not being included """ res = IntervalTree() prev = None # normal iteration is not in a predictable order ranges = sorted([x for x in self.range_set], key=lambda x: x.begin) for rng in ranges: if prev is None: prev = rng continue res.add(Interval(prev.end, rng.begin)) prev = rng # means we've seeked past the end if len(self.range_set[self.tell()]) != 1: res.add(Interval(prev.end, self.tell())) return res
[ "def", "unconsumed_ranges", "(", "self", ")", ":", "res", "=", "IntervalTree", "(", ")", "prev", "=", "None", "# normal iteration is not in a predictable order", "ranges", "=", "sorted", "(", "[", "x", "for", "x", "in", "self", ".", "range_set", "]", ",", "k...
Return an IntervalTree of unconsumed ranges, of the format (start, end] with the end value not being included
[ "Return", "an", "IntervalTree", "of", "unconsumed", "ranges", "of", "the", "format", "(", "start", "end", "]", "with", "the", "end", "value", "not", "being", "included" ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L219-L241
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream._update_consumed_ranges
def _update_consumed_ranges(self, start_pos, end_pos): """Update the ``self.consumed_ranges`` array with which byte ranges have been consecutively consumed. """ self.range_set.add(Interval(start_pos, end_pos+1)) self.range_set.merge_overlaps()
python
def _update_consumed_ranges(self, start_pos, end_pos): """Update the ``self.consumed_ranges`` array with which byte ranges have been consecutively consumed. """ self.range_set.add(Interval(start_pos, end_pos+1)) self.range_set.merge_overlaps()
[ "def", "_update_consumed_ranges", "(", "self", ",", "start_pos", ",", "end_pos", ")", ":", "self", ".", "range_set", ".", "add", "(", "Interval", "(", "start_pos", ",", "end_pos", "+", "1", ")", ")", "self", ".", "range_set", ".", "merge_overlaps", "(", ...
Update the ``self.consumed_ranges`` array with which byte ranges have been consecutively consumed.
[ "Update", "the", "self", ".", "consumed_ranges", "array", "with", "which", "byte", "ranges", "have", "been", "consecutively", "consumed", "." ]
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L247-L252
train
d0c-s4vage/pfp
pfp/bitwrap.py
BitwrappedStream._flush_bits_to_stream
def _flush_bits_to_stream(self): """Flush the bits to the stream. This is used when a few bits have been read and ``self._bits`` contains unconsumed/ flushed bits when data is to be written to the stream """ if len(self._bits) == 0: return 0 bits = list(self._bits) diff = 8 - (len(bits) % 8) padding = [0] * diff bits = bits + padding self._stream.write(bits_to_bytes(bits)) self._bits.clear()
python
def _flush_bits_to_stream(self): """Flush the bits to the stream. This is used when a few bits have been read and ``self._bits`` contains unconsumed/ flushed bits when data is to be written to the stream """ if len(self._bits) == 0: return 0 bits = list(self._bits) diff = 8 - (len(bits) % 8) padding = [0] * diff bits = bits + padding self._stream.write(bits_to_bytes(bits)) self._bits.clear()
[ "def", "_flush_bits_to_stream", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_bits", ")", "==", "0", ":", "return", "0", "bits", "=", "list", "(", "self", ".", "_bits", ")", "diff", "=", "8", "-", "(", "len", "(", "bits", ")", "%", "8...
Flush the bits to the stream. This is used when a few bits have been read and ``self._bits`` contains unconsumed/ flushed bits when data is to be written to the stream
[ "Flush", "the", "bits", "to", "the", "stream", ".", "This", "is", "used", "when", "a", "few", "bits", "have", "been", "read", "and", "self", ".", "_bits", "contains", "unconsumed", "/", "flushed", "bits", "when", "data", "is", "to", "be", "written", "t...
32f2d34fdec1c70019fa83c7006d5e3be0f92fcd
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L254-L271
train
expfactory/expfactory
expfactory/validator/library.py
LibraryValidator._validate_markdown
def _validate_markdown(self, expfile): '''ensure that fields are present in markdown file''' try: import yaml except: bot.error('Python yaml is required for testing yml/markdown files.') sys.exit(1) self.metadata = {} uid = os.path.basename(expfile).strip('.md') if os.path.exists(expfile): with open(expfile, "r") as stream: docs = yaml.load_all(stream) for doc in docs: if isinstance(doc,dict): for k,v in doc.items(): print('%s: %s' %(k,v)) self.metadata[k] = v self.metadata['uid'] = uid fields = ['github', 'preview', 'name', 'layout', 'tags', 'uid', 'maintainer'] # Tests for all fields for field in fields: if field not in self.metadata: return False if self.metadata[field] in ['',None]: return False if 'github' not in self.metadata['github']: return notvalid('%s: not a valid github repository' % name) if not isinstance(self.metadata['tags'],list): return notvalid('%s: tags must be a list' % name) if not re.search("(\w+://)(.+@)*([\w\d\.]+)(:[\d]+){0,1}/*(.*)", self.metadata['github']): return notvalid('%s is not a valid URL.' %(self.metadata['github'])) return True
python
def _validate_markdown(self, expfile): '''ensure that fields are present in markdown file''' try: import yaml except: bot.error('Python yaml is required for testing yml/markdown files.') sys.exit(1) self.metadata = {} uid = os.path.basename(expfile).strip('.md') if os.path.exists(expfile): with open(expfile, "r") as stream: docs = yaml.load_all(stream) for doc in docs: if isinstance(doc,dict): for k,v in doc.items(): print('%s: %s' %(k,v)) self.metadata[k] = v self.metadata['uid'] = uid fields = ['github', 'preview', 'name', 'layout', 'tags', 'uid', 'maintainer'] # Tests for all fields for field in fields: if field not in self.metadata: return False if self.metadata[field] in ['',None]: return False if 'github' not in self.metadata['github']: return notvalid('%s: not a valid github repository' % name) if not isinstance(self.metadata['tags'],list): return notvalid('%s: tags must be a list' % name) if not re.search("(\w+://)(.+@)*([\w\d\.]+)(:[\d]+){0,1}/*(.*)", self.metadata['github']): return notvalid('%s is not a valid URL.' %(self.metadata['github'])) return True
[ "def", "_validate_markdown", "(", "self", ",", "expfile", ")", ":", "try", ":", "import", "yaml", "except", ":", "bot", ".", "error", "(", "'Python yaml is required for testing yml/markdown files.'", ")", "sys", ".", "exit", "(", "1", ")", "self", ".", "metada...
ensure that fields are present in markdown file
[ "ensure", "that", "fields", "are", "present", "in", "markdown", "file" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/validator/library.py#L62-L101
train
expfactory/expfactory
expfactory/views/utils.py
perform_checks
def perform_checks(template, do_redirect=False, context=None, next=None, quiet=False): '''return all checks for required variables before returning to desired view Parameters ========== template: the html template to render do_redirect: if True, perform a redirect and not render context: dictionary of context variables to pass to render_template next: a pre-defined next experiment, will calculate if None quiet: decrease verbosity ''' from expfactory.server import app username = session.get('username') subid = session.get('subid') # If redirect, "last" is currently active (about to start) # If render, "last" is last completed / active experiment (just finished) last = session.get('exp_id') if next is None: next = app.get_next(session) session['exp_id'] = next # Headless mode requires token if "token" not in session and app.headless is True: flash('A token is required for these experiments.') return redirect('/') # Update the user / log if quiet is False: app.logger.info("[router] %s --> %s [subid] %s [user] %s" %(last, next, subid, username)) if username is None and app.headless is False: flash('You must start a session before doing experiments.') return redirect('/') if subid is None: flash('You must have a participant identifier before doing experiments') return redirect('/') if next is None: flash('Congratulations, you have finished the battery!') return redirect('/finish') if do_redirect is True: app.logger.debug('Redirecting to %s' %template) return redirect(template) if context is not None and isinstance(context, dict): app.logger.debug('Rendering %s' %template) return render_template(template, **context) return render_template(template)
python
def perform_checks(template, do_redirect=False, context=None, next=None, quiet=False): '''return all checks for required variables before returning to desired view Parameters ========== template: the html template to render do_redirect: if True, perform a redirect and not render context: dictionary of context variables to pass to render_template next: a pre-defined next experiment, will calculate if None quiet: decrease verbosity ''' from expfactory.server import app username = session.get('username') subid = session.get('subid') # If redirect, "last" is currently active (about to start) # If render, "last" is last completed / active experiment (just finished) last = session.get('exp_id') if next is None: next = app.get_next(session) session['exp_id'] = next # Headless mode requires token if "token" not in session and app.headless is True: flash('A token is required for these experiments.') return redirect('/') # Update the user / log if quiet is False: app.logger.info("[router] %s --> %s [subid] %s [user] %s" %(last, next, subid, username)) if username is None and app.headless is False: flash('You must start a session before doing experiments.') return redirect('/') if subid is None: flash('You must have a participant identifier before doing experiments') return redirect('/') if next is None: flash('Congratulations, you have finished the battery!') return redirect('/finish') if do_redirect is True: app.logger.debug('Redirecting to %s' %template) return redirect(template) if context is not None and isinstance(context, dict): app.logger.debug('Rendering %s' %template) return render_template(template, **context) return render_template(template)
[ "def", "perform_checks", "(", "template", ",", "do_redirect", "=", "False", ",", "context", "=", "None", ",", "next", "=", "None", ",", "quiet", "=", "False", ")", ":", "from", "expfactory", ".", "server", "import", "app", "username", "=", "session", "."...
return all checks for required variables before returning to desired view Parameters ========== template: the html template to render do_redirect: if True, perform a redirect and not render context: dictionary of context variables to pass to render_template next: a pre-defined next experiment, will calculate if None quiet: decrease verbosity
[ "return", "all", "checks", "for", "required", "variables", "before", "returning", "to", "desired", "view" ]
27ce6cc93e17231df8a8024f18e631336afd3501
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/views/utils.py#L45-L105
train