示例#1
0
        private TypeToken Type()
        {
            TypeToken type = (TypeToken)look;

            Match(Tags.BASIC_TYPE);
            return(type);
        }
 public VariableDeclarationExpression(TypeToken type, IEnumerable <AssignmentExpression> variables,
                                      TextSpan textSpan = default)
     : base(textSpan)
 {
     Type      = type;
     Variables = variables as List <AssignmentExpression> ?? variables.ToList();
 }
示例#3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject Token = JObject.Load(reader);

            if (!Token.TryGetValue("@type", StringComparison.OrdinalIgnoreCase, out JToken TypeToken))
            {
                throw new InvalidOperationException("Invalid presto query plan node object.");
            }

            Type ActualType = PlanNode.GetType(TypeToken.ToObject <PlanNodeType>(serializer));

            if (existingValue == null || existingValue.GetType() != ActualType)
            {
                // Don't use this approach, since there are no default constructors
                // JsonContract Contract = serializer.ContractResolver.ResolveContract(ActualType);
                // existingValue = Contract.DefaultCreator();
                return(Token.ToObject(ActualType, serializer));
            }
            else
            {
                using (JsonReader DerivedTypeReader = Token.CreateReader())
                {
                    serializer.Populate(DerivedTypeReader, existingValue);
                }

                return(existingValue);
            }
        }
示例#4
0
        /// <summary>
        /// Reads the json and converts to appropriate Geometry class using the 'type' field as an indicator
        /// to which object it should be deserialized back to
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject Token = JObject.Load(reader);

            if (!Token.TryGetValue("type", StringComparison.OrdinalIgnoreCase, out JToken TypeToken))
            {
                throw new JsonReaderException("Invalid geojson geometry object, does not have 'type' field.");
            }

            Type ActualType = Geometry.GetType(TypeToken.ToObject <GeoJsonType>(serializer));

            if (existingValue == null || existingValue.GetType() != ActualType)
            {
                return(Token.ToObject(ActualType, serializer));
            }
            else
            {
                using (JsonReader DerivedTypeReader = Token.CreateReader())
                {
                    serializer.Populate(DerivedTypeReader, existingValue);
                }

                return(existingValue);
            }
        }
示例#5
0
        /// <summary>
        /// Emits the typeof(Type)
        /// </summary>
        /// <param name="generator">The generator.</param>
        /// <param name="type">The type.</param>
        public static void EmitTypeOf(this ILGenerator generator, TypeToken type)
        {
            generator.Emit(OpCodes.Ldtoken, type.Token);
            var tTypeMeth = typeof(Type).GetMethod("GetTypeFromHandle", new[] { typeof(RuntimeTypeHandle) });

            generator.Emit(OpCodes.Call, tTypeMeth);
        }
示例#6
0
        private Statement VariableDeclaration()
        {
            // TODO : multiple declarations style int a, b, c;

            TypeToken type            = Type();
            WordToken identifierToken = look as WordToken;

            Match(Tags.ID);

            Expression initialValue = null;

            if (look.Tag == '=')
            {
                Match('=');
                initialValue = Bool();
            }

            Match(';');

            LocalVariableSymbol symbol = symbolTable.PutVar(identifierToken.Lexeme, type.DotNetType);

            memoryUsed += type.Width;

            return(new VariableDeclarationStatement(symbol, initialValue));
        }
示例#7
0
        /// <summary>
        /// var a = new A
        /// {
        ///     b = 2,
        ///     c = 3,
        /// }
        ///
        /// var a = new A();
        /// a.b = 2;
        /// a.c = 3;
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public override Ust VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var typeToken = new TypeToken("Anonymous", node.OpenBraceToken.GetTextSpan());

            Expression[] args = node.Initializers.Select(init =>
            {
                try
                {
                    var left = init.NameEquals == null ? null :
                               new MemberReferenceExpression(typeToken,
                                                             ConvertId(init.NameEquals.Name.Identifier), init.NameEquals.Name.GetTextSpan());
                    var right = (Expression)base.Visit(init.Expression);

                    var assignment = new AssignmentExpression(left, right, init.GetTextSpan());
                    return(assignment);
                }
                catch (Exception ex) when(!(ex is ThreadAbortException))
                {
                    Logger.LogError(new ConversionException(root?.SourceCodeFile, message: ex.Message));
                    return(null);
                }
            }).ToArray();
            var argsNode = new ArgsUst(args, node.GetTextSpan());

            var result = new ObjectCreateExpression(typeToken, argsNode, node.GetTextSpan());

            return(result);
        }
        public Ust VisitClassOrInterfaceType(JavaParser.ClassOrInterfaceTypeContext context)
        {
            var id            = (IdToken)Visit(context.IDENTIFIER(0));
            var typeArguments = context.typeArguments();
            var typeNodes     = new StringBuilder();

            foreach (var typeArgument in typeArguments)
            {
                for (int i = 0; i < typeArgument.ChildCount; i++)
                {
                    if (typeArgument.GetChild(i) is ITerminalNode terminalNode)
                    {
                        typeNodes.Append(terminalNode.Symbol.Text);
                        continue;
                    }

                    if (typeArgument.GetChild(i) is JavaParser.TypeArgumentContext typeNode)
                    {
                        typeNodes.Append(((TypeToken)Visit(typeNode))?.TypeText);
                    }
                }
            }

            var result = new TypeToken(id.Id + typeNodes.ToString(), context.GetTextSpan());

            return(result);
        }
示例#9
0
 public FixedStatement(TypeToken type, IEnumerable <AssignmentExpression> vars, Statement embedded, TextSpan textSpan, FileNode fileNode)
     : base(textSpan, fileNode)
 {
     Type      = type;
     Variables = vars as List <AssignmentExpression> ?? vars.ToList();
     Embedded  = embedded;
 }
示例#10
0
        public override UstNode VisitGenericName(GenericNameSyntax node)
        {
            var typeName = string.Join("", node.DescendantTokens().Select(t => t.ValueText));
            var result   = new TypeToken(typeName, node.GetTextSpan(), FileNode);

            return(result);
        }
        private void GenerateValueMemberBlock(TypeToken typeToken, IMethodBlock memberAccess, Method.BlockCollection block)
        {
            var instanceInitializer        = CreateInstanceInitializer(typeToken, memberAccess);
            var defaultInstanceInitializer = instanceInitializer == default(IMethodBlock);

            if (defaultInstanceInitializer && typeToken.IsClass)
            {
                instanceInitializer = new Method.Assignment(memberAccess, typeToken.NewExpression().ToMethodBlock());
            }

            if (instanceInitializer != default)
            {
                block.Children.Add(instanceInitializer);
            }

            if (!defaultInstanceInitializer)
            {
                return;
            }

            foreach (var subMemberToken in MemberProvider(typeToken))
            {
                GenerateMemberBlock(subMemberToken, memberAccess, block);
            }
        }
示例#12
0
        public override Ust VisitArrayType(ArrayTypeSyntax node)
        {
            var arrayType = node.ToString().Replace(",", "][");
            var result    = new TypeToken(arrayType, node.GetTextSpan());

            return(result);
        }
示例#13
0
 public CatchClause(TypeToken type, IdToken varName, BlockStatement body, TextSpan textSpan)
     : base(textSpan)
 {
     Type    = type;
     VarName = varName;
     Body    = body;
 }
示例#14
0
        public override UstNode VisitCatchClause(CatchClauseSyntax node)
        {
            TypeToken typeToken;
            IdToken   varName;

            if (node.Declaration == null)
            {
                typeToken = new TypeToken("Exception", node.CatchKeyword.GetTextSpan(), FileNode);
                varName   = new IdToken("e", node.CatchKeyword.GetTextSpan(), FileNode);
            }
            else
            {
                typeToken = ConvertType(base.Visit(node.Declaration.Type));
                varName   = new IdToken(node.Declaration.Identifier.ValueText ?? "", node.Declaration.GetTextSpan(), FileNode);
            }

            var body   = (BlockStatement)VisitBlock(node.Block);
            var result = new CatchClause(
                typeToken,
                varName,
                body,
                node.GetTextSpan(),
                FileNode);

            return(result);
        }
示例#15
0
        public Ust VisitPrimitiveType(JavaParser.PrimitiveTypeContext context)
        {
            var name   = context.GetChild <ITerminalNode>(0).GetText();
            var result = new TypeToken(name, context.GetTextSpan());

            return(result);
        }
示例#16
0
        /// <summary>
        /// Reads the json and converts to appropriate GeoJson class using the 'type' field as an indicator
        /// to which object it should be deserialized back to
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // Allow an abstract GeoJson to be null in deserialization
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            JObject token = JObject.Load(reader);

            if (!token.TryGetValue("type", StringComparison.OrdinalIgnoreCase, out JToken TypeToken))
            {
                throw new JsonReaderException("Invalid geojson object, does not have 'type' field.");
            }

            Type actualType = GeoJson.GetType(TypeToken.ToObject <GeoJsonType>(serializer));

            if (existingValue == null || existingValue.GetType() != actualType)
            {
                return((GeoJson)token.ToObject(actualType, serializer));
            }
            else
            {
                using (JsonReader derivedTypeReader = token.CreateReader())
                {
                    serializer.Populate(derivedTypeReader, existingValue);
                }

                return(existingValue);
            }
        }
        public static string GenerateAssembly()
        {
            var directoryInfo = new DirectoryInfo(GeneratedAssembliesDirectoryName);

            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }
            var assemblyName     = $"assembly{Guid.NewGuid().ToString("N")}";
            var assemblyFilePath = Path.Combine(directoryInfo.FullName, assemblyName + ".dll");

            AssemblyName    aName = new AssemblyName(assemblyName);
            AssemblyBuilder ab    = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save, GeneratedAssembliesDirectoryName);
            ModuleBuilder   mb    = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

            TypeToken tt = mb.GetTypeToken(typeof(String)); // not sure this is needed, it supposedly forces mscorlib to be injected

            TypeBuilder            tb            = mb.DefineType(GeneratedTypeName, TypeAttributes.Public);
            MethodBuilder          meth          = tb.DefineMethod(GeneratedMethodName, MethodAttributes.Public, typeof(string), new Type[] { typeof(string) });
            ConstructorInfo        classCtorInfo = typeof(NewRelic.Api.Agent.TransactionAttribute).GetConstructor(new Type[] {});
            CustomAttributeBuilder myCABuilder2  = new CustomAttributeBuilder(classCtorInfo, new object[] { });

            meth.SetCustomAttribute(myCABuilder2);
            ILGenerator methIL = meth.GetILGenerator();

            methIL.Emit(OpCodes.Ldarg_1);
            methIL.Emit(OpCodes.Ret);
            Type t = tb.CreateType();

            ab.Save(aName.Name + ".dll");

            return(assemblyFilePath);
        }
示例#18
0
    public AccessingOperationExpression Offset(IdExpression idExpression)
    {
        IExpression booleanExpression;
        IExpression constantExpression;
        IExpression arithmeticOperationExpression1;
        IExpression arithmeticOperationExpression2;
        IExpression loc;
        TypeToken   typeToken = idExpression.TypeToken;

        MatchThenLookAhead('[');
        booleanExpression = Boolean();
        MatchThenLookAhead(']');
        typeToken                      = ((ArrayTypeToken)typeToken).OfTypeToken;
        constantExpression             = new ConstantExpression(typeToken.Width, _emitterNode);
        arithmeticOperationExpression1 = new ArithmeticOperationExpression(new Token('*'), booleanExpression, constantExpression, _emitterNode);
        loc = arithmeticOperationExpression1;
        while (LookAheadToken?.Tag == '[')
        {
            MatchThenLookAhead('[');
            booleanExpression = Boolean();
            MatchThenLookAhead(']');
            typeToken                      = ((ArrayTypeToken)typeToken).OfTypeToken;
            constantExpression             = new ConstantExpression(typeToken.Width, _emitterNode);
            arithmeticOperationExpression1 = new ArithmeticOperationExpression(new Token('*'), booleanExpression, constantExpression, _emitterNode);
            arithmeticOperationExpression2 = new ArithmeticOperationExpression(new Token('+'), loc, arithmeticOperationExpression1, _emitterNode);
            loc = arithmeticOperationExpression2;
        }
        return(new AccessingOperationExpression(idExpression, loc, typeToken, _emitterNode));
    }
