<commit_before>#include "disassembler.h"
#include "util.h"
#include "symtab.h"

#include <vector>
#include <cctype>

using namespace std;

enum ByteTypeGuess {
	UNINITIALIZED,
	UNKNOWN,
	CHAR_DATA,
	UNINITIALIZED_CHAR_DATA,
	WORD_DATA,
	UNINITIALIZED_WORD_DATA,
	CODE,
};

struct program {
	ByteTypeGuess byte_type_guess[65536];
	char memory[65536];
	bool is_labelled[65536];

	string name;
	string starting_address;
	int length_of_program;
	string first_executable_instruction;
	program() {
		for ( int i = 0 ; i < 65536 ; i++ ) {
			byte_type_guess[i] = UNINITIALIZED;
			memory[i] = 0;
			is_labelled[i] = false;
		}
		name = "";
		starting_address = "";
		length_of_program = 0;
		first_executable_instruction = "";
	}
};

bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);

bool disassemble(ifstream &ifile, ofstream &ofile) {
	string record;
	program p;
	while ( read_record(ifile, record) ) {
		record_to_memory(record, p);
	}
	status("Done reading records");
	analyze_code_data(p);
	status("Done analyzing program for code and data");
	write_assembly(p, ofile);
	status("Done writing output file");
	return true;
}

string read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
	string ret;
	char t;
	for ( int col = col_begin ; col <= col_end ; col++ ) {
		t = ifile.get();
		if ( t == EOF || t == '\n' ) {
			string errstr;
			errstr += "Unexpected end of ";
			errstr += record_type;
			errstr += " record";
			fatal(errstr);
		}
		ret += t;
	}
	return ret;
}

string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
	string ret;
	ret = read_columns(ifile,col_begin,col_end,record_type);
	make_upper_case(ret);
	if ( !is_hex_string(ret) ) {
		string errstr;
		errstr += "Unexpected non-hexadecimal character found in ";
		errstr += record_type;
		errstr += " record";
		fatal(errstr);
	}
	return ret;
}

bool read_record(ifstream &ifile, string &record) {
	int temp_int;
	string temp_str;
	char t;

	do {
		t = ifile.get();
		if ( t == EOF ) {
			return false;
		}
	} while ( t == '\n' || t == ' ' );
	record = "";
	record += t;

	switch (t) {
		case 'H': // Header
			record += read_columns(ifile,2,7,'H');
			record += read_hex_columns(ifile,8,19,'H');
			break;
		case 'T': // Text
			record += read_hex_columns(ifile,2,7,'T');
			temp_str = read_hex_columns(ifile,8,9,'T');
			temp_int = hex2int(temp_str);
			record += temp_str;
			record +=  read_hex_columns(ifile,10,9+2*temp_int,'T');
			break;
		case 'E': // End
			record += read_hex_columns(ifile,2,7,'E');
			break;
		default:
			{
				string errstr = "Unknown record type ";
				errstr += t;
				fatal(errstr);
			}
	}
	return true;
}

void record_to_memory(const string record, program &p) {
	const char * c_record = record.c_str();
	switch (*c_record) {
		case 'H': // Header
			if ( p.name.length() != 0 ) {
				fatal("Multiple H records");
			}
			p.name = record.substr(1,6);
			p.starting_address = record.substr(7,6);
			p.length_of_program = hex2int(record.substr(13,6));
			break;
		case 'T': // Text
			{
				int text_start = hex2int(record.substr(1,6));
				int bit_length = hex2int(record.substr(7,2));
				for ( int i = 0 ; i < bit_length ; i++ ) {
					p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
					p.byte_type_guess[i+text_start] = UNKNOWN;
				}
			}
			break;
		case 'E': // End
			if ( p.first_executable_instruction.length() != 0 ) {
				fatal("Multiple E records");
			}
			p.first_executable_instruction = record.substr(1,6);
			break;
		default:
			{
				string errstr;
				errstr += "Unknown record type ";
				errstr += *c_record;
				fatal(errstr);
			}
	}
}

void mark_code_data(program &p, int location, ByteTypeGuess btg) {
	if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
		return;
	}
	switch (btg) {
		case UNINITIALIZED:
		case UNKNOWN:
			break;
		case CHAR_DATA:
		case UNINITIALIZED_CHAR_DATA:
			{
				if ( p.byte_type_guess[location] != UNKNOWN &&
					 p.byte_type_guess[location] != UNINITIALIZED ) {
					break;
				}
				if ( p.byte_type_guess[location] == UNINITIALIZED )
					btg = UNINITIALIZED_CHAR_DATA;
				p.byte_type_guess[location] = btg;
				break;
			}
		case WORD_DATA:
		case UNINITIALIZED_WORD_DATA:
			{
				if ( p.byte_type_guess[location] != UNKNOWN &&
					 p.byte_type_guess[location] != UNINITIALIZED ) {
					break;
				}
				if ( p.byte_type_guess[location] == UNINITIALIZED )
					btg = UNINITIALIZED_WORD_DATA;
				p.byte_type_guess[location+0] = btg;
				p.byte_type_guess[location+1] = btg;
				p.byte_type_guess[location+2] = btg;
				break;
			}
		case CODE:
			{
				if ( p.byte_type_guess[location] == UNINITIALIZED ) {
					fatal("Attempting to use uninitialized section as code");
				}
				if ( p.byte_type_guess[location] == CODE ) {
					break;
				}
				p.byte_type_guess[location+0] = btg;
				p.byte_type_guess[location+1] = btg;
				p.byte_type_guess[location+2] = btg;

				string opcode_val = byte2hex(p.memory[location]);
				string opcode;
				string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
				operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
				if ( ! find_from_symtab(opcode,opcode_val) ) {
					string errstr;
					errstr += "Unknown opcode ";
					errstr += opcode_val;
					errstr += " at location ";
					errstr += int2hex(location);
					fatal(errstr);
				}

				if ( opcode == "ADD"  ||
					 opcode == "AND"  ||
					 opcode == "COMP" ||
					 opcode == "DIV"  ||
					 opcode == "LDA"  ||
					 opcode == "LDL"  ||
					 opcode == "LDX"  ||
					 opcode == "MUL"  ||
					 opcode == "OR"   ||
					 opcode == "STA"  ||
					 opcode == "STL"  ||
					 opcode == "STX"  ||
					 opcode == "SUB"  ||
					 opcode == "TIX" ) {
					give_label(operand);
					p.is_labelled[hex2int(operand)] = true;
					mark_code_data(p,hex2int(operand),WORD_DATA);
				}

				if ( opcode == "LDCH" ||
					 opcode == "STCH" ) {
					give_label(operand);
					p.is_labelled[hex2int(operand)] = true;
					mark_code_data(p,hex2int(operand),CHAR_DATA);
				}

				if ( opcode == "J"    ||
					 opcode == "JEQ"  ||
					 opcode == "JGT"  ||
					 opcode == "JLT"  ||
					 opcode == "JSUB" ||
					 opcode == "RSUB" ) {
					give_label(operand);
					p.is_labelled[hex2int(operand)] = true;
					mark_code_data(p,hex2int(operand),CODE);
				}

				if ( opcode != "J" &&
					 opcode != "RSUB" ) {
					mark_code_data(p,location+3,btg);
				}

				break;
			}
	}
}

void analyze_code_data(program &p) {
	if ( p.name.length() == 0 ) {
		fatal("No Header record");
	}
	if ( p.first_executable_instruction.length() == 0 ) {
		fatal("No End record");
	}
	initialize_symtab();
	add_to_symtab("FIRST",p.first_executable_instruction);
	p.is_labelled[hex2int(p.first_executable_instruction)] = true;
	mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}

string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
	const int labellength = 8;
	const int opcodelength = 6;
	string ret = "";
	ret += label + string(labellength-label.length(),' ');
	ret += opcode + string(opcodelength-opcode.length(),' ');
	ret += operand;
	if ( is_indexed ) {
		ret += ",X";
	}
	ret += '\n';
	return ret;
}

