示例#1
0
        /// <summary>
        /// Reports function overload resolution error.
        /// </summary>
        internal static void ReportFunctionOverloadError(AST.MethodExpr functionExpr, EdmFunction functionType, List<TypeUsage> argTypes)
        {
            string strDelim = "";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(functionType.Name).Append("(");
            for (int i = 0 ; i < argTypes.Count ; i++)
            {
                sb.Append(strDelim);
                sb.Append(argTypes[i] != null ? argTypes[i].EdmType.FullName : "NULL");
                strDelim = ", ";
            }
            sb.Append(")");

            Func<object, object, object, string> formatString;
            if (TypeSemantics.IsAggregateFunction(functionType))
            {
                formatString = TypeHelpers.IsCanonicalFunction(functionType) ? 
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoCanonicalAggrFunctionOverloadMatch :
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoAggrFunctionOverloadMatch;
            }
            else
            {
                formatString = TypeHelpers.IsCanonicalFunction(functionType) ?
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoCanonicalFunctionOverloadMatch :
                                            (Func<object, object, object, string>)System.Data.Entity.Strings.NoFunctionOverloadMatch;
            }

            throw EntityUtil.EntitySqlError(functionExpr.ErrCtx.CommandText,
                                 formatString(functionType.NamespaceName, functionType.Name, sb.ToString()),
                                 functionExpr.ErrCtx.InputPosition,
                                 System.Data.Entity.Strings.CtxFunction(functionType.Name),
                                 false /* loadContextInfoFromResource */);
        }
示例#2
0
        private static AST.Clause DcgClauseToNormalClause (AST.DcgClause dcgClause)
        {
            var dcgGoalConverter = new AST.DcgGoalConverter ();

            var body = dcgClause.Body.Select (dcgGoalConverter.DcgGoalToNormalGoal).ToArray ();

            return new AST.Clause 
            {
                Head = new AST.Goal 
                {
                    PredicateName = dcgClause.Head.PredicateName, 
                    Arguments = new []
                                    {
                                        dcgClause.Head.Arguments,
                                        new [] // add 2 extra arguments, L0 and Ln
                                            {
                                                new Variable ("L0"),
                                                new Variable ("L" + dcgGoalConverter.DcgSubgoalCount)
                                            }
                                    }.SelectMany (a => a).ToArray ()
                },

                Body = body
            };
        }
示例#3
0
        private INode Emit(AST a, IGraph to)
        {
            String text = a.getText();
            int iType = a.Type;
            String type = parserpackage.GetTypeName(iType);
            NodeType currentNodeType = GetNodeType(type, to);
            INode currentNode = to.AddNode(currentNodeType);
            currentNode.SetAttribute("value", text);

            if (a.getNumberOfChildren() > 0)
            {
                List<AST> l = GetChildren(a);
                INode previousChild = null;
                foreach (AST current in l)
                {
                    INode childNode = Emit(current, to);
                    EdgeType childType = GetEdgeType("child", to);
                    to.AddEdge(childType, currentNode, childNode);

                    if (previousChild != null)
                    {
                        EdgeType nextType = GetEdgeType("next", to);
                        to.AddEdge(nextType, previousChild, childNode);
                    }
                    previousChild = childNode;
                }
            }
            return currentNode;
        }
        public override bool VisitFunctionDecl(AST.Function function)
        {
            if (AlreadyVisited(function))
                return false;

            if (function.IsAmbiguous)
                return false;

            var overloads = function.Namespace.GetFunctionOverloads(function);

            foreach (var overload in overloads)
            {
                if (function.OperatorKind == CXXOperatorKind.Conversion)
                    continue;

                if (overload == function) continue;

                if (overload.Ignore) continue;

                if (!CheckDefaultParameters(function, overload))
                    continue;

                if (!CheckConstness(function, overload))
                    continue;

                function.IsAmbiguous = true;
                overload.IsAmbiguous = true;
            }

            if (function.IsAmbiguous)
                Driver.Diagnostics.EmitWarning("Found ambiguous overload: {0}",
                    function.QualifiedOriginalName);

            return true;
        }
示例#5
0
		public virtual void resetState()
		{
			traceDepth  = 0;
			returnAST	= null;
			retTree_	= null;
			inputState.reset();
		}
