Exemple #1
0
        public static Expression data(params StringLiteralExpression[] expressions)
        {
            var arrayExpression = new ArrayLiteralExpression();

            for (var i = 0; i < expressions.Length; i++)
            {
                arrayExpression.Items.Add(expressions[i]);
            }

            return(new MethodInvocationExpression(
                       new ReferenceExpression("SetData"),
                       arrayExpression
                       ));
        }
Exemple #2
0
        public static bool IsCompoundAssignment(Expression expression,
                                                out ArrayLiteralExpression assignments)
        {
            assignments = expression as ArrayLiteralExpression;

            if (assignments != null)
            {
                BinaryExpression assignment;
                return(assignments.Items.Count > 1 &&
                       IsAssignment(assignments.Items[1], out assignment));
            }

            return(false);
        }
Exemple #3
0
        public static Expression tasks(params ReferenceExpression[] expressions)
        {
            var arrayExpression = new ArrayLiteralExpression();

            for (var i = 0; i < expressions.Length; i++)
            {
                arrayExpression.Items.Add(new StringLiteralExpression(expressions[i].Name));
            }

            return(new MethodInvocationExpression(
                       new ReferenceExpression("SetBuildTargets"),
                       arrayExpression
                       ));
        }
Exemple #4
0
        public ArrayLiteralExpression CreateArray(IType arrayType, ExpressionCollection items)
        {
            if (!arrayType.IsArray)
            {
                throw new ArgumentException(string.Format("'{0}'  is not an array type!", arrayType), "arrayType");
            }

            var array = new ArrayLiteralExpression();

            array.ExpressionType = arrayType;
            array.Items.AddRange(items);
            TypeSystemServices.MapToConcreteExpressionTypes(array.Items);
            return(array);
        }
Exemple #5
0
        /// <summary>
        /// Array literals inside object literals should mostly be spread on multiple lines, single items can still be on one line.
        /// </summary>
        public override void VisitArrayLiteralExpression(ArrayLiteralExpression node)
        {
            var actualCount = IsInObjectLiteralContext ? 1 : 3;

            AppendList(
                node.Elements,
                separatorToken: ScriptWriter.SeparateArrayToken,
                startBlockToken: ScriptWriter.StartArrayToken,
                endBlockToken: ScriptWriter.EndArrayToken,
                placeSeparatorOnLastElement: true,
                minimumCountBeforeNewLines: actualCount,
                printTrailingComments: true,
                visitItem: n => HandleArrayLiteralElement(n));
        }
        /// <summary>
        /// Perform the actual expansion of the macro
        /// </summary>
        /// <param name="macro">The macro.</param>
        /// <returns></returns>
        protected override Statement DoExpand(MacroStatement macro)
        {
            Block          body        = (Block)macro.GetAncestor(NodeType.Block);
            MacroStatement macroParent = (MacroStatement)macro.GetAncestor(NodeType.MacroStatement);

            if (macro.Body.Statements.Count < 1 && parent.Name == "join")
            {
                Errors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo, "Join " + name + " section must contain at least a single expression statement"));
                return(null);
            }

            if (macro.Arguments.Count == 0 && parent.Name != "join")
            {
                Errors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo, "Join " + name + " section must contain at least one key column"));
                return(null);
            }

            if (macro.Arguments.Count > 0)
            {
                ArrayLiteralExpression ale = new ArrayLiteralExpression(macro.LexicalInfo);
                ale.Type = new ArrayTypeReference(CodeBuilder.CreateTypeReference(typeof(string)));
                foreach (Expression argument in macro.Arguments)
                {
                    ReferenceExpression expr = argument as ReferenceExpression;
                    if (expr == null)
                    {
                        Errors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo, "Join " + name + " section arguments must be reference expressions. Example: " + name + " name, surname"));
                        return(null);
                    }
                    ale.Items.Add(new StringLiteralExpression(expr.Name));
                }
                var keyExpr = new BinaryExpression(BinaryOperatorType.Assign, new ReferenceExpression(name + "KeyColumns"), ale);
                macroParent.Arguments.Add(keyExpr);
            }

            foreach (Statement statement in macro.Body.Statements)
            {
                ExpressionStatement exprStmt = statement as ExpressionStatement;
                if (exprStmt == null)
                {
                    Errors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo, "Join " + name + " section can only contain expressions"));
                    return(null);
                }
                Expression expr = exprStmt.Expression;
                parent.Arguments.Add(new MethodInvocationExpression(new ReferenceExpression(name), expr));
            }

            return(null);
        }
Exemple #7
0
 public override void OnArrayLiteralExpression(ArrayLiteralExpression node)
 {
     Write("new ");
     if (node.Type != null)
     {
         Write(node.Type);
     }
     else
     {
         Write("[]");
     }
     Write(" {");
     WriteCommaSeparatedList(node.Items);
     Write("}");
 }
Exemple #8
0
        private ArrayLiteralExpression GetArrayForIndices(SlicingExpression node)
        {
            ArrayLiteralExpression args = new ArrayLiteralExpression();

            foreach (Slice index in node.Indices)
            {
                if (AstUtil.IsComplexSlice(index))
                {
                    throw CompilerErrorFactory.NotImplemented(index, "complex slice for duck");
                }
                args.Items.Add(index.Begin);
            }
            BindExpressionType(args, TypeSystemServices.ObjectArrayType);
            return(args);
        }
Exemple #9
0
        private Method CreateGetColumnsToGroupByMethod(MacroStatement macro, IEnumerable <string> columns)
        {
            Method method = new Method("GetColumnsToGroupBy");

            method.Modifiers = TypeMemberModifiers.Override;
            ArrayLiteralExpression ale = new ArrayLiteralExpression(macro.LexicalInfo);

            ale.Type = new ArrayTypeReference(CodeBuilder.CreateTypeReference(typeof(string)));

            foreach (string column in columns)
            {
                ale.Items.Add(new StringLiteralExpression(column));
            }
            method.Body.Statements.Add(new ReturnStatement(ale));
            return(method);
        }
