Пример #1
0
 public ExprJsResolvedMethod(Ctx ctx, TypeReference returnType, Expr obj, string methodName, IEnumerable<Expr> args)
     : base(ctx) {
     this.returnType = returnType;
     this.Obj = obj;
     this.MethodName = methodName;
     this.Args = args;
 }
Пример #2
0
 public ExprAlloc(string type, string name, Expr expr, bool isEqualSign)
 {
     this.Type = type;
     this.Name = new List<string> { name };
     this.ExprList = new List<Expr> { expr };
     this.IsEqualSign = isEqualSign;
 }
Пример #3
0
        private void InternalValidate(Expr expr,object obj,out object output)
        {
            output = null;
            var eqGoal   = obj as EqGoal;
            var query    = obj as Query;
            var equation = obj as Equation;
            var shape = obj as ShapeSymbol;

            if (eqGoal != null)
            {
                InternalValidate(expr, eqGoal, out output);
                return;
            }
            if (query != null)
            {
                InternalValidate(expr, query, out output);
                return;
            }
            if (equation != null)
            {
                InternalValidate(expr, equation, out output);
                return;
            }
            if (shape != null)
            {
                InternalValidate(expr, shape, out output);
            }
        }
Пример #4
0
    /*
    ** 2001 September 15
    **
    ** The author disclaims copyright to this source code.  In place of
    ** a legal notice, here is a blessing:
    **
    **    May you do good and not evil.
    **    May you find forgiveness for yourself and forgive others.
    **    May you share freely, never taking more than you give.
    **
    *************************************************************************
    ** This file contains routines used for analyzing expressions and
    ** for generating VDBE code that evaluates expressions in SQLite.
    *************************************************************************
    **  Included in SQLite3 port to C#-SQLite;  2008 Noah B Hart
    **  C#-SQLite is an independent reimplementation of the SQLite software library
    **
    **  SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
    **
    *************************************************************************
    */
    //#include "sqliteInt.h"

    /*
    ** Return the 'affinity' of the expression pExpr if any.
    **
    ** If pExpr is a column, a reference to a column via an 'AS' alias,
    ** or a sub-select with a column as the return value, then the
    ** affinity of that column is returned. Otherwise, 0x00 is returned,
    ** indicating no affinity for the expression.
    **
    ** i.e. the WHERE clause expresssions in the following statements all
    ** have an affinity:
    **
    ** CREATE TABLE t1(a);
    ** SELECT * FROM t1 WHERE a;
    ** SELECT a AS b FROM t1 WHERE b;
    ** SELECT * FROM t1 WHERE (select a from t1);
    */
    static char sqlite3ExprAffinity( Expr pExpr )
    {
      int op = pExpr.op;
      if ( op == TK_SELECT )
      {
        Debug.Assert( ( pExpr.flags & EP_xIsSelect ) != 0 );
        return sqlite3ExprAffinity( pExpr.x.pSelect.pEList.a[0].pExpr );
      }
#if !SQLITE_OMIT_CAST
      if ( op == TK_CAST )
      {
        Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
        return sqlite3AffinityType( pExpr.u.zToken );
      }
#endif
      if ( ( op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER )
      && pExpr.pTab != null
      )
      {
        /* op==TK_REGISTER && pExpr.pTab!=0 happens when pExpr was originally
        ** a TK_COLUMN but was previously evaluated and cached in a register */
        int j = pExpr.iColumn;
        if ( j < 0 )
          return SQLITE_AFF_INTEGER;
        Debug.Assert( pExpr.pTab != null && j < pExpr.pTab.nCol );
        return pExpr.pTab.aCol[j].affinity;
      }
      return pExpr.affinity;
    }
Пример #5
0
 /// <summary>
 /// Initialize
 /// </summary>
 /// <param name="start">start expression</param>
 /// <param name="condition">condition for loop</param>
 /// <param name="inc">increment expression</param>
 public ForExpr(Expr start, Expr condition, Expr inc)
     : base(condition)
 {
     this.Nodetype = NodeTypes.SysFor;
     InitBoundary(true, "}");
     Init(start, condition, inc);
 }
 public ExprArgAddress(Ctx ctx, Expr arg, TypeReference type)
     : base(ctx) {
     //this.Index = index;
     this.Arg = arg;
     this.ElementType = type;
     this.type = type.MakePointer();
 }
Пример #7
0
  void PredicateCmd(Expr p, Expr pDom, List<Block> blocks, Block block, Cmd cmd, out Block nextBlock) {
    var cCmd = cmd as CallCmd;
    if (cCmd != null && !useProcedurePredicates(cCmd.Proc)) {
      if (p == null) {
        block.Cmds.Add(cmd);
        nextBlock = block;
        return;
      }

      var trueBlock = new Block();
      blocks.Add(trueBlock);
      trueBlock.Label = block.Label + ".call.true";
      trueBlock.Cmds.Add(new AssumeCmd(Token.NoToken, p));
      trueBlock.Cmds.Add(cmd);

      var falseBlock = new Block();
      blocks.Add(falseBlock);
      falseBlock.Label = block.Label + ".call.false";
      falseBlock.Cmds.Add(new AssumeCmd(Token.NoToken, Expr.Not(p)));

      var contBlock = new Block();
      blocks.Add(contBlock);
      contBlock.Label = block.Label + ".call.cont";

      block.TransferCmd =
        new GotoCmd(Token.NoToken, new List<Block> { trueBlock, falseBlock });
      trueBlock.TransferCmd = falseBlock.TransferCmd =
        new GotoCmd(Token.NoToken, new List<Block> { contBlock });
      nextBlock = contBlock;
    } else {
      PredicateCmd(p, pDom, block.Cmds, cmd);
      nextBlock = block;
    }
  }
Пример #8
0
        /// <summary>
        /// Sets a value on a member of a basic type.
        /// </summary>
        /// <param name="ctx">The context of the runtime</param>
        /// <param name="varExp">The expression representing the index of the instance to set</param>
        /// <param name="valExp">The expression representing the value to set</param>
        /// <param name="node">The assignment ast node</param>
        public static void SetIndexValue(Context ctx, IAstVisitor visitor, AstNode node, Expr varExp, Expr valExp)
        {
            // 1. Get the value that is being assigned.
            var val = valExp.Evaluate(visitor) as LObject;

            // 2. Check the limit if string.
            ctx.Limits.CheckStringLength(node, val);

            // 3. Evaluate expression to get index info.
            var indexExp = varExp.Evaluate(visitor) as IndexAccess;
            if (indexExp == null)
                throw ComLib.Lang.Helpers.ExceptionHelper.BuildRunTimeException(node, "Value to assign is null");

            // 4. Get the target of the index access and the name / number to set.
            var target = indexExp.Instance;
            var memberNameOrIndex = indexExp.MemberName;

            // Get methods associated with type.
            var methods = ctx.Methods.Get(target.Type);

            // Case 1: users[0] = 'kishore'
            if (target.Type == LTypes.Array)
            {
                var index = Convert.ToInt32(((LNumber)memberNameOrIndex).Value);
                methods.SetByNumericIndex(target, index, val);
            }
            // Case 2: users['total'] = 20
            else if (target.Type == LTypes.Map)
            {
                var name = ((LString)memberNameOrIndex).Value;
                methods.SetByStringMember(target, name, val);
            }
        }
Пример #9
0
 /// <summary>
 /// Initialize
 /// </summary>
 /// <param name="isDeclaration">Whether or not the variable is being declared in addition to assignment.</param>
 /// <param name="varExp">Expression representing the variable name to set</param>
 /// <param name="valueExp">Expression representing the value to set variable to.</param>
 public AssignExpr(bool isDeclaration, Expr varExp, Expr valueExp)
 {
     this.Nodetype = NodeTypes.SysAssign;
     this.IsDeclaration = isDeclaration;
     this.VarExp = varExp;
     this.ValueExp = valueExp;
 }
