public static string Format_Literal_Expression(LiteralExpression literal)
        {
            switch (literal.LiteralType)
            {
                case LiteralType.True:
                    return "true";
                case LiteralType.False:
                    return "false";
                case LiteralType.Null:
                    return "null";
                /*
            case LiteralType.DecimalInteger:
                break;
            case LiteralType.HexadecimalInteger:
                break;
            case LiteralType.OctalInteger:
                break;
            case LiteralType.Real:
                break;
            case LiteralType.Character:
                break;
            case LiteralType.String:
                break;
            case LiteralType.VerbatimString:
                break;
                 */
            }

            return literal.LiteralValue;
        }
        protected void Verify(string source, object value)
        {
            if (!(value is Expression))
                value = new LiteralExpression(value);

            base.Verify(source, (Expression)value);
        }
        /// <summary>
        /// Initializes a new instance of the LabelStatement class.
        /// </summary>
        /// <param name="tokens">
        /// The list of tokens that form the statement.
        /// </param>
        /// <param name="identifier">
        /// The label identifier.
        /// </param>
        internal LabelStatement(CsTokenList tokens, LiteralExpression identifier)
            : base(StatementType.Label, tokens)
        {
            Param.AssertNotNull(tokens, "tokens");
            Param.AssertNotNull(identifier, "identifier");

            this.identifier = identifier;
            this.AddExpression(identifier);
        }
        /// <summary>
        /// Initializes a new instance of the EventDeclaratorExpression class.
        /// </summary>
        /// <param name="tokens">
        /// The list of tokens that form the statement.
        /// </param>
        /// <param name="identifier">
        /// The identifier name of the event.
        /// </param>
        /// <param name="initializer">
        /// The initialization expression for the event.
        /// </param>
        internal EventDeclaratorExpression(CsTokenList tokens, LiteralExpression identifier, Expression initializer)
            : base(ExpressionType.EventDeclarator, tokens)
        {
            Param.AssertNotNull(tokens, "tokens");
            Param.AssertNotNull(identifier, "identifier");
            Param.Ignore(initializer);

            this.identifier = identifier;
            this.initializer = initializer;

            this.AddExpression(identifier);

            if (initializer != null)
            {
                this.AddExpression(initializer);
            }
        }
        private static Expression CoerceLiteralExpression(LiteralExpression literal)
        {
            // Force 0 and 1 literals to boolean.

            if (literal.Value is int)
            {
                switch ((int)literal.Value)
                {
                    case 0:
                        return new LiteralExpression(false, LiteralType.Boolean);

                    case 1:
                        return new LiteralExpression(true, LiteralType.Boolean);
                }
            }

            throw new ODataException(ErrorMessages.Parser_ExpectedBooleanExpression);
        }
        /// <summary>
        /// Initializes a new instance of the AttributeExpression class.
        /// </summary>
        /// <param name="tokens">
        /// The list of tokens that form the expression.
        /// </param>
        /// <param name="target">
        /// The attribute target, if any.
        /// </param>
        /// <param name="initialization">
        /// The attribute initialization call.
        /// </param>
        internal AttributeExpression(CsTokenList tokens, LiteralExpression target, Expression initialization)
            : base(ExpressionType.Attribute, tokens)
        {
            Param.AssertNotNull(tokens, "tokens");
            Param.Ignore(target);
            Param.AssertNotNull(initialization, "initialization");

            // Add the target expression.
            this.target = target;
            if (target != null)
            {
                this.AddExpression(target);
            }

            // Add the initialization expression.
            this.initialization = initialization;
            this.AddExpression(initialization);
        }
Beispiel #7
0
	void LiteralExpression(ref ExpressionTreeBase expr) {
		if (la.kind == 35) {
			Get();
			expr = new RangeExpression(t.val); 
		} else if (la.kind == 3) {
			Get();
			expr = new LiteralExpression(t.val); 
		} else if (la.kind == 4) {
			Get();
			expr = new LiteralExpression(t.val.Substring(1, t.val.Length - 2), true); 
		} else if (la.kind == 5) {
			Get();
			expr = new ValueExpression(Int32.Parse(t.val.Substring(1))); 
		} else if (la.kind == 1) {
			Get();
			expr = new LiteralExpression(t.val); 
		} else SynErr(53);
	}
        public sealed override void Initialize(AnalysisContext context)
        {
            context.RegisterCompilationStartAction(
                (compilationContext) =>
            {
                Dictionary <IFieldSymbol, HashSet <INamedTypeSymbol> > fieldsSourceTypes = new Dictionary <IFieldSymbol, HashSet <INamedTypeSymbol> >();

                compilationContext.RegisterOperationBlockStartAction(
                    (operationBlockContext) =>
                {
                    if (operationBlockContext.OwningSymbol is IMethodSymbol containingMethod)
                    {
                        Dictionary <ILocalSymbol, HashSet <INamedTypeSymbol> > localsSourceTypes = new Dictionary <ILocalSymbol, HashSet <INamedTypeSymbol> >();

                        // Track explicit assignments.
                        operationBlockContext.RegisterOperationAction(
                            (operationContext) =>
                        {
                            if (operationContext.Operation is IAssignmentExpression assignment)
                            {
                                AssignTo(assignment.Target, localsSourceTypes, fieldsSourceTypes, assignment.Value);
                            }
                            else if (operationContext.Operation is IIncrementOrDecrementExpression increment)
                            {
                                SyntaxNode syntax = increment.Syntax;
                                ITypeSymbol type  = increment.Type;
                                Optional <object> constantValue = new Optional <object>(1);
                                bool isImplicit = increment.IsImplicit;
                                var value       = new LiteralExpression(operationContext.Compilation.GetSemanticModel(syntax.SyntaxTree), syntax, type, constantValue, isImplicit);

                                AssignTo(increment.Target, localsSourceTypes, fieldsSourceTypes, value);
                            }
                            else
                            {
                                throw TestExceptionUtilities.UnexpectedValue(operationContext.Operation);
                            }
                        },
                            OperationKind.SimpleAssignmentExpression,
                            OperationKind.CompoundAssignmentExpression,
                            OperationKind.IncrementExpression);

                        // Track arguments that match out or ref parameters.
                        operationBlockContext.RegisterOperationAction(
                            (operationContext) =>
                        {
                            IInvocationExpression invocation = (IInvocationExpression)operationContext.Operation;
                            foreach (IArgument argument in invocation.ArgumentsInEvaluationOrder)
                            {
                                if (argument.Parameter.RefKind == RefKind.Out || argument.Parameter.RefKind == RefKind.Ref)
                                {
                                    AssignTo(argument.Value, localsSourceTypes, fieldsSourceTypes, argument.Parameter.Type);
                                }
                            }
                        },
                            OperationKind.InvocationExpression);

                        // Track local variable initializations.
                        operationBlockContext.RegisterOperationAction(
                            (operationContext) =>
                        {
                            IVariableDeclarationStatement declaration = (IVariableDeclarationStatement)operationContext.Operation;
                            foreach (IVariableDeclaration variable in declaration.Declarations)
                            {
                                foreach (ILocalSymbol local in variable.Variables)
                                {
                                    if (variable.Initializer != null)
                                    {
                                        AssignTo(local, local.Type, localsSourceTypes, variable.Initializer);
                                    }
                                }
                            }
                        },
                            OperationKind.VariableDeclarationStatement);

                        // Report locals that could have more specific types.
                        operationBlockContext.RegisterOperationBlockEndAction(
                            (operationBlockEndContext) =>
                        {
                            foreach (ILocalSymbol local in localsSourceTypes.Keys)
                            {
                                if (HasMoreSpecificSourceType(local, local.Type, localsSourceTypes, out var mostSpecificSourceType))
                                {
                                    Report(operationBlockEndContext, local, mostSpecificSourceType, LocalCouldHaveMoreSpecificTypeDescriptor);
                                }
                            }
                        });
                    }
                });

                // Track field initializations.
                compilationContext.RegisterOperationAction(
                    (operationContext) =>
                {
                    IFieldInitializer initializer = (IFieldInitializer)operationContext.Operation;
                    foreach (IFieldSymbol initializedField in initializer.InitializedFields)
                    {
                        AssignTo(initializedField, initializedField.Type, fieldsSourceTypes, initializer.Value);
                    }
                },
                    OperationKind.FieldInitializer);

                // Report fields that could have more specific types.
                compilationContext.RegisterCompilationEndAction(
                    (compilationEndContext) =>
                {
                    foreach (IFieldSymbol field in fieldsSourceTypes.Keys)
                    {
                        if (HasMoreSpecificSourceType(field, field.Type, fieldsSourceTypes, out var mostSpecificSourceType))
                        {
                            Report(compilationEndContext, field, mostSpecificSourceType, FieldCouldHaveMoreSpecificTypeDescriptor);
                        }
                    }
                });
            });
        }
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LayoutKeyValue"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 public LayoutKeyValue(Identifier name, LiteralExpression value)
 {
     Name  = name;
     Value = value;
 }