示例#19
0
 public FieldDeclaration(TypeToken type, IEnumerable <AssignmentExpression> variables,
                         TextSpan textSpan)
     : base(null, textSpan)
 {
     Type      = type;
     Variables = variables as List <AssignmentExpression> ?? variables.ToList();
 }
示例#20
0
        public void Convert_JavaArrayInitialization()
        {
            var sourceCodeRep = new MemoryCodeRepository(
                "class ArrayInitialization {\r\n" +
                "public void init() {\r\n" +
                "int[] arr1 = new int[] { 1, 2, 3 };\r\n" +
                "int[][] arr2 = new int[1][2];\r\n" +
                "int[][] arr3 = new int[1][];\r\n" +
                "}\r\n" +
                "}",

                "ArrayInitialization.java"
                );

            var workflow = new Workflow(sourceCodeRep, stage: Stage.Ust)
            {
                IsSimplifyUst = false
            };
            var workflowResult = workflow.Process();
            var ust            = workflowResult.Usts.First();
            var intType        = new TypeToken("int");

            var arrayData = new List <Tuple <List <Expression>, List <Expression> > >();

            // new int[] { 1, 2, 3 };
            arrayData.Add(new Tuple <List <Expression>, List <Expression> >(
                              Enumerable.Range(1, 3).Select(num => new IntLiteral(num)).ToList <Expression>(),
                              new List <Expression> {
                new IntLiteral(0)
            }
                              ));
            // new int[1][2];
            arrayData.Add(new Tuple <List <Expression>, List <Expression> >(
                              null,
                              new List <Expression> {
                new IntLiteral(1), new IntLiteral(2)
            }
                              ));
            // new int[1][];
            arrayData.Add(new Tuple <List <Expression>, List <Expression> >(
                              null,
                              new List <Expression> {
                new IntLiteral(1), new IntLiteral(0)
            }
                              ));

            for (var i = 0; i < arrayData.Count; i++)
            {
                var data = arrayData[i];
                var arrayCreationExpression = new ArrayCreationExpression
                {
                    Type         = intType,
                    Initializers = data.Item1,
                    Sizes        = data.Item2
                };
                bool exist = ust.AnyDescendant(node => node.Equals(arrayCreationExpression));
                Assert.IsTrue(exist, "Test failed on " + i + " iteration.");
            }
        }
        /// <summary>
        /// Initializes a new instance of the GenericTypeParameter class.
        /// </summary>
        /// <param name="type">
        /// The generic type parameter.
        /// </param>
        /// <param name="modifiers">
        /// Optional modifiers.
        /// </param>
        internal GenericTypeParameter(TypeToken type, ParameterModifiers modifiers)
        {
            Param.AssertNotNull(type, "type");
            Param.Ignore(modifiers);

            this.type      = type;
            this.modifiers = modifiers;
        }
示例#22
0
 public ParameterDeclaration(InOutModifierLiteral modifier, TypeToken type,
                             IdToken name, TextSpan textSpan = default)
     : base(textSpan)
 {
     Modifier = modifier;
     Type     = type;
     Name     = name;
 }
 private static Object ConvertJsonToData(string dataJson = null)
 {
     return(new Gson().FromJson(dataJson, TypeToken.GetParameterized(
                                    TypeToken.Get(Class.FromType(typeof(HashMap))).Type,
                                    TypeToken.Get(Class.FromType(typeof(String))).Type,
                                    TypeToken.Get(Class.FromType(typeof(Object))).Type)
                                .Type));
 }
示例#24
0
        public override Ust VisitAliasQualifiedName(AliasQualifiedNameSyntax node)
        {
            var alias  = (IdToken)VisitIdentifierName(node.Alias);
            var name   = (Token)base.Visit(node.Name);
            var result = new TypeToken(new[] { alias.Id, name.TextValue }, node.GetTextSpan());

            return(result);
        }
        /// <summary>
        /// Initializes a new instance of the GenericTypeParameter class.
        /// </summary>
        /// <param name="type">
        /// The generic type parameter.
        /// </param>
        /// <param name="modifiers">
        /// Optional modifiers.
        /// </param>
        internal GenericTypeParameter(TypeToken type, ParameterModifiers modifiers)
        {
            Param.AssertNotNull(type, "type");
            Param.Ignore(modifiers);

            this.type = type;
            this.modifiers = modifiers;
        }
示例#26
0
 public ArrayCreationExpression(TypeToken type, IEnumerable <Expression> sizes, IEnumerable <Expression> inits,
                                TextSpan textSpan)
     : base(textSpan)
 {
     Type         = type;
     Sizes        = sizes as List <Expression> ?? sizes?.ToList() ?? new List <Expression>();
     Initializers = inits as List <Expression> ?? inits?.ToList() ?? new List <Expression>();
 }
