Example #1
0
        private string buildFunctionLiteral(FunctionLiteral functionLiteral)
        {
            var result = "";
            // build return type
            var returntype = Build(functionLiteral.ReturnType);

            result += returntype + " ";
            // build function name
            var functionname = Prefix + Build(functionLiteral.FunctionName);

            result += functionname + "(";
            // build function arguments
            bool fristArgument = true;
            var  parameters    = "";

            functionLiteral.Parameters.ForEach(node =>
            {
                parameters += (fristArgument ? "" : ",") + Prefix + Build(node);
                if (fristArgument)
                {
                    fristArgument = false;
                }
            });
            result += parameters;
            result += ") { \n";
            // build function body
            result += Build(functionLiteral.Body);
            result += "}";
            // add to defines list
            if (blockLevel == 0)
            {
                objectDefines.Add(returntype + " " + functionname + "(" + parameters + ");");
            }
            return(result);
        }
Example #2
0
        public void Parser_CanParseFunctionLiteral()
        {
            string input = @"
fn(x, y) { x + y; }
";

            AST result = this.subject.ParseProgram(input);

            Assert.Empty(result.Errors);
            Assert.Equal(1, result.Program.Statements.Count);

            ExpressionStatement actual       = this.AssertAndCast <ExpressionStatement>(result.Program.Statements[0]);
            FunctionLiteral     fnExpression = this.AssertAndCast <FunctionLiteral>(actual.Expression);

            Assert.Equal(2, fnExpression.Parameters.Count);

            Identifier paramExpr = this.AssertAndCast <Identifier>(fnExpression.Parameters[0]);

            Assert.Equal("x", paramExpr.Value);
            paramExpr = this.AssertAndCast <Identifier>(fnExpression.Parameters[1]);
            Assert.Equal("y", paramExpr.Value);

            Assert.Equal(1, fnExpression.Body.Statements.Count);
            ExpressionStatement body     = this.AssertAndCast <ExpressionStatement>(fnExpression.Body.Statements[0]);
            InfixExpression     bodyExpr = this.AssertAndCast <InfixExpression>(body.Expression);

            Assert.Equal("x", bodyExpr.Left.TokenLiteral);
            Assert.Equal(TokenType.Plus, bodyExpr.Operator);
            Assert.Equal("y", bodyExpr.Right.TokenLiteral);
        }
 public AbstractType Visit(FunctionLiteral x)
 {
     return(new DelegateType(
                (ctxt.Options & ResolutionOptions.DontResolveBaseTypes | ResolutionOptions.ReturnMethodReferencesOnly) != 0 ? null : TypeDeclarationResolver.GetMethodReturnType(x.AnonymousMethod, ctxt),
                x,
                TypeResolution.TypeDeclarationResolver.HandleNodeMatches(x.AnonymousMethod.Parameters, ctxt)));
 }
        public virtual Expression visit(FunctionLiteral functionLiteral)
        {
            functionLiteral.name       = visitIdentifier(functionLiteral.name);
            functionLiteral.parameters = visitIdentifierArray(functionLiteral.parameters);
            functionLiteral.variables  = visitIdentifierArray(functionLiteral.variables);
            functionLiteral.functions  = visitStatementArray(functionLiteral.functions);
            functionLiteral.statements = visitStatementArray(functionLiteral.statements);

            return(functionLiteral);
        }
Example #5
0
        public static void SetMemberValue(this object target, string name, object value, Type explicitType, ScriptValues.ValueType valueType)
        {
            object          targetObject;
            bool            isEnum;
            MemberInfo      mi  = FindMember(target, name, explicitType, out targetObject, out isEnum);
            ObjectLiteral   ojl = targetObject as ObjectLiteral;
            FunctionLiteral ful = targetObject as FunctionLiteral;
            IDictionary <string, object> odi = targetObject as IDictionary <string, object>;

            if (mi == null)
            {
                if (ojl != null)
                {
                    ojl[name] = value;
                    return;
                }

                if (ful != null)
                {
                    ful.SetInitialScopeValue(name, value);
                    return;
                }

                if (odi != null)
                {
                    odi[name] = value;
                    return;
                }

                throw new ScriptException(string.Format("Member {0} is not declared on {1}", name,
                                                        targetObject));
            }

            PropertyInfo pi;
            FieldInfo    fi;

            if (mi is PropertyInfo && (pi = (PropertyInfo)mi).CanWrite)
            {
                pi.SetValue(targetObject, value, null);
            }
            else if (mi is FieldInfo && !(fi = (FieldInfo)mi).IsLiteral)
            {
                fi.SetValue(targetObject, value);
            }
            else if (mi is EventInfo && value is FunctionLiteral)
            {
                FunctionLiteral fl = value as FunctionLiteral;
                EventInfo       ev = mi as EventInfo;
                ev.AddEventHandler(targetObject, fl.CreateDelegate(ev.EventHandlerType));
            }
            else
            {
                throw new ScriptException(string.Format("SetValue is not supported for this Member ({0}", name));
            }
        }
Example #6
0
        ISemantic E(FunctionLiteral x)
        {
            var dg = new DelegateType(TypeDeclarationResolver.GetMethodReturnType(x.AnonymousMethod, ctxt), x);

            if (eval)
            {
                return(new DelegateValue(dg));
            }
            else
            {
                return(dg);
            }
        }