Beispiel #10
0
        private static MethodDeclaration GenerateMethod(ClassDeclaration clientClass, Method method, TypeReference requestType)
        {
            var m = clientClass.AddMember(new MethodDeclaration(method.MethodGroup.Name + '_' + GetMethodName(method)));

            m.SetData("Method", method);
            var buildUrlMethod = GenerateBuildUrlMethod(clientClass, method, requestType);

            GenerateMethodSignature(method, m, requestType, out var requestArgument, out var requestOptionsArgument, out var cancellationTokenArgument);
            m.Modifiers = Modifiers.Private;
            if (method.MethodType != MethodType.GetPaged)
            {
                m.Modifiers |= Modifiers.Async;
            }

            // Method body
            m.Statements = new StatementCollection();

            // 1. Create url from parameters
            var buildUrlExpression = new MethodInvokeExpression(new MemberReferenceExpression(new TypeReference(clientClass), buildUrlMethod));

            if (buildUrlMethod.Arguments.Count > 0)
            {
                buildUrlExpression.Arguments.Add(requestArgument);
            }

            var urlVariable = new VariableDeclarationStatement(typeof(string), "url", buildUrlExpression);

            m.Statements.Add(urlVariable);

            if (method.MethodType == MethodType.GetPaged)
            {
                // return new Meziantou.GitLab.PagedResponse<MergeRequest>(this, url, requestOptions);
                m.Statements.Add(new ReturnStatement(new NewObjectExpression(m.ReturnType !.Clone(), new ThisExpression(), urlVariable, requestOptionsArgument)));
            }
            else
            {
                // 2. Create HttpRequestMessage object
                var requestVariable = new VariableDeclarationStatement(typeof(HttpRequestMessage), "requestMessage", new NewObjectExpression(typeof(HttpRequestMessage)));
                var usingStatement  = new UsingStatement()
                {
                    Statement = requestVariable, Body = new StatementCollection()
                };
                m.Statements.Add(usingStatement);
                var statements = usingStatement.Body;

                statements.Add(new AssignStatement(new MemberReferenceExpression(requestVariable, nameof(HttpRequestMessage.Method)), GetHttpMethod(method.MethodType)));
                statements.Add(new AssignStatement(new MemberReferenceExpression(requestVariable, nameof(HttpRequestMessage.RequestUri)), new NewObjectExpression(typeof(Uri), urlVariable, new MemberReferenceExpression(typeof(UriKind), nameof(UriKind.RelativeOrAbsolute)))));

                CreateBodyArgument(method, statements, requestArgument, requestVariable);

                // 3. Send request
                // var response = await SendAsync(request, options, cancellationToken).ConfigureAwait(false);
                var responseVariable = new VariableDeclarationStatement(WellKnownTypes.HttpResponseTypeReference.MakeNullable(), "response", LiteralExpression.Null());
                statements.Add(responseVariable);
                var responseTry = new TryCatchFinallyStatement()
                {
                    Try = new StatementCollection()
                };
                statements.Add(responseTry);
                responseTry.Try.Add(new AssignStatement(responseVariable, new AwaitExpression(new MethodInvokeExpression(new MemberReferenceExpression(new ThisExpression(), "SendAsync"), requestVariable, requestOptionsArgument, cancellationTokenArgument)).ConfigureAwait(false)));

                // Dispose reponse in catch if Stream or in finally if not stream
                var disposeReponseStatements = new ConditionStatement()
                {
                    Condition      = new BinaryExpression(BinaryOperator.NotEquals, responseVariable, LiteralExpression.Null()),
                    TrueStatements = responseVariable.CreateInvokeMethodExpression("Dispose"),
                };

                if (method.ReturnType == ModelRef.File)
                {
                    responseTry.Catch = new CatchClauseCollection
                    {
                        new CatchClause()
                        {
                            Body = disposeReponseStatements,
                        },
                    };

                    responseTry.Catch[0].Body.Add(new ThrowStatement());
                }
                else
                {
                    responseTry.Finally = disposeReponseStatements;
                }

                // 4. Convert and return response object
                //    if (response.StatusCode == HttpStatusCode.NotFound) return default;
                if (method.MethodType == MethodType.Get)
                {
                    responseTry.Try.Add(new ConditionStatement()
                    {
                        Condition      = new BinaryExpression(BinaryOperator.Equals, responseVariable.CreateMemberReferenceExpression("StatusCode"), new MemberReferenceExpression(typeof(HttpStatusCode), "NotFound")),
                        TrueStatements = new ReturnStatement(new DefaultValueExpression()),
                    });
                }

                // await response.EnsureStatusCodeAsync(cancellationToken).ConfigureAwait(false);
                responseTry.Try.Add(new AwaitExpression(new MethodInvokeExpression(new MemberReferenceExpression(responseVariable, "EnsureStatusCodeAsync"), cancellationTokenArgument)).ConfigureAwait(false));

                if (method.ReturnType != null)
                {
                    // var result = await response.ToObjectAsync<T>(cancellationToken).ConfigureAwait(false);
                    var resultVariable = new VariableDeclarationStatement(m.ReturnType.Parameters[0].MakeNullable(), "result");
                    responseTry.Try.Add(resultVariable);
                    if (method.MethodType == MethodType.Get && method.ReturnType == ModelRef.File)
                    {
                        resultVariable.InitExpression = new AwaitExpression(responseVariable.CreateInvokeMethodExpression("ToStreamAsync", cancellationTokenArgument)).ConfigureAwait(false);
                    }
                    else if (method.MethodType == MethodType.GetCollection)
                    {
                        resultVariable.InitExpression = new AwaitExpression(responseVariable.CreateInvokeMethodExpression("ToCollectionAsync", new TypeReference[] { method.ReturnType.ToPropertyTypeReference() }, cancellationTokenArgument)).ConfigureAwait(false);
                    }
                    else
                    {
                        resultVariable.InitExpression = new AwaitExpression(responseVariable.CreateInvokeMethodExpression("ToObjectAsync", new TypeReference[] { method.ReturnType.ToPropertyTypeReference() }, cancellationTokenArgument)).ConfigureAwait(false);
                    }

                    // if (result is null)
                    //   throw new GitLabException(response.RequestMethod, response.RequestUri, response.StatusCode, $"The response cannot be converted to '{typeof(T)}' because the body is null or empty");
                    if (method.MethodType != MethodType.Get)
                    {
                        responseTry.Try.Add(new ConditionStatement()
                        {
                            Condition      = new BinaryExpression(BinaryOperator.Equals, resultVariable, LiteralExpression.Null()),
                            TrueStatements = new ThrowStatement(new NewObjectExpression(WellKnownTypes.GitLabExceptionTypeReference,
                                                                                        responseVariable.CreateMemberReferenceExpression("RequestMethod"),
                                                                                        responseVariable.CreateMemberReferenceExpression("RequestUri"),
                                                                                        responseVariable.CreateMemberReferenceExpression("StatusCode"),
                                                                                        new LiteralExpression($"The response cannot be converted to '{method.ReturnType.ToPropertyTypeReference().ClrFullTypeName}' because the body is null or empty"))),
                        });
                    }

                    responseTry.Try.Add(new ReturnStatement(resultVariable));
                }
            }

            return(m);
Beispiel #11
0
 public void VisitLiteralExpression(LiteralExpression literal)
 {
     throw new NotImplementedException();
 }
Beispiel #12
0
 protected abstract T CompileLiteralExpression(LiteralExpression expression);
Beispiel #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LayoutKeyValue"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 public LayoutKeyValue(Identifier name, LiteralExpression value)
 {
     Name = name;
     Value = value;
 }
        public Window1()
        {
            BindKey(ApplicationCommands.Find, Key.F, ModifierKeys.Control);
            BindKey(EditingCommands.Backspace, Key.N, ModifierKeys.Alt);
            BindKey(EditingCommands.Delete, Key.M, ModifierKeys.Alt);
            BindKey(EditingCommands.DeleteNextWord, Key.M, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.DeletePreviousWord, Key.N, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveDownByLine, Key.K, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveDownByPage, Key.K, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveLeftByCharacter, Key.J, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveRightByCharacter, Key.Oem3, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveUpByLine, Key.L, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveLeftByWord, Key.J, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveRightByWord, Key.M, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveToDocumentEnd, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveToDocumentStart, Key.U, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveToLineEnd, Key.Oem1, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveToLineStart, Key.U, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveUpByPage, Key.L, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.SelectDownByLine, Key.K, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectDownByPage, Key.K, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectLeftByCharacter, Key.J, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectLeftByWord, Key.J, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectRightByCharacter, Key.Oem3, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectRightByWord, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToDocumentEnd, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToDocumentStart, Key.U, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToLineEnd, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToLineStart, Key.U, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectUpByLine, Key.L, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectUpByPage, Key.L, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            InitializeComponent();
            textBox.FontSize       = 16;
            intellisense.MaxHeight = 100;
            intellisense.Width     = 200;
            intellisense.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Hidden);

            textBox.FontFamily             = new FontFamily("Courier New");
            textBox.AcceptsTab             = true;
            intellisense.MouseDoubleClick += delegate {
                Complete();
            };
            textBox.PreviewKeyDown += delegate(object sender, KeyEventArgs e) {
                if (Intellisense)
                {
                    e.Handled = true;
                    if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt)
                    {
                        if (e.Key == Key.L)
                        {
                            IntellisenseUp();
                        }
                        else if (e.Key == Key.K)
                        {
                            IntellisenseDown();
                        }
                        else
                        {
                            e.Handled = false;
                        }
                    }
                    else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
                    {
                        if (e.Key == Key.L)
                        {
                            EditingCommands.MoveToLineStart.Execute(null, textBox);
                            EditingCommands.SelectToLineEnd.Execute(null, textBox);
                            EditingCommands.Delete.Execute(null, textBox);
                        }
                        else if (e.Key == Key.Space)
                        {
                        }
                        else
                        {
                            e.Handled = false;
                        }
                    }
                    else if (e.Key == Key.Return)
                    {
                        Complete();
                    }
                    else if (e.Key == Key.Tab)
                    {
                        Complete();
                    }
                    else if (e.Key == Key.Up)
                    {
                        IntellisenseUp();
                    }
                    else if (e.Key == Key.Down)
                    {
                        IntellisenseDown();
                    }
                    else
                    {
                        e.Handled = false;
                    }
                }
            };;
            textBox.KeyDown += delegate(object obj, KeyEventArgs e) {
                if (e.Key == Key.Return)
                {
                    string line = textBox.GetLineText(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart));
                    textBox.SelectedText    = "\n".PadRight(1 + line.Length - line.TrimStart('\t').Length, '\t');
                    textBox.SelectionStart  = textBox.SelectionStart + textBox.SelectionLength;
                    textBox.SelectionLength = 0;
                    textBox.Focus();
                }
                else if (e.Key == Key.Escape)
                {
                    if (Intellisense)
                    {
                        intellisense.Visibility = Visibility.Hidden;
                    }
                }
                else if (e.Key == Key.OemPeriod)
                {
                    string text = textBox.Text.Substring(0, textBox.SelectionStart);
                    searchStart           = textBox.SelectionStart;
                    Interpreter.profiling = false;
                    foreach (Parser.CachedRule rule in Parser.CachedRule.cachedRules)
                    {
                        rule.cached.Clear();
                    }
                    Parser            parser  = new Parser(text, fileName);
                    Map               map     = null;
                    bool              matched = Parser.File.Match(parser, ref map);
                    LiteralExpression gac     = new LiteralExpression(Gac.gac, null);
                    LiteralExpression lib     = new LiteralExpression(Gac.gac["library"], gac);
                    lib.Statement             = new LiteralStatement(gac);
                    KeyStatement.intellisense = true;
                    map[CodeKeys.Function].GetExpression(lib).Statement = new LiteralStatement(lib);
                    map[CodeKeys.Function].Compile(lib);
                    Source key = new Source(
                        parser.State.Line,
                        parser.State.Column,
                        parser.FileName);
                    intellisense.Items.Clear();
                    if (Meta.Expression.sources.ContainsKey(key))
                    {
                        List <Meta.Expression> list = Meta.Expression.sources[key];
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (list[i] is Search || list[i] is Select)
                            {
                                PositionIntellisense();
                                intellisense.Items.Clear();
                                Structure     s    = list[i].EvaluateStructure();
                                List <string> keys = new List <string>();
                                if (s != null)
                                {
                                    foreach (Map m in ((LiteralStructure)s).Literal.Keys)
                                    {
                                        keys.Add(m.ToString());
                                    }
                                }
                                keys.Sort(delegate(string a, string b) {
                                    return(a.CompareTo(b));
                                });
                                if (keys.Count != 0)
                                {
                                    intellisense.Visibility = Visibility.Visible;
                                }
                                foreach (string k in keys)
                                {
                                    intellisense.Items.Add(k);
                                }
                                if (intellisense.Items.Count != 0)
                                {
                                    intellisense.SelectedIndex = 0;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("no intellisense" + Meta.Expression.sources.Count);
                    }
                    Meta.Expression.sources.Clear();
                }
            };
            DockPanel dockPanel = new DockPanel();

            Menu menu = new Menu();

            DockPanel.SetDock(menu, Dock.Top);
            MenuItem file = new MenuItem();
            MenuItem save = new MenuItem();
            MenuItem run  = new MenuItem();
            MenuItem open = new MenuItem();

            file.Header = "File";
            open.Header = "Open";
            save.Header = "Save";
            run.Header  = "Run";
            open.Click += delegate {
                OpenFileDialog dialog = new OpenFileDialog();
                if (dialog.ShowDialog() == true)
                {
                    Open(dialog.FileName);
                }
            };
            run.Click += delegate {
                Save();
                Process.Start(System.IO.Path.Combine(@"D:\Meta\", @"bin\Debug\Meta.exe"), fileName);
            };
            save.Click += delegate {
                Save();
            };
            DockPanel.SetDock(status, Dock.Bottom);
            dockPanel.Children.Add(status);

            file.Items.Add(open);
            file.Items.Add(save);
            file.Items.Add(run);
            menu.Items.Add(file);
            dockPanel.Children.Add(menu);

            DockPanel.SetDock(textBox, Dock.Bottom);
            textBox.TextChanged += delegate {
                if (Intellisense)
                {
                    if (textBox.SelectionStart <= searchStart)
                    {
                        intellisense.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        int index = textBox.Text.Substring(0, textBox.SelectionStart).LastIndexOf('.');
                        if (index != -1)
                        {
                            string text = textBox.Text.Substring(index + 1, textBox.SelectionStart - index - 1);
                            foreach (string item in intellisense.Items)
                            {
                                if (item.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                                {
                                    intellisense.SelectedItem = item;
                                    intellisense.ScrollIntoView(intellisense.SelectedItem);
                                    break;
                                }
                            }
                        }
                    }
                }
            };
            textBox.SelectionChanged += delegate {
                status.Content = "Ln " +
                                 (textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart) + 1);
            };
            Canvas canvas = new Canvas();

            canvas.Children.Add(textBox);
            canvas.Background = Brushes.Yellow;
            DockPanel.SetDock(canvas, Dock.Top);
            scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
            scrollViewer.VerticalScrollBarVisibility   = ScrollBarVisibility.Visible;
            scrollViewer.Content = canvas;
            dockPanel.Children.Add(scrollViewer);
            const int width  = 0;
            const int height = 0;

            Canvas.SetLeft(textBox, width / 2);
            Canvas.SetTop(textBox, height / 2);
            textBox.SizeChanged += delegate {
                canvas.Width  = textBox.ActualWidth + width;
                canvas.Height = textBox.ActualHeight + height;
            };
            intellisense.SelectionChanged += delegate(object sender, SelectionChangedEventArgs e) {
                if (intellisense.SelectedItem != null)
                {
                    intellisense.ScrollIntoView(intellisense.SelectedItem);
                }
            };
            intellisense.Visibility = Visibility.Hidden;
            Canvas.SetZIndex(intellisense, 100);
            canvas.Children.Add(intellisense);
            this.Content = dockPanel;
            this.Loaded += delegate {
                Open(@"D:\meta\game.meta");
                textBox.Focus();
                textBox.SelectionStart = 0;
            };
        }
Beispiel #15
0
        public object Visit(LiteralExpression literalExpression)
        {
            PrintMiddle(literalExpression.Value.Value, ConsoleColor.Magenta);

            return(null !);
        }
 public override void Visit(LiteralExpression expression)
 {
     _result = expression.Value;
 }
Beispiel #17
0
 public CaseExpression(LiteralExpression literalValue, Expression bodyExp)
 {
     this.literal = literalValue;
 }
Beispiel #18
0
 private static void FormatLiteralExpression(int prefixLength, StringBuilder builder, LiteralExpression literalExpression)
 {
     builder.AppendLine(literalExpression.LiteralValue.Value == null
         ? AddPrefix(prefixLength, "value: null")
         : AddPrefix(prefixLength,
                     $"value: {literalExpression.LiteralValue.Value}({literalExpression.ValueType.Name})"));
     builder.AppendLine(AddPrefix(prefixLength, $"raw: {literalExpression.LiteralValue.Literal}"));
 }
        public Window1()
        {
            BindKey(ApplicationCommands.Find, Key.F, ModifierKeys.Control);
            BindKey(EditingCommands.Backspace, Key.N, ModifierKeys.Alt);
            BindKey(EditingCommands.Delete, Key.M, ModifierKeys.Alt);
            BindKey(EditingCommands.DeleteNextWord, Key.M, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.DeletePreviousWord, Key.N, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveDownByLine, Key.K, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveDownByPage, Key.K, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveLeftByCharacter, Key.J, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveRightByCharacter, Key.Oem3, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveUpByLine, Key.L, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveLeftByWord, Key.J, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveRightByWord, Key.M, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveToDocumentEnd, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveToDocumentStart, Key.U, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.MoveToLineEnd, Key.Oem1, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveToLineStart, Key.U, ModifierKeys.Alt);
            BindKey(EditingCommands.MoveUpByPage, Key.L, ModifierKeys.Alt | ModifierKeys.Control);
            BindKey(EditingCommands.SelectDownByLine, Key.K, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectDownByPage, Key.K, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectLeftByCharacter, Key.J, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectLeftByWord, Key.J, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectRightByCharacter, Key.Oem3, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectRightByWord, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToDocumentEnd, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToDocumentStart, Key.U, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToLineEnd, Key.Oem1, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectToLineStart, Key.U, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectUpByLine, Key.L, ModifierKeys.Alt | ModifierKeys.Shift);
            BindKey(EditingCommands.SelectUpByPage, Key.L, ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Shift);
            InitializeComponent();
            textBox.FontSize = 16;
            intellisense.MaxHeight = 100;
            intellisense.Width = 200;
            intellisense.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Hidden);

            textBox.FontFamily = new FontFamily("Courier New");
            textBox.AcceptsTab = true;
            intellisense.MouseDoubleClick += delegate {
                Complete();
            };
            textBox.PreviewKeyDown += delegate(object sender, KeyEventArgs e) {
                if (Intellisense) {
                    e.Handled = true;
                    if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt) {
                        if (e.Key == Key.L) {
                            IntellisenseUp();
                        }
                        else if (e.Key == Key.K) {
                            IntellisenseDown();
                        }
                        else {
                            e.Handled = false;
                        }
                    }
                    else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control) {
                        if (e.Key == Key.L) {
                            EditingCommands.MoveToLineStart.Execute(null, textBox);
                            EditingCommands.SelectToLineEnd.Execute(null, textBox);
                            EditingCommands.Delete.Execute(null, textBox);
                        }
                        else if (e.Key == Key.Space) {
                        }
                        else {
                            e.Handled = false;
                        }
                    }
                    else if (e.Key == Key.Return) {
                        Complete();
                    }
                    else if (e.Key == Key.Tab) {
                        Complete();
                    }
                    else if (e.Key == Key.Up) {
                        IntellisenseUp();
                    }
                    else if (e.Key == Key.Down) {
                        IntellisenseDown();
                    }
                    else {
                        e.Handled = false;
                    }
                }
            };;
            textBox.KeyDown += delegate(object obj, KeyEventArgs e) {
                if (e.Key == Key.Return) {
                    string line = textBox.GetLineText(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart));
                    textBox.SelectedText = "\n".PadRight(1 + line.Length - line.TrimStart('\t').Length, '\t');
                    textBox.SelectionStart = textBox.SelectionStart + textBox.SelectionLength;
                    textBox.SelectionLength = 0;
                    textBox.Focus();
                }
                else if (e.Key == Key.Escape) {
                    if (Intellisense) {
                        intellisense.Visibility = Visibility.Hidden;
                    }
                }
                else if (e.Key == Key.OemPeriod) {
                    string text = textBox.Text.Substring(0, textBox.SelectionStart);
                    searchStart = textBox.SelectionStart;
                    Interpreter.profiling = false;
                    foreach (Parser.CachedRule rule in Parser.CachedRule.cachedRules) {
                        rule.cached.Clear();
                    }
                    Parser parser = new Parser(text, fileName);
                    Map map = null;
                    bool matched = Parser.File.Match(parser, ref map);
                    LiteralExpression gac = new LiteralExpression(Gac.gac, null);
                    LiteralExpression lib = new LiteralExpression(Gac.gac["library"], gac);
                    lib.Statement = new LiteralStatement(gac);
                    KeyStatement.intellisense = true;
                    map[CodeKeys.Function].GetExpression(lib).Statement = new LiteralStatement(lib);
                    map[CodeKeys.Function].Compile(lib);
                    Source key = new Source(
                        parser.State.Line,
                        parser.State.Column,
                        parser.FileName);
                    intellisense.Items.Clear();
                    if (Meta.Expression.sources.ContainsKey(key)) {
                        List<Meta.Expression> list = Meta.Expression.sources[key];
                        for (int i = 0; i < list.Count; i++) {
                            if (list[i] is Search || list[i] is Select) {
                                PositionIntellisense();
                                intellisense.Items.Clear();
                                Structure s = list[i].EvaluateStructure();
                                List<string> keys = new List<string>();
                                if (s != null) {
                                    foreach (Map m in ((LiteralStructure)s).Literal.Keys) {
                                        keys.Add(m.ToString());
                                    }
                                }
                                keys.Sort(delegate(string a, string b) {
                                    return a.CompareTo(b);
                                });
                                if (keys.Count != 0) {
                                    intellisense.Visibility = Visibility.Visible;
                                }
                                foreach (string k in keys) {
                                    intellisense.Items.Add(k);
                                }
                                if (intellisense.Items.Count != 0) {
                                    intellisense.SelectedIndex = 0;
                                }
                            }
                        }
                    }
                    else {
                        MessageBox.Show("no intellisense" + Meta.Expression.sources.Count);
                    }
                    Meta.Expression.sources.Clear();
                }
            };
            DockPanel dockPanel = new DockPanel();

            Menu menu = new Menu();
            DockPanel.SetDock(menu, Dock.Top);
            MenuItem file = new MenuItem();
            MenuItem save = new MenuItem();
            MenuItem run = new MenuItem();
            MenuItem open = new MenuItem();
            file.Header = "File";
            open.Header = "Open";
            save.Header = "Save";
            run.Header = "Run";
            open.Click += delegate {
                OpenFileDialog dialog = new OpenFileDialog();
                if (dialog.ShowDialog() == true) {
                    Open(dialog.FileName);
                }
            };
            run.Click += delegate {
                Save();
                Process.Start(System.IO.Path.Combine(@"D:\Meta\", @"bin\Debug\Meta.exe"), fileName);
            };
            save.Click += delegate {
                Save();
            };
            DockPanel.SetDock(status, Dock.Bottom);
            dockPanel.Children.Add(status);

            file.Items.Add(open);
            file.Items.Add(save);
            file.Items.Add(run);
            menu.Items.Add(file);
            dockPanel.Children.Add(menu);

            DockPanel.SetDock(textBox,Dock.Bottom);
            textBox.TextChanged += delegate {
                if (Intellisense) {
                    if (textBox.SelectionStart <= searchStart) {
                        intellisense.Visibility = Visibility.Hidden;
                    }
                    else {
                        int index = textBox.Text.Substring(0, textBox.SelectionStart).LastIndexOf('.');
                        if (index != -1) {
                            string text = textBox.Text.Substring(index + 1, textBox.SelectionStart - index - 1);
                            foreach (string item in intellisense.Items) {
                                if (item.StartsWith(text, StringComparison.OrdinalIgnoreCase)) {
                                    intellisense.SelectedItem = item;
                                    intellisense.ScrollIntoView(intellisense.SelectedItem);
                                    break;
                                }
                            }
                        }
                    }
                }
            };
            textBox.SelectionChanged += delegate {
                status.Content = "Ln " +
                    (textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart) + 1);
            };
            Canvas canvas = new Canvas();
            canvas.Children.Add(textBox);
            canvas.Background = Brushes.Yellow;
            DockPanel.SetDock(canvas, Dock.Top);
            scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
            scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            scrollViewer.Content = canvas;
            dockPanel.Children.Add(scrollViewer);
            const int width = 0;
            const int height = 0;

            Canvas.SetLeft(textBox, width/2);
            Canvas.SetTop(textBox, height/2);
            textBox.SizeChanged += delegate {
                canvas.Width = textBox.ActualWidth + width;
                canvas.Height = textBox.ActualHeight + height;
            };
            intellisense.SelectionChanged += delegate(object sender, SelectionChangedEventArgs e) {
                if (intellisense.SelectedItem != null) {
                    intellisense.ScrollIntoView(intellisense.SelectedItem);
                }
            };
            intellisense.Visibility = Visibility.Hidden;
            Canvas.SetZIndex(intellisense, 100);
            canvas.Children.Add(intellisense);
            this.Content = dockPanel;
            this.Loaded += delegate {
                Open(@"D:\meta\game.meta");
                textBox.Focus();
                textBox.SelectionStart = 0;
            };
        }
