Example #1
0
        public void visit(FunctionExpression that)
        {
            // let the arguments resolve their types
            foreach (Expression argument in that.Arguments)
            {
                argument.visit(this);
            }

            // mangle the parameter list so as to be able to look up the mangled symbol
            System.Text.StringBuilder mangled = new System.Text.StringBuilder(64);
            that.Encode(mangled);
            string name = mangled.ToString();

            // look up the function declaration
            Declaration declaration = _symbols.Lookup(name);

            if (declaration == null)
            {
                throw new CheckerError(that.Position, "Unknown function name '" + Demangler.Decode(name) + "' in function call");
            }

            // check that the symbol is actually a function
            switch (declaration.Kind)
            {
            case SymbolKind.Constant:
                throw new CheckerError(that.Position, "Cannot call constant");

            case SymbolKind.Function:
                break;

            case SymbolKind.Parameter:
                throw new CheckerError(that.Position, "Cannot call parameter");

            case SymbolKind.Variable:
                throw new CheckerError(that.Position, "Cannot call variable");

            default:
                throw new CheckerError(declaration.Position, "Unknown symbol kind: " + declaration.Kind.ToString());
            }

            // check that the number of arguments match the number of parameters
            FunctionDeclaration function = (FunctionDeclaration)declaration;

            if (that.Arguments.Length != function.Parameters.Length)
            {
                throw new CheckerError(that.Position, "Incorrect number of parameters in function call");
            }

            // check that the argument types match the parameter types
            for (int i = 0; i < that.Arguments.Length; i++)
            {
                if (that.Arguments[i].Type.Kind != function.Parameters[i].Type.Kind)
                {
                    throw new CheckerError(that.Arguments[i].Position, "Type mismatch in argument to function");
                }
            }

            that.Type = declaration.Type;
        }
        public void FunctionExpressionProducesFunctionWithBody()
        {
            var f = new FunctionExpression()
                .Parameters(new List<IdentifierExpression>())
                .Do(new List<Statement> { JS.Return() });

            Assert.AreEqual("function(){return;};", f.ToString());
        }
        public void TestAddDoubleAndInt()
        {
            var f = new FunctionExpression("+", new IExpression[] { new DoubleValue(7.5), new IntegerValue(2) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(9.5, r, "7.5+2");
        }
Example #4
0
        private IdentifierExpression QueueInsertion(FunctionExpression function, AphidExpression parent, AphidExpression after)
        {
            var id = new IdentifierExpression(NextVarId());

            _insertions.Add(id.Identifier, function);

            return(id);
        }
 protected override Expression VisitFunction(FunctionExpression func)
 {
     if (this.dbContext.ExpressionBuilder.IsRowsAffectedExpressions(func))
     {
         return(Expression.Property(this.executor, "RowsAffected"));
     }
     return(base.VisitFunction(func));
 }
        public void SumEmptyObjectArray()
        {
            var ar = new object[] { };
            var f  = new FunctionExpression("sum", new ObjectValue(ar));

            var c = new RootContext();
            var r = f.Evaluate(c);
        }
        public void TestFunctionCallWithContextNoArg()
        {
            var fo = new FunctionExpression("GetMeContext", new IExpression[] { });
            var c  = new RootContext();
            var r  = fo.Evaluate(c);

            Assert.AreEqual(12, r, "function result");
        }
        public void TestDivideDoubles()
        {
            var f = new FunctionExpression("/", new IExpression[] { new DoubleValue(2.2), new DoubleValue(2.0) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(1.1, r, "7.5+1.3");
        }
        public void TestDivideCommutation2()
        {
            var fo = new FunctionExpression("/", new IExpression[] { new IntegerValue(7), new VariableValue("p") });
            var c  = new RootContext();

            c.SetVariableValue("p", new OperatorTestObjects());
            var r = fo.Evaluate(c);
        }
        public void TestPlusNotDefined()
        {
            var fo = new FunctionExpression("/", new IExpression[] { new IntegerValue(7), new VariableValue("p") });
            var c  = new RootContext();

            c.SetVariableValue("p", new OperatorTestNotDefined());
            var r = fo.Evaluate(c);
        }
Example #11
0
        public void LoadFileWithSideEffects()
        {
            var f = new FunctionExpression("include", new IExpression[] { new StringValue("LoadFileWithSideEffects.plotlingo") });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(5, c.GetVariableValue("i"), "variable i");
        }
        public void TestBasicCalling()
        {
            var fo = new FunctionExpression("GetMe", new IExpression[] { new StringValue("hi there") });
            var c  = new RootContext();
            var r  = fo.Evaluate(c);

            Assert.AreEqual(8, r, "function result");
        }
Example #13
0
        public void TestEvalNumber()
        {
            var f = new FunctionExpression("eval", new IExpression[] { new StringValue("5;") });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(5, r, "simple eval");
        }
Example #14
0
        public void TestEvalWithContextUpdate()
        {
            var f = new FunctionExpression("eval", new IExpression[] { new StringValue("i=5;") });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(5, c.GetVariableValue("i"), "variable i");
        }
Example #15
0
        public void ScriptWithComments()
        {
            var f = new FunctionExpression("include", new IExpression[] { new StringValue("ScriptWithComments.plotlingo") });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(5, c.GetVariableValue("i"), "variable i");
        }
Example #16
0
        public void ScriptFileSetCorrectlyDuringLoad()
        {
            var f = new FunctionExpression("include", new IExpression[] { new StringValue("ReturnCurrentScriptName.plotlingo") });
            var c = new RootContext();
            var r = f.Evaluate(c) as string;

            Assert.IsTrue(r.Contains("ReturnCurrentScriptName.plotlingo"), "the script name in the file");
        }
Example #17
0
        public override IQueryState Accept(FunctionExpression exp)
        {
            IQueryState subQueryState = this.AsSubQueryState();

            IQueryState state = subQueryState.Accept(exp);

            return(state);
        }
Example #18
0
 public PixelShaderMetadata(string name, FunctionExpression entryPoint, List <ConstantExpression> constants,
                            List <ResourceExpression> resources, List <SamplerExpression> samplers, List <StructExpression> structs,
                            List <FunctionExpression> extendedFunctions, List <string> usageProcedures)
     : base(name, entryPoint, constants, structs, extendedFunctions, usageProcedures)
 {
     this.Resources = resources;
     this.Samplers  = samplers;
 }
Example #19
0
 /// <summary>
 /// Visits the function.
 /// </summary>
 /// <param name="func">The func.</param>
 /// <returns></returns>
 protected override Expression VisitFunction(FunctionExpression func)
 {
     if (this.linguist.Language.IsRowsAffectedExpressions(func))
     {
         return(Expression.Property(this.executor, "RowsAffected"));
     }
     return(base.VisitFunction(func));
 }
        public void TestMultiplyDoubles()
        {
            var f = new FunctionExpression("*", new IExpression[] { new DoubleValue(1.1), new DoubleValue(2.0) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(2.2, r, "7.5+1.3");
        }
        public void TestSubtractDoubles()
        {
            var f = new FunctionExpression("-", new IExpression[] { new DoubleValue(7.5), new DoubleValue(1.3) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(6.2, r, "7.5+1.3");
        }
Example #22
0
        public SailFunction(FunctionExpression func)
        {
            Name        = func.Name;
            ReturnTypes = func.ReturnTypes;
            Parameters  = func.Params;

            _block = func.Block;
        }
        public void TestMultiplyInts()
        {
            var f = new FunctionExpression("*", new IExpression[] { new IntegerValue(4), new IntegerValue(5) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(20, r, "4+5");
        }
        public void TestDivideInts()
        {
            var f = new FunctionExpression("/", new IExpression[] { new IntegerValue(4), new IntegerValue(8) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(0.5, r, "4+5");
        }
        public void TestSubtractInts()
        {
            var f = new FunctionExpression("-", new IExpression[] { new IntegerValue(4), new IntegerValue(5) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(-1, r, "4+5");
        }
        public void TestDivideDoubleAndInt1()
        {
            var f = new FunctionExpression("/", new IExpression[] { new DoubleValue(8), new IntegerValue(2) });
            var c = new RootContext();
            var r = f.Evaluate(c);

            Assert.AreEqual(4.0, r, "7.5+2");
        }
 void ITreeWalker.Visit(FunctionExpression expression)
 {
     expression.Validate(this);
     expression.Parameters.Accept(this);
     _loops.Push(null);
     expression.Body.Accept(this);
     _loops.Pop();
 }
Example #28
0
        InternalQuery <T1> CreateFunctionQuery <T1>(MethodInfo method, List <Expression> parameters)
        {
            FunctionExpression e = new FunctionExpression(typeof(T1), this._expression, method, parameters);
            var q = new Query <T1>(this._dbContext, e, false);
            InternalQuery <T1> iterator = q.GenenateIterator();

            return(iterator);
        }
 private AphidFunction InterpretFunctionExpression(FunctionExpression expression)
 {
     return(new AphidFunction()
     {
         Args = expression.Args.Select(x => x.Identifier).ToArray(),
         Body = expression.Body,
         ParentScope = _currentScope,
     });
 }
Example #30
0
        static void GetExtendedFunctionsFrom(FunctionExpression function, List <FunctionExpression> functionCollection, ref List <FunctionExpression> extendedFunctions, ref List <string> usageProcedures)
        {
            StatementBlockExpression result = function.ConstituentSymbols.Find(s => s is StatementBlockExpression) as StatementBlockExpression;

            if (result != null)
            {
                GetExtendedFunctionsFrom(result, functionCollection, ref extendedFunctions, ref usageProcedures);
            }
        }
Example #31
0
 public MethodDefinition(PropertyKey key, bool computed, FunctionExpression value, PropertyKind kind, bool isStatic)
 {
     Type     = Nodes.MethodDefinition;
     Static   = isStatic;
     Key      = key;
     Computed = computed;
     Value    = value;
     Kind     = kind;
 }
        public void FunctionExpressionProducesFunctionWithNameParametersAndBodyUsingProperties()
        {
            var f = new FunctionExpression();
            f.Name = JS.Id("a");
            f.Parameters.Add("b");
            f.Parameters.Add("c");
            f.Body = new CompoundStatement(JS.Return());

            Assert.AreEqual("function a(b,c){return;};", f.ToString());
        }
Example #33
0
 public override bool Replace(Node oldValue, Node newValue)
 {
   return
     Replace(Expression, oldValue, newValue, n => Expression = n)
     ||
     Replace(GetFunction, oldValue, newValue, n => GetFunction = n)
     ||
     Replace(SetFunction, oldValue, newValue, n => SetFunction = n)
     ||
     base.Replace(oldValue, newValue);
 }
Example #34
0
    public PropertyAssignment(string name, FunctionExpression getFunction, FunctionExpression setFunction)
    {
      Name = name;
      GetFunction = getFunction;
      SetFunction = setFunction;

      if (getFunction != null)
        SourceOffset = getFunction.SourceOffset;
      else
        SourceOffset = setFunction.SourceOffset;

      Use(GetFunction);
      Use(setFunction);
    }
Example #35
0
        Expression ParseAtom()
        {
            string id;
            Expression x = null;
            FunctionDefinition fnDef = null;

            switch (_token.Type)
            {
                // literals
                case TKTYPE.LITERAL:
                    x = new Expression(_token);
                    break;

                // identifiers
                case TKTYPE.IDENTIFIER:

                    // get identifier
                    id = (string)_token.Value;

                    // look for functions
                    if (_fnTbl.TryGetValue(id, out fnDef))
                    {
                        var p = GetParameters();
                        var pCnt = p == null ? 0 : p.Count;
                        if (fnDef.ParmMin != -1 && pCnt < fnDef.ParmMin)
                        {
                            Throw("Too few parameters.");
                        }
                        if (fnDef.ParmMax != -1 && pCnt > fnDef.ParmMax)
                        {
                            Throw("Too many parameters.");
                        }
                        x = new FunctionExpression(fnDef, p);
                        break;
                    }

                    // look for simple variables (much faster than binding!)
                    if (_vars.ContainsKey(id))
                    {
                        x = new VariableExpression(_vars, id);
                        break;
                    }

                    // look for external objects
                    var xObj = GetExternalObject(id);
                    if (xObj != null)
                    {
                        x = new XObjectExpression(xObj);
                        break;
                    }

                    // look for bindings
                    if (DataContext != null)
                    {
                        var list = new List<BindingInfo>();
                        for (var t = _token; t != null; t = GetMember())
                        {
                            list.Add(new BindingInfo((string)t.Value, GetParameters()));
                        }
                        x = new BindingExpression(this, list, _ci);
                        break;
                    }
                    Throw("Unexpected identifier");
                    break;

                // sub-expressions
                case TKTYPE.GROUP:

                    // anything other than opening parenthesis is illegal here
                    if (_token.ID != TKID.OPEN)
                    {
                        Throw("Expression expected.");
                    }

                    // get expression
                    GetToken();
                    x = ParseCompare();

                    // check that the parenthesis was closed
                    if (_token.ID != TKID.CLOSE)
                    {
                        Throw("Unbalanced parenthesis.");
                    }

                    break;
            }

            // make sure we got something...
            if (x == null)
            {
                Throw();
            }

            // done
            GetToken();
            return x;
        }
Example #36
0
        public virtual IQueryState Accept(FunctionExpression exp)
        {
            List<DbExpression> dbParameters = new List<DbExpression>(exp.Parameters.Count);
            foreach (Expression pExp in exp.Parameters)
            {
                var dbExp = GeneralExpressionVisitor.VisitPredicate((LambdaExpression)pExp, this.MoeList);
                dbParameters.Add(dbExp);
            }

            DbFunctionExpression dbFuncExp = new DbFunctionExpression(exp.ElementType, exp.Method, dbParameters);
            MappingFieldExpression mfe = new MappingFieldExpression(exp.ElementType, dbFuncExp);

            ResultElement result = new ResultElement();

            result.MappingObjectExpression = mfe;
            result.FromTable = this._resultElement.FromTable;
            result.AppendCondition(this._resultElement.Condition);

            FunctionQueryState state = new FunctionQueryState(result);
            return state;
        }
Example #37
0
        public void VisitFunctionExpression(FunctionExpression functionExpression)
        {
            DocComment dc = GetDocCommentBy(functionExpression);
            if (_project.EnableClosure && dc != null && functionExpression.Name != null && !IsGlobal) {
                dc.Ignore = true;
            }
            AutoFillName(dc, functionExpression.Name);

            if (dc != null)
                AutoFillMemberOf(dc);

            PushScope(dc);
            VisitStatements(functionExpression.Statements);
            ProcessCommentBefore(functionExpression);
            PopScope();

            ReturnValue = functionExpression;
        }
Example #38
0
 private void AddToJoinFilter(JoinExpression joinExpression, Expression toAdd)
 {
     Expression joinFilter = joinExpression.Filter;
     if (joinFilter != null) {
         if (toAdd != null) {
             FunctionExpression newFilter = new FunctionExpression("@and_sql");
             newFilter.Parameters.Add(toAdd);
             newFilter.Parameters.Add(joinFilter);
             toAdd = newFilter;
         } else {
             toAdd = joinFilter;
         }
     }
     joinExpression.Filter = toAdd;
 }
Example #39
0
 public override object Walk(FunctionExpression node)
 {
     var funcDec = new BikeFunction(node, node.Identifier, node.FormalParameters, node.Body,
         Context.CurrentFrame);
     if (node.Identifier != null)
         Context.CurrentFrame.Define(node.Identifier.Value, funcDec);
     return funcDec;
 }
Example #40
0
 public virtual void Exit(FunctionExpression node)
 {
 }
Example #41
0
 public AggregateTable(ITable child, FunctionExpression aggregateComposite)
     : base(child)
 {
     this.aggregateComposite = aggregateComposite;
 }
Example #42
0
 protected virtual Expression VisitFunction(FunctionExpression func)
 {
     var arguments = this.VisitExpressionList(func.Arguments);
     return this.UpdateFunction(func, func.Name, arguments);
 }
Example #43
0
        internal IndexResolver CreateResolver(ITable table, FunctionExpression sortExpression)
        {
            // Sort expressions
            string functionName = sortExpression.Name;

            if (!functionName.Equals("composite"))
                throw new ArgumentException("Invalid sort function expression.");

            int paramCount = sortExpression.Parameters.Count;

            // Extract the terms and the ordering information from the function
            int termCount = paramCount / 2;
            Expression[] sortExprs = new Expression[termCount];
            bool[] sortAscending = new bool[termCount];
            int n = 0;

            for (int i = 0; i < paramCount; i += 2) {
                sortExprs[n] = (Expression) sortExpression.Parameters[i];
                SqlObject asc = (SqlObject)sortExpression.Parameters[i + 1];
                sortAscending[n] = SqlObject.Equals(asc, new SqlObject(true));
                ++n;
            }

            // Create a Type of the composite of the expressions
            SqlType[] indexType = CreateResolverType(table, sortExprs);
            // Create the resolver,
            return new ExpressionIndexResolver(this, table, indexType, sortAscending, sortExprs);
        }
Example #44
0
 protected virtual Expression VisitFunction(FunctionExpression function)
 {
     this.Write("FUNCTION ");
     this.Write(function.Name);
     if (function.Arguments.Count > 0)
     {
         this.Write("(");
         this.VisitExpressionList(function.Arguments);
         this.Write(")");
     }
     return function;
 }
Example #45
0
 protected FunctionExpression UpdateFunction(FunctionExpression func, string name, IEnumerable<Expression> arguments)
 {
     if (name != func.Name || arguments != func.Arguments)
     {
         return new FunctionExpression(func.Type, name, arguments);
     }
     return func;
 }
Example #46
0
    // $ANTLR start "propertyAssignment"
    // I:\\Developpement\\Evaluant - R&D\\Jint\\trunk\\Jint\\ES3.g:1005:1: propertyAssignment returns [PropertyDeclarationExpression value] : (acc= accessor prop2= propertyName (parameters= formalParameterList )? statements= functionBody | prop1= propertyName COLON ass= assignmentExpression );
    public ES3Parser.propertyAssignment_return propertyAssignment() // throws RecognitionException [1]
    {   
        ES3Parser.propertyAssignment_return retval = new ES3Parser.propertyAssignment_return();
        retval.Start = input.LT(1);

        object root_0 = null;

        IToken COLON20 = null;
        ES3Parser.accessor_return acc = null;

        ES3Parser.propertyName_return prop2 = null;

        ES3Parser.formalParameterList_return parameters = null;

        ES3Parser.functionBody_return statements = null;

        ES3Parser.propertyName_return prop1 = null;

        ES3Parser.assignmentExpression_return ass = null;


        object COLON20_tree=null;


        	retval.value =  new PropertyDeclarationExpression();
        	FunctionExpression func=new FunctionExpression();

        try 
    	{
            // I:\\Developpement\\Evaluant - R&D\\Jint\\trunk\\Jint\\ES3.g:1010:2: (acc= accessor prop2= propertyName (parameters= formalParameterList )? statements= functionBody | prop1= propertyName COLON ass= assignmentExpression )
            int alt13 = 2;
            int LA13_0 = input.LA(1);

            if ( (LA13_0 == Identifier) )
            {
                int LA13_1 = input.LA(2);

                if ( (LA13_1 == COLON) )
                {
                    alt13 = 2;
                }
                else if ( ((LA13_1 >= Identifier && LA13_1 <= StringLiteral) || (LA13_1 >= DecimalLiteral && LA13_1 <= HexIntegerLiteral)) )
                {
                    alt13 = 1;
                }
                else 
                {
                    NoViableAltException nvae_d13s1 =
                        new NoViableAltException("", 13, 1, input);

                    throw nvae_d13s1;
                }
            }
            else if ( (LA13_0 == StringLiteral || (LA13_0 >= DecimalLiteral && LA13_0 <= HexIntegerLiteral)) )
            {
                alt13 = 2;
            }
            else 
            {
                NoViableAltException nvae_d13s0 =
                    new NoViableAltException("", 13, 0, input);

                throw nvae_d13s0;
            }
            switch (alt13) 
            {
                case 1 :
                    // I:\\Developpement\\Evaluant - R&D\\Jint\\trunk\\Jint\\ES3.g:1010:4: acc= accessor prop2= propertyName (parameters= formalParameterList )? statements= functionBody
                    {
                    	root_0 = (object)adaptor.GetNilNode();

                    	PushFollow(FOLLOW_accessor_in_propertyAssignment3391);
                    	acc = accessor();
                    	state.followingStackPointer--;

                    	adaptor.AddChild(root_0, acc.Tree);
                    	 retval.value.Mode=acc.value; 
                    	 retval.value.Expression=func; 
                    	PushFollow(FOLLOW_propertyName_in_propertyAssignment3399);
                    	prop2 = propertyName();
                    	state.followingStackPointer--;

                    	adaptor.AddChild(root_0, prop2.Tree);
                    	 retval.value.Name=func.Name=prop2.value; 
                    	// I:\\Developpement\\Evaluant - R&D\\Jint\\trunk\\Jint\\ES3.g:1010:130: (parameters= formalParameterList )?
                    	int alt12 = 2;
                    	int LA12_0 = input.LA(1);

                    	if ( (LA12_0 == LPAREN) )
                    	{
                    	    alt12 = 1;
                    	}
                    	switch (alt12) 
                    	{
                    	    case 1 :
                    	        // I:\\Developpement\\Evaluant - R&D\\Jint\\trunk\\Jint\\ES3.g:1010:131: parameters= formalParameterList
                    	        {
                    	        	PushFollow(FOLLOW_formalParameterList_in_propertyAssignment3406);
                    	        	parameters = formalParameterList();
                    	        	state.followingStackPointer--;

                    	        	adaptor.AddChild(root_0, parameters.Tree);
                    	        	 func.Parameters.AddRange(parameters.value); 

                    	        }
                    	        break;

                    	}

                    	PushFollow(FOLLOW_functionBody_in_propertyAssignment3414);
                    	statements = functionBody();
                    	state.followingStackPointer--;

                    	adaptor.AddChild(root_0, statements.Tree);
                    	 func.Statement=statements.value; 

                    }
                    break;
                case 2 :
                    // I:\\Developpement\\Evaluant - R&D\\Jint\\trunk\\Jint\\ES3.g:1011:4: prop1= propertyName COLON ass= assignmentExpression
                    {
                    	root_0 = (object)adaptor.GetNilNode();

                    	PushFollow(FOLLOW_propertyName_in_propertyAssignment3424);
                    	prop1 = propertyName();
                    	state.followingStackPointer--;

                    	adaptor.AddChild(root_0, prop1.Tree);
                    	 retval.value.Name=prop1.value; 
                    	COLON20=(IToken)Match(input,COLON,FOLLOW_COLON_in_propertyAssignment3428); 
                    		COLON20_tree = (object)adaptor.Create(COLON20);
                    		adaptor.AddChild(root_0, COLON20_tree);

                    	PushFollow(FOLLOW_assignmentExpression_in_propertyAssignment3432);
                    	ass = assignmentExpression();
                    	state.followingStackPointer--;

                    	adaptor.AddChild(root_0, ass.Tree);
                    	 retval.value.Expression=ass.value; 

                    }
                    break;

            }
            retval.Stop = input.LT(-1);

            	retval.Tree = (object)adaptor.RulePostProcessing(root_0);
            	adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
        }
        catch (RecognitionException re) 
    	{
            ReportError(re);
            Recover(input,re);
    	// Conversion of the second argument necessary, but harmless
    	retval.Tree = (object)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);

        }
        finally 
    	{
        }
        return retval;
    }
Example #47
0
        private static IRowCursor QueryAllMatches(SystemTransaction transaction, TableName tableName, SystemTable table,
            IList<string> columns, SqlObject val)
        {
            // Try and find an index on these columns
            SystemIndexSetDataSource indexSet = transaction.FindIndexOn(tableName, columns);

            // If index found
            if (indexSet != null)
                // Query the index and find all matches
                return indexSet.Select(SelectableRange.Is(val));

            // Otherwise no index, so scan the table for matches

            // Make an Expression for the operation;
            //  (column1, column2, ...columnn) = val
            Expression compExp;
            int sz = columns.Count;
            if (sz > 1) {
                FunctionExpression cfunExp = new FunctionExpression("composite_fetch");
                for (int i = 0; i < sz; ++i) {
                    Expression varRef = new FetchVariableExpression(new Variable(tableName, columns[i]));
                    cfunExp.Parameters.Add(varRef);
                }
                compExp = cfunExp;
            } else if (sz == 1) {
                compExp = new FetchVariableExpression(new Variable(tableName, columns[0]));
            } else {
                throw new ApplicationException("Invalid columns list size");
            }

            // Equality test
            FunctionExpression funExp = new FunctionExpression("@is_sql");
            funExp.Parameters.Add(compExp);
            funExp.Parameters.Add(new FetchStaticExpression(val));

            // Create a query processor and perform the scan operation
            QueryProcessor processor = new QueryProcessor(transaction);
            ITable result = processor.FilterByScan(table, funExp);
            // Return the row cursor
            return result.GetRowCursor();
        }
Example #48
0
        private Expression CostAnalysisAndTransform(SelectExpression selectExpression)
        {
            Expression joinGraph = selectExpression.Join;
            Expression filterGraph = selectExpression.Filter;

            // The required final ordering of the select expression if necessary.
            // This is either the 'group by' ordering for an aggregate statement,
            // or 'order by' if it's not an aggregate.

            // Are we an aggregate?
            Expression[] resultOrderExps;
            bool[] resultOrderAsc;
            Expression sortComposite = null;
            bool aggregateExpression = false;

            if (selectExpression.IsAggregated) {
                // Yes, do we have group by clause?
                int groupbyCount = selectExpression.GroupBy.Count;
                resultOrderExps = new Expression[groupbyCount];
                resultOrderAsc = new bool[groupbyCount];
                for (int i = 0; i < groupbyCount; ++i) {
                    resultOrderExps[i] = selectExpression.GroupBy[i];
                    resultOrderAsc[i] = true;      // All group by ordering is ascending
                }
                // Note the aggregate,
                aggregateExpression = true;
            } else {
                // Not an aggregate statement, do we have a order by clause?
                int orderbyCount = selectExpression.OrderBy.Count;
                resultOrderExps = new Expression[orderbyCount];
                resultOrderAsc = new bool[orderbyCount];
                for (int i = 0; i < orderbyCount; ++i) {
                    resultOrderExps[i] = selectExpression.OrderBy[i].Expression;
                    resultOrderAsc[i] = selectExpression.OrderBy[i].IsAscending;
                }
            }
            // The sort composite
            if (resultOrderExps.Length > 0) {
                sortComposite = FunctionExpression.Composite(resultOrderExps, resultOrderAsc);
            }

            // Create a new query transform object
            QueryPlanner planner = new QueryPlanner(transaction);
            planner.SetFilterGraph(filterGraph);
            planner.SetJoinGraph(joinGraph);
            planner.SetResultSortComposite(sortComposite);
            Expression cheapResolution = planner.FindCheapResolution();

            // If this is an aggregate query, we apply the aggregate filter to the
            // query plan.
            if (aggregateExpression) {
                FilterExpression aggregateFilter =
                      new FilterExpression("aggregate", cheapResolution, sortComposite);
                cheapResolution = aggregateFilter;
                // Is there a having clause?
                Expression havingExp = selectExpression.Having;
                if (havingExp != null) {
                    FilterExpression havingFilter =
                        new FilterExpression("single_filter", cheapResolution, havingExp);
                    cheapResolution = havingFilter;
                }
                // Is there an order by clause?
                int orderbyCount = selectExpression.OrderBy.Count;
                if (orderbyCount > 0) {
                    Expression[] orderExps = new Expression[orderbyCount];
                    bool[] order_asc = new bool[orderbyCount];
                    for (int i = 0; i < orderbyCount; ++i) {
                        orderExps[i] = selectExpression.OrderBy[i].Expression;
                        order_asc[i] = selectExpression.OrderBy[i].IsAscending;
                    }

                    Expression aggrSortComposite = FunctionExpression.Composite(orderExps, order_asc);
                    FilterExpression sortFilter = new FilterExpression("sort", cheapResolution, aggrSortComposite);
                    cheapResolution = sortFilter;
                }
            }

            // cheap_resolution is the best plan found, now add decoration such as
            // filter terms, etc
            int outCount = selectExpression.Output.Count;
            FunctionExpression outFunction = new FunctionExpression("table_out");
            for (int i = 0; i < outCount; ++i) {
                outFunction.Parameters.Add(selectExpression.Output[i].Expression);
            }
            // Set the filter,
            Expression outFilter = new FilterExpression("expression_table", cheapResolution, outFunction);

            QueryCostModel costModel = new QueryCostModel(transaction);
            costModel.ClearGraph(outFilter);
            costModel.Cost(outFilter, Double.PositiveInfinity, new int[1]);

            return outFilter;
        }
 protected virtual bool CompareFunction(FunctionExpression x, FunctionExpression y)
 {
     return x.Name == y.Name && this.CompareExpressionList(x.Arguments, y.Arguments);
 }
Example #50
0
        private ITable Function(FunctionExpression op)
        {
            string functionName = op.Name;
            int argCount = op.Parameters.Count;

            if (transaction.FunctionManager.FunctionExists(functionName)) {
                Expression[] expArgs = new Expression[argCount];
                for (int i = 0; i < expArgs.Length; ++i) {
                    expArgs[i] = (Expression) op.Parameters[i];
                }
                // If it's an aggregate function,
                if (transaction.FunctionManager.IsAggregate(functionName)) {
                    // (TODO: make this a 'GetGroupValue' processor function and
                    //   support subset filtered stack).
                    // The top table should be an aggregate table, or aggregate table
                    // friendly (have a near child table that is an aggregate table).
                    ITable topTable = tableStack[tableStack.Count - 1];
                    RowId rowid = rowIdStack[tableStack.Count - 1];
                    // Get the group of the current rowid
                    AggregateTable aggregateTable = GetAggregateTable(topTable);
                    ITable group = aggregateTable.GetGroupValue(rowid.ToInt64());
                    // Execute the aggregate function
                    bool distinct = op.IsDistinct;
                    return transaction.FunctionManager.EvaluateAggregate(functionName, this, distinct, group, expArgs);
                }

                return transaction.FunctionManager.Evaluate(functionName, this, expArgs);
            }

            if (functionName.Equals("range_set")) {
                // Resolve the variable
                SqlObject[] val = Result(DoExecute((Expression) op.Parameters[0]));
                SelectableRange range_set = (SelectableRange)op.Parameters[1];
                if (range_set.Intersector.ValueIntersects(val)) {
                    // If the resolved value intersects, return true
                    return ResultTable(new SqlObject(true));
                } else {
                    // Otherwise return false
                    return ResultTable(new SqlObject(false));
                }
            }

            // This function evaluates each parameter as a composite part and returns
            // an evaluation of the object as a composite object.
            if (functionName.Equals("composite_fetch")) {
                if (argCount == 0)
                    throw new ArgumentException();

                // If there's only 1 arg,
                if (argCount == 1)
                    return DoExecute((Expression)op.Parameters[0]);

                // Otherwise it's a true composite
                throw new NotImplementedException();
            }

            throw new ArgumentException("Unknown function " + functionName);
        }
Example #51
0
        public void Visit(FunctionExpression expression)
        {
            if (expression.Name == null || !expression.Metadata.HasName)
                outStream.Write("function (");
            else
                outStream.Write("function {0} (", expression.Name);

            if (expression.Parameters != null && expression.Parameters.Count > 0)
            {
                outStream.Write(expression.Parameters.First());

                foreach (var p in expression.Parameters.Skip(1))
                {
                    outStream.Write(", ");
                    outStream.Write(p);
                }
            }

            outStream.WriteLine(") {");
            Visit(expression.Metadata);
            outStream.Write("}");
        }
Example #52
0
 public override void Exit(FunctionExpression node)
 {
     level--;
 }
Example #53
0
 public virtual bool Enter(FunctionExpression node)
 {
     return true;
 }
Example #54
0
        private static void AutoCastSystemOperator(FunctionExpression exp, IList<Expression> parameters, List<SqlType> paramTypes)
        {
            SqlType t1 = paramTypes[0];
            SqlType t2 = paramTypes[1];

            // If both the types are identical, we good to go,
            if (!t1.IsComparableTo(t2))
                throw InvalidTypes(t1, t2, exp);

            // Types are compatible,
            // If they are numeric,

            if (t1.IsNumeric) {
                // The encoding is different, so now we do a static check
                if (!t1.Equals(t2)) {
                    // TODO: We should do a check on each parameter by walking the tree
                    //   to determine if it's static or not.

                    Expression exp1 = parameters[0];
                    Expression exp2 = parameters[1];

                    int staticop;
                    int varop;

                    // If the left or right is FETCHSTATIC,
                    if (exp1 is FetchStaticExpression) {
                        staticop = 0;
                        varop = 1;
                    } else if (exp2 is FetchStaticExpression) {
                        staticop = 1;
                        varop = 0;
                    } else {
                        // Neither static, so report error,
                        throw InvalidTypes(t1, t2, exp);
                    }

                    // The type of the variable and static sides,
                    SqlType varType = paramTypes[varop];

                    SqlObject castType = new SqlObject(varType.ToString());
                    FetchStaticExpression castExp = new FetchStaticExpression(castType);
                    castExp.ReturnType = SqlType.GetSqlType(typeof(string));

                    // Cast the static type to the variable type,
                    FunctionExpression newStaticExp = new FunctionExpression("@cast", new Expression[] {parameters[staticop], castExp});
                    newStaticExp.ReturnType = varType;
                    exp.Parameters[staticop] = newStaticExp;

                }
            }
        }
Example #55
0
 public override bool Enter(FunctionExpression node)
 {
     Print("FunctionExpression");
     level++;
     return true;
 }
Example #56
0
 private static Expression ComposeSetLogicalGraph(string logicalFunction, string comparisonFunction, Expression lhsExp, FunctionExpression rhsExp)
 {
     int listCount = rhsExp.Parameters.Count;
     Expression logTree = null;
     for (int i = 0; i < listCount; ++i) {
         Expression val = (Expression) rhsExp.Parameters[i];
         Expression itemFun = new FunctionExpression(comparisonFunction, new Expression[] { (Expression) lhsExp.Clone(), val });
         logTree = logTree == null ? itemFun : new FunctionExpression(logicalFunction, new Expression[] {logTree, itemFun});
     }
     return logTree;
 }
    private static Expression ParseExpression(Match match)
    {
      string expressionText = match.Value.Trim();
      Expression expression;
      lock (_expressions)
      {
        if (_expressions.TryGetValue(expressionText, out expression))
        {
          return expression;
        }
        // temporarily add a dummy expression to prevent other threads from parsing the same expression again
        Log.Debug("Cacheing expression: {0}", expressionText);
        _expressions.Add(expressionText, new LiteralExpression(expressionText));
      }

      if (match.Groups["string"].Success)
      {
        expression = new LiteralExpression(match.Groups["string"].Value);
      }
      else if (match.Groups["int"].Success)
      {
        expression = new LiteralExpression(int.Parse(match.Groups["int"].Value));
      }
      else if (match.Groups["float"].Success)
      {
        expression = new LiteralExpression(float.Parse(match.Groups["float"].Value, CultureInfo.InvariantCulture));
      }
      else if (match.Groups["property"].Success)
      {
        expression = new PropertyExpression(match.Groups["property"].Value);
      }
      else if (match.Groups["function"].Success)
      {
        string functionName = match.Groups["function"].Value;
        FunctionDefinition function;
        if (!_registeredFunctions.TryGetValue(functionName, out function))
        {
          Log.Error("Undefined function '{0}' in expression '{1}'", functionName, match.Value);
          expression = new LiteralExpression(match.Value);
        }
        else
        {
          int paramCount = match.Groups["param"].Captures.Count;
          Expression[] parameters = new Expression[paramCount];

          for (int i = 0; i < paramCount; i++)
          {
            string paramText = match.Groups["param"].Captures[i].Value;
            Match paramMatch = _expressionRegEx.Match(paramText);
            parameters[i] = ParseExpression(paramMatch);
          }

          expression = new FunctionExpression(_registeredFunctions[functionName], parameters);
        }
      }
      lock (_expressions)
      {
        // now replace with the real expression
        _expressions[expressionText] = expression;
      }
      return expression;
    }
Example #58
0
 void FunctionExpression(out Expression exp)
 {
     FunctionExpression fe = new FunctionExpression(GetPragma(la)); exp = fe; Expression e2;
     Expect(1);
     fe.func = GetFunction(t.val); int argsLeft = fe.func.Arity;
     if (la.kind == 47) {
     Get();
     }
     if ((argsLeft > 0 || (fe.func.IsVariadic && la.kind != _mkay)) && la.kind != _eos) {
     Expression(out e2);
     fe.arguments.Add(e2); argsLeft--;
     while ((argsLeft > 0 || (fe.func.IsVariadic && la.kind != _mkay)) && la.kind != _eos) {
         if (la.kind == 48) {
             Get();
         }
         Expression(out e2);
         fe.arguments.Add(e2); argsLeft--;
     }
     }
     if (fe.func.IsVariadic && la.kind != _eos) {
     Expect(10);
     }
 }
Example #59
0
 protected override Expression VisitFunction(FunctionExpression func)
 {
     this.Write(func.Name);
     if (func.Arguments.Count > 0)
     {
         this.Write("(");
         for (int i = 0, n = func.Arguments.Count; i < n; i++)
         {
             if (i > 0) this.Write(", ");
             this.Visit(func.Arguments[i]);
         }
         this.Write(")");
     }
     return func;
 }
Example #60
0
        private static void AddToSelectFilter(SelectExpression selectExpression, Expression toAdd)
        {
            Expression selectFilter = selectExpression.Filter;
            if (selectFilter != null) {
                if (toAdd != null) {
                    FunctionExpression newFilter = new FunctionExpression("@and_sql");
                    newFilter.Parameters.Add(toAdd);
                    newFilter.Parameters.Add(selectFilter);
                    toAdd = newFilter;
                } else {
                    toAdd = selectFilter;
                }
            }

            selectExpression.Filter = toAdd;
        }