Example #7
0
        public DelegateType(AbstractType ReturnType, FunctionLiteral Literal, IEnumerable <AbstractType> Parameters)
            : base(ReturnType, Literal)
        {
            this.IsFunction = Literal.LiteralToken == DTokens.Function;

            if (Parameters is AbstractType[])
            {
                this.Parameters = (AbstractType[])Parameters;
            }
            else if (Parameters != null)
            {
                this.Parameters = Parameters.ToArray();
            }
        }
Example #8
0
        public override void Visit(FunctionLiteral x)
        {
            var pop = curIndent.Peek == IndentType.Block && curIndent.ExtraSpaces > 0;

            if (pop)
            {
                curIndent.Push(IndentType.Negative);
            }
            //FixIndentation (x.Location);
            base.Visit(x);
            if (pop)
            {
                curIndent.Pop();
            }
        }
Example #9
0
        ISemantic E(FunctionLiteral x)
        {
            var dg = new DelegateType(
                (ctxt.Options & ResolutionOptions.DontResolveBaseTypes | ResolutionOptions.ReturnMethodReferencesOnly) != 0 ? null : TypeDeclarationResolver.GetMethodReturnType(x.AnonymousMethod, ctxt),
                x,
                TypeResolution.TypeDeclarationResolver.HandleNodeMatches(x.AnonymousMethod.Parameters, ctxt));

            if (eval)
            {
                return(new DelegateValue(dg));
            }
            else
            {
                return(dg);
            }
        }
Example #10
0
        private Object evalFunctionLiteral(Object context, FunctionLiteral functionLiteral)
        {
            Function function = new Function()
            {
                Engine     = this,
                Parent     = context,
                Block      = functionLiteral.Body,
                Parameters = functionLiteral.Parameters
            };

            if (!functionLiteral.Anonymous)
            {
                string functionName = functionLiteral.FunctionName.Literal;
                context[functionName] = function;
            }
            return(function);
        }
Example #11
0
        private IExpression ParseFunctionLiteral()
        {
            var lit = new FunctionLiteral {
                Token = CurrentToken
            };

            if (!ExpectPeek(Token.Lparen))
            {
                return(null);
            }
            lit.Parameters = ParseFunctionParameters();
            if (!ExpectPeek(Token.Lbrace))
            {
                return(null);
            }
            lit.Body = ParseBlockStatement();
            return(lit);
        }
Example #12
0
        private Expression ParseFunctionLiteral()
        {
            var lit = new FunctionLiteral();

            lit.Token = this._curToken;
            if (!this.ExpectPeek(TokenType.LPAREN))
            {
                throw new ParserException($"expect peek {TokenType.LPAREN} but got {this._peekToken}");
            }
            lit.Parameters = this.ParseFunctionParameters();

            if (!this.ExpectPeek(TokenType.LBRACE))
            {
                throw new ParserException($"expect peek {TokenType.LBRACE} but got {this._peekToken}");
            }
            lit.Body = this.ParseBlockStatement();
            return(lit);
        }
Example #13
0
        private IExpression parseFunctionLiteral()
        {
            var literal = new FunctionLiteral(currentToken);

            if (!ExpectPeek(TokenType.LPAREN))
            {
                return(null);
            }

            literal.Parameters = parseFunctionParameters();

            if (!ExpectPeek(TokenType.LBRACE))
            {
                return(null);
            }

            literal.Body = parseBlockStatement();

            return(literal);
        }
        private FunctionLiteral ParseFunctionLiteral()
        {
            var lit = new FunctionLiteral {
                Token = curToken
            };

            if (!ExpectPeek(TokenType.LParen))
            {
                return(null);
            }

            lit.Parameters = ParseFunctionParameters();

            if (!ExpectPeek(TokenType.LBrace))
            {
                return(null);
            }

            lit.Body = ParseBlockStatement();

            return(lit);
        }
Example #15
0
        public IExpression ParseFunctionLiteral()
        {
            var fn = new FunctionLiteral()
            {
                Token = this.CurrentToken
            };

            if (!this.ExpectPeek(TokenType.LPAREN))
            {
                return(null);
            }

            fn.Parameters = this.ParseParameters();

            if (!this.ExpectPeek(TokenType.LBRACE))
            {
                return(null);
            }

            fn.Body = this.ParseBlockStatement();

            return(fn);
        }