Beispiel #20
0
        /// <summary>
        /// 式中のメンバアクセス、定数等を解析する。
        /// </summary>
        /// <param name="syntax"></param>
        /// <param name="semanticModel"></param>
        /// <returns></returns>
        Expression ParseExpression(ExpressionSyntax syntax, SemanticModel semanticModel)
        {
            if (syntax == null)
            {
                return(null);
            }

            var mae = syntax as MemberAccessExpressionSyntax;
            var gns = syntax as GenericNameSyntax;

            var le    = syntax as LiteralExpressionSyntax;
            var ie    = syntax as InvocationExpressionSyntax;
            var oce   = syntax as ObjectCreationExpressionSyntax;
            var ce    = syntax as CastExpressionSyntax;
            var thise = syntax as ThisExpressionSyntax;
            var ae    = syntax as AssignmentExpressionSyntax;
            var pe    = syntax as ParenthesizedExpressionSyntax;

            var ine = syntax as IdentifierNameSyntax;

            var eae   = syntax as ElementAccessExpressionSyntax;
            var be    = syntax as BinaryExpressionSyntax;
            var preue = syntax as PrefixUnaryExpressionSyntax;
            var poue  = syntax as PostfixUnaryExpressionSyntax;
            var basee = syntax as BaseExpressionSyntax;

            var ace  = syntax as ArrayCreationExpressionSyntax;
            var sace = syntax as StackAllocArrayCreationExpressionSyntax;

            var iee = syntax as InitializerExpressionSyntax;

            /*
             * var coe = syntax as ConditionalExpressionSyntax;
             * var sle = syntax as SimpleLambdaExpressionSyntax;
             * var ple = syntax as ParenthesizedLambdaExpressionSyntax;
             * var oase = syntax as OmittedArraySizeExpressionSyntax;
             * var iace = syntax as ImplicitArrayCreationExpressionSyntax;
             *
             * var qua = syntax as QualifiedNameSyntax;
             * var predf = syntax as PredefinedTypeSyntax;
             */

            // 自己の型を解析
            TypeInfo?selfTypeInfo = null;

            selfTypeInfo = semanticModel.GetTypeInfo(syntax);
            var selfType = ParseType(syntax, selfTypeInfo, semanticModel);

            if (mae != null)
            {
                MemberAccessExpression exp = new MemberAccessExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Name = mae.Name.ToString();

                if (mae.Name is GenericNameSyntax)
                {
                    var gns_ = mae.Name as GenericNameSyntax;
                    exp.Types = gns_.TypeArgumentList.Arguments.Select(_ => ParseType(_, semanticModel)).ToArray();
                }

                TypeInfo?parentType = null;
                if (mae.Expression != null)
                {
                    parentType = semanticModel.GetTypeInfo(mae.Expression);
                }

                // 種類を取得
                var symbol         = semanticModel.GetSymbolInfo(mae);
                var methodSymbol   = symbol.Symbol as IMethodSymbol;
                var propertySymbol = symbol.Symbol as IPropertySymbol;

                // 親の種類を探索
                List <ClassDef> classDefPs = new List <ClassDef>();

                EnumDef      enumDefP      = null;
                InterfaceDef interfaceDefP = null;
                StructDef    structDefP    = null;

                // プロパティである
                if (propertySymbol != null)
                {
                    exp.IsProperty = true;
                }

                if (parentType.HasValue && parentType.Value.Type != null)
                {
                    if (parentType.Value.Type.TypeKind == TypeKind.Interface)
                    {
                        var memName    = mae.Name.ToString();
                        var sym        = semanticModel.GetSymbolInfo(mae);
                        var name_      = parentType.Value.Type.Name;
                        var namespace_ = Utils.ToStr(parentType.Value.Type.ContainingNamespace);
                        interfaceDefP = definitions.Interfaces.Where(_ => _.Namespace == namespace_ && _.Name == name_).FirstOrDefault();
                    }
                    else if (parentType.Value.Type.TypeKind == TypeKind.Class)
                    {
                        var memName    = mae.Name.ToString();
                        var sym        = semanticModel.GetSymbolInfo(mae);
                        var name_      = parentType.Value.Type.Name;
                        var namespace_ = Utils.ToStr(parentType.Value.Type.ContainingNamespace);

                        classDefPs = definitions.FindTypeWithBases(namespace_, name_).OfType <ClassDef>().ToList();
                    }
                    else if (parentType.Value.Type.TypeKind == TypeKind.Enum)
                    {
                        var enumName   = selfTypeInfo.Value.Type.Name;
                        var namespace_ = Utils.ToStr(selfTypeInfo.Value.Type.ContainingNamespace);
                        enumDefP = definitions.Enums.Where(_ => _.Namespace == namespace_ && _.Name == enumName).FirstOrDefault();
                    }
                    else if (parentType.Value.Type.TypeKind == TypeKind.Struct)
                    {
                        var memName    = mae.Name.ToString();
                        var sym        = semanticModel.GetSymbolInfo(mae);
                        var name_      = parentType.Value.Type.Name;
                        var namespace_ = Utils.ToStr(parentType.Value.Type.ContainingNamespace);
                        structDefP = definitions.Structs.Where(_ => _.Namespace == namespace_ && _.Name == name_).FirstOrDefault();
                    }
                }

                // 親から子を探索
                if (interfaceDefP != null)
                {
                    if (methodSymbol != null)
                    {
                        var method = interfaceDefP.Methods.Where(_ =>
                        {
                            if (_.Name != methodSymbol.Name)
                            {
                                return(false);
                            }
                            if (_.Parameters.Count() != methodSymbol.Parameters.Count())
                            {
                                return(false);
                            }

                            for (int i = 0; i < _.Parameters.Count(); i++)
                            {
                                if (_.Parameters[i].Name != methodSymbol.Parameters[i].Name)
                                {
                                    return(false);
                                }

                                // TODO 正しい変換
                                //if(_.Parameters[i].Type != methodSymbol.Parameters[i].Type)
                            }

                            return(true);
                        }).FirstOrDefault();

                        if (method != null)
                        {
                            exp.Name   = null;
                            exp.Method = method;
                        }
                    }
                    else if (propertySymbol != null)
                    {
                        var prop = interfaceDefP.Properties.Where(_ =>
                        {
                            if (_.Name != propertySymbol.Name)
                            {
                                return(false);
                            }
                            return(true);
                        }).FirstOrDefault();

                        if (prop != null)
                        {
                            exp.Name     = null;
                            exp.Property = prop;
                        }
                    }
                }
                else if (classDefPs.Count > 0)
                {
                    if (methodSymbol != null)
                    {
                        foreach (var classDefP in classDefPs)
                        {
                            var method = classDefP.Methods.Where(_ =>
                            {
                                if (_.Name != methodSymbol.Name)
                                {
                                    return(false);
                                }
                                if (_.Parameters.Count() != methodSymbol.Parameters.Count())
                                {
                                    return(false);
                                }

                                for (int i = 0; i < _.Parameters.Count(); i++)
                                {
                                    if (_.Parameters[i].Name != methodSymbol.Parameters[i].Name)
                                    {
                                        return(false);
                                    }

                                    // TODO 正しい変換
                                    //if(_.Parameters[i].Type != methodSymbol.Parameters[i].Type)
                                }

                                return(true);
                            }).FirstOrDefault();

                            if (method != null)
                            {
                                exp.Name   = null;
                                exp.Class  = classDefP;
                                exp.Method = method;

                                // staticの場合走査停止
                                if (method.IsStatic)
                                {
                                    return(exp);
                                }
                                break;
                            }
                        }
                    }
                    else if (propertySymbol != null)
                    {
                        foreach (var classDefP in classDefPs)
                        {
                            var prop = classDefP.Properties.Where(_ =>
                            {
                                if (_.Name != propertySymbol.Name)
                                {
                                    return(false);
                                }
                                return(true);
                            }).FirstOrDefault();

                            if (prop != null)
                            {
                                exp.Name     = null;
                                exp.Class    = classDefP;
                                exp.Property = prop;
                                break;
                            }
                        }
                    }
                }
                else if (structDefP != null)
                {
                    if (propertySymbol != null)
                    {
                        var prop = structDefP.Properties.Where(_ =>
                        {
                            if (_.Name != propertySymbol.Name)
                            {
                                return(false);
                            }
                            return(true);
                        }).FirstOrDefault();

                        if (prop != null)
                        {
                            exp.Name     = null;
                            exp.Struct   = structDefP;
                            exp.Property = prop;
                        }
                    }
                }
                else if (enumDefP != null)
                {
                    var name = mae.Name.ToString();
                    exp.EnumMember = enumDefP.Members.Where(_ => _.Name == name).FirstOrDefault();
                    if (exp.EnumMember != null)
                    {
                        exp.Enum = enumDefP;
                        exp.Name = null;
                    }
                }
                else
                {
                    // 代替処理
                    if (propertySymbol != null)
                    {
                        exp.Property      = new PropertyDef();
                        exp.Property.Name = exp.Name;
                    }
                }

                if (exp.EnumMember != null)
                {
                    // enumのメンバーだった場合、親は必ずenumなのでこれ以上走査しない
                }
                else if (mae.Expression != null)
                {
                    exp.Expression = ParseExpression(mae.Expression, semanticModel);
                }

                return(exp);
            }
            else if (gns != null)
            {
                var symbol         = semanticModel.GetSymbolInfo(gns);
                var methodSymbol   = symbol.Symbol as IMethodSymbol;
                var fieldSymbol    = symbol.Symbol as IFieldSymbol;
                var propertySymbol = symbol.Symbol as IPropertySymbol;

                var exp = new GenericNameExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;


                exp.Name = gns.Identifier.ValueText;

                if (methodSymbol != null)
                {
                    exp.IsMethod = true;
                }

                if (propertySymbol != null)
                {
                    exp.IsProperty = true;
                }

                exp.Types = gns.TypeArgumentList.Arguments.Select(_ => ParseType(_, semanticModel)).ToArray();
                return(exp);
            }
            else if (le != null)
            {
                var text = le.GetText().ToString();
                var exp  = new LiteralExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;


                exp.Text = text;

                return(exp);
            }
            else if (ie != null)
            {
                var exp = new InvocationExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;


                exp.Method = ParseExpression(ie.Expression, semanticModel);
                exp.Args   = ie.ArgumentList.Arguments.Select(_ => ParseExpression(_.Expression, semanticModel)).ToArray();

                return(exp);
            }
            else if (oce != null)
            {
                var exp = new ObjectCreationExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Type = ParseType(oce.Type, semanticModel);

                if (oce.ArgumentList != null)
                {
                    exp.Args = oce.ArgumentList.Arguments.Select(_ => ParseExpression(_.Expression, semanticModel)).ToArray();
                }
                else
                {
                    exp.Args = new Expression[0];
                }

                return(exp);
            }
            else if (ce != null)
            {
                var exp = new CastExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Type       = ParseType(ce.Type, semanticModel);
                exp.Expression = ParseExpression(ce.Expression, semanticModel);
                return(exp);
            }
            else if (thise != null)
            {
                var exp = new ThisExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                return(exp);
            }
            else if (ae != null)
            {
                var exp = new AssignmentExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                if (ae.Kind() == SyntaxKind.AddAssignmentExpression)
                {
                    exp.Type = AssignmentExpression.OperatorType.Add;
                }
                if (ae.Kind() == SyntaxKind.SubtractAssignmentExpression)
                {
                    exp.Type = AssignmentExpression.OperatorType.Substract;
                }
                if (ae.Kind() == SyntaxKind.SimpleAssignmentExpression)
                {
                    exp.Type = AssignmentExpression.OperatorType.Simple;
                }
                if (ae.Kind() == SyntaxKind.DivideAssignmentExpression)
                {
                    exp.Type = AssignmentExpression.OperatorType.Divide;
                }
                if (ae.Kind() == SyntaxKind.ModuloAssignmentExpression)
                {
                    exp.Type = AssignmentExpression.OperatorType.Modulo;
                }

                exp.Temp       = ae.Kind();
                exp.Target     = ParseExpression(ae.Left, semanticModel);
                exp.Expression = ParseExpression(ae.Right, semanticModel);

                return(exp);
            }
            else if (pe != null)
            {
                // ()の構文
                return(ParseExpression(pe.Expression, semanticModel));
            }
            else if (ine != null)
            {
                var symbol         = semanticModel.GetSymbolInfo(ine);
                var methodSymbol   = symbol.Symbol as IMethodSymbol;
                var fieldSymbol    = symbol.Symbol as IFieldSymbol;
                var propertySymbol = symbol.Symbol as IPropertySymbol;

                var exp = new IdentifierNameExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Name = ine.Identifier.Text;

                if (selfTypeInfo?.Type != null)
                {
                    exp.Type = ParseType(selfTypeInfo.Value.Type);
                }

                if (methodSymbol != null)
                {
                    exp.IsMethod = true;
                }

                if (propertySymbol != null)
                {
                    exp.IsProperty = true;
                }

                return(exp);
            }
            else if (eae != null)
            {
                if (eae.ArgumentList.Arguments.Count() != 1)
                {
                    throw new ParseException("多次元配列は使用禁止です。");
                }

                var value_ = eae.Expression;

                var arg = eae.ArgumentList.Arguments[0].Expression;

                var exp = new ElementAccessExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Value = ParseExpression(value_, semanticModel);
                exp.Arg   = ParseExpression(arg, semanticModel);

                return(exp);
            }
            else if (be != null)
            {
                var exp = new BinaryExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Left  = ParseExpression(be.Left, semanticModel);
                exp.Right = ParseExpression(be.Right, semanticModel);

                if (be.Kind() == SyntaxKind.AddExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Add;
                }
                if (be.Kind() == SyntaxKind.SubtractExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Subtract;
                }
                if (be.Kind() == SyntaxKind.IsExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Is;
                }
                if (be.Kind() == SyntaxKind.AsExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.As;
                }
                if (be.Kind() == SyntaxKind.EqualsExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Equals;
                }
                if (be.Kind() == SyntaxKind.NotEqualsExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.NotEquals;
                }

                if (be.Kind() == SyntaxKind.LogicalAndExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.LogicalAnd;
                }
                if (be.Kind() == SyntaxKind.LogicalOrExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.LogicalOr;
                }

                if (be.Kind() == SyntaxKind.GreaterThanExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.GreaterThan;
                }
                if (be.Kind() == SyntaxKind.GreaterThanOrEqualExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.GreaterThanOrEqual;
                }

                if (be.Kind() == SyntaxKind.LessThanExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.LessThan;
                }
                if (be.Kind() == SyntaxKind.LessThanOrEqualExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.LessThanOrEqual;
                }

                if (be.Kind() == SyntaxKind.MultiplyExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Multiply;
                }
                if (be.Kind() == SyntaxKind.DivideExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Divide;
                }

                if (be.Kind() == SyntaxKind.ModuloExpression)
                {
                    exp.Operator = BinaryExpression.OperatorType.Modulo;
                }

                if (exp.Operator == BinaryExpression.OperatorType.None)
                {
                    var span_ = syntax.SyntaxTree.GetLineSpan(syntax.Span);
                    Console.WriteLine(string.Format("{0} : {1} には未対応です。", span_, be.Kind()));
                }

                return(exp);
            }
            else if (preue != null)
            {
                var exp = new PrefixUnaryExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Expression = ParseExpression(preue.Operand, semanticModel);

                switch (preue.Kind())
                {
                case SyntaxKind.LogicalNotExpression:
                    exp.Type = PrefixUnaryExpression.OperatorType.LogicalNot;
                    break;

                case SyntaxKind.UnaryPlusExpression:
                    exp.Type = PrefixUnaryExpression.OperatorType.UnaryPlus;
                    break;

                case SyntaxKind.UnaryMinusExpression:
                    exp.Type = PrefixUnaryExpression.OperatorType.UnaryMinus;
                    break;

                case SyntaxKind.PreIncrementExpression:
                    exp.Type = PrefixUnaryExpression.OperatorType.PreIncrement;
                    break;

                default:
                    throw new Exception();
                    break;
                }

                return(exp);
            }
            else if (poue != null)
            {
                var exp = new PostfixUnaryExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Operand = ParseExpression(poue.Operand, semanticModel);

                if (poue.Kind() == SyntaxKind.PostIncrementExpression)
                {
                    exp.Type = PostfixUnaryExpression.OperatorType.PostIncrement;
                }
                if (poue.Kind() == SyntaxKind.PostDecrementExpression)
                {
                    exp.Type = PostfixUnaryExpression.OperatorType.PostDecrement;
                }

                return(exp);
            }
            else if (basee != null)
            {
                var exp = new BaseExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                return(exp);
            }
            else if (iee != null)
            {
                var exp = new InitializerExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                var expressions = iee.Expressions.Select(_ => _).ToArray();
                exp.Expressions = expressions.Select(_ => ParseExpression(_, semanticModel)).ToArray();

                return(exp);
            }
            else if (ace != null || sace != null)
            {
                // stackallocも含め、配列の確保として扱う。

                ArrayTypeSyntax ats = null;
                if (ace != null)
                {
                    ats = ace.Type;
                }
                if (sace != null)
                {
                    ats = sace.Type as ArrayTypeSyntax;
                }

                var exp = new ObjectArrayCreationExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;

                exp.Type = ParseType(ats.ElementType, semanticModel);
                exp.Args = ats.RankSpecifiers.Select(_ => ParseExpression(_.Sizes.FirstOrDefault(), semanticModel)).ToArray();

                return(exp);
            }
            else if (syntax is PredefinedTypeSyntax)
            {
                var s   = syntax as PredefinedTypeSyntax;
                var exp = new TypeExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;
                return(exp);
            }
            else if (syntax is QualifiedNameSyntax)
            {
                var s = syntax as QualifiedNameSyntax;

                var exp = new TypeExpression();
                exp.SelfType = selfType;
                exp.Internal = syntax;
                return(exp);
            }

            var span = syntax.SyntaxTree.GetLineSpan(syntax.Span);

            Console.WriteLine(string.Format("{0} : {1} には未対応です。", span, syntax.GetType()));
            return(null);
        }
