Beispiel #1
0
        public void Typecheck()
        {
            foreach (InstrNode node in block.Instructions)
            {
                Instr instruction = node.Value;
                if (instruction is VarDecl)
                {
                    VarDecl  variable = (VarDecl)instruction;
                    TypeDesc varType  = TypeResolver.ResolveType(variable.Value, env, variable.Value.Position);

                    if (variable.Type == null && !(varType is NullType))
                    {
                        variable.Type = new TypeNode(varType, variable.Value.Position);
                    }

                    env.AddEntry(variable.Name, varType, node.Position);
                }

                if (instruction is ClassDecl)
                {
                    ClassDecl classDecl = (ClassDecl)instruction;
                    env.AddEntry(classDecl.Name, new Class(classDecl.Typevars.Sequence), node.Position);
                }
            }
        }
        public override void Visit(VarDecl varDecl)
        {
            if (!this.DoneClassList)
            {
                return;
            }
            int numElements = 1;
            var dimensions  = new List <int>();

            // Calculate the dimensions and the total size.
            foreach (var dimension in varDecl.Dimensions)
            {
                dimensions.Add(int.Parse(dimension.Value));
                numElements *= dimensions.Last();
            }

            var nodeEntry = this.GetCurrentScope().Get(varDecl.Id, Classification.Variable);


            if (!this.Sizes.ContainsKey(varDecl.Type))
            {
                // If it doesn't exist, the memory size will be -1. By multiplying it by the number of elements,
                // the true size will happen when (in the class) we resolve it by doing *= -sizeof(type);
                nodeEntry.EntryMemorySize *= numElements;
            }
            else
            {
                nodeEntry.EntryMemorySize = Sizes[varDecl.Type] * numElements;
            }

            nodeEntry.MaxSizeDimensions = dimensions;
        }
Beispiel #3
0
        public override void VisitVarDecl(VarDecl decl)
        {
            if (!decl.IsExternC)
            {
                return;
            }
            if (!decl.PresumedLoc.FileName.Contains(".framework"))
            {
                return;
            }

            if (!decl.IsAvailable())
            {
                return;
            }

            var framework = Helpers.GetFramework(decl);

            if (framework == null)
            {
                return;
            }

            var name = decl.ToString();

            if (!fields.TryGetValue(name, out var mr))
            {
                Log.On(framework).Add($"!missing-field! {name} not bound");
            }
            else
            {
                fields.Remove(name);
            }
        }
Beispiel #4
0
        public override void VisitVarDecl(VarDecl decl)
        {
            if (!decl.IsExternC)
            {
                return;
            }
            if (!decl.PresumedLoc.FileName.Contains(".framework"))
            {
                return;
            }

            if (!decl.IsAvailable())
            {
                return;
            }

            var             name = decl.ToString();
            MemberReference mr;

            if (!fields.TryGetValue(name, out mr))
            {
                Console.WriteLine("!missing-field! {0} not bound", name);
                return;
            }
            else
            {
                fields.Remove(name);
            }
        }
Beispiel #5
0
        public override AstNode VisitVarDecl(VarDecl ast)
        {
            var type = GetClrType(ast.Type.ResolvedType);

            m_ilgen.DeclareLocal(type);

            return(ast);
        }
Beispiel #6
0
        public static InstrNode Consume(Parser parser)
        {
            CodePosition oldCursor = parser.Cursor;

            Instr instr;

            switch (parser.LookAhead().Type)
            {
            case TokenInfo.TokenType.EOL:
            case TokenInfo.TokenType.L_CURLY_BRACKET:
                instr = parser.TryConsumer((Parser p) => Block.Consume(p));
                break;

            case TokenInfo.TokenType.WHILE:
                instr = parser.TryConsumer(WhileLoop.Consume);
                break;

            case TokenInfo.TokenType.FOR:
                instr = parser.TryConsumer(ForLoop.Consume);
                break;

            case TokenInfo.TokenType.CONST:
            case TokenInfo.TokenType.VAR:
                instr = parser.TryConsumer((Parser p) => VarDecl.Consume(p));
                break;

            case TokenInfo.TokenType.RETURN:
                instr = parser.TryConsumer(ReturnInstr.Consume);
                break;

            case TokenInfo.TokenType.BREAK:
                instr = parser.TryConsumer(BreakInstr.Consume);
                break;

            case TokenInfo.TokenType.CONTINUE:
                instr = parser.TryConsumer(ContinueInstr.Consume);
                break;

            default:
                instr = parser.TryManyConsumers(new Func <Parser, Instr>[] {
                    VarMutation.Consume,
                    ExprInstr.Consume
                });
                break;
            }

            if (instr == null)
            {
                throw new ParserError(new FailedConsumer(), parser.Cursor);
            }

            return(new InstrNode(instr, oldCursor));
        }
Beispiel #7
0
        public static void CheckVarDecl(InstrNode node, ref Environment env)
        {
            VarDecl  variable = (VarDecl)node.Value;
            TypeDesc varType  = TypeResolver.ResolveType(variable.Value, env, variable.Value.Position);

            if (variable.Type == null && !(varType is NullType))
            {
                variable.Type = new TypeNode(varType, variable.Value.Position);
            }

            env.AddEntry(variable.Name, varType, node.Position);
        }
        public override void Visit(VarDecl varDecl)
        {
            if (varDecl.Type == "float" || varDecl.Type == "int")
            {
                return;
            }

            if (this._globalScope.Get($"{varDecl.Type}-{Classification.Class}") == null)
            {
                ErrorManager.Add($"The type {varDecl.Type} could not be found or does not exist.", varDecl.Location);
            }
        }