Example #16
0
        public bool CanGetValue(ScriptValue[] arguments)
        {
            if (!Getable)
            {
                throw new ScriptException("Get is not supported for this member");
            }

            if (creator != null)
            {
                bool ok = creator.CanInvokeExecutor(Value,arguments,bypassCompatibilityOnLazyInvokation);
                //object retVal = creator.InvokeExecutor(Value, arguments, bypassCompatibilityOnLazyInvokation, out ok);
                if (ok)
                {
                    return true;
                }
            }

            if (ValueType == ValueType.Literal)
            {
                return false;
            }

            object tmpValue = Value;
            if (ValueType == ValueType.PropertyOrField)
            {
                if (arguments == null || arguments.Length == 0)
                {
                    return true;
                }
                if (tmpValue == null)
                {
                    return false;
                }

                if (tmpValue is Type)
                {
                    return false;
                }

                object[] parameters = (from t in arguments select t.GetValue(null)).ToArray();
                if (!(tmpValue is Array))
                {
                    object[] args;
                    PropertyInfo pi = MethodHelper.GetCapableIndexer(ExplicitType??tmpValue.GetType(),
                                                                     parameters,
                                                                     out args);
                    return pi != null;
                }

                Array arr = (Array)tmpValue;
                int[] indices = parameters.Cast<int>().ToArray();
                bool retVal = true;
                for (int i = 0; i < indices.Length; i++)
                {
                    retVal &= arr.GetLength(i) > indices[i];
                }

                return retVal;
            }

            if (ValueType == ValueType.Method)
            {
                SequenceValue ta = (SequenceValue)arguments[0];
                SequenceValue a = (SequenceValue)arguments[1];
                ScriptValue et = arguments[2];
                object[] parameters = (from t in a.Sequence select t.GetValue(null)).ToArray();
                Type[] typeParameters = Type.EmptyTypes;
                if (ta != null)
                {
                    typeParameters = (from t in ta.Sequence select (Type)t.GetValue(null)).ToArray();
                }

                Type type;

                if (tmpValue == null)
                {
                    ValueType = ValueType.PropertyOrField;
                }

                if (Name == null)
                {
                    try
                    {
                        if (tmpValue is Delegate)
                        {
                            return true;
                        }

                        if (tmpValue is InvokationHelper)
                        {
                            return true;
                        }

                        if (tmpValue is FunctionLiteral)
                        {
                            return true;
                        }
                    }
                    finally
                    {
                        ValueType = ValueType.Method;
                    }
                }

                if (tmpValue == null)
                {
                    return false;
                }

                object target = tmpValue;
                bool isStatic = false;
                if (tmpValue is Type)
                {
                    type = (Type)tmpValue;
                    target = null;
                    isStatic = true;
                }
                else if (tmpValue is ObjectLiteral)
                {
                    type = tmpValue.GetType();
                    ObjectLiteral ol = tmpValue as ObjectLiteral;
                    FunctionLiteral fl = ol[Name] as FunctionLiteral;
                    if (fl != null)
                    {
                        return true;
                    }
                }
                else
                {
                    type = et?.GetValue(null) as Type ?? tmpValue.GetType();
                }

                object[] args;
#if UseDelegates
                MethodInvoker method = MethodHelper.GetCapableMethod(type, typeParameters, Name, Value is Type, parameters, out args);
#else
                bool tmpStatic = isStatic;
                MethodInfo method = MethodHelper.GetCapableMethod(type, typeParameters, Name, ref isStatic, parameters,
                                                                  out args);
                if (!tmpStatic && isStatic)
                {
                    args[0] = target;
                    target = null;
                }
#endif
                if (method == null)
                {
                    return false;
                }

                return true;
            }

            if (ValueType == ValueType.Constructor)
            {
                if (tmpValue == null || !(tmpValue is Type))
                {
                    throw new ScriptException("Require Type in order to create a new instance");
                }

                ScriptValue[] ta = null;
                if (arguments[0] != null)
                {
                    ta = ((SequenceValue)arguments[0]).Sequence;
                }

                ScriptValue[] a = ((SequenceValue)arguments[1]).Sequence;
                object[] parameters = (from t in a select t.GetValue(null)).ToArray();
                Type[] typeParameters = ta == null
                                            ? Type.EmptyTypes
                                            : (from t in ta select (Type)t.GetValue(null)).ToArray();
                Type type = (Type)tmpValue;
                if (typeParameters.Length != 0)
                {
                    //throw new ScriptException(string.Format("Unexpected usage of generic Type {0}", ((Type)Value).FullName));
                    type = type.MakeGenericType(typeParameters);
                }

                object[] args;
                ConstructorInfo constructor = MethodHelper.GetCapableConstructor(type, parameters, out args);
                if (constructor == null)
                {
                    return false;
                }

                return true;
            }

            throw new ScriptException("Unexpected Value-Type");
        }
        ISemantic E(FunctionLiteral x)
        {
            var dg = new DelegateType(TypeDeclarationResolver.GetMethodReturnType(x.AnonymousMethod, ctxt),x);

            if (eval)
                return new DelegateValue(dg);
            else
                return dg;
        }
 public void Visit(FunctionLiteral x)
 {
 }
		public void Visit(FunctionLiteral x)
		{
			
		}