示例#6
0
        public override void Visit(AST.MethodDeclNode node)
        {
            MethodBeingVisited = ClassBeingVisited.Methods.Lookup(node.methodName.name);

            if (node.paramDeclList != null)
                foreach (AST.ParamDeclNode paramDecl in node.paramDeclList)
                    paramDecl.Accept(this);

            if (node.variableDeclList != null)
                foreach (AST.VariableDeclNode variableDecl in node.variableDeclList)
                    variableDecl.Accept(this);

            if (node.statementList != null)
            {
                var reverseList = node.statementList.statementList;
                reverseList.Reverse();

                HashSet<AST.IdentifierNode> afterLiveness = new HashSet<AST.IdentifierNode>();

                foreach (AST.StatementNode statement in reverseList)
                {
                    m_R.Clear();
                    m_W.Clear();
                    statement.Accept(this);
                    afterLiveness.ExceptWith(m_W);
                    afterLiveness.UnionWith(m_R);

                    m_livenessAtNode[statement] = new HashSet<AST.IdentifierNode>(afterLiveness);
                }
            }
        }
示例#7
0
        public FunctionOutput<string>[] FastReplace(Excel.Range com, DAG dag, InputSample original, InputSample sample, AST.Address[] outputs, bool replace_original)
        {
            FunctionOutput<string>[] fo_arr;
            if (!_d.TryGetValue(sample, out fo_arr))
            {
                // replace the COM value
                ReplaceExcelRange(com, sample);

                // initialize array
                fo_arr = new FunctionOutput<string>[outputs.Length];

                // grab all outputs
                for (var k = 0; k < outputs.Length; k++)
                {
                    // save the output
                    fo_arr[k] = new FunctionOutput<string>(dag.readCOMValueAtAddress(outputs[k]), sample.GetExcludes());
                }

                // Add function values to cache
                // Don't care about return value
                _d.Add(sample, fo_arr);

                // restore the COM value
                if (replace_original)
                {
                    ReplaceExcelRange(com, original);
                }
            }
            return fo_arr;
        }
        public override bool VisitFunctionDecl(AST.Function function)
        {
            if (!VisitDeclaration(function))
                return false;

            if (function.IsAmbiguous)
                return false;

            var overloads = function.Namespace.GetOverloads(function);

            foreach (var overload in overloads)
            {
                if (function.OperatorKind == CXXOperatorKind.Conversion)
                    continue;
                if (function.OperatorKind == CXXOperatorKind.ExplicitConversion)
                    continue;

                if (overload == function) continue;

                if (!overload.IsGenerated) continue;

                if (CheckConstnessForAmbiguity(function, overload) ||
                    CheckDefaultParametersForAmbiguity(function, overload))
                {
                    function.IsAmbiguous = true;
                    overload.IsAmbiguous = true;
                }
            }

            if (function.IsAmbiguous)
                Driver.Diagnostics.Debug("Found ambiguous overload: {0}",
                    function.QualifiedOriginalName);

            return true;
        }
示例#9
0
 public LogEntry(AnalysisType procedure,
     string filename,
     AST.Address address,
     string original_value,
     string erroneous_value,
     double output_error_magnitude,
     double num_input_error_magnitude,
     double str_input_error_magnitude,
     bool was_flagged,
     bool was_error,
     double significance,
     double threshold)
 {
     _filename = filename;
     _procedure = procedure;
     _address = address;
     _original_value = original_value;
     _erroneous_value = erroneous_value;
     _output_error_magnitude = output_error_magnitude;
     _num_input_error_magnitude = num_input_error_magnitude;
     _str_input_error_magnitude = str_input_error_magnitude;
     _was_flagged = was_flagged;
     _was_error = was_error;
     _significance = significance;
     _threshold = threshold;
 }
示例#10
0
        /// <summary>
        /// Compiles AST clauses into an executable program understood by the <see cref="Runtime.Engine"/> .
        /// The input clauses are not required to be in any particular order.
        /// </summary>
        public static Compiled.Program Compile (AST.Program program)
        {
            var allClauses = new []
                                 {
                                     program.DcgClauses.Select (DcgClauseToNormalClause),
                                     program.Clauses
                                 }.SelectMany (a => a);

            var clauseGroups = allClauses.GroupBy (c => Tuple.Create (c.Head.PredicateName, c.Head.Arguments.Length), c => c).ToArray ();

            var prologPredicates = clauseGroups.ToDictionary (p => p.Key, p => new Compiled.PrologPredicate {Name = p.Key.Item1});

            // Dictionary is not covariant so it takes a new dictionary to get a dictionary of base types (Predicate).
            var predicates = prologPredicates.ToDictionary (p => p.Key, CastPrologPredicateToBasePredicate); 

            if (program.ExternalPredicates != null)
            {
                foreach (var externalPredicate in program.ExternalPredicates)
                {
                    predicates.Add (Tuple.Create(externalPredicate.Name, externalPredicate.Arity), new Compiled.ExternalPredicate (externalPredicate.Name));
                }
            }

            foreach (var clauseGroup in clauseGroups)
            {
                var prologPredicate = prologPredicates [clauseGroup.Key];

                prologPredicate.Clauses = clauseGroup.Select (c => new Compiled.Clause {Head = new Compiled.Goal {Predicate = prologPredicate, Arguments = c.Head.Arguments},
                                                                                      Body = Compile (c.Body, predicates)}).ToArray ();
            }

            return new Compiled.Program (predicates);
        }
