├── prebuild.sh
├── Module3
├── generateScanner.bat
├── a.txt
├── mymain.cs
├── LexerAddon.cs
├── SimpleLex.lex
├── generateScanner.sh
├── app.config
├── ScannerHelper.cs
└── GeneratedLexer.csproj
├── Module1
├── Lexer.cs
├── App.config
├── Properties
│ └── AssemblyInfo.cs
└── Lexer.csproj
├── Module5
├── SimpleLex.lex
├── SimpleYacc.y
├── generateParserScanner.bat
├── a.txt
├── generateParserScanner.sh
├── app.config
├── ParserHelper.cs
├── Main.cs
├── Properties
│ └── AssemblyInfo.cs
├── SimpleYacc.lst
└── GeneratedParser.csproj
├── Module6
├── SimpleLex.lex
├── SimpleYacc.y
├── Newtonsoft.Json.dll
├── generateParserScanner.bat
├── a.txt
├── generateParserScanner.sh
├── app.config
├── packages.config
├── ParserHelper.cs
├── Properties
│ └── AssemblyInfo.cs
├── ProgramTree.cs
├── Main.cs
└── ParserAST.csproj
├── Module7
├── SimpleLex.lex
├── SimpleYacc.y
├── generateParserScanner.bat
├── generateParserScanner.sh
├── app.config
├── a.txt
├── Visitors
│ ├── MaxNestCyclesVisitor.cs
│ ├── MaxIfCycleNestVisitor.cs
│ ├── AssignCountVisitor.cs
│ ├── CountCyclesOpVisitor.cs
│ ├── CommonlyUsedVarVisitor.cs
│ ├── ChangeVarIdVisitor.cs
│ ├── ExprComplexityVisitor.cs
│ ├── Visitor.cs
│ ├── AutoVisitor.cs
│ └── PrettyPrintVisitor.cs
├── ParserHelper.cs
├── Properties
│ └── AssemblyInfo.cs
├── Main.cs
├── ProgramTree.cs
└── ParserVistors.csproj
├── Module8
├── SimpleLex.lex
├── SimpleYacc.y
├── generateParserScanner.bat
├── generateParserScanner.sh
├── app.config
├── a.txt
├── Visitors
│ ├── AssignCountVisitor.cs
│ ├── Visitor.cs
│ ├── AutoVisitor.cs
│ ├── GenCodeVisitors
│ │ ├── GenCodeCreator.cs
│ │ └── GenCodeVisitor.cs
│ └── PrettyPrintVisitor.cs
├── ParserHelper.cs
├── Properties
│ └── AssemblyInfo.cs
├── Main.cs
├── SimpleYacc.lst
├── ParserGenerator.csproj
└── ProgramTree.cs
├── .gitpod.Dockerfile
├── .gitmodules
├── NunitReportParser
├── packages.config
├── App.config
├── Properties
│ └── AssemblyInfo.cs
└── NunitReport.csproj
├── Module2
├── SimpleLexerDemo
│ ├── app.config
│ ├── Program.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── SimpleLexerDemo.csproj
└── SimpleLangLexer
│ ├── Properties
│ └── AssemblyInfo.cs
│ └── SimpleLexer.csproj
├── Module4
├── SimpleLangParserTest
│ ├── app.config
│ ├── Program.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── RecursiveDescentParserDemo.csproj
└── SimpleLangParser
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── RecursiveDescentParser.csproj
│ └── SimpleLangParser.cs
├── Dockerfile
├── .gitpod.yml
├── TestLexer
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
└── TestLexer.csproj
├── TestASTParser
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
├── Tests.cs
└── TestASTParser.csproj
├── TestVisitors
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
└── TestVisitors.csproj
├── TestCodeGenerator
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
├── Tests.cs
└── TestCodeGenerator.csproj
├── TestDescentParser
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
├── TestDescentParser.csproj
└── Tests.cs
├── TestGeneratedLexer
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
├── Tests.cs
└── TestGeneratedLexer.csproj
├── TestGeneratedParser
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
├── Tests.cs
└── TestGeneratedParser.csproj
├── TestSimpleLexer
├── packages.config
├── Properties
│ └── AssemblyInfo.cs
└── TestSimpleLexer.csproj
├── run_tests.sh
├── LICENSE
├── grade.sh
├── .travis.yml
├── .gitattributes
├── README.md
├── .gitlab-ci.yml
├── .theia
└── tasks.json
└── .gitignore
/prebuild.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | nuget restore Compilers.sln
--------------------------------------------------------------------------------
/Module3/generateScanner.bat:
--------------------------------------------------------------------------------
1 | gplex.exe /noparser SimpleLex.lex
--------------------------------------------------------------------------------
/Module3/a.txt:
--------------------------------------------------------------------------------
1 | begin ggg : ; :+= 7 99.9 5
2 | 1
3 | ppp end
4 |
--------------------------------------------------------------------------------
/Module1/Lexer.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module1/Lexer.cs
--------------------------------------------------------------------------------
/Module3/mymain.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module3/mymain.cs
--------------------------------------------------------------------------------
/Module3/LexerAddon.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module3/LexerAddon.cs
--------------------------------------------------------------------------------
/Module3/SimpleLex.lex:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module3/SimpleLex.lex
--------------------------------------------------------------------------------
/Module5/SimpleLex.lex:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module5/SimpleLex.lex
--------------------------------------------------------------------------------
/Module5/SimpleYacc.y:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module5/SimpleYacc.y
--------------------------------------------------------------------------------
/Module6/SimpleLex.lex:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module6/SimpleLex.lex
--------------------------------------------------------------------------------
/Module6/SimpleYacc.y:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module6/SimpleYacc.y
--------------------------------------------------------------------------------
/Module7/SimpleLex.lex:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module7/SimpleLex.lex
--------------------------------------------------------------------------------
/Module7/SimpleYacc.y:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module7/SimpleYacc.y
--------------------------------------------------------------------------------
/Module8/SimpleLex.lex:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module8/SimpleLex.lex
--------------------------------------------------------------------------------
/Module8/SimpleYacc.y:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module8/SimpleYacc.y
--------------------------------------------------------------------------------
/Module3/generateScanner.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mono ../gplex/bin/Gplex.exe /noparser SimpleLex.lex
3 |
--------------------------------------------------------------------------------
/Module6/Newtonsoft.Json.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/czen/MMCS_CS311/HEAD/Module6/Newtonsoft.Json.dll
--------------------------------------------------------------------------------
/.gitpod.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM gitpod/workspace-dotnet
2 |
3 | RUN sudo apt-get update && sudo apt install -y nuget
4 |
--------------------------------------------------------------------------------
/Module5/generateParserScanner.bat:
--------------------------------------------------------------------------------
1 | cls
2 | gplex.exe /unicode SimpleLex.lex
3 | gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module6/generateParserScanner.bat:
--------------------------------------------------------------------------------
1 | cls
2 | gplex.exe /unicode SimpleLex.lex
3 | gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module7/generateParserScanner.bat:
--------------------------------------------------------------------------------
1 | cls
2 | gplex.exe /unicode SimpleLex.lex
3 | gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module8/generateParserScanner.bat:
--------------------------------------------------------------------------------
1 | cls
2 | gplex.exe /unicode SimpleLex.lex
3 | gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module5/a.txt:
--------------------------------------------------------------------------------
1 | begin
2 | b := 2;
3 | a := 3;
4 | a := b;
5 | cycle 3
6 | begin
7 | a := c;
8 | c := 1
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/Module6/a.txt:
--------------------------------------------------------------------------------
1 | begin
2 | b := 2;
3 | a := 3;
4 | a := b;
5 | cycle 3
6 | begin
7 | a := c;
8 | c := 1
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/Module5/generateParserScanner.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mono ../gplex/bin/Gplex.exe /unicode SimpleLex.lex
3 | mono ../gppg/bin/Gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module6/generateParserScanner.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mono ../gplex/bin/Gplex.exe /unicode SimpleLex.lex
3 | mono ../gppg/bin/Gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module7/generateParserScanner.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mono ../gplex/bin/Gplex.exe /unicode SimpleLex.lex
3 | mono ../gppg/bin/Gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/Module8/generateParserScanner.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mono ../gplex/bin/Gplex.exe /unicode SimpleLex.lex
3 | mono ../gppg/bin/Gppg.exe /no-lines /gplex SimpleYacc.y
4 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "gplex"]
2 | path = gplex
3 | url = https://github.com/czen/gplex.git
4 | [submodule "gppg"]
5 | path = gppg
6 | url = https://github.com/czen/gppg.git
7 |
--------------------------------------------------------------------------------
/Module3/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module5/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module6/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module7/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module8/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module3/ScannerHelper.cs:
--------------------------------------------------------------------------------
1 | namespace ScannerHelper
2 | {
3 | public enum Tok { EOF = 0, ID, INUM, RNUM, COLON, SEMICOLON, ASSIGN, BEGIN, END, CYCLE, COMMENT, STRINGAP, LONGCOMMENT };
4 | }
--------------------------------------------------------------------------------
/NunitReportParser/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module2/SimpleLexerDemo/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module6/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module4/SimpleLangParserTest/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | #FROM gitpod/workspace-dotnet
2 | FROM ubuntu:latest
3 |
4 | RUN apt-get update && apt install -y nuget mono-devel mono-xbuild
5 | RUN nuget update -self
6 | RUN mkdir /compilers
7 |
8 | WORKDIR /compilers
--------------------------------------------------------------------------------
/Module1/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/NunitReportParser/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Module7/a.txt:
--------------------------------------------------------------------------------
1 | begin
2 | var a,b,d;
3 | b := 2;
4 | a := 3;
5 | a := a * 4 + b;;;
6 | cycle 3
7 | begin
8 | a := a + 1;
9 | cycle 3
10 | begin
11 | a := 1
12 | end;
13 | write(a)
14 | end;
15 | cycle 3
16 | begin
17 | d := 2
18 | end
19 | end
20 |
--------------------------------------------------------------------------------
/Module7/Visitors/MaxNestCyclesVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public class MaxNestCyclesVisitor : AutoVisitor
10 | {
11 | public int MaxNest = 0;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Module7/Visitors/MaxIfCycleNestVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 |
8 | namespace SimpleLang.Visitors
9 | {
10 | public class MaxIfCycleNestVisitor : AutoVisitor
11 | {
12 | public int MaxNest = 0;
13 | }
14 | }
--------------------------------------------------------------------------------
/Module7/Visitors/AssignCountVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public class AssignCountVisitor : AutoVisitor
10 | {
11 | public int Count = 0;
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/.gitpod.yml:
--------------------------------------------------------------------------------
1 | image:
2 | file: .gitpod.Dockerfile
3 |
4 | tasks:
5 | - init: nuget restore Compilers.sln
6 | command: echo "Nuget packages restored"
7 |
8 | vscode:
9 | extensions:
10 | - patcx.vscode-nuget-gallery@0.0.20:ogiC/AHEtkvJiOuDFESvdQ==
11 | - jsw.csharpextensions@1.3.5:IAR0yr75KBtC7ZW0lqOD3w==
12 | - genuitecllc.codetogether@2.0.0:V/RKT60bcDRMrXqiAcuNzQ==
13 |
--------------------------------------------------------------------------------
/Module7/Visitors/CountCyclesOpVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public class CountCyclesOpVisitor : AutoVisitor
10 | {
11 | public int MidCount()
12 | {
13 | throw new NotImplementedException();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Module8/a.txt:
--------------------------------------------------------------------------------
1 | begin
2 | var a,b,c,d;
3 | b := 14 / 5; write(b);
4 | c := 14 % 5; write(c);
5 | a := 3;
6 | a := a * 4 + b;
7 | cycle 3
8 | begin
9 | a := a + 1;
10 | write(a)
11 | end;
12 | b := 0;
13 | a := 1;
14 | if a then b := 1;
15 | if a then c := 1 else c := 0;
16 | a := 0;
17 | if a then d := 0 else d := 1;
18 | write(b);
19 | write(c);
20 | write(d);
21 | end
22 |
--------------------------------------------------------------------------------
/Module7/Visitors/CommonlyUsedVarVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public class CommonlyUsedVarVisitor : AutoVisitor
10 | {
11 | public string mostCommonlyUsedVar()
12 | {
13 | throw new NotImplementedException();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Module7/Visitors/ChangeVarIdVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public class ChangeVarIdVisitor : AutoVisitor
10 | {
11 | private string from, to;
12 |
13 | public ChangeVarIdVisitor(string _from, string _to)
14 | {
15 | from = _from;
16 | to = _to;
17 | }
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/TestLexer/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestASTParser/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestVisitors/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestCodeGenerator/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestDescentParser/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestGeneratedLexer/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestGeneratedParser/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Module6/ParserHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace SimpleParser
4 | {
5 | public class LexException : Exception
6 | {
7 | public LexException(string msg) : base(msg) { }
8 | }
9 | public class SyntaxException : Exception
10 | {
11 | public SyntaxException(string msg) : base(msg) { }
12 | }
13 | // Класс глобальных описаний и статических методов
14 | // для использования различными подсистемами парсера и сканера
15 | public static class ParserHelper
16 | {
17 | }
18 | }
--------------------------------------------------------------------------------
/Module7/Visitors/ExprComplexityVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public class ExprComplexityVisitor : AutoVisitor
10 | {
11 | // список должен содержать сложность каждого выражения, встреченного при обычном порядке обхода AST
12 | public List getComplexityList()
13 | {
14 | throw new NotImplementedException();
15 | }
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Module5/ParserHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 |
4 | namespace SimpleParser
5 | {
6 | public class LexException : Exception
7 | {
8 | public LexException(string msg) : base(msg) { }
9 | }
10 | public class SyntaxException : Exception
11 | {
12 | public SyntaxException(string msg) : base(msg) { }
13 | }
14 | // Класс глобальных описаний и статических методов
15 | // для использования различными подсистемами парсера и сканера
16 | public static class ParserHelper
17 | {
18 | }
19 | }
--------------------------------------------------------------------------------
/TestSimpleLexer/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Module8/Visitors/AssignCountVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | class AssignCountVisitor : AutoVisitor
10 | {
11 | public int Count = 0;
12 | public override void VisitAssignNode(AssignNode a)
13 | {
14 | Count += 1;
15 | }
16 | public override void VisitWriteNode(WriteNode w)
17 | {
18 | }
19 | public override void VisitVarDefNode(VarDefNode w)
20 | {
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Module7/Visitors/Visitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public abstract class Visitor
10 | {
11 | public virtual void VisitIdNode(IdNode id) { }
12 | public virtual void VisitIntNumNode(IntNumNode num) { }
13 | public virtual void VisitBinOpNode(BinOpNode binop) { }
14 | public virtual void VisitAssignNode(AssignNode a) { }
15 | public virtual void VisitCycleNode(CycleNode c) { }
16 | public virtual void VisitBlockNode(BlockNode bl) { }
17 | public virtual void VisitWriteNode(WriteNode w) { }
18 | public virtual void VisitVarDefNode(VarDefNode w) { }
19 | public virtual void VisitEmptyNode(EmptyNode w) { }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Module8/Visitors/Visitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | public abstract class Visitor
10 | {
11 | public virtual void VisitIdNode(IdNode id) { }
12 | public virtual void VisitIntNumNode(IntNumNode num) { }
13 | public virtual void VisitBinOpNode(BinOpNode binop) { }
14 | public virtual void VisitAssignNode(AssignNode a) { }
15 | public virtual void VisitCycleNode(CycleNode c) { }
16 | public virtual void VisitBlockNode(BlockNode bl) { }
17 | public virtual void VisitWriteNode(WriteNode w) { }
18 | public virtual void VisitVarDefNode(VarDefNode w) { }
19 | public virtual void VisitEmptyNode(EmptyNode w) { }
20 | public virtual void VisitIfNode(IfNode cond) { }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Module7/ParserHelper.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System;
3 |
4 | namespace SimpleParser
5 | {
6 |
7 | public enum type { tint, tdouble };
8 |
9 | public static class SymbolTable // Таблица символов
10 | {
11 | public static Dictionary vars = new Dictionary(); // таблица символов
12 | public static void NewVarDef(string name, type t)
13 | {
14 | if (vars.ContainsKey(name))
15 | throw new Exception("Переменная " + name + " уже определена");
16 | else vars.Add(name, t);
17 | }
18 | }
19 |
20 | public class LexException : Exception
21 | {
22 | public LexException(string msg) : base(msg) { }
23 | }
24 |
25 | public class SyntaxException : Exception
26 | {
27 | public SyntaxException(string msg) : base(msg) { }
28 | }
29 |
30 | public static class ParserHelper
31 | {
32 | }
33 | }
--------------------------------------------------------------------------------
/Module8/ParserHelper.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System;
3 |
4 | namespace SimpleParser
5 | {
6 |
7 | public enum type { tint, tdouble };
8 |
9 | public static class SymbolTable // Таблица символов
10 | {
11 | public static Dictionary vars = new Dictionary(); // таблица символов
12 | public static void NewVarDef(string name, type t)
13 | {
14 | if (vars.ContainsKey(name))
15 | throw new Exception("Переменная " + name + " уже определена");
16 | else vars.Add(name, t);
17 | }
18 | }
19 |
20 | public class LexException : Exception
21 | {
22 | public LexException(string msg) : base(msg) { }
23 | }
24 |
25 | public class SyntaxException : Exception
26 | {
27 | public SyntaxException(string msg) : base(msg) { }
28 | }
29 |
30 | public static class ParserHelper
31 | {
32 | }
33 | }
--------------------------------------------------------------------------------
/Module2/SimpleLexerDemo/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.IO;
6 | using SimpleLexer;
7 |
8 | namespace SimpleLangLexerTest
9 | {
10 | class Program
11 | {
12 | public static void Main()
13 | {
14 | string fileContents = @"begin
15 | id23 := 24;
16 | cycle ; 2 id258 id29 ;
17 | end";
18 | TextReader inputReader = new StringReader(fileContents);
19 | Lexer l = new Lexer(inputReader);
20 | try
21 | {
22 | do
23 | {
24 | Console.WriteLine(l.TokToString(l.LexKind));
25 | l.NextLexem();
26 | } while (l.LexKind != Tok.EOF);
27 | }
28 | catch (LexerException e)
29 | {
30 | Console.WriteLine("lexer error: " + e.Message);
31 | }
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/run_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestLexer/bin/Debug/TestLexer.dll
3 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestSimpleLexer/bin/Debug/TestSimpleLexer.dll
4 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestGeneratedLexer/bin/Debug/TestGeneratedLexer.dll
5 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestDescentParser/bin/Debug/TestDescentParser.dll
6 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestGeneratedParser/bin/Debug/TestGeneratedParser.dll
7 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestASTParser/bin/Debug/TestASTParser.dll
8 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestVisitors/bin/Debug/TestVisitors.dll
9 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=All TestCodeGenerator/bin/Debug/TestCodeGenerator.dll
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 czen
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Module5/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using SimpleScanner;
5 | using SimpleParser;
6 |
7 | namespace SimpleCompiler
8 | {
9 | public class SimpleCompilerMain
10 | {
11 | public static void Main()
12 | {
13 | string FileName = @"..\..\a.txt";
14 | try
15 | {
16 | string Text = File.ReadAllText(FileName);
17 |
18 | Scanner scanner = new Scanner();
19 | scanner.SetSource(Text, 0);
20 |
21 | Parser parser = new Parser(scanner);
22 |
23 | var b = parser.Parse();
24 | if (!b)
25 | Console.WriteLine("Ошибка");
26 | else Console.WriteLine("Программа распознана");
27 | }
28 | catch (FileNotFoundException)
29 | {
30 | Console.WriteLine("Файл {0} не найден", FileName);
31 | }
32 | catch (LexException e)
33 | {
34 | Console.WriteLine("Лексическая ошибка. " + e.Message);
35 | }
36 | catch (SyntaxException e)
37 | {
38 | Console.WriteLine("Синтаксическая ошибка. " + e.Message);
39 | }
40 |
41 | Console.ReadLine();
42 | }
43 |
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Module4/SimpleLangParserTest/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.IO;
6 | using SimpleLangParser;
7 | using SimpleLexer;
8 |
9 | namespace SimpleLangParserTest
10 | {
11 | class Program
12 | {
13 | static void Main(string[] args)
14 | {
15 | string fileContents = @"begin
16 | a := 2;
17 | cycle a
18 | begin
19 | while 2 do begin
20 | a:=2
21 | end;
22 | b := a;
23 | c := 234
24 | end
25 | end";
26 | TextReader inputReader = new StringReader(fileContents);
27 | Lexer l = new Lexer(inputReader);
28 | Parser p = new Parser(l);
29 | try
30 | {
31 | p.Progr();
32 | if (l.LexKind == Tok.EOF)
33 | {
34 | Console.WriteLine("Program successfully recognized");
35 | }
36 | else
37 | {
38 | p.SyntaxError("end of file was expected");
39 | }
40 | }
41 | catch (ParserException e)
42 | {
43 | Console.WriteLine("lexer error: " + e.Message);
44 | }
45 | catch (LexerException le)
46 | {
47 | Console.WriteLine("parser error: " + le.Message);
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/TestLexer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestLexer")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestLexer")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("144BB4B2-AC18-4A38-9BEC-98BB22EB3382")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestVisitors/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestVisitors")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestVisitors")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("365C36ED-B8E4-428A-9AF4-A3142E06FE1E")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestASTParser/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestASTParser")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestASTParser")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("71D0BFF1-8F45-450E-A78F-153391124637")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestSimpleLexer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestSimpleLexer")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestSimpleLexer")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("53767749-BCA6-4A3A-A4E6-D23519008305")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestCodeGenerator/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestCodeGenerator")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestCodeGenerator")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("186EE1C7-7F34-4428-8A82-F63C8D4368E8")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestDescentParser/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestDescentParser")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestDescentParser")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("F6EABC41-B147-44EB-B6EF-13C3183C9961")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestGeneratedLexer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestGeneratedLexer")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestGeneratedLexer")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("24413F87-3568-4BDF-ADC8-760086CEE37A")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/TestGeneratedParser/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("TestGeneratedParser")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("TestGeneratedParser")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("76382857-9D1F-4098-8376-48EF4A702445")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/Module1/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Lexer")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Lexer")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("9715d879-f06e-4a65-ada0-a4df3619119d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module5/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLang")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLang")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("06dba63f-4805-4cd3-8a93-b329b2c7e37b")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module6/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLang")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLang")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("06dba63f-4805-4cd3-8a93-b329b2c7e37b")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module7/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLang")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLang")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("06dba63f-4805-4cd3-8a93-b329b2c7e37b")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module8/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLang")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLang")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("06dba63f-4805-4cd3-8a93-b329b2c7e37b")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/NunitReportParser/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Общие сведения об этой сборке предоставляются следующим набором
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("BAgl")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("BAgl")]
13 | [assembly: AssemblyCopyright("Copyright © 2019")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
18 | // для компонентов COM. Если необходимо обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("88e96425-f1e4-4092-8524-9c13225d2214")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер сборки
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module7/Visitors/AutoVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | // базовая логика обхода без действий
10 | // Если нужны действия или другая логика обхода, то соответствующие методы надо переопределять
11 | // При переопределении методов для задания действий необходимо не забывать обходить подузлы
12 | public class AutoVisitor: Visitor
13 | {
14 | public override void VisitBinOpNode(BinOpNode binop)
15 | {
16 | binop.Left.Visit(this);
17 | binop.Right.Visit(this);
18 | }
19 | public override void VisitAssignNode(AssignNode a)
20 | {
21 | // для каких-то визиторов порядок может быть обратный - вначале обойти выражение, потом - идентификатор
22 | a.Id.Visit(this);
23 | a.Expr.Visit(this);
24 | }
25 | public override void VisitCycleNode(CycleNode c)
26 | {
27 | c.Expr.Visit(this);
28 | c.Stat.Visit(this);
29 | }
30 | public override void VisitBlockNode(BlockNode bl)
31 | {
32 | foreach (var st in bl.StList)
33 | st.Visit(this);
34 | }
35 | public override void VisitWriteNode(WriteNode w)
36 | {
37 | w.Expr.Visit(this);
38 | }
39 | public override void VisitVarDefNode(VarDefNode w)
40 | {
41 | foreach (var v in w.vars)
42 | v.Visit(this);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Module2/SimpleLangLexer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLangLexer")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLangLexer")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("ae9968cd-e358-4d37-aa84-99d27f5dd537")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module2/SimpleLexerDemo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLexerDemo")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLexerDemo")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("ffd03552-aca5-4221-b7ce-a827ad8067e2")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module4/SimpleLangParser/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLangParser")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLangParser")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("02f0fd4f-1373-414b-a1ef-b7cf225e1470")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module4/SimpleLangParserTest/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Управление общими сведениями о сборке осуществляется с помощью
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("SimpleLangParserTest")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SimpleLangParserTest")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
18 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("780342e9-bf84-47b3-95da-830dd921148f")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер построения
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер построения и номер редакции по умолчанию,
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Module5/SimpleYacc.lst:
--------------------------------------------------------------------------------
1 |
2 | // ==========================================================================
3 | // GPPG error listing for yacc source file
4 | // ==========================================================================
5 | // Version: 1.3.6
6 | // Machine: SSM
7 | // DateTime: 17.08.2014 10:25:15
8 | // UserName: Станислав
9 | // ==========================================================================
10 |
11 |
12 | %{
13 | // Ýòè îáúÿâëåíèÿ äîáàâëÿþòñÿ â êëàññ GPPGParser, ïðåäñòàâëÿþùèé ñîáîé ïàðñåð, ãåíåðèðóåìûé ñèñòåìîé gppg
14 | public Parser(AbstractScanner scanner) : base(scanner) { }
15 | %}
16 |
17 | %output = SimpleYacc.cs
18 |
19 | %using System.IO;
20 |
21 | %namespace SimpleParser
22 |
23 | %token BEGIN END CYCLE INUM RNUM ID ASSIGN SEMICOLON
24 |
25 | %%
26 | // Error: NonTerminal symbol "st" has no productions
27 | // Warning: Terminating st fixes the following size-2 NonTerminal set
28 | // {cycle, st}
29 | // Error: There are 2 non-terminating NonTerminal Symbols
30 | // {cycle, st}
31 | // ------------------------------------------------------------------
32 |
33 | progr : block
34 | ;
35 |
36 | stlist : statement
37 | | stlist SEMICOLON statement
38 | ;
39 |
40 | statement: assign
41 | | block
42 | | cycle
43 | ;
44 |
45 | ident : ID
46 | ;
47 |
48 | assign : ident ASSIGN expr
49 | ;
50 |
51 | expr : ident
52 | | INUM
53 | ;
54 |
55 | block : BEGIN stlist END
56 | ;
57 |
58 | cycle : CYCLE expr st
59 | ;
60 |
61 | %%
62 |
63 | // ==========================================================================
64 |
65 |
--------------------------------------------------------------------------------
/grade.sh:
--------------------------------------------------------------------------------
1 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestSimpleLexer/bin/Debug/TestSimpleLexer.dll
2 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
3 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestLexer/bin/Debug/TestLexer.dll
4 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
5 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestGeneratedLexer/bin/Debug/TestGeneratedLexer.dll
6 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
7 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestDescentParser/bin/Debug/TestDescentParser.dll
8 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
9 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestGeneratedParser/bin/Debug/TestGeneratedParser.dll
10 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
11 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestASTParser/bin/Debug/TestASTParser.dll
12 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
13 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestVisitors/bin/Debug/TestVisitors.dll
14 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
15 | mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestCodeGenerator/bin/Debug/TestCodeGenerator.dll
16 | mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
--------------------------------------------------------------------------------
/Module8/Visitors/AutoVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | // базовая логика обхода без действий
10 | // Если нужны действия или другая логика обхода, то соответствующие методы надо переопределять
11 | // При переопределении методов для задания действий необходимо не забывать обходить подузлы
12 | class AutoVisitor: Visitor
13 | {
14 | public override void VisitBinOpNode(BinOpNode binop)
15 | {
16 | binop.Left.Visit(this);
17 | binop.Right.Visit(this);
18 | }
19 | public override void VisitAssignNode(AssignNode a)
20 | {
21 | // для каких-то визиторов порядок может быть обратный - вначале обойти выражение, потом - идентификатор
22 | a.Id.Visit(this);
23 | a.Expr.Visit(this);
24 | }
25 | public override void VisitCycleNode(CycleNode c)
26 | {
27 | c.Expr.Visit(this);
28 | c.Stat.Visit(this);
29 | }
30 | public override void VisitBlockNode(BlockNode bl)
31 | {
32 | foreach (var st in bl.StList)
33 | st.Visit(this);
34 | }
35 | public override void VisitWriteNode(WriteNode w)
36 | {
37 | w.Expr.Visit(this);
38 | }
39 | public override void VisitVarDefNode(VarDefNode w)
40 | {
41 | foreach (var v in w.vars)
42 | v.Visit(this);
43 | }
44 | public override void VisitIfNode(IfNode cond)
45 | {
46 | cond.expr.Visit(this);
47 | cond.ifTrue.Visit(this);
48 | if (cond.ifFalse != null)
49 | {
50 | cond.ifFalse.Visit(this);
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Module6/ProgramTree.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace ProgramTree
4 | {
5 | public enum AssignType { Assign, AssignPlus, AssignMinus, AssignMult, AssignDivide };
6 |
7 | public class Node // базовый класс для всех узлов
8 | {
9 | }
10 |
11 | public class ExprNode : Node // базовый класс для всех выражений
12 | {
13 | }
14 |
15 | public class IdNode : ExprNode
16 | {
17 | public string Name { get; set; }
18 | public IdNode(string name) { Name = name; }
19 | }
20 |
21 | public class IntNumNode : ExprNode
22 | {
23 | public int Num { get; set; }
24 | public IntNumNode(int num) { Num = num; }
25 | }
26 |
27 | public class StatementNode : Node // базовый класс для всех операторов
28 | {
29 | }
30 |
31 | public class AssignNode : StatementNode
32 | {
33 | public IdNode Id { get; set; }
34 | public ExprNode Expr { get; set; }
35 | public AssignType AssOp { get; set; }
36 | public AssignNode(IdNode id, ExprNode expr, AssignType assop = AssignType.Assign)
37 | {
38 | Id = id;
39 | Expr = expr;
40 | AssOp = assop;
41 | }
42 | }
43 |
44 | public class CycleNode : StatementNode
45 | {
46 | public ExprNode Expr { get; set; }
47 | public StatementNode Stat { get; set; }
48 | public CycleNode(ExprNode expr, StatementNode stat)
49 | {
50 | Expr = expr;
51 | Stat = stat;
52 | }
53 | }
54 |
55 | public class BlockNode : StatementNode
56 | {
57 | public List StList = new List();
58 | public BlockNode(StatementNode stat)
59 | {
60 | Add(stat);
61 | }
62 | public void Add(StatementNode stat)
63 | {
64 | StList.Add(stat);
65 | }
66 | }
67 |
68 | }
--------------------------------------------------------------------------------
/Module6/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using SimpleScanner;
5 | using SimpleParser;
6 | using System.Text;
7 | using Newtonsoft.Json;
8 |
9 | namespace SimpleCompiler
10 | {
11 | public class SimpleCompilerMain
12 | {
13 | public static void Main()
14 | {
15 | string FileName = @"..\..\a.txt";
16 | string OutputFileName = @"..\..\a.json";
17 | try
18 | {
19 | string Text = File.ReadAllText(FileName);
20 |
21 | Scanner scanner = new Scanner();
22 | scanner.SetSource(Text, 0);
23 |
24 | Parser parser = new Parser(scanner);
25 |
26 | var b = parser.Parse();
27 | if (!b)
28 | Console.WriteLine("Ошибка");
29 | else
30 | {
31 | Console.WriteLine("Синтаксическое дерево построено");
32 | JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
33 | jsonSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
34 | jsonSettings.TypeNameHandling = TypeNameHandling.All;
35 | string output = JsonConvert.SerializeObject(parser.root, jsonSettings);
36 | File.WriteAllText(OutputFileName, output);
37 | }
38 | }
39 | catch (FileNotFoundException)
40 | {
41 | Console.WriteLine("Файл {0} не найден", FileName);
42 | }
43 | catch (LexException e)
44 | {
45 | Console.WriteLine("Лексическая ошибка. " + e.Message);
46 | }
47 | catch (SyntaxException e)
48 | {
49 | Console.WriteLine("Синтаксическая ошибка. " + e.Message);
50 | }
51 |
52 | Console.ReadLine();
53 | }
54 |
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: csharp
2 | solution: Compilers.sln
3 | mono:
4 | - 6.4.0
5 |
6 | install:
7 | - sudo apt-get install nunit-console
8 | - nuget restore Compilers.sln
9 |
10 | script:
11 | - msbuild /p:TargetFrameworkVersion="v4.0"
12 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestSimpleLexer/bin/Debug/TestSimpleLexer.dll
13 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
14 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestLexer/bin/Debug/TestLexer.dll
15 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
16 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestGeneratedLexer/bin/Debug/TestGeneratedLexer.dll
17 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
18 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestDescentParser/bin/Debug/TestDescentParser.dll
19 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
20 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestGeneratedParser/bin/Debug/TestGeneratedParser.dll
21 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
22 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestASTParser/bin/Debug/TestASTParser.dll
23 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
24 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestVisitors/bin/Debug/TestVisitors.dll
25 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
26 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestCodeGenerator/bin/Debug/TestCodeGenerator.dll
27 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${TRAVIS_BUILD_DIR} ${TRAVIS_REPO_SLUG}
28 |
29 | branches:
30 | only:
31 | - master
32 |
--------------------------------------------------------------------------------
/Module8/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using System.Reflection;
5 | using System.Collections.Generic;
6 | using SimpleScanner;
7 | using SimpleParser;
8 | using SimpleLang.Visitors;
9 |
10 | namespace SimpleCompiler
11 | {
12 | public class SimpleCompilerMain
13 | {
14 | public static void Main()
15 | {
16 | string FileName = @"..\..\a.txt";
17 | try
18 | {
19 | string Text = File.ReadAllText(FileName);
20 |
21 | Scanner scanner = new Scanner();
22 | scanner.SetSource(Text, 0);
23 |
24 | Parser parser = new Parser(scanner);
25 |
26 | var b = parser.Parse();
27 | if (!b)
28 | Console.WriteLine("Ошибка");
29 | else
30 | {
31 | Console.WriteLine("Синтаксическое дерево построено");
32 |
33 | var avis = new AssignCountVisitor();
34 | parser.root.Visit(avis);
35 | Console.WriteLine("Количество присваиваний = {0}", avis.Count);
36 | Console.WriteLine("-------------------------------");
37 |
38 | var pp = new PrettyPrintVisitor();
39 | parser.root.Visit(pp);
40 | Console.WriteLine(pp.Text);
41 | Console.WriteLine("-------------------------------");
42 |
43 | var code = new GenCodeVisitor();
44 | parser.root.Visit(code);
45 | code.EndProgram();
46 | //code.PrintCommands();
47 | Console.WriteLine("-------------------------------");
48 |
49 | code.RunProgram();
50 | }
51 | }
52 | catch (FileNotFoundException)
53 | {
54 | Console.WriteLine("Файл {0} не найден", FileName);
55 | }
56 | catch (Exception e)
57 | {
58 | Console.WriteLine("{0}", e);
59 | }
60 |
61 | Console.ReadLine();
62 | }
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/TestGeneratedParser/Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using NUnit.Framework;
4 | using SimpleScanner;
5 | using SimpleParser;
6 |
7 | namespace TestGeneratedParser
8 | {
9 | [TestFixture]
10 | public class GeneratedParserTests
11 | {
12 | private bool Parse(string text)
13 | {
14 | Scanner scanner = new Scanner();
15 | scanner.SetSource(text, 0);
16 |
17 | Parser parser = new Parser(scanner);
18 |
19 | return parser.Parse();
20 | }
21 |
22 | [Test]
23 | public void TestWhile()
24 | {
25 | Assert.True(Parse(@"begin while 2 do a:=2 end"));
26 | }
27 |
28 | [Test]
29 | public void TestRepeat()
30 | {
31 | Assert.True(Parse(@"begin repeat a:=2; b:=3 until 3 end"));
32 | }
33 |
34 | [Test]
35 | public void TestFor()
36 | {
37 | Assert.True(Parse(@"begin for i:= 1 to 5 do a:=2 end"));
38 |
39 | Assert.True(Parse(@"begin for i:= 1 to 5 do if 3 then a:=2 else a:=5 end"));
40 | }
41 |
42 | [Test]
43 | public void TestWrite()
44 | {
45 | Assert.True(Parse(@"begin for i:= 1 to 5 do begin a:=2; write(a) end end"));
46 |
47 | Assert.True(Parse(@"begin if 2 then write(3) else write(4) end"));
48 |
49 | Assert.True(Parse(@"begin repeat write(5) until 2 end"));
50 | }
51 |
52 | [Test]
53 | public void TestIf()
54 | {
55 | Assert.True(Parse(@"begin if 2 then a:=3 else c:=8; if 3 then if 5 then z:=0 else n:=12 else g:=7 end"));
56 |
57 | Assert.True(Parse(@"begin while 1 do begin if 2 then a:=1 else b:=2 end end"));
58 | }
59 |
60 | [Test]
61 | public void TestVar()
62 | {
63 | Assert.True(Parse(@"begin var a,b,d end"));
64 | }
65 |
66 | [Test]
67 | public void TestExr()
68 | {
69 | Assert.True(Parse(@"begin a:=x-z*3/(c+3-(ddz)+2) end"));
70 |
71 | Assert.True(Parse(@"begin for i:=2+2*(c-3) to 5+6*2 do begin a:=x-z*3/(c+3-(ddz)+2); if (2-2) then c:=a-2 else write(2+2) end end"));
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/Module7/Visitors/PrettyPrintVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | class PrettyPrintVisitor: Visitor
10 | {
11 | public string Text = "";
12 | private int Indent = 0;
13 |
14 | private string IndentStr()
15 | {
16 | return new string(' ', Indent);
17 | }
18 | private void IndentPlus()
19 | {
20 | Indent += 2;
21 | }
22 | private void IndentMinus()
23 | {
24 | Indent -= 2;
25 | }
26 | public override void VisitIdNode(IdNode id)
27 | {
28 | Text += id.Name;
29 | }
30 | public override void VisitIntNumNode(IntNumNode num)
31 | {
32 | Text += num.Num.ToString();
33 | }
34 | public override void VisitBinOpNode(BinOpNode binop)
35 | {
36 | Text += "(";
37 | binop.Left.Visit(this);
38 | Text += " " + binop.Op + " ";
39 | binop.Right.Visit(this);
40 | Text += ")";
41 | }
42 | public override void VisitAssignNode(AssignNode a)
43 | {
44 | Text += IndentStr();
45 | a.Id.Visit(this);
46 | Text += " := ";
47 | a.Expr.Visit(this);
48 | }
49 | public override void VisitCycleNode(CycleNode c)
50 | {
51 | Text += IndentStr() + "cycle ";
52 | c.Expr.Visit(this);
53 | Text += Environment.NewLine;
54 | c.Stat.Visit(this);
55 | }
56 | public override void VisitBlockNode(BlockNode bl)
57 | {
58 | Text += IndentStr() + "begin" + Environment.NewLine;
59 | IndentPlus();
60 |
61 | var Count = bl.StList.Count;
62 |
63 | if (Count>0)
64 | bl.StList[0].Visit(this);
65 | for (var i = 1; i < Count; i++)
66 | {
67 | Text += ';';
68 | if (!(bl.StList[i] is EmptyNode))
69 | Text += Environment.NewLine;
70 | bl.StList[i].Visit(this);
71 | }
72 | IndentMinus();
73 | Text += Environment.NewLine + IndentStr() + "end";
74 | }
75 | public override void VisitWriteNode(WriteNode w)
76 | {
77 | Text += IndentStr() + "write(";
78 | w.Expr.Visit(this);
79 | Text += ")";
80 | }
81 | public override void VisitVarDefNode(VarDefNode w)
82 | {
83 | Text += IndentStr() + "var " + w.vars[0].Name;
84 | for (int i = 1; i < w.vars.Count; i++)
85 | Text += ',' + w.vars[i].Name;
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/NunitReportParser/NunitReport.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {88E96425-F1E4-4092-8524-9C13225D2214}
8 | Exe
9 | NunitReportParser
10 | NunitReportParser
11 | v4.6.1
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 | ..\packages\Newtonsoft.Json.12.0.3-beta1\lib\net45\Newtonsoft.Json.dll
38 | True
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/Module2/SimpleLangLexer/SimpleLexer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {28C0284B-2F43-45D6-A77F-AB08F919717D}
8 | Library
9 | Properties
10 | SimpleLexer
11 | SimpleLexer
12 | v4.0
13 | 512
14 |
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
61 |
--------------------------------------------------------------------------------
/Module1/Lexer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {9715D879-F06E-4A65-ADA0-A4DF3619119D}
8 | WinExe
9 | Properties
10 | Lexer
11 | Lexer
12 | v4.0
13 | 512
14 | true
15 |
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug\
23 | DEBUG;TRACE
24 | prompt
25 | 4
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | bin\Release\
32 | TRACE
33 | prompt
34 | 4
35 |
36 |
37 |
38 |
39 |
40 |
41 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
65 |
--------------------------------------------------------------------------------
/Module7/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 | using System.Reflection;
5 | using System.Collections.Generic;
6 | using SimpleScanner;
7 | using SimpleParser;
8 | using SimpleLang.Visitors;
9 |
10 | namespace SimpleCompiler
11 | {
12 | public class SimpleCompilerMain
13 | {
14 | public static void Main()
15 | {
16 | string FileName = @"..\..\a.txt";
17 | try
18 | {
19 | string Text = File.ReadAllText(FileName);
20 |
21 | Scanner scanner = new Scanner();
22 | scanner.SetSource(Text, 0);
23 |
24 | Parser parser = new Parser(scanner);
25 |
26 | var b = parser.Parse();
27 | if (!b)
28 | Console.WriteLine("Ошибка");
29 | else
30 | {
31 | Console.WriteLine("Синтаксическое дерево построено");
32 |
33 | var pp = new PrettyPrintVisitor();
34 | parser.root.Visit(pp);
35 | Console.WriteLine(pp.Text);
36 | Console.WriteLine("-------------------------------");
37 |
38 | var avis = new AssignCountVisitor();
39 | parser.root.Visit(avis);
40 | Console.WriteLine("Количество присваиваний = {0}", avis.Count);
41 | Console.WriteLine("-------------------------------");
42 |
43 | var midCount = new CountCyclesOpVisitor();
44 | parser.root.Visit(midCount);
45 | Console.WriteLine("Среднее количество операторов = {0}", midCount.MidCount());
46 | Console.WriteLine("-------------------------------");
47 |
48 | var cuv = new CommonlyUsedVarVisitor();
49 | parser.root.Visit(cuv);
50 | Console.WriteLine("Наиболее часто используемая переменная = {0}", cuv.mostCommonlyUsedVar());
51 | Console.WriteLine("-------------------------------");
52 |
53 | var cviv = new ChangeVarIdVisitor("a", "d");
54 | parser.root.Visit(cviv);
55 | Console.WriteLine("Переименование переменной a на d:");
56 | pp = new PrettyPrintVisitor();
57 | parser.root.Visit(pp);
58 | Console.WriteLine(pp.Text);
59 | Console.WriteLine("-------------------------------");
60 |
61 | var mncv = new MaxNestCyclesVisitor();
62 | parser.root.Visit(mncv);
63 | Console.WriteLine("Максимальная вложенность циклов = {0}", mncv.MaxNest);
64 | Console.WriteLine("-------------------------------");
65 | }
66 | }
67 | catch (FileNotFoundException)
68 | {
69 | Console.WriteLine("Файл {0} не найден", FileName);
70 | }
71 | catch (Exception e)
72 | {
73 | Console.WriteLine("{0}", e);
74 | }
75 |
76 | Console.ReadLine();
77 | }
78 |
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/Module8/Visitors/GenCodeVisitors/GenCodeCreator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Reflection.Emit;
6 | using System.Reflection;
7 |
8 | namespace SimpleLang.Visitors
9 | {
10 | class GenCodeCreator
11 | {
12 | private DynamicMethod dyn;
13 | private ILGenerator gen;
14 | private bool write_commands = true;
15 | private static MethodInfo writeLineInt = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) });
16 |
17 | public List commands = new List();
18 |
19 | public GenCodeCreator()
20 | {
21 | dyn = new DynamicMethod("My", null, null, typeof(void));
22 | gen = dyn.GetILGenerator();
23 | }
24 |
25 | public void Emit(OpCode op)
26 | {
27 | gen.Emit(op);
28 | if (write_commands)
29 | commands.Add(op.ToString());
30 | }
31 |
32 | public void Emit(OpCode op, int num)
33 | {
34 | gen.Emit(op,num);
35 | if (write_commands)
36 | commands.Add(op.ToString() + " " + num);
37 | }
38 |
39 | public void Emit(OpCode op, LocalBuilder lb)
40 | {
41 | gen.Emit(op, lb);
42 | if (write_commands)
43 | commands.Add(op.ToString() + " var" + lb.LocalIndex);
44 | }
45 |
46 | public void Emit(OpCode op, Label l)
47 | {
48 | gen.Emit(op, l);
49 | if (write_commands)
50 | commands.Add(op.ToString() + " Label" + l.GetHashCode());
51 | }
52 |
53 | public LocalBuilder DeclareLocal(Type t)
54 | {
55 | var lb = gen.DeclareLocal(t);
56 | if (write_commands)
57 | commands.Add("DeclareLocal " + "var" + lb.LocalIndex + ": " + t);
58 | return lb;
59 | }
60 |
61 | public Label DefineLabel()
62 | {
63 | var l = gen.DefineLabel();
64 | if (write_commands)
65 | commands.Add("DefineLabel" + " Label" + l.GetHashCode());
66 |
67 | return l;
68 | }
69 |
70 | public void MarkLabel(Label l)
71 | {
72 | gen.MarkLabel(l);
73 | if (write_commands)
74 | commands.Add("MarkLabel" + " Label" + l.GetHashCode());
75 | }
76 |
77 | public void EmitWriteLine()
78 | {
79 | gen.Emit(OpCodes.Call, writeLineInt);
80 | if (write_commands)
81 | commands.Add("WriteLine");
82 | }
83 |
84 | public void EndProgram()
85 | {
86 | gen.Emit(OpCodes.Ret);
87 | }
88 |
89 | public void RunProgram()
90 | {
91 | dyn.Invoke(null, null);
92 | }
93 |
94 | public void WriteCommandsOn()
95 | {
96 | write_commands = true;
97 | }
98 |
99 | public void WriteCommandsOff()
100 | {
101 | write_commands = false;
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/Module2/SimpleLexerDemo/SimpleLexerDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {9EE96E14-A541-4EAD-AD34-2A9011ED12C1}
8 | Exe
9 | Properties
10 | SimpleLexerDemo
11 | SimpleLexerDemo
12 | v4.0
13 | 512
14 |
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 | {28c0284b-2f43-45d6-a77f-ab08f919717d}
53 | SimpleLexer
54 |
55 |
56 |
57 |
58 |
59 |
60 |
67 |
--------------------------------------------------------------------------------
/Module4/SimpleLangParser/RecursiveDescentParser.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {837BC9FE-DAA9-416E-BCCE-0235E5C38D4B}
8 | Library
9 | Properties
10 | SimpleLangParser
11 | SimpleLangParser
12 | v4.0
13 | 512
14 |
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | {28c0284b-2f43-45d6-a77f-ab08f919717d}
56 | SimpleLexer
57 |
58 |
59 |
60 |
67 |
--------------------------------------------------------------------------------
/TestCodeGenerator/Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Net;
4 | using NUnit.Framework;
5 | using SimpleScanner;
6 | using SimpleParser;
7 | using SimpleLang.Visitors;
8 |
9 | namespace TestCodeGenerator
10 | {
11 | public class TestHelper
12 | {
13 | public static Parser Parse(string text)
14 | {
15 | Scanner scanner = new Scanner();
16 | scanner.SetSource(text, 0);
17 | Parser parser = new Parser(scanner);
18 | Assert.IsTrue(parser.Parse());
19 | return parser;
20 | }
21 |
22 | public static string GenerateNRun(string text)
23 | {
24 | var parser = TestHelper.Parse(text);
25 | var code = new GenCodeVisitor();
26 | parser.root.Visit(code);
27 | code.EndProgram();
28 | //code.PrintCommands();
29 | string output = "";
30 | using(MemoryStream ms = new MemoryStream())
31 | {
32 | var sw = new StreamWriter(ms);
33 | try
34 | {
35 | Console.SetOut(sw);
36 | code.RunProgram();
37 | sw.Flush();
38 |
39 | ms.Seek(0, SeekOrigin.Begin);
40 | var sr = new StreamReader(ms);
41 | output = sr.ReadToEnd().Trim();
42 | }
43 | finally
44 | {
45 | sw.Dispose();
46 | }
47 | }
48 | return output;
49 | }
50 | }
51 |
52 | [TestFixture]
53 | public class TestCodeGenerator
54 | {
55 | [Test]
56 | public void SmokeTest()
57 | {
58 | var parser = TestHelper.Parse(@"begin end");
59 | var code = new GenCodeVisitor();
60 | parser.root.Visit(code);
61 | code.EndProgram();
62 | //code.PrintCommands();
63 | code.RunProgram();
64 | }
65 |
66 | [Test]
67 | public void TestOutput()
68 | {
69 | Assert.AreEqual("2", TestHelper.GenerateNRun(@"begin write(2) end"));
70 | }
71 |
72 | [Test]
73 | public void TestIntDivMod()
74 | {
75 | Assert.AreEqual("48", TestHelper.GenerateNRun(@"begin var a; a := (232 / 5) + (232 % 5); write(a) end"));
76 | }
77 |
78 | [Test]
79 | public void TestIf()
80 | {
81 | Assert.AreEqual("3", TestHelper.GenerateNRun(@"begin var a1; a1 := 0; if a1 then write(2) else write(3) end"));
82 |
83 | Assert.AreEqual("3", TestHelper.GenerateNRun(@"begin var x,y; x := 1; y := x-1; if x then if y then write(2) else write(3) end"));
84 | }
85 |
86 | [Test]
87 | public void TestWhile()
88 | {
89 | Assert.AreEqual("1024", TestHelper.GenerateNRun(@"begin var a2,b2; b2:=1; a2:=10; while a2 do begin a2:=a2-1; b2:=b2*2; end; write(b2) end"));
90 | }
91 |
92 | [Test]
93 | public void TestUntil()
94 | {
95 | Assert.AreEqual("1024", TestHelper.GenerateNRun(@"begin var a3,b3; b3:=1; a3:=10; repeat a3:=a3-1; b3:=b3*2 until a3; write(b3) end"));
96 | }
97 | }
98 | }
--------------------------------------------------------------------------------
/TestGeneratedLexer/Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NUnit.Framework;
3 | using GeneratedLexer;
4 |
5 | namespace TestGeneratedLexer
6 | {
7 | [TestFixture]
8 | public class GeneratedLexerTests
9 | {
10 | [Test]
11 | public void TestIdCount()
12 | {
13 | LexerAddon lexer = new LexerAddon(@"id1 id2 id3
14 | id4 id5 ");
15 | lexer.Lex();
16 | Assert.AreEqual(5, lexer.idCount);
17 | }
18 |
19 | [Test]
20 | public void TestIdInfo()
21 | {
22 | LexerAddon lexer = new LexerAddon(@"i22d1 i id3
23 | Md4 inNd5 ");
24 | lexer.Lex();
25 | Assert.AreEqual(5, lexer.idCount);
26 | Assert.AreEqual(5, lexer.maxIdLength);
27 | Assert.AreEqual(1, lexer.minIdLength);
28 | Assert.AreEqual(3.4, lexer.avgIdLength, 0.001);
29 | }
30 |
31 | [Test]
32 | public void TestNumbers()
33 | {
34 | LexerAddon lexer = new LexerAddon(@"i22d1 5.6 i 32 id3
35 | Md4 8.9 inNd5 1 42 ");
36 | lexer.Lex();
37 |
38 | Assert.AreEqual(75, lexer.sumInt);
39 | Assert.AreEqual(14.5, lexer.sumDouble, 0.001);
40 | }
41 |
42 | [Test]
43 | public void TestString()
44 | {
45 | LexerAddon lexer = new LexerAddon(@"3 389 3 'ssfsf ' ");
46 | lexer.Lex();
47 |
48 | // TODO: checks in this test
49 | }
50 |
51 | [Test]
52 | public void TestSingleLineCmt()
53 | {
54 | LexerAddon lexer = new LexerAddon(@"i22d1 5.6 // i 32 id3
55 | Md4 8.9 inNd5 1 42 ");
56 | lexer.Lex();
57 |
58 | Assert.AreEqual(3, lexer.idCount);
59 | Assert.AreEqual(43, lexer.sumInt);
60 | Assert.AreEqual(14.5, lexer.sumDouble, 0.001);
61 | }
62 |
63 | [Test]
64 | public void TestMultiLineCmt()
65 | {
66 | LexerAddon lexer = new LexerAddon(@"i22d1 5.6 { i 32 id3
67 | Md4 2.3 2 33} 8.9 inNd5 1 42 ");
68 | lexer.Lex();
69 |
70 | Assert.AreEqual(2, lexer.idCount);
71 | Assert.AreEqual(43, lexer.sumInt);
72 | Assert.AreEqual(14.5, lexer.sumDouble, 0.001);
73 | }
74 |
75 | [Test]
76 | public void TestMultiLineCmtIds()
77 | {
78 | LexerAddon lexer = new LexerAddon(@"i22d1 5.6 { i 32 id3
79 | Md4 tgg begin ide2
80 | end ids 2.3 2 33} 8.9 inNd5 1 42 ");
81 | lexer.Lex();
82 |
83 | Assert.AreEqual(6, lexer.idsInComment.Count);
84 | Assert.Contains("i", lexer.idsInComment);
85 | Assert.Contains("id3", lexer.idsInComment);
86 | Assert.Contains("Md4", lexer.idsInComment);
87 | Assert.Contains("tgg", lexer.idsInComment);
88 | Assert.Contains("ide2", lexer.idsInComment);
89 | Assert.Contains("ids", lexer.idsInComment);
90 |
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/Module4/SimpleLangParserTest/RecursiveDescentParserDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {5DD15A1A-760A-4A3F-BA1B-A23ACDF5CC87}
8 | WinExe
9 | Properties
10 | SimpleLangParserTest
11 | SimpleLangParserTest
12 | v4.0
13 | 512
14 |
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | {28c0284b-2f43-45d6-a77f-ab08f919717d}
56 | SimpleLexer
57 |
58 |
59 | {837bc9fe-daa9-416e-bcce-0235e5c38d4b}
60 | RecursiveDescentParser
61 |
62 |
63 |
64 |
65 |
66 |
67 |
74 |
--------------------------------------------------------------------------------
/Module4/SimpleLangParser/SimpleLangParser.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using SimpleLexer;
5 | namespace SimpleLangParser
6 | {
7 | public class ParserException : System.Exception
8 | {
9 | public ParserException(string msg)
10 | : base(msg)
11 | {
12 | }
13 |
14 | }
15 |
16 | public class Parser
17 | {
18 | private SimpleLexer.Lexer l;
19 |
20 | public Parser(SimpleLexer.Lexer lexer)
21 | {
22 | l = lexer;
23 | }
24 |
25 | public void Progr()
26 | {
27 | Block();
28 | }
29 |
30 | public void Expr()
31 | {
32 | if (l.LexKind == Tok.ID || l.LexKind == Tok.INUM)
33 | {
34 | l.NextLexem();
35 | }
36 | else
37 | {
38 | SyntaxError("expression expected");
39 | }
40 | }
41 |
42 | public void Assign()
43 | {
44 | l.NextLexem(); // пропуск id
45 | if (l.LexKind == Tok.ASSIGN)
46 | {
47 | l.NextLexem();
48 | }
49 | else {
50 | SyntaxError(":= expected");
51 | }
52 | Expr();
53 | }
54 |
55 | public void StatementList()
56 | {
57 | Statement();
58 | while (l.LexKind == Tok.SEMICOLON)
59 | {
60 | l.NextLexem();
61 | Statement();
62 | }
63 | }
64 |
65 | public void Statement()
66 | {
67 | switch (l.LexKind)
68 | {
69 | case Tok.BEGIN:
70 | {
71 | Block();
72 | break;
73 | }
74 | case Tok.CYCLE:
75 | {
76 | Cycle();
77 | break;
78 | }
79 | case Tok.ID:
80 | {
81 | Assign();
82 | break;
83 | }
84 | default:
85 | {
86 | SyntaxError("Operator expected");
87 | break;
88 | }
89 | }
90 | }
91 |
92 | public void Block()
93 | {
94 | l.NextLexem(); // пропуск begin
95 | StatementList();
96 | if (l.LexKind == Tok.END)
97 | {
98 | l.NextLexem();
99 | }
100 | else
101 | {
102 | SyntaxError("end expected");
103 | }
104 |
105 | }
106 |
107 | public void Cycle()
108 | {
109 | l.NextLexem(); // пропуск cycle
110 | Expr();
111 | Statement();
112 | }
113 |
114 | public void SyntaxError(string message)
115 | {
116 | var errorMessage = "Syntax error in line " + l.LexRow.ToString() + ":\n";
117 | errorMessage += l.FinishCurrentLine() + "\n";
118 | errorMessage += new String(' ', l.LexCol - 1) + "^\n";
119 | if (message != "")
120 | {
121 | errorMessage += message;
122 | }
123 | throw new ParserException(errorMessage);
124 | }
125 |
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/Module8/Visitors/PrettyPrintVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 |
7 | namespace SimpleLang.Visitors
8 | {
9 | class PrettyPrintVisitor: Visitor
10 | {
11 | public string Text = "";
12 | private int Indent = 0;
13 |
14 | private string IndentStr()
15 | {
16 | return new string(' ', Indent);
17 | }
18 | private void IndentPlus()
19 | {
20 | Indent += 2;
21 | }
22 | private void IndentMinus()
23 | {
24 | Indent -= 2;
25 | }
26 | public override void VisitIdNode(IdNode id)
27 | {
28 | Text += id.Name;
29 | }
30 | public override void VisitIntNumNode(IntNumNode num)
31 | {
32 | Text += num.Num.ToString();
33 | }
34 | public override void VisitBinOpNode(BinOpNode binop)
35 | {
36 | Text += "(";
37 | binop.Left.Visit(this);
38 | Text += " " + binop.Op + " ";
39 | binop.Right.Visit(this);
40 | Text += ")";
41 | }
42 | public override void VisitAssignNode(AssignNode a)
43 | {
44 | Text += IndentStr();
45 | a.Id.Visit(this);
46 | Text += " := ";
47 | a.Expr.Visit(this);
48 | }
49 | public override void VisitCycleNode(CycleNode c)
50 | {
51 | Text += IndentStr() + "cycle ";
52 | c.Expr.Visit(this);
53 | Text += Environment.NewLine;
54 | c.Stat.Visit(this);
55 | }
56 | public override void VisitBlockNode(BlockNode bl)
57 | {
58 | Text += IndentStr() + "begin" + Environment.NewLine;
59 | IndentPlus();
60 |
61 | var Count = bl.StList.Count;
62 |
63 | if (Count>0)
64 | bl.StList[0].Visit(this);
65 | for (var i = 1; i < Count; i++)
66 | {
67 | Text += ';';
68 | if (!(bl.StList[i] is EmptyNode))
69 | Text += Environment.NewLine;
70 | bl.StList[i].Visit(this);
71 | }
72 | IndentMinus();
73 | Text += Environment.NewLine + IndentStr() + "end";
74 | }
75 | public override void VisitWriteNode(WriteNode w)
76 | {
77 | Text += IndentStr() + "write(";
78 | w.Expr.Visit(this);
79 | Text += ")";
80 | }
81 | public override void VisitVarDefNode(VarDefNode w)
82 | {
83 | Text += IndentStr() + "var " + w.vars[0].Name;
84 | for (int i = 1; i < w.vars.Count; i++)
85 | Text += ',' + w.vars[i].Name;
86 | }
87 | public override void VisitIfNode(IfNode cond)
88 | {
89 | Text += IndentStr() + "if ";
90 | cond.expr.Visit(this);
91 | Text += " then ";
92 | Text += Environment.NewLine;
93 | IndentPlus();
94 | cond.ifTrue.Visit(this);
95 | IndentMinus();
96 | if (null != cond.ifFalse)
97 | {
98 | Text += Environment.NewLine;
99 | Text += IndentStr() + "else ";
100 | Text += Environment.NewLine;
101 | IndentPlus();
102 | cond.ifFalse.Visit(this);
103 | IndentMinus();
104 | }
105 | }
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/TestASTParser/Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NUnit.Framework;
3 | using SimpleScanner;
4 | using SimpleParser;
5 | using System.Text;
6 | using Newtonsoft.Json;
7 | using Newtonsoft.Json.Linq;
8 |
9 | namespace TestASTParser
10 | {
11 | public class ASTParserTests
12 | {
13 | public static JObject Parse(string text)
14 | {
15 | Scanner scanner = new Scanner();
16 | scanner.SetSource(text, 0);
17 |
18 | Parser parser = new Parser(scanner);
19 |
20 | var b = parser.Parse();
21 | if (!b)
22 | Assert.Fail("программа не распознана");
23 | else
24 | {
25 | JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
26 | jsonSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
27 | jsonSettings.TypeNameHandling = TypeNameHandling.All;
28 | string output = JsonConvert.SerializeObject(parser.root, jsonSettings);
29 | return JObject.Parse(output);
30 | }
31 |
32 | return null;
33 |
34 | }
35 | }
36 |
37 | [TestFixture]
38 | public class WhileTests
39 | {
40 |
41 | [Test]
42 | public void TestWhile()
43 | {
44 | var tree = ASTParserTests.Parse("begin while 2 do a:=2 end");
45 | Assert.AreEqual("ProgramTree.WhileNode, SimpleLang", (string)tree["StList"]["$values"][0]["$type"]);
46 | Assert.AreEqual("ProgramTree.IntNumNode, SimpleLang", (string)tree["StList"]["$values"][0]["Expr"]["$type"]);
47 | Assert.AreEqual("2", ((string)tree["StList"]["$values"][0]["Expr"]["Num"]).Trim());
48 | Assert.AreEqual("ProgramTree.AssignNode, SimpleLang", (string)tree["StList"]["$values"][0]["Stat"]["$type"]);
49 | }
50 | }
51 |
52 | [TestFixture]
53 | public class RepeatTests
54 | {
55 |
56 | [Test]
57 | public void TestRepeat()
58 | {
59 | var tree = ASTParserTests.Parse("begin repeat a:=2 until 2 end");
60 | Assert.AreEqual("ProgramTree.RepeatNode, SimpleLang", (string)tree["StList"]["$values"][0]["$type"]);
61 | // TODO: проверить узлы содержимого repeat
62 | }
63 | }
64 |
65 | [TestFixture]
66 | public class ForTests
67 | {
68 |
69 | [Test]
70 | public void TestFor()
71 | {
72 | var tree = ASTParserTests.Parse("begin for i:=2 to 10 do a:=2 end");
73 | Assert.AreEqual("ProgramTree.ForNode, SimpleLang", (string)tree["StList"]["$values"][0]["$type"]);
74 | // TODO: проверить узлы содержимого for
75 | }
76 | }
77 |
78 | [TestFixture]
79 | public class WriteTests
80 | {
81 |
82 | [Test]
83 | public void TestWrite()
84 | {
85 | var tree = ASTParserTests.Parse("begin write(2) end");
86 | Assert.AreEqual("ProgramTree.WriteNode, SimpleLang", (string)tree["StList"]["$values"][0]["$type"]);
87 | // TODO: проверить содержимое write
88 | }
89 | }
90 |
91 | [TestFixture]
92 | public class ExtraTests
93 | {
94 |
95 | [Test]
96 | public void TestIf()
97 | {
98 | Assert.Fail();
99 | // TODO: дописать тест
100 | }
101 |
102 | [Test]
103 | public void TestVarDef()
104 | {
105 | Assert.Fail();
106 | // TODO: дописать тест
107 | }
108 |
109 | [Test]
110 | public void TestBinary()
111 | {
112 | Assert.Fail();
113 | // TODO: дописать тест
114 | }
115 | }
116 | }
--------------------------------------------------------------------------------
/Module8/SimpleYacc.lst:
--------------------------------------------------------------------------------
1 |
2 | // ==========================================================================
3 | // GPPG error listing for yacc source file
4 | // ==========================================================================
5 | // Version: 1.3.6
6 | // Machine: SSM
7 | // DateTime: 19.08.2014 13:28:35
8 | // UserName: Станислав
9 | // ==========================================================================
10 |
11 |
12 | %{
13 | // Ýòè îáúÿâëåíèÿ äîáàâëÿþòñÿ â êëàññ GPPGParser, ïðåäñòàâëÿþùèé ñîáîé ïàðñåð, ãåíåðèðóåìûé ñèñòåìîé gppg
14 | public BlockNode root; // Êîðíåâîé óçåë ñèíòàêñè÷åñêîãî äåðåâà
15 | public Parser(AbstractScanner scanner) : base(scanner) { }
16 | private bool InDefSect = false;
17 | %}
18 |
19 | %output = SimpleYacc.cs
20 |
21 | %union {
22 | public double dVal;
23 | public int iVal;
24 | public string sVal;
25 | public Node nVal;
26 | public ExprNode eVal;
27 | public StatementNode stVal;
28 | public BlockNode blVal;
29 | }
30 |
31 | %using System.IO;
32 | %using ProgramTree;
33 |
34 | %namespace SimpleParser
35 |
36 | %start progr
37 |
38 | %token BEGIN END CYCLE ASSIGN ASSIGNPLUS ASSIGNMINUS ASSIGNMULT SEMICOLON WRITE VAR PLUS MINUS MULT DIV LPAREN RPAREN COLUMN
39 | %token INUM
40 | %token RNUM
41 | %token ID
42 |
43 | %type varlist
44 | %type expr ident T F
45 | %type statement assign block cycle write empty var
46 | %type stlist block
47 |
48 | %%
49 | // Error: NonTerminal symbol "st" has no productions
50 | // Warning: Terminating st fixes the following size-2 NonTerminal set
51 | // {cycle, st}
52 | // Error: There are 2 non-terminating NonTerminal Symbols
53 | // {cycle, st}
54 | // ------------------------------------------------------------------
55 |
56 | progr : block { root = $1; }
57 | ;
58 |
59 | stlist : statement
60 | {
61 | $$ = new BlockNode($1);
62 | }
63 | | stlist SEMICOLON statement
64 | {
65 | $1.Add($3);
66 | $$ = $1;
67 | }
68 | ;
69 |
70 | statement: assign { $$ = $1; }
71 | | block { $$ = $1; }
72 | | cycle { $$ = $1; }
73 | | write { $$ = $1; }
74 | | var { $$ = $1; }
75 | | empty { $$ = $1; }
76 | ;
77 |
78 | empty : { $$ = new EmptyNode(); }
79 | ;
80 |
81 | ident : ID
82 | {
83 | if (!InDefSect)
84 | if (!SymbolTable.vars.ContainsKey($1))
85 | throw new Exception("("+@1.StartLine+","+@1.StartColumn+"): Ïåðåìåííàÿ "+$1+" íå îïèñàíà");
86 | $$ = new IdNode($1);
87 | }
88 | ;
89 |
90 | assign : ident ASSIGN expr { $$ = new AssignNode($1 as IdNode, $3); }
91 | ;
92 |
93 | expr : expr PLUS T { $$ = new BinOpNode($1,$3,'+'); }
94 | | expr MINUS T { $$ = new BinOpNode($1,$3,'-'); }
95 | | T { $$ = $1; }
96 | ;
97 |
98 | T : T MULT F { $$ = new BinOpNode($1,$3,'*'); }
99 | | T DIV F { $$ = new BinOpNode($1,$3,'/'); }
100 | | F { $$ = $1; }
101 | ;
102 |
103 | F : ident { $$ = $1 as IdNode; }
104 | | INUM { $$ = new IntNumNode($1); }
105 | | LPAREN expr RPAREN { $$ = $2; }
106 | ;
107 |
108 | block : BEGIN stlist END { $$ = $2; }
109 | ;
110 |
111 | cycle : CYCLE expr st { $$ = new CycleNode($2,$3); }
112 | ;
113 |
114 | write : WRITE LPAREN expr RPAREN { $$ = new WriteNode($3); }
115 | ;
116 |
117 | var : VAR { InDefSect = true; } varlist
118 | {
119 | foreach (var v in ($3 as VarDefNode).vars)
120 | SymbolTable.NewVarDef(v.Name, type.tint);
121 | InDefSect = false;
122 | }
123 | ;
124 |
125 | varlist : ident
126 | {
127 | $$ = new VarDefNode($1 as IdNode);
128 | }
129 | | varlist COLUMN ident
130 | {
131 | ($1 as VarDefNode).Add($3 as IdNode);
132 | $$ = $1;
133 | }
134 | ;
135 |
136 | %%
137 |
138 | // ==========================================================================
139 |
140 |
--------------------------------------------------------------------------------
/Module8/Visitors/GenCodeVisitors/GenCodeVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using ProgramTree;
6 | using System.Reflection.Emit;
7 |
8 | namespace SimpleLang.Visitors
9 | {
10 | public class GenCodeVisitor: Visitor
11 | {
12 | private Dictionary vars = new Dictionary();
13 | private GenCodeCreator genc;
14 |
15 | public GenCodeVisitor()
16 | {
17 | genc = new GenCodeCreator();
18 | }
19 | public override void VisitIdNode(IdNode id)
20 | {
21 | // Этот Visit не вызывается если переменная стоит слева от оператора присваивания !
22 | // Т.е. он вызывается только если id находится в выражении, а значит, мы просто кладем его значение на стек!
23 | genc.Emit(OpCodes.Ldloc, vars[id.Name]);
24 | }
25 | public override void VisitIntNumNode(IntNumNode num)
26 | {
27 | genc.Emit(OpCodes.Ldc_I4, num.Num);
28 | }
29 | public override void VisitBinOpNode(BinOpNode binop)
30 | {
31 | binop.Left.Visit(this);
32 | binop.Right.Visit(this);
33 | switch (binop.Op)
34 | {
35 | case '+':
36 | genc.Emit(OpCodes.Add);
37 | break;
38 | case '-':
39 | genc.Emit(OpCodes.Sub);
40 | break;
41 | case '*':
42 | genc.Emit(OpCodes.Mul);
43 | break;
44 | case '/':
45 | genc.Emit(OpCodes.Div);
46 | break;
47 | }
48 | }
49 | public override void VisitAssignNode(AssignNode a)
50 | {
51 | a.Expr.Visit(this);
52 | genc.Emit(OpCodes.Stloc, vars[a.Id.Name]);
53 | }
54 | public override void VisitCycleNode(CycleNode c)
55 | {
56 | var i = genc.DeclareLocal(typeof(int)); // переменная цикла cycle
57 | c.Expr.Visit(this); // сгенерировать команды, связанные с вычислением количества итераций цикла
58 | genc.Emit(OpCodes.Stloc, i); // i := кво итераций
59 |
60 | Label startLoop = genc.DefineLabel();
61 | Label endLoop = genc.DefineLabel();
62 |
63 | genc.MarkLabel(startLoop);
64 |
65 | genc.Emit(OpCodes.Ldloc, i);
66 | genc.Emit(OpCodes.Ldc_I4_0);
67 | genc.Emit(OpCodes.Ble, endLoop); // if i<=0 then goto endLoop
68 |
69 | c.Stat.Visit(this); // выполнить тело цикла
70 |
71 | genc.Emit(OpCodes.Ldloc, i); // положить i на стек
72 | genc.Emit(OpCodes.Ldc_I4_1); // положить 1 на стек
73 | genc.Emit(OpCodes.Sub);
74 | genc.Emit(OpCodes.Stloc, i); // i := i - 1;
75 |
76 | genc.Emit(OpCodes.Br, startLoop);
77 |
78 | genc.MarkLabel(endLoop);
79 | }
80 | public override void VisitBlockNode(BlockNode bl)
81 | {
82 | foreach (var st in bl.StList)
83 | st.Visit(this);
84 | }
85 | public override void VisitWriteNode(WriteNode w)
86 | {
87 | w.Expr.Visit(this);
88 | genc.EmitWriteLine();
89 | }
90 |
91 | public override void VisitVarDefNode(VarDefNode w)
92 | {
93 | foreach (var v in w.vars)
94 | vars[v.Name] = genc.DeclareLocal(typeof(int));
95 | }
96 |
97 | public void EndProgram()
98 | {
99 | genc.EndProgram();
100 | }
101 |
102 | public void RunProgram()
103 | {
104 | genc.RunProgram();
105 | }
106 |
107 | public void PrintCommands()
108 | {
109 | foreach (var s in genc.commands)
110 | Console.WriteLine(s);
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/Module5/GeneratedParser.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | x86
6 | 8.0.30703
7 | 2.0
8 | {0ED50D29-F6C3-44F3-BF13-BC1A433F6119}
9 | Exe
10 | Properties
11 | SimpleLang
12 | SimpleLang
13 | v4.0
14 |
15 |
16 | 512
17 |
18 |
19 | x86
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | x86
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 | true
39 | bin\Debug\
40 | DEBUG;TRACE
41 | full
42 | AnyCPU
43 | prompt
44 | MinimumRecommendedRules.ruleset
45 |
46 |
47 | bin\Release\
48 | TRACE
49 | true
50 | pdbonly
51 | AnyCPU
52 | prompt
53 | MinimumRecommendedRules.ruleset
54 |
55 |
56 |
57 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
91 |
--------------------------------------------------------------------------------
/Module7/ProgramTree.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using SimpleLang.Visitors;
3 |
4 | namespace ProgramTree
5 | {
6 | public enum AssignType { Assign, AssignPlus, AssignMinus, AssignMult, AssignDivide };
7 |
8 | public abstract class Node // базовый класс для всех узлов
9 | {
10 | public abstract void Visit(Visitor v);
11 | }
12 |
13 | public abstract class ExprNode : Node // базовый класс для всех выражений
14 | {
15 | }
16 |
17 | public class IdNode : ExprNode
18 | {
19 | public string Name { get; set; }
20 | public IdNode(string name) { Name = name; }
21 | public override void Visit(Visitor v)
22 | {
23 | v.VisitIdNode(this);
24 | }
25 | }
26 |
27 | public class IntNumNode : ExprNode
28 | {
29 | public int Num { get; set; }
30 | public IntNumNode(int num) { Num = num; }
31 | public override void Visit(Visitor v)
32 | {
33 | v.VisitIntNumNode(this);
34 | }
35 | }
36 |
37 | public class BinOpNode : ExprNode
38 | {
39 | public ExprNode Left { get; set; }
40 | public ExprNode Right { get; set; }
41 | public char Op { get; set; }
42 | public BinOpNode(ExprNode Left, ExprNode Right, char op)
43 | {
44 | this.Left = Left;
45 | this.Right = Right;
46 | this.Op = op;
47 | }
48 | public override void Visit(Visitor v)
49 | {
50 | v.VisitBinOpNode(this);
51 | }
52 | }
53 |
54 | public abstract class StatementNode : Node // базовый класс для всех операторов
55 | {
56 | }
57 |
58 | public class AssignNode : StatementNode
59 | {
60 | public IdNode Id { get; set; }
61 | public ExprNode Expr { get; set; }
62 | public AssignType AssOp { get; set; }
63 | public AssignNode(IdNode id, ExprNode expr, AssignType assop = AssignType.Assign)
64 | {
65 | Id = id;
66 | Expr = expr;
67 | AssOp = assop;
68 | }
69 | public override void Visit(Visitor v)
70 | {
71 | v.VisitAssignNode(this);
72 | }
73 | }
74 |
75 | public class CycleNode : StatementNode
76 | {
77 | public ExprNode Expr { get; set; }
78 | public StatementNode Stat { get; set; }
79 | public CycleNode(ExprNode expr, StatementNode stat)
80 | {
81 | Expr = expr;
82 | Stat = stat;
83 | }
84 | public override void Visit(Visitor v)
85 | {
86 | v.VisitCycleNode(this);
87 | }
88 | }
89 |
90 | public class BlockNode : StatementNode
91 | {
92 | public List StList = new List();
93 | public BlockNode(StatementNode stat)
94 | {
95 | Add(stat);
96 | }
97 | public void Add(StatementNode stat)
98 | {
99 | StList.Add(stat);
100 | }
101 | public override void Visit(Visitor v)
102 | {
103 | v.VisitBlockNode(this);
104 | }
105 | }
106 |
107 | public class WriteNode : StatementNode
108 | {
109 | public ExprNode Expr { get; set; }
110 | public WriteNode(ExprNode Expr)
111 | {
112 | this.Expr = Expr;
113 | }
114 | public override void Visit(Visitor v)
115 | {
116 | v.VisitWriteNode(this);
117 | }
118 | }
119 |
120 | public class EmptyNode : StatementNode
121 | {
122 | public override void Visit(Visitor v)
123 | {
124 | v.VisitEmptyNode(this);
125 | }
126 | }
127 |
128 | public class VarDefNode : StatementNode
129 | {
130 | public List vars = new List();
131 | public VarDefNode(IdNode id)
132 | {
133 | Add(id);
134 | }
135 |
136 | public void Add(IdNode id)
137 | {
138 | vars.Add(id);
139 | }
140 | public override void Visit(Visitor v)
141 | {
142 | v.VisitVarDefNode(this);
143 | }
144 | }
145 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### Как использовать этот репозиторий
2 |
3 | git clone --recurse-submodules <репозиторий>
4 |
5 | ### Как запустить тесты из репозитория
6 |
7 | [Инструкция](https://github.com/czen/MMCS_CS311/wiki/Как-запустить-тесты-из-репозитория)
8 |
9 | ### Учебная карта дисциплины
10 |
11 | [См. страничку в Moodle](http://edu.mmcs.sfedu.ru/course/view.php?id=194)
12 |
13 | ### Программа курса
14 |
15 | [Программа курса 2014-15](http://it.mmcs.sfedu.ru/docs/Miks/MPC/ProgrMPC2014-15.pdf)
16 |
17 | ### Страница курса на Moodle
18 |
19 | [Страница курса на Moodle](http://edu.mmcs.sfedu.ru/course/view.php?id=194)
20 |
21 | ### Авторы курса
22 |
23 | * Лекции, практические задания - С.С. Михалкович
24 | * дополнительные задания, подготовка и сопровождение материалов - А.П. Баглий
25 |
26 | #### Скан лекций
27 |
28 | [Скан лекций](http://it.mmcs.sfedu.ru/files?func=fileinfo&id=1937) (2008/09 уч. год)
29 |
30 | #### Лекции
31 |
32 | [Наброски к лекциям](../../wiki/Наброски_к_лекциям_"Методы_построения_компиляторов" "wikilink")
33 |
34 | #### Практические занятия
35 |
36 | Тема 1. [Синтаксические диаграммы автоматных языков и реализация распознавателей на их основе](../../wiki/Синтаксические_диаграммы_автоматных_языков_и_реализация_распознавателей_на_их_основе "wikilink")
37 |
38 | Тема 2. [ Создание ручного лексического анализатора простого языка программирования](../../wiki/Создание_лексического_анализатора_простого_языка_программирования "wikilink")
39 |
40 | Тема 3. [Создание лексического анализатора с помощью программы GPLex](../../wiki/Создание_лексического_анализатора_с_помощью_программы_GPLex "wikilink")
41 |
42 | Тема 4. [ Создание ручного синтаксического анализатора простого языка программирования](../../wiki/Создание_синтаксического_анализатора_простого_языка_программирования "wikilink")
43 |
44 | Тема 5. [Создание синтаксического анализатора с помощью программы GPPG](../../wiki/Создание_синтаксического_анализатора_с_помощью_программы_GPPG "wikilink")
45 |
46 | Тема 6. [Семантические действия при синтаксическом разборе. Построение синтаксического дерева программы](../../wiki/Семантические_действия_при_синтаксическом_разборе._Построение_синтаксического_дерева_программы "wikilink")
47 |
48 | Тема 7. [Визиторы по синтаксическому дереву](../../wiki/Визиторы_по_синтаксическому_дереву "wikilink")
49 |
50 | Тема 8. [Генерация и выполнение IL-кода](../../wiki/Генерация_и_выполнение_IL-кода "wikilink")
51 |
52 | #### Устаревшие темы
53 |
54 | Тема 1. [Конечные автоматы и реализация распознавателей на их основе](../../wiki/Конечные_автоматы_и_реализация_распознавателей_на_их_основе "wikilink")
55 |
56 | Тема 6. [Создание парсеров на основе GPLEX+GPPG](../../wiki/Создание_парсеров_на_основе_GPLEX+GPPG "wikilink")
57 |
58 | Тема 7. [Семантические действия в синтаксическом анализаторе. Построение дерева программы](../../wiki/Семантические_действия_в_синтаксическом_анализаторе._Построение_дерева_программы "wikilink")
59 |
60 | [Устаревшие вспомогательные материалы к теме Yacc-файл и его формат](../../wiki/Занятие_4_по_курсу_МПК "wikilink")
61 |
62 | [Устаревшие задания](http://pascalabc.net/wiki/index.php/GPLex_%2B_GPPG)
63 |
64 | [ Индивидуальное задание 3 на зачет 2011 г.](../../wiki/Задания_на_зачет_2011 "wikilink")
65 |
66 | Выполнить:
67 |
68 | 1. создав ручной компилятор с нисходящим разбором
69 | 2. создав компилятор с использованием GPLex+GPPG
70 |
71 | ------------------------------------------------------------------------
72 |
73 | #### Дополнительная информация
74 |
75 | [Рекомендуемая литература](http://it.mmcs.sfedu.ru/wiki/Рекомендуемая_литература#.D0.9C.D0.B5.D1.82.D0.BE.D0.B4.D1.8B_.D0.BF.D0.BE.D1.81.D1.82.D1.80.D0.BE.D0.B5.D0.BD.D0.B8.D1.8F_.D0.BA.D0.BE.D0.BC.D0.BF.D0.B8.D0.BB.D1.8F.D1.82.D0.BE.D1.80.D0.BE.D0.B2)
76 |
77 | #### Литература
78 |
79 | 1. А.Ахо, М.Лам, Р.Сети, Д.Ульман. Компиляторы. Принципы, технологии, инструменты. М, Вильямс, 2008
80 | 2. С.З.Свердлов. Языки программирования и методы трансляции. Питер, 2007
81 | 3. Э.А.Опалева, В.П.Самойленко. Языки программирования и методы трансляции. BHV, 2005
82 | 4. Ю.Г.Карпов. Основы построения трансляторов. BHV, 2005
83 | 5. [В.А.Серебряков, М.П.Галочкин «Основы конструирования компиляторов»](http://citforum.ru/programming/theory/serebryakov/)
84 | 6. [Книга “Языки и трансляции” Б. К. Мартыненко](http://www.math.spbu.ru/user/mbk/ЯЗЫКИ_И_ТРАНСЛЯЦИИ(изд.2)/Reference.htm)
85 |
86 |
--------------------------------------------------------------------------------
/.gitlab-ci.yml:
--------------------------------------------------------------------------------
1 | stages:
2 | - build
3 | - simplelexer
4 | - lexer
5 | - generatedlexer
6 | - descentparser
7 | - generatedparser
8 | - astparser
9 | - visitors
10 | - codegenerator
11 |
12 | build_all:
13 | stage: build
14 | image: czen/ubuntu_xbuild
15 | script:
16 | - ./prebuild.sh
17 | - ./build.sh
18 | tags:
19 | - docker
20 | #artifacts:
21 | # paths:
22 | # - ./NunitReportParser/bin/Debug/NunitReportParser.exe
23 | # - ./TestSimpleLexer/bin/Debug/TestSimpleLexer.dll
24 | # - ./TestLexer/bin/Debug/TestLexer.dll
25 | # - ./TestGeneratedLexer/bin/Debug/TestGeneratedLexer.dll
26 | # - ./TestDescentParser/bin/Debug/TestDescentParser.dll
27 | # - ./TestGeneratedParser/bin/Debug/TestGeneratedParser.dll
28 | # - ./TestASTParser/bin/Debug/TestASTParser.dll
29 | # - ./TestVisitors/bin/Debug/TestVisitors.dll
30 | # - ./TestCodeGenerator/bin/Debug/TestCodeGenerator.dll
31 | # expire_in: 1 week
32 |
33 |
34 | testsimplelexer:
35 | stage: simplelexer
36 | image: czen/ubuntu_xbuild
37 | script:
38 | - ./prebuild.sh
39 | - ./build.sh
40 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestSimpleLexer/bin/Debug/TestSimpleLexer.dll
41 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
42 | tags:
43 | - docker
44 |
45 | testlexer:
46 | stage: lexer
47 | image: czen/ubuntu_xbuild
48 | script:
49 | - ./prebuild.sh
50 | - ./build.sh
51 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestLexer/bin/Debug/TestLexer.dll
52 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
53 | tags:
54 | - docker
55 |
56 | testgeneratedlexer:
57 | stage: generatedlexer
58 | image: czen/ubuntu_xbuild
59 | script:
60 | - ./prebuild.sh
61 | - ./build.sh
62 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestGeneratedLexer/bin/Debug/TestGeneratedLexer.dll
63 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
64 | tags:
65 | - docker
66 |
67 | testdescentparser:
68 | stage: descentparser
69 | image: czen/ubuntu_xbuild
70 | script:
71 | - ./prebuild.sh
72 | - ./build.sh
73 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestDescentParser/bin/Debug/TestDescentParser.dll
74 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
75 | tags:
76 | - docker
77 |
78 | testgeneratedparser:
79 | stage: generatedparser
80 | image: czen/ubuntu_xbuild
81 | script:
82 | - ./prebuild.sh
83 | - ./build.sh
84 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestGeneratedParser/bin/Debug/TestGeneratedParser.dll
85 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
86 | tags:
87 | - docker
88 |
89 | testastparser:
90 | stage: astparser
91 | image: czen/ubuntu_xbuild
92 | script:
93 | - ./prebuild.sh
94 | - ./build.sh
95 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestASTParser/bin/Debug/TestASTParser.dll
96 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
97 | tags:
98 | - docker
99 |
100 | testvisitors:
101 | stage: visitors
102 | image: czen/ubuntu_xbuild
103 | script:
104 | - ./prebuild.sh
105 | - ./build.sh
106 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestVisitors/bin/Debug/TestVisitors.dll
107 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
108 | tags:
109 | - docker
110 |
111 | testcodegenerator:
112 | stage: codegenerator
113 | image: czen/ubuntu_xbuild
114 | script:
115 | - ./prebuild.sh
116 | - ./build.sh
117 | - mono packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe --labels=ON TestCodeGenerator/bin/Debug/TestCodeGenerator.dll
118 | - mono NunitReportParser/bin/Debug/NunitReportParser.exe ${CI_PROJECT_DIR} ${GITLAB_USER_LOGIN}
119 | tags:
120 | - docker
121 |
--------------------------------------------------------------------------------
/TestVisitors/TestVisitors.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {365C36ED-B8E4-428A-9AF4-A3142E06FE1E}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestVisitors
14 | TestVisitors
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
43 | True
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | {5f9f534d-dde0-4b4a-9bc2-2af8c9ed83fa}
57 | ParserVistors
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
67 |
68 |
69 |
70 |
71 |
78 |
--------------------------------------------------------------------------------
/Module6/ParserAST.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | x86
6 | 8.0.30703
7 | 2.0
8 | {9815F576-CAB5-4D52-9963-F9B8277E340C}
9 | Exe
10 | Properties
11 | SimpleLang
12 | SimpleLang
13 | v4.0
14 |
15 |
16 | 512
17 |
18 |
19 | x86
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | x86
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 | true
39 | bin\Debug\
40 | DEBUG;TRACE
41 | full
42 | AnyCPU
43 | prompt
44 | MinimumRecommendedRules.ruleset
45 |
46 |
47 | bin\Release\
48 | TRACE
49 | true
50 | pdbonly
51 | AnyCPU
52 | prompt
53 | MinimumRecommendedRules.ruleset
54 |
55 |
56 |
57 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
58 |
59 |
60 | ..\packages\Newtonsoft.Json.11.0.2\lib\net35\Newtonsoft.Json.dll
61 | True
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
96 |
--------------------------------------------------------------------------------
/TestCodeGenerator/TestCodeGenerator.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {186EE1C7-7F34-4428-8A82-F63C8D4368E8}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestCodeGenerator
14 | TestCodeGenerator
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
43 | True
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | {f8734914-3677-4a80-a87d-c274f52576fd}
57 | ParserGenerator
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
67 |
68 |
69 |
70 |
71 |
78 |
--------------------------------------------------------------------------------
/TestGeneratedParser/TestGeneratedParser.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {76382857-9D1F-4098-8376-48EF4A702445}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestGeneratedParser
14 | TestGeneratedParser
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
43 | True
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | {0ed50d29-f6c3-44f3-bf13-bc1a433f6119}
57 | GeneratedParser
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
67 |
68 |
69 |
70 |
71 |
78 |
--------------------------------------------------------------------------------
/TestGeneratedLexer/TestGeneratedLexer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {24413F87-3568-4BDF-ADC8-760086CEE37A}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestGeneratedLexer
14 | TestGeneratedLexer
15 | v4.0
16 | 512
17 | 6
18 |
19 |
20 |
21 |
22 |
23 | AnyCPU
24 | true
25 | full
26 | false
27 | bin\Debug\
28 | DEBUG;TRACE
29 | prompt
30 | 4
31 |
32 |
33 | AnyCPU
34 | pdbonly
35 | true
36 | bin\Release\
37 | TRACE
38 | prompt
39 | 4
40 |
41 |
42 |
43 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
44 | True
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | {4dd13462-dcb4-4c3e-b777-7fea90cea9d1}
58 | GeneratedLexer
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
68 |
69 |
70 |
71 |
72 |
79 |
--------------------------------------------------------------------------------
/Module8/ParserGenerator.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | x86
6 | 8.0.30703
7 | 2.0
8 | {F8734914-3677-4A80-A87D-C274F52576FD}
9 | Exe
10 | Properties
11 | SimpleLang
12 | SimpleLang
13 | v4.0
14 |
15 |
16 | 512
17 |
18 |
19 | x86
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | x86
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 | true
39 | bin\Debug\
40 | DEBUG;TRACE
41 | full
42 | AnyCPU
43 | prompt
44 | MinimumRecommendedRules.ruleset
45 |
46 |
47 | bin\Release\
48 | TRACE
49 | true
50 | pdbonly
51 | AnyCPU
52 | prompt
53 | MinimumRecommendedRules.ruleset
54 |
55 |
56 |
57 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
98 |
--------------------------------------------------------------------------------
/Module3/GeneratedLexer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | {4DD13462-DCB4-4C3E-B777-7FEA90CEA9D1}
7 | Exe
8 | false
9 |
10 |
11 |
12 |
13 | OnBuildSuccess
14 |
15 |
16 |
17 |
18 | 3.5
19 | true
20 | v4.0
21 | http://localhost/sss/
22 | true
23 | Web
24 | true
25 | Foreground
26 | 7
27 | Days
28 | false
29 | false
30 | true
31 | 0
32 | 1.0.0.%2a
33 | false
34 | true
35 | 5
36 |
37 |
38 |
39 | true
40 | full
41 | false
42 | .\bin\Debug\
43 | DEBUG;TRACE
44 |
45 |
46 | pdbonly
47 | true
48 | .\bin\Release\
49 | TRACE
50 |
51 |
52 |
53 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | False
69 | Клиентский профиль .NET Framework 3.5 с пакетом обновления 1 %28SP1%29
70 | false
71 |
72 |
73 | False
74 | .NET Framework 2.0 %28x86%29
75 | true
76 |
77 |
78 | False
79 | .NET Framework 3.0 %28x86%29
80 | false
81 |
82 |
83 | False
84 | .NET Framework 3.5
85 | false
86 |
87 |
88 | False
89 | .NET Framework 3.5 SP1
90 | false
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/TestLexer/TestLexer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {144BB4B2-AC18-4A38-9BEC-98BB22EB3382}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestLexer
14 | TestLexer
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
43 |
44 |
45 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
46 | True
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | {9715d879-f06e-4a65-ada0-a4df3619119d}
60 | Lexer
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
70 |
71 |
72 |
73 |
74 |
81 |
--------------------------------------------------------------------------------
/TestASTParser/TestASTParser.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {71D0BFF1-8F45-450E-A78F-153391124637}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestASTParser
14 | TestASTParser
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | ..\packages\Newtonsoft.Json.11.0.2\lib\net35\Newtonsoft.Json.dll
43 |
44 |
45 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
46 | True
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | {9815f576-cab5-4d52-9963-f9b8277e340c}
60 | ParserAST
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
70 |
71 |
72 |
73 |
74 |
81 |
--------------------------------------------------------------------------------
/TestSimpleLexer/TestSimpleLexer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {53767749-BCA6-4A3A-A4E6-D23519008305}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestSimpleLexer
14 | TestSimpleLexer
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
43 |
44 |
45 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
46 | True
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | {28c0284b-2f43-45d6-a77f-ab08f919717d}
60 | SimpleLexer
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
70 |
71 |
72 |
73 |
74 |
81 |
--------------------------------------------------------------------------------
/TestDescentParser/TestDescentParser.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Debug
8 | AnyCPU
9 | {F6EABC41-B147-44EB-B6EF-13C3183C9961}
10 | {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
11 | Library
12 | Properties
13 | TestDescentParser
14 | TestDescentParser
15 | v4.0
16 | 512
17 |
18 |
19 |
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | ..\packages\NUnit.3.12.0\lib\net40\nunit.framework.dll
43 | True
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | {28c0284b-2f43-45d6-a77f-ab08f919717d}
57 | SimpleLexer
58 |
59 |
60 | {837bc9fe-daa9-416e-bcce-0235e5c38d4b}
61 | RecursiveDescentParser
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.
71 |
72 |
73 |
74 |
75 |
82 |
--------------------------------------------------------------------------------
/.theia/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | // See https://go.microsoft.com/fwlink/?LinkId=733558
3 | // for the documentation about the tasks.json format
4 | "version": "2.0.0",
5 | "tasks": [
6 | {
7 | "label": "build",
8 | "type": "shell",
9 | "command": "xbuild",
10 | "args": [
11 | // Ask msbuild to generate full paths for file names.
12 | //"/property:GenerateFullPaths=true",
13 | //"/t:build",
14 | // Do not generate summary otherwise it leads to duplicate errors in Problems panel
15 | //"/consoleloggerparameters:NoSummary",
16 | "/p:TargetFrameworkVersion=\"v4.0\""
17 | ],
18 | "group": "build",
19 | "presentation": {
20 | // Reveal the output only if unrecognized errors occur.
21 | "reveal": "silent"
22 | },
23 | // Use the standard MS compiler pattern to detect errors, warnings and infos
24 | "problemMatcher": "$msCompile"
25 | },
26 | {
27 | "label": "test lexer",
28 | "type": "shell",
29 | "command": "mono",
30 | "args": [
31 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
32 | " --labels=All",
33 | "TestLexer/bin/Debug/TestLexer.dll"
34 | ],
35 | "group": "test",
36 | // Use the standard MS compiler pattern to detect errors, warnings and infos
37 | "problemMatcher": "$msCompile"
38 | },
39 | {
40 | "label": "test simple lexer",
41 | "type": "shell",
42 | "command": "mono",
43 | "args": [
44 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
45 | " --labels=All",
46 | "TestSimpleLexer/bin/Debug/TestSimpleLexer.dll"
47 | ],
48 | "group": "test",
49 | // Use the standard MS compiler pattern to detect errors, warnings and infos
50 | "problemMatcher": "$msCompile"
51 | },
52 | {
53 | "label": "test generated lexer",
54 | "type": "shell",
55 | "command": "mono",
56 | "args": [
57 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
58 | " --labels=All",
59 | "TestGeneratedLexer/bin/Debug/TestGeneratedLexer.dll"
60 | ],
61 | "group": "test",
62 | // Use the standard MS compiler pattern to detect errors, warnings and infos
63 | "problemMatcher": "$msCompile"
64 | },
65 | {
66 | "label": "test descent parser",
67 | "type": "shell",
68 | "command": "mono",
69 | "args": [
70 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
71 | " --labels=All",
72 | "TestDescentParser/bin/Debug/TestDescentParser.dll"
73 | ],
74 | "group": "test",
75 | // Use the standard MS compiler pattern to detect errors, warnings and infos
76 | "problemMatcher": "$msCompile"
77 | },
78 | {
79 | "label": "test generated parser",
80 | "type": "shell",
81 | "command": "mono",
82 | "args": [
83 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
84 | " --labels=All",
85 | "TestGeneratedParser/bin/Debug/TestGeneratedParser.dll"
86 | ],
87 | "group": "test",
88 | // Use the standard MS compiler pattern to detect errors, warnings and infos
89 | "problemMatcher": "$msCompile"
90 | },
91 | {
92 | "label": "test ast parser",
93 | "type": "shell",
94 | "command": "mono",
95 | "args": [
96 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
97 | " --labels=All",
98 | "TestASTParser/bin/Debug/TestASTParser.dll"
99 | ],
100 | "group": "test",
101 | // Use the standard MS compiler pattern to detect errors, warnings and infos
102 | "problemMatcher": "$msCompile"
103 | },
104 | {
105 | "label": "test visitors",
106 | "type": "shell",
107 | "command": "mono",
108 | "args": [
109 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
110 | " --labels=All",
111 | "TestVisitors/bin/Debug/TestVisitors.dll"
112 | ],
113 | "group": "test",
114 | // Use the standard MS compiler pattern to detect errors, warnings and infos
115 | "problemMatcher": "$msCompile"
116 | },
117 | {
118 | "label": "test code generator",
119 | "type": "shell",
120 | "command": "mono",
121 | "args": [
122 | "packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe",
123 | " --labels=All",
124 | "TestCodeGenerator/bin/Debug/TestCodeGenerator.dll"
125 | ],
126 | "group": "test",
127 | // Use the standard MS compiler pattern to detect errors, warnings and infos
128 | "problemMatcher": "$msCompile"
129 | }
130 | ]
131 | }
--------------------------------------------------------------------------------
/Module8/ProgramTree.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using SimpleLang.Visitors;
3 |
4 | namespace ProgramTree
5 | {
6 | public enum AssignType { Assign, AssignPlus, AssignMinus, AssignMult, AssignDivide };
7 |
8 | public abstract class Node // базовый класс для всех узлов
9 | {
10 | public abstract void Visit(Visitor v);
11 | }
12 |
13 | public abstract class ExprNode : Node // базовый класс для всех выражений
14 | {
15 | }
16 |
17 | public class IdNode : ExprNode
18 | {
19 | public string Name { get; set; }
20 | public IdNode(string name) { Name = name; }
21 | public override void Visit(Visitor v)
22 | {
23 | v.VisitIdNode(this);
24 | }
25 | }
26 |
27 | public class IntNumNode : ExprNode
28 | {
29 | public int Num { get; set; }
30 | public IntNumNode(int num) { Num = num; }
31 | public override void Visit(Visitor v)
32 | {
33 | v.VisitIntNumNode(this);
34 | }
35 | }
36 |
37 | public class BinOpNode : ExprNode
38 | {
39 | public ExprNode Left { get; set; }
40 | public ExprNode Right { get; set; }
41 | public char Op { get; set; }
42 | public BinOpNode(ExprNode Left, ExprNode Right, char op)
43 | {
44 | this.Left = Left;
45 | this.Right = Right;
46 | this.Op = op;
47 | }
48 | public override void Visit(Visitor v)
49 | {
50 | v.VisitBinOpNode(this);
51 | }
52 | }
53 |
54 | public abstract class StatementNode : Node // базовый класс для всех операторов
55 | {
56 | }
57 |
58 | public class AssignNode : StatementNode
59 | {
60 | public IdNode Id { get; set; }
61 | public ExprNode Expr { get; set; }
62 | public AssignType AssOp { get; set; }
63 | public AssignNode(IdNode id, ExprNode expr, AssignType assop = AssignType.Assign)
64 | {
65 | Id = id;
66 | Expr = expr;
67 | AssOp = assop;
68 | }
69 | public override void Visit(Visitor v)
70 | {
71 | v.VisitAssignNode(this);
72 | }
73 | }
74 |
75 | public class CycleNode : StatementNode
76 | {
77 | public ExprNode Expr { get; set; }
78 | public StatementNode Stat { get; set; }
79 | public CycleNode(ExprNode expr, StatementNode stat)
80 | {
81 | Expr = expr;
82 | Stat = stat;
83 | }
84 | public override void Visit(Visitor v)
85 | {
86 | v.VisitCycleNode(this);
87 | }
88 | }
89 |
90 | public class BlockNode : StatementNode
91 | {
92 | public List StList = new List();
93 | public BlockNode(StatementNode stat)
94 | {
95 | Add(stat);
96 | }
97 | public void Add(StatementNode stat)
98 | {
99 | StList.Add(stat);
100 | }
101 | public override void Visit(Visitor v)
102 | {
103 | v.VisitBlockNode(this);
104 | }
105 | }
106 |
107 | public class WriteNode : StatementNode
108 | {
109 | public ExprNode Expr { get; set; }
110 | public WriteNode(ExprNode Expr)
111 | {
112 | this.Expr = Expr;
113 | }
114 | public override void Visit(Visitor v)
115 | {
116 | v.VisitWriteNode(this);
117 | }
118 | }
119 |
120 | public class EmptyNode : StatementNode
121 | {
122 | public override void Visit(Visitor v)
123 | {
124 | v.VisitEmptyNode(this);
125 | }
126 | }
127 |
128 | public class VarDefNode : StatementNode
129 | {
130 | public List vars = new List();
131 | public VarDefNode(IdNode id)
132 | {
133 | Add(id);
134 | }
135 |
136 | public void Add(IdNode id)
137 | {
138 | vars.Add(id);
139 | }
140 | public override void Visit(Visitor v)
141 | {
142 | v.VisitVarDefNode(this);
143 | }
144 | }
145 |
146 | public class IfNode : StatementNode
147 | {
148 | public ExprNode expr;
149 | public StatementNode ifTrue, ifFalse;
150 |
151 | public IfNode(ExprNode expr, StatementNode ifTrue, StatementNode ifFalse = null)
152 | {
153 | this.expr = expr;
154 | this.ifTrue = ifTrue;
155 | this.ifFalse = ifFalse;
156 | }
157 |
158 | public override void Visit(Visitor v)
159 | {
160 | v.VisitIfNode(this);
161 | }
162 | }
163 | }
--------------------------------------------------------------------------------
/Module7/ParserVistors.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | x86
6 | 8.0.30703
7 | 2.0
8 | {5F9F534D-DDE0-4B4A-9BC2-2AF8C9ED83FA}
9 | Exe
10 | Properties
11 | SimpleLang
12 | SimpleLang
13 | v4.0
14 |
15 |
16 | 512
17 |
18 |
19 | x86
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | x86
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 | true
39 | bin\Debug\
40 | DEBUG;TRACE
41 | full
42 | AnyCPU
43 | prompt
44 | MinimumRecommendedRules.ruleset
45 |
46 |
47 | bin\Release\
48 | TRACE
49 | true
50 | pdbonly
51 | AnyCPU
52 | prompt
53 | MinimumRecommendedRules.ruleset
54 |
55 |
56 |
57 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.dll
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
101 |
--------------------------------------------------------------------------------
/TestDescentParser/Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NUnit.Framework;
3 | using SimpleLexer;
4 | using SimpleLangParser;
5 | using System.IO;
6 |
7 | namespace TestDescentParser
8 | {
9 | [TestFixture]
10 | public class DescentParserTests
11 | {
12 | private bool Parse(string text)
13 | {
14 | TextReader inputReader = new StringReader(text);
15 | Lexer l = new Lexer(inputReader);
16 | Parser p = new Parser(l);
17 | p.Progr();
18 | if (l.LexKind == Tok.EOF)
19 | {
20 | return true;
21 | }
22 | else
23 | {
24 | return false;
25 | }
26 | }
27 |
28 | [Test]
29 | public void TestWhile()
30 | {
31 | Assert.IsTrue(Parse(@"begin while 5 do a:=2 end"));
32 |
33 | Assert.IsTrue(Parse(@"begin
34 | while 5 do
35 | begin
36 | a:=2
37 | end
38 | end"));
39 |
40 | Assert.IsTrue(Parse(@"begin
41 | while 5 do
42 | begin
43 | while 6 do
44 | a:=2;
45 | while 7 do
46 | begin
47 | a:=3;
48 | c:=4
49 | end
50 | end
51 | end"));
52 |
53 | }
54 |
55 | [Test]
56 | public void TestFor()
57 | {
58 | Assert.IsTrue(Parse(@"begin
59 | for a:=1 to 5 do
60 | begin
61 | b:=1
62 | end
63 | end"));
64 |
65 | Assert.IsTrue(Parse(@"begin
66 | for a:=1 to 5 do
67 | begin
68 | for i:=1 to 6 do
69 | c:=1;
70 | b:=1
71 | end
72 | end"));
73 |
74 | }
75 |
76 | [Test]
77 | public void TestIf()
78 | {
79 | Assert.IsTrue(Parse(@"begin
80 | if 2 then
81 | a:=2
82 | else
83 | b:=2;
84 |
85 | if 3 then
86 | if c then
87 | c:=4
88 | else
89 | m:=1
90 | else
91 | v:=8;
92 |
93 | if 4 then
94 | if 4 then
95 | if 6 then
96 | m:=0
97 | end"));
98 |
99 | }
100 |
101 | [Test]
102 | public void TestExpr()
103 | {
104 | Assert.IsTrue(Parse(@"begin
105 | if 2+2*(c-d/3) then
106 | begin
107 | a:=2;
108 | while 2-3+f do c:=c*2
109 | end
110 | else
111 | b:=2-3*(c-d/f*3);
112 |
113 | for i:=2-3*(s-d) to (c-3) do
114 | a:=(a-(3-3));
115 |
116 | if 3 then
117 | if (c-3) then
118 | c:=4+2
119 | else
120 | m:=1
121 | else
122 | v:=(8+2)
123 | end"));
124 |
125 | }
126 | }
127 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | [Xx]64/
19 | [Xx]86/
20 | [Bb]uild/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 |
85 | # Visual Studio profiler
86 | *.psess
87 | *.vsp
88 | *.vspx
89 | *.sap
90 |
91 | # TFS 2012 Local Workspace
92 | $tf/
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 | *.DotSettings.user
101 |
102 | # JustCode is a .NET coding add-in
103 | .JustCode
104 |
105 | # TeamCity is a build add-in
106 | _TeamCity*
107 |
108 | # DotCover is a Code Coverage Tool
109 | *.dotCover
110 |
111 | # NCrunch
112 | _NCrunch_*
113 | .*crunch*.local.xml
114 | nCrunchTemp_*
115 |
116 | # MightyMoose
117 | *.mm.*
118 | AutoTest.Net/
119 |
120 | # Web workbench (sass)
121 | .sass-cache/
122 |
123 | # Installshield output folder
124 | [Ee]xpress/
125 |
126 | # DocProject is a documentation generator add-in
127 | DocProject/buildhelp/
128 | DocProject/Help/*.HxT
129 | DocProject/Help/*.HxC
130 | DocProject/Help/*.hhc
131 | DocProject/Help/*.hhk
132 | DocProject/Help/*.hhp
133 | DocProject/Help/Html2
134 | DocProject/Help/html
135 |
136 | # Click-Once directory
137 | publish/
138 |
139 | # Publish Web Output
140 | *.[Pp]ublish.xml
141 | *.azurePubxml
142 |
143 | # TODO: Un-comment the next line if you do not want to checkin
144 | # your web deploy settings because they may include unencrypted
145 | # passwords
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # NuGet Packages
150 | *.nupkg
151 | # The packages folder can be ignored because of Package Restore
152 | **/packages/*
153 | # except build/, which is used as an MSBuild target.
154 | !**/packages/build/
155 | # Uncomment if necessary however generally it will be regenerated when needed
156 | #!**/packages/repositories.config
157 | # NuGet v3's project.json files produces more ignoreable files
158 | *.nuget.props
159 | *.nuget.targets
160 |
161 | # Microsoft Azure Build Output
162 | csx/
163 | *.build.csdef
164 |
165 | # Microsoft Azure Emulator
166 | ecf/
167 | rcf/
168 |
169 | # Microsoft Azure ApplicationInsights config file
170 | ApplicationInsights.config
171 |
172 | # Windows Store app package directory
173 | AppPackages/
174 | BundleArtifacts/
175 |
176 | # Visual Studio cache files
177 | # files ending in .cache can be ignored
178 | *.[Cc]ache
179 | # but keep track of directories ending in .cache
180 | !*.[Cc]ache/
181 |
182 | # Others
183 | ClientBin/
184 | [Ss]tyle[Cc]op.*
185 | ~$*
186 | *~
187 | *.dbmdl
188 | *.dbproj.schemaview
189 | *.pfx
190 | *.publishsettings
191 | node_modules/
192 | orleans.codegen.cs
193 |
194 | # RIA/Silverlight projects
195 | Generated_Code/
196 |
197 | # Backup & report files from converting an old project file
198 | # to a newer Visual Studio version. Backup files are not needed,
199 | # because we have git ;-)
200 | _UpgradeReport_Files/
201 | Backup*/
202 | UpgradeLog*.XML
203 | UpgradeLog*.htm
204 |
205 | # SQL Server files
206 | *.mdf
207 | *.ldf
208 |
209 | # Business Intelligence projects
210 | *.rdl.data
211 | *.bim.layout
212 | *.bim_*.settings
213 |
214 | # Microsoft Fakes
215 | FakesAssemblies/
216 |
217 | # GhostDoc plugin setting file
218 | *.GhostDoc.xml
219 |
220 | # Node.js Tools for Visual Studio
221 | .ntvs_analysis.dat
222 |
223 | # Visual Studio 6 build log
224 | *.plg
225 |
226 | # Visual Studio 6 workspace options file
227 | *.opt
228 |
229 | # Visual Studio LightSwitch build output
230 | **/*.HTMLClient/GeneratedArtifacts
231 | **/*.DesktopClient/GeneratedArtifacts
232 | **/*.DesktopClient/ModelManifest.xml
233 | **/*.Server/GeneratedArtifacts
234 | **/*.Server/ModelManifest.xml
235 | _Pvt_Extensions
236 |
237 | # LightSwitch generated files
238 | GeneratedArtifacts/
239 | ModelManifest.xml
240 |
241 | # Paket dependency manager
242 | .paket/paket.exe
243 |
244 | # FAKE - F# Make
245 | .fake/
246 |
247 | #JetBrains ide files
248 | .idea
--------------------------------------------------------------------------------