Beispiel #9
0
        public override AstNode VisitVarDecl(VarDecl ast)
        {
            if (CheckVariableDecl(ast))
            {
                //add to current variable table
                m_currentMethodVariables.Add(new VariableInfo()
                {
                    Name = ast.VariableName.Content, Type = ast.Type.ResolvedType, Index = m_currentVariableIndex
                });
                ++m_currentVariableIndex;
            }

            return(ast);
        }
Beispiel #10
0
    public bool GetVarByIdent(string ident, out VarDecl varDecl)
    {
        for (int i = 0; i < varsTable.Count; i++)
        {
            if (varsTable[i].Ident == ident)
            {
                varDecl = varsTable[i];
                return(true);
            }
        }

        varDecl = new VarDecl();

        return(false);
    }
Beispiel #11
0
    public bool AddVar(string ident, int scope, bool isArgument)
    {
        VarDecl var;

        if (GetVarByIdent(ident, out var, scope))
        {
            return(false);
        }

        var = new VarDecl();

        var.Ident = ident;
        if (scope == -1)
        {
            var.Idx = varIdx;
            varIdx++;
        }
        else
        {
            FuncDecl func = funcTable[scope];
            if (isArgument)
            {
                var.Idx = func.argIdx;
                func.argIdx++;
            }
            else
            {
                var.Idx = func.varIdx;
                func.varIdx++;
            }
            var.isArg        = isArgument;
            funcTable[scope] = func;
        }

        var.scope = scope;

        if (scope == -1)
        {
            globalVarSize++;
        }

        varsTable.Add(var);

        return(true);
    }
Beispiel #12
0
    public bool AddVar(string ident)
    {
        VarDecl var;

        if (GetVarByIdent(ident, out var))
        {
            return(false);
        }

        var = new VarDecl();

        var.Ident = ident;
        var.Idx   = varsTable.Count;

        varsTable.Add(var);

        return(true);
    }
Beispiel #13
0
        private bool CheckVariableDecl(VarDecl ast)
        {
            //step1, check local parameter & variable definitions
            if (m_currentMethodParameters.Contains(ast.VariableName.Content))
            {
                AddError(c_SE_VariableDuplicates, ast.VariableName.Span, ast.VariableName.Content);
                return(false);
            }
            else if (m_currentMethodVariables.Contains(ast.VariableName.Content))
            {
                AddError(c_SE_VariableDuplicates, ast.VariableName.Span, ast.VariableName.Content);
                return(false);
            }

            //step2, resolve type
            ResolveTypeNode(ast.Type);
            return(true);
        }
Beispiel #14
0
        internal ForStmt ParseForStmt()
        {
            Token t;

            ExpectAndGet(TokenType.FOR, out t);
            VarDecl    d = null;
            AssignExpr a = null;

            if (ExpectAny(TokenType.IMPLIED, TokenType.VAR) || (La(2) == TokenType.IMPLIED && Expect(TokenType.LOCAL) && Expect(TokenType.IMPLIED)))
            {
                d = ParseForDecl(true);
            }
            else if (Expect(TokenType.LOCAL))
            {
                d = ParseForDecl(false);
            }
            else
            {
                a = ParseExpression() as AssignExpr;
                Require(a?.Left is IdExpr, ErrorCode.Expected, "variable assignemnt expression");
            }
            var  dir   = Require(ExpectAndGetAny(TokenType.UPTO, TokenType.DOWNTO, TokenType.TO), ErrorCode.Expected, TokenType.TO);
            Expr final = RequireExpression();
            Expr step  = null;

            if (Expect(TokenType.STEP))
            {
                step = RequireExpression();
            }
            Require(TokenType.EOS);
            var s = ParseStatementBlock();

            if (Expect(TokenType.END))
            {
                Expect(TokenType.FOR);
            }
            else
            {
                Require(Expect(TokenType.NEXT), ErrorCode.Expected, "END FOR");
            }
            Require(TokenType.EOS);
            return(a != null ? new ForStmt(t, a, dir, final, step, s)
                : new ForStmt(t, d, dir, final, step, s));
        }
Beispiel #15
0
        internal ForeachStmt ParseForeachStmt()
        {
            Token r = ExpectToken(TokenType.FOR) ?? RequireAndGet(TokenType.FOREACH);

            if (r.Type == TokenType.FOR)
            {
                Require(TokenType.EACH);
            }

            VarDecl v = null;

            if (Expect(TokenType.IMPLIED) || Expect(TokenType.VAR))
            {
                Token n = RequireVarIdName();
                v = new ImpliedVarDecl(n, null);
            }
            else
            {
                Token n = RequireVarIdName();
                Require(TokenType.AS);
                TypeExpr type = Require(ParseType(), ErrorCode.Expected, "type");
                v = new VarDecl(n, type);
            }

            Require(TokenType.IN);
            var e = RequireExpression();

            Require(TokenType.EOS);

            var s = ParseStatementBlock();

            if (!Expect(TokenType.NEXT))
            {
                Require(TokenType.END);
                ExpectAny(TokenType.FOR, TokenType.FOREACH);
            }
            Require(TokenType.EOS);

            return(new ForeachStmt(r, v, e, s));
        }