Beispiel #21
0
 public static string CoerceString(LiteralExpression literal)
 {
     if (literal.LiteralType == LiteralType.String)
         return (string)literal.Value;
     else
         return literal.Value.ToString();
 }
Beispiel #22
0
 public virtual void VisitLiteralExpression(LiteralExpression node)
 {
 }
        private Expression GetNextExpression(
            ExpressionPrecedence previousPrecedence, bool unsafeCode, bool allowVariableDeclaration, bool typeExpression)
        {
            Param.Ignore(previousPrecedence);
            Param.Ignore(unsafeCode);
            Param.Ignore(allowVariableDeclaration);
            Param.Ignore(typeExpression);

            // Saves the next expression.
            Expression expression = null;

            // Get the next symbol.
            Symbol symbol = this.GetNextSymbol();

            if (symbol != null)
            {
                switch (symbol.SymbolType)
                {
                    case SymbolType.Other:
                        if (this.IsLambdaExpression())
                        {
                            expression = this.GetLambdaExpression(unsafeCode);
                        }
                        else if (this.IsQueryExpression(unsafeCode))
                        {
                            expression = this.GetQueryExpression(unsafeCode);
                        }

                        // If the expression is still null now, this is just a regular 'other' expression.
                        if (expression == null)
                        {
                            expression = this.GetOtherExpression(allowVariableDeclaration, unsafeCode);
                        }

                        break;

                    case SymbolType.Checked:
                        expression = this.GetCheckedExpression(unsafeCode);
                        break;

                    case SymbolType.Unchecked:
                        expression = this.GetUncheckedExpression(unsafeCode);
                        break;

                    case SymbolType.New:
                        expression = this.GetNewAllocationExpression(unsafeCode);
                        break;

                    case SymbolType.Stackalloc:
                        expression = this.GetStackallocExpression(unsafeCode);
                        break;

                    case SymbolType.Sizeof:
                        expression = this.GetSizeofExpression(unsafeCode);
                        break;

                    case SymbolType.Typeof:
                        expression = this.GetTypeofExpression(unsafeCode);
                        break;

                    case SymbolType.Default:
                        expression = this.GetDefaultValueExpression(unsafeCode);
                        break;

                    case SymbolType.Delegate:
                        expression = this.GetAnonymousMethodExpression(unsafeCode);
                        break;

                    case SymbolType.Increment:
                        if (this.IsUnaryExpression())
                        {
                            expression = this.GetUnaryIncrementExpression(unsafeCode);
                        }

                        break;

                    case SymbolType.Decrement:
                        if (this.IsUnaryExpression())
                        {
                            expression = this.GetUnaryDecrementExpression(unsafeCode);
                        }

                        break;

                    case SymbolType.Plus:
                    case SymbolType.Minus:
                        if (this.IsUnaryExpression())
                        {
                            expression = this.GetUnaryExpression(unsafeCode);
                        }

                        break;

                    case SymbolType.Not:
                    case SymbolType.Tilde:
                        expression = this.GetUnaryExpression(unsafeCode);
                        break;

                    case SymbolType.OpenParenthesis:
                        if (this.IsLambdaExpression())
                        {
                            expression = this.GetLambdaExpression(unsafeCode);
                        }
                        else
                        {
                            expression = this.GetOpenParenthesisExpression(unsafeCode);
                        }

                        break;
                            
                    case SymbolType.Number:
                        Node<CsToken> tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Number, SymbolType.Number));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.String:
                        tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.String, SymbolType.String));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.True:
                        tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.True, SymbolType.True));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.False:
                        tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.False, SymbolType.False));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.Null:
                        tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Null, SymbolType.Null));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.This:
                        tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.This, SymbolType.This));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.Base:
                        tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Base, SymbolType.Base));
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        break;

                    case SymbolType.Multiplication:
                        if (!unsafeCode)
                        {
                            goto default;
                        }

                        expression = this.GetUnsafeAccessExpression(unsafeCode);
                        break;

                    case SymbolType.LogicalAnd:
                        if (!unsafeCode)
                        {
                            goto default;
                        }

                        expression = this.GetUnsafeAccessExpression(unsafeCode);
                        break;

                    default:
                        throw new SyntaxException(this.document.SourceCode, symbol.LineNumber);
                }
            }

            // Gather up all extensions to this expression.
            while (expression != null)
            {
                // Check if there is an extension to this expression.
                Expression extension = this.GetExpressionExtension(expression, previousPrecedence, unsafeCode, typeExpression);
                if (extension != null)
                {
                    // The larger expression is what we want to return here.
                    expression = extension;
                }
                else
                {
                    // There are no more extensions.
                    break;
                }
            }

            // Return the expression.
            return expression;
        }
 public Expression visit(LiteralExpression e)
 {
     return(e);
 }
		protected virtual void VisitLiteral(LiteralExpression literal)
		{
		}
