kfiles.cpp 31.8 KB
Newer Older
1 2
#include "kumirstdlib.hpp"

Alexander A. Maly's avatar
Alexander A. Maly committed
3 4 5 6 7
#if defined(WIN32) || defined(_WIN32)
# define NOMINMAX
# include <Windows.h>
#else
# include <sys/stat.h>
8
# include <errno.h>
Alexander A. Maly's avatar
Alexander A. Maly committed
9 10 11 12 13 14 15
# include <unistd.h>
#endif

#include <string.h>
#include <vector>
#include <set>

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
namespace Kumir {

static FILE *assignedIN = stdin;
static FILE *assignedOUT = stdout;

static std::deque<FileType> openedFiles;

static AbstractInputBuffer *consoleInputBuffer = 0;
static AbstractOutputBuffer *consoleOutputBuffer = 0;

static Encoding fileEncoding;
static String inputDelimiters;

#if defined(WIN32) || defined(_WIN32)
static Encoding LOCALE_ENCODING = CP866;
#else
static Encoding LOCALE_ENCODING = UTF8;
#endif


36 37 38 39 40 41 42 43 44
AbstractInputBuffer::~AbstractInputBuffer()
{
}

AbstractOutputBuffer::~AbstractOutputBuffer()
{
}


45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
AbstractInputBuffer *Files::getConsoleInputBuffer()
{
	return consoleInputBuffer;
}

void Files::setConsoleInputBuffer(AbstractInputBuffer *b)
{
	consoleInputBuffer = b;
}

AbstractOutputBuffer *Files::getConsoleOutputBuffer()
{
	return consoleOutputBuffer;
}

void Files::setConsoleOutputBuffer(AbstractOutputBuffer *b)
{
	consoleOutputBuffer = b;
}

bool Files::isOpenedFiles()
{
	bool remainingOpenedFiles = false;
	for (
		std::deque<FileType>::iterator it = openedFiles.begin();
		it != openedFiles.end();
		++it
	) {
		FileType &f = *it;
		if (!f.autoClose) {
			remainingOpenedFiles = true;
			break;
		}
	}
	return remainingOpenedFiles;
}

void Files::init()
{
	fileEncoding = DefaultEncoding;
	openedFiles.clear();

	assignedIN = stdin;
	assignedOUT = stdout;
Alexander A. Maly's avatar
Alexander A. Maly committed
89
	inputDelimiters = Kumir::Core::fromAscii(" \n\r\t");
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
}

void Files::finalize()
{
	if (isOpenedFiles() && Core::getError().length() == 0) {
		Core::abort(Core::fromUtf8("Остались незакрытые файлы"));
	}

	for (size_t i = 0; i < openedFiles.size(); i++) {
		FileType &f = openedFiles[i];
		if (f.handle) {
			fclose(f.handle);
		}
	}

	openedFiles.clear();

	if (assignedIN != stdin) {
		fclose(assignedIN);
	}

	if (assignedOUT != stdout) {
		fclose(assignedOUT);
	}

	assignedIN = stdin;
	assignedOUT = stdout;
}

void Files::setFileEncoding(const String &enc)
{
	String encoding = Core::toLowerCaseW(enc);
	StringUtils::trim<String, Char>(encoding);
	if (encoding.length() == 0) {
		fileEncoding = DefaultEncoding;
		return;
	}

	size_t minus = encoding.find_first_of(Char('-'));
	if (minus != String::npos) {
		encoding.erase(minus, 1);
	}

	static const String ansi1 = Core::fromAscii("cp1251");
	static const String ansi2 = Core::fromAscii("windows1251");
	static const String ansi3 = Core::fromAscii("windows");
	static const String ansi4 = Core::fromAscii("ansi");
	static const String ansi5 = Core::fromAscii("1251");
	static const String oem1 = Core::fromAscii("cp866");
	static const String oem2 = Core::fromAscii("ibm866");
	static const String oem3 = Core::fromAscii("ibm");
	static const String oem4 = Core::fromAscii("oem");
	static const String oem5 = Core::fromAscii("oem866");
	static const String oem6 = Core::fromAscii("dos");
	static const String koi1 = Core::fromAscii("koi8");
	static const String koi2 = Core::fromAscii("koi8r");
	static const String koi3 = Core::fromUtf8("кои8");
	static const String koi4 = Core::fromUtf8("кои8р");
	static const String utf1 = Core::fromAscii("utf");
	static const String utf2 = Core::fromAscii("utf8");
	static const String utf3 = Core::fromAscii("linux");
	static const String intel1 = Core::fromAscii("unicode");
	static const String intel2 = Core::fromAscii("utf16");
	static const String intel3 = Core::fromAscii("utf16le");
	static const String intel4 = Core::fromUtf8("юникод");
	static const String motorola = Core::fromAscii("utf16be");

	if (
		encoding == ansi1 || encoding == ansi2 || encoding == ansi3 ||
		encoding == ansi4 || encoding == ansi5
	) {
		fileEncoding = CP1251;
	} else if (
		encoding == oem1 || encoding == oem2 || encoding == oem3 ||
		encoding == oem4 || encoding == oem5 || encoding == oem6
	) {
		fileEncoding = CP866;
	} else if (
		encoding == koi1 || encoding == koi2 || encoding == koi3 ||
		encoding == koi4
	) {
		fileEncoding = KOI8R;
	} else if (
		encoding == utf1 || encoding == utf2 || encoding == utf3
	) {
		fileEncoding = UTF8;
	} else if (
		encoding == intel1 || encoding == intel2 || encoding == intel3 ||
		encoding == intel4
	) {
		fileEncoding = UTF16INTEL;
	} else if (
		encoding == motorola
	) {
		fileEncoding = UTF16MOTOROLA;
	} else {
		Core::abort(Core::fromUtf8("Неизвестная кодировка"));
	}
}

String Files::getAbsolutePath(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	wchar_t cwd[1024];
	GetCurrentDirectoryW(1024, cwd);
	String workDir;
	workDir = String(cwd);
	workDir.push_back(Char('\\'));
	String absPath;
	if (
		fileName.length() == 0 ||
		(fileName.length() > 2 && fileName.at(1) == Char(':') && fileName.at(2) == Char('\\'))
	) {
		absPath = fileName;
	} else {
		absPath = workDir + fileName;
	}
	return getNormalizedPath(absPath, Char('\\'));
#else
	char cwd[1024];
	getcwd(cwd, 1024 * sizeof(char));
	String workDir;
	std::string sworkDir = std::string(cwd);
	workDir = Core::fromUtf8(sworkDir);
	workDir.push_back(Char('/'));
	String absPath;
	if (fileName.length() == 0 || fileName.at(0) == Char('/')) {
		absPath = fileName;
	} else {
		absPath = workDir + fileName;
	}
	return getNormalizedPath(absPath, Char('/'));
#endif
}

String Files::CurrentWorkingDirectory()
{
#if defined(WIN32) || defined(_WIN32)
	wchar_t cwd[1024];
	GetCurrentDirectoryW(1024, cwd);
	String workDir;
	workDir = String(cwd);
	return workDir;
#else
	char cwd[1024];
	getcwd(cwd, 1024 * sizeof(char));
	String workDir;
	std::string sworkDir = std::string(cwd);
	workDir = Core::fromUtf8(sworkDir);
	return workDir;
#endif
}

String Files::getNormalizedPath(const String &path, Char sep)
{
	if (path.length() == 0) {
		return path;
	}
	StringList parts = Core::splitString(path, sep, true);
	StringList normParts;
	int skip = 0;
	String result;
	static const String CUR = Core::fromAscii(".");
	static const String UP  = Core::fromAscii("..");
	for (int i = parts.size() - 1; i >= 0; i--) {
		const String &apart = parts[i];
		if (apart == CUR) {
			// pass
		} else if (apart == UP) {
			skip += 1;
		} else {
			if (skip == 0) {
				normParts.push_front(apart);
			} else {
				skip -= 1;
			}
		}
	}
	result = normParts.join(sep);
	if (path.at(0) == sep) {
		result.insert(0, 1, sep);
	}
	if (path.length() > 1 && path.at(path.length() - 1) == sep) {
		result.push_back(sep);
	}
	return result;
}

bool Files::canOpenForRead(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	return exist(fileName); // TODO implement me
#else
	char *path = reinterpret_cast<char *>(calloc(fileName.length() * 2 + 1, sizeof(char)));
	size_t pl = wcstombs(path, fileName.c_str(), fileName.length() * 2 + 1);
	path[pl] = '\0';
	struct stat st;
	int res = stat(path, &st);
	free(path);

	bool exists = (res == 0);
	bool readAsOwner = false;
	bool readAsGroup = false;
	bool readAsOther = false;
	if (exists) {
		bool w = st.st_mode & S_IRUSR;
		bool g = st.st_mode & S_IRGRP;
		bool o = st.st_mode & S_IROTH;
		readAsOwner = w && getuid() == st.st_uid;
		readAsGroup = g && getgid() == st.st_gid;
		readAsOther = o;
	}
	bool result = readAsOwner || readAsGroup || readAsOther;
	return result;
#endif
}

bool Files::canOpenForWrite(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	return true; // TODO implement me
#else

	char *path = reinterpret_cast<char *>(calloc(fileName.length() * 2 + 1, sizeof(char)));
	size_t pl = wcstombs(path, fileName.c_str(), fileName.length() * 2 + 1);
	path[pl] = '\0';
	struct stat st;
	int res = stat(path, &st);
	bool exists = res == 0;
	bool writeAsOwner = false;
	bool writeAsGroup = false;
	bool writeAsOther = false;
	if (exists) {
		bool w = st.st_mode & S_IRUSR;
		bool g = st.st_mode & S_IRGRP;
		bool o = st.st_mode & S_IROTH;
		writeAsOwner = w && getuid() == st.st_uid;
		writeAsGroup = g && getgid() == st.st_gid;
		writeAsOther = o;
	} else if (errno == ENOENT) {
		while (!exists) {
			int i = 0;
			for (i = strlen(path) - 1; i >= 0; i++) {
				if (path[i] == '/') {
					path[i] = '\0';
					break;
				}
			}
			if (i == 0) {
				break;
			}
			res = stat(path, &st);
			exists = res == 0;
			if (exists) {
				bool w = st.st_mode & S_IRUSR;
				bool g = st.st_mode & S_IRGRP;
				bool o = st.st_mode & S_IROTH;
				writeAsOwner = w && getuid() == st.st_uid;
				writeAsGroup = g && getgid() == st.st_gid;
				writeAsOther = o;
				break;
			}
		}
	}
	free(path);
	bool result = writeAsOwner || writeAsGroup || writeAsOther;
	return result;
#endif
}

bool Files::exist(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	DWORD dwAttrib = GetFileAttributesW(fileName.c_str());
	return dwAttrib != INVALID_FILE_ATTRIBUTES;
#else
	EncodingError encodingError;
	std::string localName = Kumir::Coder::encode(Kumir::UTF8, fileName, encodingError);
	const char *path = localName.c_str();
	struct stat st;
	int res = stat(path, &st);
	bool result = (res == 0);
	return result;
#endif
}

bool Files::isDirectory(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	DWORD dwAttrib = GetFileAttributesW(fileName.c_str());
	return (
		(dwAttrib != INVALID_FILE_ATTRIBUTES) &&
		(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)
	);
#else
	char *path = reinterpret_cast<char *>(calloc(fileName.length() * 2 + 1, sizeof(char)));
	size_t pl = wcstombs(path, fileName.c_str(), fileName.length() * 2 + 1);
	path[pl] = '\0';
	struct stat st;
	int res = stat(path, &st);
	free(path);
	bool result = (res == 0) && S_ISDIR(st.st_mode);
	return result;
#endif
}

bool Files::mkdir(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	BOOL result = CreateDirectoryW(fileName.c_str(), NULL);
	return result != 0;
#else
	char *path = reinterpret_cast<char *>(calloc(fileName.length() * 2 + 1, sizeof(char)));
	size_t pl = wcstombs(path, fileName.c_str(), fileName.length() * 2 + 1);
	path[pl] = '\0';
	int res = ::mkdir(path, 0666);
	free(path);
	bool result = (res == 0);
	return result;
#endif
}

bool Files::unlink(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	if (DeleteFileW(fileName.c_str()) != 0) {
		return true;
	} else {
		if (GetLastError() == ERROR_FILE_NOT_FOUND) {
			return false;
		} else {
			return false;
		}
	}
#else
	char *path = reinterpret_cast<char *>(calloc(fileName.length() * 2 + 1, sizeof(char)));
	size_t pl = wcstombs(path, fileName.c_str(), fileName.length() * 2 + 1);
	path[pl] = '\0';
	int res = ::unlink(path);
	free(path);
	bool result = (res == 0);
	return result;
#endif
}

bool Files::rmdir(const String &fileName)
{
#if defined(WIN32) || defined(_WIN32)
	if (RemoveDirectoryW(fileName.c_str())) {
		return true;
	} else {
		return false;
	}
#else
	char *path = reinterpret_cast<char *>(calloc(fileName.length() * 2 + 1, sizeof(char)));
	size_t pl = wcstombs(path, fileName.c_str(), fileName.length() * 2 + 1);
	path[pl] = '\0';
	int res = ::rmdir(path);
	free(path);
	bool result = (res == 0);
	return result;
#endif
}


FileType Files::getConsoleBuffer()
{
	if (!consoleInputBuffer) {
		Core::abort(Core::fromUtf8("Консоль не доступна"));
		return FileType();
	} else {
		FileType ft;
		ft.valid = true;
		ft.setType(FileType::Console);
		return ft;
	}
}

FileType Files::open(
	const String &shortName,
	FileType::OpenMode mode,
	bool remember,
	FILE **fh
) {
	String fileName = getAbsolutePath(shortName);
	for (std::deque<FileType>::const_iterator it = openedFiles.begin(); it != openedFiles.end(); ++it) {
		const FileType &f = (*it);
		if (f.getName() == fileName) {
			Core::abort(Core::fromUtf8("Файл уже открыт: ") + fileName);
			return FileType();
		}
	}
	bool isCorrectName = true;
	std::string localName;
#if !defined(WIN32) && !defined(_WIN32)
	EncodingError encodingError;
	localName = Coder::encode(UTF8, fileName, encodingError);
	isCorrectName = NoEncodingError == encodingError;
#endif
	if (!isCorrectName) {
		Kumir::Core::abort(Kumir::Core::fromUtf8("Ошибка открытия файла: имя содержит недопустимый символ"));
		return FileType();
	}
	const char *path = localName.c_str();
	FILE *res = 0;

#if defined(WIN32) || defined(_WIN32)
	const wchar_t *fmode = 0;
	if (mode == FileType::Read) {
		fmode = L"rb";
	} else if (mode == FileType::Write) {
		fmode = L"wb";
	} else if (mode == FileType::Append) {
		fmode = L"ab";
	}
	res = _wfopen(fileName.c_str(), fmode);
#else
	const char *fmode = 0;
	if (mode == FileType::Read) {
		fmode = "rb";
	} else if (mode == FileType::Write) {
		fmode = "wb";
	} else if (mode == FileType::Append) {
		fmode = "ab";
	}
	res = fopen(path, fmode);
#endif

	bool file_not_exists = ENOENT == errno;
	FileType f;
	if (res == 0) {
		if (file_not_exists) {
			Core::abort(Core::fromUtf8("Файл не существует: ") + fileName);
		} else {
			Core::abort(Core::fromUtf8("Невозможно открыть файл: ") + fileName);
		}
	} else {
		if (mode == FileType::Append) {
			mode = FileType::Write;
		}
		f.setName(fileName);
		f.setMode(mode);
		f.handle = res;
		f.autoClose = !remember;
		openedFiles.push_back(f);
		if (fh) {
			*fh = res;
		}
	}
	return f;
}

void Files::close(const FileType &key)
{
	std::deque<FileType>::iterator it = openedFiles.begin();
	for (; it != openedFiles.end(); ++it) {
		FileType f = (*it);
		if (f == key) {
			break;
		}
	}
	if (it == openedFiles.end()) {
		Core::abort(Core::fromUtf8("Неверный ключ"));
		return;
	}
	FileType f = (*it);
	FILE *fh = f.handle;
	f.invalidate();
	if (fh) {
		fclose(fh);
	}
	openedFiles.erase(it);
}

void Files::reset(FileType &key)
{
	std::deque<FileType>::iterator it = openedFiles.begin();
	for (; it != openedFiles.end(); ++it) {
		const FileType &f = (*it);
		if (f == key) {
			break;
		}
	}
	if (it == openedFiles.end()) {
		Core::abort(Core::fromUtf8("Неверный ключ"));
		return;
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
577
	FILE *fh = it->handle;
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	fseek(fh, 0, 0);
}

bool Files::eof(const FileType &key)
{
	std::deque<FileType>::iterator it = openedFiles.begin();
	for (; it != openedFiles.end(); ++it) {
		const FileType &f = (*it);
		if (f == key) {
			break;
		}
	}
	if (it == openedFiles.end()) {
		Core::abort(Core::fromUtf8("Неверный ключ"));
		return false;
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
594 595
	FILE *fh = it->handle;

596 597 598
	if (feof(fh)) {
		return true;
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
599 600 601 602

	int ch = fgetc(fh);
	if (ch < 0) {
		return true;
603
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
604 605 606

	ungetc(ch, fh);
	return false;
607 608 609 610 611 612 613 614 615 616 617
}

bool Files::hasData(const FileType &key)
{
	std::deque<FileType>::iterator it = openedFiles.begin();
	for (; it != openedFiles.end(); ++it) {
		const FileType &f = (*it);
		if (f == key) {
			break;
		}
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
618

619 620 621 622
	if (it == openedFiles.end()) {
		Core::abort(Core::fromUtf8("Неверный ключ"));
		return false;
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
	FILE *fh = it->handle;
#if 1
	for (;;) {
		int c = fgetc(fh);
		if (c < 0) {
			return false;
		}
		if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
			continue;
		}
		ungetc(c, fh);
		return true;
	}

#else
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
	long backPos = -1;
	if (fh != stdin) {
		backPos = ftell(fh);
	}
	std::vector<char> buffer(1024);
	size_t readAmount = 0;
	bool result = false;
	while (1) {
		if (feof(fh)) {
			break;
		}
		char ch = fgetc(fh);
		if ((unsigned char)(ch) == 0xFF) {
			break;
		}
		if (fh == stdin) {
			if (readAmount >= buffer.size()) {
				buffer.resize(buffer.size() * 2);
			}
			buffer[readAmount] = ch;
			readAmount ++;
		}
		if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') {
			// found a whitespace
		} else {
			result = true;
			break;
		}
	}
	if (fh == stdin) {
		for (int i = readAmount - 1; i >= 0; i--) {
			ungetc(buffer[i], fh);
		}
	} else {
		fseek(fh, backPos, SEEK_SET);
	}
	return result;
Alexander A. Maly's avatar
Alexander A. Maly committed
675
#endif
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
}

bool Files::overloadedStdIn()
{
	return assignedIN != stdin;
}

bool Files::overloadedStdOut()
{
	return assignedOUT != stdout;
}

FILE *Files::getAssignedIn()
{
	return assignedIN;
}

FILE *Files::getAssignedOut()
{
	return assignedOUT;
}

void Files::assignInStream(String fileName)
{
	StringUtils::trim<String, Char>(fileName);
	if (assignedIN != stdin) {
		fclose(assignedIN);
	}
	if (fileName.length() > 0) {
		open(fileName, FileType::Read, false, &assignedIN);
	} else {
		assignedIN = stdin;
	}
}

void Files::assignOutStream(String fileName)
{
	StringUtils::trim<String, Char>(fileName);
	if (assignedIN != stdout) {
		fclose(assignedOUT);
	}
	if (fileName.length() > 0) {
		open(fileName, FileType::Write, false, &assignedOUT);
	} else {
		assignedOUT = stdout;
	}
}

Alexander A. Maly's avatar
Alexander A. Maly committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
IO::OutputStream::OutputStream(FILE *f, Encoding enc)
{
	streamType_ = File;
	file = f;
	encoding = enc;
	if (encoding == DefaultEncoding) {
		encoding = UTF8;
	}
	externalBuffer_ = 0;

	if (encoding == UTF8 && ftell(file) == 0) {
		static const char *BOM = "\xEF\xBB\xBF";
		fwrite(BOM, sizeof(char), 3, file);
	}
}

740 741 742 743
void IO::OutputStream::writeRawString(const String &s)
{
	if (type() == File) {
		EncodingError encodingError;
Alexander A. Maly's avatar
Alexander A. Maly committed
744
		std::string bytes = Coder::encode(encoding, s, encodingError);
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
		if (encodingError) {
			Core::abort(Core::fromUtf8("Ошибка кодирования строки вывода: недопустимый символ"));
		}
		fwrite(bytes.c_str(), sizeof(char), bytes.length(), file);
	} else if (type() == ExternalBuffer) {
		if (!externalBuffer_) {
			Core::abort(Core::fromUtf8("Ошибка вывода: консоль не доступна"));
		} else {
			externalBuffer_->writeRawString(s);
		}
	} else {
		buffer.append(s);
	}
}

IO::InputStream::InputStream(FILE *f, Encoding enc)
{
	streamType_ = File;
	file_ = f;
	externalBuffer_ = 0;
	encoding_ = enc;
Alexander A. Maly's avatar
Alexander A. Maly committed
766 767 768
	lastChar_ = 0;
	lastCharLength_ = 0;
	lastCharHere_ = false;
769 770 771

	if (encoding_ == DefaultEncoding) {
		bool forceUtf8 = false;
Alexander A. Maly's avatar
Alexander A. Maly committed
772
		if (f != stdin && UTF8 != Core::getSystemEncoding()) {
773 774 775 776
			long curpos = ftell(f);
			fseek(f, 0, SEEK_SET);
			unsigned char B[3];
			if (fread(B, 1, 3, f) == 3) {
Alexander A. Maly's avatar
Alexander A. Maly committed
777
				forceUtf8 = (B[0] == 0xEF && B[1] == 0xBB && B[2] == 0xBF);
778 779 780 781 782 783 784 785 786 787 788 789 790
			}
			fseek(f, curpos, SEEK_SET);
		}
		if (forceUtf8) {
			encoding_ = UTF8;
		} else {
			encoding_ = Core::getSystemEncoding();
		}
	}
	errStart_ = 0;
	errLength_ = 0;
	currentPosition_ = 0;

Alexander A. Maly's avatar
Alexander A. Maly committed
791 792
	if (f != stdin) {
		currentPosition_ = ftell(f);
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
	}
}

bool IO::InputStream::readRawChar(Char &x)
{
	if (type() == InternalBuffer) {
		if ((size_t) currentPosition_ == buffer_.length()) {
			return false;
		}
		x = buffer_.at(currentPosition_);
		currentPosition_ += 1;
		errLength_ += 1;
		return true;
	} else if (type() == ExternalBuffer) {
		return externalBuffer_->readRawChar(x);
	} else {
Alexander A. Maly's avatar
Alexander A. Maly committed
809 810 811 812 813
		if (lastCharHere_) {
			lastCharHere_ = false;
			currentPosition_ += lastCharLength_;
			x = lastChar_;
			return true;
814
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
815 816 817 818
		lastCharLength_ = 0;
		char buf[4] = {0, 0, 0, 0};
		int ch = fgetc(file_);
		if (ch < 0) {
819 820
			return false;
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
821
		buf[0] = ch;
822
		if (encoding_ != UTF8) {
Alexander A. Maly's avatar
Alexander A. Maly committed
823 824
			lastCharLength_ = 1;
			currentPosition_ +=  lastCharLength_;
825
		} else {
Alexander A. Maly's avatar
Alexander A. Maly committed
826
#if 0
827
			// More complex...
Alexander A. Maly's avatar
Alexander A. Maly committed
828 829
			long cpos = 1; //ftell(file_);
			fprintf(stderr, "cpos=%ld\n", cpos);
830 831 832 833 834 835 836 837 838 839 840 841 842
			if (cpos == 0) {
				// Try to read BOM
				static const char *BOM = "\xEF\xBB\xBF";
				char firstThree[3];
				bool seekBack = true;
				if (fread(firstThree, sizeof(char), 3, file_) == 3
					&& strncmp(BOM, firstThree, 3) == 0) {
					seekBack = false;
				}
				if (seekBack) {
					fseek(file_, 0, SEEK_SET);
				}
			}
Alexander A. Maly's avatar
Alexander A. Maly committed
843 844 845 846
			int ch = fgetc(file_);
			fprintf(stderr, "%s:%d ch=%d \n", __FILE__, __LINE__, ch);
			if (ch < 0) {
				return - 1;
847
			}
Alexander A. Maly's avatar
Alexander A. Maly committed
848 849 850 851
			lastCharBuffer_[0] = ch;
#endif

			uint8_t firstByte = buf[0];
852
			int extraBytes = 0;
Alexander A. Maly's avatar
Alexander A. Maly committed
853 854
			if (firstByte & 0x80) {
				if ((firstByte >> 5) == 0x06) {
855
					extraBytes = 1;
Alexander A. Maly's avatar
Alexander A. Maly committed
856
				} else if ((firstByte >> 4) == 0x0E) {
857
					extraBytes = 2;
Alexander A. Maly's avatar
Alexander A. Maly committed
858 859
				} else if ((firstByte >> 3) == 0x1E) {
					extraBytes = 3;
860 861
				}
			}
Alexander A. Maly's avatar
Alexander A. Maly committed
862 863
			lastCharLength_ = 1 + extraBytes;
			currentPosition_ += lastCharLength_;
864
			for (int i = 0; i < extraBytes; i++) {
Alexander A. Maly's avatar
Alexander A. Maly committed
865 866
				ch = fgetc(file_);
				if ((ch >> 6) != 2) {
867 868 869
					Core::abort(Core::fromUtf8("Ошибка чтения данных из файла: UTF-8 файл поврежден"));
					return false;
				}
Alexander A. Maly's avatar
Alexander A. Maly committed
870
				buf[i + 1] = ch;
871 872
			}
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
873 874

		std::string sb(buf);
875
		EncodingError encodingError;
Alexander A. Maly's avatar
Alexander A. Maly committed
876
		std::wstring res = Coder::decode(encoding_, sb, encodingError);
877 878 879 880
		if (encodingError) {
			Core::abort(Core::fromUtf8("Ошибка перекодирования при чтении данных из текстового файла"));
			return false;
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
881
		if (res.length() != 1) {
882 883 884
			Core::abort(Core::fromUtf8("Ошибка перекодирования при чтении данных из текстового файла"));
			return false;
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
885 886 887 888 889
		x = lastChar_ = res.at(0);
		if (x == 0xfeff && currentPosition_ == lastCharLength_) {
			// Initial BOM, transform it to space
			x = lastChar_ = Char(' ');
		}
890 891 892 893 894 895 896 897 898 899 900 901 902
		return true;
	}
}


void IO::InputStream::pushLastCharBack()
{
	if (type() == InternalBuffer) {
		currentPosition_ -= 1;
		errLength_ -= 1;
	} else if (type() == ExternalBuffer) {
		externalBuffer_->pushLastCharBack();
	} else { /* File */
Alexander A. Maly's avatar
Alexander A. Maly committed
903 904

#if 0
905 906 907 908 909 910 911
		if (file_ == stdin) {
			if (lastCharBuffer_[2] != '\0') {
				ungetc(lastCharBuffer_[2], file_);
			}
			if (lastCharBuffer_[1] != '\0') {
				ungetc(lastCharBuffer_[1], file_);
			}
Alexander A. Maly's avatar
Alexander A. Maly committed
912 913
			int res = ungetc(lastCharBuffer_[0], file_);
			fprintf(stderr, "%s:%d ungetc=%d \n", __FILE__, __LINE__, res);
914 915 916
		} else {
			fseek(file_, -1 * strlen(lastCharBuffer_), SEEK_CUR);
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
917 918 919 920 921 922 923 924
#else
		if (lastCharHere_) {
			fprintf(stderr, "InputStream: cannot push back more than one character, doing nothing.");
		} else {
			lastCharHere_ = true;
			currentPosition_ -= lastCharLength_;
		}
#endif
925 926 927 928 929 930 931
	}
}


String IO::InputStream::readUntil(const String &delimeters)
{
	String result;
Alexander A. Maly's avatar
Alexander A. Maly committed
932
	result.reserve(10);
933 934
	Char current;
	while (readRawChar(current)) {
Alexander A. Maly's avatar
Alexander A. Maly committed
935
		if (delimeters.find_first_of(current) != String::npos ) {
936 937 938
			pushLastCharBack();
			break;
		} else {
Alexander A. Maly's avatar
Alexander A. Maly committed
939
			result.push_back(current);
940 941 942 943 944 945 946 947
		}
	}
	return result;
}


void IO::InputStream::skipDelimiters(const String &del)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
948
	const String &delim = del.empty() ? inputDelimiters : del;
949 950 951 952

	// Skip delimiters until lexem
	Char skip(32);
	while (readRawChar(skip)) {
Alexander A. Maly's avatar
Alexander A. Maly committed
953
		if (delim.find_first_of(skip) == String::npos) {
954 955 956 957
			pushLastCharBack();
			break;
		}
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
958
	markPossibleErrorStart();
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
}


// Format parsing functions
StringList IO::splitIntoLexemsByDelimeter(
	const String &s,
	Char delim
) {
	StringList result;
	String current;
	current.reserve(10);
	for (size_t i = 0; i < s.length(); i++) {
		if (s[i] == delim) {
			result.push_back(current);
			current.clear();
		} else if (s[i] != ' ') {
			current.push_back(s[i]);
		}
	}
	if (current.length() > 0) {
		result.push_back(current);
	}
	return result;
}

String IO::readWord(InputStream &is)
{
	String delim = inputDelimiters;
	// Mark as lexem begin position
Alexander A. Maly's avatar
Alexander A. Maly committed
988
	is.skipDelimiters(delim);
989 990 991 992 993 994 995 996
	return is.readUntil(delim);
}


String IO::readString(InputStream &is)
{
	String delim = inputDelimiters;
	// Mark as lexem begin position
Alexander A. Maly's avatar
Alexander A. Maly committed
997
	is.skipDelimiters(delim);
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	Char bracket = Char('\0');
	if (!is.readRawChar(bracket)) {
		is.setError(Core::fromUtf8("Не могу прочитать литерал: текст закончился"));
		return String();
	}
	if (bracket != Char('\'') && bracket != Char('"')) {
		is.pushLastCharBack();
		return is.readUntil(delim);
	}
	Char current;
	String result;
Alexander A. Maly's avatar
Alexander A. Maly committed
1009
	result.reserve(10);
1010 1011 1012 1013 1014 1015 1016 1017
	while (is.readRawChar(current)) {
		if (current != bracket) {
			result.push_back(current);
		} else {
			break;
		}
	}
	if (current != bracket) {
Alexander A. Maly's avatar
Alexander A. Maly committed
1018
//		is.setError(Core::fromUtf8("Ошибка чтения литерала: текст закончился раньше, чем появилась закрывающая кавычка"));
1019 1020 1021 1022 1023 1024 1025
	}
	return result;
}

String IO::readLine(InputStream &is)
{
	String result;
Alexander A. Maly's avatar
Alexander A. Maly committed
1026
	result.reserve(10);
1027 1028
	Char current;
	while (is.readRawChar(current)) {
Alexander A. Maly's avatar
Alexander A. Maly committed
1029
		if (current == '\n') {
1030 1031
			break;
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
1032 1033 1034
		if (current != '\r') {
			result.push_back(current);
		}
1035
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
	return result;
}

Char IO::readChar(InputStream &is)
{
	Char result(0);
	if (is.hasError()) {
		return result;
	}

Alexander A. Maly's avatar
Alexander A. Maly committed
1047
	bool ok = is.readRawChar(result);
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
	if (!ok) {
		is.setError(Core::fromUtf8("Ошибка ввода символа: текст закончился"));
	}

	return result;
}

int IO::readInteger(InputStream &is)
{
	String word = readWord(is);
Alexander A. Maly's avatar
Alexander A. Maly committed
1058
	//fprintf(stderr, "%s:%d word='%S' \n", __FILE__, __LINE__, word.c_str());
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
	if (is.hasError()) {
		return 0;
	}
	Converter::ParseError error = Converter::NoError;
	int result = Converter::parseInt(word, 0, error);
	if (error == Converter::EmptyWord) {
		is.setError(Core::fromUtf8("Ошибка ввода целого числа: текст закончился"));
	} else if (error == Converter::BadSymbol) {
		is.setError(Core::fromUtf8("Ошибка ввода целого числа: число содержит неверный символ"));
	} else if (error == Converter::Overflow) {
		is.setError(Core::fromUtf8("Ошибка ввода: слишком большое целое число"));
	}
	return result;
}

real IO::readReal(InputStream &is)
{
	String word = readWord(is);
	if (is.hasError()) {
		return 0;
	}
	Converter::ParseError error = Converter::NoError;
	real result = Converter::parseReal(word, '.', error);
	if (error == Converter::EmptyWord) {
		is.setError(Core::fromUtf8("Ошибка ввода вещественного числа: текст закончился"));
	} else if (error == Converter::BadSymbol) {
		is.setError(Core::fromUtf8("Ошибка ввода вещественного числа: число содержит неверный символ"));
	} else if (error == Converter::WrongExpForm) {
		is.setError(Core::fromUtf8("Ошибка ввода вещественного числа: неверная запись экспоненциальной формы"));
	} else if (error == Converter::WrongReal) {
		is.setError(Core::fromUtf8("Ошибка ввода вещественного числа: неверная запись"));
	} else if (error == Converter::Overflow) {
		is.setError(Core::fromUtf8("Ошибка ввода: слишком большое вещественное число"));
	}
	return result;
}

Alexander A. Maly's avatar
Alexander A. Maly committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
static struct BoolCode {
	bool value;
	const wchar_t *name;
} boolCodes[] = {
	{0, L"0"},
	{1, L"1"},
	{0, L"false"},
	{0, L"no"},
	{1, L"true"},
	{1, L"yes"},
	{1, L"да"},
	{1, L"истина"},
	{0, L"ложь"},
	{0, L"нет"},
}; // should be lexicographically ordered
static int boolCodesSize = sizeof(boolCodes) / sizeof(boolCodes[0]);

static bool operator <(const BoolCode &x, const BoolCode &y) {
	return String(x.name) < String(y.name);
}


1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
bool IO::readBool(InputStream &is)
{
	String word = Core::toLowerCaseW(readWord(is));
	if (is.hasError()) {
		return 0;
	}
	if (word.length() == 0) {
		is.setError(Core::fromUtf8("Ошибка ввода логического значения: ничего не введено"));
	}

Alexander A. Maly's avatar
Alexander A. Maly committed
1128 1129 1130 1131 1132
#if 0
	for (int i = 0; i < boolCodesSize; i++) {
		if (word == boolCodes[i].name) {
			return boolCodes[i].value;
		}
1133
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
1134 1135 1136 1137 1138 1139
#else
	const BoolCode pat {.name = word.c_str()};
	const BoolCode *first = boolCodes, *last = boolCodes + boolCodesSize;
	const BoolCode *here = std::lower_bound(first, last, pat);
	if (here != last && word == here->name) {
		return here->value;
1140
	}
Alexander A. Maly's avatar
Alexander A. Maly committed
1141
#endif
1142

Alexander A. Maly's avatar
Alexander A. Maly committed
1143 1144
	is.setError(Core::fromUtf8("Ошибка ввода логического значения: неизвестное значение"));
	return false;
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
}

void IO::writeString(OutputStream &os, const String &str, int width)
{
	String data = str;
	if (width) {
		// TODO implement me
	}
	os.writeRawString(data);
}

void IO::writeChar(OutputStream &os, const Char &chr, int width)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
1158
	String data(1, chr);
1159 1160 1161 1162 1163 1164 1165 1166
	if (width) {
		// TODO implement me
	}
	os.writeRawString(data);
}

void IO::writeInteger(OutputStream &os, int value, int width)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
1167
	String strval = Converter::sprintfInt(value, 10, width, 'r');
1168 1169 1170 1171 1172
	os.writeRawString(strval);
}

void IO::writeReal(OutputStream &os, real value, int width, int decimals)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
1173
	String strval = Converter::sprintfReal(value, '.', false, width, decimals, 'r');
1174 1175 1176 1177 1178
	os.writeRawString(strval);
}

void IO::writeBool(OutputStream &os, bool value, int width)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
1179 1180 1181 1182
	static const wchar_t *names[2] = {L"нет", L"да"};
//	static const String YES = Core::fromUtf8("да");
//	static const String NO = Core::fromUtf8("нет");
	String sval = names[value ? 1 : 0];
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
	if (width) {
		// TODO implement me
	}
	os.writeRawString(sval);
}


void IO::setLocaleEncoding(Encoding enc)
{
	LOCALE_ENCODING = enc;
}

IO::InputStream IO::makeInputStream(FileType fileNo, bool fromStdIn)
{
	if (fromStdIn && fileNo.getType() != FileType::Console) {
		return InputStream(Files::getAssignedIn(), LOCALE_ENCODING);
	} else if (fileNo.getType() == FileType::Console) {
		return InputStream(consoleInputBuffer);
	} else {
		std::deque<FileType>::iterator it = openedFiles.begin();
		for (; it != openedFiles.end(); ++it) {
			if (*it == fileNo) {
				break;
			}
		}
		if (it == openedFiles.end()) {
			Core::abort(Core::fromUtf8("Файл с таким ключем не открыт"));
			return InputStream();
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
1212
		if (it->getMode() != FileType::Read) {
1213 1214 1215
			Core::abort(Core::fromUtf8("Файл с таким ключем открыт на запись"));
			return InputStream();
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
1216
		return InputStream(it->handle, fileEncoding);
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
	}
}

IO::OutputStream IO::makeOutputStream(FileType fileNo, bool toStdOut)
{
	if (toStdOut) {
		return OutputStream(Files::getAssignedOut(), LOCALE_ENCODING);
	} else if (fileNo.getType() == FileType::Console) {
		return OutputStream(consoleOutputBuffer);
	} else {
		std::deque<FileType>::iterator it = openedFiles.begin();
		for (; it != openedFiles.end(); ++it) {
			if (*it == fileNo) {
				break;
			}
		}
		if (it == openedFiles.end()) {
			Core::abort(Core::fromUtf8("Файл с таким ключем не открыт"));
			return OutputStream();
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
1237
		if (it->getMode() == FileType::Read) {
1238 1239 1240
			Core::abort(Core::fromUtf8("Файл с таким ключем открыт на чтение"));
			return OutputStream();
		}
Alexander A. Maly's avatar
Alexander A. Maly committed
1241
		return OutputStream(it->handle, fileEncoding);
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
	}
}


String IO::readString(FileType fileNo, bool fromStdIn)
{
	InputStream stream = makeInputStream(fileNo, fromStdIn);
	if (Core::getError().length() > 0) {
		return String();
	}
	return readString(stream);
}

String IO::readLine(FileType fileNo, bool fromStdIn)
{
	InputStream stream = makeInputStream(fileNo, fromStdIn);
	if (Core::getError().length() > 0) {
		return String();
	}
	return readLine(stream);
}

int IO::readInteger(FileType fileNo, bool fromStdIn)
{
	InputStream stream = makeInputStream(fileNo, fromStdIn);
	if (Core::getError().length() > 0) {
		return 0;
	}
	return readInteger(stream);
}

real IO::readReal(FileType fileNo, bool fromStdIn)
{
	InputStream stream = makeInputStream(fileNo, fromStdIn);
	if (Core::getError().length() > 0) {
		return 0.0;
	}
	return readReal(stream);
}

bool IO::readBool(FileType fileNo, bool fromStdIn)
{
	InputStream stream = makeInputStream(fileNo, fromStdIn);
	if (Core::getError().length() > 0) {
		return false;
	}
	return readBool(stream);
}

Char IO::readChar(FileType fileNo, bool fromStdIn)
{
	InputStream stream = makeInputStream(fileNo, fromStdIn);
	if (Core::getError().length() > 0) {
		return Char(' ');
	}
	return readChar(stream);
}


void IO::writeString(int width, const String &value, FileType fileNo, bool toStdOut)
{
	OutputStream stream = makeOutputStream(fileNo, toStdOut);
	if (Core::getError().length() > 0) {
		return;
	}
	writeString(stream, value, width);
}

void IO::writeChar(int width, Char value, FileType fileNo, bool toStdOut)
{
	OutputStream stream = makeOutputStream(fileNo, toStdOut);
	if (Core::getError().length() > 0) {
		return;
	}
	writeChar(stream, value, width);
}

void IO::writeInteger(int width, int value, FileType fileNo, bool toStdOut)
{
	OutputStream stream = makeOutputStream(fileNo, toStdOut);
	if (Core::getError().length() > 0) {
		return;
	}
	writeInteger(stream, value, width);
}

void IO::writeReal(int width, int decimals, real value, FileType fileNo, bool toStdOut)
{
	OutputStream stream = makeOutputStream(fileNo, toStdOut);
	if (Core::getError().length() > 0) {
		return;
	}
	writeReal(stream, value, width, decimals);
}

void IO::writeBool(int width, bool value, FileType fileNo, bool toStdOut)
{
	OutputStream stream = makeOutputStream(fileNo, toStdOut);
	if (Core::getError().length() > 0) {
		return;
	}
	writeBool(stream, value, width);
}


} // namespace Kumir