Пример #10
0
 public ExprTernary(Ctx ctx, Expr condition, Expr ifTrue, Expr ifFalse)
     : base(ctx) {
     this.Condition = condition;
     this.IfTrue = ifTrue;
     this.IfFalse = ifFalse;
     this.type = TypeCombiner.Combine(ctx, ifTrue, ifFalse);
 }
Пример #11
0
 /// <summary>
 /// Initialize
 /// </summary>
 /// <param name="aggregateType">sum avg min max count total</param>
 /// <param name="source"></param>
 public AggregateExpr(string aggregateType, Expr source)
 {
     this.Nodetype = "FSExtAggregate";
     this.InitBoundary(true, ")");
     this._aggregateType = aggregateType;
     this._source = source;
 }
Пример #12
0
 /// <summary>
 /// Called by the framework after the parse method is called
 /// </summary>
 /// <param name="node">The node returned by this implementations Parse method</param>
 public void OnParseAssignComplete(Expr expr)
 {
     var stmt = expr as AssignMultiExpr;
     if (stmt.Assignments == null || stmt.Assignments.Count == 0)
         return;
     foreach (var assignment in stmt.Assignments)
     {
         var exp = assignment.VarExp;
         if (exp.IsNodeType(NodeTypes.SysVariable))
         {
             var varExp = exp as VariableExpr;
             var valExp = assignment.ValueExp;
             var name = varExp.Name;
             var registeredTypeVar = false;
             var ctx = this._parser.Context;
             if (valExp != null && valExp.IsNodeType(NodeTypes.SysNew))
             {
                 var newExp = valExp as NewExpr;
                 if (ctx.Types.Contains(newExp.TypeName))
                 {
                     var type = ctx.Types.Get(newExp.TypeName);
                     var ltype = LangTypeHelper.ConvertToLangTypeClass(type);
                     ctx.Symbols.DefineVariable(name, ltype);
                     registeredTypeVar = true;
                 }
             }
             if (!registeredTypeVar)
                 ctx.Symbols.DefineVariable(name, LTypes.Object);
         }
     }
 }
Пример #13
0
        /// <summary>
        /// Sets a value on a member of a basic type.
        /// </summary>
        /// <param name="ctx">The context of the runtime</param>
        /// <param name="node">The assignment ast node</param>
        /// <param name="isDeclaration">Whether or not this is a declaration</param>
        /// <param name="varExp">The expression representing the index of the instance to set</param>
        /// <param name="valExp">The expression representing the value to set</param>
        public static void SetVariableValue(Context ctx, IAstVisitor visitor, AstNode node, bool isDeclaration, Expr varExp, Expr valExp)
        {
            string varname = ((VariableExpr)varExp).Name;

            // Case 1: var result;
            if (valExp == null)
            {
                ctx.Memory.SetValue(varname, LObjects.Null, isDeclaration);
            }
            // Case 2: var result = <expression>;
            else
            {
                var result = valExp.Evaluate(visitor);
                
                // Check for type: e.g. LFunction ? when using Lambda?
                if (result != null && result != LObjects.Null)
                {
                    var lobj = result as LObject;
                    if (lobj != null && lobj.Type.TypeVal == TypeConstants.Function)
                    {
                        // 1. Define the function in global symbol scope
                        SymbolHelper.ResetSymbolAsFunction(varExp.SymScope, varname, lobj);
                    }
                }
                // CHECK_LIMIT:
                ctx.Limits.CheckStringLength(node, result);
                ctx.Memory.SetValue(varname, result, isDeclaration);
            }

            // LIMIT CHECK
            ctx.Limits.CheckScopeCount(varExp);
            ctx.Limits.CheckScopeStringLength(varExp);
        }
 private Expr Convert(Expr e, TypeReference toType) {
     if (e == null) {
         return null;
     }
     var eType = e.Type.FullResolve(e.Ctx);
     if (eType.IsPointer) {
         // HACK: ?? This is probably a hack, not quite sure yet
         eType = ((PointerType)eType).ElementType;
     }
     if (eType.IsAssignableTo(toType)) {
         return e;
     }
     if (e.ExprType == Expr.NodeType.Literal) {
         var eLit = (ExprLiteral)e;
         if (toType.IsChar()) {
             if (eType.IsInt32()) {
                 return new ExprLiteral(e.Ctx, (char)(int)eLit.Value, e.Ctx.Char);
             }
         }
         if (toType.IsBoolean()) {
             if (eType.IsInt32()) {
                 return new ExprLiteral(e.Ctx, ((int)eLit.Value) != 0, e.Ctx.Boolean);
             }
         }
     }
     return e;
 }
 public ExprVariableAddress(Ctx ctx, Expr variable, TypeReference type)
     : base(ctx) {
     //this.Index = index;
     this.Variable = variable;
     this.ElementType = type;
     this.type = type.MakePointer();
 }
Пример #16
0
 public ExprAlloc(SugarType type, string name, Expr expr, AllocType style)
 {
     this.Type = type;
     this.Name = new List<string> { name };
     this.ExprList = new List<Expr> { expr };
     this.Style = style;
 }
Пример #17
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="expr"></param>
 /// <param name="stmt"></param>
 public If(Expr expr, Stmt stmt)
 {
     this.Expr = expr;
     this.Stmt = stmt;
     if(this.Expr.Type != Type.Bool)
         this.Expr.Error("boolean required in if");
 }
Пример #18
0
    /*
    ** 2008 August 18
    **
    ** The author disclaims copyright to this source code.  In place of
    ** a legal notice, here is a blessing:
    **
    **    May you do good and not evil.
    **    May you find forgiveness for yourself and forgive others.
    **    May you share freely, never taking more than you give.
    **
    *************************************************************************
    **
    ** This file contains routines used for walking the parser tree and
    ** resolve all identifiers by associating them with a particular
    ** table and column.
    *************************************************************************
    **  Included in SQLite3 port to C#-SQLite;  2008 Noah B Hart
    **  C#-SQLite is an independent reimplementation of the SQLite software library
    **
    **  SQLITE_SOURCE_ID: 2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7
    **
    **  $Header$
    *************************************************************************
    */
    //#include "sqliteInt.h"
    //#include <stdlib.h>
    //#include <string.h>

    /*
    ** Turn the pExpr expression into an alias for the iCol-th column of the
    ** result set in pEList.
    **
    ** If the result set column is a simple column reference, then this routine
    ** makes an exact copy.  But for any other kind of expression, this
    ** routine make a copy of the result set column as the argument to the
    ** TK_AS operator.  The TK_AS operator causes the expression to be
    ** evaluated just once and then reused for each alias.
    **
    ** The reason for suppressing the TK_AS term when the expression is a simple
    ** column reference is so that the column reference will be recognized as
    ** usable by indices within the WHERE clause processing logic.
    **
    ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
    ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
    **
    **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
    **
    ** Is equivalent to:
    **
    **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
    **
    ** The result of random()%5 in the GROUP BY clause is probably different
    ** from the result in the result-set.  We might fix this someday.  Or
    ** then again, we might not...
    */
    static void resolveAlias(
    Parse pParse,         /* Parsing context */
    ExprList pEList,      /* A result set */
    int iCol,             /* A column in the result set.  0..pEList.nExpr-1 */
    Expr pExpr,       /* Transform this into an alias to the result set */
    string zType          /* "GROUP" or "ORDER" or "" */
    )
    {
      Expr pOrig;           /* The iCol-th column of the result set */
      Expr pDup;            /* Copy of pOrig */
      sqlite3 db;           /* The database connection */

      Debug.Assert( iCol >= 0 && iCol < pEList.nExpr );
      pOrig = pEList.a[iCol].pExpr;
      Debug.Assert( pOrig != null );
      Debug.Assert( ( pOrig.flags & EP_Resolved ) != 0 );
      db = pParse.db;
      if ( pOrig.op != TK_COLUMN && ( zType.Length == 0 || zType[0] != 'G' ) )
      {
        pDup = sqlite3ExprDup( db, pOrig, 0 );
        pDup = sqlite3PExpr( pParse, TK_AS, pDup, null, null );
        if ( pDup == null ) return;
        if ( pEList.a[iCol].iAlias == 0 )
        {
          pEList.a[iCol].iAlias = (u16)( ++pParse.nAlias );
        }
        pDup.iTable = pEList.a[iCol].iAlias;
      }
      else if ( ExprHasProperty( pOrig, EP_IntValue ) || pOrig.u.zToken == null )
      {
        pDup = sqlite3ExprDup( db, pOrig, 0 );
        if ( pDup == null ) return;
      }
      else
      {
        string zToken = pOrig.u.zToken;
        Debug.Assert( zToken != null );
        pOrig.u.zToken = null;
        pDup = sqlite3ExprDup( db, pOrig, 0 );
        pOrig.u.zToken = zToken;
        if ( pDup == null ) return;
        Debug.Assert( ( pDup.flags & ( EP_Reduced | EP_TokenOnly ) ) == 0 );
        pDup.flags2 |= EP2_MallocedToken;
        pDup.u.zToken = zToken;// sqlite3DbStrDup( db, zToken );
      }
      if ( ( pExpr.flags & EP_ExpCollate ) != 0 )
      {
        pDup.pColl = pExpr.pColl;
        pDup.flags |= EP_ExpCollate;
      }

      /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
      ** prevents ExprDelete() from deleting the Expr structure itself,
      ** allowing it to be repopulated by the memcpy() on the following line.
      */
      ExprSetProperty( pExpr, EP_Static );
      sqlite3ExprDelete( db, ref pExpr );
      pExpr.CopyFrom( pDup ); //memcpy(pExpr, pDup, sizeof(*pExpr));
      sqlite3DbFree( db, ref pDup );
    }
