コード例 #1
0
        public static IQueryable OrderBy(this IQueryable source, string ordering, QueryResolver queryResolver)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (ordering == null)
            {
                throw new ArgumentNullException("ordering");
            }

            ParameterExpression[] parameters = new ParameterExpression[] 
            {
                Expression.Parameter(source.ElementType, "") 
            };
            ExpressionParser parser = new ExpressionParser(parameters, ordering, queryResolver);
            IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
            Expression queryExpr = source.Expression;
            string methodAsc = "OrderBy";
            string methodDesc = "OrderByDescending";
            foreach (DynamicOrdering o in orderings)
            {
                queryExpr = Expression.Call(
                    typeof(Queryable),
                    o.Ascending ? methodAsc : methodDesc,
                    new Type[] { source.ElementType, o.Selector.Type },
                    queryExpr,
                    Expression.Quote(DynamicExpression.Lambda(o.Selector, parameters)));
                methodAsc = "ThenBy";
                methodDesc = "ThenByDescending";
            }
            return source.Provider.CreateQuery(queryExpr);
        }
コード例 #2
0
ファイル: Calculator.cs プロジェクト: gaiazov/Calculator
 public double Calculate(string expressionString)
 {
     var parser = new ExpressionParser(expressionString);
     var expression = parser.Parse();
     var result = expression.Evaluate();
     return result;
 }
コード例 #3
0
ファイル: ParserTests.cs プロジェクト: helgihaf/Alpha
        public void TestParse()
        {
            ExpressionParser parser = new ExpressionParser();
            Node node = parser.Parse("1 + 2 * 3");

            BinaryNode plusNode = node as BinaryNode;
            Assert.IsNotNull(plusNode);
            Assert.AreEqual(BinaryOperator.Add, plusNode.Operator);

            IntLiteralNode leftNode = plusNode.Left as IntLiteralNode;
            Assert.IsNotNull(leftNode);
            Assert.AreEqual(1, leftNode.Value);

            BinaryNode multiplyNode = plusNode.Right as BinaryNode;
            Assert.IsNotNull(multiplyNode);
            Assert.AreEqual(BinaryOperator.Multiply, multiplyNode.Operator);

            IntLiteralNode multLeftNode = multiplyNode.Left as IntLiteralNode;
            Assert.IsNotNull(multLeftNode);
            Assert.AreEqual(2, multLeftNode.Value);

            IntLiteralNode multRightNode = multiplyNode.Right as IntLiteralNode;
            Assert.IsNotNull(multRightNode);
            Assert.AreEqual(3, multRightNode.Value);
        }
コード例 #4
0
        private static Expression ParseTokens(CommonTokenStream input)
        {
            ExpressionParser.ExpressionContext startContext = new ExpressionParser(input).expression();

            ExpressionVisitor visit = new ExpressionVisitor();
            Expression expr = visit.Visit(startContext);
            return expr;
        }
コード例 #5
0
ファイル: Expressions.cs プロジェクト: elkdanger/kilo
        public void Can_get_expression_path()
        {
            ExpressionParser<TestNestedObject, object> parser = new ExpressionParser<TestNestedObject, object>();

            string path = parser.GetPropertyPathFromExpression(t => t.Name);

            Assert.AreEqual("Name", path);
        }
コード例 #6
0
            public void FloatsAreParsedToAConstExpression()
            {
                var parser = new ExpressionParser(new FakeScanner(new[] { new Token("FLOAT", "2.34", 0, 0, 0) }));

                var result = parser.ParseAll();

                Assert.AreEqual(typeof(ConstantExpr), result.GetType());
            }
コード例 #7
0
ファイル: ParserTests.cs プロジェクト: helgihaf/Alpha
 public void TestVisitor()
 {
     var visitor = new WriterVisitor();
     ExpressionParser parser = new ExpressionParser();
     Node node = parser.Parse("1 + 2 * 3");
     // ( 1  Plus ( 2  Multiply  3 ))
     node.Accept(visitor);
 }
コード例 #8
0
            public void IntegersAreParsedToAConstExpression()
            {
                var parser = new ExpressionParser(new FakeScanner(new [] { new Token("INTEGER", "1", 0, 0, 0) }));

                var result = parser.ParseAll();

                Assert.AreEqual(typeof(ConstantExpr), result.GetType());
            }
コード例 #9
0
ファイル: FloatFormula.cs プロジェクト: AlKoulounil/GBG
		public override void Initialize (IFormulaParent _parent)
		{
			base.Initialize (_parent);

			ExpressionParser parser = new ExpressionParser ();
			Expression expression = parser.EvaluateExpression (mFormulaText);
			ApplyFormula = expression.ToDelegate(new List<string>(mParameters.Keys).ToArray());
		}
コード例 #10
0
        private static void TestParse(string text)
        {
            var expression = new ExpressionParser().Parse(text);

            Console.WriteLine(text);
            Console.WriteLine(expression);

            Assert.That(expression.ToString(), Is.EqualTo(text));
        }
コード例 #11
0
		public void StringAndCodeDomExpressionParserPerformanceCheck()
		{
			var stringExpressionParser = new ExpressionParser();

			var codeDomExpressionParser = new CachedCodeDomExpressionParser();

			CheckPerformance(stringExpressionParser, KnownExpressions.SingleProperty.Source);

			CheckPerformance(codeDomExpressionParser, KnownExpressions.SingleProperty.Compiled);
		}
コード例 #12
0
 //Source: http://wiki.unity3d.com/index.php/ExpressionParser#ExpressionParser.cs
 void Start()
 {
     string s = "(4+1333)/1337+5-27*2";
     string f = "(3*(2))/6+6";
     var parser = new ExpressionParser();
     Expression exp = parser.EvaluateExpression(s);
     print (exp.Value);
     exp = parser.EvaluateExpression(f);
     print (exp.Value);
 }
コード例 #13
0
ファイル: FormBase.cs プロジェクト: Quaka95/MyGeoCoso
 //Costritture
 public FormBase()
 {
     InitializeComponent();
     par = new GraphParametr();
     bpar = new BisezioneParametr();
     spar = new SecantiParametr();
     tpar = new TagentiParametr();
     ipar = new IntegraliParametr();
     _parser = new ExpressionParser();
 }
コード例 #14
0
		public bool EvaluateAsBoolean (string source)
		{
			try {
				var el = new ExpressionParser ().Parse (source, ExpressionValidationType.StrictBoolean);
				if (el.Count () != 1)
					throw new InvalidProjectFileException ("Unexpected number of tokens: " + el.Count ());
				return el.First ().EvaluateAsBoolean (CreateContext (source));
			} catch (yyParser.yyException ex) {
				throw new InvalidProjectFileException (string.Format ("failed to evaluate expression as boolean: '{0}': {1}", source, ex.Message), ex);
			}
		}
コード例 #15
0
 public void ImplementsParse()
 {
     IParser target = new ExpressionParser(new FakeScanner(new []{ Token.Empty }));
     try
     {
         Expression actual = target.ParseAll();;
         Assert.Fail("No tokens to parse");
     }
     catch (ParseException)
     {
     }
 }