示例#27
0
        public virtual Expression ToExpression()
        {
            var blockBody = new List <Expression>();

            // AccessExpression is null on the root node (It's a dummy node)
            // ReadExpression.Count > 1 can only happen if we decided to roll a loop, in which case all elements are identical.
            // ReadExpression.Count = 0 can happen if the type is a value type. Otherwise this is new T[...] or new T().
            if (AccessExpression != null)
            {
                if (ReadExpression.Count > 0)
                {
                    blockBody.Add(Expression.Assign(AccessExpression, ReadExpression[0]));
                }
                else if (TypeToken.IsArray)
                {
                    blockBody.Add(Expression.Assign(AccessExpression,
                                                    TypeToken.GetElementTypeToken().NewArrayBounds(Expression.Constant(MemberToken.Cardinality))));
                }
                else if (TypeToken.IsClass)
                {
                    if (!TypeToken.HasDefaultConstructor)
                    {
                        throw new InvalidOperationException("Missing default constructor for " + TypeToken.Name);
                    }

                    blockBody.Add(Expression.Assign(AccessExpression, TypeToken.NewExpression()));
                }
            }

            if (Children.Count > 0)
            {
                // Produce children if there are any
                foreach (var child in Children)
                {
                    blockBody.Add(child.ToExpression());
                }

                // Assert that there is at least one node in the block emitted.
                if (blockBody.Count == 0)
                {
                    throw new InvalidOperationException("Empty block");
                }
            }

            // We allow empty blocks if there are no children for primitive types
            if (blockBody.Count == 0)
            {
                return(Expression.Empty());
            }

            // If there's only one expression, just return it.
            if (blockBody.Count == 1)
            {
                return(blockBody[0]);
            }

            return(Expression.Block(blockBody));
        }
示例#28
0
 public Token(double valueToken, TypeToken typeToken, AdvancedTypeToken advancedTypeToken,
              int priority, string expressionToken)
 {
     ValToken          = valueToken;
     TypeToken         = typeToken;
     AdvancedTypeToken = advancedTypeToken;
     Priority          = priority;
     ExpressionToken   = expressionToken;
 }
示例#29
0
 public ForeachStatement(TypeToken type, IdToken varName, Expression inExpression,
                         Statement embeddedStatement, TextSpan textSpan, FileNode fileNode)
     : base(textSpan, fileNode)
 {
     Type              = type;
     VarName           = varName;
     InExpression      = inExpression;
     EmbeddedStatement = embeddedStatement;
 }
示例#30
0
        public Ust VisitCatchType(JavaParser.CatchTypeContext context)
        {
            string[] names = context.qualifiedName().Select(name => ((StringLiteral)Visit(name))?.Text)
                             .Where(n => n != null).ToArray();

            var result = new TypeToken(string.Join("|", names), context.GetTextSpan());

            return(result);
        }
示例#31
0
        public UstNode VisitObjectCreationExpression(DslParser.ObjectCreationExpressionContext context)
        {
            var      literal   = (Token)VisitLiteralOrPatternId(context.literalOrPatternId());
            var      typeToken = new TypeToken(literal.TextValue, literal.TextSpan, null);
            ArgsNode args      = context.args() == null ? new ArgsNode() : (ArgsNode)VisitArgs(context.args());
            var      result    = new ObjectCreateExpression(typeToken, args, context.GetTextSpan(), null);

            return(result);
        }
示例#32
0
        /// <summary>
        /// Initializes a new instance of the Field class.
        /// </summary>
        /// <param name="proxy">Proxy object for the field.</param>
        /// <param name="name">The name of the field.</param>
        /// <param name="attributes">The list of attributes attached to this element.</param>
        /// <param name="fieldType">The type of the field.</param>
        /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param>
        internal Field(CodeUnitProxy proxy, string name, ICollection<Attribute> attributes, TypeToken fieldType, bool unsafeCode)
            : base(proxy, ElementType.Field, name, attributes, unsafeCode)
        {
            Param.AssertNotNull(proxy, "proxy");
            Param.AssertValidString(name, "name");
            Param.Ignore(attributes);
            Param.AssertNotNull(fieldType, "fieldType");
            Param.Ignore(unsafeCode);

            this.fieldType.Value = fieldType;
        }
示例#33
0
        /// <summary>
        /// Initializes a new instance of the Property class.
        /// </summary>
        /// <param name="proxy">Proxy object for the property.</param>
        /// <param name="name">The name of the property.</param>
        /// <param name="attributes">The list of attributes attached to this element.</param>
        /// <param name="returnType">The property return type.</param>
        /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param>
        internal Property(CodeUnitProxy proxy, string name, ICollection<Attribute> attributes, TypeToken returnType, bool unsafeCode)
            : base(proxy, ElementType.Property, name, attributes, unsafeCode)
        {
            Param.AssertNotNull(proxy, "proxy");
            Param.AssertValidString(name, "name");
            Param.Ignore(attributes);
            Param.AssertNotNull(returnType, "returnType");
            Param.Ignore(unsafeCode);

            this.returnType.Value = returnType;
        }
示例#34
0
        /// <summary>
        /// Initializes a new instance of the Event class.
        /// </summary>
        /// <param name="proxy">Proxy object for the event.</param>
        /// <param name="name">The name of the event.</param>
        /// <param name="attributes">The list of attributes attached to this element.</param>
        /// <param name="eventHandlerType">The type of the event handler.</param>
        /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param>
        internal Event(CodeUnitProxy proxy, string name, ICollection<Attribute> attributes, TypeToken eventHandlerType, bool unsafeCode)
            : base(proxy, ElementType.Event, name, attributes, unsafeCode)
        {
            Param.AssertNotNull(proxy, "proxy");
            Param.AssertValidString(name, "name");
            Param.Ignore(attributes);
            Param.AssertNotNull(eventHandlerType, "eventHandlerType");
            Param.Ignore(unsafeCode);

            this.eventHandlerType.Value = eventHandlerType;
        }
