Просмотр исходного кода

feat: HuanGetText支持设定base_name

SongZihuan 3 лет назад
Родитель
Сommit
d74b62ad3e
7 измененных файлов с 72 добавлено и 59 удалено
  1. 1 1
      include/tool/tool.h
  2. 8 4
      lang/hgt.cmake
  3. 37 28
      lang/hgt.py
  4. 2 2
      src/core/core_init.c
  5. 12 12
      src/main.c
  6. 3 3
      src/main_build.c
  7. 9 9
      src/runtime/aFunlang.c

+ 1 - 1
include/tool/tool.h

@@ -25,6 +25,6 @@
 #include "log.h"
 
 #include "fflags.h"
-#include "_ht.h"
+#include "aFun_ht.h"
 
 #endif //AFUN_TOOL_H

+ 8 - 4
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(${CMAKE_CURRENT_LIST_DIR}/tr tr_n)
 to_native_path(${CMAKE_SOURCE_DIR}/src src_n)
+set(hgt_name aFun)
 
 set(HGT_COMMAND
     "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_LIST_DIR}/hgt.py"
@@ -13,6 +14,7 @@ set(HGT_COMMAND
     baseHTExport
     BASEHT_EXPORT
     ${tr_n}
+    ${hgt_name}
     ${src_n})
 
 unset(hgt_dir_n)
@@ -36,8 +38,8 @@ endif()
 
 add_library(hgt-base SHARED)
 target_sources(hgt-base
-               PRIVATE ${hgt_dir}/_ht.c
-               PUBLIC $<BUILD_INTERFACE:${hgt_dir}/_ht.h> $<INSTALL_INTERFACE:${INSTALL_INCLUDEDIR}/_ht.h>)
+               PRIVATE ${hgt_dir}/${hgt_name}_ht.c
+               PUBLIC $<BUILD_INTERFACE:${hgt_dir}/${hgt_name}_ht.h> $<INSTALL_INTERFACE:${INSTALL_INCLUDEDIR}/${hgt_name}_ht.h>)
 target_link_libraries(hgt-base ${dlfcn_lib})
 add_dependencies(hgt-base hgt)
 set(hgt-lib hgt-base)