Exemple #10
0
        void ProcessDuckSlicingPropertySet(BinaryExpression node)
        {
            SlicingExpression slice = (SlicingExpression)node.Left;

            ArrayLiteralExpression args = GetArrayForIndices(slice);

            args.Items.Add(node.Right);

            MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
                node.LexicalInfo,
                RuntimeServices_SetSlice,
                GetSlicingTarget(slice),
                CodeBuilder.CreateStringLiteral(GetSlicingMemberName(slice)),
                args);

            Replace(mie);
        }
        public override void OnUnpackStatement(UnpackStatement node)
        {
            ArrayLiteralExpression ale = node.Expression as ArrayLiteralExpression;

            for (int i = 0; i < node.Declarations.Count; i++)
            {
                Declaration decl = node.Declarations[i];
                if (acceptImplicit && ale != null && ale.Items.Count > i)
                {
                    DeclarationFound(decl.Name, decl.Type, ale.Items[i], decl.LexicalInfo);
                }
                else if (decl.Type != null)
                {
                    DeclarationFound(decl.Name, decl.Type, null, decl.LexicalInfo);
                }
            }
        }
Exemple #12
0
        public static Expression exclude(BlockExpression action)
        {
            var arrayExpression = new ArrayLiteralExpression();

            foreach (Statement statement in action.Body.Statements)
            {
                var stringLiteral =
                    new StringLiteralExpression(
                        ((MethodInvocationExpression)(((ExpressionStatement)(statement)).Expression)).Arguments[0].ToString().Trim(new[] { '\'' }));

                arrayExpression.Items.Add(stringLiteral);
            }

            return(new MethodInvocationExpression(
                       new ReferenceExpression("SetExcludeList"),
                       arrayExpression
                       ));
        }
        override public void LeaveSlicingExpression(SlicingExpression node)
        {
            if (!IsDuckTyped(node.Target))
            {
                return;
            }
            if (AstUtil.IsLhsOfAssignment(node))
            {
                return;
            }

            // todo
            // a[foo]
            // RuntimeServices.GetSlice(a, "", (foo,))
            ArrayLiteralExpression args = new ArrayLiteralExpression();

            foreach (Slice index in node.Indices)
            {
                if (AstUtil.IsComplexSlice(index))
                {
                    throw CompilerErrorFactory.NotImplemented(index, "complex slice for duck");
                }
                args.Items.Add(index.Begin);
            }
            BindExpressionType(args, TypeSystemServices.ObjectArrayType);

            Expression target     = node.Target;
            string     memberName = "";

            if (NodeType.MemberReferenceExpression == target.NodeType)
            {
                MemberReferenceExpression mre = ((MemberReferenceExpression)target);
                target     = mre.Target;
                memberName = mre.Name;
            }

            MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
                RuntimeServices_GetSlice,
                target,
                CodeBuilder.CreateStringLiteral(memberName),
                args);

            Replace(mie);
        }
Exemple #14
0
        public override void OnArrayLiteralExpression(ArrayLiteralExpression node)
        {
            BooResolver resolver   = new BooResolver();
            IReturnType createType = resolver.GetTypeOfExpression(node, null);

            if (createType == null)
            {
                createType = pc.SystemTypes.Object;
            }
            CodeExpression[] initializers = new CodeExpression[node.Items.Count];
            for (int i = 0; i < initializers.Length; i++)
            {
                _expression = null;
                node.Items[i].Accept(this);
                initializers[i] = _expression;
            }
            _expression = new CodeArrayCreateExpression(createType.FullyQualifiedName, initializers);
            _expression.UserData["unknownType"] = node.Type != null;
        }
Exemple #15
0
        public static Expression include(BlockExpression includes)
        {
            var includeList = new ArrayLiteralExpression();

            foreach (var statement in includes.Body.Statements)
            {
                var expression = (MethodInvocationExpression)((ExpressionStatement)statement).Expression;

                var repositoryName = ((ReferenceExpression)expression.Arguments[0]).Name;
                var includePath    = ((StringLiteralExpression)((MethodInvocationExpression)expression.Arguments[1]).Arguments[0]).Value;
                var exportPath     = ((StringLiteralExpression)((MethodInvocationExpression)expression.Arguments[2]).Arguments[0]).Value;;

                var repositoryInclude = new MethodInvocationExpression(new ReferenceExpression("RepositoryElement"),
                                                                       new StringLiteralExpression(repositoryName),
                                                                       new StringLiteralExpression(includePath),
                                                                       new StringLiteralExpression(exportPath));

                includeList.Items.Add(repositoryInclude);
            }

            return(new MethodInvocationExpression(new ReferenceExpression("ParseIncludes"), includeList));
        }
Exemple #16
0
        public override void OnBlockExpression(BlockExpression node)
        {
            var dependencies = new ArrayLiteralExpression();

            foreach (Statement statement in node.Body.Statements)
            {
                var expressionStatement = (ExpressionStatement)statement;
                var expression          = (MethodInvocationExpression)expressionStatement.Expression;

                OnMethodInvocationExpression(dependencies, expression);
            }

            if (dependencies.Items.Count == 0)
            {
                return;
            }

            var referenceExpression = new ReferenceExpression("AddDependencies");
            var replacementMethod   = new MethodInvocationExpression(referenceExpression, dependencies);

            ReplaceCurrentNode(replacementMethod);
        }
Exemple #17
0
        public static Expression export(BlockExpression exportUrls)
        {
            var exportList = new ArrayLiteralExpression();

            foreach (var statement in exportUrls.Body.Statements)
            {
                var expression = (MethodInvocationExpression)((ExpressionStatement)statement).Expression;

                var sourceType = expression.Target.ToString();
                var remoteUrl  = ((StringLiteralExpression)expression.Arguments[0]).Value;

                MethodInvocationExpression export;

                if (expression.Arguments.Count == 1)
                {
                    export = new MethodInvocationExpression(new ReferenceExpression("ExportData"),
                                                            new StringLiteralExpression(remoteUrl),
                                                            new StringLiteralExpression(sourceType));

                    exportList.Items.Add(export);

                    continue;
                }

                var to = ((StringLiteralExpression)((MethodInvocationExpression)expression.Arguments[1]).Arguments[0]).Value;

                export = new MethodInvocationExpression(new ReferenceExpression("ExportData"),
                                                        new StringLiteralExpression(remoteUrl),
                                                        new StringLiteralExpression(sourceType),
                                                        new StringLiteralExpression(to));

                exportList.Items.Add(export);
            }

            return(new MethodInvocationExpression(new ReferenceExpression("ParseExportList"), exportList));
        }
