Розробка системних програмних модулів та компонент систем програмування

Автор: Пользователь скрыл имя, 25 Февраля 2012 в 16:19, курсовая работа

Описание работы

Незважаючи на більш ніж піввікову історію обчислювальної техніки, формально роком народження теорії трансляторів можна вважати 1957, коли з'явився перший транслятор мови Фортран, створений Бекасом. До цього часу створення трансляторів було досить "творчим" процесом. Лише поява теорії формальних мов і строгих математичних моделей дозволило перейти від "творчості" до "науки".

Содержание

Вступ
1. Огляд методів та способів проектування трансляторів
1.1. Основні поняття і визначення
1.2. Узагальнена структура транслятора
1.4. Варіанти взаємодії блоків транслятора
2. Формальний опис вхідної мови програмування
2.1. Деталізований опис вхідної мови в термінах розширеної нотації Бекуса-Наура
2.2. Опис термінальних символів та ключових слів
3. Розробка транслятора вхідної мови програмування
3.1. Вибір технології програмування
3.2. Проектування таблиць транслятора та вибір структур даних
3.3. Розробка лексичного аналізатора
3.3.1. Розробка граф-схеми алгоритму
3.3.2. Опис програмної реалізації лексичного аналізатора
3.4. Розробка синтаксичного та семантичного аналізатора
3.4.1. Розробка граф-схеми алгоритму
3.4.2. Опис програмної реалізації синтаксичного та семантичного аналізатора
3.5. Розробка генератора коду
3.5.1. Розробка граф-схеми алгоритму
3.5.2. Опис програмної реалізації генератора коду
4. Опис інтерфейсу та інструкції користувача
4.1. Опис інтерфейсу
4.1.1. Головне меню та панель інструментів.
4.2. Інструкція програміста
4.2.1. Алфавіт мови
4.2.2. Коментарі
4.2.3. Тип даних
4.2.4. Розділи, використовувані при написанні програм
4.2.5. Типи операцій
4.2.6. Типи операторів
5. Відлагодження та тестування програми
5.1. Виявлення лексичних помилок
5.2. Виявлення синтаксичних помилок
5.3. Виявлення семантичних помилок
5.4. Загальна перевірка коректності роботи транслятора
Висновки
Список літератури
Додатки
А. Лістинг програми

Работа содержит 1 файл

asm_cource_k9.doc