Example #20
0
        public static Type GetMemberType(this object target, string name, Type explicitType, ScriptValues.ValueType valueType)
        {
            if (valueType == ScriptValues.ValueType.Method || valueType == ScriptValues.ValueType.Constructor)
            {
                return(null);
            }

            object          targetObject;
            bool            isEnum;
            MemberInfo      mi  = FindMember(target, name, explicitType, out targetObject, out isEnum);
            ObjectLiteral   ojl = targetObject as ObjectLiteral;
            FunctionLiteral ful = targetObject as FunctionLiteral;
            IDictionary <string, object> odi = targetObject as IDictionary <string, object>;
            IBasicKeyValueProvider       iba = targetObject as IBasicKeyValueProvider;

            if (mi == null)
            {
                if (ojl != null)
                {
                    return(ojl[name]?.GetType() ?? typeof(object));
                }

                if (ful != null)
                {
                    return(ful.GetInitialScopeValue(name)?.GetType() ?? typeof(object));
                }

                if (odi != null && odi.ContainsKey(name))
                {
                    return(odi[name]?.GetType() ?? typeof(object));
                }
                else if (odi != null)
                {
                    return(null);
                }

                if (iba != null && iba.ContainsKey(name))
                {
                    return(iba[name]?.GetType() ?? typeof(object));
                }
                else if (iba != null)
                {
                    return(null);
                }
            }

            if (isEnum)
            {
                return((Type)targetObject);
            }

            if (mi == null)
            {
                throw new ScriptException(string.Format("Member {0} is not declared on {1}", name,
                                                        targetObject));
            }

            if (mi is PropertyInfo pi)
            {
                if (pi.CanRead)
                {
                    return(pi.PropertyType);
                }

                return(null);
            }

            if (mi is FieldInfo fi)
            {
                return(fi.FieldType);
            }

            if (mi is EventInfo ev)
            {
                return(ev.EventHandlerType);
            }

            throw new ScriptException(string.Format("GetValue is not supported for MemberType {0}", mi.MemberType));
        }
Example #21
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 };
        }
