Skip to content
Snippets Groups Projects
Commit 5520e871 authored by Anton Bagliy's avatar Anton Bagliy
Browse files

ADD: better module 2 & 4

parent 319a824f
Branches
No related merge requests found
Showing
with 859 additions and 204 deletions
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
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")]
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;
}
}
}
<?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

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
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
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")]
<?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
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")]
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);
}
}
}
<?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

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
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);
}
}
}
}
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")]
<?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
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment