diff --git a/Module2/Lexer.cs b/Module2/Lexer.cs deleted file mode 100644 index 9dd18460846954e232c394d38a27ef0836dd6e00..0000000000000000000000000000000000000000 --- a/Module2/Lexer.cs +++ /dev/null @@ -1,204 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -public class LexerException : System.Exception -{ - public LexerException(string msg) - : base(msg) - { - } - -} - -public enum Tok -{ - EOF, - ID, - INUM, - COLON, - SEMICOLON, - ASSIGN, - BEGIN, - END, - CYCLE -} - -public class Lexer -{ - - private string inputText; - private int position; - private char currentCh; // Текущий символ - private int LexRow, LexCol; // Строка-столбец начала лексемы. Конец лексемы = LexCol+LexText.Length - private int row, col; // текущие строка и столбец в файле - private StringReader inputReader; - private Dictionary<string, Tok> keywordsMap; // Словарь, сопоставляющий ключевым словам константы типа TLex. Инициализируется процедурой InitKeywords - private Tok LexKind; // Тип лексемы - private string LexText; // Текст лексемы - private int LexValue; // Целое значение, связанное с лексемой LexNum - - public Lexer(string input) - { - inputText = input; - inputReader = new StringReader(input); - keywordsMap = new Dictionary<string, Tok>(); - InitKeywords(); - row = 1; col = 1; - NextCh(); // Считать первый символ в ch - NextLexem(); // Считать первую лексему, заполнив LexText, LexKind и, возможно, LexValue - } - - private void PassSpaces() - { - while (char.IsWhiteSpace(currentCh)) - { - NextCh(); - } - } - - private void InitKeywords() - { - keywordsMap["begin"] = Tok.BEGIN; - keywordsMap["end"] = Tok.END; - keywordsMap["cycle"] = Tok.CYCLE; - } - - private void LexError(string message) - { - var reader = new StringReader(inputText); - for (int i = 0; i < row - 1; i++) - { - reader.ReadLine(); - } - var errorString = reader.ReadLine(); - System.Text.StringBuilder errorDescription = new System.Text.StringBuilder(); - errorDescription.AppendFormat("Lexical error in line {0}:", row); - errorDescription.Append("\n"); - errorDescription.Append(errorString); - errorDescription.Append("\n"); - errorDescription.Append(new String(' ', col - 1) + '^'); - errorDescription.Append('\n'); - if (message != "") - { - errorDescription.Append(message); - } - throw new LexerException(errorDescription.ToString()); - } - - private void NextCh() - { - // В LexText накапливается предыдущий символ и считывается следующий символ - LexText += currentCh; - var nextChar = inputReader.Read(); - if (nextChar != -1) - { - currentCh = (char)nextChar; - if (currentCh != '\n') - { - col += 1; - } - else - { - row += 1; - col = 1; - } - } - else - { - currentCh = (char)0; // если достигнут конец файла, то возвращается #0 - } - } - - private void NextLexem() - { - PassSpaces(); - // R К этому моменту первый символ лексемы считан в ch - LexText = ""; - LexRow = row; - LexCol = col; - // Тип лексемы определяется по ее первому символу - // Для каждой лексемы строится синтаксическая диаграмма - if (currentCh == ';') { - NextCh(); - LexKind = Tok.SEMICOLON; - } else if (currentCh == ':') { - NextCh(); - if (currentCh != '=') - { - LexError("= was expected"); - } - NextCh(); - LexKind = Tok.ASSIGN; - } else if (char.IsLetter(currentCh)) { - while (char.IsLetterOrDigit(currentCh)) - { - NextCh(); - } - if (keywordsMap.ContainsKey(LexText)) - { - LexKind = keywordsMap[LexText]; - } - else - { - LexKind = Tok.ID; - } - } - else if (char.IsDigit(currentCh)) - { - while (char.IsDigit(currentCh)) - { - NextCh(); - } - LexValue = Int32.Parse(LexText); - LexKind = Tok.INUM; - } else if ((int)currentCh == 0) { - LexKind = Tok.EOF; - } else { - LexError("Incorrect symbol " + currentCh); - } - } - - public virtual void Parse() - { - do - { - Console.WriteLine(TokToString(LexKind)); - NextLexem(); - } while (LexKind != Tok.EOF); - } - - private string TokToString(Tok t) - { - var result = t.ToString(); - switch (t) - { - case Tok.ID: result += ' ' + LexText; - break; - case Tok.INUM: result += ' ' + LexValue.ToString(); - break; - } - return result; - } -} - - -public class Program -{ - public static void Main() - { - string fileContents = @"begin -id23 := 24; -cycle; 2 id258 id29 ; -end"; - Lexer l = new Lexer(fileContents); - try - { - l.Parse(); - } - catch (LexerException e) - { - Console.WriteLine("lexer error: " + e.Message); - } - } -} \ No newline at end of file diff --git a/Module2/SimpleLangLexer/Properties/AssemblyInfo.cs b/Module2/SimpleLangLexer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..08669ddecd31592b2d8c5768a078a6990c85fe0d --- /dev/null +++ b/Module2/SimpleLangLexer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +п»їusing System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Управление общими сведениями Рѕ СЃР±РѕСЂРєРµ осуществляется СЃ помощью +// набора атрибутов. Рзмените значения этих атрибутов, чтобы изменить сведения, +// связанные СЃРѕ СЃР±РѕСЂРєРѕР№. +[assembly: AssemblyTitle("SimpleLangLexer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleLangLexer")] +[assembly: AssemblyCopyright("Copyright В© 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Параметр ComVisible СЃРѕ значением FALSE делает типы РІ СЃР±РѕСЂРєРµ невидимыми +// для COM-компонентов. Если требуется обратиться Рє типу РІ этой СЃР±РѕСЂРєРµ через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("ae9968cd-e358-4d37-aa84-99d27f5dd537")] + +// Сведения Рѕ версии СЃР±РѕСЂРєРё состоят РёР· следующих четырех значений: +// +// РћСЃРЅРѕРІРЅРѕР№ номер версии +// Дополнительный номер версии +// Номер построения +// Редакция +// +// Можно задать РІСЃРµ значения или принять номер построения Рё номер редакции РїРѕ умолчанию, +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Module2/SimpleLangLexer/SimpleLangLexer.cs b/Module2/SimpleLangLexer/SimpleLangLexer.cs new file mode 100644 index 0000000000000000000000000000000000000000..107066b5b50ee0cd939b8374955f7ff2c22211e3 --- /dev/null +++ b/Module2/SimpleLangLexer/SimpleLangLexer.cs @@ -0,0 +1,203 @@ +п»їusing System; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace SimpleLangLexer +{ + + public class LexerException : System.Exception + { + public LexerException(string msg) + : base(msg) + { + } + + } + + public enum Tok + { + EOF, + ID, + INUM, + COLON, + SEMICOLON, + ASSIGN, + BEGIN, + END, + CYCLE + } + + public class Lexer + { + private int position; + private char currentCh; // Текущий СЃРёРјРІРѕР» + public int LexRow, LexCol; // Строка-столбец начала лексемы. Конец лексемы = LexCol+LexText.Length + private int row, col; // текущие строка Рё столбец РІ файле + private TextReader inputReader; + private Dictionary<string, Tok> keywordsMap; // Словарь, сопоставляющий ключевым словам константы типа TLex. Рнициализируется процедурой InitKeywords + public Tok LexKind; // РўРёРї лексемы + public string LexText; // Текст лексемы + public int LexValue; // Целое значение, связанное СЃ лексемой LexNum + + private string CurrentLineText; // Накапливает символы текущей строки для сообщений РѕР± ошибках + + + public Lexer(TextReader input) + { + CurrentLineText = ""; + inputReader = input; + keywordsMap = new Dictionary<string, Tok>(); + InitKeywords(); + row = 1; col = 0; + NextCh(); // Считать первый СЃРёРјРІРѕР» РІ ch + NextLexem(); // Считать первую лексему, заполнив LexText, LexKind Рё, возможно, LexValue + } + + public void Init() { + + } + + private void PassSpaces() + { + while (char.IsWhiteSpace(currentCh)) + { + NextCh(); + } + } + + private void InitKeywords() + { + keywordsMap["begin"] = Tok.BEGIN; + keywordsMap["end"] = Tok.END; + keywordsMap["cycle"] = Tok.CYCLE; + } + + public string FinishCurrentLine() + { + return CurrentLineText + inputReader.ReadLine(); + } + + private void LexError(string message) + { + System.Text.StringBuilder errorDescription = new System.Text.StringBuilder(); + errorDescription.AppendFormat("Lexical error in line {0}:", row); + errorDescription.Append("\n"); + errorDescription.Append(FinishCurrentLine()); + errorDescription.Append("\n"); + errorDescription.Append(new String(' ', col - 1) + '^'); + errorDescription.Append('\n'); + if (message != "") + { + errorDescription.Append(message); + } + throw new LexerException(errorDescription.ToString()); + } + + private void NextCh() + { + // Р’ LexText накапливается предыдущий СЃРёРјРІРѕР» Рё считывается следующий СЃРёРјРІРѕР» + LexText += currentCh; + var nextChar = inputReader.Read(); + if (nextChar != -1) + { + currentCh = (char)nextChar; + if (currentCh != '\n') + { + col += 1; + CurrentLineText += currentCh; + } + else + { + row += 1; + col = 0; + CurrentLineText = ""; + } + } + else + { + currentCh = (char)0; // если достигнут конец файла, то возвращается #0 + } + } + + public void NextLexem() + { + PassSpaces(); + // R Рљ этому моменту первый СЃРёРјРІРѕР» лексемы считан РІ ch + LexText = ""; + LexRow = row; + LexCol = col; + // РўРёРї лексемы определяется РїРѕ ее первому символу + // Для каждой лексемы строится синтаксическая диаграмма + if (currentCh == ';') + { + NextCh(); + LexKind = Tok.SEMICOLON; + } + else if (currentCh == ':') + { + NextCh(); + if (currentCh != '=') + { + LexError("= was expected"); + } + NextCh(); + LexKind = Tok.ASSIGN; + } + else if (char.IsLetter(currentCh)) + { + while (char.IsLetterOrDigit(currentCh)) + { + NextCh(); + } + if (keywordsMap.ContainsKey(LexText)) + { + LexKind = keywordsMap[LexText]; + } + else + { + LexKind = Tok.ID; + } + } + else if (char.IsDigit(currentCh)) + { + while (char.IsDigit(currentCh)) + { + NextCh(); + } + LexValue = Int32.Parse(LexText); + LexKind = Tok.INUM; + } + else if ((int)currentCh == 0) + { + LexKind = Tok.EOF; + } + else + { + LexError("Incorrect symbol " + currentCh); + } + } + + public virtual void ParseToConsole() + { + do + { + Console.WriteLine(TokToString(LexKind)); + NextLexem(); + } while (LexKind != Tok.EOF); + } + + public string TokToString(Tok t) + { + var result = t.ToString(); + switch (t) + { + case Tok.ID: result += ' ' + LexText; + break; + case Tok.INUM: result += ' ' + LexValue.ToString(); + break; + } + return result; + } + } +} diff --git a/Module2/SimpleLangLexer/SimpleLangLexer.csproj b/Module2/SimpleLangLexer/SimpleLangLexer.csproj new file mode 100644 index 0000000000000000000000000000000000000000..6f0ed34f2475c6890800ea455ca6d342ad9ac0cb --- /dev/null +++ b/Module2/SimpleLangLexer/SimpleLangLexer.csproj @@ -0,0 +1,58 @@ +п»ї<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{28C0284B-2F43-45D6-A77F-AB08F919717D}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>SimpleLangLexer</RootNamespace> + <AssemblyName>SimpleLangLexer</AssemblyName> + <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup> + <StartupObject /> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="SimpleLangLexer.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/Module2/SimpleLangLexer/SimpleLangLexer.sln b/Module2/SimpleLangLexer/SimpleLangLexer.sln new file mode 100644 index 0000000000000000000000000000000000000000..95e7cf8f92303feb64ad061e89555526544442c8 --- /dev/null +++ b/Module2/SimpleLangLexer/SimpleLangLexer.sln @@ -0,0 +1,29 @@ +п»ї +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLangLexer", "SimpleLangLexer.csproj", "{28C0284B-2F43-45D6-A77F-AB08F919717D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLangLexerTest", "..\SimpleLangLexerTest\SimpleLangLexerTest.csproj", "{9EE96E14-A541-4EAD-AD34-2A9011ED12C1}" + ProjectSection(ProjectDependencies) = postProject + {28C0284B-2F43-45D6-A77F-AB08F919717D} = {28C0284B-2F43-45D6-A77F-AB08F919717D} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {28C0284B-2F43-45D6-A77F-AB08F919717D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28C0284B-2F43-45D6-A77F-AB08F919717D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28C0284B-2F43-45D6-A77F-AB08F919717D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28C0284B-2F43-45D6-A77F-AB08F919717D}.Release|Any CPU.Build.0 = Release|Any CPU + {9EE96E14-A541-4EAD-AD34-2A9011ED12C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9EE96E14-A541-4EAD-AD34-2A9011ED12C1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9EE96E14-A541-4EAD-AD34-2A9011ED12C1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9EE96E14-A541-4EAD-AD34-2A9011ED12C1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Module2/SimpleLangLexerTest/Program.cs b/Module2/SimpleLangLexerTest/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..453e91ddd10f873fa621bbf83bfd3c90122c18fa --- /dev/null +++ b/Module2/SimpleLangLexerTest/Program.cs @@ -0,0 +1,34 @@ +п»їusing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using SimpleLangLexer; + +namespace SimpleLangLexerTest +{ + class Program + { + public static void Main() + { + string fileContents = @"begin +id23 := 24; +cycle ; 2 id258 id29 ; +end"; + TextReader inputReader = new StringReader(fileContents); + Lexer l = new Lexer(inputReader); + try + { + do + { + Console.WriteLine(l.TokToString(l.LexKind)); + l.NextLexem(); + } while (l.LexKind != Tok.EOF); + } + catch (LexerException e) + { + Console.WriteLine("lexer error: " + e.Message); + } + } + } +} \ No newline at end of file diff --git a/Module2/SimpleLangLexerTest/Properties/AssemblyInfo.cs b/Module2/SimpleLangLexerTest/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..296801534d4ec4e2549499502b249a3c1ef83d24 --- /dev/null +++ b/Module2/SimpleLangLexerTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +п»їusing System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Управление общими сведениями Рѕ СЃР±РѕСЂРєРµ осуществляется СЃ помощью +// набора атрибутов. Рзмените значения этих атрибутов, чтобы изменить сведения, +// связанные СЃРѕ СЃР±РѕСЂРєРѕР№. +[assembly: AssemblyTitle("SimpleLangLexerTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleLangLexerTest")] +[assembly: AssemblyCopyright("Copyright В© 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Параметр ComVisible СЃРѕ значением FALSE делает типы РІ СЃР±РѕСЂРєРµ невидимыми +// для COM-компонентов. Если требуется обратиться Рє типу РІ этой СЃР±РѕСЂРєРµ через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("ffd03552-aca5-4221-b7ce-a827ad8067e2")] + +// Сведения Рѕ версии СЃР±РѕСЂРєРё состоят РёР· следующих четырех значений: +// +// РћСЃРЅРѕРІРЅРѕР№ номер версии +// Дополнительный номер версии +// Номер построения +// Редакция +// +// Можно задать РІСЃРµ значения или принять номер построения Рё номер редакции РїРѕ умолчанию, +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Module2/SimpleLangLexerTest/SimpleLangLexerTest.csproj b/Module2/SimpleLangLexerTest/SimpleLangLexerTest.csproj new file mode 100644 index 0000000000000000000000000000000000000000..2eb26ad3eb73dd0daa780d8db4b77c44bcdf05b0 --- /dev/null +++ b/Module2/SimpleLangLexerTest/SimpleLangLexerTest.csproj @@ -0,0 +1,61 @@ +п»ї<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{9EE96E14-A541-4EAD-AD34-2A9011ED12C1}</ProjectGuid> + <OutputType>Exe</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>SimpleLangLexerTest</RootNamespace> + <AssemblyName>SimpleLangLexerTest</AssemblyName> + <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Program.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\SimpleLangLexer\SimpleLangLexer.csproj"> + <Project>{28c0284b-2f43-45d6-a77f-ab08f919717d}</Project> + <Name>SimpleLangLexer</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/Module4/SimpleLangParser/Properties/AssemblyInfo.cs b/Module4/SimpleLangParser/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..fa52685a337b3866e133733c45f44195f3227112 --- /dev/null +++ b/Module4/SimpleLangParser/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +п»їusing System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Управление общими сведениями Рѕ СЃР±РѕСЂРєРµ осуществляется СЃ помощью +// набора атрибутов. Рзмените значения этих атрибутов, чтобы изменить сведения, +// связанные СЃРѕ СЃР±РѕСЂРєРѕР№. +[assembly: AssemblyTitle("SimpleLangParser")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleLangParser")] +[assembly: AssemblyCopyright("Copyright В© 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Параметр ComVisible СЃРѕ значением FALSE делает типы РІ СЃР±РѕСЂРєРµ невидимыми +// для COM-компонентов. Если требуется обратиться Рє типу РІ этой СЃР±РѕСЂРєРµ через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("02f0fd4f-1373-414b-a1ef-b7cf225e1470")] + +// Сведения Рѕ версии СЃР±РѕСЂРєРё состоят РёР· следующих четырех значений: +// +// РћСЃРЅРѕРІРЅРѕР№ номер версии +// Дополнительный номер версии +// Номер построения +// Редакция +// +// Можно задать РІСЃРµ значения или принять номер построения Рё номер редакции РїРѕ умолчанию, +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Module4/SimpleLangParser/SimpleLangParser.cs b/Module4/SimpleLangParser/SimpleLangParser.cs new file mode 100644 index 0000000000000000000000000000000000000000..8103d34ddf532900bf96bbfe85f211662c4ae983 --- /dev/null +++ b/Module4/SimpleLangParser/SimpleLangParser.cs @@ -0,0 +1,129 @@ +п»їusing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SimpleLangLexer; + +namespace SimpleLangParser +{ + public class ParserException : System.Exception + { + public ParserException(string msg) + : base(msg) + { + } + + } + + public class Parser + { + private SimpleLangLexer.Lexer l; + + public Parser(SimpleLangLexer.Lexer lexer) + { + l = lexer; + } + + public void Progr() + { + Block(); + } + + public void Expr() + { + if (l.LexKind == Tok.ID || l.LexKind == Tok.INUM) + { + l.NextLexem(); + } + else + { + SyntaxError("expression expected"); + } + } + + public void Assign() + { + l.NextLexem(); // РїСЂРѕРїСѓСЃРє id + if (l.LexKind == Tok.ASSIGN) + { + l.NextLexem(); + } + else { + SyntaxError(":= expected"); + } + Expr(); + } + + public void StatementList() + { + Statement(); + while (l.LexKind == Tok.SEMICOLON) + { + l.NextLexem(); + Statement(); + } + } + + public void Statement() + { + switch (l.LexKind) + { + case Tok.BEGIN: + { + Block(); + break; + } + case Tok.CYCLE: + { + Cycle(); + break; + } + case Tok.ID: + { + Assign(); + break; + } + default: + { + SyntaxError("Operator expected"); + break; + } + } + } + + public void Block() + { + l.NextLexem(); // РїСЂРѕРїСѓСЃРє begin + StatementList(); + if (l.LexKind == Tok.END) + { + l.NextLexem(); + } + else + { + SyntaxError("end expected"); + } + + } + + public void Cycle() + { + l.NextLexem(); // РїСЂРѕРїСѓСЃРє cycle + Expr(); + Statement(); + } + + public void SyntaxError(string message) + { + var errorMessage = "Syntax error in line " + l.LexRow.ToString() + ":\n"; + errorMessage += l.FinishCurrentLine() + "\n"; + errorMessage += new String(' ', l.LexCol - 1) + "^\n"; + if (message != "") + { + errorMessage += message; + } + throw new ParserException(errorMessage); + } + + } +} diff --git a/Module4/SimpleLangParser/SimpleLangParser.csproj b/Module4/SimpleLangParser/SimpleLangParser.csproj new file mode 100644 index 0000000000000000000000000000000000000000..4f878b7077c8a5d7a624fee96b27d2a814d37821 --- /dev/null +++ b/Module4/SimpleLangParser/SimpleLangParser.csproj @@ -0,0 +1,62 @@ +п»ї<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>SimpleLangParser</RootNamespace> + <AssemblyName>SimpleLangParser</AssemblyName> + <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup> + <StartupObject /> + </PropertyGroup> + <ItemGroup> + <Reference Include="SimpleLangLexer, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>\\192.168.0.110\work\SFedU\РљСѓСЂСЃС‹2017\Методы_построения_компиляторов\Тема2\SimpleLangLexer\bin\Debug\SimpleLangLexer.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="SimpleLangParser.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/Module4/SimpleLangParser/SimpleLangParser.sln b/Module4/SimpleLangParser/SimpleLangParser.sln new file mode 100644 index 0000000000000000000000000000000000000000..97ce736a52a4b0c849e4c1c8f479b0dc711f6437 --- /dev/null +++ b/Module4/SimpleLangParser/SimpleLangParser.sln @@ -0,0 +1,26 @@ +п»ї +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLangParser", "SimpleLangParser.csproj", "{837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLangParserTest", "..\SimpleLangParserTest\SimpleLangParserTest.csproj", "{5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}.Release|Any CPU.Build.0 = Release|Any CPU + {5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Module4/SimpleLangParserTest/Program.cs b/Module4/SimpleLangParserTest/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..d2895a68b135ff15e3e0337275867eeaa002ad9a --- /dev/null +++ b/Module4/SimpleLangParserTest/Program.cs @@ -0,0 +1,48 @@ +п»їusing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using SimpleLangParser; +using SimpleLangLexer; + +namespace SimpleLangParserTest +{ + class Program + { + static void Main(string[] args) + { + string fileContents = @"begin + a := 2; + cycle a + begin + b := a; + c := 234 + end +end"; + TextReader inputReader = new StringReader(fileContents); + Lexer l = new Lexer(inputReader); + Parser p = new Parser(l); + try + { + p.Progr(); + if (l.LexKind == Tok.EOF) + { + Console.WriteLine("Program successfully recognized"); + } + else + { + p.SyntaxError("end of file was expected"); + } + } + catch (ParserException e) + { + Console.WriteLine("lexer error: " + e.Message); + } + catch (LexerException le) + { + Console.WriteLine("parser error: " + le.Message); + } + } + } +} diff --git a/Module4/SimpleLangParserTest/Properties/AssemblyInfo.cs b/Module4/SimpleLangParserTest/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..2688c6e933d416dde6ff34896a9c5a0aa5581723 --- /dev/null +++ b/Module4/SimpleLangParserTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +п»їusing System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Управление общими сведениями Рѕ СЃР±РѕСЂРєРµ осуществляется СЃ помощью +// набора атрибутов. Рзмените значения этих атрибутов, чтобы изменить сведения, +// связанные СЃРѕ СЃР±РѕСЂРєРѕР№. +[assembly: AssemblyTitle("SimpleLangParserTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SimpleLangParserTest")] +[assembly: AssemblyCopyright("Copyright В© 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Параметр ComVisible СЃРѕ значением FALSE делает типы РІ СЃР±РѕСЂРєРµ невидимыми +// для COM-компонентов. Если требуется обратиться Рє типу РІ этой СЃР±РѕСЂРєРµ через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("780342e9-bf84-47b3-95da-830dd921148f")] + +// Сведения Рѕ версии СЃР±РѕСЂРєРё состоят РёР· следующих четырех значений: +// +// РћСЃРЅРѕРІРЅРѕР№ номер версии +// Дополнительный номер версии +// Номер построения +// Редакция +// +// Можно задать РІСЃРµ значения или принять номер построения Рё номер редакции РїРѕ умолчанию, +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Module4/SimpleLangParserTest/SimpleLangParserTest.csproj b/Module4/SimpleLangParserTest/SimpleLangParserTest.csproj new file mode 100644 index 0000000000000000000000000000000000000000..92492224d435d2209e823351ec0f83c3f91de1d0 --- /dev/null +++ b/Module4/SimpleLangParserTest/SimpleLangParserTest.csproj @@ -0,0 +1,65 @@ +п»ї<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}</ProjectGuid> + <OutputType>Exe</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>SimpleLangParserTest</RootNamespace> + <AssemblyName>SimpleLangParserTest</AssemblyName> + <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="SimpleLangLexer, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>\\192.168.0.110\work\SFedU\РљСѓСЂСЃС‹2017\Методы_построения_компиляторов\Тема2\SimpleLangLexer\bin\Debug\SimpleLangLexer.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Program.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\SimpleLangParser\SimpleLangParser.csproj"> + <Project>{837bc9fe-daa9-416e-bcce-0235e5c38d4b}</Project> + <Name>SimpleLangParser</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file