Beispiel #26
0
        private PatternExpression ParseExpression(bool readBinOp = false)
        {
            PatternExpression ret;
            PatternToken      token = ReadToken();

            switch (token.Type)
            {
            case TokenType.Literal:
                ret = new LiteralExpression(token.Value);
                break;

            case TokenType.LParens:
            {
                ret = ParseExpression(true);
                PatternToken parens = ReadToken();
                if (parens.Type != TokenType.RParens)
                {
                    throw MismatchParens(token.Position.Value);
                }
            }
            break;

            case TokenType.Identifier:
                if (IsOperator(token))
                {
                    // unary operator
                    PatternOperator op = ops[token.Value]();
                    if (!op.IsUnary)
                    {
                        throw UnexpectedToken(token);
                    }
                    op.OperandA = ParseExpression();
                    ret         = op;
                }
                else if (IsFunction(token))
                {
                    // function
                    PatternFunction fn = fns[token.Value]();

                    PatternToken parens = ReadToken();
                    if (parens.Type != TokenType.LParens)
                    {
                        throw UnexpectedToken(parens, '(');
                    }

                    fn.Arguments = new List <PatternExpression>(fn.ArgumentCount);
                    for (int i = 0; i < fn.ArgumentCount; i++)
                    {
                        if (PeekToken() == null)
                        {
                            throw UnexpectedEnd();
                        }
                        if (PeekToken().Value.Type == TokenType.RParens)
                        {
                            throw BadArgCount(token, fn.ArgumentCount);
                        }
                        if (i != 0)
                        {
                            PatternToken comma = ReadToken();
                            if (comma.Type != TokenType.Comma)
                            {
                                throw UnexpectedToken(comma, ',');
                            }
                        }
                        fn.Arguments.Add(ParseExpression());
                    }

                    parens = ReadToken();
                    if (parens.Type == TokenType.Comma)
                    {
                        throw BadArgCount(token, fn.ArgumentCount);
                    }
                    if (parens.Type != TokenType.RParens)
                    {
                        throw MismatchParens(parens.Position.Value);
                    }

                    ret = fn;
                }
                else
                {
                    bool boolValue;
                    if (bool.TryParse(token.Value, out boolValue))
                    {
                        ret = new LiteralExpression(boolValue);
                    }
                    else
                    {
                        throw UnknownToken(token);
                    }
                }

                break;

            default:
                throw UnexpectedToken(token);
            }

            if (!readBinOp)
            {
                return(ret);
            }

            // binary operator
            PatternToken?peek = PeekToken();

            while (peek != null)
            {
                if (peek.Value.Type != TokenType.Identifier)
                {
                    break;
                }
                if (!IsOperator(peek.Value))
                {
                    break;
                }

                PatternToken    binOpToken = ReadToken();
                PatternOperator binOp      = ops[binOpToken.Value]();
                if (binOp.IsUnary)
                {
                    throw UnexpectedToken(binOpToken);
                }
                binOp.OperandA = ret;
                binOp.OperandB = ParseExpression();
                ret            = binOp;

                peek = PeekToken();
            }

            return(ret);
        }
 public void VisitLiteralExpression(LiteralExpression literal)
 {
     //no op
 }
