1
0

common.cpp 31 KB

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