示例#35
0
        /// <summary>
        /// Initializes a new instance of the Delegate class.
        /// </summary>
        /// <param name="proxy">Proxy object for the delegate.</param>
        /// <param name="name">The name of the delegate.</param>
        /// <param name="attributes">The list of attributes attached to this element.</param>
        /// <param name="returnType">The return type.</param>
        /// <param name="typeConstraints">The list of type constraints on the element.</param>
        /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param>
        internal Delegate(CodeUnitProxy proxy, string name, ICollection<Attribute> attributes, TypeToken returnType, ICollection<TypeParameterConstraintClause> typeConstraints, bool unsafeCode)
            : base(proxy, ElementType.Delegate, name, attributes, unsafeCode)
        {
            Param.AssertNotNull(proxy, "proxy");
            Param.AssertValidString(name, "name");
            Param.Ignore(attributes);
            Param.AssertNotNull(returnType, "returnType");
            Param.Ignore(typeConstraints);
            Param.Ignore(unsafeCode);

            this.returnType.Value = returnType;

            this.typeConstraints.Value = typeConstraints ?? TypeParameterConstraintClause.EmptyTypeParameterConstraintClause;
            CsLanguageService.Debug.Assert(typeConstraints == null || typeConstraints.IsReadOnly, "Must be a read-only collection.");
        }
示例#36
0
        /// <summary>
        /// Initializes a new instance of the Method class.
        /// </summary>
        /// <param name="proxy">Proxy object for the method.</param>
        /// <param name="name">The name of the method.</param>
        /// <param name="attributes">The list of attributes attached to this element.</param>
        /// <param name="returnType">The method's return type.</param>
        /// <param name="typeConstraints">The list of type constraints on the element.</param>
        /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param>
        internal Method(CodeUnitProxy proxy, string name, ICollection<Attribute> attributes, TypeToken returnType, ICollection<TypeParameterConstraintClause> typeConstraints, bool unsafeCode)
            : base(proxy, ElementType.Method, name, attributes, unsafeCode)
        {
            Param.AssertNotNull(proxy, "proxy");
            Param.AssertValidString(name, "name");
            Param.Ignore(attributes);
            Param.Ignore(returnType);
            Param.Ignore(typeConstraints);
            Param.Ignore(unsafeCode);

            CsLanguageService.Debug.Assert(
                returnType != null || this.ContainsModifier(TokenType.Explicit, TokenType.Implicit),
                "A method's return type can only be null in an explicit or implicit operator overload method.");

            this.returnType.Value = returnType;

            this.typeConstraints.Value = typeConstraints ?? TypeParameterConstraintClause.EmptyTypeParameterConstraintClause;
            CsLanguageService.Debug.Assert(typeConstraints == null || typeConstraints.IsReadOnly, "Must be a read-only collection.");
        }
示例#37
0
        /// <summary>
        /// Gets the base name and generic symbols for a type token.
        /// </summary>
        /// <param name="typeTokenProxy">Proxy object for the TypeToken being created.</param>
        /// <param name="startIndex">The start index within the symbol list.</param>
        /// <param name="unsafeCode">Indicates whether the type is within a block of unsafe code.</param>
        private void GetTypeTokenBaseName(ref CodeUnitProxy typeTokenProxy, ref int startIndex, bool unsafeCode)
        {
            Param.AssertNotNull(typeTokenProxy, "typeTokenProxy");
            Param.AssertGreaterThanOrEqualToZero(startIndex, "startIndex");
            Param.Ignore(unsafeCode);

            Symbol symbol = this.symbols.Peek(startIndex);

            // First get the full name of the type.
            int index = -1;
            while (true)
            {
                this.GatherNonTokenSymbols(typeTokenProxy, ref startIndex);
                symbol = this.symbols.Peek(startIndex);

                var innerTypeTokenProxy = new CodeUnitProxy(this.document);

                // Add the next word. The type of the next word must either be an unknown
                // word type, which will be the name of the next item in the type, or else
                // it must be the 'this' keyword. This is used when implementing an explicit
                // interface member which is an indexer.
                if (symbol.SymbolType == SymbolType.Other || symbol.SymbolType == SymbolType.This)
                {
                    innerTypeTokenProxy.Children.Add(new LiteralToken(this.document, symbol.Text, symbol.Location, this.symbols.Generated));
                }
                else
                {
                    throw new SyntaxException(this.document, symbol.LineNumber);
                }

                ++startIndex;

                // Look at the type of the next non-whitespace character.
                index = this.GetNextCodeSymbolIndex(startIndex);
                if (index == -1)
                {
                    break;
                }

                // If the next character is an opening generic bracket, get the generic.
                GenericTypeToken generic = null;

                symbol = this.symbols.Peek(index);
                if (symbol.SymbolType == SymbolType.LessThan)
                {
                    int end;
                    if (this.GetGenericArgumentList(innerTypeTokenProxy, unsafeCode, null, startIndex, out end))
                    {
                        // Create a new GenericTypeToken which represents this generic type.
                        generic = new GenericTypeToken(innerTypeTokenProxy);
                        typeTokenProxy.Children.Add(generic);

                        // Advance the symbol index.
                        startIndex = end + 1;

                        // Look at the type of the next non-whitespace character.
                        index = this.GetNextCodeSymbolIndex(startIndex);
                        if (index == -1)
                        {
                            break;
                        }
                    }
                }

                if (generic == null)
                {
                    // Since this is not a generic type, it is just a regular type token. Create and add this type token.
                    TypeToken innerType = new TypeToken(innerTypeTokenProxy);
                    typeTokenProxy.Children.Add(innerType);
                }

                // If the next character is not a dot or a qualified alias, break now.
                symbol = this.symbols.Peek(index);
                if (symbol.SymbolType != SymbolType.Dot && symbol.SymbolType != SymbolType.QualifiedAlias)
                {
                    break;
                }

                // Add any whitspace.
                this.GatherNonTokenSymbols(typeTokenProxy, ref startIndex);
                symbol = this.symbols.Peek(startIndex);

                // Add the dot or qualified alias.
                if (symbol.SymbolType == SymbolType.Dot)
                {
                    typeTokenProxy.Children.Add(new MemberAccessOperator(this.document, symbol.Text, symbol.Location, this.symbols.Generated));
                }
                else
                {
                    CsLanguageService.Debug.Assert(symbol.SymbolType == SymbolType.QualifiedAlias, "Expected a qualified alias keyword");
                    typeTokenProxy.Children.Add(new QualifiedAliasOperator(this.document, symbol.Text, symbol.Location, this.symbols.Generated));
                }

                // Get the next symbol.
                symbol = this.symbols.Peek(++startIndex);
            }
        }