Example #22
0
        IExpression PrimaryExpression(IBlockNode Scope=null)
        {
            bool isModuleScoped = laKind == Dot;
            if (isModuleScoped)
            {
                Step();
                if (IsEOF)
                {
                    var dot = new TokenExpression(Dot) { Location = t.Location, EndLocation = t.EndLocation };
                    return new PostfixExpression_Access{ PostfixForeExpression = dot, AccessExpression = new TokenExpression(DTokens.Incomplete) };
                }
            }

            // TemplateInstance
            if (IsTemplateInstance)
            {
                var tix = TemplateInstance(Scope);
                if (tix != null)
                    tix.ModuleScopedIdentifier = isModuleScoped;
                return tix;
            }

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

            CodeLocation startLoc;
            switch (laKind)
            {
                // ArrayLiteral | AssocArrayLiteral
                case OpenSquareBracket:
                    return ArrayLiteral(Scope);
                case New:
                    return NewExpression(Scope);
                case Typeof:
                    return new TypeDeclarationExpression(TypeOf());
                case __traits:
                    return TraitsExpression();
                // Dollar (== Array length expression)
                case Dollar:
                    Step();
                    return new TokenExpression(t.Kind)
                    {
                        Location = t.Location,
                        EndLocation = t.EndLocation
                    };
                case 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
                case This:
                case Super:
                case Null:
                case True:
                case False:
                    Step();
                    return new TokenExpression(t.Kind)
                    {
                        Location = t.Location,
                        EndLocation = t.EndLocation
                    };
                case OpenParenthesis:
                    if (IsFunctionLiteral())
                        goto case Function;
                    // ( Expression )
                    Step();
                    var ret = new SurroundingParenthesesExpression() {Location=t.Location };

                    ret.Expression = Expression();

                    Expect(CloseParenthesis);
                    ret.EndLocation = t.EndLocation;
                    return ret;
                case Literal:
                    Step();
                    startLoc = t.Location;

                    // Concatenate multiple string literals here
                    if (t.LiteralFormat == LiteralFormat.StringLiteral || t.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                    {
                        var sb = new StringBuilder(t.RawCodeRepresentation ?? t.Value);
                        while (la.LiteralFormat == LiteralFormat.StringLiteral || la.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                        {
                            Step();
                            sb.Append(t.RawCodeRepresentation ?? t.Value);
                        }
                        return new IdentifierExpression(sb.ToString(), 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 };
                // FunctionLiteral
                case Delegate:
                case Function:
                case OpenCurlyBrace:
                    var fl = new FunctionLiteral() { Location=la.Location};
                    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 (!IsFunctionAttribute && 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);

                        FunctionAttributes(fl.AnonymousMethod);
                    }

                    if (!IsEOF)
                    {
                        FunctionBody(fl.AnonymousMethod);
                        fl.EndLocation = fl.AnonymousMethod.EndLocation;
                    }
                    else
                        fl.EndLocation = la.Location;

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

                    return fl;
                // AssertExpression
                case Assert:
                    Step();
                    startLoc = t.Location;
                    Expect(OpenParenthesis);
                    var ce = new AssertExpression() { Location=startLoc};

                    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;
                // MixinExpression
                case Mixin:
                    Step();
                    var me = new MixinExpression() { Location=t.Location};
                    if (Expect(OpenParenthesis))
                    {
                        me.AssignExpression = AssignExpression();
                        Expect(CloseParenthesis);
                    }
                    me.EndLocation = t.EndLocation;
                    return me;
                // ImportExpression
                case Import:
                    Step();
                    var ie = new ImportExpression() { Location=t.Location};
                    Expect(OpenParenthesis);

                    ie.AssignExpression = AssignExpression();

                    Expect(CloseParenthesis);
                    ie.EndLocation = t.EndLocation;
                    return ie;
                // TypeidExpression
                case Typeid:
                    Step();
                    var tide = new TypeidExpression() { Location=t.Location};
                    Expect(OpenParenthesis);

                    if (IsAssignExpression())
                        tide.Expression = AssignExpression(Scope);
                    else
                    {
                        Lexer.PushLookAheadBackup();
                        AllowWeakTypeParsing = true;
                        tide.Type = Type();
                        AllowWeakTypeParsing = false;

                        if (tide.Type == null || laKind != CloseParenthesis)
                        {
                            Lexer.RestoreLookAheadBackup();
                            tide.Expression = AssignExpression();
                        }
                        else
                            Lexer.PopLookAheadBackup();
                    }

                    Expect (CloseParenthesis);

                    tide.EndLocation = t.EndLocation;
                    return tide;
                // IsExpression
                case Is:
                    Step();
                    var ise = new IsExpression() { Location = t.Location };
                    Expect(OpenParenthesis);

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

                    if (ise.TestedType != null)
                    {
                        if (laKind == Identifier && (Lexer.CurrentPeekToken.Kind == CloseParenthesis || Lexer.CurrentPeekToken.Kind == Equal
                            || Lexer.CurrentPeekToken.Kind == Colon))
                        {
                            Step();
                            Strings.Add(strVal);
                            ise.TypeAliasIdentifierHash = strVal.GetHashCode();
                            ise.TypeAliasIdLocation = t.Location;
                        }
                        else if (IsEOF)
                            ise.TypeAliasIdentifierHash = DTokens.IncompleteIdHash;
                    }

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

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

                    bool specialTest = false;
                    if (ise.EqualityTest)
                    {
                        switch (laKind)
                        {
                            case Typedef: // typedef is possible although it's not yet documented in the syntax docs
                            case Enum:
                            case Delegate:
                            case Function:
                            case Super:
                            case Return:
                                specialTest = true;
                                break;
                            case Const:
                            case Immutable:
                            case InOut:
                            case Shared:
                                specialTest = Peek(1).Kind == CloseParenthesis || Lexer.CurrentPeekToken.Kind == Comma;
                                break;
                            default:
                                specialTest = IsClassLike(laKind);
                                break;
                        }
                    }
                    if (specialTest)
                    {
                        Step();
                        ise.TypeSpecializationToken = t.Kind;
                    }
                    else
                        ise.TypeSpecialization = Type();

                    // TemplateParameterList
                    if (laKind == Comma)
                    {
                        var tempParam = new List<TemplateParameter>();
                        do
                        {
                            Step();
                            tempParam.Add(TemplateParameter(null));
                        }
                        while (laKind == Comma);
                        ise.TemplateParameterList = tempParam.ToArray();
                    }

                    Expect(CloseParenthesis);
                    ise.EndLocation = t.EndLocation;
                    return ise;
                default:
                    if (DTokens.IsMetaIdentifier(laKind))
                        goto case Dollar;
                    else if (IsBasicType())
                    {
                        // BasicType . Identifier
                        startLoc = la.Location;

                        var bt=BasicType();

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

                        // Things like incomplete 'float.' expressions shall be parseable, too
                        if (Expect(Dot) && (Expect(Identifier) || IsEOF))
                            return new PostfixExpression_Access()
                            {
                                PostfixForeExpression = new TypeDeclarationExpression(bt),
                                AccessExpression = IsEOF ? new TokenExpression(Incomplete) as IExpression : new IdentifierExpression(t.Value) { Location=t.Location, EndLocation=t.EndLocation },
                                EndLocation = t.EndLocation
                            };

                        return null;
                    }

                    SynErr(Identifier);
                    if(laKind != CloseCurlyBrace)
                        Step();

                    if (IsEOF)
                        return new TokenExpression (DTokens.Incomplete) { Location = t.Location, EndLocation = t.Location };

                    // Don't know why, in rare situations, t tends to be null..
                    if (t == null)
                        return null;
                    return new TokenExpression() { Location = t.Location, EndLocation = t.EndLocation };
            }
        }
Example #23
0
 public virtual Expression visit(FunctionLiteral literal)
 {
     return(literal);
 }
Example #24
0
        public static object GetMemberValue(this object target, string name, Type explicitType, ScriptValues.ValueType valueType)
        {
            if (valueType == ScriptValues.ValueType.Method || valueType == ScriptValues.ValueType.Constructor)
            {
                var bv  = target;
                var olt = bv as ObjectLiteral;
                if (valueType == ScriptValues.ValueType.Constructor && olt != null)
                {
                    return(olt[name]);
                }

                return(bv);
            }

            object          targetObject;
            bool            isEnum;
            MemberInfo      mi  = FindMember(target, name, explicitType, out targetObject, out isEnum);
            ObjectLiteral   ojl = targetObject as ObjectLiteral;
            FunctionLiteral ful = targetObject as FunctionLiteral;
            IDictionary <string, object> odi = targetObject as IDictionary <string, object>;
            IBasicKeyValueProvider       iba = targetObject as IBasicKeyValueProvider;

            if (mi == null)
            {
                if (ojl != null)
                {
                    return(ojl[name]);
                }

                if (ful != null)
                {
                    return(ful.GetInitialScopeValue(name));
                }

                if (odi != null && odi.ContainsKey(name))
                {
                    return(odi[name]);
                }
                else if (odi != null)
                {
                    return(null);
                }

                if (iba != null && iba.ContainsKey(name))
                {
                    return(iba[name]);
                }
                else if (iba != null)
                {
                    return(null);
                }
            }

            if (
                isEnum)
            {
                return(Enum.Parse((Type)targetObject, name));
            }

            if (mi == null)
            {
                throw new ScriptException(string.Format("Member {0} is not declared on {1}", name,
                                                        targetObject));
            }

            if (mi is PropertyInfo)
            {
                PropertyInfo pi = (PropertyInfo)mi;
                if (pi.CanRead)
                {
                    return(pi.GetValue(targetObject, null));
                }

                return(null);
            }

            if (mi is FieldInfo)
            {
                return(((FieldInfo)mi).GetValue(targetObject));
            }

            if (mi is EventInfo)
            {
                return(null);
            }

            throw new ScriptException(string.Format("GetValue is not supported for MemberType {0}", mi.MemberType));
        }
Example #25
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 };
                    TrackerVariables.ExpectingIdentifier = true;
                }
            }

            // Dollar (== Array length expression)
            if (laKind == Dollar || DTokens.MetaIdentifiers[laKind])
            {
                Step();
                return new TokenExpression(t.Kind)
                {
                    Location = t.Location,
                    EndLocation = t.EndLocation
                };
            }

            // TemplateInstance
            if (IsTemplateInstance)
            {
                var tix = TemplateInstance(Scope);
                if (tix != null)
                    tix.ModuleScopedIdentifier = 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 sb = new StringBuilder(t.RawCodeRepresentation ?? t.Value);
                    while (la.LiteralFormat == LiteralFormat.StringLiteral || la.LiteralFormat == LiteralFormat.VerbatimStringLiteral)
                    {
                        Step();
                        sb.Append(t.RawCodeRepresentation ?? t.Value);
                    }
                    return new IdentifierExpression(sb.ToString(), 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(null) {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 List<IExpression>();
                    LastParsedObject = ae;

                    ae.Add(firstExpression);

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

                    Expect(CloseSquareBracket);
                    return new ArrayLiteralExpression(ae){ Location=startLoc, EndLocation = t.EndLocation };
                }
            }
            #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 (!IsFunctionAttribute && 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);

                    FunctionAttributes(fl.AnonymousMethod);
                }

                if(!IsEOF)
                    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);

                if (IsAssignExpression())
                    ce.Expression = AssignExpression(Scope);
                else
                {
                    Lexer.PushLookAheadBackup();
                    AllowWeakTypeParsing = true;
                    ce.Type = Type();
                    AllowWeakTypeParsing = false;

                    if (ce.Type == null || laKind != CloseParenthesis)
                    {
                        Lexer.RestoreLookAheadBackup();
                        ce.Expression = AssignExpression();
                    }
                    else
                        Lexer.PopLookAheadBackup();
                }

                if (!Expect(CloseParenthesis) && IsEOF)
                    LastParsedObject = (ISyntaxRegion)ce.Type ?? ce.Expression;

                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();
                    Strings.Add(strVal);
                    ce.TypeAliasIdentifierHash = strVal.GetHashCode();
                    ce.TypeAliasIdLocation = t.Location;
                }

                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();

                // TemplateParameterList
                if (laKind == Comma)
                {
                    var ret = new List<TemplateParameter>();
                    do
                    {
                        Step();
                        ret.Add(TemplateParameter(null));
                    }
                    while (laKind == Comma);
                    ce.TemplateParameterList = ret.ToArray();
                }

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

            // NewExpression
            if (laKind == (New))
                return NewExpression(Scope);

            // ( 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 || bt is MemberFunctionAttributeDecl) && laKind!=Dot)
                    return new TypeDeclarationExpression(bt);

                // Things like incomplete 'float.' expressions shall be parseable, too
                if (Expect(Dot) && (Expect(Identifier) || IsEOF))
                    return new PostfixExpression_Access()
                    {
                        PostfixForeExpression = new TypeDeclarationExpression(bt),
                        AccessExpression = string.IsNullOrEmpty(t.Value) ? null : new IdentifierExpression(t.Value) { Location=t.Location, EndLocation=t.EndLocation },
                        EndLocation = t.EndLocation
                    };

                return null;
            }
            #endregion

            SynErr(Identifier);
            if(laKind != CloseCurlyBrace)
                Step();

            // Don't know why, in rare situations, t tends to be null..
            if (t == null)
                return null;
            return new TokenExpression() { Location = t.Location, EndLocation = t.EndLocation };
        }