Beispiel #16
0
 void SymbolDecl.IVisitor.Visit(VarDecl decl)
 {
     Fix(decl);
     Execute(decl.Type);
 }
Beispiel #17
0
 public virtual void Visit(VarDecl varDecl)
 {
 }
 public override void Visit(VarDecl var)
 {
 }
Beispiel #19
0
        static SymbolDecl[] ParseSymbolInternal(string[] tokens, ref int index)
        {
            if (CppParser.Token(tokens, ref index, "public") || CppParser.Token(tokens, ref index, "protected") || CppParser.Token(tokens, ref index, "private"))
            {
                index--;
                return(null);
            }
            TemplateDecl templateDecl = null;

            if (CppParser.Token(tokens, ref index, "template"))
            {
                templateDecl = new TemplateDecl
                {
                    TypeParameters = new List <TypeParameterDecl>(),
                    Specialization = new List <TypeDecl>(),
                };
                CppParser.EnsureToken(tokens, ref index, "<");
                if (!CppParser.Token(tokens, ref index, ">"))
                {
                    while (true)
                    {
                        string token = null;
                        CppParser.SkipUntilInTemplate(tokens, ref index, out token, ",", ">", "=");

                        index -= 2;
                        templateDecl.TypeParameters.Add(new TypeParameterDecl
                        {
                            Name = CppParser.EnsureId(tokens, ref index),
                        });
                        index++;

                        if (token == "=")
                        {
                            CppParser.SkipUntilInTemplate(tokens, ref index, out token, ",", ">");
                        }

                        if (token == ">")
                        {
                            break;
                        }
                    }
                }
            }

            if (CppParser.Token(tokens, ref index, "friend"))
            {
                int    oldIndex = index - 1;
                string token    = null;
                CppParser.SkipUntil(tokens, ref index, out token, ";", "{");
                if (token == ";")
                {
                    return(null);
                }
                else
                {
                    index         = oldIndex;
                    tokens[index] = "static";
                }
            }

            if (CppParser.Token(tokens, ref index, "namespace"))
            {
                if (templateDecl != null)
                {
                    throw new ArgumentException("Failed to parse.");
                }
                var decl = new NamespaceDecl();
                decl.Name = CppParser.EnsureId(tokens, ref index);

                CppParser.EnsureToken(tokens, ref index, "{");
                ParseSymbols(tokens, ref index, decl);
                CppParser.EnsureToken(tokens, ref index, "}");

                return(new SymbolDecl[] { decl });
            }
            else if (CppParser.Token(tokens, ref index, "using"))
            {
                if (CppParser.Token(tokens, ref index, "namespace"))
                {
                    if (templateDecl != null)
                    {
                        throw new ArgumentException("Failed to parse.");
                    }
                    var decl = new UsingNamespaceDecl();
                    decl.Path = new List <string>();
                    decl.Path.Add(CppParser.EnsureId(tokens, ref index));

                    while (!CppParser.Token(tokens, ref index, ";"))
                    {
                        CppParser.EnsureToken(tokens, ref index, ":");
                        CppParser.EnsureToken(tokens, ref index, ":");
                        decl.Path.Add(CppParser.EnsureId(tokens, ref index));
                    }

                    return(new SymbolDecl[] { decl });
                }
                else
                {
                    string name = null;
                    if (CppParser.Id(tokens, ref index, out name))
                    {
                        if (templateDecl != null)
                        {
                            if (CppParser.Token(tokens, ref index, "<"))
                            {
                                while (true)
                                {
                                    templateDecl.Specialization.Add(CppTypeParser.EnsureTypeWithoutName(tokens, ref index));
                                    if (CppParser.Token(tokens, ref index, ">"))
                                    {
                                        break;
                                    }
                                    CppParser.EnsureToken(tokens, ref index, ",");
                                }
                            }
                        }
                        if (CppParser.Token(tokens, ref index, "="))
                        {
                            SymbolDecl decl = new TypedefDecl
                            {
                                Name = name,
                                Type = CppTypeParser.EnsureTypeWithoutName(tokens, ref index),
                            };
                            CppParser.EnsureToken(tokens, ref index, ";");

                            if (templateDecl != null)
                            {
                                templateDecl.Element = decl;
                                decl = templateDecl;
                            }
                            return(new SymbolDecl[] { decl });
                        }
                    }
                    if (templateDecl != null)
                    {
                        throw new ArgumentException("Failed to parse.");
                    }
                    CppParser.SkipUntil(tokens, ref index, ";");
                }
            }
            else if (CppParser.Token(tokens, ref index, "typedef"))
            {
                if (templateDecl != null)
                {
                    throw new ArgumentException("Failed to parse.");
                }
                string name = null;
                var    type = CppTypeParser.EnsureTypeWithName(tokens, ref index, out name);
                CppParser.EnsureToken(tokens, ref index, ";");

                var decl = new TypedefDecl();
                decl.Name = name;
                decl.Type = type;
                return(new SymbolDecl[] { decl });
            }
            else if (CppParser.Token(tokens, ref index, "enum"))
            {
                if (templateDecl != null)
                {
                    throw new ArgumentException("Failed to parse.");
                }
                bool   enumClass = CppParser.Token(tokens, ref index, "class");
                string name      = CppParser.EnsureId(tokens, ref index);
                if (CppParser.Token(tokens, ref index, ":"))
                {
                    CppTypeParser.EnsureTypeWithoutName(tokens, ref index);
                }
                if (!CppParser.Token(tokens, ref index, ";"))
                {
                    CppParser.EnsureToken(tokens, ref index, "{");
                    var decl = new EnumDecl
                    {
                        Name      = name,
                        EnumClass = enumClass,
                        Children  = new List <SymbolDecl>(),
                    };

                    while (true)
                    {
                        if (CppParser.Token(tokens, ref index, "}"))
                        {
                            break;
                        }

                        while (index < tokens.Length && tokens[index].Length >= 3 && tokens[index].StartsWith("///"))
                        {
                            index++;
                        }
                        decl.Children.Add(new EnumItemDecl
                        {
                            Name = CppParser.EnsureId(tokens, ref index),
                        });

                        string token = null;
                        CppParser.SkipUntil(tokens, ref index, out token, ",", "}");
                        if (token == "}")
                        {
                            break;
                        }
                    }

                    if (CppParser.Id(tokens, ref index, out name))
                    {
                        var varDecl = new VarDecl
                        {
                            Static = false,
                            Name   = name,
                            Type   = new RefTypeDecl
                            {
                                Name = decl.Name,
                            },
                        };
                        CppParser.EnsureToken(tokens, ref index, ";");
                        return(new SymbolDecl[] { decl, varDecl });
                    }
                    else
                    {
                        CppParser.EnsureToken(tokens, ref index, ";");
                        return(new SymbolDecl[] { decl });
                    }
                }
            }
            else if (CppParser.Token(tokens, ref index, "struct") || CppParser.Token(tokens, ref index, "class") || CppParser.Token(tokens, ref index, "union"))
            {
                if (CppParser.Token(tokens, ref index, "{"))
                {
                    if (tokens[index - 2] == "class")
                    {
                        throw new ArgumentException("Failed to parse.");
                    }

                    var decl = new GroupedFieldDecl
                    {
                        Grouping = tokens[index - 2] == "struct" ? Grouping.Struct : Grouping.Union,
                    };
                    ParseSymbols(tokens, ref index, decl);
                    CppParser.EnsureToken(tokens, ref index, "}");
                    CppParser.EnsureToken(tokens, ref index, ";");
                    return(new SymbolDecl[] { decl });
                }
                else
                {
                    string name = CppParser.EnsureId(tokens, ref index);
                    if (!CppParser.Token(tokens, ref index, ";"))
                    {
                        var classDecl = new ClassDecl
                        {
                            ClassType =
                                tokens[index - 2] == "struct" ? ClassType.Struct :
                                tokens[index - 2] == "class" ? ClassType.Class :
                                ClassType.Union,
                            BaseTypes = new List <BaseTypeDecl>(),
                            Name      = name,
                        };

                        if (templateDecl != null)
                        {
                            if (CppParser.Token(tokens, ref index, "<"))
                            {
                                if (!CppParser.Token(tokens, ref index, ">"))
                                {
                                    while (true)
                                    {
                                        int oldIndex = index;
                                        try
                                        {
                                            templateDecl.Specialization.Add(CppTypeParser.EnsureTypeWithoutName(tokens, ref index));
                                        }
                                        catch (ArgumentException)
                                        {
                                            index = oldIndex;
                                            CppParser.SkipUntilInTemplate(tokens, ref index, ",", ">");
                                            index--;

                                            templateDecl.Specialization.Add(new ConstantTypeDecl
                                            {
                                                Value = tokens
                                                        .Skip(oldIndex)
                                                        .Take(index - oldIndex)
                                                        .Aggregate((a, b) => a + " " + b),
                                            });
                                        }
                                        if (CppParser.Token(tokens, ref index, ">"))
                                        {
                                            break;
                                        }
                                        CppParser.EnsureToken(tokens, ref index, ",");
                                    }
                                }
                            }
                        }

                        CppParser.Token(tokens, ref index, "abstract");
                        if (CppParser.Token(tokens, ref index, ":"))
                        {
                            while (true)
                            {
                                Access access = classDecl.ClassType == ClassType.Class ? Access.Private : Access.Public;
                                CppParser.Token(tokens, ref index, "virtual");
                                if (CppParser.Token(tokens, ref index, "private"))
                                {
                                    access = Access.Private;
                                }
                                else if (CppParser.Token(tokens, ref index, "protected"))
                                {
                                    access = Access.Protected;
                                }
                                else if (CppParser.Token(tokens, ref index, "public"))
                                {
                                    access = Access.Public;
                                }
                                CppParser.Token(tokens, ref index, "virtual");
                                classDecl.BaseTypes.Add(new BaseTypeDecl
                                {
                                    Access = access,
                                    Type   = CppTypeParser.EnsureTypeWithoutName(tokens, ref index),
                                });
                                if (!CppParser.Token(tokens, ref index, ","))
                                {
                                    break;
                                }
                            }
                        }

                        CppParser.EnsureToken(tokens, ref index, "{");
                        while (true)
                        {
                            if (CppParser.Token(tokens, ref index, "}"))
                            {
                                break;
                            }

                            Access access = classDecl.ClassType == ClassType.Class ? Access.Private : Access.Public;
                            if (CppParser.Token(tokens, ref index, "private"))
                            {
                                access = Access.Private;
                                CppParser.EnsureToken(tokens, ref index, ":");
                            }
                            else if (CppParser.Token(tokens, ref index, "protected"))
                            {
                                access = Access.Protected;
                                CppParser.EnsureToken(tokens, ref index, ":");
                            }
                            else if (CppParser.Token(tokens, ref index, "public"))
                            {
                                access = Access.Public;
                                CppParser.EnsureToken(tokens, ref index, ":");
                            }
                            ParseSymbols(tokens, ref index, classDecl, access);
                        }

                        SymbolDecl decl = classDecl;
                        if (templateDecl != null)
                        {
                            templateDecl.Element = decl;
                            decl = templateDecl;
                        }

                        if (CppParser.Id(tokens, ref index, out name))
                        {
                            var varDecl = new VarDecl
                            {
                                Static = false,
                                Name   = name,
                                Type   = new RefTypeDecl
                                {
                                    Name = classDecl.Name,
                                },
                            };
                            CppParser.EnsureToken(tokens, ref index, ";");
                            return(new SymbolDecl[] { decl, varDecl });
                        }
                        else
                        {
                            CppParser.EnsureToken(tokens, ref index, ";");
                            return(new SymbolDecl[] { decl });
                        }
                    }
                }
            }
            else if (!CppParser.Token(tokens, ref index, ";"))
            {
                Function function = Function.Function;
                {
                    int    oldIndex = index;
                    string name     = null;
                    if (CppParser.Id(tokens, ref index, out name))
                    {
                        if (CppParser.Token(tokens, ref index, "("))
                        {
                            CppParser.SkipUntil(tokens, ref index, ")");
                            if (CppParser.Token(tokens, ref index, ";") || CppParser.Token(tokens, ref index, "=") || CppParser.Token(tokens, ref index, ":") || CppParser.Token(tokens, ref index, "{"))
                            {
                                function = Function.Constructor;
                            }
                        }
                        index = oldIndex;
                    }
                    else if (CppParser.Token(tokens, ref index, "~"))
                    {
                        function = Function.Destructor;
                    }
                }

                if (function == Function.Function)
                {
                    Virtual virtualFunction = Virtual.Normal;
                    CppParser.Token(tokens, ref index, "extern");
                    CppParser.Token(tokens, ref index, "mutable");
                    if (CppParser.Token(tokens, ref index, "virtual"))
                    {
                        virtualFunction = Virtual.Virtual;
                    }
                    else if (CppParser.Token(tokens, ref index, "static"))
                    {
                        virtualFunction = Virtual.Static;
                    }
                    CppParser.Token(tokens, ref index, "inline");
                    CppParser.Token(tokens, ref index, "__forceinline");

                    if (CppParser.Token(tokens, ref index, "operator"))
                    {
                        TypeDecl returnType = null;
                        {
                            int oldIndex = index;
                            CppParser.SkipUntilInTemplate(tokens, ref index, "(");
                            int modify = --index;

                            tokens[modify] = "$";
                            index          = oldIndex;
                            returnType     = CppTypeParser.EnsureTypeWithoutName(tokens, ref index);
                            if (index != modify)
                            {
                                throw new ArgumentException("Failed to parse.");
                            }
                            tokens[modify] = "(";
                        }
                        var decl = new FuncDecl
                        {
                            Virtual  = Virtual.Normal,
                            Name     = "operator",
                            Function = function,
                        };

                        TypeDecl          functionType      = null;
                        Action <TypeDecl> continuation      = null;
                        CallingConvention callingConvention = CallingConvention.Default;
                        CppTypeParser.ParseTypeContinueAfterName(tokens, ref index, ref callingConvention, out functionType, out continuation);
                        continuation(returnType);
                        decl.Type = functionType;

                        if (!CppParser.Token(tokens, ref index, ";"))
                        {
                            CppParser.EnsureToken(tokens, ref index, "{");
                            CppParser.SkipUntil(tokens, ref index, "}");
                        }

                        if (templateDecl != null)
                        {
                            templateDecl.Element = decl;
                            return(new SymbolDecl[] { templateDecl });
                        }
                        else
                        {
                            return(new SymbolDecl[] { decl });
                        }
                    }
                    else
                    {
                        string   name = null;
                        TypeDecl type = null;
                        if (CppTypeParser.ParseType(tokens, ref index, out type, out name))
                        {
                            if (name == null)
                            {
                                throw new ArgumentException("Failed to parse.");
                            }

                            if (type is FunctionTypeDecl)
                            {
                                if (CppParser.Token(tokens, ref index, "="))
                                {
                                    if (CppParser.Token(tokens, ref index, "0"))
                                    {
                                        virtualFunction = Virtual.Abstract;
                                    }
                                    else
                                    {
                                        CppParser.EnsureToken(tokens, ref index, "default", "delete");
                                    }
                                }

                                var decl = new FuncDecl
                                {
                                    Virtual  = virtualFunction,
                                    Name     = name,
                                    Type     = type,
                                    Function = Function.Function,
                                };
                                if (!CppParser.Token(tokens, ref index, ";"))
                                {
                                    CppParser.EnsureToken(tokens, ref index, "{");
                                    CppParser.SkipUntil(tokens, ref index, "}");
                                }

                                if (templateDecl != null)
                                {
                                    templateDecl.Element = decl;
                                    return(new SymbolDecl[] { templateDecl });
                                }
                                else
                                {
                                    return(new SymbolDecl[] { decl });
                                }
                            }
                            else
                            {
                                if (virtualFunction != Virtual.Normal && virtualFunction != Virtual.Static)
                                {
                                    throw new ArgumentException("Failed to parse.");
                                }
                                if (CppParser.Token(tokens, ref index, "="))
                                {
                                    CppParser.SkipUntil(tokens, ref index, ";");
                                }
                                else
                                {
                                    CppParser.EnsureToken(tokens, ref index, ";");
                                }

                                if (!(type is ClassMemberTypeDecl))
                                {
                                    var decl = new VarDecl
                                    {
                                        Static = virtualFunction == Virtual.Static,
                                        Name   = name,
                                        Type   = type,
                                    };
                                    return(new SymbolDecl[] { decl });
                                }
                            }
                        }
                    }
                }
                else
                {
                    var decl = new FuncDecl
                    {
                        Virtual  = Virtual.Normal,
                        Name     = (function == Function.Constructor ? "" : "~") + CppParser.EnsureId(tokens, ref index),
                        Function = function,
                    };

                    TypeDecl          functionType      = null;
                    Action <TypeDecl> continuation      = null;
                    CallingConvention callingConvention = CallingConvention.Default;
                    CppTypeParser.ParseTypeContinueAfterName(tokens, ref index, ref callingConvention, out functionType, out continuation);
                    continuation(new RefTypeDecl
                    {
                        Name = "void"
                    });
                    decl.Type = functionType;

                    if (CppParser.Token(tokens, ref index, "="))
                    {
                        CppParser.EnsureToken(tokens, ref index, "default", "delete");
                    }

                    if (!CppParser.Token(tokens, ref index, ";"))
                    {
                        if (CppParser.Token(tokens, ref index, ":"))
                        {
                            CppParser.SkipUntil(tokens, ref index, "{");
                        }
                        else
                        {
                            CppParser.EnsureToken(tokens, ref index, "{");
                        }
                        CppParser.SkipUntil(tokens, ref index, "}");
                    }

                    if (templateDecl != null)
                    {
                        templateDecl.Element = decl;
                        return(new SymbolDecl[] { templateDecl });
                    }
                    else
                    {
                        return(new SymbolDecl[] { decl });
                    }
                }
            }
            return(null);
        }