Beispiel #28
0
 public override void Visit(LiteralExpression node)
 {
     base.Visit(node);
     _result = Expression.Constant(node.Value, typeof(object));
 }
Beispiel #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LayoutKeyValue"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 public LayoutKeyValue(Identifier name, object value)
 {
     Name  = name;
     Value = new LiteralExpression(value);
 }
 public virtual void VisitLiteralExpression(LiteralExpression literalExpression)
 {
     VisitChildren (literalExpression);
 }
Beispiel #31
0
 private static LiteralExpression Clone(LiteralExpression expression)
 {
     return(expression);
 }
Beispiel #32
0
 /// <summary>
 /// Initializes a new instance of the MemberAccessExpression class.
 /// </summary>
 /// <param name="proxy">Proxy object for the expression.</param>
 /// <param name="leftHandSide">The left side of the operation.</param>
 /// <param name="rightHandSide">The member being accessed.</param>
 internal MemberAccessExpression(CodeUnitProxy proxy, Expression leftHandSide, LiteralExpression rightHandSide)
     : base(proxy, ExpressionType.MemberAccess, leftHandSide, rightHandSide)
 {
     Param.Ignore(proxy, leftHandSide, rightHandSide);
 }
Beispiel #33
0
        private static Expression ParseExpression(Match match)
        {
            string     expressionText = match.Value.Trim();
            Expression expression;

            lock (_expressions)
            {
                if (_expressions.TryGetValue(expressionText, out expression))
                {
                    return(expression);
                }
                // temporarily add a dummy expression to prevent other threads from parsing the same expression again
                Log.Debug("Cacheing expression: {0}", expressionText);
                _expressions.Add(expressionText, new LiteralExpression(expressionText));
            }

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

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

                    expression = new FunctionExpression(_registeredFunctions[functionName], parameters);
                }
            }
            lock (_expressions)
            {
                // now replace with the real expression
                _expressions[expressionText] = expression;
            }
            return(expression);
        }
 private void FixBooleanLiteral(LiteralExpression literal)
 {
     literal.Value = Convert.ToBoolean(literal.Value);
 }
 /// <summary>
 /// Initializes a new instance of the PointerAccessExpression class.
 /// </summary>
 /// <param name="proxy">Proxy object for the expression.</param>
 /// <param name="leftHandSide">The left side of the operation.</param>
 /// <param name="rightHandSide">The member being accessed.</param>
 internal PointerAccessExpression(CodeUnitProxy proxy, Expression leftHandSide, LiteralExpression rightHandSide)
     : base(proxy, ExpressionType.PointerAccess, leftHandSide, rightHandSide)
 {
     Param.Ignore(proxy, leftHandSide, rightHandSide);
 }
 private void FixCharLiteral(LiteralExpression literal)
 {
     literal.Value = Convert.ToChar(literal.Value);
 }
    private static Expression ParseExpression(Match match)
    {
      string expressionText = match.Value.Trim();
      Expression expression;
      lock (_expressions)
      {
        if (_expressions.TryGetValue(expressionText, out expression))
        {
          return expression;
        }
        // temporarily add a dummy expression to prevent other threads from parsing the same expression again
        Log.Debug("Cacheing expression: {0}", expressionText);
        _expressions.Add(expressionText, new LiteralExpression(expressionText));
      }

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

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

          expression = new FunctionExpression(_registeredFunctions[functionName], parameters);
        }
      }
      lock (_expressions)
      {
        // now replace with the real expression
        _expressions[expressionText] = expression;
      }
      return expression;
    }