void write_assembly(const program &p, ofstream &ofile) {
	ofile << asm_to_line(p.name,"START",p.starting_address,false);
	int start_of_program = hex2int(p.starting_address);
	int end_of_program = start_of_program + p.length_of_program;

	for ( int locctr = start_of_program ; locctr < end_of_program ; ) {
		string label = "";
		string opcode = "";
		string operand = "";
		bool is_indexed = false;

		if ( p.is_labelled[locctr] ) {
			if ( !find_from_symtab(label,int2hex(locctr)) ) {
				string errstr;
				errstr += "Label not created for location ";
				errstr += int2hex(locctr);
				error(errstr);
			}
		}

		if ( p.byte_type_guess[locctr] == CODE ) {
			if ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {
				string errstr;
				errstr += "Unknown opcode ";
				errstr += opcode;
				errstr += " at location ";
				errstr += int2hex(locctr);
				fatal(errstr);
			}
			operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);
			is_indexed = (hex2int(operand)&0x8000);
			operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag

			if ( opcode != "RD" &&
				 opcode != "TD" &&
				 opcode != "WD" &&
				 opcode != "RSUB" ) {
				if ( !find_from_symtab(operand,operand) ) {
					string errstr;
					errstr += "Label not created for operand ";
					errstr += operand;
					error(errstr);
				}
			}

			if ( opcode == "RSUB" ) {
				operand = "";
			}

			locctr += 3;
		} else if ( p.byte_type_guess[locctr] == CHAR_DATA ||
					p.byte_type_guess[locctr] == UNKNOWN ) {
			if ( p.byte_type_guess[locctr] == UNKNOWN ) {
				label = "UNUSED"; // This should not happen in a well written code
			}

			vector<char> byte_list;
			bool type_c = true;
			do {
				byte_list.push_back(p.memory[locctr]);
				if ( !isprint(p.memory[locctr]) ) {
					type_c = false;
				}
				locctr++;
			} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );

			opcode = "CHAR";

			operand += (type_c?"C":"X");
			operand += "'";
			for ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {
				if ( type_c ) {
					operand += byte_list[i];
				} else {
					operand += byte2hex(byte_list[i]);
				}
			}
			operand += "'";
		} else if ( p.byte_type_guess[locctr] == WORD_DATA ) {
			opcode = "WORD";
			operand = int2str(
					p.memory[locctr+0]*256*256+
					p.memory[locctr+1]*256+
					p.memory[locctr+2]
				);
			locctr += 3;
		} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA ||
		            p.byte_type_guess[locctr] == UNINITIALIZED ) {
			opcode = "RESB";
			int buf_size = 0;
			do {
				buf_size++;
				locctr++;
			} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA
				    || p.byte_type_guess[locctr] == UNINITIALIZED)
			        && !p.is_labelled[locctr]
			        && locctr < end_of_program);
			if ( locctr >= end_of_program ) {
				buf_size--;
			}
			operand = int2str(buf_size);
		} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA ) {
			opcode = "RESW";
			int buf_size = 0;
			do {
				buf_size++;
				locctr+=3;
			} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA
				    || p.byte_type_guess[locctr] == UNINITIALIZED)
					&& !p.is_labelled[locctr]
					&& locctr < end_of_program);
			if ( locctr >= end_of_program ) {
				buf_size--;
			}
			operand = int2str(buf_size);
		} else {
			fatal("Reached part of decompiler that should not be reached");
		}
		ofile << asm_to_line(label,opcode,operand,is_indexed);
	}
	ofile << asm_to_line("","END","FIRST",false);
}<commit_msg>Prevent code marking for RSUB<commit_after>#include "disassembler.h"
#include "util.h"
#include "symtab.h"

#include <vector>
#include <cctype>

using namespace std;

enum ByteTypeGuess {
	UNINITIALIZED,
	UNKNOWN,
	CHAR_DATA,
	UNINITIALIZED_CHAR_DATA,
	WORD_DATA,
	UNINITIALIZED_WORD_DATA,
	CODE,
};

struct program {
	ByteTypeGuess byte_type_guess[65536];
	char memory[65536];
	bool is_labelled[65536];

	string name;
	string starting_address;
	int length_of_program;
	string first_executable_instruction;
	program() {
		for ( int i = 0 ; i < 65536 ; i++ ) {
			byte_type_guess[i] = UNINITIALIZED;
			memory[i] = 0;
			is_labelled[i] = false;
		}
		name = "";
		starting_address = "";
		length_of_program = 0;
		first_executable_instruction = "";
	}
};

bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);

bool disassemble(ifstream &ifile, ofstream &ofile) {
	string record;
	program p;
	while ( read_record(ifile, record) ) {
		record_to_memory(record, p);
	}
	status("Done reading records");
	analyze_code_data(p);
	status("Done analyzing program for code and data");
	write_assembly(p, ofile);
	status("Done writing output file");
	return true;
}

string read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
	string ret;
	char t;
	for ( int col = col_begin ; col <= col_end ; col++ ) {
		t = ifile.get();
		if ( t == EOF || t == '\n' ) {
			string errstr;
			errstr += "Unexpected end of ";
			errstr += record_type;
			errstr += " record";
			fatal(errstr);
		}
		ret += t;
	}
	return ret;
}

string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
	string ret;
	ret = read_columns(ifile,col_begin,col_end,record_type);
	make_upper_case(ret);
	if ( !is_hex_string(ret) ) {
		string errstr;
		errstr += "Unexpected non-hexadecimal character found in ";
		errstr += record_type;
		errstr += " record";
		fatal(errstr);
	}
	return ret;
}

bool read_record(ifstream &ifile, string &record) {
	int temp_int;
	string temp_str;
	char t;

	do {
		t = ifile.get();
		if ( t == EOF ) {
			return false;
		}
	} while ( t == '\n' || t == ' ' );
	record = "";
	record += t;

	switch (t) {
		case 'H': // Header
			record += read_columns(ifile,2,7,'H');
			record += read_hex_columns(ifile,8,19,'H');
			break;
		case 'T': // Text
			record += read_hex_columns(ifile,2,7,'T');
			temp_str = read_hex_columns(ifile,8,9,'T');
			temp_int = hex2int(temp_str);
			record += temp_str;
			record +=  read_hex_columns(ifile,10,9+2*temp_int,'T');
			break;
		case 'E': // End
			record += read_hex_columns(ifile,2,7,'E');
			break;
		default:
			{
				string errstr = "Unknown record type ";
				errstr += t;
				fatal(errstr);
			}
	}
	return true;
}

void record_to_memory(const string record, program &p) {
	const char * c_record = record.c_str();
	switch (*c_record) {
		case 'H': // Header
			if ( p.name.length() != 0 ) {
				fatal("Multiple H records");
			}
			p.name = record.substr(1,6);
			p.starting_address = record.substr(7,6);
			p.length_of_program = hex2int(record.substr(13,6));
			break;
		case 'T': // Text
			{
				int text_start = hex2int(record.substr(1,6));
				int bit_length = hex2int(record.substr(7,2));
				for ( int i = 0 ; i < bit_length ; i++ ) {
					p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
					p.byte_type_guess[i+text_start] = UNKNOWN;
				}
			}
			break;
		case 'E': // End
			if ( p.first_executable_instruction.length() != 0 ) {
				fatal("Multiple E records");
			}
			p.first_executable_instruction = record.substr(1,6);
			break;
		default:
			{
				string errstr;
				errstr += "Unknown record type ";
				errstr += *c_record;
				fatal(errstr);
			}
	}
}

void mark_code_data(program &p, int location, ByteTypeGuess btg) {
	if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
		return;
	}
	switch (btg) {
		case UNINITIALIZED:
		case UNKNOWN:
			break;
		case CHAR_DATA:
		case UNINITIALIZED_CHAR_DATA:
			{
				if ( p.byte_type_guess[location] != UNKNOWN &&
					 p.byte_type_guess[location] != UNINITIALIZED ) {
					break;
				}
				if ( p.byte_type_guess[location] == UNINITIALIZED )
					btg = UNINITIALIZED_CHAR_DATA;
				p.byte_type_guess[location] = btg;
				break;
			}
		case WORD_DATA:
		case UNINITIALIZED_WORD_DATA:
			{
				if ( p.byte_type_guess[location] != UNKNOWN &&
					 p.byte_type_guess[location] != UNINITIALIZED ) {
					break;
				}
				if ( p.byte_type_guess[location] == UNINITIALIZED )
					btg = UNINITIALIZED_WORD_DATA;
				p.byte_type_guess[location+0] = btg;
				p.byte_type_guess[location+1] = btg;
				p.byte_type_guess[location+2] = btg;
				break;
			}
		case CODE:
			{
				if ( p.byte_type_guess[location] == UNINITIALIZED ) {
					fatal("Attempting to use uninitialized section as code");
				}
				if ( p.byte_type_guess[location] == CODE ) {
					break;
				}
				p.byte_type_guess[location+0] = btg;
				p.byte_type_guess[location+1] = btg;
				p.byte_type_guess[location+2] = btg;

				string opcode_val = byte2hex(p.memory[location]);
				string opcode;
				string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
				operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
				if ( ! find_from_symtab(opcode,opcode_val) ) {
					string errstr;
					errstr += "Unknown opcode ";
					errstr += opcode_val;
					errstr += " at location ";
					errstr += int2hex(location);
					fatal(errstr);
				}

				if ( opcode == "ADD"  ||
					 opcode == "AND"  ||
					 opcode == "COMP" ||
					 opcode == "DIV"  ||
					 opcode == "LDA"  ||
					 opcode == "LDL"  ||
					 opcode == "LDX"  ||
					 opcode == "MUL"  ||
					 opcode == "OR"   ||
					 opcode == "STA"  ||
					 opcode == "STL"  ||
					 opcode == "STX"  ||
					 opcode == "SUB"  ||
					 opcode == "TIX" ) {
					give_label(operand);
					p.is_labelled[hex2int(operand)] = true;
					mark_code_data(p,hex2int(operand),WORD_DATA);
				}

				if ( opcode == "LDCH" ||
					 opcode == "STCH" ) {
					give_label(operand);
					p.is_labelled[hex2int(operand)] = true;
					mark_code_data(p,hex2int(operand),CHAR_DATA);
				}

				if ( opcode == "J"    ||
					 opcode == "JEQ"  ||
					 opcode == "JGT"  ||
					 opcode == "JLT"  ||
					 opcode == "JSUB" ) {
					give_label(operand);
					p.is_labelled[hex2int(operand)] = true;
					mark_code_data(p,hex2int(operand),CODE);
				}

				if ( opcode != "J" &&
					 opcode != "RSUB" ) {
					mark_code_data(p,location+3,btg);
				}

				break;
			}
	}
}