示例#11
0
        public CSharpGen(AST.AstNode topNode, string name_space)
        {
            if (!(topNode is AST.GrammarFile))
                throw new Exception("Unable to generate.");

            this.gNamespace = name_space;
            this.grammar = topNode as AST.GrammarFile;
        }
示例#12
0
		protected internal virtual void  match(AST t, int ttype)
		{
			//System.out.println("match("+ttype+"); cursor is "+t);
			if (t == null || t == ASTNULL || t.Type != ttype)
			{
				throw new MismatchedTokenException(getTokenNames(), t, ttype, false);
			}
		}
示例#13
0
文件: Symbol.cs 项目: chenzuo/blue
        // Used by a labelstatement
        public LabelEntry(string stName, AST.LabelStatement node)
        {
            Debug.Assert(node != null);
            Debug.Assert(stName != null);

            m_strName = stName;
            m_node = node;
        }
示例#14
0
 public void Nested_Content_Of_TagNode_As_Raw()
 {
     const string TEMPLATE = @"<c:out>Hello <c:out>${Stranger}</c:out></c:out>";
     var formatter = new Formatter(TEMPLATE).Parse();
     var ast = new AST(formatter.ParsedTemplate, AST.Options.DontTrackContext);
     var raw = (((TagNode)ast.Nodes[0]).Raw);
     Assert.That(raw, Is.EqualTo("Hello <c:out>${Stranger}</c:out>"));
 }
示例#15
0
 internal override void Accept(AST ast)
 {
     ast.nodes.ForEach(node =>
     {
         node.isResultRequired = false;
         node.Visit(this);
     });
 }
示例#16
0
        private static IEnumerable <Dictionary <string, Runtime.IConcreteValue>> CallConcat (AST.Goal makeGoal)
        {
            var program = Compiler.Compile (new AST.Program {ExternalPredicates = Helper.GetConcatDeclaration ()});

            program.SetExternalPredicateCallbacks (Helper.GetConcat ());

            return Helper.GetSolutions (makeGoal, program);
        }
 public override Tuple<AST.Env, List<Tuple<AST.Env, AST.ExternDecln>>> GetExternDecln(AST.Env env)
 {
     Tuple<AST.Env, AST.FuncDef> r_def = GetFuncDef(env);
     return new Tuple<AST.Env, List<Tuple<AST.Env, AST.ExternDecln>>>(
         r_def.Item1,
         new List<Tuple<AST.Env, AST.ExternDecln>>() { Tuple.Create(r_def.Item1, (AST.ExternDecln)r_def.Item2) }
     );
 }
示例#18
0
        public void AddAccess(AST.Identifier variable)
        {
            if (!this.Accessing.ContainsKey(variable.Name))
            {
                this.Accessing[variable.Name] = new List<AST.Identifier>();
            }

            this.Accessing[variable.Name].Add(variable);
        }
示例#19
0
 public void Combined_Content_Of_TagNode_As_Raw()
 {
     const string TEMPLATE = @"<c:out>Hello ${Stranger}</c:out>";
     var formatter = new Formatter(TEMPLATE).Parse();
     var ast = new AST(formatter.ParsedTemplate, AST.Options.DontTrackContext);
     var expected = new AST()
         .Add(new TagNode("c", "out").Add(new TextNode("Hello world")));
     var raw = (((TagNode)ast.Nodes[0]).Raw);
     Assert.That(raw, Is.EqualTo("Hello ${Stranger}"));
 }
示例#20
0
        public Declaration(Position position, string name, SymbolKind kind, AST.Type type)
            : base(position)
        {
            _name = name;

            _kind = kind;

            _type = type;
            _type.Parent = this;
        }
示例#21
0
文件: Utility.cs 项目: etosch/parcel
 public static AST.Address makeAddressForA1(string col, int row, AST.Env env)
 {
     return AST.Address.fromA1(
         row,
         col,
         env.WorksheetName,
         env.WorkbookName,
         env.Path
     );
 }
示例#22
0
        public AST root; // current root of tree

        #endregion Fields

        #region Methods

        /*Make sure that child is the last sibling */
        public void advanceChildToEnd()
        {
            if (child != null)
            {
                while (child.getNextSibling() != null)
                {
                    child = child.getNextSibling();
                }
            }
        }