Example #26
0
 LLVMValueRef IExpressionVisitor.Visit(FunctionLiteral exp)
 {
     return(codegen.GetFunctionPointer(exp.Value));
 }
 public FunctionDeclaration(FunctionLiteral literal)
 {
     this.literal = literal;
 }
Example #28
0
        FunctionLiteral LambaExpression(IBlockNode Scope=null)
        {
            var fl = new FunctionLiteral { IsLambda=true };

            fl.Location = fl.AnonymousMethod.Location = la.Location;

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

                var p = new DVariable {
                    Name = t.Value,
                    Location = t.Location,
                    EndLocation = t.EndLocation };

                p.Attributes.Add(new DAttribute(Auto));

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

            if (Expect(GoesTo))
            {
                fl.AnonymousMethod.Body = new BlockStatement { Location= la.Location };

                var ae = AssignExpression(fl.AnonymousMethod);

                fl.AnonymousMethod.Body.Add(new ReturnStatement
                {
                    Location = ae.Location,
                    EndLocation = ae.EndLocation,
                    ReturnExpression=ae
                });

                fl.AnonymousMethod.Body.EndLocation = t.EndLocation;
            }

            fl.EndLocation = fl.AnonymousMethod.EndLocation = t.EndLocation;

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

            return fl;
        }
		public override void Visit (FunctionLiteral x)
		{
			var pop = curIndent.Peek == IndentType.Block && curIndent.ExtraSpaces > 0;
			if (pop)
				curIndent.Push (IndentType.Negative);
			//FixIndentation (x.Location);
			base.Visit (x);
			if (pop)
				curIndent.Pop ();
		}