Пример #19
0
 public AssertCmd(IToken/*!*/ tok, Expr/*!*/ expr, QKeyValue kv)
     : base(tok, expr, kv)
 {
     Contract.Requires(tok != null);
       Contract.Requires(expr != null);
       errorDataEnhanced = GenerateBoundVarMiningStrategy(expr);
 }
Пример #20
0
 static Expr InverseFunctionConvolution(IContext context, Expr arg)
 {
     return arg
         .ConvertAs<FunctionExpr>()
         .If(x => context.GetFunction(x.FunctionName) is ExpFunction)
         .Return(x => x.Args.First(), () => null);
 }
Пример #21
0
        /// <summary>
        /// Adds an expression to be interpolated.
        /// </summary>
        /// <param name="exp"></param>
        public void Add(Expr exp)
        {
            if (_expressions == null)
                _expressions = new List<Expr>();

            _expressions.Add(exp);
        }
Пример #22
0
 public ExprBinary(Ctx ctx, BinaryOp op, TypeReference type, Expr left, Expr right)
     : base(ctx) {
     this.Op = op;
     this.type = type;
     this.Left = left;
     this.Right = right;
 }
 protected override ICode VisitExpr(Expr e) {
     Expr r;
     if (this.replace.TryGetValue(e, out r)) {
         return r;
     }
     return base.VisitExpr(e);
 }
Пример #24
0
    /*
    ** 2008 August 16
    **
    ** The author disclaims copyright to this source code.  In place of
    ** a legal notice, here is a blessing:
    **
    **    May you do good and not evil.
    **    May you find forgiveness for yourself and forgive others.
    **    May you share freely, never taking more than you give.
    **
    *************************************************************************
    ** This file contains routines used for walking the parser tree for
    ** an SQL statement.
    *************************************************************************
    **  Included in SQLite3 port to C#-SQLite;  2008 Noah B Hart
    **  C#-SQLite is an independent reimplementation of the SQLite software library
    **
    **  SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
    **
    *************************************************************************
    */
    //#include "sqliteInt.h"
    //#include <stdlib.h>
    //#include <string.h>


    /*
    ** Walk an expression tree.  Invoke the callback once for each node
    ** of the expression, while decending.  (In other words, the callback
    ** is invoked before visiting children.)
    **
    ** The return value from the callback should be one of the WRC_*
    ** constants to specify how to proceed with the walk.
    **
    **    WRC_Continue      Continue descending down the tree.
    **
    **    WRC_Prune         Do not descend into child nodes.  But allow
    **                      the walk to continue with sibling nodes.
    **
    **    WRC_Abort         Do no more callbacks.  Unwind the stack and
    **                      return the top-level walk call.
    **
    ** The return value from this routine is WRC_Abort to abandon the tree walk
    ** and WRC_Continue to continue.
    */
    static int sqlite3WalkExpr( Walker pWalker, ref Expr pExpr )
    {
      int rc;
      if ( pExpr == null )
        return WRC_Continue;
      testcase( ExprHasProperty( pExpr, EP_TokenOnly ) );
      testcase( ExprHasProperty( pExpr, EP_Reduced ) );
      rc = pWalker.xExprCallback( pWalker, ref pExpr );
      if ( rc == WRC_Continue
      && !ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
      {
        if ( sqlite3WalkExpr( pWalker, ref pExpr.pLeft ) != 0 )
          return WRC_Abort;
        if ( sqlite3WalkExpr( pWalker, ref pExpr.pRight ) != 0 )
          return WRC_Abort;
        if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
        {
          if ( sqlite3WalkSelect( pWalker, pExpr.x.pSelect ) != 0 )
            return WRC_Abort;
        }
        else
        {
          if ( sqlite3WalkExprList( pWalker, pExpr.x.pList ) != 0 )
            return WRC_Abort;
        }
      }
      return rc & WRC_Abort;
    }
Пример #25
0
        static void ResolveAlias(Parse parse, ExprList list, int colId, Expr expr, string type, int subqueries)
        {
            Debug.Assert(colId >= 0 && colId < list.Exprs);
            Expr orig = list.Ids[colId].Expr; // The iCol-th column of the result set
            Debug.Assert(orig != null);
            Debug.Assert((orig.Flags & EP.Resolved) != 0);
            Context ctx = parse.Ctx; // The database connection
            Expr dup = Expr.Dup(ctx, orig, 0); // Copy of pOrig
            if (orig.OP != TK.COLUMN && (type.Length == 0 || type[0] != 'G'))
            {
                IncrAggFunctionDepth(dup, subqueries);
                dup = Expr.PExpr_(parse, TK.AS, dup, null, null);
                if (dup == null) return;
                if (list.Ids[colId].Alias == 0)
                    list.Ids[colId].Alias = (ushort)(++parse.Alias.length);
                dup.TableId = list.Ids[colId].Alias;
            }
            if (expr.OP == TK.COLLATE)
                dup = Expr.AddCollateString(parse, dup, expr.u.Token);

            // Before calling sqlite3ExprDelete(), set the EP_Static flag. This prevents ExprDelete() from deleting the Expr structure itself,
            // allowing it to be repopulated by the memcpy() on the following line.
            E.ExprSetProperty(expr, EP.Static);
            Expr.Delete(ctx, ref expr);
            expr.memcpy(dup);
            if (!E.ExprHasProperty(expr, EP.IntValue) && expr.u.Token != null)
            {
                Debug.Assert((dup.Flags & (EP.Reduced | EP.TokenOnly)) == 0);
                dup.u.Token = expr.u.Token;
                dup.Flags2 |= EP2.MallocedToken;
            }
            C._tagfree(ctx, ref dup);
        }
 public ExprFieldAddress(Ctx ctx, Expr obj, FieldReference field)
     : base(ctx) {
     this.Obj = obj;
     this.Field = field;
     this.ElementType = field.FieldType.FullResolve(field);
     this.type = this.ElementType.MakePointer();
 }
Пример #27
0
 public ForItemDownTo(string var, Expr from, Expr to, Expr by)
 {
     this.Var = var;
     this.From = from;
     this.To = to;
     this.By = by;
 }
Пример #28
0
        /*
        ** The first parameter (pDef) is a function implementation.  The
        ** second parameter (pExpr) is the first argument to this function.
        ** If pExpr is a column in a virtual table, then let the virtual
        ** table implementation have an opportunity to overload the function.
        **
        ** This routine is used to allow virtual table implementations to
        ** overload MATCH, LIKE, GLOB, and REGEXP operators.
        **
        ** Return either the pDef argument (indicating no change) or a
        ** new FuncDef structure that is marked as ephemeral using the
        ** SQLITE_FUNC_EPHEM flag.
        */
        FuncDef *sqlite3VtabOverloadFunction(
            sqlite3 *db,    /* Database connection for reporting malloc problems */
            FuncDef *pDef,  /* Function to possibly overload */
            int nArg,       /* Number of arguments to the function */
            Expr *pExpr     /* First argument to the function */
            )
        {
            Table *pTab;
              sqlite3_vtab *pVtab;
              sqlite3_module *pMod;
              void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
              void *pArg = 0;
              FuncDef *pNew;
              int rc = 0;
              char *zLowerName;
              unsigned char *z;

              /* Check to see the left operand is a column in a virtual table */
              if( NEVER(pExpr==0) ) return pDef;
              if( pExpr->op!=TK_COLUMN ) return pDef;
              pTab = pExpr->pTab;
              if( NEVER(pTab==0) ) return pDef;
              if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
              pVtab = sqlite3GetVTable(db, pTab)->pVtab;
              assert( pVtab!=0 );
              assert( pVtab->pModule!=0 );
              pMod = (sqlite3_module *)pVtab->pModule;
              if( pMod->xFindFunction==0 ) return pDef;

              /* Call the xFindFunction method on the virtual table implementation
              ** to see if the implementation wants to overload this function
              */
              zLowerName = sqlite3DbStrDup(db, pDef->zName);
              if( zLowerName ){
            for(z=(unsigned char*)zLowerName; *z; z++){
              *z = sqlite3UpperToLower[*z];
            }
            rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
            sqlite3DbFree(db, zLowerName);
              }
              if( rc==0 ){
            return pDef;
              }

              /* Create a new ephemeral function definition for the overloaded
              ** function */
              pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
                             + sqlite3Strlen30(pDef->zName) + 1);
              if( pNew==0 ){
            return pDef;
              }
              *pNew = *pDef;
              pNew->zName = (char *)&pNew[1];
              memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
              pNew->xFunc = xFunc;
              pNew->pUserData = pArg;
              pNew->flags |= SQLITE_FUNC_EPHEM;
              return pNew;
        }