示例#23
0
        public override Tuple<AST.Env, List<Tuple<AST.Env, AST.ExternDecln>>> GetExternDecln(AST.Env env) {
            Tuple<AST.Env, List<Tuple<AST.Env, AST.Decln>>> r_declns = GetDeclns(env);
            env = r_declns.Item1;

            List<Tuple<AST.Env, AST.ExternDecln>> declns = r_declns
                .Item2
                .ConvertAll(_ => new Tuple<AST.Env, AST.ExternDecln>(_.Item1, _.Item2));

            return new Tuple<AST.Env, List<Tuple<AST.Env, AST.ExternDecln>>>(env, declns);
        }
示例#24
0
 public Dictionary<AST.Address, HashSet<int>> AllRefDistances(AST.Address from)
 {
     if (!_matrix.ContainsKey(from))
     {
         return new Dictionary<AST.Address, HashSet<int>>();
     } else
     {
         return _matrix[from];
     }
 }
示例#25
0
					public static bool PeekAndParse(CharStream stream, out AST.INode expression)
					{
						if (stream.PeekNext() == '(' || Primary.Peek(stream))
						{
							expression = Parenthesis.Parse(stream);
							return true;
						}

						expression = null;
						return false;
					}
示例#26
0
文件: Index.cs 项目: GlenDC/L20n.cs
				public static bool PeekAndParse(CharStream stream, out AST.INode index)
				{
					if (stream.PeekNext() != '[')
					{
						index = null;
						return false;
					}
					
					index = Index.Parse(stream);
					return true;
				}
示例#27
0
				public static bool PeekAndParse(CharStream stream, out AST.Attributes.Item item)
				{
					if (KeyValuePair.Peek(stream))
					{
						item = KeyValuePair.Parse(stream);
						return true;
					}
					
					item = null;
					return false;
				}
示例#28
0
        public void SaveVariableToMemorySpace()
        {
            MemorySpaceNodeListCache cache = new MemorySpaceNodeListCache();

            AST root = new AST();
            MemorySpace memorySpace = new MemorySpace("globals", root, new Scope(Scope.ScopeType.MAIN_SCOPE, "blah"), cache);
            ReturnValue val = new ReturnValue(5.9f);
            memorySpace.setValue("x", val);
            Assert.AreEqual(ReturnValueType.NUMBER, memorySpace.getValue("x").getReturnValueType());
            Assert.AreEqual(5.9f, memorySpace.getValue("x").NumberValue);
        }
示例#29
0
        public void SaveVariableToMemorySpace()
        {
            MemorySpaceNodeListCache cache = new MemorySpaceNodeListCache();

            AST root = new AST();
            MemorySpace memorySpace = new MemorySpace("globals", root, new Scope(Scope.ScopeType.MAIN_SCOPE, "blah"), cache);
            object val = 5.9f;
            memorySpace.setValue("x", val);
            Assert.AreEqual(typeof(float), memorySpace.getValue("x").GetType());
            Assert.AreEqual(5.9f, (float)memorySpace.getValue("x"));
        }
示例#30
0
文件: Value.cs 项目: GlenDC/L20n.cs
				public static bool PeekAndParse(
					CharStream stream, out AST.INode value)
				{
					if (StringValue.PeekAndParse(stream, out value))
						return true;
					
					if (HashValue.PeekAndParse(stream, out value))
						return true;

					return false;
				}
示例#31
0
 public void visit_boolNode(AST node)
 {
     node.builtinType = Utils.Type.BOOLEAN;
 }
示例#32
0
        public AST parse()
        {
            AST expr = this.expr();

            return(expr);
        }
示例#33
0
 public void Initialize(AST root, Func <ExpressionNode, List <TypeNode>, TypeNode> dispatcher)
 {
     _functions = root.Functions;
     _getType   = dispatcher;
 }
示例#34
0
 public FnDefAST(string fName, List <string> formalParams, AST body)
 {
     Value        = Operator = fName;
     FormalParams = formalParams;
     Body         = body;
 }