Beispiel #38
0
 public Unit VisitLiteralExpression(LiteralExpression expression)
 {
     return(Unit.Value);
 }
		protected override void VisitLiteral(LiteralExpression literal)
		{
			base.VisitLiteral(literal);
			AppendCodeBlock(String.Format(@"{0}.push({1});", 
				CodeBufferVariableName, _serializer.Serialize(literal.Literal)));
		}
Beispiel #40
0
 public virtual T visitLiteral(LiteralExpression literal, A arg) => visit(literal, arg);
Beispiel #41
0
        public static bool TryCoerceInt(LiteralExpression expression, out int result)
        {
            switch (expression.LiteralType)
            {
                case LiteralType.Int:
                    result = (int)expression.Value;
                    return true;

                case LiteralType.Long:
                    result = (int)(long)expression.Value;
                    return true;

                default:
                    result = 0;
                    return false;
            }
        }
Beispiel #42
0
 /// <summary>
 /// Creates a call to the REGEX function
 /// </summary>
 public static BooleanExpression Regex(this ExpressionBuilder eb, LiteralExpression text, VariableExpression pattern, string flags)
 {
     return(Regex(text.Expression, pattern.Expression, flags.ToConstantTerm()));
 }
Beispiel #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LayoutKeyValue"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 public LayoutKeyValue(Identifier name, object value)
 {
     Name = name;
     Value = new LiteralExpression(value);
 }
Beispiel #44
0
 /// <summary>
 /// Creates a call to the LANGMATCHES function
 /// </summary>
 public static BooleanExpression LangMatches(this ExpressionBuilder eb, LiteralExpression languageTag, string languageRange)
 {
     return(LangMatches(languageTag.Expression, languageRange.ToConstantTerm()));
 }
 public string GetExpression(LiteralExpression expression, ref List<OleDbParameter> parameters)
 {
     string name = "p" + parameters.Count.ToString();
     OleDbParameter parameter = new OleDbParameter(name, expression.Value);
     parameters.Add(parameter);
     return " ? ";
 }
Beispiel #46
0
 /// <summary>
 /// Creates a call to the LANGMATCHES function
 /// </summary>
 public static BooleanExpression LangMatches(this ExpressionBuilder eb, LiteralExpression languageTag, VariableExpression languageRange)
 {
     return(LangMatches(languageTag.Expression, languageRange.Expression));
 }
Beispiel #47
0
        /// <summary>
        /// Initializes a new instance of the CatchStatement class.
        /// </summary>
        /// <param name="tokens">
        /// The list of tokens that form the statement.
        /// </param>
        /// <param name="tryStatement">
        /// The try-statement that this catch-statement is attached to.
        /// </param>
        /// <param name="classExpression">
        /// The inner expression.
        /// </param>
        /// <param name="embeddedStatement">
        /// The statement embedded within the catch-statement.
        /// </param>
        internal CatchStatement(CsTokenList tokens, TryStatement tryStatement, Expression classExpression, BlockStatement embeddedStatement)
            : base(StatementType.Catch, tokens)
        {
            Param.AssertNotNull(tokens, "tokens");
            Param.AssertNotNull(tryStatement, "tryStatement");
            Param.Ignore(classExpression);
            Param.AssertNotNull(embeddedStatement, "embeddedStatement");

            this.tryStatement = tryStatement;
            this.catchExpression = classExpression;
            this.embeddedStatement = embeddedStatement;

            if (classExpression != null)
            {
                this.AddExpression(classExpression);

                if (classExpression != null)
                {
                    if (classExpression.ExpressionType == ExpressionType.Literal)
                    {
                        this.classType = ((LiteralExpression)classExpression).Token as TypeToken;
                    }
                    else if (classExpression.ExpressionType == ExpressionType.VariableDeclaration)
                    {
                        VariableDeclarationExpression variableDeclaration = (VariableDeclarationExpression)classExpression;

                        this.classType = variableDeclaration.Type;

                        foreach (VariableDeclaratorExpression declarator in variableDeclaration.Declarators)
                        {
                            this.identifier = declarator.Identifier;
                            break;
                        }
                    }
                }
            }

            this.AddStatement(embeddedStatement);
        }
