def load_from_string(text, package_context='', full_name='', short_name=''): """ Load message specification from a string. @param text: .msg text @type text: str @param package_context: package name to use for the type name or '' to use the local (relative) naming convention. @type package_context: str @return: Message specification @rtype: L{MsgSpec} @raise MsgSpecException: if syntax errors or other problems are detected in file """ types = [] names = [] constants = [] for orig_line in text.split('\n'): l = orig_line.split(COMMENTCHAR)[0].strip() #strip comments if not l: continue #ignore empty lines splits = [s for s in [x.strip() for x in l.split(" ")] if s] #split type/name, filter out empties type_ = splits[0] if not is_valid_msg_type(type_): raise MsgSpecException("%s is not a legal message type"%type_) if CONSTCHAR in l: if not is_valid_constant_type(type_): raise MsgSpecException("%s is not a legal constant type"%type_) if type_ == 'string': # strings contain anything to the right of the equals sign, there are no comments allowed idx = orig_line.find(CONSTCHAR) name = orig_line[orig_line.find(' ')+1:idx] val = orig_line[idx+1:] else: splits = [x.strip() for x in ' '.join(splits[1:]).split(CONSTCHAR)] #resplit on '=' if len(splits) != 2: raise MsgSpecException("Invalid declaration: %s"%l) name = splits[0] val = splits[1] try: val_converted = _convert_val(type_, val) except Exception as e: raise MsgSpecException("Invalid declaration: %s"%e) constants.append(Constant(type_, name, val_converted, val.strip())) else: if len(splits) != 2: raise MsgSpecException("Invalid declaration: %s"%l) name = splits[1] if not is_valid_msg_field_name(name): raise MsgSpecException("%s is not a legal message field name"%name) if package_context and not SEP in type_: if not base_msg_type(type_) in RESERVED_TYPES: #print "rewrite", type_, "to", "%s/%s"%(package_context, type_) type_ = "%s/%s"%(package_context, type_) types.append(type_) names.append(name) return MsgSpec(types, names, constants, text, full_name, short_name, package_context)