— 1,020.00 Кб (Скачать)

                                return ProcessIdent();

                            }

                            return Lex;

                        }

                    case 'P':

                        {

                            if (SourcePointer < Source.Length - 7)

                            {

                                string sub = Source.Substring(SourcePointer, 7);

                                if ((sub == "Program") & (LexemEnd(Source[SourcePointer + 7]) | IsSeparator(Source[SourcePointer + 7]) | (Source[SourcePointer + 7] == '$')))

                                {

                                    Lex.Type = LexemType.Program;

                                    Lex.Text = "Program";

                                    Lex.Line = Line;

                                    Lex.Value = 0;

                                    SourcePointer += 7;

                                }

                                else

                                {

                                    return ProcessIdent();

                                }

                            }

                            else

                            {

                                return ProcessIdent();

                            }

                            return Lex;

                        }

                    case 'V':

                        {

                            if (SourcePointer < Source.Length - 3)

                            {

                                string sub = Source.Substring(SourcePointer, 3);

                                if ((sub == "Var") & (LexemEnd(Source[SourcePointer + 3]) | IsSeparator(Source[SourcePointer + 3]) | (Source[SourcePointer + 3] == '$')))

                                {

                                    Lex.Type = LexemType.Var;

                                    Lex.Text = "Var";

                                    Lex.Line = Line;

                                    Lex.Value = 0;

                                    SourcePointer += 3;

                                }

                                else

                                {

                                    return ProcessIdent();

                                }

                            }

                            else

                            {

                                return ProcessIdent();

                            }

                            return Lex;

                        }

                    case '\"':

                        {

                            string lex = "";

                            while (Source[SourcePointer] != '$')

                            {

                                lex += Source[SourcePointer++];

                                if (Source[SourcePointer] == '\"')

                                {

                                    lex += Source[SourcePointer++];

                                    Lex.Line = Line;

                                    Lex.Text = lex;

                                    Lex.Type = LexemType.String;

                                    return Lex;

                                }

 

                            }

                            Lex.Line = Line;

                            Lex.Text = lex;

                            Lex.Type = LexemType.Null;

                            AddError("Do not closed string", Line);

                            return Lex;

                        }

                    case 'S':

                        {

                            if (SourcePointer < Source.Length - 5)

                            {

                                string sub = Source.Substring(SourcePointer, 5);

                                if ((sub == "Start") & (LexemEnd(Source[SourcePointer + 5]) | IsSeparator(Source[SourcePointer + 5]) | (Source[SourcePointer + 3] == '$')))

                                {

                                    Lex.Type = LexemType.Start;

                                    Lex.Text = "Start";

                                    Lex.Line = Line;

                                    Lex.Value = 0;

                                    SourcePointer += 5;

                                }

                                else

                                {

                                    return ProcessIdent();

                                }

                            }

                            else

                            {

                                return ProcessIdent();

                            }

                            return Lex;

                        }

                }

                if ((Source[SourcePointer] >= '0') & (Source[SourcePointer] <= '9'))

                {

                    return ProcessConst();

                }

                return ProcessIdent();

            }

            else

            {

                string lex = "";

                while (Source[SourcePointer] != '$')

                {

                    lex += Source[SourcePointer++];

                    if (LexemEnd(Source[SourcePointer]) | IsSeparator(Source[SourcePointer]) | (Source[SourcePointer] == '$'))

                    {

                        break;

                    }

                }

                AddError("Unrecognized identifier [" + lex + "]", Line);

                Lex.Text = "Error";

                Lex.Type = LexemType.Null;

                return Lex;

            }

        }

        private Lexema ProcessConst()

        {

            Lexema Lex = new Lexema();

            string lex = "";

            while (Source[SourcePointer] != '$')

            {

                lex += Source[SourcePointer++];

                if (LexemEnd(Source[SourcePointer]) | IsSeparator(Source[SourcePointer]) | (Source[SourcePointer] == '$'))

                {

                    break;

                }

            }

            bool IsConst = true;

            int i = 0;

            if (lex[0] == '-')

            {

                i = 1;

            }

            for (; i < lex.Length; i++)

            {

                if (!((lex[i] >= '0')&(lex[i] <= '9')))

                {

                    IsConst = false;

                    break;

                }

            }

            if (IsConst)

            {

                Lex.Type = LexemType.Const;

                Lex.Text = lex;

                Lex.Line = Line;

                Lex.Value = Convert.ToInt32(lex);

            }

            else

            {

                Lex.Type = LexemType.Null;

                Lex.Line = Line;

                AddError("Unrecognized symbol [" + lex + "]", Line);

            }

            return Lex;

        }

        private Lexema ProcessIdent()

        {

            Lexema Lex = new Lexema();

            string lex = "";

            while (Source[SourcePointer] != '$')

            {

                lex += Source[SourcePointer++];

                if (LexemEnd(Source[SourcePointer]) | IsSeparator(Source[SourcePointer]) | (Source[SourcePointer] == '$'))

                {

                    break;

                }

            }

            bool IsIdent = true;

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

            {

                if (!IdentContain(lex[i]))

                {

                    IsIdent = false;

                    break;

                }

            }

            if (IsIdent)

            {

                Lex.Type = LexemType.Ident;

                Lex.Text = lex;

                Lex.Line = Line;

            }

            else

            {

                Lex.Type = LexemType.Null;

                Lex.Line = Line;

                AddError("Unrecognized symbol [" + lex +"]",Line);

            }

            return Lex;

        }

        private bool IsSeparator(char ch)

        {

            if ((ch == '\n') | (ch == '\t') | (ch == ' '))

                return true;

            else

                return false;

        }

        private bool LexemEnd(char ch)

        {

            if ((ch == ';') | (ch == '\"') | (ch == '(') | (ch == ')') | (ch == ',') | (ch == '/'))

            {

                return true;

            }

            else

            {

                return false;

            }

        }

        private bool LexemStart(char ch)

        {

            if (((ch >= 65) & (ch <= 90)) | (ch == ';') | (ch == ':') |

                (ch == '+') | (ch == '-') | (ch == '!') | (ch == '&') |

                (ch == '|') | ((ch >= 48) & (ch <= 57)) | (ch == '=') |

                (ch == '\"') | (ch == '(') | (ch == ')') | (ch == ',') |

                (ch == '$'))

            {

                return true;

            }

            else

            {

                return false;

            }

        }

        private bool IdentContain(char ch)

        {

            if (((ch >= 65) & (ch <= 90)) | ((ch >= 48) & (ch <= 57)) | ((ch >= 'a') & (ch <= 'z')) | (ch == '_'))

            {

                return true;

            }

            else

            {

                return false;

            }

        }

        private void AddError(string error_text, int line)

        {

            Error Err = new Error();

            Err.Line = line;

            Err.Text = error_text;

            LexErrors.Add(Err);

        }

        private int SourcePointer;

        private int Line;

        private string Source;

        public Errors LexErrors;

    }

    public class SyntaxAnalizer

    {

        //constructor

        public SyntaxAnalizer(List<Lexema> Lt,int[,] tbl)

        {

            LblCount = 0;

            ExitCicleCount = 0;

            StartCicleCount = 0;

            StrCount = 0;

            StringTable = new List<Strings>();

            Strings temp = new Strings();

            temp.Name = "format";

            temp.Value = "\"%i\"";

            StringTable.Add(temp);

            GramTree = new TreeNode("Дерево граматичного розбору:");

            LexTable = Lt;

            SyntaxErrors = new Errors();

            IdentTable = new List<Identificator>();

            PriorityTable = new Int32[40, 40];

            int length = Convert.ToInt32(Math.Sqrt(Convert.ToDouble(tbl.Length)));

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

            {

                for (int j = 0; j < length; j++)

                {

                    PriorityTable[i, j] = tbl[i, j];

                }

            }

            //Створення таблиці констант, які зустрічаються в вхідній програмі

            ConstTable = new List<Identificator>();

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

            {

                if (Lt[i].Type == LexemType.Const)

                {

                    Identificator Id = new Identificator();

                    Id.Line = Lt[i].Line;

                    Id.Name = "const" + Lt[i].Text;

                    Id.Value = Convert.ToInt32(Lt[i].Text);

                    Id.IsDeclared = true;

                    bool contain = false;

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

                    {

                        if (ConstTable[j].Value == Id.Value)

                        {

                            contain = true;

                        }

                    }

                    if (!contain)

                    {

                        ConstTable.Add(Id);

                    }

                }

            }

 

        }

        //main process which start all subprocesses and check program header

        public TreeNode BuildTree()

        {

            //Check header

            if (LexTable.Count < 3)

            {

                AddError("Unrecognized program header!",0);

                return GramTree;

            }

            else

            {

                if ((LexTable[0].Type == LexemType.Program) & (LexTable[1].Type == LexemType.Ident) & (LexTable[2].Type == LexemType.Semicolon))

                {

                    TreeNode Node = new TreeNode("Program_Header");

                    Node.Nodes.Add(LexToNode(LexTable[0]));

                    Node.Nodes.Add(LexToNode(LexTable[1]));

                    Node.Nodes.Add(LexToNode(LexTable[2]));

                    GramTree.Nodes.Add(Node);

                    if (LexTable.Count > 4)

                    {

                        if (LexTable[3].Type == LexemType.Var)

                        {

                            GramTree.Nodes.Add(ProcessVarDefinition());

                            int i = 3;

                            while (true)

                            {

                                if ((LexTable[i].Type == LexemType.EOF) | (LexTable[i].Type == LexemType.Start))

                                {

                                    break;

                                }

                                i++;

                            }

                            if (LexTable[i].Type == LexemType.EOF)

                            {

                                AddError("Expected code block!", LexTable[i].Line);

                            }

                            else

                            {

                                //Check is all used identifiers are declared and initialized

                                if (CheckIdentForDefine(i))

                                {

                                    //Process code

                                    GramTree.Nodes.Add(ProcessCodeBlock(i));

                                }

                                else

                                {

                                    return GramTree;

                                }

                            }

                        }

                        else

                        {

                            AddError("Expected Var definition!", LexTable[3].Line);

                        }

                    }

                    else

                    {

                        AddError("Expected Var definition!", LexTable[2].Line + 1);

                    }

Информация о работе Розробка системних програмних модулів та компонент систем програмування