void analyze_code_data(program &p) {
	if ( p.name.length() == 0 ) {
		fatal("No Header record");
	}
	if ( p.first_executable_instruction.length() == 0 ) {
		fatal("No End record");
	}
	initialize_symtab();
	add_to_symtab("FIRST",p.first_executable_instruction);
	p.is_labelled[hex2int(p.first_executable_instruction)] = true;
	mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}

string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
	const int labellength = 8;
	const int opcodelength = 6;
	string ret = "";
	ret += label + string(labellength-label.length(),' ');
	ret += opcode + string(opcodelength-opcode.length(),' ');
	ret += operand;
	if ( is_indexed ) {
		ret += ",X";
	}
	ret += '\n';
	return ret;
}

void write_assembly(const program &p, ofstream &ofile) {
	ofile << asm_to_line(p.name,"START",p.starting_address,false);
	int start_of_program = hex2int(p.starting_address);
	int end_of_program = start_of_program + p.length_of_program;

	for ( int locctr = start_of_program ; locctr < end_of_program ; ) {
		string label = "";
		string opcode = "";
		string operand = "";
		bool is_indexed = false;

		if ( p.is_labelled[locctr] ) {
			if ( !find_from_symtab(label,int2hex(locctr)) ) {
				string errstr;
				errstr += "Label not created for location ";
				errstr += int2hex(locctr);
				error(errstr);
			}
		}

		if ( p.byte_type_guess[locctr] == CODE ) {
			if ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {
				string errstr;
				errstr += "Unknown opcode ";
				errstr += opcode;
				errstr += " at location ";
				errstr += int2hex(locctr);
				fatal(errstr);
			}
			operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);
			is_indexed = (hex2int(operand)&0x8000);
			operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag

			if ( opcode != "RD" &&
				 opcode != "TD" &&
				 opcode != "WD" &&
				 opcode != "RSUB" ) {
				if ( !find_from_symtab(operand,operand) ) {
					string errstr;
					errstr += "Label not created for operand ";
					errstr += operand;
					error(errstr);
				}
			}

			if ( opcode == "RSUB" ) {
				operand = "";
			}

			locctr += 3;
		} else if ( p.byte_type_guess[locctr] == CHAR_DATA ||
					p.byte_type_guess[locctr] == UNKNOWN ) {
			if ( p.byte_type_guess[locctr] == UNKNOWN ) {
				label = "UNUSED"; // This should not happen in a well written code
			}

			vector<char> byte_list;
			bool type_c = true;
			do {
				byte_list.push_back(p.memory[locctr]);
				if ( !isprint(p.memory[locctr]) ) {
					type_c = false;
				}
				locctr++;
			} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );

			opcode = "CHAR";

			operand += (type_c?"C":"X");
			operand += "'";
			for ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {
				if ( type_c ) {
					operand += byte_list[i];
				} else {
					operand += byte2hex(byte_list[i]);
				}
			}
			operand += "'";
		} else if ( p.byte_type_guess[locctr] == WORD_DATA ) {
			opcode = "WORD";
			operand = int2str(
					p.memory[locctr+0]*256*256+
					p.memory[locctr+1]*256+
					p.memory[locctr+2]
				);
			locctr += 3;
		} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA ||
		            p.byte_type_guess[locctr] == UNINITIALIZED ) {
			opcode = "RESB";
			int buf_size = 0;
			do {
				buf_size++;
				locctr++;
			} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA
				    || p.byte_type_guess[locctr] == UNINITIALIZED)
			        && !p.is_labelled[locctr]
			        && locctr < end_of_program);
			if ( locctr >= end_of_program ) {
				buf_size--;
			}
			operand = int2str(buf_size);
		} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA ) {
			opcode = "RESW";
			int buf_size = 0;
			do {
				buf_size++;
				locctr+=3;
			} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA
				    || p.byte_type_guess[locctr] == UNINITIALIZED)
					&& !p.is_labelled[locctr]
					&& locctr < end_of_program);
			if ( locctr >= end_of_program ) {
				buf_size--;
			}
			operand = int2str(buf_size);
		} else {
			fatal("Reached part of decompiler that should not be reached");
		}
		ofile << asm_to_line(label,opcode,operand,is_indexed);
	}
	ofile << asm_to_line("","END","FIRST",false);
}<|endoftext|>


<commit_before>#include <iostream>
using namespace std;

class Message {
  int myId;
  public:
    operator int() { return myId; }
    Message(int id) : myId(id) {}
/*
  equalTo - the Message Obect determines its equality with another message object. This may well be an == operator
*/
    bool equalTo(int id) {
      return id % myId == 0;
    }
};

class HandlerBase {

  Message myMessage;
  protected:
    HandlerBase *m_successor;
  public:
    HandlerBase(HandlerBase *s, Message *m) : m_successor(s), myMessage(*m) {}
    void HandleMessage(Message *m) {
        if(myMessage.equalTo(*m)) { // test equality with own message and handle it
            cout << "Message " << *m << " got handled by " << myMessage << "\n";
        } else if(m_successor) { // else hand over to next handler in line
            cout << "Message " << *m << " got handed to successor" << "\n";
            m_successor->HandleMessage(m);
        } else { // or if this was the last handler, give up
            cout << "Message " << *m << " had no handler" << "\n";
        }
    }
};

int main() {
  Message m1(3), m2(5), m3(7), m4(4);
  HandlerBase h1(0, &m1), h2(&h1,&m2), h3(&h2,&m3), h4(&h3,&m4); // create handler chain h4 <> h3 <> h2 <> h1
  int m;
  while(cin >> m) {
    Message newMsg(m);
    h4.HandleMessage(&newMsg);
  }
  return 0;
}

<commit_msg>Update chainresp_01.cpp<commit_after>#include <iostream>
using namespace std;

class Message {
  protected:
  int myId;
  public:
    operator int() { return myId; }
    Message(int id) : myId(id) {}
/*
  equalTo - the Message Obect determines its equality with another message object. This may well be an == operator
*/
    virtual bool equalTo(int id) {
      return id % myId == 0;
    }
};

class HandlerBase {

  Message myMessage;
  protected:
    HandlerBase *m_successor;
  public:
    HandlerBase(HandlerBase *s, Message *m) : m_successor(s), myMessage(*m) {}
    virtual void HandleMessage(Message *m) {
        if(myMessage.equalTo(*m)) { // test equality with own message and handle it
            cout << "Message " << *m << " got handled by " << myMessage << "\n";
        } else if(m_successor) { // else hand over to next handler in line
            cout << "Message " << *m << " got handed to successor" << "\n";
            m_successor->HandleMessage(m);
        } else { // or if this was the last handler, give up
            cout << "Message " << *m << " had no handler" << "\n";
        }
    }
};

