UGDK
|
00001 00002 00003 #ifndef UGDK_UTIL_GDD_READER_H_ 00004 #define UGDK_UTIL_GDD_READER_H_ 00005 00006 #include <cstdio> 00007 #include <string> 00008 #include <vector> 00009 00010 #include <ugdk/util/gdd/parserutility.h> 00011 00012 namespace ugdk { 00013 00014 namespace gdd { 00015 00016 class Reader { 00017 00018 public: 00019 00020 Reader(FILE *file) : file_path_("<unknown>"), file_(file), line_(1) {} 00021 00022 Reader(const std::string &file_path); 00023 00024 ~Reader() {} 00025 00026 std::string& file_path() { return file_path_; } 00027 00028 size_t line() { return line_; } 00029 00030 bool Begin() { 00031 file_ = fopen(file_path_.c_str(), "r"); 00032 return file_ != NULL; 00033 } 00034 00035 int Next() { 00036 int token = fgetc(file_); 00037 if (token == '\n') 00038 line_++; 00039 return token; 00040 } 00041 00042 void SkipComment() { 00043 int token = 0; 00044 while ((token = fgetc(file_)) != '\n' && token != EOF); 00045 line_++; 00046 } 00047 00048 void SkipSpace() { 00049 int token = 0; 00050 while ((token = fgetc(file_)) == ' ' || token == '\t'); 00051 ungetc(token, file_); 00052 } 00053 00054 bool IsReserved(int token) { 00055 switch (token) { 00056 case '#': 00057 case '$': 00058 case '%': 00059 case '@': 00060 case '+': 00061 case '[': 00062 case ']': 00063 return true; 00064 default: 00065 return false; 00066 } 00067 } 00068 00069 bool UntilNextTag() { 00070 int token = 0; 00071 while ((token = fgetc(file_)) == ' ' || token == '\t'); 00072 ungetc(token, file_); 00073 return !IsReserved(token) && token != '\n' && token != '\r' && token != EOF; 00074 } 00075 00076 bool Name(std::string &name) { 00077 int token = 0; 00078 token = fgetc(file_); 00079 ASSERT_PARSE(VALID_NAME_BEGIN(token), 00080 ERR_BAD_NAME_BEGIN((*this)), 00081 false); 00082 name.push_back(static_cast<char>(token)); 00083 for (token = fgetc(file_); VALID_NAME_TOKEN(token); token = fgetc(file_)) 00084 name.push_back(static_cast<char>(token)); 00085 ungetc(token, file_); 00086 return true; 00087 } 00088 00089 void Value(std::string &value) { 00090 int token = 0; 00091 for (token = fgetc(file_); VALID_VALUE_TOKEN(token); token = fgetc(file_)) 00092 value.push_back(static_cast<char>(token)); 00093 ungetc(token, file_); 00094 } 00095 00096 void ValueSequence(std::vector<std::string> &values) { 00097 while (UntilNextTag()) { 00098 std::string value = ""; 00099 Value(value); 00100 if (value.length() == 0) break; 00101 values.push_back(value); 00102 } 00103 } 00104 00105 private: 00106 00107 std::string file_path_; 00108 FILE *file_; 00109 size_t line_; 00110 00111 }; 00112 00113 } /* namespace gdd */ 00114 00115 } /* namespace ugdk */ 00116 00117 #endif /* UGDK_UTIL_GDD_READER_H_ */