Beispiel #20
0
        private bool CheckVariableDecl(VarDecl ast)
        {
            //step1, check local parameter & variable definitions
            if (m_currentMethodParameters.Contains(ast.VariableName.Value))
            {
                m_errorManager.AddError(c_SE_VariableDuplicates, ast.VariableName.Span, ast.VariableName.Value);
                return false;
            }
            else if (m_currentMethodVariables.Contains(ast.VariableName.Value))
            {
                m_errorManager.AddError(c_SE_VariableDuplicates, ast.VariableName.Span, ast.VariableName.Value);
                return false;
            }

            //step2, resolve type
            ResolveTypeNode(ast.Type);
            return true;
        }
Beispiel #21
0
 public virtual AstNode VisitVarDecl(VarDecl ast)
 {
     return(ast);
 }
Beispiel #22
0
 void SymbolDecl.IVisitor.Visit(VarDecl decl)
 {
     EntryDecl(decl);
 }
Beispiel #23
0
        private Statement parseStatement()
        {
            // Bloque
            if (token.TokenType == TokenType.LLAVEI)
            {
                entornoActual = new Entorno(entornoActual);
                eat(TokenType.LLAVEI);
                // recursively call parseStatement() until closing brace
                StatementList stms = new StatementList();
                while (token.TokenType != TokenType.LLAVED && token.TokenType != TokenType.EOF)
                {
                    stms.addElement(parseStatement());
                }
                eat(TokenType.LLAVED);
                entornoActual = entornoActual.Anterior;
                return(new Block(stms, entornoActual));
            }

            switch (token.TokenType)
            {
            case TokenType.PUNTOYCOMA:
                eat(TokenType.PUNTOYCOMA);
                return(Statement.Null);

            case TokenType.IF:
                eat(TokenType.IF);
                // parse conditional expression
                eat(TokenType.IPAREN);
                Expresion condExp = parseExpression();
                eat(TokenType.DPAREN);
                Statement trueStm = parseStatement();
                if (token.TokenType != TokenType.ELSE)
                {
                    return(new If(condExp, trueStm));
                }
                eat(TokenType.ELSE);
                Statement falseStm = parseStatement();
                return(new Else(condExp, trueStm, falseStm));

            case TokenType.WHILE:
                eat(TokenType.WHILE);
                eat(TokenType.IPAREN);
                Expresion x = parseExpression();
                eat(TokenType.DPAREN);
                Statement loopStm   = parseStatement();
                While     nodowhile = new While(x, loopStm);
                return(nodowhile);

            case TokenType.DO:
                eat(TokenType.DO);
                Statement loopStnm = parseStatement();

                eat(TokenType.WHILE);
                eat(TokenType.IPAREN);
                Expresion bulcleBody = parseExpression();
                eat(TokenType.DPAREN);
                eat(TokenType.PUNTOYCOMA);
                return(new Do(loopStnm, bulcleBody));

            case TokenType.FOR:
                entornoActual = new Entorno(entornoActual);     // Crera un nuevo entorno para el bucle for
                eat(TokenType.FOR);
                eat(TokenType.IPAREN);
                VarDecl   declararion = parseVarDecl();
                Expresion loopExpr    = parseExpression();
                eat(TokenType.PUNTOYCOMA);
                Asignacion incExpr = Asignar(bucleFor: true);
                eat(TokenType.DPAREN);
                Statement stm = parseStatement();
                entornoActual = entornoActual.Anterior;
                return(new For(declararion, loopExpr, incExpr, stm));

            case TokenType.ID:
                if (token.Lexeme == "System")
                {
                    eat(TokenType.ID);
                    eat(TokenType.PUNTO);
                    if (token.Lexeme != "out")
                    {
                        error("Se esperaba out");
                    }
                    eat(TokenType.ID);
                    eat(TokenType.PUNTO);
                    if (token.Lexeme != "println")
                    {
                        error("Se esperaba out");
                    }
                    eat(TokenType.ID);
                    eat(TokenType.IPAREN);
                    Expresion expresion = parseExpression();
                    eat(TokenType.DPAREN);
                    return(new Print(expresion));
                }
                return(Asignar());
            }

            switch (token.TokenType)
            {
            // int and boolean signals start of var declaration
            case TokenType.INT:
                return(parseVarDecl());

            case TokenType.BOOLEAN:
                return(parseVarDecl());

            case TokenType.FLOAT:
                return(parseVarDecl());

            case TokenType.STRING:
                return(parseVarDecl());

            case TokenType.CHAR:
                return(parseVarDecl());

            case TokenType.DOUBLE:
                return(parseVarDecl());
            }


            // statement type unknown
            error("Error no se esperaba " + token.TokenType);
            return(null);
        }