示例#38
0
        /// <summary>
        /// Parses and returns the declarators for a field.
        /// </summary>
        /// <param name="parentProxy">Represents the parent item.</param>
        /// <param name="unsafeCode">Indicates whether the code is marked as unsafe.</param>
        /// <param name="fieldType">The field type.</param>
        /// <returns>Returns the name of the first field.</returns>
        private string GetFieldDeclarators(CodeUnitProxy parentProxy, bool unsafeCode, TypeToken fieldType)
        {
            Param.AssertNotNull(parentProxy, "parentProxy");
            Param.Ignore(unsafeCode);
            Param.AssertNotNull(fieldType, "fieldType");

            string firstFieldName = null;
            Symbol symbol = this.PeekNextSymbol();

            while (symbol.SymbolType != SymbolType.Semicolon)
            {
                this.AdvanceToNextCodeSymbol(parentProxy);
                var declaratorProxy = new CodeUnitProxy(this.document);

                // Get the identifier.
                var identifierExpressionProxy = new CodeUnitProxy(this.document);
                Token identifier = this.GetElementNameToken(identifierExpressionProxy, unsafeCode, true);

                var identifierExpression = new LiteralExpression(identifierExpressionProxy, identifier);
                declaratorProxy.Children.Add(identifierExpression);

                if (firstFieldName == null)
                {
                    firstFieldName = identifier.Text;
                }

                Expression initialization = null;

                // Check whether there is an equals sign.
                symbol = this.PeekNextSymbol();
                if (symbol.SymbolType == SymbolType.Equals)
                {
                    this.GetOperatorSymbolToken(declaratorProxy, OperatorType.Equals);

                    // Get the expression after the equals sign. If the expression starts with an
                    // opening curly bracket, then this is an initialization expression or an
                    // anonymous type initialization expression.
                    symbol = this.PeekNextSymbol();
                    if (symbol.SymbolType == SymbolType.OpenCurlyBracket)
                    {
                        // Determine whether this is an array or an anonymous type.
                        if (fieldType.Text == "var" || (
                            fieldType.Text != "Array" && fieldType.Text != "System.Array" && !fieldType.Text.Contains("[")))
                        {
                            initialization = this.GetAnonymousTypeInitializerExpression(declaratorProxy, unsafeCode);
                        }
                        else
                        {
                            initialization = this.GetArrayInitializerExpression(declaratorProxy, unsafeCode);
                        }
                    }
                    else
                    {
                        initialization = this.GetNextExpression(declaratorProxy, ExpressionPrecedence.None, unsafeCode);
                    }

                    if (initialization == null)
                    {
                        throw this.CreateSyntaxException();
                    }
                }

                var declaratorExpression = new VariableDeclaratorExpression(declaratorProxy, identifierExpression, initialization);

                parentProxy.Children.Add(declaratorExpression);

                // If the next symbol is a comma, continue.
                symbol = this.PeekNextSymbol();
                if (symbol.SymbolType == SymbolType.Comma)
                {
                    this.GetToken(parentProxy, TokenType.Comma, SymbolType.Comma);
                    symbol = this.PeekNextSymbol();
                }
            }

            // Return the declarators as a read-only collection.
            return firstFieldName;
        }
示例#39
0
        /// <summary>
        /// Gets a token representing a type identifier.
        /// </summary>
        /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param>
        /// <param name="includeArrayBrackets">Indicates whether to include array brackets in the type token.</param>
        /// <param name="isExpression">Indicates whether this type token comes at the end of an 'is' expression.</param>
        /// <param name="startIndex">The start position in the symbol list of the first symbol in the type token.</param>
        /// <param name="endIndex">Returns the index of the last symbol in the type token.</param>
        /// <returns>Returns the token.</returns>
        private TypeToken GetTypeTokenAux(bool unsafeCode, bool includeArrayBrackets, bool isExpression, int startIndex, out int endIndex)
        {
            Param.Ignore(unsafeCode);
            Param.Ignore(includeArrayBrackets);
            Param.Ignore(isExpression);
            Param.AssertGreaterThanOrEqualToZero(startIndex, "startIndex");

            // Get the next symbol and make sure it is an unknown word.
            Symbol symbol = this.symbols.Peek(startIndex);
            CsLanguageService.Debug.Assert(symbol != null && symbol.SymbolType == SymbolType.Other, "Expected a text symbol");

            var typeTokenProxy = new CodeUnitProxy(this.document);

            // Get the name of the type token plus any generic symbols and types.
            this.GetTypeTokenBaseName(ref typeTokenProxy, ref startIndex, unsafeCode);

            TypeToken typeToken = null;

            // If the type token base name consistents of one single TypeToken (which is not generic), then we should just use this TypeToken as our own TypeToken and throw away the outer wrapper.
            if (typeTokenProxy.Children.Count == 1 && typeTokenProxy.Children.First.Is(TokenType.Type) && !(typeTokenProxy.Children.First is GenericTypeToken))
            {
                // Pull out the inner TypeToken and throw away the outer wrapper.
                typeToken = (TypeToken)typeTokenProxy.Children.First;
                typeToken.Detach();
                typeTokenProxy = typeToken.ThisProxy;
            }
            else
            {
                // The type token is more complex. Create the strongly typed type token now.
                typeToken = new TypeToken(typeTokenProxy);
            }

            bool allowNullableType = true;

            // Add dereference symbols if they exist.
            if (unsafeCode)
            {
                if (this.GetTypeTokenDereferenceSymbols(typeTokenProxy, ref startIndex))
                {
                    allowNullableType = false;
                }
            }

            // Now look for the nullable type symbol, if needed.
            if (allowNullableType)
            {
                this.GetTypeTokenNullableTypeSymbol(typeTokenProxy, isExpression, ref startIndex);
            }

            // Get the array brackets if they exist.
            if (includeArrayBrackets)
            {
                this.GetTypeTokenArrayBrackets(typeTokenProxy, ref startIndex);
            }

            if (typeTokenProxy.Children.Count == 0)
            {
                throw this.CreateSyntaxException();
            }

            // Set the end index.
            endIndex = startIndex - 1;

            // If the type token only contains a single child which is a generic type, then throw away the outer wrapper and just return that inner type.
            if (typeTokenProxy.Children.Count == 1 && typeTokenProxy.Children.First.Is(TokenType.Type))
            {
                GenericTypeToken generic = typeTokenProxy.Children.First as GenericTypeToken;
                if (generic != null)
                {
                    generic.Detach();
                    return generic;
                }
            }

            // The type is either not generic, or else it is composed of a more complex type which includes a generic 
            // (for example, an array of a generic type). Return the more complex type.
            return typeToken;
        }