int main() {
  Message m1(3), m2(5), m3(7), m4(4);
  HandlerBase h1(0, &m1), h2(&h1,&m2), h3(&h2,&m3), h4(&h3,&m4); // create handler chain h4 <> h3 <> h2 <> h1
  int m;
  while(cin >> m) {
    Message newMsg(m);
    h4.HandleMessage(&newMsg);
  }
  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: flt_reghelper.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:25:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Ocke Janssen
 *
 *
 ************************************************************************/

#ifndef _FLT_REGHELPER_HXX_
#define _FLT_REGHELPER_HXX_

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

namespace dbaxml
{

    #define _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_
    #include "registrationhelper.hxx"
    #undef _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_

}

#endif // _FLT_REGHELPER_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.204); FILE MERGED 2005/09/05 17:33:00 rt 1.2.204.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: flt_reghelper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:13:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FLT_REGHELPER_HXX_
#define _FLT_REGHELPER_HXX_

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

namespace dbaxml
{

    #define _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_
    #include "registrationhelper.hxx"
    #undef _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_

}

#endif // _FLT_REGHELPER_HXX_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: browserids.hxx,v $
 *
 *  $Revision: 1.33 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:55:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#define DBACCESS_UI_BROWSER_ID_HXX

#ifndef _SBASLTID_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _DBACCESS_SLOTID_HRC_
#include "dbaccess_slotid.hrc"
#endif

#define ID_BROWSER_COPY                     SID_COPY
#define ID_BROWSER_CUT                      SID_CUT
#define ID_BROWSER_EDITDOC                  SID_EDITDOC
#define ID_BROWSER_UNDORECORD               SID_FM_RECORD_UNDO
#define ID_BROWSER_SAVERECORD               SID_FM_RECORD_SAVE
#define ID_BROWSER_PASTE                    SID_PASTE
#define ID_BROWSER_CLIPBOARD_FORMAT_ITEMS   SID_CLIPBOARD_FORMAT_ITEMS
#define ID_BROWSER_REDO                     SID_REDO
#define ID_BROWSER_SAVEDOC                  SID_SAVEDOC
#define ID_BROWSER_SAVEASDOC                SID_SAVEASDOC
#define ID_BROWSER_TITLE                    SID_DOCINFO_TITLE
#define ID_BROWSER_UNDO                     SID_UNDO
#define ID_BROWSER_INSERTCOLUMNS            SID_SBA_BRW_INSERT
#define ID_BROWSER_FORMLETTER               SID_SBA_BRW_MERGE
#define ID_BROWSER_INSERTCONTENT            SID_SBA_BRW_UPDATE

#define ID_BROWSER_SEARCH                   SID_FM_SEARCH
#define ID_BROWSER_SORTUP                   SID_FM_SORTUP
#define ID_BROWSER_SORTDOWN                 SID_FM_SORTDOWN
#define ID_BROWSER_AUTOFILTER               SID_FM_AUTOFILTER
#define ID_BROWSER_FILTERCRIT               SID_FM_FILTERCRIT
#define ID_BROWSER_ORDERCRIT                SID_FM_ORDERCRIT
#define ID_BROWSER_REMOVEFILTER             SID_FM_REMOVE_FILTER_SORT
#define ID_BROWSER_FILTERED                 SID_FM_FORM_FILTERED
#define ID_BROWSER_REFRESH                  SID_FM_REFRESH
#define ID_BROWSER_EXPL_PREVLEVEL           SID_EXPLORER_PREVLEVEL
#define ID_BROWSER_COLATTRSET               20  // Spaltenformatierung
#define ID_BROWSER_COLWIDTH                 21  // Spaltenbreite
#define ID_BROWSER_TABLEATTR                22  // table format attributes
#define ID_BROWSER_ROWHEIGHT                23  // Zeilenhoehe
#define ID_BROWSER_COLUMNINFO               24  // copies the column description to insert it into the table design
#define ID_BROWSER_COUNTALL                 SID_FM_COUNTALL // count all
#define ID_BROWSER_ADDTABLE                 SID_FM_ADDTABLE
#define ID_BROWSER_DESIGN                   SID_SBA_QRY_DESIGN
#define ID_BROWSER_EXPLORER                 SID_DSBROWSER_EXPLORER
#define ID_BROWSER_DOCUMENT_DATASOURCE      SID_DOCUMENT_DATA_SOURCE

// The following ids are local to special components (e.g. menus), so they don't need to be unique
// overall. Please have this in mind when changing anything
#define ID_TREE_ADMINISTRATE                 1
#define ID_TREE_CLOSE_CONN                   2
#define ID_TREE_REBUILD_CONN                 3
#define ID_TREE_RELATION_DESIGN              7
#define ID_TABLE_DESIGN_NO_CONNECTION        8
#define ID_OPEN_DOCUMENT                     9
#define ID_EDIT_DOCUMENT                    10
// free
// free
// free
#define ID_CREATE_NEW_DOC                   14
#define ID_FORM_NEW_TEXT                    15
#define ID_FORM_NEW_CALC                    16
#define ID_FORM_NEW_IMPRESS                 17
#define ID_FORM_NEW_PILOT                   18
#define ID_FORM_NEW_TEMPLATE                19
#define ID_NEW_QUERY_DESIGN                 20
#define ID_EDIT_QUERY_DESIGN                21
#define ID_NEW_QUERY_SQL                    22
#define ID_EDIT_QUERY_SQL                   23
#define ID_DROP_QUERY                       24
#define ID_NEW_TABLE_DESIGN                 25
#define ID_EDIT_TABLE                       26
#define ID_DROP_TABLE                       27
#define ID_NEW_VIEW_DESIGN                  28
#define ID_DIRECT_SQL                       32
#define ID_BROWSER_REFRESH_REBUILD          34
#define ID_RENAME_ENTRY                     35
#define ID_INDEX_NEW                        36
#define ID_INDEX_DROP                       37
#define ID_INDEX_RENAME                     38
#define ID_INDEX_SAVE                       39
#define ID_INDEX_RESET                      40
#define ID_DOCUMENT_CREATE_REPWIZ           41
#define ID_BROWSER_SQL                      42
#define ID_APP_NEW_FORM                     43
#define ID_APP_NEW_QUERY_AUTO_PILOT         44
#define ID_NEW_TABLE_DESIGN_AUTO_PILOT      45
#define ID_NEW_VIEW_DESIGN_AUTO_PILOT       46
#define ID_NEW_VIEW_SQL                     47
#define ID_DOCUMENT_CREATE_REPWIZ_PRE_SEL   48
#define ID_FORM_NEW_PILOT_PRE_SEL           49
#define ID_APP_NEW_FOLDER                   50

// image ids
#define SID_DB_FORM_DELETE                  65
#define SID_DB_FORM_RENAME                  66
#define SID_DB_FORM_EDIT                    67
#define SID_DB_FORM_OPEN                    68
#define SID_DB_REPORT_DELETE                69
#define SID_DB_REPORT_RENAME                70
#define SID_DB_REPORT_EDIT                  71
#define SID_DB_REPORT_OPEN                  72
#define SID_DB_QUERY_OPEN                   73
#define SID_DB_TABLE_OPEN                   74
#define SID_DB_QUERY_EDIT                   75

// other
#define ID_BROWSER_QUERY_EXECUTE            SID_FM_EXECUTE
#define ID_BROWSER_CLEAR_QUERY              SID_SBA_CLEAR_QUERY
#define ID_RELATION_ADD_RELATION            SID_SBA_ADD_RELATION
#define ID_BROWSER_QUERY_VIEW_FUNCTIONS     SID_SBA_QUERY_VIEW_FUNCTIONS
#define ID_BROWSER_QUERY_VIEW_TABLES        SID_SBA_QUERY_VIEW_TABLES
#define ID_BROWSER_QUERY_VIEW_ALIASES       SID_SBA_QUERY_VIEW_ALIASES
#define ID_BROWSER_QUERY_DISTINCT_VALUES    SID_SBA_QUERY_DISTINCT_VALUES
#define ID_BROWSER_CLOSE                    SID_CLOSEWIN
#define ID_BROWSER_ESACPEPROCESSING         SID_FM_NATIVESQL

#define ID_QUERY_FUNCTION                   (SID_SBA_START + 41) // Funktionen anzeigen
#define ID_QUERY_TABLENAME                  (SID_SBA_START + 42) // Tabellennamen anzeigen
#define ID_QUERY_ALIASNAME                  (SID_SBA_START + 43) // Aliasnamen anzeigen
#define ID_QUERY_DISTINCT                   (SID_SBA_START + 44) // Distinct anzeigen
#define ID_QUERY_EDIT_JOINCONNECTION        (SID_SBA_START + 45) // show-edit Join
#define ID_QUERY_ZOOM_IN                    SID_ZOOM_IN
#define ID_QUERY_ZOOM_OUT                   SID_ZOOM_OUT

#endif // DBACCESS_UI_BROWSER_ID_HXX
<commit_msg>INTEGRATION: CWS insight02 (1.33.2); FILE MERGED 2004/08/13 14:28:19 oj 1.33.2.2: #i32563# toolbox changes 2004/08/13 08:52:54 oj 1.33.2.1: #i32563# toolbox changes<commit_after>/*************************************************************************
 *
 *  $RCSfile: browserids.hxx,v $
 *
 *  $Revision: 1.34 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-09 09:44:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#define DBACCESS_UI_BROWSER_ID_HXX

#ifndef _SBASLTID_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _DBACCESS_SLOTID_HRC_
#include "dbaccess_slotid.hrc"
#endif

#define ID_BROWSER_COPY                     SID_COPY
#define ID_BROWSER_CUT                      SID_CUT
#define ID_BROWSER_EDITDOC                  SID_EDITDOC
#define ID_BROWSER_UNDORECORD               SID_FM_RECORD_UNDO
#define ID_BROWSER_SAVERECORD               SID_FM_RECORD_SAVE
#define ID_BROWSER_PASTE                    SID_PASTE
#define ID_BROWSER_CLIPBOARD_FORMAT_ITEMS   SID_CLIPBOARD_FORMAT_ITEMS
#define ID_BROWSER_REDO                     SID_REDO
#define ID_BROWSER_SAVEDOC                  SID_SAVEDOC
#define ID_BROWSER_SAVEASDOC                SID_SAVEASDOC
#define ID_BROWSER_TITLE                    SID_DOCINFO_TITLE
#define ID_BROWSER_UNDO                     SID_UNDO
#define ID_BROWSER_INSERTCOLUMNS            SID_SBA_BRW_INSERT
#define ID_BROWSER_FORMLETTER               SID_SBA_BRW_MERGE
#define ID_BROWSER_INSERTCONTENT            SID_SBA_BRW_UPDATE

#define ID_BROWSER_SEARCH                   SID_FM_SEARCH
#define ID_BROWSER_SORTUP                   SID_FM_SORTUP
#define ID_BROWSER_SORTDOWN                 SID_FM_SORTDOWN
#define ID_BROWSER_AUTOFILTER               SID_FM_AUTOFILTER
#define ID_BROWSER_FILTERCRIT               SID_FM_FILTERCRIT
#define ID_BROWSER_ORDERCRIT                SID_FM_ORDERCRIT
#define ID_BROWSER_REMOVEFILTER             SID_FM_REMOVE_FILTER_SORT
#define ID_BROWSER_FILTERED                 SID_FM_FORM_FILTERED
#define ID_BROWSER_REFRESH                  SID_FM_REFRESH
#define ID_BROWSER_EXPL_PREVLEVEL           SID_EXPLORER_PREVLEVEL
#define ID_BROWSER_COLATTRSET               20  // Spaltenformatierung
#define ID_BROWSER_COLWIDTH                 21  // Spaltenbreite
#define ID_BROWSER_TABLEATTR                22  // table format attributes
#define ID_BROWSER_ROWHEIGHT                23  // Zeilenhoehe
#define ID_BROWSER_COLUMNINFO               24  // copies the column description to insert it into the table design
#define ID_BROWSER_COUNTALL                 SID_FM_COUNTALL // count all
#define ID_BROWSER_ADDTABLE                 SID_FM_ADDTABLE
#define ID_BROWSER_EXPLORER                 SID_DSBROWSER_EXPLORER
#define ID_BROWSER_DOCUMENT_DATASOURCE      SID_DOCUMENT_DATA_SOURCE

// The following ids are local to special components (e.g. menus), so they don't need to be unique
// overall. Please have this in mind when changing anything
#define ID_TREE_ADMINISTRATE                 1
#define ID_TREE_CLOSE_CONN                   2
#define ID_TREE_REBUILD_CONN                 3
// free
// free
// free
// free
#define ID_FORM_NEW_TEXT                    15
#define ID_FORM_NEW_CALC                    16
#define ID_FORM_NEW_IMPRESS                 17
#define ID_FORM_NEW_PILOT                   18
#define ID_NEW_QUERY_DESIGN                 20
#define ID_EDIT_QUERY_DESIGN                21
#define ID_NEW_QUERY_SQL                    22
#define ID_EDIT_QUERY_SQL                   23
#define ID_NEW_TABLE_DESIGN                 25
#define ID_NEW_VIEW_DESIGN                  28
#define ID_DIRECT_SQL                       32
#define ID_BROWSER_REFRESH_REBUILD          34
#define ID_INDEX_NEW                        36
#define ID_INDEX_DROP                       37
#define ID_INDEX_RENAME                     38
#define ID_INDEX_SAVE                       39
#define ID_INDEX_RESET                      40
#define ID_DOCUMENT_CREATE_REPWIZ           41
#define ID_BROWSER_SQL                      42

#define ID_APP_NEW_QUERY_AUTO_PILOT         44
#define ID_NEW_TABLE_DESIGN_AUTO_PILOT      45
#define ID_NEW_VIEW_DESIGN_AUTO_PILOT       46
#define ID_NEW_VIEW_SQL                     47

// other
#define ID_BROWSER_QUERY_EXECUTE            SID_FM_EXECUTE

#define ID_BROWSER_CLOSE                    SID_CLOSEWIN
#define ID_BROWSER_ESACPEPROCESSING         SID_FM_NATIVESQL

#define ID_QUERY_FUNCTION                   (SID_SBA_START + 41) // Funktionen anzeigen
#define ID_QUERY_TABLENAME                  (SID_SBA_START + 42) // Tabellennamen anzeigen
#define ID_QUERY_ALIASNAME                  (SID_SBA_START + 43) // Aliasnamen anzeigen
#define ID_QUERY_DISTINCT                   (SID_SBA_START + 44) // Distinct anzeigen
#define ID_QUERY_EDIT_JOINCONNECTION        (SID_SBA_START + 45) // show-edit Join
#define ID_QUERY_ZOOM_IN                    SID_ZOOM_IN
#define ID_QUERY_ZOOM_OUT                   SID_ZOOM_OUT

#endif // DBACCESS_UI_BROWSER_ID_HXX
<|endoftext|>


<commit_before>#include <cassert>
#include <ostream>
#include <exception>

#include "vm.hh"
#include "env.hh"
#include "printer.hh"
#include "zs_memory.hh"

VM vm;

VM::VM() : code(), stack(),
           return_value(1, {}),
           extent(),
           symtable(),
           frame(nullptr),
           exception_handler()
{}

VM::VM(const VM& other) : code(other.code), stack(other.stack),
                          return_value(other.return_value),
                          extent(other.extent),
                          symtable(other.symtable),
                          frame(other.frame),
                          exception_handler(other.exception_handler)
{}

VM::~VM(){}

VM& VM::operator=(const VM& other){
  code = other.code;
  stack = other.stack;
  return_value = other.return_value;
  extent = other.extent,
  symtable = other.symtable;
  frame = other.frame;
  exception_handler = other.exception_handler;
  return *this;
}

std::ostream& operator<<(std::ostream& f, const VM& v){
  f << "--- [code] ---\n";
  for(auto i = v.code.rbegin(), e = v.code.rend(); i != e; ++i){
    f << *i << '\n';
  }

  f << "--- [stack] ---\n";
  for(auto i = v.stack.rbegin(), e = v.stack.rend(); i != e; ++i){
    f << *i << '\n';
  }

  f << "--- [return value] ---\n";
  f << '[' << v.return_value.size() << "] ";
  for(auto i = v.return_value.begin(), e = v.return_value.end(); i != e; ++i){
    f << '\t' << *i << '\n';
  }

  if(!v.extent.empty()){
    f << "--- [extent] ---\n";
    for(auto i = v.extent.begin(), e = v.extent.end(); i != e; ++i){
      f << i->thunk << ": " << i->before << ", " << i->after << "\n";
    }
  }

  // f << "--- [env] ---\n";
  // f << *v.frame_;

  // f << "--- [symtable] ---\n";
  // f << *v.symtable_;

  if(!v.exception_handler.empty()){
    f << "--- [exception handler] ---\n";
    for(auto i = v.exception_handler.rbegin(), e = v.exception_handler.rend(); i != e; ++i){
      f << *i << "\n";
    }
  }

  f << "\n\n";

  return f;
}

// class ZsArgs
// - invalidate() :: marks as unusable.
// - cleanup() :: destroys vm's arguments really.

ZsArgs::ZsArgs()
  : size_(vm.stack.back().get<int>()),
    stack_iter_s_(vm.stack.end() - (size_ + 1)){}

ZsArgs::ZsArgs(ZsArgs&& other)
  : size_(other.size_),
    stack_iter_s_(move(other.stack_iter_s_)){
  other.invalidate();
}

ZsArgs::~ZsArgs(){
  cleanup();
}

ZsArgs& ZsArgs::operator=(ZsArgs&& other){
  size_ = other.size_;
  stack_iter_s_ = move(other.stack_iter_s_);
  other.invalidate();
  return *this;
}

void ZsArgs::cleanup(){
  if(size_ < 0) return;

  if(!std::uncaught_exception()){
    vm.stack.erase(this->begin(), this->end() + 1);
    invalidate();
  }
}

inline
void ZsArgs::invalidate(){
  size_ = -1;
}

inline
bool ZsArgs::valid() const{
  return (size_ >= 0);
}
<commit_msg>cleanup vm.cc<commit_after>#include <cassert>
#include <ostream>
#include <exception>

#include "vm.hh"
#include "env.hh"
#include "printer.hh"
#include "zs_memory.hh"

VM vm;

VM::VM() : code(), stack(),
           return_value(1, {}),
           extent(),
           symtable(),
           frame(nullptr),
           exception_handler()
{}

VM::VM(const VM&) = default;

VM::~VM() = default;

VM& VM::operator=(const VM&) = default;

std::ostream& operator<<(std::ostream& f, const VM& v){
  f << "--- [code] ---\n";
  for(auto i = v.code.rbegin(), e = v.code.rend(); i != e; ++i){
    f << *i << '\n';
  }

  f << "--- [stack] ---\n";
  for(auto i = v.stack.rbegin(), e = v.stack.rend(); i != e; ++i){
    f << *i << '\n';
  }

  f << "--- [return value] ---\n";
  f << '[' << v.return_value.size() << "] ";
  for(auto i = v.return_value.begin(), e = v.return_value.end(); i != e; ++i){
    f << '\t' << *i << '\n';
  }

  if(!v.extent.empty()){
    f << "--- [extent] ---\n";
    for(auto i = v.extent.begin(), e = v.extent.end(); i != e; ++i){
      f << i->thunk << ": " << i->before << ", " << i->after << "\n";
    }
  }

  // f << "--- [env] ---\n";
  // f << *v.frame_;

  // f << "--- [symtable] ---\n";
  // f << *v.symtable_;

  if(!v.exception_handler.empty()){
    f << "--- [exception handler] ---\n";
    for(auto i = v.exception_handler.rbegin(), e = v.exception_handler.rend(); i != e; ++i){
      f << *i << "\n";
    }
  }

  f << "\n\n";

  return f;
}

// class ZsArgs
// - invalidate() :: marks as unusable.
// - cleanup() :: destroys vm's arguments really.

ZsArgs::ZsArgs()
  : size_(vm.stack.back().get<int>()),
    stack_iter_s_(vm.stack.end() - (size_ + 1)){}

ZsArgs::ZsArgs(ZsArgs&& other)
  : size_(other.size_),
    stack_iter_s_(move(other.stack_iter_s_)){
  other.invalidate();
}

ZsArgs::~ZsArgs(){
  cleanup();
}

ZsArgs& ZsArgs::operator=(ZsArgs&& other){
  size_ = other.size_;
  stack_iter_s_ = move(other.stack_iter_s_);
  other.invalidate();
  return *this;
}

void ZsArgs::cleanup(){
  if(size_ < 0) return;

  if(!std::uncaught_exception()){
    vm.stack.erase(this->begin(), this->end() + 1);
    invalidate();
  }
}

inline
void ZsArgs::invalidate(){
  size_ = -1;
}

inline
bool ZsArgs::valid() const{
  return (size_ >= 0);
}
<|endoftext|>


<commit_before>#include "CppLINQ.h"
#include <iostream>
#include <string>

int main()
{
	using namespace	LL;
	struct PetOwner
	{
		PetOwner() = default;
		PetOwner(const std::string &name, const std::vector<std::string> &pets, const std::vector<int> &num)
			:name_(name), pets_(pets), num_(num) {};
		std::string name_;
		std::vector<std::string> pets_;
		std::vector<int> num_;
	};
	std::vector<PetOwner> vp{ PetOwner("higa", std::vector<std::string>{std::string("scruffy"), std::string("sam")}, std::vector<int>{10,20,30}), PetOwner("ronen", std::vector<std::string>{std::string("walker"), std::string("sugar")}, std::vector<int>{40,50,60}) };
	auto s = from(vp).select_many([](PetOwner i) {return i.pets_; });

	std::vector<std::vector<int>> a{ std::vector<int>{1,2},std::vector<int>{4,5,6,7},std::vector<int>{8,10,11,12} };
	std::vector<int> a1{ 1, 2, 3, 4, 5, 6 };
	std::vector<int> a3{};
	std::vector<float> a2{ 123.456f };
	std::vector<int> a4{ 1,2,2,3,4,4,10 };
	auto b = from(a1);
	auto c = from(a1).skip(2);
	auto e = b.concat(c);
	auto f = from(a4).distinct().linq_union(from(a4));
	auto g = from(a3).default_if_empty();
	//auto b = from(a).select_many([](auto i) {return i; }).to_vector();
	//auto d = from(a2).cast<std::string>();
	//for(auto ele:b)
	//std::cout << ele << std::endl;
	//for (auto ele : e)
		//std::cout << ele << std::endl;

	for (auto ele : s)
	{
		std::cout << ele << std::endl;
	}

	//std::cout << c.last_or_default([](auto i) {return i < 0; }) << std::endl;
}
<commit_msg>add test<commit_after>#ifdef _MSC_VER
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include "CppLINQ.h"
#include <iostream>
#include <string>
#include <assert.h>
#include <algorithm>

using namespace	LL;
struct PetOwner
{
    PetOwner() = default;
    PetOwner(const std::string &name, const std::vector<std::string> &pets, const std::vector<int> &num)
        :name_(name), pets_(pets), num_(num) {};
    std::string name_;
    std::vector<std::string> pets_;
    std::vector<int> num_;
};

void test()
{
	//////////////////////////////////////////////////////////////////
	// from
	//////////////////////////////////////////////////////////////////
	{
        std::vector<int> xs = { 1, 2, 3, 4, 5 };
		int sum = 0;
		for (auto x : from(xs.begin(), xs.end()))
		{
			sum += x;
		}
		assert(sum == 15);
	}
	{
        std::vector<int> xs = { 1, 2, 3, 4, 5 };
		int sum = 0;
		for (auto x : from(xs))
		{
			sum += x;
		}
		assert(sum == 15);
	}
	{
		int xs[] = { 1, 2, 3, 4, 5 };
		int sum = 0;
		for (auto x : from(from(from(xs))))
		{
			sum += x;
		}
		assert(sum == 15);
	}
	//////////////////////////////////////////////////////////////////
	// select
	//////////////////////////////////////////////////////////////////
	{
		int xs[] = { 1, 2, 3, 4, 5 };
		assert(from(xs).select([](int x){return x * 2; }).sequence_equal({ 2, 4, 6, 8, 10 }));
	}
	//////////////////////////////////////////////////////////////////
	// hide type test
	//////////////////////////////////////////////////////////////////
	{
		//int xs[] = { 1, 2, 3, 4, 5 };
		//linq<int> hidden = from(xs).select([](int x){return x * 2; });
		//assert(hidden.sequence_equal({ 2, 4, 6, 8, 10 }));
	}
	//////////////////////////////////////////////////////////////////
	// where
	//////////////////////////////////////////////////////////////////
	{
		int xs[] = { 1, 2, 3, 4, 5 };
		assert(from(xs).where([](int x){return x % 2 == 0; }).sequence_equal({ 2, 4 }));
	}
	//////////////////////////////////////////////////////////////////
	// iterating
	//////////////////////////////////////////////////////////////////
	{
        std::vector<int> empty;
		int xs[] = { 1, 2, 3, 4, 5 };
		int ys[] = { 1, 2, 3 };
		int zs[] = { 4, 5 };
		assert(from(xs).take(3).sequence_equal(ys));
		assert(from(xs).skip(3).sequence_equal(zs));
		assert(from(xs).take_while([](int a){return a != 4; }).sequence_equal(ys));
		assert(from(xs).skip_while([](int a){return a != 4; }).sequence_equal(zs));
		assert(from(xs).take(0).sequence_equal(empty));
		assert(from(xs).skip(5).sequence_equal(empty));
		assert(from(ys).concat(from(zs)).sequence_equal(xs));
		assert(from(xs).concat(from(empty)).sequence_equal(xs));
		assert(from(empty).concat(from(xs)).sequence_equal(xs));
		assert(from(empty).concat(from(empty)).sequence_equal(empty));
		assert(from(ys).concat(zs).sequence_equal(xs));
		assert(from(xs).concat(empty).sequence_equal(xs));
		assert(from(empty).concat(xs).sequence_equal(xs));
		assert(from(empty).concat(empty).sequence_equal(empty));
	}
	//////////////////////////////////////////////////////////////////
	// counting
	//////////////////////////////////////////////////////////////////
	{
		int a[] = { 1, 2, 3, 4, 5 };
        std::vector<int> b = { 1, 2, 3, 4, 5 };
        std::vector<int> c;
		int d[] = { 1, 2, 3, 4 };
		int e[] = { 1, 2, 3, 4, 5, 6 };
		int f[] = { 6, 7, 8, 9, 10 };
		int g[] = { 0 };
		//linq<int> xs[] = { from(b), from(c), from(d), from(e), from(f) };

		//assert(from(a).sequence_equal(b));
		//for (auto& x : xs)
		//{
			//for (auto& y : xs)
			//{
				//assert(x.sequence_equal(y) == (&x == &y));
			//}
		//}

		assert(from(a).contains(1));
		assert(from(a).contains(5));
		assert(!from(a).contains(6));
		assert(!from(c).contains(6));

		assert(from(a).count() == 5);
		assert(from(c).count() == 0);

		assert(from(a).default_if_empty(0).sequence_equal(b));
		assert(from(c).default_if_empty(0).sequence_equal(g));

		assert(from(a).element_at(0) == 1);
		assert(from(a).element_at(4) == 5);
		try{ from(a).element_at(-1); assert(false); }
		catch (const linq_exception&){}
		try{ from(a).element_at(6); assert(false); }
		catch (const linq_exception&){}
		try{ from(c).element_at(0); assert(false); }
		catch (const linq_exception&){}

		assert(!from(a).empty());
		assert(from(c).empty());

		assert(from(a).first() == 1);
		assert(from(a).first_or_default() == 1);
		assert(from(a).last() == 5);
		assert(from(a).last_or_default() == 5);
		assert(from(c).first_or_default() == 0);
		assert(from(c).last_or_default() == 0);
		try{ from(c).first(); assert(false); }
		catch (const linq_exception&){}
		try{ from(c).last(); assert(false); }
		catch (const linq_exception&){}

		assert(from(c).single_or_default() == 0);
		assert(from(g).single() == 0);
		try{ from(a).single(); assert(false); }
		catch (const linq_exception&){}
		try{ from(a).single_or_default(); assert(false); }
		catch (const linq_exception&){}
		try{ from(c).single(); assert(false); }
		catch (const linq_exception&){}
	}
	//////////////////////////////////////////////////////////////////
	// containers
	//////////////////////////////////////////////////////////////////
	{
		int xs[] = { 1, 2, 3, 4, 5 };
		assert(from(xs).sequence_equal(from(xs).to_vector()));
		assert(from(xs).sequence_equal(from(xs).to_list()));
		assert(from(xs).sequence_equal(from(xs).to_set()));

		auto f = [](int x){return x; };
		assert(from(xs).sequence_equal(from(from(xs).to_map(f, f)).select([](std::pair<int, int> p){return p.first; })));
		assert(from(xs).sequence_equal(from(from(xs).to_map(f, f)).select([](std::pair<int, int> p){return p.second; })));
	}
	//////////////////////////////////////////////////////////////////
	// aggregating
	//////////////////////////////////////////////////////////////////
	{
		int xs[] = { 1, 2, 3, 4, 5 };
		assert(from(xs).aggregate([](int a, int b){return a + b; }) == 15);
		assert(from(xs).aggregate(0, [](int a, int b){return a + b; }) == 15);
		assert(from(xs).sum() == 15);
		assert(from(xs).aggregate([](int a, int b){return a * b; }) == 120);
		assert(from(xs).aggregate(1, [](int a, int b){return a * b; }) == 120);
		assert(from(xs).all([](int a){return a > 1; }) == false);
		assert(from(xs).all([](int a){return a > 0; }) == true);
		assert(from(xs).any([](int a){return a > 1; }) == true);
		assert(from(xs).any([](int a){return a > 0; }) == true);
		assert(from(xs).min() == 1);
		assert(from(xs).max() == 5);
		assert(from(xs).average() == 3);

        std::vector<int> ys;
		try{ from(ys).min(); assert(false); }
		catch (const linq_exception&){}
		try{ from(ys).max(); assert(false); }
		catch (const linq_exception&){}
		try{ from(ys).average(); assert(false); }
		catch (const linq_exception&){}
	}
	//////////////////////////////////////////////////////////////////
	// set
	//////////////////////////////////////////////////////////////////
	{
		int xs[] = { 1, 1, 2, 2, 3, 3 };
		int ys[] = { 2, 2, 3, 3, 4, 4 };
		assert(from(xs).distinct().sequence_equal({ 1, 2, 3 }));
		assert(from(ys).distinct().sequence_equal({ 2, 3, 4 }));
		//assert(from(xs).except_with(ys).sequence_equal({ 1 }));
		//assert(from(xs).intersect_with(ys).sequence_equal({ 2, 3 }));
		//assert(from(xs).union_with(ys).sequence_equal({ 1, 2, 3, 4 }));
	}
	//////////////////////////////////////////////////////////////////
	// restructuring
	//////////////////////////////////////////////////////////////////
	{
		int xs[] = { 1, 2, 3, 4, 5 };
		int ys[] = { 6, 7, 8, 9, 10 };

		//zip_pair<int, int> zs[] = { { 1, 6 }, { 2, 7 }, { 3, 8 }, { 4, 9 }, { 5, 10 } };
		//assert(from(xs).zip_with(ys).sequence_equal(zs));

		//auto g = from(xs).group_by([](int x){return x % 2; });
		//assert(g.select([](zip_pair<int, linq<int>> p){return p.first; }).sequence_equal({ 0, 1 }));
		//assert(g.first().second.sequence_equal({ 2, 4 }));
		//assert(g.last().second.sequence_equal({ 1, 3, 5 }));

		//assert(
			//from_values({ 1, 2, 3 })
			//.select_many([](int x){return from_values({ x, x*x, x*x*x }); })
			//.sequence_equal({ 1, 1, 1, 2, 4, 8, 3, 9, 27 })
			//);
	}
	//////////////////////////////////////////////////////////////////
	// ordering
	//////////////////////////////////////////////////////////////////
	{
		//int xs[] = { 7, 1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10 };
		//int ys[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
		//int zs[] = { 10, 1, 11, 2, 12, 3, 13, 4, 5, 6, 7, 8, 9 };

		//assert(from(xs).order_by([](int x){return x; }).sequence_equal(ys));
		//assert(
			//flatten(
				//from(xs)
				//.first_order_by([](int x){return x % 10; })
				//.then_order_by([](int x){return x / 10; })
				//)
			//.sequence_equal(zs)
			//);
	}
	//////////////////////////////////////////////////////////////////
	// joining
	//////////////////////////////////////////////////////////////////
	{
        //person magnus = { "Hedlund, Magnus" };
        //person terry = { "Adams, Terry" };
        //person charlotte = { "Weiss, Charlotte" };
        //person persons[] = { magnus, terry, charlotte };

        //pet barley = { "Barley", terry };
        //pet boots = { "Boots", terry };
        //pet whiskers = { "Whiskers", charlotte };
        //pet daisy = { "Daisy", magnus };
        //pet pets[] = { barley, boots, whiskers, daisy };

        //auto person_name = [](const person& p){return p.name; };
        //auto pet_name = [](const pet& p){return p.name; };
        //auto pet_owner_name = [](const pet& p){return p.owner.name; };

        //auto f = from(persons).full_join(from(pets), person_name, pet_owner_name);
        //{
            //typedef join_pair<string, linq<person>, linq<pet>> TItem;
            //auto xs = f.to_vector();
            //assert(from(xs).select([](const TItem& item){return item.first; }).sequence_equal({ terry.name, magnus.name, charlotte.name }));
            //assert(xs[0].second.first.select(person_name).sequence_equal({ terry.name }));
            //assert(xs[1].second.first.select(person_name).sequence_equal({ magnus.name }));
            //assert(xs[2].second.first.select(person_name).sequence_equal({ charlotte.name }));
            //assert(xs[0].second.second.select(pet_name).sequence_equal({ barley.name, boots.name }));
            //assert(xs[1].second.second.select(pet_name).sequence_equal({ daisy.name }));
            //assert(xs[2].second.second.select(pet_name).sequence_equal({ whiskers.name }));
        //}
        //auto g = from(persons).group_join(from(pets), person_name, pet_owner_name);
        //{
            //typedef join_pair<string, person, linq<pet>> TItem;
            //auto xs = g.to_vector();
            //assert(from(xs).select([](const TItem& item){return item.first; }).sequence_equal({ terry.name, magnus.name, charlotte.name }));
            //assert(xs[0].second.first.name == terry.name);
            //assert(xs[1].second.first.name == magnus.name);
            //assert(xs[2].second.first.name == charlotte.name);
            //assert(xs[0].second.second.select(pet_name).sequence_equal({ barley.name, boots.name }));
            //assert(xs[1].second.second.select(pet_name).sequence_equal({ daisy.name }));
            //assert(xs[2].second.second.select(pet_name).sequence_equal({ whiskers.name }));
        //}
        //auto j = from(persons).join(from(pets), person_name, pet_owner_name);
        //{
            //typedef join_pair<string, person, pet> TItem;
            //auto xs = j.to_vector();
            //assert(from(xs).select([](const TItem& item){return item.first; }).sequence_equal({ terry.name, terry.name, magnus.name, charlotte.name }));
            //assert(xs[0].second.first.name == terry.name);
            //assert(xs[1].second.first.name == terry.name);
            //assert(xs[2].second.first.name == magnus.name);
            //assert(xs[3].second.first.name == charlotte.name);
            //assert(xs[0].second.second.name == barley.name);
            //assert(xs[1].second.second.name == boots.name);
            //assert(xs[2].second.second.name == daisy.name);
            //assert(xs[3].second.second.name == whiskers.name);
        }

}

int main()
{
    test();
    {
        // calculate sum of squares of odd numbers
        int xs[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int sum = from(xs)
            .where([](int x){return x % 2 == 1; })
            .select([](int x){return x * x; })
            .sum();
        std::cout << sum << std::endl;
        assert(sum == 165);
    }

    {
        // iterate of squares of odd numbers ordered by the last digit
        std::vector<int> xs = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        for (auto x : from(xs)
                .where([](int x){return x % 2 == 1; })
                .select([](int x){return x * x; })
            )
        {
            std::cout << x << " ";
        }
        // prints 1 81 25 9 49
    }

    {
        std::vector<PetOwner> vp{ PetOwner("higa", std::vector<std::string>{std::string("scruffy"), std::string("sam")}, std::vector<int>{10,20,30}), PetOwner("ronen", std::vector<std::string>{std::string("walker"), std::string("sugar")}, std::vector<int>{40,50,60}) };
        auto xs = from(vp).select_many([](PetOwner i) {return i.pets_; });
        for (auto ele : xs)
        {
            std::cout << ele << std::endl;
        }
        std::vector<std::string> result {"scruffy", "sam", "walker", "sugar"};
        assert(xs.to_vector() == result);
    }

#ifdef _MSC_VER
    _CrtDumpMemoryLeaks();
#endif
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkGradientShader.h"
#include "SkTypeface.h"

static SkShader* make_heatGradient(const SkPoint pts[2]) {
    const SkColor colors[] = {
        SK_ColorBLACK, SK_ColorBLUE, SK_ColorCYAN, SK_ColorGREEN,
        SK_ColorYELLOW, SK_ColorRED, SK_ColorWHITE
    };
    const SkColor bw[] = { SK_ColorBLACK, SK_ColorWHITE };

    return SkGradientShader::CreateLinear(pts, bw, NULL,
                                          SK_ARRAY_COUNT(bw),
                                          SkShader::kClamp_TileMode);
}

static bool setFont(SkPaint* paint, const char name[]) {
    SkTypeface* tf = SkTypeface::CreateFromName(name, SkTypeface::kNormal);
    if (tf) {
        paint->setTypeface(tf)->unref();
        return true;
    }
    return false;
}

#ifdef SK_BUILD_FOR_MAC
#import <ApplicationServices/ApplicationServices.h>
#define BITMAP_INFO_RGB     (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host)

static CGContextRef makeCG(const SkBitmap& bm) {
    if (SkBitmap::kARGB_8888_Config != bm.config() ||
        NULL == bm.getPixels()) {
        return NULL;
    }
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGContextRef cg = CGBitmapContextCreate(bm.getPixels(), bm.width(), bm.height(),
                                            8, bm.rowBytes(), space, BITMAP_INFO_RGB);
    CFRelease(space);

    CGContextSetAllowsFontSubpixelQuantization(cg, false);
    CGContextSetShouldSubpixelQuantizeFonts(cg, false);

    return cg;
}

extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face);

static CGFontRef typefaceToCGFont(const SkTypeface* face) {
    if (NULL == face) {
        return 0;
    }

    CTFontRef ct = SkTypeface_GetCTFontRef(face);
    return CTFontCopyGraphicsFont(ct, NULL);
}

static void cgSetPaintForText(CGContextRef cg, const SkPaint& paint) {
    SkColor c = paint.getColor();
    CGFloat rgba[] = {
        SkColorGetB(c) / 255.0,
        SkColorGetG(c) / 255.0,
        SkColorGetR(c) / 255.0,
        SkColorGetA(c) / 255.0,
    };
    CGContextSetRGBFillColor(cg, rgba[0], rgba[1], rgba[2], rgba[3]);

    CGContextSetTextDrawingMode(cg, kCGTextFill);
    CGContextSetFont(cg, typefaceToCGFont(paint.getTypeface()));
    CGContextSetFontSize(cg, SkScalarToFloat(paint.getTextSize()));

    CGContextSetAllowsFontSubpixelPositioning(cg, paint.isSubpixelText());
    CGContextSetShouldSubpixelPositionFonts(cg, paint.isSubpixelText());

    CGContextSetShouldAntialias(cg, paint.isAntiAlias());
    CGContextSetShouldSmoothFonts(cg, paint.isLCDRenderText());
}

static void cgDrawText(CGContextRef cg, const void* text, size_t len,
                       float x, float y, const SkPaint& paint) {
    if (cg) {
        cgSetPaintForText(cg, paint);

        uint16_t glyphs[200];
        int count = paint.textToGlyphs(text, len, glyphs);

        CGContextShowGlyphsAtPoint(cg, x, y, glyphs, count);
    }
}
#endif

namespace skiagm {

/**
   Test a set of clipping problems discovered while writing blitAntiRect,
   and test all the code paths through the clipping blitters.
   Each region should show as a blue center surrounded by a 2px green
   border, with no red.
*/

#define HEIGHT 480

class GammaTextGM : public GM {
public:
    GammaTextGM() {

    }

protected:
    virtual SkString onShortName() {
        return SkString("gammatext");
    }

    virtual SkISize onISize() {
        return make_isize(1024, HEIGHT);
    }

    static void drawGrad(SkCanvas* canvas) {
        SkPoint pts[] = { { 0, 0 }, { 0, SkIntToScalar(HEIGHT) } };
#if 0
        const SkColor colors[] = { SK_ColorBLACK, SK_ColorWHITE };
        SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode);
#else
        SkShader* s = make_heatGradient(pts);
#endif

        canvas->clear(SK_ColorRED);
        SkPaint paint;
        paint.setShader(s)->unref();
        SkRect r = { 0, 0, SkIntToScalar(1024), SkIntToScalar(HEIGHT) };
        canvas->drawRect(r, paint);
    }

    virtual void onDraw(SkCanvas* canvas) {
#ifdef SK_BUILD_FOR_MAC
        CGContextRef cg = makeCG(canvas->getDevice()->accessBitmap(false));
#endif

        drawGrad(canvas);

        const SkColor fg[] = {
            0xFFFFFFFF,
            0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
            0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
            0xFF000000,
        };

        const char* text = "Hamburgefons";
        size_t len = strlen(text);

        SkPaint paint;
        setFont(&paint, "Times");
        paint.setTextSize(SkIntToScalar(16));
        paint.setAntiAlias(true);
        paint.setLCDRenderText(true);

        SkScalar x = SkIntToScalar(10);
        for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
            paint.setColor(fg[i]);

            SkScalar y = SkIntToScalar(40);
            SkScalar stopy = SkIntToScalar(HEIGHT);
            while (y < stopy) {
#if 1
                canvas->drawText(text, len, x, y, paint);
#else
                cgDrawText(cg, text, len, x, SkIntToScalar(HEIGHT) - y, paint);
#endif
                y += paint.getTextSize() * 2;
            }
            x += SkIntToScalar(1024) / SK_ARRAY_COUNT(fg);
        }
    }

private:
    typedef GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new GammaTextGM; }
static GMRegistry reg(MyFactory);

}
<commit_msg>Fix some float/scalar/int confusion.<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkGradientShader.h"
#include "SkTypeface.h"

