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 4243 additions and 0 deletions
begin
b := 2;
a := 3;
a := b;
cycle 3
begin
a := c;
c := 1
end
end
cls
gplex.exe /unicode SimpleLex.lex
gppg.exe /no-lines /gplex SimpleYacc.y
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("Синтаксическое дерево построено");
//foreach (var st in parser.root.StList)
//Console.WriteLine(st);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("Файл {0} не найден", FileName);
}
catch (LexException e)
{
Console.WriteLine("Лексическая ошибка. " + e.Message);
}
catch (SyntaxException e)
{
Console.WriteLine("Синтаксическая ошибка. " + e.Message);
}
Console.ReadLine();
}
}
}
using System;
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.Collections.Generic;
namespace ProgramTree
{
public enum AssignType { Assign, AssignPlus, AssignMinus, AssignMult, AssignDivide };
public class Node // базовый класс для всех узлов
{
}
public class ExprNode : Node // базовый класс для всех выражений
{
}
public class IdNode : ExprNode
{
public string Name { get; set; }
public IdNode(string name) { Name = name; }
}
public class IntNumNode : ExprNode
{
public int Num { get; set; }
public IntNumNode(int num) { Num = num; }
}
public class StatementNode : Node // базовый класс для всех операторов
{
}
public class AssignNode : StatementNode
{
public IdNode Id { get; set; }
public ExprNode Expr { get; set; }
public AssignType AssOp { get; set; }
public AssignNode(IdNode id, ExprNode expr, AssignType assop = AssignType.Assign)
{
Id = id;
Expr = expr;
AssOp = assop;
}
}
public class CycleNode : StatementNode
{
public ExprNode Expr { get; set; }
public StatementNode Stat { get; set; }
public CycleNode(ExprNode expr, StatementNode stat)
{
Expr = expr;
Stat = stat;
}
}
public class BlockNode : StatementNode
{
public List<StatementNode> StList = new List<StatementNode>();
public BlockNode(StatementNode stat)
{
Add(stat);
}
public void Add(StatementNode stat)
{
StList.Add(stat);
}
}
}
\ 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="ProgramTree.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 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLang1", "SimpleLang1.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} {
yylval.iVal = int.Parse(yytext);
return (int)Tokens.INUM;
}
{REALNUM} {
yylval.dVal = double.Parse(yytext);
return (int)Tokens.RNUM;
}
{ID} {
int res = ScannerHelper.GetIDToken(yytext);
if (res == (int)Tokens.ID)
yylval.sVal = yytext;
return res;
}
":=" { return (int)Tokens.ASSIGN; }
";" { return (int)Tokens.SEMICOLON; }
[^ \r\n] {
LexError();
}
%{
yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol);
%}
%%
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:37:24
// 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;
using ProgramTree;
namespace SimpleParser
{
public enum Tokens {
error=1,EOF=2,BEGIN=3,END=4,CYCLE=5,ASSIGN=6,
SEMICOLON=7,INUM=8,RNUM=9,ID=10};
public struct ValueType
{
public double dVal;
public int iVal;
public string sVal;
public Node nVal;
public ExprNode eVal;
public StatementNode stVal;
public BlockNode blVal;
}
// Abstract base class for GPLEX scanners
public abstract class ScanBase : AbstractScanner<ValueType,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<ValueType, LexLocation>
{
// Verbatim content from SimpleYacc.y
// GPPGParser, , gppg
public BlockNode root; //
public Parser(AbstractScanner<ValueType, 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[] {
"expr", "ident", "assign", "statement", "cycle", "stlist", "block", "progr",
"$accept", };
static Parser() {
states[0] = new State(new int[]{3,4},new int[]{-8,1,-7,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[]{10,14,3,4,5,18},new int[]{-6,5,-4,21,-3,9,-2,10,-7,16,-5,17});
states[5] = new State(new int[]{4,6,7,7});
states[6] = new State(-12);
states[7] = new State(new int[]{10,14,3,4,5,18},new int[]{-4,8,-3,9,-2,10,-7,16,-5,17});
states[8] = new State(-4);
states[9] = new State(-5);
states[10] = new State(new int[]{6,11});
states[11] = new State(new int[]{10,14,8,15},new int[]{-1,12,-2,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[]{10,14,8,15},new int[]{-1,19,-2,13});
states[19] = new State(new int[]{10,14,3,4,5,18},new int[]{-4,20,-3,9,-2,10,-7,16,-5,17});
states[20] = new State(-13);
states[21] = new State(-3);
rules[1] = new Rule(-9, new int[]{-8,2});
rules[2] = new Rule(-8, new int[]{-7});
rules[3] = new Rule(-6, new int[]{-4});
rules[4] = new Rule(-6, new int[]{-6,7,-4});
rules[5] = new Rule(-4, new int[]{-3});
rules[6] = new Rule(-4, new int[]{-7});
rules[7] = new Rule(-4, new int[]{-5});
rules[8] = new Rule(-2, new int[]{10});
rules[9] = new Rule(-3, new int[]{-2,6,-1});
rules[10] = new Rule(-1, new int[]{-2});
rules[11] = new Rule(-1, new int[]{8});
rules[12] = new Rule(-7, new int[]{3,-6,4});
rules[13] = new Rule(-5, new int[]{5,-1,-4});
}
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)
{
case 2: // progr -> block
{ root = ValueStack[ValueStack.Depth-1].blVal; }
break;
case 3: // stlist -> statement
{
CurrentSemanticValue.blVal = new BlockNode(ValueStack[ValueStack.Depth-1].stVal);
}
break;
case 4: // stlist -> stlist, SEMICOLON, statement
{
ValueStack[ValueStack.Depth-3].blVal.Add(ValueStack[ValueStack.Depth-1].stVal);
CurrentSemanticValue.blVal = ValueStack[ValueStack.Depth-3].blVal;
}
break;
case 5: // statement -> assign
{ CurrentSemanticValue.stVal = ValueStack[ValueStack.Depth-1].stVal; }
break;
case 6: // statement -> block
{ CurrentSemanticValue.stVal = ValueStack[ValueStack.Depth-1].blVal; }
break;
case 7: // statement -> cycle
{ CurrentSemanticValue.stVal = ValueStack[ValueStack.Depth-1].stVal; }
break;
case 8: // ident -> ID
{ CurrentSemanticValue.eVal = new IdNode(ValueStack[ValueStack.Depth-1].sVal); }
break;
case 9: // assign -> ident, ASSIGN, expr
{ CurrentSemanticValue.stVal = new AssignNode(ValueStack[ValueStack.Depth-3].eVal as IdNode, ValueStack[ValueStack.Depth-1].eVal); }
break;
case 10: // expr -> ident
{ CurrentSemanticValue.eVal = ValueStack[ValueStack.Depth-1].eVal as IdNode; }
break;
case 11: // expr -> INUM
{ CurrentSemanticValue.eVal = new IntNumNode(ValueStack[ValueStack.Depth-1].iVal); }
break;
case 12: // block -> BEGIN, stlist, END
{ CurrentSemanticValue.blVal = ValueStack[ValueStack.Depth-2].blVal; }
break;
case 13: // cycle -> CYCLE, expr, statement
{ CurrentSemanticValue.stVal = new CycleNode(ValueStack[ValueStack.Depth-2].eVal, ValueStack[ValueStack.Depth-1].stVal); }
break;
}
}
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);
}
}
}
%{
// GPPGParser, , gppg
public BlockNode root; //
public Parser(AbstractScanner<ValueType, LexLocation> scanner) : base(scanner) { }
%}
%output = SimpleYacc.cs
%union {
public double dVal;
public int iVal;
public string sVal;
public Node nVal;
public ExprNode eVal;
public StatementNode stVal;
public BlockNode blVal;
}
%using ProgramTree;
%namespace SimpleParser
%token BEGIN END CYCLE ASSIGN SEMICOLON
%token <iVal> INUM
%token <dVal> RNUM
%token <sVal> ID
%type <eVal> expr ident
%type <stVal> assign statement cycle
%type <blVal> stlist block
%%
progr : block { root = $1; }
;
stlist : statement
{
$$ = new BlockNode($1);
}
| stlist SEMICOLON statement
{
$1.Add($3);
$$ = $1;
}
;
statement: assign { $$ = $1; }
| block { $$ = $1; }
| cycle { $$ = $1; }
;
ident : ID { $$ = new IdNode($1); }
;
assign : ident ASSIGN expr { $$ = new AssignNode($1 as IdNode, $3); }
;
expr : ident { $$ = $1 as IdNode; }
| INUM { $$ = new IntNumNode($1); }
;
block : BEGIN stlist END { $$ = $2; }
;
cycle : CYCLE expr statement { $$ = new CycleNode($2, $3); }
;
%%
begin
b := 2;
a := 3;
a := b;
cycle 3
begin
a := c;
c := 1
end
end
cls
gplex.exe /unicode SimpleLex.lex
gppg.exe /no-lines /gplex SimpleYacc.y
using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using SimpleScanner;
using SimpleParser;
using SimpleLang.Visitors;
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("Синтаксическое дерево построено");
var avis = new AssignCountVisitor();
parser.root.Visit(avis);
Console.WriteLine("Количество присваиваний = {0}", avis.Count);
Console.WriteLine("-------------------------------");
var pp = new PrettyPrintVisitor();
parser.root.Visit(pp);
Console.WriteLine(pp.Text);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("Файл {0} не найден", FileName);
}
catch (Exception e)
{
Console.WriteLine("{0}", e);
}
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System;
namespace SimpleParser
{
public enum type { tint, tdouble };
public static class SymbolTable // Таблица символов
{
public static Dictionary<string, type> vars = new Dictionary<string, type>(); // таблица символов
public static void NewVarDef(string name, type t)
{
if (vars.ContainsKey(name))
throw new Exception("Переменная " + name + " уже определена");
else vars.Add(name, t);
}
}
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.Collections.Generic;
using SimpleLang.Visitors;
namespace ProgramTree
{
public enum AssignType { Assign, AssignPlus, AssignMinus, AssignMult, AssignDivide };
public abstract class Node // базовый класс для всех узлов
{
public abstract void Visit(Visitor v);
}
public abstract class ExprNode : Node // базовый класс для всех выражений
{
}
public class IdNode : ExprNode
{
public string Name { get; set; }
public IdNode(string name) { Name = name; }
public override void Visit(Visitor v)
{
v.VisitIdNode(this);
}
}
public class IntNumNode : ExprNode
{
public int Num { get; set; }
public IntNumNode(int num) { Num = num; }
public override void Visit(Visitor v)
{
v.VisitIntNumNode(this);
}
}
public class BinOpNode : ExprNode
{
public ExprNode Left { get; set; }
public ExprNode Right { get; set; }
public char Op { get; set; }
public BinOpNode(ExprNode Left, ExprNode Right, char op)
{
this.Left = Left;
this.Right = Right;
this.Op = op;
}
public override void Visit(Visitor v)
{
v.VisitBinOpNode(this);
}
}
public abstract class StatementNode : Node // базовый класс для всех операторов
{
}
public class AssignNode : StatementNode
{
public IdNode Id { get; set; }
public ExprNode Expr { get; set; }
public AssignType AssOp { get; set; }
public AssignNode(IdNode id, ExprNode expr, AssignType assop = AssignType.Assign)
{
Id = id;
Expr = expr;
AssOp = assop;
}
public override void Visit(Visitor v)
{
v.VisitAssignNode(this);
}
}
public class CycleNode : StatementNode
{
public ExprNode Expr { get; set; }
public StatementNode Stat { get; set; }
public CycleNode(ExprNode expr, StatementNode stat)
{
Expr = expr;
Stat = stat;
}
public override void Visit(Visitor v)
{
v.VisitCycleNode(this);
}
}
public class BlockNode : StatementNode
{
public List<StatementNode> StList = new List<StatementNode>();
public BlockNode(StatementNode stat)
{
Add(stat);
}
public void Add(StatementNode stat)
{
StList.Add(stat);
}
public override void Visit(Visitor v)
{
v.VisitBlockNode(this);
}
}
public class WriteNode : StatementNode
{
public ExprNode Expr { get; set; }
public WriteNode(ExprNode Expr)
{
this.Expr = Expr;
}
public override void Visit(Visitor v)
{
v.VisitWriteNode(this);
}
}
public class EmptyNode : StatementNode
{
public override void Visit(Visitor v)
{
v.VisitEmptyNode(this);
}
}
public class VarDefNode : StatementNode
{
public List<IdNode> vars = new List<IdNode>();
public VarDefNode(IdNode id)
{
Add(id);
}
public void Add(IdNode id)
{
vars.Add(id);
}
public override void Visit(Visitor v)
{
v.VisitVarDefNode(this);
}
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
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