示例#40
0
            /// <summary>
            /// Initializes a new instance of the QueryClauseVariable class.
            /// </summary>
            /// <param name="type">The type of the variable.</param>
            /// <param name="name">The name of the variable.</param>
            /// <param name="location">The location of the variable.</param>
            /// <param name="generated">Indicates whethre the variable is located within a block of generated code.</param>
            internal QueryClauseVariable(TypeToken type, string name, CodeLocation location, bool generated)
            {
                Param.Ignore(type);
                Param.RequireValidString(name, "name");
                Param.RequireNotNull(location, "location");
                Param.Ignore(generated);

                this.type = type;
                this.name = name;
                this.location = location;
                this.generated = generated;
            }
示例#41
0
        /// <summary>
        /// Initializes a new instance of the CatchStatement class.
        /// </summary>
        /// <param name="tokens">
        /// The list of tokens that form the statement.
        /// </param>
        /// <param name="tryStatement">
        /// The try-statement that this catch-statement is attached to.
        /// </param>
        /// <param name="classExpression">
        /// The inner expression.
        /// </param>
        /// <param name="embeddedStatement">
        /// The statement embedded within the catch-statement.
        /// </param>
        internal CatchStatement(CsTokenList tokens, TryStatement tryStatement, Expression classExpression, BlockStatement embeddedStatement)
            : base(StatementType.Catch, tokens)
        {
            Param.AssertNotNull(tokens, "tokens");
            Param.AssertNotNull(tryStatement, "tryStatement");
            Param.Ignore(classExpression);
            Param.AssertNotNull(embeddedStatement, "embeddedStatement");

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

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

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

                        this.classType = variableDeclaration.Type;

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

            this.AddStatement(embeddedStatement);
        }
示例#42
0
 private void AssertHasAttribute(EventTemplate evt, TypeToken tt, string name)
 {
     AttributeTemplate attr = evt[name];
     Assert.IsNotNull(attr);
     Assert.AreEqual(tt, attr.TypeToken);
 }
 public bool Equals(TypeToken obj)
 {
 }
示例#44
0
 private void NextPlayer()
 {
     currentPlayer = currentPlayer == TypeToken.TOKEN_BLACK ? TypeToken.TOKEN_RED : TypeToken.TOKEN_BLACK;
     opponentPlayer = opponentPlayer == TypeToken.TOKEN_BLACK ? TypeToken.TOKEN_RED : TypeToken.TOKEN_BLACK;
 }
示例#45
0
        /// <summary>
        /// Parses and returns the declarators for an event.
        /// </summary>
        /// <param name="parentProxy">Represents the parent item.</param>
        /// <param name="unsafeCode">Indicates whether the code is marked as unsafe.</param>
        /// <param name="eventHandlerType">The event type.</param>
        /// <returns>Returns the name of the first event.</returns>
        private string GetEventDeclarators(CodeUnitProxy parentProxy, bool unsafeCode, TypeToken eventHandlerType)
        {
            Param.AssertNotNull(parentProxy, "parentProxy");
            Param.Ignore(unsafeCode);
            Param.AssertNotNull(eventHandlerType, "eventHandlerType");

            string firstEventName = null;
            Symbol symbol = this.PeekNextSymbol();

            while (symbol.SymbolType != SymbolType.Semicolon && symbol.SymbolType != SymbolType.OpenCurlyBracket)
            {
                this.AdvanceToNextCodeSymbol(parentProxy);
                var declaratorProxy = new CodeUnitProxy(this.document);

                // Get the identifier.
                var identifierExpressionProxy = new CodeUnitProxy(this.document);
                Token identifier = this.GetElementNameToken(identifierExpressionProxy, unsafeCode, true);

                if (firstEventName == null)
                {
                    firstEventName = identifier.Text;
                }

                var identifierExpression = new LiteralExpression(identifierExpressionProxy, identifier);
                declaratorProxy.Children.Add(identifierExpression);

                Expression initialization = null;

                // Check whether there is an equals sign.
                symbol = this.PeekNextSymbol();
                if (symbol.SymbolType == SymbolType.Equals)
                {
                    this.GetOperatorSymbolToken(declaratorProxy, OperatorType.Equals);
                    initialization = this.GetNextExpression(declaratorProxy, ExpressionPrecedence.None, unsafeCode);

                    if (initialization == null)
                    {
                        throw this.CreateSyntaxException();
                    }
                }

                var declaratorExpression = new EventDeclaratorExpression(declaratorProxy, identifierExpression, initialization);

                parentProxy.Children.Add(declaratorExpression);

                // If the next symbol is a comma, continue.
                symbol = this.PeekNextSymbol();
                if (symbol.SymbolType == SymbolType.Comma)
                {
                    this.GetToken(parentProxy, TokenType.Comma, SymbolType.Comma);
                    symbol = this.PeekNextSymbol();
                }
            }

            return firstEventName;
        }
        /// <summary>
        /// Replaces the given TypeToken with the first child of that token.
        /// </summary>
        /// <param name="typeToken">The TypeToken to replace.</param>
        private static void ReplaceTypeTokenWithFirstChildToken(TypeToken typeToken)
        {
            Param.AssertNotNull(typeToken, "typeToken");
            CsLanguageService.Debug.Assert(typeToken.Children.Count == 1, "This operation only makes sense when the type token contains a single child.");

            // Detach the child token from the parent TypeToken.
            Token token = typeToken.FindFirstChildToken();
            CsLanguageService.Debug.Assert(token != null, "The child token of the type token should be a token.");

            token.Detach();

            CodeUnit parent = typeToken.Parent;
            CsLanguageService.Debug.Assert(parent != null, "The type token has not been added to a collection");

            parent.Children.Replace(typeToken, token);
        }
        /// <summary>
        /// Converts the given expression into a literal expression containing a type token.
        /// </summary>
        /// <param name="expression">The expression to convert.</param>
        /// <returns>Returns the converted expression.</returns>
        private LiteralExpression ConvertTypeExpression(Expression expression)
        {
            // todo; handle this.
            Param.AssertNotNull(expression, "expression");

            // Get the first and last token in the expression.
            Token firstToken = expression.FindFirstDescendentToken();

            // Create a new token list containing these tokens.
            var typeTokenProxy = new CodeUnitProxy(this.document);
            for (Token token = firstToken; token != null; token = token.FindNextDescendentTokenOf(expression))
            {
                typeTokenProxy.Children.Add(token);
            }

            // Create the new type token.
            var typeToken = new TypeToken(typeTokenProxy);

            var expressionProxy = new CodeUnitProxy(this.document);
            expressionProxy.Children.Add(typeToken);

            // Create the literal expression.
            return new LiteralExpression(expressionProxy, typeToken);
        }