Exemple #18
0
 public override void PostWalk(ArrayLiteralExpression node)
 {
 }
 public override void OnArrayLiteralExpression(ArrayLiteralExpression node)
 {
     base.OnArrayLiteralExpression(node);
     Check(node);
 }
		ISemantic E(ArrayLiteralExpression arr)
		{
			if (eval)
			{
				var elements = new List<ISymbolValue>(arr.Elements.Count);

				//ISSUE: Type-check each item to distinguish not matching items
				foreach (var e in arr.Elements)
					elements.Add(E(e) as ISymbolValue);

				if(elements.Count == 0){
					EvalError(arr, "Array literal must contain at least one element.");
					return null;
				}

				return new ArrayValue(new ArrayType(elements[0].RepresentedType, arr), elements.ToArray());
			}

			if (arr.Elements != null && arr.Elements.Count > 0)
			{
				// Simply resolve the first element's type and take it as the array's value type
				var valueType = AbstractType.Get(E(arr.Elements[0]));

				return new ArrayType(valueType, arr);
			}

			ctxt.LogError(arr, "Array literal must contain at least one element.");
			return null;
		}
 public override void OnArrayLiteralExpression(ArrayLiteralExpression node)
 {
     this._currentStatement.Expression = new CodeArrayCreateExpression(BooCodeDomConverter.GetType(node.Type.ElementType.ToCodeString()), node.Items.Select(this.VisitExpr).ToArray());
 }
Exemple #22
0
 public virtual void Visit(ArrayLiteralExpression node)
 {
     DefaultVisit(node);
 }
Exemple #23
0
 public virtual void Visit(ArrayLiteralExpression node)
 {
     DefaultVisit(node);
 }
Exemple #24
0
        private static Expression ParseExpression(BinaryReader reader, CodeSectionInfo codeSectionInfo, int blockId, bool parseMember = true)
        {
            Expression expression = null;
            byte       b          = reader.ReadByte();

            switch (b)
            {
            case 1:
                expression = new ParamListEnd();
                break;

            case 22:
                expression = null;
                break;

            case 23:
                expression = new NumberLiteral(reader.ReadDouble());
                break;

            case 24:
                expression = new BoolLiteral(reader.ReadInt16() != 0);
                break;

            case 25:
                expression = new DateTimeLiteral(DateTime.FromOADate(reader.ReadDouble()));
                break;

            case 26:
                expression = new StringLiteral(reader.ReadStringWithLengthPrefix());
                break;

            case 27:
                expression = new ConstantExpression(-2, reader.ReadInt32());
                break;

            case 28:
                expression = new ConstantExpression(reader.ReadInt16(), reader.ReadInt16());
                break;

            case 29:
                if (reader.ReadByte() != 56)
                {
                    throw new Exception();
                }
                expression = new VariableExpression(reader.ReadInt32(), codeSectionInfo, blockId);
                break;

            case 30:
                expression = new SubPtrExpression(reader.ReadInt32(), codeSectionInfo);
                break;

            case 33:
                expression = ParseCallExpressionWithoutType(reader, codeSectionInfo, blockId);
                break;

            case 35:
                expression = new EmnuConstantExpression(reader.ReadInt32(), reader.ReadInt32());
                break;

            case 31:
            {
                ArrayLiteralExpression arrayLiteralExpression = new ArrayLiteralExpression();
                Expression             item;
                while (!((item = ParseExpression(reader, codeSectionInfo, blockId, true)) is ArrayLiteralEnd))
                {
                    arrayLiteralExpression.Value.Add(item);
                }
                expression = arrayLiteralExpression;
                break;
            }

            case 32:
                expression = new ArrayLiteralEnd();
                break;

            case 56:
            {
                int num = reader.ReadInt32();
                if (num == 83951614)
                {
                    reader.ReadByte();
                    expression = ParseExpression(reader, codeSectionInfo, blockId, true);
                }
                else
                {
                    expression = new VariableExpression(num, codeSectionInfo, blockId);
                }
                break;
            }

            case 59:
                expression = new NumberLiteral((double)reader.ReadInt32());
                break;

            default:
                throw new Exception(string.Format("Unknown Type: {0}", b.ToString("X2")));

            case 55:
                break;
            }
            //bool flag = false;
            if (parseMember && (expression is VariableExpression || expression is CallExpression))
            {
                while (reader.BaseStream.Position != reader.BaseStream.Length)
                {
                    switch (reader.ReadByte())
                    {
                    case 57:
                        break;

                    case 58:
                        goto IL_027a;

                    default:
                        reader.BaseStream.Position -= 1L;
                        goto IL_02eb;

                    case 55:
                        goto IL_02eb;
                    }
                    int memberId = reader.ReadInt32();
                    int structId = reader.ReadInt32();
                    expression = new AccessMemberExpression(expression, structId, memberId);
                    continue;
IL_027a:
                    bool parseMember2           = reader.ReadByte() == 56;
                    reader.BaseStream.Position -= 1L;
                    expression = new AccessArrayExpression(expression, ParseExpression(reader, codeSectionInfo, blockId, parseMember2));
                }
            }
            goto IL_02eb;
IL_02eb:
            return(expression);
        }
Exemple #25
0
 override public void LeaveArrayLiteralExpression(ArrayLiteralExpression node)
 {
     OnExpression(node);
 }