示例#35
0
        public object visit_opNode(AST node)
        {
            TokenType type = node.token.getType();

            if (type == TokenType.PLUS)
            {
                if (node.builtinType == Utils.Type.INTEGER)
                {
                    return((int)this.visit(node.left) + (int)this.visit(node.right));
                }
                else if (node.builtinType == Utils.Type.STRING)
                {
                    return((string)this.visit(node.left) + (string)this.visit(node.right));
                }
            }
            else if (type == TokenType.MINUS)
            {
                return((int)this.visit(node.left) - (int)this.visit(node.right));
            }
            else if (type == TokenType.MULT)
            {
                return((int)this.visit(node.left) * (int)this.visit(node.right));
            }
            else if (type == TokenType.DIV)
            {
                int left  = (int)this.visit(node.left);
                int right = (int)this.visit(node.right);
                if (right == 0)
                {
                    throw new DivideByZeroException();
                }
                return((int)this.visit(node.left) / (int)this.visit(node.right));
            }
            else if (type == TokenType.EQUALS)
            {
                object left  = this.visit(node.left);
                object right = this.visit(node.right);
                if (node.left.builtinType == Utils.Type.BOOLEAN)
                {
                    return((bool)left == (bool)right);
                }
                else if (node.left.builtinType == Utils.Type.INTEGER)
                {
                    return((int)left == (int)right);
                }
                else if (node.left.builtinType == Utils.Type.STRING)
                {
                    return((string)left == (string)right);
                }
            }
            else if (type == TokenType.LESSTHAN)
            {
                if (node.left.builtinType == Utils.Type.BOOLEAN)
                {
                    int boolValueLeft  = boolToInt((bool)this.visit(node.left));
                    int boolValueRight = boolToInt((bool)this.visit(node.right));
                    return(boolValueLeft < boolValueRight);
                }
                else if (node.left.builtinType == Utils.Type.INTEGER)
                {
                    return((int)this.visit(node.left) < (int)this.visit(node.right));
                }
                else if (node.left.builtinType == Utils.Type.STRING)
                {
                    if (String.Compare((string)this.visit(node.left), (string)this.visit(node.right)) < 0)
                    {
                        return(true);
                    }
                    return(false);
                }
            }
            else if (type == TokenType.AND)
            {
                return((bool)this.visit(node.left) && (bool)(this.visit(node.right)));
            }
            return(null);
        }
示例#36
0
 public UnaryOp(Token op, AST right)
 {
     this.expr = right;
     this.op   = op;
 }
示例#37
0
 public BinOp(AST left, Token op, AST right)
 {
     this.left  = left;
     this.right = right;
     this.op    = op;
 }
示例#38
0
 internal InstallStatus(AST <Program> program, InstallKind status)
 {
     Program = program;
     Status  = status;
 }
        public static AST Parse(Token[] tokens)
        {
            int index = 0;

            Node Walk()
            {
                Token token = tokens[index];

                if (token is Number)
                {
                    return(new NumberLiteral {
                        Value = ((Number)tokens[index++]).Value
                    });
                }

                if (token is Tokens.String)
                {
                    return(new StringLiteral {
                        Value = ((Tokens.String)tokens[index++]).Value
                    });
                }

                if (token is Parenthesis && ((Parenthesis)token).Value == Parenthesis.Type.Start)
                {
                    token = tokens[++index];

                    CallExpression callExpression = new CallExpression
                    {
                        Name       = ((Name)token).Value, // assuming next token is a name
                        Parameters = new List <Node>()
                    };

                    token = tokens[++index];

                    while (!(token is Parenthesis parenthesis) || parenthesis.Value != Parenthesis.Type.End)
                    {
                        callExpression.Parameters.Add(Walk());

                        token = tokens[index];
                    }

                    index++;

                    return(callExpression);
                }

                throw new Exception("Unmanaged token");
            }

            AST ast = new AST
            {
                Body = new List <Node>()
            };

            while (index < tokens.Length)
            {
                ast.Body.Add(Walk());
            }

            return(ast);
        }
示例#40
0
 public object visit_strNode(AST node)
 {
     return(node.token.getLexeme());
 }
示例#41
0
 public Program(string name, AST block)
 {
     Name       = name;
     this.block = (Block)block;
 }
示例#42
0
 public object  visit_numNode(AST node)
 {
     return(Int32.Parse(node.token.getLexeme()));
 }
示例#43
0
 public Assign(AST left, Token op, AST right)
 {
     this.left  = left;
     this.right = right;
     this.op    = op;
 }
