common.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. #include "common.h"
  2. #include <cassert>
  3. #include <iostream>
  4. #include <cstring>
  5. #include <fstream>
  6. #include <string>
  7. #include <iterator>
  8. #include <algorithm>
  9. #include <sstream>
  10. #if defined(__APPLE__) && defined(__MACH__)
  11. #include <sys/types.h>
  12. #include <sys/sysctl.h>
  13. #endif
  14. #if defined(_WIN32)
  15. #define WIN32_LEAN_AND_MEAN
  16. #define NOMINMAX
  17. #include <windows.h>
  18. #include <fcntl.h>
  19. #include <io.h>
  20. #else
  21. #include <sys/ioctl.h>
  22. #include <unistd.h>
  23. #include <wchar.h>
  24. #endif
  25. int32_t get_num_physical_cores() {
  26. #ifdef __linux__
  27. std::ifstream cpuinfo("/proc/cpuinfo");
  28. std::string line;
  29. while (std::getline(cpuinfo, line)) {
  30. std::size_t pos = line.find("cpu cores");
  31. if (pos != std::string::npos) {
  32. pos = line.find(": ", pos);
  33. if (pos != std::string::npos) {
  34. try {
  35. // Extract the number and return it
  36. return static_cast<int32_t>(std::stoul(line.substr(pos + 2)));
  37. } catch (const std::invalid_argument &) {
  38. // Ignore if we could not parse
  39. }
  40. }
  41. }
  42. }
  43. #elif defined(__APPLE__) && defined(__MACH__)
  44. int32_t num_physical_cores;
  45. size_t len = sizeof(num_physical_cores);
  46. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  47. if (result == 0) {
  48. return num_physical_cores;
  49. }
  50. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  51. if (result == 0) {
  52. return num_physical_cores;
  53. }
  54. #elif defined(_WIN32)
  55. //TODO: Implement
  56. #endif
  57. unsigned int n_threads = std::thread::hardware_concurrency();
  58. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  59. }
  60. void process_escapes(std::string& input) {
  61. std::size_t input_len = input.length();
  62. std::size_t output_idx = 0;
  63. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  64. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  65. switch (input[++input_idx]) {
  66. case 'n': input[output_idx++] = '\n'; break;
  67. case 'r': input[output_idx++] = '\r'; break;
  68. case 't': input[output_idx++] = '\t'; break;
  69. case '\'': input[output_idx++] = '\''; break;
  70. case '\"': input[output_idx++] = '\"'; break;
  71. case '\\': input[output_idx++] = '\\'; break;
  72. default: input[output_idx++] = '\\';
  73. input[output_idx++] = input[input_idx]; break;
  74. }
  75. } else {
  76. input[output_idx++] = input[input_idx];
  77. }
  78. }
  79. input.resize(output_idx);
  80. }
  81. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  82. bool invalid_param = false;
  83. bool escape_prompt = false;
  84. std::string arg;
  85. gpt_params default_params;
  86. for (int i = 1; i < argc; i++) {
  87. arg = argv[i];
  88. if (arg == "-s" || arg == "--seed") {
  89. #if defined(GGML_USE_CUBLAS)
  90. fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
  91. #endif
  92. if (++i >= argc) {
  93. invalid_param = true;
  94. break;
  95. }
  96. params.seed = std::stoi(argv[i]);
  97. } else if (arg == "-t" || arg == "--threads") {
  98. if (++i >= argc) {
  99. invalid_param = true;
  100. break;
  101. }
  102. params.n_threads = std::stoi(argv[i]);
  103. } else if (arg == "-p" || arg == "--prompt") {
  104. if (++i >= argc) {
  105. invalid_param = true;
  106. break;
  107. }
  108. params.prompt = argv[i];
  109. } else if (arg == "-e") {
  110. escape_prompt = true;
  111. } else if (arg == "--prompt-cache") {
  112. if (++i >= argc) {
  113. invalid_param = true;
  114. break;
  115. }
  116. params.path_prompt_cache = argv[i];
  117. } else if (arg == "--prompt-cache-all") {
  118. params.prompt_cache_all = true;
  119. } else if (arg == "-f" || arg == "--file") {
  120. if (++i >= argc) {
  121. invalid_param = true;
  122. break;
  123. }
  124. std::ifstream file(argv[i]);
  125. if (!file) {
  126. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  127. invalid_param = true;
  128. break;
  129. }
  130. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  131. if (params.prompt.back() == '\n') {
  132. params.prompt.pop_back();
  133. }
  134. } else if (arg == "-n" || arg == "--n_predict") {
  135. if (++i >= argc) {
  136. invalid_param = true;
  137. break;
  138. }
  139. params.n_predict = std::stoi(argv[i]);
  140. } else if (arg == "--top_k") {
  141. if (++i >= argc) {
  142. invalid_param = true;
  143. break;
  144. }
  145. params.top_k = std::stoi(argv[i]);
  146. } else if (arg == "-c" || arg == "--ctx_size") {
  147. if (++i >= argc) {
  148. invalid_param = true;
  149. break;
  150. }
  151. params.n_ctx = std::stoi(argv[i]);
  152. } else if (arg == "--memory_f32") {
  153. params.memory_f16 = false;
  154. } else if (arg == "--top_p") {
  155. if (++i >= argc) {
  156. invalid_param = true;
  157. break;
  158. }
  159. params.top_p = std::stof(argv[i]);
  160. } else if (arg == "--temp") {
  161. if (++i >= argc) {
  162. invalid_param = true;
  163. break;
  164. }
  165. params.temp = std::stof(argv[i]);
  166. } else if (arg == "--tfs") {
  167. if (++i >= argc) {
  168. invalid_param = true;
  169. break;
  170. }
  171. params.tfs_z = std::stof(argv[i]);
  172. } else if (arg == "--typical") {
  173. if (++i >= argc) {
  174. invalid_param = true;
  175. break;
  176. }
  177. params.typical_p = std::stof(argv[i]);
  178. } else if (arg == "--repeat_last_n") {
  179. if (++i >= argc) {
  180. invalid_param = true;
  181. break;
  182. }
  183. params.repeat_last_n = std::stoi(argv[i]);
  184. } else if (arg == "--repeat_penalty") {
  185. if (++i >= argc) {
  186. invalid_param = true;
  187. break;
  188. }
  189. params.repeat_penalty = std::stof(argv[i]);
  190. } else if (arg == "--frequency_penalty") {
  191. if (++i >= argc) {
  192. invalid_param = true;
  193. break;
  194. }
  195. params.frequency_penalty = std::stof(argv[i]);
  196. } else if (arg == "--presence_penalty") {
  197. if (++i >= argc) {
  198. invalid_param = true;
  199. break;
  200. }
  201. params.presence_penalty = std::stof(argv[i]);
  202. } else if (arg == "--mirostat") {
  203. if (++i >= argc) {
  204. invalid_param = true;
  205. break;
  206. }
  207. params.mirostat = std::stoi(argv[i]);
  208. } else if (arg == "--mirostat_lr") {
  209. if (++i >= argc) {
  210. invalid_param = true;
  211. break;
  212. }
  213. params.mirostat_eta = std::stof(argv[i]);
  214. } else if (arg == "--mirostat_ent") {
  215. if (++i >= argc) {
  216. invalid_param = true;
  217. break;
  218. }
  219. params.mirostat_tau = std::stof(argv[i]);
  220. } else if (arg == "-b" || arg == "--batch_size") {
  221. if (++i >= argc) {
  222. invalid_param = true;
  223. break;
  224. }
  225. params.n_batch = std::stoi(argv[i]);
  226. params.n_batch = std::min(512, params.n_batch);
  227. } else if (arg == "--keep") {
  228. if (++i >= argc) {
  229. invalid_param = true;
  230. break;
  231. }
  232. params.n_keep = std::stoi(argv[i]);
  233. } else if (arg == "-m" || arg == "--model") {
  234. if (++i >= argc) {
  235. invalid_param = true;
  236. break;
  237. }
  238. params.model = argv[i];
  239. } else if (arg == "--lora") {
  240. if (++i >= argc) {
  241. invalid_param = true;
  242. break;
  243. }
  244. params.lora_adapter = argv[i];
  245. params.use_mmap = false;
  246. } else if (arg == "--lora-base") {
  247. if (++i >= argc) {
  248. invalid_param = true;
  249. break;
  250. }
  251. params.lora_base = argv[i];
  252. } else if (arg == "-i" || arg == "--interactive") {
  253. params.interactive = true;
  254. } else if (arg == "--embedding") {
  255. params.embedding = true;
  256. } else if (arg == "--interactive-first") {
  257. params.interactive_first = true;
  258. } else if (arg == "-ins" || arg == "--instruct") {
  259. params.instruct = true;
  260. } else if (arg == "--multiline-input") {
  261. params.multiline_input = true;
  262. } else if (arg == "--color") {
  263. params.use_color = true;
  264. } else if (arg == "--mlock") {
  265. params.use_mlock = true;
  266. } else if (arg == "--no-mmap") {
  267. params.use_mmap = false;
  268. } else if (arg == "--mtest") {
  269. params.mem_test = true;
  270. } else if (arg == "--verbose-prompt") {
  271. params.verbose_prompt = true;
  272. } else if (arg == "-r" || arg == "--reverse-prompt") {
  273. if (++i >= argc) {
  274. invalid_param = true;
  275. break;
  276. }
  277. params.antiprompt.push_back(argv[i]);
  278. } else if (arg == "--perplexity") {
  279. params.perplexity = true;
  280. } else if (arg == "--ignore-eos") {
  281. params.logit_bias[llama_token_eos()] = -INFINITY;
  282. } else if (arg == "--no-penalize-nl") {
  283. params.penalize_nl = false;
  284. } else if (arg == "-l" || arg == "--logit-bias") {
  285. if (++i >= argc) {
  286. invalid_param = true;
  287. break;
  288. }
  289. std::stringstream ss(argv[i]);
  290. llama_token key;
  291. char sign;
  292. std::string value_str;
  293. try {
  294. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  295. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  296. } else {
  297. throw std::exception();
  298. }
  299. } catch (const std::exception &e) {
  300. invalid_param = true;
  301. break;
  302. }
  303. } else if (arg == "--n_parts") {
  304. if (++i >= argc) {
  305. invalid_param = true;
  306. break;
  307. }
  308. params.n_parts = std::stoi(argv[i]);
  309. } else if (arg == "-h" || arg == "--help") {
  310. gpt_print_usage(argc, argv, default_params);
  311. exit(0);
  312. } else if (arg == "--random-prompt") {
  313. params.random_prompt = true;
  314. } else if (arg == "--in-prefix") {
  315. if (++i >= argc) {
  316. invalid_param = true;
  317. break;
  318. }
  319. params.input_prefix = argv[i];
  320. } else if (arg == "--in-suffix") {
  321. if (++i >= argc) {
  322. invalid_param = true;
  323. break;
  324. }
  325. params.input_suffix = argv[i];
  326. } else {
  327. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  328. gpt_print_usage(argc, argv, default_params);
  329. exit(1);
  330. }
  331. }
  332. if (invalid_param) {
  333. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  334. gpt_print_usage(argc, argv, default_params);
  335. exit(1);
  336. }
  337. if (params.prompt_cache_all &&
  338. (params.interactive || params.interactive_first ||
  339. params.instruct || params.antiprompt.size())) {
  340. fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
  341. gpt_print_usage(argc, argv, default_params);
  342. exit(1);
  343. }
  344. if (escape_prompt) {
  345. process_escapes(params.prompt);
  346. }
  347. return true;
  348. }
  349. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  350. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  351. fprintf(stderr, "\n");
  352. fprintf(stderr, "options:\n");
  353. fprintf(stderr, " -h, --help show this help message and exit\n");
  354. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  355. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  356. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  357. fprintf(stderr, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  358. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  359. fprintf(stderr, " run in interactive mode and poll user input upon seeing PROMPT (can be\n");
  360. fprintf(stderr, " specified more than once for multiple prompts).\n");
  361. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  362. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  363. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  364. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  365. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  366. fprintf(stderr, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  367. fprintf(stderr, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  368. fprintf(stderr, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  369. fprintf(stderr, " not supported with --interactive or other interactive options\n");
  370. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  371. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  372. fprintf(stderr, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  373. fprintf(stderr, " -f FNAME, --file FNAME\n");
  374. fprintf(stderr, " prompt file to start generation.\n");
  375. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  376. fprintf(stderr, " --top_k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  377. fprintf(stderr, " --top_p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  378. fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  379. fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  380. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
  381. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  382. fprintf(stderr, " --presence_penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  383. fprintf(stderr, " --frequency_penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  384. fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
  385. fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  386. fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  387. fprintf(stderr, " --mirostat_lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  388. fprintf(stderr, " --mirostat_ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  389. fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  390. fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
  391. fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  392. fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  393. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  394. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  395. fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
  396. fprintf(stderr, " --memory_f32 use f32 instead of f16 for memory key+value\n");
  397. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  398. fprintf(stderr, " --n_parts N number of model parts (default: -1 = determine from dimensions)\n");
  399. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  400. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  401. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  402. if (llama_mlock_supported()) {
  403. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  404. }
  405. if (llama_mmap_supported()) {
  406. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  407. }
  408. fprintf(stderr, " --mtest compute maximum memory usage\n");
  409. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  410. fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  411. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  412. fprintf(stderr, " -m FNAME, --model FNAME\n");
  413. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  414. fprintf(stderr, "\n");
  415. }
  416. std::string gpt_random_prompt(std::mt19937 & rng) {
  417. const int r = rng() % 10;
  418. switch (r) {
  419. case 0: return "So";
  420. case 1: return "Once upon a time";
  421. case 2: return "When";
  422. case 3: return "The";
  423. case 4: return "After";
  424. case 5: return "If";
  425. case 6: return "import";
  426. case 7: return "He";
  427. case 8: return "She";
  428. case 9: return "They";
  429. default: return "To";
  430. }
  431. return "The";
  432. }
  433. // TODO: not great allocating this every time
  434. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  435. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  436. std::vector<llama_token> res(text.size() + (int) add_bos);
  437. const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  438. assert(n >= 0);
  439. res.resize(n);
  440. return res;
  441. }
  442. struct llama_context * llama_init_from_gpt_params(const gpt_params & params) {
  443. auto lparams = llama_context_default_params();
  444. lparams.n_ctx = params.n_ctx;
  445. lparams.n_parts = params.n_parts;
  446. lparams.seed = params.seed;
  447. lparams.f16_kv = params.memory_f16;
  448. lparams.use_mmap = params.use_mmap;
  449. lparams.use_mlock = params.use_mlock;
  450. lparams.logits_all = params.perplexity;
  451. lparams.embedding = params.embedding;
  452. llama_context * lctx = llama_init_from_file(params.model.c_str(), lparams);
  453. if (lctx == NULL) {
  454. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  455. return NULL;
  456. }
  457. if (!params.lora_adapter.empty()) {
  458. int err = llama_apply_lora_from_file(lctx,
  459. params.lora_adapter.c_str(),
  460. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  461. params.n_threads);
  462. if (err != 0) {
  463. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  464. return NULL;
  465. }
  466. }
  467. return lctx;
  468. }
  469. void console_init(console_state & con_st) {
  470. #if defined(_WIN32)
  471. // Windows-specific console initialization
  472. DWORD dwMode = 0;
  473. con_st.hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  474. if (con_st.hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(con_st.hConsole, &dwMode)) {
  475. con_st.hConsole = GetStdHandle(STD_ERROR_HANDLE);
  476. if (con_st.hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(con_st.hConsole, &dwMode))) {
  477. con_st.hConsole = NULL;
  478. }
  479. }
  480. if (con_st.hConsole) {
  481. // Enable ANSI colors on Windows 10+
  482. if (con_st.use_color && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
  483. SetConsoleMode(con_st.hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
  484. }
  485. // Set console output codepage to UTF8
  486. SetConsoleOutputCP(CP_UTF8);
  487. }
  488. HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
  489. if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) {
  490. // Set console input codepage to UTF16
  491. _setmode(_fileno(stdin), _O_WTEXT);
  492. // Turn off ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT)
  493. dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  494. SetConsoleMode(hConIn, dwMode);
  495. }
  496. #else
  497. // POSIX-specific console initialization
  498. struct termios new_termios;
  499. tcgetattr(STDIN_FILENO, &con_st.prev_state);
  500. new_termios = con_st.prev_state;
  501. new_termios.c_lflag &= ~(ICANON | ECHO);
  502. new_termios.c_cc[VMIN] = 1;
  503. new_termios.c_cc[VTIME] = 0;
  504. tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
  505. con_st.tty = fopen("/dev/tty", "w+");
  506. if (con_st.tty != nullptr) {
  507. con_st.out = con_st.tty;
  508. }
  509. setlocale(LC_ALL, "");
  510. #endif
  511. }
  512. void console_cleanup(console_state & con_st) {
  513. // Reset console color
  514. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  515. #if !defined(_WIN32)
  516. if (con_st.tty != nullptr) {
  517. con_st.out = stdout;
  518. fclose(con_st.tty);
  519. con_st.tty = nullptr;
  520. }
  521. // Restore the terminal settings on POSIX systems
  522. tcsetattr(STDIN_FILENO, TCSANOW, &con_st.prev_state);
  523. #endif
  524. }
  525. /* Keep track of current color of output, and emit ANSI code if it changes. */
  526. void console_set_color(console_state & con_st, console_color_t color) {
  527. if (con_st.use_color && con_st.color != color) {
  528. fflush(stdout);
  529. switch(color) {
  530. case CONSOLE_COLOR_DEFAULT:
  531. fprintf(con_st.out, ANSI_COLOR_RESET);
  532. break;
  533. case CONSOLE_COLOR_PROMPT:
  534. fprintf(con_st.out, ANSI_COLOR_YELLOW);
  535. break;
  536. case CONSOLE_COLOR_USER_INPUT:
  537. fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_GREEN);
  538. break;
  539. }
  540. con_st.color = color;
  541. fflush(con_st.out);
  542. }
  543. }
  544. char32_t getchar32() {
  545. wchar_t wc = getwchar();
  546. if (static_cast<wint_t>(wc) == WEOF) {
  547. return WEOF;
  548. }
  549. #if WCHAR_MAX == 0xFFFF
  550. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  551. wchar_t low_surrogate = getwchar();
  552. if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate
  553. return (static_cast<char32_t>(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000;
  554. }
  555. }
  556. if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair
  557. return 0xFFFD; // Return the replacement character U+FFFD
  558. }
  559. #endif
  560. return static_cast<char32_t>(wc);
  561. }
  562. void pop_cursor(console_state & con_st) {
  563. #if defined(_WIN32)
  564. if (con_st.hConsole != NULL) {
  565. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  566. GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo);
  567. COORD newCursorPosition = bufferInfo.dwCursorPosition;
  568. if (newCursorPosition.X == 0) {
  569. newCursorPosition.X = bufferInfo.dwSize.X - 1;
  570. newCursorPosition.Y -= 1;
  571. } else {
  572. newCursorPosition.X -= 1;
  573. }
  574. SetConsoleCursorPosition(con_st.hConsole, newCursorPosition);
  575. return;
  576. }
  577. #endif
  578. putc('\b', con_st.out);
  579. }
  580. int estimateWidth(char32_t codepoint) {
  581. #if defined(_WIN32)
  582. return 1;
  583. #else
  584. return wcwidth(codepoint);
  585. #endif
  586. }
  587. int put_codepoint(console_state & con_st, const char* utf8_codepoint, size_t length, int expectedWidth) {
  588. #if defined(_WIN32)
  589. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  590. if (!GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo)) {
  591. // go with the default
  592. return expectedWidth;
  593. }
  594. COORD initialPosition = bufferInfo.dwCursorPosition;
  595. DWORD nNumberOfChars = length;
  596. WriteConsole(con_st.hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL);
  597. CONSOLE_SCREEN_BUFFER_INFO newBufferInfo;
  598. GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
  599. // Figure out our real position if we're in the last column
  600. if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) {
  601. DWORD nNumberOfChars;
  602. WriteConsole(con_st.hConsole, &" \b", 2, &nNumberOfChars, NULL);
  603. GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
  604. }
  605. int width = newBufferInfo.dwCursorPosition.X - initialPosition.X;
  606. if (width < 0) {
  607. width += newBufferInfo.dwSize.X;
  608. }
  609. return width;
  610. #else
  611. // we can trust expectedWidth if we've got one
  612. if (expectedWidth >= 0 || con_st.tty == nullptr) {
  613. fwrite(utf8_codepoint, length, 1, con_st.out);
  614. return expectedWidth;
  615. }
  616. fputs("\033[6n", con_st.tty); // Query cursor position
  617. int x1, x2, y1, y2;
  618. int results = 0;
  619. results = fscanf(con_st.tty, "\033[%d;%dR", &y1, &x1);
  620. fwrite(utf8_codepoint, length, 1, con_st.tty);
  621. fputs("\033[6n", con_st.tty); // Query cursor position
  622. results += fscanf(con_st.tty, "\033[%d;%dR", &y2, &x2);
  623. if (results != 4) {
  624. return expectedWidth;
  625. }
  626. int width = x2 - x1;
  627. if (width < 0) {
  628. // Calculate the width considering text wrapping
  629. struct winsize w;
  630. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  631. width += w.ws_col;
  632. }
  633. return width;
  634. #endif
  635. }
  636. void replace_last(console_state & con_st, char ch) {
  637. #if defined(_WIN32)
  638. pop_cursor(con_st);
  639. put_codepoint(con_st, &ch, 1, 1);
  640. #else
  641. fprintf(con_st.out, "\b%c", ch);
  642. #endif
  643. }
  644. void append_utf8(char32_t ch, std::string & out) {
  645. if (ch <= 0x7F) {
  646. out.push_back(static_cast<unsigned char>(ch));
  647. } else if (ch <= 0x7FF) {
  648. out.push_back(static_cast<unsigned char>(0xC0 | ((ch >> 6) & 0x1F)));
  649. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  650. } else if (ch <= 0xFFFF) {
  651. out.push_back(static_cast<unsigned char>(0xE0 | ((ch >> 12) & 0x0F)));
  652. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  653. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  654. } else if (ch <= 0x10FFFF) {
  655. out.push_back(static_cast<unsigned char>(0xF0 | ((ch >> 18) & 0x07)));
  656. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 12) & 0x3F)));
  657. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  658. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  659. } else {
  660. // Invalid Unicode code point
  661. }
  662. }
  663. // Helper function to remove the last UTF-8 character from a string
  664. void pop_back_utf8_char(std::string & line) {
  665. if (line.empty()) {
  666. return;
  667. }
  668. size_t pos = line.length() - 1;
  669. // Find the start of the last UTF-8 character (checking up to 4 bytes back)
  670. for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) {
  671. if ((line[pos] & 0xC0) != 0x80) break; // Found the start of the character
  672. }
  673. line.erase(pos);
  674. }
  675. bool console_readline(console_state & con_st, std::string & line) {
  676. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  677. if (con_st.out != stdout) {
  678. fflush(stdout);
  679. }
  680. line.clear();
  681. std::vector<int> widths;
  682. bool is_special_char = false;
  683. bool end_of_stream = false;
  684. char32_t input_char;
  685. while (true) {
  686. fflush(con_st.out); // Ensure all output is displayed before waiting for input
  687. input_char = getchar32();
  688. if (input_char == '\r' || input_char == '\n') {
  689. break;
  690. }
  691. if (input_char == WEOF || input_char == 0x04 /* Ctrl+D*/) {
  692. end_of_stream = true;
  693. break;
  694. }
  695. if (is_special_char) {
  696. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  697. replace_last(con_st, line.back());
  698. is_special_char = false;
  699. }
  700. if (input_char == '\033') { // Escape sequence
  701. char32_t code = getchar32();
  702. if (code == '[' || code == 0x1B) {
  703. // Discard the rest of the escape sequence
  704. while ((code = getchar32()) != WEOF) {
  705. if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') {
  706. break;
  707. }
  708. }
  709. }
  710. } else if (input_char == 0x08 || input_char == 0x7F) { // Backspace
  711. if (!widths.empty()) {
  712. int count;
  713. do {
  714. count = widths.back();
  715. widths.pop_back();
  716. // Move cursor back, print space, and move cursor back again
  717. for (int i = 0; i < count; i++) {
  718. replace_last(con_st, ' ');
  719. pop_cursor(con_st);
  720. }
  721. pop_back_utf8_char(line);
  722. } while (count == 0 && !widths.empty());
  723. }
  724. } else {
  725. int offset = line.length();
  726. append_utf8(input_char, line);
  727. int width = put_codepoint(con_st, line.c_str() + offset, line.length() - offset, estimateWidth(input_char));
  728. if (width < 0) {
  729. width = 0;
  730. }
  731. widths.push_back(width);
  732. }
  733. if (!line.empty() && (line.back() == '\\' || line.back() == '/')) {
  734. console_set_color(con_st, CONSOLE_COLOR_PROMPT);
  735. replace_last(con_st, line.back());
  736. is_special_char = true;
  737. }
  738. }
  739. bool has_more = con_st.multiline_input;
  740. if (is_special_char) {
  741. replace_last(con_st, ' ');
  742. pop_cursor(con_st);
  743. char last = line.back();
  744. line.pop_back();
  745. if (last == '\\') {
  746. line += '\n';
  747. fputc('\n', con_st.out);
  748. has_more = !has_more;
  749. } else {
  750. // llama will just eat the single space, it won't act as a space
  751. if (line.length() == 1 && line.back() == ' ') {
  752. line.clear();
  753. pop_cursor(con_st);
  754. }
  755. has_more = false;
  756. }
  757. } else {
  758. if (end_of_stream) {
  759. has_more = false;
  760. } else {
  761. line += '\n';
  762. fputc('\n', con_st.out);
  763. }
  764. }
  765. fflush(con_st.out);
  766. return has_more;
  767. }