России Бориса Николаевича Ельцина Кафедра "Информационные технологии и автоматизация проектирования" курсовая

Вид материалаКурсовая

Содержание


Operation = 1
Подобный материал:
1   2   3
itsFinalStates;


public ReadAndOptimize(string path, List graph, Lexeme lex)

{

setInputKA(path, graph, lex);

}


private void setInputKA(string path, List graph, Lexeme lex)

{

Decomposition decomposition = new Decomposition();

StreamReader fin = new StreamReader(path);

itsSymbols = new List();

itsFinalStates = new List();

List itsTransition = new List();

List> itsReplaceList = new List>();

List> itsStates = new List>();

List itsAchievable;

List itsReplaceForNotAvailableStates;

int symbols = 0, states = 0;

try

{

decomposition.setString(fin.ReadLine());

for (int i = 0; i < decomposition.getNumber(0) ; ++i)

lex.Add(fin.ReadLine());


decomposition.setString(fin.ReadLine());

states = decomposition.getNumber(0);

symbols = decomposition.getNumber(1);


for (int i = 0; i < symbols; ++i) itsSymbols.Add(fin.ReadLine()[0]);


decomposition.setString(fin.ReadLine());

for (int i = 0; i < decomposition.Count; ++i) itsFinalStates.Add(decomposition.getNumber(i));


for (int i = 0; i < states; ++i)

{

decomposition.setString(fin.ReadLine());

for (int j = 0; j < decomposition.Count; ++j)

{

itsTransition.Add(decomposition.getNumber(j));

}

addTransition(itsTransition, itsStates, itsReplaceList, i);

itsTransition.Clear();

}

}

catch (Exception)

{

throw new IOException();

}

finally

{

fin.Close();

}

Replace(itsStates, itsFinalStates, itsReplaceList);

itsAchievable = new List();

createListOfAchievable(0, itsAchievable, itsStates);

itsReplaceForNotAvailableStates = new List();

createReplaceList(itsStates, itsReplaceForNotAvailableStates, itsAchievable);

Replace(itsStates, itsFinalStates, itsReplaceForNotAvailableStates);

//***************************

createStates(graph, itsSymbols, itsStates);

}


private void addTransition(List transition, List> states, List> replacelist, int currentstate)

{

int tmp = 0;

tmp = Contains(states, transition);

if (tmp != -1)

{

foreach (List trans in replacelist)

{

if (trans.Contains(tmp))

{

trans.Add(currentstate);

return;

}

}

}

states.Add(new List(transition));

replacelist.Add(new List());

replacelist[replacelist.Count - 1].Add(currentstate);

}


private int Contains(List> list, List item)

{

bool flag = false;

int index = -1;

foreach (List inlist in list)

{

++index;

if (inlist.Count != item.Count) continue;

flag = true;

for (int i = 0; i < inlist.Count; ++i)

{

if (inlist[i] != item[i]) flag = false;

}

if (flag) return index;

}

return -1;

}


private void Replace(List> states, List finalstates, List> replacelist)

{

foreach (List state in states)

{

for (int i = 0; i < state.Count; ++i)

state[i] = getNewState(replacelist, state[i]);

}

for (int i = 0; i < finalstates.Count; ++i) finalstates[i] = getNewState(replacelist, finalstates[i]);

}

//second, for not available states

private void Replace(List> states, List finalstates, List replacelist)

{

foreach (List state in states)

{

for (int i = 0; i < state.Count; ++i)

if (state[i] != -1) state[i] = replacelist.IndexOf(state[i]);

}

for (int i = 0; i < finalstates.Count; ++i)

if (!replacelist.Contains(finalstates[i])) finalstates.RemoveAt(i);

else finalstates[i] = replacelist.IndexOf(finalstates[i]);

}


private int getNewState(List> replacelist, int item)

{

if (item == -1) return -1;

for (int index = 0; index < replacelist.Count; ++index)

if (replacelist[index].Contains(item)) return index;

return -1;

}


private void createStates(List states, List symbols, List> optimizestates)

{

int tmp = -1;

bool flag;

foreach (List transition in optimizestates)

{

++tmp;

flag = false;

if (itsFinalStates.Contains(tmp)) flag = true;

states.Add(new State(symbols, transition, flag));

}

}