示例#48
0
        public void ClickBtnColumn(int column)
        {
            SquareViewModel s = GetEmptySquareInColumn(column);
            if (s != null)
            {
                s.Token = (int)currentPlayer;

                bool checkEndGame_CurrentPlayerWins = CheckEndGame_CurrentPlayerWins();
                bool checkEndGame_NoEmptySquares = CheckEndGame_NoEmptySquares();

                if (checkEndGame_CurrentPlayerWins)
                {
                    string msg = "Red player wins!";
                    if (currentPlayer == TypeToken.TOKEN_BLACK)
                        msg = "Black player wins!";
                    MessageBox.Show(msg);
                    NuevoJuego();
                }
                else if (checkEndGame_NoEmptySquares)
                {
                    MessageBox.Show("Draw, Empate");
                    NuevoJuego();
                }
                else
                {
                    if (currentPlayer == TypeToken.TOKEN_BLACK)
                        currentPlayer = TypeToken.TOKEN_RED;
                    else
                        currentPlayer = TypeToken.TOKEN_BLACK;
                }

                if (SelectedOption == OPTION_ORDENADOR && currentPlayer == TypeToken.TOKEN_RED)
                {
                    OrdenadorIA ordenadorIA = new OrdenadorIA(Squares, NumRows, NumColumns);
                    int columnSelectedByIA = ordenadorIA.GetSelectedColumn();
                    //Random r = new Random();
                    //int columnSelectedByIA = 0;
                    //do
                    //{
                    //    columnSelectedByIA = r.Next(0, NumColumns);
                    //}
                    //while (GetEmptySquareInColumn(columnSelectedByIA) == null);
                    ClickBtnColumn(columnSelectedByIA);
                }
            }
        }
示例#49
0
        private void NuevoJuego()
        {
            var rand = new Random();
            Squares = Enumerable
                .Range(1, NumRows * NumColumns)
                .Select(a => new SquareViewModel() { Token = (int)TypeToken.TOKEN_NONE })// rand.Next(-1, 2) })
                .ToList();

            currentPlayer = TypeToken.TOKEN_BLACK;
        }
示例#50
0
		public bool Equals(TypeToken other)
		{
			return this == other;
		}
 public static bool op_Inequality(TypeToken a, TypeToken b)
 {
 }
        /// <summary>
        /// Converts the given expression into a literal expression containing a type token.
        /// </summary>
        /// <param name="expression">The expression to convert.</param>
        /// <returns>Returns the converted expression.</returns>
        private LiteralExpression ConvertTypeExpression(Expression expression)
        {
            Param.AssertNotNull(expression, "expression");

            // Get the first and last token in the expression.
            Node<CsToken> firstTokenNode = expression.Tokens.First;
            Node<CsToken> lastTokenNode = expression.Tokens.Last;

            // Create a new token list containing these tokens.
            List<CsToken> tokenList = new List<CsToken>();
            foreach (CsToken token in expression.Tokens)
            {
                tokenList.Add(token);
            }

            // Remove the extra tokens from the master list.
            if (firstTokenNode != null && expression.Tokens.First != null)
            {
                Node<CsToken> temp = firstTokenNode.Next;
                if (!expression.Tokens.OutOfBounds(temp))
                {
                    this.tokens.RemoveRange(temp, expression.Tokens.Last);
                }
            }

            // Add the child tokens to a token list.
            MasterList<CsToken> childTokens = new MasterList<CsToken>(tokenList);

            // Create the new type token.
            TypeToken typeToken = new TypeToken(
                childTokens, CodeLocation.Join(firstTokenNode, lastTokenNode), firstTokenNode.Value.Generated);

            // Insert the new token.
            Node<CsToken> typeTokenNode = this.tokens.Replace(firstTokenNode, typeToken);

            // Create the literal expression.
            return new LiteralExpression(
                new CsTokenList(this.tokens, firstTokenNode, firstTokenNode),
                typeTokenNode);
        }