Beispiel #24
0
    public virtual void AddResolvedGhostStatement(Statement stmt)
    {
        BlockStmt          block      = stmt as BlockStmt;
        IfStmt             ifStmt     = stmt as IfStmt;
        AssertStmt         assertStmt = stmt as AssertStmt;
        AssignStmt         assignStmt = stmt as AssignStmt;
        CallStmt           callStmt   = stmt as CallStmt;
        VarDecl            varDecl    = stmt as VarDecl;
        CalcStmt           calcStmt   = stmt as CalcStmt;
        ForallStmt         forallStmt = stmt as ForallStmt;
        AssignSuchThatStmt existsStmt = stmt as AssignSuchThatStmt;

        if (block != null)
        {
            var oldRenamer = PushRename();
            block.Body.ForEach(AddGhostStatement);
            PopRename(oldRenamer);
        }
        else if (varDecl != null)
        {
            AddGhostVarDecl(varDecl.Name, varDecl.Type, varDecl.IsGhost);
        }
        else if (minVerify)
        {
            return;
        }
        else if (assignStmt != null)
        {
            ExprRhs expRhs = assignStmt.Rhs as ExprRhs;
            if (expRhs != null)
            {
                FieldSelectExpr fieldSelect = assignStmt.Lhs as FieldSelectExpr;
                RtlVar          destVar;
                if (fieldSelect != null)
                {
                    destVar = new RtlVar(GhostVar(fieldSelect.FieldName), true, fieldSelect.Type);
                }
                else
                {
                    destVar = AsVar(assignStmt.Lhs);
                    Util.Assert(destVar != null);
                }
                stmts.Add(new RtlGhostMove(new RtlVar[] { destVar },
                                           new RtlExp[] { GhostExpression(expRhs.Expr) }));
            }
            else
            {
                throw new Exception("not implemented: " + assignStmt.Rhs);
            }
        }
        else if (callStmt != null)
        {
            AddGhostCall(callStmt.Lhs.ConvertAll(AsVar), callStmt.Args,
                         dafnySpec.Compile_Method(callStmt.Method,
                                                  callStmt.TypeArgumentSubstitutions.ToDictionary(p => p.Key, p => AppType(p.Value))),
                         DafnySpec.IsHeapMethod(callStmt.Method));
            SymdiffLinearityPoint();
        }
        else if (ifStmt != null)
        {
            stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ") {",
                                               new RtlExp[] { GhostExpression(ifStmt.Guard) }));
            Indent();
            AddGhostStatement(ifStmt.Thn);
            Unindent();
            stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            if (ifStmt.Els != null)
            {
                stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ") {",
                                                   new RtlExp[] {
                    GhostExpression(new UnaryExpr(Bpl.Token.NoToken, UnaryExpr.Opcode.Not, ifStmt.Guard))
                }));
                Indent();
                AddGhostStatement(ifStmt.Els);
                Unindent();
                stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            }
        }
        else if (assertStmt != null)
        {
            stmts.Add(new RtlAssert(GhostExpression(assertStmt.Expr)));
        }
        else if (forallStmt != null)
        {
            var    oldRenamer = PushRename(forallStmt.BoundVars.Select(v => v.Name));
            RtlExp ens        = new RtlLiteral("true");
            foreach (var e in forallStmt.Ens)
            {
                ens = new RtlBinary("&&", ens, GhostExpression(e.E));
            }
            RtlExp range = (forallStmt.Range == null) ? new RtlLiteral("true")
                : GhostExpression(forallStmt.Range);
            List <RtlExp> wellFormed = GetTypeWellFormed(forallStmt.BoundVars.
                                                         Select(x => Tuple.Create(GhostVar(x.Name), x.IsGhost, x.Type)).ToList());
            wellFormed.ForEach(e => range = new RtlBinary("&&", e, range));
            ens = new RtlBinary("==>", range, ens);
            string vars = String.Join(", ", forallStmt.BoundVars.Select(x => GhostVar(x.Name) + ":" +
                                                                        TypeString(AppType(x.Type))));
            stmts.Add(new RtlGhostStmtComputed(s => "forall " + vars + "::(" + s.args[0] + ")",
                                               new List <RtlExp> {
                ens
            }));
            stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
            Indent();
            stmts.Add(PushForall());
            stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ")",
                                               new List <RtlExp> {
                range
            }));
            stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
            Indent();
            AddGhostStatement(forallStmt.Body);
            foreach (var e in forallStmt.Ens)
            {
                stmts.Add(new RtlAssert(GhostExpression(e.E)));
            }
            PopForall();
            Unindent();
            stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            Unindent();
            stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            PopRename(oldRenamer);
        }
        else if (existsStmt != null)
        {
            List <RtlStmt> assigns = new List <RtlStmt>();
            List <RtlVar>  tmps    = new List <RtlVar>();
            List <Tuple <string, bool, Type> > varTuples = new List <Tuple <string, bool, Type> >();
            var oldRenamer = PushRename();
            foreach (var lhs in existsStmt.Lhss)
            {
                IdentifierExpr idExp   = lhs.Resolved as IdentifierExpr;
                RtlVar         origVar = AsVar(lhs);
                AddRename(idExp.Name);
                RtlVar renameVar = AsVar(lhs);
                tmps.Add(renameVar);
                varTuples.Add(Tuple.Create(renameVar.ToString(), true, idExp.Type));
                assigns.Add(new RtlGhostMove(new RtlVar[] { origVar },
                                             new RtlExp[] { renameVar }));
            }
            string vars = String.Join(", ", tmps.Select(x => x.getName() + ":" + TypeString(AppType(x.type))));
            stmts.Add(new RtlGhostStmtComputed(s => "exists " + vars + "::(" + s.args[0] + ");",
                                               new List <RtlExp> {
                GetTypeWellFormedExp(varTuples.ToList(), "&&", GhostExpression(existsStmt.Expr))
            }));
            stmts.AddRange(assigns);
            PopRename(oldRenamer);
        }
        else if (calcStmt != null)
        {
            Util.Assert(calcStmt.Steps.Count == calcStmt.Hints.Count);
            CalcStmt.BinaryCalcOp binOp = calcStmt.Op as CalcStmt.BinaryCalcOp;
            bool isImply = binOp != null && binOp.Op == BinaryExpr.Opcode.Imp && calcStmt.Steps.Count > 0;
            if (isImply)
            {
                stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ")",
                                                   new RtlExp[] { GhostExpression(CalcStmt.Lhs(calcStmt.Steps[0])) }));
                stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
                Indent();
            }
            var stepCount = calcStmt.Hints.Last().Body.Count == 0 ? calcStmt.Steps.Count - 1 : calcStmt.Steps.Count;
            for (int i = 0; i < stepCount; i++)
            {
                if (calcStmt.Hints[i] == null)
                {
                    stmts.Add(new RtlAssert(GhostExpression(calcStmt.Steps[i])));
                }
                else
                {
                    stmts.Add(new RtlGhostStmtComputed(s => "forall::(" + s.args[0] + ")",
                                                       new List <RtlExp> {
                        GhostExpression(calcStmt.Steps[i])
                    }));
                    stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
                    Indent();
                    var dict = new Dictionary <string, RtlVar>();
                    stmts.Add(new RtlGhostStmtComputed(s => String.Concat(dict.Values.Select(
                                                                              x => "var " + x.x + ":" + TypeString(x.type) + ";")),
                                                       new RtlExp[0]));
                    forallVars.Add(dict);
                    AddGhostStatement(calcStmt.Hints[i]);
                    forallVars.RemoveAt(forallVars.Count - 1);
                    Unindent();
                    stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
                }
            }
            if (isImply)
            {
                Unindent();
                stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            }
        }
        else
        {
            throw new Exception("not implemented in ghost methods: " + stmt);
        }
    }
Beispiel #25
0
        public override AstNode VisitVarDecl(VarDecl ast)
        {
            var type = GetClrType(ast.Type.ResolvedType);
            m_ilgen.DeclareLocal(type);

            return ast;
        }
Beispiel #26
0
        public override AstNode VisitVarDecl(VarDecl ast)
        {
            if (CheckVariableDecl(ast))
            {
                //add to current variable table
                m_currentMethodVariables.Add(new VariableInfo() { Name = ast.VariableName.Value, Type = ast.Type.ResolvedType, Index = m_currentVariableIndex });
                ++m_currentVariableIndex;
            }

            return ast;
        }
 public void Visit(VarDecl varDecl)
 {
     Return(varDecl);
 }
Beispiel #28
0
        private void Visit(VarDecl item)
        {
            var type = this.symbolTable.Lookup(item.TypeNode.Value);

            symbolTable.Define(new VarSymbol(item.VarNode.Value, type));
        }