common.cpp 33 KB

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