static SkShader* make_heatGradient(const SkPoint pts[2]) {
    const SkColor colors[] = {
        SK_ColorBLACK, SK_ColorBLUE, SK_ColorCYAN, SK_ColorGREEN,
        SK_ColorYELLOW, SK_ColorRED, SK_ColorWHITE
    };
    const SkColor bw[] = { SK_ColorBLACK, SK_ColorWHITE };

    return SkGradientShader::CreateLinear(pts, bw, NULL,
                                          SK_ARRAY_COUNT(bw),
                                          SkShader::kClamp_TileMode);
}

static bool setFont(SkPaint* paint, const char name[]) {
    SkTypeface* tf = SkTypeface::CreateFromName(name, SkTypeface::kNormal);
    if (tf) {
        paint->setTypeface(tf)->unref();
        return true;
    }
    return false;
}

#ifdef SK_BUILD_FOR_MAC
#import <ApplicationServices/ApplicationServices.h>
#define BITMAP_INFO_RGB     (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host)

static CGContextRef makeCG(const SkBitmap& bm) {
    if (SkBitmap::kARGB_8888_Config != bm.config() ||
        NULL == bm.getPixels()) {
        return NULL;
    }
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGContextRef cg = CGBitmapContextCreate(bm.getPixels(), bm.width(), bm.height(),
                                            8, bm.rowBytes(), space, BITMAP_INFO_RGB);
    CFRelease(space);

    CGContextSetAllowsFontSubpixelQuantization(cg, false);
    CGContextSetShouldSubpixelQuantizeFonts(cg, false);

    return cg;
}

extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face);

static CGFontRef typefaceToCGFont(const SkTypeface* face) {
    if (NULL == face) {
        return 0;
    }

    CTFontRef ct = SkTypeface_GetCTFontRef(face);
    return CTFontCopyGraphicsFont(ct, NULL);
}

static void cgSetPaintForText(CGContextRef cg, const SkPaint& paint) {
    SkColor c = paint.getColor();
    CGFloat rgba[] = {
        SkColorGetB(c) / 255.0,
        SkColorGetG(c) / 255.0,
        SkColorGetR(c) / 255.0,
        SkColorGetA(c) / 255.0,
    };
    CGContextSetRGBFillColor(cg, rgba[0], rgba[1], rgba[2], rgba[3]);

    CGContextSetTextDrawingMode(cg, kCGTextFill);
    CGContextSetFont(cg, typefaceToCGFont(paint.getTypeface()));
    CGContextSetFontSize(cg, SkScalarToFloat(paint.getTextSize()));

    CGContextSetAllowsFontSubpixelPositioning(cg, paint.isSubpixelText());
    CGContextSetShouldSubpixelPositionFonts(cg, paint.isSubpixelText());

    CGContextSetShouldAntialias(cg, paint.isAntiAlias());
    CGContextSetShouldSmoothFonts(cg, paint.isLCDRenderText());
}

