from ply import yacc from lexer import tokens root_dict = dict() current_header = root_dict def p_toml(p): """toml : content""" def p_content_multi(p): """content : content tomlEntries""" def p_content_single(p): """content : tomlEntries""" def p_tomlEntries_table(p): """tomlEntries : table""" def p_tomlEntries_object(p): """tomlEntries : object""" def p_table_simple(p): """table : '[' ID ']'""" global root_dict, current_header headers = p[2].split('.') temp = root_dict for header in headers: if header not in temp: temp[header] = {} temp = temp[header] current_header = temp # isto ta errado def p_table_array(p): """table : '[' '[' ID ']' ']'""" global root_dict, current_header headers = p[3].split('.') temp = root_dict for header in headers: if header not in temp: temp[header] = [{}] temp = temp[header][-1] current_header = temp def p_object(p): """object : key '=' value | key '=' array | key '=' dict""" global current_header headers = p[1].split('.') temp = current_header for header in headers[:-1]: if header not in temp: temp[header] = {} temp = temp[header] temp[headers[-1]] = p[3] def p_array_cont(p): """array : '[' aCont ']'""" p[0] = p[2] def p_array_empty(p): """array : '[' ']'""" p[0] = [] def p_aCont_multiple(p): """aCont : aCont ',' aElem""" arr:list = p[1] p[0] = arr.append(p[3]) def p_aCont_single(p): """aCont : aElem""" p[0] = [p[1]] def p_aElem(p): """aElem : value | array | dict""" p[0] = p[1] def p_dict_cont(p): """dict : '{' dictCont '}'""" p[0] = p[2] def p_dict_empty(p): """dict : '{' '}'""" p[0] = {} def p_dictCont_multiple(p): """dictCont : dictCont ',' dictElem""" #checar se os dicts nao teem keys repetidas p[0] = p[1].update(p[3]) def p_dictCont_single(p): """dictCont : dictElem""" p[0] = p[1] def p_dictElem_object(p): """dictElem : key '=' value | key '=' array | key '=' dict""" headers = p[1].split('.') p[0] = {} temp = p[0] for header in headers[:-1]: if header not in temp: temp[header] = {} temp = temp[header] temp[headers[-1]] = p[3] def p_key_id(p): """key : ID""" p[0] = p[1] def p_key_str(p): """key : STR""" p[0] = p[1] def p_key_float(p): """key : FLOAT""" p[0] = p[1] def p_key_int(p): """key : INT""" p[0] = p[1] def p_value_str(p): """value : STR""" p[0] = p[1] def p_value_mlstr(p): """value : MLSTR""" p[0] = p[1] def p_value_date(p): """value : DATE""" p[0] = p[1] def p_value_datetime(p): """value : DATETIME""" p[0] = p[1] def p_value_time(p): """value : TIME""" p[0] = p[1] def p_value_int(p): """value : INT""" p[0] = int(p[1]) def p_value_float(p): """value : FLOAT""" p[0] = float(p[1]) def p_value_hex(p): """value : HEX""" p[0] = hex(p[1]) def p_value_bin(p): """value : BIN""" p[0] = bin(p[1]) def p_value_oct(p): """value : OCT""" p[0] = oct(p[1]) def p_value_inf(p): """value : INF""" p[0] = float(p[1]) def p_value_nan(p): """value : NAN""" p[0] = p[1] def p_error(p): print(p) parser = yacc.yacc() f = open('example.toml', 'r') parser.parse(f.read()) print(root_dict)