示例#44
0
文件: Parser.cs 项目: Stu042/SimpleC
        BlockAST Statments(int startIndent = 0)
        {
            List <AST> stmts    = new List <AST>();
            Token      firstTok = tokens.current;

            do
            {
                string found = GetStmntMatch(tokens);
                switch (found)
                {
                case "Command": {
                    AST stmtAST = null;
                    switch (tokens.curTokenType)
                    {
                    case TokenType.Return:
                        Token   retTok = tokens.current;
                        ExprAST expAST = ParseExpr();
                        stmtAST = new RetCmdAST(retTok, expAST);
                        break;

                    default:
                        ShowError("Unknown command", tokens.current);
                        break;
                    }
                    if (stmtAST != null)
                    {
                        stmts.Add(stmtAST);
                    }
                    break;
                }

                case "Main": {
                    TypeAST  typeAST = new TypeAST(tokens.current);
                    Token    mainTok = tokens.Next();
                    ArgAST[] argsAST = ParseArgs();
                    symbols.AddParent(typeAST, mainTok.value, argsAST);
                    BlockAST stmtAST = Statments(startIndent + 1);
                    symbols.RemParent();
                    AST functAST = new FuncDefAST(mainTok, typeAST, argsAST, stmtAST);
                    stmts.Add(functAST);
                    break;
                }

                case "Function": {
                    TypeAST  typeAST = new TypeAST(tokens.current);
                    Token    instTok = tokens.Next();
                    ArgAST[] argsAST = ParseArgs();
                    symbols.AddParent(typeAST, instTok.value, argsAST);
                    BlockAST stmtAST = Statments(startIndent + 1);
                    symbols.RemParent();
                    AST functAST = new FuncDefAST(instTok, typeAST, argsAST, stmtAST);
                    stmts.Add(functAST);
                    break;
                }

                case "ObjectDef": {                             // TokenType.Identifier, TokenType.Colon
                    TypeAST typeAST = new TypeAST(tokens.current);
                    tokens.Next();
                    symbols.AddParent(typeAST, "", null);
                    tokens.Next();
                    BlockAST stmtAST = Statments(startIndent + 1);
                    symbols.RemParent();
                    ObjDefAST odAST = new ObjDefAST(tokens.current, stmtAST);
                    stmts.Add(odAST);
                    break;
                }

                case "SimpleObjectInst": {                          // TokenType.AllTypes, TokenType.Identifier
                    TypeAST typeAST = new TypeAST(tokens.current);
                    tokens.Next();
                    symbols.Add(typeAST, tokens.current.value, null);
                    ObjInstAST odAST = new ObjInstAST(tokens.current, typeAST, null);
                    stmts.Add(odAST);
                    break;
                }

                case "ObjectInst": {
                    TypeAST typeAST = new TypeAST(tokens.current);
                    tokens.Next();
                    symbols.Add(typeAST, tokens.current.value, null);
                    ObjInstAST odAST = new ObjInstAST(tokens.current, typeAST, null);
                    stmts.Add(odAST);
                    break;
                }

                case "SimpleObjectInstAssigned": {
                    TypeAST typeAST = new TypeAST(tokens.current);
                    Token   instTok = tokens.Next();
                    symbols.Add(typeAST, instTok.value, null);
                    tokens.Next();
                    NumAST     numAST = new NumAST(tokens.current, tokens.current.value, tokens.curTokenType);
                    ObjInstAST odAST  = new ObjInstAST(instTok, typeAST, numAST);
                    stmts.Add(odAST);
                    break;
                }

                case "ObjectInstAssigned": {
                    TypeAST typeAST = new TypeAST(tokens.current);
                    Token   instTok = tokens.Next();
                    symbols.Add(typeAST, instTok.value, null);
                    tokens.Next();
                    NumAST     numAST = new NumAST(tokens.current, tokens.current.value, tokens.curTokenType);
                    ObjInstAST odAST  = new ObjInstAST(instTok, typeAST, numAST);
                    stmts.Add(odAST);
                    break;
                }

                default:
                    ShowError("Unable to parse statement", tokens.current);
                    break;
                }
            } while (tokens.Remaining() > 0);
            return(new BlockAST(firstTok, stmts.ToArray()));
        }
示例#45
0
 public object run(AST program)
 {
     return(this.visit(program));
 }
示例#46
0
文件: Parser.cs 项目: Stu042/SimpleC
 public object DoForAST(AST ast, object options = null)
 {
     ConsoleEx.WriteLine("{0}(AST)", ConsoleColor.DarkBlue);
     return(options);
 }
示例#47
0
        public void visit_assignNode(AST node)
        {
            string name = node.left.token.getLexeme();

            memory[name] = this.visit(node.right);
        }
示例#48
0
 public BinOp(AST l, Token op, AST r)
 {
     left = l; right = r; oper = op;
 }
示例#49
0
 public Assign(Var l, Token op, AST r)
 {
     left = l; right = r; oper = op;
 }