Пример #29
0
 /// <summary>
 /// Initialize using values.
 /// </summary>
 /// <param name="varName">The name of the variable representing each item in the source</param>
 /// <param name="source">The data source being queried</param>
 /// <param name="filter">The filter to apply on the datasource</param>
 /// <param name="sorts">The sorting to apply after filtering.</param>
 public LinqExpr(string varName, Expr source, Expr filter, List<Expr> sorts)
 {
     this.Nodetype = "FSExtLinq";
     _varName = varName;
     _sorts = sorts;
     _source = source;
     _filter = filter;
 }
Пример #30
0
 /// <summary>
 /// Initializes a new runtime error.
 /// </summary>
 /// <param name="culprit">The expression. Can not be null.</param>
 /// <param name="thrownValue">The error value. Can not be null.</param>
 public RuntimeError( Expr culprit, RuntimeObj thrownValue )
     : base(culprit)
 {
     if( thrownValue == null ) throw new ArgumentNullException();
     if( thrownValue is RefRuntimeObj ) throw new ArgumentException();
     Message = "Runtime error.";
     ThrownValue = thrownValue;
 }
Пример #31
0
 /// <summary>
 /// Constructor for QuantifiedExpr.
 /// </summary>
 /// <param name="type">
 ///            Type (0 for SOME, 1 for ALL). </param>
 /// <param name="varexp">
 ///            Expressions. </param>
 /// <param name="ret">
 ///            Returned expression. </param>
 public QuantifiedExpr(int type, ICollection <VarExprPair> varexp, Expr ret)
 {
     _type           = type;
     _var_expr_pairs = varexp;
     _return         = ret;
 }
Пример #32
0
 /// <summary>
 /// Set next expression.
 /// </summary>
 /// <param name="e">
 ///            Expression. </param>
 public virtual void set_expr(Expr e)
 {
     _return = e;
 }
Пример #33
0
        public string EvaluateToOutputForm(Expr exprObject, int pageWidth = 0)
        {
            CacheMisses++;

            return(KernelLink.EvaluateToOutputForm(exprObject, pageWidth));
        }
        public void Should_properly_map_parameters()
        {
            Func <int, char, string, long, bool, string> formatMethod = Format;
            var func = CreateFunc <int, char, string, long, bool, string>(Expr.Return(Expr.Call(
                                                                                          formatMethod.Method,
                                                                                          Expr.Parameter(0, typeof(int)),
                                                                                          Expr.Parameter(1, typeof(char)),
                                                                                          Expr.Parameter(2, typeof(string)),
                                                                                          Expr.Parameter(3, typeof(long)),
                                                                                          Expr.Parameter(4, typeof(bool)))));

            Assert.That(func(1, 'a', "text", -23, false), Is.EqualTo("1_a_text_-23_False"));
        }
        public void Should_not_allow_parameter_type_not_matching_to_method_signature()
        {
            var ex = Assert.Throws <InvalidOperationException>(() => CreateFunc <object, int>(Expr.Return(Expr.Parameter(0, typeof(int)))));

            Assert.That(ex.Message, Is.StringContaining("Parameter index 0 is of System.Int32 type, while type System.Object is expected"));
        }
Пример #36
0
 public abstract void Set(string nvar, Expr e);
Пример #37
0
 public ContractRequiresInfo(Expr originalExpr, Expr rewrittenExpr)
 {
     this.OriginalExpr  = originalExpr;
     this.RewrittenExpr = rewrittenExpr;
 }
Пример #38
0
 private MathematicaPattern(MathematicaInterface parentCas, Expr mathExpr)
     : base(parentCas, mathExpr)
 {
 }