Exemple #26
0
 public virtual void PostWalk(ArrayLiteralExpression node)
 {
 }
		public void Visit(ArrayLiteralExpression x)
		{
			
		}
Exemple #28
0
        private static Expression ParseExpression(BinaryReader reader, Encoding encoding, bool parseMember = true)
        {
            Expression result = null;
            byte       type;

            while (true)
            {
                type = reader.ReadByte();
                switch (type)
                {
                case 0x01:
                    result = ParamListEnd.Instance;
                    break;

                case 0x16:
                    result = DefaultValueExpression.Instance;
                    break;

                case 0x17:
                    result = new NumberLiteral(reader.ReadDouble());
                    break;

                case 0x18:
                    result = BoolLiteral.ValueOf(reader.ReadInt16() != 0);
                    break;

                case 0x19:
                    result = new DateTimeLiteral(DateTime.FromOADate(reader.ReadDouble()));
                    break;

                case 0x1A:
                    result = new StringLiteral(reader.ReadBStr(encoding));
                    break;

                case 0x1B:
                    result = new ConstantExpression(reader.ReadInt32());
                    break;

                case 0x1C:
                    result = new ConstantExpression((short)(reader.ReadInt16() - 1), (short)(reader.ReadInt16() - 1));
                    break;

                case 0x1D:
                    // 0x1D 0x38 <Int32:VarId>
                    continue;

                case 0x1E:
                    result = new MethodPtrExpression(reader.ReadInt32());
                    break;

                case 0x21:
                    result = ParseCallExpressionWithoutType(reader, encoding);
                    break;

                case 0x23:
                    result = new EmnuConstantExpression((short)(reader.ReadInt16() - 1), (short)(reader.ReadInt16() - 1), reader.ReadInt32() - 1);
                    break;

                case 0x37:
                    continue;

                case 0x1F:
                {
                    var        array = new ArrayLiteralExpression();
                    Expression exp;
                    while (!((exp = ParseExpression(reader, encoding)) is ArrayLiteralEnd))
                    {
                        array.Add(exp);
                    }
                    result = array;
                }
                break;

                case 0x20:
                    result = ArrayLiteralEnd.Instance;
                    break;

                case 0x38:     // ThisCall Or 访问变量
                {
                    int variable = reader.ReadInt32();
                    if (variable == 0x0500FFFE)
                    {
                        reader.ReadByte();         // 0x3A
                        return(ParseExpression(reader, encoding, true));
                    }
                    else
                    {
                        result      = new VariableExpression(variable);
                        parseMember = true;
                    }
                }
                break;

                case 0x3B:
                    result = new NumberLiteral(reader.ReadInt32());
                    break;

                default:
                    throw new Exception($"Unknown Type: {type.ToString("X2")}");
                }
                break;
            }
            if (parseMember &&
                (result is VariableExpression ||
                 result is CallExpression ||
                 result is AccessMemberExpression ||
                 result is AccessArrayExpression))
            {
                while (reader.BaseStream.Position != reader.BaseStream.Length)
                {
                    switch (reader.ReadByte())
                    {
                    case 0x39:
                        int memberId = reader.ReadInt32();
                        if (EplSystemId.GetType(memberId) == EplSystemId.Type_StructMember)
                        {
                            result = new AccessMemberExpression(result, reader.ReadInt32(), memberId);
                        }
                        else
                        {
                            result = new AccessMemberExpression(result, (short)(reader.ReadInt16() - 1), (short)(reader.ReadInt16() - 1), memberId - 1);
                        }
                        break;

                    case 0x3A:
                        result = new AccessArrayExpression(result, ParseExpression(reader, encoding, false));
                        break;

                    case 0x37:
                        goto parse_member_finish;

                    default:
                        reader.BaseStream.Position -= 1;
                        goto parse_member_finish;
                    }
                }
            }
parse_member_finish:
            return(result);
        }
