repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
ljnferreira/TP1ED1-2021
|
relatorios.h
|
<filename>relatorios.h<gh_stars>0
#ifndef _RELATORIOS_H_
#define _RELATORIOS_H_
void relatorioDadosNF();
void relatorioDadosCompra();
void relatorioDadosCompraPorData();
void relatorioVendasVendedorDia();
void relatorioVendasVendedorMes();
void relatorioMelhoresVendedoresMes();
void relatorioMelhoresVendedoresIntervaloDatas();
void relatorioHistoricoValorProduto();
#endif
|
ljnferreira/TP1ED1-2021
|
utils.h
|
<reponame>ljnferreira/TP1ED1-2021
#ifndef _UTILS_H_
#define _UTILS_H_
//Funções de validação
int validaCPF(char *cpf);
int validaCNPJ(char *cnpj);
int validaData(char *data);
int validaEmail(char *email);
void retiraEnter(char *string);
int campovazio(char *nome);
void padronizaString(char *texto);
void getSystemDate(char date[11]);
#endif
|
ljnferreira/TP1ED1-2021
|
crud.c
|
<reponame>ljnferreira/TP1ED1-2021
#include <bits/types/FILE.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "crud.h"
#include "dataTypes.h"
#include "memoryManagement.h"
#include "userInteraction.h"
#include "utils.h"
#include "files.h"
void cadastrarCliente(){
FILE *clientes;
Cliente cliente;
int opcao = 1;
clientes = abrirArquivo(CLIENTE);
if(clientes){
do {
cliente.id = getNewUniqueId(clientes, sizeof(Cliente));
do {
printf("Digite o nome do cliente: ");
setbuf(stdin, NULL);
fgets(cliente.nome, 100, stdin);
setbuf(stdin, NULL);
padronizaString(cliente.nome);
}while (!campovazio(cliente.nome));
do {
printf("Digite o email do cliente: ");
setbuf(stdin, NULL);
fgets(cliente.email, 50, stdin);
setbuf(stdin, NULL);
if(!validaEmail(cliente.email)){
printf("Email inválido!\n\n");
}
}while (!campovazio(cliente.email) || !validaEmail(cliente.email));
do {
printf("Digite o CPF do cliente: ");
setbuf(stdin, NULL);
fgets(cliente.cpf, 12, stdin);
setbuf(stdin, NULL);
if(!validaCPF(cliente.cpf)){
printf("CPF inválido!\n\n");
}
}while (!campovazio(cliente.cpf) || !validaCPF(cliente.cpf) ||
(findClienteByCPF(clientes, cliente.cpf) != -1));
do {
printf("Digite o telefone (formato: (xx)xxxxx-xxxx ) do cliente: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(cliente.telefone, 15, stdin);
setbuf(stdin, NULL);
}while (!campovazio(cliente.telefone));
gravarRegistroFinalArquivo(&cliente, clientes, sizeof(Cliente));
printf("Digite 0 para sair ou 1 para cadastrar um novo cliente: ");
scanf("%d", &opcao);
}while (opcao != 0);
fecharArquivo(clientes);
}else{
printf("Não foi possível acessar a Base de dados, não sera possivel efetuar cadastro no momento");
}
}
void consultarCliente(){
FILE *clientes;
Cliente cliente;
int tamanho = 0, *vetor, posicao, opcao;
unsigned long id;
char cpf[12], prefixo[100];
clientes = abrirArquivo(CLIENTE);
if (clientes) {
limparTela();
do {
printf("Escolha uma opção de acordo com o menu abaixo:\n");
printf("1 - Consulta por CPF\n");
printf("2 - Consulta por ID\n");
printf("3 - Consulta por prefixo do nome\n");
printf("0 - Sair\n");
scanf("%d", &opcao);
switch (opcao) {
case 1:
printf("Digite o CPF do cliente: ");
setbuf(stdin, NULL);
fgets(cpf, 12, stdin);
setbuf(stdin, NULL);
if(validaCPF(cpf)){
posicao = findClienteByCPF(clientes, cpf);
}else{
printf("CPF Invalido!\n");
}
break;
case 2:
printf("Digite o Id do cliente: ");
scanf("%ld", &id);
posicao = findClienteById(clientes, id);
break;
case 3:
printf("Digite o prefixo do nome do cliente: ");
setbuf(stdin, NULL);
fgets(prefixo, 100, stdin);
setbuf(stdin, NULL);
retiraEnter(prefixo);
padronizaString(prefixo);
vetor = findClientesByName(clientes, prefixo, &tamanho);
if(tamanho){
for (int i = 0; i < tamanho; i++) {
lerRegistroEmArquivo(&cliente, clientes, vetor[i], sizeof(Cliente));
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
cliente.id, cliente.nome, cliente.telefone, cliente.email, cliente.cpf);
}
}
break;
}
if(posicao != -1 && opcao !=3){
lerRegistroEmArquivo(&cliente, clientes, posicao, sizeof(Cliente));
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
cliente.id, cliente.nome, cliente.telefone, cliente.email, cliente.cpf);
}
}while (opcao != 0);
fecharArquivo(clientes);
}else{
printf("\nNão foi possivel acessar a base de dados!\n");
}
}
void alterarCliente(){
FILE *clientes;
Cliente cliente;
unsigned long id;
int posicao, opcao;
clientes = abrirArquivo(CLIENTE);
if (clientes) {
limparTela();
printf("\nDigite o ID do cliente que deseja alterar: ");
scanf("%ld", &id);
posicao = findClienteById(clientes, id);
if(posicao != -1){
lerRegistroEmArquivo(&cliente, clientes, posicao, sizeof(Cliente));
printf("Deseja alterar o nome de %s? \n1 - Sim 2 - Não: ", cliente.nome);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo nome do cliente: ");
setbuf(stdin, NULL);
fgets(cliente.nome, 100, stdin);
setbuf(stdin, NULL);
padronizaString(cliente.nome);
}while (!campovazio(cliente.nome));
}
printf("Deseja alterar o CPF (%s)? \n1 - Sim 2 - Não: ", cliente.cpf);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o CPF do cliente: ");
setbuf(stdin, NULL);
fgets(cliente.cpf, 12, stdin);
setbuf(stdin, NULL);
if(!validaCPF(cliente.cpf)){
printf("CPF inválido!\n\n");
}
}while (!campovazio(cliente.cpf) || !validaCPF(cliente.cpf) ||
(findClienteByCPF(clientes, cliente.cpf) != -1));
}
printf("Deseja alterar o email (%s)? \n1 - Sim 2 - Não: ", cliente.email);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo email do cliente: ");
setbuf(stdin, NULL);
fgets(cliente.email, 50, stdin);
setbuf(stdin, NULL);
if(!validaEmail(cliente.email)){
printf("Email inválido!\n\n");
}
}while (!campovazio(cliente.email) || !validaEmail(cliente.email));
}
printf("Deseja alterar o telefone (%s)? \n1 - Sim 2 - Não: ", cliente.telefone);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo telefone (formato: (xx)xxxxx-xxxx ) do cliente: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(cliente.telefone, 15, stdin);
setbuf(stdin, NULL);
}while (!campovazio(cliente.telefone));
}
printf("Novos dados do cliente: \nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
cliente.id, cliente.nome, cliente.telefone, cliente.email, cliente.cpf);
gravarRegistroEmArquivo(&cliente, clientes, posicao, sizeof(Cliente));
}else{
printf("\nRegistro não encontrado!!!\n");
}
fecharArquivo(clientes);
}else{
printf("\nNão foi possivel acessar a base de dados!\n");
}
}
void listarClientes(){
FILE *clientes;
Cliente cliente;
clientes = abrirArquivo(CLIENTE);
limparTela();
printf("Listagem de clientes: \n");
fseek(clientes, 0, SEEK_SET);
while (fread(&cliente, sizeof(Cliente), 1, clientes)) {
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
cliente.id, cliente.nome, cliente.telefone, cliente.email, cliente.cpf);
}
fecharArquivo(clientes);
pause();
}
void cadastrarVendedor(){
FILE *vendedores;
Vendedor vendedor;
int opcao = 1, cadastrado = 0, invalido = 0;
vendedores = abrirArquivo(VENDEDOR);
if(vendedores){
do {
vendedor.id = getNewUniqueId(vendedores, sizeof(Vendedor));
do {
printf("Digite o nome do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.nome, 100, stdin);
setbuf(stdin, NULL);
padronizaString(vendedor.nome);
}while (!campovazio(vendedor.nome));
do {
printf("Digite o email do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.email, 50, stdin);
setbuf(stdin, NULL);
if(!validaEmail(vendedor.email)){
printf("Email inválido!\n\n");
invalido = 1;
}
if(isEmailCadastradoVendedor(vendedores, vendedor.email)){
printf("Email já cadastrado para outro vendedor!\n\n");
cadastrado = 1;
}
}while (!campovazio(vendedor.email) || invalido || cadastrado);
do {
printf("Digite o CPF do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.cpf, 12, stdin);
setbuf(stdin, NULL);
if(!validaCPF(vendedor.cpf)){
printf("CPF inválido!\n\n");
}
}while (!campovazio(vendedor.cpf) || !validaCPF(vendedor.cpf) ||
(findVendedorByCPF(vendedores, vendedor.cpf)!= -1));
do {
printf("Digite o telefone (formato: (xx)xxxxx-xxxx ) do vendedor: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(vendedor.telefone, 15, stdin);
setbuf(stdin, NULL);
}while (!campovazio(vendedor.telefone));
do {
printf("Digite a nova senha do vendedor: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(vendedor.password, 20, stdin);
setbuf(stdin, NULL);
}while (!campovazio(vendedor.password));
gravarRegistroFinalArquivo(&vendedor, vendedores, sizeof(Vendedor));
printf("Digite 0 para sair ou 1 para cadastrar um novo vendedor: ");
scanf("%d", &opcao);
}while (opcao != 0);
fecharArquivo(vendedores);
}else{
printf("Não foi possível acessar a Base de dados, não sera possivel efetuar cadastro no momento");
}
}
void alterarVendedor(){
FILE *vendedores;
Vendedor vendedor;
unsigned long id;
int posicao, opcao;
vendedores = abrirArquivo(VENDEDOR);
if (vendedores) {
limparTela();
printf("\nDigite o ID do vendedor que deseja alterar: ");
scanf("%ld", &id);
posicao = findVendedorById(vendedores, id);
printf("posicao: %ld", id);
if(posicao != -1){
lerRegistroEmArquivo(&vendedor, vendedores, posicao, sizeof(Vendedor));
printf("Deseja alterar o nome de %s? \n1 - Sim 2 - Não: ", vendedor.nome);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo nome do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.nome, 100, stdin);
setbuf(stdin, NULL);
padronizaString(vendedor.nome);
}while (!campovazio(vendedor.nome));
}
printf("Deseja alterar o CPF (%s)? \n1 - Sim 2 - Não: ", vendedor.cpf);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o CPF do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.cpf, 12, stdin);
setbuf(stdin, NULL);
if(!validaCPF(vendedor.cpf)){
printf("CPF inválido!\n\n");
}
}while (!campovazio(vendedor.cpf) || !validaCPF(vendedor.cpf) ||
(findVendedorByCPF(vendedores, vendedor.cpf) != -1));
}
printf("Deseja alterar o email (%s)? \n1 - Sim 2 - Não: ", vendedor.email);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo email do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.email, 50, stdin);
setbuf(stdin, NULL);
if(!validaEmail(vendedor.email)){
printf("Email inválido!\n\n");
}
}while (!campovazio(vendedor.email) || !validaEmail(vendedor.email));
}
printf("Deseja alterar o telefone (%s)? \n1 - Sim 2 - Não: ", vendedor.telefone);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo telefone (formato: (xx)xxxxx-xxxx ) do vendedor: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(vendedor.telefone, 15, stdin);
setbuf(stdin, NULL);
}while (!campovazio(vendedor.telefone));
}
printf("Deseja alterar a senha do vendedor? \n1 - Sim 2 - Não: ");
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite a nova senha do vendedor: ");
setbuf(stdin, NULL);
fgets(vendedor.password, 20, stdin);
setbuf(stdin, NULL);
}while (!campovazio(vendedor.password));
}
printf("Novos dados do vendedor: \nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
vendedor.id, vendedor.nome, vendedor.telefone, vendedor.email, vendedor.cpf);
gravarRegistroEmArquivo(&vendedor, vendedores, posicao, sizeof(Vendedor));
fecharArquivo(vendedores);
}else{
printf("\nRegistro não encontrado!!!\n");
}
}else{
printf("\nNão foi possivel acessar a base de dados!\n");
}
}
void consultarVendedor(){
FILE *vendedores;
Vendedor vendedor;
int tamanho = 0, *vetor, posicao, opcao;
unsigned long id;
char cpf[12], prefixo[100];
vendedores = abrirArquivo(VENDEDOR);
if (vendedores) {
limparTela();
do {
printf("Escolha uma opção de acordo com o menu abaixo:\n");
printf("1 - Consulta por CPF\n");
printf("2 - Consulta por ID\n");
printf("3 - Consulta por prefixo do nome\n");
printf("0 - Sair\n");
scanf("%d", &opcao);
switch (opcao) {
case 1:
printf("Digite o CPF do vendedor: ");
setbuf(stdin, NULL);
fgets(cpf, 12, stdin);
setbuf(stdin, NULL);
if(validaCPF(cpf)){
posicao = findVendedorByCPF(vendedores, cpf);
}else{
printf("CPF Invalido!\n");
}
break;
case 2:
printf("Digite o Id do vendedor: ");
scanf("%ld", &id);
posicao = findVendedorById(vendedores, id);
break;
case 3:
printf("Digite o prefixo do nome do vendedor: ");
setbuf(stdin, NULL);
fgets(prefixo, 100, stdin);
setbuf(stdin, NULL);
retiraEnter(prefixo);
padronizaString(prefixo);
vetor = findVendedoresByName(vendedores, prefixo, &tamanho);
if(tamanho){
for (int i = 0; i < tamanho; i++) {
lerRegistroEmArquivo(&vendedor, vendedores, vetor[i], sizeof(Vendedor));
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
vendedor.id, vendedor.nome, vendedor.telefone, vendedor.email, vendedor.cpf);
}
}
break;
}
if(posicao != -1 && opcao !=3){
lerRegistroEmArquivo(&vendedor, vendedores, posicao, sizeof(Vendedor));
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
vendedor.id, vendedor.nome, vendedor.telefone, vendedor.email, vendedor.cpf);
}
}while (opcao != 0);
fecharArquivo(vendedores);
}else{
printf("\nNão foi possivel acessar a base de dados!\n");
}
}
void listarVendedores(){
FILE *vendedores;
Vendedor vendedor;
vendedores = abrirArquivo(VENDEDOR);
limparTela();
printf("Listagem de vendedores: \n");
fseek(vendedores, 0, SEEK_SET);
while (fread(&vendedor, sizeof(Vendedor), 1, vendedores)) {
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
vendedor.id, vendedor.nome, vendedor.telefone, vendedor.email, vendedor.cpf);
}
fecharArquivo(vendedores);
pause();
}
void cadastrarFornecedor(){
FILE *fornecedores;
Fornecedor fornecedor;
int opcao = 1, cadastrado = 0, invalido = 0;
fornecedores = abrirArquivo(FORNECEDOR);
if(fornecedores){
do {
fornecedor.id = getNewUniqueId(fornecedores, sizeof(Vendedor));
do {
printf("Digite o nome do fornecedor: ");
setbuf(stdin, NULL);
fgets(fornecedor.nome, 100, stdin);
setbuf(stdin, NULL);
retiraEnter(fornecedor.nome);
padronizaString(fornecedor.nome);
cadastrado = isNomeFornecedorCadastrado(fornecedores, fornecedor.nome);
if(cadastrado){
printf("\nO nome já foi cadastrado para outro fornecedor!\n\n");
}
}while (!campovazio(fornecedor.nome) || cadastrado);
cadastrado = 0;
do {
printf("Digite o email do fornecedor: ");
setbuf(stdin, NULL);
fgets(fornecedor.email, 50, stdin);
setbuf(stdin, NULL);
if(!validaEmail(fornecedor.email)){
printf("Email inválido!\n\n");
invalido = 1;
}
if(isEmailCadastradoVendedor(fornecedores, fornecedor.email)){
printf("Email já cadastrado para outro fornecedor!\n\n");
cadastrado = 1;
}
}while (!campovazio(fornecedor.email) || invalido || cadastrado);
cadastrado = 0;
invalido = 0;
do {
printf("Digite o CNPJ do fornecedor: ");
setbuf(stdin, NULL);
fgets(fornecedor.CNPJ, 15, stdin);
setbuf(stdin, NULL);
if(!validaCNPJ(fornecedor.CNPJ)){
printf("CNPJ inválido!\n\n");
invalido = 1;
}
if(findFornecedorByCNPJ(fornecedores, fornecedor.CNPJ)!= -1){
printf("CNPJ Já cadastrado para outro Fornecedor!\n\n");
cadastrado = 1;
}
}while (!campovazio(fornecedor.CNPJ) || invalido || cadastrado);
do {
printf("Digite o telefone (formato: (xx)xxxxx-xxxx ) do fornecedor: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(fornecedor.telefone, 15, stdin);
setbuf(stdin, NULL);
}while (!campovazio(fornecedor.telefone));
gravarRegistroFinalArquivo(&fornecedor, fornecedores, sizeof(Fornecedor));
printf("Digite 0 para sair ou 1 para cadastrar um novo fornecedor: ");
scanf("%d", &opcao);
}while (opcao != 0);
fecharArquivo(fornecedores);
}else{
printf("Não foi possível acessar a Base de dados, não sera possivel efetuar cadastro no momento");
}
}
void alterarFornecedor(){
FILE *fornecedores;
Fornecedor fornecedor;
unsigned long id;
int posicao, opcao;
fornecedores = abrirArquivo(FORNECEDOR);
if (fornecedores) {
limparTela();
printf("\nDigite o ID do fornecedor que deseja alterar: ");
scanf("%ld", &id);
posicao = findFornecedorById(fornecedores, id);
if(posicao != -1){
lerRegistroEmArquivo(&fornecedor, fornecedores, posicao, sizeof(fornecedor));
printf("Deseja alterar o nome de %s? \n1 - Sim 2 - Não: ", fornecedor.nome);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo nome do fornecedor: ");
setbuf(stdin, NULL);
fgets(fornecedor.nome, 100, stdin);
setbuf(stdin, NULL);
retiraEnter(fornecedor.nome);
padronizaString(fornecedor.nome);
}while (!campovazio(fornecedor.nome) ||
isNomeFornecedorCadastrado(fornecedores, fornecedor.nome));
}
printf("Deseja alterar o CNPJ (%s)? \n1 - Sim 2 - Não: ", fornecedor.CNPJ);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o CNPJ do fornecedor: ");
setbuf(stdin, NULL);
fgets(fornecedor.CNPJ, 12, stdin);
setbuf(stdin, NULL);
if(!validaCNPJ(fornecedor.CNPJ)){
printf("CNPJ inválido!\n\n");
}
}while (!campovazio(fornecedor.CNPJ) || !validaCNPJ(fornecedor.CNPJ) ||
(findFornecedorByCNPJ(fornecedores, fornecedor.CNPJ) != -1));
}
printf("Deseja alterar o email (%s)? \n1 - Sim 2 - Não: ", fornecedor.email);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo email do fornecedor: ");
setbuf(stdin, NULL);
fgets(fornecedor.email, 50, stdin);
setbuf(stdin, NULL);
if(!validaEmail(fornecedor.email)){
printf("Email inválido!\n\n");
}
}while (!campovazio(fornecedor.email) || !validaEmail(fornecedor.email));
}
printf("Deseja alterar o telefone (%s)? \n1 - Sim 2 - Não: ", fornecedor.telefone);
scanf("%d", &opcao);
if(opcao == 1){
do {
printf("Digite o novo telefone (formato: (xx)xxxxx-xxxx ) do fornecedor: ");
setbuf(stdin, NULL);
setbuf(stdin, NULL);
fgets(fornecedor.telefone, 15, stdin);
setbuf(stdin, NULL);
}while (!campovazio(fornecedor.telefone));
}
printf("Novos dados do fornecedor: \nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCPF: %s\n\n",
fornecedor.id, fornecedor.nome, fornecedor.telefone, fornecedor.email, fornecedor.CNPJ);
gravarRegistroEmArquivo(&fornecedor, fornecedores, posicao, sizeof(Fornecedor));
}else{
printf("\nRegistro não encontrado!!!\n");
}
fecharArquivo(fornecedores);
}else{
printf("\nNão foi possivel acessar a base de dados!\n");
}
}
void consultarFornecedor(){
FILE *fornecedores;
Fornecedor fornecedor;
int tamanho = 0, *vetor, posicao, opcao;
unsigned long id;
char cnpj[15], prefixo[100];
fornecedores = abrirArquivo(FORNECEDOR);
if (fornecedores) {
limparTela();
do {
printf("Escolha uma opção de acordo com o menu abaixo:\n");
printf("1 - Consulta por CNPJ\n");
printf("2 - Consulta por ID\n");
printf("3 - Consulta por prefixo do nome\n");
printf("0 - Sair\n");
scanf("%d", &opcao);
switch (opcao) {
case 1:
printf("Digite o CNPJ do fornecedor: ");
setbuf(stdin, NULL);
fgets(cnpj, 15, stdin);
setbuf(stdin, NULL);
if(validaCNPJ(cnpj)){
posicao = findFornecedorByCNPJ(fornecedores, cnpj);
}else{
printf("CNPJ Invalido!\n");
}
break;
case 2:
printf("Digite o Id do fornecedor: ");
scanf("%ld", &id);
posicao = findFornecedorById(fornecedores, id);
break;
case 3:
printf("Digite o prefixo do nome do fornecedor: ");
setbuf(stdin, NULL);
fgets(prefixo, 100, stdin);
setbuf(stdin, NULL);
retiraEnter(prefixo);
padronizaString(prefixo);
posicao = findFornecedorByName(fornecedores, prefixo);
break;
}
if(posicao != -1){
lerRegistroEmArquivo(&fornecedor, fornecedores, posicao, sizeof(Fornecedor));
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCNPJ: %s\n\n",
fornecedor.id, fornecedor.nome, fornecedor.telefone, fornecedor.email, fornecedor.CNPJ);
}
}while (opcao != 0);
fecharArquivo(fornecedores);
}else{
printf("\nNão foi possivel acessar a base de dados!\n");
}
}
void listarFornecedores(){
FILE *fornecedores;
Fornecedor fornecedor;
fornecedores = abrirArquivo(FORNECEDOR);
limparTela();
printf("Listagem de fornecedores: \n");
fseek(fornecedores, 0, SEEK_SET);
while (fread(&fornecedor, sizeof(Cliente), 1, fornecedores)) {
printf("\nId: %ld \nNome: %s \nTelefone: %s \nEmail : %s \nCNPJ: %s\n\n",
fornecedor.id, fornecedor.nome, fornecedor.telefone, fornecedor.email, fornecedor.CNPJ);
}
fecharArquivo(fornecedores);
pause();
}
void cadastrarProduto(){
FILE *produtos;
Produto produto;
int opcao;
produtos = abrirArquivo(PRODUTO);
if(produtos){
do {
produto.id = getNewUniqueId(produtos, sizeof(Produto));
produto.quantidadeEstoque = 0;
do {
printf("Digite o nome do produto: ");
setbuf(stdin, NULL);
fgets(produto.nome, 100, stdin);
setbuf(stdin, NULL);
padronizaString(produto.nome);
}while (!campovazio(produto.nome));
do{
printf("Digite o preço unitario do produto: ");
scanf("%f", &produto.precoUnitario);
}while(produto.precoUnitario <= 0);
gravarRegistroFinalArquivo(&produto, produtos, sizeof(Produto));
printf("Deseja Sair? \n1 - Sim 2 - Não: ");
scanf("%d", &opcao);
}while (opcao != 1);
fecharArquivo(produtos);
}
}
void listarProdutos(){
Produto produto;
FILE *produtos;
produtos = abrirArquivo(PRODUTO);
printf("\t|\t Id \t|\t Nome \t|\n");
while (fread(&produto, sizeof(Produto), 1, produtos)) {
printf("\t|\t %ld \t|\t %s \t|\n", produto.id, produto.nome);
}
fecharArquivo(produtos);
}
void atualizarPreco(){
FILE *historicoPrecos;
FILE *produtos;
Produto produto;
HistoricoPreco historicoPreco;
int valorAjuste = 0, opcao, contador = 0;
float porcentagem = 0;
unsigned long id;
historicoPrecos = abrirArquivo(HISTORICO_PRECOS);
produtos = abrirArquivo(PRODUTO);
if(historicoPrecos && produtos){
do{
printf("Qual o valor (em porcentagem) do ajuste? (valor entre -100 e 100 ");
scanf("%d", &valorAjuste);
}while(valorAjuste < -100 && valorAjuste > 100);
porcentagem = (1 + (float) valorAjuste/100);
do{
printf("O ajuste é para apenas um produto ou para todos? \n1 - somente um \n2 -todos \n opção: ");
scanf("%d", &opcao);
}while(opcao < 1 || opcao > 2);
if(opcao ==1){
printf("\t\t\tListagem de produtos: \n\n");
printf("|\tNome \t\t|\t id \t|\n");
fseek(produtos, 0, SEEK_SET);
while(fread(&produto, sizeof(Produto), 1, produtos)){
printf("|\t%s \t|\t %ld \t|\n", produto.nome, produto.id);
}
fseek(produtos, 0, SEEK_SET);
printf("\n\n");
printf("Digite o id do produto: ");
scanf("%ld",&id);
fseek(produtos, 0, SEEK_SET);
while(fread(&produto, sizeof(Produto), 1, produtos)){
if(produto.id == id){
produto.precoUnitario = produto.precoUnitario * porcentagem;
historicoPreco.idProduto = produto.id;
getSystemDate(historicoPreco.data);
historicoPreco.valor = produto.precoUnitario;
gravarRegistroFinalArquivo(&historicoPreco, historicoPrecos, sizeof(HistoricoPreco));
gravarRegistroEmArquivo(&produto, produtos, contador, sizeof(Produto));
}
contador ++;
}
}else{
contador = 0;
fseek(produtos, 0, SEEK_SET);
while(fread(&produto, sizeof(Produto), 1, produtos)){
produto.precoUnitario = produto.precoUnitario * porcentagem;
historicoPreco.idProduto = produto.id;
getSystemDate(historicoPreco.data);
historicoPreco.valor = produto.precoUnitario;
gravarRegistroFinalArquivo(&historicoPreco, historicoPrecos, sizeof(HistoricoPreco));
gravarRegistroEmArquivo(&produto, produtos, contador, sizeof(Produto));
contador ++;
}
}
printf("\t\t\tListagem de produtos com novos preços: \n\n");
printf("|\t\tNome \t\t|\t id \t| \t preço unitário |\n");
fseek(produtos, 0, SEEK_SET);
while(fread(&produto, sizeof(Produto), 1, produtos)){
printf("|\t%s \t|\t %ld \t|\t %.2f|\n", produto.nome, produto.id, produto.precoUnitario);
}
pause();
fecharArquivo(produtos);
fecharArquivo(historicoPrecos);
}
}
void efetuarCompra(){
FILE *produtos, *fornecedores, *notasCompra, *itensNotaCompra;
Produto produto;
Fornecedor fornecedor;
NotaCompra notaCompra;
ItemNotaCompra itemNotaCompra;
ItemCarrinho *carrinho, item;
produtos = abrirArquivo(PRODUTO);
fornecedores = abrirArquivo(FORNECEDOR);
notasCompra = abrirArquivo(NOTA_COMPRA);
int tamanho = 1, contador = 0, opcao, quantidade, posicao;
unsigned long id;
float totalNota = 0;
carrinho = alocaCarrinho(tamanho);
do {
printf("Para efetuar uma compra escolha o fornecedor de acordo com a tabela abaixo:");
listarFornecedores();
printf("Digite o id do fornecedor: ");
scanf("%ld", &id);
}while (findFornecedorById(fornecedores, id) == -1);
notaCompra.idFornecedor = id;
notaCompra.id = getNewUniqueId(notasCompra, sizeof(NotaCompra));
getSystemDate(notaCompra.dataCompra);
do{
do {
limparTela();
listarProdutos();
printf("Digite o Id do produto que deseja adicionar: ");
scanf("%ld", &id);
}while (findProdutoById(produtos, id) == -1);
do{
printf("Digite a quantidade (deve ser um valor maior que zero) do produto: ");
scanf("%d", &quantidade);
}while(quantidade <= 0);
do{
printf("Digite o valor unitario do produto: ");
scanf("%f", &item.valorUnitario);
}while(item.valorUnitario <= 0);
item.quantidade = quantidade;
item.idProduto = id;
if(contador == tamanho){
carrinho = aumentaCarrinho(carrinho, &tamanho);
}
carrinho[contador] = item;
contador++;
printf("Deseja comprar mais um produto? \n1 - Sim 2 - Não");
scanf("%d", &opcao);
}while(opcao ==1);
for(int i = 0; i < contador; i++){
itensNotaCompra = abrirArquivo(ITEM_NOTA_COMPRA);
itemNotaCompra.idNotaCompra = notaCompra.id;
itemNotaCompra.id = getNewUniqueId(itensNotaCompra, sizeof(ItemNotaCompra));
itemNotaCompra.quantidade = carrinho[i].quantidade;
itemNotaCompra.idProduto = carrinho[i].idProduto;
itemNotaCompra.valorUnitario = carrinho[i].valorUnitario;
totalNota += itemNotaCompra.valorUnitario * itemNotaCompra.quantidade;
gravarRegistroFinalArquivo(&itemNotaCompra, itensNotaCompra, sizeof(ItemNotaCompra));
posicao = findProdutoById(produtos, item.idProduto);
lerRegistroEmArquivo(&produto, produtos, posicao, sizeof(Produto));
produto.quantidadeEstoque += carrinho[i].quantidade;
gravarRegistroEmArquivo(&produto, produtos, posicao, sizeof(Produto));
fecharArquivo(itensNotaCompra);
}
notaCompra.valorTotal = totalNota;
gravarRegistroFinalArquivo(¬aCompra, notasCompra, sizeof(NotaCompra));
fecharArquivo(produtos);
fecharArquivo(fornecedores);
fecharArquivo(notasCompra);
}
void efetuarVenda(){
FILE *produtos, *clientes, *notasFiscais, *itensNotaFiscal;
Produto produto;
Cliente cliente;
NotaFiscal notaFiscal;
ItemNotaFiscal itemNotaFiscal;
ItemCarrinho *carrinho, item;
produtos = abrirArquivo(PRODUTO);
clientes = abrirArquivo(CLIENTE);
notasFiscais = abrirArquivo(NOTA_FISCAL);
int tamanho = 1, contador = 0, opcao, quantidade, posicao;
unsigned long id;
float totalNota = 0;
carrinho = alocaCarrinho(tamanho);
do {
printf("Para efetuar uma venda escolha o Cliente de acordo com a tabela abaixo:");
listarClientes();
printf("Digite o id do cliente: ");
scanf("%ld", &id);
}while (findClienteById(clientes, id) == -1);
notaFiscal.idCliente = id;
notaFiscal.id = getNewUniqueId(notasFiscais, sizeof(NotaFiscal));
getSystemDate(notaFiscal.dataCompra);
do{
do {
limparTela();
listarProdutos();
printf("Digite o Id do produto que deseja adicionar: ");
scanf("%ld", &id);
}while (findProdutoById(produtos, id) == -1);
posicao = findProdutoById(produtos, id);
lerRegistroEmArquivo(&produto, produtos, posicao, sizeof(Produto));
do{
printf("Digite a quantidade (max: %d) do produto: ", produto.quantidadeEstoque);
scanf("%d", &quantidade);
}while(quantidade <= 0 || quantidade > produto.quantidadeEstoque);
item.quantidade = quantidade;
item.idProduto = id;
if(contador == tamanho){
carrinho = aumentaCarrinho(carrinho, &tamanho);
}
carrinho[contador] = item;
contador++;
printf("Deseja comprar mais um produto? \n1 - Sim 2 - Não ");
scanf("%d", &opcao);
}while(opcao ==1);
for(int i = 0; i < contador; i++){
itensNotaFiscal = abrirArquivo(ITEM_NOTA_FISCAL);
posicao = findProdutoById(produtos, item.idProduto);
lerRegistroEmArquivo(&produto, produtos, posicao, sizeof(Produto));
produto.quantidadeEstoque -= carrinho[i].quantidade;
gravarRegistroEmArquivo(&produto, produtos, posicao, sizeof(Produto));
carrinho[i].valorUnitario = produto.precoUnitario;
itemNotaFiscal.idNotaFiscal = notaFiscal.id;
itemNotaFiscal.id = getNewUniqueId(itensNotaFiscal, sizeof(ItemNotaFiscal));
itemNotaFiscal.quantidade = carrinho[i].quantidade;
itemNotaFiscal.idProduto = carrinho[i].idProduto;
itemNotaFiscal.valorVenda = carrinho[i].valorUnitario;
totalNota += itemNotaFiscal.valorVenda * itemNotaFiscal.quantidade;
gravarRegistroFinalArquivo(&itemNotaFiscal, itensNotaFiscal, sizeof(itemNotaFiscal));
fecharArquivo(itensNotaFiscal);
}
notaFiscal.valorTotal = totalNota;
gravarRegistroFinalArquivo(¬aFiscal, notasFiscais, sizeof(notaFiscal));
fecharArquivo(produtos);
fecharArquivo(clientes);
fecharArquivo(notasFiscais);
printf("Valor total da compra: %.2f", totalNota);
pause();
}
|
ljnferreira/TP1ED1-2021
|
utils.c
|
<reponame>ljnferreira/TP1ED1-2021
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "utils.h"
//Funções de validação
/**
* Função que verifica se um char é uma letra
*/
int isChar(char c){
return ((c >= 'a' && c <= 'z')|| (c >= 'A' && c <= 'Z'));
}
/**
* Função que verifica se um char é um numero
*/
int isDigit(const char c){
return (c >= '0' && c <= '9');
}
int validaCPF(char *cpf){
int i, j, digito1 = 0, digito2 = 0;
/*verificando se o tamanho do vetor é diferente de 11, caso
seja ele retorna 0 invalidando o cpf*/
if(strlen(cpf) != 11)
return 0;
else if(!strcmp(cpf,"00000000000") || !strcmp(cpf,"11111111111") || !strcmp(cpf,"22222222222") ||
!strcmp(cpf,"33333333333") || !strcmp(cpf,"44444444444") || !strcmp(cpf,"55555555555") ||
!strcmp(cpf,"66666666666") || !strcmp(cpf,"77777777777") || !strcmp(cpf,"88888888888") ||
!strcmp(cpf,"99999999999") || !strcmp(cpf,"12345678909") || !strcmp(cpf,"01234567890"))
return 0; //se o CPF tiver todos os números iguais ou for formado por sequencias ele é inválido.
else
{
// verificando digito 1---------------------------------------------------
for(i = 0, j = 10; i < strlen(cpf)-2; i++, j--) //multiplica os números de 10 a 2 e soma os resultados dentro de digito1
digito1 += (cpf[i]-48) * j;
digito1 %= 11;
if(digito1 < 2)
digito1 = 0;
else
digito1 = 11 - digito1;
if((cpf[9]-48) != digito1)
return 0; ///se o digito 1 não for o mesmo que o da validação CPF é inválido
else
// verificando digito 2--------------------------------------------------
{
for(i = 0, j = 11; i < strlen(cpf)-1; i++, j--) ///multiplica os números de 11 a 2 e soma os resultados dentro de digito2
digito2 += (cpf[i]-48) * j;
digito2 %= 11;
if(digito2 < 2)
digito2 = 0;
else
digito2 = 11 - digito2;
if((cpf[10]-48) != digito2)
return 0; ///se o digito 2 não for o mesmo que o da validação CPF é inválido
}
}
return 1;
}
int validaCNPJ(char *cnpj){
int mascaraPrimeiroDigito[] = {5 ,4 ,3 ,2 ,9 ,8 ,7 ,6 ,5 ,4 ,3 ,2};
int mascaraSegundoDigito[] = {6, 5 ,4 ,3 ,2 ,9 ,8 ,7 ,6 ,5 ,4 ,3 ,2};
int valido = 0, digitoUm, digitoDois, somatorio = 0, cnpjInt[14];
if(strlen(cnpj) !=14){
return 0;
}
if(!strcmp(cnpj, "00000000000000")||
!strcmp(cnpj, "11111111111111")||
!strcmp(cnpj, "22222222222222")||
!strcmp(cnpj, "33333333333333")||
!strcmp(cnpj, "44444444444444")||
!strcmp(cnpj, "55555555555555")||
!strcmp(cnpj, "66666666666666")||
!strcmp(cnpj, "77777777777777")||
!strcmp(cnpj, "88888888888888")||
!strcmp(cnpj, "99999999999999")){
return 0;
}
// percorre o vetor de char convertendo os caracteres pra inteiro e salvando
// no vetor de inteiros
for (int i = 0; i < strlen(cnpj); i++){
if(isDigit(cnpj[i])){
cnpjInt[i] = (int) cnpj[i]-48;
}else{
return 0;
}
}
//calculando digito 1
for (int i = 0; i < 12; i++){
somatorio += cnpjInt[i] * mascaraPrimeiroDigito[i];
}
somatorio = somatorio % 11;
digitoUm = somatorio <= 2 ? somatorio : 11 - somatorio;
somatorio = 0;
//calculando digito 2
for (int i = 0; i < 13; i++){
if (i == 12){ // verifica se a posicação a ser acessada é a do digito 1
somatorio += digitoUm * mascaraSegundoDigito[i];
}else{
somatorio += cnpjInt[i] * mascaraSegundoDigito[i];
}
}
somatorio = somatorio % 11;
digitoDois = somatorio <= 2 ? somatorio : 11 - somatorio;
if (digitoUm == cnpjInt[12] && digitoDois == cnpjInt[13]){
valido = 1;
}
return valido;
}
int validaData(char *data){
int dia,mes,ano,n1,n2,n3;
/* convertendo a data char para int */
n1=(data[0]-48)*10;
dia = n1 + (data[1]-48);
n1=0;
n1=(data[3]-48)*10;
mes = n1 + (data[4]-48);
n1=0;
n1=(data[6]-48)*1000;
n2=(data[7]-48)*100;
n3=(data[8]-48)*10;
ano = n1 + n2 + n3 +(data[9]-48);
/*Validando a data*/
if ((dia >= 1 && dia <= 31) && (mes >= 1 && mes <= 12) && (ano >= 1950 && ano <= 2100)){ //verifica se os numeros sao validos{
if(ano <= 1950 && mes <= 6 && dia <= 20 )
return 0;
if ((dia == 29 && mes == 2) && ((ano % 4) == 0)) //verifica se o ano e bissexto
return 1;
if (dia <= 28 && mes == 2) //verifica o mes de feveireiro
return 1;
if ((dia <= 30) && (mes == 4 || mes == 6 || mes == 9 || mes == 11)) //verifica os meses de 30 dias
return 1;
if ((dia <=31) && (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes ==8 || mes == 10 || mes == 12)) //verifica os meses de 31 dias
return 1;
else
return 0;
}
else
return 0;
}
/**
* Função que verifica se um email é valido, retornando 1 caso seja e 0 caso contrario
*/
int validaEmail(char *email){
//verifica se o primeiro caractere é uma letra
if (!isChar(email[0])) {
return 0;
}
//variaveis para armazenar a posição do ponto e da arroba
int arroba = -1, ponto = -1;
//Percorre o array para descobrir a posição do ponto e da arroba
for (int i = 0; i < strlen(email); i++) {
if (email[i] == '@') {
arroba = i;
}
else if (email[i] == '.') {
ponto = i;
}
}
// verifica se falta ponto ou arroba
if (arroba == -1 || ponto == -1)
return 0;
// verifica se o ponto esta antes da arroba
if (arroba > ponto)
return 0;
// verifica se o ponto esta presente no final
return !(ponto >= (strlen(email) - 1));
}
/**
* Essa função recebe como entrada uma string, removendo
* o caratere de escape \n de seu final.
*/
void retiraEnter(char *string){
if(string[strlen(string)-1]=='\n'){
string[strlen(string)-1] = '\0';
}
}
/**
* Essa função recebe como entrada uma string, verificando se
* a mesma se encontra vazia.
*/
int campovazio(char *nome){
retiraEnter(nome);
if(strlen(nome) == 0)
return 0;
return 1;
}
/**
* Essa função recebe como entrada uma string e retira todos os acentos,
* convertendo tbm as letras minusculas em maiusculas.
*/
void padronizaString(char *texto){
int tamanho = strlen(texto), caractere;
char aux;
retiraEnter(texto);
//percorre toda a string convertendo para caixa alta e removendo acentuação
for (int i = 0; i < tamanho; i++){
caractere = (int) texto[i];
if (caractere == -61 || caractere == -67 || caractere == -31 || caractere == -59) {
texto[i] = texto[i+1];
texto[i+1] = ' ';
i--;
}
if(caractere == -95 || caractere == -96 || caractere == -93 || caractere == -94 ||
caractere == -127 || caractere == -128 || caractere == -125 ||caractere == -126){
texto[i] = 'a';
}
if(caractere == -87 || caractere == -88 || caractere == -86 || caractere == -119 ||
caractere == -118 || caractere == -120){
texto[i] = 'e';
}
if(caractere == -83 || caractere == -84 || caractere == -60 || caractere == -82 ||
caractere == -115 || caractere == -116){
texto[i] = 'i';
}
if(caractere == -77 || caractere == -78 || caractere == -75 || caractere == -76 ||
caractere == -107 || caractere == -108 || caractere == -109 ||caractere == -110){
texto[i] = 'o';
}
if(caractere == -70 || caractere == -71 || caractere == -102 || caractere == -103 ){
texto[i] = 'u';
}
if(caractere == -89 || caractere == -121){
texto[i] = 'c';
}
texto[i] = toupper(texto[i]); //converte em letras maiusculas
}
tamanho = strlen(texto);
//removendo espaços em branco resultantes da remoção da acentuação
for (int i = 0; i < tamanho ; i++) {
if(texto[i] != '\0'){
if(texto[i] == ' ' && texto[i+1] == ' '){
for (int k = i + 1; k < tamanho; k++){
aux = texto[k];
texto[k] = texto[k+1];
texto[k+1] = aux;
}
}
}
}
}
void getSystemDate(char date[11]){
strcpy(date, "xx/xx/xxxx");
time_t actualTime = time(NULL);
struct tm localtimer = *localtime(&actualTime);
int dia, mes, ano;
dia = localtimer.tm_mday;
mes = localtimer.tm_mon + 1;
ano = localtimer.tm_year + 1900;
date[0] = dia/10 + 48;
date[1] = dia%10 + 48;
date[3] = mes/10 + 48;
date[4] = mes%10 + 48;
date[6] = ano/1000 + 48;
date[7] = ano%1000/100 + 48;
date[8] = ano%1000%100/10 + 48;
date[9] = ano%1000%100%10 + 48;
}
|
ljnferreira/TP1ED1-2021
|
files.c
|
<gh_stars>0
#include <stdio.h>
#include <string.h>
#include "files.h"
#include "dataTypes.h"
#include "memoryManagement.h"
FILE *abrirArquivo(char location[]){
FILE *file;
file = fopen(location, "rb+");
if(!file){
file = fopen(location, "wb+");
}
if (file){
return file;
}else{
return NULL;
}
}
int fecharArquivo(FILE *file){
return fclose(file);
}
int gravarRegistroFinalArquivo(void *data, FILE *file, unsigned long size){
fseek(file, 0, SEEK_END);
return fwrite(data, size, 1, file);
}
int gravarRegistroEmArquivo(void *data, FILE *file, int posicao, unsigned long size){
fseek(file, posicao * size, SEEK_SET);
return fwrite(data, size, 1, file);
}
void lerRegistroEmArquivo(void *data, FILE *file, int position, unsigned int size){
fseek(file, position * size, SEEK_SET);
fread(data, size, 1, file);
}
unsigned long getNewUniqueId(FILE *file, unsigned long sizeOfRegister){
unsigned long int tamanho;
fseek(file, 0, SEEK_END);
tamanho = ftell(file);
return (tamanho / sizeOfRegister) + 1;
}
int findClienteById(FILE *file, unsigned long id){
Cliente cliente;
int tamanho, posicao = -1;
fseek(file, 0, SEEK_END);
tamanho = ftell(file) / sizeof (Cliente);
fseek(file, 0, SEEK_SET);
for(int i = 0; i < tamanho; i++){
fread(&cliente, sizeof(Cliente), 1, file);
if(cliente.id == id){
posicao = i;
return posicao;
}
}
return posicao;
}
int findClienteByCPF(FILE *file, char *cpf){
Cliente cliente;
int posicao = -1, contador = 0;
fseek(file, 0, SEEK_SET);
while(fread(&cliente, sizeof(Cliente), 1, file)){
if(!strcmp(cliente.cpf, cpf)){
posicao = contador;
return posicao;
}
contador ++;
}
return posicao;
}
/**
* Recebe como parametro o arquivo e o texto a ser procurado, além de um
* ponteiro para armazenar o tamanho do vetor
* e retorna um array de inteiros com a posição de cada ocorrencia
* do texto entre os registros. Após uso do array deve-se usar
* a função free da biblioteca stdlib para liberar a memoria alocada.
*/
int *findClientesByName(FILE *file, char *name, int *tamanho){
Cliente cliente;
int tamanhoArquivo, posicao = -1, tamanhoVetor = 1, qtdRegistros = 0;
int *vetor = alocaVetorInteiros(tamanhoVetor);
fseek(file, 0, SEEK_END);
tamanhoArquivo = ftell(file) / sizeof(Cliente);
fseek(file, 0, SEEK_SET);
for(int i = 0; i < tamanhoArquivo; i++){
fread(&cliente, sizeof(Cliente), 1, file);
if(strstr(cliente.nome, name)){
if(qtdRegistros == 0){
vetor[qtdRegistros] = i;
qtdRegistros++;
}else{
vetor = realocaVetorInteiros(vetor, &tamanhoVetor, 1);
vetor[qtdRegistros] = i;
qtdRegistros ++;
}
}
}// percorre todo o arquivo
*tamanho = qtdRegistros;
if(qtdRegistros == 0){
return NULL;
}else
return vetor;
}
int findVendedorById(FILE *file, unsigned long id){
Vendedor vendedor;
int contador = 0, posicao = -1;
fseek(file, 0, SEEK_SET);
while(fread(&vendedor, sizeof(Vendedor), 1, file)){
if(vendedor.id == id){
posicao = contador;
return posicao;
}
}
return posicao;
}
int findVendedorByCPF(FILE *file, char *cpf){
Vendedor vendedor;
int contador = 0, posicao = -1;
fseek(file, 0, SEEK_SET);
while(fread(&vendedor, sizeof(Vendedor), 1, file)){
if(!strcmp(vendedor.cpf, cpf)){
posicao = contador;
return posicao;
}
contador++;
}
return posicao;
}
/**
* Recebe como parametro o arquivo e o texto a ser procurado, além de um
* ponteiro para armazenar o tamanho do vetor
* e retorna um array de inteiros com a posição de cada ocorrencia
* do texto entre os registros. Após uso do array deve-se usar
* a função free da biblioteca stdlib para liberar a memoria alocada.
*/
int *findVendedoresByName(FILE *file, char *name, int *tamanho){
Vendedor vendedor;
int tamanhoArquivo, posicao = -1, tamanhoVetor = 1, qtdRegistros = 0;
int *vetor = alocaVetorInteiros(tamanhoVetor);
fseek(file, 0, SEEK_END);
tamanhoArquivo = ftell(file) / sizeof(Vendedor);
fseek(file, 0, SEEK_SET);
for(int i = 0; i < tamanhoArquivo; i++){
fread(&vendedor, sizeof(Vendedor), 1, file);
if(strstr(vendedor.nome, name)){
if(qtdRegistros == 0){
vetor[qtdRegistros] = i;
qtdRegistros++;
}else{
vetor = realocaVetorInteiros(vetor, &tamanhoVetor, 1);
vetor[qtdRegistros] = i;
qtdRegistros ++;
}
}
}// percorre todo o arquivo
*tamanho = qtdRegistros;
if(qtdRegistros == 0){
return NULL;
}else
return vetor;
}
int isEmailCadastradoVendedor(FILE *file, char *email){
Vendedor vendedor;
int tamanho;
fseek(file, 0, SEEK_END);
tamanho = ftell(file) / sizeof(Vendedor);
for (int i = 0; i < tamanho; i++) {
fread(&vendedor, sizeof(Vendedor), 1, file);
if (strcmp(vendedor.email, email)) {
return 1;
}
}
return 0;
}
int findFornecedorById(FILE *file, unsigned long id){
Fornecedor fornecedor;
int contador = 0, posicao = -1;
fseek(file, 0, SEEK_SET);
while(fread(&fornecedor, sizeof(Fornecedor), 1, file)){
if(fornecedor.id ==id){
posicao = contador;
return posicao;
}
contador++;
}
return posicao;
}
int findFornecedorByCNPJ(FILE *file, char *cnpj){
Fornecedor fornecedor;
int contador = 0, posicao = -1;
fseek(file, 0, SEEK_SET);
while(fread(&fornecedor, sizeof(Fornecedor), 1, file)){
if(!strcmp(fornecedor.CNPJ, cnpj)){
posicao = contador;
return posicao;
}
contador++;
}
return posicao;
}
/**
* Recebe como parametro o arquivo e o texto a ser procurado, além de um
* ponteiro para armazenar o tamanho do vetor
* e retorna um array de inteiros com a posição de cada ocorrencia
* do texto entre os registros. Após uso do array deve-se usar
* a função free da biblioteca stdlib para liberar a memoria alocada.
*/
int findFornecedorByName(FILE *file, char *name){
Fornecedor fornecedor;
int posicao = -1, contador = 0;
fseek(file, 0, SEEK_SET);
while(fread(&fornecedor, sizeof(Fornecedor), 1, file)){
if(strstr(fornecedor.nome, name)){
posicao = contador;
return contador;
}
contador ++;
}
return posicao;
}
int isNomeFornecedorCadastrado(FILE *file, char * nome){
Fornecedor fornecedor;
fseek(file, 0, SEEK_SET);
while(fread(&fornecedor, sizeof(Fornecedor), 1, file)){
if(!strcmp(fornecedor.nome, nome)){
return 1;
}
}
return 0;
}
int findProdutoById(FILE *file, unsigned long id){
Produto produto;
int contador = 0, posicao = -1;
fseek(file, 0, SEEK_SET);
while(fread(&produto, sizeof(Produto), 1, file)){
if(produto.id == id){
posicao = contador;
return posicao;
}
}
return posicao;
}
int findNotaFiscalById(FILE *file, unsigned long id){
NotaFiscal notaFiscal;
int tamanho, posicao = -1;
fseek(file, 0, SEEK_END);
tamanho = ftell(file) / sizeof (NotaFiscal);
for(int i = 0; i < tamanho; i++){
fread(¬aFiscal, sizeof(NotaFiscal), 1, file);
if(notaFiscal.id == id){
posicao = i;
}
}
return posicao;
}
int findNotaCompraById(FILE *file, unsigned long id){
NotaCompra notaCompra;
int tamanho, posicao = -1;
fseek(file, 0, SEEK_END);
tamanho = ftell(file) / sizeof (NotaCompra);
for(int i = 0; i < tamanho; i++){
fread(¬aCompra, sizeof(NotaCompra), 1, file);
if(notaCompra.id == id){
posicao = i;
}
}
return posicao;
}
int findItemNotaCompraById(FILE *file, unsigned long id){
ItemNotaCompra itemNotaCompra;
int tamanho, posicao = -1;
fseek(file, 0, SEEK_END);
tamanho = ftell(file) / sizeof (ItemNotaCompra);
for(int i = 0; i < tamanho; i++){
fread(&itemNotaCompra, sizeof(ItemNotaCompra), 1, file);
if(itemNotaCompra.id == id){
posicao = i;
}
}
return posicao;
}
|
ljnferreira/TP1ED1-2021
|
userInteraction.c
|
#include <stdio.h>
#include <stdlib.h>
#include "userInteraction.h"
#include "crud.h"
void crudCliente(){
int opcao = 0;
do {
limparTela();
bemVindo();
printf("Escolha uma das opções abaixo: \n");
printf("1 - Cadastrar Cliente\n");
printf("2 - Consultar Cliente\n");
printf("3 - Alterar Cliente\n");
printf("4 - Listar Clientes\n");
printf("0 - Sair \n");
scanf("%d", &opcao);
if(opcao > 0 && opcao < 5)
switch (opcao) {
case 1 :
cadastrarCliente();
break;
case 2:
consultarCliente();
break;
case 3:
alterarCliente();
break;
case 4:
listarClientes();
break;
}
}while (opcao > 0 && opcao < 5);
}
void crudVendedor(){
int opcao = 0;
do {
limparTela();
printf("Escolha uma das opções abaixo: \n");
printf("1 - Cadastrar Vendedor\n");
printf("2 - Consultar Vendedor\n");
printf("3 - Alterar Vendedor\n");
printf("4 - Listar Vendedores\n");
printf("0 - Sair \n");
scanf("%d", &opcao);
if(opcao > 0 && opcao < 5)
switch (opcao) {
case 1 :
cadastrarVendedor();
break;
case 2:
consultarVendedor();
break;
case 3:
alterarVendedor();
break;
case 4:
listarVendedores();
break;
}
}while (opcao > 0 && opcao < 5);
}
void crudFornecedor(){
int opcao = 0;
do {
limparTela();
printf("Escolha uma das opções abaixo: \n");
printf("1 - Cadastrar Fornecedor\n");
printf("2 - Consultar Fornecedor\n");
printf("3 - Alterar Fornecedor\n");
printf("4 - Listar Fornecedores\n");
printf("0 - Sair \n");
scanf("%d", &opcao);
if(opcao > 0 && opcao < 5)
switch (opcao) {
case 1 :
cadastrarFornecedor();
break;
case 2:
consultarFornecedor();
break;
case 3:
alterarFornecedor();
break;
case 4:
listarFornecedores();
break;
}
}while (opcao > 0 && opcao < 5);
}
void bemVindo(){
printf("\t\t================================================================================\n");
printf("\t\t= Seja bem Vindo ao programa de gerenciamento da farmacia de Alvinópolis =\n");
printf("\t\t================================================================================\n");
}
void menuPrincipal(){
int opcao = 0;
limparTela();
bemVindo();
do{
printf("Escolha uma das opções abaixo: \n");
printf("1 - Gerenciar clientes \n");
printf("2 - Gerenciar Vendedores \n");
printf("3 - Gerenciar Fornedores \n");
printf("4 - Cadastrar Produtos \n");
printf("5 - Efetuar venda \n");
printf("6 - Efetuar compra \n");
printf("7 - Atualizar preço \n");
printf("8 - Relatórios \n");
printf("0 - Sair \n");
scanf("%d", &opcao);
if (opcao > 0 && opcao < 9){
switch (opcao) {
case 1 :
crudCliente();
break;
case 2:
crudVendedor();
break;
case 3:
crudFornecedor();
break;
case 4:
cadastrarProduto();
break;
case 5:
efetuarVenda();
break;
case 6:
efetuarCompra();
break;
case 7:
atualizarPreco();
break;
case 8:
break;
}
}
}while(opcao > 0 && opcao < 9);
}
void limparTela(){
system("cls||clear");
}
void pause(){
if(PAUSE)
system("read -p \"Pressione enter para sair\" saindo");
else
system("pause");
}
void creditos(){}
|
ljnferreira/TP1ED1-2021
|
memoryManagement.c
|
#include <stdlib.h>
#include "dataTypes.h"
#include "memoryManagement.h"
int *alocaVetorInteiros(int tamanho){
int *vetor = (int*)malloc(sizeof(int)* tamanho);
return vetor;
}
int *realocaVetorInteiros(int *vetor, int *tamanho, int acrescimo){
vetor = (int*)realloc( vetor,sizeof(int)* (*tamanho + acrescimo));
*tamanho += acrescimo;
return vetor;
}
ItemCarrinho *alocaCarrinho(int tamanho){
ItemCarrinho *carrinho = (ItemCarrinho*)malloc(sizeof(ItemCarrinho)* tamanho);
return carrinho;
}
ItemCarrinho *aumentaCarrinho(ItemCarrinho *carrinho, int *tamanho){
carrinho = (ItemCarrinho*)realloc( carrinho,sizeof(ItemCarrinho)* (*tamanho + 1));
*tamanho += 1;
return carrinho;
}
ItemCarrinho *diminuiCarrinho(ItemCarrinho *carrinho, int *tamanho){
ItemCarrinho *aux;
aux = (ItemCarrinho*)malloc(sizeof(ItemCarrinho)* (*tamanho - 1));
*tamanho -= 1;
for(int i = 0; i < *tamanho - 1; i++){
aux[i] = carrinho[i];
}
carrinho = aux;
return carrinho;
}
|
ljnferreira/TP1ED1-2021
|
crud.h
|
#ifndef _CRUD_H_
#define _CRUD_H_
/**
* Le e cadastra os dados de cliente no respectivo arquivo
*/
void cadastrarCliente();
/**
* permite ler novos dados e atualizar os dados de cliente no respectivo arquivo
*/
void alterarCliente();
/**
* permite consultar os dados de cliente no respectivo arquivo
*/
void consultarCliente();
/**
* permite listar os dados de todos os clientes contidos no respectivo arquivo
*/
void listarClientes();
/**
* Le e cadastra os dados de Vendedor no respectivo arquivo
*/
void cadastrarVendedor();
/**
* permite ler novos dados e atualizar os dados de Vendedor no respectivo arquivo
*/
void alterarVendedor();
/**
* permite consultar os dados de Vendedor no respectivo arquivo
*/
void consultarVendedor();
/**
* permite listar os dados de todos os Vendedores contidos no respectivo arquivo
*/
void listarVendedores();
/**
* Le e cadastra os dados de Fornecedor no respectivo arquivo
*/
void cadastrarFornecedor();
/**
* permite ler novos dados e atualizar os dados de Fornecedor no respectivo arquivo
*/
void alterarFornecedor();
/**
* permite consultar os dados de Fornecedor no respectivo arquivo
*/
void consultarFornecedor();
/**
* permite listar os dados de todos os Fornecedores contidos no respectivo arquivo
*/
void listarFornecedores();
void cadastrarProduto();
void alterarProduto();
void consultarProduto();
void atualizarPreco();
void efetuarCompra();
void efetuarVenda();
#endif
|
asowers1/PushMGR
|
BLE-Tutorial_2/BTSAppDelegate.h
|
<reponame>asowers1/PushMGR
//
// BTSAppDelegate.h
// PushMGR
//
// Created by <NAME> on 3/15/12.
// Copyright (c) 2012 ST alliance AS. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BTSAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
asowers1/PushMGR
|
BLE-Tutorial_2/CBCPCtrl.h
|
<gh_stars>1-10
//
// CBCPCtrl.h
// PushMGR
//
// Created by <NAME> on 3/16/12.
// Copyright (c) 2012 ST alliance AS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@protocol CBCPCtrlDelegate <NSObject>
@required
-(void) updateCPLog:(NSString *)text;
-(void) servicesRead;
-(void) updatedRSSI:(CBPeripheral *)peripheral;
-(void) updatedCharacteristic:(CBPeripheral *)peripheral sUUID:(CBUUID *)sUUID cUUID:(CBUUID *)cUUID data:(NSData *)data;
@end
@interface CBCPCtrl : NSObject <CBPeripheralDelegate>
@property (strong,nonatomic) CBPeripheral *cBCP;
@property (strong,nonatomic) id<CBCPCtrlDelegate> delegate;
-(void)writeCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID data:(NSData *)data;
-(void)readCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID;
-(void)setNotificationForCharacteristic:(CBPeripheral *)peripheral sUUID:(NSString *)sUUID cUUID:(NSString *)cUUID enable:(BOOL)enable;
@end
|
asowers1/PushMGR
|
BLE-Tutorial_2/CBCMCtrl.h
|
//
// CBCMCtrl.h
// PushMGR
//
// Created by <NAME> on 3/15/12.
// Copyright (c) 2012 ST alliance AS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@protocol CBCMCtrlDelegate <NSObject>
@required
- (void) updateCMLog:(NSString *)text;
- (void) foundPeripheral:(CBPeripheral *)p;
- (void) connectedPeripheral:(CBPeripheral *)p;
@end
@interface CBCMCtrl : NSObject <CBCentralManagerDelegate> {
}
@property bool cBReady;
@property (nonatomic,strong) CBCentralManager *cBCM;
@property (nonatomic,assign) id<CBCMCtrlDelegate> delegate;
@end
|
asowers1/PushMGR
|
BLE-Tutorial_2/BTSViewController.h
|
//
// BTSViewController.h
// PushMGR
//
// Created by <NAME> on 3/15/12.
// Copyright (c) 2012 ST alliance AS. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "CBCMCtrl.h"
#import "CBCPCtrl.h"
@interface BTSViewController : UIViewController <CBCMCtrlDelegate,CBCPCtrlDelegate>
@property (strong,nonatomic) UIWindow *window;
@property (strong,nonatomic) CBCMCtrl *CBC;
@property (strong,nonatomic) CBCPCtrl *CBP;
@property (nonatomic) boolean_t wasConnectedBeforBackground;
- (IBAction)scanButtonPress:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *scanButton;
@property (weak, nonatomic) IBOutlet UITextView *dbgText;
- (IBAction)connectButtonPress:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *connectButton;
@property (weak, nonatomic) IBOutlet UIButton *scanServicesButton;
- (IBAction)scanServicesButtonPress:(id)sender;
- (void) applicationDidEnterBackground:(UIApplication *)application;
- (void) applicationDidBecomeActive:(UIApplication *)application;
@property (weak, nonatomic) IBOutlet UIProgressView *RSSIBar;
- (void) updateRSSITimer:(NSTimer *)timer;
@property (strong, nonatomic) IBOutlet UIButton *readCharacteristicButton;
- (IBAction)readCharacteristicButtonClick:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *writeCharacteristicButton;
- (IBAction)writeCharacteristicClick:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *notifyCharacteristicButton;
- (IBAction)notifyCharacteristicButtonClick:(id)sender;
@end
|
Teeerry/simple-clock
|
Source/iic.h
|
#ifndef _iic_h_
#define _iic_h_
#include <reg52.h>
sbit SCL=P2^1;
sbit SDA=P2^0;
void delayus(unsigned char x);
void iic_start(void);
void iic_stop(void);
void iic_ask(bit askbit);
unsigned char iic_waitask(void);
void iic_sendbyte(unsigned char byte);
unsigned char iic_readbyte(void);
void AT2402_SendByte(unsigned char saddr, unsigned char baddr, unsigned char byte);
unsigned char AT2402_ReceiveByte(unsigned char saddr,unsigned char baddr);
#endif
|
Teeerry/simple-clock
|
Source/i2c.h
|
<reponame>Teeerry/simple-clock<gh_stars>1-10
#ifndef __I2C_H_
#define __I2C_H_
#include "reg52.h"
sbit SCL=P2^1;
sbit SDA=P2^0;
void I2cStart();
void I2cStop();
unsigned char I2cSendByte(unsigned char dat);
unsigned char I2cReadByte();
void At24c02Write(unsigned char addr,unsigned char dat);
unsigned char At24c02Read(unsigned char addr);
#endif
|
mmdoogie/auto-lcd-font
|
alf.c
|
#include <stdio.h>
#include <stdlib.h>
#include <ft2build.h>
#include FT_FREETYPE_H
int minChar = 32;
int maxChar = 126;
typedef unsigned char byte;
const char* MARK = "*";
const char* SPACE = " ";
char transpose = 0;
void usage() {
fprintf(stderr, "usage: alf fontfile.ttf fontsize [-t]\n");
fprintf(stderr, "fontsize is desired height in px\n");
fprintf(stderr, "optional -t transposes font for vertical blitting\n");
}
void print_raw_glyph_bmp(FT_Bitmap bmp) {
fprintf(stderr, "Raw glyph size: %d x %d\n", bmp.width, bmp.rows);
for (int y = 0; y < bmp.rows; y++) {
int bpr = bmp.width / 8 + (bmp.width % 8 ? 1 : 0);
int w = 0;
for (int x = 0; x < bpr; x++) {
unsigned char v = bmp.buffer[y * bmp.pitch + x];
for (int i = 0; i < 8; i++) {
printf("%s", (v & 0x80) ? MARK : SPACE);
v = v << 1;
if (++w == bmp.width) break;
}
printf("\n");
}
}
}
void char_bin_for_row(byte* buff, byte* row, int charWidth) {
for (int x = 0; x < charWidth; x++) {
byte* b = buff + (x / 8);
if (x % 8 == 0) *b = 0;
if (x >= charWidth) continue;
if (row[x / 8] & (1 << (7 - (x % 8)))) *b = *b | (1 << (7 - (x % 8)));
}
}
void print_char_bin_bmp(byte* buff, int charWidth) {
for (int x = 0; x < charWidth; x++) {
if (buff[x / 8] & (1 << (7 - (x % 8)))) {
printf("%s", MARK);
} else {
printf("%s", SPACE);
}
}
}
int bytes_for_charWidth(int charWidth) {
return charWidth / 8 + ((charWidth % 8) ? 1 : 0);
}
void print_char_bin_hex(byte* buff, int charWidth, char* sep) {
int byteCount = bytes_for_charWidth(charWidth);
for (int i = 0; i < byteCount; i++) {
printf("0x%02X%s", buff[i], sep);
}
}
void print_char_fontdata(FT_Bitmap bmp, int bmpTop, int cellHeight, int cellBaseline) {
int topRows = cellHeight - bmpTop - cellBaseline;
int charRows = bmp.rows;
int bottomRows = cellHeight - topRows - charRows;
int binSize = bytes_for_charWidth(bmp.width);
byte* buff = malloc(binSize * cellHeight);
for (int y = 0; y < cellHeight; y++) {
if (y < topRows) {
for (int i = 0; i < binSize; i++) buff[y*binSize+i] = 0;
} else if (y < topRows + charRows) {
int cy = y - topRows;
byte* row = bmp.buffer + (cy * bmp.pitch);
char_bin_for_row(buff+y*binSize, row, bmp.width);
} else {
for (int i = 0; i < binSize; i++) buff[y*binSize+i] = 0;
}
}
if (!transpose) {
for (int y = 0; y < cellHeight; y++) {
print_char_bin_hex(buff+y*binSize, bmp.width, ", ");
printf(" //|");
print_char_bin_bmp(buff+y*binSize, bmp.width);
printf("|\n");
}
} else {
int colSize = bytes_for_charWidth(cellHeight);
byte* outBuff = malloc(colSize);
for (int x = 0; x < bmp.width; x++) {
for (int i = 0; i < colSize; i++) outBuff[i] = 0;
for (int y = 0; y < cellHeight; y++) {
if (buff[y*binSize + x/8] & (1 << (7-x%8))) {
outBuff[y/8] += (1 << (y%8));
} else {
}
}
for (int y = 0; y < colSize; y++) {
printf("0x%02x, ", outBuff[y]);
}
printf("\n");
}
}
}
void print_space_fontdata(int charWidth, int cellHeight) {
int binSize = bytes_for_charWidth(charWidth);
byte* buff = malloc(binSize);
for (int y = 0; y < cellHeight; y++) {
for (int i = 0; i < binSize; i++) buff[i] = 0;
print_char_bin_hex(buff, charWidth, ", ");
printf(" //|");
print_char_bin_bmp(buff, charWidth);
printf("|\n");
}
}
int main(int argc, char** argv) {
if (argc < 3 || argc > 4 || ((argc == 4) && strcmp(argv[3], "-t") != 0)) {
usage();
return 1;
}
if (argc == 4) transpose = 1;
int err;
FT_Library lib;
err = FT_Init_FreeType(&lib);
if (err) {
fprintf(stderr, "Error initializing FreeType library!\n");
return 2;
}
char* fn = argv[1];
FT_Face face;
err = FT_New_Face(lib, fn, 0, &face);
if (err) {
fprintf(stderr, "Unable to create FreeType face from %s\n", fn);
return 2;
}
fprintf(stderr, "Font Info: %s\n", fn);
fprintf(stderr, "Number of faces: %d\n", face->num_faces);
fprintf(stderr, "Number of glyphs: %d\n", face->num_glyphs);
fprintf(stderr, "Flags: 0x%04X\n", face->face_flags);
fprintf(stderr, "Fixed Sizes: %d\n", face->num_fixed_sizes);
if (face->num_fixed_sizes) {
for (int i = 0; i < face->num_fixed_sizes; i++) {
fprintf(stderr, " * %dx%d\n", face->available_sizes[i].width, face->available_sizes[i].height);
}
}
int fs = atoi(argv[2]);
err = FT_Set_Pixel_Sizes(face, 0, fs);
if (err) {
fprintf(stderr, "Unable to set size %d for font.\n", fs);
return 2;
}
fprintf(stderr, "\nSet font size to %dpx height\n\n", fs);
fprintf(stderr, "Collecting stats\n");
FT_GlyphSlot slot = face->glyph;
int minTop = 1e6;
int maxBot = -1e6;
int maxWidth = -1e6;
int *charWidths = malloc(sizeof(int) * (maxChar - minChar + 1));
int meanWidth = 0;
for (int c = minChar; c <= maxChar; c++) {
int gidx = FT_Get_Char_Index(face, c);
err = FT_Load_Glyph(face, gidx, 0);
if (err) {
fprintf(stderr, "Unable to load Glpyh %d into slot\n", gidx);
return 2;
}
err = FT_Render_Glyph(slot, FT_RENDER_MODE_MONO);
if (err) {
fprintf(stderr, "Unable to render Glyph %d\n", gidx);
return 2;
}
int charTop = -slot->bitmap_top;
int charBot = -slot->bitmap_top + slot->bitmap.rows;
int charWidth = slot->bitmap.width;
charWidths[c - minChar] = charWidth;
meanWidth += charWidth;
if (charTop < minTop) minTop = charTop;
if (charBot > maxBot) maxBot = charBot;
if (charWidth > maxWidth) maxWidth = charWidth;
}
fprintf(stderr, "Char BB: top %d bot %d\n", minTop, maxBot);
int cellHeight = maxBot - minTop;
meanWidth = meanWidth / (maxChar - minChar + 1);
fprintf(stderr, "Cell Height: %d\nMean Width: %d\n", cellHeight, meanWidth);
fprintf(stderr, "Rendering into fixed-height cell.\n");
if (transpose) fprintf(stderr, "Transposing output.\n");
printf("#include <MonoBitFont.h>\n\n");
printf("extern \"C\" MonoBitFont *NewFont;\n\n");
printf("unsigned char fontData[] = {\n");
int *charOffsets = malloc(sizeof(int) * (maxChar - minChar + 1));
int currOffset = 0;
for (int c = minChar; c <= maxChar; c++) {
int gidx = FT_Get_Char_Index(face, c);
FT_Load_Glyph(face, gidx, 0);
FT_Render_Glyph(slot, FT_RENDER_MODE_MONO);
printf("/* Char %d - '%c' */\n", c, c);
// HACK to fix zero-width space
if (c == 32 && slot->bitmap.width == 0) {
print_space_fontdata(meanWidth, cellHeight);
charWidths[c - minChar] = meanWidth;
charOffsets[c - minChar] = currOffset;
currOffset += bytes_for_charWidth(meanWidth) * cellHeight;
} else {
print_char_fontdata(slot->bitmap, slot->bitmap_top, cellHeight, maxBot);
charOffsets[c - minChar] = currOffset;
currOffset += bytes_for_charWidth(slot->bitmap.width) * cellHeight;
}
}
printf("};\n\n");
printf("unsigned char offsetData[] = {\n");
for (int c = minChar; c <= maxChar; c++) {
printf("0x%04X, ", charOffsets[c - minChar]);
}
printf("\n};\n\n");
printf("unsigned char widthData[] = {\n");
for (int c = minChar; c <= maxChar; c++) {
printf("0x%02X, ", charWidths[c - minChar]);
}
printf("\n};\n\n");
printf("MonoBitFont *NewFont = new MonoBitFont(fontData, offsetData, widthData, %d);\n", cellHeight);
return 0;
}
|
mmdoogie/auto-lcd-font
|
MonoBitFont/MonoBitFont.h
|
#ifndef __mono_bit_font_h
#define __mono_bit_font_h
#include <stdint.h>
class MonoBitFont {
public:
MonoBitFont(uint8_t *fontData, uint8_t charWidth, uint8_t charHeight, uint8_t csOffset = 32, uint8_t csMax = 126);
MonoBitFont(uint8_t *fontData, int *offsetData, uint8_t *widthData, uint8_t charHeight, int8_t spacing = 0, uint8_t csOffset = 32, uint8_t csMax = 127);
~MonoBitFont();
uint8_t getCharWidth(char c);
int getStringWidth(const char *c);
uint8_t getCharHeight();
uint8_t getCharsetOffset();
uint8_t getCharsetMax();
uint8_t *getCharData(char c);
int8_t getExtraSpacing();
void setExtraSpacing(int8_t spacing);
int8_t getSpacing();
protected:
uint8_t *fontData;
int *offsetData;
uint8_t *widthData;
uint8_t charHeight;
uint8_t charsetOffset;
uint8_t charsetMax;
int8_t baseSpacing;
int8_t extraSpacing;
int getCharOffset(char c);
int getCharIndex(char c);
MonoBitFont();
};
#endif
|
iAmVeryQT/jsonchat_bell
|
jsonTest/mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QListWidgetItem>
#include <QMainWindow>
#include <QTcpSocket>
#include <QDialog>
#include <string>
#include <QFile>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void onReceive();//client socket
void on_AddressEdit_textChanged(const QString &arg1); // args
void on_ConnectBtn_clicked(); // 서버연결버튼
void on_TalkEdit_textEdited(const QString &arg1); // args 채팅
void on_TalkEdit_returnPressed();// enter key
void on_UserName_textEdited(const QString &arg1); //args 사용자이름 그대로 받아오기
void on_RoomName_textEdited(const QString &arg1); //args 방번호 그대로 받아오기
void on_SendFile_pressed();
void DownloadBtn(); //신호받기
void on_ImageLoad_clicked(); //이모지 리스트에 넣기
void on_ImageBox_itemClicked(QListWidgetItem *item); //이모지 클릭 -> edit 창으로
private:
Ui::MainWindow *ui;
QTcpSocket soketQt;
QString address;
QString textMessage;
QString name;
QString roomNum;
int FileSize;
QList<QFile*> mFileList;
//QList<QIcon*> mIconLoad; // * 체크
QMap<QIcon,QString> imozyset;
};
#endif // MAINWINDOW_H
|
FStefanni/DFRobot_OzoneSensor
|
DFRobot_OzoneSensor.h
|
<gh_stars>0
/*
MIT License
Copyright (C) <2019> <@DFRobot ZhiXinLiu>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __DFRobot_OzoneSensor_H__
#define __DFRobot_OzoneSensor_H__
#include <Wire.h>
#define ADDRESS_0 0x70 // iic slave Address
#define ADDRESS_1 0x71
#define ADDRESS_2 0x72
#define ADDRESS_3 0x73
#define MEASURE_MODE_AUTOMATIC 0x00 // active mode
#define MEASURE_MODE_PASSIVE 0x01 // passive mode
#define AUTO_READ_DATA 0x00 // auto read ozone data
#define PASSIVE_READ_DATA 0x01 // passive read ozone data
#define MODE_REGISTER 0x03 // mode register
#define SET_PASSIVE_REGISTER 0x04 // read ozone data register
#define AUTO_DATA_HIGE_REGISTER 0x09 // AUTO data high eight bits
#define AUTO_DATA_LOW_REGISTER 0x0A // AUTO data Low eight bits
#define PASS_DATA_HIGE_REGISTER 0x07 // AUTO data high eight bits
#define PASS_DATA_LOW_REGISTER 0x08 // AUTO data Low eight bits
#define OCOUNT 100 // Ozone Count Value
class DFRobot_OzoneSensor{
public:
DFRobot_OzoneSensor(TwoWire & wire = Wire);
~DFRobot_OzoneSensor();
bool begin(uint8_t addr = ADDRESS_0, const bool doBegin = true);
void SetModes(uint8_t Mode);
int16_t ReadOzoneData(uint8_t CollectNum = 20);
private:
void i2cWrite(uint8_t Reg , uint8_t pdata);
int16_t i2cReadOzoneData(uint8_t Reg);
int OzoneData[OCOUNT] = {0x00};
int getAverageNum(int bArray[], int iFilterLen);
TwoWire & _wire;
uint8_t _addr; // IIC Slave number
uint8_t _M_Flag = 0; // Mode flag
};
#endif
|
open-craft/chkrootkit
|
chkdirs.c
|
<gh_stars>0
/* Copyright (C) <NAME> <<EMAIL>> and <NAME>, 2002/11/24
All rights reserved. Permission granted to freely redistribute and update
as long as this Copyright notice is preserved. No warranty expressed or
implied.
$Id: chkdirs.c,v 1.3 2003/01/20 19:44:13 hal Exp $
Usage: chkdirs [-n] dir ...
Examples: chkdirs /
chkdirs -n /proc
Recursively traverses one or more directories looking for discrepancies
between the parent directory link count and the number of subdirectories
(parent directory link count should always equal the number of subdirs
plus two-- anything else indicates a "hidden" directory). "-n" option
means check directory but don't recursively descend into subdirectories.
Changelog :
2002/12/19 - Little port for *BSB and Solaris - <NAME>
2003/01/09 - More fix for Solaris - <NAME>
2003/01/14 - HP-UX patch - <NAME>
2003/01/20 - NAME_MAX Fix by <NAME>
2003/09/01 - BSDI port by <NAME> and <NAME>
2005/22/05 - APPLE test for limits.h included by <NAME>
2007/08/10 - strncpy used instead of strcpy - nm
2007/12/24 - change `c' variable type - NIDE, Naoyuki
2020/12/24 - Add a warning for btrfs (no inode usage)
*/
#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__sun) || defined (hpux) || defined (__bsdi__) || defined (bsdi) || defined (__APPLE__)
#include <limits.h>
#elif defined(__APPLE__) && defined(__MACH__)
#include <sys/syslimits.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#ifndef NAME_MAX
#define NAME_MAX PATH_MAX
#endif
struct dirinfolist {
char dil_name[NAME_MAX+1];
int dil_lc;
struct dirinfolist *dil_next;
};
void usage ()
{
fprintf(stderr, "chkdirs [-n] dir ...\n");
exit(255);
}
char *make_pathname (char *path, char *dir, char **buffer)
{
int plen, pathname_len, bufsize, offs;
bufsize = 0;
plen = strlen(path);
pathname_len = plen + strlen(dir) + 2;
if (!(*buffer) || (sizeof(*buffer) < pathname_len)) {
if (buffer) free((void *)*buffer);
bufsize = (pathname_len > PATH_MAX) ? pathname_len : PATH_MAX;
if (!(*buffer = (char *)malloc(bufsize))) {
return((char *)NULL);
}
}
if (dir[0] == '/') { /* "dir" is absolute pathname, don't prepend "path" */
offs = 0;
}
else {
strncpy(*buffer, path, bufsize);
if ((*buffer)[plen-1] == '/') { /* "path" ends in "/", don't add extra */
offs = plen;
}
else {
(*buffer)[plen] = '/';
offs = plen + 1;
}
}
strncpy((*buffer)+offs, dir, bufsize - offs);
return((*buffer));
}
int check_dir (char *dir, char *path, int linkcount, int norecurse)
{
int diff = -1;
int plen, buflen, numdirs;
char *curpath, *fullpath;
DIR *dirhandle;
struct dirent *finfo;
struct dirinfolist *dl, *dptr;
struct stat statinfo;
/* When called recursively, "path" will be the full path of the cwd,
but when called from main() "path" is empty. We need the cwd path
so we can chdir() back at the end of this routine, as well as when
printing errors and other output.
*/
if (!path || !(plen = strlen(path))) {
buflen = PATH_MAX;
retry:
if (!(curpath = (char *)malloc(buflen))) {
fprintf(stderr, "malloc() failed: %s\n", strerror(errno));
return(-1);
}
if (!getcwd(curpath, buflen)) {
if (errno == ERANGE) {
free((void *)curpath);
buflen = buflen * 2;
goto retry;
}
else {
fprintf(stderr, "getcwd() failed: %s\n", strerror(errno));
return(-1);
}
}
}
else { /* "path" is set, so just copy it into "curpath" */
if (!(curpath = (char *)malloc(plen+1))) {
fprintf(stderr, "malloc() failed: %s\n", strerror(errno));
return(-1);
}
strncpy(curpath, path, plen+1);
}
/* Now set "fullpath" to be the absolute path name of the directory
we will be checking (prepend "curpath" if "dir" is not already an
absolute pathname).
*/
fullpath = (char *)NULL;
if (!make_pathname(curpath, dir, &fullpath)) {
fprintf(stderr, "make_pathname() failed: %s\n", strerror(errno));
free((void *)curpath);
return(-1);
}
if (chdir(dir)) {
fprintf(stderr, "chdir(%s): %s\n", fullpath, strerror(errno));
free((void *)curpath);
free((void *)fullpath);
return(-1);
}
/* Again, "linkcount" (the link count of the current directory) is set
only if check_dir() is called recursively. Otherwise, we need to
stat the directory ourselves.
*/
if (!linkcount) {
if (lstat(".", &statinfo)) {
fprintf(stderr, "lstat(%s): %s\n", fullpath, strerror(errno));
goto abort;
}
linkcount = statinfo.st_nlink;
if (linkcount == 1)
{
fprintf(stderr, "WARNIING: It seems you are using BTRFS, if this is true chkdirs can't help you to find hidden files/dirs\n");
goto abort;
}
}
if (!(dirhandle = opendir("."))) {
fprintf(stderr, "opendir(%s): %s\n", fullpath, strerror(errno));
goto abort;
}
numdirs = 0;
dl = (struct dirinfolist *)NULL;
while ((finfo = readdir(dirhandle))) {
if (!strcmp(finfo->d_name, ".") || !strcmp(finfo->d_name, ".."))
continue;
if (lstat(finfo->d_name, &statinfo)) {
fprintf(stderr, "lstat(%s/%s): %s\n",
fullpath, finfo->d_name, strerror(errno));
closedir(dirhandle);
goto abort;
}
if (S_ISDIR(statinfo.st_mode)) {
numdirs++;
if (norecurse) continue; /* just count subdirs if "-n" */
/* Otherwise, keep a list of all directories found that have link
count > 2 (indicating directory contains subdirectories). We'll
call check_dir() on each of these subdirectories in a moment...
*/
if (statinfo.st_nlink > 2) {
dptr = dl;
if (!(dl = (struct dirinfolist *)malloc(sizeof(struct dirinfolist)))) {
fprintf(stderr, "malloc() failed: %s\n", strerror(errno));
norecurse = 1;
while (dptr) {
dl = dptr->dil_next;
free((void *)dptr);
dptr = dl;
}
continue;
}
strncpy(dl->dil_name, finfo->d_name, sizeof(dl->dil_name));
dl->dil_lc = statinfo.st_nlink;
dl->dil_next = dptr;
}
}
}
closedir(dirhandle);
/* Parent directory link count had better equal #subdirs+2... */
diff = linkcount - numdirs - 2;
if (diff) printf("%d\t%s\n", diff, fullpath);
/* Now check all subdirectories in turn... */
while (dl) {
check_dir(dl->dil_name, fullpath, dl->dil_lc, norecurse);
dptr = dl->dil_next;
free((void *)dl);
dl = dptr;
}
abort:
if (chdir(curpath)) {
fprintf(stderr, "Final chdir(%s) failed (%s) -- EXIT!\n",
curpath, strerror(errno));
exit(255);
}
free((void *)fullpath);
free((void *)curpath);
return(diff);
}
int main (int argc, char **argv)
{
int norecurse = 0;
int i, retval;
int c;
opterr = 0;
while ((c = getopt(argc, argv, "n")) > 0) {
switch (c) {
case 'n':
norecurse = 1;
break;
default:
usage();
}
}
if (argc <= optind) usage();
for (i = optind; i < argc; i++) {
retval = check_dir(argv[i], (char *)NULL, 0, norecurse);
}
exit(retval);
}
|
palerdot/BlingFire
|
blingfireclient.library/inc/FASecurity.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_SECURITY_H_
#define _FA_SECURITY_H_
#ifndef __out_ecount
#define __out_ecount(X)
#endif
#ifndef __out_ecount_opt
#define __out_ecount_opt(X)
#endif
#ifndef __analysis_assume
#define __analysis_assume(X)
#endif
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAGetIWsCA.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_GETIWS_CA_H_
#define _FA_GETIWS_CA_H_
#include "FAConfig.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// client-side interface for getting state's set of defined outgoing arcs
///
class FAGetIWsCA {
public:
/// returns a set of Iws for the given Dfa state
virtual const int GetIWs (
const int State,
__out_ecount_opt (MaxIwCount) int * pIws,
const int MaxIwCount
) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAWRETokenParser.h
|
<filename>blingfirecompile.library/inc/FAWRETokenParser.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WRE_TOKENPARSER_H_
#define _FA_WRE_TOKENPARSER_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FAWREToken;
class FATagSet;
///
/// This class constructs FAWREToken from the input string.
///
class FAWRETokenParser {
public:
FAWRETokenParser (FAAllocatorA * pAlloc);
public:
/// input token text
void SetTokenStr (const char * pTokenStr, const int Len);
/// output parsed WRE token
void SetToken (FAWREToken * pToken);
/// makes the parsing
void Process ();
private:
/// finds the end of what-ever list
inline const char * FindListEnd (const char * pBegin, const char * pEnd) const;
/// makes word list parsing
inline void ParseWordList (const char * pBegin, const char * pEnd);
/// makes dict list parsing
inline void ParseRegexpList (const char * pBegin, const char * pEnd);
/// makes regexp list parsing
inline void ParseDictList (const char * pBegin, const char * pEnd);
/// makes tag list parsing
inline void ParseTagList (const char * pBegin, const char * pEnd);
/// returns true if symbol at Pos is escaped
inline static const bool IsEscaped (const char * pBegin, const int Pos);
private:
/// tagset
const FATagSet * m_pTagSet;
/// token string
const char * m_pTokenStr;
int m_Len;
/// token
FAWREToken * m_pToken;
// known characters
enum {
CharWordListBegin = '"',
CharRegexpListBegin = '\'',
CharDictListBegin = '@',
CharNegative = '!',
CharListDelimier = '/',
CharDictDelimier = '@',
CharDisjunction = '|',
MaxCharSymbol = 255
};
// masks
enum {
WordListBegin = 1,
RegexpListBegin = 2,
DictListBegin = 4,
Negative = 8,
ListDelimiter = 16,
DictDelimiter = 32,
Disjunction = 64
};
/// symbol -> info mapping
FAArray_cont_t < int > m_char2info;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMealyDfa.h
|
<filename>blingfirecompile.library/inc/FAMealyDfa.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MEALYDFA_H_
#define _FA_MEALYDFA_H_
#include "FAConfig.h"
#include "FAMealyDfaA.h"
#include "FAEncoder_pref.h"
#include "FAChain2Num_hash.h"
namespace BlingFire
{
class FARSDfaCA;
///
/// FSM-compile-time interafece for Mealy DFA sigma function.
///
class FAMealyDfa : public FAMealyDfaA {
public:
FAMealyDfa (FAAllocatorA * pAlloc);
virtual ~FAMealyDfa ();
public:
// NOTE: does not return destination state if FARSDfaCA was not setup
const int GetDestOw (const int State, const int Iw, int * pOw) const;
const int GetOw (const int Src, const int Iw) const;
void SetOw (const int Src, const int Iw, const int Ow);
void Prepare ();
void Clear ();
public:
void SetRsDfa (const FARSDfaCA * pRsDfa);
private:
const FARSDfaCA * m_pRsDfa;
FAEncoder_pref m_enc;
FAChain2Num_hash m_arc2ow;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAParsedRegexp2TrBrMaps.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_PARSEDREGEXP2TRBRMAPS_H_
#define _FA_PARSEDREGEXP2TRBRMAPS_H_
#include "FAConfig.h"
#include "FASetUtils.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FARegexpTree;
class FARegexpTree2Funcs;
class FAMultiMapA;
class FAMapA;
///
/// This class builds maps necessary for sub-match extraction.
///
class FAParsedRegexp2TrBrMaps {
public:
FAParsedRegexp2TrBrMaps (FAAllocatorA * pAlloc);
public:
// input regexp tree
void SetRegexpTree (const FARegexpTree * pRegexpTree);
// input regexp functions container
void SetRegexpFuncs (const FARegexpTree2Funcs * pRegexpFuncs);
// sets up input position equivalence classes,
// if NULL all positions are unique
void SetPos2Class (const FAMapA * pPos2Class);
// output, maps regexp position to TrBr array which starts in this position
// (including this position)
void SetStartMap (FAMultiMapA * pStartTrBr);
// output, maps regexp position to TrBr set which ends in this position
// (not including this position)
void SetEndMap (FAMultiMapA * pEndTrBr);
// calculates output maps
void Process ();
private:
inline const int Pos2Class (const int Pos) const;
void Prepare ();
void BuildStartMap ();
void BuildEndMap ();
private:
const FARegexpTree * m_pRegexpTree;
const FARegexpTree2Funcs * m_pRegexpFuncs;
const FAMapA * m_pPos2Class;
FAMultiMapA * m_pStartTrBr;
FAMultiMapA * m_pEndTrBr;
FASetUtils m_sets;
FAArray_cont_t < int > m_pos_arr;
FAArray_cont_t < int > m_node_arr;
int m_MaxPos;
private:
// compares node_ids by offsets
class TTrBrOffsetCmp {
public:
TTrBrOffsetCmp (const FARegexpTree * pRegexpTree);
public:
const bool operator() (const int NodeId1, const int NodeId2) const;
private:
const FARegexpTree * m_pRegexpTree;
};
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FANfas2CommonENfa.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_NFAS2COMMONENFA_H_
#define _FA_NFAS2COMMONENFA_H_
#include "FAConfig.h"
#include "FARSNfa_ar_judy.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FARSNfaA;
///
/// Merges N-nfas together by putting e-transitions to the each one.
/// L(ENfa) = L(Nfa_1) U L(Nfa_2) ... U L(Nfa_N)
///
class FANfas2CommonENfa {
public:
FANfas2CommonENfa (FAAllocatorA * pAlloc);
public:
/// specifies whether to add Nfa num info or not, does not add by default
void SetAddNfaNums (const bool AddNfaNums);
/// specifies the base Iw for the NfaNum information, 0 is used by default
void SetNfaNumBase (const int NfaNumBase);
/// make the resulting automaton empty
void Clear ();
/// specifies the Epsilon symbol
void SetEpsilonIw (const int EpsilonIw);
/// adds one more nfa to the common resulting nfa
void AddNfa (const FARSNfaA * pNfa);
/// makes the result usable
void Process ();
/// returns common nfa
const FARSNfaA * GetCommonNfa () const;
private:
/// copies transitions into the common nfa making renumeration
inline void AddTransitions (const int StateOffset);
/// copies final states making renumeration
inline void AddFinals (const int StateOffset);
/// copies initial states making renumeration and adds epsilon transitions
inline void AddInitials (const int StateOffset);
/// adds Nfa Nums into the common Nfa
inline void AddNfaNums ();
private:
/// true if no automatons has been added yet
bool m_empty;
/// input nfa
const FARSNfaA * m_pInNfa;
/// epsilon transition
int m_EpsilonIw;
/// the resulting automaton
FARSNfa_ar_judy m_common_nfa;
/// temporary storage for states renumeration
FAArray_cont_t < int > m_states;
/// epsilon destination states
FAArray_cont_t < int > m_eps_dst;
///
bool m_AddNfaNums;
int m_NfaNumBase;
/// mapping from the final state num into NfaNum
FAArray_cont_t < int > m_fsnum2nfanum;
/// number of nfas added
int m_NfaCount;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMealyNfaA.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MEALYNFAA_H_
#define _FA_MEALYNFAA_H_
#include "FAConfig.h"
#include "FAMealyNfaCA.h"
namespace BlingFire
{
///
/// FSM-compile-time interafece for Mealy NFA sigma function.
///
class FAMealyNfaA : public FAMealyNfaCA {
public:
/// sets up Ow for the given arc <Src, Iw, Dst>
/// if -1 == Ow then it remove associated (if there was any) Ow
virtual void SetOw (
const int Src,
const int Iw,
const int Dst,
const int Ow
) = 0;
/// have to be called after all transitions have been added
virtual void Prepare () = 0;
/// returns container into the state as if it was just constructed
virtual void Clear () = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FASuffixRules2Chains.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_SUFFIXRULES2CHAINS_H_
#define _FA_SUFFIXRULES2CHAINS_H_
#include "FAConfig.h"
#include "FAMultiMap_ar.h"
#include "FAChain2Num_hash.h"
#include "FAArray_cont_t.h"
#include "FAStr2Utf16.h"
#include <iostream>
namespace BlingFire
{
class FATagSet;
///
/// This class converts suffix rules into a digital chains and extracts rules'
/// right parts into a separate map. If tagset is specified then it converts
/// tag names into corresponding tag values.
///
/// 1.1. Rules syntax (without tags)
/// ...
/// suffix_i --> act_i
/// suffix_{i+1} --> act_{i+1}
/// ...
///
/// 1.2. Rules syntax (with tag or two tags)
/// ...
/// suffix_i --> [FromTag][ToTag]act_i
/// suffix_{i+1} --> [FromTag][ToTag]act_{i+1}
/// ...
/// or
/// ...
/// suffix_i --> [Tag]act_i
/// suffix_{i+1} --> [Tag]act_{i+1}
/// ...
///
/// suffix_i ::= ^<non-empty string>
/// suffix_i ::= <non-empty string>
///
/// act_i ::= -N_i+str_i
/// act_i ::= -N_i
/// N_i ::= <number of letters to trip from the end>
/// str_i ::= <non-empty string>
///
/// The following are valid suffix rules:
///
/// ioned --> [VBD][VB]-1
/// ion --> [VB][VBD]-0+ed
/// cut --> [VB][VBD]-0
/// cut --> [VBD][VB]-0
///
/// 2. Action map is multimap of integers:
/// ...
/// i -> N c_1 ... c_M
/// ...
///
/// c_i, i \in 1..M are unicode (UTF-32) symbols
///
class FASuffixRules2Chains {
public:
FASuffixRules2Chains (FAAllocatorA * pAlloc);
public:
// input text encoding
void SetEncodingName (const char * pInputEnc);
// tag set, if there are tags in rules
void SetTagSet (const FATagSet * pTagSet);
// sets up base value for Keys identifying actions, 0 is used by default
void SetKeyBase (const int KeyBase);
// specifies the number of digitis per value to use in the output
void SetNumSize (const int NumSize);
// if true then it will always insert a 0-delimiter
// otherwise only if '^' is explicitly specified withing a rule
void SetImplicitDelim (const bool ImplicitDelim);
// input stream of rules
void SetRulesIn (std::istream * pIs);
// output stream of regular expression
void SetChainsOut (std::ostream * pOs);
// makes convertion
void Process ();
// returns stored action map
const FAMultiMapA * GetActions () const;
// returns stored Ow -> Freq array
const int GetOw2Freq (const int ** pOw2Freq) const;
private:
// returns object into initial state
void Clear ();
// finds " --> " delimiter
inline const int GetDelimPos () const;
// right part processing
void ParseRight (const int RightPos, const int RightLen);
// left part processing
void ParseLeft (const int LeftPos, const int LeftLen);
// helper method, builds an array of UTF-32 characters from the string
inline void Str2Arr (
const char * pStr,
const int StrLen,
FAArray_cont_t < int > * pArr
);
// helper, parses -N+str chunks
inline void ParseAct (
const char * pRight,
const int RightLen,
int * pCut,
FAArray_cont_t < int > * pArr
);
// maps chain into a unique key
inline const int GetKey (const int * pChain, const int Size);
// make left and right chains ready for output
void PrepareChains ();
// print left part
void PrintLeft () const;
// builds multi-map of actions and Ow --> Freq array
void BuildMap ();
private:
// indicates whether input is in UTF-8
bool m_use_utf8;
// key base
int m_KeyBase;
// number of digits to print
int m_NumSize;
// indicates whether delimiter should always be insterted
bool m_ImplicitDelim;
// input stream
std::istream * m_pIs;
// output stream
std::ostream * m_pOs;
// tagset pointer, can be NULL
const FATagSet * m_pTagSet;
// encodes actions' text
FAStr2Utf16 m_recode;
// actions in the above format
FAMultiMap_ar m_acts;
// keeps set of actions
FAChain2Num_hash m_act2num;
// input string
const char * m_pStr;
int m_StrLen;
// first tag
int m_TagFrom;
// second tag
int m_TagTo;
// cut values
int m_SuffixCut;
int m_PrefixCut;
// chains
FAArray_cont_t < int > m_left_chain;
FAArray_cont_t < int > m_suffix_chain;
FAArray_cont_t < int > m_prefix_chain;
FAArray_cont_t < int > m_right_chain;
// Ow -> Freq array
FAArray_cont_t < int > m_Ow2Freq;
enum { DefNumSize = 5 };
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARSNfa_ro.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_RSNFA_RO_H_
#define _FA_RSNFA_RO_H_
#include "FAConfig.h"
#include "FARSNfaA.h"
#include "FAArray_cont_t.h"
#include "FANfaDelta_ro.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Read-only NFA container.
///
/// Note:
/// 1. Normally the object of this class is supposed to be loaded and used
/// and then cleared and reloaded and so on (but not modified).
/// 2. Transitions should be added in lexicographical order, see
/// FANfaDelta_ro.h for details, FAAutIOTools guarantee that.
///
class FARSNfa_ro : public FARSNfaA {
public:
FARSNfa_ro (FAAllocatorA * pAlloc);
virtual ~FARSNfa_ro ();
public:
const int GetMaxState () const;
const int GetMaxIw () const;
const int GetInitials (const int ** ppStates) const;
const int GetFinals (const int ** ppStates) const;
const bool IsFinal (const int State) const;
const bool IsFinal (const int * pStates, const int Count) const;
const int GetIWs (
const int State,
const int ** ppIws
) const;
const int GetDest (
const int State,
const int Iw,
const int ** ppIwDstStates
) const;
const int GetDest (
const int State,
const int Iw,
int * pDstStates,
const int MaxCount
) const;
public:
void SetMaxState (const int MaxState);
void SetMaxIw (const int MaxIw);
void Create ();
void SetTransition (
const int State,
const int Iw,
const int * pDstStates,
const int Count
);
void SetInitials (const int * pStates, const int Count);
void SetFinals (const int * pStates, const int Count);
void Prepare ();
void Clear ();
private:
void SetTransition (const int FromState, const int Iw, const int DstState);
private:
int m_MaxState;
int m_MaxIw;
FAArray_cont_t < int > m_initials;
FAArray_cont_t < int > m_finals;
FANfaDelta_ro m_delta;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAConfig.h
|
<reponame>palerdot/BlingFire<filename>blingfireclient.library/inc/FAConfig.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_CONFIG_H_
#define _FA_CONFIG_H_
#ifndef NEW
#define NEW new
#endif
#if _MSC_VER < 1400
# ifndef fopen_s
# define fopen_s(ppF,pN,pA) int(0); *ppF = fopen(pN,pA);
# endif
# ifndef _set_fmode
# define _set_fmode(X) _fmode = X;
# endif
#endif
#include <ctype.h>
#include <fcntl.h>
#ifdef BLING_FIRE_MAC
#include <string>
#else
#include <malloc.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <limits.h>
#include <stdint.h>
#include <stddef.h>
#ifndef BLING_FIRE_NOWINDOWS
/// Windows specific
#include <io.h>
#include <windows.h>
#include <process.h>
#else
/// non-Windows specific
#include <unistd.h>
#ifndef _getpid
#define _getpid getpid
#endif
#ifndef _unlink
#define _unlink unlink
#endif
#ifndef __cdecl
#define __cdecl __attribute__((__cdecl__))
#endif
#ifndef ULONG
#define ULONG unsigned long
#endif
#ifndef LONG
#define LONG long
#endif
#ifndef __stdcall
#define __stdcall
#endif
#ifndef HANDLE
#define HANDLE void*
#endif
#include <stdint.h>
/* because we have stdint.h
#ifndef __int32
#define __int32 int32_t
#endif
#ifndef __int16
#define __int16 int16_t
#endif
#ifndef uint16_t
#define uint16_t u_int16_t
#endif
#ifndef uint32_t
#define uint32_t u_int32_t
#endif
#ifndef uint8_t
#define uint8_t u_int8_t
#endif
*/
#ifndef __fallthrough
#define __fallthrough
#endif
#endif
#ifndef PATH_MAX
#define PATH_MAX 32000
#endif
// enable this to track the memory allocations and leaks in BlingFire
/// #define _DEBUG_MEMORY
// no APSDK or Memlfp dependecies
#ifdef BLING_FIRE_NOAP
#ifndef UInt8
#define UInt8 uint8_t
#endif
#undef LogAssert
#undef DebugLogAssert
// Disable conditional expr constant warning
#pragma warning(disable : 4127)
// LogAssert
#include <stdexcept>
#define LogAssert(exp, ...) \
do { \
if (!(exp)) { \
char szMessage[1024]; \
snprintf(szMessage, sizeof(szMessage), \
"%s, %d: assertion failed: %s\n", __FILE__, __LINE__, #exp); \
throw std::runtime_error(szMessage); \
} \
} while (0)
// DebugLogAssert
#include <assert.h>
#define DebugLogAssert assert
#else
#include "LogAssert.h"
#endif // of #ifdef BLING_FIRE_NOAP
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAUnAmbiguous.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_UNAMBIGUOUS_H_
#define _FA_UNAMBIGUOUS_H_
#include "FAConfig.h"
#include "FAChain2Num_hash.h"
#include "FAArray_cont_t.h"
#include "FARSNfa_ar_judy.h"
#include "FAMealyNfa.h"
#include "FARemoveUnreachable.h"
namespace BlingFire
{
class FAAllocatorA;
class FALessA;
///
/// This processor takes ambiguous Mealy NFA and returns unambiguous Mealy NFA
///
/// For example:
///
/// Input NFA(S(('a:1''b:1')|(('a:2'|'p:2')'b:2'))S)
/// S a b S -> S 1 1 S
/// S a b S -> S 2 2 S
/// S p b S -> S 2 2 S
///
/// Output NFA
/// S a b S -> S 1 1 S
/// S p b S -> S 2 2 S
///
/// Note: This algorithm is described in MERL TR-96-13
///
class FAUnAmbiguous {
public:
FAUnAmbiguous (FAAllocatorA * pAlloc);
public:
/// sets up comparison operator, if not set then < operator is used
void SetLess (const FALessA * pLess);
/// sets up input automaton
void SetInMealy (const FARSNfaA * pInNfa, const FAMealyNfaA * pInSigma);
/// makes processing
void Process ();
/// returns output automaton
const FARSNfaA * GetNfa () const;
const FAMealyNfaA * GetSigma () const;
/// returns object into the initial state
void Clear ();
private:
void Prepare ();
inline const int AddState (const int * pXS, const int Size);
inline const int GetXS (const int Q, const int ** ppXS) const;
inline const bool IsInitial (const int State) const;
inline const bool IsFinal (const int State) const;
// returns false if this new state should not be added
const bool CalcNewState (
const int X1,
const int Iw,
const int Y1,
const int Ow1,
const int * pS,
const int SSize,
const int * pDst,
const int Count
);
void PrepareOutNfa ();
void CreateOutNfa ();
void RmUnreach ();
private:
/// input
const FALessA * m_pLess;
const FARSNfaA * m_pInNfa;
const FAMealyNfaA * m_pInSigma;
/// output
FARSNfa_ar_judy m_OutNfa;
FAMealyNfa m_OutSigma;
/// keeps bi-directional mapping Q <--> < X, {S} >, where Q is a new state,
/// X is an old state and {S} is a set of states with a strictly less path
FAChain2Num_hash m_q2xs;
/// max new state stored in m_q2xs
int m_MaxQ;
/// temporary array
FAArray_cont_t < int > m_xs;
FAArray_cont_t < int > m_initials;
FAArray_cont_t < int > m_finals;
/// removes unreachable states
FARemoveUnreachable m_rm;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAActionsArray_static.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ACTIONSARRAY_STATIC_H_
#define _FA_ACTIONSARRAY_STATIC_H_
#include "FAConfig.h"
#include "FAActionsArrayA.h"
namespace BlingFire
{
///
/// Implementation based on static array.
///
class FAActionsArray_static : public FAActionsArrayA {
public:
FAActionsArray_static (const FAActionsA ** pActsArr, const int Count);
virtual ~FAActionsArray_static ();
public:
const int GetStageCount () const;
const FAActionsA * GetStage (const int Num) const;
private:
const FAActionsA ** m_pActsArr;
const int m_Count;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FANfaDelta_ro.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_NFADELTA_RO_H_
#define _FA_NFADELTA_RO_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FAChain2Num_hash.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Constant Delta function of NFA.
///
/// Note: transitions has to be sorted first by State then by Iw!
///
class FANfaDelta_ro {
public:
FANfaDelta_ro (FAAllocatorA * pAlloc);
public:
/// adds transitions
void AddTransition (
const int State,
const int Iw,
const int * pDsts,
const int Count
);
/// returns into the initial state and frees memory
void Clear ();
public:
// returns Iws for the given State
const int GetIWs (
const int State,
const int ** ppIws
) const;
// returns Dsts for the given State, Iw pair
const int GetDest (
const int State,
const int Iw,
const int ** ppDsts
) const;
private:
/// State --> <First, Count>, where First is index in m_IwDstIdx
FAArray_cont_t < int > m_State2FC;
/// two parallel arrays: m_Iws and
/// Iws: [m_Iws [First], ..., m_Iws [First + Count]]
FAArray_cont_t < int > m_Iws;
/// Dsts: [m_Dsts [First], ..., m_Dsts [First + Count]]
/// if m_Dsts [i] >= 0 then
/// Dsts == { m_Dsts [i] } // a set of one element
/// else
/// Dsts == m_Sets [-(m_Dsts [i] + 1)] // a set from m_Sets
FAArray_cont_t < int > m_Dsts;
/// DstIdx <--> DstSet map, keeps only sets of size > 1
FAChain2Num_hash m_Sets;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARSDfa_ar_judy.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_RSDFA_AR_JUDY_H_
#define _FA_RSDFA_AR_JUDY_H_
#include "FAConfig.h"
#include "FARSDfaA.h"
#include "FAArray_cont_t.h"
#include "FABitArray.h"
#include "FAMap_judy.h"
namespace BlingFire
{
class FAAllocatorA;
class FARSDfa_ar_judy : public FARSDfaA {
public:
FARSDfa_ar_judy (FAAllocatorA * pAlloc);
virtual ~FARSDfa_ar_judy ();
// read interface implementation
public:
const int GetMaxState () const;
const int GetMaxIw () const;
const int GetInitial () const;
const int GetFinals (const int ** ppStates) const;
const int GetIWs (const int ** ppIws) const;
const int GetIWs (
__out_ecount_opt (MaxIwCount) int * pIws,
const int MaxIwCount
) const;
const bool IsFinal (const int State) const;
const int GetDest (const int State, const int Iw) const;
// write interface implementation
public:
void SetMaxState (const int MaxState);
void SetMaxIw (const int MaxIw);
void Create ();
void SetInitial (const int State);
void SetFinals (const int * pStates, const int Size);
void SetIWs (const int * pIws, const int IwsCount);
void SetTransition (const int FromState,
const int Iw,
const int DstState);
void SetTransition (const int FromState,
const int * pIws,
const int * pDstStates,
const int Count);
void Prepare ();
void Clear ();
public:
/// adds more states to the automaton,
/// new size is OldSize + StatesCount states
void AddStateCount (const int StatesCount);
/// actually, just increments m_IwCount
/// the new IwCount is old IwCount plus IwCount
void AddIwCount (const int IwCount);
private:
/// creates a new state
void create_state (const int State);
private:
int m_MaxIw;
unsigned int m_StateCount;
int m_initial;
/// q \in m_finals iff q >= m_min_final && q <= m_max_final
int m_min_final;
int m_max_final;
FAArray_cont_t < int > m_finals;
/// alphabet of Iws
FAArray_cont_t < int > m_alphabet;
/// mapping: Iw -> 1 iff Iw \in m_alphabet
FABitArray m_iw2bool;
/// m_state_iw2dst {State -> {Iw -> Dst}},
/// State \in 0, ..., MaxState
FAArray_cont_t < FAMap_judy * > m_state_iw2dst;
FAAllocatorA * m_pAlloc;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAImageDump.h
|
<reponame>palerdot/BlingFire<filename>blingfireclient.library/inc/FAImageDump.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_IMAGEDUMP_H_
#define _FA_IMAGEDUMP_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// Keeps thread sharable data resources
///
class FAImageDump {
public:
FAImageDump ();
~FAImageDump ();
public:
// loads image dump from file, entire file is used as single image
void Load (const char * pFileName, const bool fUseMemMapping = false);
// sets up image dump from the external pointer
void SetImageDump (const unsigned char * pImageDump);
// returns pointer to the image dump
const unsigned char * GetImageDump () const;
private:
// load file into the heap
void FALoadHeap (const char * pFileName);
// frees heap memory
void FAFreeHeap ();
// load file via memory mapped files
void FALoadMm (const char * pFileName);
// returns all memory map related resources back
void FAFreeMm ();
private:
/// pointer to the data
unsigned char * m_pImageDump;
/// true if the memory should be returned to heap
bool m_MustDelete;
/// not 0, if data are loaded thru the memory mapped file
HANDLE m_hFileMapping;
/// true if the memory should be unmapped
bool m_MustUnmap;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARegexpTree2Hash.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_REGEXPTREE2HASH_H_
#define _FA_REGEXPTREE2HASH_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FATopoSort_t.h"
#include "FARegexpTreeTopoGraph.h"
namespace BlingFire
{
class FAAllocatorA;
class FARegexpTree;
///
/// This class calculates hash values for each node of the regular
/// expression tree.
///
class FARegexpTree2Hash {
public:
FARegexpTree2Hash (FAAllocatorA * pAlloc);
public:
// sets up original regular expression text
// offsets from pTree refer to this text
void SetRegexp (const char * pRegexp, const int Length);
// regular expression tree
void SetRegexpTree (FARegexpTree * pTree);
// builds hash values for each node
void Process ();
// returns hash value
const int GetKey (const int NodeId) const;
// updates NodeId's hash value and all the parents
void Update (const int NodeId);
private:
inline const int Node2Key (const int NodeId) const;
inline const int Symbol2Key (const int Offset, const int Length) const;
private:
const char * m_pRegexp;
int m_Length;
FARegexpTree * m_pTree;
// topological sorter
FATopoSort_t < FARegexpTreeTopoGraph > m_sort;
// node -> key
FAArray_cont_t < int > m_node2key;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FATrBrNfa2MealyNfa.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TRBRNFA2MEALYNFA_H_
#define _FA_TRBRNFA2MEALYNFA_H_
#include "FAConfig.h"
#include "FAEpsilonRemoval.h"
#include "FAEpsilonGraph_mealy.h"
#include "FARSNfa_wo_ro.h"
#include "FAMealyNfa.h"
#include "FAArray_cont_t.h"
#include "FAMultiMap_judy.h"
namespace BlingFire
{
class FARSNfaA;
class FAMealyNfaA;
///
/// This class converts triangular bracket RS NFA into Mealy NFA, where
/// output weights represent combinations of openning and closing triangular
/// brackets.
///
/// Note: pInNfa and pOutNfa can point to the same object
///
class FATrBrNfa2MealyNfa {
public:
FATrBrNfa2MealyNfa (FAAllocatorA * pAlloc);
public:
/// sets up base value for triangular bracket transitions
void SetTrBrBaseIw (const int TrBrBaseIw);
/// sets up max value for triangular bracket transitions
void SetTrBrMaxIw (const int TrBrMaxIw);
/// specifies which symbol can be used as Epsilon
void SetEpsilonIw (const int EpsilonIw);
/// sets up Nfa with bracket transitions
void SetInNfa (const FARSNfaA * pInNfa);
/// sets up the output Mealy Nfa
void SetOutNfa (FARSNfaA * pOutNfa, FAMealyNfaA * pOutOws);
/// makes convertion
void Process ();
/// returns Ow -> [TrBr] map
const FAMultiMapA * GetOw2TrBrMap () const;
private:
// returns object into the initial state
inline void Clear ();
// builds epsilon Mealy NFA from RS NFA
inline void BuildEpsilonMealy ();
// removes epsilon transitions
inline void RemoveEpsilons ();
// makes Ows contiguous, based from 0
inline void RemapOws ();
private:
const FARSNfaA * m_pInNfa;
FARSNfaA * m_pOutNfa;
FAMealyNfaA * m_pOutOws;
int m_TrBrBaseIw;
int m_TrBrMaxIw;
int m_EpsilonIw;
/// epsilon removal algorithm
FAEpsilonRemoval m_erm;
/// epsilon graph making concatenation of Ows in output NFA
FAEpsilonGraph_mealy m_g;
/// temporary storage for Mealy E-NFA
FARSNfa_wo_ro m_tmp_nfa;
/// Mealy E-NFA sigma function
FAMealyNfa m_tmp_ows1;
/// Mealy NFA sigma function
FAMealyNfa m_tmp_ows2;
/// temporary array
FAArray_cont_t < int > m_tmp;
/// keeps mapping from Ow -> [Ows]
FAMultiMap_judy m_ow2trbrs;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMergeSets.h
|
<filename>blingfirecompile.library/inc/FAMergeSets.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MERGE_SETS_H_
#define _FA_MERGE_SETS_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Creates a system of non-intersecting sets by merging pairs of sets.
/// Can be used to find connected components.
///
class FAMergeSets {
public:
FAMergeSets (FAAllocatorA * pAlloc);
public:
// makes the object ready, creates Count sets of one element each
void Prepare (const int Count);
// merges two sets by two elements
void Merge (const int e1, const int e2);
// returns set idx for the element e
const int GetSet (const int E);
private:
/// faster m_e2p access
int * m_pE2P;
/// maps e -> p
/// if p > 0 then p is parent index + 1
/// if p <= 0 then e is the root of a set and |p| is a rank value
FAArray_cont_t < int > m_e2p;
/// stack for path compression
FAArray_cont_t < int > m_stack;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARegexp2MinDfa.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_REGEXP2MINDFA_H_
#define _FA_REGEXP2MINDFA_H_
#include "FAConfig.h"
#include "FARSNfaA.h"
#include "FARSDfaA.h"
#include "FARSNfa_wo_ro.h"
#include "FARSDfa_ro.h"
#include "FARSDfa_wo_ro.h"
#include "FARegexp2Nfa.h"
#include "FANfaCreator_char.h"
#include "FAAny2AnyOther_global_t.h"
#include "FANfa2Dfa_t.h"
#include "FADfa2MinDfa_hg_t.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// This class builds Min DFA from the textual regular expression.
///
class FARegexp2MinDfa {
public:
FARegexp2MinDfa (FAAllocatorA * pAlloc);
public:
/// specifies input encoding name, e.g. CP1251, KOI8-R
void SetEncodingName (const char * pEncStr);
/// sets up input regexp text
void SetRegexp (const char * pRegexp, const int Length);
/// makes the construction
void Process ();
/// returns read-only interface to the corresponding Min DFA
const FARSDfaA * GetRsDfa () const;
private:
// Regexp -> NFA
FARegexp2Nfa m_regexp2nfa;
FANfaCreator_char m_nfa_char;
// '.' - expansion
FAAny2AnyOther_global_t < FARSNfaA, FARSNfa_wo_ro > m_dot_exp;
FARSNfa_wo_ro m_nfa;
// NFA -> DFA
FANfa2Dfa_t < FARSNfa_wo_ro, FARSDfa_wo_ro > m_nfa2dfa;
FARSDfa_wo_ro m_dfa;
// DFA -> Min DFA
FADfa2MinDfa_hg_t < FARSDfa_wo_ro, FARSDfa_ro > m_dfa2mindfa;
FARSDfa_ro m_min_dfa;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAParser_triv_t.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_PARSER_TRIV_T_H_
#define _FA_PARSER_TRIV_T_H_
#include "FAConfig.h"
#include "FAParser_base_t.h"
#include "FAState2OwsCA.h"
namespace BlingFire
{
///
/// This parser does not allows nestings at single pass, if there are
/// conflicts it prefers left-most longest constituent, if there are more
/// than one constituent of that kind it takes one with bigger tag value.
///
template < class Ty >
class FAParser_triv_t : public FAParser_base_t < Ty > {
public:
FAParser_triv_t (FAAllocatorA * pAlloc);
~FAParser_triv_t ();
public:
void SetActions (const FAMultiMapCA * pRule2Act);
private:
void Prepare ();
const int UpdateResults (
const int FromPos,
const int ToPos,
const int State
);
const bool ApplyResults ();
private:
/// max left context
int m_MaxLc;
/// mapping From --> < Tag, To > pair
FAArray_cont_t < int > m_From2To;
int * m_pFrom2To;
FAArray_cont_t < int > m_From2Tag;
int * m_pFrom2Tag;
/// mapping From --> span's < From, To >
FAArray_cont_t < int > m_From2SpanFrom;
int * m_pFrom2SpanFrom;
FAArray_cont_t < int > m_From2SpanTo;
int * m_pFrom2SpanTo;
enum {
DefActionSize = 3, // e.g. < Lc, Rc, Tag >
};
typedef FAParser_base_t < Ty > BASE;
};
template < class Ty >
FAParser_triv_t< Ty >::FAParser_triv_t (FAAllocatorA * pAlloc) :
FAParser_base_t < Ty > (pAlloc),
m_MaxLc (0),
m_pFrom2To (NULL),
m_pFrom2Tag (NULL),
m_pFrom2SpanFrom (NULL),
m_pFrom2SpanTo (NULL)
{
m_From2To.SetAllocator (pAlloc);
m_From2To.Create ();
m_From2Tag.SetAllocator (pAlloc);
m_From2Tag.Create ();
m_From2SpanFrom.SetAllocator (pAlloc);
m_From2SpanFrom.Create ();
m_From2SpanTo.SetAllocator (pAlloc);
m_From2SpanTo.Create ();
}
template < class Ty >
FAParser_triv_t< Ty >::~FAParser_triv_t ()
{}
template < class Ty >
void FAParser_triv_t< Ty >::
SetActions (const FAMultiMapCA * pRule2Act)
{
BASE::m_pRule2Act = pRule2Act;
m_MaxLc = 0;
if (BASE::m_pRule2Act) {
/// rule nums are contiguous values starting from 0
int RuleNum = 0;
const int * pAct;
int Size = BASE::m_pRule2Act->Get (RuleNum++, &pAct);
DebugLogAssert (DefActionSize == Size && pAct);
while (-1 != Size) {
const int Lc = *pAct;
if (Lc > m_MaxLc) {
m_MaxLc = Lc;
}
Size = BASE::m_pRule2Act->Get (RuleNum++, &pAct);
DebugLogAssert ((-1 == Size) || (DefActionSize == Size && pAct));
} // of while (-1 != Size) ...
DebugLogAssert (0 <= m_MaxLc);
} // of if (BASE::m_pRule2Act) ...
}
template < class Ty >
void FAParser_triv_t< Ty >::Prepare ()
{
BASE::Prepare ();
DebugLogAssert (m_From2To.size () == m_From2Tag.size ());
const int OldSize = m_From2To.size ();
m_From2To.resize (BASE::m_UpperCount);
m_From2Tag.resize (BASE::m_UpperCount);
m_From2SpanFrom.resize (BASE::m_UpperCount);
m_From2SpanTo.resize (BASE::m_UpperCount);
m_pFrom2To = m_From2To.begin ();
m_pFrom2Tag = m_From2Tag.begin ();
m_pFrom2SpanFrom = m_From2SpanFrom.begin ();
m_pFrom2SpanTo = m_From2SpanTo.begin ();
// initialize, what is necessary
if (OldSize < BASE::m_UpperCount) {
const int IniCount = BASE::m_UpperCount - OldSize;
memset (m_pFrom2To + OldSize, -1, IniCount * sizeof (int));
memset (m_pFrom2Tag + OldSize, -1, IniCount * sizeof (int));
memset (m_pFrom2SpanFrom + OldSize, -1, IniCount * sizeof (int));
memset (m_pFrom2SpanTo + OldSize, -1, IniCount * sizeof (int));
}
// debug check
#ifndef NDEBUG
for (int i = 0; i < BASE::m_UpperCount; ++i) {
DebugLogAssert (-1 == m_From2To [i]);
DebugLogAssert (-1 == m_From2Tag [i]);
DebugLogAssert (-1 == m_From2SpanFrom [i]);
DebugLogAssert (-1 == m_From2SpanTo [i]);
}
#endif
}
template < class Ty >
const int FAParser_triv_t< Ty >::UpdateResults (
const int FromPos,
const int ToPos,
const int State
)
{
DebugLogAssert (BASE::m_pState2Rules);
DebugLogAssert (m_From2To.begin () == m_pFrom2To);
DebugLogAssert (m_From2Tag.begin () == m_pFrom2Tag);
DebugLogAssert (m_From2SpanFrom.begin () == m_pFrom2SpanFrom);
DebugLogAssert (m_From2SpanTo.begin () == m_pFrom2SpanTo);
DebugLogAssert (m_From2To.size () == m_From2Tag.size ());
DebugLogAssert (m_From2SpanFrom.size () == m_From2Tag.size ());
DebugLogAssert (m_From2SpanTo.size () == m_From2Tag.size ());
DebugLogAssert ((unsigned int) BASE::m_UpperCount <= m_From2To.size ());
bool NoLc = true;
const int Count = BASE::m_pState2Rules->GetOws \
(State, BASE::m_pRules, BASE::m_MaxRulesSize);
DebugLogAssert (0 < Count && Count <= BASE::m_MaxRulesSize);
const int * pAct;
for (int i = 0; i < Count; ++i) {
const int RuleNum = BASE::m_pRules [i];
#ifndef NDEBUG
const int ActSize =
#endif
BASE::m_pRule2Act->Get (RuleNum, &pAct);
DebugLogAssert (DefActionSize == ActSize && pAct);
if (0 != pAct [0]) {
NoLc = false;
}
// += Left Context Size
int From2 = FromPos + pAct [0];
if (0 > From2) {
From2 = 0; // due to the included left anchor
}
// -= Right Context Size
int To2 = ToPos - pAct [1];
if (To2 >= BASE::m_UpperCount) {
To2 = BASE::m_UpperCount - 1; // due to the included right anchor
}
// get action Tag
const int Tag = pAct [2];
DebugLogAssert (0 <= From2 && 0 <= To2 && From2 <= To2);
DebugLogAssert (FALimits::MinTag <= Tag && FALimits::MaxTag >= Tag);
const int LastTo2 = m_pFrom2To [From2];
const int LastSpanFrom = m_pFrom2SpanFrom [From2];
const int LastSpanTo = m_pFrom2SpanTo [From2];
// due to FromPos never decreases from call to call
DebugLogAssert (!(To2 == LastTo2 && FromPos < LastSpanFrom));
if (To2 > LastTo2) {
m_pFrom2Tag [From2] = Tag;
m_pFrom2To [From2] = To2;
m_pFrom2SpanFrom [From2] = FromPos;
m_pFrom2SpanTo [From2] = ToPos;
} else if (To2 == LastTo2 && FromPos == LastSpanFrom) {
if (ToPos > LastSpanTo) {
m_pFrom2Tag [From2] = Tag;
m_pFrom2SpanTo [From2] = ToPos;
} else if (ToPos == LastSpanTo && Tag > m_pFrom2Tag [From2]) {
m_pFrom2Tag [From2] = Tag;
}
}
} // of for (int i = 0; ...
// see whether it is possible to skip something
if (NoLc) {
const int MaxTo = m_pFrom2To [FromPos];
const int NextPos = MaxTo - m_MaxLc;
if (NextPos > FromPos) {
return NextPos;
}
}
return FromPos;
}
template < class Ty >
const bool FAParser_triv_t< Ty >::ApplyResults ()
{
DebugLogAssert (m_From2To.begin () == m_pFrom2To);
DebugLogAssert (m_From2Tag.begin () == m_pFrom2Tag);
DebugLogAssert (m_From2SpanFrom.begin () == m_pFrom2SpanFrom);
DebugLogAssert (m_From2SpanTo.begin () == m_pFrom2SpanTo);
DebugLogAssert (m_From2To.size () == m_From2Tag.size ());
DebugLogAssert (m_From2SpanFrom.size () == m_From2Tag.size ());
DebugLogAssert (m_From2SpanTo.size () == m_From2Tag.size ());
DebugLogAssert ((unsigned int) BASE::m_UpperCount <= m_From2To.size ());
bool ResFound = false;
for (int From = 0; From < BASE::m_UpperCount; ++From) {
DebugLogAssert (-1 != m_pFrom2To [From] || -1 == m_pFrom2Tag [From]);
const int To = m_pFrom2To [From];
if (-1 != To) {
DebugLogAssert (To >= From);
const int Tag = m_pFrom2Tag [From];
DebugLogAssert (FALimits::MinTag <= Tag && FALimits::MaxTag >= Tag);
BASE::m_pTree->AddNode (-Tag, From, To);
From = To;
ResFound = true;
}
}
if (ResFound) {
const int Count = BASE::m_UpperCount * sizeof (int);
memset (m_pFrom2To, -1, Count);
memset (m_pFrom2Tag, -1, Count);
memset (m_pFrom2SpanFrom, -1, Count);
memset (m_pFrom2SpanTo, -1, Count);
}
return ResFound;
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FACalcMealy2.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_CALCMEALY2_H_
#define _FA_CALCMEALY2_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FARSNfa_wo_ro.h"
#include "FARSNfa2RevNfa.h"
#include "FAMealyNfa.h"
#include <set>
namespace BlingFire
{
class FARSDfaA;
class FAMealyDfaA;
///
/// This class is a helper for the FAMealyNfa2Dfa converter, it builds
/// the second component of the decomposition. Don't use this class directly.
///
class FACalcMealy2 {
public:
FACalcMealy2 (FAAllocatorA * pAlloc);
public:
/// sets up reversed RS NFA
void SetInNfa (const FARSNfaA * pInRevNfa);
/// sets up sigma function of the original automaton
void SetSigma (const FAMealyNfaA * pOrigSigma);
/// sets up first component of the cascade
void SetMealy1 (const FARSDfaA * pInDfa, const FAMealyDfaA * pInSigma);
/// calculates RS component of the Mealy NFA/DFA 2
/// Note: Sigma function is left original, as output RS DFA has exactly
/// the same states as input Mealy NFA
void Process ();
/// returns RS component of the Mealy NFA/DFA 2
const FARSNfaA * GetOutNfa () const;
const FAMealyNfaA * GetSigma () const;
/// returns object into the initial state
void Clear ();
private:
inline void Prepare ();
inline void EnqueueInitials ();
inline void SubstNfa ();
inline void Reverse ();
private:
const FARSNfaA * m_pInRevNfa;
const FAMealyNfaA * m_pOrigSigma;
const FARSDfaA * m_pInDfa;
const FAMealyDfaA * m_pInSigma;
// stack
FAArray_cont_t < int > m_s;
std::set < std::pair < int, int > > m_P;
// reversed automaton with substituted inputs
FARSNfa_wo_ro m_tmp_out;
// reversing algorithm
FARSNfa2RevNfa m_rev;
// direct automaton with substituted inputs
FARSNfa_wo_ro m_OutNfa;
FAMealyNfa m_OutSigma;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAParser_base_t.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_PARSER_BASE_T_H_
#define _FA_PARSER_BASE_T_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FARSDfaCA.h"
#include "FAState2OwsCA.h"
#include "FAParseTreeA.h"
#include "FAFsmConst.h"
#include "FALimits.h"
#include "FADigitizer_t.h"
#include "FADigitizer_dct_t.h"
namespace BlingFire
{
class FAState2OwCA;
class FAAllocatorA;
///
/// This class keeps common functionality for Moore-WRE rules based parser.
/// (see FAParser2WRE.h for syntax description)
///
template < class Ty >
class FAParser_base_t {
public:
FAParser_base_t (FAAllocatorA * pAlloc);
virtual ~FAParser_base_t ();
public:
/// sets up rules automaton
virtual void SetRules (
const FARSDfaCA * pRulesDfa,
const FAState2OwsCA * pState2Rules
);
/// sets up RuleNum -> Action mapping
virtual void SetActions (const FAMultiMapCA * pRule2Act);
/// sets up text digitizer, if needed
virtual void SetDigitizer (
const FARSDfaCA * pDfa,
const FAState2OwCA * pState2Ow
);
/// sets up dictionary digitizer, if needed
virtual void SetDctDigitizer (
const FADictInterpreter_t <Ty> * pTagDict,
const FAArrayCA * pSetId2Ow
);
/// this flag is passed to the text digitizer
virtual void SetIgnoreCase (const bool IgnoreCase);
/// sets up WRE token type (a bitwise combination of WRE_TT_* constants)
virtual void SetTokenType (const int TokenType);
/// sets up base value for tag output weights
virtual void SetTagOwBase (const int TagOwBase);
/// sets up maximum amount of passes
virtual void SetMaxPassCount (const int MaxPassCount);
/// sets up output tree container
virtual void SetParseTree (FAParseTreeA * pTree);
/// sets up whether parser should resume from preexisting tree
virtual void SetResume (const bool Resume);
/// specifies a custom initial state
virtual void SetCustomInitial (const int State);
public:
/// adds next word, all options should already be setup
void AddWord (
const Ty * pText, // word text
const int TextLen, // word text length
const int Tag, // POS tag (after disambiguation)
const int DctSetId = -1 // tag dictionary id for the given word
);
/// makes parsing
void Process ();
private:
/// makes a lookup by a label at position i
inline const int GetNextState (int State, const int i) const;
/// finds all rule matches
inline void FindResults ();
protected:
/// makes parser ready to work
/// (called before parsing started)
virtual void Prepare ();
/// returns parser into initial state
/// (called after parsing stoped)
virtual void Clear ();
/// updates results storage and returns position to continue from,
/// normally it should be the same position as FromPos
/// (called several times per pass each time the final state is found)
virtual const int UpdateResults (
const int FromPos,
const int ToPos,
const int State
) = 0;
/// applies all the results from a given pass to the tree
/// returns true if parser should attempt one more pass
/// or false to stop parsing
/// (called each time current pass if finished)
virtual const bool ApplyResults () = 0;
protected:
/// rules automaton
const FARSDfaCA * m_pRulesDfa;
const FAState2OwsCA * m_pState2Rules;
/// RuleNum -> Act mapping
const FAMultiMapCA * m_pRule2Act;
/// output tree
FAParseTreeA * m_pTree;
/// maximum amount of parsing iterations
int m_MaxPassCount;
/// tag Ow base
int m_TagOwBase;
/// WRE token type
int m_TokenType;
/// upper level count
int m_UpperCount;
/// upper labels
const int * m_pLabels;
/// resume flag
bool m_Resume;
/// custom initial state, -1 if not used
int m_CustomInitial;
/// text digitizer
FADigitizer_t < Ty > m_w2ow;
/// dict digitizer
FADigitizer_dct_t < Ty > m_w2ow_dct;
/// text digitizer output weights
FAArray_cont_t < int > m_i2ow_txt;
const int * m_pI2Ow_txt;
/// tag "digitizer" output weights
FAArray_cont_t < int > m_i2ow_tag;
const int * m_pI2Ow_tag;
/// dict "digitizer" output weights
FAArray_cont_t < int > m_i2ow_dct;
const int * m_pI2Ow_dct;
/// rule nums storage
FAArray_cont_t < int > m_Rules;
int * m_pRules;
int m_MaxRulesSize;
enum {
DefMaxPassCount = 1,
};
};
template < class Ty >
FAParser_base_t< Ty >::FAParser_base_t (FAAllocatorA * pAlloc) :
m_pRulesDfa (NULL),
m_pState2Rules (NULL),
m_pRule2Act (NULL),
m_pTree (NULL),
m_MaxPassCount (DefMaxPassCount),
m_TagOwBase (FAFsmConst::IW_EPSILON + 1),
m_TokenType (FAFsmConst::WRE_TT_DEFAULT),
m_UpperCount (0),
m_pLabels (NULL),
m_Resume (false),
m_CustomInitial (-1),
m_pI2Ow_txt (NULL),
m_pI2Ow_tag (NULL),
m_pI2Ow_dct (NULL),
m_pRules (NULL),
m_MaxRulesSize (0)
{
m_w2ow.SetAnyIw (FAFsmConst::IW_ANY);
m_w2ow.SetAnyOw (FAFsmConst::IW_ANY);
m_w2ow_dct.SetAnyOw (FAFsmConst::IW_ANY);
m_i2ow_txt.SetAllocator (pAlloc);
m_i2ow_txt.Create ();
m_i2ow_tag.SetAllocator (pAlloc);
m_i2ow_tag.Create ();
m_i2ow_dct.SetAllocator (pAlloc);
m_i2ow_dct.Create ();
m_Rules.SetAllocator (pAlloc);
m_Rules.Create ();
}
template < class Ty >
FAParser_base_t< Ty >::~FAParser_base_t ()
{}
template < class Ty >
void FAParser_base_t< Ty >::
SetRules (
const FARSDfaCA * pRulesDfa,
const FAState2OwsCA * pState2Rules
)
{
m_pRulesDfa = pRulesDfa;
m_pState2Rules = pState2Rules;
if (m_pState2Rules) {
m_MaxRulesSize = m_pState2Rules->GetMaxOwsCount ();
m_Rules.resize (m_MaxRulesSize);
m_pRules = m_Rules.begin ();
}
}
template < class Ty >
void FAParser_base_t< Ty >::SetActions (const FAMultiMapCA * pRule2Act)
{
m_pRule2Act = pRule2Act;
}
template < class Ty >
void FAParser_base_t< Ty >::SetDigitizer (
const FARSDfaCA * pDfa,
const FAState2OwCA * pState2Ow
)
{
m_w2ow.SetRsDfa (pDfa);
m_w2ow.SetState2Ow (pState2Ow);
if (pDfa && pState2Ow) {
m_w2ow.Prepare ();
}
}
template < class Ty >
void FAParser_base_t< Ty >::
SetDctDigitizer (
const FADictInterpreter_t <Ty> * pTagDict,
const FAArrayCA * pSetId2Ow
)
{
m_w2ow_dct.SetTagDict (pTagDict);
m_w2ow_dct.SetSet2Ow (pSetId2Ow);
}
template < class Ty >
void FAParser_base_t< Ty >::SetIgnoreCase (const bool IgnoreCase)
{
m_w2ow.SetIgnoreCase (IgnoreCase);
}
template < class Ty >
void FAParser_base_t< Ty >::SetTokenType (const int TokenType)
{
DebugLogAssert (TokenType & FAFsmConst::WRE_TT_TEXT || \
TokenType & FAFsmConst::WRE_TT_TAGS || \
TokenType & FAFsmConst::WRE_TT_DCTS);
m_TokenType = TokenType;
}
template < class Ty >
void FAParser_base_t< Ty >::SetTagOwBase (const int TagOwBase)
{
DebugLogAssert (0 <= TagOwBase);
m_TagOwBase = TagOwBase;
}
template < class Ty >
void FAParser_base_t< Ty >::SetMaxPassCount (const int MaxPassCount)
{
DebugLogAssert (0 < MaxPassCount);
m_MaxPassCount = MaxPassCount;
}
template < class Ty >
void FAParser_base_t< Ty >::SetParseTree (FAParseTreeA * pTree)
{
DebugLogAssert (pTree);
m_pTree = pTree;
}
template < class Ty >
void FAParser_base_t< Ty >::SetResume (const bool Resume)
{
m_Resume = Resume;
}
template < class Ty >
void FAParser_base_t< Ty >::SetCustomInitial (const int State)
{
m_CustomInitial = State;
}
template < class Ty >
void FAParser_base_t< Ty >::AddWord (
const Ty * pText,
const int TextLen,
const int Tag,
const int DctSetId
)
{
DebugLogAssert (FALimits::MinTag <= Tag && FALimits::MaxTag >= Tag);
int Ow;
if (FAFsmConst::WRE_TT_TEXT & m_TokenType) {
DebugLogAssert (pText && 0 < TextLen);
Ow = m_w2ow.Process (pText, TextLen);
m_i2ow_txt.push_back (Ow);
}
if (FAFsmConst::WRE_TT_TAGS & m_TokenType) {
DebugLogAssert (0 < Tag);
Ow = Tag + m_TagOwBase;
m_i2ow_tag.push_back (Ow);
}
if (FAFsmConst::WRE_TT_DCTS & m_TokenType) {
DebugLogAssert (pText && 0 < TextLen);
if (-1 == DctSetId) {
Ow = m_w2ow_dct.Process (pText, TextLen);
} else {
Ow = m_w2ow_dct.Process (DctSetId);
}
m_i2ow_dct.push_back (Ow);
}
m_UpperCount++;
}
template < class Ty >
inline const int FAParser_base_t< Ty >::
GetNextState (int State, const int i) const
{
DebugLogAssert (m_pLabels && m_pRulesDfa && \
m_pI2Ow_txt && m_pI2Ow_tag && m_pI2Ow_dct);
int Iw;
// this is normal symbol
if (0 <= i && i < m_UpperCount) {
const int L = m_pLabels [i];
if (FAFsmConst::WRE_TT_TEXT & m_TokenType && -1 != State) {
if (0 <= L) {
DebugLogAssert ((unsigned int) L < m_i2ow_txt.size ());
Iw = m_pI2Ow_txt [L];
} else {
Iw = FAFsmConst::IW_ANY;
}
State = m_pRulesDfa->GetDest (State, Iw);
}
if (FAFsmConst::WRE_TT_TAGS & m_TokenType && -1 != State) {
if (0 <= L) {
DebugLogAssert ((unsigned int) L < m_i2ow_tag.size ());
Iw = m_pI2Ow_tag [L];
} else {
Iw = m_TagOwBase - L;
}
State = m_pRulesDfa->GetDest (State, Iw);
}
if (FAFsmConst::WRE_TT_DCTS & m_TokenType && -1 != State) {
if (0 <= L) {
DebugLogAssert ((unsigned int) L < m_i2ow_dct.size ());
Iw = m_pI2Ow_dct [L];
} else {
Iw = FAFsmConst::IW_ANY;
}
State = m_pRulesDfa->GetDest (State, Iw);
}
// process the left anchor
} else if (-1 == i) {
if (FAFsmConst::WRE_TT_TEXT & m_TokenType && -1 != State) {
State = m_pRulesDfa->GetDest (State, FAFsmConst::IW_L_ANCHOR);
}
if (FAFsmConst::WRE_TT_TAGS & m_TokenType && -1 != State) {
State = m_pRulesDfa->GetDest (State, FAFsmConst::IW_L_ANCHOR);
}
if (FAFsmConst::WRE_TT_DCTS & m_TokenType && -1 != State) {
State = m_pRulesDfa->GetDest (State, FAFsmConst::IW_L_ANCHOR);
}
// process the right anchor
} else {
DebugLogAssert (m_UpperCount == i);
if (FAFsmConst::WRE_TT_TEXT & m_TokenType && -1 != State) {
State = m_pRulesDfa->GetDest (State, FAFsmConst::IW_R_ANCHOR);
}
if (FAFsmConst::WRE_TT_TAGS & m_TokenType && -1 != State) {
State = m_pRulesDfa->GetDest (State, FAFsmConst::IW_R_ANCHOR);
}
if (FAFsmConst::WRE_TT_DCTS & m_TokenType && -1 != State) {
State = m_pRulesDfa->GetDest (State, FAFsmConst::IW_R_ANCHOR);
}
}
return State;
}
template < class Ty >
inline void FAParser_base_t< Ty >::FindResults ()
{
DebugLogAssert (m_pRulesDfa);
int State;
// update input labels
m_UpperCount = m_pTree->GetUpperLabels (&m_pLabels);
// save the initial state
const int InitialState = -1 == m_CustomInitial ? \
m_pRulesDfa->GetInitial () : m_CustomInitial;
// -1 to include the left anchor
for (int j = -1; j < m_UpperCount; ++j) {
State = InitialState;
const int FromPos = j;
// <= to include the right anchor
for (int i = FromPos; i <= m_UpperCount; ++i) {
// lookup the next state
State = GetNextState (State, i);
if (-1 == State)
break;
if (m_pRulesDfa->IsFinal (State)) {
const int Ji = UpdateResults (FromPos, i, State);
if (Ji > j) {
j = Ji;
}
}
} // of for (int i = 0; ...
} // of for (int j = 0; ...
}
template < class Ty >
void FAParser_base_t< Ty >::Clear ()
{
m_i2ow_txt.resize (0);
m_i2ow_tag.resize (0);
m_i2ow_dct.resize (0);
m_UpperCount = 0;
m_pLabels = NULL;
}
template < class Ty >
void FAParser_base_t< Ty >::Prepare ()
{
// update fast access pointers
m_pI2Ow_txt = m_i2ow_txt.begin ();
m_pI2Ow_tag = m_i2ow_tag.begin ();
m_pI2Ow_dct = m_i2ow_dct.begin ();
// create an empty tree, if needed
if (!m_Resume) {
m_pTree->Init (m_UpperCount);
}
}
template < class Ty >
void FAParser_base_t< Ty >::Process ()
{
Prepare ();
bool Continue = true;
int PassCount = 0;
while (Continue && ++PassCount <= m_MaxPassCount) {
FindResults ();
Continue = ApplyResults ();
m_pTree->Update ();
}
Clear ();
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FACorpusIOTools_utf8.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_CORPUSIOTOOLS_UTF8_H_
#define _FA_CORPUSIOTOOLS_UTF8_H_
#include "FAConfig.h"
#include <iostream>
namespace BlingFire
{
class FAAllocatorA;
class FATaggedTextA;
class FATaggedTextCA;
class FAParseTreeA;
class FATagSet;
///
/// Reads/Writes different objects from textual representation.
///
class FACorpusIOTools_utf8 {
public:
FACorpusIOTools_utf8 (FAAllocatorA * pAlloc);
public:
/// sets up tagset for both tree nodes and words
void SetTagSet (const FATagSet * pTagSet);
/// specifies whether words don't have POS tags
void SetNoPosTags (const bool NoPosTags);
public:
// reads tagged text object
void Read (
std::istream& is,
FATaggedTextA * pS
) const;
// writes tagged text object
void Print (
std::ostream& os,
const FATaggedTextCA * pS
) const;
// reads parsed text object
void Read (
std::istream& is,
FATaggedTextA * pS,
FAParseTreeA * pT
) const;
// writes parsed text object
void Print (
std::ostream& os,
const FATaggedTextCA * pS,
const FAParseTreeA * pT
) const;
private:
FAAllocatorA * m_pAlloc;
const FATagSet * m_pTagSet;
bool m_NoPosTags;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAutInterpretTools_trbr_t.h
|
<filename>blingfirecompile.library/inc/FAAutInterpretTools_trbr_t.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_AUTINTERPRETTOOLS_TRBR_T_H_
#define _FA_AUTINTERPRETTOOLS_TRBR_T_H_
#include "FAConfig.h"
#include "FAAutInterpretTools_pos_t.h"
#include "FAArray_cont_t.h"
#include "FAMultiMapCA.h"
#include "FABrResultA.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// This class idendifies correspondence between positions of _matched_ text
/// and triangular brackets from the regular expression.
///
template < class Ty >
class FAAutInterpretTools_trbr_t : public FAAutInterpretTools_pos_t < Ty > {
public:
FAAutInterpretTools_trbr_t (FAAllocatorA * pAlloc);
public:
/// sets up brackets beginning map
void SetPos2BrBegin (const FAMultiMapCA * pPos2BrBegin);
/// sets up brackets ending map
void SetPos2BrEnd (const FAMultiMapCA * pPos2BrEnd);
public:
/// if the input chain is accepted by the automaton then
/// returns true and a fills in bracket results else returns false.
const bool Chain2BrRes (const Ty * pInChain,
const int Size,
FABrResultA * pBrRes);
/// the same as above but works with locally expanded Any symbols in DFA
const bool Chain2BrRes_local (const Ty * pInChain,
const int Size,
FABrResultA * pBrRes);
private:
/// returns true if BrId ends before Pos
inline const bool Ends (const int BrId, const int Pos) const;
/// extracts brackets
inline void ExtractBrackets (
const int * pPosChain,
const int Size,
FABrResultA * pBrRes
);
private:
const FAMultiMapCA * m_pPos2BrBegin;
const FAMultiMapCA * m_pPos2BrEnd;
FAArray_cont_t < int > m_pos_chain;
FAArray_cont_t < int > m_br_pos_stack;
};
template < class Ty >
FAAutInterpretTools_trbr_t< Ty >::
FAAutInterpretTools_trbr_t (FAAllocatorA * pAlloc) :
FAAutInterpretTools_pos_t < Ty > (pAlloc),
m_pPos2BrBegin (NULL),
m_pPos2BrEnd (NULL)
{
m_pos_chain.SetAllocator (pAlloc);
m_pos_chain.Create ();
m_br_pos_stack.SetAllocator (pAlloc);
m_br_pos_stack.Create ();
}
template < class Ty >
void FAAutInterpretTools_trbr_t< Ty >::
SetPos2BrBegin (const FAMultiMapCA * pPos2BrBegin)
{
m_pPos2BrBegin = pPos2BrBegin;
}
template < class Ty >
void FAAutInterpretTools_trbr_t< Ty >::
SetPos2BrEnd (const FAMultiMapCA * pPos2BrEnd)
{
m_pPos2BrEnd = pPos2BrEnd;
}
template < class Ty >
const bool FAAutInterpretTools_trbr_t< Ty >::
Ends (const int BrId, const int Pos) const
{
DebugLogAssert (m_pPos2BrEnd);
const int * pBrs;
const int BrCount = m_pPos2BrEnd->Get (Pos, &pBrs);
if (0 < BrCount)
return (-1 != FAFind_log (pBrs, BrCount, BrId));
else
return false;
}
template < class Ty >
inline void FAAutInterpretTools_trbr_t< Ty >::
ExtractBrackets (const int * pPosChain, const int Size, FABrResultA * pBrRes)
{
DebugLogAssert (pBrRes);
int i, TopPos;
int TopBr = -1;
int StackSize = 0;
m_br_pos_stack.resize (0);
for (i = 0; i < Size; ++i) {
const int Pos = pPosChain [i];
if (0 < StackSize) {
// see whether we can close any opened brackets
TopBr = m_br_pos_stack [StackSize - 1];
while (Ends (TopBr, Pos)) {
TopPos = m_br_pos_stack [StackSize - 2];
pBrRes->AddRes (TopBr, TopPos, i - 1);
m_br_pos_stack.pop_back ();
m_br_pos_stack.pop_back ();
StackSize -= 2;
if (0 != StackSize) {
TopBr = m_br_pos_stack [StackSize - 1];
} else {
TopBr = -1;
break;
}
} // of while (Ends (TopBr, Pos)) ...
} // of if (0 < StackSize) ...
const int * pBrBegin;
const int BrBeginCount = m_pPos2BrBegin->Get (Pos, &pBrBegin);
if (0 < BrBeginCount) {
DebugLogAssert (pBrBegin);
for (int j = 0; j < BrBeginCount; ++j) {
const int Br = pBrBegin [j];
if (Br != TopBr) {
m_br_pos_stack.push_back (i);
m_br_pos_stack.push_back (Br);
StackSize += 2;
}
} // of for (int j = 0; ...
} // of if (0 < BrBeginCount) ...
} // of for (int i = 0; ...
while (0 < StackSize) {
TopBr = m_br_pos_stack [StackSize - 1];
TopPos = m_br_pos_stack [StackSize - 2];
pBrRes->AddRes (TopBr, TopPos, i - 1);
m_br_pos_stack.pop_back ();
m_br_pos_stack.pop_back ();
StackSize -= 2;
}
DebugLogAssert (0 == StackSize);
}
template < class Ty >
const bool FAAutInterpretTools_trbr_t< Ty >::
Chain2BrRes (
const Ty * pInChain,
const int Size,
FABrResultA * pBrRes
)
{
DebugLogAssert (0 < Size && pInChain);
DebugLogAssert (pBrRes);
m_pos_chain.resize (Size);
int * pPosChain = m_pos_chain.begin ();
if (true == this->Chain2PosChain (pInChain, pPosChain, Size)) {
ExtractBrackets (pPosChain, Size, pBrRes);
return true;
} else {
return false;
}
}
template < class Ty >
const bool FAAutInterpretTools_trbr_t< Ty >::
Chain2BrRes_local (
const Ty * pInChain,
const int Size,
FABrResultA * pBrRes
)
{
DebugLogAssert (0 < Size && pInChain);
DebugLogAssert (pBrRes);
m_pos_chain.resize (Size);
int * pPosChain = m_pos_chain.begin ();
if (true == Chain2PosChain_local (pInChain, pPosChain, Size)) {
ExtractBrackets (pPosChain, Size, pBrRes);
return true;
} else {
return false;
}
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/blingfire-compile_src_pch.h
|
<reponame>palerdot/BlingFire
#pragma once
#include "FAConfig.h"
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARegexpLexer_triv.h
|
<filename>blingfirecompile.library/inc/FARegexpLexer_triv.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_REGEXPLEXER_TRIV_H_
#define _FA_REGEXPLEXER_TRIV_H_
#include "FAConfig.h"
#include "FARegexpLexerA.h"
namespace BlingFire
{
///
/// The lexer assumes that the input is the combination of the following:
///
/// 1. space or '\n' separated non-negative numbers: /[0-9]+/
/// 2. and following special symbols: /[.*+?|)(}{^$]\]\[/
///
/// The following expression is correct:
/// (10|23|234)? 234 234*
///
class FARegexpLexer_triv : public FARegexpLexerA {
public:
FARegexpLexer_triv ();
virtual ~FARegexpLexer_triv ();
public:
void SetRegexp (const char * pRegexp, const int Length);
void SetTokens (FAArray_cont_t < FAToken > * pTokens);
void Process ();
protected:
/// returns token's type and length at position Pos
/// or -1 if not identified
virtual const int FindToken (const int Pos, int * pLength) const;
/// returns true if symbol at position Pos is escaped
const bool IsEscaped (const int Pos) const;
/// returns true, if C is a special symbol
const bool IsSpecial (const char C) const;
/// returns true if C can be a part of hex number
const bool IsHex (const char C) const;
/// returns FARegexpTree::TYPE_ for the given symbols
const int GetType (const char C) const;
protected:
const char * m_pRegexp;
int m_Length;
FAArray_cont_t < FAToken > * m_pTokens;
enum { AsciiSize = 128 };
int m_char2type [AsciiSize];
private:
/// adds token to the tokens container
void PushToken (const int Type, const int Offset, const int Length);
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FANfa2Dfa_t.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_NFA2DFA_T_H_
#define _FA_NFA2DFA_T_H_
#include "FAConfig.h"
#include "FAAllocatorA.h"
#include "FAArray_t.h"
#include "FAArray_cont_t.h"
#include "FAChain2Num_judy.h"
#include "FAChain2Num_hash.h"
#include "FAEncoder_pm_dpm.h"
#include "FAState2OwsA.h"
#include "FAFsmConst.h"
#include "FAUtils.h"
#include <algorithm>
namespace BlingFire
{
///
/// This processor builds DFA from NFA.
///
/// Note: Template parameters allows to have non-const _TNfa objects,
/// this may be usefull when _TNfa object does not exist and is just a result
/// of on-fly conversion. However, whenever possible instantiate it as
/// FANfa2Dfa_t < const _TNfa, _TDfa >.
///
template <class _TNfa, class _TDfa>
class FANfa2Dfa_t {
public:
FANfa2Dfa_t (FAAllocatorA * pAlloc);
~FANfa2Dfa_t ();
public:
/// sets up Nfa
void SetNFA (const _TNfa * nfa);
/// sets up Dfa
void SetDFA (_TDfa * dfa);
/// sets up special symbol which means any but existing at the given state
/// (by default no special processing is added to any symbol)
void SetAnyIw (const int AnyIw);
/// specifies whether it is necessary to map new states to old ones,
/// does not do mapping by default
void SetNew2Old (FAState2OwsA * pNew2Old);
/// makes determinization
void Process ();
/// returns into the initial state, automatically called by Process
void Clear ();
private:
/// prepares processor to work,
/// this method must be called after Nfa has been initialized
void Prepare ();
// maps oldset into a new state
// If such an oldset does not exist, it creates a new,
// otherwise returns a new state associated with the oldset.
// Modifies m_was_added.
const int set2state (const int * pOldset, const int Count);
// builds map from iw to dst set
void build_iw2dst (const int * States, const int Count);
// marks the NewState to be final, if there are any finals withing the States
void build_finals (const int NewState,
const int * pStates,
const int Count);
// helper-method is called from build_iw2dst
void sort_uniq_iw2dst ();
// helper-method is called from sort_uniq_iw2dst
const int sort_uniq (int * pBegin, int * pEnd);
// helper-method is called from build_iw2dst
void clear_iw2dst ();
// makes additional processing for any-other symbol (if asked)
void process_any_iw2dst(const int * pStates, const int Count);
// adds transitions into Dfa (without any symbol)
void add_transitions ();
// adds transitions into Dfa (with any symbol)
void add_transitions_any ();
private:
/// input Nfa
const _TNfa * m_nfa;
/// output Dfa
_TDfa * m_dfa;
/// output new2old mapping
FAState2OwsA * m_pNew2Old;
/// state sets encoder
FAEncoder_pm_dpm m_encoder;
/// maps a set of old states into a new one
FAChain2Num_judy m_oldset2state;
// FAChain2Num_hash m_oldset2state;
/// maps a set of old states (which contains only one state) into a new one
FAArray_t < int > m_old2state;
/// stack of unseen states
FAArray_t < int * > m_stack;
/// new final states are placed here
FAArray_cont_t < int > m_finals;
/// first avaliable state number
int m_states;
/// indicates whether a new state was created
bool m_was_added;
/// maps input weihgts to arrays of destination sets
FAArray_cont_t < FAArray_cont_t < int > * > m_iw2dst;
/// maps input weights to flags whether the arrays of destination states
/// have to be sorted
FAArray_cont_t < int > m_iw2need_sort;
/// newly built state
int m_new_state;
/// all outgoing iws at m_new_state
FAArray_cont_t < int > m_iws;
/// all destination states corresponding to the m_iws
FAArray_cont_t < int > m_dsts;
/// if true, we should process any-other symbol
bool m_process_any;
/// Any value
int m_any_iw;
/// indicates whether m_new_state has an Any-outgoing Iw
/// holds: If false == m_any_iw Then false == m_has_any;
bool m_has_any;
/// memory allocator
FAAllocatorA * m_pAlloc;
};
template <class _TNfa, class _TDfa>
FANfa2Dfa_t<_TNfa, _TDfa>::FANfa2Dfa_t (FAAllocatorA * pAlloc) :
m_nfa (NULL),
m_dfa (NULL),
m_pNew2Old (NULL),
m_new_state (-1),
m_process_any (false),
m_any_iw (-1),
m_has_any (false),
m_pAlloc (pAlloc)
{
m_stack.SetAllocator (m_pAlloc);
m_old2state.SetAllocator (m_pAlloc);
m_iws.SetAllocator (m_pAlloc);
m_dsts.SetAllocator (m_pAlloc);
m_iw2dst.SetAllocator (m_pAlloc);
m_iw2need_sort.SetAllocator (m_pAlloc);
m_finals.SetAllocator (m_pAlloc);
m_oldset2state.SetAllocator (m_pAlloc);
m_oldset2state.SetEncoder (&m_encoder);
}
template <class _TNfa, class _TDfa>
FANfa2Dfa_t<_TNfa, _TDfa>::~FANfa2Dfa_t ()
{
int i;
const int IwCount = m_iw2dst.size ();
for (i = 0; i < IwCount; ++i) {
FAArray_cont_t < int > * pDstSet = m_iw2dst [i];
DebugLogAssert (pDstSet);
delete pDstSet;
}
m_iw2dst.Clear ();
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::Prepare ()
{
DebugLogAssert (m_nfa);
FANfa2Dfa_t::Clear ();
const int IwCount = m_nfa->GetMaxIw () + 1;
m_iw2need_sort.resize (IwCount);
m_iw2dst.resize (IwCount);
/// make initialization
for (int i = 0; i < IwCount; ++i) {
FAArray_cont_t < int > * pDstSet = NEW FAArray_cont_t < int >;
DebugLogAssert (pDstSet);
pDstSet->SetAllocator (m_pAlloc);
/// make the default allocation
pDstSet->Create (2);
/// size of this array should always be >= 1
pDstSet->resize (1);
/// initialize the pointer
m_iw2dst [i] = pDstSet;
/// initialize iw 2 need_sort map
m_iw2need_sort [i] = false;
}
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::SetNFA (const _TNfa * nfa)
{
DebugLogAssert (nfa);
m_nfa = nfa;
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::SetDFA (_TDfa * dfa)
{
DebugLogAssert (dfa);
m_dfa = dfa;
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::SetAnyIw (const int AnyIw)
{
m_process_any = true;
m_any_iw = AnyIw;
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::SetNew2Old (FAState2OwsA * pNew2Old)
{
m_pNew2Old = pNew2Old;
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::Clear ()
{
DebugLogAssert (0 == m_stack.size ());
m_states = 0;
m_new_state = -1;
m_has_any = false;
m_stack.Clear ();
m_stack.Create ();
m_old2state.Clear ();
m_old2state.Create ();
m_finals.Clear ();
m_finals.Create ();
m_oldset2state.Clear ();
m_iw2need_sort.Clear ();
m_iw2need_sort.Create ();
m_iws.Clear ();
m_iws.Create ();
m_dsts.Clear ();
m_dsts.Create ();
const int IwCount = m_iw2dst.size ();
for (int i = 0; i < IwCount; ++i) {
FAArray_cont_t < int > * pDstSet = m_iw2dst [i];
DebugLogAssert (pDstSet);
delete pDstSet;
}
m_iw2dst.Clear ();
m_iw2dst.Create ();
}
template <class _TNfa, class _TDfa>
inline const int FANfa2Dfa_t<_TNfa, _TDfa>::set2state (const int * pOldSet,
const int Count)
{
DebugLogAssert (NULL != pOldSet);
// the empty set: [ 0 ] states for transition to the dead state
DebugLogAssert (0 < Count);
m_was_added = false;
if (2 < Count) {
// try to find a state
const int * pValue = m_oldset2state.Get (pOldSet, Count);
// it exists
if (NULL != pValue) {
return *pValue;
}
const int NewSatate = m_states;
// add a new one
m_oldset2state.Add (pOldSet, Count, NewSatate);
// increment the number of states used
m_states++;
m_was_added = true;
return NewSatate;
} else if (2 == Count) {
const int OldState = pOldSet [1];
const int OrigSize = m_old2state.size ();
// check whether we have to enlarge the m_old2state array
if (OrigSize <= OldState) {
m_old2state.resize (OldState + 1);
// invalidate the interval from the OrigSize upto the *pOldSet
for (int i = OrigSize; i <= OldState; ++i) {
m_old2state [i] = -1;
}
}
// try to find a state
int NewState = m_old2state [OldState];
// state not found
if (-1 == NewState) {
NewState = m_states;
// add a new one
m_old2state [OldState] = NewState;
// increment the number of states used
m_states++;
m_was_added = true;
}
return NewState;
} else {
return FAFsmConst::DFA_DEAD_STATE;
}
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::clear_iw2dst ()
{
const int IwCount = m_iws.size ();
for (int i = 0; i < IwCount; ++i) {
const int Iw = m_iws [i];
FAArray_cont_t < int > * pDstStates = m_iw2dst [Iw];
DebugLogAssert (pDstStates);
pDstStates->resize (1);
/// for a while
m_iw2need_sort [Iw] = false;
}
m_iws.resize (0);
m_dsts.resize (0);
}
template <class _TNfa, class _TDfa>
inline const int FANfa2Dfa_t<_TNfa, _TDfa>::sort_uniq (int * pBegin, int * pEnd)
{
DebugLogAssert (pBegin);
DebugLogAssert (pEnd);
std::sort (pBegin, pEnd);
const int NewSize = int (std::unique (pBegin, pEnd) - pBegin);
return NewSize;
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::sort_uniq_iw2dst ()
{
const int NewSize = sort_uniq (m_iws.begin (), m_iws.end ());
m_iws.resize (NewSize);
const int IwCount = m_iws.size ();
for (int i = 0; i < IwCount; ++i) {
const int Iw = m_iws [i];
FAArray_cont_t < int > * pDstStates = m_iw2dst [Iw];
DebugLogAssert (pDstStates);
const int OldSize = pDstStates->size ();
/// check whether we have no work to do
/// (the array has only one element or its elements are already sorted)
if (false == m_iw2need_sort [Iw]) {
/// make the array of [n + 1, a_1, a_2, ... a_n]
(*pDstStates) [0] = OldSize;
} else {
/// arrays from one element must not be sorted
DebugLogAssert (2 < OldSize);
int * pBegin = pDstStates->begin () + 1;
int * pEnd = pDstStates->end ();
const int DstStatesNewSize = 1 + sort_uniq (pBegin, pEnd);
pDstStates->resize (DstStatesNewSize);
/// make the array of [n + 1, a_1, a_2, ... a_n]
(*pDstStates) [0] = DstStatesNewSize;
/// clear this flag
m_iw2need_sort [Iw] = false;
}
}
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::
build_iw2dst (const int * pStates, const int Count)
{
DebugLogAssert (pStates);
DebugLogAssert (0 < Count);
// clear the map from the prev usage
clear_iw2dst ();
const int * pIw;
const int * pIwDstStates;
// build new dst sets
for (int i = 0; i < Count; ++i) {
// get source state
const int State = pStates [i];
// get input weights
const int IwCount = m_nfa->GetIWs (State, &pIw);
// there is no outgoing arcs at this state
if (0 == IwCount)
continue;
const int OldIwsSize = m_iws.size ();
m_iws.resize (OldIwsSize + IwCount);
DebugLogAssert (pIw);
// make iteration thru its input weights
for (int iw_idx = 0; iw_idx < IwCount; ++iw_idx) {
// input weight
const int Iw = pIw [iw_idx];
// add iw
m_iws [OldIwsSize + iw_idx] = Iw;
// get dest set pointer
FAArray_cont_t < int > * pDstStates = m_iw2dst [Iw];
DebugLogAssert (pDstStates);
const int OldSize = pDstStates->size ();
// get the number of dest states
const int IwDstCount = m_nfa->GetDest (State, Iw, &pIwDstStates);
// 0 == IwDstCount iff there is an only transition to the dead state
if (0 < IwDstCount) {
DebugLogAssert (pIwDstStates);
// adjust *pDstStates's size
pDstStates->resize (OldSize + IwDstCount);
int * pDstStatesPtr = pDstStates->begin () + OldSize;
// append pIwDstStates into pDstStates
memcpy (pDstStatesPtr, pIwDstStates, sizeof (int) * IwDstCount);
// check whether there were already some States inserted
if (1 < OldSize) {
// this condition can be refined in the following way:
// > - we have to sort and unique
// = - we have to unique only
if (*(pDstStatesPtr - 1) >= *pDstStatesPtr)
m_iw2need_sort [Iw] = true;
}
}
} // of iteration thru the weights
} // of iteration thru the states
// define the order and remove doubles
sort_uniq_iw2dst ();
if (true == m_process_any) {
// process any symbol if asked
process_any_iw2dst (pStates, Count);
}
}
///
/// Additional ANY-symbols processing to the general procedure
///
/// foreach Iw \in NewState, s.t. ANY != Iw do
/// foreach Q \in NewState do
/// if (Q, ANY, S) \in Nfa && !(Q, Iw, P) \in Nfa then
/// NewState.Dst[Iw].push S;
///
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::
process_any_iw2dst (const int * pStates, const int Count)
{
DebugLogAssert (pStates);
m_has_any = false;
/// new state consists of only one old
if (1 >= Count)
return;
const int IwsSize = m_iws.size ();
const int * pIws = m_iws.begin ();
DebugLogAssert (pIws);
/// all old states have the same transition, or no transitions at all
if (1 >= IwsSize)
return;
int i;
for (i = 0; i < IwsSize; ++i) {
const int Iw = pIws [i];
if (Iw == m_any_iw) {
m_has_any = true;
break;
}
}
/// no old state contains the special any symbol
if (i == IwsSize)
return;
// make iteration thru the alphabet of a new state
for (i = 0; i < IwsSize; ++i) {
const int Iw = pIws [i];
if (Iw == m_any_iw)
continue;
// get dest set pointer
FAArray_cont_t < int > * pDstStates = m_iw2dst [Iw];
DebugLogAssert (pDstStates);
// make iteration thru the old states
for (int idx = 0; idx < Count; ++idx) {
const int Q = pStates [idx];
const int * pIwDst;
const int IwDstSize = m_nfa->GetDest (Q, Iw, &pIwDst);
// find out whether this symbol is absent
//// 0 == IwDstSize for dead state only
if (-1 == IwDstSize) {
const int * pAnyDst;
const int AnyDstSize = m_nfa->GetDest (Q, m_any_iw, &pAnyDst);
// but there is any symbol
if (0 < AnyDstSize) {
DebugLogAssert (pAnyDst);
// then append AnyDst to the m_iw2dst [Iw]
const int OldSize = pDstStates->size ();
// adjust *pDstStates's size
pDstStates->resize (OldSize + AnyDstSize);
int * pDstStatesPtr = pDstStates->begin () + OldSize;
// append pAnyDst into pDstStates
memcpy (pDstStatesPtr, pAnyDst, sizeof (int) * AnyDstSize);
if (2 < OldSize + AnyDstSize) {
// mark this entry to be sorted further
m_iw2need_sort [Iw] = true;
}
} // of if (0 < AnyDstSize)
} // of if (0 == IwDstSize)
} // iteration thru the old states
} // iteration thru the alphabet
// define the order and remove doubles
sort_uniq_iw2dst ();
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::build_finals (const int NewState,
const int * pStates,
const int Count)
{
DebugLogAssert (m_nfa);
if (true == m_nfa->IsFinal (pStates, Count)) {
// if there is not enough place, allocates a half of existing
m_finals.push_back (NewState);
}
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::add_transitions ()
{
DebugLogAssert (m_iws.size () == m_dsts.size ());
m_dfa->SetTransition (m_new_state, m_iws.begin (),
m_dsts.begin (), m_iws.size ());
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::add_transitions_any ()
{
DebugLogAssert (m_iws.size () == m_dsts.size ());
// find Any Idx
const int AnyIdx = FAFind_log (m_iws.begin (), m_iws.size (), m_any_iw);
DebugLogAssert (-1 != AnyIdx);
// get Any destination state
const int AnyDst = m_dsts [AnyIdx];
// put the Any transition
m_dfa->SetTransition (m_new_state, m_any_iw, AnyDst);
const int IwCount = m_iws.size ();
// put all the other transitions except that comes into AnyDst
for (int i = 0; i < IwCount; ++i) {
const int Iw = m_iws [i];
const int Dst = m_dsts [i];
if (Iw != m_any_iw && Dst != AnyDst) {
// put a transition
m_dfa->SetTransition (m_new_state, Iw, Dst);
}
}
}
template <class _TNfa, class _TDfa>
void FANfa2Dfa_t<_TNfa, _TDfa>::Process ()
{
DebugLogAssert (m_dfa && m_nfa);
Prepare ();
const int * pStates;
int i;
// build an initial state
const int Count = m_nfa->GetInitials (&pStates);
if (0 < Count) {
int * pSet = (int *) FAAlloc (m_pAlloc, sizeof (int) * (Count + 2));
pSet [1] = Count + 1;
for (i = 2; i < int (Count + 2); ++i) {
pSet [i] = pStates [i - 2];
}
// create a new state
const int State = set2state (&(pSet [1]), Count + 1);
DebugLogAssert (0 == State);
// set up the initial state
m_dfa->SetInitial (State);
// make pSet to be [NewState, N + 1, Old_1, ..., Old_N]
pSet [0] = State;
// push the initial state
m_stack.push_back (pSet);
while (!m_stack.empty ()) {
// get next state
int * pFromSet = m_stack [m_stack.size () - 1];
DebugLogAssert (pFromSet);
// remove it from stack
m_stack.pop_back ();
m_new_state = pFromSet [0];
const int FromCount = pFromSet [1] - 1;
const int * pFromOldStates = pFromSet + 2;
// build iw to dst set map
build_iw2dst (pFromOldStates, FromCount);
// build final states
build_finals (m_new_state, pFromOldStates, FromCount);
// build transitions
const int IwCount = m_iws.size ();
// make the array of destination states of the same size
m_dsts.resize (IwCount);
for (int iw_idx = 0; iw_idx < IwCount; ++iw_idx) {
const int Iw = m_iws [iw_idx];
FAArray_cont_t < int > * pDstStateSet = m_iw2dst [Iw];
DebugLogAssert (pDstStateSet);
DebugLogAssert (pDstStateSet->size ());
DebugLogAssert (0 <= (*pDstStateSet) [0] && \
pDstStateSet->size () == (unsigned int) (*pDstStateSet) [0]);
int * pDstSetPtr = pDstStateSet->begin ();
const int DstSetSize = *pDstSetPtr;
// create or find a destination state
const int DstState = set2state (pDstSetPtr, DstSetSize);
m_dsts [iw_idx] = DstState;
/// check if we should add this state for further processing
if (true == m_was_added) {
int * pDstState_DstSet =
(int*) FAAlloc (m_pAlloc, sizeof (int) * (DstSetSize + 1));
// add DstState
pDstState_DstSet [0] = DstState;
// copy DstStateSet
memcpy (&(pDstState_DstSet [1]),
pDstSetPtr,
sizeof (int) * DstSetSize);
// push for processing
m_stack.push_back (pDstState_DstSet);
}
} // of for
// add transitions into Dfa
if (false == m_has_any) {
add_transitions ();
} else {
add_transitions_any ();
}
if (m_pNew2Old) {
DebugLogAssert (pFromSet);
const int NewState = pFromSet [0];
const int OldSetSize = pFromSet [1] - 1;
const int * pOldSet = pFromSet + 2;
m_pNew2Old->SetOws (NewState, pOldSet, OldSetSize);
}
// destroy pFromSet and forget about it
FAFree (m_pAlloc, pFromSet);
} // of while
} // of if (0 < Count)
// set up final states
std::sort (m_finals.begin (), m_finals.end ());
m_dfa->SetFinals (m_finals.begin (), m_finals.size ());
// make it ready to use
m_dfa->Prepare ();
}
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAOw2Iw_pack_triv.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_OW2IW_PACK_TRIV_H_
#define _FA_OW2IW_PACK_TRIV_H_
#include "FAConfig.h"
#include "FASetImageA.h"
#include "FAOw2IwCA.h"
#include "FAChains_pack_triv.h"
namespace BlingFire
{
///
/// FAOw2IwCA memory dump based implementation. Can be initialized from
/// the memory dump created with FADfaPack_triv.
///
class FAOw2Iw_pack_triv : public FASetImageA,
public FAOw2IwCA {
public:
FAOw2Iw_pack_triv ();
public:
void SetImage (const unsigned char * pImage);
const int GetDestIwOw (
const int State,
const int Ow1,
int * pIw,
int * pOw2
) const;
private:
// pointer to the image dump
const unsigned char * m_pAutImage;
// initial state
int m_InitialState;
// Ows keeper
FAChains_pack_triv m_UnpackOws;
// dst size
int m_DstSize;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FARSDfaCA.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_RSDFA_CA_H_
#define _FA_RSDFA_CA_H_
#include "FAConfig.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// client-side interface for Rabin-Scott NFA
///
class FARSDfaCA {
public:
/// returns the initial state
virtual const int GetInitial () const = 0;
/// returns true if the State is a final
virtual const bool IsFinal (const int State) const = 0;
/// for the given State and the Iw returns the Destination state
/// returns -1 if transition does not exist
virtual const int GetDest (const int State, const int Iw) const = 0;
/// returns automaton's alphabet
virtual const int GetIWs (
__out_ecount_opt (MaxIwCount) int * pIws,
const int MaxIwCount
) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FASubstInterpretTools_t.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_SUBSTINTERPRETTOOLS_H_
#define _FA_SUBSTINTERPRETTOOLS_H_
#include "FAConfig.h"
#include "FABrResultA.h"
#include "FAArray_cont_t.h"
#include "FAAutInterpretTools_trbr_t.h"
#include "FAUtf8Utils.h"
#include "FASecurity.h"
namespace BlingFire
{
class FAAllocatorA;
class FARSNfaCA;
///
/// This class is responsible for substituter rules interpretation.
///
/// Note:
/// 1. All Process functions return the size of the output chain
/// if no rule matches the input then output chain size is -1.
///
template < class Ty >
class FASubstInterpretTools_t : public FABrResultA {
public:
FASubstInterpretTools_t (FAAllocatorA * pAlloc);
virtual ~FASubstInterpretTools_t ();
public:
/// sets up whether rules reversed or not
void SetReverse (const bool Reverse);
/// sets up Moore's RS part of automaton
void SetRsDfa (const FARSDfaCA * pDfa);
/// sets up Moore's reaction part of automaton
void SetState2Ows (const FAState2OwsCA * pState2Ows);
/// sets up reversed position NFA
void SetFollow (const FARSNfaCA * pFollow);
/// sets up regexp-pos to openning brackets
void SetPos2BrBegin (const FAMultiMapCA * pPos2BrBegin);
/// sets up regexp-pos to closing brackets
void SetPos2BrEnd (const FAMultiMapCA * pPos2BrEnd);
/// sets up rules' actions map
void SetActs (const FAMultiMapCA * pActs);
/// returns output string for tagless rules
/// returns -1 if not matched
const int Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
);
/// returns output string for one-tags transformation rules
/// returns -1 if not matched
const int Process (
const Ty * pIn,
const int InSize,
const int Tag,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
);
/// returns output string for two-tags transformation rules
/// returns -1 if not matched
const int Process (
const Ty * pIn,
const int InSize,
const int FromTag,
const int ToTag,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
);
public:
void AddRes (const int TrBr, const int From, const int To);
private:
inline const int Process_direct (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
);
inline const int Process_reverse (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
);
inline void Clear ();
private:
FAAutInterpretTools_trbr_t < Ty > m_trbr_interp;
const FAMultiMapCA * m_pActs;
// TrBr -> (From,To); (-1,-1) stands for uninitialized pair
FAArray_cont_t < int > m_trbr2fromto;
FAArray_cont_t < unsigned int > m_idxs;
// keeps action to be executed
int m_ActNum;
bool m_Reverse;
FAArray_cont_t < int > m_tmp_chain;
// special Iws
enum {
AnyIw = 0,
};
};
template < class Ty >
FASubstInterpretTools_t< Ty >::FASubstInterpretTools_t (FAAllocatorA * pAlloc) :
m_trbr_interp (pAlloc),
m_pActs (NULL),
m_ActNum (-1),
m_Reverse (false)
{
m_trbr2fromto.SetAllocator (pAlloc);
m_trbr2fromto.Create ();
m_trbr2fromto.resize (100);
for (int i = 0; i < 100; ++i) {
m_trbr2fromto [i] = -1;
}
m_idxs.SetAllocator (pAlloc);
m_idxs.Create ();
m_trbr_interp.SetAnyIw (AnyIw);
m_tmp_chain.SetAllocator (pAlloc);
m_tmp_chain.Create (100);
}
template < class Ty >
FASubstInterpretTools_t< Ty >::~FASubstInterpretTools_t ()
{}
template < class Ty >
void FASubstInterpretTools_t< Ty >::SetRsDfa (const FARSDfaCA * pDfa)
{
m_trbr_interp.SetRsDfa (pDfa);
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
SetState2Ows (const FAState2OwsCA * pState2Ows)
{
m_trbr_interp.SetState2Ows (pState2Ows);
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::SetFollow (const FARSNfaCA * pFollow)
{
m_trbr_interp.SetFollow (pFollow);
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
SetPos2BrBegin (const FAMultiMapCA * pPos2BrBegin)
{
m_trbr_interp.SetPos2BrBegin (pPos2BrBegin);
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
SetPos2BrEnd (const FAMultiMapCA * pPos2BrEnd)
{
m_trbr_interp.SetPos2BrEnd (pPos2BrEnd);
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
SetActs (const FAMultiMapCA * pActs)
{
m_pActs = pActs;
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
SetReverse (const bool Reverse)
{
m_Reverse = Reverse;
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
AddRes (const int TrBr, const int From, const int To)
{
const unsigned int OldSize = m_trbr2fromto.size ();
const int ActNum = (0xffff0000 & (unsigned int)TrBr) >> 16;
if (0 < ActNum) {
m_ActNum = ActNum;
}
const unsigned int Idx = (0xffff & (unsigned int)TrBr) << 1;
if (OldSize > Idx) {
m_trbr2fromto [Idx] = From;
m_trbr2fromto [Idx + 1] = To;
} else {
m_trbr2fromto.resize (Idx + 2);
int * pDst = m_trbr2fromto.begin ();
DebugLogAssert (pDst);
for (unsigned int idx = OldSize; idx < Idx; ++idx) {
pDst [idx] = -1;
}
pDst [Idx] = From;
pDst [Idx + 1] = To;
}
m_idxs.push_back (Idx);
}
template < class Ty >
void FASubstInterpretTools_t< Ty >::
Clear ()
{
m_ActNum = -1;
const int IdxCount = m_idxs.size ();
int * pTrbr2FromTo = m_trbr2fromto.begin ();
for (int i = 0; i < IdxCount; ++i) {
const unsigned int Idx = m_idxs [i];
DebugLogAssert (Idx < m_trbr2fromto.size ());
DebugLogAssert (pTrbr2FromTo);
pTrbr2FromTo [Idx] = -1;
pTrbr2FromTo [Idx + 1] = -1;
}
m_idxs.resize (0);
}
template < class Ty >
inline const int FASubstInterpretTools_t< Ty >::
Process_direct (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
)
{
DebugLogAssert (m_pActs);
DebugLogAssert (pIn && 0 < InSize);
if (!m_trbr_interp.Chain2BrRes_local (pIn, InSize, this)) {
return -1;
}
int OutSize = 0;
if (0 < m_ActNum) {
const int * pActValues;
const int ActSize = m_pActs->Get (m_ActNum, &pActValues);
const unsigned int IdxCount = m_trbr2fromto.size ();
const int * pIdx2FromTo = m_trbr2fromto.begin ();
DebugLogAssert (pIdx2FromTo);
for (int i = 0; i < ActSize; ++i) {
DebugLogAssert (pActValues);
const int ActValue = pActValues [i];
if (0 >= ActValue) {
const int TrBr = -ActValue;
DebugLogAssert (0 <= TrBr);
const unsigned int Idx = ((unsigned int)TrBr) << 1;
if (Idx < IdxCount) {
const int From = pIdx2FromTo [Idx];
const int To = pIdx2FromTo [Idx + 1];
for (int j = From; j <= To; ++j) {
OutSize++;
if (OutSize <= MaxOutSize) {
const int Symbol = pIn [j];
*pOut++ = Symbol;
}
}
}
} else {
OutSize++;
if (OutSize <= MaxOutSize) {
*pOut++ = (Ty) ActValue;
}
}
} // of for (int i = 0; ...
} // if (0 < m_ActNum) ...
FASubstInterpretTools_t< Ty >::Clear ();
return OutSize;
}
template < class Ty >
inline const int FASubstInterpretTools_t< Ty >::
Process_reverse (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
)
{
DebugLogAssert (m_pActs);
DebugLogAssert (pIn && 0 < InSize);
if (!m_trbr_interp.Chain2BrRes_local (pIn, InSize, this)) {
return -1;
}
int OutSize = 0;
if (0 < m_ActNum) {
const int * pActValues;
const int ActSize = m_pActs->Get (m_ActNum, &pActValues);
const unsigned int IdxCount = m_trbr2fromto.size ();
const int * pIdx2FromTo = m_trbr2fromto.begin ();
DebugLogAssert (pIdx2FromTo);
for (int i = 0; i < ActSize; ++i) {
DebugLogAssert (pActValues);
const int ActValue = pActValues [i];
if (0 >= ActValue) {
const int TrBr = -ActValue;
DebugLogAssert (0 <= TrBr);
const unsigned int Idx = ((unsigned int)TrBr) << 1;
if (Idx < IdxCount) {
const int From = pIdx2FromTo [Idx];
const int To = pIdx2FromTo [Idx + 1];
for (int j = To; j >= From; --j) {
OutSize++;
if (OutSize <= MaxOutSize) {
const int Symbol = pIn [j];
*pOut++ = Symbol;
}
}
}
} else {
OutSize++;
if (OutSize <= MaxOutSize) {
*pOut++ = (Ty) ActValue;
}
}
} // of for (int i = 0; ...
} // if (0 < m_ActNum) ...
FASubstInterpretTools_t< Ty >::Clear ();
return OutSize;
}
template < class Ty >
const int FASubstInterpretTools_t< Ty >::
Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
)
{
if (false == m_Reverse) {
const int OutSize = \
Process_direct (pIn, InSize, pOut, MaxOutSize);
return OutSize;
} else {
m_tmp_chain.resize (InSize);
int * pRevChain = m_tmp_chain.begin ();
DebugLogAssert (pRevChain);
DebugLogAssert (pIn);
for (int i = 0; i < InSize; ++i) {
const int Symbol = pIn [i];
pRevChain [InSize - i - 1] = Symbol;
}
const int OutSize = \
Process_reverse (pRevChain, InSize, pOut, MaxOutSize);
return OutSize;
}
}
template < class Ty >
const int FASubstInterpretTools_t< Ty >::
Process (
const Ty * pIn,
const int InSize,
const int Tag,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
)
{
DebugLogAssert (pIn && 0 < InSize);
DebugLogAssert (-1 != Tag);
m_tmp_chain.resize (InSize + 2);
int * pBegin = m_tmp_chain.begin ();
DebugLogAssert (pBegin);
if (false == m_Reverse) {
int * pChain = pBegin;
*pChain++ = Tag;
for (int i = 0; i < InSize; ++i) {
const int Symbol = pIn [i];
*pChain++ = Symbol;
}
*pChain++ = Tag;
const int OutSize = \
Process_direct (pBegin, InSize + 2, pOut, MaxOutSize);
return OutSize;
} else {
int * pRevChain = pBegin;
*pRevChain++ = Tag;
for (int i = 0; i < InSize; ++i) {
const int Symbol = pIn [i];
pRevChain [InSize - (i + 1)] = Symbol;
}
pRevChain [InSize] = Tag;
const int OutSize = \
Process_reverse (pBegin, InSize + 2, pOut, MaxOutSize);
return OutSize;
}
}
template < class Ty >
const int FASubstInterpretTools_t< Ty >::
Process (
const Ty * pIn,
const int InSize,
const int FromTag,
const int ToTag,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
)
{
DebugLogAssert (pIn && 0 < InSize);
DebugLogAssert (-1 != FromTag && -1 != ToTag);
m_tmp_chain.resize (InSize + 4);
int * pBegin = m_tmp_chain.begin ();
DebugLogAssert (pBegin);
if (false == m_Reverse) {
int * pChain = pBegin;
*pChain++ = FromTag;
*pChain++ = ToTag;
for (int i = 0; i < InSize; ++i) {
const int Symbol = pIn [i];
*pChain++ = Symbol;
}
*pChain++ = FromTag;
*pChain++ = ToTag;
const int OutSize = \
Process_direct (pBegin, InSize + 4, pOut, MaxOutSize);
return OutSize;
} else {
int * pRevChain = pBegin;
*pRevChain++ = FromTag;
*pRevChain++ = ToTag;
for (int i = 0; i < InSize; ++i) {
const int Symbol = pIn [i];
pRevChain [InSize - (i + 1)] = Symbol;
}
pRevChain [InSize] = FromTag;
pRevChain [InSize + 1] = ToTag;
const int OutSize = \
Process_reverse (pBegin, InSize + 4, pOut, MaxOutSize);
return OutSize;
}
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAParseTree.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_PARSETREE_H_
#define _FA_PARSETREE_H_
#include "FAConfig.h"
#include "FAParseTreeA.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Parsing tree container class.
///
/// Note:
/// The tree should be updated as follows:
/// 0. Init
/// [ 1. GetUpper* ] ; getting chain to parse
/// 2. AddNode ; setting up first results from parser
/// ...
/// 2. AddNode
/// 3. Update ; making ready
/// 4. GetUpper* ; getting chain to parse
/// 5. AddNode ; setting up next results from parser
/// ...
/// 5. AddNode ; ...
/// 6. Update
/// 7. GetUpper*
/// ...
///
class FAParseTree : public FAParseTreeA {
public:
FAParseTree (FAAllocatorA * pAlloc);
virtual ~FAParseTree ();
public:
const int GetUpperNodes (const int ** ppNodes) const;
const int GetUpperLabels (const int ** ppLabels) const;
const int GetNext (const int Node) const;
const int GetChild (const int Node) const;
const int GetLabel (const int Node) const;
public:
void Init (const int Count);
void AddNode (const int Label, const int FromPos, const int ToPos);
void Update ();
private:
struct FANodeData {
int m_Next; // right neighbour, -1 if no right neighbour
int m_Child; // left child, -1 if no left child
int m_Label;
};
/// node idx -> data
FAArray_cont_t < FANodeData > m_i2n;
/// upper level position -> node idx
FAArray_cont_t < int > m_p2i;
/// upper level position -> node label (redundant but speeds things up)
FAArray_cont_t < int > m_p2l;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAState2Ows_amb.h
|
<filename>blingfirecompile.library/inc/FAState2Ows_amb.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_STATE2OWS_AMB_H_
#define _FA_STATE2OWS_AMB_H_
#include "FAConfig.h"
#include "FAState2Ows.h"
#include "FABitArray.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FARSNfaA;
///
/// This class keeps State2Ows mapping only for ambiguous from
/// NFA point of view positions.
///
class FAState2Ows_amb : public FAState2Ows {
public:
FAState2Ows_amb (FAAllocatorA * pAlloc);
public:
// sets up reversed position NFA
void SetRevPosNfa (const FARSNfaA * pRevPosNfa);
// calculates ambiguous positions
void Prepare ();
// overrides SetOws, so only ambiguous positions are stored
void SetOws (const int State, const int * pOws, const int Size);
private:
const FARSNfaA * m_pRevPosNfa;
FABitArray m_is_amb;
FAArray_cont_t < int > m_ows;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMapA.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MAP_A_H_
#define _FA_MAP_A_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// General interface for Key -> Val map M.
///
/// Note: No duplicate Keys are not allowed.
///
class FAMapA {
public:
/// returns pointer to the Value by the Key, NULL if not found
virtual const int * Get (const int Key) const = 0;
/// makes an association Key -> Value
virtual void Set (const int Key, const int Value) = 0;
/// search for the next Key present that is greater than the passed Key
/// and returns the pointer to its Value, NULL if not found
virtual const int * Next (int * pKey) const = 0;
/// similar to the Next
virtual const int * Prev (int * pKey) const = 0;
/// removes Key -> Value pair
virtual void Remove (const int Key) = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FANfaCreator_digit.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_NFACREATOR_DIGIT_H_
#define _FA_NFACREATOR_DIGIT_H_
#include "FAConfig.h"
#include "FANfaCreator_base.h"
namespace BlingFire
{
class FAAllocatorA;
class FANfaCreator_digit : public FANfaCreator_base {
public:
FANfaCreator_digit (FAAllocatorA * pAlloc);
public:
void SetTransition (const int FromState,
const int ToState,
const int LabelOffset,
const int LabelLength);
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FANfa2EqPairs.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_NFA2EQPAIRS_H_
#define _FA_NFA2EQPAIRS_H_
#include "FAConfig.h"
#include "FANfa2Dfa_t.h"
#include "FAChain2Num_hash.h"
#include "FARSNfaA.h"
#include "FAState2OwsA.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// This processor takes FSM and calculates all pairs of states < q1 q2 >
/// reachable by word w, such as q1 != q2 .
///
/// Note: Unlike E.Roche's this algorithm does not calculate A^2, this
/// algorithm is based on NFA -> DFA but while DFA states are constructed
/// it collects all uniq pairs of NFA states from there. On practice that is
/// faster than calculate A^2.
///
class FANfa2EqPairs : private FAState2OwsA {
public:
FANfa2EqPairs (FAAllocatorA * pAlloc);
virtual ~FANfa2EqPairs ();
public:
/// sets up input NFA
void SetNfa (const FARSNfaA * pNfa);
/// gets all pairs
void Process ();
/// returns pairs Count
const int GetPairCount () const;
/// returns specified pair by index
void GetPair (const int Num, int * pQ1, int * pQ2) const;
/// returns object into the initial state
void Clear ();
private:
// collects pairs via this method
void SetOws (const int State, const int * pOldStates, const int Count);
private:
const int GetOws (const int, int *, const int) const;
const int GetOws (const int, const int **) const;
const int GetMaxOwsCount () const;
// stub, as we are not interested in DFA output
class TDfaStub {
public:
void SetTransition (const int, const int *, const int *, const int);
void SetTransition (const int, const int, const int);
void SetInitial (const int);
void SetFinals (const int * , const int);
void Prepare ();
};
private:
const FARSNfaA * m_pNfa;
TDfaStub m_dfa;
FANfa2Dfa_t < FARSNfaA, TDfaStub > m_nfa2dfa;
FAChain2Num_hash m_pairs;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FATokenSegmentationToolsCA_t.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TOKENSEGMENTATIONTOOLSCA_T_H_
#define _FA_TOKENSEGMENTATIONTOOLSCA_T_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// This is a common interface for different tokenization algorithms
/// to avoid having a many if/then/else at runtime.
///
template < class Ty >
class FATokenSegmentationToolsCA_t {
public:
virtual const int Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize,
const int UnkId
) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAActionsA.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ACTIONSA_H_
#define _FA_ACTIONSA_H_
#include "FAConfig.h"
namespace BlingFire
{
class FABrResultCA;
///
/// Execution call-back for right part actions.
///
class FAActionsA {
public:
virtual void Process (
const int ActNum, // RuleNum 0..MaxRule
const int From, // starting match position
const int To, // ending match position
const FABrResultCA * pRes, // sub-expressions
void * pContext = NULL // context to be modified
) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FATrWordIOTools_utf8.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TRWORDIOTOOLS_UTF8_H_
#define _FA_TRWORDIOTOOLS_UTF8_H_
#include "FAConfig.h"
#include "FASecurity.h"
namespace BlingFire
{
class FAMultiMapCA;
///
/// Input format:
/// a[XX]b[YY]...c[ZZ], where
/// a,b,c - are non-empty input strings and
/// [XX],[YY],[ZZ] - are optional output symbols
///
/// Only the following syntax is allowed in square brackets:
///
/// =D - normal hyphen
/// c=D - add letter before hyphen
/// Xc=D - change letter before hyphen
/// X=D - delete letter before hyphen
/// =DXc - change letter after hyphen
/// X=DXc - delete letter before and change letter after hyphen
/// ? - don't care (the annotation unknown)
///
/// D - non-negative integer value
/// c - a UTF-8 chracter (not 'X', '?', or '=')
///
/// For example:
/// correct: ap[=0]pli[=0]ca[=0]tion
/// correct: a[?]p[?]p[?]l[?]i[?]c[?]a[=]t[?]i[?]o[?]n
/// incorrect: ap[=0]pli[=0][=0]ca[=0]tion
///
class FATrWordIOTools_utf8 {
public:
// makes word parsing
static const int Str2IwOw (
const char * pText, // word text
const int Len, // word length
__out_ecount(MaxOutSize) int * pIws, // Iws buffer, can be NULL
__out_ecount(MaxOutSize) int * pOws, // Ows buffer, can be NULL
const int MaxOutSize, // buffer size
const bool IgnoreCase = false, // ignore-case flag
const FAMultiMapCA * pCharMap = NULL // normalization charmap
);
// builds a parsable UTF-8 string from the Iws/Ows arrays
static const int IwOw2Str (
const int * pIws,
const int * pOws,
const int Size,
__out_ecount (MaxOutSize) char * pOut,
const int MaxOutSize
);
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAPosNfa_pack_triv.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_POSNFA_PACK_TRIV_H_
#define _FA_POSNFA_PACK_TRIV_H_
#include "FAConfig.h"
#include "FASetImageA.h"
#include "FARSNfaCA.h"
#include "FAOffsetTable_pack.h"
#include "FAChains_pack_triv.h"
#include "FAIwMap_pack.h"
namespace BlingFire
{
///
/// This class is able to interpret automaton image stored by FAPosNfaPack_triv
///
class FAPosNfa_pack_triv : public FASetImageA,
public FARSNfaCA {
public:
FAPosNfa_pack_triv ();
public:
void SetImage (const unsigned char * pAutImage);
public:
const int GetInitials (const int ** ppStates) const;
const bool IsFinal (const int State) const;
const int GetDest (
const int State,
const int Iw,
int * pDstStates,
const int MaxCount
) const;
private:
// pointer to the automaton image
const unsigned char * m_pAutImage;
// Iw2Iw map
FAIwMap_pack m_iw2iw;
// State -> Offset mapping
FAOffsetTable_pack m_state2offset;
// destination sets keeper
FAChains_pack_triv m_dest_sets;
// initial state count
int m_InitialCount;
// pointer to the array of the initial states
const int * m_pInitials;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAMealyNfaCA.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MEALYNFACA_H_
#define _FA_MEALYNFACA_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// Client side interface for Mealy NFA reaction representation.
///
class FAMealyNfaCA {
public:
/// returns output weight for the given arc <Src, Iw, Dst>
/// returns -1, if no Ow was associated
virtual const int GetOw (
const int Src,
const int Iw,
const int Dst
) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMealyNfa2Dfa.h
|
<filename>blingfirecompile.library/inc/FAMealyNfa2Dfa.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MEALYNFA2DFA_H_
#define _FA_MEALYNFA2DFA_H_
#include "FAConfig.h"
#include "FANfa2EqPairs.h"
#include "FAColorGraph_t.h"
#include "FAArray_cont_t.h"
#include "FARSNfa2RevNfa.h"
#include "FARSDfa_wo_ro.h"
#include "FARSNfa_wo_ro.h"
#include "FARSDfa_ro.h"
#include "FASplitStates.h"
#include "FACalcMealy1.h"
#include "FACalcMealy2.h"
#include "FAMealyDfa.h"
namespace BlingFire
{
class FAAllocatorA;
class FAMealyNfaA;
///
/// This processor takes Mealy NFA A with minimal deterministic projection
/// over Iw:Ow and if A has non-deterministic projection over Iw the algorithm
/// constructs the equivalent cascade of left-to-right minimal deterministic
/// Mealy DFA A1 and right-to-left Mealy NFA A2. However, if the relation
/// representeted by A is functional then A2 is also a minimal deterministic
/// Mealy DFA.
///
/// Notes:
///
/// 1. It is not necessary to provide minimal deterministic projection
/// over Iw:Ow however the output relation won't be minimal if not to do so.
///
/// 2. If it is enough to have only one left-to-right automaton to represent
/// the given relation then the algorithm won't construct trivial right-to-left
/// automaton.
///
class FAMealyNfa2Dfa {
public:
FAMealyNfa2Dfa (FAAllocatorA * pAlloc);
public:
/// sets up whether A1 and A2 should work as bi-machine, false by default
void SetUseBiMachine (const bool UseBiMachine);
/// sets up input mealy automaton
void SetInNfa (
const FARSNfaA * pInNfa,
const FAMealyNfaA * pInSigma
);
/// sets up output containers for Fsm1 (left-to-right)
void SetOutFsm1 (FARSDfaA * pFsm1Dfa, FAMealyDfaA * pFsm1Ows);
/// sets up output containers for optional Fsm2 (right-to-left)
void SetOutFsm2 (FARSDfaA * pFsm2Dfa, FAMealyDfaA * pFsm2Ows);
/// makes conversion
void Process ();
/// returns object into the initial state and frees memory
void Clear ();
public:
/// returns true if the resulting second automaton is non-deterministic
const bool IsNonDet () const;
/// returns second non-deterministic automaton
const FARSNfaA * GetNfa2 () const;
/// returns second non-deterministic sigma function
const FAMealyNfaA * GetSigma2 () const;
private:
void CreateDfa_triv ();
void CalcEqPairs ();
void ColorGraph ();
void SplitStates ();
void CalcRevNfa ();
void CalcFsm1 ();
void CalcFsm2 ();
void RmArcs1 ();
void SetMaxClasses ();
private:
class _TEqGraph {
public:
_TEqGraph (const int * pV, const int Count, const FANfa2EqPairs * pE);
public:
const int GetVertices (const int ** ppV) const;
const int GetArcCount () const;
void GetArc (const int Num, int * pFrom, int * pTo) const;
private:
const int * const m_pV;
const int m_Count;
const FANfa2EqPairs * const m_pE;
};
private:
// input Mealy NFA
const FARSNfaA * m_pInNfa;
const FAMealyNfaA * m_pInOws;
// output containers
FAMealyDfaA * m_pFsm1Ows;
FARSDfaA * m_pFsm1Dfa;
FAMealyDfaA * m_pFsm2Ows;
FARSDfaA * m_pFsm2Dfa;
FAArray_cont_t < int > m_tmp;
FANfa2EqPairs m_eq_pairs;
FAColorGraph_t < _TEqGraph > m_q2c;
FASplitStates m_split_states;
FARSNfa2RevNfa m_rev;
FARSNfa_wo_ro m_rev_nfa;
FACalcMealy1 m_calc_fsm1;
FACalcMealy2 m_calc_fsm2;
bool m_UseBiMachine;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAWREConf_pack.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WRECONF_PACK_H_
#define _FA_WRECONF_PACK_H_
#include "FAConfig.h"
#include "FAWREConfCA.h"
#include "FASetImageA.h"
namespace BlingFire
{
class FAArray_pack;
class FAMultiMap_pack;
class FAState2Ow_pack_triv;
class FAState2Ows_pack_triv;
class FAMealyDfa_pack_triv;
class FARSDfa_pack_triv;
///
/// An container for the compiled WRE.
///
class FAWREConf_pack : public FASetImageA,
public FAWREConfCA {
public:
FAWREConf_pack ();
virtual ~FAWREConf_pack ();
public:
void SetImage (const unsigned char * pImage);
public:
const int GetType () const;
const int GetTokenType () const;
const int GetTagOwBase () const;
const FARSDfaCA * GetTxtDigDfa () const;
const FAState2OwCA * GetTxtDigOws () const;
const FAArrayCA * GetDictDig () const;
const FARSDfaCA * GetDfa1 () const;
const FARSDfaCA * GetDfa2 () const;
const FAState2OwsCA * GetState2Ows () const;
const FAMealyDfaCA * GetSigma1 () const;
const FAMealyDfaCA * GetSigma2 () const;
const FAMultiMapCA * GetTrBrMap () const;
private:
void Clear ();
private:
int m_WreType;
int m_TokenType;
int m_TagOwBase;
FARSDfa_pack_triv * m_pTxtDfa;
FAState2Ow_pack_triv * m_pTxtOws;
FAArray_pack * m_pDctArr;
FARSDfa_pack_triv * m_pDfa1;
FARSDfa_pack_triv * m_pDfa2;
FAState2Ows_pack_triv * m_pState2Ows;
FAMealyDfa_pack_triv * m_pSigma1;
FAMealyDfa_pack_triv * m_pSigma2;
FAMultiMap_pack * m_pTrBr;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAllocatorA.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ALLOCATORA_H_
#define _FA_ALLOCATORA_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// General interface for allocators. _DEBUG_MEMORY should be defined when
/// memory usage debugging is needed.
///
class FAAllocatorA {
public:
#ifndef _DEBUG_MEMORY
/// allocates size of characters
virtual void * Alloc (const int size) = 0;
/// if the data does not fit the memory it allocates a new block and
/// makes a byte copy
virtual void * ReAlloc (void * ptr, const int size) = 0;
/// frees the allocation
virtual void Free (void * ptr) = 0;
#else
/// allocates size of characters
virtual void * Alloc (
const int size,
const char * pFile,
const int Line
) = 0;
/// if the data does not fit the memory it allocates a new block and
/// makes a byte copy
virtual void * ReAlloc (
void * ptr,
const int size,
const char * pFile,
const int Line
) = 0;
/// frees the allocation
virtual void Free (
void * ptr,
const char * pFile,
const int Line
) = 0;
#endif // _DEBUG_MEMORY
};
}
#ifndef _DEBUG_MEMORY
#define FAAlloc(A, S) (A)->Alloc(S)
#define FAReAlloc(A, P, S) (A)->ReAlloc(P, S)
#define FAFree(A, P) (A)->Free(P)
#else
#define FAAlloc(A, S) (A)->Alloc(S, __FILE__, __LINE__)
#define FAReAlloc(A, P, S) (A)->ReAlloc(P, S, __FILE__, __LINE__)
#define FAFree(A, P) (A)->Free(P, __FILE__, __LINE__)
#endif // _DEBUG_MEMORY
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FADfa2MinDfa_hg_t.h
|
<filename>blingfirecompile.library/inc/FADfa2MinDfa_hg_t.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_DFA2MINDFA_HG_T_H_
#define _FA_DFA2MINDFA_HG_T_H_
#include "FAConfig.h"
#include "FAFsmConst.h"
#include "FAAllocatorA.h"
#include "FAArray_t.h"
#include "FAArray_cont_t.h"
#include "FABitArray.h"
#include "FAChain2Num_judy.h"
#include "FAEncoder_pref_mask.h"
#include "FANfaDelta_ro.h"
#include "FAUtils.h"
#include <algorithm>
namespace BlingFire
{
//
// Hopcroft-Gries minimization algorithm, O(|Q|*log(|Q|)) complexity.
//
// Notes:
// 1. states of input Dfa are always in small letters,
// e.g. state, final_state, state1, state2 and so on.
// 2. n-equivalence classes of states of the input Dfa are always Capitalized
// e.g. State, FinalState, State1, State2 and so on.
//
template < class DFA_in, class DFA_out >
class FADfa2MinDfa_hg_t {
public:
FADfa2MinDfa_hg_t (FAAllocatorA * pAlloc);
~FADfa2MinDfa_hg_t ();
public:
/// sets input dfa
void SetInDfa (const DFA_in * pInDfa);
/// sets output dfa
void SetOutDfa (DFA_out * pOutDfa);
/// makes convertion
void Process ();
/// mapping avaliable after procesing
const int GetEqClass (const int state) const;
/// returns object into the initial state, called automatically by Process
void Clear ();
private:
/// initializes internal structures
void Prepare ();
/// calculates 1-equivalence classes
void CalcInitialEqClasses ();
/// calculates equivalence classes
void CalcEqClasses ();
/// builds output dfa
void BuildOutDfa ();
/// methods which makes automaton to look like fully defined one
/// returns state count of fully defined automaton
inline const int GetMaxState_full () const;
/// defines destination for each <state, Iw> pair
inline const int GetDest_full (const int state, const int Iw) const;
/// returns true if state is final
inline const bool IsFinal_full (const int state) const;
/// working set methods
/// true if pair exisits
inline const bool HasPair (const int Iw, const int ClassFrom) const;
/// inserts a new pair into m_P
inline void InsertPair (const int Iw, const int ClassFrom);
/// removes pair
inline void RemovePair (const int Iw, const int ClassFrom);
/// sets splitting methods
/// calculates D-set for the given partition pair
inline void CalcDSet (const int Iw, const int ClassFrom);
/// helper, moves state from its block/class to its block twin
inline void MoveToTwin (const int state);
/// splits all blocks/classes wrt states in D
inline void SplitBlocks ();
/// inserts new splitting pairs
inline void UpdatePairs ();
/// reverse delta support
inline const int StateIw2Idx (const int state, const int Iw);
inline const int GetIdx (const int state, const int Iw) const;
inline void AddBackTransition (
const int dst_state,
const int Iw,
const int src_state
);
inline const int GetSrcSet (
const int state,
const int Iw,
const int ** pp_src_set
) const;
private:
/// input / output dfas
const DFA_in * m_pInDfa;
DFA_out * m_pOutDfa;
/// contains DFAs' alphabet
const int * m_pAlphabet;
int m_AlphabetSize;
/// contains state count of the m_pInDfa
int m_real_state_count;
/// contains state count of fully defined m_pInDfa
int m_state_count;
/// partition of states into n-equivalence classes:
/// m_elements - all the states
/// m_B_from - maps state to the first position in m_elements of its class
/// m_B_size - class' size m_B_size[m_B_from[state1]]
FAArray_cont_t < int > m_B_from;
FAArray_cont_t < int > m_B_size;
FAArray_cont_t < int > m_elements;
/// reversed m_elements, e.g. i == m_e2i [m_elements [i]]
FAArray_cont_t < int > m_e2i;
/// m_P - pairs (m_B_from[i], Iw) over which partitioning should be done
/// m_PairCount - the number of elements in m_P,
/// all pairs with idx upto m_PairCount - 1 are valid and stored in m_P
/// m_idx2iw - reverse map, maps pair idx to Iw
/// m_idx2from - reverse map, maps pair idx to m_B_from[i]
FAChain2Num_judy m_P;
FAArray_cont_t < int > m_idx2iw;
FAArray_cont_t < int > m_idx2from;
unsigned int m_PairCount;
/// special encoder for pairs
FAEncoder_pref_mask m_encoder;
/// m_D - is a set of states from the input dfa which could be affected by
/// the current partitioning pair
/// m_state2D - mapping: if m_state2D [dfa state] == 1 then dfa state \in D
FAArray_cont_t < int > m_D;
FABitArray m_state2D;
/// m_C - is a set of classes with twins
/// m_HasTwin - indicates whether C is in m_C has twin class made
FAArray_cont_t < int > m_C;
FABitArray m_HasTwin;
/// keeps SrcSets, ordered by < State, Iw > pairs
FAArray_t < FAArray_cont_t < int > * > m_SrcSets;
/// keeps Rev(Delta) of input DFA
FANfaDelta_ro m_rev_delta;
/// m_states, m_iws - are used for finite states remapping
FAArray_cont_t < int > m_states;
FAArray_cont_t < int > m_iws;
/// allocator
FAAllocatorA * m_pAlloc;
};
template < class DFA_in, class DFA_out >
FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
FADfa2MinDfa_hg_t (FAAllocatorA * pAlloc) :
m_pInDfa (NULL),
m_pOutDfa (NULL),
m_pAlphabet (NULL),
m_AlphabetSize (-1),
m_real_state_count (-1),
m_state_count (-1),
m_rev_delta (pAlloc),
m_pAlloc (pAlloc)
{
m_B_from.SetAllocator (m_pAlloc);
m_B_from.Create ();
m_B_size.SetAllocator (m_pAlloc);
m_B_size.Create ();
m_elements.SetAllocator (m_pAlloc);
m_elements.Create ();
m_e2i.SetAllocator (m_pAlloc);
m_e2i.Create ();
m_idx2iw.SetAllocator (m_pAlloc);
m_idx2iw.Create ();
m_idx2from.SetAllocator (m_pAlloc);
m_idx2from.Create ();
m_P.SetAllocator (m_pAlloc);
m_P.SetEncoder (&m_encoder);
m_D.SetAllocator (m_pAlloc);
m_D.Create ();
m_state2D.SetAllocator (m_pAlloc);
m_state2D.Create ();
m_C.SetAllocator (m_pAlloc);
m_C.Create ();
m_HasTwin.SetAllocator (m_pAlloc);
m_HasTwin.Create ();
m_SrcSets.SetAllocator (m_pAlloc);
m_SrcSets.Create ();
m_states.SetAllocator (m_pAlloc);
m_states.Create ();
m_iws.SetAllocator (m_pAlloc);
m_iws.Create ();
}
template < class DFA_in, class DFA_out >
FADfa2MinDfa_hg_t < DFA_in, DFA_out >::~FADfa2MinDfa_hg_t ()
{
const int SrcSetCount = m_SrcSets.size ();
for (int i = 0; i < SrcSetCount; ++i) {
FAArray_cont_t < int > * pSrcSet = m_SrcSets [i];
DebugLogAssert (pSrcSet);
pSrcSet->Clear ();
FAFree (m_pAlloc, pSrcSet);
}
m_SrcSets.resize (0);
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::SetInDfa (const DFA_in * pInDfa)
{
m_pInDfa = pInDfa;
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::SetOutDfa (DFA_out * pOutDfa)
{
m_pOutDfa = pOutDfa;
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::Clear ()
{
DebugLogAssert (0 == m_SrcSets.size ());
m_PairCount = 0;
m_P.Clear ();
m_states.Clear ();
m_states.Create ();
m_iws.Clear ();
m_iws.Create ();
m_elements.Clear ();
m_elements.Create ();
m_e2i.Clear ();
m_e2i.Create ();
m_B_from.Clear ();
m_B_from.Create ();
m_B_size.Clear ();
m_B_size.Create ();
m_D.Clear ();
m_D.Create ();
m_state2D.Clear ();
m_state2D.Create ();
m_C.Clear ();
m_C.Create ();
m_HasTwin.Clear ();
m_HasTwin.Create ();
m_rev_delta.Clear ();
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::Process ()
{
DebugLogAssert (NULL != m_pInDfa);
DebugLogAssert (NULL != m_pOutDfa);
Clear ();
Prepare ();
CalcInitialEqClasses ();
CalcEqClasses ();
BuildOutDfa ();
}
template < class DFA_in, class DFA_out >
inline const int FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
GetSrcSet (const int state, const int Iw, const int ** pp_src_set) const
{
DebugLogAssert (pp_src_set);
const int Count = m_rev_delta.GetDest (state, Iw, pp_src_set);
if (0 < Count)
return Count;
else
return 0;
}
template < class DFA_in, class DFA_out >
inline const int FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
StateIw2Idx (const int state, const int Iw)
{
int p [2];
p [0] = state;
p [1] = Iw;
const int Idx = m_P.Add (p, 2, 0);
return Idx;
}
template < class DFA_in, class DFA_out >
inline const int FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
GetIdx (const int state, const int Iw) const
{
int p [2];
p [0] = state;
p [1] = Iw;
const int Idx = m_P.GetIdx (p, 2);
return Idx;
}
template < class DFA_in, class DFA_out >
inline void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
AddBackTransition (const int dst_state, const int Iw, const int src_state)
{
const int SrcSetIdx = StateIw2Idx (dst_state, Iw);
FAArray_cont_t < int > * pSrcSet;
if ((unsigned int) SrcSetIdx == m_SrcSets.size ()) {
// create a new SrcSet
pSrcSet = (FAArray_cont_t < int > *)
FAAlloc (m_pAlloc, sizeof (FAArray_cont_t < int >));
pSrcSet->SetAllocator (m_pAlloc);
pSrcSet->Create ();
pSrcSet->push_back (src_state, 0);
m_SrcSets.push_back (pSrcSet);
} else {
DebugLogAssert (0 <= SrcSetIdx && m_SrcSets.size () > (unsigned int) SrcSetIdx);
pSrcSet = m_SrcSets [SrcSetIdx];
/// see whether such an element already in the set
const int * pBegin = pSrcSet->begin ();
const int Size = pSrcSet->size ();
DebugLogAssert (FAIsSortUniqed (pBegin, Size));
const int Pos = FAFind_log (pBegin, Size, src_state);
// check whether we have to insert a new element
if (-1 == Pos) {
DebugLogAssert (pBegin);
// check whether needs no reordering
if (pBegin [Size - 1] < src_state) {
pSrcSet->push_back (src_state, (unsigned short) Size);
} else {
pSrcSet->push_back (src_state, (unsigned short) Size);
std::sort (pSrcSet->begin (), pSrcSet->end ());
}
} // of if (pPos == pEnd) ...
}
}
template < class DFA_in, class DFA_out >
inline const int FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
GetMaxState_full () const
{
DebugLogAssert (m_pInDfa);
return m_real_state_count + 1;
}
template < class DFA_in, class DFA_out >
inline const int FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
GetDest_full (const int state, const int Iw) const
{
DebugLogAssert (m_pInDfa);
if (state == m_real_state_count)
return m_real_state_count;
const int dst_state = m_pInDfa->GetDest (state, Iw);
// assuming a dead-state is less than 0
if (0 <= dst_state)
return dst_state;
else
return m_real_state_count;
}
template < class DFA_in, class DFA_out >
inline const bool FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
IsFinal_full (const int state) const
{
DebugLogAssert (m_pInDfa);
if (state != m_real_state_count)
return m_pInDfa->IsFinal (state);
else
return false;
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::Prepare ()
{
DebugLogAssert (NULL != m_pInDfa);
// keep real state count
m_real_state_count = m_pInDfa->GetMaxState ();
// keep the state count
m_state_count = GetMaxState_full ();
/// will be initialized by the 1-equiv classes calculation
m_elements.resize (m_state_count);
m_e2i.resize (m_state_count);
m_B_from.resize (m_state_count);
m_B_size.resize (m_state_count);
m_state2D.resize (m_state_count);
m_HasTwin.resize (m_state_count);
m_state2D.set_bits (0, m_state_count - 1, false);
m_HasTwin.set_bits (0, m_state_count - 1, false);
int i;
#ifndef NDEBUG
for (i = 0; i < m_state_count; ++i) {
m_elements [i] = -1;
m_e2i [i] = -1;
m_B_from [i] = -1;
m_B_size [i] = -1;
}
#endif
// get the alphabet
m_AlphabetSize = m_pInDfa->GetIWs (&m_pAlphabet);
DebugLogAssert (0 < m_AlphabetSize && m_pAlphabet);
DebugLogAssert (FAIsSortUniqed (m_pAlphabet, m_AlphabetSize));
// build back-transitions map
for (int src_state = 0; src_state < m_state_count; ++src_state) {
for (i = 0; i < m_AlphabetSize; ++i) {
const int Iw = m_pAlphabet [i];
const int dst_state = GetDest_full (src_state, Iw);
DebugLogAssert (-1 != dst_state);
// uses m_P for <state, Iw> --> Idx mapping
AddBackTransition (dst_state, Iw, src_state);
} // of for (i = 0
} // of for (src_state = 0; ...
// copy reverse transitions into more compact container
for (int state = 0; state < m_state_count; ++state) {
for (i = 0; i < m_AlphabetSize; ++i) {
const int Iw = m_pAlphabet [i];
const int Idx = GetIdx (state, Iw);
if (-1 == Idx)
continue;
DebugLogAssert (0 <= Idx && m_SrcSets.size () > (unsigned int) Idx);
FAArray_cont_t < int > * pSrcSet = m_SrcSets [Idx];
DebugLogAssert (pSrcSet);
const int * pBegin = pSrcSet->begin ();
const int Size = pSrcSet->size ();
m_rev_delta.AddTransition (state, Iw, pBegin, Size);
pSrcSet->Clear ();
FAFree (m_pAlloc, pSrcSet);
}
}
m_SrcSets.Clear ();
m_SrcSets.Create ();
m_P.Clear ();
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
CalcInitialEqClasses ()
{
DebugLogAssert (m_pAlphabet);
DebugLogAssert (NULL != m_pInDfa);
int Iw, IwIdx;
int state;
/// split states into two classes
int i = 0;
int j = m_state_count;
for (state = 0; state < m_state_count; ++state) {
if (IsFinal_full (state)) {
j--;
m_elements [j] = state;
m_e2i [state] = j;
} else {
m_B_from [state] = 0;
m_elements [i] = state;
m_e2i [state] = i;
i++;
}
}
/// setup m_B_from map for class of final states
const int FinalFirst = j;
for (int idx = FinalFirst; idx < m_state_count; ++idx) {
state = m_elements [idx];
m_B_from [state] = FinalFirst;
}
/// store the size of the second class here
j = m_state_count - j;
DebugLogAssert (0 < i || 0 < j);
/// add first set if there is one
if (0 < i) {
m_B_size [0] = i;
/// add only the smallest one
///if (i < j) {
/// for (IwIdx = 0; IwIdx < m_AlphabetSize; ++IwIdx) {
/// Iw = m_pAlphabet [IwIdx];
/// InsertPair (Iw, 0);
/// }
///}
} // of if (0 != i) ...
/// add second set if there is one
if (0 < j) {
m_B_size [FinalFirst] = j;
/// add only the smallest one
///if (j <= i) {
for (IwIdx = 0; IwIdx < m_AlphabetSize; ++IwIdx) {
Iw = m_pAlphabet [IwIdx];
InsertPair (Iw, FinalFirst);
}
///}
} // of if (0 != j) ...
}
template < class DFA_in, class DFA_out >
inline const bool FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
HasPair (const int Iw, const int ClassFrom) const
{
int pair [2];
pair [0] = Iw;
pair [1] = ClassFrom;
const int * pIdx = m_P.Get (pair, 2);
return NULL != pIdx;
}
template < class DFA_in, class DFA_out >
inline void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
InsertPair (const int Iw, const int ClassFrom)
{
int pair [2];
pair [0] = Iw;
pair [1] = ClassFrom;
m_P.Add (pair, 2, m_PairCount);
m_idx2iw.push_back (Iw);
m_idx2from.push_back (ClassFrom);
m_PairCount++;
}
template < class DFA_in, class DFA_out >
inline void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
RemovePair (const int Iw, const int ClassFrom)
{
int pair [2];
pair [0] = Iw;
pair [1] = ClassFrom;
m_P.Remove (pair, 2);
m_idx2iw.pop_back ();
m_idx2from.pop_back ();
m_PairCount--;
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
CalcDSet (const int Iw, const int ClassFrom)
{
int i;
int j;
// clear from the prev step
const int DSize = m_D.size ();
for (i = 0; i < DSize; ++i) {
const int state = m_D [i];
m_state2D.set_bit (state, false);
}
m_D.resize (0);
// make iteration thru the states of the ClassFrom class
int src_state_count;
const int * p_src_states;
const int Size = m_B_size [ClassFrom];
for (i = ClassFrom; i < ClassFrom + Size; ++i) {
const int state = m_elements [i];
src_state_count = GetSrcSet (state, Iw, &p_src_states);
for (j = 0; j < src_state_count; ++j) {
DebugLogAssert (p_src_states);
const int src_state = p_src_states [j];
/// it has not been already seen
if (false == m_state2D.get_bit (src_state)) {
/// add affected state
m_D.push_back (src_state);
m_state2D.set_bit (src_state, true);
}
} // for (j = 0; ...
} // of for (i = 0; ...
}
template < class DFA_in, class DFA_out >
inline void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
MoveToTwin (const int state)
{
const int ClassFrom = m_B_from [state];
const int ClassSize = m_B_size [ClassFrom];
// if 1== ClassSize then after this method Class + Twin become the orinal
// Class as if there were no sptliiting.
DebugLogAssert (0 < ClassSize);
int TwinSize = 0;
// has any splitting been done for this class/block?
if (false == m_HasTwin.get_bit (ClassFrom)) {
if (1 == ClassSize) {
// skip elementary classes
return;
} else {
// mark as been split
m_HasTwin.set_bit (ClassFrom, true);
m_C.push_back (ClassFrom);
}
} else {
// get TwinClass size
const int TwinFrom = ClassFrom + ClassSize;
DebugLogAssert (0 <= TwinFrom && (unsigned int) TwinFrom < m_B_size.size ());
TwinSize = m_B_size [TwinFrom];
DebugLogAssert (0 < TwinSize);
}
// proceed splitting
if (1 < ClassSize) {
const int i = m_e2i [state] - ClassFrom;
int * pClass = m_elements.begin () + ClassFrom;
DebugLogAssert (i == FAFind_linear (pClass, ClassSize, state));
const int last_state = pClass [ClassSize - 1];
pClass [i] = last_state;
m_e2i [last_state] = ClassFrom + i;
pClass [ClassSize - 1] = state;
m_e2i [state] = ClassFrom + ClassSize - 1;
const int NewClassSize = ClassSize - 1;
const int NewTwinSize = TwinSize + 1;
m_B_size [ClassFrom] = NewClassSize;
m_B_size [ClassFrom + NewClassSize] = NewTwinSize;
// convert to the original class (this is done at most once per class)
} else {
// as we never split elementary blocks
DebugLogAssert (0 < TwinSize && 1 == ClassSize);
const int NewClassSize = TwinSize + 1;
const int NewClassFrom = ClassFrom;
m_B_size [NewClassFrom] = NewClassSize;
const int * pNewClass = m_elements.begin () + NewClassFrom;
for (int j = 0; j < NewClassSize; ++j) {
const int q = pNewClass [j];
m_B_from [q] = NewClassFrom;
}
// mark it back as unchanged, note: m_C will still contain ClassFrom
m_HasTwin.set_bit (ClassFrom, false);
} // of if (1 < ClassSize) ...
}
/// has O(|D|) complexity
template < class DFA_in, class DFA_out >
inline void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::SplitBlocks ()
{
int i;
// clean up from the prev. run of SplitBlocks; at most O(|D|)
const int CSize = m_C.size ();
for (i = 0; i < CSize; ++i) {
const int Class = m_C [i];
m_HasTwin.set_bit (Class, false);
}
m_C.resize (0);
const int * pD = m_D.begin ();
const int DSize = m_D.size ();
for (i = 0; i < DSize; ++i) {
DebugLogAssert (pD);
const int state = pD [i];
// amortized time over DSize runs is exactly O(1)
MoveToTwin (state);
} // of for (int i = 0; i < DSize; ...
// update Twins' m_B_from; exactly O(|D|)
const int NewCSize = m_C.size ();
for (i = 0; i < NewCSize; ++i) {
const int ClassFrom = m_C [i];
if (false == m_HasTwin.get_bit (ClassFrom)) {
continue;
}
const int ClassSize = m_B_size [ClassFrom];
const int TwinClassFrom = ClassFrom + ClassSize;
const int TwinClassSize = m_B_size [TwinClassFrom];
const int * pTwinClass = m_elements.begin () + TwinClassFrom;
DebugLogAssert (pTwinClass);
for (int j = 0; j < TwinClassSize; ++j) {
const int twin_state = pTwinClass [j];
m_B_from [twin_state] = TwinClassFrom;
}
} // of for (i = 0; i < NewCSize; ...
}
template < class DFA_in, class DFA_out >
inline void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
UpdatePairs ()
{
DebugLogAssert (m_pAlphabet);
const int NewCSize = m_C.size ();
for (int i = 0; i < NewCSize; ++i) {
const int ClassFrom = m_C [i];
if (false == m_HasTwin.get_bit (ClassFrom)) {
continue;
}
const int ClassSize = m_B_size [ClassFrom];
const int TwinClassFrom = ClassFrom + ClassSize;
const int TwinClassSize = m_B_size [TwinClassFrom];
for (int j = 0; j < m_AlphabetSize; ++j) {
const int Iw = m_pAlphabet [j];
if (true == HasPair (Iw, ClassFrom)) {
InsertPair (Iw, TwinClassFrom);
} else {
if (ClassSize <= TwinClassSize) {
InsertPair (Iw, ClassFrom);
} else {
InsertPair (Iw, TwinClassFrom);
}
}
} // of for (int j = 0; j < m_AlphabetSize; ...
} // of for (i = 0; i < NewCSize; ...
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::CalcEqClasses ()
{
while (0 < m_PairCount) {
DebugLogAssert (m_PairCount == m_idx2iw.size ());
DebugLogAssert (m_PairCount == m_idx2from.size ());
// pick one pair
const int Iw = m_idx2iw [m_PairCount - 1];
const int ClassFrom = m_idx2from [m_PairCount - 1];
// determine splitting of all blocks wrt <Iw, ClassFrom>
CalcDSet (Iw, ClassFrom);
// remove <Iw, ClassFrom> splitting pair
RemovePair (Iw, ClassFrom);
// split each block wrt <Iw, ClassFrom>
SplitBlocks ();
// update set of splitting pairs according to modified classes
UpdatePairs ();
} // of while (0 < m_PairCount) ...
}
template < class DFA_in, class DFA_out >
void FADfa2MinDfa_hg_t < DFA_in, DFA_out >::BuildOutDfa ()
{
int i, state, State, state_count;
const int * p_states;
DebugLogAssert (m_pInDfa);
DebugLogAssert (m_pAlphabet);
// make the output container ready
const int MaxState = m_pInDfa->GetMaxState ();
m_pOutDfa->SetMaxState (MaxState);
const int MaxIw = m_pInDfa->GetMaxIw ();
m_pOutDfa->SetMaxIw (MaxIw);
m_pOutDfa->Create ();
// remap initial state
state = m_pInDfa->GetInitial ();
State = m_elements [m_B_from [state]];
m_pOutDfa->SetInitial (State);
// remap final states
state_count = m_pInDfa->GetFinals (&p_states);
m_states.resize (state_count);
for (i = 0; i < state_count; ++i) {
DebugLogAssert (NULL != p_states);
state = p_states [i];
State = m_elements [m_B_from [state]];
m_states [i] = State;
}
m_pOutDfa->SetFinals (m_states.begin (), state_count);
// remap all the transitions
for (state = 0; state <= MaxState; ++state) {
m_states.resize (0);
m_iws.resize (0);
for (int idx = 0; idx < m_AlphabetSize; ++idx) {
const int Iw = m_pAlphabet [idx];
const int dst_state = m_pInDfa->GetDest (state, Iw);
if (0 <= dst_state) {
const int DstState = m_elements [m_B_from [dst_state]];
m_states.push_back (DstState);
m_iws.push_back (Iw);
} else if (FAFsmConst::DFA_DEAD_STATE == dst_state) {
m_states.push_back (FAFsmConst::DFA_DEAD_STATE);
m_iws.push_back (Iw);
}
}
/// set up remapped transitions for state
const int TrCount = m_iws.size ();
if (0 < TrCount) {
DebugLogAssert (m_states.size () == (unsigned int) TrCount);
State = m_elements [m_B_from [state]];
m_pOutDfa->SetTransition (State, m_iws.begin (), m_states.begin (), TrCount);
}
}
/// make the output automaton ready to work
m_pOutDfa->Prepare ();
}
template < class DFA_in, class DFA_out >
const int FADfa2MinDfa_hg_t < DFA_in, DFA_out >::
GetEqClass (const int state) const
{
const int State = m_elements [m_B_from [state]];
return State;
}
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAWgConfKeeper.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WG_CONFKEEPER_H_
#define _FA_WG_CONFKEEPER_H_
#include "FAConfig.h"
namespace BlingFire
{
class FALDB;
class FARSDfa_pack_triv;
class FAState2Ows_pack_triv;
class FARSDfaCA;
class FAState2OwsCA;
class FAMultiMapCA;
class FAMultiMap_pack_fixed;
///
/// Keeps configuration for word-guesser module.
///
/// Note: Resource pointers may not be initialized and be NULL.
///
class FAWgConfKeeper {
public:
FAWgConfKeeper ();
~FAWgConfKeeper ();
public:
/// initialization
void Initialize (const FALDB * pLDB, const int * pValues, const int Size);
/// returns object into the initial state
void Clear ();
public:
const FARSDfaCA * GetRsDfa () const;
const FAState2OwsCA * GetState2Ows () const;
const int GetDirection () const;
const int GetMaxLen () const;
const bool GetNoTrUse () const;
// returns tag value or -1 if it was not specified
const int GetDefTag () const;
const bool GetDictMode () const;
const bool GetIgnoreCase () const;
// the numrical value corresponding to 1 of the prob, prob guesser only
const int GetMaxProb () const;
const FAMultiMapCA * GetCharMap () const;
const float GetMinProbVal () const;
const float GetMaxProbVal () const;
// returns true if logarithmic scale was used
const bool GetIsLog () const;
// returns the end-of-sequence (EOS) tag value
const int GetEosTag () const;
// returns the order parameter (e.g. n-gram order if ngrams are stored in the WG)
// (returns -1 if was not specified)
const int GetOrder () const;
private:
FARSDfa_pack_triv * m_pDfa;
FAState2Ows_pack_triv * m_pState2Ows;
int m_Direction;
int m_MaxLen;
int m_DefTag;
bool m_NoTrUse;
bool m_DictMode;
bool m_IgnoreCase;
int m_MaxProb;
FAMultiMap_pack_fixed * m_pCharMap;
float m_MinProbVal;
float m_MaxProbVal;
bool m_fLogScale;
int m_TagEos;
int m_Order;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FANfas2TupleNfa.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_NFAS2TUPLENFA_H_
#define _FA_NFAS2TUPLENFA_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FAChain2Num_judy.h"
#include "FAEncoder_pref.h"
namespace BlingFire
{
class FAAllocatorA;
class FARSNfaA;
///
/// This class build tuple-NFA from the array of N parallel Nfa-s.
///
/// Nfa_a and Nfa_b are parallel if the following holds:
/// |Qa| == |Qb| and if qa == qb then Pa == Pb,
/// where \forall pa \in Pa, <qa, iwa, pa> \in Ea, iwa \in IWa
/// and \forall pb \in Pb, <qb, iwb, pb> \in Eb, iwb \in IWb.
///
/// The transitions <q, <Iw_1, ..., Iw_N>, p> of tuple-NFA where
/// <qi, Iw_i, pi> \in Nfa_i and qi == q, pi == p are represented as N
/// consiquent transitions.
///
/// Note:
///
/// 1. This class does not copy input NFAs (just store the pointers) so NFAs
/// must exist during the entire processing.
///
class FANfas2TupleNfa {
public:
FANfas2TupleNfa (FAAllocatorA * pAlloc);
public:
/// sets up ignore interval
void SetIgnoreBase (const int IgnoreBase);
/// sets up ignore interval
void SetIgnoreMax (const int IgnoreMax);
/// adds one more NFA to merge
void AddNfa (const FARSNfaA * pNfa);
/// sets up output container
void SetOutNfa (FARSNfaA * pNfa);
/// makes transformation
void Process ();
/// returns object into the initial state
void Clear ();
private:
inline const int GetMaxState () const;
inline const int GetMaxIw () const;
inline const int GetInitials (const int ** ppStates) const;
inline const int GetFinals (const int ** ppStates) const;
inline void RemapStates (
const int * pStates,
const int Count,
const int ** ppOutStates
);
inline void RemapStates2 (
const int FromState,
const int Idx,
const int * pStates,
const int Count,
const int ** ppOutStates
);
inline const bool Ignore (const int Iw) const;
void CalcStateMap ();
void AddTransitions (const int Idx, const int State);
void AddIgnoredTransitions (const int State);
private:
// input
FAArray_cont_t < const FARSNfaA * > m_NfaArr;
const FARSNfaA ** m_pNfaArr;
int m_Count;
// output
FARSNfaA * m_pOutNfa;
// mapping from state / transition -> new state
FAChain2Num_judy m_state2state;
FAEncoder_pref m_encoder;
// keeps Max new state number
int m_NewMaxState;
// temporary arrays for states remapping
FAArray_cont_t < int > m_tmp;
// ignore interval
int m_IgnoreBase;
int m_IgnoreMax;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FATokenSegmentationTools_1best_bpe_with_merges_t.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TOKENSEGMENTATIONTOOLS_1BEST_BPE_WITH_MERGES_T_H_
#define _FA_TOKENSEGMENTATIONTOOLS_1BEST_BPE_WITH_MERGES_T_H_
#include "FAConfig.h"
#include "FARSDfaCA.h"
#include "FAMealyDfaCA.h"
#include "FAArrayCA.h"
#include "FAMultiMapCA.h"
#include "FADictConfKeeper.h"
#include "FALimits.h"
#include "FASecurity.h"
#include "FATokenSegmentationToolsCA_t.h"
#include <cstdlib>
#include <vector>
#include <stdio.h>
namespace BlingFire
{
///
/// Splits input sequence into segments using BPE algorithm.
///
/// Note this algorithm takes merge ranks from a separate field and
/// it does not assume that the rank is an ID of a token from the
/// vocaulary.
///
/// Input: sequence of characters
/// Output: array of tuples <TokenId, From, To>
///
template < class Ty >
class FATokenSegmentationTools_1best_bpe_with_merges_t : public FATokenSegmentationToolsCA_t <Ty> {
public:
FATokenSegmentationTools_1best_bpe_with_merges_t ();
public:
/// initializes from the valid configuration object
void SetConf (const FADictConfKeeper * pConf);
/// writes an array of tuples <TokenId, From, To> into pOut
/// returns the actual / needed size of the array to fit all the tuples or
/// -1 in case of an error
const int Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize,
const int UnkId
) const;
private:
// Mealy DFA keeping a map from a known segment to idx and
// and MultiMap keeping a realtion between idx and <ID, Score> pair
const FARSDfaCA * m_pDfa;
const FAMealyDfaCA * m_pMealy;
const FAArrayCA * m_pK2I; // note this is an identify since we don't have duplicate ID's
const FAMultiMapCA * m_pI2Info;
bool m_fFastBpe;
// to keep track of arc data (note we use ID as a score for BPE since it follows strict ordering)
struct _TArc {
int _Start; // the begging position of the segment
int _End; // the ending position of the segment
int _Id; // ID of a segment from the vocab
float _Rank; // merge order/rank
public:
_TArc ():
_Start(0),
_End(0),
_Id(0),
_Rank(0.0f)
{}
_TArc (int b, int e, int id, float rank):
_Start(b),
_End(e),
_Id(id),
_Rank(rank)
{}
};
};
template < class Ty >
FATokenSegmentationTools_1best_bpe_with_merges_t < Ty >::
FATokenSegmentationTools_1best_bpe_with_merges_t () :
m_pDfa (NULL),
m_pMealy (NULL),
m_pK2I (NULL),
m_pI2Info (NULL),
m_fFastBpe (false)
{}
template < class Ty >
void FATokenSegmentationTools_1best_bpe_with_merges_t < Ty >::
SetConf (const FADictConfKeeper * pConf)
{
LogAssert (pConf);
LogAssert(FAFsmConst::TYPE_MEALY_DFA == pConf->GetFsmType());
// allows to use optimizations such as:
// 1. whole word will be always prefered over the pieces
m_fFastBpe = FAFsmConst::TOKENIZE_BPE_OPT_WITH_MERGES == pConf->GetTokAlgo ();
m_pDfa = pConf->GetRsDfa ();
m_pMealy = pConf->GetMphMealy ();
m_pK2I = pConf->GetK2I ();
m_pI2Info = pConf->GetI2Info ();
LogAssert(0 < m_pK2I->GetCount ());
}
// SENTENCE PIECE DELIMITER, used if m_fFastBpe is enabled
#define __FASpDelimiter__ 0x2581
template < class Ty >
const int FATokenSegmentationTools_1best_bpe_with_merges_t < Ty >::
Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize,
const int UnkId
) const
{
DebugLogAssert (m_pDfa && m_pMealy && m_pK2I && m_pI2Info);
if (0 >= InSize) {
return 0;
}
LogAssert (pIn && InSize <= FALimits::MaxArrSize);
// allocate storage for all segments found in the text
std::vector <_TArc> arcs;
arcs.reserve(InSize);
// get the initial state
const int InitialState = m_pDfa->GetInitial ();
// populate the arcs
for (int start = 0; start < InSize; ++start) {
int State = InitialState;
int SumOw = 0;
int Ow = 0;
bool TokenUnknown = true;
// three variables below are used if m_fFastBpe
const bool fTokenStart = __FASpDelimiter__ == pIn [start];
const size_t ArcCountAtStart = arcs.size ();
int startFastForward = start;
// go as deep as we can from the start position
for (int i = start; i < InSize; ++i) {
const Ty Iw = pIn [i];
State = m_pMealy->GetDestOw (State, Iw, &Ow);
// see if the does not have a transition
if (-1 == State) {
break;
}
SumOw += Ow;
DebugLogAssert (0 <= Ow);
// see if the destination state is a final state
if (m_pDfa->IsFinal (State)) {
// look up the id of the segment, we ignore the score if it is there
const int * pValues = NULL;
const int Count = m_pI2Info->Get (SumOw, &pValues);
LogAssert (1 <= Count && NULL != pValues);
// get the ID
const int id = pValues [0];
const float rank = *(float*)(pValues + 1);
// see if the optimization should be applied
const bool fApplyOpt = m_fFastBpe && fTokenStart && \
((i < InSize - 1) ? __FASpDelimiter__ == pIn [i + 1] : true) && \
ArcCountAtStart < arcs.size ();
// always add the arc if optimization is off
if (!fApplyOpt)
{
// add the arc
arcs.push_back(_TArc(start, i, id, rank));
} else {
// remove all intermediate arcs, if the whole token arc is found
// Note: this does not prevent to have arcs *larger* than one token
arcs [ArcCountAtStart] = _TArc(start, i, id, rank);
arcs.resize (ArcCountAtStart + 1); // resize deletes elements from the end
startFastForward = i;
}
// the token is not an unknown
TokenUnknown = false;
}
} // of for(int i = start; i < InSize; ++start) ...
if (TokenUnknown) {
// if we are here then nothing matched from the start
// check if the prevous arc is also unknown
const int ArcCount = arcs.size();
if (0 < ArcCount && UnkId == arcs [ArcCount - 1]._Id) {
// modify previous arc (make unknown segment longer)
arcs [ArcCount - 1]._End = start;
} else {
// add a new unknown arc
arcs.push_back(_TArc(start, start, UnkId, 0.0f));
}
}
if (m_fFastBpe) {
start = startFastForward; // and +1 will be added by the for loop
}
} // for(int start = 0; start < InSize; ++start) ...
// sort the arcs
_TArc * pArcs = arcs.data();
const size_t ArcCount = arcs.size();
std::qsort(pArcs, ArcCount, sizeof(_TArc), [](const void* a, const void* b) {
const _TArc* pA = static_cast<const _TArc*>(a);
const _TArc* pB = static_cast<const _TArc*>(b);
// bigger ranks first, since we made them negative in the pos-dict
if (pA->_Rank > pB->_Rank) {
return -1;
} else if (pA->_Rank == pB->_Rank) {
// smaller ids first
if (pA->_Id < pB->_Id) {
return -1;
} else if (pA->_Id == pB->_Id) {
// if ids are the same left-most first
if (pA->_Start < pB->_Start) {
return -1;
} else if (pA->_Start == pB->_Start) {
return 0;
}
}
}
return 1;
});
// keep track of the from --> to, from --> id and intermediate positions
std::vector <int> tos_ids (InSize * 3, 0);
// all 0's
int * pTos = tos_ids.data ();
// all UnkId's
int * pIds = pTos + InSize;
for(int i = 0; i < InSize; ++i) {
pIds [i] = UnkId;
}
// point to the third array of ints and cast it to the array of bytes
// Note: all of the values are set to 0
unsigned char * pIntermediate = (unsigned char *)(pTos + (InSize * 2));
// go over all acrs in order
for(size_t i = 0; i < ArcCount; ++i) {
const _TArc * pA = pArcs + i;
const int Start = pA->_Start;
const int End = pA->_End;
// see start/end are avaible for the merge
if(0 == pIntermediate [Start] &&
(End + 1 == InSize || 0 == pIntermediate [End + 1])) {
pTos [Start] = End;
pIds [Start] = pA->_Id;
// more efficient variant of:
// for (int j = Start + 1; j <= End; ++j) {
// pIntermediate [j] = 1;
// }
const int IntermediateCount = End - Start;
if (0 < IntermediateCount) {
memset (pIntermediate + Start + 1, 1, IntermediateCount);
}
}
}
// copy the results
int ActualOutSize = 0;
for (int start = 0; start < InSize; start++) {
const int end = pTos [start];
const int id = pIds [start];
if (ActualOutSize + 3 <= MaxOutSize) {
pOut [ActualOutSize] = id;
pOut [ActualOutSize + 1] = start;
pOut [ActualOutSize + 2] = end;
}
ActualOutSize += 3;
start = end; // and +1 will be added by the for loop
}
return ActualOutSize;
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAIwOwSuffArr2Patterns.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_IWOWSUFFARR2PATTERNS_H_
#define _FA_IWOWSUFFARR2PATTERNS_H_
#include "FAConfig.h"
#include "FARSDfa_ar_judy.h"
#include "FARSDfa_dynamic_t.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// This class builds list patterns from the sorted suffixes of Iw/Ow chains.
///
/// Notes:
///
/// 1. The algorithm generates each pattern as general as possible (e.g. as
/// short as possible), but with no less than N% precision.
///
/// 2. Expects chains in the following format: [Iw_1, Ow_1, ..., Iw_n, Ow_n].
///
/// 3. State1, Dst1, Src1 are states of IwOw-trie and
/// State2, Dst2, Src2 are *corresponding* states of the Iw-trie
///
class FAIwOwSuffArr2Patterns {
public:
FAIwOwSuffArr2Patterns (FAAllocatorA * pAlloc);
virtual ~FAIwOwSuffArr2Patterns ();
public:
/// sets up minimal length of pattern
void SetMinPatLen (const int MinPatLen);
/// sets up a lower precision bound for patterns, 100 is used by default
void SetMinPatPrec (const float MinPatPrec);
/// should be called for each input chain e.g. Iw_1, Ow_1, ..., Iw_n, Ow_n
void AddChain (const int * pChain, const int Size, const int Freq);
/// should be called after all chains added
void Process ();
/// callback, returns all accepted patterns
virtual void PutPattern (const int * pPat, const int Size, const int Freq);
private:
// returns true if the m_MinPatLen of Iws has changed
inline const bool HasPrefChanged (const int * pChain, const int Size) const;
// adds chain's tail to the existing State of IwOw-trie
void AddTail_iwow (
const int State,
const int * pTail,
const int Size,
const int Freq
);
// adds chain's tail to the existing State2 of Iw-trie
void AddTail_iw (
const int State1,
const int State2,
const int * pTail,
const int Size,
const int Freq
);
// adds chain (internal)
void AddChain_int (const int * pChain, const int Size, const int Freq);
// updates Iws and Ows alphabets
inline void UpdateAlphabets (const int * pChain, const int Size);
// builds pattern text, symbol by symbol
inline void SetIwOw (const int Iw, const int Ow, const int Pos);
// builds all patterns
void BuildPatterns ();
// internal clean-up
void Clear ();
private:
// min pattern length
int m_MinPatLen;
// min pattern precision
float m_MinPatPrec;
// trie of all Iw:Ow suffixes (suffixes with the same m_MinPatLen prefix)
FARSDfa_dynamic_t < FARSDfa_ar_judy > m_iwow_trie;
// trie of all Iw suffixes (suffixes with the same m_MinPatLen prefix)
FARSDfa_dynamic_t < FARSDfa_ar_judy > m_iw_trie;
// IwOw Trie State -> Freq
FAArray_cont_t < int > m_iwow_state2freq;
// Iw Trie State -> Freq
FAArray_cont_t < int > m_iw_state2freq;
// Iw State -> IwOw State (or -1)
FAArray_cont_t < int > m_state2state;
// input alphabet
FAArray_cont_t < int > m_iws;
// output alphabet
FAArray_cont_t < int > m_ows;
// prev chain / traversal stack
FAArray_cont_t < int > m_tmp_arr;
// pattern buffer
FAArray_cont_t < int > m_pat;
enum {
DefMinPatLen = 3,
};
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAutIOTools.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_AUT_IO_TOOLS_H_
#define _FA_AUT_IO_TOOLS_H_
#include "FAConfig.h"
#include <iostream>
namespace BlingFire
{
class FAAllocatorA;
class FARSNfaA;
class FARSDfaA;
class FAState2OwA;
class FAState2OwsA;
class FAMealyNfaA;
class FAMealyDfaA;
///
/// A set of methods for printing out and reading in different kinds of
/// automata in ascii representation.
///
/// Notes:
/// Read (...) - reads from textual representation
/// Print (...) - saves in textual representation
///
class FAAutIOTools {
public:
FAAutIOTools (FAAllocatorA * pAlloc);
/// tools for FARSNfaA
public:
void Read (std::istream& is, FARSNfaA * pNFA);
void Print (std::ostream& os, const FARSNfaA * pNFA);
/// tools for Mealy NFA
public:
void Read (std::istream& is, FARSNfaA * pNFA, FAMealyNfaA * pOws);
void Print (std::ostream& os, const FARSNfaA * pNFA, const FAMealyNfaA * pOws);
/// tools for FARSDfaA
public:
void Read (std::istream& is, FARSDfaA * pDFA);
void Print (std::ostream& os, const FARSDfaA * pDFA);
/// tools for Mealy DFA
public:
void Read (std::istream& is, FARSDfaA * pDFA, FAMealyDfaA * pOws);
void Print (std::ostream& os, const FARSDfaA * pDFA, const FAMealyDfaA * pOws);
/// tools for deterministic Moore machines with single output
public:
void Read (std::istream& is, FARSDfaA * pDFA, FAState2OwA * pOwMap);
void Print (std::ostream& os, const FARSDfaA * pDFA, const FAState2OwA * pOwMap);
/// tools for deterministic Moore machines with multiple outputs
public:
void Read (std::istream& is, FARSDfaA * pDFA, FAState2OwsA * pOwsMap);
void Print (std::ostream& os, const FARSDfaA * pDFA, const FAState2OwsA * pOwsMap);
private:
void PrintHeader (std::ostream& os, const FARSNfaA * pNFA);
void PrintHeader (std::ostream& os, const FARSDfaA * pDFA);
void PrintNfaCommon (std::ostream& os, const FARSNfaA * pNFA, const FAMealyNfaA * pOws);
void ReadNfaCommon (std::istream& is, FARSNfaA * pNFA, FAMealyNfaA * pOws);
void PrintDfaCommon (std::ostream& os, const FARSDfaA * pDFA, const FAMealyDfaA * pOws);
void ReadDfaCommon (std::istream& is, FARSDfaA * pDFA, FAMealyDfaA * pOws);
private:
FAAllocatorA * m_pAlloc;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAWREConfPack.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WRECONFPACK_H_
#define _FA_WRECONFPACK_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FAArrayPack.h"
#include "FAMultiMapPack.h"
#include "FADfaPack_triv.h"
namespace BlingFire
{
class FAAllocatorA;
class FAWREConfA;
///
/// This class builds a memory-dump representation for the compiled WRE
///
class FAWREConfPack {
public:
FAWREConfPack (FAAllocatorA * pAlloc);
public:
/// sets up WRE
void SetWre (const FAWREConfA * pWre);
/// builds dump
void Process ();
/// returns output dump representation
const int GetDump (const unsigned char ** ppDump) const;
private:
/// makes object ready
void Prepare ();
/// returns the resulting dump size
const int BuildDumps ();
private:
/// input WRE
const FAWREConfA * m_pWre;
/// resulting memory dump
FAArray_cont_t < unsigned char > m_dump;
/// configuration vector
FAArray_cont_t < int > m_conf;
/// a trivial-pack family
FADfaPack_triv m_pack_txt_dig;
FAArrayPack m_pack_dct_dig;
FADfaPack_triv m_pack_fsm1;
FADfaPack_triv m_pack_fsm2;
FAMultiMapPack m_pack_trbr;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAct2ArrA.h
|
<reponame>palerdot/BlingFire<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ACT2ARRA_H_
#define _FA_ACT2ARRA_H_
#include "FAConfig.h"
namespace BlingFire
{
class FATagSet;
///
/// a callback interface for converting an action text into the array
/// of integers that runtime can use
///
class FAAct2ArrA {
public:
/// tagset (symbol table) setup
virtual void SetTagSet (const FATagSet * pTagSet) = 0;
/// returns array size (-1 in case of a syntax error, 0 in case
/// of an empty action)
virtual const int Process (
const char * pStr,
const int Len,
const int ** ppArr,
int * pLeftCxAdjust,
int * pRightCxAdjust
) = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAEncoder_pref.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ENCODER_PREF_H_
#define _FA_ENCODER_PREF_H_
#include "FAConfig.h"
#include "FAEncoderA.h"
namespace BlingFire
{
/// Does the following:
/// foreach V \in Chain do
/// if V <= 0x7F then
/// *pOut = (unsigned char) V;
/// else if V <= 0x3FFF then
/// ...
/// else if V <= 0x1FFFFF then
/// ...
/// else if V <= 0xFFFFFFF then
/// ...
/// else if V <= 0xFFFFFFFF then
/// ...
/// end
class FAEncoder_pref : public FAEncoderA {
public:
const int GetMaxBytes () const;
const int Encode (const int * pChain,
const int Size,
unsigned char * pOutBuffer) const;
private:
enum { MAX_BYTES_PER_INT = 5 };
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAutInterpretTools_t.h
|
<reponame>palerdot/BlingFire<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_AUTINTERPRETTOOLS_T_H_
#define _FA_AUTINTERPRETTOOLS_T_H_
#include "FAConfig.h"
#include "FARSDfaCA.h"
#include "FAState2OwCA.h"
#include "FAState2OwsCA.h"
#include "FASetUtils.h"
#include "FASecurity.h"
namespace BlingFire
{
template < class Ty >
class FAAutInterpretTools_t {
public:
FAAutInterpretTools_t (FAAllocatorA * pAlloc);
public:
/// sets up AnyIw, 0 by default
void SetAnyIw (const int AnyIw);
/// sets RS Dfa interface
void SetRsDfa (const FARSDfaCA * pDfa);
/// sets State -> Ow map
void SetState2Ow (const FAState2OwCA * pState2Ow);
/// sets State -> Ows map
void SetState2Ows (const FAState2OwsCA * pState2Ows);
public:
/// returns true if RS Dfa accepts the chain
const bool Chain2Bool (const Ty * pChain, const int Size) const;
/// returns ow corresponding to the input chain in the final state of RS
const int Chain2Ow (const Ty * pChain, const int Size) const;
/// returns set of ows corresponding to the input chain in the final states
/// the return value is size of set,
/// if the return value is -1 then return pointer is undefined
const int Chain2Ows (const Ty * pChain,
const int Size,
const int ** ppOws);
/// converts chain of input weights into the chain of output weights
void Chain2OwChain (const Ty * pChain,
__out_ecount(Size) int * pOwChain,
const int Size) const;
/// converts chain of input weights into the chain of sets of output weights
void Chain2OwSetChain (const Ty * pChain,
__out_ecount(Size) const int ** pOwsPtrs,
__out_ecount(Size) int * pOwsSizes,
const int Size);
private:
const FARSDfaCA * m_pDfa;
const FAState2OwCA * m_pState2Ow;
const FAState2OwsCA * m_pState2Ows;
int m_AnyIw;
FASetUtils m_sets;
};
template < class Ty >
FAAutInterpretTools_t< Ty >::
FAAutInterpretTools_t (FAAllocatorA * pAlloc) :
m_pDfa (NULL),
m_pState2Ow (NULL),
m_pState2Ows (NULL),
m_AnyIw (0),
m_sets (pAlloc)
{
}
template < class Ty >
void FAAutInterpretTools_t< Ty >::SetAnyIw (const int AnyIw)
{
m_AnyIw = AnyIw;
}
template < class Ty >
void FAAutInterpretTools_t< Ty >::SetRsDfa (const FARSDfaCA * pDfa)
{
m_pDfa = pDfa;
}
template < class Ty >
void FAAutInterpretTools_t< Ty >::SetState2Ow (const FAState2OwCA * pState2Ow)
{
m_pState2Ow = pState2Ow;
}
template < class Ty >
void FAAutInterpretTools_t< Ty >::
SetState2Ows (const FAState2OwsCA * pState2Ows)
{
m_pState2Ows = pState2Ows;
}
template < class Ty >
const bool FAAutInterpretTools_t< Ty >::Chain2Bool (const Ty * pChain,
const int Size) const
{
DebugLogAssert (m_pDfa);
int State = m_pDfa->GetInitial ();
for (int i = 0; i < Size; ++i) {
DebugLogAssert (pChain);
// convert input symbol into int
const int Iw = pChain [i];
// get go to the following state
State = m_pDfa->GetDest (State, Iw);
if (-1 == State) {
// no way to process Iw
return false;
}
}
if (m_pDfa->IsFinal (State))
return true;
else
return false;
}
template < class Ty >
const int FAAutInterpretTools_t< Ty >::Chain2Ow (const Ty * pChain,
const int Size) const
{
DebugLogAssert (m_pDfa);
DebugLogAssert (m_pState2Ow);
int State = m_pDfa->GetInitial ();
for (int i = 0; i < Size; ++i) {
DebugLogAssert (pChain);
// convert input symbol into int
const int Iw = pChain [i];
// get go to the following state
State = m_pDfa->GetDest (State, Iw);
if (-1 == State)
return -1;
}
// get the Ow
const int Ow = m_pState2Ow->GetOw (State);
return Ow;
}
template < class Ty >
const int FAAutInterpretTools_t< Ty >::Chain2Ows (const Ty * pChain,
const int Size,
const int ** ppOws)
{
DebugLogAssert (m_pDfa);
DebugLogAssert (m_pState2Ows);
DebugLogAssert (ppOws);
int State = m_pDfa->GetInitial ();
for (int i = 0; i < Size; ++i) {
DebugLogAssert (pChain);
// convert input symbol into int
const int Iw = pChain [i];
// get go to the following state
State = m_pDfa->GetDest (State, Iw);
if (-1 == State) {
// no way to process Iw
return -1;
}
}
// get the size of the reaction set
const int OwsCount = m_pState2Ows->GetOws (State, NULL, 0);
if (0 < OwsCount) {
m_sets.Resize (OwsCount, 0);
int * pSet;
m_sets.GetRes (&pSet, 0);
DebugLogAssert (pSet);
// copy results
m_pState2Ows->GetOws (State, pSet, OwsCount);
*ppOws = pSet;
return OwsCount;
} else {
*ppOws = NULL;
return 0;
}
}
template < class Ty >
void FAAutInterpretTools_t< Ty >::
Chain2OwChain (
const Ty * pChain,
__out_ecount(Size) int * pOwChain,
const int Size
) const
{
DebugLogAssert (m_pDfa);
DebugLogAssert (m_pState2Ow);
int State = m_pDfa->GetInitial ();
for (int i = 0; i < Size; ++i) {
DebugLogAssert (pChain);
DebugLogAssert (pOwChain);
// convert input symbol into int
const int Iw = pChain [i];
// get go to the following state
State = m_pDfa->GetDest (State, Iw);
if (-1 == State) {
// no way for further processing
for (int j = i; j < Size; j++) {
pOwChain [j] = -1;
}
return;
}
const int Ow = m_pState2Ow->GetOw (State);
pOwChain [i] = Ow;
}
}
template < class Ty >
void FAAutInterpretTools_t< Ty >::
Chain2OwSetChain (
const Ty * pChain,
__out_ecount(Size) const int ** pOwsPtrs,
__out_ecount(Size) int * pOwsSizes,
const int Size
)
{
DebugLogAssert (m_pDfa);
DebugLogAssert (m_pState2Ows);
m_sets.SetResCount (Size);
int State = m_pDfa->GetInitial ();
for (int i = 0; i < Size; ++i) {
DebugLogAssert (pChain);
DebugLogAssert (pOwsPtrs);
DebugLogAssert (pOwsSizes);
// convert input symbol into int
const int Iw = pChain [i];
// get go to the following state
State = m_pDfa->GetDest (State, Iw);
if (-1 == State) {
// no way for further processing
for (int j = i; j < Size; j++) {
pOwsSizes [j] = -1;
}
return;
}
// get the size of the reaction set
const int OwsCount = m_pState2Ows->GetOws (State, NULL, 0);
if (0 < OwsCount) {
m_sets.Resize (OwsCount, i);
int * pSet;
m_sets.GetRes (&pSet, i);
DebugLogAssert (pSet);
// copy results
m_pState2Ows->GetOws (State, pSet, OwsCount);
pOwsSizes [i] = OwsCount;
pOwsPtrs [i] = pSet;
} else {
pOwsSizes [i] = 0;
pOwsPtrs [i] = NULL;
}
}
}
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FALexTools_t.h
|
<filename>blingfireclient.library/inc/FALexTools_t.h<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_LEXTOOLS_T_H_
#define _FA_LEXTOOLS_T_H_
#include "FAConfig.h"
#include "FAFsmConst.h"
#include "FAUtf32Utils.h"
#include "FARSDfaCA.h"
#include "FAState2OwCA.h"
#include "FAMultiMapCA.h"
#include "FAWbdConfKeeper.h"
#include "FALimits.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// Lexical analyzer runtime.
///
/// This runtime interprets the rules of the following format:
///
/// re* < re > re* --> Tag
/// re* < re > re* --> _call FnTag
/// re* < re > re* --> Tag _call FnTag
/// re* < re > re* --> _call FnTag1 FnTag2 ...
/// re* < re > re* --> Tag _call FnTag1 FnTag2 ...
///
/// _function FnTag
/// <same kind of rules>
/// _end
///
/// see doc\lex.html, doc\lex.ppt for description
///
/// Usage notes:
///
/// 1. The object supposed to be initialized before it's used, it is caller
/// responsibility to guarantee this.
///
/// 2. It is possible to execute either all rules or a particular function
/// in the later case it is caller responsibility to know function tag values,
/// the values can be predefined (and frozen) in the tagset.txt file of the
/// the corresponding grammar.
///
template < class Ty >
class FALexTools_t {
public:
FALexTools_t ();
public:
/// sets up the data containers
void SetConf (const FAWbdConfKeeper * pWbdConf);
/// makes a processing
const int Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize
) const;
/// makes a processing, starting from a particular _function
const int Process (
const int FnTag,
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize
) const;
private:
/// validates consitensy between data structures
inline void Validate () const;
// internal processing function, returns the size of the output array
const int Process_int (
const int Initial,
const int Offset,
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize,
const int RecDepth,
const bool fOnce = false
) const;
private:
/// input objects
const FARSDfaCA * m_pDfa;
const FAState2OwCA * m_pState2Ow;
const FAMultiMapCA * m_pActs;
bool m_IgnoreCase;
int m_MaxDepth;
/// maps function id into an initial state, or -1 if not valid
const int * m_pFn2Ini;
unsigned int m_Fn2IniSize;
/// maximum token length
int m_MaxTokenLength;
/// constants
enum {
DefMaxDepth = 2,
MinActSize = 3,
DefSubIw = FAFsmConst::IW_EPSILON,
};
};
template < class Ty >
FALexTools_t< Ty >::FALexTools_t () :
m_pDfa (NULL),
m_pState2Ow (NULL),
m_pActs (NULL),
m_IgnoreCase (false),
m_MaxDepth (DefMaxDepth),
m_pFn2Ini (NULL),
m_Fn2IniSize (0),
m_MaxTokenLength (FALimits::MaxWordLen)
{}
template < class Ty >
void FALexTools_t< Ty >::SetConf (const FAWbdConfKeeper * pWbdConf)
{
if (pWbdConf) {
m_pDfa = pWbdConf->GetRsDfa();
m_pState2Ow = pWbdConf->GetState2Ow();
m_IgnoreCase = pWbdConf->GetIgnoreCase();
m_MaxDepth = pWbdConf->GetMaxDepth ();
m_pActs = pWbdConf->GetMMap ();
m_Fn2IniSize = pWbdConf->GetFnIniStates (&m_pFn2Ini);
m_MaxTokenLength = pWbdConf->GetMaxTokenLength ();
} else {
m_pDfa = NULL;
m_pState2Ow = NULL;
m_IgnoreCase = false;
m_MaxDepth = DefMaxDepth;
m_pActs = NULL;
m_Fn2IniSize = 0;
m_pFn2Ini = NULL;
m_MaxTokenLength = FALimits::MaxWordLen;
}
Validate ();
}
template < class Ty >
inline void FALexTools_t< Ty >::Validate () const
{
if (m_pActs && m_pDfa) {
const int * pAct;
int ActSize;
int ActId = 0;
while (-1 != (ActSize = m_pActs->Get (ActId++, &pAct))) {
// invalid action
LogAssert (pAct && MinActSize <= ActSize);
const int LeftCx = pAct [0];
const int RightCx = pAct [1];
LogAssert (-FALimits::MaxTag <= LeftCx && LeftCx <= FALimits::MaxTag);
LogAssert (-FALimits::MaxTag <= RightCx && RightCx <= FALimits::MaxTag);
int i = ActSize;
// just one tag
if (MinActSize == ActSize && 0 != pAct [MinActSize - 1]) {
continue;
// delimiter and fn(s), but no tag
} else if (MinActSize < ActSize && 0 == pAct [MinActSize - 1]) {
i = MinActSize;
// tag, delimiter and fn(s)
} else if (MinActSize + 1 < ActSize && 0 == pAct [MinActSize]) {
i = MinActSize + 1;
} else {
// invalid action
LogAssert (false);
}
// validate the function id
for (; i < ActSize; ++i) {
const int FnId = pAct [i];
// bad function id
LogAssert (0 <= FnId && (unsigned) FnId < m_Fn2IniSize);
LogAssert (m_pFn2Ini && 0 <= m_pFn2Ini [FnId]);
}
} // of while (-1 != (ActSize = ...
} // of if (m_pActs && m_pDfa) ...
}
template < class Ty >
const int FALexTools_t< Ty >::
Process_int (
const int Initial,
const int Offset,
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize,
const int RecDepth,
const bool fOnce
) const
{
int OutSize = 0;
int Iw;
int Dst;
if (m_MaxDepth < RecDepth) {
return 0;
}
const int MaxTokenLength = m_MaxTokenLength;
/// iterate thru all possible start positions
for (int FromPos = -1; FromPos < InSize; ++FromPos) {
int State = Initial;
int FinalState = -1;
int FinalPos = -1;
int j = FromPos;
// maximum token length bounds j
int LengthBound = FromPos + MaxTokenLength;
if (InSize < LengthBound) {
LengthBound = InSize;
}
/// feed the left anchor, if appropriate
if (-1 == j) {
State = m_pDfa->GetDest (Initial, FAFsmConst::IW_L_ANCHOR);
if (-1 == State) {
State = m_pDfa->GetDest (Initial, FAFsmConst::IW_ANY);
if (-1 == State)
continue;
}
j++;
}
/// feed the letters
for (; j < LengthBound; ++j) {
Iw = pIn [j];
// prevent regular input weights to match control input weights
if (FAFsmConst::IW_EPSILON > Iw) {
Iw = DefSubIw;
}
if (m_IgnoreCase) {
Iw = FAUtf32ToLower (Iw);
}
Dst = m_pDfa->GetDest (State, Iw);
if (-1 == Dst) {
Dst = m_pDfa->GetDest (State, FAFsmConst::IW_ANY);
if (-1 == Dst)
break;
}
if (m_pDfa->IsFinal (Dst)) {
FinalState = Dst;
FinalPos = j;
}
State = Dst;
} // of for (; j < InSize; ...
/// feed the right anchor, if appropriate
if (InSize == j) {
DebugLogAssert (-1 != State);
Dst = m_pDfa->GetDest (State, FAFsmConst::IW_R_ANCHOR);
if (-1 == Dst) {
Dst = m_pDfa->GetDest (State, FAFsmConst::IW_ANY);
}
if (-1 != Dst && m_pDfa->IsFinal (Dst)) {
FinalState = Dst;
FinalPos = j;
}
}
// use the FinalState and the deepest FinalPos(ition)
if (-1 != FinalPos) {
DebugLogAssert (-1 != FinalState);
DebugLogAssert (FinalPos >= FromPos);
const int Ow = m_pState2Ow->GetOw (FinalState);
const int * pAct;
const int ActSize = m_pActs->Get (Ow, &pAct);
DebugLogAssert (MinActSize <= ActSize && pAct);
const int LeftCx = pAct [0];
const int RightCx = pAct [1];
const int Tag = pAct [2];
// From position in the data
int FromPos2 = FromPos + LeftCx;
if (0 > FromPos2)
{
FromPos2 = 0;
}
else if (InSize <= FromPos2)
{
FromPos2 = InSize - 1;
}
// To position in the data
int ToPos2 = FinalPos - RightCx;
if (0 > ToPos2)
{
ToPos2 = 0;
}
else if (InSize <= ToPos2)
{
ToPos2 = InSize - 1;
}
int FnIdx = MinActSize;
// create the token, if Tag is specified
if (0 != Tag) {
if (OutSize + 3 <= MaxOutSize) {
pOut [OutSize++] = Tag;
pOut [OutSize++] = FromPos2 + Offset;
pOut [OutSize++] = ToPos2 + Offset;
} else {
// stop processing, the output buffer is not enough
return OutSize;
}
FnIdx = MinActSize + 1;
}
// set "once" flag for called functions, if there is more than one
const bool fFnOnce = 1 < (ActSize - FnIdx);
// functions' starting position
int FnFrom = FromPos2;
// apply functions, if any
for (; FnIdx < ActSize; ++FnIdx) {
const int FnId = pAct [FnIdx];
DebugLogAssert (0 <= FnId && (unsigned) FnId < m_Fn2IniSize);
const int FnIni = m_pFn2Ini [FnId];
DebugLogAssert (-1 != FnIni);
const Ty * pFnIn = pIn + FnFrom;
const int FnInSize = ToPos2 - FnFrom + 1;
int * pFnOut = pOut + OutSize;
const int FnMaxOutSize = MaxOutSize - OutSize;
const int FnOutSize = Process_int (FnIni, FnFrom + Offset, \
pFnIn, FnInSize, pFnOut, FnMaxOutSize, RecDepth + 1, \
0 == FnId ? false : fFnOnce);
DebugLogAssert (0 == FnOutSize % 3);
DebugLogAssert (FnOutSize <= FnMaxOutSize);
__analysis_assume (FnOutSize <= FnMaxOutSize);
// see if any tokens have been extracted
if (0 < FnOutSize) {
// updated the total output count
OutSize += FnOutSize;
// next function starts from the last token's To + 1
FnFrom = pOut [OutSize - 1] + 1 - Offset;
// see if no text is left
if (FnFrom > ToPos2) {
break;
}
}
} // of for (; FnIdx < ActSize; ...
// check if the function is supposed to be called once
if (fOnce) {
return OutSize;
}
// see if we can move the FromPos to the right more than one step
if (FinalPos - RightCx > FromPos)
{
FromPos = FinalPos - RightCx;
}
} // of if (-1 != FinalPos)
} // of for (FromPos = 0;
return OutSize;
}
template < class Ty >
const int FALexTools_t< Ty >::
Process (
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize
) const
{
if (!m_pActs || !m_pDfa || !m_pState2Ow) {
return -1;
}
const int Initial = m_pDfa->GetInitial ();
const int OutSize = Process_int (Initial, 0, pIn, InSize, pOut, MaxOutSize, 1);
return OutSize;
}
template < class Ty >
const int FALexTools_t< Ty >::
Process (
const int FnTag,
const Ty * pIn,
const int InSize,
__out_ecount(MaxOutSize) int * pOut,
const int MaxOutSize
) const
{
if (!m_pActs || !m_pDfa || !m_pState2Ow) {
return -1;
}
if (0 == FnTag) {
const int Initial = m_pDfa->GetInitial ();
const int OutSize = Process_int (Initial, 0, pIn, InSize, pOut, MaxOutSize, 1);
return OutSize;
} else if (0 < FnTag && (unsigned int) FnTag < m_Fn2IniSize) {
const int FnIni = m_pFn2Ini [FnTag];
if (-1 == FnIni) {
// the function tag is unknown
return -1;
}
const int OutSize = Process_int (FnIni, 0, pIn, InSize, pOut, MaxOutSize, 1);
return OutSize;
}
// the function tag is unknown
return -1;
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAGcLDB.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_GCLDB_H_
#define _FA_GCLDB_H_
#include "FAConfig.h"
#include "FALDB.h"
#include "FAWREConf_pack.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Keeps all resources needed for GC rules execution.
///
class FAGcLDB : public FALDB {
public:
FAGcLDB (FAAllocatorA * pAlloc);
virtual ~FAGcLDB ();
public:
void SetImage (const unsigned char * pImgDump);
const FAWREConfCA * GetCommon () const;
const FAWREConfCA * GetRule (const int i) const;
private:
void Clear ();
private:
/// common Moore WRE
FAWREConf_pack m_common_wre;
/// Mealy WREs each one per rule, NULL if does not exist
FAWREConf_pack ** m_ppMealyWres;
/// rule count
int m_Count;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAWbdConfKeeper.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WBDCONFKEEPER_H_
#define _FA_WBDCONFKEEPER_H_
#include "FAConfig.h"
namespace BlingFire
{
class FALDB;
class FARSDfa_pack_triv;
class FAState2Ow_pack_triv;
class FAState2Ows_pack_triv;
class FAMultiMap_pack;
class FAMultiMap_pack_fixed;
class FARSDfaCA;
class FAMultiMapCA;
class FAState2OwCA;
class FAState2OwsCA;
///
/// Keeps dictionary object configuration and common containers.
///
/// Note: The pointers can be NULL, if yet not initialized
///
class FAWbdConfKeeper {
public:
FAWbdConfKeeper ();
~FAWbdConfKeeper ();
public:
/// initialization vector
void Initialize (const FALDB * pLDB, const int * pValues, const int Size);
/// returns object into the initial state
void Clear ();
public:
const FARSDfaCA * GetRsDfa () const;
const FAState2OwCA * GetState2Ow () const;
const FAState2OwsCA * GetState2Ows () const;
const FAMultiMapCA * GetMMap () const;
const bool GetIgnoreCase() const;
const FAMultiMapCA * GetCharMap () const;
/// return maximum call depth, if functions are used
const int GetMaxDepth () const;
const int GetWbdTagEos () const;
const int GetWbdTagEop () const;
const int GetWbdTagPunkt () const;
const int GetWbdTagWord () const;
const int GetWbdTagXWord () const;
const int GetWbdTagSeg () const;
const int GetWbdTagIgnore () const;
const int GetMaxTag () const;
/// returns an array of function initial states, the array contains -1
/// for undefined function ids
const unsigned int GetFnIniStates (const int ** ppFn2Ini) const;
/// returns an optional map with action data, if this map does not exist returns NULL
const FAMultiMapCA * GetActData () const;
/// returns maximum allowed token length, FALimits::MaxWordLen is used by default
const int GetMaxTokenLength () const;
public:
// overrides RS Dfa from the LDB
void SetRsDfa (const FARSDfaCA * pDfa);
// overrides State -> Ow from the LDB
void SetState2Ow (const FAState2OwCA * pState2Ow);
// overrides Action map from the LDB
void SetMMap (const FAMultiMapCA * pMMap);
// overrides the ignore case from the LDB
void SetIgnoreCase (const bool IgnoreCase);
// overrides maximum allowed depth for function calls
void SetMaxDepth (const int MaxRecDepth);
// overrides action data map
void SetActData (const FAMultiMapCA * pActData);
private:
/// sets up rules' actions map
inline void CalcFnIniStates ();
private:
FARSDfa_pack_triv * m_pRsDfa;
FAState2Ow_pack_triv * m_pState2Ow;
FAState2Ows_pack_triv * m_pState2Ows;
FAMultiMap_pack * m_pMMapTriv;
FAMultiMap_pack_fixed * m_pCharMap;
FAMultiMap_pack * m_pActData;
bool m_IgnoreCase;
int m_MaxDepth;
int m_TagEos;
int m_TagEop;
int m_TagPunkt;
int m_TagWord;
int m_TagXWord;
int m_TagSeg;
int m_TagIgnore;
int m_MaxTag;
const FARSDfaCA * m_pRsDfaA;
const FAState2OwCA * m_pState2OwA;
const FAMultiMapCA * m_pMMapA;
const FAMultiMapCA * m_pActDataCA;
/// maps function id into an initial state, or to -1 if not valid
int * m_pFn2Ini;
unsigned int m_Fn2IniSize;
/// maximum token length
int m_MaxTokenLength;
enum {
DefMaxDepth = 5,
MinActSize = 3,
MaxFunctionId = 65536,
};
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAct2Arr_css.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ACT2ARR_CSS_H_
#define _FA_ACT2ARR_CSS_H_
#include "FAConfig.h"
#include "FAAct2ArrA.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FATagSet;
///
/// Parses CSS suggestion rules of the following format:
///
/// WORD [ WORD ] SCORE [ EDIT_TYPE ]
/// WORD ::= "any text" (only quotes should be escaped e.g. "\"")
/// SCORE ::= a C-style floating-point number in the range:
/// from -INT_MAX/127 to +INT_MAX/127
/// EDIT_TYPE ::= one of edit type tags
/// (where [X] means X is optional)
///
class FAAct2Arr_css : public FAAct2ArrA {
public:
FAAct2Arr_css (FAAllocatorA * pAlloc);
public:
void SetTagSet (const FATagSet * pTagSet);
/// (see FAAct2ArrA for details)
const int Process (const char * pStr, const int Len, const int ** ppArr,
int * pLeftCxAdjust, int * pRightCxAdjust);
private:
inline const int ParseWord (const char * pStr, const int Len);
inline const int ParseScore (const char * pStr, const int Len);
inline const int ParseEditType (const char * pStr, const int Len);
private:
FAArray_cont_t < int > m_arr;
const FATagSet * m_pTagSet;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FASplitStates.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_SPLITSTATES_H_
#define _FA_SPLITSTATES_H_
#include "FAConfig.h"
#include "FASplitSets.h"
#include "FAArray_cont_t.h"
#include "FAEncoder_pref.h"
#include "FAChain2Num_hash.h"
namespace BlingFire
{
class FARSNfaA;
class FASplitStates {
public:
FASplitStates (FAAllocatorA * pAlloc);
public:
/// sets up input automaton
void SetNfa (const FARSNfaA * pNfa);
/// sets up initial state -> eq class mapping
void SetS2C (const int * pS2C, const int Size);
/// makes processing
void Process ();
/// sets up output state -> eq class mapping
const int GetS2C (const int ** ppS2C);
/// returns object into the initial state
void Clear ();
private:
inline const int GetDstId (const int * pDsts, const int Dsts);
private:
const FARSNfaA * m_pNfa;
const int * m_pS2C;
int m_Size;
FAArray_cont_t < int > m_alphabet;
FAArray_cont_t < int > m_info;
FAArray_cont_t < int > m_tmp;
FASplitSets m_split_sets;
FAEncoder_pref m_enc;
FAChain2Num_hash m_dsts2num;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAChain2NumA.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_CHAIN2NUMA_H_
#define _FA_CHAIN2NUMA_H_
#include "FAConfig.h"
namespace BlingFire
{
class FAEncoderA;
class FAChain2NumA {
public:
// sets up chain encoder
virtual void SetEncoder (const FAEncoderA * pEncoder) = 0;
/// finds a Value by a Chain, returns NULL if not found
virtual const int * Get (const int * pChain, const int Size) const = 0;
/// adds a Chain -> Value pair, returns ChainIdx using by the GetChain method
virtual const int Add (const int * pChain,
const int Size,
const int Value) = 0;
/// returns the total number of chains stored in the map
virtual const int GetChainCount () const = 0;
/// returns Chain by its idx
/// idx \in [0, GetChainCount ())
/// return value is the size of the Chain
virtual const int GetChain (const int Idx,
const int ** pChain) const = 0;
/// returns value by its idx
virtual const int GetValue (const int Idx) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAWreRulesConfKeeper.h
|
<filename>blingfirecompile.library/inc/FAWreRulesConfKeeper.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WRERULESCONFKEEPER_H_
#define _FA_WRERULESCONFKEEPER_H_
#include "FAConfig.h"
namespace BlingFire
{
class FALDB;
class FAWREConfCA;
class FAMultiMapCA;
class FAWREConf_pack;
class FAMultiMap_pack;
///
/// Keeps compiled left and right sides of WRE rules and related execution
/// parameters.
///
/// Note: The pointers can be NULL, if yet not initialized
///
class FAWreRulesConfKeeper {
public:
FAWreRulesConfKeeper ();
~FAWreRulesConfKeeper ();
public:
/// this LDB will be used to get the data from
void SetLDB (const FALDB * pLDB);
/// initialization vector
void Init (const int * pValues, const int Size);
/// returns object into the initial state
void Clear ();
public:
/// returns compiled WRE configuration
const FAWREConfCA * GetWre () const;
/// returns actions associated with WRE rules
const FAMultiMapCA * GetActions () const;
/// returns true if case should be normalized
const bool GetIgnoreCase() const;
/// returns a minimal acceptable value for the unigram tag probaility
/// the value is a log prob
const float GetMinUniProb () const;
private:
// input LDB
const FALDB * m_pLDB;
// data
FAWREConf_pack * m_pWre;
FAMultiMap_pack * m_pActs;
bool m_IgnoreCase;
float m_MinUniProb;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAPrintUtils.h
|
<filename>blingfirecompile.library/inc/FAPrintUtils.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_PRINT_UTILS_H_
#define _FA_PRINT_UTILS_H_
#include "FAConfig.h"
#include <iostream>
namespace BlingFire
{
class FARegexpTree;
class FARegexpTree2Funcs;
class FAToken;
class FAWREToken;
class FATagSet;
/// template function for printing of arrays
/// array elements must support << operator
template <class Ty>
void FAPrintArray (std::ostream& os, const Ty * pA, const int Size)
{
if (NULL != pA) {
os << "[";
for (int i = 0; i < Size; ++i) {
os << " " << (int) pA [i];
}
os << " ]";
} else {
os << "NULL";
}
}
/// template function for reversed printing of arrays
/// array elements must support << operator
template <class Ty>
void FAPrintArray_rev (std::ostream& os, const Ty * pA, const int Size)
{
if (NULL != pA) {
os << "[";
for (int i = Size - 1; i >= 0; --i) {
os << " " << (int) pA [i];
}
os << " ]";
} else {
os << "NULL";
}
}
template<>
void FAPrintArray (std::ostream& os, const FAToken * pA, const int Size);
template<>
void FAPrintArray (std::ostream& os, const FAWREToken * pA, const int Size);
template<>
void FAPrintArray (std::ostream& os, const float * pA, const int Size);
/// prints out RegexpTree in dotty format
void FAPrintRegexpTree (
std::ostream& os,
const FARegexpTree * pTree,
const char * pRegexp
);
/// prints regexp functions in dotty format
void FAPrintRegexpFuncs (
std::ostream& os,
const FARegexpTree2Funcs * pFuncs,
const FARegexpTree * pTree
);
/// FAToken << operator
std::ostream& operator <<(std::ostream& os, const FAToken& Token);
/// FAWREToken << operator
std::ostream& operator <<(std::ostream& os, const FAWREToken& Token);
/// prints 0-separated list of words (in UTF-8)
void FAPrintWordList (
std::ostream& os,
const int * pWordList,
const int Count,
const char Delim = ' '
);
/// prints splitted chain (in UTF-8)
void FAPrintSplitting (
std::ostream& os,
const int * pChain,
const int ChainSize,
const int * pEnds,
const int EndsCount,
const char Delim = ' '
);
/// print a list of tags (in ASCII)
void FAPrintTagList (
std::ostream& os,
const FATagSet * pTagSet,
const int * pTags,
const int Count,
const char Delim = ' '
);
/// prints word (in UTF-8)
void FAPrintWord (
std::ostream& os,
const int * pWord,
const int WordLen
);
/// prints tagged word (in UTF-8)
void FAPrintTaggedWord (
std::ostream& os,
const FATagSet * pTagSet,
const int * pWord,
const int WordLen,
const int Tag
);
/// prints a single value (in ASCII)
void FAPrintValue (
std::ostream& os,
const int Value,
const int Width,
const bool Hex
);
/// prints a chain of digitis (in ASCII)
void FAPrintChain (
std::ostream& os,
const int * pChain,
const int ChainSize,
const int Dir,
const int Width,
const bool Hex
);
/// prints hyphenated word in UTF-8
void FAPrintHyphWord (
std::ostream& os,
const int * pWord,
const int * pHyphs,
const int WordLen
);
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FATransform_prefix_rev_t.h
|
<reponame>palerdot/BlingFire<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TRANSFORM_PREFIX_REV_T_H_
#define _FA_TRANSFORM_PREFIX_REV_T_H_
#include "FAConfig.h"
#include "FATransformCA_t.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// Makes reverse transformation to FATransform_prefix_t.
///
/// For example: if m_Delim == '_' then "rest_pref" -> "prefrest"
///
/// Notes:
/// 1. Transformation can be made in-place.
/// 2. If transformation is made in-place it needs word+pref memory,
/// even if the output result is always word length.
/// 3. m_Delim value should not interfere with word's alphabet
///
template < class Ty >
class FATransform_prefix_rev_t : public FATransformCA_t < Ty > {
public:
FATransform_prefix_rev_t ();
public:
/// sets up prefix delimiter value
void SetDelim (const Ty Delim);
/// makes transformation
/// Note: this function has to be *within* the class definition, because otherwise compiler makes an error
/// and generates some warnings about "unreferenced local function has been removed".
const int Process (
const Ty * pIn,
const int InCount,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
) const
{
// as __in_range(0, FALimits::MaxWordSize) const int InCount does not work
__analysis_assume (0 < InCount && FALimits::MaxWordSize >= InCount && pIn);
DebugLogAssert (0 < InCount && FALimits::MaxWordSize >= InCount && pIn);
const int DelimPos = GetDelimPos (pIn, InCount);
if (-1 == DelimPos)
return -1;
// see FATransform_prefix_rev_t< Ty >::GetDelimPos implementation
__analysis_assume (0 <= DelimPos && InCount > DelimPos);
DebugLogAssert (0 <= DelimPos && InCount > DelimPos);
// copy
if (pIn != pOut) {
if (MaxOutSize >= InCount - 1) {
int i;
// copy prefix
for (i = DelimPos + 1; i < InCount; ++i) {
*pOut++ = pIn [i];
}
// copy root
for (i = 0; i < DelimPos; ++i) {
*pOut++ = pIn [i];
}
}
// in-place
} else {
const int PrefLen = InCount - DelimPos - 1;
if (MaxOutSize >= InCount + PrefLen) {
int i;
// save prefix copy
Ty * pPrefCopy = pOut + InCount;
const Ty * pPref = pIn + DelimPos + 1;
for (i = 0; i < PrefLen; ++i) {
pPrefCopy [i] = pPref [i];
}
// move root right
Ty * pOutEnd = pOut + InCount - 2;
for (i = DelimPos - 1; i >= 0; --i) {
*pOutEnd-- = pIn [i];
}
// copy prefix back
for (i = 0; i < PrefLen; ++i) {
*pOut++ = pPrefCopy [i];
}
}
}
return InCount - 1;
}
private:
/// finds delimiter position
/// returns -1, if transformation cannot be applied
inline const int GetDelimPos (const Ty * pIn, const int InCount) const;
private:
// delimiter
Ty m_Delim;
// constants
enum {
DefDelim = 3,
};
};
template < class Ty >
FATransform_prefix_rev_t< Ty >::
FATransform_prefix_rev_t () :
m_Delim (DefDelim)
{
}
template < class Ty >
void FATransform_prefix_rev_t< Ty >::
SetDelim (const Ty Delim)
{
m_Delim = Delim;
}
template < class Ty >
inline const int FATransform_prefix_rev_t< Ty >::
GetDelimPos (const Ty * pIn, const int InCount) const
{
DebugLogAssert (pIn && 0 < InCount);
for (int i = 0; i < InCount; ++i) {
if (m_Delim == pIn [i])
return i;
}
return -1;
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMultiMapPack_fixed.h
|
<filename>blingfirecompile.library/inc/FAMultiMapPack_fixed.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MULTIMAPPACK_FIXED_H_
#define _FA_MULTIMAPPACK_FIXED_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAMultiMapA;
class FAAllocatorA;
///
/// Builds memory dump for the given FAMultiMapA
///
class FAMultiMapPack_fixed {
public:
FAMultiMapPack_fixed (FAAllocatorA * pAlloc);
public:
// sets up input map
void SetMultiMap (const FAMultiMapA * pMMap);
// sets up min sizeof value, otherwise minimum possible is used
void SetSizeOfValue (const int SizeOfValue);
// builds dump
void Process ();
// returns bulit dump
const int GetDump (const unsigned char ** ppDump) const;
private:
const int Prepare ();
private:
// input multi-map
const FAMultiMapA * m_pMMap;
// value size
int m_ValueSize;
// min Key
int m_MinKey;
// max Key
int m_MaxKey;
// maximum amount of values associated with a Key
int m_MaxCount;
// output dump
FAArray_cont_t < unsigned char > m_dump;
unsigned char * m_pDump;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAMultiMap_pack_fixed.h
|
<reponame>palerdot/BlingFire<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MULTIMAP_PACK_FIXED_H_
#define _FA_MULTIMAP_PACK_FIXED_H_
#include "FAConfig.h"
#include "FASetImageA.h"
#include "FAMultiMapCA.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// This class interprets dump created by FAMultiMapPack_fixed.
///
class FAMultiMap_pack_fixed : public FASetImageA,
public FAMultiMapCA {
public:
FAMultiMap_pack_fixed ();
public:
void SetImage (const unsigned char * pDump);
public:
const int Get (const int Key, const int ** ppValues) const;
const int Get (
const int Key,
__out_ecount_opt(MaxCount) int * pValues,
const int MaxCount
) const;
const int GetMaxCount () const;
private:
// points to encoded arrays
const unsigned char * m_pData;
// bytes per value
unsigned int m_SizeOfValue;
// bytes per array
unsigned int m_SizeOfArr;
// maximum array size
int m_MaxCount;
// min key value
int m_MinKey;
// min key value
int m_MaxKey;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAUtils.h
|
<gh_stars>1-10
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_UTILS_H_
#define _FA_UTILS_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FAUtils_cl.h"
#include "FAUtf32Utils.h"
#include "FAFsmConst.h"
#include "FAMultiMapCA.h"
#include "FASecurity.h"
namespace BlingFire
{
class FARSNfaA;
class FARSDfaA;
class FAMealyDfaA;
class FAMealyNfaA;
class FAMapA;
class FAMultiMapA;
class FATaggedTextCA;
class FATaggedTextA;
///
/// General purpose utility
///
/// makes output in binary mode
void FAIOSetup ();
/// makes input in binary mode
void FAInputIOSetup ();
/// Raises syntax error
///
/// pBuffer can be NULL if unknown
/// pMsg can be NULL if unknown
/// Offset can be -1 if unknown
///
void FASyntaxError (const char * pBuffer, // processing buffer pointer
const int BuffLength, // processing buffer length
const int Offset, // error offset
const char * pMsg); // error message
/// returns WIN32 code page number by the given encoding name
/// returns 0 if encoding name is unknown
const unsigned int FAEncoding2CodePage (const char * pEncStr);
/// implements comparison of indices by array values (for big to small sorting)
class FAIdxCmp_b2s {
public:
FAIdxCmp_b2s (const int * pValues);
public:
const bool operator () (const int Idx1, const int Idx2) const;
private:
const int * m_pValues;
};
/// implements comparison of indices by array values (for small to big sorting)
class FAIdxCmp_s2b {
public:
FAIdxCmp_s2b (const int * pValues);
public:
const bool operator () (const int Idx1, const int Idx2) const;
private:
const int * m_pValues;
};
/// returns true if the position in text is escaped
const bool FAIsEscaped (const int Pos, const char * pStr, const int StrLen);
/// returns true if FARSNfaA is in fact a DFA
const bool FAIsDfa (const FARSNfaA * pNfa);
/// builds alphabet for FARSNfaA
void FAGetAlphabet (const FARSNfaA * pNfa, FAArray_cont_t <int> * pA);
/// makes an NFA -> NFA copy
void FACopyNfa (FARSNfaA * pDstNfa, const FARSNfaA * pSrcNfa);
/// makes an DFA -> NFA copy
void FACopyDfa2Nfa (FARSNfaA * pDstNfa, const FARSDfaA * pSrcDfa);
/// makes an NFA -> DFA copy, possible only if FAIsDfa(pNfa) is true
void FACopyNfa2Dfa (FARSDfaA * pDstDfa, const FARSNfaA * pSrcNfa);
/// returns true if FAMultiMapA is empty
const bool FAIsEmpty (const FAMultiMapA * pMMap);
/// remaps OldDfa into NewDfa using Old2New Iw map,
/// in-place modification is not allowed
void FARemapRsFsmIws (
const FARSDfaA * pOldDfa,
FARSDfaA * pNewDfa,
const FAMapA * pOld2New
);
/// remaps OldNfa into NewNfa using Old2New Iw map,
/// in-place modification is not allowed
void FARemapRsFsmIws (
const FARSNfaA * pOldNfa,
FARSNfaA * pNewNfa,
const FAMapA * pOld2New
);
/// remaps OldSigma into NewSigma changing its Ows,
/// in-place modification is allowed
void FARemapMealySigma1 (
const FARSDfaA * pOldDfa,
const FAMealyDfaA * pOldSigma,
FAMealyDfaA * pNewSigma,
const FAMapA * pOld2New
);
/// remaps OldSigma into NewSigma changing its Iws,
/// in-place modification is not allowed
void FARemapMealySigma2 (
const FARSDfaA * pOldDfa,
const FAMealyDfaA * pOldSigma,
FAMealyDfaA * pNewSigma,
const FAMapA * pOld2New
);
/// remaps OldSigma into NewSigma changing its Iws,
/// in-place modification is not allowed
void FARemapMealySigma2 (
const FARSNfaA * pOldNfa,
const FAMealyNfaA * pOldSigma,
FAMealyNfaA * pNewSigma,
const FAMapA * pOld2New
);
/// reverse N:1 map
void FAReverseMap (FAMultiMapA * pRevMap, const FAMapA * pMap);
/// copies tagged text
void FACopyTaggedText (FATaggedTextA * pOut, const FATaggedTextCA * pIn);
///
/// Converts a string of space-separated integers into an array.
///
/// Base specifies the number base to use (see the help for strtol() for more details)
///
/// Returns the actual array size, if the return value is bigger than
/// MaxChainSize then array size should be increased to at least the
/// return value elements.
///
const int FAReadIntegerChain (
const char * pLine,
const int LineLen,
const int Base,
__out_ecount(MaxOutSize) int * pChain,
const int MaxChainSize
);
///
/// Converts a string of space separated hexadecial numbers into an array.
///
/// Calling this function is equivalent to calling
/// FAReadIntegerChain(pLine, LineLen, 16, pChain, MaxChainSize)
///
/// Returns the actual array size, if the return value is bigger than
/// MaxChainSize then array size should be increased to at least the
/// return value elements.
///
const int FAReadHexChain (
const char * pLine,
const int LineLen,
__out_ecount(MaxOutSize) int * pChain,
const int MaxChainSize
);
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FATestCmpMultiMap.h
|
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FATestCmpMultiMap.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TESTCMPMULTIMAP_H_
#define _FA_TESTCMPMULTIMAP_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FAMultiMapCA;
///
/// Compares whether two FAMultiMapCA interfaces behave the same way.
///
class FATestCmpMultiMap {
public:
FATestCmpMultiMap (FAAllocatorA * pAlloc);
public:
// sets up the first map
void SetMap1 (const FAMultiMapCA * pMMap1);
// sets up the second map
void SetMap2 (const FAMultiMapCA * pMMap2);
// returns true if interfaces behave identically
const bool Process (const int MaxKey);
private:
inline const int GetChain1 (const int Key, const int ** ppChain);
inline const int GetChain2 (const int Key, const int ** ppChain);
// returns true if chains are equal
inline const bool Equal (
const int * pChain1,
const int Size1,
const int * pChain2,
const int Size2
) const;
private:
const FAMultiMapCA * m_pMMap1;
const FAMultiMapCA * m_pMMap2;
FAArray_cont_t < int > m_chain1;
int * m_pChainBuff1;
int m_MaxChainSize1;
FAArray_cont_t < int > m_chain2;
int * m_pChainBuff2;
int m_MaxChainSize2;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMultiMapPack_mph.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MULTIMAPPACK_MPH_H_
#define _FA_MULTIMAPPACK_MPH_H_
#include "FAConfig.h"
#include "FAMap_judy.h"
#include "FASortMultiMap.h"
#include "FAChains2MinDfa_sort.h"
#include "FARSDfa2PerfHash.h"
#include "FAState2Ows_ar_uniq.h"
#include "FADfaPack_triv.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAMultiMapA;
class FAAllocatorA;
///
/// This class builds memory dump representation for the Multi Map refered
/// by some automaton or other structure. The class returns mapping from old
/// keys to new keys so the referee structure keys must be updated.
///
/// Note:
/// 1. Such a representation is very efficient from the memory point
/// of view for maps with huge number of keys as it uses RS-DFA to keep arrays
/// of values.
///
/// 2. The memory dump representation is as follows:
///
/// BEGIN
/// <MaxArraySize> : int
/// <Direction> : int
/// <DFA dump> : see FADfaPack_triv.h for details
/// END
///
class FAMultiMapPack_mph {
public:
FAMultiMapPack_mph (FAAllocatorA * pAlloc);
public:
/// sets up input map
void SetMultiMap (const FAMultiMapA * pMMap);
/// sets up direction, e.g. l2r, r2l in which to store multi-map arrays
void SetDirection (const int Direction);
/// builds dump
void Process ();
/// returns Old2New map for multi-map keys
const FAMapA * GetOld2New () const;
/// returns built dump
const int GetDump (const unsigned char ** ppDump) const;
private:
// returns object into initial state
inline void Clear ();
// helper method
inline const int GetChain (const int Key, const int ** ppChain);
inline void ProcessChains ();
private:
// input multi-map
const FAMultiMapA * m_pMMap;
// direction to process arrays
int m_Direction;
// sorts mmap's arrays in specified order
FASortMultiMap m_mmap_sort;
// builds min dfa from the list of sorted arrays
FAChains2MinDfa_sort m_arr2dfa;
// builds MPH for the given min DFA
FARSDfa2PerfHash m_dfa2mph;
// keeps MPH's transition reactions
FAState2Ows_ar_uniq m_state2ows;
// packs min Moore-Multi DFA into memory dump
FADfaPack_triv m_fsm2dump;
// keeps OldKey -> NewKey map
FAMap_judy m_old2new;
// keeps resulting memory dump
FAArray_cont_t < unsigned char > m_dump;
// keeps current chain if needed
FAArray_cont_t < int > m_chain_buff;
int * m_pChainBuff;
int m_MaxChainSize;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FABitMatrix_t.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_BITMATRIX_H_
#define _FA_BITMATRIX_H_
#include "FAConfig.h"
#include "FABitArray.h"
#include "FAAllocatorA.h"
namespace BlingFire
{
///
/// Maps (X,Y) -> T|F
/// X \in 0..N, Y \in 0..K
///
/// Additionaly holds:
/// 1. y = MinY (x), s.t. y = Min ({y_i}), Pred (x,y_i) == T
/// 2. y = MaxY (x), s.t. y = Max ({y_i}), Pred (x,y_i) == T
///
/// Note: It is assumed that base types to be used as X and Y
///
template < class Ty >
class FABitMatrix_t {
public:
FABitMatrix_t (FAAllocator * pAlloc);
~FABitMatrix_t ();
public:
// returns predicate value for the given pair
inline const bool Get (const Ty X, const Ty Y) const;
// returns min set Y for the given X
// returns -1 if not defined
inline const Ty GetMinY (const Ty X) const;
// returns max set Y for the given X
// returns -1 if not defined
inline const Ty GetMaxY (const Ty X) const;
// for the given X sets up all Ys s.t. (X,Y) == 1
void Set (const Ty X, const Ty * pYs, const int YsCount);
// returns container into the initial state
void Clear ();
private:
// makes sure that m_x2ys [X] contains new empty entry
inline void AddEmpty (const Ty X);
private:
class TPredYs {
public:
Ty m_min_y;
FABitArray m_values;
};
private:
FAArray_cont_t < TPredYs > m_x2ys;
FAAllocatorA * m_pAlloc;
};
template < class Ty >
FABitMatrix_t< Ty >::FABitMatrix_t (FAAllocator * pAlloc) :
m_pAlloc (pAlloc)
{
m_x2ys.SetAllocator (pAlloc);
m_x2ys.Create ();
}
template < class Ty >
FABitMatrix_t< Ty >::~FABitMatrix_t ()
{
FABitMatrix_t< Ty >::Clear ();
}
template < class Ty >
void FABitMatrix_t< Ty >::Clear ()
{
const int XCount = m_x2ys.size ();
for (int x = 0; x < XCount; ++x) {
m_x2ys [x].m_values.Clear ();
}
m_x2ys.Clear ();
}
template < class Ty >
void FABitMatrix_t< Ty >::AddEmpty (const Ty X)
{
const int XCount = m_x2ys.size ();
// see whether we should allocate new X entry
if (XCount <= X) {
m_x2ys.resize (X + 1, 10);
for (int x = XCount; x <= X; ++x) {
TPredYs & ys = m_x2ys [x];
ys.m_min_y = -1;
ys.m_values.SetAllocator (m_pAlloc);
ys.m_values.Create ();
}
} else {
// just clean existing X entry
TPredYs & ys = m_x2ys [X];
ys.m_min_y = -1;
ys.m_values.resize (0);
}
}
template < class Ty >
void FABitMatrix_t< Ty >::Set (const Ty X, const Ty * pYs, const int YsCount)
{
DebugLogAssert (0 <= X);
DebugLogAssert (FAIsSortUniqed (pYs, YsCount));
// ensure there is entry for X allocated
AddEmpty (X);
// store new values
if (0 < YsCount) {
DebugLogAssert (pYs);
const Ty MinY = pYs [0];
DebugLogAssert (0 <= MinY);
TPredYs & ys = m_x2ys [X];
ys.m_min_y = MinY;
const Ty MaxY = pYs [YsCount - 1];
FABitArray * pBits = &(ys.m_values);
DebugLogAssert (pBits);
const int BitCount = MaxY - MinY + 1;
pBits->resize (BitCount, 0);
pBits->set_bits (0, BitCount - 1, false);
for (int i = 0; i < YsCount; ++i) {
DebugLogAssert (pYs);
const int Bit = pYs [i] - MinY;
pBits->set_bit (Bit, true);
}
}
}
template < class Ty >
const bool FABitMatrix_t< Ty >::Get (const Ty X, const Ty Y) const
{
DebugLogAssert (0 <= X);
DebugLogAssert (0 <= Y);
const Ty MaxX = m_x2ys.size () - 1;
if (MaxX >= X) {
const TPredYs & ys = m_x2ys [X];
const Ty MinY = ys.m_min_y;
if (MinY <= Y) {
const FABitArray * pBits = &(ys.m_values);
DebugLogAssert (pBits);
const int BitCount = pBits->size ();
const int MaxY = MinY + BitCount - 1;
if (MaxY >= Y) {
const bool Val = pBits->get_bit (Y - MinY);
return Val;
} // of if (MaxY >= Y)
} // of if (MinY <= Y)
} // of if (MaxX >= X)
return false;
}
template < class Ty >
const Ty FABitMatrix_t< Ty >::GetMinY (const Ty X) const
{
DebugLogAssert (0 <= X);
const Ty MaxX = m_x2ys.size () - 1;
if (MaxX >= X) {
const TPredYs & ys = m_x2ys [X];
const Ty MinY = ys.m_min_y;
return MinY;
}
return -1;
}
template < class Ty >
const Ty FABitMatrix_t< Ty >::GetMaxY (const Ty X) const
{
DebugLogAssert (0 <= X);
const Ty MaxX = m_x2ys.size () - 1;
if (MaxX >= X) {
const TPredYs & ys = m_x2ys [X];
const Ty MinY = ys.m_min_y;
const FABitArray * pBits = &(ys.m_values);
DebugLogAssert (pBits);
const int BitCount = pBits->size ();
const int MaxY = MinY + BitCount - 1;
return MaxY;
}
return -1;
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAGcInterpreter_t.h
|
<filename>blingfirecompile.library/inc/FAGcInterpreter_t.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_GCINTERPRETER_T_H_
#define _FA_GCINTERPRETER_T_H_
#include "FAConfig.h"
#include "FAFsmConst.h"
#include "FAArray_cont_t.h"
#include "FAGcLDB.h"
#include "FAActionsA.h"
#include "FABrResult.h"
#include "FADigitizer_t.h"
#include "FADigitizer_dct_t.h"
#include "FAAutInterpretTools2_trbr_t.h"
#include "FAResolveMatchA.h"
#include "FAState2OwsCA.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Left part interpreter for left-hand-side GC-like rules. Takes single dump
/// (dump array) file as a data input. Ty defines word character type.
///
/// Usage:
/// 1. SetLDB
/// 2. SetActions
/// 3. SetIgnoreCase
/// foreach (Word in Input) do
/// 4. AddWord (Word)
/// 5. Process ()
/// done
///
template < class Ty >
class FAGcInterpreter_t {
public:
FAGcInterpreter_t (FAAllocatorA * pAlloc);
public:
/// sets up all resources needed for interpretation
void SetLDB (const FAGcLDB * pLDB);
/// sets up action execution call-back
void SetActions (const FAActionsA * pActs);
/// sets up ignore-case flag
void SetIgnoreCase (const bool IgnoreCase);
/// sets up match-resolver, if not specified uses all match-results
void SetResolver (FAResolveMatchA * pResolver);
/// sets up tag dictionary (needed for Process1 only)
void SetTagDict (const FADictInterpreter_t <Ty> * pTagDict);
/// adds next word (object should already be set up)
void AddWord (
const Ty * pText, // word text
const int TextLen, // word text length
const int Tag, // POS tag after disambiguation
const int DctSetId = -1 // tag dictionary id for the given word
);
/// sets up the context which will passed to actions, NULL by default
void SetContext (void * pContext);
/// makes analysis
void Process ();
private:
inline void Prepare ();
inline void Process_int ();
inline const int UpdateResults (
const int From,
const int To,
const int State
);
inline const int UpdateResults_resolver (
const int From,
const int To,
const int State
);
inline void ApplyResults_resolver ();
inline void Clear ();
private:
/// LDB
const FAGcLDB * m_pLDB;
int m_TokenType;
int m_TagOwBase;
const FAActionsA * m_pActs;
int m_WordCount;
/// text digitizer
FADigitizer_t < Ty > m_w2ow;
/// dict digitizer
FADigitizer_dct_t < Ty > m_w2ow_dct;
/// contiguous storage for tuples: <iw1, iw2>_1, <iw1, iw2>_2 ...
FAArray_cont_t < int > m_i2ows;
const int * m_pI2Ows;
/// common rules automaton
const FARSDfaCA * m_pRulesDfa;
const FAState2OwsCA * m_pRulesMap;
/// storage for matched rule nums
FAArray_cont_t < int > m_rule_nums;
int * m_pRuleNums;
int m_MaxRuleCount;
/// optional match resolver
FAResolveMatchA * m_pResolver;
/// trbr interpreter
FAAutInterpretTools2_trbr_t < int > m_r2trbr;
/// sub-expressions
FABrResult m_trbrs;
/// context pointer, can be NULL
void * m_pContext;
};
template < class Ty >
FAGcInterpreter_t< Ty >::FAGcInterpreter_t (FAAllocatorA * pAlloc) :
m_pLDB (NULL),
m_TokenType (0),
m_TagOwBase (0),
m_pActs (NULL),
m_WordCount (1),
m_pI2Ows (NULL),
m_pRulesDfa (NULL),
m_pRulesMap (NULL),
m_pRuleNums (NULL),
m_MaxRuleCount (0),
m_pResolver (NULL),
m_r2trbr (pAlloc),
m_trbrs (pAlloc),
m_pContext (NULL)
{
m_i2ows.SetAllocator (pAlloc);
m_i2ows.Create ();
m_i2ows.resize (FAFsmConst::DIGITIZER_COUNT);
int * pOut = m_i2ows.begin ();
for (int i = 0; i < FAFsmConst::DIGITIZER_COUNT; ++i) {
pOut [i] = FAFsmConst::IW_L_ANCHOR;
}
m_rule_nums.SetAllocator (pAlloc);
m_rule_nums.Create ();
m_w2ow.SetAnyIw (FAFsmConst::IW_ANY);
m_w2ow.SetAnyOw (FAFsmConst::IW_ANY);
m_w2ow_dct.SetAnyOw (FAFsmConst::IW_ANY);
}
template < class Ty >
void FAGcInterpreter_t< Ty >::SetIgnoreCase (const bool IgnoreCase)
{
m_w2ow.SetIgnoreCase (IgnoreCase);
}
template < class Ty >
void FAGcInterpreter_t< Ty >::SetLDB (const FAGcLDB * pLDB)
{
m_TokenType = 0;
m_TagOwBase = 0;
m_pRulesDfa = NULL;
m_pRulesMap = NULL;
m_pRuleNums = NULL;
m_pLDB = pLDB;
if (pLDB) {
const FAWREConfCA * pCm = pLDB->GetCommon ();
DebugLogAssert (pCm);
m_TokenType = pCm->GetTokenType ();
m_TagOwBase = pCm->GetTagOwBase ();
m_pRulesDfa = pCm->GetDfa1 ();
DebugLogAssert (m_pRulesDfa);
m_pRulesMap = pCm->GetState2Ows ();
DebugLogAssert (m_pRulesMap);
m_MaxRuleCount = m_pRulesMap->GetMaxOwsCount ();
DebugLogAssert (0 < m_MaxRuleCount);
m_rule_nums.resize (m_MaxRuleCount);
m_pRuleNums = m_rule_nums.begin ();
if (FAFsmConst::WRE_TT_TEXT & m_TokenType) {
const FARSDfaCA * pDigDfa = pCm->GetTxtDigDfa ();
const FAState2OwCA * pDigMap = pCm->GetTxtDigOws ();
DebugLogAssert (pDigDfa && pDigMap);
m_w2ow.SetRsDfa (pDigDfa);
m_w2ow.SetState2Ow (pDigMap);
m_w2ow.Prepare ();
}
if (FAFsmConst::WRE_TT_DCTS & m_TokenType) {
const FAArrayCA * pSet2Ow = pCm->GetDictDig ();
DebugLogAssert (pSet2Ow);
m_w2ow_dct.SetSet2Ow (pSet2Ow);
}
}
}
template < class Ty >
void FAGcInterpreter_t< Ty >::SetActions (const FAActionsA * pActs)
{
m_pActs = pActs;
}
template < class Ty >
void FAGcInterpreter_t< Ty >::SetResolver (FAResolveMatchA * pResolver)
{
m_pResolver = pResolver;
}
template < class Ty >
void FAGcInterpreter_t< Ty >::
SetTagDict (const FADictInterpreter_t <Ty> * pTagDict)
{
m_w2ow_dct.SetTagDict (pTagDict);
}
template < class Ty >
void FAGcInterpreter_t< Ty >::SetContext (void * pContext)
{
m_pContext = pContext;
}
template < class Ty >
void FAGcInterpreter_t< Ty >::
AddWord (
const Ty * pText,
const int TextLen,
const int Tag,
const int DctSetId
)
{
DebugLogAssert (FALimits::MinTag <= Tag && FALimits::MaxTag >= Tag);
DebugLogAssert (pText && 0 < TextLen);
int Ow;
// get Ow from text digitizer
if (FAFsmConst::WRE_TT_TEXT & m_TokenType) {
Ow = m_w2ow.Process (pText, TextLen);
m_i2ows.push_back (Ow);
} else {
m_i2ows.push_back (-1);
}
// get Ow from tag digitizer
if (FAFsmConst::WRE_TT_TAGS & m_TokenType) {
Ow = Tag + m_TagOwBase;
m_i2ows.push_back (Ow);
} else {
m_i2ows.push_back (-1);
}
// get Ow from dict digitizer
if (FAFsmConst::WRE_TT_DCTS & m_TokenType) {
if (-1 == DctSetId)
Ow = m_w2ow_dct.Process (pText, TextLen);
else
Ow = m_w2ow_dct.Process (DctSetId);
m_i2ows.push_back (Ow);
} else {
m_i2ows.push_back (-1);
}
m_WordCount++;
}
template < class Ty >
inline void FAGcInterpreter_t< Ty >::Prepare ()
{
DebugLogAssert (1 <= m_WordCount && \
m_i2ows.size () == (unsigned int) m_WordCount * FAFsmConst::DIGITIZER_COUNT);
// add right anchor as a last word
m_WordCount++;
const int OldSize = m_i2ows.size ();
m_i2ows.resize (OldSize + FAFsmConst::DIGITIZER_COUNT);
int * pOut = m_i2ows.begin () + OldSize;
for (int i = 0; i < FAFsmConst::DIGITIZER_COUNT; ++i) {
pOut [i] = FAFsmConst::IW_R_ANCHOR;
}
m_pI2Ows = m_i2ows.begin ();
}
template < class Ty >
inline void FAGcInterpreter_t< Ty >::Clear ()
{
m_WordCount = 1;
m_i2ows.resize (FAFsmConst::DIGITIZER_COUNT);
}
template < class Ty >
inline const int FAGcInterpreter_t< Ty >::
UpdateResults (const int From, const int To, const int State)
{
DebugLogAssert (m_pLDB);
DebugLogAssert (m_pActs);
DebugLogAssert (0 <= From && 0 <= To && From <= To);
// take left anchor into account
int From2;
if (0 < From) {
From2 = From - 1;
m_trbrs.SetBase (From - 1);
} else {
From2 = 0;
m_trbrs.SetBase (-1);
}
// take right anchor into account
int To2 = To - 1;
if (To == (m_WordCount - 1)) {
To2--;
}
const int Count = m_pRulesMap->GetOws (State, m_pRuleNums, m_MaxRuleCount);
DebugLogAssert (0 < Count && Count <= m_MaxRuleCount);
for (int i = 0; i < Count; ++i) {
const int RuleNum = m_pRuleNums [i];
// see whether sub-match is expected for this rule, NULL if not
const FAWREConfCA * pR = m_pLDB->GetRule (RuleNum);
if (pR) {
// get the configuration
const int TokenType = pR->GetTokenType ();
const FARSDfaCA * pDfa1 = pR->GetDfa1 ();
const FAMealyDfaCA * pSigma1 = pR->GetSigma1 ();
const FARSDfaCA * pDfa2 = pR->GetDfa2 ();
const FAMealyDfaCA * pSigma2 = pR->GetSigma2 ();
const FAMultiMapCA * pTrBrMap = pR->GetTrBrMap ();
// set the configuration up
m_r2trbr.SetTokenType (TokenType);
m_r2trbr.SetMealy1 (pDfa1, pSigma1);
m_r2trbr.SetMealy2 (pDfa2, pSigma2);
m_r2trbr.SetTrBrMap (pTrBrMap);
// calc input pointer and length
const int * pIn = m_pI2Ows + (From * FAFsmConst::DIGITIZER_COUNT);
DebugLogAssert ((unsigned int) From * FAFsmConst::DIGITIZER_COUNT < m_i2ows.size ());
const int Size = (To - From + 1) * FAFsmConst::DIGITIZER_COUNT;
DebugLogAssert (0 < Size && (unsigned int) Size <= m_i2ows.size ());
// make a sub-match extraction
m_r2trbr.Process2 (pIn, Size, &m_trbrs);
}
// call an action
m_pActs->Process (RuleNum, From2, To2, &m_trbrs, m_pContext);
m_trbrs.Clear ();
}
return From;
}
template < class Ty >
inline const int FAGcInterpreter_t< Ty >::
UpdateResults_resolver (
const int From,
const int To,
const int State
)
{
DebugLogAssert (m_pResolver);
DebugLogAssert (0 <= From && 0 <= To && From <= To);
const int Count = m_pRulesMap->GetOws (State, m_pRuleNums, m_MaxRuleCount);
DebugLogAssert (0 < Count && Count <= m_MaxRuleCount);
for (int i = 0; i < Count; ++i) {
const int RuleNum = m_pRuleNums [i];
m_pResolver->AddResult (RuleNum, From, To);
}
return From;
}
template < class Ty >
inline void FAGcInterpreter_t< Ty >::ApplyResults_resolver ()
{
DebugLogAssert (m_pResolver && m_pActs);
int RuleNum, From, To;
m_pResolver->Process ();
const int Count = m_pResolver->GetCount ();
for (int i = 0; i < Count; ++i) {
// get next resolved result
m_pResolver->GetResult (i, &RuleNum, &From, &To);
DebugLogAssert (0 <= From && 0 <= To && From <= To);
// take left anchor into account
int From2;
if (0 < From) {
From2 = From - 1;
m_trbrs.SetBase (From - 1);
} else {
From2 = 0;
m_trbrs.SetBase (-1);
}
// take right anchor into account
int To2 = To - 1;
if (To == (m_WordCount - 1)) {
To2--;
}
// see whether sub-match is expected for this rule, NULL if not
const FAWREConfCA * pR = m_pLDB->GetRule (RuleNum);
if (pR) {
// get the rest of configuration
const int TokenType = pR->GetTokenType ();
const FARSDfaCA * pDfa1 = pR->GetDfa1 ();
const FAMealyDfaCA * pSigma1 = pR->GetSigma1 ();
const FARSDfaCA * pDfa2 = pR->GetDfa2 ();
const FAMealyDfaCA * pSigma2 = pR->GetSigma2 ();
const FAMultiMapCA * pTrBrMap = pR->GetTrBrMap ();
// set the configuration up
m_r2trbr.SetTokenType (TokenType);
m_r2trbr.SetMealy1 (pDfa1, pSigma1);
m_r2trbr.SetMealy2 (pDfa2, pSigma2);
m_r2trbr.SetTrBrMap (pTrBrMap);
// calc input pointer and length
const int * pIn = m_pI2Ows + (From * FAFsmConst::DIGITIZER_COUNT);
DebugLogAssert ((unsigned int) From * FAFsmConst::DIGITIZER_COUNT < m_i2ows.size ());
const int Size = (To - From + 1) * FAFsmConst::DIGITIZER_COUNT;
DebugLogAssert (0 < Size && (unsigned int) Size <= m_i2ows.size ());
// make sub-match extraction
m_r2trbr.Process2 (pIn, Size, &m_trbrs);
}
// call the action
m_pActs->Process (RuleNum, From2, To2, &m_trbrs, m_pContext);
m_trbrs.Clear ();
}
m_pResolver->Clear ();
}
template < class Ty >
inline void FAGcInterpreter_t< Ty >::Process_int ()
{
int State, Iw;
const int InitialState = m_pRulesDfa->GetInitial ();
for (int j = 0; j < m_WordCount; ++j) {
State = InitialState;
const int FromPos = j;
for (int i = FromPos; i < m_WordCount; ++i) {
if (FAFsmConst::WRE_TT_TEXT & m_TokenType) {
Iw = m_pI2Ows [i * FAFsmConst::DIGITIZER_COUNT];
State = m_pRulesDfa->GetDest (State, Iw);
if (-1 == State)
break;
}
if (FAFsmConst::WRE_TT_TAGS & m_TokenType) {
Iw = m_pI2Ows [(i * FAFsmConst::DIGITIZER_COUNT) + 1];
State = m_pRulesDfa->GetDest (State, Iw);
if (-1 == State)
break;
}
if (FAFsmConst::WRE_TT_DCTS & m_TokenType) {
Iw = m_pI2Ows [(i * FAFsmConst::DIGITIZER_COUNT) + 2];
State = m_pRulesDfa->GetDest (State, Iw);
if (-1 == State)
break;
}
if (m_pRulesDfa->IsFinal (State)) {
int Ji;
if (m_pResolver) {
Ji = UpdateResults_resolver (FromPos, i, State);
} else {
Ji = UpdateResults (FromPos, i, State);
}
if (Ji > j) {
j = Ji;
}
}
} // of for (int i = 0; ...
} // of for (int j = 0; ...
if (m_pResolver) {
ApplyResults_resolver ();
}
}
template < class Ty >
void FAGcInterpreter_t< Ty >::Process ()
{
Prepare ();
Process_int ();
Clear ();
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARegexpParser_msyacc.h
|
/* *
* Microsoft VCBU Internal C++ YACC Parser v1.00.4101, <NAME> *
* *
* Modified by <NAME>, sergeio *
* *
* Note: Do not delete this file, it was not generated. *
* */
#ifndef _FA_REGEXPPARSER_MSYACC_H_
#define _FA_REGEXPPARSER_MSYACC_H_
#include "FASecurity.h"
#ifndef YYAPI_PACKAGE
# define YYAPI_TOKENNAME yychar //name used for return value of yylex
# define YYAPI_TOKENTYPE int //type of the token
# define YYAPI_TOKENEME(t) (t) //the value of the token that the parser should see
# define YYAPI_TOKENNONE -1 //the representation when there is no token
# define YYAPI_TOKENSTR(t) (itoa(t)) //string representation of the token
# define YYAPI_VALUENAME yylval //the name of the value of the token
# define YYAPI_VALUETYPE YYSTYPE //the type of the value of the token (if null, then the value is derivable from the token itself)
# define YYAPI_VALUEOF(v) (v) //how to get the value of the token
# define YYAPI_CALLAFTERYYLEX(t) //
# define YYAPI_PACKAGE //package is in use
#endif // YYAPI_PACKAGE
#ifndef YYMAXDEPTH
#define YYMAXDEPTH 7500
#endif
#ifndef YYFARDATA
#define YYFARDATA
#endif
#if ! defined YYSTATIC
#define YYSTATIC
#endif
#if ! defined YYCONST
#define YYCONST
#endif
#ifndef YYACT
#define YYACT yyact
#endif
#ifndef YYPACT
#define YYPACT yypact
#endif
#ifndef YYPGO
#define YYPGO yypgo
#endif
#ifndef YYR1
#define YYR1 yyr1
#endif
#ifndef YYR2
#define YYR2 yyr2
#endif
#ifndef YYCHK
#define YYCHK yychk
#endif
#ifndef YYDEF
#define YYDEF yydef
#endif
#ifndef YYV
#define YYV yyv
#endif
#ifndef YYS
#define YYS yys
#endif
#ifndef YYLOCAL
#define YYLOCAL
#endif
#ifndef YYR_T
#define YYR_T int
#endif
typedef YYR_T yyr_t;
#ifndef YYEXIND_T
#define YYEXIND_T unsigned int
#endif
typedef YYEXIND_T yyexind_t;
#ifndef YYOPTTIME
#define YYOPTTIME 0
#endif
#ifndef YYLEX
# define YYLEX yylex
#endif
//provided for compatibility with YACC
#define yyerrok ClearErrRecoveryState()
#define yyclearin YYAPI_TOKENNAME = YYAPI_TOKENNONE
namespace BlingFire
{
class FAToken;
class FARegexpTree;
class FAParserStateKeeper_msyacc {
public:
FAParserStateKeeper_msyacc ()
{
ResetState ();
}
protected:
void ResetState ()
{
YYAPI_TOKENNAME = YYAPI_TOKENNONE;
yynerrs = yyerrflag = yystate = 0;
// disable warning for array index out of range
#pragma warning ( push )
#pragma warning ( disable : 6201 )
yyps = &yys[-1];
yypv = &yyv[-1];
#pragma warning ( pop )
#ifdef YYDEBUG
yydebug = 0;
#endif
}
protected:
typedef union {
int node_id;
const FAToken* value;
} YYSTYPE;
// current input token
YYAPI_TOKENTYPE YYAPI_TOKENNAME;
#ifdef YYAPI_VALUETYPE
YYAPI_VALUETYPE YYAPI_VALUENAME;
#endif
YYSTYPE yyval;
int yynerrs;
int yyerrflag;
short yystate, *yyps;
YYSTYPE *yypv;
YYSTYPE yyv [YYMAXDEPTH];
short yys [YYMAXDEPTH];
#ifdef YYDEBUG
int yydebug;
#endif
};
class FARegexpParser_msyacc : public FAParserStateKeeper_msyacc {
public:
FARegexpParser_msyacc ();
~FARegexpParser_msyacc ();
public:
/* make processing */
void Process ();
/* sets up an input container */
void SetTokens (const FAToken * pTokens, const int TokensCount);
/* sets up regular expression text */
void SetRegexp (const char * pRegexp, const int RegexpLen);
/* sets up an output container */
void SetTree (FARegexpTree * pTree);
/* returns false, if the parsing was successful */
const bool GetStatus () const;
/* returns index of the last accepted token */
const int GetTokenIdx () const;
private:
int Parse ();
int NoOfErrors () const;
int ErrRecoveryState () const;
void ClearErrRecoveryState ();
YYAPI_TOKENTYPE GetCurrentToken () const;
void SetCurrentToken (YYAPI_TOKENTYPE newToken);
int yylex ();
void Clear ();
#ifdef YYDUMP
void DumpYYS ();
void DumpYYV ();
#endif
#ifdef YYDEBUG
const char* yytokenstr (int token);
void Trace (const char *message, const char *tokname, short state = 0);
void Trace (const char *message, int state, short tostate = 0, short token = 0);
#endif
void yyerror (const char *szMsg);
private:
/* output tree */
FARegexpTree * m_pTree;
/* input tokens */
const FAToken * m_pTokens;
/* the number of tokens */
int m_token_count;
/* currently processing token */
int m_token_pos;
/* true, if something went wrong */
bool m_parse_failed;
/* regexp text and length */
const char * m_pRegexp;
int m_RegexpLen;
static YYCONST short yyexca [];
#if YYOPTTIME
static YYCONST yyexind_t yyexcaind [];
#endif
static YYCONST short yyact [];
static YYCONST short yypact [];
static YYCONST short yypgo [];
static YYCONST yyr_t yyr1 [];
static YYCONST yyr_t yyr2 [];
static YYCONST short yychk [];
static YYCONST short yydef [];
#ifdef YYRECOVER
static YYCONST short yyrecover [];
#endif
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FATrBr2Symbol.h
|
<reponame>palerdot/BlingFire<filename>blingfirecompile.library/inc/FATrBr2Symbol.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TRBR2SYMBOL_H_
#define _FA_TRBR2SYMBOL_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FAToken.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// This class changes triangular brackets into artificial FARegexpTree::SYMBOL
/// tokens + ordinary brackets so the parser will treat them as an ordinary
/// symbols. FANfaCreator_*_trbr(s) use these symbols to create special arcs.
///
/// 1. trbr-regexp:
/// <1 Re1 > <2 Re2 >
/// 2. lexer's output:
/// LTRBR:'<1' Re1 RTRBR:'>' LTRBR:'<2' Re2 RTRBR:'>'
/// 3. tokens substitution:
/// LBR SYMBOL:<1,-1> LBR Re1 RBR SYMBOL::<1,-2> RBR
/// LBR SYMBOL:<2,-1> LBR Re2 RBR SYMBOL:<2,-2> RBR
/// 4. tokens sequence looks as if someone wrote:
/// ( '<1' ( Re1 ) '1>' ) ( '<2' ( Re2 ) '2>' )
///
/// SYMBOL:<1,-1> - token type symbol, offset == 1, length == -1
///
class FATrBr2Symbol {
public:
FATrBr2Symbol (FAAllocatorA * pAlloc);
public:
// sets up regular expression text
void SetRegexp (const char * pRegexp, const int Length);
// sets up input/output tokens contaner
void SetTokens (FAArray_cont_t < FAToken > * pTokens);
// makes processing
void Process ();
private:
// regexp text
const char * m_pRegexp;
int m_Length;
// input/output container
FAArray_cont_t < FAToken > * m_pTokens;
FAArray_cont_t < int > m_stack;
FAArray_cont_t < FAToken > m_tmp_tokens;
static const FAToken m_left_br;
static const FAToken m_right_br;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAWordToProb_t.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_WORDTOPROB_T_H_
#define _FA_WORDTOPROB_T_H_
#include "FAConfig.h"
#include "FARSDfaCA.h"
#include "FAState2OwCA.h"
#include "FAUtils_cl.h"
#include "FAFsmConst.h"
#include "FATransformCA_t.h"
#include "FAW2PConfKeeper.h"
#include "FALimits.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// Word --> Probability Guesser
///
/// Notes:
///
/// 1. The Ty is the character type, can be any basic type enough to hold
/// expected Unicode values.
///
template < class Ty >
class FAWordToProb_t {
public:
FAWordToProb_t ();
virtual ~FAWordToProb_t ();
public:
/// Note: this method expects initialized configuration object
/// pInTr can be NULL if no transformation assumed
virtual void SetConf (
const FAW2PConfKeeper * pConf,
const FATransformCA_t < Ty > * pInTr
);
/// returns a log prob of the input word
const float GetProb (
const Ty * pWordStr, // input word
const int WordLen // inpur word length
);
/// returns an int value proportional to the log prob of the input word
const int GetIntProb (
const Ty * pWordStr, // input word
const int WordLen // inpur word length
);
private:
/// returns object into the initial state
inline void Clear ();
// takes results from the m_pIn and stores into pOut
inline void ApplyInTr (
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
);
private:
const FARSDfaCA * m_pDfa;
const FAState2OwCA * m_pState2Ow;
const FATransformCA_t < Ty > * m_pInTr;
const Ty * m_pIn;
int m_InSize;
bool m_IgnoreCase;
int m_MaxIntProb;
float * m_pInt2Float;
float m_MinProbVal;
float m_MaxProbVal;
bool m_fReady;
/// charmap
const FAMultiMapCA * m_pCharMap;
enum {
DefUnfoundProb = 2 * FAFsmConst::MIN_LOG_PROB,
DefDelimIw = FAFsmConst::IW_ANY,
};
};
template < class Ty >
FAWordToProb_t< Ty >::FAWordToProb_t () :
m_pDfa (NULL),
m_pState2Ow (NULL),
m_pInTr (NULL),
m_pIn (NULL),
m_InSize (0),
m_IgnoreCase (false),
m_MaxIntProb (0),
m_pInt2Float (NULL),
m_MinProbVal (0),
m_MaxProbVal (1),
m_fReady (false),
m_pCharMap (NULL)
{
}
template < class Ty >
FAWordToProb_t< Ty >::~FAWordToProb_t ()
{
FAWordToProb_t< Ty >::Clear ();
}
template < class Ty >
inline void FAWordToProb_t< Ty >::Clear ()
{
m_IgnoreCase = false;
m_fReady = false;
m_pCharMap = NULL;
m_MaxIntProb = 0;
m_MinProbVal = 0;
m_MaxProbVal = 1;
if (m_pInt2Float) {
delete [] m_pInt2Float;
m_pInt2Float = NULL;
}
}
template < class Ty >
void FAWordToProb_t< Ty >::SetConf (
const FAW2PConfKeeper * pConf,
const FATransformCA_t < Ty > * pInTr
)
{
FAWordToProb_t< Ty >::Clear ();
DebugLogAssert (false == m_fReady);
if (NULL == pConf) {
return;
}
m_pDfa = pConf->GetRsDfa ();
m_pState2Ow = pConf->GetState2Ow ();
m_IgnoreCase = pConf->GetIgnoreCase ();
m_pCharMap = pConf->GetCharMap ();
m_pInTr = pInTr;
m_MaxIntProb = pConf->GetMaxProb ();
if (0 < m_MaxIntProb) {
// allocate the dictionary
m_pInt2Float = NEW float [m_MaxIntProb + 1];
LogAssert (m_pInt2Float);
const float Min = pConf->GetMinProbVal ();
const float Max = pConf->GetMaxProbVal ();
for (int i = 0; i <= m_MaxIntProb; ++i) {
const float LogProb =
((float(i) / float(m_MaxIntProb)) * (Max - Min)) + Min;
m_pInt2Float [i] = LogProb;
}
}
m_fReady = m_pDfa && m_pState2Ow && m_pInt2Float && 0 < m_MaxIntProb;
}
template < class Ty >
inline void FAWordToProb_t< Ty >::
ApplyInTr (__out_ecount(MaxOutSize) Ty * pOut, const int MaxOutSize)
{
DebugLogAssert (m_pInTr);
DebugLogAssert (m_pIn && 0 < m_InSize && m_InSize <= FALimits::MaxWordLen);
DebugLogAssert (pOut && 0 < MaxOutSize);
// apply the transformation, possibly in-place
const int OutSize = m_pInTr->Process (m_pIn, m_InSize, pOut, MaxOutSize);
// see whether there was some transformation made
if (0 < OutSize && OutSize <= MaxOutSize) {
m_pIn = pOut;
m_InSize = OutSize;
}
}
template < class Ty >
const int FAWordToProb_t< Ty >::GetIntProb (const Ty * pWordStr, const int WordSize)
{
DebugLogAssert (pWordStr && 0 < WordSize && FALimits::MaxWordLen >= WordSize);
__analysis_assume (pWordStr && 0 < WordSize && FALimits::MaxWordLen >= WordSize);
if (!m_fReady) {
return -1;
}
const int TmpBuffSize = 2 * FALimits::MaxWordLen;
Ty TmpBuff [TmpBuffSize];
m_pIn = pWordStr;
m_InSize = WordSize;
// normalize case, if needed
if (m_IgnoreCase) {
for (int i = 0 ; i < WordSize; ++i) {
const int InSymbol = (int) m_pIn [i] ;
const int OutSymbol = FAUtf32ToLower (InSymbol) ;
TmpBuff [i] = (Ty) OutSymbol ;
}
m_pIn = TmpBuff;
}
// normalize characters
if (m_pCharMap) {
// in-place is fine
m_InSize = FANormalizeWord (m_pIn, m_InSize, \
TmpBuff, TmpBuffSize, m_pCharMap);
m_pIn = TmpBuff;
}
// apply transformation, if needed
if (m_pInTr) {
ApplyInTr (TmpBuff, TmpBuffSize);
}
int Pos = 0;
int State = m_pDfa->GetInitial ();
// read word left to right direction
for (; Pos < m_InSize; ++Pos) {
const int Iw = (unsigned int) (m_pIn [Pos]);
State = m_pDfa->GetDest (State, Iw);
if (-1 == State) {
break;
}
}
if (-1 != State) {
const int Ow = m_pState2Ow->GetOw (State);
// could be -1, if state does not have a reaction
return Ow;
}
return -1;
}
template < class Ty >
const float FAWordToProb_t< Ty >::GetProb (const Ty * pWordStr, const int WordSize)
{
const int IntProb = GetIntProb (pWordStr, WordSize);
if (-1 != IntProb) {
DebugLogAssert (0 <= IntProb && IntProb <= m_MaxIntProb);
return m_pInt2Float [IntProb];
} else {
return float (DefUnfoundProb);
}
}
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAArrayCA.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ARRAYCA_H_
#define _FA_ARRAYCA_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// This is a common interface for packed read-only arrays.
///
class FAArrayCA {
public:
/// returns value by the index, 0..Count-1
virtual const int GetAt (const int Idx) const = 0;
/// returns number of elementes in the array
virtual const int GetCount () const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAOw2IwCA.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_OW2IW_CA_H_
#define _FA_OW2IW_CA_H_
#include "FAConfig.h"
namespace BlingFire
{
///
/// Returns input weight and destination state for the given output weight
/// and source state.
///
/// Note: This is basicly needed by automaton-based reversed Minimal Perfect
/// Hash (MPH), e.g. for Id -> Chain mapping.
///
class FAOw2IwCA {
public:
/// For the given State and Ow1 returns DstState, Iw and Ow2,
/// where Ow2 is equal or less to the specified Ow1. If no transition
/// exist, e.g. no Ow exist less than Ow1 at the State then it returns -1.
virtual const int GetDestIwOw (
const int State,
const int Ow1,
int * pIw,
int * pOw2
) const = 0;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAMultiMap_ar_uniq.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MULTIMAP_AR_UNIQ_H_
#define _FA_MULTIMAP_AR_UNIQ_H_
#include "FAConfig.h"
#include "FAMultiMapA.h"
#include "FAArray_cont_t.h"
#include "FAMap_judy.h"
#include "FASecurity.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Array-based implementation of FAMultiMapA.
///
/// Note:
/// 1. Add (one element to the end) and Remove operations are not supported
///
class FAMultiMap_ar_uniq : public FAMultiMapA {
public:
FAMultiMap_ar_uniq ();
virtual ~FAMultiMap_ar_uniq ();
public:
// sets up allocator (call before any usage)
void SetAllocator (FAAllocatorA * pAlloc);
// makes map as if it was just constructed
void Clear ();
/// FAMultiMapA
public:
const int Get (
const int Key,
__out_ecount_opt(MaxCount) int * pValues,
const int MaxCount
) const;
const int GetMaxCount () const;
const int Get (const int Key, const int ** ppValues) const;
void Set (const int Key, const int * pValues, const int ValuesCount);
// not implemented
void Add (const int Key, const int Value);
const int Next (int * pKey, const int ** ppValues) const;
const int Prev (int * pKey, const int ** ppValues) const;
public:
// makes Arrays of values sorted and uniq
void SortUniq ();
private:
// ensures m_key2idx holds the Key
inline void ensure (const int Key);
// calculates hash key
inline static const int hash_key (const int * pValues, const int Size);
// compares values with array by index Idx
inline const bool equal (
const int Idx,
const int * pValues,
const int Size
) const;
private:
// mapping: key -> idx
FAArray_cont_t < int > m_key2idx;
// mapping: idx -> array
FAArray_cont_t < FAArray_cont_t < int > > m_idx2arr;
// mapping: HashKey (array) -> idx
FAMap_judy m_hash2idx;
// keeps max number of elements Get can return
int m_MaxCount;
// allocator
FAAllocatorA * m_pAlloc;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAAct2Arr_score_tag.h
|
<reponame>palerdot/BlingFire
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_ACT2ARR_SCORE_TAG_H_
#define _FA_ACT2ARR_SCORE_TAG_H_
#include "FAConfig.h"
#include "FAAct2ArrA.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
class FATagSet;
///
/// Parses SCORE TAG actions of the following format:
///
/// SCORE TAG
/// SCORE ::= an integer value
/// TAG ::= one of tags defined in the tagset
///
class FAAct2Arr_score_tag : public FAAct2ArrA {
public:
FAAct2Arr_score_tag (FAAllocatorA * pAlloc);
public:
void SetTagSet (const FATagSet * pTagSet);
/// (see FAAct2ArrA for details)
const int Process (const char * pStr, const int Len, const int ** ppArr,
int * pLeftCxAdjust, int * pRightCxAdjust);
private:
inline const int ParseScore (const char * pStr, const int Len);
inline const int ParseTag (const char * pStr, const int Len);
private:
FAArray_cont_t < int > m_arr;
const FATagSet * m_pTagSet;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FAUtf32ToEnc.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_UTF32TOENC_H_
#define _FA_UTF32TOENC_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FASecurity.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Converts from the UTF-32LE into the specified encoding
///
class FAUtf32ToEnc {
public:
FAUtf32ToEnc (FAAllocatorA * pAlloc);
~FAUtf32ToEnc ();
public:
/// specifies output encoding or codepage name, e.g. 1251, CP1251, KOI8-R
void SetEncodingName (const char * pEncStr);
/// returns actual number of bytes (not symbols) in the output buffer
/// returns -1 if convertion is not possible
const int Process (
const int * pInStr,
unsigned int InSize,
__out_ecount(MaxOutSize) char * pOutStr,
const unsigned int MaxOutSize
);
private:
bool m_is_utf16;
bool m_fBE;
bool m_is_utf8;
unsigned int m_cp;
FAArray_cont_t < wchar_t > m_tmp_buff;
enum { DefTmpBuffSize = 1024 };
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FAUtf8Utils.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_UTF8UTILS_H_
#define _FA_UTF8UTILS_H_
#include "FAConfig.h"
#include "FASecurity.h"
namespace BlingFire
{
/// Converts UTF-8 symbol into int (UTF-32LE),
/// returns new pointer in the multi byte sequence,
/// NULL if the sequence is not a valid UTF8 string
const char * FAUtf8ToInt (const char * ptr, int * result);
/// Converts UTF-8 symbol into int (UTF-32LE),
/// returns new pointer in the multi byte sequence,
/// NULL if the sequence is not a valid UTF8 string
/// empty input buffers are not allowed
const char * FAUtf8ToInt (
const char * pBegin,
const char * pEnd,
int * pResult
);
/// Converts int (UTF-32LE) into UTF-8 symbol
/// returns end pointer of the output sequence
char * FAIntToUtf8 (
const int Symbol,
__out_ecount(MaxSize) char * ptr,
const int MaxSize
);
/// returns the size of UTF-8 symbol
/// returns 0 if it is not a valid symbol
const int FAUtf8Size (const char * ptr);
/// returns the size of UTF-32LE symbol in UTF-8 encoding
/// returns 0 if it is not a valid symbol
const int FAUtf8Size (const int Symbol);
/// Converts 0-terminated UTF8 string to the array of ints.
/// Returns the number of used elements in the array.
/// Returns -1 if the input sequence is invalid.
const int FAStrUtf8ToArray (
const char * pStr,
__out_ecount(MaxSize) int * pArray,
const int MaxSize
);
/// Converts UTF8 string of specified length to the array of ints.
/// Returns the number of used elements in the array.
/// Returns -1 if the input sequence is invalid.
const int FAStrUtf8ToArray (
const char * pStr,
const int Len,
__out_ecount(MaxSize) int * pArray,
const int MaxSize
);
/// Converts UTF8 string of specified length to the array of ints and
/// for each UTF-32 character returns its offset in the pStr.
/// Returns the number of used elements in the array.
/// Returns -1 if the input sequence is invalid.
const int FAStrUtf8ToArray (
const char * pStr,
const int Len,
__out_ecount(MaxSize) int * pArray,
__out_ecount(MaxSize) int * pOffsets,
const int MaxSize
);
/// Converts UTF8 string of specified length to the array of ints
/// using each byte as a character.
/// Returns the number of used elements in the array.
/// Returns -1 if the input sequence is invalid.
const int FAStrUtf8AsBytesToArray (
const char * pStr,
const int Len,
__out_ecount(MaxSize) int * pArray,
const int MaxSize
);
/// Converts UTF8 string of specified length to the array of ints
/// using each byte as a character and for each returned character
// returns its offset in the pStr.
/// Returns the number of used elements in the array.
/// Returns -1 if the input sequence is invalid.
const int FAStrUtf8AsBytesToArray (
const char * pStr,
const int Len,
__out_ecount(MaxSize) int * pArray,
__out_ecount(MaxSize) int * pOffsets,
const int MaxSize
);
/// Converts int (UTF-32LE) into UTF-16LE encoded string
/// returns end pointer of the output sequence
/// return NULL if buffer length is insufficient
wchar_t * FAIntToUtf16LE (
int Symbol,
__out_ecount(MaxSize) wchar_t * ptr,
const int MaxSize
);
/// Converts UTF-8 string of specified length to UTF-16LE string
/// for each UTF-16 character returns its offset in the pStr.
/// Returns the number of used elements in the array.
/// If the input buffer is not sufficient for all input sequences, decodes as many that fit in the supplied buffer
/// Returns -1 if the input sequence is invalid.
const int FAStrUtf8ToUtf16LE (
const char * pStr,
const int Len,
__out_ecount(MaxSize) wchar_t * pArray,
__out_ecount(MaxSize) int * pOffsets,
const int MaxSize
);
/// Converts array of ints (UTF-32LE) into UTF-8 string of upto MaxStrSize
/// length, does not place terminating 0-byte. Returns output string length.
/// Returns -1 for invalid input sequence.
const int FAArrayToStrUtf8 (
const int * pArray,
const int Size,
__out_ecount(MaxStrSize) char * pStr,
const int MaxStrSize
);
/// returns true if pEncName is a valid UTF-8 encoding name
const bool FAIsUtf8Enc (const char * pEncName);
/// Normalizes characters in the valid input UTF-8 string and returns a valid
/// UTF-8 string. if the input string is invalid UTF-8 then -1 is returned
/// otherwise the output string size is returned.
///
/// Note: if the output buffer is not big enough, the needed size is returned
/// but no actual data is copied to the output buffer.
///
/// Parameters:
/// pStr, Len represent the input string
/// pOutStr, MaxOutSize output buffer of MaxOutSize elements
/// NormAlgo specifies the normalization algorithm :
/// FAFsmConst::NORMALIZE_DEFAULT -- current production normalization for case and diacritics
/// FAFsmConst::NORMALIZE_PRESERVE_DIACRITICS -- preserves all diacritics, but drops the case
/// FAFsmConst::NORMALIZE_REMOVE_DIACRITICS -- removes diacritics (more than DEFAULT) and drops the case
///
const int FAStrUtf8Normalize (
const char * pStr,
const int Len,
__out_ecount(MaxOutSize) char * pOutStr,
const int MaxOutSize,
const int NormAlgo
);
/// UTF-8 constants
class FAUtf8Const {
public:
enum {
MAX_CHAR_SIZE = 4,
};
};
}
#endif
|
palerdot/BlingFire
|
blingfireclient.library/inc/FATransform_hyph_redup_rev_t.h
|
<filename>blingfireclient.library/inc/FATransform_hyph_redup_rev_t.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TRANSFORM_HYPH_REDUP_REV_T_H_
#define _FA_TRANSFORM_HYPH_REDUP_REV_T_H_
#include "FAConfig.h"
#include "FATransformCA_t.h"
#include "FASecurity.h"
namespace BlingFire
{
///
/// This class makes reverse to FATransform_hyph_redup_t transformation.
///
/// For example:
/// "aaab\x02ce" -> "aaab-aaabce"
/// Where 0x02 was selected as a delimiter
///
/// Note:
/// 1. If the transformation is not applicable then Process method return -1.
/// 2. if pIn == pOut then transformation is made in-place.
///
template < class Ty >
class FATransform_hyph_redup_rev_t : public FATransformCA_t < Ty > {
public:
FATransform_hyph_redup_rev_t ();
public:
/// sets up delimiter value
void SetDelim (const Ty Delim);
/// makes transformation
/// Note: this function has to be *within* the class definition, because otherwise compiler makes an error
/// and generates some warnings about "unreferenced local function has been removed".
const int Process (
const Ty * pIn,
const int InCount,
__out_ecount(MaxOutSize) Ty * pOut,
const int MaxOutSize
) const
{
// as __in_range(0, FALimits::MaxWordSize) const int InCount does not work
__analysis_assume (0 < InCount && FALimits::MaxWordSize >= InCount && pIn);
DebugLogAssert (0 < InCount && FALimits::MaxWordSize >= InCount && pIn);
// find reduplication delimiter
const int DelimPos = GetDelimPos (pIn, InCount);
DebugLogAssert (DelimPos < InCount);
// most of the times it won't be found
if (-1 == DelimPos) {
return -1;
} else {
// see FATransform_hyph_redup_rev_t< Ty >::GetDelimPos for details
__analysis_assume (0 <= DelimPos && InCount > DelimPos);
DebugLogAssert (0 <= DelimPos && InCount > DelimPos);
const int OutSize = InCount + DelimPos;
if (MaxOutSize >= OutSize) {
// move or copy suffix, if needed
const int SuffixLen = InCount - (DelimPos + 1);
if (0 < SuffixLen) {
const Ty * pSuffIn = pIn + DelimPos + 1;
Ty * pSuffOut = pOut + (DelimPos << 1) + 1;
for (int i = SuffixLen - 1; i >= 0; --i) {
pSuffOut [i] = pSuffIn [i];
}
}
// change delimiter to hyphen
pOut [DelimPos] = DefHyphen;
// check whether transformation is made in-place
if (pIn == pOut) {
Ty * pPrefOut = pOut + DelimPos + 1;
for (int i = 0; i < DelimPos; ++i) {
pPrefOut [i] = pIn [i];
}
} else {
Ty * pOut2 = pOut + DelimPos + 1;
for (int i = 0; i < DelimPos; ++i) {
const Ty Symbol = pIn [i];
pOut [i] = Symbol;
pOut2 [i] = Symbol;
}
}
} // of if (MaxOutSize >= OutSize) ...
return OutSize;
} // of if (-1 == DelimPos) ...
}
private:
// returns delimiter position, -1 if not found
inline const int GetDelimPos (const Ty * pIn, const int InCount) const;
private:
// delimiter
Ty m_Delim;
// constants
enum {
DefDelim = 2,
DefHyphen = '-',
};
};
template < class Ty >
FATransform_hyph_redup_rev_t< Ty >::
FATransform_hyph_redup_rev_t () :
m_Delim (DefDelim)
{
}
template < class Ty >
void FATransform_hyph_redup_rev_t< Ty >::
SetDelim (const Ty Delim)
{
m_Delim = Delim;
}
template < class Ty >
inline const int FATransform_hyph_redup_rev_t< Ty >::
GetDelimPos (const Ty * pIn, const int InCount) const
{
for (int i = 0; i < InCount; ++i) {
if (m_Delim == pIn [i]) {
return i;
}
}
return -1;
}
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FATaggedText.h
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_TAGGEDTEXT_H_
#define _FA_TAGGEDTEXT_H_
#include "FAConfig.h"
#include "FATaggedTextA.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAAllocatorA;
///
/// Tagged text container.
///
class FATaggedText : public FATaggedTextA {
public:
FATaggedText (FAAllocatorA * pAlloc);
virtual ~FATaggedText ();
public:
const int GetWordCount () const;
const int GetWord (const int Num, const int ** pWord) const;
const int GetTag (const int Num) const;
const int GetOffset (const int Num) const;
public:
void AddWord (
const int * pWord,
const int Length,
const int Tag
);
void AddWord (
const int * pWord,
const int Length,
const int Tag,
const int Offset
);
void Clear ();
public:
void SetTags (const int * pTags, const int Count);
private:
FAArray_cont_t < int > m_chars;
FAArray_cont_t < int > m_num2sl;
FAArray_cont_t < int > m_num2tag;
FAArray_cont_t < int > m_num2offset;
};
}
#endif
|
palerdot/BlingFire
|
blingfirecompile.library/inc/FARegexpTree2PosEqs.h
|
<gh_stars>1000+
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_REGEXPTREE2POSEQS_H_
#define _FA_REGEXPTREE2POSEQS_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
#include "FAMap_judy.h"
#include "FATopoSort_t.h"
#include "FABitArray.h"
#include "FARegexpTreeTopoGraph.h"
namespace BlingFire
{
class FARegexpTree;
///
/// This class calculates equivalence classes on regular expresion's
/// positions.
///
/// Note:
///
/// 1. In order to get maximum gain from the class regular expression is
/// ought to be simplified, e.g. (a*b)* -> (a|b)*; (a b d)|(a c d) ->
/// a(b|c)d; (a+b?)* -> (a|b)* ...
///
/// 2. All disjunctions in sub-expressions have to be left or right
/// associative only.
///
class FARegexpTree2PosEqs {
public:
FARegexpTree2PosEqs (FAAllocatorA * pAlloc);
public:
// sets up regular expression tree
void SetRegexpTree (const FARegexpTree * pTree);
// calculates position equivalence classes
void Process ();
// returns mapping from each position to the smallest equivalent position
const FAMapA * GetPos2Class () const;
private:
/// builds node -> pos map
void CalcNode2Pos ();
/// sorts nodes in topological order
void TopoSort ();
/// finds a set of equivalent positions for the given node NodeId
void FindEqPos (const int NodeId);
/// fills m_Pos2Class in
void BuildEqClasses ();
private:
// input tree
const FARegexpTree * m_pTree;
// topological sorter
FATopoSort_t < FARegexpTreeTopoGraph > m_sort;
// pos: 0 .. m_MaxPos
int m_MaxPos;
// mapping from node_id into position, -1 if undefined
FAArray_cont_t < int > m_Node2Pos;
// temporary storage of equivalent nodes and positions
FAArray_cont_t < int > m_eq_pos;
// seen nodes
FABitArray m_seen;
// mapping from pos to the smallest equivalent position
FAMap_judy m_Pos2Class;
};
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.