private void createListOfAchievable(int currentstate, List achievable, List> states)

{

if (achievable.Contains(currentstate)) return;

achievable.Add(currentstate);

foreach (int transition in states[currentstate])

{

if ((transition != -1) && (!achievable.Contains(transition))) createListOfAchievable(transition, achievable, states);

}


}


private void createReplaceList(List> states, List replacelist, List achievable)

{

for (int i = 0; i < states.Count; ++i)

{

if (achievable.Contains(i)) replacelist.Add(i);

}


for (int i = states.Count - 1; i >= 0; --i)

{

if (!achievable.Contains(i))

{

states.RemoveAt(i);

}

}

}

public List Symbols

{

get { return itsSymbols; }

}

}

Сохранение автомата:

class SaveKA

{

public SaveKA(string path, List states, List symbols)

{

StreamWriter fout = new StreamWriter(path);

try

{

fout.WriteLine(states.Count.ToString() + " " + symbols.Count.ToString());

for (int i = 0; i < symbols.Count; ++i)

fout.WriteLine(symbols[i]);

writeFinaleStates(fout, states);

writeTransitions(fout, states, symbols);

}

catch (Exception)

{

throw new IOException();

}

finally

{

fout.Close();

}

}


private void writeFinaleStates(StreamWriter fout, List states)

{

bool flag = true;

for (int i = 0; i < states.Count; ++i)

if (states[i].FiniteState)

if (flag)

{

fout.Write(i.ToString());

flag = false;

}

else fout.Write(" " + i.ToString());

}


private void writeTransitions(StreamWriter fout, List states, List symbols)

{

bool flag;

for (int i = 0; i < states.Count; ++i)

{

flag = true;

fout.WriteLine();

for (int j = 0; j < symbols.Count; ++j)

{

try

{

if (flag) fout.Write(states[i].setNextSymbol(symbols[j]).ToString());

else fout.Write(" " + states[i].setNextSymbol(symbols[j]).ToString());

flag = false;

}

catch (IncorrectSymbolExeption)

{

if (flag) fout.Write("-1");

else fout.Write(" " + "-1");

flag = false;

}

}

}

}

}

Класс который формирует лексемы:

class Lexeme