Пример #39
0
        // Parse a leaf node
        // (For the moment this is just a number)
        Expr ParseLeaf()
        {
            // Is it a number?
            if (_tokenizer.Current.Token == Token.Number)
            {
                var node = Expr.Number(_tokenizer.Current.Number);
                _tokenizer.MoveNext();
                return(node);
            }
            // Bracket?
            if (_tokenizer.Current.Token == Token.OpenBracket)
            {
                // array
                // Skip '['
                _tokenizer.MoveNext();

                var elements = new List <Expr>();
                while (true)
                {
                    // Parse argument and add to list
                    elements.Add(ParseAddSubtract());

                    // Is there another argument?
                    if (_tokenizer.Current.Token == Token.Comma)
                    {
                        _tokenizer.MoveNext();
                        continue;
                    }

                    // Get out
                    break;
                }

                // Check and skip ')'
                if (_tokenizer.Current.Token != Token.CloseBracket)
                {
                    throw new SyntaxException("Missing close bracket");
                }
                _tokenizer.MoveNext();

                return(Expr.FromArray(elements));
            }

            // Parenthesis?
            if (_tokenizer.Current.Token == Token.OpenParens)
            {
                // Skip '('
                _tokenizer.MoveNext();

                // Parse a top-level expression
                var node = ParseAddSubtract();

                // Check and skip ')'
                if (_tokenizer.Current.Token != Token.CloseParens)
                {
                    throw new SyntaxException("Missing close parenthesis");
                }
                _tokenizer.MoveNext();

                // Return
                return(node);
            }

            // Variable
            if (_tokenizer.Current.Token == Token.Identifier)
            {
                // Capture the name and skip it
                var name = _tokenizer.Current.Identifier;
                _tokenizer.MoveNext();

                // Parens indicate a function call, otherwise just a variable
                if (_tokenizer.Current.Token != Token.OpenParens)
                {
                    return(Expr.VariableOrConst(name));
                }
                else
                {
                    // Function call

                    // Skip parens
                    _tokenizer.MoveNext();

                    // Parse arguments
                    var arguments = new List <Expr>();
                    while (true)
                    {
                        // Parse argument and add to list
                        arguments.Add(ParseAddSubtract());

                        // Is there another argument?
                        if (_tokenizer.Current.Token == Token.Comma)
                        {
                            _tokenizer.MoveNext();
                            continue;
                        }

                        // Get out
                        break;
                    }

                    // Check and skip ')'
                    if (_tokenizer.Current.Token != Token.CloseParens)
                    {
                        throw new SyntaxException("Missing close parenthesis");
                    }
                    _tokenizer.MoveNext();

                    // Create the function call node
                    switch (arguments.Count)
                    {
                    case 1:
                        if (FindOperation(name, out UnaryOp uop))
                        {
                            return(Expr.Unary(uop, arguments[0]));
                        }
                        throw new ArgumentException($"Invalid unary function {name}");

                    case 2:
                        if (FindOperation(name, out BinaryOp bop))
                        {
                            return(Expr.Binary(bop, arguments[0], arguments[1]));
                        }
                        throw new ArgumentException($"Invalid binary function {name}");

                    default:
                        throw new SyntaxException("Invalid number of arguments");
                    }
                }
            }

            // Don't Understand
            throw new SyntaxException($"Unexpected token: {_tokenizer.Current.Token}");
        }