Example #30
0
        /// <summary>
        /// Gets the effective Value of this ScriptValue instance
        /// </summary>
        /// <param name="arguments">indexer/method/constructor arguments</param>
        /// <returns>an object that represents the value of this ScriptValue</returns>
        public virtual object GetValue(ScriptValue[] arguments)
        {
            if (!Getable)
            {
                throw new ScriptException("Get is not supported for this member");
            }

            if (creator != null)
            {
                bool ok;
                object retVal = creator.InvokeExecutor(Value, arguments, bypassCompatibilityOnLazyInvokation, out ok);
                if (ok)
                {
                    return retVal;
                }
            }

            if (ValueType == ValueType.Literal)
            {
                return Value;
            }

            object tmpValue = Value;
            if (ValueType == ValueType.PropertyOrField)
            {
                if (arguments == null || arguments.Length == 0)
                {
                    var invokationHelper = tmpValue as InvokationHelper;
                    if (invokationHelper != null)
                    {
                        bool ok;
                        object retVal = invokationHelper.Invoke(null, out ok);
                        if (ok)
                        {
                            return retVal;
                        }
                    }

                    FunctionLiteral fx = tmpValue as FunctionLiteral;
                    if (fx != null && fx.AutoInvokeEnabled)
                    {
                        return ((FunctionLiteral) tmpValue).Invoke(null);
                    }

                    return tmpValue;
                }
                if (tmpValue == null)
                {
                    throw new ScriptException("Indexer Failed for NULL - Value");
                }

                if (tmpValue is Type)
                {
                    throw new ScriptException("Indexer call for Types not supported");
                }

                object[] parameters = (from t in arguments select t.GetValue(null)).ToArray();
                if (!(tmpValue is Array))
                {
                    object[] args;
                    Type targetType = tmpValue.GetType();
                    if (ExplicitType != null)
                    {
                        if (!ExplicitType.IsAssignableFrom(targetType))
                        {
                            throw new ScriptException("Provided Type is not implemented by the target-object");
                        }

                        targetType = ExplicitType;
                    }
                    PropertyInfo pi = MethodHelper.GetCapableIndexer(targetType,
                                                                     parameters,
                                                                     out args);
                    if (pi == null)
                    {
                        throw new ScriptException("No capable Indexer found for the provided arguments");
                    }

                    if (creator != null)
                    {
                        creator.SetPreferredExecutor(new LazyIndexer(pi,parameters.Length != args.Length));
                    }

                    return pi.GetValue(tmpValue, args);
                }

                Array arr = (Array)tmpValue;
                return arr.GetValue(parameters.Cast<int>().ToArray());
            }

            if (ValueType == ValueType.Method)
            {
                SequenceValue ta = (SequenceValue) arguments[0];
                SequenceValue a = (SequenceValue) arguments[1];
                ScriptValue et = arguments[2];
                Type explicitType = null;
                object[] parameters = (from t in a.Sequence select t.GetValue(null)).ToArray();
                Type[] typeParameters = Type.EmptyTypes;
                if (ta != null)
                {
                    typeParameters = (from t in ta.Sequence select (Type) t.GetValue(null)).ToArray();
                }

                if (et != null)
                {
                    explicitType = et.GetValue(null) as Type;
                }

                Type type;
                
                if (tmpValue == null)
                {
                    ValueType = ValueType.PropertyOrField;
                }

                if (Name == null)
                {
                    try
                    {
                        if (tmpValue is Delegate)
                        {
                            Delegate dlg = (Delegate) tmpValue;
                            return dlg.DynamicInvoke(parameters);
                        }

                        if (tmpValue is InvokationHelper)
                        {
                            InvokationHelper ih = (InvokationHelper) tmpValue;
                            bool ok;
                            var retVal = ih.Invoke(parameters, out ok);
                            if (ok)
                            {
                                return retVal;
                            }

                            throw new ScriptException($"Failed to call method {Name}. Possible Arguments-mismatch.");
                        }

                        if (tmpValue is FunctionLiteral)
                        {
                            FunctionLiteral fl = (FunctionLiteral) tmpValue;
                            return fl.Invoke(parameters);
                        }
                    }
                    finally
                    {
                        ValueType = ValueType.Method;
                    }
                }

                if (tmpValue == null)
                {
                    throw new Exception("Method call failed for NULL - Value");
                }

                object target = tmpValue;
                bool isStatic = false;
                if (tmpValue is Type)
                {
                    type = (Type)tmpValue;
                    target = null;
                    isStatic = true;
                }
                else if (tmpValue is ObjectLiteral)
                {
                    type = tmpValue.GetType();
                    ObjectLiteral ol = tmpValue as ObjectLiteral;
                    FunctionLiteral fl = ol[Name] as FunctionLiteral;
                    if (fl != null)
                    {
                        return fl.Invoke(parameters);
                    }
                }
                else
                {
                    type = explicitType??tmpValue.GetType();
                }

                object[] args;
#if UseDelegates
                MethodInvoker method = MethodHelper.GetCapableMethod(type, typeParameters, Name, Value is Type, parameters, out args);
#else
                bool tmpStatic = isStatic;
                MethodInfo method = MethodHelper.GetCapableMethod(type, typeParameters, Name, ref isStatic, parameters,
                                                                  out args);
                if (!tmpStatic && isStatic)
                {
                    args[0] = target;
                    target = null;
                }
#endif
                if (method == null)
                {
                    throw new ScriptException(string.Format("No capable Method found for {0}", Name));
                }

                var writeBacks = MethodHelper.GetWritebacks(method, args, a.Sequence);
                if (creator != null)
                {
                    creator.SetPreferredExecutor(new LazyMethod(method, tmpStatic, !tmpStatic && isStatic, args.Length != a.Sequence.Length));
                }
#if UseDelegates
                if (target != null)
                {
                    target = target.WrapIfValueType();
                }

                return method(target, args);
                if (target != null)
                {

                    /*object[] newArgs = new object[args.Length + 1];
                    newArgs[0] = target;
                    Array.Copy(args, 0, newArgs, 1, args.Length);*/
                    args[0] = target;
                    if (!(target is System.ValueType))
                    {
                        return method.FastDynamicInvoke(args);
                    }

                    return method.DynamicInvoke(args);
#else
                try
                {
                    return method.Invoke(target, args);
                }
                finally
                {
                    foreach (var wb in writeBacks)
                    {
                        wb.Target.SetValue(args[wb.Index]);
                    }
                }
#endif
#if UseDelegates
                }


                return method.FastDynamicInvoke(args);
#endif
            }

            if (ValueType == ValueType.Constructor)
            {
                if (tmpValue == null || !(tmpValue is Type))
                {
                    throw new ScriptException("Require Type in order to create a new instance");
                }

                ScriptValue[] ta = null;
                if (arguments[0] != null)
                {
                    ta = ((SequenceValue)arguments[0]).Sequence;
                }

                ScriptValue[] a = ((SequenceValue) arguments[1]).Sequence;
                object[] parameters = (from t in a select t.GetValue(null)).ToArray();
                Type[] typeParameters = ta == null
                                            ? Type.EmptyTypes
                                            : (from t in ta select (Type) t.GetValue(null)).ToArray();
                Type type = (Type)tmpValue;
                if (typeParameters.Length != 0)
                {
                    //throw new ScriptException(string.Format("Unexpected usage of generic Type {0}", ((Type)Value).FullName));
                    type = type.MakeGenericType(typeParameters);
                }

                object[] args;
                ConstructorInfo constructor = MethodHelper.GetCapableConstructor(type, parameters, out args);
                if (constructor == null)
                {
                    throw new ScriptException(string.Format("No appropriate Constructor was found for {0}",
                                                            ((Type)tmpValue).FullName));
                }

                if (creator != null)
                {
                    creator.SetPreferredExecutor(new LazyConstructor(constructor, args.Length != a.Length));
                }

                return constructor.Invoke(args);
            }

            throw new ScriptException("Unexpected Value-Type");
        }