static void cgDrawText(CGContextRef cg, const void* text, size_t len,
                       float x, float y, const SkPaint& paint) {
    if (cg) {
        cgSetPaintForText(cg, paint);

        uint16_t glyphs[200];
        int count = paint.textToGlyphs(text, len, glyphs);

        CGContextShowGlyphsAtPoint(cg, x, y, glyphs, count);
    }
}
#endif

namespace skiagm {

/**
   Test a set of clipping problems discovered while writing blitAntiRect,
   and test all the code paths through the clipping blitters.
   Each region should show as a blue center surrounded by a 2px green
   border, with no red.
*/

#define HEIGHT 480

class GammaTextGM : public GM {
public:
    GammaTextGM() {

    }

protected:
    virtual SkString onShortName() {
        return SkString("gammatext");
    }

    virtual SkISize onISize() {
        return make_isize(1024, HEIGHT);
    }

    static void drawGrad(SkCanvas* canvas) {
        SkPoint pts[] = { { 0, 0 }, { 0, SkIntToScalar(HEIGHT) } };
#if 0
        const SkColor colors[] = { SK_ColorBLACK, SK_ColorWHITE };
        SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode);
#else
        SkShader* s = make_heatGradient(pts);
#endif

        canvas->clear(SK_ColorRED);
        SkPaint paint;
        paint.setShader(s)->unref();
        SkRect r = { 0, 0, SkIntToScalar(1024), SkIntToScalar(HEIGHT) };
        canvas->drawRect(r, paint);
    }