{

private enum TypeOfLexeme

{

TYPE = 0,

OPERATION = 1,

IDENTIFICATOR = 2,

CONSTANT = 3

}


private int Entier;

private int Fractional;

private int Power;

private string Identificator;

private CurrentAnalysis Flag;


private List ListOfLexeme;

private List ListOfReservedWords;


public Lexeme()

{

ListOfLexeme = new List();

ListOfReservedWords = new List();

Entier = 0;

Fractional = 0;

Power = 0;

Flag = new CurrentAnalysis();

}

public void Add(string reservedword)

{

ListOfReservedWords.Add(reservedword);

}

public void ClearLex()

{

ListOfLexeme.Clear();

}

public void Reset()

{

Entier = 0;

Fractional = 0;

Power = 0;

Identificator = "";

Flag.Reset();

}


public void OnStateChange(char symbol)

{

switch (symbol)

{

case '.':

if (Flag.Current == CurrentAnalysis.ENTIER)

{

Flag.Current = CurrentAnalysis.FRACTIONAL;

}

break;

case '+':

case '-':

case '*':

case '/':

case '(':

case ')':

case '=':

case ',':

case '':

if (Flag.InProcess)

{

if (Flag.Current == CurrentAnalysis.ENTIER) ListOfLexeme.Add(new Lexemes.CINTEGER(Entier));

if (Flag.Current == CurrentAnalysis.FRACTIONAL) ListOfLexeme.Add(new Lexemes.CFLOAT(Entier, Fractional, Power));

if (Flag.Current == CurrentAnalysis.IDENTIFICATOR)

{

if (Identificator == "integer") ListOfLexeme.Add(new Lexemes.TINTEGER());

else if (Identificator == "float") ListOfLexeme.Add(new Lexemes.TFLOAT());

else ListOfLexeme.Add(new Lexemes.IDENTIFICATOR(Identificator));

}

Reset();

}

createLexemeOperation(symbol);

break;

case ';':

if (Flag.InProcess)

{

if (Flag.Current == CurrentAnalysis.ENTIER) ListOfLexeme.Add(new Lexemes.CINTEGER(Entier));

if (Flag.Current == CurrentAnalysis.FRACTIONAL) ListOfLexeme.Add(new Lexemes.CFLOAT(Entier, Fractional, Power));

if (Flag.Current == CurrentAnalysis.IDENTIFICATOR)

{

if (Identificator == "integer") ListOfLexeme.Add(new Lexemes.TINTEGER());

else if (Identificator == "float") ListOfLexeme.Add(new Lexemes.TFLOAT());

else ListOfLexeme.Add(new Lexemes.IDENTIFICATOR(Identificator));

}

Reset();

ListOfLexeme.Add(new Lexemes.END());

}

break;

case ' ':

case '\n':

if (Flag.InProcess)

{

if (Flag.Current == CurrentAnalysis.ENTIER) ListOfLexeme.Add(new Lexemes.CINTEGER(Entier));

if (Flag.Current == CurrentAnalysis.FRACTIONAL) ListOfLexeme.Add(new Lexemes.CFLOAT(Entier, Fractional, Power));

if (Flag.Current == CurrentAnalysis.IDENTIFICATOR)

{

if (Identificator == "integer") ListOfLexeme.Add(new Lexemes.TINTEGER());

else if (Identificator == "float") ListOfLexeme.Add(new Lexemes.TFLOAT());

else ListOfLexeme.Add(new Lexemes.IDENTIFICATOR(Identificator));

}

Reset();

}

break;

default:

if ((Flag.InProcess) && (Flag.Current == CurrentAnalysis.FRACTIONAL))

{

setNextSymbol(symbol);

return;

}

if (char.IsNumber(symbol))

{

Entier = symbol - '0';

Flag.InProcess = true;

Flag.Current = CurrentAnalysis.ENTIER;

}

else

{

Identificator = symbol.ToString();

Flag.InProcess = true;

Flag.Current = CurrentAnalysis.IDENTIFICATOR;

}

break;

}

}


public void setNextSymbol(char symbol)

{

if (Flag.InProcess)//in process

{

switch (Flag.Current)

{

case (0)://Entier

Entier = Entier * 10 + (symbol - '0');

break;

case (1)://FRACTIONAL

Fractional = Fractional * 10 + (symbol - '0');

++Power;

break;

case (2)://symbols

Identificator += symbol;

break;

default: break;

}

}

else //empty

{

switch (symbol)

{

case ' ':

case '\n':

break;

case ';':

ListOfLexeme.Add(new Lexemes.END());

break;

case '+':

case '-':

case '*':

case '/':

case '(':

case ')':

case '=':

case ',':

case '':

createLexemeOperation(symbol);

break;

default:

if (char.IsNumber(symbol)) Entier = symbol - '0';

else Identificator = symbol.ToString();

break;


}

}

}

private void createLexemeOperation(char ch)

{

switch (ch)

{

case '+': ListOfLexeme.Add(new Lexemes.PLUS()); break;

case '-': ListOfLexeme.Add(new Lexemes.MINUS()); break;

case '*': ListOfLexeme.Add(new Lexemes.MULTIPLY()); break;

case '/': ListOfLexeme.Add(new Lexemes.DIVISION()); break;

case '=': ListOfLexeme.Add(new Lexemes.GIVE()); break;

case '(': ListOfLexeme.Add(new Lexemes.OPENPARENTHESIS()); break;

case ')': ListOfLexeme.Add(new Lexemes.CLOSEPARENTHESIS()); break;

case ',': ListOfLexeme.Add(new Lexemes.COMMA()); break;

case '': ListOfLexeme.Add(new Lexemes.POW()); break;

default: break;

}

}


private class CurrentAnalysis

{

private bool Process;

private int CurrentLexeme;

public const int ENTIER = 0;

public const int FRACTIONAL = 1;

public const int IDENTIFICATOR = 2;


public CurrentAnalysis()

{

InProcess = false;

CurrentLexeme = -1;

}

public void Reset()

{

InProcess = false;

CurrentLexeme = -1;

}

public int Current

{

get { return CurrentLexeme; }

set { CurrentLexeme = value; }

}

public bool InProcess

{

get { return Process; }

set { Process = value; }

}

}


public List LexemsList

{

get { return ListOfLexeme; }

}


}