Exemple #29
0
        IExpression PrimaryExpression(IBlockNode Scope=null)
        {
            bool isModuleScoped = false;
            // For minimizing possible overhead, skip 'useless' tokens like an initial dot <<< TODO
            if (isModuleScoped= laKind == Dot)
                Step();

            if (laKind == __FILE__ || laKind == __LINE__)
            {
                Step();

                object id = null;

                if (t.Kind == __FILE__ && doc != null)
                    id = doc.FileName;
                else if(t.Kind==__LINE__)
                    id = t.line;

                return new IdentifierExpression(id)
                {
                    Location=t.Location,
                    EndLocation=t.EndLocation
                };
            }

            // Dollar (== Array length expression)
            if (laKind == Dollar)
            {
                Step();
                return new TokenExpression(laKind)
                {
                    Location = t.Location,
                    EndLocation = t.EndLocation
                };
            }

            // TemplateInstance
            if (laKind == (Identifier) && Lexer.CurrentPeekToken.Kind == (Not)
                && (Peek().Kind != Is && Lexer.CurrentPeekToken.Kind != In)
                /* Very important: The 'template' could be a '!is'/'!in' expression - With two tokens each! */)
                return TemplateInstance();

            // Identifier
            if (laKind == (Identifier))
            {
                Step();
                return new IdentifierExpression(t.Value)
                {
                    Location = t.Location,
                    EndLocation = t.EndLocation
                };
            }

            // SpecialTokens (this,super,null,true,false,$) // $ has been handled before
            if (laKind == (This) || laKind == (Super) || laKind == (Null) || laKind == (True) || laKind == (False))
            {
                Step();
                return new TokenExpression(t.Kind)
                {
                    Location = t.Location,
                    EndLocation = t.EndLocation
                };
            }

            #region Literal
            if (laKind == Literal)
            {
                Step();
                var startLoc = t.Location;

                // Concatenate multiple string literals here
                if (t.LiteralFormat == LiteralFormat.StringLiteral || t.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                {
                    var a = t.LiteralValue as string;
                    while (la.LiteralFormat == LiteralFormat.StringLiteral || la.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                    {
                        Step();
                        a += t.LiteralValue as string;
                    }
                    return new IdentifierExpression(a, t.LiteralFormat) { Location = startLoc, EndLocation = t.EndLocation };
                }
                //else if (t.LiteralFormat == LiteralFormat.CharLiteral)return new IdentifierExpression(t.LiteralValue) { LiteralFormat=t.LiteralFormat,Location = startLoc, EndLocation = t.EndLocation };
                return new IdentifierExpression(t.LiteralValue, t.LiteralFormat) { Location = startLoc, EndLocation = t.EndLocation };
            }
            #endregion

            #region ArrayLiteral | AssocArrayLiteral
            if (laKind == (OpenSquareBracket))
            {
                Step();
                var startLoc = t.Location;

                // Empty array literal
                if (laKind == CloseSquareBracket)
                {
                    Step();
                    return new ArrayLiteralExpression() {Location=startLoc, EndLocation = t.EndLocation };
                }

                var firstExpression = AssignExpression();

                // Associtative array
                if (laKind == Colon)
                {
                    Step();

                    var ae = new AssocArrayExpression() { Location=startLoc};
                    LastParsedObject = ae;

                    var firstValueExpression = AssignExpression();

                    ae.KeyValuePairs.Add(firstExpression, firstValueExpression);

                    while (laKind == Comma)
                    {
                        Step();
                        var keyExpr = AssignExpression();
                        Expect(Colon);
                        var valueExpr = AssignExpression();

                        ae.KeyValuePairs.Add(keyExpr, valueExpr);
                    }

                    Expect(CloseSquareBracket);
                    ae.EndLocation = t.EndLocation;
                    return ae;
                }
                else // Normal array literal
                {
                    var ae = new ArrayLiteralExpression() { Location=startLoc};
                    LastParsedObject = ae;
                    var expressions = new List<IExpression>();
                    expressions.Add(firstExpression);

                    while (laKind == Comma)
                    {
                        Step();
                        if (laKind == CloseSquareBracket) // And again, empty expressions are allowed
                            break;
                        expressions.Add(AssignExpression());
                    }

                    ae.Expressions = expressions;

                    Expect(CloseSquareBracket);
                    ae.EndLocation = t.EndLocation;
                    return ae;
                }
            }
            #endregion

            #region FunctionLiteral
            if (laKind == Delegate || laKind == Function || laKind == OpenCurlyBrace || (laKind == OpenParenthesis && IsFunctionLiteral()))
            {
                var fl = new FunctionLiteral() { Location=la.Location};
                LastParsedObject = fl;
                fl.AnonymousMethod.StartLocation = la.Location;

                if (laKind == Delegate || laKind == Function)
                {
                    Step();
                    fl.LiteralToken = t.Kind;
                }

                // file.d:1248
                /*
                    listdir (".", delegate bool (DirEntry * de)
                    {
                        auto s = std.string.format("%s : c %s, w %s, a %s", de.name,
                                toUTCString (de.creationTime),
                                toUTCString (de.lastWriteTime),
                                toUTCString (de.lastAccessTime));
                        return true;
                    }
                    );
                */
                if (laKind != OpenCurlyBrace) // foo( 1, {bar();} ); -> is a legal delegate
                {
                    if (!MemberFunctionAttribute[laKind] && Lexer.CurrentPeekToken.Kind == OpenParenthesis)
                        fl.AnonymousMethod.Type = BasicType();
                    else if (laKind != OpenParenthesis && laKind != OpenCurlyBrace)
                        fl.AnonymousMethod.Type = Type();

                    if (laKind == OpenParenthesis)
                        fl.AnonymousMethod.Parameters = Parameters(fl.AnonymousMethod);
                }

                FunctionBody(fl.AnonymousMethod);

                fl.EndLocation = t.EndLocation;

                if (Scope != null)
                    Scope.Add(fl.AnonymousMethod);

                return fl;
            }
            #endregion

            #region AssertExpression
            if (laKind == (Assert))
            {
                Step();
                var startLoc = t.Location;
                Expect(OpenParenthesis);
                var ce = new AssertExpression() { Location=startLoc};
                LastParsedObject = ce;

                var exprs = new List<IExpression>();
                exprs.Add(AssignExpression());

                if (laKind == (Comma))
                {
                    Step();
                    exprs.Add(AssignExpression());
                }
                ce.AssignExpressions = exprs.ToArray();
                Expect(CloseParenthesis);
                ce.EndLocation = t.EndLocation;
                return ce;
            }
            #endregion

            #region MixinExpression | ImportExpression
            if (laKind == Mixin)
            {
                Step();
                var e = new MixinExpression() { Location=t.Location};
                LastParsedObject = e;
                Expect(OpenParenthesis);

                e.AssignExpression = AssignExpression();

                Expect(CloseParenthesis);
                e.EndLocation = t.EndLocation;
                return e;
            }

            if (laKind == Import)
            {
                Step();
                var e = new ImportExpression() { Location=t.Location};
                LastParsedObject = e;
                Expect(OpenParenthesis);

                e.AssignExpression = AssignExpression();

                Expect(CloseParenthesis);
                e.EndLocation = t.EndLocation;
                return e;
            }
            #endregion

            if (laKind == (Typeof))
            {
                var startLoc = la.Location;
                return new TypeDeclarationExpression(TypeOf()) {Location=startLoc,EndLocation=t.EndLocation};
            }

            // TypeidExpression
            if (laKind == (Typeid))
            {
                Step();
                var ce = new TypeidExpression() { Location=t.Location};
                LastParsedObject = ce;
                Expect(OpenParenthesis);

                AllowWeakTypeParsing = true;
                ce.Type = Type();
                AllowWeakTypeParsing = false;

                if (ce.Type==null)
                    ce.Expression = AssignExpression();

                Expect(CloseParenthesis);
                ce.EndLocation = t.EndLocation;
                return ce;
            }

            #region IsExpression
            if (laKind == Is)
            {
                Step();
                var ce = new IsExpression() { Location=t.Location};
                LastParsedObject = ce;
                Expect(OpenParenthesis);

                var LookAheadBackup = la;

                AllowWeakTypeParsing = true;
                ce.TestedType = Type();
                AllowWeakTypeParsing = false;

                if (ce.TestedType!=null && laKind == Identifier && (Lexer.CurrentPeekToken.Kind == CloseParenthesis || Lexer.CurrentPeekToken.Kind == Equal
                    || Lexer.CurrentPeekToken.Kind == Colon))
                {
                    Step();
                    ce.TypeAliasIdentifier = strVal;
                }
                else
                // D Language specs mistake: In an IsExpression there also can be expressions!
                if(ce.TestedType==null || !(laKind==CloseParenthesis || laKind==Equal||laKind==Colon))
                {
                    // Reset lookahead token to prior position
                    la = LookAheadBackup;
                    // Reset wrongly parsed type declaration
                    ce.TestedType = null;
                    ce.TestedExpression = ConditionalExpression();
                }

                if(ce.TestedExpression==null && ce.TestedType==null)
                    SynErr(laKind,"In an IsExpression, either a type or an expression is required!");

                if (laKind == CloseParenthesis)
                {
                    Step();
                    ce.EndLocation = t.EndLocation;
                    return ce;
                }

                if (laKind == Colon || laKind == Equal)
                {
                    Step();
                    ce.EqualityTest = t.Kind == Equal;
                }
                else if (laKind == CloseParenthesis)
                {
                    Step();
                    ce.EndLocation = t.EndLocation;
                    return ce;
                }

                /*
                TypeSpecialization:
                    Type
                        struct
                        union
                        class
                        interface
                        enum
                        function
                        delegate
                        super
                    const
                    immutable
                    inout
                    shared
                        return
                */

                if (ClassLike[laKind] || laKind==Typedef || // typedef is possible although it's not yet documented in the syntax docs
                    laKind==Enum || laKind==Delegate || laKind==Function || laKind==Super || laKind==Return)
                {
                    Step();
                    ce.TypeSpecializationToken = t.Kind;
                }
                else
                    ce.TypeSpecialization = Type();

                if (laKind == Comma)
                {
                    Step();
                    ce.TemplateParameterList =
                        TemplateParameterList(false);
                }

                Expect(CloseParenthesis);
                ce.EndLocation = t.EndLocation;
                return ce;
            }
            #endregion

            // ( Expression )
            if (laKind == OpenParenthesis)
            {
                Step();
                var ret = new SurroundingParenthesesExpression() {Location=t.Location };
                LastParsedObject = ret;

                ret.Expression = Expression();

                Expect(CloseParenthesis);
                ret.EndLocation = t.EndLocation;
                return ret;
            }

            // TraitsExpression
            if (laKind == (__traits))
                return TraitsExpression();

            #region BasicType . Identifier
            if (laKind == (Const) || laKind == (Immutable) || laKind == (Shared) || laKind == (InOut) || BasicTypes[laKind])
            {
                Step();
                var startLoc = t.Location;
                IExpression left = null;
                if (!BasicTypes[t.Kind])
                {
                    int tk = t.Kind;
                    // Put an artificial parenthesis around the following type declaration
                    if (laKind != OpenParenthesis)
                    {
                        var mttd = new MemberFunctionAttributeDecl(tk);
                        LastParsedObject = mttd;
                        mttd.InnerType = Type();
                        left = new TypeDeclarationExpression(mttd) { Location = startLoc, EndLocation = t.EndLocation };
                    }
                    else
                    {
                        Expect(OpenParenthesis);
                        var mttd = new MemberFunctionAttributeDecl(tk);
                        LastParsedObject = mttd;
                        mttd.InnerType = Type();
                        Expect(CloseParenthesis);
                        left = new TypeDeclarationExpression(mttd) { Location = startLoc, EndLocation = t.EndLocation };
                    }
                }
                else
                    left = new TokenExpression(t.Kind) {Location=startLoc,EndLocation=t.EndLocation };

                if (laKind == (Dot) && Peek(1).Kind==Identifier)
                {
                    Step();
                    Step();

                    var meaex = new PostfixExpression_Access() { PostfixForeExpression=left,
                        TemplateOrIdentifier=new IdentifierDeclaration(t.Value),EndLocation=t.EndLocation };

                    return meaex;
                }
                return left;
            }
            #endregion

            // TODO? Expressions can of course be empty...
            //return null;

            SynErr(Identifier);
            Step();
            return new TokenExpression(t.Kind) { Location = t.Location, EndLocation = t.EndLocation };
        }
		public ISymbolValue Visit(ArrayLiteralExpression arr)
		{
			var elements = new List<ISymbolValue>(arr.Elements.Count);

			//ISSUE: Type-check each item to distinguish not matching items
			foreach (var e in arr.Elements)
				elements.Add(e != null ? e.Accept(this) as ISymbolValue : null);

			if(elements.Count == 0){
				EvalError(arr, "Array literal must contain at least one element.");
				return null;
			}

			AbstractType baseType = null;
			foreach (var ev in elements)
				if (ev != null && (baseType = ev.RepresentedType) != null)
					break;
			
			return new ArrayValue(new ArrayType(baseType), elements.ToArray());
		}
 public void Visit(ArrayLiteralExpression x)
 {
 }
Exemple #32
0
 public override void OnArrayLiteralExpression(ArrayLiteralExpression node)
 {
     OnListLiteralExpression(node);
 }
Exemple #33
0
 // ArrayLiteralExpression
 public virtual bool Walk(ArrayLiteralExpression node)
 {
     return true;
 }
Exemple #34
0
        IExpression PrimaryExpression(IBlockNode Scope=null)
        {
            bool isModuleScoped = laKind == Dot;
            if (isModuleScoped)
            {
                Step();
                if (IsEOF)
                {
                    LastParsedObject = new TokenExpression(Dot) { Location = t.Location, EndLocation = t.EndLocation };
                    ExpectingIdentifier = true;
                }
            }

            if (laKind == __FILE__ || laKind == __LINE__)
            {
                Step();

                object id = null;

                if (t.Kind == __FILE__ && doc != null)
                    id = doc.FileName;
                else if(t.Kind==__LINE__)
                    id = t.line;

                return new IdentifierExpression(id)
                {
                    Location=t.Location,
                    EndLocation=t.EndLocation
                };
            }

            // Dollar (== Array length expression)
            if (laKind == Dollar)
            {
                Step();
                return new TokenExpression(laKind)
                {
                    Location = t.Location,
                    EndLocation = t.EndLocation
                };
            }

            // TemplateInstance
            if (IsTemplateInstance)
            {
                var tix = TemplateInstance();
                if (tix != null && tix.TemplateIdentifier!=null)
                    tix.TemplateIdentifier.ModuleScoped = isModuleScoped;
                return tix;
            }

            if (IsLambaExpression())
                return LambaExpression(Scope);

            // Identifier
            if (laKind == Identifier)
            {
                Step();

                return new IdentifierExpression(t.Value)
                    {
                        Location = t.Location,
                        EndLocation = t.EndLocation,
                        ModuleScoped = isModuleScoped
                    };
            }

            // SpecialTokens (this,super,null,true,false,$) // $ has been handled before
            if (laKind == (This) || laKind == (Super) || laKind == (Null) || laKind == (True) || laKind == (False))
            {
                Step();
                return new TokenExpression(t.Kind)
                {
                    Location = t.Location,
                    EndLocation = t.EndLocation
                };
            }

            #region Literal
            if (laKind == Literal)
            {
                Step();
                var startLoc = t.Location;

                // Concatenate multiple string literals here
                if (t.LiteralFormat == LiteralFormat.StringLiteral || t.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                {
                    var a = t.LiteralValue as string;
                    while (la.LiteralFormat == LiteralFormat.StringLiteral || la.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                    {
                        Step();
                        a += t.LiteralValue as string;
                    }
                    return new IdentifierExpression(a, t.LiteralFormat, t.Subformat) { Location = startLoc, EndLocation = t.EndLocation };
                }
                //else if (t.LiteralFormat == LiteralFormat.CharLiteral)return new IdentifierExpression(t.LiteralValue) { LiteralFormat=t.LiteralFormat,Location = startLoc, EndLocation = t.EndLocation };
                return new IdentifierExpression(t.LiteralValue, t.LiteralFormat, t.Subformat) { Location = startLoc, EndLocation = t.EndLocation };
            }
            #endregion

            #region ArrayLiteral | AssocArrayLiteral
            if (laKind == (OpenSquareBracket))
            {
                Step();
                var startLoc = t.Location;

                // Empty array literal
                if (laKind == CloseSquareBracket)
                {
                    Step();
                    return new ArrayLiteralExpression() {Location=startLoc, EndLocation = t.EndLocation };
                }

                /*
                 * If it's an initializer, allow NonVoidInitializers as values.
                 * Normal AssignExpressions otherwise.
                 */
                bool isInitializer = TrackerVariables.IsParsingInitializer;

                var firstExpression = isInitializer? NonVoidInitializer(Scope) : AssignExpression(Scope);

                // Associtative array
                if (laKind == Colon)
                {
                    Step();

                    var ae = isInitializer ?
                        new ArrayInitializer { Location = startLoc } :
                        new AssocArrayExpression { Location=startLoc };
                    LastParsedObject = ae;

                    var firstValueExpression = isInitializer? NonVoidInitializer(Scope) : AssignExpression();

                    ae.Elements.Add(new KeyValuePair<IExpression,IExpression>(firstExpression, firstValueExpression));

                    while (laKind == Comma)
                    {
                        Step();

                        if (laKind == CloseSquareBracket)
                            break;

                        var keyExpr = AssignExpression();
                        var valExpr=Expect(Colon) ?
                            (isInitializer?
                                NonVoidInitializer(Scope) :
                                AssignExpression(Scope)) :
                            null;

                        ae.Elements.Add(new KeyValuePair<IExpression,IExpression>(keyExpr,valExpr));
                    }

                    Expect(CloseSquareBracket);
                    ae.EndLocation = t.EndLocation;
                    return ae;
                }
                else // Normal array literal
                {
                    var ae = new ArrayLiteralExpression() { Location=startLoc };
                    LastParsedObject = ae;

                    ae.Elements.Add(firstExpression);

                    while (laKind == Comma)
                    {
                        Step();
                        if (laKind == CloseSquareBracket) // And again, empty expressions are allowed
                            break;
                        ae.Elements.Add(isInitializer? NonVoidInitializer(Scope) : AssignExpression(Scope));
                    }

                    Expect(CloseSquareBracket);
                    ae.EndLocation = t.EndLocation;
                    return ae;
                }
            }
            #endregion

            #region FunctionLiteral
            if (laKind == Delegate || laKind == Function || laKind == OpenCurlyBrace || (laKind == OpenParenthesis && IsFunctionLiteral()))
            {
                var fl = new FunctionLiteral() { Location=la.Location};
                LastParsedObject = fl;
                fl.AnonymousMethod.Location = la.Location;

                if (laKind == Delegate || laKind == Function)
                {
                    Step();
                    fl.LiteralToken = t.Kind;
                }

                // file.d:1248
                /*
                    listdir (".", delegate bool (DirEntry * de)
                    {
                        auto s = std.string.format("%s : c %s, w %s, a %s", de.name,
                                toUTCString (de.creationTime),
                                toUTCString (de.lastWriteTime),
                                toUTCString (de.lastAccessTime));
                        return true;
                    }
                    );
                */
                if (laKind != OpenCurlyBrace) // foo( 1, {bar();} ); -> is a legal delegate
                {
                    if (!MemberFunctionAttribute[laKind] && Lexer.CurrentPeekToken.Kind == OpenParenthesis)
                        fl.AnonymousMethod.Type = BasicType();
                    else if (laKind != OpenParenthesis && laKind != OpenCurlyBrace)
                        fl.AnonymousMethod.Type = Type();

                    if (laKind == OpenParenthesis)
                        fl.AnonymousMethod.Parameters = Parameters(fl.AnonymousMethod);

                    while (FunctionAttribute[laKind])
                    {
                        Step();
                        fl.AnonymousMethod.Attributes.Add(new DAttribute(t.Kind, t.Value));
                    }
                }

                FunctionBody(fl.AnonymousMethod);

                fl.EndLocation = t.EndLocation;

                if (Scope != null)
                    Scope.Add(fl.AnonymousMethod);

                return fl;
            }
            #endregion

            #region AssertExpression
            if (laKind == (Assert))
            {
                Step();
                var startLoc = t.Location;
                Expect(OpenParenthesis);
                var ce = new AssertExpression() { Location=startLoc};
                LastParsedObject = ce;

                var exprs = new List<IExpression>();
                exprs.Add(AssignExpression());

                if (laKind == (Comma))
                {
                    Step();
                    exprs.Add(AssignExpression());
                }
                ce.AssignExpressions = exprs.ToArray();
                Expect(CloseParenthesis);
                ce.EndLocation = t.EndLocation;
                return ce;
            }
            #endregion

            #region MixinExpression | ImportExpression
            if (laKind == Mixin)
            {
                Step();
                var e = new MixinExpression() { Location=t.Location};
                LastParsedObject = e;
                if (Expect(OpenParenthesis))
                {
                    e.AssignExpression = AssignExpression();
                    Expect(CloseParenthesis);
                }
                e.EndLocation = t.EndLocation;
                return e;
            }

            if (laKind == Import)
            {
                Step();
                var e = new ImportExpression() { Location=t.Location};
                LastParsedObject = e;
                Expect(OpenParenthesis);

                e.AssignExpression = AssignExpression();

                Expect(CloseParenthesis);
                e.EndLocation = t.EndLocation;
                return e;
            }
            #endregion

            if (laKind == (Typeof))
            {
                return new TypeDeclarationExpression(TypeOf());
            }

            // TypeidExpression
            if (laKind == (Typeid))
            {
                Step();
                var ce = new TypeidExpression() { Location=t.Location};
                LastParsedObject = ce;
                Expect(OpenParenthesis);

                AllowWeakTypeParsing = true;
                ce.Type = Type();
                AllowWeakTypeParsing = false;

                if (ce.Type==null)
                    ce.Expression = AssignExpression();

                Expect(CloseParenthesis);
                ce.EndLocation = t.EndLocation;
                return ce;
            }

            #region IsExpression
            if (laKind == Is)
            {
                Step();
                var ce = new IsExpression() { Location=t.Location};
                LastParsedObject = ce;
                Expect(OpenParenthesis);

                if((ce.TestedType = Type())==null)
                    SynErr(laKind, "In an IsExpression, either a type or an expression is required!");

                if (ce.TestedType!=null && laKind == Identifier && (Lexer.CurrentPeekToken.Kind == CloseParenthesis || Lexer.CurrentPeekToken.Kind == Equal
                    || Lexer.CurrentPeekToken.Kind == Colon))
                {
                    Step();
                    ce.TypeAliasIdentifier = strVal;
                }

                if (laKind == CloseParenthesis)
                {
                    Step();
                    ce.EndLocation = t.EndLocation;
                    return ce;
                }

                if (laKind == Colon || laKind == Equal)
                {
                    Step();
                    ce.EqualityTest = t.Kind == Equal;
                }
                else if (laKind == CloseParenthesis)
                {
                    Step();
                    ce.EndLocation = t.EndLocation;
                    return ce;
                }

                /*
                TypeSpecialization:
                    Type
                        struct
                        union
                        class
                        interface
                        enum
                        function
                        delegate
                        super
                    const
                    immutable
                    inout
                    shared
                        return
                */

                if (ce.EqualityTest && (ClassLike[laKind] || laKind==Typedef || // typedef is possible although it's not yet documented in the syntax docs
                    laKind==Enum || laKind==Delegate || laKind==Function || laKind==Super || laKind==Return ||
                    ((laKind==Const || laKind == Immutable || laKind == InOut || laKind == Shared) &&
                    (Peek(1).Kind==CloseParenthesis || Lexer.CurrentPeekToken.Kind==Comma))))
                {
                    Step();
                    ce.TypeSpecializationToken = t.Kind;
                }
                else
                    ce.TypeSpecialization = Type();

                if (laKind == Comma)
                {
                    Step();
                    ce.TemplateParameterList =
                        TemplateParameterList(false);
                }

                Expect(CloseParenthesis);
                ce.EndLocation = t.EndLocation;
                return ce;
            }
            #endregion

            // ( Expression )
            if (laKind == OpenParenthesis)
            {
                Step();
                var ret = new SurroundingParenthesesExpression() {Location=t.Location };
                LastParsedObject = ret;

                ret.Expression = Expression();

                Expect(CloseParenthesis);
                ret.EndLocation = t.EndLocation;
                return ret;
            }

            // TraitsExpression
            if (laKind == (__traits))
                return TraitsExpression();

            #region BasicType . Identifier
            if (IsBasicType())
            {
                var startLoc = la.Location;

                var bt=BasicType();

                if (bt is TypeOfDeclaration && laKind!=Dot)
                    return new TypeDeclarationExpression(bt);

                if (Expect(Dot) && Expect(Identifier))
                    return new PostfixExpression_Access()
                    {
                        PostfixForeExpression = new TypeDeclarationExpression(bt),
                        AccessExpression = new IdentifierExpression(t.Value) { Location=t.Location, EndLocation=t.EndLocation },
                        EndLocation = t.EndLocation
                    };

                return null;
            }
            #endregion

            SynErr(Identifier);
            Step();
            return new TokenExpression() { Location = t.Location, EndLocation = t.EndLocation };
        }
Exemple #35
0
 // ArrayLiteralExpression
 public override bool Walk(ArrayLiteralExpression node)
 {
     return false;
 }
Exemple #36
0
 public override void LeaveArrayLiteralExpression(ArrayLiteralExpression node)
 {
     node.Type = null;
 }