Пример #40
0
        public override object GetValor(Entorno e, LinkedList <Salida> log, LinkedList <Error> errores)
        {
            object valExpr = Expr.GetValor(e, log, errores);

            if (valExpr != null)
            {
                if (valExpr is Throw)
                {
                    return(valExpr);
                }

                if (InExpr == null)
                {
                    Tipo = Expr.Tipo;
                    return(valExpr);
                }
                else
                {
                    Tipo = new Tipo(Type.BOOLEAN);

                    foreach (Expresion exprActual in InExpr)
                    {
                        object valExprActual = exprActual.GetValor(e, log, errores);

                        if (valExprActual != null)
                        {
                            if (valExprActual is Throw)
                            {
                                return(valExprActual);
                            }

                            if (exprActual.Tipo.IsCollection())
                            {
                                Collection collection = (Collection)valExprActual;
                                if (Expr.Tipo.Equals(collection.Tipo.Valor))
                                {
                                    foreach (CollectionValue value in collection.Valores)
                                    {
                                        if (valExpr.Equals(value.Valor))
                                        {
                                            return(true);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (Expr.Tipo.Equals(exprActual.Tipo))
                                {
                                    if (valExpr.Equals(valExprActual))
                                    {
                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                    return(false);
                }
            }
            return(null);
        }
 public void ExpressionTypeTest()
 {
     Assert.That(Expr.Parameter(0, typeof(byte)).ExpressionType, Is.EqualTo(typeof(byte)));
 }
        public void Should_not_allow_parameter_index_being_outside_of_bounds()
        {
            var ex = Assert.Throws <InvalidOperationException>(() => CreateFunc <int, int>(Expr.Return(Expr.Parameter(1, typeof(int)))));

            Assert.That(ex.Message, Is.StringContaining("Parameter index 1 is outside of bounds. Expected parameters: [System.Int32]"));
        }
Пример #43
0
 private void ParseWhere()
 {
     _tokenIt.ExpectIdText("where");
     _filter = _parser.ParseExpression(_terminators, enablePlugins: true, passNewLine: false);
 }
Пример #44
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void pushVariables(ExprAbstractEvaluationContext paramExprAbstractEvaluationContext, org.boris.expr.Expr[] paramArrayOfExpr) throws org.boris.expr.ExprException
        public virtual void pushVariables(ExprAbstractEvaluationContext paramExprAbstractEvaluationContext, Expr[] paramArrayOfExpr)
        {
            bool @bool = false;

            if (this.jsLanguage && this.engine == null)
            {
                @bool = true;
            }
            this.previousArgs.Clear();
            sbyte b = 0;

            foreach (FunctionArgumentTable functionArgumentTable in this.inputArguments)
            {
                if (paramExprAbstractEvaluationContext.hasAdditionalVariable(this.fTable.Name.ToUpper()))
                {
                    this.previousArgs[functionArgumentTable.Name] = paramExprAbstractEvaluationContext.getAdditionalVariableValue(functionArgumentTable.Name);
                }
                paramExprAbstractEvaluationContext.addAdditionalVariable(functionArgumentTable.Name.ToUpper(), paramArrayOfExpr[b]);
                if (this.jsLanguage)
                {
                    if (paramArrayOfExpr[b] is ExprDouble)
                    {
                        Engine.put(functionArgumentTable.Name, Convert.ToDouble(((ExprDouble)paramArrayOfExpr[b]).doubleValue()));
                    }
                    else if (paramArrayOfExpr[b] is ExprInteger)
                    {
                        Engine.put(functionArgumentTable.Name, Convert.ToInt32(((ExprInteger)paramArrayOfExpr[b]).intValue()));
                    }
                    else if (paramArrayOfExpr[b] is ExprBoolean)
                    {
                        Engine.put(functionArgumentTable.Name, Convert.ToBoolean(((ExprBoolean)paramArrayOfExpr[b]).booleanValue()));
                    }
                    else if (paramArrayOfExpr[b] is ExprArray)
                    {
                        Engine.put(functionArgumentTable.Name, ExprArrayUtil.toObjectArray((ExprArray)paramArrayOfExpr[b]));
                    }
                    else
                    {
                        Engine.put(functionArgumentTable.Name, ((ExprString)paramArrayOfExpr[b]).str);
                    }
                }
                b++;
            }
            foreach (FunctionArgumentTable functionArgumentTable in this.constArguments)
            {
                if (paramExprAbstractEvaluationContext.hasAdditionalVariable(this.fTable.Name.ToUpper()))
                {
                    this.previousArgs[functionArgumentTable.Name] = paramExprAbstractEvaluationContext.getAdditionalVariableValue(functionArgumentTable.Name);
                }
                Expr expr = evaluateConstant(paramExprAbstractEvaluationContext, functionArgumentTable);
                paramExprAbstractEvaluationContext.addAdditionalVariable(functionArgumentTable.Name.ToUpper(), expr);
                if (this.jsLanguage)
                {
                    if (expr is ExprDouble)
                    {
                        Engine.put(functionArgumentTable.Name, Convert.ToDouble(((ExprDouble)expr).doubleValue()));
                        continue;
                    }
                    if (expr is ExprInteger)
                    {
                        Engine.put(functionArgumentTable.Name, Convert.ToInt32(((ExprInteger)expr).intValue()));
                        continue;
                    }
                    if (expr is ExprBoolean)
                    {
                        Engine.put(functionArgumentTable.Name, Convert.ToInt32(((ExprBoolean)expr).intValue()));
                        continue;
                    }
                    if (paramArrayOfExpr[b] is ExprArray)
                    {
                        Engine.put(functionArgumentTable.Name, ExprArrayUtil.toObjectArray((ExprArray)paramArrayOfExpr[b]));
                        continue;
                    }
                    Engine.put(functionArgumentTable.Name, ((ExprString)expr).str);
                }
            }
            if (@bool)
            {
                string str = "function " + this.fTable.Name + "() {" + this.fTable.Implementation + "\n}";
                try
                {
                    Engine.eval(str);
                }
                catch (ScriptException scriptException)
                {
                    string str1 = scriptException.Message;
                    if (scriptException.InnerException != null)
                    {
                        str1 = scriptException.InnerException.Message;
                    }
                    if (str1.IndexOf(":", StringComparison.Ordinal) != -1)
                    {
                        str1 = str1.Substring(str1.LastIndexOf(":", StringComparison.Ordinal));
                    }
                    throw new ExprException(str1);
                }
                catch (Exception exception)
                {
                    throw new ExprException(exception.Message);
                }
            }
        }
Пример #45
0
    protected override void InitializeTargetObject()
    {
        base.InitializeTargetObject();

        if (ContextID == null)
        {
            GoToMissingRecordPage();
        }

        Search s = new Search(msInvoice.CLASS_NAME);

        s.AddCriteria(Expr.Equals("ID", ContextID));
        s.AddOutputColumn("LocalID");
        s.AddOutputColumn("Date");
        s.AddOutputColumn("Total");
        s.AddOutputColumn("BalanceDue");
        s.AddOutputColumn("AmountPaid");
        s.AddOutputColumn("Order");
        s.AddOutputColumn("Order.Name");
        s.AddOutputColumn("BillTo.Name");
        s.AddOutputColumn("BillTo");
        s.AddOutputColumn("BillingAddress");
        s.AddOutputColumn("PurchaseOrderNumber");

        var sr = APIExtensions.GetSearchResult(s, 0, 1);

        if (sr.TotalRowCount == 0)
        {
            GoToMissingRecordPage();
        }

        targetInvoice = sr.Table.Rows[0];


        if (string.IsNullOrWhiteSpace(LeaderOfId))
        {
            return;
        }

        var leaderOf = APIExtensions.LoadObjectFromAPI(LeaderOfId);

        switch (leaderOf.ClassType)
        {
        case msChapter.CLASS_NAME:
            targetChapter = leaderOf.ConvertTo <msChapter>();
            break;

        case msSection.CLASS_NAME:
            targetSection = leaderOf.ConvertTo <msSection>();
            break;

        case msOrganizationalLayer.CLASS_NAME:
            targetOrganizationalLayer = leaderOf.ConvertTo <msOrganizationalLayer>();
            break;

        default:
            QueueBannerError(string.Format("Invalid leader object type specified '{0}'",
                                           leaderOf.ClassType));
            GoHome();
            return;
        }
    }
Пример #46
0
        [ContractVerification(false)] // F: Clousot ForAll decompilation gets confused below. Setting verification off until I fixed the bug
        internal Quantifier(Context ctx, bool isForall, Sort[] sorts, Symbol[] names, Expr body, uint weight = 1, Pattern[] patterns = null, Expr[] noPatterns = null, Symbol quantifierID = null, Symbol skolemID = null)
            : base(ctx, IntPtr.Zero)
        {
            Contract.Requires(ctx != null);
            Contract.Requires(sorts != null);
            Contract.Requires(names != null);
            Contract.Requires(body != null);
            Contract.Requires(sorts.Length == names.Length);
            Contract.Requires(Contract.ForAll(sorts, s => s != null));
            Contract.Requires(Contract.ForAll(names, n => n != null));
            Contract.Requires(patterns == null || Contract.ForAll(patterns, p => p != null));
            Contract.Requires(noPatterns == null || Contract.ForAll(noPatterns, np => np != null));

            Context.CheckContextMatch <Pattern>(patterns);
            Context.CheckContextMatch <Expr>(noPatterns);
            Context.CheckContextMatch <Sort>(sorts);
            Context.CheckContextMatch <Symbol>(names);
            Context.CheckContextMatch(body);

            if (sorts.Length != names.Length)
            {
                throw new Z3Exception("Number of sorts does not match number of names");
            }

            if (noPatterns == null && quantifierID == null && skolemID == null)
            {
                NativeObject = Native.Z3_mk_quantifier(ctx.nCtx, (isForall) ? 1 : 0, weight,
                                                       AST.ArrayLength(patterns), AST.ArrayToNative(patterns),
                                                       AST.ArrayLength(sorts), AST.ArrayToNative(sorts),
                                                       Symbol.ArrayToNative(names),
                                                       body.NativeObject);
            }
            else
            {
                NativeObject = Native.Z3_mk_quantifier_ex(ctx.nCtx, (isForall) ? 1 : 0, weight,
                                                          AST.GetNativeObject(quantifierID), AST.GetNativeObject(skolemID),
                                                          AST.ArrayLength(patterns), AST.ArrayToNative(patterns),
                                                          AST.ArrayLength(noPatterns), AST.ArrayToNative(noPatterns),
                                                          AST.ArrayLength(sorts), AST.ArrayToNative(sorts),
                                                          Symbol.ArrayToNative(names),
                                                          body.NativeObject);
            }
        }
        public void Should_properly_map_parameters_with_this()
        {
            MethodInfo mi   = typeof(DerivedType).GetMethod("Call");
            var        func = CreateFunc <DerivedType, int, DerivedType>(Expr.Return(Expr.Call(Expr.Parameter(0, typeof(DerivedType)), mi, Expr.Parameter(1, typeof(int)))));
            var        obj  = func(new DerivedType(), 32);

            Assert.That(obj.X, Is.EqualTo(32));
        }
Пример #48
0
        public Image EvaluateToImage(Expr exprObject, int width = 0, int height = 0)
        {
            CacheMisses++;

            return(KernelLink.EvaluateToImage(exprObject, width, height));
        }
        public void Should_not_allow_parameter_type_be_implicitly_boxed()
        {
            var ex = Assert.Throws <InvalidOperationException>(() => CreateFunc <int, int>(Expr.Return(Expr.Convert(Expr.Parameter(0, typeof(object)), typeof(int)))));

            Assert.That(ex.Message, Is.StringContaining("Parameter index 0 is of System.Object type, while type System.Int32 is expected"));
        }
Пример #50
0
        public Image EvaluateToTypeset(Expr exprObject, int width = 0)
        {
            CacheMisses++;

            return(KernelLink.EvaluateToTypeset(exprObject, width));
        }
 public void Should_not_allow_null_type()
 {
     Assert.Throws <ArgumentNullException>(() => Expr.Parameter(0, null));
 }
Пример #52
0
        public TrafficNetworkModel
            (int numberOfNodes,
            int source_idx,
            int sink_idx,
            int[]    arc_i,
            int[]    arc_j,
            double[] arcSensitivity,
            double[] arcCapacity,
            double[] arcBaseTravelTime,
            double T) : base("Traffic Network")

        {
            bool finished = false;

            try
            {
                int n     = numberOfNodes;
                int narcs = arc_j.Length;

                double[] n_ones = new double[narcs]; for (int i = 0; i < narcs; ++i)
                {
                    n_ones[i] = 1.0;
                }
                Set    NxN  = Set.Make(n, n);
                Matrix sens =
                    Matrix.Sparse(n, n, arc_i, arc_j, arcSensitivity);
                Matrix cap =
                    Matrix.Sparse(n, n, arc_i, arc_j, arcCapacity);
                Matrix basetime =
                    Matrix.Sparse(n, n, arc_i, arc_j, arcBaseTravelTime);
                Matrix e =
                    Matrix.Sparse(n, n, arc_i, arc_j, n_ones);
                Matrix e_e =
                    Matrix.Sparse(n, n,
                                  new int[]  { sink_idx }, new int[] { source_idx },
                                  new double[] { 1.0 });

                double[] cs_inv = new double[narcs];
                double[] s_inv  = new double[narcs];
                for (int i = 0; i < narcs; ++i)
                {
                    cs_inv[i] = 1.0 / (arcSensitivity[i] * arcCapacity[i]);
                }
                for (int i = 0; i < narcs; ++i)
                {
                    s_inv[i] = 1.0 / arcSensitivity[i];
                }
                Matrix cs_inv_matrix = Matrix.Sparse(n, n, arc_i, arc_j, cs_inv);
                Matrix s_inv_matrix  = Matrix.Sparse(n, n, arc_i, arc_j, s_inv);

                flow = Variable("traffic_flow", NxN, Domain.GreaterThan(0.0));

                Variable x = flow;
                Variable t = Variable("travel_time", NxN, Domain.GreaterThan(0.0));
                Variable d = Variable("d", NxN, Domain.GreaterThan(0.0));
                Variable z = Variable("z", NxN, Domain.GreaterThan(0.0));


                // Set the objective:
                Objective("Average travel time", ObjectiveSense.Minimize,
                          Expr.Mul(1.0 / T, Expr.Add(Expr.Dot(basetime, x), Expr.Dot(e, d))));

                // Set up constraints
                // Constraint (1a)
                {
                    Variable[][] v = new Variable[narcs][];
                    for (int i = 0; i < narcs; ++i)
                    {
                        v[i] = new Variable[3] {
                            d.Index(arc_i[i], arc_j[i]),
                            z.Index(arc_i[i], arc_j[i]),
                            x.Index(arc_i[i], arc_j[i])
                        };
                    }
                    Constraint("(1a)", mosek.fusion.Var.Stack(v), Domain.InRotatedQCone(narcs, 3));
                }

                // Constraint (1b)
                //
                Constraint("(1b)",
                           Expr.Sub(Expr.Add(Expr.MulElm(z, e),
                                             Expr.MulElm(x, cs_inv_matrix)),
                                    s_inv_matrix),
                           Domain.EqualsTo(0.0));

                // Constraint (2)
                Constraint("(2)", Expr.Sub(Expr.Add(Expr.MulDiag(x, e.Transpose()),
                                                    Expr.MulDiag(x, e_e.Transpose())),
                                           Expr.Add(Expr.MulDiag(x.Transpose(), e),
                                                    Expr.MulDiag(x.Transpose(), e_e))),
                           Domain.EqualsTo(0.0));
                // Constraint (3)
                Constraint("(3)", x.Index(sink_idx, source_idx), Domain.EqualsTo(T));
                finished = true;
            }
            finally
            {
                if (!finished)
                {
                    Dispose();
                }
            }
        }
Пример #53
0
 protected MathematicaExpression(MathematicaInterface parentCas, Expr mathExpr)
 {
     CasInterface = parentCas;
     ExpressionId = GetNewExprId();
     Expression   = mathExpr;
 }
Пример #54
0
 public CalcPosts(PostHandler handler, Expr amountExpr, bool calcRunningTotal = false)
     : base(handler)
 {
     AmountExpr       = amountExpr;
     CalcRunningTotal = calcRunningTotal;
 }
Пример #55
0
 public static MathematicaExpression Create(MathematicaInterface parentCas, Expr mathExpr)
 {
     return(new MathematicaExpression(parentCas, mathExpr));
 }
Пример #56
0
    private Stmt ParseStmt()
    {
        Stmt resultado;

        if (this.indice == this.tokens.Count)
        {
            throw new System.Exception("se esperaban sentencias, se llego al final del archivo");
        }

        // <stmt> := print <expr>

        // <expr> := <string>
        // | <int>
        // | <arith_expr>
        // | <ident>
        if (this.tokens[this.indice].Equals("print"))
        {
            this.indice++;
            Print print = new Print();
            print.Expr = this.ParseExpr();
            resultado  = print;
        }
        else if (this.tokens[this.indice].Equals("var"))
        {
            this.indice++;
            DeclareVar declareVar = new DeclareVar();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                declareVar.Ident = (string)this.tokens[this.indice];
            }
            else
            {
                throw new System.Exception("Se esperaba nombre de variable despues de 'var'");
            }

            this.indice++;

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("se esperaba = despues de 'var ident'");
            }

            this.indice++;

            declareVar.Expr = this.ParseExpr();
            resultado       = declareVar;
        }
        else if (this.tokens[this.indice].Equals("read_int"))
        {
            this.indice++;
            ReadInt readInt = new ReadInt();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                readInt.Ident = (string)this.tokens[this.indice++];
                resultado     = readInt;
            }
            else
            {
                throw new System.Exception("Se esperaba el nombre de la variable 'read_int'");
            }
        }
        //*******************
        else if (this.tokens[this.indice].Equals("if"))
        {
            this.indice++;
            mcIf mcif = new mcIf();
            Expr temp = ParseExpr();
            if (this.tokens[this.indice] == Scanner.Eq || this.tokens[this.indice] == Scanner.Neq ||
                this.tokens[this.indice] == Scanner.Gt || this.tokens[this.indice] == Scanner.Gte ||
                this.tokens[this.indice] == Scanner.Lt || this.tokens[this.indice] == Scanner.Lte)
            {
                CompExpr compExpr = new CompExpr();
                compExpr.Left = temp;
                object op = this.tokens[this.indice++];
                if (op == Scanner.Eq)
                {
                    compExpr.Op = CompOp.Eq;
                }
                else if (op == Scanner.Neq)
                {
                    compExpr.Op = CompOp.Neq;
                }
                else if (op == Scanner.Gt)
                {
                    compExpr.Op = CompOp.Gt;
                }
                else if (op == Scanner.Gte)
                {
                    compExpr.Op = CompOp.Gte;
                }
                else if (op == Scanner.Lt)
                {
                    compExpr.Op = CompOp.Lt;
                }
                else if (op == Scanner.Lte)
                {
                    compExpr.Op = CompOp.Lte;
                }
                compExpr.Rigth = ParseExpr();
                temp           = compExpr;
            }
            mcif.compExpr = temp;
            if (this.indice == this.tokens.Count || !this.tokens[this.indice].Equals("then"))
            {
                throw new System.Exception("Se esperaba el identificador 'then' despues de 'if'");
            }
            this.indice++;
            mcif.Then = ParseStmt();
            if (this.tokens[this.indice].Equals("else"))
            {
                this.indice++;
                mcif.Else = ParseStmt();
            }

            resultado = mcif;
            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("Sentencia if inconclusa");
            }

            this.indice++;
        }
        else if (this.tokens[this.indice].Equals("while"))
        {
            this.indice++;
            WhileLoop whileLoop = new WhileLoop();
            Expr      temp      = ParseExpr();
            if (this.tokens[this.indice] == Scanner.Eq || this.tokens[this.indice] == Scanner.Neq ||
                this.tokens[this.indice] == Scanner.Gt || this.tokens[this.indice] == Scanner.Gte ||
                this.tokens[this.indice] == Scanner.Lt || this.tokens[this.indice] == Scanner.Lte)
            {
                CompExpr compExpr = new CompExpr();
                compExpr.Left = temp;
                object op = this.tokens[this.indice++];
                if (op == Scanner.Eq)
                {
                    compExpr.Op = CompOp.Eq;
                }
                else if (op == Scanner.Neq)
                {
                    compExpr.Op = CompOp.Neq;
                }
                else if (op == Scanner.Gt)
                {
                    compExpr.Op = CompOp.Gt;
                }
                else if (op == Scanner.Gte)
                {
                    compExpr.Op = CompOp.Gte;
                }
                else if (op == Scanner.Lt)
                {
                    compExpr.Op = CompOp.Lt;
                }
                else if (op == Scanner.Lte)
                {
                    compExpr.Op = CompOp.Lte;
                }
                compExpr.Rigth = ParseExpr();
                temp           = compExpr;
            }
            whileLoop.Cond = temp;
            if (this.indice == this.tokens.Count || !this.tokens[this.indice].Equals("do"))
            {
                throw new System.Exception("Se esperaba el identificador 'do' despues de 'while'");
            }
            this.indice++;
            whileLoop.Body = ParseStmt();
            resultado      = whileLoop;
            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("sentencia while inconclusa");
            }
            this.indice++;
        }
        //*******************
        else if (this.tokens[this.indice].Equals("for"))
        {
            this.indice++;
            ForLoop forLoop = new ForLoop();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                forLoop.Ident = (string)this.tokens[this.indice];
            }
            else
            {
                throw new System.Exception("se esperaba un indentificador despues de 'for'");
            }

            this.indice++;

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("no se encontro en la sentencia for '='");
            }

            this.indice++;

            forLoop.From = this.ParseExpr();

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("to"))
            {
                throw new System.Exception("se epsaraba 'to' despues de for");
            }

            this.indice++;

            forLoop.To = this.ParseExpr();

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("do"))
            {
                throw new System.Exception("se esperaba 'do' despues de la expresion en el ciclo for");
            }

            this.indice++;

            forLoop.Body = this.ParseStmt();
            resultado    = forLoop;

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("setencia for inconclusa");
            }

            this.indice++;
        }
        else if (this.tokens[this.indice] is string)
        {
            // assignment

            Assign assign = new Assign();
            assign.Ident = (string)this.tokens[this.indice++];

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("se esperaba '='");
            }

            this.indice++;

            assign.Expr = this.ParseExpr();
            resultado   = assign;
        }
        else
        {
            throw new System.Exception("Error en el token " + this.indice + ": " + this.tokens[this.indice]);
        }

        if (this.indice < this.tokens.Count && this.tokens[this.indice] == Scanner.PyC)
        {
            this.indice++;

            if (this.indice < this.tokens.Count &&
                !this.tokens[this.indice].Equals("end") && !this.tokens[this.indice].Equals("else"))
            {
                Sequence sequence = new Sequence();
                sequence.First  = resultado;
                sequence.Second = this.ParseStmt();
                resultado       = sequence;
            }
        }

        return(resultado);
    }
