# # svalue.py -- read/write MudOS "svalues" # # Written by Greg Stein sometime in early May, 1995. # import types import regex _regex_string = regex.symcomp('"\(\([^"\\]\|\\\\.\)*\)"') _regex_number = regex.compile('-?[-+.0-9e]+') error = 'svalue error' def read_svalue(str): if str[0] == '(': if str[1] == '{' or str[1] == '/': array = [] str = str[2:] while str[0] != '}' and str[0] != '/': value, str = read_svalue(str) array = array + [ value ] if str[0] != ',': raise error, 'missing comma in array:'+str str = str[1:] if str[1] != ')': raise error, 'bad termination of array:'+str return array, str[2:] elif str[1] == '[': mapping = {} str = str[2:] while str[0] != ']': key, str = read_svalue(str) if str[0] != ':': raise error, 'missing colon in mapping:'+str value, str = read_svalue(str[1:]) mapping[key] = value if str[0] != ',': raise error, 'missing comma in mapping:'+str str = str[1:] if str[1] != ')': raise error, 'bad termination of mapping:'+str return mapping, str[2:] else: raise error, 'bad character after opening paren:'+str elif str[0] == '"': mlen = _regex_string.match(str) if mlen < 0: raise error, 'bad string format:'+str return _regex_string.group('str'), str[mlen:] elif (str[0] >= '0' and str[0] <= '9') or str[0] == '-': mlen = _regex_number.match(str) if mlen < 0: raise error, 'bad number format:'+str return eval(str[:mlen]), str[mlen:] else: raise error, 'bad initial character:'+str def write_svalue(value): if type(value) in [ types.IntType, types.FloatType ]: return repr(value) elif type(value) is types.StringType: return '"' + value + '"' elif type(value) is types.ListType: return '({'+reduce(lambda x,y: x+write_svalue(y)+',', value, '') + '})' elif type(value) is types.DictionaryType: return '(['+reduce(lambda x,y: (x+write_svalue(y[0])+':'+ write_svalue(y[1])+','), value.items(), '') + '])' else: raise error, 'bad type: %s %s' % (type(value), value)