Beispiel #48
0
 /// <summary>
 /// Creates a call to the REGEX function
 /// </summary>
 public static BooleanExpression Regex(this ExpressionBuilder eb, LiteralExpression text, string pattern)
 {
     return(Regex(text.Expression, pattern.ToSimpleLiteral(), null));
 }
 /// <summary>
 /// Initializes a new instance of the QualifiedAliasExpression class.
 /// </summary>
 /// <param name="proxy">Proxy object for the expression.</param>
 /// <param name="leftHandSide">The left side of the operation.</param>
 /// <param name="rightHandSide">The member being accessed.</param>
 internal QualifiedAliasExpression(CodeUnitProxy proxy, Expression leftHandSide, LiteralExpression rightHandSide)
     : base(proxy, ExpressionType.QualifiedAlias, leftHandSide, rightHandSide)
 {
     Param.Ignore(proxy, leftHandSide, rightHandSide);
 }
Beispiel #50
0
 /// <summary>
 /// Creates a call to the REGEX function
 /// </summary>
 public static BooleanExpression Regex(this ExpressionBuilder eb, LiteralExpression text, VariableExpression pattern)
 {
     return(Regex(text.Expression, pattern.Expression, null));
 }
 /// <summary>
 /// Initializes a new instance of the QualifiedAliasExpression class.
 /// </summary>
 /// <param name="proxy">Proxy object for the expression.</param>
 /// <param name="leftHandSide">The left side of the operation.</param>
 /// <param name="rightHandSide">The member being accessed.</param>
 internal QualifiedAliasExpression(CodeUnitProxy proxy, Expression leftHandSide, LiteralExpression rightHandSide)
     : base(proxy, ExpressionType.QualifiedAlias, leftHandSide, rightHandSide)
 {
     Param.Ignore(proxy, leftHandSide, rightHandSide);
 }
 public virtual ICodeNode VisitLiteralExpression(LiteralExpression node)
 {
     return(node);
 }
Beispiel #53
0
 /// <summary>
 /// Creates a call to the REGEX function
 /// </summary>
 public static BooleanExpression Regex(this ExpressionBuilder eb, LiteralExpression text, string pattern, string flags)
 {
     return(Regex(text.Expression, pattern.ToSimpleLiteral(), flags.ToConstantTerm()));
 }
Beispiel #54
0
        private static MethodDeclaration GenerateBuildUrlMethod(ClassDeclaration clientClass, Method method, TypeReference requestType)
        {
            var m = clientClass.AddMember(new MethodDeclaration(method.MethodGroup.Name + '_' + GetMethodName(method) + "_BuildUrl"));

            m.Modifiers  = Modifiers.Private | Modifiers.Static;
            m.ReturnType = typeof(string);

            // Method body
            m.Statements = new StatementCollection();

            var urlVariable = new VariableDeclarationStatement(typeof(string), "url");

            m.Statements.Add(urlVariable);

            // 1. Create url from parameters
            var parameters = method.Parameters.Where(p => GetParameterLocation(method, p) == ParameterLocation.Url).ToList();

            if (parameters.Any())
            {
                var requestArgument = m.AddArgument("request", requestType);

                // [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "<Pending>")]
                m.CustomAttributes.Add(new CustomAttribute(typeof(SuppressMessageAttribute))
                {
                    Arguments =
                    {
                        new CustomAttributeArgument(new LiteralExpression("Reliability")),
                        new CustomAttributeArgument(new LiteralExpression("CA2000:Dispose objects before losing scope")),
                        new CustomAttributeArgument("Justification",                                                     new LiteralExpression("The rule doesn't understand ref struct")),
                    },
                });

                var segments   = GetSegments(method.UrlTemplate);
                var urlBuilder = new VariableDeclarationStatement(
                    WellKnownTypes.UrlBuilderTypeReference, "urlBuilder",
                    new NewObjectExpression(WellKnownTypes.UrlBuilderTypeReference));
                var urlUsingStatement = new UsingStatement()
                {
                    Statement = urlBuilder,
                    Body      = new StatementCollection(),
                };
                var usingStatements = urlUsingStatement.Body;
                m.Statements.Add(urlUsingStatement);

                foreach (var segment in segments)
                {
                    if (segment[0] == ':')
                    {
                        var param = parameters.SingleOrDefault(p => p.Name == segment[1..]);
                        if (param == null)
                        {
                            throw new InvalidOperationException($"Parameter '{segment}' is not mapped for method '{method.UrlTemplate}'");
                        }

                        AddParameter(param, separator: null, encoded: true);
                        parameters.Remove(param);
                    }
                    else if (segment[0] == '*')
                    {
                        var param = parameters.SingleOrDefault(p => p.Name == segment[1..]);
                        if (param == null)
                        {
                            throw new InvalidOperationException($"Parameter '{segment}' is not mapped for method '{method.UrlTemplate}'");
                        }

                        AddParameter(param, separator: null, encoded: false);
                        parameters.Remove(param);
                    }
                    else if (segment.StartsWith("[.", StringComparison.Ordinal))
                    {
                        var param = parameters.SingleOrDefault(p => p.Name == segment[2..^ 1]);
                        if (param == null)
                        {
                            throw new InvalidOperationException($"Parameter '{segment}' is not mapped for method '{method.UrlTemplate}'");
                        }

                        AddParameter(param, separator: null, encoded: false, prefix: ".");
                        parameters.Remove(param);
                    }
                    else
                    {
                        usingStatements.Add(urlBuilder.CreateInvokeMethodExpression("Append", new LiteralExpression(segment)));
                    }
                }

                if (parameters.Any())
                {
                    var separator = new VariableDeclarationStatement(typeof(char), "separator", new LiteralExpression('?'));
                    usingStatements.Add(separator);

                    foreach (var param in parameters)
                    {
                        AddParameter(param, separator, encoded: true);
                    }
                }

                usingStatements.Add(new AssignStatement(urlVariable, urlBuilder.CreateInvokeMethodExpression("ToString")));

                void AddParameter(MethodParameter param, VariableDeclarationStatement separator, bool encoded, string prefix = null)
                {
                    var appendParameterMethodName = encoded ? "AppendParameter" : "AppendRawParameter";

                    void AddSeparator(StatementCollection statements)
                    {
                        if (separator != null)
                        {
                            statements.Add(urlBuilder.CreateInvokeMethodExpression("Append", separator));
                            statements.Add(new AssignStatement(separator, new LiteralExpression('&')));
                            statements.Add(urlBuilder.CreateInvokeMethodExpression("Append", new LiteralExpression(param.Name + '=')));
                        }
                    }

                    void AppendPrefix(StatementCollection statements)
                    {
                        if (!string.IsNullOrEmpty(prefix))
                        {
                            statements.Add(urlBuilder.CreateInvokeMethodExpression("Append", prefix));
                        }
                    }

                    if (param.Type.IsParameterEntity)
                    {
                        var propertyName      = param.Type.ParameterEntity.FinalType == ModelRef.Object ? "ValueAsString" : "Value";
                        var hasValueCondition = new ConditionStatement
                        {
                            Condition      = CreatePropertyReference().CreateMemberReferenceExpression(nameof(Nullable <int> .HasValue)),
                            TrueStatements = new StatementCollection(),
                        };

                        AddSeparator(hasValueCondition.TrueStatements);
                        AppendPrefix(hasValueCondition.TrueStatements);
                        hasValueCondition.TrueStatements.Add(urlBuilder
                                                             .CreateInvokeMethodExpression(
                                                                 appendParameterMethodName,
                                                                 FormatValue(param.Type, CreatePropertyReference().CreateInvokeMethodExpression("GetValueOrDefault").CreateMemberReferenceExpression(propertyName))));

                        urlUsingStatement.Body.Add(hasValueCondition);
                    }
                    else
                    {
                        var isValueType = param.Type.IsValueType && !param.Type.IsCollection;

                        var hasValueCondition = new ConditionStatement
                        {
                            Condition = isValueType ? CreatePropertyReference().CreateMemberReferenceExpression("HasValue") :
                                        new UnaryExpression(UnaryOperator.Not,
                                                            new MethodInvokeExpression(
                                                                new MemberReferenceExpression(new TypeReference(typeof(object)), "ReferenceEquals"),
                                                                CreatePropertyReference(), LiteralExpression.Null())),
                            TrueStatements = new StatementCollection(),
                        };

                        AddSeparator(hasValueCondition.TrueStatements);
                        AppendPrefix(hasValueCondition.TrueStatements);

                        Expression value        = isValueType ? CreatePropertyReference().CreateInvokeMethodExpression("GetValueOrDefault") : CreatePropertyReference();
                        var        appendMethod = new MethodInvokeExpression(
                            new MemberReferenceExpression(urlBuilder, appendParameterMethodName),
                            FormatValue(param.Type, value));

                        hasValueCondition.TrueStatements.Add(appendMethod);
                        urlUsingStatement.Body.Add(hasValueCondition);
                    }

                    MemberReferenceExpression CreatePropertyReference()
                    {
                        return(requestArgument.CreateMemberReferenceExpression(ToPropertyName(param.Name)));
                    }
                }
            }
            else
            {
                m.Statements.Add(new AssignStatement(urlVariable, new LiteralExpression(method.UrlTemplate)));
            }

            m.Statements.Add(new ReturnStatement(urlVariable));
            return(m);
        }