Пример #57
0
 private ExprResult FinishCall(Expr expr) =>
 from args in Arguments().ToList().ToResult()
 from rParen in Consume(TokenType.RightParen, "Expected ')'.")
 select new CallExpr(expr, rParen, args) as Expr;
Пример #58
0
        private List <Block> CreateAssertsBlocks(Implementation queryImplementation, Implementation targetImplementation, List <Tuple <Variable, Expr, Expr> > assumeVars)
        {
            var exprs       = CreateAssertsExprs(queryImplementation, targetImplementation);
            var assertsCmds = CreateAsserts(exprs);

            queryImplementation.InParams.Iter(iq =>
            {
                targetImplementation.InParams.Iter(it =>
                {
                    if (Equals(iq.TypedIdent.Type, it.TypedIdent.Type))
                    {
                        var eqVar = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, AssumeVarPrefix + "_" + _eqVarsCounter++, BType.Bool));
                        assumeVars.Add(new Tuple <Variable, Expr, Expr>(eqVar, Expr.Ident(iq), Expr.Ident(it)));
                        queryImplementation.Blocks[0].Cmds.Insert(0, Utils.BoogieUtils.CreateAssignCmd(new List <IdentifierExpr>()
                        {
                            Expr.Ident(eqVar)
                        }, new List <Expr>()
                        {
                            Expr.Eq(Expr.Ident(iq), Expr.Ident(it))
                        }));
                    }
                });
            });

            // The equality vars are grouped according to lhs. This means that expressions like eq_0 = `rax == v2.rcx` and eq_13 = `rax == v2.p0` will be
            // grouped together, to make the assumes choosing algorithm more efficient (we won't select eq_0 and eq_13 for the same section)
            var eqVarsGroups = new Dictionary <string, List <Tuple <Variable, Expr, Expr> > >();

            assumeVars.Iter(t =>
            {
                var lhs = t.Item2.ToString();
                if (!eqVarsGroups.ContainsKey(lhs))
                {
                    eqVarsGroups[lhs] = new List <Tuple <Variable, Expr, Expr> >();
                }
                eqVarsGroups[lhs].Add(t);
            });
            assumeVars.Iter(t => queryImplementation.LocVars.Add(t.Item1));
            return(CreateAssertsWithAssumes(eqVarsGroups.Values.ToList(), assertsCmds));
        }