示例#50
0
        public BatchExeResult Execute(string filename, out string expected, out string current)
        {
            BatchExeResult result   = BatchExeResult.SolcError;
            string         filePath = Path.Combine(testDirectory, filename);

            // compile the program
            SolidityCompiler compiler       = new SolidityCompiler();
            CompilerOutput   compilerOutput = compiler.Compile(solcPath, filePath);

            if (compilerOutput.ContainsError())
            {
                compilerOutput.PrintErrorsToConsole();
                throw new SystemException("Compilation Error");
            }

            // build the Solidity AST from solc output
            AST solidityAST = new AST(compilerOutput, Path.GetDirectoryName(filePath));

            // read the corral configuration from Json
            string configJsonPath            = Path.Combine(configDirectory, Path.GetFileNameWithoutExtension(filename) + ".json");
            string jsonString                = File.ReadAllText(configJsonPath);
            CorralConfiguration corralConfig = JsonConvert.DeserializeObject <CorralConfiguration>(jsonString);

            // translate Solidity to Boogie
            try
            {
                BoogieTranslator translator = new BoogieTranslator();
                var translatorFlags         = new TranslatorFlags();
                translatorFlags.GenerateInlineAttributes = false;
                if (corralConfig.TranslatorOptions != null)
                {
                    ParseTranslatorFlags(translatorFlags, corralConfig.TranslatorOptions);
                }

                BoogieAST boogieAST = translator.Translate(solidityAST, new HashSet <Tuple <string, string> >(), translatorFlags);

                // dump the Boogie program to a file
                using (var outWriter = new StreamWriter(outFile))
                {
                    outWriter.WriteLine(boogieAST.GetRoot());
                }
            } catch (Exception e)
            {
                Console.WriteLine($"VeriSol translation error: {e.Message}");
                result   = BatchExeResult.SolToBoogieError;
                expected = current = null;
                return(result);
            }

            // read the corral configuration from Json
            //string configJsonPath = Path.Combine(configDirectory, Path.GetFileNameWithoutExtension(filename) + ".json");
            //string jsonString = File.ReadAllText(configJsonPath);
            //CorralConfiguration corralConfig = JsonConvert.DeserializeObject<CorralConfiguration>(jsonString);

            string corralOutput = RunCorral(corralConfig);

            expected = corralConfig.ExpectedResult;
            current  = corralOutput;
            result   = CompareCorralOutput(corralConfig.ExpectedResult, corralOutput);
            return(result);
        }
示例#51
0
 public UnaryOp(Token op, AST r)
 {
     right = r; oper = op;
 }
示例#52
0
    public static void Main(string[] args)
    {
        string filename   = null;
        bool   printAST   = false;
        bool   printASTtc = false;

        foreach (string arg in args)
        {
            if (arg.StartsWith("-"))
            {
                switch (arg)
                {
                case "-ast":
                    printAST = true;  break;

                case "-tc":
                    printASTtc = true;  break;

                default:
                    Console.WriteLine("Unknown option {0}, ignored", arg);
                    break;
                }
            }
            else
            {
                if (filename != null)
                {
                    Usage();
                }
                filename = arg;
            }
        }
        // require exactly one input file to be provided
        if (filename == null)
        {
            Usage();
        }
        // require a filename suffix of .cb or .cs
        if (!filename.EndsWith(".cb") && !filename.EndsWith(".cs"))
        {
            Usage();
        }

        AST tree = DoParse(filename);

        if (tree == null)
        {
            Console.WriteLine("\n-- no tree constructed");
            return;
        }

        if (printAST)
        {
            PrVisitor printVisitor = new PrVisitor();
            tree.Accept(printVisitor);
        }

        int numErrors = 0;

        // perform typechecking ...
        TcVisitor typeCheckVisitor = new TcVisitor();

        tree.Accept(typeCheckVisitor);
        numErrors = typeCheckVisitor.NumErrors;

        if (printASTtc)
        {
            PrVisitor printVisitor = new PrVisitor();
            tree.Accept(printVisitor);    // print AST with datatype annotations
        }

        // generate intermediate code

        if (numErrors > 0)
        {
            Console.WriteLine("\n{0} errors reported, compilation halted", numErrors);
            return;
        }
    }
        /// <summary>
        /// Generates aggregate function mapping.
        /// </summary>
        /// <param name="aggregate">Aggrrgate function model.</param>
        /// <param name="functionsGroup">Functions region.</param>
        private void BuildAggregateFunction(AggregateFunctionModel aggregate, Func <RegionGroup> functionsGroup)
        {
            // generation sample:

            /*
             * [Sql.Function("test_avg", ArgIndices = new []{ 1 }, ServerSideOnly = true, IsAggregate = true)]
             * public static double? TestAvg<TSource>(this IEnumerable<TSource> src, Expression<Func<TSource, double>> value)
             * {
             *     throw new InvalidOperationException("error message here");
             * }
             */
            // where
            // - src/TSource: any aggregated table-like source
            // - value: actual aggregated value (value selector from source)

            var method = DefineMethod(
                functionsGroup().New(aggregate.Method.Name).Methods(false),
                aggregate.Method);

            // aggregates cannot be used outside of query context, so we throw exception from method
            var body = method
                       .Body()
                       .Append(
                AST.Throw(AST.New(
                              WellKnownTypes.System.InvalidOperationException,
                              AST.Constant(EXCEPTION_QUERY_ONLY_ASSOCATION_CALL, true))));

            // build mappings
            _metadataBuilder.BuildFunctionMetadata(aggregate.Metadata, method);

            var source = AST.TypeParameter(AST.Name(AGGREGATE_RECORD_TYPE));

            method.TypeParameter(source);

            method.Returns(aggregate.ReturnType);

            // define parameters
            // aggregate has at least one parameter - collection of aggregated values
            // and optionally could have one or more additional scalar parameters
            var sourceParam = AST.Parameter(
                WellKnownTypes.System.Collections.Generic.IEnumerable(source),
                AST.Name(AGGREGATE_SOURCE_PARAMETER),
                CodeParameterDirection.In);

            method.Parameter(sourceParam);

            if (aggregate.Parameters.Count > 0)
            {
                for (var i = 0; i < aggregate.Parameters.Count; i++)
                {
                    var param         = aggregate.Parameters[i];
                    var parameterType = param.Parameter.Type;

                    // scalar parameters have following type:
                    // Expression<Func<TSource, param_type>>
                    // which allows user to specify aggregated value(s) selection from source record
                    parameterType = WellKnownTypes.System.Linq.Expressions.Expression(
                        WellKnownTypes.System.Func(parameterType, source));

                    var p = AST.Parameter(parameterType, AST.Name(param.Parameter.Name, null, i + 1), CodeParameterDirection.In);
                    method.Parameter(p);

                    if (param.Parameter.Description != null)
                    {
                        method.XmlComment().Parameter(p.Name, param.Parameter.Description);
                    }
                }
            }
        }