Вспомогательный класс для чтения из файла, разбивает текст

class Decomposition

{

private List Numbers;

private int itsCount;

public Decomposition()

{

Numbers = new List();

itsCount = 0;

}

public void setString(string str)

{

Numbers.Clear();

int SpacePosition = 0;

for (int i = 0; i < str.Length; ++i)

{

if ((str[i] == ' ') | (i == str.Length - 1) | (str[i] == '\t'))

{

Numbers.Add(int.Parse(str.Substring(SpacePosition, i - SpacePosition + 1)));

SpacePosition = i;

}

if ((Numbers.Count == 0) & (i == str.Length)) Numbers.Add(int.Parse(str));

}

itsCount = Numbers.Count;

}

public int getNumber(int index)

{

if (index >= Numbers.Count) return 0;

return Numbers[index];

}

public int Count

{

get { return itsCount; }

}

}

Лексемы:

class CFLOAT : ILexeme

{

private MyType number;

public CFLOAT(int entier, int fractional, int power)

{

int tmp = 1;

for (int i = 0; i < power; ++i)

tmp *= 10;

number = new MyType((float)entier + (float)fractional / tmp);

}

public char Symbol

{ get { return 'c'; } }

public override string ToString()

{

return number.ToString();

}

public MyType Number

{

get { return number; }

}

}

class CINTEGER : ILexeme

{

private MyType number;

public CINTEGER(int entier)

{

number = new MyType(entier);

}

public char Symbol

{ get { return 'c'; } }

public override string ToString()

{

return number.ToString();

}

public MyType Number

{

get { return number; }

}

}

class CLOSEPARENTHESIS : ILexeme

{

public CLOSEPARENTHESIS() { }

public char Symbol

{ get { return ')'; } }

public override string ToString()

{

return ")";

}


#region ILexeme Members


public MyType Number

{

get { throw new Exception("The method or operation is not implemented."); }

}


#endregion

}

class COMMA : ILexeme

{

public COMMA() { }

public char Symbol

{ get { return ','; } }

public override string ToString()

{

return ",";

}


MyType ILexeme.Number

{

get { throw new Exception("The method or operation is not implemented."); }

}

}

class DIVISION : ILexeme

{

public DIVISION() { }

public char Symbol

{ get { return '/'; } }

public override string ToString()

{

return "/";

}


#region ILexeme Members


public MyType Number

{

get { throw new Exception("The method or operation is not implemented."); }

}


#endregion

}

class END : ILexeme

{

public END() { }

public char Symbol

{ get { return ';'; } }

public override string ToString()

{

return ";";

}


#region ILexeme Members


public MyType Number

{

get { throw new Exception("The method or operation is not implemented."); }

}


#endregion

}

class GIVE : ILexeme

{

public GIVE() { }

public char Symbol

{ get { return '='; } }

public override string ToString()

{

return "=";

}


#region ILexeme Members


public MyType Number

{

get { throw new Exception("The method or operation is not implemented."); }

}


#endregion

}

class IDENTIFICATOR : ILexeme

{

private string name;

public IDENTIFICATOR(string identity)

{

name = identity;

}

public char Symbol

{ get { return 'v'; } }

public override string ToString()

{

return name;

}


#region ILexeme Members


public MyType Number

{

get { throw new Exception("The method or operation is not implemented."); }

}


#endregion

}

class MINUS : ILexeme

{

public MINUS() { }

public char Symbol

{ get { return '-'; } }

public override string ToString()

{

return "-";

}


#region ILexeme Members


public MyType Number

{

get { throw new Exception("The method or operation is not implemented."); }

}


#endregion

}

class MULTIPLY : ILexeme

{

public MULTIPLY() { }

public char Symbol

{ get { return '*'; } }

public override string ToString()

{

return "*";

}