@@ -48,7 +50,7 @@ generate_export_header(hgt-base EXPORT_FILE_NAME "${hgt_dir}/baseHTExport.h" BAS
 target_include_directories(hgt-base PUBLIC
                            $<BUILD_INTERFACE:${hgt_dir}>
                            $<INSTALL_INTERFACE:${INSTALL_INCLUDEDIR}>)
-set_target_properties(hgt-base PROPERTIES PUBLIC_HEADER "${hgt_dir}/_ht.h")
+set_target_properties(hgt-base PROPERTIES PUBLIC_HEADER "${hgt_dir}/${hgt_name}_ht.h")
 
 install(TARGETS hgt-base
         EXPORT aFunlang
@@ -86,4 +88,6 @@ build_lang()  # 使用函数防止 CMAKE_RUNTIME_OUTPUT_DIRECTORY 影响外部
 add_custom_command(TARGET hgt-zh_cn
                    COMMAND ${CMAKE_COMMAND} -E echo "$<TARGET_FILE_NAME:hgt-zh_cn>" ">>" "LANG"
                    WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/${INSTALL_LANGDIR}"
-                   COMMENT "Creat file ${CMAKE_BINARY_DIR}/${INSTALL_LANGDIR}/LANG")
+                   COMMENT "Creat file ${CMAKE_BINARY_DIR}/${INSTALL_LANGDIR}/LANG")
+
+unset(hgt-name)

+ 37 - 28
lang/hgt.py

@@ -23,28 +23,30 @@ if __name__ != '__main__':
     raise RunError()
 
 argv = sys.argv
-if len(argv) < 6:
-    print(f"{len(argv)}")
+if len(argv) < 7:
+    warnings.warn(f"Too few argument [{len(argv)}]")
     raise ArgError()
 
 output_dir = argv[1]
 export_h = argv[2]
 export = argv[3]
 translation = argv[4]
-input_dir = argv[5:]
+base_name = argv[5]
+input_dir = argv[6:]
 translation_output = os.path.join(output_dir, "tr")
 base_tr_file = os.path.join(translation, "base.py")
 
 try:
-    os.makedirs(output_dir)
+    os.makedirs(output_dir)  # 生成输出目录
 except OSError:
     ...
 
 try:
-    os.makedirs(translation_output)
+    os.makedirs(translation_output)  # 生成tr目录
 except OSError:
     ...
 
+# 执行base.py代码, 并保存结果
 base_tr = {}
 if os.path.exists(base_tr_file):
     with open(base_tr_file, "r", encoding="utf-8") as f:
@@ -53,6 +55,12 @@ if os.path.exists(base_tr_file):
 
 
 def getFileFromPath(paths: List[str], file_type_: str) -> FileList:
+    """
+    函数名: 获取目录列表中所有指定后缀的文件
+    :param paths: 目录列表
+    :param file_type_: 指定后在
+    :return: 文件列表
+    """
     tmp: FileList = []
     for path in paths:
         for file_path, dir_names, file_names in os.walk(path):
@@ -63,8 +71,9 @@ def getFileFromPath(paths: List[str], file_type_: str) -> FileList:
     return tmp
 
 
+# 获取宏 HT_aFunGetText的列表并计算
 file_list: FileList = getFileFromPath(input_dir, '.c')
-pattern = re.compile(r'HT_getText\(([\S]+),[\s]*(\"[^\"]*\")\)')
+pattern = re.compile(f'HT_{base_name}GetText' + r'\(([\S]+),[\s]*(\"[^\"]*\")\)')  # 宏的定义
 flat_list: FlatList = {}
 for file in file_list:
     with open(file, "r", encoding="utf-8") as f:
@@ -87,50 +96,50 @@ for file in file_list:
                 flat_list[i[0]] = (default_,)  # 生成一个数组
             data = f.readline()
 
-with open(os.path.join(output_dir, f"_ht.py"), "w", encoding="utf-8") as fpy:
-    with open(os.path.join(output_dir, f"_ht.c"), "w", encoding="utf-8") as fc:
-        with open(os.path.join(output_dir, f"_ht.h"), "w", encoding="utf-8") as fh:
+# 生成对应文件
+with open(os.path.join(output_dir, f"{base_name}_ht.py"), "w", encoding="utf-8") as fpy:
+    with open(os.path.join(output_dir, f"{base_name}_ht.c"), "w", encoding="utf-8") as fc:
+        with open(os.path.join(output_dir, f"{base_name}_ht.h"), "w", encoding="utf-8") as fh:
             head = f'''/*
- * File: _ht.c/_ht.c
+ * File: {base_name}_ht.c/{base_name}_ht.c
  * The file is automatically generated by Huan-GetText
  * Encoding: utf-8
  */'''
             fc.write(head + '\n\n')
-            fc.write(f"#include \"_ht.h\"\n")
-            fc.write("#undef HT_getText\n")
+            fc.write(f"#include \"{base_name}_ht.h\"\n")
+            fc.write(f"#undef HT_{base_name}GetText\n")
 
             fh.write(head + '\n\n')
             fh.write("#ifndef HT_GETTEXT_H\n")
             fh.write("#define HT_GETTEXT_H\n")
 
-            fh.write("#ifdef HT_getText\n")
-            fh.write("#error \"Double define HT_getText\"\n")
+            fh.write(f"#ifdef HT_{base_name}GetText\n")
+            fh.write(f"#error \"Double define HT_{base_name}GetText\"\n")
             fh.write("#endif\n")
 
             fh.write(f"#include \"{export_h}.h\"\n")
-            fh.write("#define HT_getText(name, ...) ((char *)(HT_TEXT_ ## name))\n")
-            fh.write(f"{export} int HT_initGetText(char *lang);\n")
+            fh.write(f"#define HT_{base_name}GetText(name, ...) ((char *)(HT_TEXT_{base_name}_ ## name))\n")
+            fh.write(f"{export} int HT_init{base_name}GetText(char *lang);\n")
 
             fpy.write("# Example for tr file" + '\n\n')
 
             for i in flat_list:
-                fc.write(f"{export} const char *HT_TEXT_{i} = {flat_list[i][0]};\n")
-                fh.write(f"{export} const char *HT_TEXT_{i};\n")
+                fc.write(f"{export} const char *HT_TEXT_{base_name}_{i} = {flat_list[i][0]};\n")
+                fh.write(f"{export} const char *HT_TEXT_{base_name}_{i};\n")
                 fpy.write(f"# {i}: str = \"\"  # {flat_list[i][0]}\n")
 
-            fc.write('''\n
-/* define initGetText */
+            fc.write(f'''\n
+/* define init{base_name}GetText */
 /* need dlfcn or dlfcn-win32 */
-
 #include "dlfcn.h"
 #include "stdlib.h"
 static void *handle = NULL;
 
-static void destructExit(void) {
+static void destructExit(void) {{
     dlclose(handle);
-}
+}}
 
-int HT_initGetText(char *lang) {
+int HT_init{base_name}GetText(char *lang) {{
     if (lang == NULL || handle != NULL)
         return 2;
 
@@ -141,8 +150,8 @@ int HT_initGetText(char *lang) {
     char **tmp;\n\n''')
 
             for i in flat_list:
-                fc.write(f'''    tmp = dlsym(handle, "HT__TEXT_{i}");\n''')
-                fc.write(f'''    if (tmp != NULL) HT_TEXT_{i} = *tmp;\n\n''')
+                fc.write(f'''    tmp = dlsym(handle, "HT__TEXT_{base_name}_{i}");\n''')
+                fc.write(f'''    if (tmp != NULL) HT_TEXT_{base_name}_{i} = *tmp;\n\n''')
 
             fc.write('    return 0;\n}\n')
 
@@ -165,8 +174,8 @@ for t in translation_list:
             var[i] = flat_list[i][0][1:-2]  # [1:-2] 去除引号
         exec(code, var, var)
         with open(os.path.join(translation_output, f"{name}.c"), "w", encoding="utf-8") as fc:
-            fc.write(f"#include \"{export_h}.h\"\n")
+            fc.write(f"#include \"{export_h}.h\"\n")  # 需要导出
             for i in flat_list:  # 根据 flat_list 生成变量
                 var[i].strip()  # 去除首尾不需要的符号
                 res = var[i].replace('\n', '\\n').replace('\r', '')
-                fc.write(f"{export} const char *const HT__TEXT_{i} = \"{res}\";\n")
+                fc.write(f"{export} const char *const HT__TEXT_{base_name}_{i} = \"{res}\";\n")

+ 2 - 2
src/core/core_init.c

@@ -64,12 +64,12 @@ bool aFunCoreInit(aFunCoreInitInfo *info) {
         writeDebugLog(aFunCoreLogger, "LANG = %s", LANG);
 
         char *LANG_lib = strJoin(lang_path, LANG, false, false);
-        if (HT_initGetText(LANG_lib) == 0)
+        if (HT_initaFunGetText(LANG_lib) == 0)
             writeDebugLog(aFunCoreLogger, "aFunCore lang init: %s", LANG_lib);
         free(LANG_lib);
         fclose(LANG_file);
     } else
-        HT_initGetText(NULL);
+        HT_initaFunGetText(NULL);
     free(LANG_path);
 
     return true;

+ 12 - 12
src/main.c

@@ -106,14 +106,14 @@ static void printVersion(void) {
 }
 
 static void printWelcomeInfo(void) {
-    printf_stdout(0, "aFunlang " aFunVersion " %s (" __DATE__ ", " __TIME__ ")\n", HT_getText(command_line_n, "CommandLine"));
+    printf_stdout(0, "aFunlang " aFunVersion " %s (" __DATE__ ", " __TIME__ ")\n", HT_aFunGetText(command_line_n, "CommandLine"));
     fputs_stdout("["compilerID"] on "systemName"\n");
-    printf_stdout(0, "(%s)\n", HT_getText(command_line_tips, "Enter the aFun code to run in the top activity"));
+    printf_stdout(0, "(%s)\n", HT_aFunGetText(command_line_tips, "Enter the aFun code to run in the top activity"));
 }
 
 static void printHelp(void) {
-    printf_stdout(0, "aFunlang %s:\n", HT_getText(usage_n, "Usage"));
-    printf_stdout(0, "%s\n", HT_getText(help_info, "<base-tr>"));
+    printf_stdout(0, "aFunlang %s:\n", HT_aFunGetText(usage_n, "Usage"));
+    printf_stdout(0, "%s\n", HT_aFunGetText(help_info, "<base-tr>"));
 }
 
 /*
@@ -122,7 +122,7 @@ static void printHelp(void) {
  */
 static void printError(ff_FFlags *ff) {
     writeErrorLog(aFunlangLogger, "%s argument error", ff_getChild(ff));
-    printf_stdout(0, "%s (%s)\n", HT_getText(cl_arg_error_e, "Command line argument error"), ff_getChild(ff));
+    printf_stdout(0, "%s (%s)\n", HT_aFunGetText(cl_arg_error_e, "Command line argument error"), ff_getChild(ff));
     printHelp();
 }
 
@@ -182,7 +182,7 @@ static int mainRun(ff_FFlags *ff) {
         writeErrorLog(aFunlangLogger, "aFun exit code: %d", exit_code);
     else
         writeInfoLog(aFunlangLogger, "aFun exit code: %d", exit_code);
-    printf_stderr(0, "aFun %s: %d\n", HT_getText(exit_code_n, "exit code"), exit_code);
+    printf_stderr(0, "aFun %s: %d\n", HT_aFunGetText(exit_code_n, "exit code"), exit_code);
 
     return exit_code;
 }
@@ -248,7 +248,7 @@ static int mainCL(ff_FFlags *ff) {
 
     if (rl == NULL && !command_line) {
         writeErrorLog(aFunlangLogger, "CL not file to run");
-        printf_stderr(0, "%s\n", HT_getText(cl_not_file_e, "There are not file run"));
+        printf_stderr(0, "%s\n", HT_aFunGetText(cl_not_file_e, "There are not file run"));
         return EXIT_FAILURE;
     }
 
@@ -276,7 +276,7 @@ static int mainCL(ff_FFlags *ff) {
         writeErrorLog(aFunlangLogger, "aFun exit code: %d", exit_code);
     else
         writeInfoLog(aFunlangLogger, "aFun exit code: %d", exit_code);
-    printf_stderr(0, "aFun %s: %d\n", HT_getText(exit_code_n, "exit code"), exit_code);
+    printf_stderr(0, "aFun %s: %d\n", HT_aFunGetText(exit_code_n, "exit code"), exit_code);
 
     destructAFunEnvironment(env);
     freeAllRunList(rl);
@@ -297,7 +297,7 @@ static int mainBuild(ff_FFlags *ff) {
             case 'o':
                 if (path != NULL) {
                     writeErrorLog(aFunlangLogger, "Build argument conflict");
-                    printf_stderr(0, "%s (--out, --path)\n", HT_getText(arg_conflict_n, "Argument conflict"));
+                    printf_stderr(0, "%s (--out, --path)\n", HT_aFunGetText(arg_conflict_n, "Argument conflict"));
                     goto error;
                 }
                 out_put = text;
@@ -305,7 +305,7 @@ static int mainBuild(ff_FFlags *ff) {
             case 'p':
                 if (out_put != NULL) {
                     writeErrorLog(aFunlangLogger, "Build argument conflict");
-                    printf_stderr(0, "%s (--out, --path)\n", HT_getText(arg_conflict_n, ""));
+                    printf_stderr(0, "%s (--out, --path)\n", HT_aFunGetText(arg_conflict_n, ""));
                     goto error;
                 }
                 path = text;
@@ -327,7 +327,7 @@ out:
         /* 如果没有参数 */
         if (!ff_getopt_wild(&text, ff)) {
             writeErrorLog(aFunlangLogger, "Build not source file");
-            printf_stderr(0, "%s\n", HT_getText(build_not_src_e, "There are not source file to build"));
+            printf_stderr(0, "%s\n", HT_aFunGetText(build_not_src_e, "There are not source file to build"));
             goto error;
         } else
             in = text;
@@ -335,7 +335,7 @@ out:
         /* 如果还有第二个参数 */
         if (ff_getopt_wild(&text, ff)) {
             writeErrorLog(aFunlangLogger, "Build too many source file");
-            printf_stderr(0, "%s\n", HT_getText(build_many_src_e, "There are too many source file to build (Do not use --out option)"));
+            printf_stderr(0, "%s\n", HT_aFunGetText(build_many_src_e, "There are too many source file to build (Do not use --out option)"));
             goto error;
         }
 

+ 3 - 3
src/main_build.c

@@ -8,19 +8,19 @@ int buildFileOutput(FilePath out, FilePath in, bool force) {
 
         if (time_1 == 0 && time_2 == 0) {
             writeErrorLog(aFunlangLogger, "Source not exists: %s", in);
-            printf_stderr(0, "%s [%s]\n", HT_getText(build_src_not_exists_e, "Source not exists"), in);
+            printf_stderr(0, "%s [%s]\n", HT_aFunGetText(build_src_not_exists_e, "Source not exists"), in);
             return -1;
         }
 
         if (time_2 >= time_1) {
             writeWarningLog(aFunlangLogger, "Source already build %s", in);
-            printf_stderr("%s (%s), %s\n", HT_getText(build_src_already, "Source already build"), in, HT_getText(build_use_f, "use --force to build again"));
+            printf_stderr("%s (%s), %s\n", HT_aFunGetText(build_src_already, "Source already build"), in, HT_aFunGetText(build_use_f, "use --force to build again"));
             return 0;
         }
     }
 
     writeInfoLog(aFunlangLogger, "Build %s, %s",  in, out);
-    printf_stdout("Source will be build (%s -> %s)\n", HT_getText(build_file, "Source will be build"), in, out);
+    printf_stdout("Source will be build (%s -> %s)\n", HT_aFunGetText(build_file, "Source will be build"), in, out);
     return buildFile(out, in);
 }
 

+ 9 - 9
src/runtime/aFunlang.c

@@ -78,7 +78,7 @@ static int runCode_(FilePath name, af_Parser *parser, int mode, FilePath save_pa
         int res = writeByteCode(bt_code, save_path);
         if (res != 1) {
             writeErrorLog(aFunCoreLogger, "Save %s bytecode error: %s", save_path, writeByteCodeError[res]);
-            printf_stderr(0, "%s: %s\n", HT_getText(run_save_e, "Save aFun Bytecode file error"), save_path);
+            printf_stderr(0, "%s: %s\n", HT_aFunGetText(run_save_e, "Save aFun Bytecode file error"), save_path);
         }
     }
 
@@ -116,7 +116,7 @@ int runCodeFromFileSource(FilePath file, bool save_afb, FilePath save_path, int
     char *sufix = getFileSurfix(file);
     if (sufix == NULL || !EQ_STR(".aun", sufix)) {
         writeErrorLog(aFunCoreLogger, "Source is not .aun file: %s", (sufix == NULL ? "" : sufix));
-        printf_stderr(0, "%s: %s\n", HT_getText(run_source_not_aub_e, "Source is not .aun file"), (sufix == NULL ? "" : sufix));
+        printf_stderr(0, "%s: %s\n", HT_aFunGetText(run_source_not_aub_e, "Source is not .aun file"), (sufix == NULL ? "" : sufix));
         return -2;
     }
 
@@ -176,7 +176,7 @@ int runCodeFromFileByte(FilePath file, int mode, af_Environment *env){
     char *sufix = getFileSurfix(file);
     if (sufix == NULL || !EQ_STR(".aub", sufix)) {
         writeErrorLog(aFunCoreLogger, "Bytecode not .aub file: %s", (sufix == NULL ? "" : sufix));
-        printf_stderr(0, "%s: %s\n", HT_getText(run_bt_not_aub_e, "Bytecode not .aub file"), (sufix == NULL ? "" : sufix));
+        printf_stderr(0, "%s: %s\n", HT_aFunGetText(run_bt_not_aub_e, "Bytecode not .aub file"), (sufix == NULL ? "" : sufix));
         return -2;
     }
 
@@ -184,7 +184,7 @@ int runCodeFromFileByte(FilePath file, int mode, af_Environment *env){
     int res = readByteCode(&code, file);
     if(res != 1) {
         writeErrorLog(aFunCoreLogger, "Load %s bytecode file error: %s", file, readByteCodeError[res]);
-        printf_stderr(0, "%s: %s\n", HT_getText(run_load_bt_e, "Load bytecode file error"), file);
+        printf_stderr(0, "%s: %s\n", HT_aFunGetText(run_load_bt_e, "Load bytecode file error"), file);
         return -2;
     }
 
@@ -204,7 +204,7 @@ int runCodeFromFile(FilePath file, bool save_afb, int mode, af_Environment *env)
     char *sufix = getFileSurfix(file);
     if (sufix != NULL && !EQ_STR(".aun", sufix) && !EQ_STR(".aub", sufix)) {  // 不是源文件, 字节码文件或无后缀文件
         writeErrorLog(aFunCoreLogger, "Run file not .aun/.aub file: %s", sufix);
-        printf_stderr(0, "%s: %s\n", HT_getText(run_file_aun_aub_e, "Run file not .aun/.aub file"), file);
+        printf_stderr(0, "%s: %s\n", HT_aFunGetText(run_file_aun_aub_e, "Run file not .aun/.aub file"), file);
         return -2;
     }
 
@@ -217,7 +217,7 @@ int runCodeFromFile(FilePath file, bool save_afb, int mode, af_Environment *env)
 
     if (time_1 == 0 && time_2 == 0) {
         writeErrorLog(aFunCoreLogger, "Run file not exists: %s", file);
-        printf_stderr(0, "%s: %s\n", HT_getText(run_file_not_exists_e, "Run file not exists"), file);
+        printf_stderr(0, "%s: %s\n", HT_aFunGetText(run_file_not_exists_e, "Run file not exists"), file);
         free(path_1);
         free(path_2);
         return -3;
@@ -250,13 +250,13 @@ int buildFile(FilePath out, FilePath in){
     char *suffix_out = getFileSurfix(out);
     if (suffix_in == NULL || !EQ_STR(".aun", suffix_in)) {  // 不是源文件
         writeErrorLog(aFunCoreLogger, "Input not .aun %s", (suffix_in == NULL ? "" : suffix_in));
-        printf_stderr("%s: %s\n", HT_getText(build_in_aun_e, "Input file is not .aun file"), (suffix_in == NULL ? "" : suffix_in));
+        printf_stderr("%s: %s\n", HT_aFunGetText(build_in_aun_e, "Input file is not .aun file"), (suffix_in == NULL ? "" : suffix_in));
         return -2;
     }
 
     if (suffix_out == NULL || !EQ_STR(".aub", suffix_out)) {  // 不是字节码文件
         writeErrorLog(aFunCoreLogger, "Output not .aub %s", (suffix_out == NULL ? "" : suffix_out));
-        printf_stderr("%s: %s\n", HT_getText(build_out_aub_e, "Output file is not .aub file"), (suffix_out == NULL ? "" : suffix_out));
+        printf_stderr("%s: %s\n", HT_aFunGetText(build_out_aub_e, "Output file is not .aub file"), (suffix_out == NULL ? "" : suffix_out));
         return -2;
     }
 
@@ -271,7 +271,7 @@ int buildFile(FilePath out, FilePath in){
 
     if (res != 1) {
         writeErrorLog(aFunCoreLogger, "Build %s error: %s", in, writeByteCodeError[res]);
-        printf_stderr(0, "%s: %s\n", HT_getText(build_error_e, "Build error"), in);
+        printf_stderr(0, "%s: %s\n", HT_aFunGetText(build_error_e, "Build error"), in);
         return -3;
     }