示例#54
0
 public void visit_assertNode(AST node)
 {
     Console.WriteLine((bool)this.visit(node.left));
 }
示例#55
0
        public AST node;         // handles parsing and treeparsing

        public NoViableAltException(AST t) : base("NoViableAlt", "<AST>", -1, -1)
        {
            node = t;
        }
示例#56
0
 public BinaryOpAST(AST left, string op, AST right)
 {
     Operator = op;
     Children.Add(left);
     Children.Add(right);
 }
示例#57
0
        private void ParseAst(AST ast, string sp)
        {
            if (ast == null)
            {
                return;
            }

            //_logView.LogStr("JS->" + sp + ast.ToString() + "\t\t" + ast.GetType().Name);

            if (ast is Function)
            {
                Function func = ast as Function;

                JSMethodItem methodItem = new JSMethodItem(func.func_obj.name + "()", _fileItem);
                //methodItem.Icon = Properties.Resources.JSMethodItem;
                methodItem.MethodInfo = ast;

                _fileItem.Methods.Add(methodItem);
                _projectBrowser.AddLookup(methodItem, methodItem.GetID(), _invert);

                _currentMethodStack.Insert(0, func.func_obj.name);

                ParseAstList(func.func_obj.body.elems, sp + "  ");

                _currentMethodStack.RemoveAt(0);
            }
            else if (ast is Assign)
            {
                Assign ass = ast as Assign;

                if ((ass.left is Binary) && (ass.right is FunctionExpression))
                {
                    // Can't see useful properties on this, except ToString().
                    string[] parts = ass.left.ToString().Split('.');
                    if (parts.Length > 2 && parts[1] == "prototype")
                    {
                        // We've found a class method, prototype style.
                        string className  = parts[0];
                        string methodName = parts[2];

                        AddMethod(className, methodName, ass);
                    }
                    else if (parts.Length > 2 && parts[2] == "This")
                    {
                        string className  = _currentMethodStack[0];
                        string methodName = parts[3];

                        AddMethod(className, methodName, ass);
                    }
                }
            }
            else if (ast is Expression)
            {
                Expression expr = ast as Expression;
                ParseAstList(expr.exprs, sp + "  ");
            }
            else if (ast is FunctionExpression)
            {
            }
            else if (ast is If)
            {
                If expr = ast as If;
                ParseAst(expr.true_stm, sp + "t  ");
                ParseAst(expr.false_stm, sp + "f  ");
            }
            else if (ast is Block)
            {
                Block block = ast as Block;
                ParseAstList(block.elems, sp + "  ");
            }
        }
示例#58
0
 public void visit_numNode(AST node)
 {
     node.builtinType = Utils.Type.INTEGER;
 }
 public static string Generate(AST ast)
 {
     return(ast.Transform(null).Generate());
 }
示例#60
0
 public void visit_printNode(AST node)
 {
     Console.Write(this.visit(node.left).ToString());
 }