diff --git a/Module7/Gplex.exe b/Module7/Gplex.exe new file mode 100644 index 0000000000000000000000000000000000000000..51a522e221f5ca52cc934933e08745f1653a98b5 Binary files /dev/null and b/Module7/Gplex.exe differ diff --git a/Module7/Gppg.exe b/Module7/Gppg.exe new file mode 100644 index 0000000000000000000000000000000000000000..edca401986741541f14b7d4bd89adc57802327a2 Binary files /dev/null and b/Module7/Gppg.exe differ diff --git a/Module7/ProgramTree.cs b/Module7/ProgramTree.cs index e48dcb56fcb811d4b2e7f37bbf71e935306aedc6..1fd81289f22c3d1948399adebfe65fe1fc080319 100644 --- a/Module7/ProgramTree.cs +++ b/Module7/ProgramTree.cs @@ -142,4 +142,23 @@ namespace ProgramTree v.VisitVarDefNode(this); } } + + public class IfNode : StatementNode + { + public ExprNode Expr { get; set; } + public StatementNode ThenStat { get; set; } + public StatementNode ElseStat { get; set; } + public IfNode(ExprNode expr, StatementNode then_stat, StatementNode else_stat = null) + { + Expr = expr; + ThenStat = then_stat; + ElseStat = else_stat; + } + + public override void Visit(Visitor v) + { + v.VisitIfNode(this); + } + } + } \ No newline at end of file diff --git a/Module7/SimpleLex.cs b/Module7/SimpleLex.cs index 98388ef125489f1e1cc850a1341825c4971cf640..cc772d5a971c79603413736f0fcf87f7cbb9a240 100644 --- a/Module7/SimpleLex.cs +++ b/Module7/SimpleLex.cs @@ -1,14 +1,10 @@ // // This CSharp output file generated by Gardens Point LEX -// Gardens Point LEX (GPLEX) is Copyright (c) John Gough, QUT 2006-2014. -// Output produced by GPLEX is the property of the user. -// See accompanying file GPLEXcopyright.rtf. -// -// GPLEX Version: 1.2.2 -// Machine: MAINHOMEPC2 -// DateTime: 30.09.2018 18:17:27 -// UserName: someone -// GPLEX input file <SimpleLex.lex - 24.09.2018 23:47:03> +// Version: 1.1.3.301 +// Machine: DESKTOP-H0VRSS3 +// DateTime: 06.11.2022 21:58:12 +// UserName: nikit +// GPLEX input file <SimpleLex.lex> // GPLEX frame file <embedded resource> // // Option settings: unicode, parser, minimize @@ -17,8 +13,8 @@ // // -// Revised backup code -// Version 1.2.1 of 24-June-2013 +// Experimental embedded frame +// Version 1.1.3 of 18-April-2010 // // #define BACKUP @@ -305,7 +301,8 @@ int NextState() { public Scanner(Stream file, string codepage) { SetSource(file, CodePageHandling.GetCodePage(codepage)); - } + } + #endif // !NOFILES public Scanner() { } @@ -333,7 +330,7 @@ int NextState() { if (next < 0xDC00 || next > 0xDFFF) code = ScanBuff.UnicodeReplacementChar; else - code = (0x10000 + ((code & 0x3FF) << 10) + (next & 0x3FF)); + code = (0x10000 + (code & 0x3FF << 10) + (next & 0x3FF)); } #endif cCol++; @@ -386,7 +383,9 @@ int NextState() { GetCode(); } +#if !NOFILES // ================ LineBuffer Initialization =================== + /// <summary> /// Create and initialize a LineBuff buffer object for this scanner /// </summary> @@ -400,7 +399,6 @@ int NextState() { GetCode(); } -#if !NOFILES // =============== StreamBuffer Initialization ================== /// <summary> @@ -502,12 +500,6 @@ int NextState() { } } - /// <summary> - /// Discards all but the first "n" codepoints in the recognized pattern. - /// Resets the buffer position so that only n codepoints have been consumed; - /// yytext is also re-evaluated. - /// </summary> - /// <param name="n">The number of codepoints to consume</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] void yyless(int n) { @@ -527,10 +519,6 @@ int NextState() { // but it does not seem possible to re-establish // the correct column counts except by going forward. // - /// <summary> - /// Removes the last "n" code points from the pattern. - /// </summary> - /// <param name="n">The number to remove</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] void _yytrunc(int n) { yyless(yyleng - n); } @@ -543,23 +531,18 @@ int NextState() { // can't use (tokEPos - tokPos) because of the // possibility of surrogate pairs in the token. // - /// <summary> - /// The length of the pattern in codepoints (not the same as - /// string-length if the pattern contains any surrogate pairs). - /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "yyleng")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "yyleng")] public int yyleng { get { +#if BYTEMODE + return tokEPos - tokPos; +#else if (tokELin == tokLin) return tokECol - tokCol; - else -#if BYTEMODE - return tokEPos - tokPos; -#else - { + else { int ch; int count = 0; int save = buffer.Pos; @@ -568,7 +551,7 @@ int NextState() { ch = buffer.Read(); if (!char.IsHighSurrogate((char)ch)) count++; } while (buffer.Pos < tokEPos && ch != ScanBuff.EndOfFile); - buffer.Pos = save; + buffer.Pos = save; return count; } #endif // BYTEMODE @@ -593,56 +576,65 @@ int NextState() { // ============== The main tokenizer code ================= - int Scan() { + int Scan() + { try { - for (; ; ) { - int next; // next state to enter + for (; ; ) + { + int next; // next state to enter +#if BACKUP + Result rslt = Result.noMatch; +#endif // BACKUP #if LEFTANCHORS - for (;;) { + for (;;) + { // Discard characters that do not start any pattern. // Must check the left anchor condition after *every* GetCode! state = ((cCol == 0) ? anchorState[currentScOrd] : currentStart); - if ((next = NextState()) != goStart) break; // LOOP EXIT HERE... + if ((next = NextState()) != goStart) + break; // LOOP EXIT HERE... GetCode(); } #else // !LEFTANCHORS state = currentStart; - while ((next = NextState()) == goStart) { + while ((next = NextState()) == goStart) // At this point, the current character has no // transition from the current state. We discard // the "no-match" char. In traditional LEX such // characters are echoed to the console. GetCode(); - } #endif // LEFTANCHORS // At last, a valid transition ... MarkToken(); state = next; - GetCode(); + GetCode(); + + while ((next = NextState()) > eofNum) // Exit for goStart AND for eofNum #if BACKUP - bool contextSaved = false; - while ((next = NextState()) > eofNum) { // Exit for goStart AND for eofNum - if (state <= maxAccept && next > maxAccept) { // need to prepare backup data - // Store data for the *latest* accept state that was found. - SaveStateAndPos( ref ctx ); - contextSaved = true; + if (state <= maxAccept && next > maxAccept) // need to prepare backup data + { + // ctx is an object. The fields may be + // mutated by the call to Recurse2. + // On return the data in ctx is the + // *latest* accept state that was found. + + rslt = Recurse2(ref ctx, next); + if (rslt == Result.noMatch) + RestoreStateAndPos(ref ctx); + break; } - state = next; - GetCode(); - } - if (state > maxAccept && contextSaved) - RestoreStateAndPos( ref ctx ); -#else // BACKUP - while ((next = NextState()) > eofNum) { // Exit for goStart AND for eofNum - state = next; - GetCode(); - } + else #endif // BACKUP - if (state <= maxAccept) { + { + state = next; + GetCode(); + } + if (state <= maxAccept) + { MarkEnd(); #region ActionSwitch -#pragma warning disable 162, 1522 +#pragma warning disable 162 switch (state) { case eofNum: @@ -706,7 +698,7 @@ yylval.dVal = double.Parse(yytext); default: break; } -#pragma warning restore 162, 1522 +#pragma warning restore 162 #endregion } } @@ -719,7 +711,29 @@ yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol); } #if BACKUP - void SaveStateAndPos(ref Context ctx) { + Result Recurse2(ref Context ctx, int next) + { + // Assert: at entry "state" is an accept state AND + // NextState(state, code) != goStart AND + // NextState(state, code) is not an accept state. + // + SaveStateAndPos(ref ctx); + state = next; + GetCode(); + + while ((next = NextState()) > eofNum) + { + if (state <= maxAccept && next > maxAccept) // need to update backup data + SaveStateAndPos(ref ctx); + state = next; + if (state == eofNum) return Result.accept; + GetCode(); + } + return (state <= maxAccept ? Result.accept : Result.noMatch); + } + + void SaveStateAndPos(ref Context ctx) + { ctx.bPos = buffer.Pos; ctx.rPos = readPos; ctx.cCol = cCol; @@ -728,7 +742,8 @@ yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol); ctx.cChr = code; } - void RestoreStateAndPos(ref Context ctx) { + void RestoreStateAndPos(ref Context ctx) + { buffer.Pos = ctx.bPos; readPos = ctx.rPos; cCol = ctx.cCol; @@ -736,7 +751,8 @@ yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol); state = ctx.state; code = ctx.cChr; } -#endif // BACKUP + +#endif // BACKUP // ============= End of the tokenizer code ================ @@ -768,16 +784,16 @@ yylloc = new LexLocation(tokLin, tokCol, tokELin, tokECol); #region UserCodeSection -public override void yyerror(string format, params object[] args) // îáðà áîòêà ñèГГІГ ГЄГ±ГЁГ·ГҐГ±ГЄГЁГµ îøèáîê +public override void yyerror(string format, params object[] args) // обработка синтаксических ошибок { var ww = args.Skip(1).Cast<string>().ToArray(); - string errorMsg = string.Format("({0},{1}): Âñòðå÷åГГ® {2}, à îæèäà ëîñü {3}", yyline, yycol, args[0], string.Join(" èëè ", ww)); + string errorMsg = string.Format("({0},{1}): Встречено {2}, а ожидалось {3}", yyline, yycol, args[0], string.Join(" или ", ww)); throw new SyntaxException(errorMsg); } public void LexError() { - string errorMsg = string.Format("({0},{1}): ÍåèçâåñòГûé ñèìâîë {2}", yyline, yycol, yytext); + string errorMsg = string.Format("({0},{1}): Неизвестный символ {2}", yyline, yycol, yytext); throw new LexException(errorMsg); } @@ -793,6 +809,9 @@ class ScannerHelper keywords.Add("cycle",(int)Tokens.CYCLE); keywords.Add("write",(int)Tokens.WRITE); keywords.Add("var",(int)Tokens.VAR); + keywords.Add("if",(int)Tokens.IF); + keywords.Add("then",(int)Tokens.THEN); + keywords.Add("else",(int)Tokens.ELSE); } public static int GetIDToken(string s) { @@ -853,7 +872,6 @@ class ScannerHelper return new LineBuffer(source); } -#if (!NOFILES) public static ScanBuff GetBuffer(Stream source) { return new BuildBuffer(source); @@ -864,8 +882,7 @@ class ScannerHelper { return new BuildBuffer(source, fallbackCodePage); } -#endif // !BYTEMODE -#endif // !NOFILES +#endif } #region Buffer classes @@ -988,7 +1005,7 @@ class ScannerHelper { ix = lstart = 0; } - while (ix < numLines) + for (; ; ) { int len = line[ix].Length + 1; if (pos < lstart + len) break; @@ -1046,8 +1063,7 @@ class ScannerHelper { cPos = value; findIndex(cPos, out cLine, out curLineStart); - // cLine should be the *next* line after curLine. - curLine = (cLine < numLines ? line[cLine++] : ""); + curLine = line[cLine]; curLineEnd = curLineStart + curLine.Length; } } @@ -1055,7 +1071,7 @@ class ScannerHelper public override string ToString() { return "LineBuffer"; } } -#if (!NOFILES) + // ============================================================== // ===== class BuildBuff : for unicode text files ======== // ============================================================== @@ -1296,13 +1312,12 @@ class ScannerHelper } #endif // !BYTEMODE } -#endif // !NOFILES #endregion Buffer classes // ============================================================== // ============ class CodePageHandling ============= // ============================================================== -#if (!NOFILES) + public static class CodePageHandling { public static int GetCodePage(string option) @@ -1513,7 +1528,6 @@ class ScannerHelper #endif // !BYTEMODE #endregion -#endif // !NOFILES // End of code copied from embedded resource diff --git a/Module7/SimpleLex.lex b/Module7/SimpleLex.lex index 00dfa1249dd0572b3061e40d49d86058b4e1baee..4a392d9d7f03f0cf6ee15a9bf02ecc06f2c9129c 100644 --- a/Module7/SimpleLex.lex +++ b/Module7/SimpleLex.lex @@ -78,6 +78,9 @@ class ScannerHelper keywords.Add("cycle",(int)Tokens.CYCLE); keywords.Add("write",(int)Tokens.WRITE); keywords.Add("var",(int)Tokens.VAR); + keywords.Add("if",(int)Tokens.IF); + keywords.Add("then",(int)Tokens.THEN); + keywords.Add("else",(int)Tokens.ELSE); } public static int GetIDToken(string s) { diff --git a/Module7/SimpleYacc.cs b/Module7/SimpleYacc.cs index e0ec2ad6ff794b912c8c7509d7cc14a3103253c0..da799da84ca1050013f01459f6f8c97d18f8f132 100644 --- a/Module7/SimpleYacc.cs +++ b/Module7/SimpleYacc.cs @@ -1,18 +1,17 @@ // This code was generated by the Gardens Point Parser Generator -// Copyright (c) Wayne Kelly, John Gough, QUT 2005-2014 +// Copyright (c) Wayne Kelly, QUT 2005-2010 // (see accompanying GPPGcopyright.rtf) -// GPPG version 1.5.2 -// Machine: MAINHOMEPC2 -// DateTime: 30.09.2018 18:17:29 -// UserName: someone -// Input file <SimpleYacc.y - 24.09.2018 23:47:03> +// GPPG version 1.3.6 +// Machine: DESKTOP-H0VRSS3 +// DateTime: 06.11.2022 21:58:12 +// UserName: nikit +// Input file <SimpleYacc.y> // options: no-lines gplex using System; using System.Collections.Generic; -using System.CodeDom.Compiler; using System.Globalization; using System.Text; using QUT.Gppg; @@ -21,10 +20,12 @@ using ProgramTree; namespace SimpleParser { -public enum Tokens {error=2,EOF=3,BEGIN=4,END=5,CYCLE=6, - ASSIGN=7,ASSIGNPLUS=8,ASSIGNMINUS=9,ASSIGNMULT=10,SEMICOLON=11,WRITE=12, - VAR=13,PLUS=14,MINUS=15,MULT=16,DIV=17,LPAREN=18, - RPAREN=19,COLUMN=20,INUM=21,RNUM=22,ID=23}; +public enum Tokens { + error=1,EOF=2,BEGIN=3,END=4,CYCLE=5,ASSIGN=6, + ASSIGNPLUS=7,ASSIGNMINUS=8,ASSIGNMULT=9,SEMICOLON=10,WRITE=11,VAR=12, + PLUS=13,MINUS=14,MULT=15,DIV=16,LPAREN=17,RPAREN=18, + COLUMN=19,IF=20,THEN=21,ELSE=22,INUM=23,RNUM=24, + ID=25}; public struct ValueType { @@ -37,124 +38,120 @@ public struct ValueType public BlockNode blVal; } // Abstract base class for GPLEX scanners -[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")] public abstract class ScanBase : AbstractScanner<ValueType,LexLocation> { private LexLocation __yylloc = new LexLocation(); public override LexLocation yylloc { get { return __yylloc; } set { __yylloc = value; } } protected virtual bool yywrap() { return true; } } -// Utility class for encapsulating token information -[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")] -public class ScanObj { - public int token; - public ValueType yylval; - public LexLocation yylloc; - public ScanObj( int t, ValueType val, LexLocation loc ) { - this.token = t; this.yylval = val; this.yylloc = loc; - } -} - -[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")] public class Parser: ShiftReduceParser<ValueType, LexLocation> { - // Verbatim content from SimpleYacc.y - 24.09.2018 23:47:03 -// ГќГІГЁ îáúÿâëåГГЁГї äîáà âëÿþòñÿ Гў êëà ññ GPPGParser, ïðåäñòà âëÿþùèé ñîáîé ïà ðñåð, ГЈГҐГåðèðóåìûé ñèñòåìîé gppg - public BlockNode root; // ÊîðГåâîé óçåë Г±ГЁГòà êñè÷åñêîãî äåðåâà + // Verbatim content from SimpleYacc.y +// Эти объявления добавляются в класс GPPGParser, представляющий собой парсер, генерируемый системой gppg + public BlockNode root; // Корневой узел синтаксического дерева public Parser(AbstractScanner<ValueType, LexLocation> scanner) : base(scanner) { } private bool InDefSect = false; - // End verbatim content from SimpleYacc.y - 24.09.2018 23:47:03 + // End verbatim content from SimpleYacc.y #pragma warning disable 649 - private static Dictionary<int, string> aliases; + private static Dictionary<int, string> aliasses; #pragma warning restore 649 - private static Rule[] rules = new Rule[30]; - private static State[] states = new State[48]; + private static Rule[] rules = new Rule[33]; + private static State[] states = new State[55]; private static string[] nonTerms = new string[] { "progr", "expr", "ident", "T", "F", "statement", "assign", "block", "cycle", - "write", "empty", "var", "varlist", "stlist", "$accept", "Anon@1", }; + "write", "empty", "var", "varlist", "if", "stlist", "$accept", "Anon@1", + }; static Parser() { - states[0] = new State(new int[]{4,4},new int[]{-1,1,-8,3}); - states[1] = new State(new int[]{3,2}); + states[0] = new State(new int[]{3,4},new int[]{-1,1,-8,3}); + states[1] = new State(new int[]{2,2}); states[2] = new State(-1); states[3] = new State(-2); - states[4] = new State(new int[]{23,18,4,4,6,31,12,35,13,40,5,-11,11,-11},new int[]{-14,5,-6,47,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46}); - states[5] = new State(new int[]{5,6,11,7}); - states[6] = new State(-23); - states[7] = new State(new int[]{23,18,4,4,6,31,12,35,13,40,5,-11,11,-11},new int[]{-6,8,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46}); + states[4] = new State(new int[]{25,18,3,4,5,31,11,35,12,40,20,48,4,-12,10,-12},new int[]{-15,5,-6,54,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46,-14,47}); + states[5] = new State(new int[]{4,6,10,7}); + states[6] = new State(-24); + states[7] = new State(new int[]{25,18,3,4,5,31,11,35,12,40,20,48,4,-12,10,-12},new int[]{-6,8,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46,-14,47}); states[8] = new State(-4); states[9] = new State(-5); - states[10] = new State(new int[]{7,11}); - states[11] = new State(new int[]{23,18,21,19,18,20},new int[]{-2,12,-4,28,-5,27,-3,17}); - states[12] = new State(new int[]{14,13,15,23,5,-13,11,-13}); - states[13] = new State(new int[]{23,18,21,19,18,20},new int[]{-4,14,-5,27,-3,17}); - states[14] = new State(new int[]{16,15,17,25,14,-14,15,-14,5,-14,11,-14,19,-14,23,-14,4,-14,6,-14,12,-14,13,-14}); - states[15] = new State(new int[]{23,18,21,19,18,20},new int[]{-5,16,-3,17}); - states[16] = new State(-17); - states[17] = new State(-20); - states[18] = new State(-12); - states[19] = new State(-21); - states[20] = new State(new int[]{23,18,21,19,18,20},new int[]{-2,21,-4,28,-5,27,-3,17}); - states[21] = new State(new int[]{19,22,14,13,15,23}); - states[22] = new State(-22); - states[23] = new State(new int[]{23,18,21,19,18,20},new int[]{-4,24,-5,27,-3,17}); - states[24] = new State(new int[]{16,15,17,25,14,-15,15,-15,5,-15,11,-15,19,-15,23,-15,4,-15,6,-15,12,-15,13,-15}); - states[25] = new State(new int[]{23,18,21,19,18,20},new int[]{-5,26,-3,17}); - states[26] = new State(-18); - states[27] = new State(-19); - states[28] = new State(new int[]{16,15,17,25,14,-16,15,-16,5,-16,11,-16,19,-16,23,-16,4,-16,6,-16,12,-16,13,-16}); + states[10] = new State(new int[]{6,11}); + states[11] = new State(new int[]{25,18,23,19,17,20},new int[]{-2,12,-4,28,-5,27,-3,17}); + states[12] = new State(new int[]{13,13,14,23,4,-14,10,-14,22,-14}); + states[13] = new State(new int[]{25,18,23,19,17,20},new int[]{-4,14,-5,27,-3,17}); + states[14] = new State(new int[]{15,15,16,25,13,-15,14,-15,4,-15,10,-15,22,-15,18,-15,25,-15,3,-15,5,-15,11,-15,12,-15,20,-15,21,-15}); + states[15] = new State(new int[]{25,18,23,19,17,20},new int[]{-5,16,-3,17}); + states[16] = new State(-18); + states[17] = new State(-21); + states[18] = new State(-13); + states[19] = new State(-22); + states[20] = new State(new int[]{25,18,23,19,17,20},new int[]{-2,21,-4,28,-5,27,-3,17}); + states[21] = new State(new int[]{18,22,13,13,14,23}); + states[22] = new State(-23); + states[23] = new State(new int[]{25,18,23,19,17,20},new int[]{-4,24,-5,27,-3,17}); + states[24] = new State(new int[]{15,15,16,25,13,-16,14,-16,4,-16,10,-16,22,-16,18,-16,25,-16,3,-16,5,-16,11,-16,12,-16,20,-16,21,-16}); + states[25] = new State(new int[]{25,18,23,19,17,20},new int[]{-5,26,-3,17}); + states[26] = new State(-19); + states[27] = new State(-20); + states[28] = new State(new int[]{15,15,16,25,13,-17,14,-17,4,-17,10,-17,22,-17,18,-17,25,-17,3,-17,5,-17,11,-17,12,-17,20,-17,21,-17}); states[29] = new State(-6); states[30] = new State(-7); - states[31] = new State(new int[]{23,18,21,19,18,20},new int[]{-2,32,-4,28,-5,27,-3,17}); - states[32] = new State(new int[]{14,13,15,23,23,18,4,4,6,31,12,35,13,40,5,-11,11,-11},new int[]{-6,33,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46}); - states[33] = new State(-24); + states[31] = new State(new int[]{25,18,23,19,17,20},new int[]{-2,32,-4,28,-5,27,-3,17}); + states[32] = new State(new int[]{13,13,14,23,25,18,3,4,5,31,11,35,12,40,20,48,4,-12,10,-12,22,-12},new int[]{-6,33,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46,-14,47}); + states[33] = new State(-25); states[34] = new State(-8); - states[35] = new State(new int[]{18,36}); - states[36] = new State(new int[]{23,18,21,19,18,20},new int[]{-2,37,-4,28,-5,27,-3,17}); - states[37] = new State(new int[]{19,38,14,13,15,23}); - states[38] = new State(-25); + states[35] = new State(new int[]{17,36}); + states[36] = new State(new int[]{25,18,23,19,17,20},new int[]{-2,37,-4,28,-5,27,-3,17}); + states[37] = new State(new int[]{18,38,13,13,14,23}); + states[38] = new State(-26); states[39] = new State(-9); - states[40] = new State(-26,new int[]{-16,41}); - states[41] = new State(new int[]{23,18},new int[]{-13,42,-3,45}); - states[42] = new State(new int[]{20,43,5,-27,11,-27}); - states[43] = new State(new int[]{23,18},new int[]{-3,44}); - states[44] = new State(-29); - states[45] = new State(-28); + states[40] = new State(-27,new int[]{-17,41}); + states[41] = new State(new int[]{25,18},new int[]{-13,42,-3,45}); + states[42] = new State(new int[]{19,43,4,-28,10,-28,22,-28}); + states[43] = new State(new int[]{25,18},new int[]{-3,44}); + states[44] = new State(-30); + states[45] = new State(-29); states[46] = new State(-10); - states[47] = new State(-3); - - for (int sNo = 0; sNo < states.Length; sNo++) states[sNo].number = sNo; + states[47] = new State(-11); + states[48] = new State(new int[]{25,18,23,19,17,20},new int[]{-2,49,-4,28,-5,27,-3,17}); + states[49] = new State(new int[]{21,50,13,13,14,23}); + states[50] = new State(new int[]{25,18,3,4,5,31,11,35,12,40,20,48,4,-12,10,-12,22,-12},new int[]{-6,51,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46,-14,47}); + states[51] = new State(new int[]{22,52,4,-31,10,-31}); + states[52] = new State(new int[]{25,18,3,4,5,31,11,35,12,40,20,48,4,-12,10,-12,22,-12},new int[]{-6,53,-7,9,-3,10,-8,29,-9,30,-10,34,-12,39,-11,46,-14,47}); + states[53] = new State(-32); + states[54] = new State(-3); - rules[1] = new Rule(-15, new int[]{-1,3}); + rules[1] = new Rule(-16, new int[]{-1,2}); rules[2] = new Rule(-1, new int[]{-8}); - rules[3] = new Rule(-14, new int[]{-6}); - rules[4] = new Rule(-14, new int[]{-14,11,-6}); + rules[3] = new Rule(-15, new int[]{-6}); + rules[4] = new Rule(-15, new int[]{-15,10,-6}); rules[5] = new Rule(-6, new int[]{-7}); rules[6] = new Rule(-6, new int[]{-8}); rules[7] = new Rule(-6, new int[]{-9}); rules[8] = new Rule(-6, new int[]{-10}); rules[9] = new Rule(-6, new int[]{-12}); rules[10] = new Rule(-6, new int[]{-11}); - rules[11] = new Rule(-11, new int[]{}); - rules[12] = new Rule(-3, new int[]{23}); - rules[13] = new Rule(-7, new int[]{-3,7,-2}); - rules[14] = new Rule(-2, new int[]{-2,14,-4}); - rules[15] = new Rule(-2, new int[]{-2,15,-4}); - rules[16] = new Rule(-2, new int[]{-4}); - rules[17] = new Rule(-4, new int[]{-4,16,-5}); - rules[18] = new Rule(-4, new int[]{-4,17,-5}); - rules[19] = new Rule(-4, new int[]{-5}); - rules[20] = new Rule(-5, new int[]{-3}); - rules[21] = new Rule(-5, new int[]{21}); - rules[22] = new Rule(-5, new int[]{18,-2,19}); - rules[23] = new Rule(-8, new int[]{4,-14,5}); - rules[24] = new Rule(-9, new int[]{6,-2,-6}); - rules[25] = new Rule(-10, new int[]{12,18,-2,19}); - rules[26] = new Rule(-16, new int[]{}); - rules[27] = new Rule(-12, new int[]{13,-16,-13}); - rules[28] = new Rule(-13, new int[]{-3}); - rules[29] = new Rule(-13, new int[]{-13,20,-3}); + rules[11] = new Rule(-6, new int[]{-14}); + rules[12] = new Rule(-11, new int[]{}); + rules[13] = new Rule(-3, new int[]{25}); + rules[14] = new Rule(-7, new int[]{-3,6,-2}); + rules[15] = new Rule(-2, new int[]{-2,13,-4}); + rules[16] = new Rule(-2, new int[]{-2,14,-4}); + rules[17] = new Rule(-2, new int[]{-4}); + rules[18] = new Rule(-4, new int[]{-4,15,-5}); + rules[19] = new Rule(-4, new int[]{-4,16,-5}); + rules[20] = new Rule(-4, new int[]{-5}); + rules[21] = new Rule(-5, new int[]{-3}); + rules[22] = new Rule(-5, new int[]{23}); + rules[23] = new Rule(-5, new int[]{17,-2,18}); + rules[24] = new Rule(-8, new int[]{3,-15,4}); + rules[25] = new Rule(-9, new int[]{5,-2,-6}); + rules[26] = new Rule(-10, new int[]{11,17,-2,18}); + rules[27] = new Rule(-17, new int[]{}); + rules[28] = new Rule(-12, new int[]{12,-17,-13}); + rules[29] = new Rule(-13, new int[]{-3}); + rules[30] = new Rule(-13, new int[]{-13,19,-3}); + rules[31] = new Rule(-14, new int[]{20,-2,21,-6}); + rules[32] = new Rule(-14, new int[]{20,-2,21,-6,22,-6}); } protected override void Initialize() { @@ -166,7 +163,6 @@ public class Parser: ShiftReduceParser<ValueType, LexLocation> protected override void DoAction(int action) { -#pragma warning disable 162, 1522 switch (action) { case 2: // progr -> block @@ -201,85 +197,93 @@ public class Parser: ShiftReduceParser<ValueType, LexLocation> case 10: // statement -> empty { CurrentSemanticValue.stVal = ValueStack[ValueStack.Depth-1].stVal; } break; - case 11: // empty -> /* empty */ + case 11: // statement -> if +{ CurrentSemanticValue.stVal = ValueStack[ValueStack.Depth-1].stVal; } + break; + case 12: // empty -> /* empty */ { CurrentSemanticValue.stVal = new EmptyNode(); } break; - case 12: // ident -> ID + case 13: // ident -> ID { if (!InDefSect) if (!SymbolTable.vars.ContainsKey(ValueStack[ValueStack.Depth-1].sVal)) - throw new Exception("("+LocationStack[LocationStack.Depth-1].StartLine+","+LocationStack[LocationStack.Depth-1].StartColumn+"): ÏåðåìåГГГ Гї "+ValueStack[ValueStack.Depth-1].sVal+" ГГҐ îïèñà ГГ "); + throw new Exception("("+LocationStack[LocationStack.Depth-1].StartLine+","+LocationStack[LocationStack.Depth-1].StartColumn+"): Переменная "+ValueStack[ValueStack.Depth-1].sVal+" не описана"); CurrentSemanticValue.eVal = new IdNode(ValueStack[ValueStack.Depth-1].sVal); } break; - case 13: // assign -> ident, ASSIGN, expr + case 14: // assign -> ident, ASSIGN, expr { CurrentSemanticValue.stVal = new AssignNode(ValueStack[ValueStack.Depth-3].eVal as IdNode, ValueStack[ValueStack.Depth-1].eVal); } break; - case 14: // expr -> expr, PLUS, T + case 15: // expr -> expr, PLUS, T { CurrentSemanticValue.eVal = new BinOpNode(ValueStack[ValueStack.Depth-3].eVal,ValueStack[ValueStack.Depth-1].eVal,'+'); } break; - case 15: // expr -> expr, MINUS, T + case 16: // expr -> expr, MINUS, T { CurrentSemanticValue.eVal = new BinOpNode(ValueStack[ValueStack.Depth-3].eVal,ValueStack[ValueStack.Depth-1].eVal,'-'); } break; - case 16: // expr -> T + case 17: // expr -> T { CurrentSemanticValue.eVal = ValueStack[ValueStack.Depth-1].eVal; } break; - case 17: // T -> T, MULT, F + case 18: // T -> T, MULT, F { CurrentSemanticValue.eVal = new BinOpNode(ValueStack[ValueStack.Depth-3].eVal,ValueStack[ValueStack.Depth-1].eVal,'*'); } break; - case 18: // T -> T, DIV, F + case 19: // T -> T, DIV, F { CurrentSemanticValue.eVal = new BinOpNode(ValueStack[ValueStack.Depth-3].eVal,ValueStack[ValueStack.Depth-1].eVal,'/'); } break; - case 19: // T -> F + case 20: // T -> F { CurrentSemanticValue.eVal = ValueStack[ValueStack.Depth-1].eVal; } break; - case 20: // F -> ident + case 21: // F -> ident { CurrentSemanticValue.eVal = ValueStack[ValueStack.Depth-1].eVal as IdNode; } break; - case 21: // F -> INUM + case 22: // F -> INUM { CurrentSemanticValue.eVal = new IntNumNode(ValueStack[ValueStack.Depth-1].iVal); } break; - case 22: // F -> LPAREN, expr, RPAREN + case 23: // F -> LPAREN, expr, RPAREN { CurrentSemanticValue.eVal = ValueStack[ValueStack.Depth-2].eVal; } break; - case 23: // block -> BEGIN, stlist, END + case 24: // block -> BEGIN, stlist, END { CurrentSemanticValue.blVal = ValueStack[ValueStack.Depth-2].blVal; } break; - case 24: // cycle -> CYCLE, expr, statement + case 25: // cycle -> CYCLE, expr, statement { CurrentSemanticValue.stVal = new CycleNode(ValueStack[ValueStack.Depth-2].eVal,ValueStack[ValueStack.Depth-1].stVal); } break; - case 25: // write -> WRITE, LPAREN, expr, RPAREN + case 26: // write -> WRITE, LPAREN, expr, RPAREN { CurrentSemanticValue.stVal = new WriteNode(ValueStack[ValueStack.Depth-2].eVal); } break; - case 26: // Anon@1 -> /* empty */ + case 27: // Anon@1 -> /* empty */ { InDefSect = true; } break; - case 27: // var -> VAR, Anon@1, varlist + case 28: // var -> VAR, Anon@1, varlist { foreach (var v in (ValueStack[ValueStack.Depth-1].stVal as VarDefNode).vars) SymbolTable.NewVarDef(v.Name, type.tint); InDefSect = false; } break; - case 28: // varlist -> ident + case 29: // varlist -> ident { CurrentSemanticValue.stVal = new VarDefNode(ValueStack[ValueStack.Depth-1].eVal as IdNode); } break; - case 29: // varlist -> varlist, COLUMN, ident + case 30: // varlist -> varlist, COLUMN, ident { (ValueStack[ValueStack.Depth-3].stVal as VarDefNode).Add(ValueStack[ValueStack.Depth-1].eVal as IdNode); CurrentSemanticValue.stVal = ValueStack[ValueStack.Depth-3].stVal; } break; + case 31: // if -> IF, expr, THEN, statement +{ CurrentSemanticValue.stVal = new IfNode(ValueStack[ValueStack.Depth-3].eVal, ValueStack[ValueStack.Depth-1].stVal); } + break; + case 32: // if -> IF, expr, THEN, statement, ELSE, statement +{ CurrentSemanticValue.stVal = new IfNode(ValueStack[ValueStack.Depth-5].eVal, ValueStack[ValueStack.Depth-3].stVal, ValueStack[ValueStack.Depth-1].stVal); } + break; } -#pragma warning restore 162, 1522 } protected override string TerminalToString(int terminal) { - if (aliases != null && aliases.ContainsKey(terminal)) - return aliases[terminal]; + if (aliasses != null && aliasses.ContainsKey(terminal)) + return aliasses[terminal]; else if (((Tokens)terminal).ToString() != terminal.ToString(CultureInfo.InvariantCulture)) return ((Tokens)terminal).ToString(); else diff --git a/Module7/SimpleYacc.y b/Module7/SimpleYacc.y index 20087e00b11254a052c1bfcd87f137d81203b253..42a88a6f6948d50a74d775a210cdd6fbb0049dfe 100644 --- a/Module7/SimpleYacc.y +++ b/Module7/SimpleYacc.y @@ -24,13 +24,13 @@ %start progr -%token BEGIN END CYCLE ASSIGN ASSIGNPLUS ASSIGNMINUS ASSIGNMULT SEMICOLON WRITE VAR PLUS MINUS MULT DIV LPAREN RPAREN COLUMN +%token BEGIN END CYCLE ASSIGN ASSIGNPLUS ASSIGNMINUS ASSIGNMULT SEMICOLON WRITE VAR PLUS MINUS MULT DIV LPAREN RPAREN COLUMN IF THEN ELSE %token <iVal> INUM %token <dVal> RNUM %token <sVal> ID %type <eVal> expr ident T F -%type <stVal> statement assign block cycle write empty var varlist +%type <stVal> statement assign block cycle write empty var varlist if %type <blVal> stlist block %% @@ -55,6 +55,7 @@ statement: assign { $$ = $1; } | write { $$ = $1; } | var { $$ = $1; } | empty { $$ = $1; } + | if { $$ = $1; } ; empty : { $$ = new EmptyNode(); } @@ -114,6 +115,10 @@ varlist : ident $$ = $1; } ; + +if : IF expr THEN statement { $$ = new IfNode($2, $4); } + | IF expr THEN statement ELSE statement { $$ = new IfNode($2, $4, $6); } + ; %% diff --git a/Module7/Visitors/AutoVisitor.cs b/Module7/Visitors/AutoVisitor.cs index 4bc07787c1c5f14bc9f05ff665e570994bd17e63..0f303e4a261d6259614e155377dc50b63368ea50 100644 --- a/Module7/Visitors/AutoVisitor.cs +++ b/Module7/Visitors/AutoVisitor.cs @@ -41,5 +41,12 @@ namespace SimpleLang.Visitors foreach (var v in w.vars) v.Visit(this); } + public override void VisitIfNode(IfNode node) + { + node.Expr.Visit(this); + node.ThenStat.Visit(this); + if (node.ElseStat != null) + node.ElseStat.Visit(this); + } } } diff --git a/Module7/Visitors/ChangeVarIdVisitor.cs b/Module7/Visitors/ChangeVarIdVisitor.cs index 7e8942df896a2c4f3d4539a1ae3012d3bb483cc4..0c03306e3ac90c34294088a234326166c78280f2 100644 --- a/Module7/Visitors/ChangeVarIdVisitor.cs +++ b/Module7/Visitors/ChangeVarIdVisitor.cs @@ -15,6 +15,12 @@ namespace SimpleLang.Visitors from = _from; to = _to; } - + + public override void VisitIdNode(IdNode id) + { + if (id.Name == from) + id.Name = to; + } + } } diff --git a/Module7/Visitors/CommonlyUsedVarVisitor.cs b/Module7/Visitors/CommonlyUsedVarVisitor.cs index a73e3b6cfeb2662db626d3649d7cefc95e687c2d..772f0dee206a9b5761d26fb4452f04be2f944a1b 100644 --- a/Module7/Visitors/CommonlyUsedVarVisitor.cs +++ b/Module7/Visitors/CommonlyUsedVarVisitor.cs @@ -3,14 +3,35 @@ using System.Collections.Generic; using System.Linq; using System.Text; using ProgramTree; +using static System.Net.Mime.MediaTypeNames; namespace SimpleLang.Visitors { public class CommonlyUsedVarVisitor : AutoVisitor { + public Dictionary<string, int> Variables = new Dictionary<string, int>(); public string mostCommonlyUsedVar() { - throw new NotImplementedException(); + int MaxNumber = -1; + string MostCommonVariable = ""; + foreach(var kv in Variables) + { + if (kv.Value > MaxNumber) + { + MaxNumber = kv.Value; + MostCommonVariable = kv.Key; + } + } + return MostCommonVariable; } + + public override void VisitIdNode(IdNode id) + { + if (Variables.ContainsKey(id.Name)) + Variables[id.Name] += 1; + else + Variables[id.Name] = 1; + } + } } diff --git a/Module7/Visitors/CountCyclesOpVisitor.cs b/Module7/Visitors/CountCyclesOpVisitor.cs index 5b5368b01bb2ece936bdcff542998c8c01009aa5..538777e195b179e0b008d7195faea69cbde33706 100644 --- a/Module7/Visitors/CountCyclesOpVisitor.cs +++ b/Module7/Visitors/CountCyclesOpVisitor.cs @@ -8,9 +8,31 @@ namespace SimpleLang.Visitors { public class CountCyclesOpVisitor : AutoVisitor { + public int OverallCyclesNumber = 0; + public int CurrentCyclesNumber = 0; + public int OpsNumber = 0; + public int MidCount() { - throw new NotImplementedException(); + if (OpsNumber > 0) + return OpsNumber / OverallCyclesNumber; + else + return 0; + } + + public override void VisitCycleNode(CycleNode c) + { + ++OverallCyclesNumber; + ++CurrentCyclesNumber; + base.VisitCycleNode(c); + --CurrentCyclesNumber; + } + + public override void VisitAssignNode(AssignNode c) + { + if (CurrentCyclesNumber > 0) + ++OpsNumber; + base.VisitAssignNode(c); } } } diff --git a/Module7/Visitors/ExprComplexityVisitor.cs b/Module7/Visitors/ExprComplexityVisitor.cs index ef9f0b2a9e8e6d76f0cb90d25515bea16760776e..1eefb6911e230cc4e74ce9df6e3bdbde22981eb1 100644 --- a/Module7/Visitors/ExprComplexityVisitor.cs +++ b/Module7/Visitors/ExprComplexityVisitor.cs @@ -8,11 +8,35 @@ namespace SimpleLang.Visitors { public class ExprComplexityVisitor : AutoVisitor { + public int OperationsDepth = 0; + public int OperationsComplexity = 0; + public List<int> ExpressionComplexity = new List<int>(); // СЃРїРёСЃРѕРє должен содержать сложность каждого выражения, встреченного РїСЂРё обычном РїРѕСЂСЏРґРєРµ РѕР±С…РѕРґР° AST public List<int> getComplexityList() { - throw new NotImplementedException(); + return ExpressionComplexity; } - } + public override void VisitBinOpNode(BinOpNode binop) + { + if (binop.Op == '+' || binop.Op == '-') + OperationsComplexity += 1; + else if (binop.Op == '*' || binop.Op == '/') + OperationsComplexity += 3; + ++OperationsDepth; + base.VisitBinOpNode(binop); + --OperationsDepth; + if (OperationsDepth == 0) + { + ExpressionComplexity.Add(OperationsComplexity); + OperationsComplexity = 0; + } + } + + public override void VisitIntNumNode(IntNumNode num) + { + if (OperationsDepth == 0) + ExpressionComplexity.Add(OperationsComplexity); + } + } } diff --git a/Module7/Visitors/MaxIfCycleNestVisitor.cs b/Module7/Visitors/MaxIfCycleNestVisitor.cs index c399a8ec4e3a067d99e207abc8e8e04f1f0baadb..15cba64e903a5d7cb60e5b4a532626174ee1460f 100644 --- a/Module7/Visitors/MaxIfCycleNestVisitor.cs +++ b/Module7/Visitors/MaxIfCycleNestVisitor.cs @@ -10,5 +10,23 @@ namespace SimpleLang.Visitors public class MaxIfCycleNestVisitor : AutoVisitor { public int MaxNest = 0; + public int CurrentNest = 0; + public override void VisitIfNode(IfNode node) + { + ++CurrentNest; + if (CurrentNest > MaxNest) + MaxNest = CurrentNest; + base.VisitIfNode(node); + --CurrentNest; + } + + public override void VisitCycleNode(CycleNode node) + { + ++CurrentNest; + if (CurrentNest > MaxNest) + MaxNest = CurrentNest; + base.VisitCycleNode(node); + --CurrentNest; + } } } \ No newline at end of file diff --git a/Module7/Visitors/MaxNestCyclesVisitor.cs b/Module7/Visitors/MaxNestCyclesVisitor.cs index e5c768b4052dd05dd6eb58a87db533df5929cf0a..90791fdd3577079a154875dece0474950624da52 100644 --- a/Module7/Visitors/MaxNestCyclesVisitor.cs +++ b/Module7/Visitors/MaxNestCyclesVisitor.cs @@ -9,5 +9,14 @@ namespace SimpleLang.Visitors public class MaxNestCyclesVisitor : AutoVisitor { public int MaxNest = 0; + public int CurrentNest = 0; + public override void VisitCycleNode(CycleNode c) + { + ++CurrentNest; + if (CurrentNest > MaxNest) + MaxNest = CurrentNest; + base.VisitCycleNode(c); + --CurrentNest; + } } } diff --git a/Module7/Visitors/PrettyPrintVisitor.cs b/Module7/Visitors/PrettyPrintVisitor.cs index 87892b1214d751d13640e7adf61bd276ef870904..cf72badbae2b199c3b1da8135bd05f3645b4590f 100644 --- a/Module7/Visitors/PrettyPrintVisitor.cs +++ b/Module7/Visitors/PrettyPrintVisitor.cs @@ -84,5 +84,21 @@ namespace SimpleLang.Visitors for (int i = 1; i < w.vars.Count; i++) Text += ',' + w.vars[i].Name; } + public override void VisitIfNode(IfNode w) + { + Text += IndentStr() + "if "; + w.Expr.Visit(this); + Text += " then" + Environment.NewLine; + IndentPlus(); + w.ThenStat.Visit(this); + IndentMinus(); + if (w.ElseStat != null) + { + Text += Environment.NewLine + IndentStr() + "else" + Environment.NewLine; + IndentPlus(); + w.ElseStat.Visit(this); + IndentMinus(); + } + } } } diff --git a/Module7/Visitors/Visitor.cs b/Module7/Visitors/Visitor.cs index b9dcae028c1c74893e7bf551cd0feccf5bcbf0c9..4270567e587eb2f79f5024519f71e3c9418808c8 100644 --- a/Module7/Visitors/Visitor.cs +++ b/Module7/Visitors/Visitor.cs @@ -17,5 +17,6 @@ namespace SimpleLang.Visitors public virtual void VisitWriteNode(WriteNode w) { } public virtual void VisitVarDefNode(VarDefNode w) { } public virtual void VisitEmptyNode(EmptyNode w) { } + public virtual void VisitIfNode(IfNode node) { } } } diff --git a/TestVisitors/Tests.cs b/TestVisitors/Tests.cs index a5d43a509bcc0eb6b91f8d6fc8d7853ee67b02f4..8e7018bb699ebcadfc97378d8e0c0b9a5ce284ed 100644 --- a/TestVisitors/Tests.cs +++ b/TestVisitors/Tests.cs @@ -20,7 +20,7 @@ namespace TestVisitors } [TestFixture] - [Ignore("This test is disabled")] + //[Ignore("This test is disabled")] public class TestAvgOpCount: ParserTest { [Test] @@ -72,7 +72,7 @@ namespace TestVisitors } [TestFixture] - [Ignore("This test is disabled")] + //[Ignore("This test is disabled")] public class TestCommonVariable: ParserTest { [Test] @@ -97,7 +97,7 @@ namespace TestVisitors } [TestFixture] - [Ignore("This test is disabled")] + //[Ignore("This test is disabled")] public class TestExprComplexity: ParserTest { [Test] @@ -202,7 +202,7 @@ namespace TestVisitors } [TestFixture] - [Ignore("This test is disabled")] + //[Ignore("This test is disabled")] public class TestIfCycleNest: ParserTest { [Test]