瀏覽代碼

feat: 语法系统新增错误输出和翻译

SongZihuan 3 年之前
父節點
當前提交
4eddfee70d

+ 37 - 14
include/core/info/parserl_warning_error.h

@@ -6,28 +6,51 @@
 #define AFUN_PARSERL_WARNING_ERROR_H
 #define AFUN_PARSERL_WARNING_ERROR_H
 
 
 /* 词法分析器错误和警告信息 */
 /* 词法分析器错误和警告信息 */
-#define LEXICAL_ERROR(status, info) ("status: " #status " " info)
+#define IllegalCharLog "Get illegal characters"
+#define IllegalCharConsole HT_aFunGetText(IllegalChar, "Get illegal characters")
 
 
-#define SYS_ILLEGAL_CHAR(status) LEXICAL_ERROR(status, "System error to obtain illegal characters") /* switch分支获得了不可能的字符 */
-#define ILLEGAL_CHAR(status) LEXICAL_ERROR(status, "Illegal characters") /* 输入了非法字符 */
+#define IncompleteFileLog "Incomplete file" /* 文件不完整 */
+#define IncompleteFileConsole HT_aFunGetText(LexicalIncompleteFile, "Incomplete file")
 
 
-#define SYS_ERROR_STATUS(status) LEXICAL_ERROR(status, "System error to jump status") /* 状态跳转错误 */
-#define INCOMPLETE_FILE(status) LEXICAL_ERROR(status, "Incomplete file") /* 文件不完整 */
-#define INCULDE_CONTROL(status) LEXICAL_ERROR(status, "Include control characters in the text (not recommended)") /* 文本中包含控制符 */
+#define IncludeControlCharLog "Include control characters in the text (not recommended)" /* 文本中包含控制符 */
+#define IncludeControlCharConsole HT_aFunGetText(LexicalIncludeCTRL, "Include control characters in the text (not recommended)")
 
 
 /* 语法分析器错误和经过信息 */
 /* 语法分析器错误和经过信息 */
-#define SYNTACTIC_ERROR(status, info) (#status ": " info)
+#define CodeListStartErrorLog "CodeList did not get a suitable start symbol"
+#define CodeListStartErrorConsole HT_aFunGetText(SyntacticCodeListStartError, "CodeList did not get a suitable start symbol")
 
 
-#define CodeListStartError() SYNTACTIC_ERROR(CodeList, "CodeList did not get a suitable start symbol")
-#define CodeListEndError() SYNTACTIC_ERROR(CodeList, "CodeList did not get EOF/NUL with end")
+#define CodeListEndErrorLog "CodeList did not get EOF/NUL with end"
+#define CodeListEndErrorConsole HT_aFunGetText(SyntacticCodeListEndError, "CodeList did not get EOF/NUL with end")
 
 
-#define CodeStartError() SYNTACTIC_ERROR(Code, "Code did not get a suitable start symbol")
-#define CodeEndError(p) SYNTACTIC_ERROR(Code, "Code-Block did not get " p " with end")
+#define CodeStartErrorLog "Code did not get a suitable start symbol"
+#define CodeStartErrorConsole HT_aFunGetText(SyntacticCodeStartError, "Code did not get a suitable start symbol")
 
 
-#define MakeCodeFail() SYNTACTIC_ERROR(Code, "Make code fail (Maybe by prefix)")
+#define CodeBlockEndErrorLog "Code-Block did not get end block symbol with end"
+#define CodeBlockEndErrorConsole HT_aFunGetText(SyntacticCodeBolckEndError, "Code-Block did not get end block symbol with end")
 
 
-#define SYNTACTIC_TOO_DEEP() SYNTACTIC_ERROR(Syntactic, "Recursion too deep")
+#define MakeCodeFailLog "Make code fail (Maybe by prefix)"
+#define MakeCodeFailConsole HT_aFunGetText(SyntacticMakeCodeFail, "Make code fail (Maybe by prefix)")
 
 
-#define PREFIX_ERROR(satus) SYNTACTIC_ERROR(status, "The system gets the prefix error")
+#define MakeCodeFailLog "Make code fail (Maybe by prefix)"
+#define MakeCodeFailConsole HT_aFunGetText(SyntacticMakeCodeFail, "Make code fail (Maybe by prefix)")
+
+#define TooDeepLog "Recursion too deep"
+#define TooDeepConsole HT_aFunGetText(SyntacticTooDeep, "Recursion too deep")
+
+#define PrefixErrorLog "The system gets the prefix error"
+#define PrefixErrorConsole HT_aFunGetText(SyntacticPrefixError, "The system gets the prefix error")
+
+/* 封装Reader的错误 */
+#define BOMErrorLog "Parser utf-8 with error BOM"
+#define BOMErrorConsole HT_aFunGetText(ReaderBOMError, "Parser utf-8 with error BOM")
+
+#define FileIOErrorLog "File IO error"
+#define FileIOErrorConsole HT_aFunGetText(ReaderFileIOError, "File IO error")
+
+#define StdinErrorLog "Stdin error/eof"
+#define StdinErrorConsole HT_aFunGetText(ReaderStdinError, "Stdin error/eof")
+
+#define TooMuchInputErrorLog "Too much input for stdin"
+#define TooMuchInputErrorConsole HT_aFunGetText(TooMuchInputError, "Too much input for stdin")
 
 
 #endif //AFUN_PARSERL_WARNING_ERROR_H
 #endif //AFUN_PARSERL_WARNING_ERROR_H

+ 5 - 4
include/core/parser.h

@@ -12,14 +12,15 @@ typedef struct af_Parser af_Parser;
 
 
 /* Parser 创建与释放 */
 /* Parser 创建与释放 */
 AFUN_CORE_EXPORT af_Parser *
 AFUN_CORE_EXPORT af_Parser *
-makeParser(DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size);
+makeParser(FilePath file, DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func,
+           size_t data_size);
 AFUN_CORE_EXPORT void freeParser(af_Parser *parser);
 AFUN_CORE_EXPORT void freeParser(af_Parser *parser);
-AFUN_CORE_EXPORT af_Parser *makeParserByString(char *str, bool free_str);
+AFUN_CORE_EXPORT af_Parser *makeParserByString(FilePath name, char *str, bool free_str);
 AFUN_CORE_EXPORT af_Parser *makeParserByFile(FilePath path);
 AFUN_CORE_EXPORT af_Parser *makeParserByFile(FilePath path);
-AFUN_CORE_EXPORT af_Parser *makeParserByStdin(void);
+AFUN_CORE_EXPORT af_Parser *makeParserByStdin(FilePath file);
 
 
 /* Parser 相关操作 */
 /* Parser 相关操作 */
-AFUN_CORE_EXPORT af_Code *parserCode(FilePath file, af_Parser *parser);
+AFUN_CORE_EXPORT af_Code *parserCode(af_Parser *parser);
 AFUN_CORE_EXPORT void initParser(af_Parser *parser);
 AFUN_CORE_EXPORT void initParser(af_Parser *parser);
 
 
 #endif //AFUN_PARSER_H
 #endif //AFUN_PARSER_H

+ 4 - 1
lang/hgt.cmake

@@ -6,6 +6,7 @@ file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/hgt)
 to_native_path(${hgt_dir} hgt_dir_n)
 to_native_path(${hgt_dir} hgt_dir_n)
 to_native_path(${CMAKE_CURRENT_LIST_DIR}/tr tr_n)
 to_native_path(${CMAKE_CURRENT_LIST_DIR}/tr tr_n)
 to_native_path(${CMAKE_SOURCE_DIR}/src src_n)
 to_native_path(${CMAKE_SOURCE_DIR}/src src_n)