    virtual void onDraw(SkCanvas* canvas) {
#ifdef SK_BUILD_FOR_MAC
        CGContextRef cg = makeCG(canvas->getDevice()->accessBitmap(false));
#endif

        drawGrad(canvas);

        const SkColor fg[] = {
            0xFFFFFFFF,
            0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
            0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
            0xFF000000,
        };

        const char* text = "Hamburgefons";
        size_t len = strlen(text);

        SkPaint paint;
        setFont(&paint, "Times");
        paint.setTextSize(SkIntToScalar(16));
        paint.setAntiAlias(true);
        paint.setLCDRenderText(true);

        SkScalar x = SkIntToScalar(10);
        for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
            paint.setColor(fg[i]);

            SkScalar y = SkIntToScalar(40);
            SkScalar stopy = SkIntToScalar(HEIGHT);
            while (y < stopy) {
#if 1
                canvas->drawText(text, len, x, y, paint);
#else
                cgDrawText(cg, text, len, SkScalarToFloat(x),
                           static_cast<float>(HEIGHT) - SkScalarToFloat(y),
                           paint);
#endif
                y += paint.getTextSize() * 2;
            }
            x += SkIntToScalar(1024) / SK_ARRAY_COUNT(fg);
        }
    }

private:
    typedef GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new GammaTextGM; }
static GMRegistry reg(MyFactory);

}
<|endoftext|>