コード例 #16
0
        public void Enter_ConstantWithValue3_MustReturn3()
        {
            // Arrange
            var input = "3";
            var sut = new ExpressionParser();

            // Act
            IExpression actual = sut.Parse(input);

            // Assert
            Assert.AreEqual(3, actual.Eval());
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: gaiazov/Calculator
        static void Main()
        {
            while (true)
            {
                var expressionString = Console.ReadLine();
                var parser = new ExpressionParser(expressionString);
                var expression = parser.Parse();
                var result = expression.Evaluate();

                Console.WriteLine($"The outcome is {result}");
            }
        }
コード例 #18
0
        public void Input_MulAndSum()
        {
            // Arrange
            var input = "1 2 + 3 *";
            var sut = new ExpressionParser();

            // Act
            IExpression actual = sut.Parse(input);

            // Assert
            Assert.AreEqual(9, actual.Eval());
        }
コード例 #19
0
        public void Input_Sum()
        {
            // Arrange
            var input = "6 5 +";
            var sut = new ExpressionParser();

            // Act
            IExpression actual = sut.Parse(input);

            // Assert
            Assert.AreEqual(11, actual.Eval());
        }
コード例 #20
0
        public void Parse_AString_Should_Return_Stacked_Parts()
        {
            // Arrange
            var sut = new ExpressionParser();
            var input = "6 5 +";

            // Act
            var actual = sut.Parse(input);

            // Assert
            Assert.IsInstanceOfType(actual, typeof(SumExpression));
        }
コード例 #21
0
        public void Parse_AStringWithOnlyOneConstant_Should_Return_AConstantExpressionInTheStack()
        {
            // Arrange
            var sut = new ExpressionParser();
            var input = "6";

            // Act
            var actual = sut.Parse(input);

            // Assert
            Assert.IsInstanceOfType(actual, typeof(ConstantExpression));
        }
コード例 #22
0
    public void calculate()
    {
        if (infocus) {
            try {
                var parser = new ExpressionParser ();
                Expression exp = parser.EvaluateExpression (expression);
                hasValue = true;
                vAnswer = (float)exp.Value;

            } catch (UnityException e) {
                print (e);
                hasValue = false;
                vAnswer = 0;
            }
        }
    }
コード例 #23
0
        public void Input_SumAndThenSum()
        {
            // Arrange
            var input = "1 2 3 * + ";
            var sut = new ExpressionParser();

            // Act
            IExpression actual = sut.Parse(input);

            var v = new Visitor.Visitor();
            ((BinaryExpression)actual).Accept(v);

            // Assert
            Assert.AreEqual(7, actual.Eval());
            Assert.AreEqual("1 + 2 * 3", v.ToString());
        }
コード例 #24
0
ファイル: calcForm.cs プロジェクト: cschar1/testClusterRepo
        public calcForm()
        {
            InitializeComponent();

            factoryDataList = new List<dummyObject>();
            //Populate list to simulate variables user will do calculations with
            factoryDataList.Add(new dummyObject(50, "R1"));
            factoryDataList.Add(new dummyObject(5.75, "R2"));
            factoryDataList.Add(new dummyObject(1000, "R3"));

            foreach (dummyObject d in factoryDataList)
            {
                listBox1.Items.Add(d);
            }

            parser = new ExpressionParser(factoryDataList);
        }
コード例 #25
0
ファイル: Class1.cs プロジェクト: john-guo/hodgepodge
        static void Main()
        {
            var tree = CSharpSyntaxTree.ParseText(@"_(){
                () => 10;
                //i => ++i;
                //i => i;
                //()=> 3;
                //5+3;
                /*from method in type.GetMethods()
                        let parameters = from p in method.GetParameters() select p.ParameterType
                        where method.Name == name
                        where method.IsDefined(typeof(ExtensionAttribute), false)
                        where parameters.SequenceEqual(arguments, new ParameterComparer())
                        select method;*/
            ");

            var p = new ExpressionParser();
            var a = p.Parse<Func<int,int,int>>("(i,j)=>i=1").Compile();
            var i = a(2,1);
            Console.ReadLine();
        }
コード例 #26
0
        public void ExpressionParserAdditionParseTest()
        {
            CircuitTestSocket socket = null;
            ExpressionParser  parser = new ExpressionParser(socket);
            TruthState        state  = new TruthState(0, 0);

            this.Valid(parser, state, 0, "0 + 0");
            this.Valid(parser, state, 2, "1 + 1");
            this.Valid(parser, state, 6, "1 + 2 + 3");
            this.Valid(parser, state, -18, "10 + 2 - 30");
            this.Valid(parser, state, 8, "10 - 2");
            this.Valid(parser, state, -12, "-10 - 2");

            this.Invalid(parser, state, "3 + ");
            this.Invalid(parser, state, "5 - ");
            this.Invalid(parser, state, "3 - 2 + ");
            this.Invalid(parser, state, "3 + 2 - ");

            // check priority of expressions
            this.Valid(parser, state, 7, "1 + 3 * 2");
            this.Valid(parser, state, 8, "(1 + 3) * 2");
            this.Valid(parser, state, 26, "2 * 3 + 5 * 4");
            this.Valid(parser, state, -26, "-2 * 3 - 5 * 4");
        }
コード例 #27
0
        public void ExpressionParserConjunctionParseTest()
        {
            CircuitTestSocket socket = null;
            ExpressionParser  parser = new ExpressionParser(socket);
            TruthState        state  = new TruthState(0, 0);

            this.Valid(parser, state, 0, "0 | 0");
            this.Valid(parser, state, 1, "1 | 1");
            this.Valid(parser, state, 7, "1 | 2 | 4");
            this.Valid(parser, state, 1, "1 ^ 1 ^ 1");
            this.Valid(parser, state, 0, "1 ^ 1 ^ 1 ^ 1");
            this.Valid(parser, state, 0, "1 ^ 1");
            this.Valid(parser, state, 0, "198 ^ 198");
            this.Valid(parser, state, 3, "1 | 2");

            this.Invalid(parser, state, "3 | ");
            this.Invalid(parser, state, "5 ^ ");
            this.Invalid(parser, state, "3 | 2 ^ ");
            this.Invalid(parser, state, "3 ^ 2 | ");

            // check priority of expressions
            this.Valid(parser, state, 7, "7 | 2 & 1");
            this.Valid(parser, state, 6, "7 ^ 3 & 1");
        }
コード例 #28
0
        protected virtual void VisitValue(
            XElement element, XAttribute attribute,
            MSBuildElementSyntax resolvedElement, MSBuildAttributeSyntax resolvedAttribute,
            ITypedSymbol valueDescriptor, string value, int offset)
        {
            var kind = MSBuildCompletionExtensions.InferValueKindIfUnknown(valueDescriptor);

            if (!kind.AllowExpressions())
            {
                VisitValueExpression(
                    element, attribute, resolvedElement, resolvedAttribute,
                    valueDescriptor, kind, new ExpressionText(offset, value, true));
                return;
            }

            var expression =
                valueDescriptor?.ValueKind == MSBuildValueKind.Condition
                                        ? ExpressionParser.ParseCondition(value, offset)
                                        : ExpressionParser.Parse(value, kind.GetExpressionOptions(), offset);

            VisitValueExpression(
                element, attribute, resolvedElement, resolvedAttribute,
                valueDescriptor, kind, expression);
        }
コード例 #29
0
ファイル: MainForm.cs プロジェクト: TienLg/BetS
        private void btnExecute_Click(object sender, EventArgs e)
        {
            // get Numbers collection
            List<double[]> collectSet = collectNumbers();
            // Parse Expression
            ExpressionParser parser = new ExpressionParser();
            parser.Values.Add("a", 1);
            parser.Values.Add("b", 1);
            parser.Values.Add("c", 1);
            string func = tbFormula.Text;
            parser.Parse(func);
            Expression expression = parser.Expressions[func];

            // Reset
            if (statisticTable.Rows.Count > 0)
                statisticTable.Rows.Clear();
            dataView.RowFilter = "1=1";

            foreach (double[] arr in collectSet)
            {
                parser.Values["a"].SetValue(arr[0]);
                parser.Values["b"].SetValue(arr[1]);
                parser.Values["c"].SetValue(arr[2]);
                double result = parser.EvalExpression(expression);

                DataRow row = statisticTable.NewRow();
                row["NumberA"] = arr[0];
                row["NumberB"] = arr[1];
                row["NumberC"] = arr[2];
                row["Result"] = Math.Round(result, 4);
                statisticTable.Rows.Add(row);
            }

            // Fetch to DataGridView
            //dataGridView.DataSource = statisticTable;
        }
コード例 #30
0
        public void ResolveMethodArgumentsShouldReturnCorrectCollectionOfArgumentsInformation()
        {
            var requestModel = TestObjectFactory.GetValidRequestModel();

            object obj = 1;
            Expression <Func <WebApiController, IHttpActionResult> > expression = c => c.OkResultActionWithRequestBody((int)obj, requestModel);

            var result = ExpressionParser.ResolveMethodArguments(expression);

            var arguments      = result as IList <MethodArgumentInfo> ?? result.ToArray();
            var firstArgument  = arguments.First();
            var secondArgument = arguments.Last();
            var secondArgumentAsRequestModel = secondArgument.Value as RequestModel;

            Assert.AreEqual("id", firstArgument.Name);
            Assert.AreEqual(typeof(int), firstArgument.Type);
            Assert.AreEqual(1, firstArgument.Value);

            Assert.AreEqual("model", secondArgument.Name);
            Assert.AreEqual(typeof(RequestModel), secondArgument.Type);
            Assert.IsNotNull(secondArgumentAsRequestModel);
            Assert.AreEqual(2, secondArgumentAsRequestModel.Integer);
            Assert.AreEqual("Test", secondArgumentAsRequestModel.RequiredString);
        }
コード例 #31
0
        public void ParseDelegateTest_GenericList()
        {
            {
                string code     = "(m)=>new List<string>(){ Capacity = m * 3 }.Capacity";
                var    expected = new List <string>()
                {
                    Capacity = 3 * 3
                }.Capacity;

                Func <int, int> func   = ExpressionParser.Compile <Func <int, int> >(code, "System", "System.Collections.Generic");
                var             actual = func(3);
                Assert.AreEqual(expected, actual);
            }
            {
                string code     = "()=>new List<string>(){ \"abc\",\"def\" }[1]";
                var    expected = new List <string>()
                {
                    "abc", "def"
                }[1];

                var actual = ExpressionParser.Compile(code, "System", "System.Collections.Generic").DynamicInvoke();
                Assert.AreEqual(expected, actual);
            }
        }
コード例 #32
0
 //Metodi
 /// <summary>
 /// Pulisce i parametri
 /// </summary>
 public void Clear()
 {
     _a = 0; //Settaggio di default delle variabili
     _b = 0;
     _fa = 0;
     _fb = 0;
     _inc = 0;
     _tan = "";
     _x = 0;
     _parser = new ExpressionParser();
     _funzione = "";
     _precisione = 0;
     _cicli = 0;
 }
コード例 #33
0
        public static void RegisterServices(IServiceCollection services, [WebPartConfig("ContextSettings")] SecurityContextOptions contextOptions,
                                            [WebPartConfig("ActivationSettings")] ActivationOptions partActivation)
        {
            Type t = null;

            if (!string.IsNullOrEmpty(contextOptions.ContextType))
            {
                var dic = new Dictionary <string, object>();
                t = (Type)ExpressionParser.Parse(contextOptions.ContextType, dic);
            }

            if (partActivation.ActivateDbContext)
            {
                if (t != null)
                {
                    services.UseDbIdentities(t, options => options.UseSqlServer(partActivation.ConnectionStringName));
                }
                else
                {
                    services.UseDbIdentities(options => options.UseSqlServer(partActivation.ConnectionStringName));
                }
            }

            if (partActivation.UseNavigation)
            {
                if (t != null)
                {
                    services.UseDbNavigation(t);
                }
                else
                {
                    services.UseDbNavigation();
                }
            }

            if (partActivation.UsePlugins)
            {
                services.UseDbPlugins();
            }

            if (partActivation.UseGlobalSettings)
            {
                services.UseDbGlobalSettings();
            }

            if (partActivation.UseTenantSettings)
            {
                services.UseTenantSettings();
            }

            if (partActivation.UseLogAdapter)
            {
                services.UseDbLogAdapter();
            }

            /*if (!string.IsNullOrEmpty(options?.ContextType))
             * {
             *  var dic = new Dictionary<string, object>();
             *  var t = (Type)ExpressionParser.Parse(options.ContextType, dic);
             *  manager.EnableItvUserView(t);
             * }
             * else
             * {
             *  manager.EnableItvUserView();
             * }*/
        }
コード例 #34
0
        public void GetMethodNameShouldThrowArgumentExceptionWithInvalidMethodCallExpression()
        {
            Expression <Func <int> > expression = () => 0;

            ExpressionParser.GetMethodName(expression);
        }
コード例 #35
0
        //private void Parse(string expression)
        //{
        //    ExpressionNode root = ExpressionParser.Parse(expression, false);
        //    //validate name nodes

        //    this.BeginUpdate();
        //    this.Clear();

        //    Stack<ExpressionNode> nodeStack = new Stack<ExpressionNode>();
        //    nodeStack.Push(root);

        //    Stack<FilterExpressionCollection> collectionStack = new Stack<FilterExpressionCollection>();
        //    collectionStack.Push(this);

        //    while (nodeStack.Count > 0)
        //    {
        //        ExpressionNode current = nodeStack.Pop();
        //        FilterExpressionCollection expressions = collectionStack.Pop();

        //        UnaryOpNode unaryNode = current as UnaryOpNode;
        //        if (unaryNode != null)
        //        {
        //            if (unaryNode.Op == Operator.Noop)
        //            {
        //                nodeStack.Push(((UnaryOpNode)current).Right);
        //                collectionStack.Push(expressions);
        //                continue;
        //            }
        //        }

        //        BinaryOpNode binaryNode = current as BinaryOpNode;
        //        if (binaryNode != null)
        //        {
        //            if (this.IsPredicate(binaryNode))
        //            {
        //                FilterExpression filterExpression = new FilterExpression();
        //                expressions.Add(filterExpression);
        //                continue;
        //            }

        //            nodeStack.Push(binaryNode.Right);
        //            FilterExpressionCollection collection = expressions;
        //            if(!this.IsPredicate(binaryNode.Right))
        //            {
        //                CompositeFilterExpression  compositeExpression = new CompositeFilterExpression();
        //                expressions.Add(compositeExpression);
        //                collection = compositeExpression.FilterExpressions;
        //            }
        //            collectionStack.Push(collection);

        //            nodeStack.Push(binaryNode.Left);
        //            collection = expressions;
        //            if (!this.IsPredicate(binaryNode.Left))
        //            {
        //                CompositeFilterExpression compositeExpression = new CompositeFilterExpression();
        //                compositeExpression.BinaryOperator = (binaryNode.Op == Operator.And) ? FilterExpression.BinaryOperation.AND : FilterExpression.BinaryOperation.OR;
        //                expressions.Add(compositeExpression);
        //                collection = compositeExpression.FilterExpressions;
        //            }
        //            collectionStack.Push(collection);
        //        }
        //    }

        //    this.EndUpdate();
        //}

        //private bool IsPredicate(ExpressionNode node)
        //{
        //    while (node is UnaryOpNode)
        //    {
        //        node = ((UnaryOpNode)node).Right;
        //    }

        //    BinaryOpNode binaryNode = node as BinaryOpNode;
        //    if (binaryNode == null)
        //    {
        //        return false;
        //    }

        //    if (binaryNode.Left is NameNode || binaryNode.Right is NameNode)
        //    {
        //        return true;
        //    }

        //    return false;
        //}

        private void Parse(string expression)
        {
            ExpressionNode root = ExpressionParser.Parse(expression, false);

            //validate name nodes

            this.BeginUpdate();
            this.Clear();

            Stack <ExpressionNode> nodeStack = new Stack <ExpressionNode>();

            nodeStack.Push(root);

            Stack <FilterDescriptorCollection> collectionStack = new Stack <FilterDescriptorCollection>();

            collectionStack.Push(this);

            while (nodeStack.Count > 0)
            {
                ExpressionNode             current     = nodeStack.Pop();
                FilterDescriptorCollection expressions = collectionStack.Pop();

                UnaryOpNode unaryNode = current as UnaryOpNode;
                if (unaryNode != null)
                {
                    if (unaryNode.Op == Operator.Noop)
                    {
                        nodeStack.Push(((UnaryOpNode)current).Right);
                        collectionStack.Push(expressions);
                        continue;
                    }
                }

                BinaryOpNode binaryNode = current as BinaryOpNode;
                if (binaryNode != null)
                {
                    if (this.IsPredicate(binaryNode))
                    {
                        FilterDescriptor filterDescriptor = this.CreateFilterDescriptor(binaryNode);

                        expressions.Add(filterDescriptor);
                        continue;
                    }

                    nodeStack.Push(binaryNode.Right);
                    FilterDescriptorCollection collection = expressions;
                    if (!this.IsPredicate(binaryNode.Right))
                    {
                        CompositeFilterDescriptor compositeExpression = new CompositeFilterDescriptor();
                        expressions.Add(compositeExpression);
                        collection = compositeExpression.FilterDescriptors;
                    }
                    collectionStack.Push(collection);

                    nodeStack.Push(binaryNode.Left);
                    collection = expressions;
                    if (!this.IsPredicate(binaryNode.Left))
                    {
                        CompositeFilterDescriptor compositeExpression = new CompositeFilterDescriptor();
                        compositeExpression.LogicalOperator = (binaryNode.Op == Operator.And) ? FilterLogicalOperator.And : FilterLogicalOperator.Or;
                        expressions.Add(compositeExpression);
                        collection = compositeExpression.FilterDescriptors;
                    }
                    collectionStack.Push(collection);
                }
            }

            this.EndUpdate();
        }
コード例 #36
0
    protected void HandleInput(string source)
    {
        List <string> x;
        List <string> y;
        List <string> z;
        List <string> umin = ExpressionParser.Parse("");
        List <string> umax = ExpressionParser.Parse("");
        List <string> tmin = ExpressionParser.Parse("");
        List <string> tmax = ExpressionParser.Parse("");
        List <string> vmin = ExpressionParser.Parse("");
        List <string> vmax = ExpressionParser.Parse("");
        List <string> wmin = ExpressionParser.Parse("");
        List <string> wmax = ExpressionParser.Parse("");

        ExpressionSet expressionSet = calcManager.expressionSet;

        switch (source)
        {
        default:
            x    = ExpressionParser.Parse("0.75*sin(2*pi*v)");
            y    = ExpressionParser.Parse("sin(pi*u)*(1.5+0.75*cos(2*pi*v))");
            z    = ExpressionParser.Parse("cos(pi*u)*(1.5+0.75*cos(2*pi*v))");
            umin = ExpressionParser.Parse("1.5");
            umax = ExpressionParser.Parse("2.5");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("1");

            List <string> x2    = ExpressionParser.Parse("0.75*cos(pi*u)");
            List <string> y2    = ExpressionParser.Parse("0.75*sin(pi*u)*cos(2*pi*v)+2.4");
            List <string> z2    = ExpressionParser.Parse("0.75*sin(pi*u)*sin(2*pi*v)+2.6");
            List <string> umin2 = ExpressionParser.Parse("0");
            List <string> umax2 = ExpressionParser.Parse("1");
            List <string> vmin2 = ExpressionParser.Parse("0");
            List <string> vmax2 = ExpressionParser.Parse("1");

            List <string> x3    = ExpressionParser.Parse("0.75*sin(2*pi*u)");
            List <string> y3    = ExpressionParser.Parse("0.75*cos(2*pi*u)+1.5*cos(pi/8*v)");
            List <string> z3    = ExpressionParser.Parse("-1.5*sin(pi/8*v)");
            List <string> umin3 = ExpressionParser.Parse("0");
            List <string> umax3 = ExpressionParser.Parse("1");
            List <string> vmin3 = ExpressionParser.Parse("0");
            List <string> vmax3 = ExpressionParser.Parse("1");

            List <string> x4    = ExpressionParser.Parse("0.75*sin(2*pi*u)");
            List <string> y4    = ExpressionParser.Parse("0.75*cos(2*pi*u)-1.5*cos(pi/8*v)");
            List <string> z4    = ExpressionParser.Parse("-1.5*sin(pi/8*v)");
            List <string> umin4 = ExpressionParser.Parse("0");
            List <string> umax4 = ExpressionParser.Parse("1");
            List <string> vmin4 = ExpressionParser.Parse("0");
            List <string> vmax4 = ExpressionParser.Parse("1");

            Expression X  = new Expression(x);
            Expression Y  = new Expression(y);
            Expression Z  = new Expression(z);
            Expression X2 = new Expression(x2);
            Expression Y2 = new Expression(y2);
            Expression Z2 = new Expression(z2);
            Expression X3 = new Expression(x3);
            Expression Y3 = new Expression(y3);
            Expression Z3 = new Expression(z3);
            Expression X4 = new Expression(x4);
            Expression Y4 = new Expression(y4);
            Expression Z4 = new Expression(z4);

            Range            zeroRange    = new Range(ExpressionParser.Parse("0"));
            Range            oneRange     = new Range(ExpressionParser.Parse("1"));
            Range            onePointFive = new Range(ExpressionParser.Parse("1.5"));
            Range            twoPointFive = new Range(ExpressionParser.Parse("2.5"));
            RangePair        zeroToZero   = new RangePair(zeroRange, zeroRange);
            RangePair        zeroToOne    = new RangePair(zeroRange, oneRange);
            List <RangePair> rangePairs   = new List <RangePair>()
            {
                zeroToZero, new RangePair(onePointFive, twoPointFive), zeroToOne, zeroToOne
            };
            List <RangePair> rangePairs2 = new List <RangePair>()
            {
                zeroToZero, zeroToOne, zeroToOne, zeroToZero
            };
            ExpressionSet expSet = new ExpressionSet(new string[] { "t", "u", "v", "w" }, rangePairs, new string[] { "X", "Y", "Z" }, new List <Expression>()
            {
                X, Y, Z
            });
            ExpressionSet expSet2 = new ExpressionSet(new string[] { "t", "u", "v", "w" }, rangePairs2, new string[] { "X", "Y", "Z" }, new List <Expression>()
            {
                X2, Y2, Z2
            });
            ExpressionSet expSet3 = new ExpressionSet(new string[] { "t", "u", "v", "w" }, rangePairs2, new string[] { "X", "Y", "Z" }, new List <Expression>()
            {
                X3, Y3, Z3
            });
            ExpressionSet expSet4 = new ExpressionSet(new string[] { "t", "u", "v", "w" }, rangePairs2, new string[] { "X", "Y", "Z" }, new List <Expression>()
            {
                X4, Y4, Z4
            });

            List <ExpressionSet> nanomeLogo = new List <ExpressionSet>()
            {
                expSet, expSet2, expSet3, expSet4
            };
            CalcManager.Instance.LoadSavedExpressionSets(nanomeLogo);
            print("unknown preset pressed");
            return;

        //R1 -> R1
        case "Cinquefoil Knot":
            x    = ExpressionParser.Parse("cos(t)*(2-cos(2*t/5))");
            y    = ExpressionParser.Parse("sin(t)*(2-cos(2*t/5))");
            z    = ExpressionParser.Parse("-sin(2*t/5)");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("10*pi");
            break;

        case "Circle":
            x    = ExpressionParser.Parse("cos(t)");
            y    = ExpressionParser.Parse("sin(t)");
            z    = ExpressionParser.Parse("0");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("2pi");
            break;

        case "Sphere Outline":
            x    = ExpressionParser.Parse("sin(t)*cos(32*t)");
            y    = ExpressionParser.Parse("sin(t)*sin(32*t)");
            z    = ExpressionParser.Parse("cos(t)");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("pi");
            break;

        case "Hypocloid":
            x    = ExpressionParser.Parse("cos(t)^3");
            y    = ExpressionParser.Parse("sin(t)^3");
            z    = ExpressionParser.Parse("0");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("4pi");
            break;

        case "Hypocloid Surface":
            x    = ExpressionParser.Parse("10*cos(t*32)^3");
            y    = ExpressionParser.Parse("10*sin(t*32)^3");
            z    = ExpressionParser.Parse("t-2*pi");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("4pi");
            break;

        case "Trefoil Knot":
            x    = ExpressionParser.Parse("sin(t)+2*sin(2*t)");
            y    = ExpressionParser.Parse("cos(t)-2*cos(2*t)");
            z    = ExpressionParser.Parse("-sin(3*t)");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("2*pi");
            break;

        case "Turnip":
            x    = ExpressionParser.Parse("(sin(t/16)^2)*cos(8*t)*8*pi");
            y    = ExpressionParser.Parse("(sin(t/16))^2*sin(8*t)*8*pi");
            z    = ExpressionParser.Parse("8*pi-t");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("16pi");
            break;

        case "Wavy Surface":
            x    = ExpressionParser.Parse("(sin(t/2)^(1/2)*cos(256*t)*pi)");
            y    = ExpressionParser.Parse("(sin(t/2))^(1/2)*sin(64*t)*pi");
            z    = ExpressionParser.Parse("pi-t");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("2pi");
            break;

        case "High-res Sphere":
            x    = ExpressionParser.Parse("sin(t)*cos(1024*t)");
            y    = ExpressionParser.Parse("sin(t)*sin(1024*t)");
            z    = ExpressionParser.Parse("cos(t)");
            tmin = ExpressionParser.Parse("0");
            tmax = ExpressionParser.Parse("pi");
            break;

        //R2->R3
        case "Astroidal Ellipse":
            x    = ExpressionParser.Parse("(2*cos(u)*cos(v))^3");
            y    = ExpressionParser.Parse("(2*sin(u)*cos(v))^3");
            z    = ExpressionParser.Parse("(2*sin(v))^3");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2*pi");
            break;

        case "Bumpy Sphere":
            x    = ExpressionParser.Parse("5*sin(u)*sin(v)+cos(30*v)*0.15");
            y    = ExpressionParser.Parse("5*cos(u)*sin(v)+cos(30*u)*0.15");
            z    = ExpressionParser.Parse("5*cos(v)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("2*pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("pi");
            break;

        case "Dini's Surface":
            x    = ExpressionParser.Parse("3*cos(u)*sin(v)");
            y    = ExpressionParser.Parse("3*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("3*(cos(v)+log(tan(0.5*v)))+0.4*u");
            umin = ExpressionParser.Parse("-4*pi");
            umax = ExpressionParser.Parse("4*pi");
            vmin = ExpressionParser.Parse("0.005");
            vmax = ExpressionParser.Parse("3.135");
            break;

        case "Figure-8":
            x    = ExpressionParser.Parse("(3+cos(u/2)*sin(v)-sin(u/2)*sin(2*v))*cos(u)");
            y    = ExpressionParser.Parse("(3+cos(u/2)*sin(v)-sin(u/2)*sin(2*v))*sin(u)");
            z    = ExpressionParser.Parse("sin(u/2)*sin(v)-cos(u/2)*sin(2*v)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("2*pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2*pi");
            break;

        case "Gray's Surface":
            x    = ExpressionParser.Parse("(3+cos(3*u/2)*sin(v)-sin(3*u/2)*sin(2*v))*cos(u/2)");
            y    = ExpressionParser.Parse("(3+cos(3*u/2)*sin(v)-sin(3*u/2)*sin(2*v))*sin(u/2)");
            z    = ExpressionParser.Parse("sin(3*u/2)*sin(v)+cos(3*u/2)*sin(2*v)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("4*pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Knot":
            x    = ExpressionParser.Parse("3*sin(3*u)/2+cos(v)))");
            y    = ExpressionParser.Parse("3*(sin(u)+2*sin(2*u))/(2+cos(v+pi*2/3))");
            z    = ExpressionParser.Parse("3/2*(cos(u)-2*cos(2*u))*(2+cos(v))*(2+cos(v+pi*2/3))/4");
            umin = ExpressionParser.Parse("-pi");
            umax = ExpressionParser.Parse("2pi");
            vmin = ExpressionParser.Parse("-pi");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Mobius":
            x    = ExpressionParser.Parse("(5+u*cos(0.5*v))*cos(v)");
            y    = ExpressionParser.Parse("(5+u*cos(0.5*v))*sin(v)");
            z    = ExpressionParser.Parse("u*sin(0.5*v)");
            umin = ExpressionParser.Parse("-1");
            umax = ExpressionParser.Parse("1");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2*pi");
            break;

        case "Radial Wave":
            x    = ExpressionParser.Parse("u");
            y    = ExpressionParser.Parse("v");
            z    = ExpressionParser.Parse("cos((u^2+v^2)^0.5)");
            umin = ExpressionParser.Parse("-10");
            umax = ExpressionParser.Parse("10");
            vmin = ExpressionParser.Parse("-10");
            vmax = ExpressionParser.Parse("10");
            break;

        case "Torus":
            x    = ExpressionParser.Parse("(5+cos(v))*cos(u)");
            y    = ExpressionParser.Parse("(5+cos(v))*sin(u)");
            z    = ExpressionParser.Parse("sin(v)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("2pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        //R3->R3
        case "Cone":
            x    = ExpressionParser.Parse("ucos(v)w");
            y    = ExpressionParser.Parse("usin(v)w");
            z    = ExpressionParser.Parse("w");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("1");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            wmin = ExpressionParser.Parse("0");
            wmax = ExpressionParser.Parse("1");
            break;

        case "Cube":
            x    = ExpressionParser.Parse("u");
            y    = ExpressionParser.Parse("v");
            z    = ExpressionParser.Parse("w");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("1");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("1");
            wmin = ExpressionParser.Parse("0");
            wmax = ExpressionParser.Parse("1");
            break;

        case "Cylinder":
            x    = ExpressionParser.Parse("ucos(v)");
            y    = ExpressionParser.Parse("usin(v)");
            z    = ExpressionParser.Parse("w");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("1");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            wmin = ExpressionParser.Parse("0");
            wmax = ExpressionParser.Parse("1");
            break;

        case "Sphere":
            x    = ExpressionParser.Parse("ucos(v)sin(w)");
            y    = ExpressionParser.Parse("usin(v)sin(w)");
            z    = ExpressionParser.Parse("ucos(w)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("1");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            wmin = ExpressionParser.Parse("0");
            wmax = ExpressionParser.Parse("2pi");
            break;

        case "Tetrahedron":
            x    = ExpressionParser.Parse("u(1-v)");
            y    = ExpressionParser.Parse("uv(1-w)");
            z    = ExpressionParser.Parse("uvw");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("1");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("1");
            wmin = ExpressionParser.Parse("0");
            wmax = ExpressionParser.Parse("1");
            break;

        // Orbitals
        case "S":
            x    = ExpressionParser.Parse("(1/2*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(1/2*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(1/2*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Px":
            x    = ExpressionParser.Parse("(3^(1/2)/2*sin(u)*1/pi^(1/2)*sin(v))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(3^(1/2)/2*sin(u)*1/pi^(1/2)*sin(v))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(3^(1/2)/2*sin(u)*1/pi^(1/2)*sin(v))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Py":
            x    = ExpressionParser.Parse("(3^(1/2)/2*sin(u)*1/pi^(1/2)*cos(v))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(3^(1/2)/2*sin(u)*1/pi^(1/2)*cos(v))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(3^(1/2)/2*sin(u)*1/pi^(1/2)*cos(v))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Pz":
            x    = ExpressionParser.Parse("(3^(1/2)/2*cos(u)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(3^(1/2)/2*cos(u)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(3^(1/2)/2*cos(u)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Dz\x00B2":
            goto case "Dz2";

        case "Dz2":
            x    = ExpressionParser.Parse("(5^(1/2)/4*(3*((cos(u))^2)-1)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(5^(1/2)/4*(3*((cos(u))^2)-1)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(5^(1/2)/4*(3*((cos(u))^2)-1)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Dxz":
            x    = ExpressionParser.Parse("(15^(1/2)/2*sin(u)*cos(u)*1/pi^(1/2)*sin(v))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(15^(1/2)/2*sin(u)*cos(u)*1/pi^(1/2)*sin(v))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(15^(1/2)/2*sin(u)*cos(u)*1/pi^(1/2)*sin(v))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Dyz":
            x    = ExpressionParser.Parse("(15^(1/2)/2*sin(u)*cos(u)*1/pi^(1/2)*cos(v))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(15^(1/2)/2*sin(u)*cos(u)*1/pi^(1/2)*cos(v))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(15^(1/2)/2*sin(u)*cos(u)*1/pi^(1/2)*cos(v))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Dxy":
            x    = ExpressionParser.Parse("(15^(1/2)/4*sin(u)^2*1/pi^(1/2)*sin(2v))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(15^(1/2)/4*sin(u)^2*1/pi^(1/2)*sin(2v))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(15^(1/2)/4*sin(u)^2*1/pi^(1/2)*sin(2v))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Dx\x00B2-y\x00B2":
            goto case "Dx2-y2";

        case "Dx2-y2":
            x    = ExpressionParser.Parse("(15^(1/2)/4*sin(u)^2*1/pi^(1/2)*cos(2v))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(15^(1/2)/4*sin(u)^2*1/pi^(1/2)*cos(2v))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(15^(1/2)/4*sin(u)^2*1/pi^(1/2)*cos(2v))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fz\x00B3":
            goto case "Fz3";

        case "Fz3":
            x    = ExpressionParser.Parse("(7^(1/2)/4*(5*((cos(u))^2)-3)*cos(u)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(7^(1/2)/4*(5*((cos(u))^2)-3)*cos(u)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(7^(1/2)/4*(5*((cos(u))^2)-3)*cos(u)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fxz\x00B2":
            goto case "Fxz2";

        case "Fxz2":
            x    = ExpressionParser.Parse("(42^(1/2)/8*(5*((cos(u))^2)-1)*sin(u)*sin(v)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(42^(1/2)/8*(5*((cos(u))^2)-1)*sin(u)*sin(v)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(42^(1/2)/8*(5*((cos(u))^2)-1)*sin(u)*sin(v)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fyz\x00B2":
            goto case "Fyz2";

        case "Fyz2":
            x    = ExpressionParser.Parse("(42^(1/2)/8*(5*((cos(u))^2)-1)*sin(u)*cos(v)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(42^(1/2)/8*(5*((cos(u))^2)-1)*sin(u)*cos(v)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(42^(1/2)/8*(5*((cos(u))^2)-1)*sin(u)*cos(v)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fxyz":
            x    = ExpressionParser.Parse("(105^(1/2)/4*sin(u)^2*cos(u)*cos(2v)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(105^(1/2)/4*sin(u)^2*cos(u)*cos(2v)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(105^(1/2)/4*sin(u)^2*cos(u)*cos(2v)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fz\x0028x\x00B2-y\x00B2\x0029":
            goto case "Fzx2y2";

        case "Fzx2y2":
            x    = ExpressionParser.Parse("(105^(1/2)/4*sin(u)^2*cos(u)*sin(2v)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(105^(1/2)/4*sin(u)^2*cos(u)*sin(2v)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(105^(1/2)/4*sin(u)^2*cos(u)*sin(2v)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fx\x0028x\x00B2-3y\x00B2\x0029":
            goto case "Fxx23y2";

        case "Fxx23y2":
            x    = ExpressionParser.Parse("(70^(1/2)/8*sin(u)^3*sin(3v)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(70^(1/2)/8*sin(u)^3*sin(3v)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(70^(1/2)/8*sin(u)^3*sin(3v)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;

        case "Fy\x00283x\x00B2-y\x00B2\x0029":
            goto case "Fy3x2y2";

        case "Fy3x2y2":
            x    = ExpressionParser.Parse("(70^(1/2)/8*sin(u)^3*cos(3v)*1/pi^(1/2))^2*sin(u)*cos(v)");
            y    = ExpressionParser.Parse("(70^(1/2)/8*sin(u)^3*cos(3v)*1/pi^(1/2))^2*sin(u)*sin(v)");
            z    = ExpressionParser.Parse("(70^(1/2)/8*sin(u)^3*cos(3v)*1/pi^(1/2))^2*cos(u)");
            umin = ExpressionParser.Parse("0");
            umax = ExpressionParser.Parse("pi");
            vmin = ExpressionParser.Parse("0");
            vmax = ExpressionParser.Parse("2pi");
            break;
        }

        expressionSet.AddExpression("X", x);
        expressionSet.AddExpression("Y", y);
        expressionSet.AddExpression("Z", z);
        expressionSet.AddRange("t", tmin, tmax);
        expressionSet.AddRange("u", umin, umax);
        expressionSet.AddRange("v", vmin, vmax);
        expressionSet.AddRange("w", wmin, wmax);
        calcManager.PresetPressed();
    }
コード例 #37
0
 public ExpressionParserTests()
 {
     _expressionParser = new ExpressionParser(
         () => _searchParameterDefinitionManager,
         _searchParameterExpressionParser);
 }
コード例 #38
0
 public QueryProvider(ExpressionParser expressionParser, IDataQueryExecutor executor)
 {
     _expressionParser = expressionParser ?? throw new ArgumentNullException(nameof(expressionParser));
     _executor         = executor ?? throw new ArgumentNullException(nameof(executor));
 }
コード例 #39
0
ファイル: RowPropertyMapper.cs プロジェクト: akawa777/Dagent
        public void Do()
        {
            if (targetPropertyExpression != null)
            {
                PropertyInfo property = ExpressionParser.GetPropertyInfo(targetPropertyExpression);

                if (!property.CanWrite)
                {
                    return;
                }

                P value = create();

                bool success = true;

                if (autoMapping)
                {
                    success = ModelMapper <P> .Map(value, row, validColumnNames, prefixColumnName, columnNamePropertyMap, ignoreCase);
                }

                if (success)
                {
                    DynamicMethodBuilder <T, P> .CreateSetMethod(property)(model, value);

                    if (mapAction != null)
                    {
                        mapAction(value);
                    }
                }
            }
            else if (targetListPropertyExpression != null)
            {
                PropertyInfo property = ExpressionParser.GetPropertyInfo(targetListPropertyExpression);

                if (!property.CanWrite || !property.CanRead)
                {
                    return;
                }

                Func <T, List <P> > getMethod = DynamicMethodBuilder <T, List <P> > .CreateGetMethod(property);

                List <P> list = getMethod(model);

                if (list == null)
                {
                    list = new List <P>();
                    DynamicMethodBuilder <T, List <P> > .CreateSetMethod(property)(model, list);
                }

                P value;

                if (list.Count != 0 && row.PrevRow != null && uniqueColumnNames.Length > 0 && row.Compare(row.PrevRow, uniqueColumnNames))
                {
                    value = list[list.Count - 1];

                    if (mapAction != null)
                    {
                        mapAction(value);
                    }
                }
                else
                {
                    value = create();

                    bool success = true;

                    if (autoMapping)
                    {
                        success = ModelMapper <P> .Map(value, row, validColumnNames, prefixColumnName, columnNamePropertyMap, ignoreCase);
                    }

                    if (success)
                    {
                        list.Add(value);

                        if (mapAction != null)
                        {
                            mapAction(value);
                        }
                    }
                }
            }
        }
コード例 #40
0
ファイル: DynamicExpression.cs プロジェクト: brezaie/CoreFra
        public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values)
        {
            ExpressionParser parser = new ExpressionParser(parameters, expression, values);

            return(Expression.Lambda(parser.Parse(resultType), parameters));
        }
コード例 #41
0
 public void SetUp()
 {
     _parser = new ExpressionParser();
 }
コード例 #42
0
        public void TestLiteral(string expression)
        {
            var expr = ExpressionParser.Parse(expression, ExpressionOptions.Metadata);

            Assert.IsInstanceOf <ExpressionLiteral> (expr);
        }
コード例 #43
0
ファイル: TableQuery.cs プロジェクト: Winvision/Sandboxable
        internal ExecutionInfo Bind()
        {
            ExecutionInfo retVal = new ExecutionInfo();

            // IQueryable impl
            if (this.Expression != null)
            {
                Dictionary <Expression, Expression> normalizerRewrites = new Dictionary <Expression, Expression>(ReferenceEqualityComparer <Expression> .Instance);

                // Step 1. Evaluate any local evaluatable expressions ( lambdas etc)
                Expression partialEvaluatedExpression = Evaluator.PartialEval(this.Expression);

                // Step 2. Normalize expression, replace String Comparisons etc.
                Expression normalizedExpression = ExpressionNormalizer.Normalize(partialEvaluatedExpression, normalizerRewrites);

                // Step 3. Bind Expression, Analyze predicates and create query option expressions. End result is a single ResourceSetExpression
                Expression boundExpression = ResourceBinder.Bind(normalizedExpression);

                // Step 4. Parse the Bound expression into sub components, i.e. take count, filter, select columns, request options, opcontext, etc.
                ExpressionParser parser = new ExpressionParser();
                parser.Translate(boundExpression);

                // Step 5. Store query components & params
                this.TakeCount          = parser.TakeCount;
                this.FilterString       = parser.FilterString;
                this.SelectColumns      = parser.SelectColumns;
                retVal.RequestOptions   = parser.RequestOptions;
                retVal.OperationContext = parser.OperationContext;

                // Step 6. If projection & no resolver then generate a resolver to perform the projection
                if (parser.Resolver == null)
                {
                    if (parser.Projection != null && parser.Projection.Selector != ProjectionQueryOptionExpression.DefaultLambda)
                    {
                        Type intermediateType = parser.Projection.Selector.Parameters[0].Type;

                        // Convert Expression to take type object as input to allow for direct invocation.
                        ParameterExpression paramExpr = Expression.Parameter(typeof(object));

                        Func <object, TElement> projectorFunc = Expression.Lambda <Func <object, TElement> >(
                            Expression.Invoke(parser.Projection.Selector, Expression.Convert(paramExpr, intermediateType)), paramExpr).Compile();

                        // Generate a resolver to do the projection.
                        retVal.Resolver = (pk, rk, ts, props, etag) =>
                        {
                            // Parse to intermediate type
                            ITableEntity intermediateObject = (ITableEntity)EntityUtilities.InstantiateEntityFromType(intermediateType);
                            intermediateObject.PartitionKey = pk;
                            intermediateObject.RowKey       = rk;
                            intermediateObject.Timestamp    = ts;
                            intermediateObject.ReadEntity(props, parser.OperationContext);
                            intermediateObject.ETag = etag;

                            // Invoke lambda expression
                            return(projectorFunc(intermediateObject));
                        };
                    }
                    else
                    {
                        // No op - No resolver or projection specified.
                    }
                }
                else
                {
                    retVal.Resolver = (EntityResolver <TElement>)parser.Resolver.Value;
                }
            }

            retVal.RequestOptions   = TableRequestOptions.ApplyDefaults(retVal.RequestOptions, this.queryProvider.Table.ServiceClient);
            retVal.OperationContext = retVal.OperationContext ?? new OperationContext();
            return(retVal);
        }
コード例 #44
0
 /// <summary>
 /// Ripulisce i dati
 /// </summary>
 public void Clear()
 {
     _a = 0; //Valori di default
     _b = 0;
     _fa = 0;
     _fb = 0;
     _divisioni = 0;
     _retMax = false;
     _retMin = false;
     _trap = false;
     _funzione = "";
     _parser = new ExpressionParser();
 }
コード例 #45
0
ファイル: StaticsDB.cs プロジェクト: JosephClay/Stareater
        public static StaticsDB Load(IEnumerable <TracableStream> dataSources)
        {
            //TODO(v0.8) update IKON with HasNext with tag
            //TODO(v0.8) support nested subformulas
            var subformulas = new Dictionary <string, Formula>();

            foreach (var source in dataSources)
            {
                try
                {
                    var queue = new Parser(source.Stream).ParseAll();

                    while (queue.CountOf("Subformulas") > 0)
                    {
                        var data = queue.Dequeue("Subformulas").To <IkonComposite>();
                        foreach (var key in data.Keys)
                        {
                            subformulas[key] = data[key].To <Formula>();
                        }
                    }
                }
                catch (IOException e)
                {
                    throw new IOException(source.SourceInfo, e);
                }
                catch (FormatException e)
                {
                    throw new FormatException(source.SourceInfo, e);
                }
            }
            subformulas = ExpressionParser.ResloveSubformulaNesting(subformulas);

            var db = new StaticsDB();

            foreach (var source in dataSources)
            {
                var parser = new Parser(source.Stream, subformulas);
                try
                {
                    foreach (var data in parser.ParseAll().Select(x => x.Value.To <IkonComposite>()))
                    {
                        switch ((string)data.Tag)
                        {
                        case "Building":
                            db.Buildings.Add(data[GeneralCodeKey].To <string>(), loadBuilding(data));
                            break;

                        case "ColonyFormulas":
                            db.ColonyFormulas = loadColonyFormulas(data);
                            break;

                        case "Constructable":
                            db.Constructables.Add(loadConstructable(data));
                            break;

                        case "DevelopmentFocusOptions":
                            db.DevelopmentFocusOptions.AddRange(loadFocusOptions(data));
                            break;

                        case "DevelopmentTopic":
                            db.DevelopmentTopics.Add(loadDevelopmentTopic(data));
                            break;

                        case "Subformulas":
                            //TODO(v0.8) remove after IKON update
                            break;

                        case "Natives":
                            db.loadNatives(data.To <IkonComposite>());
                            break;

                        case "PlanetFormulas":
                            var formulaSet = loadPlanetFormulas(data);
                            db.PlanetForumlas[formulaSet.Key] = formulaSet.Value;
                            break;

                        case "PlayerFormulas":
                            db.PlayerFormulas = loadPlayerFormulas(data);
                            break;

                        case "SystemPolicy":
                            db.Policies.Add(loadPolicy(data));
                            break;

                        case "PredefinedDesign":
                            db.PredeginedDesigns.Add(loadDesignTemplate(data));
                            break;

                        case "ResearchTopic":
                            db.ResearchTopics.Add(loadResearchTopic(data));
                            break;

                        case "ShipFormulas":
                            db.ShipFormulas = loadShipFormulas(data);
                            break;

                        case "StarFormulas":
                            db.StellarisFormulas = loadStarFormulas(data);
                            break;

                        case "PlanetTrait":
                            db.PlanetTraits.Add(data[GeneralCodeKey].To <string>(), loadPlanetTrait(data));
                            break;

                        case "StarTrait":
                            db.StarTraits.Add(data[GeneralCodeKey].To <string>(), loadStarTrait(data));
                            break;

                        case ArmorTag:
                            db.Armors.Add(data[GeneralCodeKey].To <string>(), loadArmor(data));
                            break;

                        case HullTag:
                            db.Hulls.Add(data[GeneralCodeKey].To <string>(), loadHull(data));
                            break;

                        case IsDriveTag:
                            db.IsDrives.Add(data[GeneralCodeKey].To <string>(), loadIsDrive(data));
                            break;

                        case MissionEquipmentTag:
                            db.MissionEquipment.Add(data[GeneralCodeKey].To <string>(), loadMissionEquiptment(data));
                            break;

                        case ReactorTag:
                            db.Reactors.Add(data[GeneralCodeKey].To <string>(), loadReactor(data));
                            break;

                        case SensorTag:
                            db.Sensors.Add(data[GeneralCodeKey].To <string>(), loadSensor(data));
                            break;

                        case ShieldTag:
                            db.Shields.Add(data[GeneralCodeKey].To <string>(), loadShield(data));
                            break;

                        case SpecialEquipmentTag:
                            db.SpecialEquipment.Add(data[GeneralCodeKey].To <string>(), loadSpecialEquiptment(data));
                            break;

                        case ThrusterTag:
                            db.Thrusters.Add(data[GeneralCodeKey].To <string>(), loadThruster(data));
                            break;

                        default:
                            throw new FormatException("Invalid game data object with tag " + data.Tag);
                        }
                    }
                }
                catch (IOException e)
                {
                    throw new IOException(source.SourceInfo, e);
                }
                catch (FormatException e)
                {
                    throw new FormatException(source.SourceInfo, e);
                }
            }

            foreach (var research in db.ResearchTopics)
            {
                for (int level = 0; level <= research.MaxLevel; level++)
                {
                    foreach (var unlock in research.Unlocks[level])
                    {
                        db.DevelopmentRequirements[unlock] = new DevelopmentRequirement(research.IdCode, level);
                    }
                }
            }

            return(db);
        }
コード例 #46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StaticChecker"/> class.
 /// </summary>
 /// <param name="templates">Templates wihch would be checked.</param>
 public StaticChecker(Templates templates)
 {
     _templates            = templates;
     _baseExpressionParser = templates.ExpressionParser;
 }
コード例 #47
0
        // Return value of given expression.
        public static String ExpressionToString(String expression)
        {
            Object value = ExpressionNotFoundError();

            try
            {
                if (expression == null)
                {
                    return(Error("null expression"));
                }

                ExpressionParser parser = new ExpressionParser(expression);
                String           name;
                String[]         args;

                // Parse start of the expression.
                if (!parser.Read(out name, out args))
                {
                    return(value.ToString());
                }

                // Check for constant
                if (Char.IsDigit(name, 0))
                {
                    return(name);
                }

                // Find matching local variable/function parameter
                value = GetLocal(name);

                // Try instance members
                if (value == error)
                {
                    Object instance = GetLocal("this");
                    if (instance != error)
                    {
                        value = GetNonStaticMemberValue(instance, name,
                                                        null);
                    }
                    else
                    {
                        error = value;                                          // restore last error
                    }
                }

                // Call indexer if local variable found
                // and arguments were specified
                if (value != error)
                {
                    if (args != null)
                    {
                        value = GetNonStaticMemberValue(value,
                                                        "get_Item", args);
                    }
                }
                else
                {
                    // Check for static member
                    Type matchingType = FindType(name);

                    // Parse member name or try current method owner
                    if (matchingType != null)
                    {
                        parser.Read(out name, out args);
                    }
                    else
                    {
                        matchingType = methodOwner;
                    }

                    // Find matching static field/method/property
                    if (matchingType != null)
                    {
                        value = GetStaticMemberValue(matchingType,
                                                     name, args);
                    }
                }

                // Expression was not found
                if (value == error)
                {
                    return(value.ToString());
                }

                // Iterate until the leftmost member reference
                while (parser.Read(out name, out args) && value != error)
                {
                    value = GetNonStaticMemberValue(value, name, args);
                }

                return(ObjectToString(value));
            }
            catch (Exception ex)
            {
                return(Error(ex.Message));
            }
        }
コード例 #48
0
        public static bool ParseSharpLine(FunctionLabelLine label, StringStream st, ScriptPosition position,
                                          List <string> OnlyLabel)
        {
            st.ShiftNext();                                       //'#'を飛ばす
            var token = LexicalAnalyzer.ReadSingleIdentifier(st); //#~自体にはマクロ非適用

            if (Config.ICFunction)
            {
                token = token.ToUpper();
            }
            //#行として不正な行でもAnalyzeに行って引っかかることがあるので、先に存在しない#~は弾いてしまう
            if (token == null || token != "SINGLE" && token != "LATER" && token != "PRI" && token != "ONLY" &&
                token != "FUNCTION" && token != "FUNCTIONS" &&
                token != "LOCALSIZE" && token != "LOCALSSIZE" && token != "DIM" && token != "DIMS")
            {
                ParserMediator.Warn("解釈できない#行です", position, 1);
                return(false);
            }
            try
            {
                var wc = LexicalAnalyzer.Analyse(st, LexEndWith.EoL, LexAnalyzeFlag.AllowAssignment);
                switch (token)
                {
                case "SINGLE":
                    if (label.IsMethod)
                    {
                        ParserMediator.Warn("式中関数では#SINGLEは機能しません", position, 1);
                        break;
                    }
                    else if (!label.IsEvent)
                    {
                        ParserMediator.Warn("イベント関数以外では#SINGLEは機能しません", position, 1);
                        break;
                    }
                    else if (label.IsSingle)
                    {
                        ParserMediator.Warn("#SINGLEが重複して使われています", position, 1);
                        break;
                    }
                    else if (label.IsOnly)
                    {
                        ParserMediator.Warn("#ONLYが指定されたイベント関数では#SINGLEは機能しません", position, 1);
                        break;
                    }
                    label.IsSingle = true;
                    break;

                case "LATER":
                    if (label.IsMethod)
                    {
                        ParserMediator.Warn("式中関数では#LATERは機能しません", position, 1);
                        break;
                    }
                    else if (!label.IsEvent)
                    {
                        ParserMediator.Warn("イベント関数以外では#LATERは機能しません", position, 1);
                        break;
                    }
                    else if (label.IsLater)
                    {
                        ParserMediator.Warn("#LATERが重複して使われています", position, 1);
                        break;
                    }
                    else if (label.IsOnly)
                    {
                        ParserMediator.Warn("#ONLYが指定されたイベント関数では#LATERは機能しません", position, 1);
                        break;
                    }
                    else if (label.IsPri)
                    {
                        ParserMediator.Warn("#PRIと#LATERが重複して使われています(この関数は2度呼ばれます)", position, 1);
                    }
                    label.IsLater = true;
                    break;

                case "PRI":
                    if (label.IsMethod)
                    {
                        ParserMediator.Warn("式中関数では#PRIは機能しません", position, 1);
                        break;
                    }
                    else if (!label.IsEvent)
                    {
                        ParserMediator.Warn("イベント関数以外では#PRIは機能しません", position, 1);
                        break;
                    }
                    else if (label.IsPri)
                    {
                        ParserMediator.Warn("#PRIが重複して使われています", position, 1);
                        break;
                    }
                    else if (label.IsOnly)
                    {
                        ParserMediator.Warn("#ONLYが指定されたイベント関数では#PRIは機能しません", position, 1);
                        break;
                    }
                    else if (label.IsLater)
                    {
                        ParserMediator.Warn("#PRIと#LATERが重複して使われています(この関数は2度呼ばれます)", position, 1);
                    }
                    label.IsPri = true;
                    break;

                case "ONLY":
                    if (label.IsMethod)
                    {
                        ParserMediator.Warn("式中関数では#ONLYは機能しません", position, 1);
                        break;
                    }
                    else if (!label.IsEvent)
                    {
                        ParserMediator.Warn("イベント関数以外では#ONLYは機能しません", position, 1);
                        break;
                    }
                    else if (label.IsOnly)
                    {
                        ParserMediator.Warn("#ONLYが重複して使われています", position, 1);
                        break;
                    }
                    else if (OnlyLabel.Contains(label.LabelName))
                    {
                        ParserMediator.Warn("このイベント関数\"@" + label.LabelName + "\"にはすでに#ONLYが宣言されています(この関数は実行されません)",
                                            position, 1);
                    }
                    OnlyLabel.Add(label.LabelName);
                    label.IsOnly = true;
                    if (label.IsPri)
                    {
                        ParserMediator.Warn("このイベント関数には#PRIが宣言されていますが無視されます", position, 1);
                        label.IsPri = false;
                    }
                    if (label.IsLater)
                    {
                        ParserMediator.Warn("このイベント関数には#LATERが宣言されていますが無視されます", position, 1);
                        label.IsLater = false;
                    }
                    if (label.IsSingle)
                    {
                        ParserMediator.Warn("このイベント関数には#SINGLEが宣言されていますが無視されます", position, 1);
                        label.IsSingle = false;
                    }
                    break;

                case "FUNCTION":
                case "FUNCTIONS":
                    if (!string.IsNullOrEmpty(label.LabelName) && char.IsDigit(label.LabelName[0]))
                    {
                        ParserMediator.Warn("#" + token + "属性は関数名が数字で始まる関数には指定できません", position, 1);
                        label.IsError = true;
                        label.ErrMes  = "関数名が数字で始まっています";
                        break;
                    }
                    if (label.IsMethod)
                    {
                        if (label.MethodType == typeof(long) && token == "FUNCTION" ||
                            label.MethodType == typeof(string) && token == "FUNCTIONS")
                        {
                            ParserMediator.Warn("関数" + label.LabelName + "にはすでに#" + token + "が宣言されています(この行は無視されます)",
                                                position, 1);
                            return(false);
                        }
                        if (label.MethodType == typeof(long) && token == "FUNCTIONS")
                        {
                            ParserMediator.Warn("関数" + label.LabelName + "にはすでに#FUNCTIONが宣言されています", position, 2);
                        }
                        else if (label.MethodType == typeof(string) && token == "FUNCTION")
                        {
                            ParserMediator.Warn("関数" + label.LabelName + "にはすでに#FUNCTIONSが宣言されています", position, 2);
                        }
                        return(false);
                    }
                    if (label.Depth == 0)
                    {
                        ParserMediator.Warn("システム関数に#" + token + "が指定されています", position, 2);
                        return(false);
                    }
                    label.IsMethod = true;
                    label.Depth    = 0;
                    if (token == "FUNCTIONS")
                    {
                        label.MethodType = typeof(string);
                    }
                    else
                    {
                        label.MethodType = typeof(long);
                    }
                    if (label.IsPri)
                    {
                        ParserMediator.Warn("式中関数では#PRIは機能しません", position, 1);
                        label.IsPri = false;
                    }
                    if (label.IsLater)
                    {
                        ParserMediator.Warn("式中関数では#LATERは機能しません", position, 1);
                        label.IsLater = false;
                    }
                    if (label.IsSingle)
                    {
                        ParserMediator.Warn("式中関数では#SINGLEは機能しません", position, 1);
                        label.IsSingle = false;
                    }
                    if (label.IsOnly)
                    {
                        ParserMediator.Warn("式中関数では#ONLYは機能しません", position, 1);
                        label.IsOnly = false;
                    }
                    break;

                case "LOCALSIZE":
                case "LOCALSSIZE":
                {
                    if (wc.EOL)
                    {
                        ParserMediator.Warn("#" + token + "の後に有効な数値が指定されていません", position, 2);
                        break;
                    }
                    //イベント関数では指定しても無視される
                    if (label.IsEvent)
                    {
                        ParserMediator.Warn(
                            "イベント関数では#" + token + "による" + token.Substring(0, token.Length - 4) + "のサイズ指定は無視されます",
                            position, 1);
                        break;
                    }
                    var arg      = ExpressionParser.ReduceIntegerTerm(wc, TermEndWith.EoL);
                    var sizeTerm = arg.Restructure(null) as SingleTerm;
                    if (sizeTerm == null || sizeTerm.GetOperandType() != typeof(long))
                    {
                        ParserMediator.Warn("#" + token + "の後に有効な定数式が指定されていません", position, 2);
                        break;
                    }
                    if (sizeTerm.Int <= 0)
                    {
                        ParserMediator.Warn("#" + token + "に0以下の値(" + sizeTerm.Int + ")が与えられました。設定は無視されます",
                                            position, 1);
                        break;
                    }
                    if (sizeTerm.Int >= int.MaxValue)
                    {
                        ParserMediator.Warn("#" + token + "に大きすぎる値(" + sizeTerm.Int + ")が与えられました。設定は無視されます",
                                            position, 1);
                        break;
                    }
                    var size = (int)sizeTerm.Int;
                    if (token == "LOCALSIZE")
                    {
                        if (GlobalStatic.IdentifierDictionary.getLocalIsForbid("LOCAL"))
                        {
                            ParserMediator.Warn("#" + token + "が指定されていますが変数LOCALは使用禁止されています", position, 2);
                            break;
                        }
                        if (label.LocalLength > 0)
                        {
                            ParserMediator.Warn("この関数にはすでに#LOCALSIZEが定義されています。(以前の定義は無視されます)", position, 1);
                        }
                        label.LocalLength = size;
                    }
                    else
                    {
                        if (GlobalStatic.IdentifierDictionary.getLocalIsForbid("LOCALS"))
                        {
                            ParserMediator.Warn("#" + token + "が指定されていますが変数LOCALSは使用禁止されています", position, 2);
                            break;
                        }
                        if (label.LocalsLength > 0)
                        {
                            ParserMediator.Warn("この関数にはすでに#LOCALSSIZEが定義されています。(以前の定義は無視されます)", position, 1);
                        }
                        label.LocalsLength = size;
                    }
                }
                break;

                case "DIM":
                case "DIMS":
                {
                    var data = UserDefinedVariableData.Create(wc, token == "DIMS", true, position);
                    if (!label.AddPrivateVariable(data))
                    {
                        ParserMediator.Warn("変数名" + data.Name + "は既に使用されています", position, 2);
                        return(false);
                    }
                    break;
                }

                default:
                    ParserMediator.Warn("解釈できない#行です", position, 1);
                    break;
                }
                if (!wc.EOL)
                {
                    ParserMediator.Warn("#の識別子の後に余分な文字があります", position, 1);
                }
            }
            catch (Exception e)
            {
                ParserMediator.Warn(e.Message, position, 2);
                goto err;
            }
            return(true);

err:
            return(false);
        }
コード例 #49
0
        public static ExpressionParsedRouteContext Parse(
            LambdaExpression actionCallExpression,
            object additionalRouteValues      = null,
            bool considerParameterDescriptors = false)
        {
            var methodCallExpression = ExpressionParser.GetMethodCallExpression(actionCallExpression);

            var methodInfo     = methodCallExpression.Method;
            var controllerType = methodCallExpression.Object?.Type;

            if (controllerType == null)
            {
                throw new InvalidOperationException($"Method {methodInfo.Name} is static and it is not a valid controller action.");
            }

            var controllerActionDescriptorCache = TestServiceProvider.GetRequiredService <IControllerActionDescriptorCache>();
            var controllerActionDescriptor      = controllerActionDescriptorCache.GetActionDescriptor(methodInfo);

            if (controllerActionDescriptor == null)
            {
                var declaringType    = methodInfo.DeclaringType;
                var classNameMessage = declaringType != null ? $"in class {declaringType.Name} " : string.Empty;
                throw new InvalidOperationException($"Method {methodInfo.Name} {classNameMessage}is not a valid controller action.");
            }

            var controllerName = controllerActionDescriptor.ControllerName;
            var actionName     = controllerActionDescriptor.ActionName;

            var routeValues = GetRouteValues(
                methodInfo,
                methodCallExpression,
                controllerActionDescriptor,
                considerParameterDescriptors);

            // If there is a required route value, add it to the result.
            foreach (var requiredRouteValue in controllerActionDescriptor.RouteValues)
            {
                var routeKey   = requiredRouteValue.Key;
                var routeValue = requiredRouteValue.Value;

                if (string.Equals(routeKey, RouteGroupKey))
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(routeValue))
                {
                    // Override the 'default' values.
                    if (string.Equals(routeKey, "controller", StringComparison.OrdinalIgnoreCase))
                    {
                        controllerName = routeValue;
                    }
                    else if (string.Equals(routeKey, "action", StringComparison.OrdinalIgnoreCase))
                    {
                        actionName = routeValue;
                    }
                    else
                    {
                        routeValues[routeKey] = routeValue;
                    }
                }
            }

            routeValues.Add(additionalRouteValues);

            return(new ExpressionParsedRouteContext(
                       controllerType,
                       controllerName,
                       actionName,
                       routeValues));
        }
コード例 #50
0
        /// <summary>Compile the code or expression and return a TDelegate of type Func or Action to execute.</summary>
        /// <typeparam name="TDelegate">Type of the delegate (Func or Action) to use to compile the code or expression.</typeparam>
        /// <param name="context">The eval context used to compile the code or expression.</param>
        /// <param name="code">The code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <param name="resultType">Type of the compiled code or expression result.</param>
        /// <param name="parameterKind">The parameter kind for the code or expression to compile.</param>
        /// <returns>A TDelegate of type Func or Action that represents the compiled code or expression.</returns>
        internal static TDelegate Compile <TDelegate>(EvalContext context, string code, IDictionary <string, Type> parameterTypes, Type resultType, EvalCompilerParameterKind parameterKind)
        {
            var cacheKey = context.UseCache ? ResolveCacheKey(context, typeof(TDelegate), code, parameterTypes) : "";

            if (context.UseCache)
            {
                var item = EvalManager.Cache.Get(cacheKey);

                if (item != null)
                {
                    return((TDelegate)item);
                }
            }

            // Options
            var scope = new ExpressionScope
            {
                AliasExtensionMethods = context.AliasExtensionMethods,
                //AliasGlobalConstants = context.AliasGlobalConstants,
                //AliasGlobalVariables = context.AliasGlobalVariables,
                AliasNames          = context.AliasNames,
                AliasStaticMembers  = context.AliasStaticMembers,
                AliasTypes          = context.AliasTypes,
                BindingFlags        = context.BindingFlags,
                UseCaretForExponent = context.UseCaretForExponent
            };

            // Resolve Parameter
            var parameterExpressions = ResolveParameter(scope, parameterKind, parameterTypes);

            // ADD global constants
            if (context.AliasGlobalConstants.Count > 0)
            {
                scope.Constants = new Dictionary <string, ConstantExpression>(context.AliasGlobalConstants);
            }

            // ADD global variables
            if (context.AliasGlobalVariables.Count > 0)
            {
                foreach (var keyValue in context.AliasGlobalVariables)
                {
                    scope.CreateLazyVariable(keyValue.Key, new Lazy <Expression>(() =>
                    {
                        var innerParameter  = scope.CreateVariable(keyValue.Value.GetType(), keyValue.Key);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Constant(keyValue.Value));
                        scope.Expressions.Add(innerExpression);
                        return(innerParameter);
                    }));
                }
            }

            // CodeAnalysis
            var syntaxRoot = SyntaxParser.ParseText(code);

            // CodeCompiler
            var expression = ExpressionParser.ParseSyntax(scope, syntaxRoot, resultType);

            // Compile the expression
            var compiled = Expression.Lambda <TDelegate>(expression, parameterExpressions).Compile();

            if (context.UseCache)
            {
                EvalManager.Cache.AddOrGetExisting(new CacheItem(cacheKey, compiled), new CacheItemPolicy());
            }

            return(compiled);
        }
コード例 #51
0
        public bool TryGetHint(ExpressionParser parser, Expression expression, out string hint)
        {
            var binaryExpression = expression as BinaryExpression;

            if (binaryExpression != null && binaryExpression.NodeType == ExpressionType.Equal)
            {
                var left = binaryExpression.Left as MemberExpression;
                if (left != null)
                {
                    if (CheckValues(parser, out hint, left, binaryExpression.Right))
                    {
                        return(true);
                    }
                }

                var right = binaryExpression.Right as MemberExpression;
                if (right != null)
                {
                    if (CheckValues(parser, out hint, right, binaryExpression.Left))
                    {
                        return(true);
                    }
                }
            }

            var methE = expression as MethodCallExpression;

            if (methE != null)
            {
                if (EqualsMethodInfos.Any(x => x == methE.Method))
                {
                    var objectToCheck = methE.Object as MemberExpression;
                    if (objectToCheck != null)
                    {
                        if (CheckValues(parser, out hint, objectToCheck, methE.Arguments.Single()))
                        {
                            return(true);
                        }
                    }

                    var argToCheck = methE.Arguments.Single() as MemberExpression;
                    if (argToCheck != null)
                    {
                        if (CheckValues(parser, out hint, argToCheck, methE.Object))
                        {
                            return(true);
                        }
                    }
                }
                else if (StaticEqualsMethodInfos.Any(x => x == methE.Method))
                {
                    // this gets a little hairy as there is a conversion to object before the Equals method is called

                    var leftOuter = methE.Arguments[0] as UnaryExpression;
                    if (leftOuter != null && leftOuter.NodeType == ExpressionType.Convert)
                    {
                        var leftInner = leftOuter.Operand as MemberExpression;
                        if (leftInner != null)
                        {
                            if (CheckValues(parser, out hint, leftInner, methE.Arguments[1]))
                            {
                                return(true);
                            }
                        }
                    }

                    var rightOuter = methE.Arguments[1] as UnaryExpression;
                    if (rightOuter != null && rightOuter.NodeType == ExpressionType.Convert)
                    {
                        var rightInner = rightOuter.Operand as MemberExpression;
                        if (rightInner != null)
                        {
                            if (CheckValues(parser, out hint, rightInner, methE.Arguments[0]))
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            hint = null;
            return(false);
        }
コード例 #52
0
 public bool IsSatisfied(CasePlanInstanceExecutionContext executionContext)
 {
     return(ExpressionParser.IsValid(Expression.Body, executionContext));
 }
コード例 #53
0
        public void GetPropertyNameShouldThrowExceptionWithInvalidMemberExpression()
        {
            Expression <Func <WebApiController, object> > expression = c => c.OkResultWithResponse();

            ExpressionParser.GetPropertyName(expression);
        }
コード例 #54
0
 public JSONQuerySelector()
 {
     parser = new ExpressionParser();
 }
コード例 #55
0
        public void ResolveMethodArgumentsShouldThrowArgumentExceptionWithInvalidMethodCallExpression()
        {
            Expression <Func <int> > expression = () => 0;

            ExpressionParser.ResolveMethodArguments(expression);
        }
コード例 #56
0
        internal SqlServerFhirStorageTestsFixture(int maximumSupportedSchemaVersion, string databaseName, IOptions <CoreFeatureConfiguration> coreFeatures = null)
        {
            var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString;

            _maximumSupportedSchemaVersion = maximumSupportedSchemaVersion;
            _databaseName        = databaseName;
            TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString)
            {
                InitialCatalog = _databaseName
            }.ToString();

            var schemaOptions = new SqlServerSchemaOptions {
                AutomaticUpdatesEnabled = true
            };
            var config = Options.Create(new SqlServerDataStoreConfiguration {
                ConnectionString = TestConnectionString, Initialize = true, SchemaOptions = schemaOptions, StatementTimeout = TimeSpan.FromMinutes(10)
            });

            SchemaInformation = new SchemaInformation(SchemaVersionConstants.Min, maximumSupportedSchemaVersion);
            var scriptProvider      = new ScriptProvider <SchemaVersion>();
            var baseScriptProvider  = new BaseScriptProvider();
            var mediator            = Substitute.For <IMediator>();
            var sqlSortingValidator = new SqlServerSortingValidator(SchemaInformation);

            var sqlConnectionStringProvider = new DefaultSqlConnectionStringProvider(config);

            SqlConnectionFactory = new DefaultSqlConnectionFactory(sqlConnectionStringProvider);
            var schemaManagerDataStore = new SchemaManagerDataStore(SqlConnectionFactory, config, NullLogger <SchemaManagerDataStore> .Instance);

            _schemaUpgradeRunner = new SchemaUpgradeRunner(scriptProvider, baseScriptProvider, NullLogger <SchemaUpgradeRunner> .Instance, SqlConnectionFactory, schemaManagerDataStore);
            _schemaInitializer   = new SchemaInitializer(config, schemaManagerDataStore, _schemaUpgradeRunner, SchemaInformation, SqlConnectionFactory, sqlConnectionStringProvider, mediator, NullLogger <SchemaInitializer> .Instance);

            _searchParameterDefinitionManager = new SearchParameterDefinitionManager(ModelInfoProvider.Instance, _mediator, () => _searchService.CreateMockScope(), NullLogger <SearchParameterDefinitionManager> .Instance);

            _searchParameterDefinitionManager.StartAsync(CancellationToken.None);

            _filebasedSearchParameterStatusDataStore = new FilebasedSearchParameterStatusDataStore(_searchParameterDefinitionManager, ModelInfoProvider.Instance);

            var securityConfiguration = new SecurityConfiguration {
                PrincipalClaims = { "oid" }
            };

            var sqlServerFhirModel = new SqlServerFhirModel(
                SchemaInformation,
                _searchParameterDefinitionManager,
                () => _filebasedSearchParameterStatusDataStore,
                Options.Create(securityConfiguration),
                SqlConnectionFactory,
                Substitute.For <IMediator>(),
                NullLogger <SqlServerFhirModel> .Instance);

            SqlServerFhirModel = sqlServerFhirModel;

            var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSqlServerTableRowParameterGenerators();
            serviceCollection.AddSingleton(sqlServerFhirModel);
            serviceCollection.AddSingleton <ISqlServerFhirModel>(sqlServerFhirModel);
            serviceCollection.AddSingleton(searchParameterToSearchValueTypeMap);

            ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

            var upsertResourceTvpGeneratorV6           = serviceProvider.GetRequiredService <V6.UpsertResourceTvpGenerator <ResourceMetadata> >();
            var upsertResourceTvpGeneratorV7           = serviceProvider.GetRequiredService <V7.UpsertResourceTvpGenerator <ResourceMetadata> >();
            var upsertResourceTvpGeneratorV13          = serviceProvider.GetRequiredService <V13.UpsertResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var upsertResourceTvpGeneratorV17          = serviceProvider.GetRequiredService <V17.UpsertResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var upsertResourceTvpGeneratorVLatest      = serviceProvider.GetRequiredService <VLatest.UpsertResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var reindexResourceTvpGeneratorV17         = serviceProvider.GetRequiredService <V17.ReindexResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var bulkReindexResourceTvpGeneratorV17     = serviceProvider.GetRequiredService <V17.BulkReindexResourcesTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var reindexResourceTvpGeneratorVLatest     = serviceProvider.GetRequiredService <VLatest.ReindexResourceTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var bulkReindexResourceTvpGeneratorVLatest = serviceProvider.GetRequiredService <VLatest.BulkReindexResourcesTvpGenerator <IReadOnlyList <ResourceWrapper> > >();
            var upsertSearchParamsTvpGenerator         = serviceProvider.GetRequiredService <VLatest.UpsertSearchParamsTvpGenerator <List <ResourceSearchParameterStatus> > >();

            _supportedSearchParameterDefinitionManager = new SupportedSearchParameterDefinitionManager(_searchParameterDefinitionManager);

            SqlTransactionHandler       = new SqlTransactionHandler();
            SqlConnectionWrapperFactory = new SqlConnectionWrapperFactory(SqlTransactionHandler, new SqlCommandWrapperFactory(), SqlConnectionFactory);

            SqlServerSearchParameterStatusDataStore = new SqlServerSearchParameterStatusDataStore(
                () => SqlConnectionWrapperFactory.CreateMockScope(),
                upsertSearchParamsTvpGenerator,
                () => _filebasedSearchParameterStatusDataStore,
                SchemaInformation,
                sqlSortingValidator,
                sqlServerFhirModel,
                _searchParameterDefinitionManager);

            IOptions <CoreFeatureConfiguration> options = coreFeatures ?? Options.Create(new CoreFeatureConfiguration());

            _fhirDataStore = new SqlServerFhirDataStore(
                sqlServerFhirModel,
                searchParameterToSearchValueTypeMap,
                upsertResourceTvpGeneratorV6,
                upsertResourceTvpGeneratorV7,
                upsertResourceTvpGeneratorV13,
                upsertResourceTvpGeneratorV17,
                upsertResourceTvpGeneratorVLatest,
                reindexResourceTvpGeneratorV17,
                reindexResourceTvpGeneratorVLatest,
                bulkReindexResourceTvpGeneratorV17,
                bulkReindexResourceTvpGeneratorVLatest,
                options,
                SqlConnectionWrapperFactory,
                new CompressedRawResourceConverter(),
                NullLogger <SqlServerFhirDataStore> .Instance,
                SchemaInformation);

            _fhirOperationDataStore = new SqlServerFhirOperationDataStore(SqlConnectionWrapperFactory, NullLogger <SqlServerFhirOperationDataStore> .Instance);

            _fhirRequestContextAccessor.RequestContext.CorrelationId.Returns(Guid.NewGuid().ToString());
            _fhirRequestContextAccessor.RequestContext.RouteName.Returns("routeName");

            var searchableSearchParameterDefinitionManager = new SearchableSearchParameterDefinitionManager(_searchParameterDefinitionManager, _fhirRequestContextAccessor);
            var searchParameterExpressionParser            = new SearchParameterExpressionParser(new ReferenceSearchValueParser(_fhirRequestContextAccessor));
            var expressionParser = new ExpressionParser(() => searchableSearchParameterDefinitionManager, searchParameterExpressionParser);

            var searchOptionsFactory = new SearchOptionsFactory(
                expressionParser,
                () => searchableSearchParameterDefinitionManager,
                options,
                _fhirRequestContextAccessor,
                sqlSortingValidator,
                NullLogger <SearchOptionsFactory> .Instance);

            var searchParamTableExpressionQueryGeneratorFactory = new SearchParamTableExpressionQueryGeneratorFactory(searchParameterToSearchValueTypeMap);
            var sqlRootExpressionRewriter = new SqlRootExpressionRewriter(searchParamTableExpressionQueryGeneratorFactory);
            var chainFlatteningRewriter   = new ChainFlatteningRewriter(searchParamTableExpressionQueryGeneratorFactory);
            var sortRewriter = new SortRewriter(searchParamTableExpressionQueryGeneratorFactory);
            var partitionEliminationRewriter = new PartitionEliminationRewriter(sqlServerFhirModel, SchemaInformation, () => searchableSearchParameterDefinitionManager);

            _searchService = new SqlServerSearchService(
                searchOptionsFactory,
                _fhirDataStore,
                sqlServerFhirModel,
                sqlRootExpressionRewriter,
                chainFlatteningRewriter,
                sortRewriter,
                partitionEliminationRewriter,
                SqlConnectionWrapperFactory,
                SchemaInformation,
                _fhirRequestContextAccessor,
                new CompressedRawResourceConverter(),
                NullLogger <SqlServerSearchService> .Instance);

            ISearchParameterSupportResolver searchParameterSupportResolver = Substitute.For <ISearchParameterSupportResolver>();

            searchParameterSupportResolver.IsSearchParameterSupported(Arg.Any <SearchParameterInfo>()).Returns((true, false));

            _searchParameterStatusManager = new SearchParameterStatusManager(
                SqlServerSearchParameterStatusDataStore,
                _searchParameterDefinitionManager,
                searchParameterSupportResolver,
                mediator,
                NullLogger <SearchParameterStatusManager> .Instance);

            _testHelper = new SqlServerFhirStorageTestHelper(initialConnectionString, MasterDatabaseName, sqlServerFhirModel, SqlConnectionFactory);
        }
コード例 #57
0
        void TestParse(string expression, ExpressionNode expected, ExpressionOptions options = ExpressionOptions.None, int baseOffset = 0)
        {
            var expr = ExpressionParser.Parse(expression, options, baseOffset);

            AssertEqual(expected, expr);
        }
コード例 #58
0
ファイル: DynamicExpression.cs プロジェクト: brezaie/CoreFra
        public static Expression Parse(Type resultType, string expression, params object[] values)
        {
            ExpressionParser parser = new ExpressionParser(null, expression, values);

            return(parser.Parse(resultType));
        }
コード例 #59
0
        /// <inheritdoc />
        public override IEnumerable <TokenPair> Tokenize(TokenInfo token, ParserOptions options)
        {
            var trim = token.Token;

            if (trim.StartsWith(TagOpen, StringComparison.OrdinalIgnoreCase))
            {
                yield return(new TokenPair(TagOpen.Trim(), token.TokenizerContext.CurrentLocation, ExpressionParser.ParseExpression(trim.Remove(0, OpenTag.Length).Trim(), token.TokenizerContext)));
            }
            if (string.Equals(trim, TagClose, StringComparison.OrdinalIgnoreCase))
            {
                yield return(new TokenPair(TagClose, trim, token.TokenizerContext.CurrentLocation));
            }
        }
コード例 #60
0
        /// <summary>Parses a lambda expression.</summary>
        /// <param name="service">Service with data and configuration.</param>
        /// <param name="setForIt">Resource set for "it" contextual variable.</param>
        /// <param name="typeForIt">Type for "it" contextual variable.</param>
        /// <param name="queryElementType">Actual (clr) element type for the sequence</param>
        /// <param name="expression">Expression to parse.</param>
        /// <returns>The parsed expression.</returns>
        private static LambdaExpression ParseLambdaForWhere(IDataService service, ResourceSetWrapper setForIt, ResourceType typeForIt, Type queryElementType, string expression)
        {
            Debug.Assert(service != null, "service != null");
            Debug.Assert(typeForIt != null, "typeForIt != null");
            Debug.Assert(typeForIt.ResourceTypeKind != ResourceTypeKind.EntityType || setForIt != null, "setForIt cannot be null if typeForIt is an entity type.");
            Debug.Assert(queryElementType != null, "queryElementType != null");
            Debug.Assert(expression != null, "expression != null");
            Debug.Assert(typeForIt.InstanceType == queryElementType, "typeForIt.InstanceType == queryElementType");

            ParameterExpression parameterForIt = Expression.Parameter(queryElementType, "it");
            ExpressionParser parser = new ExpressionParser(service, setForIt, typeForIt, parameterForIt, expression);
            return Expression.Lambda(parser.ParseWhere(), parameterForIt);
        }