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

ADD: all materials for modules 1-8

parent 5520e871
Branches
No related merge requests found
Showing
with 5635 additions and 0 deletions
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}</ProjectGuid>
<OutputType>Exe</OutputType>
<NoStandardLibraries>false</NoStandardLibraries>
<AssemblyName>sss</AssemblyName>
<RootNamespace>sss</RootNamespace>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<IsWebBootstrapper>true</IsWebBootstrapper>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<PublishUrl>http://localhost/sss/</PublishUrl>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>.\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>.\bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ScannerHelper.cs" />
<Compile Include="SimpleLex.cs" />
<Compile Include="mymain.cs" />
<Compile Include="ShiftReduceParserCode.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>Клиентский профиль .NET Framework 3.5 с пакетом обновления 1 %28SP1%29</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.2.0">
<Visible>False</Visible>
<ProductName>.NET Framework 2.0 %28x86%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
<Visible>False</Visible>
<ProductName>.NET Framework 3.0 %28x86%29</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<None Include="SimpleLex.lex" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" />
<ProjectExtensions>
<VisualStudio AllowExistingFolder="true" />
</ProjectExtensions>
<PropertyGroup>
<PreBuildEvent>dir</PreBuildEvent>
</PropertyGroup>
</Project>
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lex1", "Lex1.csproj", "{4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
namespace ScannerHelper
{
public enum Tok { EOF = 0, ID, INUM, RNUM, COLON, SEMICOLON, ASSIGN, BEGIN, END, CYCLE };
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
%using ScannerHelper;
%namespace SimpleScanner
Alpha [a-zA-Z_]
Digit [0-9]
AlphaDigit {Alpha}|{Digit}
INTNUM {Digit}+
REALNUM {INTNUM}\.{INTNUM}
ID {Alpha}{AlphaDigit}*
// , - Scanner
%{
public int LexValueInt;
public double LexValueDouble;
%}
%%
{INTNUM} {
LexValueInt = int.Parse(yytext);
return (int)Tok.INUM;
}
{REALNUM} {
LexValueDouble = double.Parse(yytext);
return (int)Tok.RNUM;
}
begin {
return (int)Tok.BEGIN;
}
end {
return (int)Tok.END;
}
cycle {
return (int)Tok.CYCLE;
}
{ID} {
return (int)Tok.ID;
}
":" {
return (int)Tok.COLON;
}
":=" {
return (int)Tok.ASSIGN;
}
";" {
return (int)Tok.SEMICOLON;
}
[^ \r\n] {
LexError();
return 0; //
}
%%
// - Scanner
public void LexError()
{
Console.WriteLine("({0},{1}): {2}", yyline, yycol, yytext);
}
public string TokToString(Tok tok)
{
switch (tok)
{
case Tok.ID:
return tok + " " + yytext;
case Tok.INUM:
return tok + " " + LexValueInt;
case Tok.RNUM:
return tok + " " + LexValueDouble;
default:
return tok + "";
}
}
begin ggg : ; :+= 7 99.9 5
1
ppp end
gplex.exe /noparser SimpleLex.lex
\ No newline at end of file
using System;
using System.IO;
using SimpleScanner;
using ScannerHelper;
namespace Main
{
class mymain
{
static void Main(string[] args)
{
// 3.14 ( 3,14 Culture)
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
var fname = @"..\..\a.txt";
Console.WriteLine(File.ReadAllText(fname));
Console.WriteLine("-------------------------");
Scanner scanner = new Scanner(new FileStream(fname, FileMode.Open));
int tok = 0;
do {
tok = scanner.yylex();
if (tok == (int)Tok.EOF)
break;
Console.WriteLine(scanner.TokToString((Tok)tok));
} while (true);
Console.ReadKey();
}
}
}
using System;
using System.IO;
using System.Collections.Generic;
using SimpleScanner;
using SimpleParser;
namespace SimpleCompiler
{
public class SimpleCompilerMain
{
public static void Main()
{
string FileName = @"..\..\a.txt";
try
{
string Text = File.ReadAllText(FileName);
Scanner scanner = new Scanner();
scanner.SetSource(Text, 0);
Parser parser = new Parser(scanner);
var b = parser.Parse();
if (!b)
Console.WriteLine("Ошибка");
else Console.WriteLine("Программа распознана");
}
catch (FileNotFoundException)
{
Console.WriteLine("Файл {0} не найден", FileName);
}
catch (LexException e)
{
Console.WriteLine("Лексическая ошибка. " + e.Message);
}
catch (SyntaxException e)
{
Console.WriteLine("Синтаксическая ошибка. " + e.Message);
}
Console.ReadLine();
}
}
}
using System;
using System.Linq;
namespace SimpleParser
{
public class LexException : Exception
{
public LexException(string msg) : base(msg) { }
}
public class SyntaxException : Exception
{
public SyntaxException(string msg) : base(msg) { }
}
// Класс глобальных описаний и статических методов
// для использования различными подсистемами парсера и сканера
public static class ParserHelper
{
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("SimpleLang")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleLang")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("06dba63f-4805-4cd3-8a93-b329b2c7e37b")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер построения
// Редакция
//
// Можно задать все значения или принять номер построения и номер редакции по умолчанию,
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{12B9D996-7B4A-4EE4-9AD8-2E24EAF3F574}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SimpleLang</RootNamespace>
<AssemblyName>SimpleLang</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</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|x86' ">
<PlatformTarget>x86</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="Main.cs" />
<Compile Include="ParserHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ShiftReduceParserCode.cs" />
<Compile Include="SimpleLex.cs" />
<Compile Include="SimpleYacc.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 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLang", "SimpleLang.csproj", "{12B9D996-7B4A-4EE4-9AD8-2E24EAF3F574}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{12B9D996-7B4A-4EE4-9AD8-2E24EAF3F574}.Debug|x86.ActiveCfg = Debug|x86
{12B9D996-7B4A-4EE4-9AD8-2E24EAF3F574}.Debug|x86.Build.0 = Debug|x86
{12B9D996-7B4A-4EE4-9AD8-2E24EAF3F574}.Release|x86.ActiveCfg = Release|x86
{12B9D996-7B4A-4EE4-9AD8-2E24EAF3F574}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
This diff is collapsed.
%using SimpleParser;
%using QUT.Gppg;
%using System.Linq;
%namespace SimpleScanner
Alpha [a-zA-Z_]
Digit [0-9]
AlphaDigit {Alpha}|{Digit}
INTNUM {Digit}+
REALNUM {INTNUM}\.{INTNUM}
ID {Alpha}{AlphaDigit}*
%%
{INTNUM} {
return (int)Tokens.INUM;
}
{REALNUM} {
return (int)Tokens.RNUM;
}
{ID} {
int res = ScannerHelper.GetIDToken(yytext);
return res;
}
":=" { return (int)Tokens.ASSIGN; }
";" { return (int)Tokens.SEMICOLON; }
[^ \r\n] {
LexError();
return (int)Tokens.EOF; //
}
%{
yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol); // ( ), @1 @2 ..
%}
%%
public override void yyerror(string format, params object[] args) //
{
var ww = args.Skip(1).Cast<string>().ToArray();
string errorMsg = string.Format("({0},{1}): {2}, {3}", yyline, yycol, args[0], string.Join(" ", ww));
throw new SyntaxException(errorMsg);
}
public void LexError()
{
string errorMsg = string.Format("({0},{1}): {2}", yyline, yycol, yytext);
throw new LexException(errorMsg);
}
class ScannerHelper
{
private static Dictionary<string,int> keywords;
static ScannerHelper()
{
keywords = new Dictionary<string,int>();
keywords.Add("begin",(int)Tokens.BEGIN);
keywords.Add("end",(int)Tokens.END);
keywords.Add("cycle",(int)Tokens.CYCLE);
}
public static int GetIDToken(string s)
{
if (keywords.ContainsKey(s.ToLower())) //
return keywords[s];
else
return (int)Tokens.ID;
}
}
// This code was generated by the Gardens Point Parser Generator
// Copyright (c) Wayne Kelly, QUT 2005-2010
// (see accompanying GPPGcopyright.rtf)
// GPPG version 1.3.6
// Machine: HUB
// DateTime: 21.09.2017 20:15:14
// UserName: someone
// Input file <SimpleYacc.y>
// options: no-lines gplex
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using QUT.Gppg;
namespace SimpleParser
{
public enum Tokens {
error=1,EOF=2,BEGIN=3,END=4,CYCLE=5,INUM=6,
RNUM=7,ID=8,ASSIGN=9,SEMICOLON=10};
// Abstract base class for GPLEX scanners
public abstract class ScanBase : AbstractScanner<int,LexLocation> {
private LexLocation __yylloc = new LexLocation();
public override LexLocation yylloc { get { return __yylloc; } set { __yylloc = value; } }
protected virtual bool yywrap() { return true; }
}
public class Parser: ShiftReduceParser<int, LexLocation>
{
// Verbatim content from SimpleYacc.y
// Ýòè îáúÿâëåíèÿ äîáàâëÿþòñÿ â êëàññ GPPGParser, ïðåäñòàâëÿþùèé ñîáîé ïàðñåð, ãåíåðèðóåìûé ñèñòåìîé gppg
public Parser(AbstractScanner<int, LexLocation> scanner) : base(scanner) { }
// End verbatim content from SimpleYacc.y
#pragma warning disable 649
private static Dictionary<int, string> aliasses;
#pragma warning restore 649
private static Rule[] rules = new Rule[14];
private static State[] states = new State[22];
private static string[] nonTerms = new string[] {
"progr", "$accept", "block", "stlist", "statement", "assign", "cycle",
"ident", "expr", };
static Parser() {
states[0] = new State(new int[]{3,4},new int[]{-1,1,-3,3});
states[1] = new State(new int[]{2,2});
states[2] = new State(-1);
states[3] = new State(-2);
states[4] = new State(new int[]{8,14,3,4,5,18},new int[]{-4,5,-5,21,-6,9,-8,10,-3,16,-7,17});
states[5] = new State(new int[]{4,6,10,7});
states[6] = new State(-12);
states[7] = new State(new int[]{8,14,3,4,5,18},new int[]{-5,8,-6,9,-8,10,-3,16,-7,17});
states[8] = new State(-4);
states[9] = new State(-5);
states[10] = new State(new int[]{9,11});
states[11] = new State(new int[]{8,14,6,15},new int[]{-9,12,-8,13});
states[12] = new State(-9);
states[13] = new State(-10);
states[14] = new State(-8);
states[15] = new State(-11);
states[16] = new State(-6);
states[17] = new State(-7);
states[18] = new State(new int[]{8,14,6,15},new int[]{-9,19,-8,13});
states[19] = new State(new int[]{8,14,3,4,5,18},new int[]{-5,20,-6,9,-8,10,-3,16,-7,17});
states[20] = new State(-13);
states[21] = new State(-3);
rules[1] = new Rule(-2, new int[]{-1,2});
rules[2] = new Rule(-1, new int[]{-3});
rules[3] = new Rule(-4, new int[]{-5});
rules[4] = new Rule(-4, new int[]{-4,10,-5});
rules[5] = new Rule(-5, new int[]{-6});
rules[6] = new Rule(-5, new int[]{-3});
rules[7] = new Rule(-5, new int[]{-7});
rules[8] = new Rule(-8, new int[]{8});
rules[9] = new Rule(-6, new int[]{-8,9,-9});
rules[10] = new Rule(-9, new int[]{-8});
rules[11] = new Rule(-9, new int[]{6});
rules[12] = new Rule(-3, new int[]{3,-4,4});
rules[13] = new Rule(-7, new int[]{5,-9,-5});
}
protected override void Initialize() {
this.InitSpecialTokens((int)Tokens.error, (int)Tokens.EOF);
this.InitStates(states);
this.InitRules(rules);
this.InitNonTerminals(nonTerms);
}
protected override void DoAction(int action)
{
switch (action)
{
}
}
protected override string TerminalToString(int terminal)
{
if (aliasses != null && aliasses.ContainsKey(terminal))
return aliasses[terminal];
else if (((Tokens)terminal).ToString() != terminal.ToString(CultureInfo.InvariantCulture))
return ((Tokens)terminal).ToString();
else
return CharToString((char)terminal);
}
}
}
// ==========================================================================
// GPPG error listing for yacc source file <SimpleYacc.y>
// ==========================================================================
// Version: 1.3.6
// Machine: SSM
// DateTime: 17.08.2014 10:25:15
// UserName: Станислав
// ==========================================================================
%{
// Ýòè îáúÿâëåíèÿ äîáàâëÿþòñÿ â êëàññ GPPGParser, ïðåäñòàâëÿþùèé ñîáîé ïàðñåð, ãåíåðèðóåìûé ñèñòåìîé gppg
public Parser(AbstractScanner<int, LexLocation> scanner) : base(scanner) { }
%}
%output = SimpleYacc.cs
%using System.IO;
%namespace SimpleParser
%token BEGIN END CYCLE INUM RNUM ID ASSIGN SEMICOLON
%%
// Error: NonTerminal symbol "st" has no productions
// Warning: Terminating st fixes the following size-2 NonTerminal set
// {cycle, st}
// Error: There are 2 non-terminating NonTerminal Symbols
// {cycle, st}
// ------------------------------------------------------------------
progr : block
;
stlist : statement
| stlist SEMICOLON statement
;
statement: assign
| block
| cycle
;
ident : ID
;
assign : ident ASSIGN expr
;
expr : ident
| INUM
;
block : BEGIN stlist END
;
cycle : CYCLE expr st
;
%%
// ==========================================================================
%{
// GPPGParser, , gppg
public Parser(AbstractScanner<int, LexLocation> scanner) : base(scanner) { }
%}
%output = SimpleYacc.cs
%namespace SimpleParser
%token BEGIN END CYCLE INUM RNUM ID ASSIGN SEMICOLON
%%
progr : block
;
stlist : statement
| stlist SEMICOLON statement
;
statement: assign
| block
| cycle
;
ident : ID
;
assign : ident ASSIGN expr
;
expr : ident
| INUM
;
block : BEGIN stlist END
;
cycle : CYCLE expr statement
;
%%
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