Пример #59
0
    public static List <string> GetEntitiesEligibleForGroupRegistration(msEvent targetEvent, msEntity currentEntity, IConciergeAPIService api)
    {
        if (targetEvent == null)
        {
            throw new ArgumentNullException("targetEvent");
        }
        if (api == null)
        {
            throw new ArgumentNullException("api");
        }

        List <string> applicableRelationshipTypes = targetEvent.SafeGetValue <List <string> >("GroupRegistrationRelationshipTypes");

        if (applicableRelationshipTypes == null || applicableRelationshipTypes.Count == 0)
        {
            return(null); // there are no registration types enabled
        }
        if (currentEntity == null)
        {
            return(null);
        }


        List <string> entities = new List <string>();

        if (currentEntity.ClassType == msOrganization.CLASS_NAME) // an organization can always manage themselves
        {
            entities.Add(currentEntity.ID);
            return(entities);
        }

        // OK, let's see if this person is linked to any companies
        Search s = new Search("RelationshipsForARecord");

        s.Context = currentEntity.ID;
        s.AddCriteria(Expr.Equals("IsLeftSide", false));   // the right side of the relationship is the individual
        // MSIV-5 Indivdiuals with expired relationships should not be eligible for Event Group Registration
        var sog1 = new SearchOperationGroup {
            GroupType = SearchOperationGroupType.Or
        };

        sog1.Criteria.Add(Expr.Equals(msRelationship.FIELDS.StartDate, null));
        sog1.Criteria.Add(Expr.IsLessThanOrEqual(msRelationship.FIELDS.StartDate, DateTime.Today.Date));
        s.AddCriteria(sog1);
        var sog2 = new SearchOperationGroup {
            GroupType = SearchOperationGroupType.Or
        };

        sog2.Criteria.Add(Expr.Equals(msRelationship.FIELDS.EndDate, null));
        sog2.Criteria.Add(Expr.IsGreaterThan(msRelationship.FIELDS.EndDate, DateTime.Today.Date));
        s.AddCriteria(sog2);

        // now, we do an is one of the follow for relationship types
        IsOneOfTheFollowing isTypes = new IsOneOfTheFollowing {
            FieldName = "Type_ID"
        };

        isTypes.ValuesToOperateOn = new List <object>(applicableRelationshipTypes);

        s.AddCriteria(isTypes);

        s.AddOutputColumn("Target_ID");

        var values = api.GetSearchResult(s, 0, null).Table;

        foreach (DataRow dr in values.Rows)
        {
            entities.Add(Convert.ToString(dr["Target_ID"]));
        }

        // keep in mind we may have orphaned relationships, so we have to make sure each org ID exists!
        return(entities.Distinct().ToList());
    }
Пример #60
0
 public TupleLiteralElement Clone(CloneContext clonectx)
 {
     return(new TupleLiteralElement(Name, Expr.Clone(clonectx), Location));
 }