+to_native_path(${CMAKE_SOURCE_DIR}/include include_n)
 set(hgt_name aFun)
 set(hgt_name aFun)
 
 
 set(HGT_COMMAND
 set(HGT_COMMAND
@@ -15,11 +16,13 @@ set(HGT_COMMAND
     BASEHT_EXPORT
     BASEHT_EXPORT
     ${tr_n}
     ${tr_n}
     ${hgt_name}
     ${hgt_name}
-    ${src_n})
+    ${src_n}
+    ${include_n})
 
 
 unset(hgt_dir_n)
 unset(hgt_dir_n)
 unset(tr_n)
 unset(tr_n)
 unset(src_n)
 unset(src_n)
+unset(include_n)
 
 
 add_custom_target(hgt ALL)
 add_custom_target(hgt ALL)
 add_custom_command(TARGET hgt POST_BUILD
 add_custom_command(TARGET hgt POST_BUILD

+ 9 - 4
lang/hgt.py

@@ -53,8 +53,13 @@ if os.path.exists(base_tr_file):
         code = f.read()
         code = f.read()
         exec(code, base_tr, base_tr)
         exec(code, base_tr, base_tr)
 
 
+def checkFileType(dest: str, src: List[str]) -> bool:
+    for i in src:
+        if i == dest:
+            return True
+    return False
 
 
-def getFileFromPath(paths: List[str], file_type_: str) -> FileList:
+def getFileFromPath(paths: List[str], file_type_: List[str]) -> FileList:
     """
     """
     函数名: 获取目录列表中所有指定后缀的文件
     函数名: 获取目录列表中所有指定后缀的文件
     :param paths: 目录列表
     :param paths: 目录列表
@@ -66,13 +71,13 @@ def getFileFromPath(paths: List[str], file_type_: str) -> FileList:
         for file_path, dir_names, file_names in os.walk(path):
         for file_path, dir_names, file_names in os.walk(path):
             for names in file_names:
             for names in file_names:
                 file_type = os.path.splitext(names)[-1]
                 file_type = os.path.splitext(names)[-1]
-                if file_type == file_type_:
+                if checkFileType(file_type, file_type_):
                     tmp.append(os.path.join(file_path, names))
                     tmp.append(os.path.join(file_path, names))
     return tmp
     return tmp
 
 
 
 
 # 获取宏 HT_aFunGetText的列表并计算
 # 获取宏 HT_aFunGetText的列表并计算
-file_list: FileList = getFileFromPath(input_dir, '.c')
+file_list: FileList = getFileFromPath(input_dir, ['.c', '.h'])
 pattern = re.compile(f'HT_{base_name}GetText' + r'\(([\S]+),[\s]*(\"[^\"]*\")\)')  # 宏的定义
 pattern = re.compile(f'HT_{base_name}GetText' + r'\(([\S]+),[\s]*(\"[^\"]*\")\)')  # 宏的定义
 flat_list: FlatList = {}
 flat_list: FlatList = {}
 for file in file_list:
 for file in file_list:
@@ -155,7 +160,7 @@ int HT_init{base_name}GetText(char *lang) {{
 for i in flat_list:
 for i in flat_list:
     print(f"TEXT: {i}")
     print(f"TEXT: {i}")
 
 
-translation_list: FileList = getFileFromPath([translation], '.py')
+translation_list: FileList = getFileFromPath([translation], ['.py'])
 for t in translation_list:
 for t in translation_list:
     name = os.path.splitext(os.path.split(t)[-1])[0]
     name = os.path.splitext(os.path.split(t)[-1])[0]
     if name == 'base':
     if name == 'base':

+ 4 - 1
src/core/__reader.h

@@ -28,12 +28,15 @@ struct af_Reader {
     bool read_end;
     bool read_end;
     bool read_error;
     bool read_error;
     FileLine line;
     FileLine line;
+    FilePath file;
 
 
     bool init;  // 是否初始化
     bool init;  // 是否初始化
 };
 };
 
 
 /* Reader 创建与释放 */
 /* Reader 创建与释放 */
-AFUN_CORE_NO_EXPORT af_Reader *makeReader(DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size);
+AFUN_CORE_NO_EXPORT af_Reader *
+makeReader(FileLine line, FilePath file, DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func,
+           size_t data_size);
 AFUN_CORE_NO_EXPORT void freeReader(af_Reader *reader);
 AFUN_CORE_NO_EXPORT void freeReader(af_Reader *reader);
 
 
 /* Reader 初始化函数 */
 /* Reader 初始化函数 */

+ 91 - 83
src/core/lexical.c

@@ -14,14 +14,23 @@
 #define isignore(ch) (isascii(ch) && (iscntrl(ch) || isspace(ch) || (ch) == ','))  /* 被忽略的符号 */
 #define isignore(ch) (isascii(ch) && (iscntrl(ch) || isspace(ch) || (ch) == ','))  /* 被忽略的符号 */
 #define iselement(ch) (!isascii(ch) || isgraph(ch))  /* 可以作为element的符号 */
 #define iselement(ch) (!isascii(ch) || isgraph(ch))  /* 可以作为element的符号 */
 
 
-static void printLexicalError(char *info, af_Parser *parser) {
-    writeErrorLog(aFunCoreLogger, "[Lexical] %s", info);
-    parser->is_error = true;
-}
+#define DEL_TOKEN (0)
+#define FINISH_TOKEN (-1)
+#define CONTINUE_TOKEN (1)
+#define ERROR_TOKEN (-2)
 
 
-static void printLexicalWarning(char *info, af_Parser *parser) {
-    writeWarningLog(aFunCoreLogger, "[Lexical] %s", info);
-}
+#define printLexicalError(info, parser) do { \
+    writeErrorLog(aFunCoreLogger, "[Lexical] %s:%d %s", (parser)->reader->file, (parser)->reader->line, (info ## Log)); \
+    printf_stderr(0, "[%s] %s:%d : %s\n", HT_aFunGetText(lexical_n, "Lexical"), (parser)->reader->file, \
+                  (parser)->reader->line, info ## Console); \
+    (parser)->is_error = true; /* 错误标记在Parser而非Lexical中, Lexical的异常表示lexical停止运行 */ \
+} while(0)
+
+#define printLexicalWarning(info, parser) do { \
+    writeWarningLog(aFunCoreLogger, "[Lexical] %s:%d %s", (parser)->reader->file, (parser)->reader->line, (info ## Log)); \
+    printf_stderr(0, "[%s] %s:%d : %s\n", HT_aFunGetText(lexical_n, "Lexical"), (parser)->reader->file, \
+                  (parser)->reader->line, info ## Console); \
+} while(0)
 
 
 static void setLexicalLast(af_LexicalStatus status, af_TokenType token, af_Parser *parser) {
 static void setLexicalLast(af_LexicalStatus status, af_TokenType token, af_Parser *parser) {
     parser->lexical->status = status;
     parser->lexical->status = status;
@@ -43,16 +52,16 @@ static void setLexicalLast(af_LexicalStatus status, af_TokenType token, af_Parse
  * 状态机图:
  * 状态机图:
  * [lex_begin]
  * [lex_begin]
  *     -> NUL -> (lex_nul)
  *     -> NUL -> (lex_nul)
- *     -> ALL_PREFIX -> [lex_prefix] # return -1
+ *     -> ALL_PREFIX -> [lex_prefix] # return FINISH_TOKEN
  *     -> ! -> (lex_prefix_block_p)
  *     -> ! -> (lex_prefix_block_p)
  *     -> @ -> (lex_prefix_block_b)
  *     -> @ -> (lex_prefix_block_b)
  *     -> # -> (lex_prefix_block_c)
  *     -> # -> (lex_prefix_block_c)
- *     -> ( -> [lex_lp] # return -1
- *     -> [ -> [lex_lb] # return -1
- *     -> { -> [lex_lc] # return -1
- *     -> ) -> [lex_rp] # return -1
- *     -> ] -> [lex_rb] # return -1
- *     -> } -> [lex_rc] # return -1
+ *     -> ( -> [lex_lp] # return FINISH_TOKEN
+ *     -> [ -> [lex_lb] # return FINISH_TOKEN
+ *     -> { -> [lex_lc] # return FINISH_TOKEN
+ *     -> ) -> [lex_rp] # return FINISH_TOKEN
+ *     -> ] -> [lex_rb] # return FINISH_TOKEN
+ *     -> } -> [lex_rc] # return FINISH_TOKEN
  *     -> ; -> (lex_comment_before)
  *     -> ; -> (lex_comment_before)
  *     -> isignore(ch) -> [lex_space]
  *     -> isignore(ch) -> [lex_space]
  *     -> | -> (lex_element_long)
  *     -> | -> (lex_element_long)
@@ -62,10 +71,10 @@ static void setLexicalLast(af_LexicalStatus status, af_TokenType token, af_Parse
 static int doneBegin(char ch, af_Parser *parser) {
 static int doneBegin(char ch, af_Parser *parser) {
     if (ch == NUL) {
     if (ch == NUL) {
         setLexicalLast(lex_nul, TK_EOF, parser);
         setLexicalLast(lex_nul, TK_EOF, parser);
-        return -1;
+        return FINISH_TOKEN;
     } else if (strchr(ALL_PREFIX, ch)) {  /* 属于前缀 */
     } else if (strchr(ALL_PREFIX, ch)) {  /* 属于前缀 */
         setLexicalLast(lex_prefix, TK_PREFIX, parser);
         setLexicalLast(lex_prefix, TK_PREFIX, parser);
-        return -1;
+        return FINISH_TOKEN;
     } else if (strchr("!@#", ch)) {
     } else if (strchr("!@#", ch)) {
         switch (ch) {
         switch (ch) {
             case '!':
             case '!':
@@ -78,32 +87,32 @@ static int doneBegin(char ch, af_Parser *parser) {
                 parser->lexical->status = lex_prefix_block_c;
                 parser->lexical->status = lex_prefix_block_c;
                 return 1;
                 return 1;
             default:
             default:
-                printLexicalError(SYS_ILLEGAL_CHAR(lex_beging), parser);
-                return -2;
+                writeFatalErrorLog(aFunCoreLogger, EXIT_FAILURE, "Switch illegal characters");
+                return ERROR_TOKEN;
         }
         }
     } else if (strchr("([{)]}", ch)) { /* 括号 */
     } else if (strchr("([{)]}", ch)) { /* 括号 */
         switch (ch) {
         switch (ch) {
             case '(':
             case '(':
                 setLexicalLast(lex_lp, TK_LP, parser);
                 setLexicalLast(lex_lp, TK_LP, parser);
-                return -1;
+                return FINISH_TOKEN;
             case '[':
             case '[':
                 setLexicalLast(lex_lb, TK_LB, parser);
                 setLexicalLast(lex_lb, TK_LB, parser);
-                return -1;
+                return FINISH_TOKEN;
             case '{':
             case '{':
                 setLexicalLast(lex_lc, TK_LC, parser);
                 setLexicalLast(lex_lc, TK_LC, parser);
-                return -1;
+                return FINISH_TOKEN;
             case ')':
             case ')':
                 setLexicalLast(lex_rp, TK_RP, parser);
                 setLexicalLast(lex_rp, TK_RP, parser);
-                return -1;
+                return FINISH_TOKEN;
             case ']':
             case ']':
                 setLexicalLast(lex_rb, TK_RB, parser);
                 setLexicalLast(lex_rb, TK_RB, parser);
-                return -1;
+                return FINISH_TOKEN;
             case '}':
             case '}':
                 setLexicalLast(lex_rc, TK_RC, parser);
                 setLexicalLast(lex_rc, TK_RC, parser);
-                return -1;
+                return FINISH_TOKEN;
             default:
             default:
-                printLexicalError(SYS_ILLEGAL_CHAR(lex_beging), parser);
-                return -2;
+                writeFatalErrorLog(aFunCoreLogger, EXIT_FAILURE, "Switch illegal characters");
+                return ERROR_TOKEN;
         }
         }
     } else if (ch == ';') {
     } else if (ch == ';') {
         parser->lexical->status = lex_comment_before;
         parser->lexical->status = lex_comment_before;
@@ -118,66 +127,66 @@ static int doneBegin(char ch, af_Parser *parser) {
         setLexicalLast(lex_element_short, TK_ELEMENT_SHORT, parser);
         setLexicalLast(lex_element_short, TK_ELEMENT_SHORT, parser);
         return 1;
         return 1;
     }
     }
-    printLexicalError(ILLEGAL_CHAR(lex_beging), parser);
-    return 0;
+    printLexicalError(IllegalChar, parser);
+    return DEL_TOKEN;
 }
 }
 
 
 /*
 /*
  * 状态机图:
  * 状态机图:
- * [lex_prefix_block_p] -> ( -> [lex_lp] # return -1
- * [lex_prefix_block_b] -> ( -> [lex_lb] # return -1
- * [lex_prefix_block_c] -> ( -> [lex_lc] # return -1
- * [lex_prefix_block_p] -> ) -> [lex_rp] # return -1
- * [lex_prefix_block_b] -> ) -> [lex_rb] # return -1
- * [lex_prefix_block_c] -> ) -> [lex_rc] # return -1
+ * [lex_prefix_block_p] -> ( -> [lex_lp] # return FINISH_TOKEN
+ * [lex_prefix_block_b] -> ( -> [lex_lb] # return FINISH_TOKEN
+ * [lex_prefix_block_c] -> ( -> [lex_lc] # return FINISH_TOKEN
+ * [lex_prefix_block_p] -> ) -> [lex_rp] # return FINISH_TOKEN
+ * [lex_prefix_block_b] -> ) -> [lex_rb] # return FINISH_TOKEN
+ * [lex_prefix_block_c] -> ) -> [lex_rc] # return FINISH_TOKEN
  */
  */
 static int donePrefixBlock(char ch, af_Parser *parser) {
 static int donePrefixBlock(char ch, af_Parser *parser) {
     if (ch == '(') {
     if (ch == '(') {
         switch (parser->lexical->status) {
         switch (parser->lexical->status) {
             case lex_prefix_block_p:
             case lex_prefix_block_p:
                 setLexicalLast(lex_lp, TK_LP, parser);
                 setLexicalLast(lex_lp, TK_LP, parser);
-                return -1;
+                return FINISH_TOKEN;
             case lex_prefix_block_b:
             case lex_prefix_block_b:
                 setLexicalLast(lex_lb, TK_LB, parser);
                 setLexicalLast(lex_lb, TK_LB, parser);
-                return -1;
+                return FINISH_TOKEN;
             case lex_prefix_block_c:
             case lex_prefix_block_c:
                 setLexicalLast(lex_lc, TK_LC, parser);
                 setLexicalLast(lex_lc, TK_LC, parser);
-                return -1;
+                return FINISH_TOKEN;
             default:
             default:
-                printLexicalError(SYS_ERROR_STATUS(lex_prefix_block), parser);
-                return -2;
+                writeFatalErrorLog(aFunCoreLogger, EXIT_FAILURE, "Switch illegal characters");
+                return ERROR_TOKEN;
         }
         }
     } else if (ch == ')') {
     } else if (ch == ')') {
         switch (parser->lexical->status) {
         switch (parser->lexical->status) {
             case lex_prefix_block_p:
             case lex_prefix_block_p:
                 setLexicalLast(lex_rp, TK_RP, parser);
                 setLexicalLast(lex_rp, TK_RP, parser);
-                return -1;
+                return FINISH_TOKEN;
             case lex_prefix_block_b:
             case lex_prefix_block_b:
                 setLexicalLast(lex_rb, TK_RB, parser);
                 setLexicalLast(lex_rb, TK_RB, parser);
-                return -1;
+                return FINISH_TOKEN;
             case lex_prefix_block_c:
             case lex_prefix_block_c:
                 setLexicalLast(lex_rc, TK_RC, parser);
                 setLexicalLast(lex_rc, TK_RC, parser);
-                return -1;
+                return FINISH_TOKEN;
             default:
             default:
-                printLexicalError(SYS_ERROR_STATUS(lex_prefix_block), parser);
-                return -2;
+                writeFatalErrorLog(aFunCoreLogger, EXIT_FAILURE, "Switch illegal characters");
+                return ERROR_TOKEN;
         }
         }
     }
     }
-    printLexicalError(ILLEGAL_CHAR(lex_prefix_block), parser);
-    return 0;
+    printLexicalError(IllegalChar, parser);
+    return DEL_TOKEN;
 }
 }
 
 
 /*
 /*
  * 状态机图:
  * 状态机图:
  * [lex_comment_before]
  * [lex_comment_before]
- *      -> '\n' || NUL -> [lex_uni_comment_end] # return -1
+ *      -> '\n' || NUL -> [lex_uni_comment_end] # return FINISH_TOKEN
  *      -> ; -> (lex_mutli_comment) # mutli_comment = 0
  *      -> ; -> (lex_mutli_comment) # mutli_comment = 0
  *      -> other -> (lex_uni_comment)
  *      -> other -> (lex_uni_comment)
  */
  */
 static int doneCommentBefore(char ch, af_Parser *parser) {
 static int doneCommentBefore(char ch, af_Parser *parser) {
     if (ch == '\n' || ch == NUL) {
     if (ch == '\n' || ch == NUL) {
         setLexicalLast(lex_uni_comment_end, TK_COMMENT, parser);
         setLexicalLast(lex_uni_comment_end, TK_COMMENT, parser);
-        return -1;
+        return FINISH_TOKEN;
     } else if (ch == ';') {  // 多行注释
     } else if (ch == ';') {  // 多行注释
         parser->lexical->status = lex_mutli_comment;
         parser->lexical->status = lex_mutli_comment;
         parser->lexical->mutli_comment = 0;
         parser->lexical->mutli_comment = 0;
@@ -190,13 +199,13 @@ static int doneCommentBefore(char ch, af_Parser *parser) {
 /*
 /*
  * 状态机图:
  * 状态机图:
  * [lex_uni_comment]
  * [lex_uni_comment]
- *      -> '\n' || NUL -> [lex_uni_comment_end] # return -1
+ *      -> '\n' || NUL -> [lex_uni_comment_end] # return FINISH_TOKEN
  *      -> other -> (lex_uni_comment)
  *      -> other -> (lex_uni_comment)
  */
  */
 static int doneUniComment(char ch, af_Parser *parser) {
 static int doneUniComment(char ch, af_Parser *parser) {
     if (ch == '\n' || ch == NUL) {
     if (ch == '\n' || ch == NUL) {
         setLexicalLast(lex_uni_comment_end, TK_COMMENT, parser);
         setLexicalLast(lex_uni_comment_end, TK_COMMENT, parser);
-        return -1;
+        return FINISH_TOKEN;
     }
     }
     parser->lexical->status = lex_uni_comment;
     parser->lexical->status = lex_uni_comment;
     return 1;
     return 1;
@@ -205,15 +214,15 @@ static int doneUniComment(char ch, af_Parser *parser) {
 /*
 /*
  * 状态机图:
  * 状态机图:
  * [lex_mutli_comment]
  * [lex_mutli_comment]
- *      -> NUL -> [lex_mutli_comment_end] # return -1; [warning]
+ *      -> NUL -> [lex_mutli_comment_end] # return FINISH_TOKEN; [warning]
  *      -> ; -> (lex_mutli_comment_end_before)
  *      -> ; -> (lex_mutli_comment_end_before)
  *      -> other -> (lex_mutli_comment)
  *      -> other -> (lex_mutli_comment)
  */
  */
 static int doneMutliComment(char ch, af_Parser *parser) {
 static int doneMutliComment(char ch, af_Parser *parser) {
     if (ch == NUL) {
     if (ch == NUL) {
         parser->lexical->status = lex_mutli_comment_end;
         parser->lexical->status = lex_mutli_comment_end;
-        printLexicalWarning(INCOMPLETE_FILE(lex_mutli_comment), parser);
-        return -1;
+        printLexicalWarning(IncompleteFile, parser);
+        return FINISH_TOKEN;
     } else if (ch == ';')
     } else if (ch == ';')
         parser->lexical->status = lex_mutli_comment_end_before;
         parser->lexical->status = lex_mutli_comment_end_before;
     else
     else
@@ -224,17 +233,17 @@ static int doneMutliComment(char ch, af_Parser *parser) {
 /*
 /*
  * 状态机图:
  * 状态机图:
  * [lex_mutli_comment_end_before]
  * [lex_mutli_comment_end_before]
- *      -> NUL -> [lex_mutli_comment_end] # return -1; [warning]
+ *      -> NUL -> [lex_mutli_comment_end] # return FINISH_TOKEN; [warning]
  *      -> ; -> (lex_mutli_comment) # mutli_comment++;
  *      -> ; -> (lex_mutli_comment) # mutli_comment++;
  *      -> = ->
  *      -> = ->
- *              mutli_comment == 0 -> [lex_mutli_comment_end] # return -1
+ *              mutli_comment == 0 -> [lex_mutli_comment_end] # return FINISH_TOKEN
  *              else -> (lex_mutli_comment)# mutli_comment--;
  *              else -> (lex_mutli_comment)# mutli_comment--;
  */
  */
 static int doneMutliCommentBeforeEnd(char ch, af_Parser *parser) {
 static int doneMutliCommentBeforeEnd(char ch, af_Parser *parser) {
     if (ch == NUL) {
     if (ch == NUL) {
-        printLexicalWarning(INCOMPLETE_FILE(lex_mutli_comment_end_before), parser);
+        printLexicalWarning(IncompleteFile, parser);
         setLexicalLast(lex_mutli_comment_end, TK_COMMENT, parser);
         setLexicalLast(lex_mutli_comment_end, TK_COMMENT, parser);
-        return -1;
+        return FINISH_TOKEN;
     } else if (ch == ';') {
     } else if (ch == ';') {
         /* 嵌套注释 */
         /* 嵌套注释 */
         parser->lexical->mutli_comment++;
         parser->lexical->mutli_comment++;
@@ -243,7 +252,7 @@ static int doneMutliCommentBeforeEnd(char ch, af_Parser *parser) {
         if (parser->lexical->mutli_comment == 0) {
         if (parser->lexical->mutli_comment == 0) {
             /* 注释结束 */
             /* 注释结束 */
             setLexicalLast(lex_mutli_comment_end, TK_COMMENT, parser);
             setLexicalLast(lex_mutli_comment_end, TK_COMMENT, parser);
-            return -1;
+            return FINISH_TOKEN;
         } else {
         } else {
             /* 嵌套注释 */
             /* 嵌套注释 */
             parser->lexical->mutli_comment--;
             parser->lexical->mutli_comment--;
@@ -266,8 +275,8 @@ static int doneElementLong(char ch, af_Parser *parser) {
         setLexicalLast(lex_element_long_end, TK_ELEMENT_LONG, parser);
         setLexicalLast(lex_element_long_end, TK_ELEMENT_LONG, parser);
         return 1;
         return 1;
     } else if (ch == NUL) {
     } else if (ch == NUL) {
-        printLexicalError(INCOMPLETE_FILE(lex_element_long), parser);
-        return -2;
+        printLexicalError(IncompleteFile, parser);
+        return ERROR_TOKEN;
     }
     }
     parser->lexical->status = lex_element_long;
     parser->lexical->status = lex_element_long;
     return 1;
     return 1;
@@ -277,7 +286,7 @@ static int doneElementLong(char ch, af_Parser *parser) {
  * 状态机图:
  * 状态机图:
  * [lex_element_long]
  * [lex_element_long]
  *      -> | -> (lex_element_long)
  *      -> | -> (lex_element_long)
- *      -> other -> [lex_element_long_end] # return -1
+ *      -> other -> [lex_element_long_end] # return FINISH_TOKEN
  */
  */
 static int doneElementLongEnd(char ch, af_Parser *parser) {
 static int doneElementLongEnd(char ch, af_Parser *parser) {
     if (ch == '|') {  // ||表示非结束
     if (ch == '|') {  // ||表示非结束
@@ -285,14 +294,14 @@ static int doneElementLongEnd(char ch, af_Parser *parser) {
         return 1;
         return 1;
     }
     }
     parser->lexical->status = lex_element_long_end;
     parser->lexical->status = lex_element_long_end;
-    return -1;
+    return FINISH_TOKEN;
 }
 }
 
 
 /*
 /*
  * 状态机图:
  * 状态机图:
  * [lex_element_short]
  * [lex_element_short]
  *      -> !strchr("!@#([{}]);,", ch) && iselement(ch) -> (lex_element_short)
  *      -> !strchr("!@#([{}]);,", ch) && iselement(ch) -> (lex_element_short)
- *      -> other -> (lex_element_short) # return -1
+ *      -> other -> (lex_element_short) # return FINISH_TOKEN
  */
  */
 static int doneElementShort(char ch, af_Parser *parser) {
 static int doneElementShort(char ch, af_Parser *parser) {
     if (!strchr("!@#([{}]);,", ch) && iselement(ch)) {  // 除空格外的可见字符 (不包括NUL)
     if (!strchr("!@#([{}]);,", ch) && iselement(ch)) {  // 除空格外的可见字符 (不包括NUL)
@@ -300,14 +309,14 @@ static int doneElementShort(char ch, af_Parser *parser) {
         return 1;
         return 1;
     }
     }
     parser->lexical->status = lex_element_short;
     parser->lexical->status = lex_element_short;
-    return -1;
+    return FINISH_TOKEN;
 }
 }
 
 
 /*
 /*
  * 状态机图:
  * 状态机图:
  * [lex_space]
  * [lex_space]
  *      -> ch != NUL && isignore(ch) -> (lex_space)
  *      -> ch != NUL && isignore(ch) -> (lex_space)
- *      -> other -> (lex_space) # return -1
+ *      -> other -> (lex_space) # return FINISH_TOKEN
  */
  */
 static int doneSpace(char ch, af_Parser *parser) {
 static int doneSpace(char ch, af_Parser *parser) {
     if (ch != NUL && isignore(ch)) {
     if (ch != NUL && isignore(ch)) {
@@ -315,7 +324,7 @@ static int doneSpace(char ch, af_Parser *parser) {
         return 1;
         return 1;
     }
     }
     parser->lexical->status = lex_space;
     parser->lexical->status = lex_space;
-    return -1;
+    return FINISH_TOKEN;
 }
 }
 
 
 /*
 /*
@@ -331,7 +340,7 @@ af_TokenType getTokenFromLexical(char **text, af_Parser *parser) {
     if (parser->lexical->is_end) {
     if (parser->lexical->is_end) {
         *text = NULL;
         *text = NULL;
         return TK_EOF;
         return TK_EOF;
-    } else if (parser->lexical->is_error || parser->reader->read_error) {
+    } else if (parser->lexical->is_error || parser->reader->read_error) {  /* lexical和reader出现异常后不再执行 */
         *text = NULL;
         *text = NULL;
         return TK_ERROR;
         return TK_ERROR;
     }
     }
@@ -344,7 +353,7 @@ af_TokenType getTokenFromLexical(char **text, af_Parser *parser) {
         }
         }
 
 
         if (isascii(ch) && iscntrl(ch) && !isspace(ch) && ch != NUL)  // ascii 控制字符
         if (isascii(ch) && iscntrl(ch) && !isspace(ch) && ch != NUL)  // ascii 控制字符
-            printLexicalWarning(INCULDE_CONTROL(base), parser);
+            printLexicalWarning(IncludeControlChar, parser);
 
 
         switch (parser->lexical->status) {
         switch (parser->lexical->status) {
             case lex_begin:
             case lex_begin:
@@ -380,12 +389,23 @@ af_TokenType getTokenFromLexical(char **text, af_Parser *parser) {
                 re = doneElementLongEnd(ch, parser);
                 re = doneElementLongEnd(ch, parser);
                 break;
                 break;
             default:
             default:
-                printLexicalError(SYS_ERROR_STATUS(base), parser);
-                re = -3;
+                writeFatalErrorLog(aFunCoreLogger, EXIT_FAILURE, "Switch illegal characters");
+                re = ERROR_TOKEN;
                 break;
                 break;
         }
         }
 
 
-        if (re == -1) {
+        if (re == ERROR_TOKEN) {
+ERROR:
+            tt = TK_ERROR;
+            *text = NULL;
+            break;
+        } else if (re == DEL_TOKEN) {  // 删除该token, 继续执行
+            char *word = readWord(parser->lexical->last, parser->reader);
+            free(word);
+            parser->lexical->status = lex_begin;
+            parser->lexical->last = 0;
+            continue;
+        } else if (re == FINISH_TOKEN) {
             char *word = readWord(parser->lexical->last, parser->reader);
             char *word = readWord(parser->lexical->last, parser->reader);
             if (word == NULL)
             if (word == NULL)
                 goto ERROR;
                 goto ERROR;
@@ -426,18 +446,6 @@ af_TokenType getTokenFromLexical(char **text, af_Parser *parser) {
                 parser->lexical->is_end = true;
                 parser->lexical->is_end = true;
 
 
             break;
             break;
-        } else if (re == 0) {  // 删除该token, 继续执行
-            char *word = readWord(parser->lexical->last, parser->reader);
-            free(word);
-            parser->lexical->status = lex_begin;
-            parser->lexical->last = 0;
-            continue;
-        } else if (re == -2 || re == -3) {
-ERROR:
-            tt = TK_ERROR;
-            *text = NULL;
-            parser->lexical->is_error = true;
-            break;
         }
         }
     }
     }
 
 

+ 42 - 21
src/core/parser.c

@@ -12,9 +12,10 @@ static void freeLexical(af_Lexical *lex);
 static af_Syntactic *makeSyntactic(void);
 static af_Syntactic *makeSyntactic(void);
 static void freeSyntactic(af_Syntactic *syntactic);
 static void freeSyntactic(af_Syntactic *syntactic);
 
 
-af_Parser *makeParser(DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size){
+af_Parser *makeParser(FilePath file, DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func,
+                      size_t data_size){
     af_Parser *parser = calloc(1, sizeof(af_Parser));
     af_Parser *parser = calloc(1, sizeof(af_Parser));
-    parser->reader = makeReader(read_func, destruct_func, data_size);
+    parser->reader = makeReader(1, file, read_func, destruct_func, data_size);
     parser->lexical = makeLexical();
     parser->lexical = makeLexical();
     parser->syntactic = makeSyntactic();
     parser->syntactic = makeSyntactic();
     return parser;
     return parser;
@@ -52,7 +53,15 @@ static void freeSyntactic(af_Syntactic *syntactic) {
 }
 }
 
 
 /* makeParser函数封装 */
 /* makeParser函数封装 */
+#define printReaderError(info, parser, stream) do { \
+    writeErrorLog(aFunCoreLogger, "[Reader] %s:%d %s", (parser)->reader->file, (parser)->reader->line, (info ## Log)); \
+    printf_std##stream(0, "[%s] %s:%d : %s\n", HT_aFunGetText(reader_n, "Reader"), (parser)->reader->file, \
+                  (parser)->reader->line, info ## Console); \
+    (parser)->is_error = true; /* 错误标记在Parser而非Lexical中, Lexical的异常表示lexical停止运行 */ \
+} while(0)
+
 struct readerDataString {
 struct readerDataString {
+    af_Parser *parser;
     char *str;
     char *str;
     bool free_str;
     bool free_str;
     size_t index;
     size_t index;
@@ -77,13 +86,18 @@ static void destructFunc(struct readerDataString *data) {
         free(data->str);
         free(data->str);
 }
 }
 
 
-af_Parser *makeParserByString(char *str, bool free_str){
+static void initStringReader(af_Parser *parser, char *str, bool free_str, struct readerDataString *data) {
+    data->str = str;
+    data->free_str = free_str;
+    data->len = strlen(str);
+    data->parser = parser;
+}
+
+af_Parser *makeParserByString(FilePath name, char *str, bool free_str){
     DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readFuncString, readerFunc);
     DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readFuncString, readerFunc);
     DLC_SYMBOL(destructReaderFunc) destruct = MAKE_SYMBOL(destructFunc, destructReaderFunc);
     DLC_SYMBOL(destructReaderFunc) destruct = MAKE_SYMBOL(destructFunc, destructReaderFunc);
-    af_Parser *parser = makeParser(read_func, destruct, sizeof(struct readerDataString));
-    ((struct readerDataString *)parser->reader->data)->str = str;
-    ((struct readerDataString *)parser->reader->data)->free_str = free_str;
-    ((struct readerDataString *)parser->reader->data)->len = strlen(str);
+    af_Parser *parser = makeParser(name, read_func, destruct, sizeof(struct readerDataString));
+    initStringReader(parser, str, free_str, parser->reader->data);
     initParser(parser);
     initParser(parser);
     FREE_SYMBOL(read_func);
     FREE_SYMBOL(read_func);
     FREE_SYMBOL(destruct);
     FREE_SYMBOL(destruct);
@@ -91,6 +105,7 @@ af_Parser *makeParserByString(char *str, bool free_str){
 }
 }
 
 
 struct readerDataFile {
 struct readerDataFile {
+    af_Parser *parser;
     FILE *file;
     FILE *file;
     bool no_first;
     bool no_first;
 };
 };
@@ -108,8 +123,7 @@ static size_t readFuncFile(struct readerDataFile *data, char *dest, size_t len,
             /* 处理BOM编码 */
             /* 处理BOM编码 */
             char ch_[2];
             char ch_[2];
             if (fread(ch_, sizeof(char), 2, data->file) != 2 || ch_[0] != (char)0xBB || ch_[1] != (char)0xBF) {
             if (fread(ch_, sizeof(char), 2, data->file) != 2 || ch_[0] != (char)0xBB || ch_[1] != (char)0xBF) {
-                writeErrorLog(aFunCoreLogger, "Parser utf-8 with error BOM");
-                printf_stderr(0, HT_aFunGetText(error_bom, "Read utf-8 file with bad bom."));
+                printReaderError(BOMError, data->parser, err);
                 *mode = READER_MODE_ERROR;
                 *mode = READER_MODE_ERROR;
                 return 0;
                 return 0;
             }
             }
@@ -123,7 +137,7 @@ static size_t readFuncFile(struct readerDataFile *data, char *dest, size_t len,
     size_t len_r =  fread(dest, sizeof(char), len, data->file);
     size_t len_r =  fread(dest, sizeof(char), len, data->file);
     if (CLEAR_FERROR(data->file)) {  // ferror在feof前执行
     if (CLEAR_FERROR(data->file)) {  // ferror在feof前执行
         *mode = READER_MODE_ERROR;
         *mode = READER_MODE_ERROR;
-        printf_stderr(0, HT_aFunGetText(stdin_error, "The file io error/eof"));
+        printReaderError(FileIOError, data->parser, err);
     } else if (feof(data->file))
     } else if (feof(data->file))
         *mode = READER_MODE_FINISHED;
         *mode = READER_MODE_FINISHED;
     return len_r;
     return len_r;
@@ -134,6 +148,11 @@ static void destructFile(struct readerDataFile *data) {
         fclose(data->file);
         fclose(data->file);
 }
 }
 
 
+static void initFileReader(af_Parser *parser, FILE *file, struct readerDataFile *data) {
+    data->file = file;
+    data->parser = parser;
+}
+
 af_Parser *makeParserByFile(FilePath path){
 af_Parser *makeParserByFile(FilePath path){
     FILE *file = fopen(path, "rb");
     FILE *file = fopen(path, "rb");
     if (file == NULL) {
     if (file == NULL) {
@@ -144,8 +163,8 @@ af_Parser *makeParserByFile(FilePath path){
 
 
     DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readFuncFile, readerFunc);
     DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readFuncFile, readerFunc);
     DLC_SYMBOL(destructReaderFunc) destruct = MAKE_SYMBOL(destructFile, destructReaderFunc);
     DLC_SYMBOL(destructReaderFunc) destruct = MAKE_SYMBOL(destructFile, destructReaderFunc);
-    af_Parser *parser = makeParser(read_func, destruct, sizeof(struct readerDataString));
-    ((struct readerDataFile *)parser->reader->data)->file = file;
+    af_Parser *parser = makeParser(path, read_func, destruct, sizeof(struct readerDataString));
+    initFileReader(parser, file, parser->reader->data);
     initParser(parser);
     initParser(parser);
     FREE_SYMBOL(read_func);
     FREE_SYMBOL(read_func);
     FREE_SYMBOL(destruct);
     FREE_SYMBOL(destruct);
@@ -153,6 +172,7 @@ af_Parser *makeParserByFile(FilePath path){
 }
 }
 
 
 struct readerDataStdin {
 struct readerDataStdin {
+    af_Parser *parser;
     bool no_first;
     bool no_first;
 
 
     void *sig_int;
     void *sig_int;
@@ -190,8 +210,7 @@ static bool getStdinSignalFunc(void) {
 static size_t readFuncStdin(struct readerDataStdin *data, char *dest, size_t len, int *mode) {
 static size_t readFuncStdin(struct readerDataStdin *data, char *dest, size_t len, int *mode) {
     if (data->index == data->len) {  // 读取内容
     if (data->index == data->len) {  // 读取内容
         if (CLEAR_STDIN()) {
         if (CLEAR_STDIN()) {
-            writeErrorLog(aFunCoreLogger, "The stdin IO error, %d, %d", ferror(stdin), feof(stdin));
-            printf_stderr(0, HT_aFunGetText(stdin_error, ""));
+            printReaderError(StdinError, data->parser, err);
             *mode = READER_MODE_ERROR;
             *mode = READER_MODE_ERROR;
             return 0;
             return 0;
         }
         }
@@ -210,7 +229,9 @@ static size_t readFuncStdin(struct readerDataStdin *data, char *dest, size_t len
         /* 在Windows平台则是根据读取的最后一个字符是否为\n或者是否有按键按下来确定缓冲区是否有内容 */
         /* 在Windows平台则是根据读取的最后一个字符是否为\n或者是否有按键按下来确定缓冲区是否有内容 */
         while (!checkStdin()) {  // 无内容则一直循环等到
         while (!checkStdin()) {  // 无内容则一直循环等到
             if (getStdinSignalFunc()) {  // 设置了中断函数, 并且该函数返回0
             if (getStdinSignalFunc()) {  // 设置了中断函数, 并且该函数返回0
-                printf_stdout(0, "\n %s \n", HT_aFunGetText(Interrupt_n, "Interrupt"));
+                writeErrorLog(aFunCoreLogger, "Interrupt");
+                printf_stdout(0, "%s\n", HT_aFunGetText(Interrupt_n, "Interrupt"));
+                data->parser->is_error = true;
                 *mode = READER_MODE_ERROR;
                 *mode = READER_MODE_ERROR;
                 return 0;
                 return 0;
             }
             }
@@ -227,8 +248,7 @@ static size_t readFuncStdin(struct readerDataStdin *data, char *dest, size_t len
 
 
         /* 读取内容的长度不得少于STDIN_MAX_SZIE, 否则可能导致编码转换错误 */
         /* 读取内容的长度不得少于STDIN_MAX_SZIE, 否则可能导致编码转换错误 */
         if (fgets_stdin(&data->data, STDIN_MAX_SIZE) == 0) {
         if (fgets_stdin(&data->data, STDIN_MAX_SIZE) == 0) {
-            writeErrorLog(aFunCoreLogger, "The stdin buf too large (> %d)", STDIN_MAX_SIZE);
-            printf_stderr(0, "%s (> %d)", HT_aFunGetText(stdin_too_large, "The stdin buf too large"), STDIN_MAX_SIZE);
+            printReaderError(TooMuchInputError, data->parser, err);
             *mode = READER_MODE_ERROR;
             *mode = READER_MODE_ERROR;
             return 0;
             return 0;
         }
         }
@@ -252,19 +272,20 @@ static void destructStdin(struct readerDataStdin *data) {
         signal(SIGTERM, data->sig_term);
         signal(SIGTERM, data->sig_term);
 }
 }
 
 
-static void initStdin(struct readerDataStdin *data) {
+static void initStdinReader(af_Parser *parser, struct readerDataStdin *data) {
     stdin_interrupt = 0;
     stdin_interrupt = 0;
     setStdinSignalFunc(data);
     setStdinSignalFunc(data);
+    data->parser = parser;
 }
 }
 
 
-af_Parser *makeParserByStdin(){
+af_Parser *makeParserByStdin(FilePath file){
     if (CLEAR_FERROR(stdin))
     if (CLEAR_FERROR(stdin))
         return NULL;
         return NULL;
 
 
     DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readFuncStdin, readerFunc);
     DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readFuncStdin, readerFunc);
     DLC_SYMBOL(destructReaderFunc) destruct = MAKE_SYMBOL(destructStdin, destructReaderFunc);
     DLC_SYMBOL(destructReaderFunc) destruct = MAKE_SYMBOL(destructStdin, destructReaderFunc);
-    af_Parser *parser = makeParser(read_func, destruct, sizeof(struct readerDataStdin));
-    initStdin(parser->reader->data);
+    af_Parser *parser = makeParser(file, read_func, destruct, sizeof(struct readerDataStdin));
+    initStdinReader(parser, parser->reader->data);
     initParser(parser);
     initParser(parser);
     FREE_SYMBOL(read_func);
     FREE_SYMBOL(read_func);
     FREE_SYMBOL(destruct);
     FREE_SYMBOL(destruct);

+ 27 - 4
src/core/reader.c

@@ -1,7 +1,9 @@
 #include "core_init.h"
 #include "core_init.h"
 #include "__reader.h"
 #include "__reader.h"
+static void readFirstWord(af_Reader *reader);
 
 
-af_Reader *makeReader(DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size) {
+af_Reader *makeReader(FileLine line, FilePath file, DLC_SYMBOL(readerFunc) read_func,
+                      DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size){
     af_Reader *reader = calloc(1, sizeof(af_Reader));
     af_Reader *reader = calloc(1, sizeof(af_Reader));
     reader->read_func = COPY_SYMBOL(read_func, readerFunc);
     reader->read_func = COPY_SYMBOL(read_func, readerFunc);
     reader->destruct = COPY_SYMBOL(destruct_func, destructReaderFunc);
     reader->destruct = COPY_SYMBOL(destruct_func, destructReaderFunc);
@@ -12,16 +14,17 @@ af_Reader *makeReader(DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReade
     reader->buf = NEW_STR(DEFAULT_BUF_SIZE);
     reader->buf = NEW_STR(DEFAULT_BUF_SIZE);
     reader->buf_size = DEFAULT_BUF_SIZE;  // buf_size 不包括NUL
     reader->buf_size = DEFAULT_BUF_SIZE;  // buf_size 不包括NUL
     reader->read = reader->buf;
     reader->read = reader->buf;
+
+    reader->line = line;
+    reader->file = strCopy(file);
     return reader;
     return reader;
 }
 }
 
 
 af_Reader *initReader(af_Reader *reader) {
 af_Reader *initReader(af_Reader *reader) {
     if (reader->init)
     if (reader->init)
         return reader;
         return reader;
-    char *new = readWord(reader->buf_size, reader);  // 写入数据
-    free(new);
+    readFirstWord(reader);
     reader->init = true;
     reader->init = true;
-    reader->line = 1;
     return reader;
     return reader;
 }
 }
 
 
@@ -30,6 +33,7 @@ void freeReader(af_Reader *reader) {
         GET_SYMBOL(reader->destruct)(reader->data);
         GET_SYMBOL(reader->destruct)(reader->data);
     free(reader->data);
     free(reader->data);
     free(reader->buf);
     free(reader->buf);
+    free(reader->file);
     FREE_SYMBOL(reader->read_func);
     FREE_SYMBOL(reader->read_func);
     FREE_SYMBOL(reader->destruct);
     FREE_SYMBOL(reader->destruct);
     free(reader);
     free(reader);
@@ -82,6 +86,25 @@ char *readWord(size_t del_index, af_Reader *reader) {
     return re;
     return re;
 }
 }
 
 
+static void readFirstWord(af_Reader *reader) {
+    int mode = READER_MODE_NORMAL;
+    reader->read = reader->buf;  // 重置指针
+
+    char *write = reader->buf + STR_LEN(reader->buf);  // 数据写入的位置
+    size_t len_ = reader->buf_size - STR_LEN(reader->buf);
+    size_t len = GET_SYMBOL(reader->read_func)(reader->data, write, len_, &mode);
+    if (len > len_)
+        len = len_;
+    *(write + len) = NUL;
+
+    if (mode == READER_MODE_FINISHED)
+        reader->read_end = true;
+    else if (mode == READER_MODE_ERROR) {
+        reader->read_end = true;
+        reader->read_error = true;
+    }
+}
+
 char getChar(af_Reader *reader) {
 char getChar(af_Reader *reader) {
     char ch = *(reader->read);
     char ch = *(reader->read);
     if (ch != NUL) {  // 未读取到末尾
     if (ch != NUL) {  // 未读取到末尾

+ 26 - 26
src/core/syntactic.c

@@ -4,14 +4,12 @@
 #include "__parser.h"
 #include "__parser.h"
 #include "parserl_warning_error.h"
 #include "parserl_warning_error.h"
 
 
-static void printSyntacticError(char *info, af_Parser *parser) {
-    writeErrorLog(aFunCoreLogger, "[Syntactic] %s", info);
-    parser->is_error = true;
-}
-
-static void printSyntacticWarning(char *info, af_Parser *parser) {
-    writeWarningLog(aFunCoreLogger, "[Syntactic] %s", info);
-}
+#define printSyntacticError(info, parser) do { \
+    writeErrorLog(aFunCoreLogger, "[Syntactic] %s:%d %s", (parser)->reader->file, (parser)->reader->line, (info ## Log)); \
+    printf_stderr(0, "[%s] %s:%d : %s\n", HT_aFunGetText(syntactic_n, "Syntactic"), (parser)->reader->file,               \
+                  (parser)->reader->line, info ## Console); \
+    (parser)->is_error = true; \
+} while(0)
 
 
 static bool getToken(af_Parser *parser) {
 static bool getToken(af_Parser *parser) {
     if (parser->syntactic->back) {
     if (parser->syntactic->back) {
@@ -53,7 +51,7 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
             if (deep <= SYNTACTIC_MAX_DEEP)
             if (deep <= SYNTACTIC_MAX_DEEP)
                 code_list = codeList(deep, parser);
                 code_list = codeList(deep, parser);
             else
             else
-                printSyntacticError(SYNTACTIC_TOO_DEEP(), parser);
+                printSyntacticError(TooDeep, parser);
 
 
             getToken(parser);
             getToken(parser);
             switch (parser->syntactic->token) {
             switch (parser->syntactic->token) {
@@ -64,7 +62,7 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
                     return NULL;
                     return NULL;
                 default:
                 default:
                     goBackToken(parser);
                     goBackToken(parser);
-                    printSyntacticError(CodeEndError(") or !)"), parser);
+                    printSyntacticError(CodeBlockEndError, parser);
                     break;
                     break;
             }
             }
 
 
@@ -74,7 +72,7 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
             if (deep <= SYNTACTIC_MAX_DEEP)
             if (deep <= SYNTACTIC_MAX_DEEP)
                 code_list = codeList(deep, parser);
                 code_list = codeList(deep, parser);
             else
             else
-                printSyntacticError(SYNTACTIC_TOO_DEEP(), parser);
+                printSyntacticError(TooDeep, parser);
 
 
             getToken(parser);
             getToken(parser);
             switch (parser->syntactic->token) {
             switch (parser->syntactic->token) {
@@ -85,7 +83,7 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
                     return NULL;
                     return NULL;
                 default:
                 default:
                     goBackToken(parser);
                     goBackToken(parser);
-                    printSyntacticError(CodeEndError("] or @)"), parser);
+                    printSyntacticError(CodeBlockEndError, parser);
                     break;
                     break;
             }
             }
 
 
@@ -95,7 +93,7 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
             if (deep <= SYNTACTIC_MAX_DEEP)
             if (deep <= SYNTACTIC_MAX_DEEP)
                 code_list = codeList(deep, parser);
                 code_list = codeList(deep, parser);
             else
             else
-                printSyntacticError(SYNTACTIC_TOO_DEEP(), parser);
+                printSyntacticError(TooDeep, parser);
 
 
             getToken(parser);
             getToken(parser);
             switch (parser->syntactic->token) {
             switch (parser->syntactic->token) {
@@ -106,7 +104,7 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
                     return NULL;
                     return NULL;
                 default:
                 default:
                     goBackToken(parser);
                     goBackToken(parser);
-                    printSyntacticError(CodeEndError("} or #)"), parser);
+                    printSyntacticError(CodeBlockEndError, parser);
                     break;
                     break;
             }
             }
 
 
@@ -115,12 +113,12 @@ static af_Code *code(size_t deep, char prefix, af_Parser *parser) {
         case TK_ERROR:
         case TK_ERROR:
             return NULL;
             return NULL;
         default:
         default:
-            printSyntacticError(CodeStartError(), parser);
+            printSyntacticError(CodeBlockEndError, parser);
             return NULL;
             return NULL;
     }
     }
 
 
     if (re == NULL)
     if (re == NULL)
-        printSyntacticError(MakeCodeFail(), parser);
+        printSyntacticError(MakeCodeFail, parser);
     return re;
     return re;
 }
 }
 
 
@@ -129,9 +127,9 @@ static af_Code *codePrefix(size_t deep, af_Parser *parser) {
     getToken(parser);
     getToken(parser);
     if (parser->syntactic->token != TK_PREFIX) {
     if (parser->syntactic->token != TK_PREFIX) {
         goBackToken(parser);
         goBackToken(parser);
-        printSyntacticError(PREFIX_ERROR(codePrefix), parser);
+        printSyntacticError(PrefixError, parser);
     } else if (STR_LEN( parser->syntactic->text) != 1) {
     } else if (STR_LEN( parser->syntactic->text) != 1) {
-        printSyntacticError(PREFIX_ERROR(codePrefix), parser);
+        printSyntacticError(PrefixError, parser);
         free(parser->syntactic->text);
         free(parser->syntactic->text);
     } else {
     } else {
         ch = *(parser->syntactic->text);
         ch = *(parser->syntactic->text);
@@ -203,7 +201,7 @@ static af_Code *codeListEnd(af_Parser *parser) {
                     freeAllCode(re);
                     freeAllCode(re);
                     return NULL;
                     return NULL;
                 default:
                 default:
-                    printSyntacticError(CodeListEndError(), parser);
+                    printSyntacticError(CodeListEndError, parser);
                     freeAllCode(re);
                     freeAllCode(re);
                     return NULL;
                     return NULL;
             }
             }
@@ -211,24 +209,26 @@ static af_Code *codeListEnd(af_Parser *parser) {
         case TK_ERROR:
         case TK_ERROR:
             return NULL;
             return NULL;
         default:
         default:
-            printSyntacticError(CodeListStartError(), parser);
+            printSyntacticError(CodeListStartError, parser);
             return NULL;
             return NULL;
     }
     }
 
 
     return re;
     return re;
 }
 }
 
 
-af_Code *parserCode(FilePath file, af_Parser *parser) {
+af_Code *parserCode(af_Parser *parser){
     af_Code *code = codeListEnd(parser);
     af_Code *code = codeListEnd(parser);
-    if (file == NULL)
-        return NULL;
-
     if (parser->is_error || parser->reader->read_error || parser->lexical->is_error) {
     if (parser->is_error || parser->reader->read_error || parser->lexical->is_error) {
         freeAllCode(code);
         freeAllCode(code);
         return NULL;
         return NULL;
     }
     }
 
 
-    if (code != NULL)
-        code->path = pathCopy(file);
+    if (code != NULL) {
+        if (parser->reader->file != NULL)
+            code->path = pathCopy(parser->reader->file);
+        else
+            code->path = pathCopy("unknown.aun");
+    }
+
     return code;
     return code;
 }
 }

+ 9 - 9
src/runtime/aFunlang.c

@@ -10,7 +10,7 @@
 #include "unistd.h"
 #include "unistd.h"
 #endif
 #endif
 
 
-static int runCode_(FilePath name, af_Parser *parser, int mode, FilePath save_path, af_Environment *env);
+static int runCode_(af_Parser *parser, int mode, FilePath save_path, af_Environment *env);
 static bool aFunInit_mark = false;
 static bool aFunInit_mark = false;
 
 
 bool aFunInit(aFunInitInfo *info) {
 bool aFunInit(aFunInitInfo *info) {
@@ -93,11 +93,11 @@ void destructAFunEnvironment(af_Environment *env) {
     freeEnvironment(env);
     freeEnvironment(env);
 }
 }
 
 
-static int runCode_(FilePath name, af_Parser *parser, int mode, FilePath save_path, af_Environment *env){
+static int runCode_(af_Parser *parser, int mode, FilePath save_path, af_Environment *env){
     if (parser == NULL)
     if (parser == NULL)
         return -1;
         return -1;
 
 
-    af_Code *bt_code = parserCode(name, parser);
+    af_Code *bt_code = parserCode(parser);
     freeParser(parser);
     freeParser(parser);
     if (bt_code == NULL)
     if (bt_code == NULL)
         return -2;
         return -2;
@@ -130,8 +130,8 @@ int runCodeFromString(char *code, char *string_name, int mode, af_Environment *e
     if (string_name == NULL)
     if (string_name == NULL)
         string_name = "string-code.aun";
         string_name = "string-code.aun";
 
 
-    af_Parser *parser = makeParserByString(code, false);
-    return runCode_(string_name, parser, mode, NULL, env);
+    af_Parser *parser = makeParserByString(string_name, code, false);
+    return runCode_(parser, mode, NULL, env);
 }
 }
 
 
 /*
 /*
@@ -159,7 +159,7 @@ int runCodeFromFileSource(FilePath file, bool save_afb, FilePath save_path, int
         save_path = NULL;
         save_path = NULL;
 
 
     af_Parser *parser = makeParserByFile(file);
     af_Parser *parser = makeParserByFile(file);
-    int exit_code = runCode_(file, parser, mode, save_path, env);
+    int exit_code = runCode_(parser, mode, save_path, env);
     if (free_save_path)
     if (free_save_path)
         free(save_path);
         free(save_path);
     return exit_code;
     return exit_code;
@@ -176,8 +176,8 @@ int runCodeFromStdin(char *name, af_Environment *env){
     if (name == NULL)
     if (name == NULL)
         name = "sys-stdin.aun";
         name = "sys-stdin.aun";
 
 
-    af_Parser *parser = makeParserByStdin();
-    return runCode_(name, parser, 0, NULL, env);
+    af_Parser *parser = makeParserByStdin(name);
+    return runCode_(parser, 0, NULL, env);
 }
 }
 
 
 /*
 /*
@@ -290,7 +290,7 @@ int buildFile(FilePath out, FilePath in){
     }
     }
 
 
     af_Parser *parser = makeParserByFile(in);
     af_Parser *parser = makeParserByFile(in);
-    af_Code *code = parserCode(in, parser);
+    af_Code *code = parserCode(parser);
     freeParser(parser);
     freeParser(parser);
     if (code == NULL)
     if (code == NULL)
         return -2;
         return -2;

+ 15 - 2
src/tool/stdio_.c

@@ -215,6 +215,9 @@ static int fcheck_stdin(HANDLE *std_i, HANDLE *std_o) {
 }
 }
 
 
 int fgetc_stdin(void) {
 int fgetc_stdin(void) {
+    if (!_isatty(_fileno(stdin)))
+        return fgetc(stdin);
+
     HANDLE *std_i = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE *std_i = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE *std_o = GetStdHandle(STD_OUTPUT_HANDLE);
     HANDLE *std_o = GetStdHandle(STD_OUTPUT_HANDLE);
     if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
     if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
@@ -231,6 +234,9 @@ int fgetc_stdin(void) {
 }
 }
 
 
 char *fgets_stdin_(char *buf, size_t len) {
 char *fgets_stdin_(char *buf, size_t len) {
+    if (!_isatty(_fileno(stdin)))
+        return fgets(buf, len, stdin);
+
     HANDLE *std_i = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE *std_i = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE *std_o = GetStdHandle(STD_OUTPUT_HANDLE);
     HANDLE *std_o = GetStdHandle(STD_OUTPUT_HANDLE);
     if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
     if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
@@ -252,6 +258,11 @@ char *fgets_stdin_(char *buf, size_t len) {
 }
 }
 
 
 bool fclear_stdin(void) {
 bool fclear_stdin(void) {
+    if (!_isatty(_fileno(stdin))) {
+        rewind(stdin);  // 仅 winAPI 可用
+        return true;
+    }
+
     HANDLE *std_o = GetStdHandle(STD_OUTPUT_HANDLE);
     HANDLE *std_o = GetStdHandle(STD_OUTPUT_HANDLE);
     if (std_o == INVALID_HANDLE_VALUE)
     if (std_o == INVALID_HANDLE_VALUE)
         return true;
         return true;
@@ -287,9 +298,7 @@ static int convertMultiByte(char **dest, char *str, UINT from, UINT to) {
 }
 }
 
 
 int fgets_stdin(char **dest, int len) {
 int fgets_stdin(char **dest, int len) {
-    char *wstr = calloc(len, sizeof(char));
     int re = 0;
     int re = 0;
-
     if (!_isatty(_fileno(stdin))) {
     if (!_isatty(_fileno(stdin))) {
         *dest = NEW_STR(len);
         *dest = NEW_STR(len);
         re = fgets(*dest, len, stdin) != NULL;
         re = fgets(*dest, len, stdin) != NULL;
@@ -298,6 +307,7 @@ int fgets_stdin(char **dest, int len) {
         return re;
         return re;
     }
     }
 
 
+    char *wstr = calloc(len, sizeof(char));
     UINT code_page = GetConsoleCP();
     UINT code_page = GetConsoleCP();
     if (fgets_stdin_(wstr, len) != NULL)
     if (fgets_stdin_(wstr, len) != NULL)
         re = convertMultiByte(dest, wstr, code_page, CP_UTF8);
         re = convertMultiByte(dest, wstr, code_page, CP_UTF8);
@@ -305,6 +315,9 @@ int fgets_stdin(char **dest, int len) {
 }
 }
 
 
 int fungetc_stdin(int ch) {
 int fungetc_stdin(int ch) {
+    if (!_isatty(_fileno(stdin)))
+        return ungetc(ch, stdin);
+
     if (ch == 0 || index == 0 && end == BUFF_SIZE)
     if (ch == 0 || index == 0 && end == BUFF_SIZE)
         return 0;
         return 0;
 
 

+ 1 - 1
test/src/lexical.c

@@ -19,7 +19,7 @@ char *str = "Hello_var\n"
             ";= var-300\n";
             ";= var-300\n";
 
 
 int main() {
 int main() {
-    af_Parser *parser = makeParserByString(str, false);
+    af_Parser *parser = makeParserByString("test1", str, false);
     af_TokenType tt;
     af_TokenType tt;
     char *text = NULL;
     char *text = NULL;
 
 

+ 4 - 3
test/src/reader.c

@@ -10,7 +10,8 @@ DEFINE_DLC_SYMBOL(readerFunc);
 typedef void destructReaderFunc(void *data);
 typedef void destructReaderFunc(void *data);
 DEFINE_DLC_SYMBOL(destructReaderFunc);
 DEFINE_DLC_SYMBOL(destructReaderFunc);
 
 
-af_Reader *makeReader(DLC_SYMBOL(readerFunc) read_func, DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size);
+af_Reader * makeReader(FileLine line, FilePath file, DLC_SYMBOL(readerFunc) read_func,
+                       DLC_SYMBOL(destructReaderFunc) destruct_func, size_t data_size);
 void freeReader(af_Reader *reader);
 void freeReader(af_Reader *reader);
 af_Reader *initReader(af_Reader *reader);
 af_Reader *initReader(af_Reader *reader);
 void *getReaderData(af_Reader *reader);
 void *getReaderData(af_Reader *reader);
@@ -39,7 +40,7 @@ int main() {
     {
     {
         DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readTest, readerFunc);
         DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readTest, readerFunc);
         DLC_SYMBOL(destructReaderFunc) destruct_func = MAKE_SYMBOL(destructTest, destructReaderFunc);
         DLC_SYMBOL(destructReaderFunc) destruct_func = MAKE_SYMBOL(destructTest, destructReaderFunc);
-        af_Reader *reader = makeReader(read_func, destruct_func, sizeof(int));
+        af_Reader *reader = makeReader(1, "test1", read_func, destruct_func, sizeof(int));
         *(int *) getReaderData(reader) = 0;
         *(int *) getReaderData(reader) = 0;
         initReader(reader);
         initReader(reader);
         FREE_SYMBOL(read_func);
         FREE_SYMBOL(read_func);
@@ -59,7 +60,7 @@ int main() {
     {
     {
         DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readTest, readerFunc);
         DLC_SYMBOL(readerFunc) read_func = MAKE_SYMBOL(readTest, readerFunc);
         DLC_SYMBOL(destructReaderFunc) destruct_func = MAKE_SYMBOL(destructTest, destructReaderFunc);
         DLC_SYMBOL(destructReaderFunc) destruct_func = MAKE_SYMBOL(destructTest, destructReaderFunc);
-        af_Reader *reader = makeReader(read_func, destruct_func, sizeof(int));
+        af_Reader *reader = makeReader(1, "test2", read_func, destruct_func, sizeof(int));
         *(int *) getReaderData(reader) = 0;
         *(int *) getReaderData(reader) = 0;
         initReader(reader);
         initReader(reader);
         FREE_SYMBOL(read_func);
         FREE_SYMBOL(read_func);

+ 3 - 3
test/src/syntactic.c

@@ -20,8 +20,8 @@ int main() {
 }
 }
 
 
 void test1(void) {
 void test1(void) {
-    af_Parser *parser = makeParserByString(str, false);
-    af_Code *code = parserCode("test1.aun", parser);
+    af_Parser *parser = makeParserByString("test2", str, false);
+    af_Code *code = parserCode(parser);
     freeParser(parser);
     freeParser(parser);
     freeAllCode(code);
     freeAllCode(code);
 }
 }
@@ -41,7 +41,7 @@ void test2(void) {
     fclose(file);
     fclose(file);
 
 
     af_Parser *parser = makeParserByFile(path);
     af_Parser *parser = makeParserByFile(path);
-    af_Code *code = parserCode("test2.aun", parser);
+    af_Code *code = parserCode(parser);
     printCode(code);
     printCode(code);
     freeParser(parser);
     freeParser(parser);
     freeAllCode(code);
     freeAllCode(code);