Example #31
0
        FunctionLiteral LambaExpression(IBlockNode Scope=null)
        {
            var fl = new FunctionLiteral(true);

            fl.Location = fl.AnonymousMethod.Location = la.Location;

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

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

                var p = new DVariable {
                    Name = t.Value,
                    Location = t.Location,
                    EndLocation = t.EndLocation,
                    Attributes =  new List<DAttribute>{new Modifier(Auto)}
                };

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

            LambdaBody(fl.AnonymousMethod);
            fl.EndLocation = fl.AnonymousMethod.EndLocation;

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

            return fl;
        }
Example #32
0
        public DelegateType(AbstractType ReturnType, FunctionLiteral Literal, IEnumerable<AbstractType> Parameters)
            : base(ReturnType, Literal)
        {
            this.IsFunction = Literal.LiteralToken == DTokens.Function;

            if (Parameters is AbstractType[])
                this.Parameters = (AbstractType[])Parameters;
            else if (Parameters != null)
                this.Parameters = Parameters.ToArray();
        }
		public ISymbolValue Visit(FunctionLiteral x)
		{
			var dg = new DelegateType(
				(ctxt.Options & ResolutionOptions.DontResolveBaseTypes | ResolutionOptions.ReturnMethodReferencesOnly) != 0 ? null : TypeDeclarationResolver.GetMethodReturnType (x.AnonymousMethod, ctxt),
				x,
				TypeResolution.TypeDeclarationResolver.HandleNodeMatches(x.AnonymousMethod.Parameters, ctxt));

			return new DelegateValue(dg);
		}